hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequencelengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequencelengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
85cc1d3b70ab1457358c4c505c56772a8f8ae098 | 2,749 | cpp | C++ | src/MeshDataBuffer.cpp | jaredmulconry/GLProj | 722fc9804cf6bd2ee0098e6eed9261198f55d0b9 | [
"MIT"
] | 1 | 2016-11-28T07:14:41.000Z | 2016-11-28T07:14:41.000Z | src/MeshDataBuffer.cpp | jaredmulconry/GLProj | 722fc9804cf6bd2ee0098e6eed9261198f55d0b9 | [
"MIT"
] | null | null | null | src/MeshDataBuffer.cpp | jaredmulconry/GLProj | 722fc9804cf6bd2ee0098e6eed9261198f55d0b9 | [
"MIT"
] | null | null | null | #include "MeshDataBuffer.hpp"
#include "GLFW/glfw3.h"
namespace GlProj
{
namespace Graphics
{
MeshDataBuffer::MeshDataBuffer(BufferType bufferType, GLsizeiptr dataSize, const GLvoid* data,
GLenum dataType, GLint elemsPerVert, BufferUsage usage)
: bufferType(GLenum(bufferType))
, dataType(dataType)
, elementsPerVertex(elemsPerVert)
{
glGenBuffers(1, &meshDataHandle);
glBindBuffer(this->bufferType, meshDataHandle);
glBufferData(this->bufferType, dataSize, data, GLenum(usage));
}
MeshDataBuffer::MeshDataBuffer(MeshDataBuffer&& x) noexcept
: meshDataHandle(x.meshDataHandle)
, bufferType(x.bufferType)
, dataType(x.dataType)
, elementsPerVertex(x.elementsPerVertex)
{
x.meshDataHandle = invalidHandle;
}
MeshDataBuffer& MeshDataBuffer::operator=(MeshDataBuffer&& x) noexcept
{
if (this != &x)
{
if (meshDataHandle != invalidHandle)
{
glDeleteBuffers(1, &meshDataHandle);
}
meshDataHandle = x.meshDataHandle;
bufferType = x.bufferType;
dataType = x.dataType;
elementsPerVertex = x.elementsPerVertex;
x.meshDataHandle = invalidHandle;
}
return *this;
}
MeshDataBuffer::~MeshDataBuffer()
{
if (meshDataHandle != invalidHandle)
{
glDeleteBuffers(1, &meshDataHandle);
}
}
GLuint MeshDataBuffer::GetHandle() const noexcept
{
return meshDataHandle;
}
BufferType MeshDataBuffer::GetBufferType() const noexcept
{
return BufferType(bufferType);
}
GLenum MeshDataBuffer::GetDataType() const noexcept
{
return dataType;
}
GLint MeshDataBuffer::GetElementsPerVertex() const noexcept
{
return elementsPerVertex;
}
void MeshDataBuffer::UpdateData(GLintptr offset, GLsizeiptr dataSize, const GLvoid * data) const noexcept
{
glBufferSubData(bufferType, offset, dataSize, data);
}
void* MeshDataBuffer::MapBuffer(GLintptr offset, GLsizeiptr dataSize, GLbitfield access) const noexcept
{
return glMapBufferRange(bufferType, offset, dataSize, access);
}
void MeshDataBuffer::UnmapBuffer() const noexcept
{
glUnmapBuffer(bufferType);
}
void MeshDataBuffer::Bind() const noexcept
{
glBindBuffer(bufferType, GetHandle());
}
void MeshDataBuffer::BindBase(GLuint index) const noexcept
{
glBindBufferBase(bufferType, index, GetHandle());
}
void MeshDataBuffer::BindRange(GLuint index, GLintptr offset, GLsizeiptr size) const noexcept
{
glBindBufferRange(bufferType, index, GetHandle(), offset, size);
}
bool operator==(const MeshDataBuffer& x, const MeshDataBuffer& y) noexcept
{
return x.meshDataHandle == y.meshDataHandle;
}
bool operator!=(const MeshDataBuffer& x, const MeshDataBuffer& y) noexcept
{
return !(x == y);
}
}
}
| 26.95098 | 107 | 0.719534 | jaredmulconry |
85cd11adad48cfa373d705f644b8c537794fde31 | 7,135 | cc | C++ | test/web/test_parser.cc | protocolocon/nanoWeb | a89b3f9d9c9b7421a5005971565795519728f31b | [
"BSD-2-Clause"
] | null | null | null | test/web/test_parser.cc | protocolocon/nanoWeb | a89b3f9d9c9b7421a5005971565795519728f31b | [
"BSD-2-Clause"
] | null | null | null | test/web/test_parser.cc | protocolocon/nanoWeb | a89b3f9d9c9b7421a5005971565795519728f31b | [
"BSD-2-Clause"
] | null | null | null | /* -*- mode: c++; coding: utf-8; c-file-style: "stroustrup"; -*-
Contributors: Asier Aguirre
All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in the LICENSE.txt file.
*/
#include "catch.hpp"
#include "ml_parser.h"
#define _ "\n"
#define DUMP(x, ...) x, ##__VA_ARGS__
using namespace std;
using namespace webui;
namespace {
bool stringCompare(const char* str, const char* pos, int size) {
return int(strlen(str)) == size && !strncmp(str, pos, size);
}
}
TEST_CASE("parser: id", "[parser]") {
MLParser ml;
const char* str("s0mething");
REQUIRE(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 1);
CHECK(ml[0].type() == MLParser::EntryType::Id);
CHECK(stringCompare("s0mething", ml[0].pos, ml.size(0)));
}
TEST_CASE("parser: number", "[parser]") {
MLParser ml;
const char* str("123.4");
REQUIRE(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 1);
CHECK(ml[0].type() == MLParser::EntryType::Number);
CHECK(stringCompare("123.4", ml[0].pos, ml.size(0)));
}
TEST_CASE("parser: number negative", "[parser]") {
MLParser ml;
const char* str("-123.4");
REQUIRE(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 1);
CHECK(ml[0].type() == MLParser::EntryType::Number);
CHECK(stringCompare("-123.4", ml[0].pos, ml.size(0)));
}
TEST_CASE("parser: number invalid", "[parser]") {
MLParser ml;
const char* str("-12.3.4");
CHECK(!ml.parse(str, strlen(str)));
str = "12f";
CHECK(!ml.parse(str, strlen(str)));
}
TEST_CASE("parser: function", "[parser]") {
MLParser ml;
const char* str("combine(id1, id2, id3)");
REQUIRE(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 4);
CHECK(ml[0].type() == MLParser::EntryType::Function);
CHECK(ml[1].type() == MLParser::EntryType::Id);
CHECK(ml[2].type() == MLParser::EntryType::Id);
CHECK(ml[3].type() == MLParser::EntryType::Id);
CHECK(ml[0].next == ml.size());
CHECK(stringCompare("combine", ml[0].pos, ml.size(0)));
}
TEST_CASE("parser: function empty", "[parser]") {
MLParser ml;
const char* str("combine()");
REQUIRE(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 1);
CHECK(ml[0].type() == MLParser::EntryType::Function);
CHECK(ml[0].next == ml.size());
CHECK(stringCompare("combine", ml[0].pos, ml.size(0)));
}
TEST_CASE("parser: color", "[parser]") {
MLParser ml;
const char* str("#1234abcd");
REQUIRE(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 1);
CHECK(ml[0].type() == MLParser::EntryType::Color);
CHECK(stringCompare("#1234abcd", ml[0].pos, ml.size(0)));
}
TEST_CASE("parser: string", "[parser]") {
MLParser ml;
const char* str("\"str\"");
REQUIRE(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 1);
CHECK(ml[0].type() == MLParser::EntryType::String);
CHECK(stringCompare("\"str\"", ml[0].pos, ml.size(0)));
}
TEST_CASE("parser: list", "[parser]") {
MLParser ml;
const char* str("[#ffaacc, someId, [id5, id6], anotherId]");
REQUIRE(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 7);
CHECK(ml[0].type() == MLParser::EntryType::List);
CHECK(ml[3].type() == MLParser::EntryType::List);
CHECK(stringCompare("#ffaacc", ml[1].pos, ml.size(1)));
CHECK(stringCompare("someId", ml[2].pos, ml.size(2)));
CHECK(stringCompare("id5", ml[4].pos, ml.size(4)));
CHECK(stringCompare("id6", ml[5].pos, ml.size(5)));
CHECK(stringCompare("anotherId", ml[6].pos, ml.size(6)));
}
TEST_CASE("parser: operation", "[parser]") {
MLParser ml;
const char* str("a + b * (c + f(d))");
REQUIRE(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 8);
CHECK(ml[1].type() == MLParser::EntryType::Operator);
}
TEST_CASE("parser: operation invalid", "[parser]") {
MLParser ml;
const char* str("a + + b");
CHECK(!ml.parse(str, strlen(str)));
}
TEST_CASE("parser: operation invalid 2", "[parser]") {
MLParser ml;
const char* str("* c");
CHECK(!ml.parse(str, strlen(str)));
}
TEST_CASE("parser: object", "[parser]") {
MLParser ml;
const char* str("Object { // comment"
_" key: value // comment"
_" id: [list] // comment"
_" obj { } // comment"
_" obj2 { // comment"
_" obj3 { // comment"
_" [ // block"
_" id: f(x) // comment"
_" ] // comment"
_" } // comment"
_" } // comment"
_"} // comment");
REQUIRE(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
CHECK(ml[0].type() == MLParser::EntryType::Object);
CHECK(ml[0].next == ml.size());
}
TEST_CASE("parser: wildcar", "[parser]") {
MLParser ml;
const char* str("@");
CHECK(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 1);
CHECK(ml[0].type() == MLParser::EntryType::Wildcar);
CHECK(ml[0].next == ml.size());
}
TEST_CASE("parser: attributes", "[parser]") {
MLParser ml;
const char* str("self.width");
CHECK(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 2);
CHECK(ml[0].type() == MLParser::EntryType::Id);
CHECK(ml[1].type() == MLParser::EntryType::Attribute);
}
TEST_CASE("parser: assign", "[parser]") {
MLParser ml;
const char* str("a = 7");
CHECK(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 3);
CHECK(ml[0].type() == MLParser::EntryType::Id);
CHECK(ml[1].type() == MLParser::EntryType::Operator);
CHECK(ml[2].type() == MLParser::EntryType::Number);
}
TEST_CASE("parser: failing case operation", "[parser]") {
MLParser ml;
const char* str("(12 + 21) / 2");
CHECK(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 5);
}
TEST_CASE("parser: failing case operation 2", "[parser]") {
MLParser ml;
const char* str("f(x + w*0.5, (y-2) + h*0.5)");
CHECK(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 13);
CHECK(ml[2].next == 6);
}
TEST_CASE("parser: assign op", "[parser]") {
MLParser ml;
const char* str("x ^= 1");
CHECK(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 3);
CHECK(ml[1].type() == MLParser::EntryType::Operator);
}
TEST_CASE("parser: complex object properties", "[parser]") {
MLParser ml;
const char* str("Object {"
_" x: y + 1"
_" y: (x * 5) + 2"
_"}");
CHECK(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 11);
CHECK(ml[2].next == 5);
CHECK(ml[6].next == 11);
}
| 30.361702 | 68 | 0.55417 | protocolocon |
85cfdef4c6e0b72a70a5a5674f7cb49381df7379 | 4,605 | cpp | C++ | Sources/RealSense/Microsoft.Psi.RealSense_Interop.Windows.x64/RealSenseDeviceUnmanaged.cpp | pat-sweeney/psi | 273b6d442821cc9942953ea6b51cfcff0edda11f | [
"MIT"
] | 332 | 2019-05-10T20:30:40.000Z | 2022-03-14T08:42:33.000Z | Sources/RealSense/Microsoft.Psi.RealSense_Interop.Windows.x64/RealSenseDeviceUnmanaged.cpp | pat-sweeney/psi | 273b6d442821cc9942953ea6b51cfcff0edda11f | [
"MIT"
] | 117 | 2019-06-12T21:13:03.000Z | 2022-03-19T00:32:20.000Z | Sources/RealSense/Microsoft.Psi.RealSense_Interop.Windows.x64/RealSenseDeviceUnmanaged.cpp | pat-sweeney/psi | 273b6d442821cc9942953ea6b51cfcff0edda11f | [
"MIT"
] | 73 | 2019-05-08T21:39:06.000Z | 2022-03-24T08:34:26.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#include "RealSenseDeviceUnmanaged.h"
#include "librealsense2\h\rs_sensor.h"
#pragma managed(push, off)
RealSenseDeviceUnmanaged::RealSenseDeviceUnmanaged()
{
refCount = 0;
}
RealSenseDeviceUnmanaged::~RealSenseDeviceUnmanaged()
{
pipeline.stop();
}
#ifdef DUMP_DEVICE_INFO
void RealSenseDeviceUnmanaged::DumpDeviceInfo()
{
rs2::context ctx;
rs2::device_list devices = ctx.query_devices();
for (rs2::device device : devices)
{
wchar_t buf[1024];
swprintf(buf, L"Device: %S\n", device.get_info(RS2_CAMERA_INFO_NAME));
OutputDebugString(buf);
std::vector<rs2::sensor> sensors = device.query_sensors();
for (rs2::sensor sensor : sensors)
{
swprintf(buf, L"Sensor: %S\n", sensor.get_info(RS2_CAMERA_INFO_NAME));
OutputDebugString(buf);
std::vector<rs2::stream_profile> strmProfiles = sensor.get_stream_profiles();
for (int i = 0; i < strmProfiles.size(); i++)
{
rs2::stream_profile sprof = strmProfiles[i];
int w, h;
rs2_get_video_stream_resolution(sprof.get(), &w, &h, nullptr);
swprintf(buf, L"Profile %d: StrmIndex:%d StrmType:%S Width:%d Height:%d Format:%S FPS:%d\n",
i,
sprof.stream_index(),
rs2_stream_to_string(sprof.stream_type()),
w, h,
rs2_format_to_string(sprof.format()),
sprof.fps());
OutputDebugString(buf);
}
for (int i = 0; i < RS2_OPTION_COUNT; i++)
{
rs2_option option_type = static_cast<rs2_option>(i);
if (sensor.supports(option_type))
{
const char* description = sensor.get_option_description(option_type);
swprintf(buf, L" Option:%S\n", description);
OutputDebugString(buf);
float current_value = sensor.get_option(option_type);
swprintf(buf, L" Value:%f\n", current_value);
OutputDebugString(buf);
}
}
}
}
}
#endif // DUMP_DEVICE_INFO
unsigned int RealSenseDeviceUnmanaged::Initialize()
{
try
{
rs2::config config;
config.enable_all_streams();
rs2::pipeline_profile pipeprof = pipeline.start();
// Read 30 frames so that things like autoexposure settle
for (int i = 0; i < 30; i++)
{
try
{
pipeline.wait_for_frames();
}
catch (...)
{
}
}
rs2::frameset frame = pipeline.wait_for_frames();
rs2::video_frame colorFrame = frame.get_color_frame();
if (colorFrame)
{
colorWidth = colorFrame.get_width();
colorHeight = colorFrame.get_height();
colorBpp = colorFrame.get_bits_per_pixel();
colorStride = colorFrame.get_stride_in_bytes();
}
rs2::depth_frame depthFrame = frame.get_depth_frame();
if (depthFrame)
{
depthWidth = depthFrame.get_width();
depthHeight = depthFrame.get_height();
depthBpp = depthFrame.get_bits_per_pixel();
depthStride = depthFrame.get_stride_in_bytes();
}
}
catch (...)
{
return E_UNEXPECTED;
}
return 0;
}
unsigned int RealSenseDeviceUnmanaged::ReadFrame(char *colorBuffer, unsigned int colorBufferLen, char *depthBuffer, unsigned int depthBufferLen)
{
try
{
rs2::frameset frame = pipeline.wait_for_frames();
auto colorFrame = frame.get_color_frame();
int w = colorFrame.get_width();
int h = colorFrame.get_height();
int stride = colorFrame.get_stride_in_bytes();
int bpp = colorFrame.get_bytes_per_pixel();
unsigned int colorFrameSize = h * stride;
if (colorFrameSize > colorBufferLen)
{
return E_UNEXPECTED;
}
char *srcRow = (char*)colorFrame.get_data();
char *dstRow = colorBuffer;
for (int y = 0; y < h; y++)
{
char *srcCol = srcRow;
char *dstCol = dstRow;
for (int x = 0; x < w; x++)
{
dstCol[2] = srcCol[0];
dstCol[1] = srcCol[1];
dstCol[0] = srcCol[2];
srcCol += bpp;
dstCol += 3;
}
srcRow += stride;
dstRow += w * 3;
}
auto depthFrame = frame.get_depth_frame();
unsigned int depthFrameSize = depthFrame.get_height() * depthFrame.get_stride_in_bytes();
if (depthFrameSize > depthBufferLen)
{
return E_UNEXPECTED;
}
memcpy(depthBuffer, depthFrame.get_data(), depthFrameSize);
}
catch (...)
{
}
return S_OK;
}
unsigned int RealSenseDeviceUnmanaged::AddRef()
{
return refCount++;
}
unsigned int RealSenseDeviceUnmanaged::Release()
{
unsigned int refcnt = --refCount;
if (refcnt == 0)
{
delete this;
}
return refcnt;
}
unsigned int CreateRealSenseDeviceUnmanaged(IRealSenseDeviceUnmanaged **device)
{
RealSenseDeviceUnmanaged *dev = new RealSenseDeviceUnmanaged();
if (dev == nullptr)
{
return E_OUTOFMEMORY;
}
dev->Initialize();
dev->AddRef();
*device = dev;
return S_OK;
}
#pragma managed(pop)
| 24.365079 | 144 | 0.686862 | pat-sweeney |
85d8971a1c6bc4ddede096086254af866af86abd | 4,427 | hpp | C++ | Firmware/communication/can/can_simple.hpp | takijo0116/ODrive | 4c01d0bff2a1c4a67e0f9979c9797b846f5de5d2 | [
"MIT"
] | 1 | 2021-06-08T13:10:27.000Z | 2021-06-08T13:10:27.000Z | Firmware/communication/can/can_simple.hpp | takijo0116/ODrive | 4c01d0bff2a1c4a67e0f9979c9797b846f5de5d2 | [
"MIT"
] | null | null | null | Firmware/communication/can/can_simple.hpp | takijo0116/ODrive | 4c01d0bff2a1c4a67e0f9979c9797b846f5de5d2 | [
"MIT"
] | null | null | null | #ifndef __CAN_SIMPLE_HPP_
#define __CAN_SIMPLE_HPP_
#include <interfaces/canbus.hpp>
#include "axis.hpp"
class CANSimple {
public:
enum {
MSG_CO_NMT_CTRL = 0x000, // CANOpen NMT Message REC
MSG_ODRIVE_HEARTBEAT,
MSG_ODRIVE_ESTOP,
MSG_GET_MOTOR_ERROR, // Errors
MSG_GET_ENCODER_ERROR,
MSG_GET_SENSORLESS_ERROR,
MSG_SET_AXIS_NODE_ID,
MSG_SET_AXIS_REQUESTED_STATE,
MSG_SET_AXIS_STARTUP_CONFIG,
MSG_GET_ENCODER_ESTIMATES,
MSG_GET_ENCODER_COUNT,
MSG_SET_CONTROLLER_MODES,
MSG_SET_INPUT_POS,
MSG_SET_INPUT_VEL,
MSG_SET_INPUT_TORQUE,
MSG_SET_LIMITS,
MSG_START_ANTICOGGING,
MSG_SET_TRAJ_VEL_LIMIT,
MSG_SET_TRAJ_ACCEL_LIMITS,
MSG_SET_TRAJ_INERTIA,
MSG_GET_IQ,
MSG_GET_SENSORLESS_ESTIMATES,
MSG_RESET_ODRIVE,
MSG_GET_VBUS_VOLTAGE,
MSG_CLEAR_ERRORS,
MSG_CO_HEARTBEAT_CMD = 0x700, // CANOpen NMT Heartbeat SEND
};
CANSimple(CanBusBase* canbus) : canbus_(canbus) {}
bool init(fibre::Callback<bool, float, fibre::Callback<void>> timer, uint32_t tx_slots_start, uint32_t tx_slots_end, uint32_t rx_slot);
private:
struct PeriodicHandler {
CANSimple* parent_;
Axis* axis;
int type;
uint32_t* interval;
uint32_t last;
void trigger() { parent_->send_periodic(this); }
};
bool renew_subscription(size_t i);
void on_received(const can_Message_t& msg);
//void on_sent(bool success);
void send_periodic(PeriodicHandler* handler);
void do_command(Axis& axis, const can_Message_t& cmd);
// Get functions (msg.rtr bit must be set)
void get_heartbeat(const Axis& axis, can_Message_t& txmsg);
void get_motor_error_callback(const Axis& axis, can_Message_t& txmsg);
void get_encoder_error_callback(const Axis& axis, can_Message_t& txmsg);
void get_sensorless_error_callback(const Axis& axis, can_Message_t& txmsg);
void get_encoder_estimates_callback(const Axis& axis, can_Message_t& txmsg);
void get_encoder_count_callback(const Axis& axis, can_Message_t& txmsg);
void get_iq_callback(const Axis& axis, can_Message_t& txmsg);
void get_sensorless_estimates_callback(const Axis& axis, can_Message_t& txmsg);
void get_vbus_voltage_callback(const Axis& axis, can_Message_t& txmsg);
// Set functions
static void set_axis_nodeid_callback(Axis& axis, const can_Message_t& msg);
static void set_axis_requested_state_callback(Axis& axis, const can_Message_t& msg);
static void set_axis_startup_config_callback(Axis& axis, const can_Message_t& msg);
static void set_input_pos_callback(Axis& axis, const can_Message_t& msg);
static void set_input_vel_callback(Axis& axis, const can_Message_t& msg);
static void set_input_torque_callback(Axis& axis, const can_Message_t& msg);
static void set_controller_modes_callback(Axis& axis, const can_Message_t& msg);
static void set_limits_callback(Axis& axis, const can_Message_t& msg);
static void set_traj_vel_limit_callback(Axis& axis, const can_Message_t& msg);
static void set_traj_accel_limits_callback(Axis& axis, const can_Message_t& msg);
static void set_traj_inertia_callback(Axis& axis, const can_Message_t& msg);
static void set_linear_count_callback(Axis& axis, const can_Message_t& msg);
// Other functions
static void estop_callback(Axis& axis, const can_Message_t& msg);
static void clear_errors_callback(Axis& axis, const can_Message_t& msg);
static void start_anticogging_callback(const Axis& axis, const can_Message_t& msg);
static constexpr uint8_t NUM_NODE_ID_BITS = 6;
static constexpr uint8_t NUM_CMD_ID_BITS = 11 - NUM_NODE_ID_BITS;
// Utility functions
static constexpr uint32_t get_node_id(uint32_t msgID) {
return (msgID >> NUM_CMD_ID_BITS); // Upper 6 or more bits
};
static constexpr uint8_t get_cmd_id(uint32_t msgID) {
return (msgID & 0x01F); // Bottom 5 bits
}
CanBusBase* canbus_;
CanBusBase::CanSubscription* subscription_handles_[AXIS_COUNT];
fibre::Callback<bool, float, fibre::Callback<void>> timer_;
uint32_t tx_slots_start_;
uint32_t tx_slots_end_;
uint32_t response_tx_slot_;
uint32_t rx_slot_;
std::array<PeriodicHandler, 2 * AXIS_COUNT> periodic_handlers_;
};
#endif | 38.833333 | 139 | 0.727355 | takijo0116 |
85e3a224111597a9bf265290809deab4b227b0c2 | 9,112 | cpp | C++ | SVEngine/src/node/SVScene.cpp | SVEChina/SVEngine | 56174f479a3096e57165448142c1822e7db8c02f | [
"MIT"
] | 34 | 2018-09-28T08:28:27.000Z | 2022-01-15T10:31:41.000Z | SVEngine/src/node/SVScene.cpp | SVEChina/SVEngine | 56174f479a3096e57165448142c1822e7db8c02f | [
"MIT"
] | null | null | null | SVEngine/src/node/SVScene.cpp | SVEChina/SVEngine | 56174f479a3096e57165448142c1822e7db8c02f | [
"MIT"
] | 8 | 2018-10-11T13:36:35.000Z | 2021-04-01T09:29:34.000Z | //
// SVScene.cpp
// SVEngine
// Copyright 2017-2020
// yizhou Fu,long Yin,longfei Lin,ziyu Xu,xiaofan Li,daming Li
//
#include "SVScene.h"
#include "SVCameraNode.h"
#include "SVNode.h"
#include "SVNodeVisit.h"
#include "../app/SVGlobalMgr.h"
#include "../app/SVGlobalParam.h"
#include "../basesys/SVStaticData.h"
#include "../rendercore/SVRenderMgr.h"
#include "../rendercore/SVRenderScene.h"
#include "../rendercore/SVRenderer.h"
#include "../rendercore/SVRenderObject.h"
#include "../rendercore/SVRenderCmd.h"
#include "../event/SVEventMgr.h"
#include "../event/SVEvent.h"
#include "../event/SVOpEvent.h"
#include "../basesys/SVSceneMgr.h"
#include "../basesys/SVCameraMgr.h"
#include "../basesys/SVConfig.h"
#include "../mtl/SVTexMgr.h"
#include "../mtl/SVTexture.h"
SVTree4::SVTree4(SVInst *_app)
:SVGBase(_app){
m_treeLock = MakeSharedPtr<SVLock>();
for(s32 i=0;i<4;i++){
m_pTreeNode[i] = nullptr;
}
m_node = nullptr;
}
SVTree4::~SVTree4(){
m_node = nullptr;
for(s32 i=0;i<4;i++){
m_pTreeNode[i] = nullptr;
}
m_treeLock = nullptr;
}
//世界大小和深度
void SVTree4::create(SVBoundBox& _box,s32 _depth){
m_treeBox = _box;
//构建场景树
if(_depth>0){
FVec3 t_max = _box.getMax();
FVec3 t_min = _box.getMin();
FVec3 t_center = (t_max + t_min)*0.5f;
//0 第一象限
SVBoundBox t_box0(t_center,t_max);
m_pTreeNode[0] = MakeSharedPtr<SVTree4>(mApp);
m_pTreeNode[0]->create(t_box0,_depth-1);
//1 第二象限
SVBoundBox t_box1( FVec3(t_min.x,t_center.y,0.0f),FVec3(t_center.x,t_max.y,0.0f) );
m_pTreeNode[1] = MakeSharedPtr<SVTree4>(mApp);
m_pTreeNode[1]->create(t_box1,_depth-1);
//2 第三象限
SVBoundBox t_box2(t_min,t_center);
m_pTreeNode[2] = MakeSharedPtr<SVTree4>(mApp);
m_pTreeNode[2]->create(t_box2,_depth-1);
//3 第四象限
SVBoundBox t_box3( FVec3(t_center.x,t_min.y,0.0f),FVec3(t_max.x,t_center.y,0.0f) );
m_pTreeNode[3] = MakeSharedPtr<SVTree4>(mApp);
m_pTreeNode[3]->create(t_box3,_depth-1);
}else{
//叶子节点
m_node = MakeSharedPtr<SVNode>(mApp);
}
}
void SVTree4::destroy(){
m_treeLock->lock();
for(s32 i=0;i<4;i++){
if(m_pTreeNode[i]){
m_pTreeNode[i]->destroy();
}
}
m_treeLock->unlock();
clearNode();
}
void SVTree4::update(f32 _dt){
m_treeLock->lock();
//本身挂载的节点进行更新
if(m_node) {
m_node->deep_update(_dt);
}else{
for(s32 i=0;i<4;i++){
if(m_pTreeNode[i]){
m_pTreeNode[i]->update(_dt);
}
}
}
m_treeLock->unlock();
}
void SVTree4::visit(SVVisitorBasePtr _visitor){
m_treeLock->lock();
if(m_node) {
m_node->deep_visit(_visitor);
}else{
for(s32 i=0;i<4;i++){
if(m_pTreeNode[i]){
m_pTreeNode[i]->visit(_visitor);
}
}
}
m_treeLock->unlock();
}
bool SVTree4::_isIn(SVNodePtr _node) {
FVec3 t_pos = _node->getPosition();
//这块z先改为了0!!!!!!!!!!!!
t_pos.z = 0;
//在内部(以1,2,3,4)现象为顺序
if( m_treeBox.inside(t_pos) ){
return true;
}
return false;
}
void SVTree4::addNode(SVNodePtr _node, s32 iZOrder){
if (_node){
_node->setZOrder(iZOrder);
addNode(_node);
}
}
//增加节点
void SVTree4::addNode(SVNodePtr _node) {
if(m_node) {
m_node->addChild(_node);
}else{
for(s32 i=0;i<4;i++){
if( m_pTreeNode[i]->_isIn(_node) ){
m_pTreeNode[i]->addNode(_node);
break;
}
}
}
}
//移除节点
bool SVTree4::removeNode(SVNodePtr _node) {
bool t_ret = false;
if(m_node) {
t_ret = m_node->removeChild(_node);
}else{
for(s32 i=0;i<4;i++){
if( m_pTreeNode[i]->removeNode(_node) ) {
return true;
}
}
}
return t_ret;
}
//清理节点
void SVTree4::clearNode() {
if(m_node) {
m_node->clearChild();
}else{
for(s32 i=0;i<4;i++){
m_pTreeNode[i]->clearNode();
}
}
}
bool SVTree4::hasNode(SVNodePtr _node) {
if(m_node) {
return m_node->hasChild(_node);
}else{
for(s32 i=0;i<4;i++){
if( m_pTreeNode[i]->hasNode(_node) ){
return true;
}
}
}
return false;
}
//逻辑场景
SVScene::SVScene(SVInst *_app,cptr8 _name)
:SVGBase(_app) {
m_name = _name;
m_color.setColorARGB(0x00000000);
m_worldW = 0;
m_worldH = 0;
m_worldD = 0;
//场景树
m_pSceneTree = MakeSharedPtr<SVTree4>(_app);
//渲染场景
m_pRenderScene = MakeSharedPtr<SVRenderScene>(_app);
}
SVScene::~SVScene() {
if(m_pSceneTree){
m_pSceneTree->destroy();
m_pSceneTree = nullptr;
}
m_pRenderScene = nullptr;
}
void SVScene::create(f32 _worldw ,f32 _worldh,s32 _depth){
m_worldW = _worldw;
m_worldH = _worldh;
m_worldD = _depth;
if(m_pSceneTree){
SVBoundBox _box;
FVec3 t_min,t_max;
t_min.set(-0.5f*_worldw,-0.5f*_worldh, 0.0f);
t_max.set(0.5f*_worldw,0.5f*_worldh, 0.0f);
_box.set(t_min, t_max);
m_pSceneTree->create(_box,_depth);
}
s32 m_sw = mApp->m_pGlobalParam->m_inner_width;
s32 m_sh = mApp->m_pGlobalParam->m_inner_height;
SVCameraNodePtr mainCamera = mApp->getCameraMgr()->getMainCamera();
if(mainCamera) {
mainCamera->resetCamera(m_sw,m_sh);
}
//
SVCameraNodePtr uiCamera = mApp->getCameraMgr()->getUICamera();
if(uiCamera) {
uiCamera->resetCamera(m_sw,m_sh);
}
//
}
void SVScene::destroy(){
}
void SVScene::addNode(SVNodePtr _node){
if(_node && m_pSceneTree){
m_pSceneTree->addNode(_node);
}
}
void SVScene::addNode(SVNodePtr _node,s32 _zorder){
if(_node && m_pSceneTree){
_node->setZOrder(_zorder);
addNode(_node);
}
}
void SVScene::removeNode(SVNodePtr _node){
if(_node && m_pSceneTree){
m_pSceneTree->removeNode(_node);
}
}
void SVScene::active() {
}
void SVScene::unactive() {
}
void SVScene::setSceneColor(f32 _r,f32 _g,f32 _b,f32 _a) {
m_color.setColor(_r, _g, _b, _a);
}
void SVScene::update(f32 dt) {
//遍历场景树
if(m_pSceneTree){
m_pSceneTree->update(dt);
}
//
SVRendererPtr t_renderer = mApp->getRenderer();
if( t_renderer && t_renderer->hasSVTex(E_TEX_MAIN) ){
if (m_pRenderScene && false == m_pRenderScene->isSuspend() ) {
SVRenderCmdFboBindPtr t_fbo_bind = MakeSharedPtr<SVRenderCmdFboBind>(t_renderer->getRenderTexture());
t_fbo_bind->mTag = "main_frame_bind";
m_pRenderScene->pushRenderCmd(RST_SCENE_BEGIN, t_fbo_bind);
//
SVRenderCmdClearPtr t_clear = MakeSharedPtr<SVRenderCmdClear>();
t_clear->mTag = "main_frame_clear";
t_clear->setRenderer(t_renderer);
t_clear->setClearColor(m_color.r, m_color.g, m_color.b, m_color.a);
m_pRenderScene->pushRenderCmd(RST_SCENE_BEGIN, t_clear);
//
SVRenderCmdFboUnbindPtr t_fbo_unbind = MakeSharedPtr<SVRenderCmdFboUnbind>(t_renderer->getRenderTexture());
t_fbo_unbind->mTag = "main_frame_unbind";
m_pRenderScene->pushRenderCmd(RST_SCENE_END, t_fbo_unbind);
}
}
}
void SVScene::visit(SVVisitorBasePtr _visitor){
if( m_pSceneTree ){
m_pSceneTree->visit(_visitor);
}
}
SVRenderScenePtr SVScene::getRenderRS(){
return m_pRenderScene;
}
bool SVScene::procEvent(SVEventPtr _event) {
return true;
}
//序列化场景
void SVScene::toJSON(RAPIDJSON_NAMESPACE::Document::AllocatorType &_allocator,
RAPIDJSON_NAMESPACE::Value &_objValue) {
RAPIDJSON_NAMESPACE::Value locationObj(RAPIDJSON_NAMESPACE::kObjectType);//创建一个Object类型的元素
locationObj.AddMember("name", RAPIDJSON_NAMESPACE::StringRef(m_name.c_str()), _allocator);
u32 t_color = m_color.getColorARGB();
locationObj.AddMember("color", t_color, _allocator);
locationObj.AddMember("worldw", m_worldW, _allocator);
locationObj.AddMember("worldh", m_worldH, _allocator);
locationObj.AddMember("worldd", m_worldD, _allocator);
//序列化树 ? 要做这么复杂吗
if(m_pSceneTree){
}
//
_objValue.AddMember("SVScene", locationObj, _allocator);
}
void SVScene::fromJSON(RAPIDJSON_NAMESPACE::Value &item) {
if (item.HasMember("name") && item["name"].IsString()) {
m_name = item["name"].GetString();
}
if (item.HasMember("color") && item["color"].IsUint()) {
u32 t_color = item["color"].GetUint();
m_color.setColorARGB(t_color);
}
if (item.HasMember("worldw") && item["worldw"].IsFloat()) {
m_worldW = item["worldw"].GetFloat();
}
if (item.HasMember("worldh") && item["worldh"].IsFloat()) {
m_worldH = item["worldh"].GetFloat();
}
if (item.HasMember("worldd") && item["worldd"].IsInt()) {
m_worldD = item["worldd"].GetInt();
}
//
if(!m_pSceneTree){
create(m_worldW,m_worldH,m_worldD);
}
}
| 26.259366 | 119 | 0.605685 | SVEChina |
85e7b434e4ae6c6d34529f621c507473dfc60304 | 1,067 | hpp | C++ | include/edlib/Hamiltonians/TITFIsing.hpp | chaeyeunpark/ExactDiagonalization | c93754e724486cc68453399c5dda6a2dadf45cb8 | [
"MIT"
] | 1 | 2021-04-24T08:47:05.000Z | 2021-04-24T08:47:05.000Z | include/edlib/Hamiltonians/TITFIsing.hpp | chaeyeunpark/ExactDiagonalization | c93754e724486cc68453399c5dda6a2dadf45cb8 | [
"MIT"
] | 1 | 2021-09-28T19:02:14.000Z | 2021-09-28T19:02:14.000Z | include/edlib/Hamiltonians/TITFIsing.hpp | chaeyeunpark/ExactDiagonalization | c93754e724486cc68453399c5dda6a2dadf45cb8 | [
"MIT"
] | 1 | 2020-03-22T18:59:11.000Z | 2020-03-22T18:59:11.000Z | #ifndef ED_TITFI_HPP
#define ED_TITFI_HPP
#include <cstdint>
#include <cassert>
#include <algorithm>
#include <map>
#include <boost/dynamic_bitset.hpp>
//#include "BitOperations.h"
#include "../Basis/AbstractBasis1D.hpp"
template<typename UINT>
class TITFIsing
{
private:
const edlib::AbstractBasis1D<UINT>& basis_;
double J_;
double h_;
public:
TITFIsing(const edlib::AbstractBasis1D<UINT>& basis, double J, double h)
: basis_(basis), J_(J), h_(h)
{
}
std::map<std::size_t,double> getCol(UINT n) const
{
unsigned int N = basis_.getN();
UINT a = basis_.getNthRep(n);
const boost::dynamic_bitset<> bs(N, a);
std::map<std::size_t, double> m;
for(unsigned int i = 0; i < N; i++)
{
//Next-nearest
{
unsigned int j = (i+1)%N;
int sgn = (1-2*bs[i])*(1-2*bs[j]);
m[n] += -J_*sgn; //ZZ
UINT s = a;
s ^= basis_.mask({i});
int bidx;
double coeff;
std::tie(bidx, coeff) = basis_.hamiltonianCoeff(s, n);
if(bidx >= 0)
m[bidx] += -h_*coeff;
}
}
return m;
}
};
#endif //ED_TITFI_HPP
| 18.084746 | 73 | 0.618557 | chaeyeunpark |
85e909132693dfd1cd383f02695d85108c993a7b | 1,182 | hpp | C++ | src/nxt_ipc.hpp | syldrathecat/nxtlauncher | 9856999bed2531067a44a319a8b37f726d2ffb0a | [
"Unlicense"
] | 13 | 2016-09-15T23:04:48.000Z | 2021-02-27T01:42:31.000Z | src/nxt_ipc.hpp | syldrathecat/nxtlauncher | 9856999bed2531067a44a319a8b37f726d2ffb0a | [
"Unlicense"
] | 13 | 2017-04-22T16:00:07.000Z | 2020-10-13T18:18:29.000Z | src/nxt_ipc.hpp | syldrathecat/nxtlauncher | 9856999bed2531067a44a319a8b37f726d2ffb0a | [
"Unlicense"
] | 2 | 2016-09-15T19:49:24.000Z | 2018-12-28T03:11:50.000Z | #ifndef NXT_IPC_HPP
#define NXT_IPC_HPP
#include "nxt_fifo.hpp"
#include "nxt_message.hpp"
#include <functional>
#include <map>
// Creates and manages a pair of named pipes for communicating with the client
class nxt_ipc
{
public:
using handler_t = std::function<void(nxt_message&)>;
private:
nxt_fifo m_fifo_in;
nxt_fifo m_fifo_out;
std::map<int, handler_t> m_handlers;
void handle(nxt_message& message);
public:
// Initializes the files for IPC
nxt_ipc(const char* fifo_in_filename, const char* fifo_out_filename);
// Not copyable
nxt_ipc(const nxt_ipc&) = delete;
nxt_ipc& operator=(const nxt_ipc&) = delete;
// Moveable, but probably a bad idea if handlers reference the original
nxt_ipc(nxt_ipc&&) = default;
nxt_ipc& operator=(nxt_ipc&&) = default;
// Registers a handler for a given message ID
// Registering new handlers will overwrite old ones
void register_handler(int message_id, handler_t handler);
// Starts pumping messages and executing handlers
// (expected to be called from a separate thread)
void operator()();
// Sends a message to the client
void send(const nxt_message& msg);
};
#endif // NXT_IPC_HPP
| 23.64 | 78 | 0.733503 | syldrathecat |
85f1f0920a744c4e5ecaada128864ecc85a924ea | 982 | cc | C++ | kraken/resources/home/dnanexus/jellyfish-1.1.11/jellyfish/dna_codes.cc | transcript/DNAnexus_apps | 12c2ba6f57b805a9fcf6e1da4f9d64394ef72256 | [
"MIT"
] | 3 | 2015-11-20T19:40:29.000Z | 2019-07-25T15:34:24.000Z | kraken/resources/home/dnanexus/jellyfish-1.1.11/jellyfish/dna_codes.cc | transcript/DNAnexus_apps | 12c2ba6f57b805a9fcf6e1da4f9d64394ef72256 | [
"MIT"
] | null | null | null | kraken/resources/home/dnanexus/jellyfish-1.1.11/jellyfish/dna_codes.cc | transcript/DNAnexus_apps | 12c2ba6f57b805a9fcf6e1da4f9d64394ef72256 | [
"MIT"
] | 2 | 2018-09-20T08:28:36.000Z | 2019-03-06T06:26:52.000Z | #include <jellyfish/dna_codes.hpp>
#define R -1
#define I -2
#define O -3
#define A 0
#define C 1
#define G 2
#define T 3
const char jellyfish::dna_codes[256] = {
O, O, O, O, O, O, O, O, O, O, I, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, R, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, A, R, C, R, O, O, G, R, O, O, R, O, R, R, O,
O, O, R, R, T, O, R, R, R, R, O, O, O, O, O, O,
O, A, R, C, R, O, O, G, R, O, O, R, O, R, R, O,
O, O, R, R, T, O, R, R, R, R, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O
};
| 33.862069 | 50 | 0.376782 | transcript |
85f21279c2ed92b54cf93e1bc15da260fe5fffc6 | 7,756 | hpp | C++ | include/GlobalNamespace/LocalNetworkPlayersViewController.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/LocalNetworkPlayersViewController.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/LocalNetworkPlayersViewController.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: NetworkPlayersViewController
#include "GlobalNamespace/NetworkPlayersViewController.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine::UI
namespace UnityEngine::UI {
// Forward declaring type: Toggle
class Toggle;
}
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: LocalNetworkPlayerModel
class LocalNetworkPlayerModel;
// Forward declaring type: INetworkConfig
class INetworkConfig;
// Forward declaring type: INetworkPlayerModel
class INetworkPlayerModel;
}
// Forward declaring namespace: HMUI
namespace HMUI {
// Forward declaring type: ToggleBinder
class ToggleBinder;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Size: 0xBA
#pragma pack(push, 1)
// Autogenerated type: LocalNetworkPlayersViewController
class LocalNetworkPlayersViewController : public GlobalNamespace::NetworkPlayersViewController {
public:
// private UnityEngine.UI.Toggle _enableNetworkingToggle
// Size: 0x8
// Offset: 0x90
UnityEngine::UI::Toggle* enableNetworkingToggle;
// Field size check
static_assert(sizeof(UnityEngine::UI::Toggle*) == 0x8);
// private UnityEngine.UI.Toggle _enableOpenPartyToggle
// Size: 0x8
// Offset: 0x98
UnityEngine::UI::Toggle* enableOpenPartyToggle;
// Field size check
static_assert(sizeof(UnityEngine::UI::Toggle*) == 0x8);
// [InjectAttribute] Offset: 0xE25520
// private readonly LocalNetworkPlayerModel _localNetworkPlayerModel
// Size: 0x8
// Offset: 0xA0
GlobalNamespace::LocalNetworkPlayerModel* localNetworkPlayerModel;
// Field size check
static_assert(sizeof(GlobalNamespace::LocalNetworkPlayerModel*) == 0x8);
// [InjectAttribute] Offset: 0xE25530
// private readonly INetworkConfig _networkConfig
// Size: 0x8
// Offset: 0xA8
GlobalNamespace::INetworkConfig* networkConfig;
// Field size check
static_assert(sizeof(GlobalNamespace::INetworkConfig*) == 0x8);
// private HMUI.ToggleBinder _toggleBinder
// Size: 0x8
// Offset: 0xB0
HMUI::ToggleBinder* toggleBinder;
// Field size check
static_assert(sizeof(HMUI::ToggleBinder*) == 0x8);
// private System.Boolean _enableBroadcasting
// Size: 0x1
// Offset: 0xB8
bool enableBroadcasting;
// Field size check
static_assert(sizeof(bool) == 0x1);
// private System.Boolean _allowAnyoneToJoin
// Size: 0x1
// Offset: 0xB9
bool allowAnyoneToJoin;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Creating value type constructor for type: LocalNetworkPlayersViewController
LocalNetworkPlayersViewController(UnityEngine::UI::Toggle* enableNetworkingToggle_ = {}, UnityEngine::UI::Toggle* enableOpenPartyToggle_ = {}, GlobalNamespace::LocalNetworkPlayerModel* localNetworkPlayerModel_ = {}, GlobalNamespace::INetworkConfig* networkConfig_ = {}, HMUI::ToggleBinder* toggleBinder_ = {}, bool enableBroadcasting_ = {}, bool allowAnyoneToJoin_ = {}) noexcept : enableNetworkingToggle{enableNetworkingToggle_}, enableOpenPartyToggle{enableOpenPartyToggle_}, localNetworkPlayerModel{localNetworkPlayerModel_}, networkConfig{networkConfig_}, toggleBinder{toggleBinder_}, enableBroadcasting{enableBroadcasting_}, allowAnyoneToJoin{allowAnyoneToJoin_} {}
// private System.Void HandleNetworkingToggleChanged(System.Boolean enabled)
// Offset: 0x10D48F4
void HandleNetworkingToggleChanged(bool enabled);
// private System.Void HandleOpenPartyToggleChanged(System.Boolean openParty)
// Offset: 0x10D4904
void HandleOpenPartyToggleChanged(bool openParty);
// private System.Void RefreshParty(System.Boolean overrideHide)
// Offset: 0x10D4790
void RefreshParty(bool overrideHide);
// public override System.String get_myPartyTitle()
// Offset: 0x10D45B8
// Implemented from: NetworkPlayersViewController
// Base method: System.String NetworkPlayersViewController::get_myPartyTitle()
::Il2CppString* get_myPartyTitle();
// public override System.String get_otherPlayersTitle()
// Offset: 0x10D4600
// Implemented from: NetworkPlayersViewController
// Base method: System.String NetworkPlayersViewController::get_otherPlayersTitle()
::Il2CppString* get_otherPlayersTitle();
// public override INetworkPlayerModel get_networkPlayerModel()
// Offset: 0x10D4648
// Implemented from: NetworkPlayersViewController
// Base method: INetworkPlayerModel NetworkPlayersViewController::get_networkPlayerModel()
GlobalNamespace::INetworkPlayerModel* get_networkPlayerModel();
// protected override System.Void NetworkPlayersViewControllerDidActivate(System.Boolean firstActivation, System.Boolean addedToHierarchy)
// Offset: 0x10D4650
// Implemented from: NetworkPlayersViewController
// Base method: System.Void NetworkPlayersViewController::NetworkPlayersViewControllerDidActivate(System.Boolean firstActivation, System.Boolean addedToHierarchy)
void NetworkPlayersViewControllerDidActivate(bool firstActivation, bool addedToHierarchy);
// protected override System.Void DidDeactivate(System.Boolean removedFromHierarchy, System.Boolean screenSystemDisabling)
// Offset: 0x10D48B0
// Implemented from: NetworkPlayersViewController
// Base method: System.Void NetworkPlayersViewController::DidDeactivate(System.Boolean removedFromHierarchy, System.Boolean screenSystemDisabling)
void DidDeactivate(bool removedFromHierarchy, bool screenSystemDisabling);
// protected override System.Void OnDestroy()
// Offset: 0x10D48C0
// Implemented from: NetworkPlayersViewController
// Base method: System.Void NetworkPlayersViewController::OnDestroy()
void OnDestroy();
// public System.Void .ctor()
// Offset: 0x10D4914
// Implemented from: NetworkPlayersViewController
// Base method: System.Void NetworkPlayersViewController::.ctor()
// Base method: System.Void ViewController::.ctor()
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static LocalNetworkPlayersViewController* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::LocalNetworkPlayersViewController::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<LocalNetworkPlayersViewController*, creationType>()));
}
}; // LocalNetworkPlayersViewController
#pragma pack(pop)
static check_size<sizeof(LocalNetworkPlayersViewController), 185 + sizeof(bool)> __GlobalNamespace_LocalNetworkPlayersViewControllerSizeCheck;
static_assert(sizeof(LocalNetworkPlayersViewController) == 0xBA);
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::LocalNetworkPlayersViewController*, "", "LocalNetworkPlayersViewController");
| 52.405405 | 675 | 0.746648 | darknight1050 |
85fa1b1b64a0a9bf281e92dcf003ea04f2beab63 | 7,853 | cpp | C++ | obliczanie-wieku/AgeCalculator.cpp | MHellFire/random-stuff | f8d05af9019df67fcf7164a3b716e4db17d18e6a | [
"MIT"
] | null | null | null | obliczanie-wieku/AgeCalculator.cpp | MHellFire/random-stuff | f8d05af9019df67fcf7164a3b716e4db17d18e6a | [
"MIT"
] | null | null | null | obliczanie-wieku/AgeCalculator.cpp | MHellFire/random-stuff | f8d05af9019df67fcf7164a3b716e4db17d18e6a | [
"MIT"
] | null | null | null | /*********************************************************************************
* This file is part of Age Calculator. *
* *
* Copyright © 2019 Mariusz Helfajer *
* *
* This software may be modified and distributed under the terms *
* of the MIT license. See the LICENSE files for details. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy *
* of this software and associated documentation files (the "Software"), to deal *
* in the Software without restriction, including without limitation the rights *
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *
* copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN *
* THE SOFTWARE. *
* *******************************************************************************/
#include <iostream>
#include <cmath>
#include <ctime>
#include <QDate>
#include <QtMath>
// Returns age[0] = years; age[1] = months; age[2] = days;
// or nullptr if any of the given dates is not valid or if the birth date is from the future.
int* calculateAge(const QDate &birthDate, const QDate &todayDate)
{
// check if the birth date is valid date
if (!birthDate.isValid())
return nullptr;
// check if the today date is valid date
if (!todayDate.isValid())
return nullptr;
// check if the birth date is not from the future
if (birthDate > todayDate)
return nullptr;
int *age = new int[3]; // age[0] = years; age[1] = months; age[2] = days;
int t1 = birthDate.year()*12 + birthDate.month() - 1; // total months for birthdate
int t2 = todayDate.year()*12 + todayDate.month() - 1; // total months for now
int dm = t2 - t1; // delta months
if (todayDate.day() >= birthDate.day())
{
age[0] = qFloor(dm/12); // years
age[1] = dm%12; // months
age[2] = todayDate.day() - birthDate.day(); // days
}
else
{
dm--;
age[0] = qFloor(dm/12); // years
age[1] = dm%12; // months
age[2] = birthDate.daysInMonth() - birthDate.day() + todayDate.day(); // days
}
return age;
}
// Returns true if the specified year is a leap year; otherwise returns false.
bool isLeapYear(int year)
{
// No year 0 in Gregorian calendar, so -1, -5, -9 etc are leap years
// ISO 8601 - year 0000 is being equal to 1 BC
if (year < 1)
++year;
return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
}
// Returns the number of days in the month (28 to 31) for given date. Returns 0 if the date is invalid.
int daysInMonth(const tm &date)
{
const char monthDays[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (date.tm_mon == 2 && isLeapYear(date.tm_year))
return 29;
else
return monthDays[date.tm_mon];
}
// Returns age[0] = years; age[1] = months; age[2] = days;
// or nullptr if any of the given dates is not valid or if the birth date is from the future.
int* calculateAge2(const tm &birthDate, const tm &todayDate)
{
// TODO: check if dates are valid
// check if the birth date is not from the future
if (birthDate.tm_year > todayDate.tm_year)
return nullptr;
else if (birthDate.tm_year == todayDate.tm_year && birthDate.tm_mon > todayDate.tm_mon)
return nullptr;
else if (birthDate.tm_year == todayDate.tm_year && birthDate.tm_mon > todayDate.tm_mon && birthDate.tm_mday > todayDate.tm_mday)
return nullptr;
int *age = new int[3]; // age[0] = years; age[1] = months; age[2] = days;
int t1 = birthDate.tm_year*12 + birthDate.tm_mon - 1; // total months for birthdate
int t2 = todayDate.tm_year*12 + todayDate.tm_mon - 1; // total months for now
int dm = t2 - t1; // delta months
if (todayDate.tm_mday >= birthDate.tm_mday)
{
age[0] = int(floor(dm/12)); // years
age[1] = dm%12; // months
age[2] = todayDate.tm_mday - birthDate.tm_mday; // days
}
else
{
dm--;
age[0] = int(floor(dm/12)); // years
age[1] = dm%12; // months
age[2] = daysInMonth(birthDate) - birthDate.tm_mday + todayDate.tm_mday; // days
}
return age;
}
int main(int argc, char *argv[])
{
(void)(argc);
(void)(argv);
QDate birthDate(QDate(2006, 1, 30));
QDate currentDate(QDate::currentDate());
int *tmp = calculateAge(birthDate, currentDate);
if (tmp != nullptr)
{
std::cout << "Birth date: " << birthDate.toString("dd.MM.yyyy").toStdString() << std::endl;
std::cout << "Current date: " << currentDate.toString("dd.MM.yyyy").toStdString() << std::endl;
std::cout << "Years: " << tmp[0] << std::endl;
std::cout << "Months: " << tmp[1] << std::endl;
std::cout << "Days: " << tmp[2] << std::endl << std::endl;
}
delete []tmp;
tm birthDate2;
birthDate2.tm_year = birthDate.year();
birthDate2.tm_mon = birthDate.month();
birthDate2.tm_mday = birthDate.day();
tm currentDate2;
currentDate2.tm_year = currentDate.year();
currentDate2.tm_mon = currentDate.month();
currentDate2.tm_mday = currentDate.day();
int *tmp2 = calculateAge2(birthDate2, currentDate2);
if (tmp2 != nullptr)
{
char date[11];
birthDate2.tm_year-=1900; // int tm_year; years since 1900
birthDate2.tm_mon-=1; // int tm_mon; months since January [0, 11]
if (strftime(date, sizeof(date), "%d.%m.%Y", &birthDate2) != 0)
{
std::cout << "Birth date: " << date << std::endl;
}
currentDate2.tm_year-=1900; // int tm_year; years since 1900
currentDate2.tm_mon-=1; // int tm_mon; months since January [0, 11]
if (strftime(date, sizeof(date), "%d.%m.%Y", ¤tDate2) != 0)
{
std::cout << "Current date: " << date << std::endl;
}
std::cout << "Years: " << tmp2[0] << std::endl;
std::cout << "Months: " << tmp2[1] << std::endl;
std::cout << "Days: " << tmp2[2] << std::endl << std::endl;
}
delete []tmp2;
}
| 41.771277 | 132 | 0.517255 | MHellFire |
85fc290a665174108915a6b4f77f7fc8b8808d7b | 459 | hpp | C++ | src/app.hpp | trazfr/alarm | ea511eb0f16945de2005d828f452c76fce9d77e7 | [
"MIT"
] | null | null | null | src/app.hpp | trazfr/alarm | ea511eb0f16945de2005d828f452c76fce9d77e7 | [
"MIT"
] | null | null | null | src/app.hpp | trazfr/alarm | ea511eb0f16945de2005d828f452c76fce9d77e7 | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
/**
* @brief Represents the whole application
*/
class App
{
public:
struct Impl;
/**
* @attention the class keeps a reference to constructor's arguments. Make sure they stay valid
*/
explicit App(const char *configurationFile);
~App();
/**
* Runs the application
*
* This method only returns at exit time
*/
void run();
private:
std::unique_ptr<Impl> pimpl;
};
| 15.827586 | 99 | 0.614379 | trazfr |
85fe846c064c03a415db9da5779bc34a873d8e03 | 436 | cpp | C++ | matrix_using_array.cpp | xeroxzen/C-Crash-Course | d394d6d91f4f0126b3742a9d11abc129f3daaeb4 | [
"MIT"
] | 1 | 2022-02-09T00:47:25.000Z | 2022-02-09T00:47:25.000Z | matrix_using_array.cpp | xeroxzen/C-Crash-Course | d394d6d91f4f0126b3742a9d11abc129f3daaeb4 | [
"MIT"
] | null | null | null | matrix_using_array.cpp | xeroxzen/C-Crash-Course | d394d6d91f4f0126b3742a9d11abc129f3daaeb4 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(){
//Declare a 2 dimensional array of a 3x3 matrix
//Each matrix element has a value of 1 or 0
int matrix[3][3] = {
{1, 0, 1},
{0, 1, 0},
{1, 0, 1}
};
//print out the matrix
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
} | 20.761905 | 51 | 0.444954 | xeroxzen |
85ff51c427c7553b4d4520a5dca730d35c5948db | 917 | cpp | C++ | fenwick_tree/coder_rating.cpp | ankit2001/CP_Algos | eadc0f9cd92a5a01791e3171dfe894e6db948b2b | [
"MIT"
] | 1 | 2020-08-11T17:50:01.000Z | 2020-08-11T17:50:01.000Z | fenwick_tree/coder_rating.cpp | ankit2001/CP_Algos | eadc0f9cd92a5a01791e3171dfe894e6db948b2b | [
"MIT"
] | null | null | null | fenwick_tree/coder_rating.cpp | ankit2001/CP_Algos | eadc0f9cd92a5a01791e3171dfe894e6db948b2b | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#define ll long long int
using namespace std;
#define F first
#define S second
void update(ll index, vector<ll> &BIT){
for(ll i=index;i<=100000;i+=i&(-i)){
BIT[i]++;
}
}
ll query(ll index, vector<ll> &BIT){
ll count=0;
for(ll i=index;i>0;i-=i&(-i)){
count+=BIT[i];
}
return count;
}
int main(){
vector<ll> BIT(100001,0);
BIT[0]=0;
ll n;
cin>>n;
vector<pair<pair<ll,ll>,ll>> v(n);
for(ll i=0;i<n;i++){
ll x,y;
cin>>x>>y;
v[i]={{x,y},i};
}
ll ans[n];
sort(v.begin(),v.end());
for(ll i=0;i<n;i++){
ll end=i;
while(end<n and v[i].F.F==v[end].F.F and v[i].F.S==v[end].F.S){
end++;
}
for(ll j=i;j<end;j++){
ans[v[j].S]=query(v[j].F.S,BIT);
}
for(ll j=i;j<end;j++){
update(v[j].F.S,BIT);
}
i=end;
i--;
}
for(ll i=0;i<n;i++){
cout<<ans[i]<<endl;
}
return 0;
} | 17.634615 | 68 | 0.485278 | ankit2001 |
65a0b02f10bf6c385424cfdc0344cdf983b4fa58 | 1,352 | hpp | C++ | render_view.hpp | piccolo255/pde-pathtracer | d754583a308975b68675076f68f1194cbaa906ca | [
"Unlicense"
] | null | null | null | render_view.hpp | piccolo255/pde-pathtracer | d754583a308975b68675076f68f1194cbaa906ca | [
"Unlicense"
] | null | null | null | render_view.hpp | piccolo255/pde-pathtracer | d754583a308975b68675076f68f1194cbaa906ca | [
"Unlicense"
] | null | null | null | #ifndef RENDER_VIEW_HPP
#define RENDER_VIEW_HPP
// Qt includes
#include <QWidget>
#include <QPainter>
#include <QList>
#include <QMap>
// C++ includes
// math expression parsing header
#include "muParser.h"
// Local includes
#include "ode_pathtracer.hpp"
class RenderView : public QWidget
{
Q_OBJECT
public:
explicit RenderView( QRect viewportArea
, QString transformationX
, QString transformationY
, QStringList paramNames
, QWidget *parent = 0 );
~RenderView();
void updateObjects( QList<PointValues> pointPathList, int maxPathLength );
private:
QRect viewRect;
QRect viewRectAlwaysVisible;
double pointX;
double pointY;
double t;
// QStringList paramsName;
// QMap<QString, double> paramsVal;
// QMap<QString, int> paramsIndex;
QVector<double> paramVals;
QVector<mu::Parser *> coordinateParsers;
QVector<QLineF> segments;
QVector<QColor> colors;
int maxSegments = 0;
void updateViewRect( QSize newViewRectSize );
void updateColors();
void ParserError( mu::Parser::exception_type &e );
signals:
public slots:
// QWidget interface
protected:
void paintEvent( QPaintEvent *event ) override;
void resizeEvent( QResizeEvent *event ) override;
};
#endif // RENDER_VIEW_HPP
| 21.460317 | 77 | 0.674556 | piccolo255 |
65a34c65c61e56339bec1735c5007ea2009e2588 | 853 | cpp | C++ | dark_roads.cpp | mvgmb/Marathon | 0dcc428a5e6858e2427fb40cefbd7453d1abcdb5 | [
"Xnet",
"X11"
] | null | null | null | dark_roads.cpp | mvgmb/Marathon | 0dcc428a5e6858e2427fb40cefbd7453d1abcdb5 | [
"Xnet",
"X11"
] | null | null | null | dark_roads.cpp | mvgmb/Marathon | 0dcc428a5e6858e2427fb40cefbd7453d1abcdb5 | [
"Xnet",
"X11"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int parent[200005];
int size[200005];
vector<tuple<int,int,int> > lis;
int find(int x) {
if(x != parent[x]) parent[x] = find(parent[x]);
return parent[x];
}
bool same(int a, int b) {
return find(a) == find(b);
}
void unite(int a,int b) {
a = find(a);
b = find(b);
if(size[a] < size[b]) swap(a,b);
size[a] += size[b];
parent[b] = a;
}
int main() {
int m, n, u, v, w, i, c, tot;
while(cin >> m >> n && m != 0 && n != 0) {
for(i=0;i<m;i++) {
parent[i] = i;
size[i] = 1;
}
lis.clear();
tot = 0;
while(n--) {
cin >> u >> v >> w;
tot += w;
lis.push_back(make_tuple(w,u,v));
}
sort(lis.begin(),lis.end());
c = 0;
for(i=0;i<lis.size();i++) {
tie(w,u,v) = lis[i];
if(!same(u,v)) {
c += w;
unite(u,v);
}
}
cout << (tot- c) << endl;
}
return 0;
} | 16.403846 | 48 | 0.494725 | mvgmb |
65a4e8c1c6e529c6cdc1a015ccca4a644b955680 | 279 | cpp | C++ | Codeforces Online Judge Solve/all divs/main (9).cpp | Remonhasan/programming-solve | 5a4ac8c738dd361e1c974162e0eaebbaae72fd80 | [
"Apache-2.0"
] | null | null | null | Codeforces Online Judge Solve/all divs/main (9).cpp | Remonhasan/programming-solve | 5a4ac8c738dd361e1c974162e0eaebbaae72fd80 | [
"Apache-2.0"
] | null | null | null | Codeforces Online Judge Solve/all divs/main (9).cpp | Remonhasan/programming-solve | 5a4ac8c738dd361e1c974162e0eaebbaae72fd80 | [
"Apache-2.0"
] | null | null | null | /*last time Tumi ami from uap*/
#include <iostream>
using namespace std;
typedef long long ll;
int main() {
ll a,ami;
cin>>a>>ami;
ll tumi=a;
ll taka=0;
while(tumi<ami){
tumi*=a;
taka++;
}
if(tumi==ami)
cout<<"YES"<<endl<<taka;
else
cout<<"NO";
return 0;
}
| 13.285714 | 31 | 0.598566 | Remonhasan |
65acc90ed1a5c8e334436ca0894d3f2b89478da0 | 23,489 | hpp | C++ | include/ak_toolkit/markable.hpp | akrzemi1/markable | fc435319fb32ed5753e6ae6762f78d98e0d33c73 | [
"BSL-1.0"
] | 82 | 2016-03-12T11:53:55.000Z | 2022-02-17T15:18:02.000Z | include/ak_toolkit/markable.hpp | akrzemi1/markable | fc435319fb32ed5753e6ae6762f78d98e0d33c73 | [
"BSL-1.0"
] | 10 | 2016-03-12T13:53:49.000Z | 2020-12-17T22:20:16.000Z | include/ak_toolkit/markable.hpp | akrzemi1/markable | fc435319fb32ed5753e6ae6762f78d98e0d33c73 | [
"BSL-1.0"
] | 11 | 2016-09-01T15:53:32.000Z | 2021-09-28T15:51:32.000Z | // Copyright (C) 2015-2021 Andrzej Krzemienski.
//
// 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)
#ifndef AK_TOOLBOX_COMPACT_OPTIONAL_HEADER_GUARD_
#define AK_TOOLBOX_COMPACT_OPTIONAL_HEADER_GUARD_
#include <cassert>
#include <utility>
#include <limits>
#include <new>
#include <type_traits>
#include <limits>
# if defined AK_TOOLKIT_WITH_CONCEPTS
#include <concepts>
# endif
#if defined AK_TOOLBOX_NO_ARVANCED_CXX11
# define AK_TOOLKIT_NOEXCEPT
# define AK_TOOLKIT_IS_NOEXCEPT(E) true
# define AK_TOOLKIT_CONSTEXPR
# define AK_TOOLKIT_CONSTEXPR_OR_CONST const
# define AK_TOOLKIT_EXPLICIT_CONV
# define AK_TOOLKIT_NOEXCEPT_AS(E)
#else
# define AK_TOOLKIT_NOEXCEPT noexcept
# define AK_TOOLKIT_IS_NOEXCEPT(E) noexcept(E)
# define AK_TOOLKIT_CONSTEXPR constexpr
# define AK_TOOLKIT_CONSTEXPR_OR_CONST constexpr
# define AK_TOOLKIT_EXPLICIT_CONV explicit
# define AK_TOOLKIT_NOEXCEPT_AS(E) noexcept(noexcept(E))
# define AK_TOOLKIT_CONSTEXPR_NOCONST // fix in the future
#endif
#ifndef AK_TOOLKIT_LIKELY
# if defined __GNUC__
# define AK_TOOLKIT_LIKELY(EXPR) __builtin_expect(!!(EXPR), 1)
# else
# define AK_TOOLKIT_LIKELY(EXPR) (!!(EXPR))
# endif
#endif
#ifndef AK_TOOLKIT_ASSERT
# if defined NDEBUG
# define AK_TOOLKIT_ASSERT(EXPR) void(0)
# else
# define AK_TOOLKIT_ASSERT(EXPR) ( AK_TOOLKIT_LIKELY(EXPR) ? void(0) : []{assert(!#EXPR);}() )
# endif
#endif
#ifndef AK_TOOLKIT_ASSERTED_EXPRESSION
# if defined NDEBUG
# define AK_TOOLKIT_ASSERTED_EXPRESSION(CHECK, EXPR) (EXPR)
# else
# define AK_TOOLKIT_ASSERTED_EXPRESSION(CHECK, EXPR) (AK_TOOLKIT_LIKELY(CHECK) ? (EXPR) : ([]{assert(!#CHECK);}(), (EXPR)))
# endif
#endif
#if defined __cpp_concepts && __cpp_concepts == 201507
// TODO: will conditionally support concepts
#endif
namespace ak_toolkit {
namespace markable_ns {
# if defined AK_TOOLKIT_WITH_CONCEPTS
template <typename MP>
concept mark_policy =
requires
{
typename MP::value_type;
typename MP::storage_type;
typename MP::reference_type;
typename MP::representation_type;
} &&
requires(const typename MP::representation_type & cr,
typename MP::representation_type && rr,
const typename MP::storage_type & s,
const typename MP::value_type & cv,
typename MP::value_type && rv)
{
{ MP::marked_value() }
-> ::std::convertible_to<typename MP::representation_type>;
{ MP::is_marked_value(cr) }
-> ::std::convertible_to<bool>;
{ MP::access_value(s) }
-> ::std::same_as<typename MP::reference_type>;
{ MP::representation(s) }
-> ::std::same_as<const typename MP::representation_type &>;
{ MP::store_value(cv) }
-> ::std::convertible_to<typename MP::storage_type>;
{ MP::store_value(::std::move(rv)) }
-> ::std::convertible_to<typename MP::storage_type>;
{ MP::store_representation(cr) }
-> ::std::convertible_to<typename MP::storage_type>;
{ MP::store_representation(::std::move(rr)) }
-> ::std::convertible_to<typename MP::storage_type>;
};
# define AK_TOOLKIT_MARK_POLICY mark_policy
# else
# define AK_TOOLKIT_MARK_POLICY typename
# endif
struct default_tag{};
template <typename T, typename REPT = T, typename CREF = const T&, typename STOR = REPT>
struct markable_type
{
typedef T value_type; // the type we claim we (optionally) store
typedef REPT representation_type; // the type we use to represent the marked state
typedef CREF reference_type; // the type that we return upon "dereference"
typedef STOR storage_type; // the type we use for storage
static AK_TOOLKIT_CONSTEXPR reference_type access_value(const storage_type& v) { return reference_type(v); }
static AK_TOOLKIT_CONSTEXPR const representation_type& representation(const storage_type& v) { return v; }
static AK_TOOLKIT_CONSTEXPR const storage_type& store_value(const value_type& v) { return v; }
static AK_TOOLKIT_CONSTEXPR storage_type&& store_value(value_type&& v) { return std::move(v); }
static AK_TOOLKIT_CONSTEXPR const storage_type& store_representation(const representation_type& v) { return v; }
static AK_TOOLKIT_CONSTEXPR storage_type&& store_representation(representation_type&& v) { return std::move(v); }
};
template <typename T, T Val>
struct mark_int : markable_type<T>
{
static AK_TOOLKIT_CONSTEXPR T marked_value() AK_TOOLKIT_NOEXCEPT { return Val; }
static AK_TOOLKIT_CONSTEXPR bool is_marked_value(T v) AK_TOOLKIT_NOEXCEPT { return v == Val; }
};
template <typename FPT>
struct mark_fp_nan : markable_type<FPT>
{
static AK_TOOLKIT_CONSTEXPR FPT marked_value() AK_TOOLKIT_NOEXCEPT { return std::numeric_limits<FPT>::quiet_NaN(); }
static AK_TOOLKIT_CONSTEXPR bool is_marked_value(FPT v) AK_TOOLKIT_NOEXCEPT { return v != v; }
};
template <typename T> // requires Regular<T>
struct mark_value_init : markable_type<T>
{
static AK_TOOLKIT_CONSTEXPR T marked_value() AK_TOOLKIT_NOEXCEPT_AS(T()) { return T(); }
static AK_TOOLKIT_CONSTEXPR bool is_marked_value(const T& v) AK_TOOLKIT_NOEXCEPT_AS(T()) { return v == T(); }
};
template <typename T>
struct mark_stl_empty : markable_type<T>
{
static AK_TOOLKIT_CONSTEXPR T marked_value() AK_TOOLKIT_NOEXCEPT_AS(T()) { return T(); }
static AK_TOOLKIT_CONSTEXPR bool is_marked_value(const T& v) { return v.empty(); }
};
template <typename OT>
struct mark_optional : markable_type<typename OT::value_type, OT>
{
typedef typename OT::value_type value_type;
typedef OT storage_type;
static OT marked_value() AK_TOOLKIT_NOEXCEPT { return OT(); }
static bool is_marked_value(const OT& v) { return !v; }
static const value_type& access_value(const storage_type& v) { return *v; }
static storage_type store_value(const value_type& v) { return v; }
static storage_type store_value(value_type&& v) { return std::move(v); }
};
struct mark_bool : markable_type<bool, char, bool>
{
static AK_TOOLKIT_CONSTEXPR char marked_value() AK_TOOLKIT_NOEXCEPT { return char(2); }
static AK_TOOLKIT_CONSTEXPR bool is_marked_value(char v) AK_TOOLKIT_NOEXCEPT { return v == 2; }
static AK_TOOLKIT_CONSTEXPR bool access_value(const char& v) { return bool(v); }
static AK_TOOLKIT_CONSTEXPR char store_value(const bool& v) { return v; }
};
#ifndef AK_TOOLBOX_NO_UNDERLYING_TYPE
template <typename Enum, typename std::underlying_type<Enum>::type Val>
struct mark_enum : markable_type<Enum, typename std::underlying_type<Enum>::type, Enum>
{
typedef markable_type<Enum, typename std::underlying_type<Enum>::type, Enum> base;
static_assert(std::is_enum<Enum>::value, "mark_enum only works with enum types");
#else
template <typename Enum, int Val>
struct mark_enum : markable_type<Enum, int, Enum>
{
typedef markable_type<Enum, int, Enum> base;
static_assert(sizeof(Enum) == sizeof(int), "in this compiler underlying type of enum must be int");
#endif // AK_TOOLBOX_NO_UNDERLYING_TYPE
typedef typename base::representation_type representation_type;
typedef typename base::storage_type storage_type;
static AK_TOOLKIT_CONSTEXPR representation_type marked_value() AK_TOOLKIT_NOEXCEPT { return Val; }
static AK_TOOLKIT_CONSTEXPR bool is_marked_value(const representation_type& v) AK_TOOLKIT_NOEXCEPT { return v == Val; }
static AK_TOOLKIT_CONSTEXPR Enum access_value(const storage_type& v) AK_TOOLKIT_NOEXCEPT { return static_cast<Enum>(v); }
static AK_TOOLKIT_CONSTEXPR storage_type store_value(const Enum& v) AK_TOOLKIT_NOEXCEPT { return static_cast<storage_type>(v); }
};
namespace detail_ {
struct _init_nothing_tag {};
template <typename MP>
union dual_storage_union
{
typedef typename MP::value_type value_type;
typedef typename MP::representation_type representation_type;
char _nothing;
value_type _value;
representation_type _marking;
constexpr explicit dual_storage_union(_init_nothing_tag) AK_TOOLKIT_NOEXCEPT
: _nothing() {}
constexpr explicit dual_storage_union(representation_type && v) AK_TOOLKIT_NOEXCEPT_AS(representation_type(std::move(v)))
: _marking(std::move(v)) {}
constexpr explicit dual_storage_union(value_type && v) AK_TOOLKIT_NOEXCEPT_AS(value_type(std::move(v)))
: _value(std::move(v)) {}
constexpr explicit dual_storage_union(const value_type& v) AK_TOOLKIT_NOEXCEPT_AS(value_type(std::move(v)))
: _value(v) {}
~dual_storage_union() {/* nothing here; will be properly destroyed by the owner */}
};
template <typename MVP, typename = void>
struct check_safe_dual_storage_exception_safety : ::std::true_type {};
template <typename MVP>
struct check_safe_dual_storage_exception_safety<MVP, typename MVP::is_safe_dual_storage_mark_policy>
: std::integral_constant<bool, AK_TOOLKIT_IS_NOEXCEPT(typename MVP::representation_type(MVP::marked_value()))>
{
};
} // namespace detail_
template <typename T>
struct representation_of
{
static_assert(sizeof(T) == 0, "class template representation_of<T> needs to be specialized for your type");
};
template <typename MP>
struct dual_storage
{
typedef typename MP::value_type value_type;
typedef typename MP::representation_type representation_type;
typedef typename MP::reference_type reference_type;
private:
typedef detail_::dual_storage_union<MP> union_type;
union_type value_;
private:
void* address() { return static_cast<void*>(std::addressof(value_)); }
void construct_value(const value_type& v) { ::new (address()) value_type(v); }
void construct_value(value_type&& v) { ::new (address()) value_type(std::move(v)); }
void change_to_value(const value_type& v)
try {
destroy_storage();
construct_value(v);
}
catch (...)
{ // now, neither value nor no-value. We have to try to assign no-value
construct_storage_checked();
throw;
}
void change_to_value(value_type&& v)
try {
destroy_storage();
construct_value(std::move(v));
}
catch (...)
{ // now, neither value nor no-value. We have to try to assign no-value
construct_storage_checked();
throw;
}
void construct_storage() { ::new (address()) representation_type(MP::marked_value()); }
void construct_storage_checked() AK_TOOLKIT_NOEXCEPT { construct_storage(); } // std::terminate() if MP::marked_value() throws
void destroy_value() AK_TOOLKIT_NOEXCEPT { as_value().value_type::~value_type(); }
void destroy_storage() AK_TOOLKIT_NOEXCEPT { representation().representation_type::~representation_type(); }
public:
void clear_value() AK_TOOLKIT_NOEXCEPT { destroy_value(); construct_storage(); } // std::terminate() if MP::marked_value() throws
bool has_value() const AK_TOOLKIT_NOEXCEPT { return !MP::is_marked_value(representation()); }
value_type& as_value() { return value_._value; }
const value_type& as_value() const { return value_._value; }
public:
representation_type& representation() AK_TOOLKIT_NOEXCEPT { return value_._marking; }
const representation_type& representation() const AK_TOOLKIT_NOEXCEPT { return value_._marking; }
constexpr explicit dual_storage(representation_type&& mv) AK_TOOLKIT_NOEXCEPT_AS(union_type(std::move(mv)))
: value_(std::move(mv)) {}
constexpr explicit dual_storage(const value_type& v) AK_TOOLKIT_NOEXCEPT_AS(union_type(v))
: value_(v) {}
constexpr explicit dual_storage(value_type&& v) AK_TOOLKIT_NOEXCEPT_AS(union_type(std::move(v)))
: value_(std::move(v)) {}
dual_storage(const dual_storage& rhs) // TODO: add noexcept
: value_(detail_::_init_nothing_tag{})
{
if (rhs.has_value())
construct_value(rhs.as_value());
else
construct_storage();
}
dual_storage(dual_storage&& rhs) // TODO: add noexcept
: value_(detail_::_init_nothing_tag{})
{
if (rhs.has_value())
construct_value(std::move(rhs.as_value()));
else
construct_storage();
}
void operator=(const dual_storage& rhs)
{
if (has_value() && rhs.has_value())
{
as_value() = rhs.as_value();
}
else if (has_value() && !rhs.has_value())
{
clear_value();
}
else if (!has_value() && rhs.has_value())
{
change_to_value(rhs.as_value());
}
}
void operator=(dual_storage&& rhs) // TODO: add noexcept
{
if (has_value() && rhs.has_value())
{
as_value() = std::move(rhs.as_value());
}
else if (has_value() && !rhs.has_value())
{
clear_value();
}
else if (!has_value() && rhs.has_value())
{
change_to_value(std::move(rhs.as_value()));
}
}
void swap_impl(dual_storage& rhs)
{
using namespace std;
if (has_value() && rhs.has_value())
{
swap(as_value(), rhs.as_value());
}
else if (has_value() && !rhs.has_value())
{
rhs.change_to_value(std::move(as_value()));
clear_value();
}
else if (!has_value() && rhs.has_value())
{
change_to_value(std::move(rhs.as_value()));
rhs.clear_value();
}
}
friend void swap(dual_storage& lhs, dual_storage& rhs) { lhs.swap_impl(rhs); }
~dual_storage()
{
if (has_value())
destroy_value();
else
destroy_storage();
}
};
template <typename MPT, typename T, typename REP_T = typename representation_of<T>::type>
struct markable_dual_storage_type_unsafe
{
static_assert(sizeof(T) == sizeof(REP_T), "representation of T has to have the same size and alignment as T");
static_assert(std::is_standard_layout<T>::value, "T must be a Standard Layout type");
static_assert(std::is_standard_layout<REP_T>::value, "representation of T must be a Standard Layout type");
#ifndef AK_TOOLBOX_NO_ARVANCED_CXX11
static_assert(alignof(T) == alignof(REP_T), "representation of T has to have the same alignment as T");
#endif // AK_TOOLBOX_NO_ARVANCED_CXX11
// TODO: in C++20: static_assert(std::is_layout_compatible_v<T, REP_T>, "representation of T has to be layout-compatible with T");
typedef T value_type;
typedef REP_T representation_type;
typedef const T& reference_type;
typedef dual_storage<MPT> storage_type;
static reference_type access_value(const storage_type& v)
{ return v.as_value(); }
static const representation_type& representation(const storage_type& v)
{ return v.representation(); }
static storage_type store_value(const value_type& v)
{ return storage_type(v); }
static storage_type store_value(value_type&& v)
{ return storage_type(std::move(v)); }
static storage_type store_representation(const representation_type& r)
{ return storage_type(r); }
static storage_type store_representation(representation_type&& r)
{ return storage_type(std::move(r)); }
};
template <typename MPT, typename T, typename REP_T = typename representation_of<T>::type>
struct markable_dual_storage_type : markable_dual_storage_type_unsafe<MPT, T, REP_T>
{
// The presence of this typedef is a request to check if T is nothrow move constructible
typedef void is_safe_dual_storage_mark_policy;
};
// ### Ordering policies
class order_none {};
template <AK_TOOLKIT_MARK_POLICY MP, typename OP = order_none>
class markable;
class order_by_representation
{
template <typename MP, typename OP>
static bool unique_marked_value(const markable<MP, OP>& mk)
{
// returns false if mk has no value but its storage is different
// than the MP::marked_value().
return mk.has_value() || mk.representation_value() == MP::marked_value();
}
public:
template <typename MP, typename OP>
static auto equal(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(l.representation_value() == r.representation_value())
{
assert(unique_marked_value(l));
assert(unique_marked_value(r));
return l.representation_value() == r.representation_value();
}
template <typename MP, typename OP>
static auto less(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(l.representation_value() < r.representation_value())
{
assert(unique_marked_value(l));
assert(unique_marked_value(r));
return l.representation_value() < r.representation_value();
}
};
class order_by_value
{
public:
template <typename MP, typename OP>
static auto equal(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(l.value() == r.value())
{
return !l.has_value() ? !r.has_value() : r.has_value() && l.value() == r.value();
}
template <typename MP, typename OP>
static auto less(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(l.value() < r.value())
{
return !r.has_value() ? false : (!l.has_value() ? true : l.value() < r.value());
}
};
struct with_representation_t
{
AK_TOOLKIT_CONSTEXPR explicit with_representation_t() {}
};
AK_TOOLKIT_CONSTEXPR_OR_CONST with_representation_t with_representation {};
template <AK_TOOLKIT_MARK_POLICY MP, typename OP>
class markable
{
// The following assert is only in case a safe dual storage is used.
// It then checks if the value_type is nothrow move constructible.
// I cannot check it inside the dual storage, because I need a complete
// type to determine nothrow traits.
static_assert (detail_::check_safe_dual_storage_exception_safety<MP>::value,
"while building a markable type: representation of T must not throw exceptions from move constructor or when creating the marked value");
public:
typedef typename MP::value_type value_type;
typedef typename MP::representation_type representation_type;
typedef typename MP::reference_type reference_type;
private:
typename MP::storage_type _storage;
public:
AK_TOOLKIT_CONSTEXPR markable() AK_TOOLKIT_NOEXCEPT_AS(MP::marked_value())
: _storage(MP::store_representation(MP::marked_value())) {}
AK_TOOLKIT_CONSTEXPR explicit markable(const value_type& v)
: _storage(MP::store_value(v)) {}
AK_TOOLKIT_CONSTEXPR explicit markable(value_type&& v)
: _storage(MP::store_value(std::move(v))) {}
AK_TOOLKIT_CONSTEXPR explicit markable(with_representation_t, const representation_type& r)
: _storage(MP::store_representation(r)) {}
AK_TOOLKIT_CONSTEXPR explicit markable(with_representation_t, representation_type&& r)
: _storage(MP::store_representation(::std::move(r))) {}
AK_TOOLKIT_CONSTEXPR bool has_value() const {
return !MP::is_marked_value(MP::representation(_storage));
}
AK_TOOLKIT_CONSTEXPR reference_type value() const { return AK_TOOLKIT_ASSERT(has_value()), MP::access_value(_storage); }
AK_TOOLKIT_CONSTEXPR representation_type const& representation_value() const {
return MP::representation(_storage);
}
void assign(value_type&& v) { _storage = MP::store_value(std::move(v)); }
void assign(const value_type& v) { _storage = MP::store_value(v); }
void assign_representation(representation_type&& s) { _storage = MP::store_representation(std::move(s)); }
void assign_representation(representation_type const& s) { _storage = MP::store_representation(s); }
friend void swap(markable& lhs, markable& rhs) {
using std::swap; swap(lhs._storage, rhs._storage);
}
};
template <typename MP, typename OP>
auto operator==(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(OP::equal(l, r))
{
return OP::equal(l, r);
}
template <typename MP, typename OP>
auto operator!=(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(OP::equal(l, r))
{
return !OP::equal(l, r);
}
template <typename MP, typename OP>
auto operator<(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(OP::less(l, r))
{
return OP::less(l, r);
}
template <typename MP, typename OP>
auto operator>(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(OP::less(l, r))
{
return OP::less(r, l);
}
template <typename MP, typename OP>
auto operator<=(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(OP::less(l, r))
{
return !OP::less(r, l);
}
template <typename MP, typename OP>
auto operator>=(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(OP::less(l, r))
{
return !OP::less(l, r);
}
// This defines a customization point for selecting the default makred value
// policy for a given type
template <typename T, typename = void>
struct default_mark_policy
{
using type = mark_value_init<T>;
};
template <typename T>
struct default_mark_policy<T, typename std::enable_if<std::is_integral<T>::value>::type>
{
using type = mark_int<T, std::numeric_limits<T>::max()>;
};
template <typename T>
struct default_mark_policy<T, typename std::enable_if<std::is_floating_point<T>::value>::type>
{
using type = mark_fp_nan<T>;
};
template <>
struct default_mark_policy<bool, void>
{
using type = mark_bool;
};
#ifndef AK_TOOLBOX_NO_UNDERLYING_TYPE
template <typename T>
struct default_mark_policy<T, typename std::enable_if<std::is_enum<T>::value>::type>
{
using type = mark_enum<T, std::numeric_limits<typename std::underlying_type<T>::type>::max()>;
};
#else
template <typename T>
struct default_mark_policy<T, typename std::enable_if<std::is_enum<T>::value>::type>
{
using type = mark_enum<T, std::numeric_limits<int>::max()>;
};
#endif
template <typename T>
using default_markable = markable<typename default_mark_policy<T>::type, order_by_value>;
} // namespace markable_ns
using markable_ns::markable;
using markable_ns::markable_type;
using markable_ns::markable_dual_storage_type;
using markable_ns::markable_dual_storage_type_unsafe;
using markable_ns::mark_bool;
using markable_ns::mark_int;
using markable_ns::mark_fp_nan;
using markable_ns::mark_value_init;
using markable_ns::mark_optional;
using markable_ns::mark_stl_empty;
using markable_ns::mark_enum;
using markable_ns::order_none;
using markable_ns::order_by_representation;
using markable_ns::order_by_value;
using markable_ns::default_markable;
using markable_ns::with_representation;
using markable_ns::with_representation_t;
# if defined AK_TOOLKIT_WITH_CONCEPTS
using markable_ns::mark_policy;
static_assert(mark_policy<mark_bool>, "mark_policy test failed");
static_assert(mark_policy<mark_int<int, 0>>, "mark_policy test failed");
static_assert(mark_policy<mark_fp_nan<float>>, "mark_policy test failed");
static_assert(mark_policy<mark_value_init<int>>, "mark_policy test failed");
# endif
} // namespace ak_toolkit
// hashing
namespace std
{
template <typename MP>
struct hash<ak_toolkit::markable<MP, ak_toolkit::order_by_representation>>
{
typedef typename hash<typename MP::representation_type>::result_type result_type;
typedef ak_toolkit::markable<MP, ak_toolkit::order_by_representation> argument_type;
constexpr result_type operator()(argument_type const& arg) const {
return std::hash<typename MP::representation_type>{}(arg.representation_value());
}
};
template <typename MP>
struct hash<ak_toolkit::markable<MP, ak_toolkit::order_by_value>>
{
typedef typename hash<typename MP::value_type>::result_type result_type;
typedef ak_toolkit::markable<MP, ak_toolkit::order_by_value> argument_type;
constexpr result_type operator()(argument_type const& arg) const {
return arg.has_value() ? std::hash<typename MP::value_type>{}(arg.value()) : result_type{};
}
};
} // namespace std
#endif //AK_TOOLBOX_COMPACT_OPTIONAL_HEADER_GUARD_
| 33.036568 | 154 | 0.726255 | akrzemi1 |
65afd1192c8f3c63a733e303442998fd22a9fc21 | 1,130 | hpp | C++ | src/game-objects/turret.hpp | Blackhawk-TA/TowerDefense | db852a65cae9579074e435fb0245fd9b69fb720d | [
"MIT"
] | 1 | 2022-01-02T15:02:09.000Z | 2022-01-02T15:02:09.000Z | src/game-objects/turret.hpp | Blackhawk-TA/TowerDefense | db852a65cae9579074e435fb0245fd9b69fb720d | [
"MIT"
] | null | null | null | src/game-objects/turret.hpp | Blackhawk-TA/TowerDefense | db852a65cae9579074e435fb0245fd9b69fb720d | [
"MIT"
] | 1 | 2021-05-02T18:25:51.000Z | 2021-05-02T18:25:51.000Z | //
// Created by Daniel Peters on 08.04.21.
//
#pragma once
#include "../utils/utils.hpp"
using namespace blit;
class Turret {
public:
explicit Turret(Point position, TurretFacingDirection facing_direction);
void draw();
Rect get_rectangle() const;
TurretFacingDirection get_facing_direction();
uint8_t get_damage() const;
Point get_range() const;
Point get_barrel_position() const;
void animate();
bool is_animation_pending() const;
void activate_animation_pending();
private:
const uint8_t damage = 19;
const std::array<uint8_t, 5> animation_sprite_ids = {0, 56, 57, 58};
const Point range = Point(1, 4); // How far it can shoot to the left/right and forward
const Rect sprite_facing_up = Rect(10, 1, 1, 2);
const Rect sprite_facing_down = Rect(7, 2, 1, 2);
const Rect sprite_facing_left = Rect(8, 2, 2, 1);
Point spawn_position;
Point animation_position;
Point barrel_position; //The position where the turret fires from
Rect sprite;
SpriteTransform transform;
SpriteTransform animation_transform;
TurretFacingDirection facing_direction;
uint8_t animation_sprite_index;
bool animation_pending;
};
| 27.560976 | 87 | 0.761947 | Blackhawk-TA |
65b4ff162151685abad28b68ececdc12f4190c3b | 1,347 | hpp | C++ | stan/math/prim/fun/pow.hpp | bayesmix-dev/math | 3616f7195adc95ef8e719a2af845d61102bc9272 | [
"BSD-3-Clause"
] | 1 | 2020-06-14T14:33:37.000Z | 2020-06-14T14:33:37.000Z | stan/math/prim/fun/pow.hpp | bayesmix-dev/math | 3616f7195adc95ef8e719a2af845d61102bc9272 | [
"BSD-3-Clause"
] | null | null | null | stan/math/prim/fun/pow.hpp | bayesmix-dev/math | 3616f7195adc95ef8e719a2af845d61102bc9272 | [
"BSD-3-Clause"
] | 1 | 2020-05-10T12:55:07.000Z | 2020-05-10T12:55:07.000Z | #ifndef STAN_MATH_PRIM_FUN_POW_HPP
#define STAN_MATH_PRIM_FUN_POW_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/functor/apply_scalar_binary.hpp>
#include <cmath>
#include <complex>
namespace stan {
namespace math {
namespace internal {
/**
* Return the first argument raised to the power of the second
* argument. At least one of the arguments must be a complex number.
*
* @tparam U type of base
* @tparam V type of exponent
* @param[in] x base
* @param[in] y exponent
* @return base raised to the power of the exponent
*/
template <typename U, typename V>
inline complex_return_t<U, V> complex_pow(const U& x, const V& y) {
return exp(y * log(x));
}
} // namespace internal
/**
* Enables the vectorised application of the pow function, when
* the first and/or second arguments are containers.
*
* @tparam T1 type of first input
* @tparam T2 type of second input
* @param a First input
* @param b Second input
* @return pow function applied to the two inputs.
*/
template <typename T1, typename T2, require_any_container_t<T1, T2>* = nullptr>
inline auto pow(const T1& a, const T2& b) {
return apply_scalar_binary(a, b, [&](const auto& c, const auto& d) {
using std::pow;
return pow(c, d);
});
}
} // namespace math
} // namespace stan
#endif
| 26.411765 | 79 | 0.709725 | bayesmix-dev |
65b6e02cc3a10b30145392598890c316458aa999 | 641 | cpp | C++ | Sunny-Core/01_FRAMEWORK/graphics/ModelManager.cpp | adunStudio/Sunny | 9f71c1816aa62bbc0d02d2f8d6414f4bf9aee7e7 | [
"Apache-2.0"
] | 20 | 2018-01-19T06:28:36.000Z | 2021-08-06T14:06:13.000Z | Sunny-Core/01_FRAMEWORK/graphics/ModelManager.cpp | adunStudio/Sunny | 9f71c1816aa62bbc0d02d2f8d6414f4bf9aee7e7 | [
"Apache-2.0"
] | null | null | null | Sunny-Core/01_FRAMEWORK/graphics/ModelManager.cpp | adunStudio/Sunny | 9f71c1816aa62bbc0d02d2f8d6414f4bf9aee7e7 | [
"Apache-2.0"
] | 3 | 2019-01-29T08:58:04.000Z | 2021-01-02T06:33:20.000Z | #include "ModelManager.h"
namespace sunny
{
namespace graphics
{
std::map<std::string, Model*> ModelManager::s_map;
Model* ModelManager::Add(const::std::string& name, Model* Model)
{
s_map[name] = Model;
return Model;
}
void ModelManager::Clean()
{
for (auto it = s_map.begin(); it != s_map.end(); ++it)
{
if (it->second)
{
delete it->second;
}
}
}
Model* ModelManager::Get(const std::string& name)
{
return s_map[name];
}
Mesh* ModelManager::GetMesh(const std::string& name)
{
if (s_map[name] == nullptr) return nullptr;
return s_map[name]->GetMesh();
}
}
} | 16.435897 | 66 | 0.599064 | adunStudio |
65c87d7b4a07e75b0d89fbd8d6e9c91e2fc6b6b7 | 1,405 | cpp | C++ | CloudDisk_Client/httpresponse.cpp | G-Club/c-cpp | e89f8efae357fc8349d0d66f1aef703a6a287bef | [
"Apache-2.0"
] | null | null | null | CloudDisk_Client/httpresponse.cpp | G-Club/c-cpp | e89f8efae357fc8349d0d66f1aef703a6a287bef | [
"Apache-2.0"
] | 1 | 2017-02-07T00:49:21.000Z | 2017-02-16T00:55:28.000Z | CloudDisk_Client/httpresponse.cpp | G-Club/c-cpp | e89f8efae357fc8349d0d66f1aef703a6a287bef | [
"Apache-2.0"
] | null | null | null | #include "httpresponse.h"
HttpResponse::HttpResponse()
{
}
HttpResponse HttpResponse::FromByteArray(QByteArray &format)
{
/*
HTTP/1.1 200 OK\r\nServer: nginx/1.10.1\r\nDate: Sat, 29 Jul 2017 00:41:44 GMT\r\nContent-Type: text/html\r\nTransfer-Encoding: chunked\r\nConnection: keep-alive\r\n\r\n27\r\n{\"status\":201,\"error\":201,\"msg\":\"succ\"}\r\n0\r\n\r\n
*/
QString string(format),respline,data;
HttpResponse resp;
int index=-1,status;
index=string.indexOf("\r\n");
if(index<0)
{
return resp;
}
respline=string.left(index);
status=respline.split(' ').at(1).toInt();
index=string.indexOf("\r\n\r\n");
if(index<0)
{
return resp;
}
data=string.right(string.length()-index-4);
index=data.indexOf("\r\n");
data=data.right(data.length()-index-2);
index=data.indexOf("\r\n");
data=data.left(index);
resp.setData(data);
resp.setRespline(respline);
resp.setStatus(status);
return resp;
}
QString HttpResponse::getData() const
{
return data;
}
void HttpResponse::setData(const QString &value)
{
data = value;
}
QString HttpResponse::getRespline() const
{
return respline;
}
void HttpResponse::setRespline(const QString &value)
{
respline = value;
}
int HttpResponse::getStatus() const
{
return status;
}
void HttpResponse::setStatus(int value)
{
status = value;
}
| 19.513889 | 235 | 0.648399 | G-Club |
65ca00f755a60e996fd58344181d3d3ed0424b23 | 5,916 | cpp | C++ | meeting-qt/setup/src/dui/Core/Placeholder.cpp | GrowthEase/- | 5cc7cab95fc309049de8023ff618219dff22d773 | [
"MIT"
] | 48 | 2022-03-02T07:15:08.000Z | 2022-03-31T08:37:33.000Z | meeting-qt/setup/src/dui/Core/Placeholder.cpp | chandarlee/Meeting | 9350fdea97eb2cdda28b8bffd9c4199de15460d9 | [
"MIT"
] | 1 | 2022-02-16T01:54:05.000Z | 2022-02-16T01:54:05.000Z | meeting-qt/setup/src/dui/Core/Placeholder.cpp | chandarlee/Meeting | 9350fdea97eb2cdda28b8bffd9c4199de15460d9 | [
"MIT"
] | 9 | 2022-03-01T13:41:37.000Z | 2022-03-10T06:05:23.000Z | /**
* @copyright Copyright (c) 2021 NetEase, Inc. All rights reserved.
* Use of this source code is governed by a MIT license that can be found in the LICENSE file.
*/
#include "StdAfx.h"
namespace ui
{
PlaceHolder::PlaceHolder()
{
}
PlaceHolder::~PlaceHolder()
{
}
std::wstring PlaceHolder::GetName() const
{
return m_sName;
}
std::string PlaceHolder::GetUTF8Name() const
{
int multiLength = WideCharToMultiByte(CP_UTF8, NULL, m_sName.c_str(), -1, NULL, 0, NULL, NULL);
if (multiLength <= 0)
return "";
std::unique_ptr<char[]> strName(new char[multiLength]);
WideCharToMultiByte(CP_UTF8, NULL, m_sName.c_str(), -1, strName.get(), multiLength, NULL, NULL);
std::string res = strName.get();
return res;
}
void PlaceHolder::SetName(const std::wstring& pstrName)
{
m_sName = pstrName;
}
void PlaceHolder::SetUTF8Name(const std::string& pstrName)
{
int wideLength = MultiByteToWideChar(CP_UTF8, NULL, pstrName.c_str(), -1, NULL, 0);
if (wideLength <= 0)
{
m_sName = _T("");
return;
}
std::unique_ptr<wchar_t[]> strName(new wchar_t[wideLength]);
MultiByteToWideChar(CP_UTF8, NULL, pstrName.c_str(), -1, strName.get(), wideLength);
m_sName = strName.get();
}
Window* PlaceHolder::GetWindow() const
{
return m_pWindow;
}
void PlaceHolder::SetWindow(Window* pManager, Box* pParent, bool bInit)
{
m_pWindow = pManager;
m_pParent = pParent;
if (bInit && m_pParent) Init();
}
void PlaceHolder::SetWindow(Window* pManager)
{
m_pWindow = pManager;
}
void PlaceHolder::Init()
{
DoInit();
}
void PlaceHolder::DoInit()
{
}
CSize PlaceHolder::EstimateSize(CSize szAvailable)
{
return m_cxyFixed;
}
bool PlaceHolder::IsVisible() const
{
return m_bVisible && m_bInternVisible;
}
bool PlaceHolder::IsFloat() const
{
return m_bFloat;
}
void PlaceHolder::SetFloat(bool bFloat)
{
if (m_bFloat == bFloat) return;
m_bFloat = bFloat;
ArrangeAncestor();
}
int PlaceHolder::GetFixedWidth() const
{
return m_cxyFixed.cx;
}
void PlaceHolder::SetFixedWidth(int cx, bool arrange)
{
if (cx < 0 && cx != DUI_LENGTH_STRETCH && cx != DUI_LENGTH_AUTO) {
ASSERT(FALSE);
return;
}
if (m_cxyFixed.cx != cx)
{
m_cxyFixed.cx = cx;
if (arrange) {
ArrangeAncestor();
}
else {
m_bReEstimateSize = true;
}
}
//if( !m_bFloat ) ArrangeAncestor();
//else Arrange();
}
int PlaceHolder::GetFixedHeight() const
{
return m_cxyFixed.cy;
}
void PlaceHolder::SetFixedHeight(int cy)
{
if (cy < 0 && cy != DUI_LENGTH_STRETCH && cy != DUI_LENGTH_AUTO) {
ASSERT(FALSE);
return;
}
if (m_cxyFixed.cy != cy)
{
m_cxyFixed.cy = cy;
ArrangeAncestor();
}
//if( !m_bFloat ) ArrangeAncestor();
//else Arrange();
}
int PlaceHolder::GetMinWidth() const
{
return m_cxyMin.cx;
}
void PlaceHolder::SetMinWidth(int cx)
{
if (m_cxyMin.cx == cx) return;
if (cx < 0) return;
m_cxyMin.cx = cx;
if (!m_bFloat) ArrangeAncestor();
else Arrange();
}
int PlaceHolder::GetMaxWidth() const
{
return m_cxyMax.cx;
}
void PlaceHolder::SetMaxWidth(int cx)
{
if (m_cxyMax.cx == cx) return;
m_cxyMax.cx = cx;
if (!m_bFloat) ArrangeAncestor();
else Arrange();
}
int PlaceHolder::GetMinHeight() const
{
return m_cxyMin.cy;
}
void PlaceHolder::SetMinHeight(int cy)
{
if (m_cxyMin.cy == cy) return;
if (cy < 0) return;
m_cxyMin.cy = cy;
if (!m_bFloat) ArrangeAncestor();
else Arrange();
}
int PlaceHolder::GetMaxHeight() const
{
return m_cxyMax.cy;
}
void PlaceHolder::SetMaxHeight(int cy)
{
if (m_cxyMax.cy == cy) return;
m_cxyMax.cy = cy;
if (!m_bFloat) ArrangeAncestor();
else Arrange();
}
int PlaceHolder::GetWidth() const
{
return m_rcItem.right - m_rcItem.left;
}
int PlaceHolder::GetHeight() const
{
return m_rcItem.bottom - m_rcItem.top;
}
UiRect PlaceHolder::GetPos(bool bContainShadow) const
{
return m_rcItem;
}
void PlaceHolder::SetPos(UiRect rc)
{
m_rcItem = rc;
}
void PlaceHolder::Arrange()
{
if (GetFixedWidth() == DUI_LENGTH_AUTO || GetFixedHeight() == DUI_LENGTH_AUTO)
{
ArrangeAncestor();
}
else
{
ArrangeSelf();
}
}
void PlaceHolder::ArrangeAncestor()
{
m_bReEstimateSize = true;
if (!m_pWindow || !m_pWindow->GetRoot())
{
if (GetParent()) {
GetParent()->ArrangeSelf();
}
else {
ArrangeSelf();
}
}
else
{
Control* parent = GetParent();
while (parent && (parent->GetFixedWidth() == DUI_LENGTH_AUTO || parent->GetFixedHeight() == DUI_LENGTH_AUTO))
{
parent->SetReEstimateSize(true);
parent = parent->GetParent();
}
if (parent)
{
parent->ArrangeSelf();
}
else //说明root具有AutoAdjustSize属性
{
m_pWindow->GetRoot()->ArrangeSelf();
}
}
}
void PlaceHolder::ArrangeSelf()
{
if (!IsVisible()) return;
m_bReEstimateSize = true;
m_bIsArranged = true;
Invalidate();
if (m_pWindow != NULL) m_pWindow->SetArrange(true);
}
void PlaceHolder::Invalidate() const
{
if (!IsVisible()) return;
UiRect invalidateRc = GetPosWithScrollOffset();
if (m_pWindow != NULL) m_pWindow->Invalidate(invalidateRc);
}
UiRect PlaceHolder::GetPosWithScrollOffset() const
{
UiRect pos = GetPos();
pos.Offset(-GetScrollOffset().x, -GetScrollOffset().y);
return pos;
}
CPoint PlaceHolder::GetScrollOffset() const
{
CPoint scrollPos;
Control* parent = GetParent();
ListBox* lbParent = dynamic_cast<ListBox*>(parent);
if (lbParent && lbParent->IsVScrollBarValid() && IsFloat()) {
return scrollPos;
}
while (parent && (!dynamic_cast<ListBox*>(parent) || !dynamic_cast<ListBox*>(parent)->IsVScrollBarValid()))
{
parent = parent->GetParent();
}
if (parent) { //说明控件在Listbox内部
ListBox* listbox = (ListBox*)parent;
scrollPos.x = listbox->GetScrollPos().cx;
scrollPos.y = listbox->GetScrollPos().cy;
}
return scrollPos;
}
bool PlaceHolder::IsArranged() const
{
return m_bIsArranged;
}
bool IsChild(PlaceHolder* pAncestor, PlaceHolder* pControl)
{
while (pControl && pControl != pAncestor)
{
pControl = pControl->GetParent();
}
return pControl != nullptr;
}
} | 17.298246 | 111 | 0.686782 | GrowthEase |
65cca26ab81c68c2201bde3223830ec49d11faa7 | 7,042 | cc | C++ | google/cloud/storage/status_or_test.cc | roopak-qlogic/google-cloud-cpp | ed129e4c955e99d4dacb822503d95e374605c438 | [
"Apache-2.0"
] | null | null | null | google/cloud/storage/status_or_test.cc | roopak-qlogic/google-cloud-cpp | ed129e4c955e99d4dacb822503d95e374605c438 | [
"Apache-2.0"
] | null | null | null | google/cloud/storage/status_or_test.cc | roopak-qlogic/google-cloud-cpp | ed129e4c955e99d4dacb822503d95e374605c438 | [
"Apache-2.0"
] | null | null | null | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/storage/status_or.h"
#include "google/cloud/testing_util/expect_exception.h"
#include <gmock/gmock.h>
namespace google {
namespace cloud {
namespace storage {
inline namespace STORAGE_CLIENT_NS {
namespace {
using ::testing::HasSubstr;
TEST(StatusOrTest, DefaultConstructor) {
StatusOr<int> actual;
EXPECT_FALSE(actual.ok());
EXPECT_FALSE(actual.status().ok());
EXPECT_TRUE(not actual);
}
TEST(StatusOrTest, StatusConstructorNormal) {
StatusOr<int> actual(Status(404, "NOT FOUND", "It was there yesterday!"));
EXPECT_FALSE(actual.ok());
EXPECT_TRUE(not actual);
EXPECT_EQ(404, actual.status().status_code());
EXPECT_EQ("NOT FOUND", actual.status().error_message());
EXPECT_EQ("It was there yesterday!", actual.status().error_details());
}
TEST(StatusOrTest, StatusConstructorInvalid) {
testing_util::ExpectException<std::invalid_argument>(
[&] { StatusOr<int> actual(Status{}); },
[&](std::invalid_argument const& ex) {
EXPECT_THAT(ex.what(), HasSubstr("StatusOr"));
},
"exceptions are disabled: "
);
}
TEST(StatusOrTest, ValueConstructor) {
StatusOr<int> actual(42);
EXPECT_TRUE(actual.ok());
EXPECT_FALSE(not actual);
EXPECT_EQ(42, actual.value());
EXPECT_EQ(42, std::move(actual).value());
}
TEST(StatusOrTest, ValueConstAccessors) {
StatusOr<int> const actual(42);
EXPECT_TRUE(actual.ok());
EXPECT_EQ(42, actual.value());
EXPECT_EQ(42, std::move(actual).value());
}
TEST(StatusOrTest, ValueAccessorNonConstThrows) {
StatusOr<int> actual(Status(500, "BAD"));
testing_util::ExpectException<RuntimeStatusError>(
[&] { actual.value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
testing_util::ExpectException<RuntimeStatusError>(
[&] { std::move(actual).value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
}
TEST(StatusOrTest, ValueAccessorConstThrows) {
StatusOr<int> actual(Status(500, "BAD"));
testing_util::ExpectException<RuntimeStatusError>(
[&] { actual.value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
testing_util::ExpectException<RuntimeStatusError>(
[&] { std::move(actual).value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
}
TEST(StatusOrTest, StatusConstAccessors) {
StatusOr<int> const actual(Status(500, "BAD"));
EXPECT_EQ(500, actual.status().status_code());
EXPECT_EQ(500, std::move(actual).status().status_code());
}
TEST(StatusOrTest, ValueDeference) {
StatusOr<std::string> actual("42");
EXPECT_TRUE(actual.ok());
EXPECT_EQ("42", *actual);
EXPECT_EQ("42", std::move(actual).value());
}
TEST(StatusOrTest, ValueConstDeference) {
StatusOr<std::string> const actual("42");
EXPECT_TRUE(actual.ok());
EXPECT_EQ("42", *actual);
EXPECT_EQ("42", std::move(actual).value());
}
TEST(StatusOrTest, ValueArrow) {
StatusOr<std::string> actual("42");
EXPECT_TRUE(actual.ok());
EXPECT_EQ(std::string("42"), actual->c_str());
}
TEST(StatusOrTest, ValueConstArrow) {
StatusOr<std::string> const actual("42");
EXPECT_TRUE(actual.ok());
EXPECT_EQ(std::string("42"), actual->c_str());
}
TEST(StatusOrVoidTest, DefaultConstructor) {
StatusOr<void> actual;
EXPECT_FALSE(actual.ok());
EXPECT_FALSE(actual.status().ok());
}
TEST(StatusOrVoidTest, StatusConstructorNormal) {
StatusOr<void> actual(Status(404, "NOT FOUND", "It was there yesterday!"));
EXPECT_FALSE(actual.ok());
EXPECT_EQ(404, actual.status().status_code());
EXPECT_EQ("NOT FOUND", actual.status().error_message());
EXPECT_EQ("It was there yesterday!", actual.status().error_details());
}
TEST(StatusOrVoidTest, ValueConstructor) {
StatusOr<void> actual(Status{});
EXPECT_TRUE(actual.ok());
testing_util::ExpectNoException([&] { actual.value(); });
testing_util::ExpectNoException([&] { std::move(actual).value(); });
}
TEST(StatusOrVoidTest, ValueConstAccessors) {
StatusOr<void> const actual(Status{});
EXPECT_TRUE(actual.ok());
testing_util::ExpectNoException([&] { actual.value(); });
testing_util::ExpectNoException([&] { std::move(actual).value(); });
}
TEST(StatusOrVoidTest, ValueAccessorNonConstThrows) {
StatusOr<void> actual(Status(500, "BAD"));
testing_util::ExpectException<RuntimeStatusError>(
[&] { actual.value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
testing_util::ExpectException<RuntimeStatusError>(
[&] { std::move(actual).value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
}
TEST(StatusOrVoidTest, ValueAccessorConstThrows) {
StatusOr<void> actual(Status(500, "BAD"));
testing_util::ExpectException<RuntimeStatusError>(
[&] { actual.value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
testing_util::ExpectException<RuntimeStatusError>(
[&] { std::move(actual).value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
}
TEST(StatusOrVoidTest, StatusConstAccessors) {
StatusOr<void> const actual(Status(500, "BAD"));
EXPECT_EQ(500, actual.status().status_code());
EXPECT_EQ(500, std::move(actual).status().status_code());
}
} // namespace
} // namespace STORAGE_CLIENT_NS
} // namespace storage
} // namespace cloud
} // namespace google
| 31.159292 | 77 | 0.668986 | roopak-qlogic |
65d1b0b9ce08319e680aae4a187667943a9a6bd4 | 811 | hpp | C++ | src/morda/widgets/label/MouseCursor.hpp | Mactor2018/morda | 7194f973783b4472b8671fbb52e8c96e8c972b90 | [
"MIT"
] | 1 | 2018-10-27T05:07:05.000Z | 2018-10-27T05:07:05.000Z | src/morda/widgets/label/MouseCursor.hpp | Mactor2018/morda | 7194f973783b4472b8671fbb52e8c96e8c972b90 | [
"MIT"
] | null | null | null | src/morda/widgets/label/MouseCursor.hpp | Mactor2018/morda | 7194f973783b4472b8671fbb52e8c96e8c972b90 | [
"MIT"
] | null | null | null | #pragma once
#include "../Widget.hpp"
#include "../../res/ResCursor.hpp"
namespace morda{
/**
* @brief Mouse cursor widget.
* This widget displays mouse cursor.
* From GUI script this widget can be instantiated as "MouseCursor".
*
* @param cursor - reference to cursor resource.
*/
class MouseCursor : virtual public Widget{
std::shared_ptr<const ResCursor> cursor;
std::shared_ptr<const ResImage::QuadTexture> quadTex;
Vec2r cursorPos;
public:
MouseCursor(const stob::Node* chain = nullptr);
MouseCursor(const MouseCursor&) = delete;
MouseCursor& operator=(const MouseCursor&) = delete;
void setCursor(std::shared_ptr<const ResCursor> cursor);
bool onMouseMove(const morda::Vec2r& pos, unsigned pointerID) override;
void render(const morda::Matr4r& matrix) const override;
};
}
| 21.918919 | 72 | 0.731196 | Mactor2018 |
65e402da66d18090a23b95180787d18a0806e7a0 | 1,619 | hpp | C++ | CPP_Module_06/ex01/Serialize.hpp | Victor-Akio/CPP-42 | e6d64e4820ad31ae2cb353a4020d2acb8b5280eb | [
"MIT"
] | null | null | null | CPP_Module_06/ex01/Serialize.hpp | Victor-Akio/CPP-42 | e6d64e4820ad31ae2cb353a4020d2acb8b5280eb | [
"MIT"
] | null | null | null | CPP_Module_06/ex01/Serialize.hpp | Victor-Akio/CPP-42 | e6d64e4820ad31ae2cb353a4020d2acb8b5280eb | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Serialize.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vminomiy <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/03/25 00:00:06 by vminomiy #+# #+# */
/* Updated: 2022/03/26 16:15:18 by vminomiy ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef SERIALIZE_HPP
# define SERIALIZE_HPP
# include <iostream>
# include <stdint.h>
/* SERIALIZATION
** https://en.cppreference.com/w/cpp/language/reinterpret_cast
** https://www.tutorialspoint.com/cplusplus/cpp_casting_operators.htm
** UINTPTR_T - https://stackoverflow.com/questions/1845482/what-is-uintptr-t-data-type
** Usei a stdint.h no lugar da cstdint, pois a uintptr_t foi implementada originalmente na c++99(stdint.h)
** a cstdint corresponde à c++11 que entra na categoriad e forbidden.
** A estrutura pode ter qualquer coisa dentro.. no caso só para popular com algo, coloquei um "num"
*/
typedef struct s_data {
int num;
} Data;
uintptr_t serialize(Data* ptr);
Data* deserialize(uintptr_t raw);
#endif
| 46.257143 | 106 | 0.408894 | Victor-Akio |
65eb378757f196f1b0242237bbf7b0aab25022d1 | 1,112 | cpp | C++ | tugasMonteCarlo/tugasMonteCarlo-20912008-20912009/montePi.cpp | ridlo/kuliah_sains_komputasi | 83cd50857db2446bb41b78698a47a060e0eca5d8 | [
"MIT"
] | null | null | null | tugasMonteCarlo/tugasMonteCarlo-20912008-20912009/montePi.cpp | ridlo/kuliah_sains_komputasi | 83cd50857db2446bb41b78698a47a060e0eca5d8 | [
"MIT"
] | null | null | null | tugasMonteCarlo/tugasMonteCarlo-20912008-20912009/montePi.cpp | ridlo/kuliah_sains_komputasi | 83cd50857db2446bb41b78698a47a060e0eca5d8 | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdio.h>
#include <fstream>
#include <stdlib.h>
#include <time.h>
using namespace std;
double unirand()
{
return (double) rand()/ (double) RAND_MAX;
}
int main()
{
double pi, x, y, r;
unsigned int N=0, Ntot;
ofstream outfile;
outfile.open("rnd-pi.txt");
Ntot = 100000;
srand(time(NULL));
for (int i=0; i<Ntot; i++){
x = unirand();
y = unirand();
outfile << x << " " << y << "\n";
r = x*x + y*y;
if ( r <= 1. ) {
N++;}
}
outfile.close();
pi = (double)N/(double)Ntot * 4.;
printf("Hasil dari %d percobaan menghasilkan nilai PI = %f \n", Ntot, pi);
ofstream ploter;
ploter.open("pi-plot.in");
ploter << "# gnuplot command for plotting\n";
ploter << "set terminal wxt size 600, 500\n";
ploter << "set xrange [0:1]\n";
ploter << "set xlabel \"x\"\n";
ploter << "set ylabel \"y\"\n";
ploter << "plot \"rnd-pi.txt\" with dots, sqrt(1.-x*x)\n";
ploter.close();
system("gnuplot -persist < pi-plot.in");
return 0;
}
| 22.24 | 78 | 0.522482 | ridlo |
65ec377cfee6e4d0b9d9cdac2342a92ccfa6aa3b | 14,844 | hpp | C++ | pennylane_lightning_gpu/src/util/cuda_helpers.hpp | PennyLaneAI/pennylane-lightning-gpu | 1b2a361f68c8580457e61cc706d644c4cbfe04ad | [
"Apache-2.0"
] | 9 | 2022-03-14T15:18:08.000Z | 2022-03-30T03:05:36.000Z | pennylane_lightning_gpu/src/util/cuda_helpers.hpp | PennyLaneAI/pennylane-lightning-gpu | 1b2a361f68c8580457e61cc706d644c4cbfe04ad | [
"Apache-2.0"
] | 6 | 2022-03-18T13:44:10.000Z | 2022-03-31T22:07:25.000Z | pennylane_lightning_gpu/src/util/cuda_helpers.hpp | PennyLaneAI/pennylane-lightning-gpu | 1b2a361f68c8580457e61cc706d644c4cbfe04ad | [
"Apache-2.0"
] | null | null | null | // Adapted from JET: https://github.com/XanaduAI/jet.git
// and from Lightning: https://github.com/PennylaneAI/pennylane-lightning.git
#pragma once
#include <algorithm>
#include <numeric>
#include <type_traits>
#include <vector>
#include <cuComplex.h>
#include <cublas_v2.h>
#include <cuda.h>
#include <custatevec.h>
#include "Error.hpp"
#include "Util.hpp"
namespace Pennylane::CUDA::Util {
#ifndef CUDA_UNSAFE
/**
* @brief Macro that throws Exception from CUDA failure error codes.
*
* @param err CUDA function error-code.
*/
#define PL_CUDA_IS_SUCCESS(err) \
PL_ABORT_IF_NOT(err == cudaSuccess, cudaGetErrorString(err))
/**
* @brief Macro that throws Exception from cuQuantum failure error codes.
*
* @param err cuQuantum function error-code.
*/
#define PL_CUSTATEVEC_IS_SUCCESS(err) \
PL_ABORT_IF_NOT(err == CUSTATEVEC_STATUS_SUCCESS, \
GetCuStateVecErrorString(err).c_str())
#else
#define PL_CUDA_IS_SUCCESS(err) \
{ static_cast<void>(err); }
#define PL_CUSTATEVEC_IS_SUCCESS(err) \
{ static_cast<void>(err); }
#endif
static const std::string
GetCuStateVecErrorString(const custatevecStatus_t &err) {
std::string result;
switch (err) {
case CUSTATEVEC_STATUS_SUCCESS:
result = "No errors";
break;
case CUSTATEVEC_STATUS_NOT_INITIALIZED:
result = "custatevec not initialized";
break;
case CUSTATEVEC_STATUS_ALLOC_FAILED:
result = "custatevec memory allocation failed";
break;
case CUSTATEVEC_STATUS_INVALID_VALUE:
result = "Invalid value";
break;
case CUSTATEVEC_STATUS_ARCH_MISMATCH:
result = "CUDA device architecture mismatch";
break;
case CUSTATEVEC_STATUS_EXECUTION_FAILED:
result = "custatevec execution failed";
break;
case CUSTATEVEC_STATUS_INTERNAL_ERROR:
result = "Internal custatevec error";
break;
case CUSTATEVEC_STATUS_NOT_SUPPORTED:
result = "Unsupported operation/device";
break;
case CUSTATEVEC_STATUS_INSUFFICIENT_WORKSPACE:
result = "Insufficient memory for gate-application workspace";
break;
case CUSTATEVEC_STATUS_SAMPLER_NOT_PREPROCESSED:
result = "Sampler not preprocessed";
break;
default:
result = "Status not found";
}
return result;
}
// SFINAE check for existence of real() method in complex type
template <typename CFP_t>
constexpr auto is_cxx_complex(const CFP_t &t) -> decltype(t.real(), bool()) {
return true;
}
// Catch-all fallback for CUDA complex types
constexpr bool is_cxx_complex(...) { return false; }
inline cuFloatComplex operator-(const cuFloatComplex &a) {
return {-a.x, -a.y};
}
inline cuDoubleComplex operator-(const cuDoubleComplex &a) {
return {-a.x, -a.y};
}
template <class CFP_t_T, class CFP_t_U = CFP_t_T>
inline static auto Div(const CFP_t_T &a, const CFP_t_U &b) -> CFP_t_T {
if constexpr (std::is_same_v<CFP_t_T, cuComplex> ||
std::is_same_v<CFP_t_T, float2>) {
return cuCdivf(a, b);
} else if (std::is_same_v<CFP_t_T, cuDoubleComplex> ||
std::is_same_v<CFP_t_T, double2>) {
return cuCdiv(a, b);
}
}
/**
* @brief Conjugate function for CXX & CUDA complex types
*
* @tparam CFP_t Complex data type. Supports std::complex<float>,
* std::complex<double>, cuFloatComplex, cuDoubleComplex
* @param a The given complex number
* @return CFP_t The conjuagted complex number
*/
template <class CFP_t> inline static constexpr auto Conj(CFP_t a) -> CFP_t {
if constexpr (std::is_same_v<CFP_t, cuComplex> ||
std::is_same_v<CFP_t, float2>) {
return cuConjf(a);
} else {
return cuConj(a);
}
}
/**
* @brief Compile-time scalar real times complex number.
*
* @tparam U Precision of real value `a`.
* @tparam T Precision of complex value `b` and result.
* @param a Real scalar value.
* @param b Complex scalar value.
* @return constexpr std::complex<T>
*/
template <class Real_t, class CFP_t = cuDoubleComplex>
inline static constexpr auto ConstMultSC(Real_t a, CFP_t b) -> CFP_t {
if constexpr (std::is_same_v<CFP_t, cuDoubleComplex>) {
return make_cuDoubleComplex(a * b.x, a * b.y);
} else {
return make_cuFloatComplex(a * b.x, a * b.y);
}
}
/**
* @brief Utility to convert cuComplex types to std::complex types
*
* @tparam CFP_t cuFloatComplex or cuDoubleComplex types.
* @param a CUDA compatible complex type.
* @return std::complex converted a
*/
template <class CFP_t = cuDoubleComplex>
inline static constexpr auto cuToComplex(CFP_t a)
-> std::complex<decltype(a.x)> {
return std::complex<decltype(a.x)>{a.x, a.y};
}
/**
* @brief Utility to convert std::complex types to cuComplex types
*
* @tparam CFP_t std::complex types.
* @param a A std::complex type.
* @return cuComplex converted a
*/
template <class CFP_t = std::complex<double>>
inline static constexpr auto complexToCu(CFP_t a) {
if constexpr (std::is_same_v<CFP_t, std::complex<double>>) {
return make_cuDoubleComplex(a.real(), a.imag());
} else {
return make_cuFloatComplex(a.real(), a.imag());
}
}
/**
* @brief Compile-time scalar complex times complex.
*
* @tparam U Precision of complex value `a`.
* @tparam T Precision of complex value `b` and result.
* @param a Complex scalar value.
* @param b Complex scalar value.
* @return constexpr std::complex<T>
*/
template <class CFP_t_T, class CFP_t_U = CFP_t_T>
inline static constexpr auto ConstMult(CFP_t_T a, CFP_t_U b) -> CFP_t_T {
if constexpr (is_cxx_complex(b)) {
return {a.real() * b.real() - a.imag() * b.imag(),
a.real() * b.imag() + a.imag() * b.real()};
} else {
return {a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x};
}
}
template <class CFP_t_T, class CFP_t_U = CFP_t_T>
inline static constexpr auto ConstMultConj(CFP_t_T a, CFP_t_U b) -> CFP_t_T {
return ConstMult(Conj(a), b);
}
/**
* @brief Compile-time scalar complex summation.
*
* @tparam T Precision of complex value `a` and result.
* @tparam U Precision of complex value `b`.
* @param a Complex scalar value.
* @param b Complex scalar value.
* @return constexpr std::complex<T>
*/
template <class CFP_t_T, class CFP_t_U = CFP_t_T>
inline static constexpr auto ConstSum(CFP_t_T a, CFP_t_U b) -> CFP_t_T {
if constexpr (std::is_same_v<CFP_t_T, cuComplex> ||
std::is_same_v<CFP_t_T, float2>) {
return cuCaddf(a, b);
} else {
return cuCadd(a, b);
}
}
/**
* @brief Return complex value 1+0i in the given precision.
*
* @tparam T Floating point precision type. Accepts `double` and `float`.
* @return constexpr std::complex<T>{1,0}
*/
template <class CFP_t> inline static constexpr auto ONE() -> CFP_t {
return {1, 0};
}
/**
* @brief Return complex value 0+0i in the given precision.
*
* @tparam T Floating point precision type. Accepts `double` and `float`.
* @return constexpr std::complex<T>{0,0}
*/
template <class CFP_t> inline static constexpr auto ZERO() -> CFP_t {
return {0, 0};
}
/**
* @brief Return complex value 0+1i in the given precision.
*
* @tparam T Floating point precision type. Accepts `double` and `float`.
* @return constexpr std::complex<T>{0,1}
*/
template <class CFP_t> inline static constexpr auto IMAG() -> CFP_t {
return {0, 1};
}
/**
* @brief Returns sqrt(2) as a compile-time constant.
*
* @tparam T Precision of result. `double`, `float` are accepted values.
* @return constexpr T sqrt(2)
*/
template <class CFP_t> inline static constexpr auto SQRT2() {
if constexpr (std::is_same_v<CFP_t, float2> ||
std::is_same_v<CFP_t, cuFloatComplex>) {
return CFP_t{0x1.6a09e6p+0F, 0}; // NOLINT: To be replaced in C++20
} else if constexpr (std::is_same_v<CFP_t, double2> ||
std::is_same_v<CFP_t, cuDoubleComplex>) {
return CFP_t{0x1.6a09e667f3bcdp+0,
0}; // NOLINT: To be replaced in C++20
} else if constexpr (std::is_same_v<CFP_t, double>) {
return 0x1.6a09e667f3bcdp+0; // NOLINT: To be replaced in C++20
} else {
return 0x1.6a09e6p+0F; // NOLINT: To be replaced in C++20
}
}
/**
* @brief Returns inverse sqrt(2) as a compile-time constant.
*
* @tparam T Precision of result. `double`, `float` are accepted values.
* @return constexpr T 1/sqrt(2)
*/
template <class CFP_t> inline static constexpr auto INVSQRT2() -> CFP_t {
if constexpr (std::is_same_v<CFP_t, std::complex<float>> ||
std::is_same_v<CFP_t, std::complex<double>>) {
return CFP_t(1 / M_SQRT2, 0);
} else {
return Div(CFP_t{1, 0}, SQRT2<CFP_t>());
}
}
/**
* @brief cuBLAS backed inner product for GPU data.
*
* @tparam T Complex data-type. Accepts cuFloatComplex and cuDoubleComplex/
* @param v1 Device data pointer 1
* @param v2 Device data pointer 2
* @param data_size Lengtyh of device data.
* @return T Inner-product result
*/
template <class T = cuFloatComplex>
inline auto innerProdC_CUDA(const T *v1, const T *v2, const int data_size,
const cudaStream_t &streamId) -> T {
T result{0.0, 0.0}; // Host result
cublasHandle_t handle;
cublasCreate(&handle);
cublasSetStream(handle, streamId);
if constexpr (std::is_same_v<T, cuFloatComplex>) {
cublasCdotc(handle, data_size, v1, 1, v2, 1, &result);
} else if constexpr (std::is_same_v<T, cuDoubleComplex>) {
cublasZdotc(handle, data_size, v1, 1, v2, 1, &result);
}
cublasDestroy(handle);
return result;
}
/**
* If T is a supported data type for gates, this expression will
* evaluate to `true`. Otherwise, it will evaluate to `false`.
*
* Supported data types are `float2`, `double2`, and their aliases.
*
* @tparam T candidate data type
*/
template <class T>
constexpr bool is_supported_data_type =
std::is_same_v<T, cuComplex> || std::is_same_v<T, float2> ||
std::is_same_v<T, cuDoubleComplex> || std::is_same_v<T, double2>;
/**
* @brief Simple overloaded method to define CUDA data type.
*
* @param t
* @return cuDoubleComplex
*/
inline cuDoubleComplex getCudaType(const double &t) {
static_cast<void>(t);
return {};
}
/**
* @brief Simple overloaded method to define CUDA data type.
*
* @param t
* @return cuFloatComplex
*/
inline cuFloatComplex getCudaType(const float &t) {
static_cast<void>(t);
return {};
}
/**
* @brief Return the number of supported CUDA capable GPU devices.
*
* @return std::size_t
*/
inline int getGPUCount() {
int result;
PL_CUDA_IS_SUCCESS(cudaGetDeviceCount(&result));
return result;
}
/**
* @brief Return the current GPU device.
*
* @return int
*/
inline int getGPUIdx() {
int result;
PL_CUDA_IS_SUCCESS(cudaGetDevice(&result));
return result;
}
inline static void deviceReset() { PL_CUDA_IS_SUCCESS(cudaDeviceReset()); }
/**
* @brief Checks to see if the given GPU supports the PennyLane-Lightning-GPU
* device. Minimum supported architecture is SM 7.0.
*
* @param device_number GPU device index
* @return bool
*/
static bool isCuQuantumSupported(int device_number = 0) {
cudaDeviceProp deviceProp;
cudaGetDeviceProperties(&deviceProp, device_number);
return deviceProp.major >= 7;
}
/**
* @brief Get current GPU major.minor support
*
* @param device_number
* @return std::pair<int,int>
*/
static std::pair<int, int> getGPUArch(int device_number = 0) {
cudaDeviceProp deviceProp;
cudaGetDeviceProperties(&deviceProp, device_number);
return std::make_pair(deviceProp.major, deviceProp.minor);
}
/** Chunk the data with the requested chunk size */
template <template <typename...> class Container, typename T>
auto chunkDataSize(const Container<T> &data, std::size_t chunk_size)
-> Container<Container<T>> {
Container<Container<T>> output;
for (std::size_t chunk = 0; chunk < data.size(); chunk += chunk_size) {
const auto chunk_end = std::min(data.size(), chunk + chunk_size);
output.emplace_back(data.begin() + chunk, data.begin() + chunk_end);
}
return output;
}
/** Chunk the data into the requested number of chunks */
template <template <typename...> class Container, typename T>
auto chunkData(const Container<T> &data, std::size_t num_chunks)
-> Container<Container<T>> {
const auto rem = data.size() % num_chunks;
const std::size_t div = static_cast<std::size_t>(data.size() / num_chunks);
if (!div) { // Match chunks to available work
return chunkDataSize(data, 1);
}
if (rem) { // We have an uneven split; ensure fair distribution
auto output =
chunkDataSize(Container<T>{data.begin(), data.end() - rem}, div);
auto output_rem =
chunkDataSize(Container<T>{data.end() - rem, data.end()}, div);
for (std::size_t idx = 0; idx < output_rem.size(); idx++) {
output[idx].insert(output[idx].end(), output_rem[idx].begin(),
output_rem[idx].end());
}
return output;
}
return chunkDataSize(data, div);
}
/** @brief `%CudaScopedDevice` uses RAII to select a CUDA device context.
*
* @see https://taskflow.github.io/taskflow/classtf_1_1cudaScopedDevice.html
*
* @note A `%CudaScopedDevice` instance cannot be moved or copied.
*
* @warning This class is not thread-safe.
*/
class CudaScopedDevice {
public:
/**
* @brief Constructs a `%CudaScopedDevice` using a CUDA device.
*
* @param device CUDA device to scope in the guard.
*/
CudaScopedDevice(int device) {
PL_CUDA_IS_SUCCESS(cudaGetDevice(&prev_device_));
if (prev_device_ == device) {
prev_device_ = -1;
} else {
PL_CUDA_IS_SUCCESS(cudaSetDevice(device));
}
}
/**
* @brief Destructs a `%CudaScopedDevice`, switching back to the previous
* CUDA device context.
*/
~CudaScopedDevice() {
if (prev_device_ != -1) {
// Throwing exceptions from a destructor can be dangerous.
// See https://isocpp.org/wiki/faq/exceptions#ctor-exceptions.
cudaSetDevice(prev_device_);
}
}
CudaScopedDevice() = delete;
CudaScopedDevice(const CudaScopedDevice &) = delete;
CudaScopedDevice(CudaScopedDevice &&) = delete;
private:
/// The previous CUDA device (or -1 if the device passed to the constructor
/// is the current CUDA device).
int prev_device_;
};
} // namespace Pennylane::CUDA::Util
| 31.119497 | 80 | 0.651846 | PennyLaneAI |
65ed7938ab2812c404caebb3d26a88d4f07e2ff5 | 1,858 | cpp | C++ | examples/CherryPicker/general_example.cpp | allison-group/indigox | 22657cb3ceb888049cc231e73d18fb2eac099604 | [
"MIT"
] | 7 | 2019-11-24T15:51:37.000Z | 2021-10-02T05:18:42.000Z | examples/CherryPicker/general_example.cpp | allison-group/indigox | 22657cb3ceb888049cc231e73d18fb2eac099604 | [
"MIT"
] | 2 | 2018-12-17T00:55:32.000Z | 2019-10-11T01:47:04.000Z | examples/CherryPicker/general_example.cpp | allison-group/indigox | 22657cb3ceb888049cc231e73d18fb2eac099604 | [
"MIT"
] | 2 | 2019-10-21T01:26:56.000Z | 2019-12-02T00:00:42.000Z | //
// C++ example that imports a molecule from an outputted binary (which you can produce from python with indigox.SaveMolecule)
// This example has CalculateElectrons on, so it will calculate formal charges and bond orders.
// Relies on the Python example having been run first so there is an Athenaeum to match the molecule to.
// Also assumes you are running from a build folder in the project root. If not, change example_folder_path below
//
#include <indigox/indigox.hpp>
#include <indigox/classes/athenaeum.hpp>
#include <indigox/classes/forcefield.hpp>
#include <indigox/classes/parameterised.hpp>
#include <indigox/algorithm/cherrypicker.hpp>
#include <experimental/filesystem>
int main() {
using namespace indigox;
namespace fs = std::experimental::filesystem;
using settings = indigox::algorithm::CherryPicker::Settings;
std::string example_folder_path = "../examples/CherryPicker/";
auto forceField = GenerateGROMOS54A7();
auto man_ath = LoadAthenaeum(example_folder_path + "ManualAthenaeum.ath");
// auto auto_ath = LoadAthenaeum(example_folder_path + "AutomaticAthenaeum.ath");
Molecule mol = LoadMolecule(example_folder_path + "TestMolecules/axinellinA.bin");
algorithm::CherryPicker cherryPicker(forceField);
cherryPicker.AddAthenaeum(man_ath);
cherryPicker.SetInt(settings::MinimumFragmentSize, 2);
cherryPicker.SetInt(settings::MaximumFragmentSize, 20);
cherryPicker.SetBool(settings::CalculateElectrons);
const indigox::ParamMolecule &molecule = cherryPicker.ParameteriseMolecule(mol);
//We can't save the parameterisation directly in ITP format from C++, but we save the binary molecule output
//which can be imported by the python module and outputted in ITP, IXD, PDB and RTP formats
SaveMolecule(mol, example_folder_path + "TestMolecules/axinellinA.out.param");
std::cout << "Done!\n";
}
| 41.288889 | 125 | 0.777718 | allison-group |
65eecaa7eecf4b5dfad13c5cc46fe6e749fea72f | 3,007 | hpp | C++ | Include/LibYT/Concepts.hpp | MalteDoemer/YeetOS2 | 82be488ec1ed13e6558af4e248977dad317b3b85 | [
"BSD-2-Clause"
] | null | null | null | Include/LibYT/Concepts.hpp | MalteDoemer/YeetOS2 | 82be488ec1ed13e6558af4e248977dad317b3b85 | [
"BSD-2-Clause"
] | null | null | null | Include/LibYT/Concepts.hpp | MalteDoemer/YeetOS2 | 82be488ec1ed13e6558af4e248977dad317b3b85 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright 2021 Malte Dömer
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "StdLibExtras.hpp"
#include "Types.hpp"
namespace YT {
template<class T>
concept ArithmeticType = IsArithmetic<T>::value;
template<class T>
concept ConstType = IsConst<T>::value;
template<class T>
concept EnumType = IsEnum<T>::value;
template<class T>
concept FloatingPointType = IsFloatingPoint<T>::value;
template<class T>
concept FundamentalType = IsFundamental<T>::value;
template<class T>
concept IntegralType = IsIntegral<T>::value;
template<class T>
concept NullPointerType = IsNullPointer<T>::value;
template<class T>
concept SigendType = IsSigned<T>::value;
template<class T>
concept UnionType = IsUnion<T>::value;
template<class T>
concept UnsigendType = IsUnsigned<T>::value;
template<class T, class U>
concept SameAs = IsSame<T, U>::value;
template<class From, class To>
concept ConvertibleTo = IsConvertible<From, To>::value;
template<class T>
concept EqualityCompareable = requires(T a, T b)
{
{ a == b } -> ConvertibleTo<bool>;
{ a != b } -> ConvertibleTo<bool>;
};
template<class T>
concept Compareable = requires(T a, T b)
{
{ a == b } -> ConvertibleTo<bool>;
{ a != b } -> ConvertibleTo<bool>;
{ a <= b } -> ConvertibleTo<bool>;
{ a >= b } -> ConvertibleTo<bool>;
{ a < b } -> ConvertibleTo<bool>;
{ a > b } -> ConvertibleTo<bool>;
};
}
using YT::ArithmeticType;
using YT::Compareable;
using YT::ConstType;
using YT::ConvertibleTo;
using YT::EnumType;
using YT::EqualityCompareable;
using YT::FloatingPointType;
using YT::FundamentalType;
using YT::IntegralType;
using YT::NullPointerType;
using YT::SameAs;
using YT::SigendType;
using YT::UnionType;
using YT::UnsigendType; | 29.480392 | 81 | 0.736615 | MalteDoemer |
65f4694160beffb076d12e39d59639ef6df2e43d | 1,073 | cpp | C++ | AzureClient/AzureClient/EventHub.cpp | Ashish-Me2/Arduino-ESP8266-AzureIoTHub-MQTT-CameraMonitoring | 695ca226ca0b9331a516573376323d71afb08f35 | [
"MIT"
] | 3 | 2019-05-22T22:03:50.000Z | 2020-11-25T11:56:38.000Z | AzureClient/AzureClient/EventHub.cpp | Ashish-Me2/Arduino-ESP8266-AzureIoTHub-MQTT-CameraMonitoring | 695ca226ca0b9331a516573376323d71afb08f35 | [
"MIT"
] | null | null | null | AzureClient/AzureClient/EventHub.cpp | Ashish-Me2/Arduino-ESP8266-AzureIoTHub-MQTT-CameraMonitoring | 695ca226ca0b9331a516573376323d71afb08f35 | [
"MIT"
] | null | null | null | #include "EventHub.h"
String Eventhub::createSas(char *key, String url){
// START: Create SAS
// https://azure.microsoft.com/en-us/documentation/articles/service-bus-sas-overview/
// Where to get seconds since the epoch: local service, SNTP, RTC
sasExpiryTime = now() + sasExpiryPeriodInSeconds;
String stringToSign = url + "\n" + sasExpiryTime;
// START: Create signature
Sha256.initHmac((const uint8_t*)key, 44);
Sha256.print(stringToSign);
char* sign = (char*) Sha256.resultHmac();
int signLen = 32;
// END: Create signature
// START: Get base64 of signature
int encodedSignLen = base64_enc_len(signLen);
char encodedSign[encodedSignLen];
base64_encode(encodedSign, sign, signLen);
// END: Get base64 of signature
// SharedAccessSignature
return "sr=" + url + "&sig="+ urlEncode(encodedSign) + "&se=" + sasExpiryTime +"&skn=" + deviceId;
// END: create SAS
}
void Eventhub::initialiseHub() {
sasUrl = urlEncode("https://") + urlEncode(host) + urlEncode(EVENT_HUB_END_POINT);
endPoint = EVENT_HUB_END_POINT;
}
| 29.805556 | 100 | 0.698043 | Ashish-Me2 |
65f5030cb99991738a96f16d0715dee55bc429ea | 2,490 | hpp | C++ | src/key/key_wallet.hpp | feitebi/main-chain | d4f2c4bb99b083d6162614a9a6b684c66ddf5d88 | [
"MIT"
] | 1 | 2018-01-17T05:08:32.000Z | 2018-01-17T05:08:32.000Z | src/key/key_wallet.hpp | feitebi/main-chain | d4f2c4bb99b083d6162614a9a6b684c66ddf5d88 | [
"MIT"
] | null | null | null | src/key/key_wallet.hpp | feitebi/main-chain | d4f2c4bb99b083d6162614a9a6b684c66ddf5d88 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2013-2014 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt)
*
* This file is part of coinpp.
*
* coinpp is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef COIN_KEY_WALLET_HPP
#define COIN_KEY_WALLET_HPP
#include <cstdint>
#include <string>
#include <coin/data_buffer.hpp>
#include <coin/key.hpp>
namespace coin {
/**
* Implements a wallet (private) key.
*/
class key_wallet : public data_buffer
{
public:
/**
* Constructor
*/
key_wallet(const std::int64_t & expires = 0);
/**
* Encodes.
*/
void encode();
/**
* Decodes
* @param buffer The data_buffer.
*/
void encode(data_buffer & buffer);
/**
* Decodes
*/
void decode();
/**
* Decodes
* @param buffer The data_buffer.
*/
void decode(data_buffer & buffer);
/**
* The private key.
*/
const key::private_t & key_private() const;
private:
/**
* The private key.
*/
key::private_t m_key_private;
/**
* The time created.
*/
std::int64_t m_time_created;
/**
* The time expires.
*/
std::int64_t m_time_expires;
/**
* The comment.
*/
std::string m_comment;
protected:
// ...
};
} // namespace coin
#endif // COIN_KEY_WALLET_HPP
| 24.653465 | 76 | 0.51245 | feitebi |
65f78b8241e1cdf7e3674e5b1cf8e06515e1c5ba | 1,476 | cpp | C++ | test/test_dumpFHESetting.cpp | fionser/MDLHElib | 3c686ab35d7b26a893213a6e9d4249cd46c2969d | [
"MIT"
] | 5 | 2017-01-16T06:20:07.000Z | 2018-05-17T12:36:34.000Z | test/test_dumpFHESetting.cpp | fionser/MDLHElib | 3c686ab35d7b26a893213a6e9d4249cd46c2969d | [
"MIT"
] | null | null | null | test/test_dumpFHESetting.cpp | fionser/MDLHElib | 3c686ab35d7b26a893213a6e9d4249cd46c2969d | [
"MIT"
] | 2 | 2017-08-26T13:16:35.000Z | 2019-03-15T02:08:20.000Z | #include "utils/FHEUtils.hpp"
#include "utils/timer.hpp"
#include "fhe/EncryptedArray.h"
#include <string>
#include "algebra/NDSS.h"
void test_load(long m, long p, long r, long L)
{
MDL::Timer timer;
std::string path("fhe_setting");
timer.start();
FHEcontext context(m, p, r);
timer.end();
printf("Initial Context costed %f\n", timer.second());
timer.reset();
FHESecKey sk(context);
timer.end();
printf("Initial SK costed %f\n", timer.second());
timer.reset();
load_FHE_setting(path, context, sk);
timer.end();
printf("Load costed %f sec.\n", timer.second());
FHEPubKey pk = sk;
NTL::ZZX plain;
Ctxt ctxt(pk);
pk.Encrypt(ctxt, NTL::to_ZZX(10));
ctxt *= ctxt;
sk.Decrypt(plain, ctxt);
assert(plain == 100);
auto G = context.alMod.getFactorsOverZZ()[0];
EncryptedArray ea(context, G);
assert(ea.size() == 4);
}
void test_dump(long m, long p, long r, long L)
{
MDL::Timer timer;
timer.start();
dump_FHE_setting_to_file("fhe_setting_32", 80, m, p, r, L);
timer.end();
printf("Cost %f to dump m : %ld, p : %ld, r : %ld, L : %ld\n",
timer.second(), m, p, r, L);
}
int main(int argc, char *argv[]) {
ArgMapping arg;
long m, p, r, L;
arg.arg("m", m, "m");
arg.arg("p", p, "p");
arg.arg("r", r, "r");
arg.arg("L", L, "L");
arg.parse(argc, argv);
//test_load(m, p, r, L);
test_dump(m, p, r, L);
return 0;
}
| 23.0625 | 66 | 0.573171 | fionser |
65f7ae9a8d8b474c1e1ec8bb2150a22ff8451fb6 | 1,762 | cpp | C++ | moon-src/luabind/lua_http.cpp | leefy4415/moon | 2a2005306e9a685a6af899a0daae9c53603b38e4 | [
"MIT"
] | 1 | 2020-09-22T01:57:54.000Z | 2020-09-22T01:57:54.000Z | moon-src/luabind/lua_http.cpp | leefy4415/moon | 2a2005306e9a685a6af899a0daae9c53603b38e4 | [
"MIT"
] | null | null | null | moon-src/luabind/lua_http.cpp | leefy4415/moon | 2a2005306e9a685a6af899a0daae9c53603b38e4 | [
"MIT"
] | null | null | null | #include "sol/sol.hpp"
#include "common/http_util.hpp"
using namespace moon;
static sol::table bind_http(sol::this_state L)
{
sol::state_view lua(L);
sol::table module = lua.create_table();
module.set_function("parse_request", [](std::string_view data) {
std::string_view method;
std::string_view path;
std::string_view query_string;
std::string_view version;
http::case_insensitive_multimap_view header;
bool ok = http::request_parser::parse(data, method, path, query_string, version, header);
return std::make_tuple(ok, method, path, query_string, version, sol::as_table(header));
});
module.set_function("parse_response", [](std::string_view data) {
std::string_view version;
std::string_view status_code;
http::case_insensitive_multimap_view header;
bool ok = http::response_parser::parse(data, version, status_code, header);
return std::make_tuple(ok, version, status_code, sol::as_table(header));
});
module.set_function("parse_query_string", [](const std::string &data) {
return sol::as_table(http::query_string::parse(data));
});
module.set_function("create_query_string", [](sol::as_table_t<http::case_insensitive_multimap> src) {
return http::query_string::create(src.value());
});
module.set_function("urlencode", [](std::string_view src) {
return http::percent::encode(std::string{ src });
});
module.set_function("urldecode", [](std::string_view src) {
return http::percent::decode(std::string{ src });
});
return module;
}
extern "C"
{
int LUAMOD_API luaopen_http(lua_State *L)
{
return sol::stack::call_lua(L, 1, bind_http);
}
}
| 32.036364 | 105 | 0.658343 | leefy4415 |
65fa36eff75fb1297b6d8f4576e3411c7e51c17c | 4,952 | cpp | C++ | modules/attention_segmentation/src/Texture.cpp | v4r-tuwien/v4r | ff3fbd6d2b298b83268ba4737868bab258262a40 | [
"BSD-1-Clause",
"BSD-2-Clause"
] | 2 | 2021-02-22T11:36:33.000Z | 2021-07-20T11:31:08.000Z | modules/attention_segmentation/src/Texture.cpp | v4r-tuwien/v4r | ff3fbd6d2b298b83268ba4737868bab258262a40 | [
"BSD-1-Clause",
"BSD-2-Clause"
] | null | null | null | modules/attention_segmentation/src/Texture.cpp | v4r-tuwien/v4r | ff3fbd6d2b298b83268ba4737868bab258262a40 | [
"BSD-1-Clause",
"BSD-2-Clause"
] | 3 | 2018-10-19T10:39:23.000Z | 2021-04-07T13:39:03.000Z | /****************************************************************************
**
** Copyright (C) 2017 TU Wien, ACIN, Vision 4 Robotics (V4R) group
** Contact: v4r.acin.tuwien.ac.at
**
** This file is part of V4R
**
** V4R is distributed under dual licenses - GPLv3 or closed source.
**
** GNU General Public License Usage
** V4R 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.
**
** V4R 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.
**
** Please review the following information to ensure the GNU General Public
** License requirements will be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
**
** Commercial License Usage
** If GPL is not suitable for your project, you must purchase a commercial
** license to use V4R. Licensees holding valid commercial V4R licenses may
** use this file in accordance with the commercial license agreement
** provided with the Software or, alternatively, in accordance with the
** terms contained in a written agreement between you and TU Wien, ACIN, V4R.
** For licensing terms and conditions please contact office<at>acin.tuwien.ac.at.
**
**
** The copyright holder additionally grants the author(s) of the file the right
** to use, copy, modify, merge, publish, distribute, sublicense, and/or
** sell copies of their contributions without any restrictions.
**
****************************************************************************/
/**
* @file Texture.cpp
* @author Richtsfeld
* @date October 2012
* @version 0.1
* @brief Calculate texture feature to compare surface texture.
*/
#include "v4r/attention_segmentation/Texture.h"
namespace v4r {
/************************************************************************************
* Constructor/Destructor
*/
Texture::Texture() {
computed = false;
have_edges = false;
have_indices = false;
}
Texture::~Texture() {}
void Texture::setInputEdges(cv::Mat &_edges) {
if ((_edges.cols <= 0) || (_edges.rows <= 0)) {
LOG(ERROR) << "Invalid image (height|width must be > 1";
throw std::runtime_error("[Texture::setInputEdges] Invalid image (height|width must be > 1)");
}
if (_edges.type() != CV_8UC1) {
LOG(ERROR) << "Invalid image type (must be 8UC1)";
throw std::runtime_error("[Texture::setInputEdges] Invalid image type (must be 8UC1)");
}
edges = _edges;
width = edges.cols;
height = edges.rows;
have_edges = true;
computed = false;
indices.reset(new pcl::PointIndices);
for (int i = 0; i < width * height; i++) {
indices->indices.push_back(i);
}
}
void Texture::setIndices(pcl::PointIndices::Ptr _indices) {
if (!have_edges) {
LOG(ERROR) << "No edges available.";
throw std::runtime_error("[Texture::setIndices]: Error: No edges available.");
}
indices = _indices;
have_indices = true;
}
void Texture::setIndices(std::vector<int> &_indices) {
indices.reset(new pcl::PointIndices);
indices->indices = _indices;
}
void Texture::setIndices(cv::Rect _rect) {
if (!have_edges) {
LOG(ERROR) << "No edges available.";
throw std::runtime_error("[Texture::setIndices]: Error: No edges available.");
}
if (_rect.y >= height) {
_rect.y = height - 1;
}
if ((_rect.y + _rect.height) >= height) {
_rect.height = height - _rect.y;
}
if (_rect.x >= width) {
_rect.x = width - 1;
}
if ((_rect.x + _rect.width) >= width) {
_rect.width = width - _rect.x;
}
VLOG(1) << "_rect = " << _rect.x << ", " << _rect.y << ", " << _rect.x + _rect.width << ", "
<< _rect.y + _rect.height;
indices.reset(new pcl::PointIndices);
for (int r = _rect.y; r < (_rect.y + _rect.height); r++) {
for (int c = _rect.x; c < (_rect.x + _rect.width); c++) {
indices->indices.push_back(r * width + c);
}
}
have_indices = true;
}
void Texture::compute() {
if (!have_edges) {
LOG(ERROR) << "No edges available.";
throw std::runtime_error("[Texture::compute]: Error: No edges available.");
}
textureRate = 0.0;
if ((indices->indices.size()) <= 0) {
computed = true;
return;
}
int texArea = 0;
for (unsigned int i = 0; i < indices->indices.size(); i++) {
int x = indices->indices.at(i) % width;
int y = indices->indices.at(i) / width;
if (edges.at<uchar>(y, x) == 255)
texArea++;
}
textureRate = (double)((double)texArea / indices->indices.size());
computed = true;
}
double Texture::compare(Texture::Ptr t) {
if (!computed || !(t->getComputed())) {
LOG(ERROR) << "Texture is not computed.";
return 0.;
}
return 1. - fabs(textureRate - t->getTextureRate());
}
} // namespace v4r
| 28.45977 | 98 | 0.625606 | v4r-tuwien |
65faebe41985ba4358f801d511d4a70b4b67e77d | 218 | cc | C++ | versus/go/01-lambdas/capture.cc | JohnMurray/cpp-vs | def49c416b5abf161241e7c1d8b41e6b01fb8cac | [
"Apache-2.0"
] | 10 | 2018-05-07T03:00:00.000Z | 2022-03-14T14:26:27.000Z | versus/ruby/01-lambda/capture.cc | JohnMurray/cpp-vs | def49c416b5abf161241e7c1d8b41e6b01fb8cac | [
"Apache-2.0"
] | 35 | 2018-05-26T16:01:58.000Z | 2022-03-30T22:39:33.000Z | versus/ruby/01-lambda/capture.cc | JohnMurray/cpp-vs | def49c416b5abf161241e7c1d8b41e6b01fb8cac | [
"Apache-2.0"
] | 1 | 2018-07-17T12:47:24.000Z | 2018-07-17T12:47:24.000Z | #include <functional>
template<typename T>
std::function<T(T)> addX(T x) {
return [x](T n) -> T {
return n + x;
};
}
int main() {
auto addFive = addX<int>(5);
addFive(10);
// returns 15
} | 14.533333 | 32 | 0.527523 | JohnMurray |
65ffc9b0a240192ee6b9cc3dfd054327cc20d6cc | 2,356 | cpp | C++ | Engine/src/Render/Camera/icMaxCam.cpp | binofet/ice | dee91da76df8b4f46ed4727d901819d8d20aefe3 | [
"MIT"
] | null | null | null | Engine/src/Render/Camera/icMaxCam.cpp | binofet/ice | dee91da76df8b4f46ed4727d901819d8d20aefe3 | [
"MIT"
] | null | null | null | Engine/src/Render/Camera/icMaxCam.cpp | binofet/ice | dee91da76df8b4f46ed4727d901819d8d20aefe3 | [
"MIT"
] | null | null | null |
#include "Render/Camera/icMaxCam.h"
#include "Core/IO/icInput.h"
#include "Math/Matrix/icMatrix44.h"
icMaxCam::icMaxCam( void )
{
m_rZoom = 100.0f;
m_rXrot = 0.0f;
m_rYrot = 0.0f;
m_rZoomMin = 50.0f;
m_rZoomMax = 500.0f;
m_v3Center.Set(0.0f,0.0f,0.0f);
bEnableInput = true;
}
icMaxCam::~icMaxCam( void )
{
}
void icMaxCam::Update( const float fDeltaTime )
{
if (bEnableInput)
{
icInput* input = icInput::Instance();
if (input->IsDown(ICMOUSE_M) || input->IsDown(ICMOUSE_R))
{
if (input->IsDown(ICKEY_LALT))
{
// arc rotate
icReal x = input->GetAxis(ICAXIS_MOUSE_X) * fDeltaTime * 5000.0f * m_rZoom/m_rZoomMax;
icReal y = input->GetAxis(ICAXIS_MOUSE_Y) * fDeltaTime * 5000.0f * m_rZoom/m_rZoomMax;
if (m_rYrot > 0)
m_rYrot += y;
else
m_rYrot -= y;
m_rXrot -= x;
}
else
{
// pan
icReal z_amt = (m_rZoom - m_rZoomMin) + 0.05f * (m_rZoomMax - m_rZoomMin);
icReal x = input->GetAxis(ICAXIS_MOUSE_X) * fDeltaTime * 200.0f * z_amt;
icReal y = input->GetAxis(ICAXIS_MOUSE_Y) * fDeltaTime * 200.0f * z_amt;
m_v3Center += m_m44ViewMat.Transform(-x,-y,0.0f);
}
}
// handle zoom
icReal zoom = input->GetAxis(ICAXIS_MOUSE_Z);
m_rZoom -= zoom * fDeltaTime * 1000.0f;
m_rZoom = icClamp(m_rZoom, m_rZoomMin, m_rZoomMax);
}
// trimming
while (m_rYrot > IC_PI * 2.0f)
m_rYrot -= 2 * IC_PI;
while (m_rYrot < 0.0f)
m_rYrot += 2 * IC_PI;
while (m_rXrot > IC_PI * 2.0f)
m_rXrot -= 2 * IC_PI;
while (m_rXrot < 0.0f)
m_rXrot += 2 * IC_PI;
icReal theta = m_rXrot;
icReal phi = m_rYrot - IC_PI;
icReal Cx, Cy, Cz;
Cx = m_rZoom * icCos(theta) * icSin(phi);
Cy = m_rZoom * icCos(phi);
Cz = m_rZoom * icSin(theta) * icSin(phi);
icVector3 point(Cx,Cy,Cz);
icVector3 position = point + m_v3Center;
if (phi < 0.0)
icCreateLookAt(position, m_v3Center,icVector3(0.0f,-1.0,0.0f),m_m44ViewMat);
else
icCreateLookAt(position, m_v3Center,icVector3::Y_AXIS,m_m44ViewMat);
} | 26.47191 | 102 | 0.547114 | binofet |
5a0052e98e648bb4eb323ab2d2191dcca614cd58 | 965 | cpp | C++ | workdir/ScopeAnalysis/LORAnalysis/SDAEstimateTOFCalib.cpp | wictus/oldScopeAnalysis | e8a15f11c504c1a1a880d4a5096cdbfac0edf2de | [
"MIT"
] | null | null | null | workdir/ScopeAnalysis/LORAnalysis/SDAEstimateTOFCalib.cpp | wictus/oldScopeAnalysis | e8a15f11c504c1a1a880d4a5096cdbfac0edf2de | [
"MIT"
] | null | null | null | workdir/ScopeAnalysis/LORAnalysis/SDAEstimateTOFCalib.cpp | wictus/oldScopeAnalysis | e8a15f11c504c1a1a880d4a5096cdbfac0edf2de | [
"MIT"
] | null | null | null | #include "./SDAEstimateTOFCalib.h"
SDAEstimateTOFCalib::SDAEstimateTOFCalib(const char* name, const char* title,
const char* in_file_suffix, const char* out_file_suffix, const double threshold) : JPetCommonAnalysisModule( name, title, in_file_suffix, out_file_suffix )
{
fSelectedThreshold = threshold;
}
SDAEstimateTOFCalib::~SDAEstimateTOFCalib(){}
void SDAEstimateTOFCalib::begin()
{
}
void SDAEstimateTOFCalib::exec()
{
fReader->getEntry(fEvent);
const JPetLOR& fLOR = dynamic_cast< JPetLOR& > ( fReader->getData() );
fTOFs.push_back( ( fLOR.getSecondHit().getTime() - fLOR.getFirstHit().getTime() ) );
fEvent++;
}
void SDAEstimateTOFCalib::end()
{
gStyle->SetOptFit(1);
TCanvas* c1 = new TCanvas();
TH1F* TOF = new TH1F("TOF", "TOF", 2000, -10, 10);
for( unsigned int i = 0; i < fTOFs.size(); i++)
{
TOF->Fill(fTOFs[i]/1000.0);
}
TOF->Sumw2();
TOF->Draw();
TOF->Fit("gaus","QI");
c1->SaveAs("TOF.png");
}
| 21.444444 | 170 | 0.674611 | wictus |
5a08229b925f117033174e8422230e6102f958af | 1,884 | cpp | C++ | Algorithms/0047.PermutationsII/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | Algorithms/0047.PermutationsII/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | Algorithms/0047.PermutationsII/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <vector>
#include "gtest/gtest.h"
namespace
{
class Solution
{
public:
std::vector<std::vector<int>> permuteUnique(std::vector<int> const &nums) const
{
std::vector<int> numbers(nums);
std::sort(numbers.begin(), numbers.end());
std::vector<bool> usedNumbers;
for (size_t index = 0; index < numbers.size(); ++index)
usedNumbers.push_back(false);
std::vector<int> current;
std::vector<std::vector<int>> dest;
generate(numbers, usedNumbers, current, dest);
return dest;
}
private:
void generate(std::vector<int> const &numbers, std::vector<bool> &usedNumbers, std::vector<int> ¤t, std::vector<std::vector<int>> &dest) const
{
size_t lastUsedIndex = numbers.size();
for (size_t index = 0; index < numbers.size(); ++index)
{
if (!usedNumbers[index])
{
if (lastUsedIndex != numbers.size() && numbers[lastUsedIndex] == numbers[index])
continue;
lastUsedIndex = index;
current.push_back(numbers[index]);
const bool isPermutation = current.size() == numbers.size();
if (isPermutation)
dest.push_back(current);
else
{
usedNumbers[index] = true;
generate(numbers, usedNumbers, current, dest);
usedNumbers[index] = false;
}
current.pop_back();
if (isPermutation)
return;
}
}
}
};
}
namespace PermutationsIITask
{
TEST(PermutationsIITaskTests, Examples)
{
const Solution solution;
ASSERT_EQ(std::vector<std::vector<int>>({{1, 1, 2}, {1, 2, 1}, {2, 1, 1}}), solution.permuteUnique({1, 1, 2}));
}
}
| 28.545455 | 152 | 0.54034 | stdstring |
5a110d9ca6988282ec336215a807428ea875e35f | 850 | hpp | C++ | pomdog/experimental/gui/debug_navigator.hpp | mogemimi/pomdog | 6dc6244d018f70d42e61c6118535cf94a9ee0618 | [
"MIT"
] | 163 | 2015-03-16T08:42:32.000Z | 2022-01-11T21:40:22.000Z | pomdog/experimental/gui/debug_navigator.hpp | mogemimi/pomdog | 6dc6244d018f70d42e61c6118535cf94a9ee0618 | [
"MIT"
] | 17 | 2015-04-12T20:57:50.000Z | 2020-10-10T10:51:45.000Z | pomdog/experimental/gui/debug_navigator.hpp | mogemimi/pomdog | 6dc6244d018f70d42e61c6118535cf94a9ee0618 | [
"MIT"
] | 21 | 2015-04-12T20:45:11.000Z | 2022-01-14T20:50:16.000Z | // Copyright mogemimi. Distributed under the MIT license.
#pragma once
#include "pomdog/basic/conditional_compilation.hpp"
#include "pomdog/chrono/duration.hpp"
#include "pomdog/chrono/game_clock.hpp"
#include "pomdog/experimental/gui/widget.hpp"
POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_BEGIN
#include <deque>
#include <memory>
#include <string>
POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_END
namespace pomdog::gui {
class DebugNavigator final : public Widget {
public:
DebugNavigator(
const std::shared_ptr<UIEventDispatcher>& dispatcher,
const std::shared_ptr<GameClock>& clock);
void Draw(DrawingContext& drawingContext) override;
private:
std::shared_ptr<GameClock> clock;
std::deque<float> frameRates;
Duration duration;
std::string frameRateString;
};
} // namespace pomdog::gui
| 25 | 61 | 0.770588 | mogemimi |
5a1420d1660d2c8ebe5911459718a6172f131fb9 | 3,888 | hpp | C++ | Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/common/pthreadcond.hpp | TiagoPedroByterev/openvpnclient-ios | a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76 | [
"MIT"
] | 10 | 2021-03-29T13:52:06.000Z | 2022-03-10T02:24:25.000Z | Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/common/pthreadcond.hpp | TiagoPedroByterev/openvpnclient-ios | a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76 | [
"MIT"
] | 1 | 2019-07-19T02:40:32.000Z | 2019-07-19T02:40:32.000Z | Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/common/pthreadcond.hpp | TiagoPedroByterev/openvpnclient-ios | a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76 | [
"MIT"
] | 7 | 2018-07-11T10:37:02.000Z | 2019-08-03T10:34:08.000Z | // OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2017 OpenVPN Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
#ifndef OPENVPN_COMMON_PTHREADCOND_H
#define OPENVPN_COMMON_PTHREADCOND_H
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <openvpn/common/stop.hpp>
namespace openvpn {
// Barrier class that is useful in cases where all threads
// need to reach a known point before executing some action.
// Note that this barrier implementation is
// constructed using C++11 condition variables.
class PThreadBarrier
{
enum State {
UNSIGNALED=0, // initial state
SIGNALED, // signal() was called
ERROR_THROWN, // error() was called
};
public:
// status return from wait()
enum Status {
SUCCESS=0, // successful
CHOSEN_ONE, // successful and chosen (only one thread is chosen)
TIMEOUT, // timeout
ERROR, // at least one thread called error()
};
PThreadBarrier(const int initial_limit = -1)
: stop(nullptr),
limit(initial_limit)
{
}
PThreadBarrier(Stop* stop_arg, const int initial_limit = -1)
: stop(stop_arg),
limit(initial_limit)
{
}
// All callers will increment count and block until
// count == limit. CHOSEN_ONE will be returned to
// the first caller to reach limit. This caller can
// then release all the other callers by calling
// signal().
int wait(const unsigned int seconds)
{
// allow asynchronous stop
Stop::Scope stop_scope(stop, [this]() {
error();
});
bool timeout = false;
int ret;
std::unique_lock<std::mutex> lock(mutex);
const unsigned int c = ++count;
while (state == UNSIGNALED
&& (limit < 0 || c < limit)
&& !timeout)
timeout = (cv.wait_for(lock, std::chrono::seconds(seconds)) == std::cv_status::timeout);
if (timeout)
ret = TIMEOUT;
else if (state == ERROR_THROWN)
ret = ERROR;
else if (state == UNSIGNALED && !chosen)
{
ret = CHOSEN_ONE;
chosen = true;
}
else
ret = SUCCESS;
return ret;
}
void set_limit(const int new_limit)
{
std::unique_lock<std::mutex> lock(mutex);
limit = new_limit;
cv.notify_all();
}
// Generally, only the CHOSEN_ONE calls signal() after its work
// is complete, to allow the other threads to pass the barrier.
void signal()
{
signal_(SIGNALED);
}
// Causes all threads waiting on wait() (and those which call wait()
// in the future) to exit with ERROR status.
void error()
{
signal_(ERROR_THROWN);
}
private:
void signal_(const State newstate)
{
std::unique_lock<std::mutex> lock(mutex);
if (state == UNSIGNALED)
{
state = newstate;
cv.notify_all();
}
}
std::mutex mutex;
std::condition_variable cv;
Stop* stop;
State state{UNSIGNALED};
bool chosen = false;
unsigned int count = 0;
int limit;
};
}
#endif
| 27 | 89 | 0.637088 | TiagoPedroByterev |
5a1c1bdce9d2b6701ef76bb1d6d295398535a614 | 1,505 | cpp | C++ | tests/algebra/operator/conjugate.cpp | qftphys/Simulate-the-non-equilibrium-dynamics-of-Fermionic-systems | 48d36fecbe4bc12af90f104cdf1f9f68352c508c | [
"MIT"
] | 2 | 2021-01-18T14:35:43.000Z | 2022-03-22T15:12:49.000Z | tests/algebra/operator/conjugate.cpp | f-koehler/ieompp | 48d36fecbe4bc12af90f104cdf1f9f68352c508c | [
"MIT"
] | null | null | null | tests/algebra/operator/conjugate.cpp | f-koehler/ieompp | 48d36fecbe4bc12af90f104cdf1f9f68352c508c | [
"MIT"
] | null | null | null | #include "operator.hpp"
using namespace ieompp::algebra;
TEST_CASE("conjugate_1")
{
const auto a = Operator1::make_creator(0ul), b = Operator1::make_annihilator(0ul);
Operator1 a_conj(a), b_conj(b);
a_conj.conjugate();
b_conj.conjugate();
REQUIRE(a_conj == b);
REQUIRE(b_conj == a);
}
TEST_CASE("conjugate_2")
{
const auto a = Operator2::make_creator(0ul, true), b = Operator2::make_annihilator(0ul, true);
Operator2 a_conj(a), b_conj(b);
a_conj.conjugate();
b_conj.conjugate();
REQUIRE(a_conj == b);
REQUIRE(b_conj == a);
}
TEST_CASE("conjugate_3")
{
const auto a = Operator3::make_creator(0ul, true, 'a'),
b = Operator3::make_annihilator(0ul, true, 'a');
Operator3 a_conj(a), b_conj(b);
a_conj.conjugate();
b_conj.conjugate();
REQUIRE(a_conj == b);
REQUIRE(b_conj == a);
}
TEST_CASE("get_conjugate_1")
{
const auto a = Operator1::make_creator(0ul), b = Operator1::make_annihilator(0ul);
REQUIRE(a.get_conjugate() == b);
REQUIRE(b.get_conjugate() == a);
}
TEST_CASE("get_conjugate_2")
{
const auto a = Operator2::make_creator(0ul, true), b = Operator2::make_annihilator(0ul, true);
REQUIRE(a.get_conjugate() == b);
REQUIRE(b.get_conjugate() == a);
}
TEST_CASE("get_conjugate_3")
{
const auto a = Operator3::make_creator(0ul, true, 'a'),
b = Operator3::make_annihilator(0ul, true, 'a');
REQUIRE(a.get_conjugate() == b);
REQUIRE(b.get_conjugate() == a);
}
| 24.274194 | 98 | 0.64186 | qftphys |
5a205b4c2557930f1cd90d29161e4aa9bb755121 | 12,929 | cpp | C++ | Sources/simdlib/SimdSse2Texture.cpp | aestesis/Csimd | b333a8bb7e7f2707ed6167badb8002cfe3504bbc | [
"Apache-2.0"
] | 6 | 2017-10-13T04:29:38.000Z | 2018-05-10T13:52:20.000Z | Sources/simdlib/SimdSse2Texture.cpp | aestesis/Csimd | b333a8bb7e7f2707ed6167badb8002cfe3504bbc | [
"Apache-2.0"
] | null | null | null | Sources/simdlib/SimdSse2Texture.cpp | aestesis/Csimd | b333a8bb7e7f2707ed6167badb8002cfe3504bbc | [
"Apache-2.0"
] | null | null | null | /*
* Simd Library (http://ermig1979.github.io/Simd).
*
* Copyright (c) 2011-2017 Yermalayeu Ihar.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "Simd/SimdMemory.h"
#include "Simd/SimdExtract.h"
#include "Simd/SimdStore.h"
#include "Simd/SimdBase.h"
namespace Simd
{
#ifdef SIMD_SSE2_ENABLE
namespace Sse2
{
SIMD_INLINE __m128i TextureBoostedSaturatedGradient16(__m128i a, __m128i b, __m128i saturation, const __m128i & boost)
{
return _mm_mullo_epi16(_mm_max_epi16(K_ZERO, _mm_add_epi16(saturation, _mm_min_epi16(_mm_sub_epi16(b, a), saturation))), boost);
}
SIMD_INLINE __m128i TextureBoostedSaturatedGradient8(__m128i a, __m128i b, __m128i saturation, const __m128i & boost)
{
__m128i lo = TextureBoostedSaturatedGradient16(_mm_unpacklo_epi8(a, K_ZERO), _mm_unpacklo_epi8(b, K_ZERO), saturation, boost);
__m128i hi = TextureBoostedSaturatedGradient16(_mm_unpackhi_epi8(a, K_ZERO), _mm_unpackhi_epi8(b, K_ZERO), saturation, boost);
return _mm_packus_epi16(lo, hi);
}
template<bool align> SIMD_INLINE void TextureBoostedSaturatedGradient(const uint8_t * src, uint8_t * dx, uint8_t * dy,
size_t stride, __m128i saturation, __m128i boost)
{
const __m128i s10 = Load<false>((__m128i*)(src - 1));
const __m128i s12 = Load<false>((__m128i*)(src + 1));
const __m128i s01 = Load<align>((__m128i*)(src - stride));
const __m128i s21 = Load<align>((__m128i*)(src + stride));
Store<align>((__m128i*)dx, TextureBoostedSaturatedGradient8(s10, s12, saturation, boost));
Store<align>((__m128i*)dy, TextureBoostedSaturatedGradient8(s01, s21, saturation, boost));
}
template<bool align> void TextureBoostedSaturatedGradient(const uint8_t * src, size_t srcStride, size_t width, size_t height,
uint8_t saturation, uint8_t boost, uint8_t * dx, size_t dxStride, uint8_t * dy, size_t dyStride)
{
assert(width >= A && int(2)*saturation*boost <= 0xFF);
if(align)
{
assert(Aligned(src) && Aligned(srcStride) && Aligned(dx) && Aligned(dxStride) && Aligned(dy) && Aligned(dyStride));
}
size_t alignedWidth = AlignLo(width, A);
__m128i _saturation = _mm_set1_epi16(saturation);
__m128i _boost = _mm_set1_epi16(boost);
memset(dx, 0, width);
memset(dy, 0, width);
src += srcStride;
dx += dxStride;
dy += dyStride;
for (size_t row = 2; row < height; ++row)
{
for (size_t col = 0; col < alignedWidth; col += A)
TextureBoostedSaturatedGradient<align>(src + col, dx + col, dy + col, srcStride, _saturation, _boost);
if(width != alignedWidth)
TextureBoostedSaturatedGradient<false>(src + width - A, dx + width - A, dy + width - A, srcStride, _saturation, _boost);
dx[0] = 0;
dy[0] = 0;
dx[width - 1] = 0;
dy[width - 1] = 0;
src += srcStride;
dx += dxStride;
dy += dyStride;
}
memset(dx, 0, width);
memset(dy, 0, width);
}
void TextureBoostedSaturatedGradient(const uint8_t * src, size_t srcStride, size_t width, size_t height,
uint8_t saturation, uint8_t boost, uint8_t * dx, size_t dxStride, uint8_t * dy, size_t dyStride)
{
if(Aligned(src) && Aligned(srcStride) && Aligned(dx) && Aligned(dxStride) && Aligned(dy) && Aligned(dyStride))
TextureBoostedSaturatedGradient<true>(src, srcStride, width, height, saturation, boost, dx, dxStride, dy, dyStride);
else
TextureBoostedSaturatedGradient<false>(src, srcStride, width, height, saturation, boost, dx, dxStride, dy, dyStride);
}
template<bool align> SIMD_INLINE void TextureBoostedUv(const uint8_t * src, uint8_t * dst, __m128i min8, __m128i max8, __m128i boost16)
{
const __m128i _src = Load<align>((__m128i*)src);
const __m128i saturated = _mm_sub_epi8(_mm_max_epu8(min8, _mm_min_epu8(max8, _src)), min8);
const __m128i lo = _mm_mullo_epi16(_mm_unpacklo_epi8(saturated, K_ZERO), boost16);
const __m128i hi = _mm_mullo_epi16(_mm_unpackhi_epi8(saturated, K_ZERO), boost16);
Store<align>((__m128i*)dst, _mm_packus_epi16(lo, hi));
}
template<bool align> void TextureBoostedUv(const uint8_t * src, size_t srcStride, size_t width, size_t height,
uint8_t boost, uint8_t * dst, size_t dstStride)
{
assert(width >= A && boost < 0x80);
if(align)
{
assert(Aligned(src) && Aligned(srcStride) && Aligned(dst) && Aligned(dstStride));
}
size_t alignedWidth = AlignLo(width, A);
int min = 128 - (128/boost);
int max = 255 - min;
__m128i min8 = _mm_set1_epi8(min);
__m128i max8 = _mm_set1_epi8(max);
__m128i boost16 = _mm_set1_epi16(boost);
for (size_t row = 0; row < height; ++row)
{
for (size_t col = 0; col < alignedWidth; col += A)
TextureBoostedUv<align>(src + col, dst + col, min8, max8, boost16);
if(width != alignedWidth)
TextureBoostedUv<false>(src + width - A, dst + width - A, min8, max8, boost16);
src += srcStride;
dst += dstStride;
}
}
void TextureBoostedUv(const uint8_t * src, size_t srcStride, size_t width, size_t height,
uint8_t boost, uint8_t * dst, size_t dstStride)
{
if(Aligned(src) && Aligned(srcStride) && Aligned(dst) && Aligned(dstStride))
TextureBoostedUv<true>(src, srcStride, width, height, boost, dst, dstStride);
else
TextureBoostedUv<false>(src, srcStride, width, height, boost, dst, dstStride);
}
template <bool align> SIMD_INLINE void TextureGetDifferenceSum(const uint8_t * src, const uint8_t * lo, const uint8_t * hi,
__m128i & positive, __m128i & negative, const __m128i & mask)
{
const __m128i _src = Load<align>((__m128i*)src);
const __m128i _lo = Load<align>((__m128i*)lo);
const __m128i _hi = Load<align>((__m128i*)hi);
const __m128i average = _mm_and_si128(mask, _mm_avg_epu8(_lo, _hi));
const __m128i current = _mm_and_si128(mask, _src);
positive = _mm_add_epi64(positive, _mm_sad_epu8(_mm_subs_epu8(current, average), K_ZERO));
negative = _mm_add_epi64(negative, _mm_sad_epu8(_mm_subs_epu8(average, current), K_ZERO));
}
template <bool align> void TextureGetDifferenceSum(const uint8_t * src, size_t srcStride, size_t width, size_t height,
const uint8_t * lo, size_t loStride, const uint8_t * hi, size_t hiStride, int64_t * sum)
{
assert(width >= A && sum != NULL);
if(align)
{
assert(Aligned(src) && Aligned(srcStride) && Aligned(lo) && Aligned(loStride) && Aligned(hi) && Aligned(hiStride));
}
size_t alignedWidth = AlignLo(width, A);
__m128i tailMask = ShiftLeft(K_INV_ZERO, A - width + alignedWidth);
__m128i positive = _mm_setzero_si128();
__m128i negative = _mm_setzero_si128();
for (size_t row = 0; row < height; ++row)
{
for (size_t col = 0; col < alignedWidth; col += A)
TextureGetDifferenceSum<align>(src + col, lo + col, hi + col, positive, negative, K_INV_ZERO);
if(width != alignedWidth)
TextureGetDifferenceSum<false>(src + width - A, lo + width - A, hi + width - A, positive, negative, tailMask);
src += srcStride;
lo += loStride;
hi += hiStride;
}
*sum = ExtractInt64Sum(positive) - ExtractInt64Sum(negative);
}
void TextureGetDifferenceSum(const uint8_t * src, size_t srcStride, size_t width, size_t height,
const uint8_t * lo, size_t loStride, const uint8_t * hi, size_t hiStride, int64_t * sum)
{
if(Aligned(src) && Aligned(srcStride) && Aligned(lo) && Aligned(loStride) && Aligned(hi) && Aligned(hiStride))
TextureGetDifferenceSum<true>(src, srcStride, width, height, lo, loStride, hi, hiStride, sum);
else
TextureGetDifferenceSum<false>(src, srcStride, width, height, lo, loStride, hi, hiStride, sum);
}
template <bool align> void TexturePerformCompensation(const uint8_t * src, size_t srcStride, size_t width, size_t height,
int shift, uint8_t * dst, size_t dstStride)
{
assert(width >= A && shift > -0xFF && shift < 0xFF && shift != 0);
if(align)
{
assert(Aligned(src) && Aligned(srcStride) && Aligned(dst) && Aligned(dstStride));
}
size_t alignedWidth = AlignLo(width, A);
__m128i tailMask = src == dst ? ShiftLeft(K_INV_ZERO, A - width + alignedWidth) : K_INV_ZERO;
if(shift > 0)
{
__m128i _shift = _mm_set1_epi8((char)shift);
for (size_t row = 0; row < height; ++row)
{
for (size_t col = 0; col < alignedWidth; col += A)
{
const __m128i _src = Load<align>((__m128i*) (src + col));
Store<align>((__m128i*) (dst + col), _mm_adds_epu8(_src, _shift));
}
if(width != alignedWidth)
{
const __m128i _src = Load<false>((__m128i*) (src + width - A));
Store<false>((__m128i*) (dst + width - A), _mm_adds_epu8(_src, _mm_and_si128(_shift, tailMask)));
}
src += srcStride;
dst += dstStride;
}
}
if(shift < 0)
{
__m128i _shift = _mm_set1_epi8((char)-shift);
for (size_t row = 0; row < height; ++row)
{
for (size_t col = 0; col < alignedWidth; col += A)
{
const __m128i _src = Load<align>((__m128i*) (src + col));
Store<align>((__m128i*) (dst + col), _mm_subs_epu8(_src, _shift));
}
if(width != alignedWidth)
{
const __m128i _src = Load<false>((__m128i*) (src + width - A));
Store<false>((__m128i*) (dst + width - A), _mm_subs_epu8(_src, _mm_and_si128(_shift, tailMask)));
}
src += srcStride;
dst += dstStride;
}
}
}
void TexturePerformCompensation(const uint8_t * src, size_t srcStride, size_t width, size_t height,
int shift, uint8_t * dst, size_t dstStride)
{
if(shift == 0)
{
if(src != dst)
Base::Copy(src, srcStride, width, height, 1, dst, dstStride);
return;
}
if(Aligned(src) && Aligned(srcStride) && Aligned(dst) && Aligned(dstStride))
TexturePerformCompensation<true>(src, srcStride, width, height, shift, dst, dstStride);
else
TexturePerformCompensation<false>(src, srcStride, width, height, shift, dst, dstStride);
}
}
#endif// SIMD_SSE2_ENABLE
}
| 48.605263 | 144 | 0.576997 | aestesis |
5a29a9fb9ebfe976013020cee8c0125af6ab4f40 | 283 | cpp | C++ | Source/Platoon/PlatoonCharacter.cpp | bernhardrieder/Platoon-AI-Simulation-UE4 | f5a3062cea090ddaae35fc97209212c8f8b4bdd9 | [
"Unlicense"
] | 1 | 2018-09-04T19:48:09.000Z | 2018-09-04T19:48:09.000Z | Source/Platoon/PlatoonCharacter.cpp | bernhardrieder/Platoon-AI-Simulation | f5a3062cea090ddaae35fc97209212c8f8b4bdd9 | [
"Unlicense"
] | null | null | null | Source/Platoon/PlatoonCharacter.cpp | bernhardrieder/Platoon-AI-Simulation | f5a3062cea090ddaae35fc97209212c8f8b4bdd9 | [
"Unlicense"
] | null | null | null | // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "Platoon.h"
#include "PlatoonCharacter.h"
APlatoonCharacter::APlatoonCharacter()
{
PrimaryActorTick.bCanEverTick = false;
PrimaryActorTick.bStartWithTickEnabled = false;
AActor::SetActorHiddenInGame(true);
} | 23.583333 | 60 | 0.791519 | bernhardrieder |
5a2ae39e781bb0be9e81f6fa5e4c9652c2588bd7 | 721 | cpp | C++ | code archive/GJ/a024.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | 4 | 2018-04-08T08:07:58.000Z | 2021-06-07T14:55:24.000Z | code archive/GJ/a024.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | null | null | null | code archive/GJ/a024.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | 1 | 2018-10-29T12:37:25.000Z | 2018-10-29T12:37:25.000Z | /**********************************************************************************/
/* Problem: a024 "所有位數和" from while 迴圈 */
/* Language: C++ */
/* Result: AC (4ms, 184KB) on ZeroJudge */
/* Author: briansu at 2016-08-25 22:23:33 */
/**********************************************************************************/
#include <iostream>
#include <math.h>
#include <string.h>
using namespace std;
int main()
{
long int n;
cin>>n;
long int m=0;
while(n>0)
{
m+=n%10;
n=floor(n/10);
}
cout<<m;
} | 27.730769 | 84 | 0.281553 | brianbbsu |
5a32da1f1584d661f8cb825a427c9278b45bb704 | 222 | cpp | C++ | AudioElement.cpp | OneNot/SFML-PacGuy | d9eb17632e43335282c514027bb93879357bfa74 | [
"Unlicense"
] | null | null | null | AudioElement.cpp | OneNot/SFML-PacGuy | d9eb17632e43335282c514027bb93879357bfa74 | [
"Unlicense"
] | null | null | null | AudioElement.cpp | OneNot/SFML-PacGuy | d9eb17632e43335282c514027bb93879357bfa74 | [
"Unlicense"
] | null | null | null | #include "AudioElement.h"
AudioElement::AudioElement(std::string file)
{
if (!buffer.loadFromFile(file))
{
std::cout << "FAILED TO LOAD: " << file << std::endl;
//todo: error handling
}
sound.setBuffer(buffer);
}
| 18.5 | 55 | 0.666667 | OneNot |
5a35d44b96820ecf83dd807b0a7b21df31f3efca | 2,027 | cc | C++ | Codeforces/339 Division 1/Problem B/B.cc | VastoLorde95/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 170 | 2017-07-25T14:47:29.000Z | 2022-01-26T19:16:31.000Z | Codeforces/339 Division 1/Problem B/B.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | null | null | null | Codeforces/339 Division 1/Problem B/B.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 55 | 2017-07-28T06:17:33.000Z | 2021-10-31T03:06:22.000Z | #include <bits/stdc++.h>
#define sd(x) scanf("%d",&x)
#define sd2(x,y) scanf("%d%d",&x,&y)
#define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define fi first
#define se second
#define pb(x) push_back(x)
#define mp(x,y) make_pair(x,y)
#define LET(x, a) __typeof(a) x(a)
#define foreach(it, v) for(LET(it, v.begin()); it != v.end(); it++)
#define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout);
#define func __FUNCTION__
#define line __LINE__
using namespace std;
typedef long long ll;
template<typename S, typename T>
ostream& operator<<(ostream& out, pair<S, T> const& p){out<<'('<<p.fi<<", "<<p.se<<')'; return out;}
template<typename T>
ostream& operator<<(ostream& out, vector<T> const & v){
ll l = v.size(); for(ll i = 0; i < l-1; i++) out<<v[i]<<' '; if(l>0) out<<v[l-1]; return out;}
void tr(){cout << endl;}
template<typename S, typename ... Strings>
void tr(S x, const Strings&... rest){cout<<x<<' ';tr(rest...);}
const ll N = 100100;
ll n, A, cf, cm, m;
vector<pair<ll, ll> > u, v;
ll ans[N], sum[N];
int main(){ _
cin >> n >> A >> cf >> cm >> m;
for(int i = 0; i < n; i++){
ll x; cin >> x;
u.pb(mp(x,i));
}
sort(u.begin(), u.end());
for(int i = 0; i < n; i++){
sum[i+1] = sum[i] + u[i].fi;
}
v = u;
ll force = -1, ansi = -1, ansm = -1;
for(int i = 0, j = 0; i <= n; i++){
ll cost = 0, tmp = 0;
cost = A*(n-i) - (sum[n] - sum[i]);
if(cost > m) continue;
tmp += (n-i)*cf;
ll rem = m - cost;
while(j < i and j*v[j].fi - sum[j] <= rem){
j++;
}
ll mn;
if(j > 0){
mn = min(A, (rem + sum[j])/j);
}
else{
mn = A;
}
tmp += mn*cm;
if(tmp > force){
force = tmp;
ansi = i;
ansm = mn;
}
}
cout << force << endl;
for(int i = 0; i < n; i++){
if(i < ansi){
v[i].fi = max(v[i].fi, ansm);
}
else v[i].fi = A;
ans[v[i].se] = v[i].fi;
}
for(int i = 0; i < n; i++){
cout << ans[i] << ' ';
}
cout << endl;
return 0;
}
| 19.304762 | 100 | 0.519487 | VastoLorde95 |
5a36e0bd1c379ad2d5982af7133e70f963b417cd | 11,042 | cpp | C++ | Milestone 4/Milestone 4/Milestone 4/Main.cpp | Shantanu-Chauhan/RigidBody | 638e7fc248cccdfca21a12c6c80b2d9b7b23e7e1 | [
"Apache-2.0"
] | 1 | 2020-09-26T11:59:55.000Z | 2020-09-26T11:59:55.000Z | Milestone 4/Milestone 4/Milestone 4/Main.cpp | Shantanu-Chauhan/RigidBody | 638e7fc248cccdfca21a12c6c80b2d9b7b23e7e1 | [
"Apache-2.0"
] | null | null | null | Milestone 4/Milestone 4/Milestone 4/Main.cpp | Shantanu-Chauhan/RigidBody | 638e7fc248cccdfca21a12c6c80b2d9b7b23e7e1 | [
"Apache-2.0"
] | null | null | null | /* Start Header -------------------------------------------------------
Copyright (C) 2018 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the prior
written consent of DigiPen Institute of Technology is prohibited.
File Name: Main.cpp
Purpose: Implementing Game Engine Architecture
Language: C++ language
Platform: Visual Studio Community 2017 - Visual C++ 15.8.2, Windows 10
Project: CS529_shantanu.chauhan_milestone1
Author: Shantanu Chauhan, shantanu.chauhan, 60002518
Creation date: 18th September 2018
- End Header --------------------------------------------------------*/
#include<GL/glew.h>
#include <SDL.h>
#include<SDL_opengl.h>
#include "stdio.h"
#include"src/Manager/Input Manager.h"
#include"src/Frame Rate Controller.h"
#include"Windows.h"
#include<iostream>
#include"src/Global_Header.h"
#include"src/Manager/Resource Manager.h"
#include"src/Manager/Game Object Manager.h"
#include"src/Manager/Event Manager.h"
#include"src/Game Object.h"
#include"Components/Sprite.h"
#include"Components/Transform.h"
#include"Components/Controller.h"
#include"Components/Component.h"
#include"src/ObjectFactory.h"
#include"Components/Body.h"
#include"src/Manager/PhysicsManager.h"
#include"src/Manager/CollisionManager.h"
#include"src/OpenGL/VertexBuffer.h"
#include"src/OpenGL/IndexBuffer.h"
#include"src/OpenGL/VertexArray.h"
#include"src/OpenGL/VertexBufferLayout.h"
#include"src/OpenGL/Texture.h"
#include"src/OpenGL/Shader.h"
#include"src/OpenGL/Renderer.h"
#include"glm/glm.hpp"
#include"glm/gtc/matrix_transform.hpp"
#include"imgui/imgui.h"
#include "imgui/imconfig.h"
#include"imgui/imgui_impl_sdl.h"
#include "imgui/imgui_impl_opengl3.h"
#include"src/Camera.h"
bool appIsRunning = true;
FrameRateController *gpFRC = nullptr;
Input_Manager *gpInputManager=nullptr;
ObjectFactory *gpGameObjectFactory = nullptr;
ResourceManager *gpResourceManager = nullptr;
GameObjectManager *gpGameObjectManager = nullptr;
PhysicsManager *gpPhysicsManager = nullptr;
CollisionManager *gpCollisionManager = nullptr;
EventManager *gpEventManager = nullptr;
Renderer *gpRenderer=nullptr;
Shader* shader=nullptr;
Camera *gpCamera = nullptr;
FILE _iob[] = { *stdin, *stdout, *stderr };
#define MAX_FRAME_RATE 60
extern "C" FILE * __cdecl __iob_func(void)
{
return _iob;
}
#pragma comment(lib, "legacy_stdio_definitions.lib")
int main(int argc, char* args[])
{
if (AllocConsole())
{
FILE* file;
freopen_s(&file, "CONOUT$", "wt", stdout);
freopen_s(&file, "CONOUT$", "wt", stderr);
freopen_s(&file, "CONOUT$", "wt", stdin);
SetConsoleTitle("CS550(MADE IT SOMEHOW!YES!) :-)");
}
SDL_Window *pWindow;
SDL_Surface *pWindowSurface;
int error = 0;
SDL_Surface *pImage = NULL;
// Initialize SDL
gpFRC = new FrameRateController(MAX_FRAME_RATE);//Paraeter is the FPS
gpInputManager =new Input_Manager();
gpGameObjectFactory = new ObjectFactory();
gpResourceManager = new ResourceManager();
gpGameObjectManager = new GameObjectManager();
gpCollisionManager = new CollisionManager();
gpEventManager = new EventManager();
gpRenderer = new Renderer();
gpCamera = new Camera(5, 10, 20, 0, 1, 0, -90, -15);
if((error = SDL_Init( SDL_INIT_VIDEO )) < 0 )
{
printf("Couldn't initialize SDL, error %i\n", error);
return 1;
}
pWindow = SDL_CreateWindow("CS550(MADE IT SOMEHOW!!!!) :-)", // window title
10, // initial x position
25, // initial y position
SCREEN_WIDTH, // width, in pixels
SCREEN_HEIGHT, // height, in pixels
SDL_WINDOW_OPENGL);
// Check that the window was successfully made
if (NULL == pWindow)
{
// In the event that the window could not be made...
printf("Could not create window: %s\n", SDL_GetError());
return 1;
}
auto OpenGL_context = SDL_GL_CreateContext(pWindow);
if (glewInit() != GLEW_OK)
printf(" Error in glew init\n");
pWindowSurface = SDL_GetWindowSurface(pWindow);
if (!pWindowSurface)
{
printf(SDL_GetError());
}
gpGameObjectFactory->LoadLevel("Title_Screenp.txt",false);
float positions[] = {
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,//* 0
0.5f, -0.5f, -0.5f, 1.0f, 0.0f,// 1
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,//** 2
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,//** 3
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,// 4
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,//* 5
//
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,//*** 6
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,// 7
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,// 8
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,// 9
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f,// 10
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,//*** 11
//
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,//
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f,//
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,//
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,//
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,//
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,//
//
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,//
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,//
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,//
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,//
0.5f, -0.5f, 0.5f, 0.0f, 0.0f,//
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,//
//
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,//
0.5f, -0.5f, -0.5f, 1.0f, 1.0f,//
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,//
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,//
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,//
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,//
//
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,//
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,//
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,//
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,//
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f,//
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f //
};
//vid 9
unsigned int indices[] = {
0,1,2,
3,4,5,
6,7,8,
9,10,11,
12,13,14,
15,16,17,
18,19,20,
21,22,23,
24,25,26,
27,28,29,
30,31,32,
33,34,35,
};
//IMGUI
ImGui::CreateContext();
ImGui_ImplSDL2_InitForOpenGL(pWindow, OpenGL_context);
ImGui_ImplOpenGL3_Init("#version 330");
std::cout << glGetString(GL_RENDERER) << std::endl;
ImGui::StyleColorsDark();
//IMGUI
GLCall(glEnable(GL_BLEND));
glEnable(GL_DEPTH_TEST);
GLCall(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
{
VertexArray va;
VertexBuffer vb(positions, 36 * 5 * sizeof(float));
VertexBufferLayout layout;
layout.Push<float>(3);
layout.Push<float>(2);
va.AddBuffer(vb, layout);
IndexBuffer ib(indices, 36);
//------------------------------------------------------------------------------------
//Writing down the shader
shader = new Shader("src/res/shaders/Basic.shader");
shader->Bind();
//------------------------------------------------------------------------------------
gpPhysicsManager = new PhysicsManager();//Keep this after level loading so that bodies can be pushed into the broad phase
// Game loop
bool reverse = false;
bool pause = true;
float deltaTime = 0.016f;
bool debug = false;
bool step = false;
while (true == appIsRunning)
{
gpFRC->FrameStart();
gpInputManager->Update();
gpRenderer->Clear();
GLCall(glClearColor(0.5, 0.5, 0.5, 1.0));
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL2_NewFrame(pWindow);
ImGui::NewFrame();
if (gpInputManager->isTriggered(SDL_SCANCODE_SPACE))
pause = !pause;
if (gpInputManager->isTriggered(SDL_SCANCODE_R))//reverse time(this doesnt work)
{
pause = false;
reverse = !reverse;
}
if (gpInputManager->isTriggered(SDL_SCANCODE_O))//debug toggle
{
debug = !debug;
}
float frameTime = (float)gpFRC->GetFrameTime();
frameTime = frameTime / 1000.0f;
gpCamera->Update(gpInputManager,frameTime);
ImGui::Begin("MADE BY SHANTANU CHAUHAN!");
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::Text("To move the camera use the arrow keys");
ImGui::Text("To rotate the camera right click and move the mouse");
ImGui::Text("Press 'O'(not zero! but 'o') to draw the mesh of the dynamicAABB tree");
ImGui::Text("Press '1' to get the BALL AND SOCKET JOINT");
ImGui::Text("Press '2' to get the big stack of cubes");
ImGui::Text("Press '3' to get the single stack of 10 cubes");
ImGui::Text("Press '4' to get HINGE JOINT");
ImGui::Text("Press '5' to get the BRIDGE");
ImGui::Text("Press 'SPACE' to pause/resume the simulation");
ImGui::Text("Press 'Enter' to step the physics update");
ImGui::Text("Press 'Escape' to close the application");
ImGui::End();
if (gpInputManager->isTriggered(SDL_SCANCODE_RETURN))//step
{
step = true;
frameTime = deltaTime;
}
if (gpInputManager->isTriggered(SDL_SCANCODE_1))//Load the big level
{
gpGameObjectFactory->LoadLevel("Title_Screenp.txt", false);
}
if (gpInputManager->isTriggered(SDL_SCANCODE_2))//Load the big level
{
gpGameObjectFactory->LoadLevel("Title_Screenp.txt",true);
}
if (gpInputManager->isTriggered(SDL_SCANCODE_3))//Load the big level
{
gpGameObjectFactory->LoadLevel("Title_Screenp.txt", true);
}
if (gpInputManager->isTriggered(SDL_SCANCODE_4))//Load the big level
{
gpGameObjectFactory->LoadLevel("Title_Screenp.txt", true);
}
if (gpInputManager->isTriggered(SDL_SCANCODE_5))//Load the big level
{
gpGameObjectFactory->LoadLevel("Title_Screenp.txt", true);
}
if (gpInputManager->isTriggered(SDL_SCANCODE_6))//Load the big level
{
gpGameObjectFactory->LoadLevel("Title_Screenp.txt", true);
}
gpEventManager->Update(frameTime);
for (int i = 0; i < static_cast<int>(gpGameObjectManager->mGameobjects.size()); ++i)
{
gpGameObjectManager->mGameobjects[i]->Update();
}
if (step)
{
pause = false;
}
if(!pause)
gpPhysicsManager->Update(1/60.0f);//Physics update
if (step)
{
pause = true;
step = false;
}
//Dubug
for (auto go : gpGameObjectManager->mGameobjects)
{
Body *pBody = static_cast<Body*>(go->GetComponent(BODY));
//ImGui::SetNextWindowPosCenter(ImGuiCond_Once);
ImGui::Begin("Cubes data(You can move them but identifying which is which is hard)");
ImGui::PushID(pBody);
ImGui::SliderFloat3("Location:", &pBody->mPos.x, -5.0f, 5.0f);
ImGui::SliderFloat4("Quat:", &pBody->quaternion.x, -1.0f, 1.0f);
ImGui::SliderFloat4("Vel:", &pBody->mVel.x, -10.0f, 10.0f);
ImGui::SliderFloat4("angular", &pBody->AngularVelocity.x, -2.0f, 2.0f);
//ImGui::Text("Angular - x-%f,y-%f,z-%f", pBody->AngularVelocity.x, pBody->AngularVelocity.y, pBody->AngularVelocity.z);
ImGui::PopID();
ImGui::End();
}
//Draw All the game objects
gpGameObjectManager->DrawObjectDraw(va, ib, shader, debug);
//Debug
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
SDL_GL_SwapWindow(pWindow);
gpFRC->FrameEnd();
}
}
delete gpFRC;
delete shader;
delete gpRenderer;
delete gpEventManager;
delete gpCollisionManager;
delete gpPhysicsManager;
delete gpGameObjectManager;
delete gpResourceManager;
delete gpGameObjectFactory;
delete gpInputManager;
SDL_DestroyWindow(pWindow);
SDL_Quit();
return 0;
} | 29.134565 | 125 | 0.642003 | Shantanu-Chauhan |
5a3a649a9888e3e73c4dd200603fd798b553f153 | 711 | hpp | C++ | include/mh/network/server.hpp | overworks/MhGameLib | 87973e29633ed09a3fa51eb27ea7fc8af5e9d71b | [
"MIT"
] | null | null | null | include/mh/network/server.hpp | overworks/MhGameLib | 87973e29633ed09a3fa51eb27ea7fc8af5e9d71b | [
"MIT"
] | null | null | null | include/mh/network/server.hpp | overworks/MhGameLib | 87973e29633ed09a3fa51eb27ea7fc8af5e9d71b | [
"MIT"
] | null | null | null | #ifndef _MH_NETWORK_SERVER_HPP_
#define _MH_NETWORK_SERVER_HPP_
/*
* 서버 인터페이스
*/
#include <mh/types.hpp>
#define SERVER_INTERFACE(name)\
name();\
virtual ~name();\
virtual bool initialize( u32 address, u16 port );\
namespace Mh
{
namespace Network
{
class Socket;
// 전송 프로토콜
enum TP // Transfort protocol
{
TP_TCP, // 일단은 이 두개만...
TP_UDP,
};
struct ServerDesc
{
u32 addrees; // 서버 주소
u16 port; // 포트
TP protocol; // 전송 프로토콜(TCP, UDP)
};
class Server
{
public:
Server() {}
virtual ~Server() {}
virtual bool initialize( u32 address, u16 port ) = 0;
};
} // namespace Mh::Network
} // namespace Mh
#endif /* _MH_NETWORK_SERVER_HPP_ */ | 14.8125 | 56 | 0.618847 | overworks |
5a3dba1ad0707e8f2523f50885675d3e4a54b7bb | 1,088 | cpp | C++ | Tutorials/Week 3/Solutions/Office.cpp | JamesMarino/CSCI204 | 17b2c44252d1be40214831c6e7e0c2b71848f500 | [
"MIT"
] | null | null | null | Tutorials/Week 3/Solutions/Office.cpp | JamesMarino/CSCI204 | 17b2c44252d1be40214831c6e7e0c2b71848f500 | [
"MIT"
] | null | null | null | Tutorials/Week 3/Solutions/Office.cpp | JamesMarino/CSCI204 | 17b2c44252d1be40214831c6e7e0c2b71848f500 | [
"MIT"
] | null | null | null | // Office.cpp
// Static field holds rent due date for an office - rents are due on the 1st
#include <iostream>
#include <string>
using namespace std;
class Office
{
private:
int officeNum;
string tenant;
int rent;
static int rentDueDate;
public:
void setOfficeData(int, string, int);
static void showRentDueDate();
void showOffice();
};
int Office::rentDueDate = 1;
void Office::setOfficeData (int num, string occupant, int rent)
{
this->officeNum = num;
this->tenant = occupant;
this->rent = rent;
}
void Office::showOffice ()
{
cout << "Office " << this->officeNum << " is occupied by " << this->tenant << "." << endl;
cout << "The rent, $" << this->rent << " is due on day " << rentDueDate << " of the month." << endl;
cout << "ALL rents are due on the day " << rentDueDate << " of the month." << endl;
}
void Office::showRentDueDate ()
{
cout << "All rents are due on day " << rentDueDate << " of the month." << endl;
}
int main()
{
Office myOffice;
myOffice.setOfficeData(234, "Dr. Smith", 450);
Office::showRentDueDate();
myOffice.showOffice();
}
| 21.76 | 101 | 0.654412 | JamesMarino |
5a467f39695c9b5c2b5e7d6e8cf80f1335bd1599 | 3,212 | hpp | C++ | include/opengl/draw_info.hpp | bjadamson/BoomHS | 60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4 | [
"MIT"
] | 2 | 2016-07-22T10:09:21.000Z | 2017-09-16T06:50:01.000Z | include/opengl/draw_info.hpp | bjadamson/BoomHS | 60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4 | [
"MIT"
] | 14 | 2016-08-13T22:45:56.000Z | 2018-12-16T03:56:36.000Z | include/opengl/draw_info.hpp | bjadamson/BoomHS | 60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4 | [
"MIT"
] | null | null | null | #pragma once
#include <opengl/bind.hpp>
#include <opengl/global.hpp>
#include <opengl/vao.hpp>
#include <opengl/vertex_attribute.hpp>
#include <boomhs/entity.hpp>
#include <common/log.hpp>
#include <common/type_macros.hpp>
#include <optional>
#include <string>
namespace boomhs
{
class ObjStore;
} // namespace boomhs
namespace opengl
{
class ShaderPrograms;
class BufferHandles
{
GLuint vbo_ = 0, ebo_ = 0;
static auto constexpr NUM_BUFFERS = 1;
explicit BufferHandles();
NO_COPY(BufferHandles);
public:
friend class DrawInfo;
~BufferHandles();
// move-construction OK.
BufferHandles(BufferHandles&&);
BufferHandles& operator=(BufferHandles&&);
auto vbo() const { return vbo_; }
auto ebo() const { return ebo_; }
std::string to_string() const;
};
std::ostream&
operator<<(std::ostream&, BufferHandles const&);
class DrawInfo
{
size_t num_vertexes_;
GLuint num_indices_;
BufferHandles handles_;
VAO vao_;
public:
DebugBoundCheck debug_check;
NO_COPY(DrawInfo);
explicit DrawInfo(size_t, GLuint);
DrawInfo(DrawInfo&&);
DrawInfo& operator=(DrawInfo&&);
void bind_impl(common::Logger&);
void unbind_impl(common::Logger&);
DEFAULT_WHILEBOUND_MEMBERFN_DECLATION();
auto vbo() const { return handles_.vbo(); }
auto ebo() const { return handles_.ebo(); }
auto num_vertexes() const { return num_vertexes_; }
auto num_indices() const { return num_indices_; }
auto& vao() { return vao_; }
auto const& vao() const { return vao_; }
std::string to_string() const;
};
struct DrawInfoHandle
{
using value_type = size_t;
value_type value;
explicit DrawInfoHandle(value_type const v)
: value(v)
{
}
};
class DrawHandleManager;
class EntityDrawHandleMap
{
std::vector<opengl::DrawInfo> drawinfos_;
std::vector<boomhs::EntityID> entities_;
friend class DrawHandleManager;
EntityDrawHandleMap() = default;
NO_COPY(EntityDrawHandleMap);
MOVE_DEFAULT(EntityDrawHandleMap);
DrawInfoHandle add(boomhs::EntityID, opengl::DrawInfo&&);
bool empty() const { return drawinfos_.empty(); }
bool has(DrawInfoHandle) const;
auto size() const
{
assert(drawinfos_.size() == entities_.size());
return drawinfos_.size();
}
DrawInfo const& get(DrawInfoHandle) const;
DrawInfo& get(DrawInfoHandle);
std::optional<DrawInfoHandle> find(boomhs::EntityID) const;
};
class DrawHandleManager
{
// These slots get a value when memory is loaded, set to none when memory is not.
EntityDrawHandleMap entities_;
EntityDrawHandleMap& entities();
EntityDrawHandleMap const& entities() const;
public:
DrawHandleManager() = default;
NO_COPY(DrawHandleManager);
MOVE_DEFAULT(DrawHandleManager);
// methods
DrawInfoHandle add_entity(boomhs::EntityID, DrawInfo&&);
DrawInfo& lookup_entity(common::Logger&, boomhs::EntityID);
DrawInfo const& lookup_entity(common::Logger&, boomhs::EntityID) const;
void add_mesh(common::Logger&, ShaderPrograms&, boomhs::ObjStore&, boomhs::EntityID,
boomhs::EntityRegistry&);
void add_cube(common::Logger&, ShaderPrograms&, boomhs::EntityID, boomhs::EntityRegistry&);
};
} // namespace opengl
| 22 | 93 | 0.711706 | bjadamson |
53fe5e6aeb1f1c44f8f4face1da69d196f13f417 | 13,467 | cpp | C++ | operators_c.cpp | ntan15/scratch_wadge | 0657069749b9507062c1f7e875c6545076fb85c8 | [
"Unlicense"
] | null | null | null | operators_c.cpp | ntan15/scratch_wadge | 0657069749b9507062c1f7e875c6545076fb85c8 | [
"Unlicense"
] | null | null | null | operators_c.cpp | ntan15/scratch_wadge | 0657069749b9507062c1f7e875c6545076fb85c8 | [
"Unlicense"
] | null | null | null | #include "operators_c.h"
#include "operators.h"
#include <Eigen/Dense>
#include <iostream>
using namespace std;
static dfloat_t *to_c(VectorXd &v)
{
dfloat_t *vdata = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * v.size());
#if USE_DFLOAT_DOUBLE == 1
Eigen::Map<Eigen::VectorXd>(vdata, v.size()) = v.cast<dfloat_t>();
#else
Eigen::Map<Eigen::VectorXf>(vdata, v.size()) = v.cast<dfloat_t>();
#endif
return vdata;
}
static dfloat_t *to_c(MatrixXd &m)
{
dfloat_t *mdata = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * m.size());
#if USE_DFLOAT_DOUBLE == 1
Eigen::Map<Eigen::MatrixXd>(mdata, m.rows(), m.cols()) = m.cast<dfloat_t>();
#else
Eigen::Map<Eigen::MatrixXf>(mdata, m.rows(), m.cols()) = m.cast<dfloat_t>();
#endif
return mdata;
}
static uintloc_t *to_c(MatrixXu32 &m)
{
uintloc_t *mdata =
(uintloc_t *)asd_malloc_aligned(sizeof(uintloc_t) * m.size());
Eigen::Map<Eigen::Matrix<uintloc_t, Eigen::Dynamic, Eigen::Dynamic>>(
mdata, m.rows(), m.cols()) = m.cast<uintloc_t>();
return mdata;
}
host_operators_t *host_operators_new_2D(int N, int M, uintloc_t E,
uintloc_t *EToE, uint8_t *EToF,
uint8_t *EToO, double *EToVX)
{
host_operators_t *ops =
(host_operators_t *)asd_malloc(sizeof(host_operators_t));
ref_elem_data *ref_data = build_ref_ops_2D(N, M, M);
VectorXd wq = ref_data->wq;
// nodal
MatrixXd Dr = ref_data->Dr;
MatrixXd Ds = ref_data->Ds;
MatrixXd Vq = ref_data->Vq;
VectorXd wfq = ref_data->wfq;
VectorXd nrJ = ref_data->nrJ;
VectorXd nsJ = ref_data->nsJ;
MatrixXd Vfqf = ref_data->Vfqf;
MatrixXd Vfq = ref_data->Vfq;
MatrixXd Pq = ref_data->Pq;
MatrixXd MM = Vq.transpose() * wq.asDiagonal() * Vq;
MatrixXd MMfq = Vfq.transpose() * wfq.asDiagonal();
MatrixXd Lq = mldivide(MM, MMfq);
MatrixXd VqLq = Vq * Lq;
MatrixXd VqPq = Vq * Pq;
MatrixXd VfPq = Vfq * Pq;
MatrixXd Drq = Vq * Dr * Pq - .5 * Vq * Lq * nrJ.asDiagonal() * Vfq * Pq;
MatrixXd Dsq = Vq * Ds * Pq - .5 * Vq * Lq * nsJ.asDiagonal() * Vfq * Pq;
ops->dim = 2;
ops->N = N;
ops->M = M;
ops->Np = (int)ref_data->r.size();
ops->Nq = (int)ref_data->rq.size();
// printf("Num cubature points Nq = %d\n",ops->Nq);
ops->Nfp = N + 1;
ops->Nfq = (int)ref_data->ref_rfq.size();
ops->Nfaces = ref_data->Nfaces;
ops->Nvgeo = 4;
ops->Nfgeo = 3;
ops->wq = to_c(wq);
ops->nrJ = to_c(nrJ);
ops->nsJ = to_c(nsJ);
ops->Drq = to_c(Drq);
ops->Dsq = to_c(Dsq);
ops->Vq = to_c(Vq);
ops->Pq = to_c(Pq);
ops->VqLq = to_c(VqLq);
ops->VqPq = to_c(VqPq);
ops->VfPq = to_c(VfPq);
ops->Vfqf = to_c(Vfqf);
Map<MatrixXd> EToVXmat(EToVX, 2 * 3, E);
if (sizeof(uintloc_t) != sizeof(uint32_t))
{
cerr << "Need to update build maps to support different integer types"
<< endl;
std::abort();
}
Map<MatrixXu32> mapEToE(EToE, 3, E);
Map<MatrixXu8> mapEToF(EToF, 3, E);
Map<MatrixXu8> mapEToO(EToO, 3, E);
geo_elem_data *geo_data = build_geofacs_2D(ref_data, EToVXmat);
map_elem_data *map_data = build_maps_2D(ref_data, mapEToE, mapEToF, mapEToO);
const int Nvgeo = ops->Nvgeo;
const int Nfgeo = ops->Nfgeo;
const int Nfaces = ref_data->Nfaces;
const int Nq = ops->Nq;
const int Nfq = ops->Nfq;
ops->xyzq =
(dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nq * 3 * E);
ops->xyzf = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nfq *
ops->Nfaces * 3 * E);
ops->vgeo =
(dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nq * Nvgeo * E);
ops->vfgeo = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nfq *
Nfaces * Nvgeo * E);
ops->fgeo = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nfq *
Nfgeo * Nfaces * E);
for (uintloc_t e = 0; e < E; ++e)
{
for (int n = 0; n < Nq; ++n)
{
ops->xyzq[n + 0 * Nq + e * Nq * 3] = (dfloat_t)geo_data->xq(n, e);
ops->xyzq[n + 1 * Nq + e * Nq * 3] = (dfloat_t)geo_data->yq(n, e);
// ops->xyzq[n + 2*Nq + e*Nq*3] = (dfloat_t)geo_data->zq(n,e);
ops->vgeo[e * Nq * Nvgeo + 0 * Nq + n] = (dfloat_t)geo_data->rxJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 1 * Nq + n] = (dfloat_t)geo_data->ryJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 2 * Nq + n] = (dfloat_t)geo_data->sxJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 3 * Nq + n] = (dfloat_t)geo_data->syJ(n, e);
}
}
for (uintloc_t e = 0; e < E; ++e)
{
for (int n = 0; n < Nfq * Nfaces; ++n)
{
ops->xyzf[n + 0 * Nfq * Nfaces + e * Nfq * Nfaces * 3] =
(dfloat_t)geo_data->xf(n, e);
ops->xyzf[n + 1 * Nfq * Nfaces + e * Nfq * Nfaces * 3] =
(dfloat_t)geo_data->yf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 0 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->rxJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 1 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->ryJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 2 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->sxJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 3 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->syJf(n, e);
ops->fgeo[e * Nfq * Nfaces * Nfgeo + 0 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->nxJ(n, e);
ops->fgeo[e * Nfq * Nfaces * Nfgeo + 1 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->nyJ(n, e);
ops->fgeo[e * Nfq * Nfaces * Nfgeo + 2 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->sJ(n, e);
}
}
ops->Jq = to_c(geo_data->J);
ops->mapPq = to_c(map_data->mapPq);
// ops->mapPqNoFields = to_c(map_data->mapPq); // save
/*
// JC: FIX LATER - only valid for tri2.msh
ops->mapPq[0] = 7;
ops->mapPq[1] = 6;
ops->mapPq[2] = 9;
ops->mapPq[3] = 8;
ops->mapPq[6] = 1;
ops->mapPq[7] = 0;
ops->mapPq[8] = 3;
ops->mapPq[9] = 2;
*/
// for(int i = 0; i < Nfq*Nfaces*E; ++i){
// printf("mapPq(%d) = %d\n",i,ops->mapPq[i]);
// }
ops->Fmask = to_c(map_data->fmask);
delete ref_data;
delete geo_data;
delete map_data;
return ops;
}
host_operators_t *host_operators_new_3D(int N, int M, uintloc_t E,
uintloc_t *EToE, uint8_t *EToF,
uint8_t *EToO, double *EToVX)
{
host_operators_t *ops =
(host_operators_t *)asd_malloc(sizeof(host_operators_t));
ref_elem_data *ref_data = build_ref_ops_3D(N, M, M);
VectorXd wq = ref_data->wq;
// nodal
MatrixXd Dr = ref_data->Dr;
MatrixXd Ds = ref_data->Ds;
MatrixXd Dt = ref_data->Dt;
MatrixXd Vq = ref_data->Vq;
MatrixXd Pq = ref_data->Pq;
MatrixXd Vfqf = ref_data->Vfqf;
MatrixXd Vfq = ref_data->Vfq;
VectorXd wfq = ref_data->wfq;
VectorXd nrJ = ref_data->nrJ;
VectorXd nsJ = ref_data->nsJ;
VectorXd ntJ = ref_data->ntJ;
MatrixXd MM = Vq.transpose() * wq.asDiagonal() * Vq;
MatrixXd MMfq = Vfq.transpose() * wfq.asDiagonal();
MatrixXd Lq = mldivide(MM, MMfq);
MatrixXd VqLq = Vq * Lq;
MatrixXd VqPq = Vq * Pq;
MatrixXd VfPq = Vfq * Pq;
MatrixXd Drq = Vq * Dr * Pq - .5 * Vq * Lq * nrJ.asDiagonal() * Vfq * Pq;
MatrixXd Dsq = Vq * Ds * Pq - .5 * Vq * Lq * nsJ.asDiagonal() * Vfq * Pq;
MatrixXd Dtq = Vq * Dt * Pq - .5 * Vq * Lq * ntJ.asDiagonal() * Vfq * Pq;
MatrixXd Drstq(Drq.rows(),3*Drq.cols());
Drstq << Drq,Dsq,Dtq;
/*
cout << "VqPq = " << endl << VqPq << endl;
cout << "VqLq = " << endl << VqLq << endl;
cout << "VfPq = " << endl << VfPq << endl;
cout << "Drq = " << endl << Drq << endl;
cout << "nrJ = " << endl << nrJ << endl;
cout << "Dsq = " << endl << Dsq << endl;
cout << "nsJ = " << endl << nsJ << endl;
cout << "Dtq = " << endl << Dtq << endl;
cout << "ntJ = " << endl << ntJ << endl;
*/
ops->dim = 3;
ops->N = N;
ops->M = M;
ops->Np = (int)ref_data->r.size();
ops->Nq = (int)ref_data->rq.size();
ops->Nfp = (N + 1) * (N + 2) / 2;
ops->Nfq = (int)ref_data->ref_rfq.size();
ops->Nfaces = ref_data->Nfaces;
ops->Nvgeo = 9;
ops->Nfgeo = 4;
ops->wq = to_c(wq);
ops->nrJ = to_c(nrJ);
ops->nsJ = to_c(nsJ);
ops->ntJ = to_c(ntJ);
ops->Drq = to_c(Drq);
ops->Dsq = to_c(Dsq);
ops->Dtq = to_c(Dtq);
ops->Drstq = to_c(Drstq);
ops->Vq = to_c(Vq);
ops->Pq = to_c(Pq);
ops->VqLq = to_c(VqLq);
ops->VqPq = to_c(VqPq);
ops->VfPq = to_c(VfPq);
ops->Vfqf = to_c(Vfqf);
Map<MatrixXd> EToVXmat(EToVX, 3 * 4, E);
if (sizeof(uintloc_t) != sizeof(uint32_t))
{
cerr << "Need to update build maps to support different integer types"
<< endl;
std::abort();
}
Map<MatrixXu32> mapEToE(EToE, 4, E);
Map<MatrixXu8> mapEToF(EToF, 4, E);
Map<MatrixXu8> mapEToO(EToO, 4, E);
geo_elem_data *geo_data = build_geofacs_3D(ref_data, EToVXmat);
map_elem_data *map_data = build_maps_3D(ref_data, mapEToE, mapEToF, mapEToO);
const int Nvgeo = ops->Nvgeo;
const int Nfgeo = ops->Nfgeo;
const int Nfaces = ref_data->Nfaces;
const int Nq = ops->Nq;
const int Nfq = ops->Nfq;
ops->xyzq =
(dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nq * 3 * E);
ops->xyzf = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nfq *
ops->Nfaces * 3 * E);
ops->vgeo =
(dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nq * Nvgeo * E);
ops->vfgeo = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nfq *
Nfaces * Nvgeo * E);
ops->fgeo = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nfq *
Nfgeo * Nfaces * E);
for (uintloc_t e = 0; e < E; ++e)
{
for (int n = 0; n < Nq; ++n)
{
ops->xyzq[n + 0 * Nq + e * Nq * 3] = (dfloat_t)geo_data->xq(n, e);
ops->xyzq[n + 1 * Nq + e * Nq * 3] = (dfloat_t)geo_data->yq(n, e);
ops->xyzq[n + 2 * Nq + e * Nq * 3] = (dfloat_t)geo_data->zq(n, e);
ops->vgeo[e * Nq * Nvgeo + 0 * Nq + n] = (dfloat_t)geo_data->rxJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 1 * Nq + n] = (dfloat_t)geo_data->ryJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 2 * Nq + n] = (dfloat_t)geo_data->rzJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 3 * Nq + n] = (dfloat_t)geo_data->sxJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 4 * Nq + n] = (dfloat_t)geo_data->syJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 5 * Nq + n] = (dfloat_t)geo_data->szJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 6 * Nq + n] = (dfloat_t)geo_data->txJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 7 * Nq + n] = (dfloat_t)geo_data->tyJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 8 * Nq + n] = (dfloat_t)geo_data->tzJ(n, e);
}
}
for (uintloc_t e = 0; e < E; ++e)
{
for (int n = 0; n < Nfq * Nfaces; ++n)
{
ops->xyzf[n + 0 * Nfq * Nfaces + e * Nfq * Nfaces * 3] =
(dfloat_t)geo_data->xf(n, e);
ops->xyzf[n + 1 * Nfq * Nfaces + e * Nfq * Nfaces * 3] =
(dfloat_t)geo_data->yf(n, e);
ops->xyzf[n + 2 * Nfq * Nfaces + e * Nfq * Nfaces * 3] =
(dfloat_t)geo_data->zf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 0 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->rxJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 1 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->ryJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 2 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->rzJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 3 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->sxJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 4 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->syJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 5 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->szJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 6 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->txJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 7 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->tyJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 8 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->tzJf(n, e);
ops->fgeo[e * Nfq * Nfaces * Nfgeo + 0 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->nxJ(n, e);
ops->fgeo[e * Nfq * Nfaces * Nfgeo + 1 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->nyJ(n, e);
ops->fgeo[e * Nfq * Nfaces * Nfgeo + 2 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->nzJ(n, e);
ops->fgeo[e * Nfq * Nfaces * Nfgeo + 3 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->sJ(n, e);
// if (e==99){
// printf("n = %d, nxJ = %f\n", n, (dfloat_t) geo_data->nxJ(n,e));
// }
}
}
ops->Jq = to_c(geo_data->J);
ops->mapPq = to_c(map_data->mapPq);
ops->Fmask = to_c(map_data->fmask);
delete ref_data;
delete geo_data;
delete map_data;
return ops;
}
void host_operators_free(host_operators_t *ops)
{
asd_free_aligned(ops->vgeo);
asd_free_aligned(ops->fgeo);
asd_free_aligned(ops->Jq);
asd_free_aligned(ops->mapPq);
asd_free_aligned(ops->Fmask);
asd_free_aligned(ops->nrJ);
asd_free_aligned(ops->nsJ);
asd_free_aligned(ops->Drq);
asd_free_aligned(ops->Dsq);
if (ops->dim == 3)
{
asd_free_aligned(ops->ntJ);
asd_free_aligned(ops->Dtq);
}
asd_free_aligned(ops->Vq);
asd_free_aligned(ops->Pq);
asd_free_aligned(ops->VqLq);
asd_free_aligned(ops->VqPq);
asd_free_aligned(ops->VfPq);
asd_free_aligned(ops->Vfqf);
}
| 31.538642 | 80 | 0.556843 | ntan15 |
99046f7f13fbffeefb6d06369b8ecde9df1dbf40 | 2,337 | cc | C++ | larq_compute_engine/mlir/transforms/fuse_padding.cc | godhj93/compute-engine | 1f812a6722e2ee6a510c883826fd5925f9c34b18 | [
"Apache-2.0"
] | null | null | null | larq_compute_engine/mlir/transforms/fuse_padding.cc | godhj93/compute-engine | 1f812a6722e2ee6a510c883826fd5925f9c34b18 | [
"Apache-2.0"
] | null | null | null | larq_compute_engine/mlir/transforms/fuse_padding.cc | godhj93/compute-engine | 1f812a6722e2ee6a510c883826fd5925f9c34b18 | [
"Apache-2.0"
] | null | null | null | #include "larq_compute_engine/mlir/transforms/padding.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include "tensorflow/compiler/mlir/lite/ir/tfl_ops.h"
namespace mlir {
namespace TFL {
namespace {
bool NoBatchAndChannelPadding(Attribute paddings_attr) {
auto paddings = GetValidPadAttr(paddings_attr);
if (!paddings) return false;
return IsNoPadding(paddings, 0) && IsNoPadding(paddings, 3);
}
// The TFLite op has `stride_height` and `stride_width` as separate attributes.
// Due to a TableGen limitation we can't pass them both in a single call.
bool IsSamePaddingPartial(Attribute paddings_attr, Value input, Value output,
Attribute strides_attr, uint64_t dimension) {
auto paddings = GetValidPadAttr(paddings_attr);
if (!paddings) return false;
auto input_shape = GetShape4D(input);
if (input_shape.empty()) return false;
auto output_shape = GetShape4D(output);
if (output_shape.empty()) return false;
if (!strides_attr.isa<IntegerAttr>()) return false;
const int stride = strides_attr.cast<IntegerAttr>().getInt();
// Check that there is no padding in the batch and channel dimensions
return IsSamePadding1D(paddings, dimension, input_shape[dimension],
output_shape[dimension], stride);
}
#include "larq_compute_engine/mlir/transforms/generated_fuse_padding.inc"
// Prepare LCE operations in functions for subsequent legalization.
struct FusePadding : public PassWrapper<FusePadding, FunctionPass> {
FusePadding() = default;
FusePadding(const FusePadding& pass) {}
void runOnFunction() override {
auto* ctx = &getContext();
OwningRewritePatternList patterns(ctx);
auto func = getFunction();
populateWithGenerated(patterns);
(void)applyPatternsAndFoldGreedily(func, std::move(patterns));
}
void getDependentDialects(DialectRegistry& registry) const override {
registry.insert<::mlir::TFL::TensorFlowLiteDialect>();
}
};
} // namespace
// Creates an instance of the TensorFlow dialect FusePadding pass.
std::unique_ptr<OperationPass<FuncOp>> CreateFusePaddingPass() {
return std::make_unique<FusePadding>();
}
static PassRegistration<FusePadding> pass(
"tfl-fuse-padding", "Fuse padding ops into (Depthwise)Convs.");
} // namespace TFL
} // namespace mlir
| 34.880597 | 79 | 0.744544 | godhj93 |
990ce40d611e8ecc977c2e5fe7133c3bcbddaf35 | 9,821 | cpp | C++ | Source/Engine/LightFroxelationTechnique.cpp | glowing-chemist/Bell | 0cf4d0ac925940869077779700c1d3bd45ff841f | [
"MIT"
] | 14 | 2020-02-12T19:13:46.000Z | 2022-03-05T02:26:06.000Z | Source/Engine/LightFroxelationTechnique.cpp | glowing-chemist/Bell | 0cf4d0ac925940869077779700c1d3bd45ff841f | [
"MIT"
] | 5 | 2020-08-06T07:19:47.000Z | 2021-01-05T21:20:51.000Z | Source/Engine/LightFroxelationTechnique.cpp | glowing-chemist/Bell | 0cf4d0ac925940869077779700c1d3bd45ff841f | [
"MIT"
] | 2 | 2021-09-18T13:36:47.000Z | 2021-12-04T15:08:53.000Z | #include "Engine/LightFroxelationTechnique.hpp"
#include "Engine/Engine.hpp"
#include "Engine/DefaultResourceSlots.hpp"
#include "Core/Executor.hpp"
constexpr const char* kFroxelIndirectArgs = "FroxelIndirectArgs";
constexpr const char* kLightIndexCounter = "lightIndexCounter";
constexpr const char* kActiveFroxelsCounter = "ActiveFroxelsCounter";
LightFroxelationTechnique::LightFroxelationTechnique(RenderEngine* eng, RenderGraph& graph) :
Technique("LightFroxelation", eng->getDevice()),
mActiveFroxelsShader(eng->getShader("./Shaders/ActiveFroxels.comp")),
mIndirectArgsShader(eng->getShader("./Shaders/IndirectFroxelArgs.comp")),
mClearCoutersShader(eng->getShader("./Shaders/LightFroxelationClearCounters.comp")),
mLightAsignmentShader(eng->getShader("./Shaders/FroxelationGenerateLightLists.comp")),
mXTiles(eng->getDevice()->getSwapChainImageView()->getImageExtent().width / 32),
mYTiles(eng->getDevice()->getSwapChainImageView()->getImageExtent().height / 32),
mLightBuffer(getDevice(), BufferUsage::DataBuffer | BufferUsage::TransferDest, (sizeof(Scene::Light) * 1000) + std::max(sizeof(uint4), getDevice()->getMinStorageBufferAlignment()), (sizeof(Scene::Light) * 1000) + std::max(sizeof(uint4), getDevice()->getMinStorageBufferAlignment()), "LightBuffer"),
mLightBufferView(mLightBuffer, std::max(sizeof(uint4), getDevice()->getMinStorageBufferAlignment())),
mLightCountView(mLightBuffer, 0, sizeof(uint4)),
mLightsSRS(getDevice(), 2),
mActiveFroxelsImage(eng->getDevice(), Format::R32Uint, ImageUsage::Storage | ImageUsage::Sampled, eng->getDevice()->getSwapChainImageView()->getImageExtent().width,
eng->getDevice()->getSwapChainImageView()->getImageExtent().height, 1, 1, 1, 1, "ActiveFroxels"),
mActiveFroxelsImageView(mActiveFroxelsImage, ImageViewType::Colour),
// Assumes an avergae max of 10 active froxels per screen space tile.
mActiveFroxlesBuffer(eng->getDevice(), BufferUsage::DataBuffer | BufferUsage::Uniform, sizeof(float4) * (mXTiles * mYTiles * 10), sizeof(float4) * (mXTiles* mYTiles * 10), "ActiveFroxelBuffer"),
mActiveFroxlesBufferView(mActiveFroxlesBuffer, std::max(eng->getDevice()->getMinStorageBufferAlignment(), sizeof(uint32_t))),
mActiveFroxelsCounter(mActiveFroxlesBuffer, 0u, static_cast<uint32_t>(sizeof(uint32_t))),
mIndirectArgsBuffer(eng->getDevice(), BufferUsage::DataBuffer | BufferUsage::IndirectArgs, sizeof(uint32_t) * 3, sizeof(uint32_t) * 3, "FroxelIndirectArgs"),
mIndirectArgsView(mIndirectArgsBuffer, 0, sizeof(uint32_t) * 3),
mSparseFroxelBuffer(eng->getDevice(), BufferUsage::DataBuffer, sizeof(float2) * (mXTiles * mYTiles * 32), sizeof(float2) * (mXTiles * mYTiles * 32), kSparseFroxels),
mSparseFroxelBufferView(mSparseFroxelBuffer),
mLightIndexBuffer(eng->getDevice(), BufferUsage::DataBuffer, sizeof(uint32_t) * (mXTiles * mYTiles * 16 * 16), sizeof(uint32_t) * (mXTiles * mYTiles * 16 * 16), kLightIndicies),
mLightIndexBufferView(mLightIndexBuffer, std::max(eng->getDevice()->getMinStorageBufferAlignment(), sizeof(uint32_t))),
mLightIndexCounterView(mLightIndexBuffer, 0, static_cast<uint32_t>(sizeof(uint32_t)))
{
// set light buffers SRS
for(uint32_t i = 0; i < getDevice()->getSwapChainImageCount(); ++i)
{
mLightsSRS.get(i)->addDataBufferRO(mLightCountView.get(i));
mLightsSRS.get(i)->addDataBufferRW(mLightBufferView.get(i));
mLightsSRS.get(i)->finalise();
}
ComputeTask clearCountersTask{ "clearFroxelationCounters" };
clearCountersTask.addInput(kActiveFroxelsCounter, AttachmentType::DataBufferWO);
clearCountersTask.addInput(kLightIndexCounter, AttachmentType::DataBufferWO);
clearCountersTask.setRecordCommandsCallback(
[this](const RenderGraph& graph, const uint32_t taskIndex, Executor* exec, RenderEngine*, const std::vector<const MeshInstance*>&)
{
PROFILER_EVENT("Clear froxel counter");
PROFILER_GPU_TASK(exec);
PROFILER_GPU_EVENT("Clear froxel counter");
const RenderTask& task = graph.getTask(taskIndex);
exec->setComputeShader(static_cast<const ComputeTask&>(task), graph, mClearCoutersShader);
exec->dispatch(1, 1, 1);
}
);
mClearCounters = graph.addTask(clearCountersTask);
ComputeTask activeFroxelTask{ "LightingFroxelation" };
activeFroxelTask.addInput(kActiveFroxels, AttachmentType::Image2D);
activeFroxelTask.addInput(kLinearDepth, AttachmentType::Texture2D);
activeFroxelTask.addInput(kCameraBuffer, AttachmentType::UniformBuffer);
activeFroxelTask.addInput(kDefaultSampler, AttachmentType::Sampler);
activeFroxelTask.addInput(kActiveFroxelBuffer, AttachmentType::DataBufferWO);
activeFroxelTask.addInput(kActiveFroxelsCounter, AttachmentType::DataBufferRW);
activeFroxelTask.setRecordCommandsCallback(
[this](const RenderGraph& graph, const uint32_t taskIndex, Executor* exec, RenderEngine* eng, const std::vector<const MeshInstance*>&)
{
PROFILER_EVENT("light froxelation");
PROFILER_GPU_TASK(exec);
PROFILER_GPU_EVENT("light froxelation");
const RenderTask& task = graph.getTask(taskIndex);
exec->setComputeShader(static_cast<const ComputeTask&>(task), graph, mActiveFroxelsShader);
const auto extent = eng->getDevice()->getSwapChainImageView()->getImageExtent();
exec->dispatch(static_cast<uint32_t>(std::ceil(extent.width / 32.0f)), static_cast<uint32_t>(std::ceil(extent.height / 32.0f)), 1);
}
);
mActiveFroxels = graph.addTask(activeFroxelTask);
ComputeTask indirectArgsTask{ "generateFroxelIndirectArgs" };
indirectArgsTask.addInput(kActiveFroxelsCounter, AttachmentType::DataBufferRO);
indirectArgsTask.addInput(kFroxelIndirectArgs, AttachmentType::DataBufferWO);
indirectArgsTask.setRecordCommandsCallback(
[this](const RenderGraph& graph, const uint32_t taskIndex, Executor* exec, RenderEngine*, const std::vector<const MeshInstance*>&)
{
const RenderTask& task = graph.getTask(taskIndex);
exec->setComputeShader(static_cast<const ComputeTask&>(task), graph, mIndirectArgsShader);
exec->dispatch(1, 1, 1);
}
);
mIndirectArgs = graph.addTask(indirectArgsTask);
ComputeTask lightListAsignmentTask{ "LightAsignment" };
lightListAsignmentTask.addInput(kActiveFroxelBuffer, AttachmentType::DataBufferRO);
lightListAsignmentTask.addInput(kActiveFroxelsCounter, AttachmentType::DataBufferRO);
lightListAsignmentTask.addInput(kLightIndicies, AttachmentType::DataBufferWO);
lightListAsignmentTask.addInput(kLightIndexCounter, AttachmentType::DataBufferRW);
lightListAsignmentTask.addInput(kSparseFroxels, AttachmentType::DataBufferWO);
lightListAsignmentTask.addInput(kCameraBuffer, AttachmentType::UniformBuffer);
lightListAsignmentTask.addInput(kLightBuffer, AttachmentType::ShaderResourceSet);
lightListAsignmentTask.addInput(kFroxelIndirectArgs, AttachmentType::IndirectBuffer);
lightListAsignmentTask.setRecordCommandsCallback(
[this](const RenderGraph& graph, const uint32_t taskIndex, Executor* exec, RenderEngine*, const std::vector<const MeshInstance*>&)
{
PROFILER_EVENT("build light lists");
PROFILER_GPU_TASK(exec);
PROFILER_GPU_EVENT("build light lists");
const RenderTask& task = graph.getTask(taskIndex);
exec->setComputeShader(static_cast<const ComputeTask&>(task), graph, mLightAsignmentShader);
exec->dispatchIndirect(this->mIndirectArgsView);
}
);
mLightListAsignment = graph.addTask(lightListAsignmentTask);
}
void LightFroxelationTechnique::render(RenderGraph&, RenderEngine* engine)
{
mActiveFroxelsImageView->updateLastAccessed();
mActiveFroxelsImage->updateLastAccessed();
mActiveFroxlesBuffer->updateLastAccessed();
mSparseFroxelBuffer->updateLastAccessed();
mLightIndexBuffer->updateLastAccessed();
mIndirectArgsBuffer->updateLastAccessed();
(*mLightBuffer)->updateLastAccessed();
(*mLightsSRS)->updateLastAccessed();
// Frustum cull the lights and send to the gpu.
Frustum frustum = engine->getCurrentSceneCamera().getFrustum();
std::vector<Scene::Light*> visibleLightPtrs = engine->getScene()->getVisibleLights(frustum);
std::vector<Scene::Light> visibleLights{};
visibleLights.reserve(visibleLightPtrs.size());
std::transform(visibleLightPtrs.begin(), visibleLightPtrs.end(), std::back_inserter(visibleLights), []
(const Scene::Light* light) { return *light; });
mLightBuffer.get()->setContents(static_cast<int>(visibleLights.size()), sizeof(uint32_t));
if(!visibleLights.empty())
{
mLightBuffer.get()->resize(visibleLights.size() * sizeof(Scene::Light), false);
mLightBuffer.get()->setContents(visibleLights.data(), static_cast<uint32_t>(visibleLights.size() * sizeof(Scene::Light)), std::max(sizeof(uint4), engine->getDevice()->getMinStorageBufferAlignment()));
}
}
void LightFroxelationTechnique::bindResources(RenderGraph& graph)
{
graph.bindShaderResourceSet(kLightBuffer, *mLightsSRS);
if(!graph.isResourceSlotBound(kActiveFroxels))
{
graph.bindImage(kActiveFroxels, mActiveFroxelsImageView);
graph.bindBuffer(kActiveFroxelBuffer, mActiveFroxlesBufferView);
graph.bindBuffer(kSparseFroxels, mSparseFroxelBufferView);
graph.bindBuffer(kLightIndicies, mLightIndexBufferView);
graph.bindBuffer(kActiveFroxelsCounter, mActiveFroxelsCounter);
graph.bindBuffer(kFroxelIndirectArgs, mIndirectArgsView);
graph.bindBuffer(kLightIndexCounter, mLightIndexCounterView);
}
}
| 53.961538 | 302 | 0.74188 | glowing-chemist |
991079589d5147f94a6171c1143c3dd8af22f512 | 4,157 | cpp | C++ | environment/interpretation/obstacle_detector/src/ObstacleDetector.cpp | krishna95/freezing-batman | 66f1ac7e73c65162f1593cf440c3363a9e4b1efb | [
"BSD-3-Clause"
] | null | null | null | environment/interpretation/obstacle_detector/src/ObstacleDetector.cpp | krishna95/freezing-batman | 66f1ac7e73c65162f1593cf440c3363a9e4b1efb | [
"BSD-3-Clause"
] | null | null | null | environment/interpretation/obstacle_detector/src/ObstacleDetector.cpp | krishna95/freezing-batman | 66f1ac7e73c65162f1593cf440c3363a9e4b1efb | [
"BSD-3-Clause"
] | null | null | null | #include "../include/ObstacleDetector.hpp"
#include <climits>
#include <cassert>
void exit_with_help(){
std::cout<<
"Usage: lane-detector [options]\n"
"options:\n"
"-d : Non-zero for debug\n"
"-s : Subscriber topic name\n"
"-p : Publisher topic name\n"
"-l : Maximum distance we need \n"
"-m : Mininum distance we need \n"
;
exit(1);
}
void ObstacleDetector::publishData(){
cv_bridge::CvImage out_msg;
out_msg.encoding = sensor_msgs::image_encodings::MONO8;
out_msg.image = img;
out_msg.encoding = sensor_msgs::image_encodings::MONO8;
pub.publish(out_msg.toImageMsg());
}
void ObstacleDetector::interpret() {
if (debug){
cvNamedWindow("Control Box", 1);
}
int s=5;
if (debug) {
cvCreateTrackbar("Kernel 1", "Control Box", &s, 20);
cv::namedWindow("Raw Scan", 0);
cv::imshow("Raw Scan", img);
cv::waitKey(WAIT_TIME);
}
int dilation_size = EXPAND_OBS;
cv::Mat element = cv::getStructuringElement( cv::MORPH_ELLIPSE,
cv::Size( 2*dilation_size + 1, 2*dilation_size+1 ),
cv::Point( dilation_size, dilation_size ) );
cv::dilate(img, img, element);
if (debug) {
cv::namedWindow("Dilate Filter", 1);
cv::imshow("Dilate Filter", img);
cv::waitKey(WAIT_TIME);
}
publishData();
}
void ObstacleDetector::scanCallback(const sensor_msgs::LaserScan& scan) {
ROS_INFO("Scan callback called");
size_t size = scan.ranges.size();
float angle = scan.angle_min;
float maxRangeForContainer = scan.range_max - 0.1f;
img = img-img; // Assign zero to all pixels
for (size_t i = 0; i < size; ++i) {
float dist = scan.ranges[i];
if ((dist > scan.range_min) && (dist < maxRangeForContainer)) {
double x1 = -1 * sin(angle) * dist;
double y1 = cos(angle) * dist;
int x = (int) ((x1 * 100) + CENTERX);
int y = (int) ((y1 * 100) + CENTERY + LIDAR_Y_SHIFT);
if (x >= 0 && y >= min_dist && (int) x < MAP_MAX && (int) y < max_dist) {
int x2 = (x);
int y2 = (MAP_MAX - y - 30 - 1);
if(!(y2 >= 0 && y2 < MAP_MAX)){
continue;
}
img.at<uchar>(y2,x2)=255;
}
}
angle += scan.angle_increment;
}
interpret();
}
ObstacleDetector::ObstacleDetector(int argc, char *argv[], ros::NodeHandle &node_handle):nh(node_handle) {
topic_name = std::string("interpreter/obstacleMap/0");
sub_topic_name = std::string("/scan");
min_dist = 0;
max_dist = 400;
debug = 0;
for(int i=1;i<argc;i++)
{
if(argv[i][0] != '-') {
break;
}
if (++i>=argc) {
}
switch(argv[i-1][1])
{
case 'd':
debug = atoi(argv[i]);
break;
case 's':
sub_topic_name = std::string(argv[i]);
break;
case 'p':
topic_name = std::string(argv[i]);
break;
case 'l':
max_dist = atoi(argv[i]);
break;
case 'm':
min_dist = atoi(argv[i]);
break;
default:
fprintf(stderr, "Unknown option: -%c\n", argv[i-1][1]);
exit_with_help();
}
}
it = new image_transport::ImageTransport(nh);
sub = nh.subscribe(sub_topic_name.c_str(), 2, &ObstacleDetector::scanCallback,this);
img = cv::Mat(MAP_MAX,MAP_MAX,CV_8UC1,cvScalarAll(0));
pub = it->advertise(topic_name.c_str(), 10);
}
ObstacleDetector::~ObstacleDetector() {
}
int main(int argc, char** argv) {
std::string node_name;
// if (argc>1){
// node_name = std::string("interpreter_obstacleDetector_") + std::string(argv[1]);
// }
// else{
// node_name = std::string("interpreter_obstacleDetector_0");
// }
ros::init(argc, argv, node_name.c_str());
ros::NodeHandle nh;
ObstacleDetector obstacle_detector(argc, argv, nh);
ros::Rate loop_rate(LOOP_RATE);
ROS_INFO("Obstacle Detector Thread Started...");
while (ros::ok()) {
ros::spinOnce();
loop_rate.sleep();
}
ROS_INFO("Obstacle code exiting");
return 0;
}
| 26.819355 | 106 | 0.566514 | krishna95 |
9915b7f000edc4973109b7ba5e2117c26dcbd15b | 15,698 | cpp | C++ | world/Room.cpp | sg-p4x347/binding-of-ryesaac | f4b4b3e8f29c5fa2dda184691358605c41f539d5 | [
"MIT"
] | null | null | null | world/Room.cpp | sg-p4x347/binding-of-ryesaac | f4b4b3e8f29c5fa2dda184691358605c41f539d5 | [
"MIT"
] | 6 | 2019-11-29T16:42:12.000Z | 2019-12-08T07:03:23.000Z | world/Room.cpp | sg-p4x347/binding-of-ryesaac | f4b4b3e8f29c5fa2dda184691358605c41f539d5 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "Room.h"
#include "geom/ModelRepository.h"
using geom::ModelRepository;
#include "tex/TextureRepository.h"
using tex::TextureRepository;
#include "geom/CollisionUtil.h"
#include "geom/Sphere.h"
#include "game/Game.h"
using game::Game;
#include "game/MultimediaPlayer.h"
using game::MultimediaPlayer;
#include <GL/glut.h>
#include "World.h"
namespace world {
const float Room::k_collisionCullRange = 1.5f;
Room::Room(RoomType type, Vector3 center) : m_center(center), m_type(type), m_inCombat(false), m_duck(0)
{
}
void Room::Update(double elapsed)
{
AiUpdate(elapsed);
AgentUpdate(elapsed);
MovementUpdate(elapsed);
CollisionUpdate(elapsed);
DoorUpdate(elapsed);
CombatUpdate(elapsed);
ItemUpdate(elapsed);
//SweepUpdate(elapsed);
DeferredUpdate(elapsed);
PlayerLocationUpdate();
}
void Room::Render()
{
for (auto& entity : ER.GetIterator<Model, Position>()) {
Position& position = entity.Get<Position>();
Model& modelComp = entity.Get<Model>();
if (!modelComp.Hidden && modelComp.ModelPtr) {
glPushMatrix();
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,TextureRepository::GetID(modelComp.ModelPtr->Name));
glTranslatef(position.Pos.X, position.Pos.Y, position.Pos.Z);
glRotatef(math::RadToDeg(position.Rot.X), 1.f, 0.f, 0.f);
glRotatef(math::RadToDeg(position.Rot.Y), 0.f, 1.f, 0.f);
glRotatef(math::RadToDeg(position.Rot.Z), 0.f, 0.f, 1.f);
geom::Model& model = *modelComp.ModelPtr;
for (auto& mesh : model.Meshes) {
glBegin(GL_TRIANGLES);
for (auto& index : mesh.Indices) {
geom::ModelMeshVertex& vertex = mesh.Vertices[index];
glNormal3f(vertex.Normal.X, vertex.Normal.Y, vertex.Normal.Z);
glTexCoord2f(vertex.TextureCoordinate.X, vertex.TextureCoordinate.Y);
glVertex3f(vertex.Position.X, vertex.Position.Y, vertex.Position.Z);
}
glEnd();
}
glBindTexture(GL_TEXTURE_2D, 0);
glPopMatrix();
}
}
}
EntityRepository& Room::GetER()
{
return ER;
}
Room::RoomType Room::GetType()
{
return m_type;
}
void Room::AddLoot(LootItem item)
{
m_loot.push_back(item);
}
void Room::DropLoot()
{
for (auto& loot : m_loot) {
string modelName = "";
switch (loot) {
case LootItem::Key: modelName = "key"; break;
}
m_deferredTasks.push_back([=] {
ER.CreateEntity(
Position(m_center, Vector3::Zero),
Movement(Vector3::Zero,Vector3(0.f,1.f,0.f)),
Model(ModelRepository::Get(modelName)),
Collision(std::make_shared<geom::Sphere>(Vector3::Zero, 0.25f)),
Item(loot)
);
});
}
// Consume the loot
m_loot.clear();
}
void Room::SweepAttack(int cornerIndex)
{
Vector3 pivot;
Vector3 start;
float angle;
switch (cornerIndex) {
case 0:
pivot = m_center + Vector3(-World::k_roomUnitSize.X, 0.f, -World::k_roomUnitSize.Y) * 0.5f;
start = m_center + Vector3(World::k_roomUnitSize.X, 0.f, -World::k_roomUnitSize.Y) * 0.5f;
angle = -math::PI / 2.f;
break;
case 1:
pivot = m_center + Vector3(World::k_roomUnitSize.X, 0.f, -World::k_roomUnitSize.Y) * 0.5f;
start = m_center + Vector3(-World::k_roomUnitSize.X, 0.f, -World::k_roomUnitSize.Y) * 0.5f;
angle = math::PI / 2.f;
break;
case 2:
pivot = m_center + Vector3(World::k_roomUnitSize.X, 0.f, World::k_roomUnitSize.Y) * 0.5f;
start = m_center + Vector3(-World::k_roomUnitSize.X, 0.f, World::k_roomUnitSize.Y) * 0.5f;
angle = math::PI / 2.f;
break;
case 3:
pivot = m_center + Vector3(-World::k_roomUnitSize.X, 0.f, World::k_roomUnitSize.Y) * 0.5f;
start = m_center + Vector3(World::k_roomUnitSize.X, 0.f, World::k_roomUnitSize.Y) * 0.5f;
angle = -math::PI / 2.f;
break;
}
Sweep sweep;
sweep.Duration = 6.f;
for (float t = 0; t <= 1; t += 1.f / 20) {
sweep.Waypoints.push_back(pivot + (math::CreateRotationY(angle * t) * (start - pivot)));
}
m_deferredTasks.push_back([=] {
ER.CreateEntity(
Position(),
Movement(Vector3::Zero, Vector3(0.f, angle / sweep.Duration, 0.f)),
Sweep(sweep),
Model(ModelRepository::Get("duck_head")),
Agent(Agent::AgentFaction::Toast, 0.f, 20, 0.f, 0.f, 1),
Collision(std::make_shared<geom::Sphere>(Vector3::Zero, 1.f))
);
});
}
ecs::EntityID Room::CreateDuck()
{
return ER.CreateEntity(
Position(Vector3::Zero, Vector3(0.f, math::PI, 0.f)),
Sweep(),
Model(ModelRepository::Get("duck_head")),
Agent(Agent::AgentFaction::Toast, 0.f, 20, 0.f, 0.f, 1),
Collision(std::make_shared<geom::Sphere>(Vector3::Zero, 1.f))
);
}
void Room::StompAttack(Vector2 focus)
{
m_deferredTasks.push_back([=] {
if (!m_duck) {
m_duck = CreateDuck();
}
for (auto& entity : ER.GetIterator<Sweep>()) {
auto& sweep = entity.Get<Sweep>();
if (sweep.ID == m_duck) {
sweep.Duration = 6.f;
static float start = 4.f;
sweep.Waypoints.push_back(Vector3(focus.X, start, focus.Y));
sweep.Waypoints.push_back(Vector3(focus.X, 0.f, focus.Y));
sweep.Waypoints.push_back(Vector3(focus.X, 0.f, focus.Y));
sweep.Waypoints.push_back(Vector3(focus.X, start, focus.Y));
}
}
});
}
void Room::AgentUpdate(double elapsed)
{
for (auto& entity : ER.GetIterator<Agent, Model, Movement, Collision, Position>()) {
auto& agent = entity.Get<Agent>();
auto& model = entity.Get<Model>();
auto& movement = entity.Get<Movement>();
auto& collision = entity.Get<Collision>();
auto& position = entity.Get<Position>();
// Convert agent heading into a velocity
agent.Heading.Normalize();
movement.Velocity = agent.Heading * agent.Speed;
// Update attack cooldown
agent.AttackCooldown = max(0.0, agent.AttackCooldown - elapsed);
// Update recovery cooldown
agent.RecoveryCooldown = max(0.0, agent.RecoveryCooldown - elapsed);
// Strobe the model while in cooldown
if (agent.RecoveryCooldown) {
static const float k_recoveryFlashPeriod = 0.25f;
model.Hidden = std::fmodf(agent.RecoveryCooldown, k_recoveryFlashPeriod) <= k_recoveryFlashPeriod * 0.5f;
}
else {
model.Hidden = false;
}
if (agent.Attack && !agent.AttackCooldown) {
shared_ptr<geom::Model> projectileModel;
switch (agent.Faction) {
case Agent::AgentFaction::Bread:
projectileModel = ModelRepository::Get("butter");
break;
case Agent::AgentFaction::Toast:
projectileModel = ModelRepository::Get("butter");
break;
}
m_deferredTasks.push_back([=] {
Agent projectile = Agent(agent.Faction, 8.f, 0, 0.f, 0.f, 1);
projectile.Heading = Vector3(std::cos(-position.Rot.Y), 0.f, std::sin(-position.Rot.Y));
ER.CreateEntity(
Position(position),
projectile,
Movement(Vector3::Zero,Vector3(0.f,math::TWO_PI * 5.f,0.f)),
Collision(std::make_shared<geom::Sphere>(Vector3::Zero, 0.25), (uint32_t)CollisionChannel::Projectile),
Model(projectileModel)
);
});
agent.AttackCooldown = agent.AttackPeriod;
}
if (agent.MaxHealth > 0) {
if (agent.Health <= 0) {
m_deferredTasks.push_back([=] {
ER.Remove(agent.ID);
});
}
else {
// Apply damage if not in recovery (temporary invincibility after taking damage)
if (!agent.RecoveryCooldown && !collision.Contacts.empty()) {
for (auto& other : ER.GetIterator<Agent>()) {
auto& otherAgent = other.Get<Agent>();
// check to see if other is a different faction and shows up in our contact list
if (otherAgent.Faction != agent.Faction && collision.Contacts.count(otherAgent.ID)) {
// Apply other agent's damage to our health
agent.Health -= otherAgent.Damage;
// Start recovery cooldown
agent.RecoveryCooldown = agent.RecoveryPeriod;
}
}
}
}
}
else {
if (!collision.Contacts.empty()) {
m_deferredTasks.push_back([=] {
ER.Remove(agent.ID);
});
}
}
}
}
void Room::AiUpdate(double elapsed)
{
for (auto& playerEntity : ER.GetIterator<Player, Agent, Position>()) {
auto& player = playerEntity.Get<Agent>();
auto& playerPos = playerEntity.Get<Position>();
for (auto& enemyEntity : ER.GetIterator<AI,Agent, Position>()) {
auto& enemy = enemyEntity.Get<Agent>();
auto& enemyPos = enemyEntity.Get<Position>();
if (enemy.Faction != player.Faction) {
enemy.Heading = playerPos.Pos - enemyPos.Pos;
enemyPos.Rot.Y = -std::atan2f(enemy.Heading.Z, enemy.Heading.X);
}
}
}
}
void Room::MovementUpdate(double elapsed)
{
for (auto& entity : ER.GetIterator<Movement, Position>()) {
auto& movement = entity.Get<Movement>();
auto& position = entity.Get<Position>();
position.Pos += movement.Velocity * elapsed;
position.Rot += movement.AngularVelocity * elapsed;
// Wrap rotations around 2 pi
position.Rot.X = std::fmodf(position.Rot.X, math::TWO_PI);
position.Rot.Y = std::fmodf(position.Rot.Y, math::TWO_PI);
position.Rot.Z = std::fmodf(position.Rot.Z, math::TWO_PI);
}
}
void Room::CollisionUpdate(double elapsed)
{
// Clear contacts
for (auto& collider : ER.GetIterator<Collision>()) {
collider.Get<Collision>().Contacts.clear();
}
for (auto& dynamicCollider : ER.GetIterator<Movement,Collision, Position>()) {
auto& movement = dynamicCollider.Get<Movement>();
auto& dynamicCollision = dynamicCollider.Get<Collision>();
auto& dynamicPosition = dynamicCollider.Get<Position>();
auto dynamicCollisionVolume = dynamicCollision.CollisionVolume->Transform(dynamicPosition.GetTransform());
for (auto& staticCollider : ER.GetIterator<Collision, Position>()) {
auto& staticCollision = staticCollider.Get<Collision>();
auto& staticPosition = staticCollider.Get<Position>();
if (
// This collision has already been handled by the other entity
!dynamicCollision.Contacts.count(staticCollision.ID)
// Only handle collisions between disjoint channels
&& !(dynamicCollision.Channel & staticCollision.Channel)
// Don't collide with ourself
&& staticCollision.ID != dynamicCollision.ID
// Be within a sane range
&& (staticPosition.Pos - dynamicPosition.Pos).LengthSquared() < k_collisionCullRange * k_collisionCullRange
) {
auto staticCollisionVolume = staticCollision.CollisionVolume->Transform(staticPosition.GetTransform());
// Use GJK to test if an intersection exists
geom::GjkIntersection intersection;
if (geom::GJK(*dynamicCollisionVolume, *staticCollisionVolume, intersection)) {
// Use EPA to get the contact details
Collision::Contact contact;
if (geom::EPA(*dynamicCollisionVolume, *staticCollisionVolume, intersection, contact)) {
// Immediately correct the position in the X-Z plane
dynamicPosition.Pos.X += contact.Normal.X * contact.PenetrationDepth;
dynamicPosition.Pos.Z += contact.Normal.Z * contact.PenetrationDepth;
// Update collision volume
dynamicCollisionVolume = dynamicCollision.CollisionVolume->Transform(dynamicPosition.GetTransform());
// Register contacts on both colliders
contact.Collider = staticCollision.ID;
dynamicCollision.Contacts[contact.Collider] = contact;
contact.Collider = dynamicCollision.ID;
staticCollision.Contacts[contact.Collider] = contact;
}
}
}
}
}
}
void Room::PlayerLocationUpdate()
{
for (auto& playerEntity : ER.GetIterator<Player, Collision>()) {
auto& player = playerEntity.Get<Player>();
if (m_type == RoomType::Duck) {
if (m_inCombat)
{
if (Game::GetInstance().state != GameState::InGame_BossBattle)
{
Game::GetInstance().state = GameState::InGame_BossBattle;
Game::GetInstance().bossStart = clock();
MultimediaPlayer::SetUp("./Assets/audio/Boss_Battle_Condesa_DuckAttacks_Overlay.wav", true, true);
MultimediaPlayer::GetInstance().startAudio();
}
}
else
{
if (Game::GetInstance().state != GameState::Outro)
{
Game::GetInstance().state = GameState::Outro;
MultimediaPlayer::SetUp("./Assets/audio/Boss_Battle_Victory.wav", true, true);
MultimediaPlayer::GetInstance().startAudio();
}
}
}
}
}
void Room::DoorUpdate(double elapsed)
{
for (auto& entity : ER.GetIterator<Door, Model, Collision>()) {
auto& door = entity.Get<Door>();
auto& model = entity.Get<Model>();
auto& collision = entity.Get<Collision>();
if (door.State == Door::DoorState::Locked) {
for (auto& playerEntity : ER.GetIterator<Player, Collision>()) {
auto& player = playerEntity.Get<Player>();
if (player.Inventory[LootItem::Key] > 0) {
if (playerEntity.Get<Collision>().Contacts.count(door.ID)) {
// unlock the door
door.State = Door::DoorState::Open;
// consume the key
player.Inventory[LootItem::Key]--;
break;
}
}
}
}
// Update model
model.ModelPtr = ModelRepository::Get("door_" + std::to_string((int)door.State));
/* Update collision channel
As long as the player shares this channel, collision will not be handled */
switch (door.State) {
case Door::DoorState::Closed:
case Door::DoorState::Locked:
collision.Channel = 0;
break;
case Door::DoorState::Open:
collision.Channel = (uint32_t)CollisionChannel::Door;
break;
}
}
}
void Room::CombatUpdate(double elapsed)
{
bool previousCombatState = m_inCombat;
// While there are enemy agents in the room, keep the doors closed
for (auto& agent : ER.GetIterator<Agent>()) {
if (agent.Get<Agent>().Faction != Agent::AgentFaction::Bread) {
// Close all the doors if they are open
m_inCombat = true;
for (auto& door : ER.GetIterator<Door>()) {
if (door.Get<Door>().State == Door::DoorState::Open)
door.Get<Door>().State = Door::DoorState::Closed;
}
return;
}
}
// not in combat - Open all the non-locked doors
m_inCombat = false;
for (auto& door : ER.GetIterator<Door>()) {
if (door.Get<Door>().State == Door::DoorState::Closed)
door.Get<Door>().State = Door::DoorState::Open;
}
// Drop loot if the combat state has dropped to false
if (previousCombatState && !m_inCombat) {
DropLoot();
}
}
void Room::ItemUpdate(double elapsed)
{
for (auto& playerEntity : ER.GetIterator<Player, Collision>()) {
auto& player = playerEntity.Get<Player>();
for (auto& entity : ER.GetIterator<Item>()) {
auto& item = entity.Get<Item>();
if (playerEntity.Get<Collision>().Contacts.count(item.ID)) {
// Perform the transaction
player.Inventory[item.Type]++;
m_deferredTasks.push_back([=] {
ER.Remove(item.ID);
});
}
}
}
}
void Room::SweepUpdate(double elapsed)
{
for (auto& entity : ER.GetIterator<Sweep, Position>()) {
auto& sweep = entity.Get<Sweep>();
auto& position = entity.Get<Position>();
sweep.Progress = min(sweep.Duration, sweep.Progress + elapsed);
float percent = (sweep.Progress / sweep.Duration);
sweep.CurrentWaypoint = percent * (sweep.Waypoints.size() - 1);
float linePercent = percent - ((float)sweep.CurrentWaypoint / (float)(sweep.Waypoints.size() - 1));
Vector3 currentWaypoint = sweep.Waypoints[sweep.CurrentWaypoint];
if (sweep.CurrentWaypoint < sweep.Waypoints.size() - 1) {
Vector3 nextWaypoint = sweep.Waypoints[sweep.CurrentWaypoint + 1];
position.Pos = (nextWaypoint - currentWaypoint) * linePercent + currentWaypoint;
}
else {
position.Pos = currentWaypoint;
}
}
}
void Room::DeferredUpdate(double elapsed)
{
for (auto& task : m_deferredTasks) {
task();
}
m_deferredTasks.clear();
}
} | 31.270916 | 112 | 0.659511 | sg-p4x347 |
9919c30b52c598b849cfdd1c15db09b41bffaef6 | 1,317 | cpp | C++ | src/Misc/PKCS1.cpp | httese/OpenPGP | 7dce08dc8b72eeb0dcbf3df56d64606a6b957938 | [
"MIT"
] | 99 | 2015-01-06T01:53:26.000Z | 2022-01-31T18:18:27.000Z | src/Misc/PKCS1.cpp | httese/OpenPGP | 7dce08dc8b72eeb0dcbf3df56d64606a6b957938 | [
"MIT"
] | 27 | 2015-03-09T05:46:53.000Z | 2020-05-06T02:52:18.000Z | src/Misc/PKCS1.cpp | httese/OpenPGP | 7dce08dc8b72eeb0dcbf3df56d64606a6b957938 | [
"MIT"
] | 42 | 2015-03-18T03:44:43.000Z | 2022-03-31T21:34:06.000Z | #include "Misc/PKCS1.h"
#include "Misc/pgptime.h"
#include "RNG/RNGs.h"
#include "common/includes.h"
namespace OpenPGP {
std::string EME_PKCS1v1_5_ENCODE(const std::string & m, const unsigned int & k) {
if (m.size() > (k - 11)) {
// "Error: EME-PKCS1 Message too long.\n";
return "";
}
std::string EM = zero + "\x02";
while (EM.size() < k - m.size() - 1) {
if (const unsigned char c = RNG::RNG().rand_bytes(1)[0]) { // non-zero octets only
EM += std::string(1, c);
}
}
return EM + zero + m;
}
std::string EME_PKCS1v1_5_DECODE(const std::string & m) {
if (m.size() > 11) {
if (!m[0]) {
if (m[1] == '\x02') {
std::string::size_type x = 2;
while ((x < m.size()) && m[x]) {
x++;
}
return m.substr(x + 1, m.size() - x - 1);
}
}
}
// "Error: EME-PKCS1 Decryption Error.\n";
return "";
}
std::string EMSA_PKCS1_v1_5(const uint8_t & hash, const std::string & hashed_data, const unsigned int & keylength) {
return zero + "\x01" + std::string(keylength - (Hash::ASN1_DER.at(hash).size() >> 1) - 3 - (Hash::LENGTH.at(hash) >> 3), (char) 0xffU) + zero + unhexlify(Hash::ASN1_DER.at(hash)) + hashed_data;
}
}
| 28.021277 | 197 | 0.515566 | httese |
991a1d83e9ae9220fd6908a25dc12d3db0a6c07f | 1,009 | cpp | C++ | Warcraft Heroes Beyond Time/Warcraft Heroes Beyond Time/EnergyItem.cpp | SoftCactusTeam/Warcraft_Adventures | 7b44294d44094ce690abe90348dd87f42cdae07d | [
"MIT"
] | 9 | 2018-03-19T21:36:53.000Z | 2020-02-28T07:05:17.000Z | Warcraft Heroes Beyond Time/Warcraft Heroes Beyond Time/EnergyItem.cpp | SoftCactusTeam/Warcraft-Heroes-Beyond-Time | 7b44294d44094ce690abe90348dd87f42cdae07d | [
"MIT"
] | 87 | 2018-03-04T15:04:57.000Z | 2018-06-07T08:42:55.000Z | Warcraft Heroes Beyond Time/Warcraft Heroes Beyond Time/EnergyItem.cpp | SoftCactusTeam/Warcraft_Adventures | 7b44294d44094ce690abe90348dd87f42cdae07d | [
"MIT"
] | 2 | 2018-02-14T08:13:05.000Z | 2018-02-16T19:17:57.000Z | #include "EnergyItem.h"
#include "Scene.h"
#include "Thrall.h"
#include "Application.h"
#include "ModuleRender.h"
EnergyItem::EnergyItem()
{
}
EnergyItem::~EnergyItem()
{
}
bool EnergyItem::Start()
{
return true;
}
bool EnergyItem::Act(ModuleItems::ItemEvent event, float dt)
{
switch (event)
{
case ModuleItems::ItemEvent::PLAYER_HITTED:
App->scene->player->IncreaseEnergy(ModuleItems::energywhenHitted);
break;
}
return true;
}
bool EnergyItem::Draw()
{
return true;
}
bool EnergyItem::printYourStuff(iPoint pos)
{
//The GUI uses this method, fill it in all the items.
iPoint iconPos = { 171 / 2 - 31 / 2 ,50 };
App->render->Blit(App->items->getItemsTexture(), pos.x + iconPos.x, pos.y + iconPos.y, &SDL_Rect(ENERGY_ITEM), 1, 0);
printMyString((char*)Title.data(), { 171 / 2 + pos.x, 100 + pos.y }, true);
printMyString((char*)softDescription.data(), { 171 / 2 + pos.x, 150 + pos.y });
return true;
}
const std::string EnergyItem::myNameIs() const
{
return std::string(Title);
}
| 19.037736 | 118 | 0.683845 | SoftCactusTeam |
991e8d7497ac0af4900c06138616500c5a5df0b2 | 297 | hpp | C++ | lib/systems/simulator/UdpMessageHandlerInterface.hpp | aep/qtsl | 8710cbbf2405ad9147c399d1afea906a80b1fbac | [
"MIT"
] | null | null | null | lib/systems/simulator/UdpMessageHandlerInterface.hpp | aep/qtsl | 8710cbbf2405ad9147c399d1afea906a80b1fbac | [
"MIT"
] | null | null | null | lib/systems/simulator/UdpMessageHandlerInterface.hpp | aep/qtsl | 8710cbbf2405ad9147c399d1afea906a80b1fbac | [
"MIT"
] | null | null | null | #ifndef QTSL_UdpMessageHandlerInterface_H
#define QTSL_UdpMessageHandlerInterface_H
namespace qtsl{
namespace udp{
struct UdpMessage;
};
class UdpMessageHandlerInterface{
public:
virtual void udpMessageHandler(qtsl::udp::UdpMessage * message)=0;
};
};
#endif
| 19.8 | 74 | 0.720539 | aep |
9922a99b0238dfc09a07e514936e3b29593b130c | 28,042 | cpp | C++ | src/hi/hicalendar.cpp | SC-One/HiCalendar | dfda3134dfbde0c7845c4c3e2d41635721511678 | [
"MIT"
] | 30 | 2020-10-30T13:01:10.000Z | 2022-02-04T04:54:11.000Z | src/hi/hicalendar.cpp | Qt-QML/HiCalendar | a9e1f2fcd111f2d5c8eb1af705acef829584b102 | [
"MIT"
] | null | null | null | src/hi/hicalendar.cpp | Qt-QML/HiCalendar | a9e1f2fcd111f2d5c8eb1af705acef829584b102 | [
"MIT"
] | 6 | 2020-10-31T09:38:13.000Z | 2022-02-04T07:20:21.000Z | #include "include/hi/hicalendar.hpp"
////::::::::::::::::::::::::::::::::::::::::::: YearMonthDay
YearMonthDay::YearMonthDay(int _Year, int _Month, int _Day, QObject *parent):
QObject(parent),year(_Year),month(_Month),day(_Day) {}
YearMonthDay::YearMonthDay(const YearMonthDay &other):
QObject(other.parent()),year(other.year),month(other.month),day(other.day) {}
YearMonthDay& YearMonthDay::operator=(const YearMonthDay &other)
{
this->setParent(other.parent());
this->year = other.year;
this->month = other.month;
this->day = other.day;
return *this;
}
bool YearMonthDay::operator !=(const YearMonthDay &other)
{
return (this->parent() != other.parent() || this->year != other.year || this->month != other.month || this->day != other.day);
}
bool YearMonthDay::operator ==(const YearMonthDay &other)
{
return !(*this != other);
}
YearMonthDay::~YearMonthDay() {}
//////::::::::::::::::::::::::::::::::::::::::::: HiCalendarSelectedDayData
HiCalendarDayModel::HiCalendarDayModel(QDate _Date, int _DayOfCustomMonth, int _DayOfCustomWeek, int _DayInCustomWeekOfMonth, bool _IsHoliday , QObject *parent):
QObject(parent),
_date(_Date),
_is_holiday(_IsHoliday)
{
_day_of_custom_month = 1;
_day_of_custom_week = 1;
_day_in_custom_week_of_month = 1;
if (_DayOfCustomMonth > 0 && _DayOfCustomMonth <32)
{
_day_of_custom_month = _DayOfCustomMonth;
}
if(_DayOfCustomWeek > 0 && _DayOfCustomWeek < 8)
{
_day_of_custom_week = _DayOfCustomWeek;
}
if(_DayInCustomWeekOfMonth > 0 && _DayInCustomWeekOfMonth < 7)
{
_day_in_custom_week_of_month = _DayInCustomWeekOfMonth;
}
emit dayModifiedSi();
}
HiCalendarDayModel::HiCalendarDayModel(const HiCalendarDayModel& item):
QObject(item.parent()),
_date(item.getGeorgianDate()),
_day_of_custom_month(item.getDayOfCustomMonth()),
_day_of_custom_week(item.getDayOfCustomWeek()),
_day_in_custom_week_of_month(item.getDayInCustomWeekNOfMonth()),
_is_holiday(item.isHoliday())
{
emit dayModifiedSi();
}
HiCalendarDayModel& HiCalendarDayModel::operator=(const HiCalendarDayModel &other)
{
this->_day_of_custom_month = other.getDayOfCustomMonth();
this->_day_of_custom_week = other.getDayOfCustomWeek();
this->_day_in_custom_week_of_month = other.getDayInCustomWeekNOfMonth();
this->_date = other.getGeorgianDate();
emit dayModifiedSi();
return *this;
}
bool HiCalendarDayModel::operator!=(const HiCalendarDayModel &other) const
{
return (_date != other.getGeorgianDate()
|| _day_of_custom_month != other.getDayOfCustomMonth()
|| _day_of_custom_week != other.getDayOfCustomWeek()
|| _day_in_custom_week_of_month != other.getDayInCustomWeekNOfMonth());
}
bool HiCalendarDayModel::operator==(const HiCalendarDayModel &other) const
{
return !(*this != other);
}
YearMonthDay HiCalendarDayModel::getJalaliDateAsYearMonthDay() const
{
QCalendar calendar(QCalendar::System::Jalali);
QCalendar::YearMonthDay jalali_date = calendar.partsFromDate(_date);
YearMonthDay output{jalali_date.year,jalali_date.month,jalali_date.day,this->parent()};
return output;
}
int HiCalendarDayModel::getJalaliYear() const
{
QCalendar calendar(QCalendar::System::Jalali);
QCalendar::YearMonthDay jalali_date = calendar.partsFromDate(_date);
return jalali_date.year;
}
int HiCalendarDayModel::getJalaliMonth() const
{
QCalendar calendar(QCalendar::System::Jalali);
QCalendar::YearMonthDay jalali_date = calendar.partsFromDate(_date);
return jalali_date.month;
}
int HiCalendarDayModel::getJalaloDay() const
{
QCalendar calendar(QCalendar::System::Jalali);
QCalendar::YearMonthDay jalali_date = calendar.partsFromDate(_date);
return jalali_date.day;
}
YearMonthDay HiCalendarDayModel::getGeorgianDateAsYearMonthDay() const
{
YearMonthDay output{_date.year(),_date.month(),_date.day(),this->parent()};
return output;
}
int HiCalendarDayModel::getGeorgianYear() const
{
return _date.year();
}
int HiCalendarDayModel::getGeorgianMonth() const
{
return _date.month();
}
int HiCalendarDayModel::getGeorgianDay() const
{
return _date.day();
}
YearMonthDay HiCalendarDayModel::getIslamicDateAsYearMonthDay() const
{
QCalendar calendar(QCalendar::System::IslamicCivil);
QCalendar::YearMonthDay islamic_date = calendar.partsFromDate(_date);
YearMonthDay output{islamic_date.year,islamic_date.month,islamic_date.day,this->parent()};
return output;
}
int HiCalendarDayModel::getIslamicYear() const
{
QCalendar calendar(QCalendar::System::IslamicCivil);
QCalendar::YearMonthDay islamic_date = calendar.partsFromDate(_date);
return islamic_date.year;
}
int HiCalendarDayModel::getIslamicMonth() const
{
QCalendar calendar(QCalendar::System::IslamicCivil);
QCalendar::YearMonthDay islamic_date = calendar.partsFromDate(_date);
return islamic_date.month;
}
int HiCalendarDayModel::getIslamicDay() const
{
QCalendar calendar(QCalendar::System::IslamicCivil);
QCalendar::YearMonthDay islamic_date = calendar.partsFromDate(_date);
return islamic_date.day;
}
bool HiCalendarDayModel::isDayOver() const
{
return (QDate::currentDate() > _date);
}
bool HiCalendarDayModel::isToday() const
{
return (_date == QDate::currentDate());
}
bool HiCalendarDayModel::isHoliday() const
{
return _is_holiday;
}
int HiCalendarDayModel::getDayOfCustomMonth() const
{
return _day_of_custom_month;
}
int HiCalendarDayModel::getDayOfCustomWeek() const
{
return _day_of_custom_week;
}
int HiCalendarDayModel::getDayInCustomWeekNOfMonth() const
{
return _day_in_custom_week_of_month;
}
QDate HiCalendarDayModel::getGeorgianDate() const
{
return _date;
}
QString HiCalendarDayModel::toString() const
{
QString output = "{\"jalali_year\":"+ QString::number(getJalaliYear()) + ",\"jalali_month\":"+ QString::number(getJalaliMonth()) + ",\"jalali_day\":"+ QString::number(getJalaloDay()) + ",\"georgian_year\":"+ QString::number(getGeorgianYear()) + ",\"georgian_month\":"+ QString::number(getGeorgianMonth()) + ",\"georgian_day\":"+ QString::number(getGeorgianDay()) + ",\"islamic_year\":"+ QString::number(getIslamicYear()) + ",\"islamic_month\":"+ QString::number(getIslamicMonth()) + ",\"islamic_day\":"+ QString::number(getIslamicDay()) + ",\"is_day_over\":"+ (isDayOver()? "true" : "false") + ",\"is_today\":"+ (isToday()? "true" : "false") + ",\"day_of_custom_month\":"+ QString::number(getDayOfCustomMonth()) + ",\"day_of_custom_week\":"+ QString::number(getDayOfCustomWeek()) + ",\"day_in_custom_week_n_of_month\":"+ QString::number(getDayInCustomWeekNOfMonth())+",\"is_holiday_in_calendar_selected_type\":"+ (isHoliday()?"true":"false") + "}";
return output;
}
HiCalendarDayModel::~HiCalendarDayModel() {}
//////////::::::::::::::::::::::::::::::::::::: Calendar Controller
HiCalendarController::HiCalendarController(HiCalendarController::CalendarTypes _CalendarType, QObject *_Parent):
QObject(_Parent),
_calendar_type(_CalendarType),
_current_selected_day(nullptr)
{
emit calendarTypeChanged(_calendar_type);
}
HiCalendarController::HiCalendarController(const HiCalendarController &_Input):
QObject(_Input.parent()),
_days_of_current_month_list(_Input.getDaysOfCurrentMonth()),
_calendar_type(_Input.getCalendarType()),
_current_selected_day(nullptr)
{
emit calendarTypeChanged(_calendar_type);
}
HiCalendarController::CalendarTypes HiCalendarController::getCalendarType() const
{
return _calendar_type;
}
QString HiCalendarController::currentMonthHeaderInfo() const
{
return _current_month_header_info;
}
const QVariantList HiCalendarController::getDaysOfCurrentMonth() const
{
return _days_of_current_month_list;
}
HiCalendarDayModel* HiCalendarController::getCurrentSelectedDay() const
{
return _current_selected_day;
}
void HiCalendarController::showCurrentSelectedYearMonthDay(QDate _SelectedDate)
{
QStringList jalali_months = {"فروردین" , "اردیبهشت", "خرداد", "تیر", "اَمرداد", "شهریور", "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند"};
QStringList georgian_months = {"January","February","March","April","May","June","July","August","September","October","November","December"};
QStringList islamic_months = {"محرم" , "صفر", "ربیعالاول", "ربیعالثانی", "جمادیالاول", "جمادیالثانی", "رجب", "شعبان", "رمضان", "شوال", "ذیقعده", "ذیحجه"};
int day_of_week = 1;
int day_is_in_week_N_of_month = 0;
int year = 1;
int month = 1;
int day = 1;
if(_SelectedDate == QDate(1,1,1))
{
_SelectedDate = QDate::currentDate();
}
QDate newDate = _SelectedDate;
if(_current_selected_day != nullptr)//is not first
{
clearCurrentDays();
_current_selected_day = nullptr;
}
if (getCalendarType() == HiCalendarController::CalendarTypes::Jalali)
{
QCalendar jalali_calendar(QCalendar::System::Jalali);
QCalendar islamic_calendar(QCalendar::System::IslamicCivil);
int first_georgian_month = 0;
int second_georgian_month = 0;
int first_islamic_month = 0;
int second_islamic_month = 0;
int first_georgian_year = 0;
int second_georgian_year = 0;
int first_islamic_year = 0;
int second_islamic_year = 0;
QCalendar::YearMonthDay jalali_date = jalali_calendar.partsFromDate(_SelectedDate);
year = jalali_date.year;//current selected year as jalali
month = jalali_date.month;//current selected month as jalali
day = jalali_date.day;//current selected day as jalali
if (day > 1)
{
newDate = _SelectedDate.addDays(-(day-1));//first day of selected month as georgian
}
QCalendar::YearMonthDay islamic_date = islamic_calendar.partsFromDate(newDate);
first_georgian_month = newDate.month();
first_georgian_year = newDate.year();
first_islamic_month = islamic_date.month;
first_islamic_year = islamic_date.year;
int day_counter = 1;
while ( jalali_calendar.partsFromDate(newDate).month == month)
{
bool is_holiday = false;
if ( newDate.dayOfWeek() < 6)
{
day_of_week = newDate.dayOfWeek()+2;
}
else
{
day_of_week = newDate.dayOfWeek() % 6 +1;
}
if(day_of_week == 1 || day_is_in_week_N_of_month == 0)
{
day_is_in_week_N_of_month++;
}
islamic_date = islamic_calendar.partsFromDate(newDate);
if(islamic_date.month != first_islamic_month)
{
second_islamic_month = islamic_date.month;
}
if(islamic_date.year != first_islamic_year)
{
second_islamic_year = islamic_date.year;
}
if(newDate.month() != first_georgian_month)
{
second_georgian_month = newDate.month();
}
if(newDate.year() != first_georgian_year)
{
second_georgian_year = newDate.year();
}
//jalali holidays
if (newDate.dayOfWeek() == 5) is_holiday = true;
if (month == 1)
{
if (day_counter >= 1 && day_counter < 5) is_holiday = true;
if (day_counter == 12 || day_counter == 13) is_holiday = true;
}
if (month == 3)
{
if (day_counter == 14 || day_counter == 15) is_holiday = true;
}
if (month == 11 && day_counter == 22) is_holiday = true;
if (month == 12 && (day_counter == 29 || day_counter == 30)) is_holiday = true;
//islamic holidays
if (islamic_date.month == 1)
{
if (islamic_date.day == 9 || islamic_date.day == 10) is_holiday = true;//tasua-ashura
}
if (islamic_date.month == 2)
{
qDebug()<<"=============2";
if (islamic_date.day == 20 || islamic_date.day == 28 || islamic_date.day == 30) is_holiday = true;
if (islamic_date.day == 29)
{
qDebug()<<newDate.toString();
QDate tmpDate = newDate.addDays(1);
qDebug()<<newDate<<" ====> ttt " << tmpDate.toString();
QCalendar::YearMonthDay islamic_date_tmp = islamic_calendar.partsFromDate(tmpDate);
if (islamic_date_tmp.month != 2)
{
is_holiday = true;
}
}
}
if (islamic_date.month == 3)
{
if (islamic_date.day == 8 || islamic_date.day == 17) is_holiday = true;
}
if (islamic_date.month == 6)
{
if (islamic_date.day == 3 ) is_holiday = true;
}
if (islamic_date.month == 7)
{
if (islamic_date.day == 13 || islamic_date.day == 27) is_holiday = true;
}
if (islamic_date.month == 8)
{
if (islamic_date.day == 15) is_holiday = true;
}
if (islamic_date.month == 9)
{
if (islamic_date.day == 19 || islamic_date.day == 21) is_holiday = true;
}
if (islamic_date.month == 10)
{
if (islamic_date.day == 1 || islamic_date.day == 2 || islamic_date.day == 25) is_holiday = true;
}
if (islamic_date.month == 12)
{
if (islamic_date.day == 10 || islamic_date.day == 18) is_holiday = true;
}
HiCalendarDayModel* newDay = new HiCalendarDayModel(newDate, day_counter, day_of_week, day_is_in_week_N_of_month,is_holiday ,this);
this->addDayItem(newDay);
if(newDate == _SelectedDate)
{
_current_selected_day = newDay;
}
newDate = newDate.addDays(1);
day_counter++;
}
_current_month_header_info = jalali_months[month-1] +" "+ QString::number(year) + "\n";
if(second_georgian_year == 0) //same georgian year
{
_current_month_header_info += georgian_months[first_georgian_month-1] + " - " + georgian_months[second_georgian_month-1] + " " + QString::number(first_georgian_year)+"\n";
}
else // different georgian years
{
_current_month_header_info += georgian_months[first_georgian_month-1] + " " + QString::number(first_georgian_year);
_current_month_header_info += " - " + georgian_months[second_georgian_month-1] + " " + QString::number(second_georgian_year)+"\n";
}
if(second_islamic_year == 0) //same islamic year
{
_current_month_header_info += islamic_months[first_islamic_month-1] + " - " + islamic_months[second_islamic_month-1] + " " + QString::number(first_islamic_year);
}
else // different islamic years
{
_current_month_header_info += islamic_months[first_islamic_month-1] + " " + QString::number(first_islamic_year);
_current_month_header_info += " - " + islamic_months[second_islamic_month-1] + " " + QString::number(second_islamic_year);
}
}
else
{
year = _SelectedDate.year();
month = _SelectedDate.month();
day = _SelectedDate.day();
QDate newDate(year,month,1);
int days_of_week_count[8] = {0,0,0,0,0,0,0,0};
while (newDate.month() == month)
{
bool is_holiday = false;
if(getCalendarType() == HiCalendarController::CalendarTypes::EuroGeorgian)
{
day_of_week = newDate.dayOfWeek();
}
else if (getCalendarType() == HiCalendarController::CalendarTypes::UsGeorgian)
{
day_of_week = (newDate.dayOfWeek() % 7) + 1;
}
if(day_of_week == 1 || day_is_in_week_N_of_month == 0)
{
day_is_in_week_N_of_month++;
}
//georgian holidays
days_of_week_count[newDate.dayOfWeek()]++;
if (newDate.dayOfWeek() == 7) is_holiday = true;
if (newDate.month() == 1)
{
if (newDate.day() == 1) is_holiday = true;
if (newDate.dayOfWeek() == 1 && days_of_week_count[newDate.dayOfWeek()] == 3) is_holiday = true;
}
if (newDate.month() == 2)
{
if (newDate.day() == 12) is_holiday = true;
if (newDate.dayOfWeek() == 1 && days_of_week_count[newDate.dayOfWeek()] == 3) is_holiday = true;
}
if (newDate.month() == 5)
{
if (newDate.day() == 5) is_holiday = true;
if (newDate.dayOfWeek() == 1 && (31 - newDate.day() <7)) is_holiday = true;
}
if (newDate.month() == 7)
{
if (newDate.day() == 4) is_holiday = true;
}
if (newDate.month() == 9)
{
if (newDate.day() == 4) is_holiday = true;
if (newDate.dayOfWeek() == 1 && days_of_week_count[newDate.dayOfWeek()] == 1) is_holiday = true;
}
if (newDate.month() == 11)
{
if (newDate.day() == 11) is_holiday = true;
if (newDate.dayOfWeek() == 3 && (30 - newDate.day() <7)) is_holiday = true;
}
if (newDate.month() == 12)
{
if (newDate.day() == 25) is_holiday = true;
}
HiCalendarDayModel* newDay = new HiCalendarDayModel(newDate, newDate.day(), day_of_week, day_is_in_week_N_of_month ,is_holiday,this);
this->addDayItem(newDay);
if(newDate == _SelectedDate)
{
_current_selected_day = newDay;
}
newDate = newDate.addDays(1);
}
_current_month_header_info = georgian_months[month-1] +" - "+ QString::number(year);
}
if (_current_selected_day != nullptr)
{
emit daySelectedSi(_current_selected_day);
}
emit refreshCalendarSi();
}
void HiCalendarController::nextDay()
{
if (_current_selected_day != nullptr && _days_of_current_month_list.length() >0)
{
this->showCurrentSelectedYearMonthDay(_current_selected_day->getGeorgianDate().addDays(1));
}
}
void HiCalendarController::prevDay()
{
if (_current_selected_day != nullptr && _days_of_current_month_list.length() >0)
{
this->showCurrentSelectedYearMonthDay(_current_selected_day->getGeorgianDate().addDays(-1));
}
}
void HiCalendarController::nextMonth()
{
if (_current_selected_day != nullptr && _days_of_current_month_list.length() >0)
{
if (getCalendarType() == HiCalendarController::CalendarTypes::Jalali)
{
QCalendar jalali_calendar(QCalendar::System::Jalali);
QDate newDate = _current_selected_day->getGeorgianDate();
QCalendar::YearMonthDay jalali_date = jalali_calendar.partsFromDate(newDate);
int year = jalali_date.year;
int month = jalali_date.month + 1;
if (month > 12)
{
month = 1;
year++;
}
newDate = jalali_calendar.dateFromParts(year,month,1);
this->showCurrentSelectedYearMonthDay(newDate);
}
else
{
QDate newDate = _current_selected_day->getGeorgianDate().addMonths(1);
newDate.setDate(newDate.year(),newDate.month(),1);
this->showCurrentSelectedYearMonthDay(newDate);
}
}
}
void HiCalendarController::prevMonth()
{
if (_current_selected_day != nullptr && _days_of_current_month_list.length() >0)
{
if (getCalendarType() == HiCalendarController::CalendarTypes::Jalali)
{
QCalendar jalali_calendar(QCalendar::System::Jalali);
QDate newDate = _current_selected_day->getGeorgianDate();
QCalendar::YearMonthDay jalali_date = jalali_calendar.partsFromDate(newDate);
int year = jalali_date.year;
int month = jalali_date.month - 1;
if (month < 1)
{
month = 12;
year--;
}
newDate = jalali_calendar.dateFromParts(year,month,1);
this->showCurrentSelectedYearMonthDay(newDate);
}
else
{
QDate newDate = _current_selected_day->getGeorgianDate().addMonths(-1);
newDate.setDate(newDate.year(),newDate.month(),1);
this->showCurrentSelectedYearMonthDay(newDate);
}
}
}
void HiCalendarController::nextYear()
{
if (_current_selected_day != nullptr && _days_of_current_month_list.length() >0)
{
if (getCalendarType() == HiCalendarController::CalendarTypes::Jalali)
{
QCalendar jalali_calendar(QCalendar::System::Jalali);
QDate newDate = _current_selected_day->getGeorgianDate();
QCalendar::YearMonthDay jalali_date = jalali_calendar.partsFromDate(newDate);
int year = jalali_date.year + 1;
int month = jalali_date.month;
newDate = jalali_calendar.dateFromParts(year,month,1);
this->showCurrentSelectedYearMonthDay(newDate);
}
else
{
QDate newDate = _current_selected_day->getGeorgianDate().addYears(1);
newDate.setDate(newDate.year(),newDate.month(),1);
this->showCurrentSelectedYearMonthDay(newDate);
}
}
}
void HiCalendarController::prevYear()
{
if (_current_selected_day != nullptr && _days_of_current_month_list.length() >0)
{
if (getCalendarType() == HiCalendarController::CalendarTypes::Jalali)
{
QCalendar jalali_calendar(QCalendar::System::Jalali);
QDate newDate = _current_selected_day->getGeorgianDate();
QCalendar::YearMonthDay jalali_date = jalali_calendar.partsFromDate(newDate);
int year = jalali_date.year - 1;
int month = jalali_date.month;
newDate = jalali_calendar.dateFromParts(year,month,1);
this->showCurrentSelectedYearMonthDay(newDate);
}
else
{
QDate newDate = _current_selected_day->getGeorgianDate().addYears(-1);
newDate.setDate(newDate.year(),newDate.month(),1);
this->showCurrentSelectedYearMonthDay(newDate);
}
}
}
void HiCalendarController::addDayItem(HiCalendarDayModel *_Day)
{
if (!_days_of_current_month_list.contains(QVariant::fromValue(_Day)))
{
_days_of_current_month_list.append(QVariant::fromValue(_Day));
}
}
void HiCalendarController::selectDayByClick(HiCalendarDayModel *_Day)
{
QDate selected_date = _Day->getGeorgianDate();
if (_days_of_current_month_list.length() >0)
{
this->showCurrentSelectedYearMonthDay(selected_date);
for (QVariantList::iterator j = _days_of_current_month_list.begin(); j != _days_of_current_month_list.end(); j++)
{
QObject* object = qvariant_cast<QObject*>(*j);
HiCalendarDayModel* day = qobject_cast<HiCalendarDayModel*>(object);
if (day->getGeorgianDate() == selected_date)
{
_current_selected_day = day;
emit daySelectedSi(_current_selected_day);
break;
}
}
}
}
void HiCalendarController::clearCurrentDays()
{
for (QVariantList::iterator j = _days_of_current_month_list.begin(); j != _days_of_current_month_list.end(); j++)
{
QObject* object = qvariant_cast<QObject*>(*j);
HiCalendarDayModel* day = qobject_cast<HiCalendarDayModel*>(object);
day->deleteLater();
}
_days_of_current_month_list.clear();
emit refreshCalendarSi();
}
HiCalendarController &HiCalendarController::operator=(const HiCalendarController &other)
{
this->_days_of_current_month_list = other.getDaysOfCurrentMonth();
this->_calendar_type = other.getCalendarType();
this->_current_selected_day = other.getCurrentSelectedDay();
this->_current_month_header_info = other.currentMonthHeaderInfo();
return *this;
}
bool HiCalendarController::operator!=(const HiCalendarController &other) const
{
return (this->_days_of_current_month_list != other.getDaysOfCurrentMonth()
|| this->_calendar_type != other.getCalendarType()
|| this->_current_selected_day != other.getCurrentSelectedDay()
|| this->_current_month_header_info != other.currentMonthHeaderInfo());
}
bool HiCalendarController::operator==(const HiCalendarController &other) const
{
return !(*this != other);
}
HiCalendarController::~HiCalendarController()
{
this->clearCurrentDays();
}
//////////:::::::::::::::::::::::::::::::::::::::::::::: Hi Calendar Context
HiCalendarContext::HiCalendarContext(QObject *parent) : QObject(parent),_calendar (nullptr) {}
void HiCalendarContext::renewCalendar(QString calendar_type)
{
calendar_type = calendar_type.toLower();
if (calendar_type == "us" || calendar_type == "us_calendar" || calendar_type == "us_georgian_calendar")
{
this->renewCalendar(HiCalendarController::CalendarTypes::UsGeorgian);
}
else if(calendar_type == "euro" || calendar_type == "euro_calendar" || calendar_type == "euro_georgian_calendar")
{
this->renewCalendar(HiCalendarController::CalendarTypes::EuroGeorgian);
}
else if (calendar_type == "jalali" || calendar_type == "jalali_calendar")
{
this->renewCalendar(HiCalendarController::CalendarTypes::Jalali);
}
}
void HiCalendarContext::renewCalendar(HiCalendarController::CalendarTypes calendar_type)
{
bool changed = false;
if (calendar_type == HiCalendarController::CalendarTypes::UsGeorgian)
{
changed = true;
if (_calendar != nullptr) _calendar->deleteLater();
_calendar = new HiCalendarController(HiCalendarController::CalendarTypes::UsGeorgian , this);
}
else if(calendar_type == HiCalendarController::CalendarTypes::EuroGeorgian)
{
changed = true;
if (_calendar != nullptr) _calendar->deleteLater();
_calendar = new HiCalendarController(HiCalendarController::CalendarTypes::EuroGeorgian, this);
}
else if (calendar_type == HiCalendarController::CalendarTypes::Jalali)
{
changed = true;
if (_calendar != nullptr) _calendar->deleteLater();
_calendar = new HiCalendarController(HiCalendarController::CalendarTypes::Jalali, this);
}
if (changed == true && _calendar != nullptr)
{
_calendar->showCurrentSelectedYearMonthDay();
emit calendarChangedSi();
}
}
HiCalendarController* HiCalendarContext::getCalendar()
{
return _calendar;
}
HiCalendarContext::~HiCalendarContext()
{
if (_calendar != nullptr)
{
_calendar->deleteLater();
}
}
| 37.741588 | 954 | 0.61308 | SC-One |
9927a78165656864eb420193b3dc3673c4a5bd6a | 1,686 | cpp | C++ | source/raytracer/implementation/geometry/object/triangle.cpp | danielil/RayTracer | 16682be15d31e9201acd66b4a12ae78c69fbc671 | [
"MIT"
] | null | null | null | source/raytracer/implementation/geometry/object/triangle.cpp | danielil/RayTracer | 16682be15d31e9201acd66b4a12ae78c69fbc671 | [
"MIT"
] | null | null | null | source/raytracer/implementation/geometry/object/triangle.cpp | danielil/RayTracer | 16682be15d31e9201acd66b4a12ae78c69fbc671 | [
"MIT"
] | null | null | null | /**
* The MIT License (MIT)
* Copyright (c) 2017-2017 Daniel Sebastian Iliescu, http://dansil.net
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "raytracer/geometry/object/triangle.hpp"
namespace raytracer::geometry::object
{
std::optional< point > triangle::intersect( const ray& ray ) const
{
// TODO
return {};
}
spatial_vector triangle::normal( const point& intersection_point ) const
{
// TODO
auto normal = intersection_point - center;
normalize( std::begin( normal ), std::end( normal ) );
return normal;
}
const image::channels& triangle::get_channels() const
{
// TODO
return this->channels;
}
} | 32.423077 | 81 | 0.734282 | danielil |
992d5d130d63c83e1a52fe236d3ece50664a82e1 | 2,009 | hpp | C++ | include/scigl_render/scene/cv_camera.hpp | Tuebel/scigl_render | ec790d54ca4a14546348a5dd2f799d5abcc4bd36 | [
"MIT"
] | null | null | null | include/scigl_render/scene/cv_camera.hpp | Tuebel/scigl_render | ec790d54ca4a14546348a5dd2f799d5abcc4bd36 | [
"MIT"
] | null | null | null | include/scigl_render/scene/cv_camera.hpp | Tuebel/scigl_render | ec790d54ca4a14546348a5dd2f799d5abcc4bd36 | [
"MIT"
] | null | null | null | #pragma once
#include <gl3w/GL/gl3w.h>
#include <scigl_render/shader/shader.hpp>
#include <scigl_render/scene/camera_intrinsics.hpp>
#include <scigl_render/scene/pose.hpp>
#include <vector>
namespace scigl_render
{
/*!
A camera has a position in the world (extrinsics) and projection (intrinsic).
The extrinsics and intrinsics are calculated using the OpenCV camera model:
- x-axis points right
- y-axis points down
- z-axis points into the image plane
So use the OpenCV / ROS frame convention to set the extrinsic pose.
*/
class CvCamera
{
public:
/*!
Current pose of the camera in cartesian coordinates according the ROS camera
frame convention (see Header defintion:
http://docs.ros.org/melodic/api/sensor_msgs/html/msg/CameraInfo.html)
*/
QuaternionPose pose;
/*!
Default constructor. Don't forget to set the intrinsics!
*/
CvCamera();
/*!
Constructor with intrinsics
*/
CvCamera(CameraIntrinsics intrinsics);
/*!
The view matrix results by moving the entire scene in the opposite direction
of the camera transformation (passive transformation of the camera). Converts
the OpenCV/ROS extrinsic pose to the OpenGL pose (negate y & z axes).
*/
glm::mat4 get_view_matrix() const;
/*!
The projection matrix based on the intrinsics configured on construction.
*/
glm::mat4 get_projection_matrix() const;
/*!
Sets the view and projection matrix in the shader, given the current values.
The variable names must be: "projection_matrix" and "view_matrix"
*/
void set_in_shader(const Shader &shader) const;
CameraIntrinsics get_intrinsics() const;
void set_intrinsics(CameraIntrinsics intrinsics);
private:
glm::mat4 projection_matrix;
CameraIntrinsics intrinsics;
/*!
Get the projection matrix for the given camera intrinsics.
\return a projection matrix calculated that transforms from view to clipping
space
*/
static glm::mat4 calc_projection_matrix(const CameraIntrinsics &intrinsics);
};
} // namespace scigl_render
| 28.7 | 79 | 0.752613 | Tuebel |
99322fd9da6141454cccef5308d5e23cc4ae3042 | 1,792 | cpp | C++ | test/query_builder_tests.cpp | Malibushko/yatgbotlib | a5109c36c9387aef0e6d15e303d2f3753eef9aac | [
"MIT"
] | 3 | 2020-04-05T23:51:09.000Z | 2020-08-14T07:24:45.000Z | test/query_builder_tests.cpp | Malibushko/yatgbotlib | a5109c36c9387aef0e6d15e303d2f3753eef9aac | [
"MIT"
] | 1 | 2020-07-24T19:46:28.000Z | 2020-07-31T14:49:28.000Z | test/query_builder_tests.cpp | Malibushko/yatgbotlib | a5109c36c9387aef0e6d15e303d2f3753eef9aac | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include "telegram_bot.h"
using namespace telegram;
TEST(QueryBuilder,builder_builtin) {
QueryBuilder builder;
int b = 5;
int c = 6;
bool d = false;
builder << make_named_pair(b) << make_named_pair(c) << make_named_pair(d);
std::string json = builder.getQuery();
std::string expected = "{\"b\":5,\"c\":6,\"d\":false}";
EXPECT_EQ(expected,json);
}
TEST(QueryBuilder,builder_variant) {
QueryBuilder builder;
using variant_type = std::variant<std::string,int,bool>;
variant_type var1 = false;
variant_type var2 = std::string("test");
variant_type var3 = 19;
builder << make_named_pair(var1) << make_named_pair(var2) << make_named_pair(var3);
std::string json = builder.getQuery();
std::string expected = "{\"var1\":false,\"var2\":\"test\",\"var3\":19}";
EXPECT_EQ(expected,json);
}
TEST(QueryBuilder,builder_array) {
QueryBuilder builder;
std::vector<int> vec{1,2,3,4};
builder << make_named_pair(vec);
std::string json = builder.getQuery();
std::string expected = "{\"vec\":[1,2,3,4]}";
EXPECT_EQ(expected,json);
}
struct MetaStruct {
declare_struct
declare_field(int,i);
};
TEST(QueryBuilder,builder_array_complex) {
QueryBuilder builder;
std::vector<MetaStruct> vec{{1},{2},{3}};
builder << make_named_pair(vec);
std::string json = builder.getQuery();
std::string expected = "{\"vec\":[{\"i\":1},{\"i\":2},{\"i\":3}]}";
EXPECT_EQ(expected,json);
}
TEST(QueryBuilder,builder_empty_document) {
QueryBuilder builder;
std::string json = builder.getQuery();
std::string expected = "null";
EXPECT_EQ(expected,json);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 28.903226 | 87 | 0.650112 | Malibushko |
9937f50614e6ba984a31acd400bde0a8bf8dc7e1 | 8,221 | cpp | C++ | ch06/6.exercise.10.cpp | 0p3r4t4/PPPUCPP2nd | cf1bd23bb22ee00a77172e43678b7eaa91f592e0 | [
"MIT"
] | 51 | 2017-03-24T06:08:11.000Z | 2022-03-18T00:28:14.000Z | ch06/6.exercise.10.cpp | 0p3r4t4/PPPUCPP2nd | cf1bd23bb22ee00a77172e43678b7eaa91f592e0 | [
"MIT"
] | 1 | 2019-06-23T07:33:42.000Z | 2019-12-12T13:14:04.000Z | ch06/6.exercise.10.cpp | 0p3r4t4/PPPUCPP2nd | cf1bd23bb22ee00a77172e43678b7eaa91f592e0 | [
"MIT"
] | 25 | 2017-04-07T13:22:45.000Z | 2022-03-18T00:28:15.000Z | // 6.exercise.10.cpp
//
// A permutation is an ordered subset of a set. For example, say you wanted to
// pick a combination to a vault. There are 60 possible numbers, and you need
// three different numbers for the combination. There are P(60,3) permutations
// for the combination, where P is defined by the formula
//
// a!
// P(a,b) = ------,
// (a-b)!
//
// where ! is used as a suffix factorial operator. For example, 4! is
// 4*3*2*1.
//
// Combinations are similar to permutations, except that the order of the
// objects doesn't matter. For example, if you were making a "banana split"
// sundea and wished to use three different flavors of ice cream out of five
// that you had, you wouldn't care if you used a scoop of vanilla at the
// beginning or the end; you would still have used vanilla. The formula for
// combination is
//
// P(a,b)
// C(a,b) = ------.
// b!
//
// Design a program that asks users for two numbers, asks them whether they
// want to calculate permutations or combinations, and prints out the result.
// This will have several parts. Do an analysis of the above requeriments.
// Write exactly what the program will have to do. Then go into design phase.
// Write pseudo code for the program, and break it into sub-components. This
// program should have error checking. Make sure that all erroneous inputs will
// generate good error messages
//
// Comments: See 6.exercise.10.md
#include "std_lib_facilities.h"
const string err_msg_pmul_with_negs = "called with negative integers.";
const string err_msg_nk_precon = "n and k parameters relationship precondition violated.";
const string err_msg_product_overflows = "integer multiplication overflows.";
const string err_msg_eoi = "Unexpected end of input.";
const string err_msg_main_bad_option = "Bad option parsing.";
const string msg_setc_get = "Set cardinality (n)? ";
const string msg_subc_get = "Subset cardinality (n)? ";
const string msg_calc_option = "What type of calculation do you want? (p)ermutation, (c)ombination or (b)oth? ";
const string msg_again_option = "Do you want to perform a new calculation (y/n)? ";
bool is_in(const char c, const vector<char>& v)
// Returns true if character c is contained in vector<char> v and returns false
// otherwise.
{
for (char cv : v)
if (cv == c) return true;
return false;
}
int get_natural(const string& msg)
// Asks the user (printing the message msg) for a positive integer.
// It keeps asking until a positive integer is entered or EOF is reached
// or signaled, in which case it throws an error.
// Tries to read an integer ignoring the rest of the line, whatever it is, and
// despite that read has been successful or not.
{
int n = 0;
for (;;) {
cout << msg;
cin >> n;
if (cin) {
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if (n < 0)
cout << n << " is not a positive integer.\n";
else
return n;
}
else if (!cin.eof()) {
cout << "Your input is not a number.\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
else {
error("get_natural(): " + err_msg_eoi);
}
}
}
char get_option(const string& msg, const vector<char>& v)
// Asks the user (printing the message msg) for a char value (option).
// It keeps asking until the answer is a char value that is present in vector
// v or EOF is reached or signales, in which case it throws and error.
// Only the first character of a line is considered, ignoring the rest of it.
{
char c = 0;
for (;;) {
cout << msg;
cin >> c;
if (cin) {
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if (!is_in(c, v))
cout << c << " is not a valid option.\n";
else
return c;
}
else {
// If cin fails reading a char, I guess the only way is to
// have reached end of input. I could be mistaken, though.
error("get_option(): " + err_msg_eoi);
}
}
}
bool check_pmul(int a, int b)
// Partial implementation not using larger integer type and only for
// positive integers, from https://www.securecoding.cert.org INT32C.
// Is its work to tell if multiplication could
// be performed or not.
// Precondition:
// Both arguments must be positive.
{
if (a < 0 || b < 0)
error("check_pmul(): " + err_msg_pmul_with_negs);
return !( a > (numeric_limits<int>::max() / b) );
}
int perm(int n, int k)
// Calculates the k-permutations of n elements, what we call P(n, k).
// This is not done with the factorial formula expressed in the statement but
// with a limited product. See 6.exercise.10.md for details.
// If either n or k equals zero, the permutation is 1.
//
// Preconditions:
// - n and k must be positive and n >= k. It's very unlikely to happen
// otherwise since we assume it is assured by previous calls to
// get_natural(), but to maintain good habits ...
{
if (n < 0 || k < 0 || n < k)
error("perm(): " + err_msg_nk_precon);
if (n == 0 || k == 0) return 1;
int prod = 1;
for (int i = n-k+1; i <= n; ++i)
if (check_pmul(prod, i))
prod *= i;
else
error("perm(): " + err_msg_product_overflows);
return prod;
}
int comb(int n, int k)
// Calculates the k-combinations of n elements, what we call C(n, k).
// This is not done with the factorial formula expressed in the statement but,
// being the k-combinations of n element also known as the binomial
// coefficient, using the multiplicative formula as stated in
// https://en.wikipedia.org/wiki/Binomial_coefficient#Multiplicative_formula
// If either n or k equals zero, the combination is 1.
//
// Preconditions:
// - n and k must be positive and n >= k. It's very unlikely to happen
// otherwise since we assume it is assured by previous calls to
// get_natural(), but to maintain good habits ...
{
if (n < 0 || k < 0 || n < k)
error("perm(): " + err_msg_nk_precon);
if (n == 0 || k == 0) return 1;
int prod = 1;
for (int i = 1; i <= k; ++i)
if (check_pmul(prod, n+1-i))
// Multiplying first by the numerator ensure the division to have
// no reminder.
prod = (prod * (n+1-i)) / i;
else
error("comb(): " + err_msg_product_overflows);
return prod;
}
int main()
try
{
const vector<char> calc_options = {'p', 'P', 'c', 'C', 'b', 'B'};
const vector<char> again_options = {'y', 'Y', 'n', 'N'};
cout << "Calculator for k-permutation and k-combination of n elements\n"
"without repetition. Beware of large numbers, the calculator\n"
"is very limited.\n";
while (cin) {
cout << endl;
int setc = get_natural(msg_setc_get);
int subc = get_natural(msg_subc_get);
char option = get_option(msg_calc_option, calc_options);
switch(option) {
case 'p':
case 'P':
cout << " P(" << setc << ", " << subc << ") = "
<< perm(setc, subc) << '\n';
break;
case 'c':
case 'C':
cout << " C(" << setc << ", " << subc << ") = "
<< comb(setc, subc) << '\n';
break;
case 'b':
case 'B':
cout << " P(" << setc << ", " << subc << ") = "
<< perm(setc, subc) << '\n';
cout << " C(" << setc << ", " << subc << ") = "
<< comb(setc, subc) << '\n';
break;
default:
error("main(): " + err_msg_main_bad_option);
}
option = get_option(msg_again_option, again_options);
if (option == 'n' || option == 'N') break;
}
cout << "\nBye!\n\n";
return 0;
}
catch(exception& e)
{
cerr << e.what() << '\n';
return 1;
}
catch(...)
{
cerr << "Oops! Unknown exception.\n";
return 2;
}
| 33.971074 | 112 | 0.585452 | 0p3r4t4 |
993c39b4a2928028fd47a4e72fb468df81a7ecff | 2,598 | cpp | C++ | Source/GUI/VintageToggleButton.cpp | grhn/gold-rush-filter | 7b91dc5c44bc1acb46804638c357f8e240becdc3 | [
"MIT"
] | 1 | 2019-09-08T19:57:22.000Z | 2019-09-08T19:57:22.000Z | Source/GUI/VintageToggleButton.cpp | grhn/gold-rush-filter | 7b91dc5c44bc1acb46804638c357f8e240becdc3 | [
"MIT"
] | null | null | null | Source/GUI/VintageToggleButton.cpp | grhn/gold-rush-filter | 7b91dc5c44bc1acb46804638c357f8e240becdc3 | [
"MIT"
] | null | null | null | //
// VintageToggleButton.cpp
// GoldRush
//
// Created by Tommi Gröhn on 26.10.2015.
//
//
#include "VintageToggleButton.h"
VintageToggleButton::VintageToggleButton (Colour baseColour, Colour switchColour) : baseColour (baseColour), switchColour (switchColour)
{
}
void VintageToggleButton::setLabel (String s)
{
label = s;
}
void VintageToggleButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
{
const float w = getWidth();
const float h = getHeight();
const float rounding = 2.0f;
const float edgeSize = 2.0f;
// Draw base
{
Path p;
g.setGradientFill(ColourGradient(Colours::darkgrey, 0, 0,
Colours::black, 0 + w / 8.0, h,
false));
p.addRoundedRectangle (0, 0, w, h,
rounding, rounding,
rounding, rounding,
rounding, rounding);
g.fillPath (p);
g.fillPath (p);
}
// Draw button
{
Path p;
if (getToggleState())
{
g.setGradientFill(ColourGradient(Colours::red, w / 2, h / 3,
Colours::darkred.darker(), 0, h,
true));
p.addRoundedRectangle (edgeSize, edgeSize, w - edgeSize * 2.0, h - edgeSize * 2.0,
rounding, rounding,
rounding, rounding,
rounding, rounding);
g.fillPath (p);
}
else
{
g.setGradientFill(ColourGradient(Colours::red.withBrightness (0.3), 0, 0,
Colours::red.withBrightness (0.1), 0, h,
false));
p.addRoundedRectangle (edgeSize, edgeSize, w - edgeSize * 2.0, h - edgeSize * 2.0,
rounding, rounding,
rounding, rounding,
rounding, rounding);
g.fillPath (p);
}
}
// Draw label on top of button
{
const float margin = 2.0;
g.setFont (goldRushFonts::logoFont.withHeight(14.0f));
g.setColour (Colours::antiquewhite);
g.drawFittedText (getName(), Rectangle<int> (margin, margin, getWidth() - 2.0 * margin, getHeight() - 2.0 * margin),
Justification::centred,
2);
}
}
| 32.475 | 136 | 0.469977 | grhn |
9945af9d2f759ea6e140d9addac71d3923741a56 | 1,534 | cpp | C++ | 2011-codeforces-saratov-school-regional/d_three-sons.cpp | galenhwang/acm-problems | 304e11a144c5589c6d9e493b05ad228f20619686 | [
"MIT"
] | null | null | null | 2011-codeforces-saratov-school-regional/d_three-sons.cpp | galenhwang/acm-problems | 304e11a144c5589c6d9e493b05ad228f20619686 | [
"MIT"
] | null | null | null | 2011-codeforces-saratov-school-regional/d_three-sons.cpp | galenhwang/acm-problems | 304e11a144c5589c6d9e493b05ad228f20619686 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <iostream>
#include <algorithm>
using namespace std;
int get (int accumTotal[], int first, int last) {
int permVal = accumTotal[last];
if (first > 0)
permVal -= accumTotal[first-1];
return permVal;
}
int numWays(int len, int accumTotal[], int sons[]) {
int val = 0;
for(int i = 0; i < len; i++) {
for(int j = i + 1; j < len - 1; j++) {
int perm[3] = { get(accumTotal, 0, i),get(accumTotal, i+1,j),
get(accumTotal, j+1,len-1) };
sort(perm, perm+3);
if(perm[0] == sons[0] && perm[1] == sons[1] && perm[2] == sons[2])
val++;
}
}
return val;
}
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int n, m;
cin >> n >> m;
int count = 0;
int accumRowTotals[n];
int accumColTotals[m];
for (int i = 0; i < n; i++) {
accumRowTotals[i] = 0;
for (int j = 0; j < m; j++) {
if (i == 0) accumColTotals[j] = 0;
int val;
cin >> val;
accumRowTotals[i] += val;
accumColTotals[j] += val;
}
if (i > 0) accumRowTotals[i] += accumRowTotals[i-1];
}
for (int j = 0; j < m; j++) {
if (j > 0) accumColTotals[j] += accumColTotals[j-1];
}
int sons[3];
for (int i = 0; i < 3; i++) {
cin >> sons[i];
}
sort(sons, sons+3);
cout << numWays(m, accumColTotals, sons) + numWays(n, accumRowTotals, sons) << endl;
}
| 26.912281 | 88 | 0.483703 | galenhwang |
994640bbfd3c68da9bda39bdace3ff969b0a97f9 | 177,106 | cc | C++ | src/bin/dhcp4/dhcp4_lexer.cc | mcr/kea | 7fbbfde2a0742a3d579d51ec94fc9b91687fb901 | [
"Apache-2.0"
] | 1 | 2019-08-10T21:52:58.000Z | 2019-08-10T21:52:58.000Z | src/bin/dhcp4/dhcp4_lexer.cc | jxiaobin/kea | 1987a50a458921f9e5ac84cb612782c07f3b601d | [
"Apache-2.0"
] | null | null | null | src/bin/dhcp4/dhcp4_lexer.cc | jxiaobin/kea | 1987a50a458921f9e5ac84cb612782c07f3b601d | [
"Apache-2.0"
] | null | null | null | #line 1 "dhcp4_lexer.cc"
#line 3 "dhcp4_lexer.cc"
#define YY_INT_ALIGNED short int
/* A lexical scanner generated by flex */
/* %not-for-header */
/* %if-c-only */
/* %if-not-reentrant */
#define yy_create_buffer parser4__create_buffer
#define yy_delete_buffer parser4__delete_buffer
#define yy_scan_buffer parser4__scan_buffer
#define yy_scan_string parser4__scan_string
#define yy_scan_bytes parser4__scan_bytes
#define yy_init_buffer parser4__init_buffer
#define yy_flush_buffer parser4__flush_buffer
#define yy_load_buffer_state parser4__load_buffer_state
#define yy_switch_to_buffer parser4__switch_to_buffer
#define yypush_buffer_state parser4_push_buffer_state
#define yypop_buffer_state parser4_pop_buffer_state
#define yyensure_buffer_stack parser4_ensure_buffer_stack
#define yy_flex_debug parser4__flex_debug
#define yyin parser4_in
#define yyleng parser4_leng
#define yylex parser4_lex
#define yylineno parser4_lineno
#define yyout parser4_out
#define yyrestart parser4_restart
#define yytext parser4_text
#define yywrap parser4_wrap
#define yyalloc parser4_alloc
#define yyrealloc parser4_realloc
#define yyfree parser4_free
/* %endif */
/* %endif */
/* %ok-for-header */
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 6
#define YY_FLEX_SUBMINOR_VERSION 4
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
/* %if-c++-only */
/* %endif */
/* %if-c-only */
#ifdef yy_create_buffer
#define parser4__create_buffer_ALREADY_DEFINED
#else
#define yy_create_buffer parser4__create_buffer
#endif
#ifdef yy_delete_buffer
#define parser4__delete_buffer_ALREADY_DEFINED
#else
#define yy_delete_buffer parser4__delete_buffer
#endif
#ifdef yy_scan_buffer
#define parser4__scan_buffer_ALREADY_DEFINED
#else
#define yy_scan_buffer parser4__scan_buffer
#endif
#ifdef yy_scan_string
#define parser4__scan_string_ALREADY_DEFINED
#else
#define yy_scan_string parser4__scan_string
#endif
#ifdef yy_scan_bytes
#define parser4__scan_bytes_ALREADY_DEFINED
#else
#define yy_scan_bytes parser4__scan_bytes
#endif
#ifdef yy_init_buffer
#define parser4__init_buffer_ALREADY_DEFINED
#else
#define yy_init_buffer parser4__init_buffer
#endif
#ifdef yy_flush_buffer
#define parser4__flush_buffer_ALREADY_DEFINED
#else
#define yy_flush_buffer parser4__flush_buffer
#endif
#ifdef yy_load_buffer_state
#define parser4__load_buffer_state_ALREADY_DEFINED
#else
#define yy_load_buffer_state parser4__load_buffer_state
#endif
#ifdef yy_switch_to_buffer
#define parser4__switch_to_buffer_ALREADY_DEFINED
#else
#define yy_switch_to_buffer parser4__switch_to_buffer
#endif
#ifdef yypush_buffer_state
#define parser4_push_buffer_state_ALREADY_DEFINED
#else
#define yypush_buffer_state parser4_push_buffer_state
#endif
#ifdef yypop_buffer_state
#define parser4_pop_buffer_state_ALREADY_DEFINED
#else
#define yypop_buffer_state parser4_pop_buffer_state
#endif
#ifdef yyensure_buffer_stack
#define parser4_ensure_buffer_stack_ALREADY_DEFINED
#else
#define yyensure_buffer_stack parser4_ensure_buffer_stack
#endif
#ifdef yylex
#define parser4_lex_ALREADY_DEFINED
#else
#define yylex parser4_lex
#endif
#ifdef yyrestart
#define parser4_restart_ALREADY_DEFINED
#else
#define yyrestart parser4_restart
#endif
#ifdef yylex_init
#define parser4_lex_init_ALREADY_DEFINED
#else
#define yylex_init parser4_lex_init
#endif
#ifdef yylex_init_extra
#define parser4_lex_init_extra_ALREADY_DEFINED
#else
#define yylex_init_extra parser4_lex_init_extra
#endif
#ifdef yylex_destroy
#define parser4_lex_destroy_ALREADY_DEFINED
#else
#define yylex_destroy parser4_lex_destroy
#endif
#ifdef yyget_debug
#define parser4_get_debug_ALREADY_DEFINED
#else
#define yyget_debug parser4_get_debug
#endif
#ifdef yyset_debug
#define parser4_set_debug_ALREADY_DEFINED
#else
#define yyset_debug parser4_set_debug
#endif
#ifdef yyget_extra
#define parser4_get_extra_ALREADY_DEFINED
#else
#define yyget_extra parser4_get_extra
#endif
#ifdef yyset_extra
#define parser4_set_extra_ALREADY_DEFINED
#else
#define yyset_extra parser4_set_extra
#endif
#ifdef yyget_in
#define parser4_get_in_ALREADY_DEFINED
#else
#define yyget_in parser4_get_in
#endif
#ifdef yyset_in
#define parser4_set_in_ALREADY_DEFINED
#else
#define yyset_in parser4_set_in
#endif
#ifdef yyget_out
#define parser4_get_out_ALREADY_DEFINED
#else
#define yyget_out parser4_get_out
#endif
#ifdef yyset_out
#define parser4_set_out_ALREADY_DEFINED
#else
#define yyset_out parser4_set_out
#endif
#ifdef yyget_leng
#define parser4_get_leng_ALREADY_DEFINED
#else
#define yyget_leng parser4_get_leng
#endif
#ifdef yyget_text
#define parser4_get_text_ALREADY_DEFINED
#else
#define yyget_text parser4_get_text
#endif
#ifdef yyget_lineno
#define parser4_get_lineno_ALREADY_DEFINED
#else
#define yyget_lineno parser4_get_lineno
#endif
#ifdef yyset_lineno
#define parser4_set_lineno_ALREADY_DEFINED
#else
#define yyset_lineno parser4_set_lineno
#endif
#ifdef yywrap
#define parser4_wrap_ALREADY_DEFINED
#else
#define yywrap parser4_wrap
#endif
/* %endif */
#ifdef yyalloc
#define parser4_alloc_ALREADY_DEFINED
#else
#define yyalloc parser4_alloc
#endif
#ifdef yyrealloc
#define parser4_realloc_ALREADY_DEFINED
#else
#define yyrealloc parser4_realloc
#endif
#ifdef yyfree
#define parser4_free_ALREADY_DEFINED
#else
#define yyfree parser4_free
#endif
/* %if-c-only */
#ifdef yytext
#define parser4_text_ALREADY_DEFINED
#else
#define yytext parser4_text
#endif
#ifdef yyleng
#define parser4_leng_ALREADY_DEFINED
#else
#define yyleng parser4_leng
#endif
#ifdef yyin
#define parser4_in_ALREADY_DEFINED
#else
#define yyin parser4_in
#endif
#ifdef yyout
#define parser4_out_ALREADY_DEFINED
#else
#define yyout parser4_out
#endif
#ifdef yy_flex_debug
#define parser4__flex_debug_ALREADY_DEFINED
#else
#define yy_flex_debug parser4__flex_debug
#endif
#ifdef yylineno
#define parser4_lineno_ALREADY_DEFINED
#else
#define yylineno parser4_lineno
#endif
/* %endif */
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
/* %if-c-only */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
/* %endif */
/* %if-tables-serialization */
/* %endif */
/* end standard C headers. */
/* %if-c-or-c++ */
/* flex integer type definitions */
#ifndef FLEXINT_H
#define FLEXINT_H
/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
* if you want the limit (max/min) macros for int types.
*/
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif
#include <inttypes.h>
typedef int8_t flex_int8_t;
typedef uint8_t flex_uint8_t;
typedef int16_t flex_int16_t;
typedef uint16_t flex_uint16_t;
typedef int32_t flex_int32_t;
typedef uint32_t flex_uint32_t;
#else
typedef signed char flex_int8_t;
typedef short int flex_int16_t;
typedef int flex_int32_t;
typedef unsigned char flex_uint8_t;
typedef unsigned short int flex_uint16_t;
typedef unsigned int flex_uint32_t;
/* Limits of integral types. */
#ifndef INT8_MIN
#define INT8_MIN (-128)
#endif
#ifndef INT16_MIN
#define INT16_MIN (-32767-1)
#endif
#ifndef INT32_MIN
#define INT32_MIN (-2147483647-1)
#endif
#ifndef INT8_MAX
#define INT8_MAX (127)
#endif
#ifndef INT16_MAX
#define INT16_MAX (32767)
#endif
#ifndef INT32_MAX
#define INT32_MAX (2147483647)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX (255U)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (4294967295U)
#endif
#ifndef SIZE_MAX
#define SIZE_MAX (~(size_t)0)
#endif
#endif /* ! C99 */
#endif /* ! FLEXINT_H */
/* %endif */
/* begin standard C++ headers. */
/* %if-c++-only */
/* %endif */
/* TODO: this is always defined, so inline it */
#define yyconst const
#if defined(__GNUC__) && __GNUC__ >= 3
#define yynoreturn __attribute__((__noreturn__))
#else
#define yynoreturn
#endif
/* %not-for-header */
/* Returned upon end-of-file. */
#define YY_NULL 0
/* %ok-for-header */
/* %not-for-header */
/* Promotes a possibly negative, possibly signed char to an
* integer in range [0..255] for use as an array index.
*/
#define YY_SC_TO_UI(c) ((YY_CHAR) (c))
/* %ok-for-header */
/* %if-reentrant */
/* %endif */
/* %if-not-reentrant */
/* %endif */
/* Enter a start condition. This macro really ought to take a parameter,
* but we do it the disgusting crufty way forced on us by the ()-less
* definition of BEGIN.
*/
#define BEGIN (yy_start) = 1 + 2 *
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START (((yy_start) - 1) / 2)
#define YYSTATE YY_START
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
/* Special action meaning "start processing a new file". */
#define YY_NEW_FILE yyrestart( yyin )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
#ifndef YY_BUF_SIZE
#ifdef __ia64__
/* On IA-64, the buffer size is 16k, not 8k.
* Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case.
* Ditto for the __ia64__ case accordingly.
*/
#define YY_BUF_SIZE 32768
#else
#define YY_BUF_SIZE 16384
#endif /* __ia64__ */
#endif
/* The state buf must be large enough to hold one state per character in the main buffer.
*/
#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
#ifndef YY_TYPEDEF_YY_BUFFER_STATE
#define YY_TYPEDEF_YY_BUFFER_STATE
typedef struct yy_buffer_state *YY_BUFFER_STATE;
#endif
#ifndef YY_TYPEDEF_YY_SIZE_T
#define YY_TYPEDEF_YY_SIZE_T
typedef size_t yy_size_t;
#endif
/* %if-not-reentrant */
extern int yyleng;
/* %endif */
/* %if-c-only */
/* %if-not-reentrant */
extern FILE *yyin, *yyout;
/* %endif */
/* %endif */
#define EOB_ACT_CONTINUE_SCAN 0
#define EOB_ACT_END_OF_FILE 1
#define EOB_ACT_LAST_MATCH 2
#define YY_LESS_LINENO(n)
#define YY_LINENO_REWIND_TO(ptr)
/* Return all but the first "n" matched characters back to the input stream. */
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
*yy_cp = (yy_hold_char); \
YY_RESTORE_YY_MORE_OFFSET \
(yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
YY_DO_BEFORE_ACTION; /* set up yytext again */ \
} \
while ( 0 )
#define unput(c) yyunput( c, (yytext_ptr) )
#ifndef YY_STRUCT_YY_BUFFER_STATE
#define YY_STRUCT_YY_BUFFER_STATE
struct yy_buffer_state
{
/* %if-c-only */
FILE *yy_input_file;
/* %endif */
/* %if-c++-only */
/* %endif */
char *yy_ch_buf; /* input buffer */
char *yy_buf_pos; /* current position in input buffer */
/* Size of input buffer in bytes, not including room for EOB
* characters.
*/
int yy_buf_size;
/* Number of characters read into yy_ch_buf, not including EOB
* characters.
*/
int yy_n_chars;
/* Whether we "own" the buffer - i.e., we know we created it,
* and can realloc() it to grow it, and should free() it to
* delete it.
*/
int yy_is_our_buffer;
/* Whether this is an "interactive" input source; if so, and
* if we're using stdio for input, then we want to use getc()
* instead of fread(), to make sure we stop fetching input after
* each newline.
*/
int yy_is_interactive;
/* Whether we're considered to be at the beginning of a line.
* If so, '^' rules will be active on the next match, otherwise
* not.
*/
int yy_at_bol;
int yy_bs_lineno; /**< The line count. */
int yy_bs_column; /**< The column count. */
/* Whether to try to fill the input buffer when we reach the
* end of it.
*/
int yy_fill_buffer;
int yy_buffer_status;
#define YY_BUFFER_NEW 0
#define YY_BUFFER_NORMAL 1
/* When an EOF's been seen but there's still some text to process
* then we mark the buffer as YY_EOF_PENDING, to indicate that we
* shouldn't try reading from the input source any more. We might
* still have a bunch of tokens to match, though, because of
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
* (via yyrestart()), so that the user can continue scanning by
* just pointing yyin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
/* %if-c-only Standard (non-C++) definition */
/* %not-for-header */
/* %if-not-reentrant */
/* Stack of input buffers. */
static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */
static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */
static YY_BUFFER_STATE * yy_buffer_stack = NULL; /**< Stack as an array. */
/* %endif */
/* %ok-for-header */
/* %endif */
/* We provide macros for accessing buffer states in case in the
* future we want to put the buffer states in a more general
* "scanner state".
*
* Returns the top of the stack, or NULL.
*/
#define YY_CURRENT_BUFFER ( (yy_buffer_stack) \
? (yy_buffer_stack)[(yy_buffer_stack_top)] \
: NULL)
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)]
/* %if-c-only Standard (non-C++) definition */
/* %if-not-reentrant */
/* %not-for-header */
/* yy_hold_char holds the character lost when yytext is formed. */
static char yy_hold_char;
static int yy_n_chars; /* number of characters read into yy_ch_buf */
int yyleng;
/* Points to current character in buffer. */
static char *yy_c_buf_p = NULL;
static int yy_init = 0; /* whether we need to initialize */
static int yy_start = 0; /* start state number */
/* Flag which is used to allow yywrap()'s to do buffer switches
* instead of setting up a fresh yyin. A bit of a hack ...
*/
static int yy_did_buffer_switch_on_eof;
/* %ok-for-header */
/* %endif */
void yyrestart ( FILE *input_file );
void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer );
YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size );
void yy_delete_buffer ( YY_BUFFER_STATE b );
void yy_flush_buffer ( YY_BUFFER_STATE b );
void yypush_buffer_state ( YY_BUFFER_STATE new_buffer );
void yypop_buffer_state ( void );
static void yyensure_buffer_stack ( void );
static void yy_load_buffer_state ( void );
static void yy_init_buffer ( YY_BUFFER_STATE b, FILE *file );
#define YY_FLUSH_BUFFER yy_flush_buffer( YY_CURRENT_BUFFER )
YY_BUFFER_STATE yy_scan_buffer ( char *base, yy_size_t size );
YY_BUFFER_STATE yy_scan_string ( const char *yy_str );
YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len );
/* %endif */
void *yyalloc ( yy_size_t );
void *yyrealloc ( void *, yy_size_t );
void yyfree ( void * );
#define yy_new_buffer yy_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! YY_CURRENT_BUFFER ){ \
yyensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer( yyin, YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
#define yy_set_bol(at_bol) \
{ \
if ( ! YY_CURRENT_BUFFER ){\
yyensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer( yyin, YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
/* %% [1.0] yytext/yyin/yyout/yy_state_type/yylineno etc. def's & init go here */
/* Begin user sect3 */
#define parser4_wrap() (/*CONSTCOND*/1)
#define YY_SKIP_YYWRAP
#define FLEX_DEBUG
typedef flex_uint8_t YY_CHAR;
FILE *yyin = NULL, *yyout = NULL;
typedef int yy_state_type;
extern int yylineno;
int yylineno = 1;
extern char *yytext;
#ifdef yytext_ptr
#undef yytext_ptr
#endif
#define yytext_ptr yytext
/* %% [1.5] DFA */
/* %if-c-only Standard (non-C++) definition */
static yy_state_type yy_get_previous_state ( void );
static yy_state_type yy_try_NUL_trans ( yy_state_type current_state );
static int yy_get_next_buffer ( void );
static void yynoreturn yy_fatal_error ( const char* msg );
/* %endif */
/* Done after the current pattern has been matched and before the
* corresponding action - sets up yytext.
*/
#define YY_DO_BEFORE_ACTION \
(yytext_ptr) = yy_bp; \
/* %% [2.0] code to fiddle yytext and yyleng for yymore() goes here \ */\
yyleng = (int) (yy_cp - yy_bp); \
(yy_hold_char) = *yy_cp; \
*yy_cp = '\0'; \
/* %% [3.0] code to copy yytext_ptr to yytext[] goes here, if %array \ */\
(yy_c_buf_p) = yy_cp;
/* %% [4.0] data tables for the DFA and the user's section 1 definitions go here */
#define YY_NUM_RULES 175
#define YY_END_OF_BUFFER 176
/* This struct is not used in this scanner,
but its presence is necessary. */
struct yy_trans_info
{
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
static const flex_int16_t yy_accept[1468] =
{ 0,
168, 168, 0, 0, 0, 0, 0, 0, 0, 0,
176, 174, 10, 11, 174, 1, 168, 165, 168, 168,
174, 167, 166, 174, 174, 174, 174, 174, 161, 162,
174, 174, 174, 163, 164, 5, 5, 5, 174, 174,
174, 10, 11, 0, 0, 157, 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, 1,
168, 168, 0, 167, 168, 3, 2, 6, 0, 168,
0, 0, 0, 0, 0, 0, 4, 0, 0, 9,
0, 158, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 160, 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,
0, 0, 0, 0, 0, 0, 0, 0, 2, 0,
0, 0, 0, 0, 0, 0, 8, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 159, 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, 67, 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, 173, 171, 0,
170, 169, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 137, 0, 136, 0, 0, 73, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 34,
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, 70, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 17,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 18, 0, 0, 0, 0, 172, 169, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 138,
0, 0, 140, 0, 0, 0, 0, 0, 0, 0,
0, 74, 0, 0, 0, 0, 0, 0, 59, 0,
0, 0, 0, 0, 91, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 37, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 58, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 62, 0, 38,
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, 88, 30, 0, 0, 35,
0, 0, 0, 0, 0, 0, 0, 0, 12, 145,
0, 142, 0, 141, 0, 0, 0, 101, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
81, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 32, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 61, 0, 0, 0,
0, 0, 0, 0, 0, 102, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 97, 0,
0, 0, 0, 0, 0, 0, 7, 0, 0, 143,
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,
72, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 83,
0, 0, 0, 0, 0, 0, 0, 0, 79, 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, 65, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 76, 0, 0, 0,
0, 0, 0, 0, 0, 64, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 95, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 107, 77,
0, 0, 0, 0, 82, 31, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 39, 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, 54, 0, 0, 0, 0, 0, 0,
0, 0, 0, 146, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 69, 0, 0, 0, 0, 0,
0, 0, 0, 0, 96, 0, 0, 0, 0, 0,
42, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 36,
0, 0, 0, 29, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 84, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 93, 0, 0, 0, 0, 0, 0, 0, 0,
120, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 66, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
23, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 125, 0, 0, 123, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 150, 0,
0, 0, 0, 0, 0, 94, 0, 0, 0, 0,
0, 0, 98, 80, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 92,
22, 0, 103, 0, 0, 0, 0, 0, 0, 0,
0, 129, 0, 0, 0, 0, 56, 0, 0, 0,
0, 0, 106, 33, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 53,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 60, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 100, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 154, 0, 57,
71, 0, 0, 0, 0, 0, 0, 0, 0, 0,
50, 0, 0, 0, 0, 0, 0, 0, 126, 0,
124, 0, 118, 117, 0, 46, 0, 21, 0, 0,
0, 0, 0, 139, 0, 0, 87, 0, 0, 0,
0, 0, 0, 0, 0, 0, 115, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 104, 15,
0, 40, 0, 0, 0, 0, 0, 128, 0, 0,
0, 0, 0, 0, 51, 0, 0, 99, 0, 0,
0, 0, 90, 0, 0, 0, 0, 0, 0, 63,
0, 148, 0, 147, 0, 153, 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, 14, 0, 0, 45,
0, 0, 0, 0, 156, 85, 27, 0, 0, 47,
116, 0, 0, 0, 151, 121, 0, 0, 0, 0,
0, 0, 0, 0, 25, 0, 0, 24, 0, 127,
0, 0, 0, 0, 0, 78, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 49,
0, 0, 0, 41, 0, 0, 0, 0, 0, 0,
0, 105, 0, 0, 0, 26, 0, 152, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 44,
0, 0, 20, 155, 55, 0, 149, 144, 28, 0,
0, 16, 0, 0, 133, 0, 0, 0, 0, 0,
0, 113, 0, 89, 0, 0, 0, 0, 0, 0,
0, 0, 68, 0, 0, 0, 0, 0, 0, 0,
0, 134, 13, 0, 0, 0, 0, 0, 122, 0,
0, 0, 0, 0, 0, 119, 0, 0, 0, 0,
0, 112, 0, 19, 0, 130, 0, 0, 0, 0,
0, 0, 0, 0, 111, 0, 0, 48, 0, 0,
43, 132, 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, 131, 0, 86,
0, 0, 0, 0, 0, 0, 109, 114, 52, 0,
0, 0, 0, 108, 0, 0, 135, 0, 0, 0,
0, 0, 75, 0, 0, 110, 0
} ;
static const YY_CHAR yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 2, 3,
1, 1, 2, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 4, 5, 6, 7, 5, 5, 5, 5, 5,
5, 8, 9, 10, 11, 12, 13, 14, 14, 14,
14, 15, 14, 16, 14, 14, 14, 17, 5, 18,
5, 19, 20, 5, 21, 22, 23, 24, 25, 26,
5, 27, 5, 28, 5, 29, 5, 30, 31, 32,
5, 33, 34, 35, 36, 37, 38, 5, 39, 5,
40, 41, 42, 5, 43, 5, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
58, 59, 60, 61, 62, 63, 64, 65, 66, 67,
68, 69, 70, 5, 71, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5
} ;
static const YY_CHAR yy_meta[72] =
{ 0,
1, 1, 2, 3, 3, 4, 3, 3, 3, 3,
3, 3, 3, 5, 5, 5, 3, 3, 3, 3,
5, 5, 5, 5, 5, 5, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 5, 5, 5, 5, 5, 5, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3
} ;
static const flex_int16_t yy_base[1480] =
{ 0,
0, 70, 19, 29, 41, 49, 52, 58, 87, 95,
1830, 1831, 32, 1826, 141, 0, 201, 1831, 206, 88,
11, 213, 1831, 1808, 114, 25, 2, 6, 1831, 1831,
73, 11, 17, 1831, 1831, 1831, 104, 1814, 1769, 0,
1806, 107, 1821, 217, 247, 1831, 1765, 185, 1764, 1770,
93, 58, 1762, 91, 211, 195, 14, 273, 195, 1761,
181, 275, 207, 211, 76, 68, 188, 1770, 232, 219,
296, 284, 280, 1753, 204, 302, 322, 305, 1772, 0,
349, 357, 370, 377, 362, 1831, 0, 1831, 301, 342,
296, 325, 201, 346, 359, 224, 1831, 1769, 1808, 1831,
353, 1831, 390, 1797, 357, 1755, 1765, 369, 220, 1760,
362, 288, 364, 374, 221, 1803, 0, 441, 366, 1747,
1744, 1748, 1744, 1752, 360, 1748, 1737, 1738, 76, 1754,
1737, 1746, 1746, 365, 1737, 365, 1738, 1736, 357, 1782,
1786, 1728, 1779, 1721, 1744, 1741, 1741, 1735, 268, 1728,
1721, 1726, 1720, 371, 1731, 1724, 1715, 1714, 1728, 379,
1714, 384, 1730, 1707, 415, 387, 419, 1728, 1725, 1726,
1724, 390, 1706, 1708, 420, 1700, 1717, 1709, 0, 386,
439, 425, 396, 440, 453, 1708, 1831, 0, 1751, 460,
1698, 1701, 437, 452, 1709, 458, 1752, 466, 1751, 462,
1750, 1831, 506, 1749, 472, 1710, 1702, 1689, 1705, 1702,
1701, 1692, 448, 1741, 1735, 1701, 1680, 1688, 1683, 1697,
1693, 1681, 1693, 1693, 1684, 1668, 1672, 1685, 1687, 1684,
1676, 1666, 1684, 1831, 1679, 1682, 1663, 1662, 1712, 1661,
1671, 1674, 496, 1670, 1658, 1669, 1705, 1652, 1708, 1645,
1660, 489, 1650, 1666, 1647, 1646, 1652, 1643, 1642, 1649,
1697, 1655, 1654, 1648, 77, 1655, 1650, 1642, 1632, 1647,
1646, 1641, 1645, 1626, 1642, 1628, 1634, 1641, 1629, 492,
1622, 1636, 1677, 1638, 485, 1629, 477, 1831, 1831, 485,
1831, 1831, 1616, 0, 456, 473, 1618, 520, 490, 1672,
1625, 484, 1831, 1670, 1831, 1664, 548, 1831, 474, 1606,
1615, 1661, 1607, 1613, 1663, 1620, 1615, 1618, 479, 1831,
1616, 1658, 1613, 1610, 528, 1616, 1654, 1648, 1603, 1598,
1595, 1644, 1603, 1592, 1608, 1640, 1588, 554, 1602, 1587,
1600, 1587, 1597, 1592, 1599, 1594, 1590, 496, 1588, 1591,
1586, 1582, 1630, 488, 1624, 1831, 1623, 1575, 1574, 1573,
1566, 1568, 1572, 1561, 1574, 518, 1619, 1574, 1571, 1831,
1574, 1563, 1563, 1575, 518, 1550, 1551, 1572, 529, 1554,
1603, 1550, 1564, 1563, 1549, 1561, 1560, 1559, 1558, 380,
1599, 1598, 1831, 1542, 1541, 572, 1554, 1831, 1831, 1553,
0, 1542, 1534, 525, 1539, 1590, 1589, 1547, 1587, 1831,
1535, 1585, 1831, 556, 603, 542, 1584, 1528, 1539, 1535,
1523, 1831, 1528, 1534, 1537, 1536, 1523, 1522, 1831, 1524,
1521, 538, 1519, 1521, 1831, 1529, 1526, 1511, 1524, 1519,
578, 1526, 1514, 1507, 1556, 1831, 1505, 1521, 1553, 1516,
1513, 1514, 1516, 1548, 1501, 1496, 1495, 1544, 1490, 1505,
1483, 1490, 1495, 1543, 1831, 1490, 1486, 1484, 1493, 1487,
1494, 1478, 1478, 1488, 1491, 1480, 1475, 1831, 1530, 1831,
1474, 1485, 1470, 1475, 1484, 1478, 1472, 1481, 1521, 1515,
1479, 1462, 1462, 1457, 1477, 1452, 1458, 1457, 1465, 1469,
1452, 1508, 1450, 1464, 1453, 1831, 1831, 1453, 1451, 1831,
1462, 1496, 1458, 0, 1442, 1459, 1497, 1447, 1831, 1831,
1444, 1831, 1450, 1831, 551, 569, 595, 1831, 1447, 1446,
1434, 1485, 1432, 1483, 1430, 1429, 1436, 1429, 1441, 1440,
1440, 1422, 1427, 1468, 1435, 1427, 1470, 1416, 1432, 1431,
1831, 1416, 1413, 1469, 1426, 1418, 1424, 1415, 1423, 1408,
1424, 1406, 1420, 520, 1402, 1396, 1401, 1416, 1413, 1414,
1411, 1452, 1409, 1831, 1395, 1397, 1406, 1404, 1441, 1440,
1393, 562, 1402, 1385, 1386, 1383, 1831, 1397, 1376, 1395,
1387, 1430, 1384, 1391, 1427, 1831, 1374, 1388, 1372, 1386,
1389, 1370, 1420, 1419, 1418, 1365, 1416, 1415, 1831, 14,
1377, 1377, 1375, 1358, 1363, 1365, 1831, 1371, 1361, 1831,
1406, 1354, 1409, 568, 501, 1352, 1350, 1357, 1400, 562,
1404, 544, 1398, 1397, 1396, 1350, 1340, 1393, 1346, 1354,
1355, 1389, 1352, 1346, 1333, 1341, 1384, 1388, 1345, 1344,
1831, 1345, 1338, 1327, 1340, 1343, 1338, 1339, 1336, 1335,
1331, 1337, 1332, 1373, 1372, 1322, 1312, 552, 1369, 1831,
1368, 1317, 1309, 1310, 1359, 1322, 1309, 1320, 1831, 1308,
1317, 1316, 1316, 1356, 1299, 1308, 1313, 1290, 1294, 1345,
1309, 1291, 1301, 1341, 1340, 1339, 1286, 1337, 1301, 580,
582, 1278, 1288, 579, 1831, 1338, 1284, 1294, 1294, 1277,
1282, 1286, 1276, 1288, 1291, 1328, 1831, 1322, 578, 1284,
15, 20, 86, 175, 242, 1831, 274, 374, 536, 561,
559, 578, 575, 576, 575, 574, 589, 585, 640, 605,
595, 611, 601, 1831, 611, 611, 604, 615, 613, 656,
600, 602, 617, 604, 662, 621, 607, 610, 1831, 1831,
620, 625, 630, 618, 1831, 1831, 632, 619, 613, 618,
636, 623, 671, 624, 674, 625, 681, 1831, 628, 632,
627, 685, 640, 630, 631, 627, 640, 651, 635, 653,
648, 649, 651, 644, 646, 647, 647, 649, 664, 703,
662, 667, 644, 1831, 669, 659, 704, 664, 654, 669,
670, 657, 671, 1831, 690, 698, 667, 662, 715, 680,
684, 723, 673, 668, 680, 675, 676, 672, 681, 676,
732, 691, 692, 683, 1831, 685, 696, 681, 697, 692,
737, 706, 690, 691, 1831, 707, 710, 693, 750, 695,
1831, 712, 715, 695, 713, 751, 711, 707, 702, 720,
719, 720, 706, 721, 713, 720, 710, 728, 713, 1831,
721, 727, 772, 1831, 723, 728, 770, 723, 735, 729,
734, 732, 730, 732, 742, 785, 731, 731, 788, 734,
746, 1831, 734, 742, 740, 745, 757, 741, 746, 756,
757, 762, 801, 760, 776, 781, 763, 761, 757, 809,
754, 1831, 754, 774, 763, 768, 775, 816, 817, 766,
1831, 814, 763, 766, 765, 785, 782, 787, 788, 774,
782, 791, 771, 788, 795, 835, 1831, 836, 837, 790,
800, 802, 791, 787, 794, 803, 846, 795, 793, 795,
812, 851, 803, 802, 808, 806, 804, 857, 858, 854,
1831, 818, 811, 802, 821, 809, 819, 816, 821, 817,
830, 830, 1831, 814, 815, 1831, 816, 874, 815, 834,
835, 832, 818, 839, 838, 822, 827, 845, 1831, 835,
868, 859, 889, 831, 853, 1831, 836, 838, 855, 853,
845, 849, 1831, 1831, 859, 859, 895, 844, 897, 846,
904, 849, 860, 852, 858, 854, 873, 874, 875, 1831,
1831, 874, 1831, 859, 861, 880, 870, 863, 875, 917,
883, 1831, 875, 925, 868, 927, 1831, 928, 872, 878,
885, 927, 1831, 1831, 877, 879, 893, 898, 881, 938,
897, 898, 899, 937, 891, 896, 945, 895, 947, 1831,
896, 949, 950, 892, 952, 913, 954, 898, 910, 915,
901, 931, 960, 1831, 919, 912, 963, 912, 927, 914,
910, 926, 931, 918, 914, 972, 927, 932, 1831, 933,
926, 935, 936, 933, 923, 926, 926, 931, 984, 985,
930, 988, 984, 927, 942, 935, 994, 1831, 949, 1831,
1831, 954, 946, 956, 942, 943, 1002, 948, 958, 1006,
1831, 956, 956, 958, 960, 1011, 954, 957, 1831, 976,
1831, 960, 1831, 1831, 974, 1831, 968, 1831, 1018, 969,
1020, 1021, 1003, 1831, 1023, 982, 1831, 970, 978, 972,
971, 974, 974, 975, 982, 972, 1831, 994, 980, 981,
996, 996, 999, 999, 996, 1038, 1002, 995, 1831, 1831,
1005, 1831, 1002, 1007, 1008, 1005, 1047, 1831, 998, 999,
999, 1005, 1004, 1015, 1831, 1054, 1003, 1831, 1004, 1004,
1006, 1012, 1831, 1014, 1066, 1017, 1020, 1069, 1032, 1831,
1029, 1831, 1026, 1831, 1049, 1831, 1074, 1075, 1076, 1035,
1021, 1079, 1080, 1035, 1025, 1030, 1084, 1085, 1081, 1046,
1042, 1084, 1034, 1039, 1037, 1094, 1052, 1096, 1056, 1098,
1061, 1051, 1045, 1061, 1061, 1105, 1049, 1066, 1065, 1049,
1105, 1106, 1055, 1108, 1073, 1074, 1831, 1074, 1061, 1831,
1072, 1119, 1079, 1092, 1831, 1831, 1831, 1066, 1123, 1831,
1831, 1072, 1070, 1084, 1831, 1831, 1074, 1123, 1068, 1073,
1131, 1081, 1091, 1092, 1831, 1135, 1090, 1831, 1137, 1831,
1082, 1097, 1085, 1100, 1104, 1831, 1138, 1106, 1099, 1108,
1090, 1097, 1151, 1112, 1111, 1154, 1155, 1156, 1107, 1831,
1158, 1159, 1160, 1831, 1110, 1110, 1163, 1109, 1108, 1166,
1121, 1831, 1163, 1116, 1113, 1831, 1127, 1831, 1130, 1173,
1128, 1175, 1136, 1119, 1121, 1118, 1134, 1135, 1144, 1831,
1134, 1184, 1831, 1831, 1831, 1180, 1831, 1831, 1831, 1181,
1138, 1831, 1136, 1143, 1831, 1140, 1145, 1143, 1193, 1194,
1139, 1831, 1154, 1831, 1155, 1145, 1157, 1200, 1144, 1152,
1153, 1166, 1831, 1165, 1153, 1207, 1168, 1159, 1168, 1170,
1174, 1831, 1831, 1213, 1158, 1215, 1175, 1217, 1831, 1213,
1177, 1178, 1165, 1160, 1181, 1831, 1182, 1183, 1226, 1185,
1188, 1831, 1229, 1831, 1192, 1831, 1174, 1232, 1233, 1178,
1195, 1181, 1181, 1183, 1831, 1188, 1198, 1831, 1184, 1196,
1831, 1831, 1201, 1195, 1199, 1190, 1242, 1191, 1199, 1208,
1201, 1196, 1211, 1202, 1209, 1196, 1211, 1216, 1259, 1218,
1261, 1206, 1222, 1213, 1227, 1223, 1216, 1831, 1268, 1831,
1269, 1270, 1227, 1226, 1227, 1217, 1831, 1831, 1831, 1275,
1219, 1235, 1278, 1831, 1274, 1225, 1831, 1224, 1226, 1237,
1284, 1235, 1831, 1244, 1287, 1831, 1831, 1293, 1298, 1303,
1308, 1313, 1318, 1323, 1326, 1300, 1305, 1307, 1320
} ;
static const flex_int16_t yy_def[1480] =
{ 0,
1468, 1468, 1469, 1469, 1468, 1468, 1468, 1468, 1468, 1468,
1467, 1467, 1467, 1467, 1467, 1470, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1471,
1467, 1467, 1467, 1472, 15, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 1473, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 1470,
1467, 1467, 1467, 1467, 1467, 1467, 1474, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1471, 1467,
1472, 1467, 1467, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 1475, 45, 1473, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 1474, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1476, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
1475, 1467, 1473, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 1467, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1477, 45, 45, 45, 45, 45, 45,
45, 45, 1467, 45, 1467, 45, 1473, 1467, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 1467,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 1467,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 1467, 45, 45, 45, 45, 1467, 1467, 1467,
1478, 45, 45, 45, 45, 45, 45, 45, 45, 1467,
45, 45, 1467, 45, 1473, 45, 45, 45, 45, 45,
45, 1467, 45, 45, 45, 45, 45, 45, 1467, 45,
45, 45, 45, 45, 1467, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 1467, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 1467, 45, 1467,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 1467, 1467, 45, 45, 1467,
45, 45, 1467, 1479, 45, 45, 45, 45, 1467, 1467,
45, 1467, 45, 1467, 45, 45, 45, 1467, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
1467, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 1467, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 1467, 45, 45, 45,
45, 45, 45, 45, 45, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 1467, 45,
45, 45, 45, 45, 45, 45, 1467, 45, 45, 1467,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
1467, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 1467,
45, 45, 45, 45, 45, 45, 45, 45, 1467, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 1467, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 1467, 45, 45, 45,
45, 45, 45, 45, 45, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 1467, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 1467, 1467,
45, 45, 45, 45, 1467, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 1467, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 1467, 45, 45, 45, 45, 45, 45,
45, 45, 45, 1467, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 1467, 45, 45, 45, 45, 45,
45, 45, 45, 45, 1467, 45, 45, 45, 45, 45,
1467, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 1467,
45, 45, 45, 1467, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 1467, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 1467, 45, 45, 45, 45, 45, 45, 45, 45,
1467, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 1467, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
1467, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 1467, 45, 45, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 1467, 45,
45, 45, 45, 45, 45, 1467, 45, 45, 45, 45,
45, 45, 1467, 1467, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 1467,
1467, 45, 1467, 45, 45, 45, 45, 45, 45, 45,
45, 1467, 45, 45, 45, 45, 1467, 45, 45, 45,
45, 45, 1467, 1467, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 1467,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 1467, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 1467, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 1467, 45, 1467,
1467, 45, 45, 45, 45, 45, 45, 45, 45, 45,
1467, 45, 45, 45, 45, 45, 45, 45, 1467, 45,
1467, 45, 1467, 1467, 45, 1467, 45, 1467, 45, 45,
45, 45, 45, 1467, 45, 45, 1467, 45, 45, 45,
45, 45, 45, 45, 45, 45, 1467, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 1467, 1467,
45, 1467, 45, 45, 45, 45, 45, 1467, 45, 45,
45, 45, 45, 45, 1467, 45, 45, 1467, 45, 45,
45, 45, 1467, 45, 45, 45, 45, 45, 45, 1467,
45, 1467, 45, 1467, 45, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 1467, 45, 45, 1467,
45, 45, 45, 45, 1467, 1467, 1467, 45, 45, 1467,
1467, 45, 45, 45, 1467, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 1467, 45, 45, 1467, 45, 1467,
45, 45, 45, 45, 45, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 1467,
45, 45, 45, 1467, 45, 45, 45, 45, 45, 45,
45, 1467, 45, 45, 45, 1467, 45, 1467, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 1467,
45, 45, 1467, 1467, 1467, 45, 1467, 1467, 1467, 45,
45, 1467, 45, 45, 1467, 45, 45, 45, 45, 45,
45, 1467, 45, 1467, 45, 45, 45, 45, 45, 45,
45, 45, 1467, 45, 45, 45, 45, 45, 45, 45,
45, 1467, 1467, 45, 45, 45, 45, 45, 1467, 45,
45, 45, 45, 45, 45, 1467, 45, 45, 45, 45,
45, 1467, 45, 1467, 45, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 1467, 45, 45, 1467, 45, 45,
1467, 1467, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 1467, 45, 1467,
45, 45, 45, 45, 45, 45, 1467, 1467, 1467, 45,
45, 45, 45, 1467, 45, 45, 1467, 45, 45, 45,
45, 45, 1467, 45, 45, 1467, 0, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467
} ;
static const flex_int16_t yy_nxt[1903] =
{ 0,
1467, 13, 14, 13, 1467, 15, 16, 1467, 17, 18,
19, 20, 21, 22, 22, 22, 23, 24, 86, 705,
37, 14, 37, 87, 25, 26, 38, 1467, 706, 27,
37, 14, 37, 42, 28, 42, 38, 92, 93, 29,
115, 30, 13, 14, 13, 91, 92, 25, 31, 93,
13, 14, 13, 13, 14, 13, 32, 40, 818, 13,
14, 13, 33, 40, 115, 92, 93, 819, 91, 34,
35, 13, 14, 13, 95, 15, 16, 96, 17, 18,
19, 20, 21, 22, 22, 22, 23, 24, 13, 14,
13, 109, 39, 91, 25, 26, 13, 14, 13, 27,
39, 85, 85, 85, 28, 42, 41, 42, 42, 29,
42, 30, 83, 108, 41, 111, 94, 25, 31, 109,
217, 218, 89, 137, 89, 139, 32, 90, 90, 90,
138, 374, 33, 140, 375, 83, 108, 820, 111, 34,
35, 44, 44, 44, 45, 45, 46, 45, 45, 45,
45, 45, 45, 45, 45, 47, 45, 45, 45, 45,
45, 48, 45, 49, 50, 45, 51, 45, 52, 53,
54, 45, 45, 45, 45, 55, 56, 45, 57, 45,
45, 58, 45, 45, 59, 60, 61, 62, 63, 64,
65, 66, 67, 52, 68, 69, 70, 71, 72, 73,
74, 75, 76, 77, 78, 79, 57, 45, 45, 45,
45, 45, 81, 105, 82, 82, 82, 81, 114, 84,
84, 84, 102, 105, 81, 83, 84, 84, 84, 821,
83, 108, 123, 112, 141, 124, 182, 83, 125, 105,
126, 114, 127, 113, 142, 200, 143, 164, 83, 119,
194, 165, 133, 83, 108, 120, 112, 103, 121, 182,
83, 45, 149, 134, 182, 136, 150, 45, 200, 45,
45, 113, 45, 135, 45, 45, 45, 194, 117, 145,
146, 45, 45, 147, 45, 45, 151, 185, 822, 148,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 90, 90, 90, 45, 128, 197,
111, 45, 129, 160, 180, 130, 131, 161, 114, 45,
242, 823, 155, 45, 243, 45, 118, 162, 132, 152,
156, 153, 157, 154, 112, 166, 197, 158, 159, 167,
180, 175, 168, 181, 113, 90, 90, 90, 102, 169,
170, 176, 85, 85, 85, 171, 177, 172, 81, 173,
82, 82, 82, 83, 180, 85, 85, 85, 89, 181,
89, 83, 113, 90, 90, 90, 83, 181, 81, 174,
84, 84, 84, 103, 190, 101, 83, 193, 196, 198,
183, 83, 101, 190, 83, 199, 211, 196, 223, 83,
224, 230, 226, 184, 231, 212, 213, 824, 232, 287,
204, 197, 190, 193, 83, 262, 196, 198, 227, 287,
101, 205, 199, 504, 101, 196, 505, 248, 101, 254,
255, 257, 271, 272, 258, 259, 101, 287, 280, 289,
101, 199, 101, 188, 203, 203, 203, 290, 263, 264,
265, 203, 203, 203, 203, 203, 203, 288, 288, 266,
299, 267, 289, 268, 269, 273, 270, 289, 283, 274,
296, 300, 302, 275, 203, 203, 203, 203, 203, 203,
304, 306, 296, 288, 291, 395, 317, 303, 299, 359,
292, 398, 390, 296, 318, 302, 348, 402, 300, 398,
319, 404, 404, 304, 409, 309, 412, 403, 306, 307,
307, 307, 426, 478, 398, 719, 307, 307, 307, 307,
307, 307, 399, 360, 406, 407, 466, 409, 432, 427,
404, 416, 433, 408, 412, 396, 467, 361, 719, 307,
307, 307, 307, 307, 307, 459, 460, 349, 517, 446,
350, 415, 415, 415, 447, 661, 662, 679, 415, 415,
415, 415, 415, 415, 487, 517, 492, 510, 488, 479,
493, 624, 511, 551, 541, 525, 517, 526, 552, 727,
728, 415, 415, 415, 415, 415, 415, 542, 825, 543,
620, 625, 718, 527, 680, 626, 763, 724, 624, 764,
448, 816, 525, 725, 526, 449, 45, 45, 45, 826,
827, 828, 829, 45, 45, 45, 45, 45, 45, 625,
718, 794, 796, 797, 830, 802, 831, 832, 795, 816,
798, 803, 833, 834, 799, 835, 45, 45, 45, 45,
45, 45, 836, 837, 838, 839, 840, 841, 842, 843,
844, 845, 847, 848, 849, 850, 846, 851, 852, 853,
854, 855, 856, 857, 858, 859, 860, 861, 862, 863,
865, 866, 867, 864, 868, 869, 870, 871, 872, 873,
874, 875, 876, 877, 878, 879, 880, 881, 882, 883,
884, 885, 886, 887, 888, 889, 890, 891, 892, 893,
894, 895, 896, 897, 898, 899, 900, 901, 902, 903,
904, 905, 906, 907, 908, 909, 910, 911, 912, 913,
914, 915, 916, 917, 918, 919, 920, 921, 922, 923,
924, 925, 926, 927, 928, 906, 929, 930, 905, 931,
932, 933, 934, 935, 936, 937, 939, 940, 941, 942,
943, 944, 945, 946, 947, 948, 949, 950, 951, 952,
953, 954, 955, 956, 958, 959, 960, 961, 962, 963,
964, 965, 966, 967, 957, 968, 969, 970, 971, 972,
973, 974, 975, 976, 977, 978, 979, 980, 981, 982,
983, 984, 985, 986, 987, 988, 989, 990, 991, 993,
992, 938, 994, 995, 996, 997, 998, 999, 1000, 1001,
1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011,
1012, 1013, 1014, 1015, 1016, 1017, 991, 992, 1018, 1019,
1020, 1021, 1023, 1025, 1026, 1027, 1022, 1028, 1029, 1030,
1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040,
1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050,
1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060,
1061, 1062, 1063, 1064, 1024, 1065, 1066, 1067, 1068, 1069,
1070, 1071, 1072, 1073, 1074, 1075, 1076, 1077, 1078, 1079,
1080, 1081, 1082, 1083, 1084, 1085, 1086, 1087, 1088, 1089,
1090, 1091, 1092, 1093, 1094, 1072, 1095, 1096, 1097, 1098,
1099, 1073, 1100, 1101, 1102, 1103, 1104, 1105, 1106, 1107,
1108, 1109, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 1117,
1118, 1119, 1120, 1121, 1122, 1123, 1124, 1125, 1127, 1128,
1129, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 1138,
1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1147, 1149,
1150, 1151, 1152, 1153, 1154, 1155, 1156, 1157, 1158, 1159,
1160, 1161, 1162, 1163, 1164, 1165, 1166, 1167, 1168, 1169,
1170, 1171, 1143, 1172, 1173, 1174, 1175, 1177, 1126, 1178,
1179, 1180, 1181, 1182, 1176, 1183, 1184, 1185, 1186, 1187,
1148, 1188, 1189, 1190, 1191, 1192, 1193, 1194, 1195, 1196,
1197, 1198, 1199, 1200, 1201, 1202, 1204, 1205, 1206, 1207,
1203, 1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216,
1217, 1218, 1219, 1220, 1221, 1222, 1223, 1224, 1225, 1226,
1205, 1227, 1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235,
1236, 1237, 1238, 1239, 1240, 1241, 1242, 1243, 1244, 1245,
1246, 1247, 1248, 1249, 1250, 1251, 1252, 1253, 1254, 1255,
1256, 1257, 1258, 1259, 1260, 1261, 1262, 1263, 1264, 1265,
1266, 1267, 1268, 1269, 1270, 1271, 1272, 1273, 1274, 1275,
1277, 1278, 1279, 1280, 1281, 1254, 1282, 1283, 1284, 1285,
1286, 1287, 1288, 1289, 1290, 1291, 1292, 1293, 1294, 1295,
1296, 1297, 1298, 1299, 1300, 1301, 1302, 1303, 1304, 1305,
1306, 1307, 1308, 1309, 1310, 1311, 1312, 1313, 1314, 1315,
1316, 1317, 1318, 1319, 1320, 1321, 1322, 1323, 1324, 1325,
1326, 1327, 1328, 1329, 1302, 1276, 1330, 1331, 1332, 1333,
1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, 1343,
1344, 1345, 1346, 1347, 1348, 1349, 1350, 1351, 1352, 1353,
1354, 1355, 1356, 1357, 1358, 1359, 1360, 1361, 1362, 1363,
1364, 1365, 1366, 1367, 1368, 1369, 1370, 1371, 1372, 1373,
1374, 1375, 1376, 1377, 1378, 1379, 1380, 1381, 1382, 1383,
1384, 1385, 1386, 1387, 1388, 1389, 1390, 1391, 1392, 1393,
1394, 1395, 1396, 1397, 1398, 1399, 1400, 1401, 1402, 1403,
1404, 1405, 1406, 1407, 1408, 1409, 1410, 1411, 1412, 1413,
1414, 1415, 1416, 1417, 1418, 1419, 1420, 1421, 1422, 1423,
1424, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433,
1434, 1435, 1436, 1437, 1438, 1439, 1440, 1441, 1442, 1443,
1444, 1445, 1446, 1447, 1448, 1449, 1450, 1451, 1452, 1453,
1454, 1455, 1456, 1457, 1458, 1459, 1460, 1461, 1462, 1463,
1464, 1465, 1466, 12, 12, 12, 12, 12, 36, 36,
36, 36, 36, 80, 294, 80, 80, 80, 99, 401,
99, 514, 99, 101, 101, 101, 101, 101, 116, 116,
116, 116, 116, 179, 101, 179, 179, 179, 201, 201,
201, 817, 815, 814, 813, 812, 811, 810, 809, 808,
807, 806, 805, 804, 801, 800, 793, 792, 791, 790,
789, 788, 787, 786, 785, 784, 783, 782, 781, 780,
779, 778, 777, 776, 775, 774, 773, 772, 771, 770,
769, 768, 767, 766, 765, 762, 761, 760, 759, 758,
757, 756, 755, 754, 753, 752, 751, 750, 749, 748,
747, 746, 745, 744, 743, 742, 741, 740, 739, 738,
737, 736, 735, 734, 733, 732, 731, 730, 729, 726,
723, 722, 721, 720, 717, 716, 715, 714, 713, 712,
711, 710, 709, 708, 707, 704, 703, 702, 701, 700,
699, 698, 697, 696, 695, 694, 693, 692, 691, 690,
689, 688, 687, 686, 685, 684, 683, 682, 681, 678,
677, 676, 675, 674, 673, 672, 671, 670, 669, 668,
667, 666, 665, 664, 663, 660, 659, 658, 657, 656,
655, 654, 653, 652, 651, 650, 649, 648, 647, 646,
645, 644, 643, 642, 641, 640, 639, 638, 637, 636,
635, 634, 633, 632, 631, 630, 629, 628, 627, 623,
622, 621, 620, 619, 618, 617, 616, 615, 614, 613,
612, 611, 610, 609, 608, 607, 606, 605, 604, 603,
602, 601, 600, 599, 598, 597, 596, 595, 594, 593,
592, 591, 590, 589, 588, 587, 586, 585, 584, 583,
582, 581, 580, 579, 578, 577, 576, 575, 574, 573,
572, 571, 570, 569, 568, 567, 566, 565, 564, 563,
562, 561, 560, 559, 558, 557, 556, 555, 554, 553,
550, 549, 548, 547, 546, 545, 544, 540, 539, 538,
537, 536, 535, 534, 533, 532, 531, 530, 529, 528,
524, 523, 522, 521, 520, 519, 518, 516, 515, 513,
512, 509, 508, 507, 506, 503, 502, 501, 500, 499,
498, 497, 496, 495, 494, 491, 490, 489, 486, 485,
484, 483, 482, 481, 480, 477, 476, 475, 474, 473,
472, 471, 470, 469, 468, 465, 464, 463, 462, 461,
458, 457, 456, 455, 454, 453, 452, 451, 450, 445,
444, 443, 442, 441, 440, 439, 438, 437, 436, 435,
434, 431, 430, 429, 428, 425, 424, 423, 422, 421,
420, 419, 418, 417, 414, 413, 411, 410, 405, 400,
397, 394, 393, 392, 391, 389, 388, 387, 386, 385,
384, 383, 382, 381, 380, 379, 378, 377, 376, 373,
372, 371, 370, 369, 368, 367, 366, 365, 364, 363,
362, 358, 357, 356, 355, 354, 353, 352, 351, 347,
346, 345, 344, 343, 342, 341, 340, 339, 338, 337,
336, 335, 334, 333, 332, 331, 330, 329, 328, 327,
326, 325, 324, 323, 322, 321, 320, 316, 315, 314,
313, 312, 311, 310, 308, 202, 305, 303, 301, 298,
297, 295, 293, 286, 285, 284, 282, 281, 279, 278,
277, 276, 261, 260, 256, 253, 252, 251, 250, 249,
247, 246, 245, 244, 241, 240, 239, 238, 237, 236,
235, 234, 233, 229, 228, 225, 222, 221, 220, 219,
216, 215, 214, 210, 209, 208, 207, 206, 202, 195,
192, 191, 189, 187, 186, 178, 163, 144, 122, 110,
107, 106, 104, 43, 100, 98, 97, 88, 43, 1467,
11, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467
} ;
static const flex_int16_t yy_chk[1903] =
{ 0,
0, 1, 1, 1, 0, 1, 1, 0, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 21, 610,
3, 3, 3, 21, 1, 1, 3, 0, 610, 1,
4, 4, 4, 13, 1, 13, 4, 27, 28, 1,
57, 1, 5, 5, 5, 26, 32, 1, 1, 33,
6, 6, 6, 7, 7, 7, 1, 7, 721, 8,
8, 8, 1, 8, 57, 27, 28, 722, 26, 1,
1, 2, 2, 2, 32, 2, 2, 33, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 9, 9,
9, 52, 5, 31, 2, 2, 10, 10, 10, 2,
6, 20, 20, 20, 2, 37, 9, 37, 42, 2,
42, 2, 20, 51, 10, 54, 31, 2, 2, 52,
129, 129, 25, 65, 25, 66, 2, 25, 25, 25,
65, 265, 2, 66, 265, 20, 51, 723, 54, 2,
2, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 17, 48, 17, 17, 17, 19, 56, 19,
19, 19, 44, 59, 22, 17, 22, 22, 22, 724,
19, 64, 61, 55, 67, 61, 93, 22, 61, 48,
61, 56, 61, 55, 67, 115, 67, 75, 17, 59,
109, 75, 63, 19, 64, 59, 55, 44, 59, 96,
22, 45, 70, 63, 93, 64, 70, 45, 115, 45,
45, 55, 45, 63, 45, 45, 45, 109, 58, 69,
69, 45, 45, 69, 45, 58, 70, 96, 725, 69,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 58, 89, 89, 89, 58, 62, 112,
71, 58, 62, 73, 91, 62, 62, 73, 78, 58,
149, 727, 72, 58, 149, 58, 58, 73, 62, 71,
72, 71, 72, 71, 77, 76, 112, 72, 72, 76,
91, 78, 76, 92, 77, 90, 90, 90, 101, 76,
76, 78, 81, 81, 81, 76, 78, 77, 82, 77,
82, 82, 82, 81, 94, 85, 85, 85, 83, 92,
83, 82, 77, 83, 83, 83, 85, 95, 84, 77,
84, 84, 84, 101, 105, 103, 81, 108, 111, 113,
94, 84, 103, 119, 82, 114, 125, 154, 134, 85,
134, 139, 136, 95, 139, 125, 125, 728, 139, 180,
119, 172, 105, 108, 84, 165, 111, 113, 136, 183,
103, 119, 114, 390, 103, 154, 390, 154, 103, 160,
160, 162, 166, 166, 162, 162, 103, 180, 172, 182,
103, 175, 103, 103, 118, 118, 118, 183, 165, 165,
165, 118, 118, 118, 118, 118, 118, 181, 184, 165,
193, 165, 182, 165, 165, 167, 165, 185, 175, 167,
190, 194, 196, 167, 118, 118, 118, 118, 118, 118,
198, 200, 205, 181, 184, 285, 213, 280, 193, 252,
185, 287, 280, 190, 213, 196, 243, 295, 194, 290,
213, 296, 309, 198, 299, 205, 302, 295, 200, 203,
203, 203, 319, 366, 287, 625, 203, 203, 203, 203,
203, 203, 290, 252, 298, 298, 354, 299, 325, 319,
296, 309, 325, 298, 302, 285, 354, 252, 625, 203,
203, 203, 203, 203, 203, 348, 348, 243, 404, 338,
243, 307, 307, 307, 338, 564, 564, 582, 307, 307,
307, 307, 307, 307, 375, 416, 379, 396, 375, 366,
379, 525, 396, 441, 432, 414, 404, 414, 441, 632,
632, 307, 307, 307, 307, 307, 307, 432, 729, 432,
527, 526, 624, 416, 582, 527, 668, 630, 525, 668,
338, 719, 414, 630, 414, 338, 415, 415, 415, 730,
731, 732, 733, 415, 415, 415, 415, 415, 415, 526,
624, 700, 701, 701, 734, 704, 735, 736, 700, 719,
701, 704, 737, 738, 701, 739, 415, 415, 415, 415,
415, 415, 740, 741, 742, 743, 745, 746, 747, 748,
749, 750, 751, 752, 753, 754, 750, 755, 756, 757,
758, 761, 762, 763, 764, 767, 768, 769, 770, 771,
772, 773, 774, 771, 775, 776, 777, 779, 780, 781,
782, 783, 784, 785, 786, 787, 788, 789, 790, 791,
792, 793, 794, 795, 796, 797, 798, 799, 800, 801,
802, 803, 805, 806, 807, 808, 809, 810, 811, 812,
813, 815, 816, 817, 818, 819, 820, 821, 822, 823,
824, 825, 826, 827, 828, 829, 830, 831, 832, 833,
834, 836, 837, 838, 839, 816, 840, 841, 815, 842,
843, 844, 846, 847, 848, 849, 850, 852, 853, 854,
855, 856, 857, 858, 859, 860, 861, 862, 863, 864,
865, 866, 867, 868, 869, 871, 872, 873, 875, 876,
877, 878, 879, 880, 868, 881, 882, 883, 884, 885,
886, 887, 888, 889, 890, 891, 893, 894, 895, 896,
897, 898, 899, 900, 901, 902, 903, 904, 905, 907,
906, 849, 908, 909, 910, 911, 913, 914, 915, 916,
917, 918, 919, 920, 922, 923, 924, 925, 926, 927,
928, 929, 930, 931, 932, 933, 905, 906, 934, 935,
936, 938, 939, 940, 941, 942, 938, 943, 944, 945,
946, 947, 948, 949, 950, 951, 952, 953, 954, 955,
956, 957, 958, 959, 960, 962, 963, 964, 965, 966,
967, 968, 969, 970, 971, 972, 974, 975, 977, 978,
979, 980, 981, 982, 939, 983, 984, 985, 986, 987,
988, 990, 991, 992, 993, 994, 995, 997, 998, 999,
1000, 1001, 1002, 1005, 1006, 1007, 1008, 1009, 1010, 1011,
1012, 1013, 1014, 1015, 1016, 991, 1017, 1018, 1019, 1022,
1024, 992, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1033,
1034, 1035, 1036, 1038, 1039, 1040, 1041, 1042, 1045, 1046,
1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056,
1057, 1058, 1059, 1061, 1062, 1063, 1064, 1065, 1066, 1067,
1068, 1069, 1070, 1071, 1072, 1073, 1075, 1076, 1077, 1078,
1079, 1080, 1081, 1082, 1083, 1084, 1085, 1086, 1087, 1088,
1090, 1091, 1092, 1093, 1094, 1095, 1096, 1097, 1098, 1099,
1100, 1101, 1072, 1102, 1103, 1104, 1105, 1106, 1054, 1107,
1109, 1112, 1113, 1114, 1105, 1115, 1116, 1117, 1118, 1119,
1077, 1120, 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1130,
1132, 1135, 1137, 1139, 1140, 1141, 1142, 1143, 1145, 1146,
1141, 1148, 1149, 1150, 1151, 1152, 1153, 1154, 1155, 1156,
1158, 1159, 1160, 1161, 1162, 1163, 1164, 1165, 1166, 1167,
1143, 1168, 1171, 1173, 1174, 1175, 1176, 1177, 1179, 1180,
1181, 1182, 1183, 1184, 1186, 1187, 1189, 1190, 1191, 1192,
1194, 1195, 1196, 1197, 1198, 1199, 1201, 1203, 1205, 1207,
1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217,
1218, 1219, 1220, 1221, 1222, 1223, 1224, 1225, 1225, 1226,
1227, 1228, 1229, 1230, 1231, 1205, 1232, 1233, 1234, 1235,
1236, 1237, 1238, 1239, 1240, 1241, 1242, 1243, 1244, 1245,
1246, 1248, 1249, 1251, 1252, 1253, 1254, 1258, 1259, 1262,
1263, 1264, 1267, 1268, 1269, 1270, 1271, 1272, 1273, 1274,
1276, 1277, 1279, 1281, 1282, 1283, 1284, 1285, 1287, 1288,
1289, 1290, 1291, 1292, 1254, 1226, 1293, 1294, 1295, 1296,
1297, 1298, 1299, 1301, 1302, 1303, 1305, 1306, 1307, 1308,
1309, 1310, 1311, 1313, 1314, 1315, 1317, 1319, 1320, 1321,
1322, 1323, 1324, 1325, 1326, 1327, 1328, 1329, 1331, 1332,
1336, 1340, 1341, 1343, 1344, 1346, 1347, 1348, 1349, 1350,
1351, 1353, 1355, 1356, 1357, 1358, 1359, 1360, 1361, 1362,
1364, 1365, 1366, 1367, 1368, 1369, 1370, 1371, 1374, 1375,
1376, 1377, 1378, 1380, 1381, 1382, 1383, 1384, 1385, 1387,
1388, 1389, 1390, 1391, 1393, 1395, 1397, 1398, 1399, 1400,
1401, 1402, 1403, 1404, 1406, 1407, 1409, 1410, 1413, 1414,
1415, 1416, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424,
1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 1434,
1435, 1436, 1437, 1439, 1441, 1442, 1443, 1444, 1445, 1446,
1450, 1451, 1452, 1453, 1455, 1456, 1458, 1459, 1460, 1461,
1462, 1464, 1465, 1468, 1468, 1468, 1468, 1468, 1469, 1469,
1469, 1469, 1469, 1470, 1476, 1470, 1470, 1470, 1471, 1477,
1471, 1478, 1471, 1472, 1472, 1472, 1472, 1472, 1473, 1473,
1473, 1473, 1473, 1474, 1479, 1474, 1474, 1474, 1475, 1475,
1475, 720, 718, 716, 715, 714, 713, 712, 711, 710,
709, 708, 707, 706, 703, 702, 699, 698, 697, 696,
695, 694, 693, 692, 691, 690, 689, 688, 687, 686,
685, 684, 683, 682, 681, 680, 678, 677, 676, 675,
674, 673, 672, 671, 669, 667, 666, 665, 664, 663,
662, 661, 660, 659, 658, 657, 656, 655, 654, 653,
652, 650, 649, 648, 647, 646, 645, 644, 643, 642,
641, 640, 639, 638, 637, 636, 635, 634, 633, 631,
629, 628, 627, 626, 623, 622, 621, 619, 618, 616,
615, 614, 613, 612, 611, 608, 607, 606, 605, 604,
603, 602, 601, 600, 599, 598, 597, 595, 594, 593,
592, 591, 590, 589, 588, 586, 585, 584, 583, 581,
580, 579, 578, 577, 576, 575, 573, 572, 571, 570,
569, 568, 567, 566, 565, 563, 562, 561, 560, 559,
558, 557, 556, 555, 554, 553, 552, 550, 549, 548,
547, 546, 545, 544, 543, 542, 541, 540, 539, 538,
537, 536, 535, 534, 533, 532, 531, 530, 529, 523,
521, 518, 517, 516, 515, 513, 512, 511, 509, 508,
505, 504, 503, 502, 501, 500, 499, 498, 497, 496,
495, 494, 493, 492, 491, 490, 489, 488, 487, 486,
485, 484, 483, 482, 481, 479, 477, 476, 475, 474,
473, 472, 471, 470, 469, 468, 467, 466, 464, 463,
462, 461, 460, 459, 458, 457, 456, 455, 454, 453,
452, 451, 450, 449, 448, 447, 445, 444, 443, 442,
440, 439, 438, 437, 436, 434, 433, 431, 430, 428,
427, 426, 425, 424, 423, 421, 420, 419, 418, 417,
412, 411, 409, 408, 407, 406, 405, 403, 402, 400,
397, 395, 394, 392, 391, 389, 388, 387, 386, 385,
384, 383, 382, 381, 380, 378, 377, 376, 374, 373,
372, 371, 369, 368, 367, 365, 364, 363, 362, 361,
360, 359, 358, 357, 355, 353, 352, 351, 350, 349,
347, 346, 345, 344, 343, 342, 341, 340, 339, 337,
336, 335, 334, 333, 332, 331, 330, 329, 328, 327,
326, 324, 323, 322, 321, 318, 317, 316, 315, 314,
313, 312, 311, 310, 306, 304, 301, 300, 297, 293,
286, 284, 283, 282, 281, 279, 278, 277, 276, 275,
274, 273, 272, 271, 270, 269, 268, 267, 266, 264,
263, 262, 261, 260, 259, 258, 257, 256, 255, 254,
253, 251, 250, 249, 248, 247, 246, 245, 244, 242,
241, 240, 239, 238, 237, 236, 235, 233, 232, 231,
230, 229, 228, 227, 226, 225, 224, 223, 222, 221,
220, 219, 218, 217, 216, 215, 214, 212, 211, 210,
209, 208, 207, 206, 204, 201, 199, 197, 195, 192,
191, 189, 186, 178, 177, 176, 174, 173, 171, 170,
169, 168, 164, 163, 161, 159, 158, 157, 156, 155,
153, 152, 151, 150, 148, 147, 146, 145, 144, 143,
142, 141, 140, 138, 137, 135, 133, 132, 131, 130,
128, 127, 126, 124, 123, 122, 121, 120, 116, 110,
107, 106, 104, 99, 98, 79, 74, 68, 60, 53,
50, 49, 47, 43, 41, 39, 38, 24, 14, 11,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467
} ;
static yy_state_type yy_last_accepting_state;
static char *yy_last_accepting_cpos;
extern int yy_flex_debug;
int yy_flex_debug = 1;
static const flex_int16_t yy_rule_linenum[175] =
{ 0,
147, 149, 151, 156, 157, 162, 163, 164, 176, 179,
184, 191, 200, 209, 218, 227, 236, 245, 255, 264,
273, 282, 291, 300, 309, 318, 327, 336, 345, 354,
366, 375, 384, 393, 402, 413, 424, 435, 446, 456,
466, 477, 488, 499, 510, 521, 532, 543, 554, 565,
576, 587, 596, 605, 615, 624, 634, 648, 664, 673,
682, 691, 700, 721, 742, 751, 761, 770, 781, 790,
799, 808, 817, 826, 836, 845, 854, 863, 872, 881,
890, 899, 908, 917, 926, 936, 947, 959, 968, 977,
987, 997, 1007, 1017, 1027, 1037, 1046, 1056, 1065, 1074,
1083, 1092, 1102, 1112, 1121, 1131, 1140, 1149, 1158, 1167,
1176, 1185, 1194, 1203, 1212, 1221, 1230, 1239, 1248, 1257,
1266, 1275, 1284, 1293, 1302, 1311, 1320, 1329, 1338, 1347,
1356, 1365, 1374, 1383, 1392, 1401, 1411, 1421, 1431, 1441,
1451, 1461, 1471, 1481, 1491, 1500, 1509, 1518, 1527, 1536,
1545, 1554, 1565, 1576, 1589, 1602, 1617, 1716, 1721, 1726,
1731, 1732, 1733, 1734, 1735, 1736, 1738, 1756, 1769, 1774,
1778, 1780, 1782, 1784
} ;
/* The intent behind this definition is that it'll catch
* any uses of REJECT which flex missed.
*/
#define REJECT reject_used_but_not_detected
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
char *yytext;
#line 1 "dhcp4_lexer.ll"
/* Copyright (C) 2016-2018 Internet Systems Consortium, Inc. ("ISC")
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#line 8 "dhcp4_lexer.ll"
/* Generated files do not make clang static analyser so happy */
#ifndef __clang_analyzer__
#include <cerrno>
#include <climits>
#include <cstdlib>
#include <string>
#include <dhcp4/parser_context.h>
#include <asiolink/io_address.h>
#include <boost/lexical_cast.hpp>
#include <exceptions/exceptions.h>
/* Please avoid C++ style comments (// ... eol) as they break flex 2.6.2 */
/* Work around an incompatibility in flex (at least versions
2.5.31 through 2.5.33): it generates code that does
not conform to C89. See Debian bug 333231
<http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=333231>. */
# undef yywrap
# define yywrap() 1
namespace {
bool start_token_flag = false;
isc::dhcp::Parser4Context::ParserType start_token_value;
unsigned int comment_start_line = 0;
using namespace isc::dhcp;
};
/* To avoid the call to exit... oops! */
#define YY_FATAL_ERROR(msg) isc::dhcp::Parser4Context::fatal(msg)
#line 1751 "dhcp4_lexer.cc"
/* noyywrap disables automatic rewinding for the next file to parse. Since we
always parse only a single string, there's no need to do any wraps. And
using yywrap requires linking with -lfl, which provides the default yywrap
implementation that always returns 1 anyway. */
/* nounput simplifies the lexer, by removing support for putting a character
back into the input stream. We never use such capability anyway. */
/* batch means that we'll never use the generated lexer interactively. */
/* avoid to get static global variables to remain with C++. */
/* in last resort %option reentrant */
/* Enables debug mode. To see the debug messages, one needs to also set
yy_flex_debug to 1, then the debug messages will be printed on stderr. */
/* I have no idea what this option does, except it was specified in the bison
examples and Postgres folks added it to remove gcc 4.3 warnings. Let's
be on the safe side and keep it. */
#define YY_NO_INPUT 1
/* These are not token expressions yet, just convenience expressions that
can be used during actual token definitions. Note some can match
incorrect inputs (e.g., IP addresses) which must be checked. */
/* for errors */
#line 94 "dhcp4_lexer.ll"
/* This code run each time a pattern is matched. It updates the location
by moving it ahead by yyleng bytes. yyleng specifies the length of the
currently matched token. */
#define YY_USER_ACTION driver.loc_.columns(yyleng);
#line 1777 "dhcp4_lexer.cc"
#line 1778 "dhcp4_lexer.cc"
#define INITIAL 0
#define COMMENT 1
#define DIR_ENTER 2
#define DIR_INCLUDE 3
#define DIR_EXIT 4
#ifndef YY_NO_UNISTD_H
/* Special case for "unistd.h", since it is non-ANSI. We include it way
* down here because we want the user's section 1 to have been scanned first.
* The user has a chance to override it with an option.
*/
/* %if-c-only */
#include <unistd.h>
/* %endif */
/* %if-c++-only */
/* %endif */
#endif
#ifndef YY_EXTRA_TYPE
#define YY_EXTRA_TYPE void *
#endif
/* %if-c-only Reentrant structure and macros (non-C++). */
/* %if-reentrant */
/* %if-c-only */
static int yy_init_globals ( void );
/* %endif */
/* %if-reentrant */
/* %endif */
/* %endif End reentrant structures and macros. */
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
int yylex_destroy ( void );
int yyget_debug ( void );
void yyset_debug ( int debug_flag );
YY_EXTRA_TYPE yyget_extra ( void );
void yyset_extra ( YY_EXTRA_TYPE user_defined );
FILE *yyget_in ( void );
void yyset_in ( FILE * _in_str );
FILE *yyget_out ( void );
void yyset_out ( FILE * _out_str );
int yyget_leng ( void );
char *yyget_text ( void );
int yyget_lineno ( void );
void yyset_lineno ( int _line_number );
/* %if-bison-bridge */
/* %endif */
/* Macros after this point can all be overridden by user definitions in
* section 1.
*/
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
extern "C" int yywrap ( void );
#else
extern int yywrap ( void );
#endif
#endif
/* %not-for-header */
#ifndef YY_NO_UNPUT
#endif
/* %ok-for-header */
/* %endif */
#ifndef yytext_ptr
static void yy_flex_strncpy ( char *, const char *, int );
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen ( const char * );
#endif
#ifndef YY_NO_INPUT
/* %if-c-only Standard (non-C++) definition */
/* %not-for-header */
#ifdef __cplusplus
static int yyinput ( void );
#else
static int input ( void );
#endif
/* %ok-for-header */
/* %endif */
#endif
/* %if-c-only */
/* %endif */
/* Amount of stuff to slurp up with each read. */
#ifndef YY_READ_BUF_SIZE
#ifdef __ia64__
/* On IA-64, the buffer size is 16k, not 8k */
#define YY_READ_BUF_SIZE 16384
#else
#define YY_READ_BUF_SIZE 8192
#endif /* __ia64__ */
#endif
/* Copy whatever the last rule matched to the standard output. */
#ifndef ECHO
/* %if-c-only Standard (non-C++) definition */
/* This used to be an fputs(), but since the string might contain NUL's,
* we now use fwrite().
*/
#define ECHO do { if (fwrite( yytext, (size_t) yyleng, 1, yyout )) {} } while (0)
/* %endif */
/* %if-c++-only C++ definition */
/* %endif */
#endif
/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
* is returned in "result".
*/
#ifndef YY_INPUT
#define YY_INPUT(buf,result,max_size) \
/* %% [5.0] fread()/read() definition of YY_INPUT goes here unless we're doing C++ \ */\
if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
{ \
int c = '*'; \
int n; \
for ( n = 0; n < max_size && \
(c = getc( yyin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
if ( c == '\n' ) \
buf[n++] = (char) c; \
if ( c == EOF && ferror( yyin ) ) \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
result = n; \
} \
else \
{ \
errno=0; \
while ( (result = (int) fread(buf, 1, (yy_size_t) max_size, yyin)) == 0 && ferror(yyin)) \
{ \
if( errno != EINTR) \
{ \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
break; \
} \
errno=0; \
clearerr(yyin); \
} \
}\
\
/* %if-c++-only C++ definition \ */\
/* %endif */
#endif
/* No semi-colon after return; correct usage is to write "yyterminate();" -
* we don't want an extra ';' after the "return" because that will cause
* some compilers to complain about unreachable statements.
*/
#ifndef yyterminate
#define yyterminate() return YY_NULL
#endif
/* Number of entries by which start-condition stack grows. */
#ifndef YY_START_STACK_INCR
#define YY_START_STACK_INCR 25
#endif
/* Report a fatal error. */
#ifndef YY_FATAL_ERROR
/* %if-c-only */
#define YY_FATAL_ERROR(msg) yy_fatal_error( msg )
/* %endif */
/* %if-c++-only */
/* %endif */
#endif
/* %if-tables-serialization structures and prototypes */
/* %not-for-header */
/* %ok-for-header */
/* %not-for-header */
/* %tables-yydmap generated elements */
/* %endif */
/* end tables serialization structures and prototypes */
/* %ok-for-header */
/* Default declaration of generated scanner - a define so the user can
* easily add parameters.
*/
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
/* %if-c-only Standard (non-C++) definition */
extern int yylex (void);
#define YY_DECL int yylex (void)
/* %endif */
/* %if-c++-only C++ definition */
/* %endif */
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after yytext and yyleng
* have been set up.
*/
#ifndef YY_USER_ACTION
#define YY_USER_ACTION
#endif
/* Code executed at the end of each rule. */
#ifndef YY_BREAK
#define YY_BREAK /*LINTED*/break;
#endif
/* %% [6.0] YY_RULE_SETUP definition goes here */
#define YY_RULE_SETUP \
YY_USER_ACTION
/* %not-for-header */
/** The main scanner function which does all the work.
*/
YY_DECL
{
yy_state_type yy_current_state;
char *yy_cp, *yy_bp;
int yy_act;
if ( !(yy_init) )
{
(yy_init) = 1;
#ifdef YY_USER_INIT
YY_USER_INIT;
#endif
if ( ! (yy_start) )
(yy_start) = 1; /* first start state */
if ( ! yyin )
/* %if-c-only */
yyin = stdin;
/* %endif */
/* %if-c++-only */
/* %endif */
if ( ! yyout )
/* %if-c-only */
yyout = stdout;
/* %endif */
/* %if-c++-only */
/* %endif */
if ( ! YY_CURRENT_BUFFER ) {
yyensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer( yyin, YY_BUF_SIZE );
}
yy_load_buffer_state( );
}
{
/* %% [7.0] user's declarations go here */
#line 100 "dhcp4_lexer.ll"
#line 104 "dhcp4_lexer.ll"
/* This part of the code is copied over to the verbatim to the top
of the generated yylex function. Explanation:
http://www.gnu.org/software/bison/manual/html_node/Multiple-start_002dsymbols.html */
/* Code run each time yylex is called. */
driver.loc_.step();
if (start_token_flag) {
start_token_flag = false;
switch (start_token_value) {
case Parser4Context::PARSER_JSON:
default:
return isc::dhcp::Dhcp4Parser::make_TOPLEVEL_JSON(driver.loc_);
case Parser4Context::PARSER_DHCP4:
return isc::dhcp::Dhcp4Parser::make_TOPLEVEL_DHCP4(driver.loc_);
case Parser4Context::SUBPARSER_DHCP4:
return isc::dhcp::Dhcp4Parser::make_SUB_DHCP4(driver.loc_);
case Parser4Context::PARSER_INTERFACES:
return isc::dhcp::Dhcp4Parser::make_SUB_INTERFACES4(driver.loc_);
case Parser4Context::PARSER_SUBNET4:
return isc::dhcp::Dhcp4Parser::make_SUB_SUBNET4(driver.loc_);
case Parser4Context::PARSER_POOL4:
return isc::dhcp::Dhcp4Parser::make_SUB_POOL4(driver.loc_);
case Parser4Context::PARSER_HOST_RESERVATION:
return isc::dhcp::Dhcp4Parser::make_SUB_RESERVATION(driver.loc_);
case Parser4Context::PARSER_OPTION_DEFS:
return isc::dhcp::Dhcp4Parser::make_SUB_OPTION_DEFS(driver.loc_);
case Parser4Context::PARSER_OPTION_DEF:
return isc::dhcp::Dhcp4Parser::make_SUB_OPTION_DEF(driver.loc_);
case Parser4Context::PARSER_OPTION_DATA:
return isc::dhcp::Dhcp4Parser::make_SUB_OPTION_DATA(driver.loc_);
case Parser4Context::PARSER_HOOKS_LIBRARY:
return isc::dhcp::Dhcp4Parser::make_SUB_HOOKS_LIBRARY(driver.loc_);
case Parser4Context::PARSER_DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_SUB_DHCP_DDNS(driver.loc_);
case Parser4Context::PARSER_CONFIG_CONTROL:
return isc::dhcp::Dhcp4Parser::make_SUB_CONFIG_CONTROL(driver.loc_);
case Parser4Context::PARSER_LOGGING:
return isc::dhcp::Dhcp4Parser::make_SUB_LOGGING(driver.loc_);
}
}
#line 2108 "dhcp4_lexer.cc"
while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */
{
/* %% [8.0] yymore()-related code goes here */
yy_cp = (yy_c_buf_p);
/* Support of yytext. */
*yy_cp = (yy_hold_char);
/* yy_bp points to the position in yy_ch_buf of the start of
* the current run.
*/
yy_bp = yy_cp;
/* %% [9.0] code to set up and find next match goes here */
yy_current_state = (yy_start);
yy_match:
do
{
YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ;
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 1468 )
yy_c = yy_meta[yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
++yy_cp;
}
while ( yy_current_state != 1467 );
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
yy_find_action:
/* %% [10.0] code to find the action number goes here */
yy_act = yy_accept[yy_current_state];
YY_DO_BEFORE_ACTION;
/* %% [11.0] code for yylineno update goes here */
do_action: /* This label is used only to access EOF actions. */
/* %% [12.0] debug code goes here */
if ( yy_flex_debug )
{
if ( yy_act == 0 )
fprintf( stderr, "--scanner backing up\n" );
else if ( yy_act < 175 )
fprintf( stderr, "--accepting rule at line %ld (\"%s\")\n",
(long)yy_rule_linenum[yy_act], yytext );
else if ( yy_act == 175 )
fprintf( stderr, "--accepting default rule (\"%s\")\n",
yytext );
else if ( yy_act == 176 )
fprintf( stderr, "--(end of buffer or a NUL)\n" );
else
fprintf( stderr, "--EOF (start condition %d)\n", YY_START );
}
switch ( yy_act )
{ /* beginning of action switch */
/* %% [13.0] actions go here */
case 0: /* must back up */
/* undo the effects of YY_DO_BEFORE_ACTION */
*yy_cp = (yy_hold_char);
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
goto yy_find_action;
case 1:
YY_RULE_SETUP
#line 147 "dhcp4_lexer.ll"
;
YY_BREAK
case 2:
YY_RULE_SETUP
#line 149 "dhcp4_lexer.ll"
;
YY_BREAK
case 3:
YY_RULE_SETUP
#line 151 "dhcp4_lexer.ll"
{
BEGIN(COMMENT);
comment_start_line = driver.loc_.end.line;;
}
YY_BREAK
case 4:
YY_RULE_SETUP
#line 156 "dhcp4_lexer.ll"
BEGIN(INITIAL);
YY_BREAK
case 5:
YY_RULE_SETUP
#line 157 "dhcp4_lexer.ll"
;
YY_BREAK
case YY_STATE_EOF(COMMENT):
#line 158 "dhcp4_lexer.ll"
{
isc_throw(Dhcp4ParseError, "Comment not closed. (/* in line " << comment_start_line);
}
YY_BREAK
case 6:
YY_RULE_SETUP
#line 162 "dhcp4_lexer.ll"
BEGIN(DIR_ENTER);
YY_BREAK
case 7:
YY_RULE_SETUP
#line 163 "dhcp4_lexer.ll"
BEGIN(DIR_INCLUDE);
YY_BREAK
case 8:
YY_RULE_SETUP
#line 164 "dhcp4_lexer.ll"
{
/* Include directive. */
/* Extract the filename. */
std::string tmp(yytext+1);
tmp.resize(tmp.size() - 1);
driver.includeFile(tmp);
}
YY_BREAK
case YY_STATE_EOF(DIR_ENTER):
case YY_STATE_EOF(DIR_INCLUDE):
case YY_STATE_EOF(DIR_EXIT):
#line 173 "dhcp4_lexer.ll"
{
isc_throw(Dhcp4ParseError, "Directive not closed.");
}
YY_BREAK
case 9:
YY_RULE_SETUP
#line 176 "dhcp4_lexer.ll"
BEGIN(INITIAL);
YY_BREAK
case 10:
YY_RULE_SETUP
#line 179 "dhcp4_lexer.ll"
{
/* Ok, we found a with space. Let's ignore it and update loc variable. */
driver.loc_.step();
}
YY_BREAK
case 11:
/* rule 11 can match eol */
YY_RULE_SETUP
#line 184 "dhcp4_lexer.ll"
{
/* Newline found. Let's update the location and continue. */
driver.loc_.lines(yyleng);
driver.loc_.step();
}
YY_BREAK
case 12:
YY_RULE_SETUP
#line 191 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::CONFIG:
return isc::dhcp::Dhcp4Parser::make_DHCP4(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("Dhcp4", driver.loc_);
}
}
YY_BREAK
case 13:
YY_RULE_SETUP
#line 200 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_INTERFACES_CONFIG(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("interfaces-config", driver.loc_);
}
}
YY_BREAK
case 14:
YY_RULE_SETUP
#line 209 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_SANITY_CHECKS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("sanity-checks", driver.loc_);
}
}
YY_BREAK
case 15:
YY_RULE_SETUP
#line 218 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SANITY_CHECKS:
return isc::dhcp::Dhcp4Parser::make_LEASE_CHECKS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("lease-checks", driver.loc_);
}
}
YY_BREAK
case 16:
YY_RULE_SETUP
#line 227 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::INTERFACES_CONFIG:
return isc::dhcp::Dhcp4Parser::make_DHCP_SOCKET_TYPE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("dhcp-socket-type", driver.loc_);
}
}
YY_BREAK
case 17:
YY_RULE_SETUP
#line 236 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_SOCKET_TYPE:
return isc::dhcp::Dhcp4Parser::make_RAW(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("raw", driver.loc_);
}
}
YY_BREAK
case 18:
YY_RULE_SETUP
#line 245 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_SOCKET_TYPE:
case isc::dhcp::Parser4Context::NCR_PROTOCOL:
return isc::dhcp::Dhcp4Parser::make_UDP(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("udp", driver.loc_);
}
}
YY_BREAK
case 19:
YY_RULE_SETUP
#line 255 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case Parser4Context::INTERFACES_CONFIG:
return isc::dhcp::Dhcp4Parser::make_OUTBOUND_INTERFACE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("outbound-interface", driver.loc_);
}
}
YY_BREAK
case 20:
YY_RULE_SETUP
#line 264 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case Parser4Context::OUTBOUND_INTERFACE:
return Dhcp4Parser::make_SAME_AS_INBOUND(driver.loc_);
default:
return Dhcp4Parser::make_STRING("same-as-inbound", driver.loc_);
}
}
YY_BREAK
case 21:
YY_RULE_SETUP
#line 273 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case Parser4Context::OUTBOUND_INTERFACE:
return Dhcp4Parser::make_USE_ROUTING(driver.loc_);
default:
return Dhcp4Parser::make_STRING("use-routing", driver.loc_);
}
}
YY_BREAK
case 22:
YY_RULE_SETUP
#line 282 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::INTERFACES_CONFIG:
return isc::dhcp::Dhcp4Parser::make_INTERFACES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("interfaces", driver.loc_);
}
}
YY_BREAK
case 23:
YY_RULE_SETUP
#line 291 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::INTERFACES_CONFIG:
return isc::dhcp::Dhcp4Parser::make_RE_DETECT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("re-detect", driver.loc_);
}
}
YY_BREAK
case 24:
YY_RULE_SETUP
#line 300 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_LEASE_DATABASE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("lease-database", driver.loc_);
}
}
YY_BREAK
case 25:
YY_RULE_SETUP
#line 309 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_HOSTS_DATABASE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("hosts-database", driver.loc_);
}
}
YY_BREAK
case 26:
YY_RULE_SETUP
#line 318 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_HOSTS_DATABASES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("hosts-databases", driver.loc_);
}
}
YY_BREAK
case 27:
YY_RULE_SETUP
#line 327 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_CONFIG_CONTROL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("config-control", driver.loc_);
}
}
YY_BREAK
case 28:
YY_RULE_SETUP
#line 336 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::CONFIG_CONTROL:
return isc::dhcp::Dhcp4Parser::make_CONFIG_DATABASES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("config-databases", driver.loc_);
}
}
YY_BREAK
case 29:
YY_RULE_SETUP
#line 345 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
return isc::dhcp::Dhcp4Parser::make_READONLY(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("readonly", driver.loc_);
}
}
YY_BREAK
case 30:
YY_RULE_SETUP
#line 354 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::OPTION_DEF:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_TYPE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("type", driver.loc_);
}
}
YY_BREAK
case 31:
YY_RULE_SETUP
#line 366 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DATABASE_TYPE:
return isc::dhcp::Dhcp4Parser::make_MEMFILE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("memfile", driver.loc_);
}
}
YY_BREAK
case 32:
YY_RULE_SETUP
#line 375 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DATABASE_TYPE:
return isc::dhcp::Dhcp4Parser::make_MYSQL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("mysql", driver.loc_);
}
}
YY_BREAK
case 33:
YY_RULE_SETUP
#line 384 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DATABASE_TYPE:
return isc::dhcp::Dhcp4Parser::make_POSTGRESQL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("postgresql", driver.loc_);
}
}
YY_BREAK
case 34:
YY_RULE_SETUP
#line 393 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DATABASE_TYPE:
return isc::dhcp::Dhcp4Parser::make_CQL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("cql", driver.loc_);
}
}
YY_BREAK
case 35:
YY_RULE_SETUP
#line 402 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_USER(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("user", driver.loc_);
}
}
YY_BREAK
case 36:
YY_RULE_SETUP
#line 413 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_PASSWORD(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("password", driver.loc_);
}
}
YY_BREAK
case 37:
YY_RULE_SETUP
#line 424 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_HOST(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("host", driver.loc_);
}
}
YY_BREAK
case 38:
YY_RULE_SETUP
#line 435 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_PORT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("port", driver.loc_);
}
}
YY_BREAK
case 39:
YY_RULE_SETUP
#line 446 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
return isc::dhcp::Dhcp4Parser::make_PERSIST(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("persist", driver.loc_);
}
}
YY_BREAK
case 40:
YY_RULE_SETUP
#line 456 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
return isc::dhcp::Dhcp4Parser::make_LFC_INTERVAL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("lfc-interval", driver.loc_);
}
}
YY_BREAK
case 41:
YY_RULE_SETUP
#line 466 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_CONNECT_TIMEOUT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("connect-timeout", driver.loc_);
}
}
YY_BREAK
case 42:
YY_RULE_SETUP
#line 477 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_KEYSPACE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("keyspace", driver.loc_);
}
}
YY_BREAK
case 43:
YY_RULE_SETUP
#line 488 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_RECONNECT_WAIT_TIME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("reconnect-wait-time", driver.loc_);
}
}
YY_BREAK
case 44:
YY_RULE_SETUP
#line 499 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_REQUEST_TIMEOUT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("request-timeout", driver.loc_);
}
}
YY_BREAK
case 45:
YY_RULE_SETUP
#line 510 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_TCP_KEEPALIVE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("tcp-keepalive", driver.loc_);
}
}
YY_BREAK
case 46:
YY_RULE_SETUP
#line 521 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_TCP_NODELAY(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("tcp-nodelay", driver.loc_);
}
}
YY_BREAK
case 47:
YY_RULE_SETUP
#line 532 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_CONTACT_POINTS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("contact-points", driver.loc_);
}
}
YY_BREAK
case 48:
YY_RULE_SETUP
#line 543 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_MAX_RECONNECT_TRIES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("max-reconnect-tries", driver.loc_);
}
}
YY_BREAK
case 49:
YY_RULE_SETUP
#line 554 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
return isc::dhcp::Dhcp4Parser::make_VALID_LIFETIME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("valid-lifetime", driver.loc_);
}
}
YY_BREAK
case 50:
YY_RULE_SETUP
#line 565 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
return isc::dhcp::Dhcp4Parser::make_RENEW_TIMER(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("renew-timer", driver.loc_);
}
}
YY_BREAK
case 51:
YY_RULE_SETUP
#line 576 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
return isc::dhcp::Dhcp4Parser::make_REBIND_TIMER(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("rebind-timer", driver.loc_);
}
}
YY_BREAK
case 52:
YY_RULE_SETUP
#line 587 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_DECLINE_PROBATION_PERIOD(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("decline-probation-period", driver.loc_);
}
}
YY_BREAK
case 53:
YY_RULE_SETUP
#line 596 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_SERVER_TAG(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("server-tag", driver.loc_);
}
}
YY_BREAK
case 54:
YY_RULE_SETUP
#line 605 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
return isc::dhcp::Dhcp4Parser::make_SUBNET4(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("subnet4", driver.loc_);
}
}
YY_BREAK
case 55:
YY_RULE_SETUP
#line 615 "dhcp4_lexer.ll"
{
switch (driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_SHARED_NETWORKS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("shared-networks", driver.loc_);
}
}
YY_BREAK
case 56:
YY_RULE_SETUP
#line 624 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
return isc::dhcp::Dhcp4Parser::make_OPTION_DEF(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("option-def", driver.loc_);
}
}
YY_BREAK
case 57:
YY_RULE_SETUP
#line 634 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
case isc::dhcp::Parser4Context::POOLS:
case isc::dhcp::Parser4Context::RESERVATIONS:
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
return isc::dhcp::Dhcp4Parser::make_OPTION_DATA(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("option-data", driver.loc_);
}
}
YY_BREAK
case 58:
YY_RULE_SETUP
#line 648 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
case isc::dhcp::Parser4Context::OPTION_DEF:
case isc::dhcp::Parser4Context::OPTION_DATA:
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
case isc::dhcp::Parser4Context::LOGGERS:
return isc::dhcp::Dhcp4Parser::make_NAME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("name", driver.loc_);
}
}
YY_BREAK
case 59:
YY_RULE_SETUP
#line 664 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OPTION_DATA:
return isc::dhcp::Dhcp4Parser::make_DATA(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("data", driver.loc_);
}
}
YY_BREAK
case 60:
YY_RULE_SETUP
#line 673 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OPTION_DATA:
return isc::dhcp::Dhcp4Parser::make_ALWAYS_SEND(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("always-send", driver.loc_);
}
}
YY_BREAK
case 61:
YY_RULE_SETUP
#line 682 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SUBNET4:
return isc::dhcp::Dhcp4Parser::make_POOLS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("pools", driver.loc_);
}
}
YY_BREAK
case 62:
YY_RULE_SETUP
#line 691 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::POOLS:
return isc::dhcp::Dhcp4Parser::make_POOL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("pool", driver.loc_);
}
}
YY_BREAK
case 63:
YY_RULE_SETUP
#line 700 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::INTERFACES_CONFIG:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::POOLS:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
case isc::dhcp::Parser4Context::OPTION_DEF:
case isc::dhcp::Parser4Context::OPTION_DATA:
case isc::dhcp::Parser4Context::RESERVATIONS:
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
case isc::dhcp::Parser4Context::CONTROL_SOCKET:
case isc::dhcp::Parser4Context::DHCP_QUEUE_CONTROL:
case isc::dhcp::Parser4Context::LOGGERS:
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_USER_CONTEXT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("user-context", driver.loc_);
}
}
YY_BREAK
case 64:
YY_RULE_SETUP
#line 721 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::INTERFACES_CONFIG:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::POOLS:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
case isc::dhcp::Parser4Context::OPTION_DEF:
case isc::dhcp::Parser4Context::OPTION_DATA:
case isc::dhcp::Parser4Context::RESERVATIONS:
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
case isc::dhcp::Parser4Context::CONTROL_SOCKET:
case isc::dhcp::Parser4Context::DHCP_QUEUE_CONTROL:
case isc::dhcp::Parser4Context::LOGGERS:
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_COMMENT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("comment", driver.loc_);
}
}
YY_BREAK
case 65:
YY_RULE_SETUP
#line 742 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SUBNET4:
return isc::dhcp::Dhcp4Parser::make_SUBNET(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("subnet", driver.loc_);
}
}
YY_BREAK
case 66:
YY_RULE_SETUP
#line 751 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
return isc::dhcp::Dhcp4Parser::make_INTERFACE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("interface", driver.loc_);
}
}
YY_BREAK
case 67:
YY_RULE_SETUP
#line 761 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SUBNET4:
return isc::dhcp::Dhcp4Parser::make_ID(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("id", driver.loc_);
}
}
YY_BREAK
case 68:
YY_RULE_SETUP
#line 770 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
return isc::dhcp::Dhcp4Parser::make_RESERVATION_MODE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("reservation-mode", driver.loc_);
}
}
YY_BREAK
case 69:
YY_RULE_SETUP
#line 781 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::RESERVATION_MODE:
return isc::dhcp::Dhcp4Parser::make_DISABLED(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("disabled", driver.loc_);
}
}
YY_BREAK
case 70:
YY_RULE_SETUP
#line 790 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::RESERVATION_MODE:
return isc::dhcp::Dhcp4Parser::make_DISABLED(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("off", driver.loc_);
}
}
YY_BREAK
case 71:
YY_RULE_SETUP
#line 799 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::RESERVATION_MODE:
return isc::dhcp::Dhcp4Parser::make_OUT_OF_POOL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("out-of-pool", driver.loc_);
}
}
YY_BREAK
case 72:
YY_RULE_SETUP
#line 808 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::RESERVATION_MODE:
return isc::dhcp::Dhcp4Parser::make_GLOBAL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("global", driver.loc_);
}
}
YY_BREAK
case 73:
YY_RULE_SETUP
#line 817 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::RESERVATION_MODE:
return isc::dhcp::Dhcp4Parser::make_ALL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("all", driver.loc_);
}
}
YY_BREAK
case 74:
YY_RULE_SETUP
#line 826 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OPTION_DEF:
case isc::dhcp::Parser4Context::OPTION_DATA:
return isc::dhcp::Dhcp4Parser::make_CODE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("code", driver.loc_);
}
}
YY_BREAK
case 75:
YY_RULE_SETUP
#line 836 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_HOST_RESERVATION_IDENTIFIERS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("host-reservation-identifiers", driver.loc_);
}
}
YY_BREAK
case 76:
YY_RULE_SETUP
#line 845 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::CONFIG:
return isc::dhcp::Dhcp4Parser::make_LOGGING(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("Logging", driver.loc_);
}
}
YY_BREAK
case 77:
YY_RULE_SETUP
#line 854 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LOGGING:
return isc::dhcp::Dhcp4Parser::make_LOGGERS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("loggers", driver.loc_);
}
}
YY_BREAK
case 78:
YY_RULE_SETUP
#line 863 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LOGGERS:
return isc::dhcp::Dhcp4Parser::make_OUTPUT_OPTIONS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("output_options", driver.loc_);
}
}
YY_BREAK
case 79:
YY_RULE_SETUP
#line 872 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OUTPUT_OPTIONS:
return isc::dhcp::Dhcp4Parser::make_OUTPUT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("output", driver.loc_);
}
}
YY_BREAK
case 80:
YY_RULE_SETUP
#line 881 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LOGGERS:
return isc::dhcp::Dhcp4Parser::make_DEBUGLEVEL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("debuglevel", driver.loc_);
}
}
YY_BREAK
case 81:
YY_RULE_SETUP
#line 890 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OUTPUT_OPTIONS:
return isc::dhcp::Dhcp4Parser::make_FLUSH(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("flush", driver.loc_);
}
}
YY_BREAK
case 82:
YY_RULE_SETUP
#line 899 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OUTPUT_OPTIONS:
return isc::dhcp::Dhcp4Parser::make_MAXSIZE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("maxsize", driver.loc_);
}
}
YY_BREAK
case 83:
YY_RULE_SETUP
#line 908 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OUTPUT_OPTIONS:
return isc::dhcp::Dhcp4Parser::make_MAXVER(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("maxver", driver.loc_);
}
}
YY_BREAK
case 84:
YY_RULE_SETUP
#line 917 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LOGGERS:
return isc::dhcp::Dhcp4Parser::make_SEVERITY(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("severity", driver.loc_);
}
}
YY_BREAK
case 85:
YY_RULE_SETUP
#line 926 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::RESERVATIONS:
return isc::dhcp::Dhcp4Parser::make_CLIENT_CLASSES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("client-classes", driver.loc_);
}
}
YY_BREAK
case 86:
YY_RULE_SETUP
#line 936 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::POOLS:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
return isc::dhcp::Dhcp4Parser::make_REQUIRE_CLIENT_CLASSES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("require-client-classes", driver.loc_);
}
}
YY_BREAK
case 87:
YY_RULE_SETUP
#line 947 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::POOLS:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
return isc::dhcp::Dhcp4Parser::make_CLIENT_CLASS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("client-class", driver.loc_);
}
}
YY_BREAK
case 88:
YY_RULE_SETUP
#line 959 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
return isc::dhcp::Dhcp4Parser::make_TEST(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("test", driver.loc_);
}
}
YY_BREAK
case 89:
YY_RULE_SETUP
#line 968 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
return isc::dhcp::Dhcp4Parser::make_ONLY_IF_REQUIRED(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("only-if-required", driver.loc_);
}
}
YY_BREAK
case 90:
YY_RULE_SETUP
#line 977 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
return isc::dhcp::Dhcp4Parser::make_RESERVATIONS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("reservations", driver.loc_);
}
}
YY_BREAK
case 91:
YY_RULE_SETUP
#line 987 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::HOST_RESERVATION_IDENTIFIERS:
case isc::dhcp::Parser4Context::RESERVATIONS:
return isc::dhcp::Dhcp4Parser::make_DUID(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("duid", driver.loc_);
}
}
YY_BREAK
case 92:
YY_RULE_SETUP
#line 997 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::HOST_RESERVATION_IDENTIFIERS:
case isc::dhcp::Parser4Context::RESERVATIONS:
return isc::dhcp::Dhcp4Parser::make_HW_ADDRESS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("hw-address", driver.loc_);
}
}
YY_BREAK
case 93:
YY_RULE_SETUP
#line 1007 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::HOST_RESERVATION_IDENTIFIERS:
case isc::dhcp::Parser4Context::RESERVATIONS:
return isc::dhcp::Dhcp4Parser::make_CLIENT_ID(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("client-id", driver.loc_);
}
}
YY_BREAK
case 94:
YY_RULE_SETUP
#line 1017 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::HOST_RESERVATION_IDENTIFIERS:
case isc::dhcp::Parser4Context::RESERVATIONS:
return isc::dhcp::Dhcp4Parser::make_CIRCUIT_ID(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("circuit-id", driver.loc_);
}
}
YY_BREAK
case 95:
YY_RULE_SETUP
#line 1027 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::HOST_RESERVATION_IDENTIFIERS:
case isc::dhcp::Parser4Context::RESERVATIONS:
return isc::dhcp::Dhcp4Parser::make_FLEX_ID(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("flex-id", driver.loc_);
}
}
YY_BREAK
case 96:
YY_RULE_SETUP
#line 1037 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::RESERVATIONS:
return isc::dhcp::Dhcp4Parser::make_HOSTNAME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("hostname", driver.loc_);
}
}
YY_BREAK
case 97:
YY_RULE_SETUP
#line 1046 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OPTION_DEF:
case isc::dhcp::Parser4Context::OPTION_DATA:
return isc::dhcp::Dhcp4Parser::make_SPACE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("space", driver.loc_);
}
}
YY_BREAK
case 98:
YY_RULE_SETUP
#line 1056 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OPTION_DATA:
return isc::dhcp::Dhcp4Parser::make_CSV_FORMAT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("csv-format", driver.loc_);
}
}
YY_BREAK
case 99:
YY_RULE_SETUP
#line 1065 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OPTION_DEF:
return isc::dhcp::Dhcp4Parser::make_RECORD_TYPES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("record-types", driver.loc_);
}
}
YY_BREAK
case 100:
YY_RULE_SETUP
#line 1074 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OPTION_DEF:
return isc::dhcp::Dhcp4Parser::make_ENCAPSULATE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("encapsulate", driver.loc_);
}
}
YY_BREAK
case 101:
YY_RULE_SETUP
#line 1083 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OPTION_DEF:
return isc::dhcp::Dhcp4Parser::make_ARRAY(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("array", driver.loc_);
}
}
YY_BREAK
case 102:
YY_RULE_SETUP
#line 1092 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
return isc::dhcp::Dhcp4Parser::make_RELAY(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("relay", driver.loc_);
}
}
YY_BREAK
case 103:
YY_RULE_SETUP
#line 1102 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::RELAY:
case isc::dhcp::Parser4Context::RESERVATIONS:
return isc::dhcp::Dhcp4Parser::make_IP_ADDRESS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("ip-address", driver.loc_);
}
}
YY_BREAK
case 104:
YY_RULE_SETUP
#line 1112 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::RELAY:
return isc::dhcp::Dhcp4Parser::make_IP_ADDRESSES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("ip-addresses", driver.loc_);
}
}
YY_BREAK
case 105:
YY_RULE_SETUP
#line 1121 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_HOOKS_LIBRARIES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("hooks-libraries", driver.loc_);
}
}
YY_BREAK
case 106:
YY_RULE_SETUP
#line 1131 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::HOOKS_LIBRARIES:
return isc::dhcp::Dhcp4Parser::make_PARAMETERS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("parameters", driver.loc_);
}
}
YY_BREAK
case 107:
YY_RULE_SETUP
#line 1140 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::HOOKS_LIBRARIES:
return isc::dhcp::Dhcp4Parser::make_LIBRARY(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("library", driver.loc_);
}
}
YY_BREAK
case 108:
YY_RULE_SETUP
#line 1149 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_EXPIRED_LEASES_PROCESSING(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("expired-leases-processing", driver.loc_);
}
}
YY_BREAK
case 109:
YY_RULE_SETUP
#line 1158 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::EXPIRED_LEASES_PROCESSING:
return isc::dhcp::Dhcp4Parser::make_RECLAIM_TIMER_WAIT_TIME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("reclaim-timer-wait-time", driver.loc_);
}
}
YY_BREAK
case 110:
YY_RULE_SETUP
#line 1167 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::EXPIRED_LEASES_PROCESSING:
return isc::dhcp::Dhcp4Parser::make_FLUSH_RECLAIMED_TIMER_WAIT_TIME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("flush-reclaimed-timer-wait-time", driver.loc_);
}
}
YY_BREAK
case 111:
YY_RULE_SETUP
#line 1176 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::EXPIRED_LEASES_PROCESSING:
return isc::dhcp::Dhcp4Parser::make_HOLD_RECLAIMED_TIME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("hold-reclaimed-time", driver.loc_);
}
}
YY_BREAK
case 112:
YY_RULE_SETUP
#line 1185 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::EXPIRED_LEASES_PROCESSING:
return isc::dhcp::Dhcp4Parser::make_MAX_RECLAIM_LEASES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("max-reclaim-leases", driver.loc_);
}
}
YY_BREAK
case 113:
YY_RULE_SETUP
#line 1194 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::EXPIRED_LEASES_PROCESSING:
return isc::dhcp::Dhcp4Parser::make_MAX_RECLAIM_TIME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("max-reclaim-time", driver.loc_);
}
}
YY_BREAK
case 114:
YY_RULE_SETUP
#line 1203 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::EXPIRED_LEASES_PROCESSING:
return isc::dhcp::Dhcp4Parser::make_UNWARNED_RECLAIM_CYCLES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("unwarned-reclaim-cycles", driver.loc_);
}
}
YY_BREAK
case 115:
YY_RULE_SETUP
#line 1212 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_DHCP4O6_PORT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("dhcp4o6-port", driver.loc_);
}
}
YY_BREAK
case 116:
YY_RULE_SETUP
#line 1221 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_CONTROL_SOCKET(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("control-socket", driver.loc_);
}
}
YY_BREAK
case 117:
YY_RULE_SETUP
#line 1230 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::CONTROL_SOCKET:
return isc::dhcp::Dhcp4Parser::make_SOCKET_TYPE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("socket-type", driver.loc_);
}
}
YY_BREAK
case 118:
YY_RULE_SETUP
#line 1239 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::CONTROL_SOCKET:
return isc::dhcp::Dhcp4Parser::make_SOCKET_NAME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("socket-name", driver.loc_);
}
}
YY_BREAK
case 119:
YY_RULE_SETUP
#line 1248 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_DHCP_QUEUE_CONTROL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("dhcp-queue-control", driver.loc_);
}
}
YY_BREAK
case 120:
YY_RULE_SETUP
#line 1257 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_DHCP_DDNS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("dhcp-ddns", driver.loc_);
}
}
YY_BREAK
case 121:
YY_RULE_SETUP
#line 1266 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_ENABLE_UPDATES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("enable-updates", driver.loc_);
}
}
YY_BREAK
case 122:
YY_RULE_SETUP
#line 1275 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_QUALIFYING_SUFFIX(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("qualifying-suffix", driver.loc_);
}
}
YY_BREAK
case 123:
YY_RULE_SETUP
#line 1284 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_SERVER_IP(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("server-ip", driver.loc_);
}
}
YY_BREAK
case 124:
YY_RULE_SETUP
#line 1293 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_SERVER_PORT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("server-port", driver.loc_);
}
}
YY_BREAK
case 125:
YY_RULE_SETUP
#line 1302 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_SENDER_IP(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("sender-ip", driver.loc_);
}
}
YY_BREAK
case 126:
YY_RULE_SETUP
#line 1311 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_SENDER_PORT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("sender-port", driver.loc_);
}
}
YY_BREAK
case 127:
YY_RULE_SETUP
#line 1320 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_MAX_QUEUE_SIZE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("max-queue-size", driver.loc_);
}
}
YY_BREAK
case 128:
YY_RULE_SETUP
#line 1329 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_NCR_PROTOCOL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("ncr-protocol", driver.loc_);
}
}
YY_BREAK
case 129:
YY_RULE_SETUP
#line 1338 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_NCR_FORMAT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("ncr-format", driver.loc_);
}
}
YY_BREAK
case 130:
YY_RULE_SETUP
#line 1347 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_OVERRIDE_NO_UPDATE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("override-no-update", driver.loc_);
}
}
YY_BREAK
case 131:
YY_RULE_SETUP
#line 1356 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_OVERRIDE_CLIENT_UPDATE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("override-client-update", driver.loc_);
}
}
YY_BREAK
case 132:
YY_RULE_SETUP
#line 1365 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_REPLACE_CLIENT_NAME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("replace-client-name", driver.loc_);
}
}
YY_BREAK
case 133:
YY_RULE_SETUP
#line 1374 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_GENERATED_PREFIX(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("generated-prefix", driver.loc_);
}
}
YY_BREAK
case 134:
YY_RULE_SETUP
#line 1383 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_HOSTNAME_CHAR_SET(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("hostname-char-set", driver.loc_);
}
}
YY_BREAK
case 135:
YY_RULE_SETUP
#line 1392 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_HOSTNAME_CHAR_REPLACEMENT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("hostname-char-replacement", driver.loc_);
}
}
YY_BREAK
case 136:
YY_RULE_SETUP
#line 1401 "dhcp4_lexer.ll"
{
/* dhcp-ddns value keywords are case insensitive */
if (driver.ctx_ == isc::dhcp::Parser4Context::NCR_PROTOCOL) {
return isc::dhcp::Dhcp4Parser::make_UDP(driver.loc_);
}
std::string tmp(yytext+1);
tmp.resize(tmp.size() - 1);
return isc::dhcp::Dhcp4Parser::make_STRING(tmp, driver.loc_);
}
YY_BREAK
case 137:
YY_RULE_SETUP
#line 1411 "dhcp4_lexer.ll"
{
/* dhcp-ddns value keywords are case insensitive */
if (driver.ctx_ == isc::dhcp::Parser4Context::NCR_PROTOCOL) {
return isc::dhcp::Dhcp4Parser::make_TCP(driver.loc_);
}
std::string tmp(yytext+1);
tmp.resize(tmp.size() - 1);
return isc::dhcp::Dhcp4Parser::make_STRING(tmp, driver.loc_);
}
YY_BREAK
case 138:
YY_RULE_SETUP
#line 1421 "dhcp4_lexer.ll"
{
/* dhcp-ddns value keywords are case insensitive */
if (driver.ctx_ == isc::dhcp::Parser4Context::NCR_FORMAT) {
return isc::dhcp::Dhcp4Parser::make_JSON(driver.loc_);
}
std::string tmp(yytext+1);
tmp.resize(tmp.size() - 1);
return isc::dhcp::Dhcp4Parser::make_STRING(tmp, driver.loc_);
}
YY_BREAK
case 139:
YY_RULE_SETUP
#line 1431 "dhcp4_lexer.ll"
{
/* dhcp-ddns value keywords are case insensitive */
if (driver.ctx_ == isc::dhcp::Parser4Context::REPLACE_CLIENT_NAME) {
return isc::dhcp::Dhcp4Parser::make_WHEN_PRESENT(driver.loc_);
}
std::string tmp(yytext+1);
tmp.resize(tmp.size() - 1);
return isc::dhcp::Dhcp4Parser::make_STRING(tmp, driver.loc_);
}
YY_BREAK
case 140:
YY_RULE_SETUP
#line 1441 "dhcp4_lexer.ll"
{
/* dhcp-ddns value keywords are case insensitive */
if (driver.ctx_ == isc::dhcp::Parser4Context::REPLACE_CLIENT_NAME) {
return isc::dhcp::Dhcp4Parser::make_WHEN_PRESENT(driver.loc_);
}
std::string tmp(yytext+1);
tmp.resize(tmp.size() - 1);
return isc::dhcp::Dhcp4Parser::make_STRING(tmp, driver.loc_);
}
YY_BREAK
case 141:
YY_RULE_SETUP
#line 1451 "dhcp4_lexer.ll"
{
/* dhcp-ddns value keywords are case insensitive */
if (driver.ctx_ == isc::dhcp::Parser4Context::REPLACE_CLIENT_NAME) {
return isc::dhcp::Dhcp4Parser::make_NEVER(driver.loc_);
}
std::string tmp(yytext+1);
tmp.resize(tmp.size() - 1);
return isc::dhcp::Dhcp4Parser::make_STRING(tmp, driver.loc_);
}
YY_BREAK
case 142:
YY_RULE_SETUP
#line 1461 "dhcp4_lexer.ll"
{
/* dhcp-ddns value keywords are case insensitive */
if (driver.ctx_ == isc::dhcp::Parser4Context::REPLACE_CLIENT_NAME) {
return isc::dhcp::Dhcp4Parser::make_NEVER(driver.loc_);
}
std::string tmp(yytext+1);
tmp.resize(tmp.size() - 1);
return isc::dhcp::Dhcp4Parser::make_STRING(tmp, driver.loc_);
}
YY_BREAK
case 143:
YY_RULE_SETUP
#line 1471 "dhcp4_lexer.ll"
{
/* dhcp-ddns value keywords are case insensitive */
if (driver.ctx_ == isc::dhcp::Parser4Context::REPLACE_CLIENT_NAME) {
return isc::dhcp::Dhcp4Parser::make_ALWAYS(driver.loc_);
}
std::string tmp(yytext+1);
tmp.resize(tmp.size() - 1);
return isc::dhcp::Dhcp4Parser::make_STRING(tmp, driver.loc_);
}
YY_BREAK
case 144:
YY_RULE_SETUP
#line 1481 "dhcp4_lexer.ll"
{
/* dhcp-ddns value keywords are case insensitive */
if (driver.ctx_ == isc::dhcp::Parser4Context::REPLACE_CLIENT_NAME) {
return isc::dhcp::Dhcp4Parser::make_WHEN_NOT_PRESENT(driver.loc_);
}
std::string tmp(yytext+1);
tmp.resize(tmp.size() - 1);
return isc::dhcp::Dhcp4Parser::make_STRING(tmp, driver.loc_);
}
YY_BREAK
case 145:
YY_RULE_SETUP
#line 1491 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::CONFIG:
return isc::dhcp::Dhcp4Parser::make_DHCP6(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("Dhcp6", driver.loc_);
}
}
YY_BREAK
case 146:
YY_RULE_SETUP
#line 1500 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::CONFIG:
return isc::dhcp::Dhcp4Parser::make_DHCPDDNS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("DhcpDdns", driver.loc_);
}
}
YY_BREAK
case 147:
YY_RULE_SETUP
#line 1509 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::CONFIG:
return isc::dhcp::Dhcp4Parser::make_CONTROL_AGENT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("Control-agent", driver.loc_);
}
}
YY_BREAK
case 148:
YY_RULE_SETUP
#line 1518 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SUBNET4:
return isc::dhcp::Dhcp4Parser::make_SUBNET_4O6_INTERFACE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("4o6-interface", driver.loc_);
}
}
YY_BREAK
case 149:
YY_RULE_SETUP
#line 1527 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SUBNET4:
return isc::dhcp::Dhcp4Parser::make_SUBNET_4O6_INTERFACE_ID(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("4o6-interface-id", driver.loc_);
}
}
YY_BREAK
case 150:
YY_RULE_SETUP
#line 1536 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SUBNET4:
return isc::dhcp::Dhcp4Parser::make_SUBNET_4O6_SUBNET(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("4o6-subnet", driver.loc_);
}
}
YY_BREAK
case 151:
YY_RULE_SETUP
#line 1545 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_ECHO_CLIENT_ID(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("echo-client-id", driver.loc_);
}
}
YY_BREAK
case 152:
YY_RULE_SETUP
#line 1554 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
return isc::dhcp::Dhcp4Parser::make_MATCH_CLIENT_ID(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("match-client-id", driver.loc_);
}
}
YY_BREAK
case 153:
YY_RULE_SETUP
#line 1565 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
return isc::dhcp::Dhcp4Parser::make_AUTHORITATIVE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("authoritative", driver.loc_);
}
}
YY_BREAK
case 154:
YY_RULE_SETUP
#line 1576 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
case isc::dhcp::Parser4Context::RESERVATIONS:
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
return isc::dhcp::Dhcp4Parser::make_NEXT_SERVER(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("next-server", driver.loc_);
}
}
YY_BREAK
case 155:
YY_RULE_SETUP
#line 1589 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
case isc::dhcp::Parser4Context::RESERVATIONS:
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
return isc::dhcp::Dhcp4Parser::make_SERVER_HOSTNAME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("server-hostname", driver.loc_);
}
}
YY_BREAK
case 156:
YY_RULE_SETUP
#line 1602 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
case isc::dhcp::Parser4Context::RESERVATIONS:
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
return isc::dhcp::Dhcp4Parser::make_BOOT_FILE_NAME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("boot-file-name", driver.loc_);
}
}
YY_BREAK
case 157:
YY_RULE_SETUP
#line 1617 "dhcp4_lexer.ll"
{
/* A string has been matched. It contains the actual string and single quotes.
We need to get those quotes out of the way and just use its content, e.g.
for 'foo' we should get foo */
std::string raw(yytext+1);
size_t len = raw.size() - 1;
raw.resize(len);
std::string decoded;
decoded.reserve(len);
for (size_t pos = 0; pos < len; ++pos) {
int b = 0;
char c = raw[pos];
switch (c) {
case '"':
/* impossible condition */
driver.error(driver.loc_, "Bad quote in \"" + raw + "\"");
break;
case '\\':
++pos;
if (pos >= len) {
/* impossible condition */
driver.error(driver.loc_, "Overflow escape in \"" + raw + "\"");
}
c = raw[pos];
switch (c) {
case '"':
case '\\':
case '/':
decoded.push_back(c);
break;
case 'b':
decoded.push_back('\b');
break;
case 'f':
decoded.push_back('\f');
break;
case 'n':
decoded.push_back('\n');
break;
case 'r':
decoded.push_back('\r');
break;
case 't':
decoded.push_back('\t');
break;
case 'u':
/* support only \u0000 to \u00ff */
++pos;
if (pos + 4 > len) {
/* impossible condition */
driver.error(driver.loc_,
"Overflow unicode escape in \"" + raw + "\"");
}
if ((raw[pos] != '0') || (raw[pos + 1] != '0')) {
driver.error(driver.loc_, "Unsupported unicode escape in \"" + raw + "\"");
}
pos += 2;
c = raw[pos];
if ((c >= '0') && (c <= '9')) {
b = (c - '0') << 4;
} else if ((c >= 'A') && (c <= 'F')) {
b = (c - 'A' + 10) << 4;
} else if ((c >= 'a') && (c <= 'f')) {
b = (c - 'a' + 10) << 4;
} else {
/* impossible condition */
driver.error(driver.loc_, "Not hexadecimal in unicode escape in \"" + raw + "\"");
}
pos++;
c = raw[pos];
if ((c >= '0') && (c <= '9')) {
b |= c - '0';
} else if ((c >= 'A') && (c <= 'F')) {
b |= c - 'A' + 10;
} else if ((c >= 'a') && (c <= 'f')) {
b |= c - 'a' + 10;
} else {
/* impossible condition */
driver.error(driver.loc_, "Not hexadecimal in unicode escape in \"" + raw + "\"");
}
decoded.push_back(static_cast<char>(b & 0xff));
break;
default:
/* impossible condition */
driver.error(driver.loc_, "Bad escape in \"" + raw + "\"");
}
break;
default:
if ((c >= 0) && (c < 0x20)) {
/* impossible condition */
driver.error(driver.loc_, "Invalid control in \"" + raw + "\"");
}
decoded.push_back(c);
}
}
return isc::dhcp::Dhcp4Parser::make_STRING(decoded, driver.loc_);
}
YY_BREAK
case 158:
/* rule 158 can match eol */
YY_RULE_SETUP
#line 1716 "dhcp4_lexer.ll"
{
/* Bad string with a forbidden control character inside */
driver.error(driver.loc_, "Invalid control in " + std::string(yytext));
}
YY_BREAK
case 159:
/* rule 159 can match eol */
YY_RULE_SETUP
#line 1721 "dhcp4_lexer.ll"
{
/* Bad string with a bad escape inside */
driver.error(driver.loc_, "Bad escape in " + std::string(yytext));
}
YY_BREAK
case 160:
YY_RULE_SETUP
#line 1726 "dhcp4_lexer.ll"
{
/* Bad string with an open escape at the end */
driver.error(driver.loc_, "Overflow escape in " + std::string(yytext));
}
YY_BREAK
case 161:
YY_RULE_SETUP
#line 1731 "dhcp4_lexer.ll"
{ return isc::dhcp::Dhcp4Parser::make_LSQUARE_BRACKET(driver.loc_); }
YY_BREAK
case 162:
YY_RULE_SETUP
#line 1732 "dhcp4_lexer.ll"
{ return isc::dhcp::Dhcp4Parser::make_RSQUARE_BRACKET(driver.loc_); }
YY_BREAK
case 163:
YY_RULE_SETUP
#line 1733 "dhcp4_lexer.ll"
{ return isc::dhcp::Dhcp4Parser::make_LCURLY_BRACKET(driver.loc_); }
YY_BREAK
case 164:
YY_RULE_SETUP
#line 1734 "dhcp4_lexer.ll"
{ return isc::dhcp::Dhcp4Parser::make_RCURLY_BRACKET(driver.loc_); }
YY_BREAK
case 165:
YY_RULE_SETUP
#line 1735 "dhcp4_lexer.ll"
{ return isc::dhcp::Dhcp4Parser::make_COMMA(driver.loc_); }
YY_BREAK
case 166:
YY_RULE_SETUP
#line 1736 "dhcp4_lexer.ll"
{ return isc::dhcp::Dhcp4Parser::make_COLON(driver.loc_); }
YY_BREAK
case 167:
YY_RULE_SETUP
#line 1738 "dhcp4_lexer.ll"
{
/* An integer was found. */
std::string tmp(yytext);
int64_t integer = 0;
try {
/* In substring we want to use negative values (e.g. -1).
In enterprise-id we need to use values up to 0xffffffff.
To cover both of those use cases, we need at least
int64_t. */
integer = boost::lexical_cast<int64_t>(tmp);
} catch (const boost::bad_lexical_cast &) {
driver.error(driver.loc_, "Failed to convert " + tmp + " to an integer.");
}
/* The parser needs the string form as double conversion is no lossless */
return isc::dhcp::Dhcp4Parser::make_INTEGER(integer, driver.loc_);
}
YY_BREAK
case 168:
YY_RULE_SETUP
#line 1756 "dhcp4_lexer.ll"
{
/* A floating point was found. */
std::string tmp(yytext);
double fp = 0.0;
try {
fp = boost::lexical_cast<double>(tmp);
} catch (const boost::bad_lexical_cast &) {
driver.error(driver.loc_, "Failed to convert " + tmp + " to a floating point.");
}
return isc::dhcp::Dhcp4Parser::make_FLOAT(fp, driver.loc_);
}
YY_BREAK
case 169:
YY_RULE_SETUP
#line 1769 "dhcp4_lexer.ll"
{
string tmp(yytext);
return isc::dhcp::Dhcp4Parser::make_BOOLEAN(tmp == "true", driver.loc_);
}
YY_BREAK
case 170:
YY_RULE_SETUP
#line 1774 "dhcp4_lexer.ll"
{
return isc::dhcp::Dhcp4Parser::make_NULL_TYPE(driver.loc_);
}
YY_BREAK
case 171:
YY_RULE_SETUP
#line 1778 "dhcp4_lexer.ll"
driver.error (driver.loc_, "JSON true reserved keyword is lower case only");
YY_BREAK
case 172:
YY_RULE_SETUP
#line 1780 "dhcp4_lexer.ll"
driver.error (driver.loc_, "JSON false reserved keyword is lower case only");
YY_BREAK
case 173:
YY_RULE_SETUP
#line 1782 "dhcp4_lexer.ll"
driver.error (driver.loc_, "JSON null reserved keyword is lower case only");
YY_BREAK
case 174:
YY_RULE_SETUP
#line 1784 "dhcp4_lexer.ll"
driver.error (driver.loc_, "Invalid character: " + std::string(yytext));
YY_BREAK
case YY_STATE_EOF(INITIAL):
#line 1786 "dhcp4_lexer.ll"
{
if (driver.states_.empty()) {
return isc::dhcp::Dhcp4Parser::make_END(driver.loc_);
}
driver.loc_ = driver.locs_.back();
driver.locs_.pop_back();
driver.file_ = driver.files_.back();
driver.files_.pop_back();
if (driver.sfile_) {
fclose(driver.sfile_);
driver.sfile_ = 0;
}
if (!driver.sfiles_.empty()) {
driver.sfile_ = driver.sfiles_.back();
driver.sfiles_.pop_back();
}
parser4__delete_buffer(YY_CURRENT_BUFFER);
parser4__switch_to_buffer(driver.states_.back());
driver.states_.pop_back();
BEGIN(DIR_EXIT);
}
YY_BREAK
case 175:
YY_RULE_SETUP
#line 1809 "dhcp4_lexer.ll"
ECHO;
YY_BREAK
#line 4390 "dhcp4_lexer.cc"
case YY_END_OF_BUFFER:
{
/* Amount of text matched not including the EOB char. */
int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1;
/* Undo the effects of YY_DO_BEFORE_ACTION. */
*yy_cp = (yy_hold_char);
YY_RESTORE_YY_MORE_OFFSET
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
{
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed yyin at a new source and called
* yylex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
* back-up) that will match for the new input source.
*/
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
/* %if-c-only */
YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
/* %endif */
/* %if-c++-only */
/* %endif */
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
}
/* Note that here we test for yy_c_buf_p "<=" to the position
* of the first EOB in the buffer, since yy_c_buf_p will
* already have been incremented past the NUL character
* (since all states make transitions on EOB to the
* end-of-buffer state). Contrast this with the test
* in input().
*/
if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
{ /* This was really a NUL. */
yy_state_type yy_next_state;
(yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
/* Okay, we're now positioned to make the NUL
* transition. We couldn't have
* yy_get_previous_state() go ahead and do it
* for us because it doesn't know how to deal
* with the possibility of jamming (and we don't
* want to build jamming into it because then it
* will run more slowly).
*/
yy_next_state = yy_try_NUL_trans( yy_current_state );
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
if ( yy_next_state )
{
/* Consume the NUL. */
yy_cp = ++(yy_c_buf_p);
yy_current_state = yy_next_state;
goto yy_match;
}
else
{
/* %% [14.0] code to do back-up for compressed tables and set up yy_cp goes here */
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
goto yy_find_action;
}
}
else switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_END_OF_FILE:
{
(yy_did_buffer_switch_on_eof) = 0;
if ( yywrap( ) )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
* yytext, we can now set up
* yy_c_buf_p so that if some total
* hoser (like flex itself) wants to
* call the scanner after we return the
* YY_NULL, it'll still work - another
* YY_NULL will get returned.
*/
(yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ;
yy_act = YY_STATE_EOF(YY_START);
goto do_action;
}
else
{
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
}
break;
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) =
(yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_match;
case EOB_ACT_LAST_MATCH:
(yy_c_buf_p) =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)];
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_find_action;
}
break;
}
default:
YY_FATAL_ERROR(
"fatal flex scanner internal error--no action found" );
} /* end of action switch */
} /* end of scanning one token */
} /* end of user's declarations */
} /* end of yylex */
/* %ok-for-header */
/* %if-c++-only */
/* %not-for-header */
/* %ok-for-header */
/* %endif */
/* yy_get_next_buffer - try to read in a new buffer
*
* Returns a code representing an action:
* EOB_ACT_LAST_MATCH -
* EOB_ACT_CONTINUE_SCAN - continue scanning from current position
* EOB_ACT_END_OF_FILE - end of file
*/
/* %if-c-only */
static int yy_get_next_buffer (void)
/* %endif */
/* %if-c++-only */
/* %endif */
{
char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
char *source = (yytext_ptr);
int number_to_move, i;
int ret_val;
if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] )
YY_FATAL_ERROR(
"fatal flex scanner internal error--end of buffer missed" );
if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
{ /* Don't try to fill the buffer, so this is an EOF. */
if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 )
{
/* We matched a single character, the EOB, so
* treat this as a final EOF.
*/
return EOB_ACT_END_OF_FILE;
}
else
{
/* We matched some text prior to the EOB, first
* process it.
*/
return EOB_ACT_LAST_MATCH;
}
}
/* Try to read more data. */
/* First move last chars to start of buffer. */
number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr) - 1);
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
/* don't do the read, it's not guaranteed to return an EOF,
* just force an EOF
*/
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0;
else
{
int num_to_read =
YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
while ( num_to_read <= 0 )
{ /* Not enough room in the buffer - grow it. */
/* just a shorter name for the current buffer */
YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE;
int yy_c_buf_p_offset =
(int) ((yy_c_buf_p) - b->yy_ch_buf);
if ( b->yy_is_our_buffer )
{
int new_size = b->yy_buf_size * 2;
if ( new_size <= 0 )
b->yy_buf_size += b->yy_buf_size / 8;
else
b->yy_buf_size *= 2;
b->yy_ch_buf = (char *)
/* Include room in for 2 EOB chars. */
yyrealloc( (void *) b->yy_ch_buf,
(yy_size_t) (b->yy_buf_size + 2) );
}
else
/* Can't grow it, we don't own it. */
b->yy_ch_buf = NULL;
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR(
"fatal error - scanner input buffer overflow" );
(yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset];
num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
number_to_move - 1;
}
if ( num_to_read > YY_READ_BUF_SIZE )
num_to_read = YY_READ_BUF_SIZE;
/* Read in more data. */
YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
(yy_n_chars), num_to_read );
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
if ( (yy_n_chars) == 0 )
{
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
yyrestart( yyin );
}
else
{
ret_val = EOB_ACT_LAST_MATCH;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
YY_BUFFER_EOF_PENDING;
}
}
else
ret_val = EOB_ACT_CONTINUE_SCAN;
if (((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
int new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1);
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc(
(void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf, (yy_size_t) new_size );
if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
/* "- 2" to take care of EOB's */
YY_CURRENT_BUFFER_LVALUE->yy_buf_size = (int) (new_size - 2);
}
(yy_n_chars) += number_to_move;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR;
(yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
return ret_val;
}
/* yy_get_previous_state - get the state just before the EOB char was reached */
/* %if-c-only */
/* %not-for-header */
static yy_state_type yy_get_previous_state (void)
/* %endif */
/* %if-c++-only */
/* %endif */
{
yy_state_type yy_current_state;
char *yy_cp;
/* %% [15.0] code to get the start state into yy_current_state goes here */
yy_current_state = (yy_start);
for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp )
{
/* %% [16.0] code to find the next state goes here */
YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 1468 )
yy_c = yy_meta[yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
}
return yy_current_state;
}
/* yy_try_NUL_trans - try to make a transition on the NUL character
*
* synopsis
* next_state = yy_try_NUL_trans( current_state );
*/
/* %if-c-only */
static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state )
/* %endif */
/* %if-c++-only */
/* %endif */
{
int yy_is_jam;
/* %% [17.0] code to find the next state, and perhaps do backing up, goes here */
char *yy_cp = (yy_c_buf_p);
YY_CHAR yy_c = 1;
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 1468 )
yy_c = yy_meta[yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
yy_is_jam = (yy_current_state == 1467);
return yy_is_jam ? 0 : yy_current_state;
}
#ifndef YY_NO_UNPUT
/* %if-c-only */
/* %endif */
#endif
/* %if-c-only */
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (void)
#else
static int input (void)
#endif
/* %endif */
/* %if-c++-only */
/* %endif */
{
int c;
*(yy_c_buf_p) = (yy_hold_char);
if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR )
{
/* yy_c_buf_p now points to the character we want to return.
* If this occurs *before* the EOB characters, then it's a
* valid NUL; if not, then we've hit the end of the buffer.
*/
if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
/* This was really a NUL. */
*(yy_c_buf_p) = '\0';
else
{ /* need more input */
int offset = (int) ((yy_c_buf_p) - (yytext_ptr));
++(yy_c_buf_p);
switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_LAST_MATCH:
/* This happens because yy_g_n_b()
* sees that we've accumulated a
* token and flags that we need to
* try matching the token before
* proceeding. But for input(),
* there's no matching to consider.
* So convert the EOB_ACT_LAST_MATCH
* to EOB_ACT_END_OF_FILE.
*/
/* Reset buffer status. */
yyrestart( yyin );
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE:
{
if ( yywrap( ) )
return 0;
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
#ifdef __cplusplus
return yyinput();
#else
return input();
#endif
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) = (yytext_ptr) + offset;
break;
}
}
}
c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */
*(yy_c_buf_p) = '\0'; /* preserve yytext */
(yy_hold_char) = *++(yy_c_buf_p);
/* %% [19.0] update BOL and yylineno */
return c;
}
/* %if-c-only */
#endif /* ifndef YY_NO_INPUT */
/* %endif */
/** Immediately switch to a different input stream.
* @param input_file A readable stream.
*
* @note This function does not reset the start condition to @c INITIAL .
*/
/* %if-c-only */
void yyrestart (FILE * input_file )
/* %endif */
/* %if-c++-only */
/* %endif */
{
if ( ! YY_CURRENT_BUFFER ){
yyensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer( yyin, YY_BUF_SIZE );
}
yy_init_buffer( YY_CURRENT_BUFFER, input_file );
yy_load_buffer_state( );
}
/* %if-c++-only */
/* %endif */
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
*
*/
/* %if-c-only */
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer )
/* %endif */
/* %if-c++-only */
/* %endif */
{
/* TODO. We should be able to replace this entire function body
* with
* yypop_buffer_state();
* yypush_buffer_state(new_buffer);
*/
yyensure_buffer_stack ();
if ( YY_CURRENT_BUFFER == new_buffer )
return;
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
yy_load_buffer_state( );
/* We don't actually know whether we did this switch during
* EOF (yywrap()) processing, but the only time this flag
* is looked at is after yywrap() is called, so it's safe
* to go ahead and always set it.
*/
(yy_did_buffer_switch_on_eof) = 1;
}
/* %if-c-only */
static void yy_load_buffer_state (void)
/* %endif */
/* %if-c++-only */
/* %endif */
{
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
(yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
/* %if-c-only */
yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
/* %endif */
/* %if-c++-only */
/* %endif */
(yy_hold_char) = *(yy_c_buf_p);
}
/** Allocate and initialize an input buffer state.
* @param file A readable stream.
* @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
*
* @return the allocated buffer state.
*/
/* %if-c-only */
YY_BUFFER_STATE yy_create_buffer (FILE * file, int size )
/* %endif */
/* %if-c++-only */
/* %endif */
{
YY_BUFFER_STATE b;
b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_buf_size = size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
b->yy_ch_buf = (char *) yyalloc( (yy_size_t) (b->yy_buf_size + 2) );
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_is_our_buffer = 1;
yy_init_buffer( b, file );
return b;
}
/* %if-c++-only */
/* %endif */
/** Destroy the buffer.
* @param b a buffer created with yy_create_buffer()
*
*/
/* %if-c-only */
void yy_delete_buffer (YY_BUFFER_STATE b )
/* %endif */
/* %if-c++-only */
/* %endif */
{
if ( ! b )
return;
if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
yyfree( (void *) b->yy_ch_buf );
yyfree( (void *) b );
}
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
* such as during a yyrestart() or at EOF.
*/
/* %if-c-only */
static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file )
/* %endif */
/* %if-c++-only */
/* %endif */
{
int oerrno = errno;
yy_flush_buffer( b );
/* %if-c-only */
b->yy_input_file = file;
/* %endif */
/* %if-c++-only */
/* %endif */
b->yy_fill_buffer = 1;
/* If b is the current buffer, then yy_init_buffer was _probably_
* called from yyrestart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER){
b->yy_bs_lineno = 1;
b->yy_bs_column = 0;
}
/* %if-c-only */
b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
/* %endif */
/* %if-c++-only */
/* %endif */
errno = oerrno;
}
/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
*
*/
/* %if-c-only */
void yy_flush_buffer (YY_BUFFER_STATE b )
/* %endif */
/* %if-c++-only */
/* %endif */
{
if ( ! b )
return;
b->yy_n_chars = 0;
/* We always need two end-of-buffer characters. The first causes
* a transition to the end-of-buffer state. The second causes
* a jam in that state.
*/
b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
b->yy_buf_pos = &b->yy_ch_buf[0];
b->yy_at_bol = 1;
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == YY_CURRENT_BUFFER )
yy_load_buffer_state( );
}
/* %if-c-or-c++ */
/** Pushes the new state onto the stack. The new state becomes
* the current state. This function will allocate the stack
* if necessary.
* @param new_buffer The new state.
*
*/
/* %if-c-only */
void yypush_buffer_state (YY_BUFFER_STATE new_buffer )
/* %endif */
/* %if-c++-only */
/* %endif */
{
if (new_buffer == NULL)
return;
yyensure_buffer_stack();
/* This block is copied from yy_switch_to_buffer. */
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
/* Only push if top exists. Otherwise, replace top. */
if (YY_CURRENT_BUFFER)
(yy_buffer_stack_top)++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
/* copied from yy_switch_to_buffer. */
yy_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
/* %endif */
/* %if-c-or-c++ */
/** Removes and deletes the top of the stack, if present.
* The next element becomes the new top.
*
*/
/* %if-c-only */
void yypop_buffer_state (void)
/* %endif */
/* %if-c++-only */
/* %endif */
{
if (!YY_CURRENT_BUFFER)
return;
yy_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
if ((yy_buffer_stack_top) > 0)
--(yy_buffer_stack_top);
if (YY_CURRENT_BUFFER) {
yy_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
}
/* %endif */
/* %if-c-or-c++ */
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
/* %if-c-only */
static void yyensure_buffer_stack (void)
/* %endif */
/* %if-c++-only */
/* %endif */
{
yy_size_t num_to_alloc;
if (!(yy_buffer_stack)) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */
(yy_buffer_stack) = (struct yy_buffer_state**)yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
(yy_buffer_stack_top) = 0;
return;
}
if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){
/* Increase the buffer to prepare for a possible push. */
yy_size_t grow_size = 8 /* arbitrary grow size */;
num_to_alloc = (yy_buffer_stack_max) + grow_size;
(yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc
((yy_buffer_stack),
num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
}
}
/* %endif */
/* %if-c-only */
/** Setup the input buffer state to scan directly from a user-specified character buffer.
* @param base the character buffer
* @param size the size in bytes of the character buffer
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size )
{
YY_BUFFER_STATE b;
if ( size < 2 ||
base[size-2] != YY_END_OF_BUFFER_CHAR ||
base[size-1] != YY_END_OF_BUFFER_CHAR )
/* They forgot to leave room for the EOB's. */
return NULL;
b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
b->yy_buf_size = (int) (size - 2); /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = NULL;
b->yy_n_chars = b->yy_buf_size;
b->yy_is_interactive = 0;
b->yy_at_bol = 1;
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
yy_switch_to_buffer( b );
return b;
}
/* %endif */
/* %if-c-only */
/** Setup the input buffer state to scan a string. The next call to yylex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
*
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
* yy_scan_bytes() instead.
*/
YY_BUFFER_STATE yy_scan_string (const char * yystr )
{
return yy_scan_bytes( yystr, (int) strlen(yystr) );
}
/* %endif */
/* %if-c-only */
/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
* scan from a @e copy of @a bytes.
* @param yybytes the byte buffer to scan
* @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes.
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_bytes (const char * yybytes, int _yybytes_len )
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n;
int i;
/* Get memory for full buffer, including space for trailing EOB's. */
n = (yy_size_t) (_yybytes_len + 2);
buf = (char *) yyalloc( n );
if ( ! buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
for ( i = 0; i < _yybytes_len; ++i )
buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
b = yy_scan_buffer( buf, n );
if ( ! b )
YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
*/
b->yy_is_our_buffer = 1;
return b;
}
/* %endif */
#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif
/* %if-c-only */
static void yynoreturn yy_fatal_error (const char* msg )
{
fprintf( stderr, "%s\n", msg );
exit( YY_EXIT_FAILURE );
}
/* %endif */
/* %if-c++-only */
/* %endif */
/* Redefine yyless() so it works in section 3 code. */
#undef yyless
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
yytext[yyleng] = (yy_hold_char); \
(yy_c_buf_p) = yytext + yyless_macro_arg; \
(yy_hold_char) = *(yy_c_buf_p); \
*(yy_c_buf_p) = '\0'; \
yyleng = yyless_macro_arg; \
} \
while ( 0 )
/* Accessor methods (get/set functions) to struct members. */
/* %if-c-only */
/* %if-reentrant */
/* %endif */
/** Get the current line number.
*
*/
int yyget_lineno (void)
{
return yylineno;
}
/** Get the input stream.
*
*/
FILE *yyget_in (void)
{
return yyin;
}
/** Get the output stream.
*
*/
FILE *yyget_out (void)
{
return yyout;
}
/** Get the length of the current token.
*
*/
int yyget_leng (void)
{
return yyleng;
}
/** Get the current token.
*
*/
char *yyget_text (void)
{
return yytext;
}
/* %if-reentrant */
/* %endif */
/** Set the current line number.
* @param _line_number line number
*
*/
void yyset_lineno (int _line_number )
{
yylineno = _line_number;
}
/** Set the input stream. This does not discard the current
* input buffer.
* @param _in_str A readable stream.
*
* @see yy_switch_to_buffer
*/
void yyset_in (FILE * _in_str )
{
yyin = _in_str ;
}
void yyset_out (FILE * _out_str )
{
yyout = _out_str ;
}
int yyget_debug (void)
{
return yy_flex_debug;
}
void yyset_debug (int _bdebug )
{
yy_flex_debug = _bdebug ;
}
/* %endif */
/* %if-reentrant */
/* %if-bison-bridge */
/* %endif */
/* %endif if-c-only */
/* %if-c-only */
static int yy_init_globals (void)
{
/* Initialization is the same as for the non-reentrant scanner.
* This function is called from yylex_destroy(), so don't allocate here.
*/
(yy_buffer_stack) = NULL;
(yy_buffer_stack_top) = 0;
(yy_buffer_stack_max) = 0;
(yy_c_buf_p) = NULL;
(yy_init) = 0;
(yy_start) = 0;
/* Defined in main.c */
#ifdef YY_STDINIT
yyin = stdin;
yyout = stdout;
#else
yyin = NULL;
yyout = NULL;
#endif
/* For future reference: Set errno on error, since we are called by
* yylex_init()
*/
return 0;
}
/* %endif */
/* %if-c-only SNIP! this currently causes conflicts with the c++ scanner */
/* yylex_destroy is for both reentrant and non-reentrant scanners. */
int yylex_destroy (void)
{
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
yy_delete_buffer( YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
yypop_buffer_state();
}
/* Destroy the stack itself. */
yyfree((yy_buffer_stack) );
(yy_buffer_stack) = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
* yylex() is called, initialization will occur. */
yy_init_globals( );
/* %if-reentrant */
/* %endif */
return 0;
}
/* %endif */
/*
* Internal utility routines.
*/
#ifndef yytext_ptr
static void yy_flex_strncpy (char* s1, const char * s2, int n )
{
int i;
for ( i = 0; i < n; ++i )
s1[i] = s2[i];
}
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (const char * s )
{
int n;
for ( n = 0; s[n]; ++n )
;
return n;
}
#endif
void *yyalloc (yy_size_t size )
{
return malloc(size);
}
void *yyrealloc (void * ptr, yy_size_t size )
{
/* The cast to (char *) in the following accommodates both
* implementations that use char* generic pointers, and those
* that use void* generic pointers. It works with the latter
* because both ANSI C and C++ allow castless assignment from
* any pointer type to void*, and deal with argument conversions
* as though doing an assignment.
*/
return realloc(ptr, size);
}
void yyfree (void * ptr )
{
free( (char *) ptr ); /* see yyrealloc() for (char *) cast */
}
/* %if-tables-serialization definitions */
/* %define-yytables The name for this specific scanner's tables. */
#define YYTABLES_NAME "yytables"
/* %endif */
/* %ok-for-header */
#line 1809 "dhcp4_lexer.ll"
using namespace isc::dhcp;
void
Parser4Context::scanStringBegin(const std::string& str, ParserType parser_type)
{
start_token_flag = true;
start_token_value = parser_type;
file_ = "<string>";
sfile_ = 0;
loc_.initialize(&file_);
yy_flex_debug = trace_scanning_;
YY_BUFFER_STATE buffer;
buffer = parser4__scan_bytes(str.c_str(), str.size());
if (!buffer) {
fatal("cannot scan string");
/* fatal() throws an exception so this can't be reached */
}
}
void
Parser4Context::scanFileBegin(FILE * f,
const std::string& filename,
ParserType parser_type)
{
start_token_flag = true;
start_token_value = parser_type;
file_ = filename;
sfile_ = f;
loc_.initialize(&file_);
yy_flex_debug = trace_scanning_;
YY_BUFFER_STATE buffer;
/* See dhcp4_lexer.cc header for available definitions */
buffer = parser4__create_buffer(f, 65536 /*buffer size*/);
if (!buffer) {
fatal("cannot scan file " + filename);
}
parser4__switch_to_buffer(buffer);
}
void
Parser4Context::scanEnd() {
if (sfile_)
fclose(sfile_);
sfile_ = 0;
static_cast<void>(parser4_lex_destroy());
/* Close files */
while (!sfiles_.empty()) {
FILE* f = sfiles_.back();
if (f) {
fclose(f);
}
sfiles_.pop_back();
}
/* Delete states */
while (!states_.empty()) {
parser4__delete_buffer(states_.back());
states_.pop_back();
}
}
void
Parser4Context::includeFile(const std::string& filename) {
if (states_.size() > 10) {
fatal("Too many nested include.");
}
FILE* f = fopen(filename.c_str(), "r");
if (!f) {
fatal("Can't open include file " + filename);
}
if (sfile_) {
sfiles_.push_back(sfile_);
}
sfile_ = f;
states_.push_back(YY_CURRENT_BUFFER);
YY_BUFFER_STATE buffer;
buffer = parser4__create_buffer(f, 65536 /*buffer size*/);
if (!buffer) {
fatal( "Can't scan include file " + filename);
}
parser4__switch_to_buffer(buffer);
files_.push_back(file_);
file_ = filename;
locs_.push_back(loc_);
loc_.initialize(&file_);
BEGIN(INITIAL);
}
namespace {
/** To avoid unused function error */
class Dummy {
/* cppcheck-suppress unusedPrivateFunction */
void dummy() { yy_fatal_error("Fix me: how to disable its definition?"); }
};
}
#endif /* !__clang_analyzer__ */
| 31.63172 | 102 | 0.591329 | mcr |
99498d75c3ba0878a454dc0cf2205c6eba578045 | 5,362 | cpp | C++ | thirdparty/qtiplot/qtiplot/src/matrix/MatrixSizeDialog.cpp | hoehnp/SpaceDesignTool | 9abd34048274b2ce9dbbb685124177b02d6a34ca | [
"IJG"
] | 6 | 2018-09-05T12:41:59.000Z | 2021-07-01T05:34:23.000Z | thirdparty/qtiplot/qtiplot/src/matrix/MatrixSizeDialog.cpp | hoehnp/SpaceDesignTool | 9abd34048274b2ce9dbbb685124177b02d6a34ca | [
"IJG"
] | 2 | 2015-02-07T19:09:21.000Z | 2015-08-14T03:15:42.000Z | thirdparty/qtiplot/qtiplot/src/matrix/MatrixSizeDialog.cpp | hoehnp/SpaceDesignTool | 9abd34048274b2ce9dbbb685124177b02d6a34ca | [
"IJG"
] | 2 | 2015-03-25T15:50:31.000Z | 2017-12-06T12:16:47.000Z | /***************************************************************************
File : MatrixSizeDialog.cpp
Project : QtiPlot
--------------------------------------------------------------------
Copyright : (C) 2004-2008 by Ion Vasilief
Email (use @ for *) : ion_vasilief*yahoo.fr
Description : Matrix dimensions dialog
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, *
* Boston, MA 02110-1301 USA *
* *
***************************************************************************/
#include "MatrixSizeDialog.h"
#include "MatrixCommand.h"
#include "../DoubleSpinBox.h"
#include <QPushButton>
#include <QLabel>
#include <QGroupBox>
#include <QSpinBox>
#include <QMessageBox>
#include <QLayout>
MatrixSizeDialog::MatrixSizeDialog( Matrix *m, QWidget* parent, Qt::WFlags fl )
: QDialog( parent, fl ),
d_matrix(m)
{
setWindowTitle(tr("QtiPlot - Matrix Dimensions"));
groupBox1 = new QGroupBox(tr("Dimensions"));
QHBoxLayout *topLayout = new QHBoxLayout(groupBox1);
topLayout->addWidget( new QLabel(tr( "Rows" )) );
boxRows = new QSpinBox();
boxRows->setRange(1, 1000000);
topLayout->addWidget(boxRows);
topLayout->addStretch();
topLayout->addWidget( new QLabel(tr( "Columns" )) );
boxCols = new QSpinBox();
boxCols->setRange(1, 1000000);
topLayout->addWidget(boxCols);
groupBox2 = new QGroupBox(tr("Coordinates"));
QGridLayout *centerLayout = new QGridLayout(groupBox2);
centerLayout->addWidget( new QLabel(tr( "X (Columns)" )), 0, 1 );
centerLayout->addWidget( new QLabel(tr( "Y (Rows)" )), 0, 2 );
centerLayout->addWidget( new QLabel(tr( "First" )), 1, 0 );
QLocale locale = m->locale();
boxXStart = new DoubleSpinBox();
boxXStart->setLocale(locale);
centerLayout->addWidget( boxXStart, 1, 1 );
boxYStart = new DoubleSpinBox();
boxYStart->setLocale(locale);
centerLayout->addWidget( boxYStart, 1, 2 );
centerLayout->addWidget( new QLabel(tr( "Last" )), 2, 0 );
boxXEnd = new DoubleSpinBox();
boxXEnd->setLocale(locale);
centerLayout->addWidget( boxXEnd, 2, 1 );
boxYEnd = new DoubleSpinBox();
boxYEnd->setLocale(locale);
centerLayout->addWidget( boxYEnd, 2, 2 );
centerLayout->setRowStretch(3, 1);
QHBoxLayout *bottomLayout = new QHBoxLayout();
bottomLayout->addStretch();
buttonApply = new QPushButton(tr("&Apply"));
buttonApply->setDefault( true );
bottomLayout->addWidget(buttonApply);
buttonOk = new QPushButton(tr("&OK"));
bottomLayout->addWidget( buttonOk );
buttonCancel = new QPushButton(tr("&Cancel"));
bottomLayout->addWidget( buttonCancel );
QVBoxLayout * mainLayout = new QVBoxLayout( this );
mainLayout->addWidget(groupBox1);
mainLayout->addWidget(groupBox2);
mainLayout->addLayout(bottomLayout);
boxRows->setValue(m->numRows());
boxCols->setValue(m->numCols());
boxXStart->setValue(m->xStart());
boxYStart->setValue(m->yStart());
boxXEnd->setValue(m->xEnd());
boxYEnd->setValue(m->yEnd());
connect( buttonApply, SIGNAL(clicked()), this, SLOT(apply()));
connect( buttonOk, SIGNAL(clicked()), this, SLOT(accept() ));
connect( buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
}
void MatrixSizeDialog::apply()
{
double fromX = boxXStart->value();
double toX = boxXEnd->value();
double fromY = boxYStart->value();
double toY = boxYEnd->value();
double oxs = d_matrix->xStart();
double oxe = d_matrix->xEnd();
double oys = d_matrix->yStart();
double oye = d_matrix->yEnd();
if(oxs != fromX || oxe != toX || oys != fromY || oye != toY){
d_matrix->undoStack()->push(new MatrixSetCoordinatesCommand(d_matrix,
oxs, oxe, oys, oye, fromX, toX, fromY, toY,
tr("Set Coordinates x[%1 : %2], y[%3 : %4]").arg(fromX).arg(toX).arg(fromY).arg(toY)));
d_matrix->setCoordinates(fromX, toX, fromY, toY);
}
d_matrix->setDimensions(boxRows->value(), boxCols->value());
}
void MatrixSizeDialog::accept()
{
apply();
close();
}
| 39.426471 | 111 | 0.560425 | hoehnp |
9949a2dfaf008c365fbe6fbb12b10e581e36e2fb | 4,382 | cpp | C++ | gui/widgets/knob.cpp | goossens/ObjectTalk | ca1d4f558b5ad2459b376102744d52c6283ec108 | [
"MIT"
] | 6 | 2021-11-12T15:03:53.000Z | 2022-01-28T18:30:33.000Z | gui/widgets/knob.cpp | goossens/ObjectTalk | ca1d4f558b5ad2459b376102744d52c6283ec108 | [
"MIT"
] | null | null | null | gui/widgets/knob.cpp | goossens/ObjectTalk | ca1d4f558b5ad2459b376102744d52c6283ec108 | [
"MIT"
] | null | null | null | // ObjectTalk Scripting Language
// Copyright (c) 1993-2022 Johan A. Goossens. All rights reserved.
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
//
// Include files
//
#include "ot/function.h"
#include "ot/vm.h"
#include "knob.h"
//
// OtKnobClass::init
//
OtObject callback;
OtObject OtKnobClass::init(size_t count, OtObject* parameters) {
switch (count) {
case 4:
setCallback(parameters[3]);
case 3:
setLabel(parameters[2]->operator std::string());
case 2:
setMargin(parameters[1]->operator int());
case 1:
setTexture(parameters[0]);
case 0:
break;
default:
OtExcept("[Knob] constructor expects up to 4 arguments (not %ld)", count);
}
return nullptr;
}
//
// OtKnobClass::setTexture
//
OtObject OtKnobClass::setTexture(OtObject object) {
// a texture can be a texture object or the name of an inamge file
if (object->isKindOf("Texture")) {
texture = object->cast<OtTextureClass>();
} else if (object->isKindOf("String")) {
texture = OtTextureClass::create();
texture->loadImage(object->operator std::string());
} else {
OtExcept("Expected a [Texture] or [String] object, not a [%s]", object->getType()->getName().c_str());
}
return shared();
}
//
// OtKnobClass::setMargin
//
OtObject OtKnobClass::setMargin(int m) {
margin = m;
return shared();
}
//
// OtKnobClass::setLabel
//
OtObject OtKnobClass::setLabel(const std::string& l) {
label = l;
return shared();
}
//
// OtKnobClass::setCallback
//
OtObject OtKnobClass::setCallback(OtObject c) {
callback = c;
return shared();
}
//
// OtKnobClass::render
//
void OtKnobClass::render() {
// add margin if required
if (margin) {
ImGui::Dummy(ImVec2(0, margin));
}
// ensure we have a texture
if (texture) {
// calculate image dimensions
float width = texture->getWidth();
float fullHeight = texture->getHeight();
float steps = fullHeight / width;
float height = fullHeight / steps;
// calculate position
float indent = ImGui::GetCursorPosX();
float availableSpace = ImGui::GetWindowSize().x - indent;
ImVec2 pos = ImVec2(indent + (availableSpace - width) / 2, ImGui::GetCursorPosY());
// setup new widget
ImGui::PushID((void*) this);
ImGui::SetCursorPos(pos);
ImGui::InvisibleButton("", ImVec2(width, height), 0);
ImGuiIO& io = ImGui::GetIO();
// detect mouse activity
if (ImGui::IsItemActive() && io.MouseDelta.y != 0.0) {
auto newValue = OtClamp(value - io.MouseDelta.y / 2.0, 0.0, 100.0);
// call user callback if value has changed
if (callback && newValue != value) {
OtVM::callMemberFunction(callback, "__call__", OtObjectCreate(value));
}
value = newValue;
}
ImGui::PopID();
// render correct frame of image strip
ImGui::SetCursorPos(pos);
float offset1 = std::floor(value / 100.0 * (steps - 1)) * height;
float offset2 = offset1 + height;
ImGui::Image(
(void*)(intptr_t) texture->getTextureHandle().idx,
ImVec2(width, height),
ImVec2(0, offset1 / fullHeight),
ImVec2(1, offset2 / fullHeight));
// render label if required
if (label.size()) {
ImGui::Dummy(ImVec2(0, 5));
ImVec2 size = ImGui::CalcTextSize(label.c_str());
ImVec2 pos = ImGui::GetCursorPos();
ImGui::SetCursorPos(ImVec2(indent + (availableSpace - size.x) / 2, pos.y));
ImGui::TextUnformatted(label.c_str());
}
}
// add margin if required
if (margin) {
ImGui::Dummy(ImVec2(0, margin));
}
}
//
// OtKnobClass::getMeta
//
OtType OtKnobClass::getMeta() {
static OtType type = nullptr;
if (!type) {
type = OtTypeClass::create<OtKnobClass>("Knob", OtWidgetClass::getMeta());
type->set("__init__", OtFunctionClass::create(&OtKnobClass::init));
type->set("setTexture", OtFunctionClass::create(&OtKnobClass::setTexture));
type->set("setMargin", OtFunctionClass::create(&OtKnobClass::setMargin));
type->set("setLabel", OtFunctionClass::create(&OtKnobClass::setLabel));
type->set("setCallback", OtFunctionClass::create(&OtKnobClass::setCallback));
type->set("setValue", OtFunctionClass::create(&OtKnobClass::setValue));
type->set("getValue", OtFunctionClass::create(&OtKnobClass::getValue));
}
return type;
}
//
// OtKnobClass::create
//
OtKnob OtKnobClass::create() {
OtKnob knob = std::make_shared<OtKnobClass>();
knob->setType(getMeta());
return knob;
}
| 21.586207 | 104 | 0.67298 | goossens |
995085d5b9ee461af1ed4d74528789e6d8bef94e | 7,773 | cpp | C++ | Motor2D/j1Pathfinding.cpp | Gerard346/Game-Dev2019 | 3e927070ff2ba8b07de2dc4d56de63a6ffd4fb84 | [
"MIT"
] | null | null | null | Motor2D/j1Pathfinding.cpp | Gerard346/Game-Dev2019 | 3e927070ff2ba8b07de2dc4d56de63a6ffd4fb84 | [
"MIT"
] | null | null | null | Motor2D/j1Pathfinding.cpp | Gerard346/Game-Dev2019 | 3e927070ff2ba8b07de2dc4d56de63a6ffd4fb84 | [
"MIT"
] | null | null | null | #include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Render.h"
#include "j1Textures.h"
#include "j1Pathfinding.h"
#include "j1Map.h"
#include <math.h>
#include "j1Input.h"
#include "j1Window.h"
j1Pathfinding::j1Pathfinding() : j1Module()
{
name.create("pathfinding");
}
// Destructor
j1Pathfinding::~j1Pathfinding()
{}
// Called before render is available
bool j1Pathfinding::Awake(const pugi::xml_node& config)
{
bool ret = true;
str_load_tex = (char*)config.child("debug_texture").child_value();
ResetPath();
return ret;
}
bool j1Pathfinding::Start()
{
debug_tex = App->tex->Load(str_load_tex);
return true;
}
bool j1Pathfinding::PreUpdate()
{
return true;
}
bool j1Pathfinding::Update(float f)
{
Draw();
return true;
}
void j1Pathfinding::ResetPath()
{
path.Clear();
frontier.Clear();
visited.clear();
breadcrumbs.clear();
memset(cost_so_far, 0, sizeof(uint) * COST_MAP * COST_MAP);
}
void j1Pathfinding::Path(int x, int y)
{
path.Clear();
iPoint goal = App->map->WorldToMap(x, y);
int goal_index = visited.find(goal);
if (goal_index == -1)
{
return;
}
path.PushBack(goal);
while (true)
{
path.PushBack(breadcrumbs[goal_index]);
goal_index = visited.find(breadcrumbs[goal_index]);
if (visited[goal_index] == breadcrumbs[goal_index])
{
break;
}
}
}
void j1Pathfinding::PropagateASTAR(iPoint origin, iPoint goal)
{
BROFILER_CATEGORY("A star", Profiler::Color::Black);
iPoint map_goal = App->map->WorldToMap(goal.x, goal.y);
ResetPath();
if (walkability_layer == nullptr)
{
return;
}
iPoint map_origin = App->map->WorldToMap(origin.x, origin.y);
frontier.Push(map_origin, 0);
visited.add(map_origin);
breadcrumbs.add(map_origin);
while (frontier.Count() > 0)
{
iPoint curr;
if (frontier.Pop(curr))
{
iPoint neighbors[4];
neighbors[0].create(curr.x + 1, curr.y + 0);
neighbors[1].create(curr.x + 0, curr.y + 1);
neighbors[2].create(curr.x - 1, curr.y + 0);
neighbors[3].create(curr.x + 0, curr.y - 1);
for (uint i = 0; i < 4; ++i)
{
int neighbor_cost = MovementCost(neighbors[i].x, neighbors[i].y);
if (neighbor_cost > 0)
{
if (visited.find(neighbors[i]) == -1)
{
int x_distance = map_goal.x > neighbors[i].x ? map_goal.x - neighbors[i].x : neighbors[i].x - map_goal.x;
int y_distance = map_goal.y > neighbors[i].y ? map_goal.y - neighbors[i].y : neighbors[i].y - map_goal.y;
frontier.Push(neighbors[i], neighbor_cost + cost_so_far[neighbors[i].x][neighbors[i].y] + x_distance + y_distance);
visited.add(neighbors[i]);
breadcrumbs.add(curr);
cost_so_far[neighbors[i].x][neighbors[i].y] = neighbor_cost;
if (neighbors[i].x == map_goal.x && neighbors[i].y == map_goal.y)
{
Path(goal.x, goal.y);
return;
}
}
}
}
}
}
}
bool j1Pathfinding::PropagateASTARf(fPoint origin, fPoint goal, p2DynArray<iPoint>& ref)
{
iPoint map_goal = App->map->WorldToMap(goal.x, goal.y);
ResetPath();
if (walkability_layer == nullptr)
{
return false;
}
iPoint map_origin = App->map->WorldToMap(origin.x, origin.y);
frontier.Push(map_origin, 0);
visited.add(map_origin);
breadcrumbs.add(map_origin);
while (frontier.Count() > 0)
{
iPoint curr;
if (frontier.Pop(curr))
{
iPoint neighbors[4];
neighbors[0].create(curr.x + 1, curr.y + 0);
neighbors[1].create(curr.x + 0, curr.y + 1);
neighbors[2].create(curr.x - 1, curr.y + 0);
neighbors[3].create(curr.x + 0, curr.y - 1);
for (uint i = 0; i < 4; ++i)
{
int neighbor_cost = MovementCost(neighbors[i].x, neighbors[i].y);
if (neighbor_cost > 0)
{
if (visited.find(neighbors[i]) == -1)
{
int x_distance = map_goal.x > neighbors[i].x ? map_goal.x - neighbors[i].x : neighbors[i].x - map_goal.x;
int y_distance = map_goal.y > neighbors[i].y ? map_goal.y - neighbors[i].y : neighbors[i].y - map_goal.y;
frontier.Push(neighbors[i], neighbor_cost + cost_so_far[neighbors[i].x][neighbors[i].y] + x_distance + y_distance);
visited.add(neighbors[i]);
breadcrumbs.add(curr);
cost_so_far[neighbors[i].x][neighbors[i].y] = neighbor_cost;
if (neighbors[i].x == map_goal.x && neighbors[i].y == map_goal.y)
{
Path(goal.x, goal.y);
if (path.Count() > 0)
{
ref.Clear();
for (int i = 0; i < path.Count(); i++)
{
ref.PushBack(*path.At(i));
}
return true;
}
else
{
return false;
}
}
}
}
}
}
}
return false;
}
bool j1Pathfinding::CanReach(const iPoint origin, const iPoint destination)
{
p2List<iPoint> closed_list;
p2PQueue<iPoint> open_list;
open_list.Push(origin,0);
uint distance_to_loop = origin.DistanceManhattan(destination) * DISTANCE_TO_REACH;
while (distance_to_loop > 0)
{
if (PropagateBFS(origin, destination, &closed_list, &open_list))
{
//LOG("TRUE");
closed_list.clear();
open_list.Clear();
return true;
}
distance_to_loop--;
}
//LOG("FALSE");
closed_list.clear();
open_list.Clear();
return false;
}
void j1Pathfinding::TypePathfinding(typePathfinding type)
{
switch (type)
{
case NONE:
break;
case WALK:
walkability_layer = App->map->GetLayer("Walkability");
break;
case FLY:
walkability_layer = App->map->GetLayer("WalkabilityFly");
break;
default:
break;
}
}
bool j1Pathfinding::IsWalkable(const iPoint& position) const
{
return walkability_layer->Get(position.x, position.y) > 0;
}
bool j1Pathfinding::PropagateBFS(const iPoint& origin, const iPoint& destination, p2List<iPoint>* closed, p2PQueue<iPoint>* open_list)
{
if (walkability_layer == nullptr)
{
return false;
}
p2List<iPoint>* closed_list;
if (closed == nullptr)
closed_list = &this->visited;
else closed_list = closed;
p2PQueue<iPoint>* open_l;
if (open_list == nullptr)
open_l = &this->frontier;
else open_l = open_list;
if (closed_list->find(destination) != -1)
{
return true;
}
iPoint point;
if (open_l->start != NULL && closed_list->find(destination) == -1)
{
open_l->Pop(point);
if (open_l->find(point) == -1)
closed_list->add(point);
iPoint neightbour[4];
neightbour[0] = { point.x - 1, point.y };
neightbour[1] = { point.x + 1, point.y };
neightbour[2] = { point.x, point.y - 1 };
neightbour[3] = { point.x, point.y + 1 };
for (uint i = 0; i < 4; i++)
{
if (closed_list->find(neightbour[i]) == -1 && IsWalkable(neightbour[i]))
{
open_l->Push(neightbour[i],0);
closed_list->add(neightbour[i]);
}
}
}
return false;
}
int j1Pathfinding::MovementCost(int x, int y) const
{
int ret = -1;
if (x >= 0 && x < walkability_layer->width && y >= 0 && y < walkability_layer->height)
{
int id = walkability_layer->Get(x, y);
if (id == 6)
{
ret = 1;
}
else
{
ret = -1;
}
}
return ret;
}
void j1Pathfinding::DrawPath()
{
iPoint point;
// Draw visited
p2List_item<iPoint>* item = visited.start;
while (item)
{
point = item->data;
iPoint pos = App->map->MapToWorld(point.x, point.y);
App->render->DrawQuad({ pos.x, pos.y, 16,16}, 255, 0, 0, 150);
item = item->next;
}
// Draw frontier
for (uint i = 0; i < frontier.Count(); ++i)
{
point = *(frontier.Peek(i));
iPoint pos = App->map->MapToWorld(point.x, point.y);
App->render->DrawQuad({ pos.x, pos.y, 16,16 }, 0, 255, 0, 150);
}
// Draw path
for (uint i = 0; i < path.Count(); ++i)
{
iPoint pos = App->map->MapToWorld(path[i].x, path[i].y);
App->render->DrawQuad({ pos.x, pos.y, 16,16 }, 0, 0, 255, 150);
break;
}
}
void j1Pathfinding::Draw()
{
if (debug) {
DrawPath();
}
}
bool j1Pathfinding::CleanUp()
{
LOG("Unloading pathfinding");
ResetPath();
return true;
}
| 20.728 | 134 | 0.63206 | Gerard346 |
9952033c3c777f60050880690f73804b8b7e1b0c | 2,516 | hpp | C++ | dLoad.hpp | dyexlzc/CppdynamicLoad | 14303e2929ecc26aa16ef7f0dad7cc2d71cb3077 | [
"MIT"
] | null | null | null | dLoad.hpp | dyexlzc/CppdynamicLoad | 14303e2929ecc26aa16ef7f0dad7cc2d71cb3077 | [
"MIT"
] | null | null | null | dLoad.hpp | dyexlzc/CppdynamicLoad | 14303e2929ecc26aa16ef7f0dad7cc2d71cb3077 | [
"MIT"
] | null | null | null | #ifndef _DLOAD_HPP
#define _DLOAD_HPP
#include <unordered_map>
#include <string>
#include <dlfcn.h> //加载动态库所需要的头文件
#include "interface.h"
class dynamicLoader
{
class SoWrapper //用来包装指针
{
public:
interface *(*getInstanceFunc)(void);
void *soPtr;
SoWrapper(interface *(*fptr)(void), void *soptr)
{
getInstanceFunc = fptr;
soPtr = soptr;
}
SoWrapper() {}
SoWrapper(const SoWrapper &sw)
{
//自己写一个拷贝构造,否则map不认
this->soPtr = sw.soPtr;
this->getInstanceFunc = sw.getInstanceFunc;
}
};
std::string mSoPath; //so库的根目录
std::unordered_map<std::string, SoWrapper> libInstanceMap; //map储存so指针实现 o(n)的效率
public:
dynamicLoader(const std::string &soPath) : mSoPath(soPath) {}
~dynamicLoader() {}
bool load(const std::string &libName)
{ //加载so库名,即so的全名,【libxxx】.so,成功或者已经加载,则返回true,失败返回false
if(libInstanceMap.count(libName)!=0)return true;
void *soPtr = dlopen((mSoPath + libName).c_str(), RTLD_LAZY);
if (!soPtr)
return false;
if (libInstanceMap.count(libName) != 0)
return true; //如果已经加载过
interface *(*getInstanceFunc)(void); //getInstance的函数指针
getInstanceFunc = (interface * (*)(void)) dlsym(soPtr, "getInstance"); //从so中获取符号,因此必须导出getInstance函数
SoWrapper sw(getInstanceFunc, soPtr); //构建warpper对象
libInstanceMap[libName] = sw;
return true; //存入instanceMap中,下次要再次使用时直接获取即可
}
bool unload(const std::string &libName)
{ //卸载类库
if (isExists(libName))
{
dlclose(libInstanceMap[libName].soPtr); //关闭so文件的调用
libInstanceMap[libName].soPtr = nullptr;
libInstanceMap[libName].getInstanceFunc = nullptr;
libInstanceMap.erase(libName);
}
return true;
}
interface *getInstance(const std::string &libName)
{ //获取实例,实例产生的方式取决于maker中的实现方式
if (isExists(libName))
{
return (interface *)(libInstanceMap[libName].getInstanceFunc()); //返回实例执行的结果
}
return nullptr;
}
bool isExists(const std::string &libName)
{ //判断是否已经加载该so
if (libInstanceMap.count(libName) == 0)
{
return false; //不存在
}
return true;
}
};
#endif | 32.675325 | 109 | 0.561208 | dyexlzc |
995c2f7a0f20072e7d8039748ef224a5e5949dba | 4,993 | hh | C++ | src/net/REDQueue.hh | drexelwireless/dragonradio | 885abd68d56af709e7a53737352641908005c45b | [
"MIT"
] | 8 | 2020-12-05T20:30:54.000Z | 2022-01-22T13:32:14.000Z | src/net/REDQueue.hh | drexelwireless/dragonradio | 885abd68d56af709e7a53737352641908005c45b | [
"MIT"
] | 3 | 2020-10-28T22:15:27.000Z | 2021-01-27T14:43:41.000Z | src/net/REDQueue.hh | drexelwireless/dragonradio | 885abd68d56af709e7a53737352641908005c45b | [
"MIT"
] | null | null | null | #ifndef REDQUEUE_HH_
#define REDQUEUE_HH_
#include <list>
#include <random>
#include "logging.hh"
#include "Clock.hh"
#include "net/Queue.hh"
#include "net/SizedQueue.hh"
/** @brief An Adaptive RED queue. */
/** See the paper Random Early Detection Gateways for Congestion Avoidance */
template <class T>
class REDQueue : public SizedQueue<T> {
public:
using const_iterator = typename std::list<T>::const_iterator;
using Queue<T>::canPop;
using SizedQueue<T>::stop;
using SizedQueue<T>::drop;
using SizedQueue<T>::done_;
using SizedQueue<T>::size_;
using SizedQueue<T>::hi_priority_flows_;
using SizedQueue<T>::m_;
using SizedQueue<T>::cond_;
using SizedQueue<T>::hiq_;
using SizedQueue<T>::q_;
REDQueue(bool gentle,
size_t min_thresh,
size_t max_thresh,
double max_p,
double w_q)
: SizedQueue<T>()
, gentle_(gentle)
, min_thresh_(min_thresh)
, max_thresh_(max_thresh)
, max_p_(max_p)
, w_q_(w_q)
, count_(-1)
, avg_(0)
, gen_(std::random_device()())
, dist_(0, 1.0)
{
}
REDQueue() = delete;
virtual ~REDQueue()
{
stop();
}
/** @brief Get flag indicating whether or not to be gentle */
/** See:
* https://www.icir.org/floyd/notes/test-suite-red.txt
*/
bool getGentle(void) const
{
return gentle_;
}
/** @brief Set flag indicating whether or not to be gentle */
void setGentle(bool gentle)
{
gentle_ = gentle;
}
/** @brief Get minimum threshold */
size_t getMinThresh(void) const
{
return min_thresh_;
}
/** @brief Set minimum threshold */
void setMinThresh(size_t min_thresh)
{
min_thresh_ = min_thresh;
}
/** @brief Get maximum threshold */
size_t getMaxThresh(void) const
{
return max_thresh_;
}
/** @brief Set maximum threshold */
void setMaxThresh(size_t max_thresh)
{
max_thresh_ = max_thresh;
}
/** @brief Get maximum drop probability */
double getMaxP(void) const
{
return max_p_;
}
/** @brief Set maximum drop probability */
void setMaxP(double max_p)
{
max_p_ = max_p;
}
/** @brief Get queue qeight */
double getQueueWeight(void) const
{
return max_p_;
}
/** @brief Set queue qeight */
void setQueueWeight(double w_q)
{
w_q_ = w_q;
}
virtual void reset(void) override
{
std::lock_guard<std::mutex> lock(m_);
done_ = false;
size_ = 0;
count_ = 0;
hiq_.clear();
q_.clear();
}
virtual void push(T&& item) override
{
{
std::lock_guard<std::mutex> lock(m_);
if (item->flow_uid && hi_priority_flows_.find(*item->flow_uid) != hi_priority_flows_.end()) {
hiq_.emplace_back(std::move(item));
return;
}
bool mark = false;
// Calculate new average queue size
if (size_ == 0)
avg_ = 0;
else
avg_ = (1 - w_q_)*avg_ + w_q_*size_;
// Determine whether or not to mark packet
if (avg_ < min_thresh_) {
count_ = -1;
} else if (min_thresh_ <= avg_ && avg_ < max_thresh_) {
count_++;
double p_b = max_p_*(avg_ - min_thresh_)/(max_thresh_ - min_thresh_);
double p_a = p_b/(1.0 - count_*p_b);
if (dist_(gen_) < p_a) {
mark = true;
count_ = 0;
}
} else if (gentle_ && avg_ < 2*max_thresh_) {
count_++;
double p_a = max_p_*(avg_ - max_thresh_)/max_thresh_;
if (dist_(gen_) < p_a) {
mark = true;
count_ = 0;
}
} else {
mark = true;
count_ = 0;
}
if (mark)
drop(item);
if (!mark) {
size_ += item->payload_size;
q_.emplace_back(std::move(item));
}
}
cond_.notify_one();
}
protected:
/** @brief Gentle flag. */
bool gentle_;
/** @brief Minimum threshold. */
size_t min_thresh_;
/** @brief Maximum threshold. */
size_t max_thresh_;
/** @brief Maximum drop probability. */
double max_p_;
/** @brief Queue weight. */
double w_q_;
/** @brief Packets since last marked packet. */
int count_;
/** @brief Average size of queue (bytes). */
double avg_;
/** @brief Random number generator */
std::mt19937 gen_;
/** @brief Uniform 0-1 real distribution */
std::uniform_real_distribution<double> dist_;
};
using REDNetQueue = REDQueue<std::shared_ptr<NetPacket>>;
#endif /* REDQUEUE_HH_ */
| 22.799087 | 105 | 0.530342 | drexelwireless |
995d417fdaf7d5b02113724963860c36fb84b251 | 3,208 | hpp | C++ | test/matrix/blas/matsub.hpp | rigarash/monolish-debian-package | 70b4917370184bcf07378e1907c5239a1ad9579b | [
"Apache-2.0"
] | 172 | 2021-04-05T10:04:40.000Z | 2022-03-28T14:30:38.000Z | test/matrix/blas/matsub.hpp | rigarash/monolish-debian-package | 70b4917370184bcf07378e1907c5239a1ad9579b | [
"Apache-2.0"
] | 96 | 2021-04-06T01:53:44.000Z | 2022-03-09T07:27:09.000Z | test/matrix/blas/matsub.hpp | termoshtt/monolish | 1cba60864002b55bc666da9baa0f8c2273578e01 | [
"Apache-2.0"
] | 8 | 2021-04-05T13:21:07.000Z | 2022-03-09T23:24:06.000Z | #include "../../test_utils.hpp"
template <typename T>
void ans_matsub(const monolish::matrix::Dense<T> &A,
const monolish::matrix::Dense<T> &B,
monolish::matrix::Dense<T> &C) {
if (A.get_row() != B.get_row()) {
std::runtime_error("A.row != B.row");
}
if (A.get_col() != B.get_col()) {
std::runtime_error("A.col != B.col");
}
// MN=MN+MN
int M = A.get_row();
int N = A.get_col();
for (int i = 0; i < A.get_nnz(); i++) {
C.val[i] = A.val[i] - B.val[i];
}
}
template <typename MAT_A, typename MAT_B, typename MAT_C, typename T>
bool test_send_matsub(const size_t M, const size_t N, double tol) {
size_t nnzrow = 27;
if ((nnzrow < M) && (nnzrow < N)) {
nnzrow = 27;
} else {
nnzrow = std::min({M, N}) - 1;
}
monolish::matrix::COO<T> seedA =
monolish::util::random_structure_matrix<T>(M, N, nnzrow, 1.0);
MAT_A A(seedA);
MAT_B B(seedA);
MAT_C C(seedA);
monolish::matrix::Dense<T> AA(seedA);
monolish::matrix::Dense<T> BB(seedA);
monolish::matrix::Dense<T> CC(seedA);
ans_matsub(AA, BB, CC);
monolish::matrix::COO<T> ansC(CC);
monolish::util::send(A, B, C);
monolish::blas::matsub(A, B, C);
C.recv();
monolish::matrix::COO<T> resultC(C);
return ans_check<T>(__func__, A.type(), resultC.val.data(), ansC.val.data(),
ansC.get_nnz(), tol);
}
template <typename MAT_A, typename MAT_B, typename MAT_C, typename T>
bool test_send_matsub_linearoperator(const size_t M, const size_t N,
double tol) {
size_t nnzrow = 27;
if ((nnzrow < M) && (nnzrow < N)) {
nnzrow = 27;
} else {
nnzrow = std::min({M, N}) - 1;
}
monolish::matrix::COO<T> seedA =
monolish::util::random_structure_matrix<T>(M, N, nnzrow, 1.0);
monolish::matrix::CRS<T> A1(seedA);
monolish::matrix::CRS<T> B1(seedA);
monolish::matrix::CRS<T> C1(seedA);
monolish::matrix::Dense<T> AA(seedA);
monolish::matrix::Dense<T> BB(seedA);
monolish::matrix::Dense<T> CC(seedA);
ans_matsub(AA, BB, CC);
monolish::matrix::COO<T> ansC(CC);
monolish::util::send(A1, B1, C1);
MAT_A A(A1);
MAT_B B(B1);
MAT_C C(C1);
monolish::blas::matsub(A, B, C);
C.recv();
monolish::matrix::COO<T> resultC(C);
return ans_check<T>(__func__, A.type(), resultC.val.data(), ansC.val.data(),
ansC.get_nnz(), tol);
}
template <typename MAT_A, typename MAT_B, typename MAT_C, typename T>
bool test_matsub(const size_t M, const size_t N, double tol) {
size_t nnzrow = 27;
if ((nnzrow < M) && (nnzrow < N)) {
nnzrow = 27;
} else {
nnzrow = std::min({M, N}) - 1;
}
monolish::matrix::COO<T> seedA =
monolish::util::random_structure_matrix<T>(M, N, nnzrow, 1.0);
MAT_A A(seedA);
MAT_B B(seedA);
MAT_C C(seedA);
monolish::matrix::Dense<T> AA(seedA);
monolish::matrix::Dense<T> BB(seedA);
monolish::matrix::Dense<T> CC(seedA);
ans_matsub(AA, BB, CC);
monolish::matrix::COO<T> ansC(CC);
monolish::blas::matsub(A, B, C);
monolish::matrix::COO<T> resultC(C);
return ans_check<T>(__func__, A.type(), resultC.val.data(), ansC.val.data(),
ansC.get_nnz(), tol);
}
| 25.259843 | 78 | 0.595387 | rigarash |
9967ae213a368f4d7eca16535649ff73f8cce3ab | 9,045 | cxx | C++ | HLT/EMCAL/AliHLTEMCALDigitMakerComponent.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | HLT/EMCAL/AliHLTEMCALDigitMakerComponent.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | HLT/EMCAL/AliHLTEMCALDigitMakerComponent.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | // $Id$
/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* All rights reserved. *
* *
* Primary Authors: Oystein Djuvsland *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliHLTEMCALDigitMakerComponent.h"
#include "AliHLTCaloDigitMaker.h"
#include "AliHLTCaloDigitDataStruct.h"
#include "AliHLTCaloChannelDataHeaderStruct.h"
#include "AliHLTCaloChannelDataStruct.h"
#include "AliHLTEMCALMapper.h"
#include "AliHLTEMCALDefinitions.h"
#include "AliCaloCalibPedestal.h"
#include "AliEMCALCalibData.h"
#include "AliCDBEntry.h"
#include "AliCDBPath.h"
#include "AliCDBManager.h"
#include "TFile.h"
#include <sys/stat.h>
#include <sys/types.h>
//#include "AliHLTEMCALConstant.h"
#include "AliHLTCaloConstants.h"
using EMCAL::NZROWSMOD;
using EMCAL::NXCOLUMNSMOD;
using EMCAL::NMODULES;
using CALO::HGLGFACTOR;
/**
* @file AliHLTEMCALDigitMakerComponent.cxx
* @author Oystein Djuvsland
* @date
* @brief A digit maker component for EMCAL HLT
*/
// see below for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
ClassImp(AliHLTEMCALDigitMakerComponent)
AliHLTEMCALDigitMakerComponent gAliHLTEMCALDigitMakerComponent;
AliHLTEMCALDigitMakerComponent::AliHLTEMCALDigitMakerComponent() :
AliHLTCaloProcessor(),
// AliHLTCaloConstantsHandler("EMCAL"),
fDigitContainerPtr(0),
fPedestalData(0),
fCalibData(0)
{
//see header file for documentation
for(int imod = 0; imod < NMODULES; imod++){
fDigitMakerPtr[imod] = NULL;
fBCMInitialised[imod] = true;
fGainsInitialised[imod] = true;
}
}
AliHLTEMCALDigitMakerComponent::~AliHLTEMCALDigitMakerComponent()
{
//see header file for documentation
}
int
AliHLTEMCALDigitMakerComponent::Deinit()
{
//see header file for documentation
for(int imod = 0; imod < NMODULES; imod++){
if(fDigitMakerPtr[imod])
{
delete fDigitMakerPtr[imod];
fDigitMakerPtr[imod] = 0;
}
}
return 0;
}
const char*
AliHLTEMCALDigitMakerComponent::GetComponentID()
{
//see header file for documentation
return "EmcalDigitMaker";
}
void
AliHLTEMCALDigitMakerComponent::GetInputDataTypes(vector<AliHLTComponentDataType>& list)
{
//see header file for documentation
list.clear();
list.push_back(AliHLTEMCALDefinitions::fgkChannelDataType);
}
AliHLTComponentDataType
AliHLTEMCALDigitMakerComponent::GetOutputDataType()
{
//see header file for documentation
// return AliHLTCaloDefinitions::fgkDigitDataType|kAliHLTDataOriginEMCAL;
return AliHLTEMCALDefinitions::fgkDigitDataType;
}
void
AliHLTEMCALDigitMakerComponent::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier)
{
//see header file for documentation
constBase = 0;
inputMultiplier = (float)sizeof(AliHLTCaloDigitDataStruct)/sizeof(AliHLTCaloChannelDataStruct) + 1;
}
int
AliHLTEMCALDigitMakerComponent::DoEvent(const AliHLTComponentEventData& evtData, const AliHLTComponentBlockData* blocks,
AliHLTComponentTriggerData& /* trigData */, AliHLTUInt8_t* outputPtr, AliHLTUInt32_t& size,
std::vector<AliHLTComponentBlockData>& outputBlocks)
{
//patch in order to skip calib events
if(! IsDataEvent()) return 0;
//see header file for documentation
UInt_t offset = 0;
UInt_t mysize = 0;
Int_t digitCount = 0;
Int_t ret = 0;
const AliHLTComponentBlockData* iter = 0;
unsigned long ndx;
UInt_t specification = 0;
AliHLTCaloChannelDataHeaderStruct* tmpChannelData = 0;
Int_t moduleID;
for( ndx = 0; ndx < evtData.fBlockCnt; ndx++ )
{
iter = blocks+ndx;
if(iter->fDataType != AliHLTEMCALDefinitions::fgkChannelDataType) continue;
if(iter->fSpecification >= 40) continue; // Do not use inactive DDLs
moduleID = int(iter->fSpecification/2);
if(!fBCMInitialised[moduleID]){
if(moduleID > -1){
for(Int_t x = 0; x < NXCOLUMNSMOD ; x++) // PTH
for(Int_t z = 0; z < NZROWSMOD ; z++) // PTH
fDigitMakerPtr[moduleID]->SetBadChannel(x, z, fPedestalData->IsBadChannel(moduleID, z, x)); // FR
//delete fBadChannelMap;
fBCMInitialised[moduleID] = true;
} else
HLTError("Error setting pedestal with module value of %d", moduleID);
}
if(!fGainsInitialised[moduleID]){
if(moduleID > -1){
for(Int_t x = 0; x < NXCOLUMNSMOD; x++) //PTH
for(Int_t z = 0; z < NZROWSMOD; z++) //PTH
// FR setting gains
fDigitMakerPtr[moduleID]->SetGain(x, z, HGLGFACTOR, fCalibData->GetADCchannel(moduleID, z, x));
fGainsInitialised[moduleID] = true;
}
else
HLTError("Error setting gains with module value of %d", moduleID);
}
tmpChannelData = reinterpret_cast<AliHLTCaloChannelDataHeaderStruct*>(iter->fPtr);
fDigitMakerPtr[moduleID]->SetDigitDataPtr(reinterpret_cast<AliHLTCaloDigitDataStruct*>(outputPtr));
ret = fDigitMakerPtr[moduleID]->MakeDigits(tmpChannelData, size-(digitCount*sizeof(AliHLTCaloDigitDataStruct)));
HLTDebug("Found %d digits", ret);
if(ret == -1) {
HLTError("Trying to write over buffer size");
return -ENOBUFS;
}
digitCount += ret;
outputPtr += sizeof(AliHLTCaloDigitDataStruct) * ret; // forward pointer
}
mysize += digitCount*sizeof(AliHLTCaloDigitDataStruct);
HLTDebug("# of digits: %d, used memory size: %d, available size: %d", digitCount, mysize, size);
if(mysize > 0) {
AliHLTComponentBlockData bd;
FillBlockData( bd );
bd.fOffset = offset;
bd.fSize = mysize;
bd.fDataType = AliHLTEMCALDefinitions::fgkDigitDataType;
bd.fSpecification = 0;
outputBlocks.push_back(bd);
}
for(Int_t imod = 0; imod < NMODULES; imod++) fDigitMakerPtr[imod]->Reset();
size = mysize;
return 0;
}
int
AliHLTEMCALDigitMakerComponent::DoInit(int argc, const char** argv )
{
//see header file for documentation
for(Int_t imod = 0; imod < NMODULES; imod++){
fDigitMakerPtr[imod] = new AliHLTCaloDigitMaker("EMCAL");
AliHLTCaloMapper *mapper = new AliHLTEMCALMapper(2);
fDigitMakerPtr[imod]->SetMapper(mapper);
for(int i = 0; i < argc; i++) {
if(!strcmp("-lowgainfactor", argv[i])) {
fDigitMakerPtr[imod]->SetGlobalLowGainFactor(atof(argv[i+1]));
}
if(!strcmp("-highgainfactor", argv[i])) {
fDigitMakerPtr[imod]->SetGlobalHighGainFactor(atof(argv[i+1]));
}
}
}
if (GetBCMFromCDB())
return -1;
if (GetGainsFromCDB())
return -1;
//GetBCMFromCDB();
//fDigitMakerPtr->SetDigitThreshold(2);
return 0;
}
int AliHLTEMCALDigitMakerComponent::GetBCMFromCDB()
{
// See header file for class documentation
for(Int_t imod = 0; imod < 20; imod++) fBCMInitialised[imod] = false;
// HLTInfo("Getting bad channel map...");
AliCDBPath path("EMCAL","Calib","Pedestals");
if(path.GetPath())
{
// HLTInfo("configure from entry %s", path.GetPath());
AliCDBEntry *pEntry = AliCDBManager::Instance()->Get(path/*,GetRunNo()*/);
if (pEntry)
{
fPedestalData = (AliCaloCalibPedestal*)pEntry->GetObject();
}
else
{
// HLTError("can not fetch object \"%s\" from CDB", path);
return -1;
}
}
if(!fPedestalData)
{
return -1;
}
return 0;
}
int AliHLTEMCALDigitMakerComponent::GetGainsFromCDB()
{
// See header file for class documentation
for(Int_t imod = 0; imod < 20; imod++) fGainsInitialised[imod] = false;
// HLTInfo("Getting bad channel map...");
AliCDBPath path("EMCAL","Calib","Data");
if(path.GetPath())
{
// HLTInfo("configure from entry %s", path.GetPath());
AliCDBEntry *pEntry = AliCDBManager::Instance()->Get(path/*,GetRunNo()*/);
if (pEntry)
{
fCalibData = (AliEMCALCalibData*)pEntry->GetObject();
}
else
{
// HLTError("can not fetch object \"%s\" from CDB", path);
return -1;
}
}
if(!fCalibData) return -1;
return 0;
}
AliHLTComponent*
AliHLTEMCALDigitMakerComponent::Spawn()
{
//see header file for documentation
return new AliHLTEMCALDigitMakerComponent();
}
| 28.443396 | 120 | 0.656385 | AllaMaevskaya |
9978b390491df18d645dde376bb564e507571ed5 | 201 | hpp | C++ | engine/engine.hpp | davidscholberg/opengl-es-test | 9792d6d6f4f01fb91a8ec59ecf0fd02cd019db79 | [
"BSD-2-Clause"
] | null | null | null | engine/engine.hpp | davidscholberg/opengl-es-test | 9792d6d6f4f01fb91a8ec59ecf0fd02cd019db79 | [
"BSD-2-Clause"
] | null | null | null | engine/engine.hpp | davidscholberg/opengl-es-test | 9792d6d6f4f01fb91a8ec59ecf0fd02cd019db79 | [
"BSD-2-Clause"
] | null | null | null | #ifndef ENGINE_HPP_
#define ENGINE_HPP_
class engine {
public:
engine();
engine(engine const &) = delete;
~engine();
void operator=(engine const &) = delete;
};
#endif // ENGINE_HPP_
| 15.461538 | 44 | 0.651741 | davidscholberg |
5f53ae65b626f3f81e712d5ccfec67ede8b34bb3 | 6,275 | cpp | C++ | ECS/Project/Project/Renderers/RendererModules/DPassLightingModule/DPassLightingModule.cpp | AshwinKumarVijay/SceneECS | 2acc115d5e7738ef9bf087c025e5e5a10cac3443 | [
"MIT"
] | 2 | 2017-01-30T23:38:49.000Z | 2017-09-08T09:34:37.000Z | ECS/Project/Project/Renderers/RendererModules/DPassLightingModule/DPassLightingModule.cpp | AshwinKumarVijay/SceneECS | 2acc115d5e7738ef9bf087c025e5e5a10cac3443 | [
"MIT"
] | null | null | null | ECS/Project/Project/Renderers/RendererModules/DPassLightingModule/DPassLightingModule.cpp | AshwinKumarVijay/SceneECS | 2acc115d5e7738ef9bf087c025e5e5a10cac3443 | [
"MIT"
] | null | null | null | #include "DPassLightingModule.h"
#include "../Renderers/ModuleRenderer/ModuleRenderer.h"
#include "../GBufferModule/GBufferModule.h"
#include "../LightsModule/LightsModule.h"
#include "../../../Camera/Camera.h"
#include "../../RendererResourceManagers/RendererShaderManager/RendererShaderData/RendererShaderData.h"
// Default DPassLightingModule Constructor.
DPassLightingModule::DPassLightingModule(std::shared_ptr<Renderer> newRenderer, std::shared_ptr<const GBufferModule> newGBufferModule, std::shared_ptr<const LightsModule> newLightsModule) : RendererModule(newRenderer)
{
// Copy over the Screen Width and Screen Height Textures.
screenWidth = newRenderer->getSceneQuality().screenWidth;
screenHeight = newRenderer->getSceneQuality().screenHeight;
// Copy over the G Buffer Module.
gBufferModule = newGBufferModule;
// Copy over the Lights Module.
lightsModule = newLightsModule;
// Create the Deferred Pass Lighting Shader.
deferredPassLightingShader = std::make_shared<RendererShaderData>();
// Add the Property Value.
deferredPassLightingShader->addPropertyValue("Shader Type", "Deferred Lighting Pass Shader");
deferredPassLightingShader->addPropertyValue("Shader Output Opacity", "False");
// Set the Vertex Shader G Buffer Source.
std::string vsSource = "Assets/ModuleRendererShaders/DeferredLightingPassShaders/PhongLightingPassShaders/PhongLightingShader.vert.glsl";
deferredPassLightingShader->addPropertyValue("Vertex Shader Source", vsSource);
// Set the Fragment Shader G Buffer Source.
std::string fsSource = "Assets/ModuleRendererShaders/DeferredLightingPassShaders/PhongLightingPassShaders/PhongLightingShader.frag.glsl";
deferredPassLightingShader->addPropertyValue("Fragment Shader Source", fsSource);
// Add the Shader to the Module Renderer.
newRenderer->addShader(deferredPassLightingShader);
//
createDeferredPassLightingTexturesAndFramebuffers();
}
// Default DPassLightingModule Destructor.
DPassLightingModule::~DPassLightingModule()
{
}
// Render the Deferred Pass Lighting Module.
void DPassLightingModule::render(const float & deltaFrameTime, const float & currentFrameTime, const float & lastFrameTime, std::shared_ptr<const Camera> activeCamera)
{
// Use the Program.
glUseProgram(deferredPassLightingShader->getShaderID());
// Bind the Deferred Pass Lighting Framebuffer Object.
glBindFramebuffer(GL_FRAMEBUFFER, deferredPassLightingFramebuffer);
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
//
std::shared_ptr<ModuleRenderer> moduleRenderer = std::dynamic_pointer_cast<ModuleRenderer>(getRenderer().lock());
// Upload the Ambient Light Data.
moduleRenderer->uploadAmbientLightData(*deferredPassLightingShader);
// Upload the Camera Data.
moduleRenderer->uploadCameraData(*deferredPassLightingShader, glm::vec4(activeCamera->getCameraPosition(), 1.0), activeCamera->getPerspectiveMatrix(), activeCamera->getViewMatrix(), glm::vec4(activeCamera->getNearClip(), activeCamera->getFarClip(), 0.0, 0.0));
// Upload the G Buffer Textures.
moduleRenderer->uploadGBufferTextures(*deferredPassLightingShader, gBufferModule.lock()->viewWorldSpacePositionTexture(), gBufferModule.lock()->viewWorldSpaceVertexNormalAndDepthTexture(), gBufferModule.lock()->viewAmbientColorTexture(), gBufferModule.lock()->viewDiffuseAlbedoAndLitTypeTexture(), gBufferModule.lock()->viewSpecularAlbedoAndLightingTypeTexture(), gBufferModule.lock()->viewMRFOTexture(), gBufferModule.lock()->viewEmissiveColorAndIntensityTexture(), 0);
// Upload the Lights Data.
lightsModule.lock()->uploadLightsData(deferredPassLightingShader);
// Draw the Arrays.
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
// Bind the Default Framebuffer.
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
// Create the Deferred Pass Lighting Textures And Framebuffers.
void DPassLightingModule::createDeferredPassLightingTexturesAndFramebuffers()
{
// Create the Deferred Pass Lighting Module Color Texture.
glGenTextures(1, &deferredPassLightingModuleColorTexture);
glBindTexture(GL_TEXTURE_2D, deferredPassLightingModuleColorTexture);
glTextureImage2DEXT(deferredPassLightingModuleColorTexture, GL_TEXTURE_2D, 0, GL_RGBA32F, screenWidth, screenHeight, 0, GL_RGBA, GL_FLOAT, NULL);
glTextureParameteri(deferredPassLightingModuleColorTexture, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTextureParameteri(deferredPassLightingModuleColorTexture, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, 0);
// Create the Deferred Pass Lighting Module Depth Texture.
glGenTextures(1, &deferredPassLightingModuleDepthTexture);
glBindTexture(GL_TEXTURE_2D, deferredPassLightingModuleDepthTexture);
glTextureImage2DEXT(deferredPassLightingModuleDepthTexture, GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, screenWidth, screenHeight, 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, NULL);
glTextureParameteri(deferredPassLightingModuleDepthTexture, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTextureParameteri(deferredPassLightingModuleDepthTexture, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, 0);
// Bind the Deferred Pass Lighting Framebuffer Object
glGenFramebuffers(1, &deferredPassLightingFramebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, deferredPassLightingFramebuffer);
// Associate the Color Texture with the Current Framebuffer.
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + 0, GL_TEXTURE_2D, deferredPassLightingModuleColorTexture, 0);
// Associate the Depth Stencil Texture with the Current Framebuffer.
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, deferredPassLightingModuleDepthTexture, 0);
// Set the Draw Buffers of the Current Framebuffer.
GLenum framebufferDrawBuffers[] = { GL_COLOR_ATTACHMENT0 + 0 };
glDrawBuffers(1, framebufferDrawBuffers);
// Bind the Default Framebuffer.
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
// Return the Deferred Pass Lighting Color Texture.
unsigned int DPassLightingModule::viewDeferredPassLightingColorTexture()
{
return deferredPassLightingModuleColorTexture;
}
// Return the Deferred Pass Lighting Depth Texture.
unsigned int DPassLightingModule::viewDeferredPassLightingDepthTexture()
{
return deferredPassLightingModuleDepthTexture;
}
| 45.80292 | 471 | 0.821514 | AshwinKumarVijay |
5f5592726c03618955fb5f662a83cf8ca5b042a6 | 343 | cpp | C++ | Source/TextureBaker/Private/TextureBakerCommands.cpp | WhiteWh/UE4TextureBaker | 976decb8a895bb7aa8c4dad17e857b25a7a753ce | [
"MIT"
] | 7 | 2021-05-04T10:33:36.000Z | 2022-02-02T20:06:21.000Z | Source/TextureBaker/Private/TextureBakerCommands.cpp | WhiteWh/UE4TextureBaker | 976decb8a895bb7aa8c4dad17e857b25a7a753ce | [
"MIT"
] | null | null | null | Source/TextureBaker/Private/TextureBakerCommands.cpp | WhiteWh/UE4TextureBaker | 976decb8a895bb7aa8c4dad17e857b25a7a753ce | [
"MIT"
] | null | null | null | // Copyright Epic Games, Inc. All Rights Reserved.
#include "TextureBakerCommands.h"
#define LOCTEXT_NAMESPACE "FTextureBakerModule"
void FTextureBakerCommands::RegisterCommands()
{
UI_COMMAND(OpenPluginWindow, "TextureBaker", "Bring up TextureBaker window", EUserInterfaceActionType::Button, FInputGesture());
}
#undef LOCTEXT_NAMESPACE
| 26.384615 | 129 | 0.80758 | WhiteWh |
5f58e8a2a07d36c37ebe2d543e363510648bc238 | 3,934 | cc | C++ | src/imageprocessing/contour.cc | SanczoPL/gt-annotate | b760d0dc3f91ce5748190b95468e2e54bee76b2a | [
"MIT"
] | null | null | null | src/imageprocessing/contour.cc | SanczoPL/gt-annotate | b760d0dc3f91ce5748190b95468e2e54bee76b2a | [
"MIT"
] | null | null | null | src/imageprocessing/contour.cc | SanczoPL/gt-annotate | b760d0dc3f91ce5748190b95468e2e54bee76b2a | [
"MIT"
] | null | null | null | #include "imageprocessing/contour.h"
#include <QJsonObject>
#include <QJsonArray>
#include <QFile>
#include <QJsonDocument>
#include <QDebug>
#include <QRectF>
#include <QString>
//#define DEBUG
constexpr auto NAME{ "Name" };
constexpr auto WIDTH{ "Width" };
constexpr auto HEIGHT{ "Height" };
constexpr auto X{ "X" };
constexpr auto Y{ "Y" };
constexpr auto SIZE{ "Size" };
constexpr auto CONTOUR{ "Contour" };
constexpr auto CANNY_TRESHOLD{ "CannyTreshold" };
constexpr auto DILATE_COUNTER{ "DilateCounter" };
constexpr auto ERODE_COUNTER{ "ErodeCounter" };
constexpr auto MIN_AREA{ "MinArea" };
constexpr auto MAX_AREA{ "MaxArea" };
constexpr auto ROTATED_RECT{ "RotatedRect" };
constexpr auto BOUNDING_RECT{ "BoundingRect" };
Contour::Contour()
{
configureDefault();
}
void Contour::configureDefault()
{
m_treshCanny = 3;
m_dilateCounter = 2;
m_erodeCounter = 2;
m_minArea = 4;
m_maxArea = 40000;
}
void Contour::configure(const QJsonObject &a_config)
{
m_treshCanny = a_config[CANNY_TRESHOLD].toInt();
m_dilateCounter = a_config[DILATE_COUNTER].toInt();
m_erodeCounter = a_config[ERODE_COUNTER].toInt();
m_minArea = a_config[MIN_AREA].toInt();
m_maxArea = a_config[MAX_AREA].toInt();
}
void Contour::createCannyImage(cv::Mat &opencv_img, cv::Mat &canny_output)
{
#ifdef DEBUG
Logger->debug("Contour::createCannyImage()");
#endif
cv::dilate(opencv_img, opencv_img, cv::Mat(), cv::Point(-1, -1), m_dilateCounter, 1, 1);
cv::erode(opencv_img, opencv_img, cv::Mat(), cv::Point(-1, -1), m_erodeCounter, 1, 1);
cv::Canny(opencv_img, canny_output, m_treshCanny, m_treshCanny*2 );
}
void Contour::findContours(cv::Mat & input, QJsonArray & contoursArray, QString label)
{
#ifdef DEBUG
Logger->debug("Contour::FindContours()");
#endif
cv::Mat canny_output;
Contour::createCannyImage(input, canny_output);
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours(input, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE );
double area;
std::vector<std::vector<cv::Point>> contoursBEST;
std::vector<cv::Vec4i> hierarchyBEST;
std::vector<cv::Point> approx;
for (unsigned int i = 0; i < contours.size(); i++)
{
area = cv::contourArea(contours[i]);
//if ((area >= m_minArea) && (area <= m_maxArea))
{
contoursBEST.push_back(contours[i]);
hierarchyBEST.push_back(hierarchy[i]);
}
}
for (unsigned int i = 0; i < contoursBEST.size(); i++)
{
cv::approxPolyDP(cv::Mat(contoursBEST[i]), approx, cv::arcLength(cv::Mat(contoursBEST[i]), true) * 0.04, true);
area = cv::contourArea(contoursBEST[i]);
cv::Rect boundRect;
boundRect = cv::boundingRect(contoursBEST[i]);
/* // TODO: add support for rotatedrect:
cv::RotatedRect;
RotatedRect = minAreaRect( contoursBEST[i] );
// rotated rectangle
Point2f rect_points[4];
minRect[i].points( rect_points );
for ( int j = 0; j < 4; j++ )
{
line( drawing, rect_points[j], rect_points[(j+1)%4], color );
}*/
int x = boundRect.x;
int y = boundRect.y;
int width = boundRect.width;
int height = boundRect.height;
int size = qAbs(width / 2) * qAbs(height / 2);
QJsonObject obj
{
{ NAME, label},
{ X, x },
{ Y, y },
{ WIDTH, width },
{ HEIGHT, height },
{ SIZE, size}
};
contoursArray.append(obj);
#ifdef DEBUG
Logger->debug("Contour::FindContours() obj, contoursArray:");
qDebug() << "obj:" << obj;
qDebug() << "contoursArray:" << contoursArray;
#endif
}
}
/*
void Contour::crateRois(cv::Mat &opencv_img, QString label, QJsonArray& contoursArray)
{
Logger->trace("Contour::CrateRois()");
cv::Mat canny_output;
Contour::CreateCannyImage(opencv_img, canny_output);
QString _name = label + "_canny_output.png";
cv::imwrite(_name.toStdString(), canny_output);
Contour::FindContours(canny_output, contoursArray, label);
Logger->trace("Contour::CrateRois() done");
}*/
| 26.402685 | 113 | 0.684291 | SanczoPL |
5f68e65393a05b2daa346d882f09e8eb4c063733 | 287 | cpp | C++ | LibreOJ/loj10230.cpp | wzl19371/OI-LIfe | f7f54542d1369b5e4047fcbb2e26c1c64d22ee26 | [
"MIT"
] | 1 | 2020-10-05T02:07:52.000Z | 2020-10-05T02:07:52.000Z | LibreOJ/loj10230.cpp | wzl19371/OI-LIfe | f7f54542d1369b5e4047fcbb2e26c1c64d22ee26 | [
"MIT"
] | null | null | null | LibreOJ/loj10230.cpp | wzl19371/OI-LIfe | f7f54542d1369b5e4047fcbb2e26c1c64d22ee26 | [
"MIT"
] | null | null | null | #include <cstdio>
using namespace std;
typedef long long ll;
const int p=5000011;
const int maxn=1e5+10;
int n,k;
ll f[maxn];
int main(){
scanf("%d%d",&n,&k);
for(int i=0;i<=k;i++) f[i]=(i+1)%p;
for(int i=k+1;i<=n;i++) f[i]=(f[i-1]+f[i-k-1])%p;
printf("%lld\n",f[n]);
}
| 20.5 | 51 | 0.550523 | wzl19371 |
5f71afccb2722ea46e95da751a1150f0d225eec0 | 1,870 | hpp | C++ | Sources/etwprof/OS/Stream/OStreamManipulators.hpp | Donpedro13/etwprof | a9db371ef556d564529c5112c231157d3789292b | [
"MIT"
] | 38 | 2018-06-11T19:09:16.000Z | 2022-03-17T04:15:15.000Z | Sources/etwprof/OS/Stream/OStreamManipulators.hpp | killvxk/etwprof | 37ca044b5dd6be39dbd77ba7653395aa95768692 | [
"MIT"
] | 12 | 2018-06-12T20:24:05.000Z | 2021-07-31T18:28:48.000Z | Sources/etwprof/OS/Stream/OStreamManipulators.hpp | killvxk/etwprof | 37ca044b5dd6be39dbd77ba7653395aa95768692 | [
"MIT"
] | 5 | 2019-02-23T04:11:03.000Z | 2022-03-17T04:15:18.000Z | #ifndef ETWP_OSTREAM_MANIPULATORS_HPP
#define ETWP_OSTREAM_MANIPULATORS_HPP
namespace ETWP {
class ConsoleOStream;
using OStreamManipulator = void (*)(ConsoleOStream*);
void Endl (ConsoleOStream* stream);
void ColorReset (ConsoleOStream* stream);
void FgColorReset (ConsoleOStream* stream);
void FgColorBlack (ConsoleOStream* stream);
void FgColorBlue (ConsoleOStream* stream);
void FgColorDarkBlue (ConsoleOStream* stream);
void FgColorCyan (ConsoleOStream* stream);
void FgColorDarkCyan (ConsoleOStream* stream);
void FgColorGray (ConsoleOStream* stream);
void FgColorDarkGray (ConsoleOStream* stream);
void FgColorGreen (ConsoleOStream* stream);
void FgColorDarkGreen (ConsoleOStream* stream);
void FgColorMagenta (ConsoleOStream* stream);
void FgColorDarkMagenta (ConsoleOStream* stream);
void FgColorRed (ConsoleOStream* stream);
void FgColorDarkRed (ConsoleOStream* stream);
void FgColorWhite (ConsoleOStream* stream);
void FgColorYellow (ConsoleOStream* stream);
void FgColorDarkYellow (ConsoleOStream* stream);
void BgColorReset (ConsoleOStream* stream);
void BgColorBlack (ConsoleOStream* stream);
void BgColorBlue (ConsoleOStream* stream);
void BgColorDarkBlue (ConsoleOStream* stream);
void BgColorCyan (ConsoleOStream* stream);
void BgColorDarkCyan (ConsoleOStream* stream);
void BgColorGray (ConsoleOStream* stream);
void BgColorDarkGray (ConsoleOStream* stream);
void BgColorGreen (ConsoleOStream* stream);
void BgColorDarkGreen (ConsoleOStream* stream);
void BgColorMagenta (ConsoleOStream* stream);
void BgColorDarkMagenta (ConsoleOStream* stream);
void BgColorRed (ConsoleOStream* stream);
void BgColorDarkRed (ConsoleOStream* stream);
void BgColorWhite (ConsoleOStream* stream);
void BgColorYellow (ConsoleOStream* stream);
void BgColorDarkYellow (ConsoleOStream* stream);
} // namespace ETWP
#endif // #ifndef ETWP_OSTREAM_MANIPULATORS_HPP | 35.961538 | 53 | 0.818182 | Donpedro13 |
5f769c53c564d2e8ab345db842a6e9f09e0a9cf4 | 115 | cpp | C++ | docs/mfc/reference/codesnippet/CPP/application-information-and-management_1.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 965 | 2017-06-25T23:57:11.000Z | 2022-03-31T14:17:32.000Z | docs/mfc/reference/codesnippet/CPP/application-information-and-management_1.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 3,272 | 2017-06-24T00:26:34.000Z | 2022-03-31T22:14:07.000Z | docs/mfc/reference/codesnippet/CPP/application-information-and-management_1.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 951 | 2017-06-25T12:36:14.000Z | 2022-03-26T22:49:06.000Z | // Print the application's executable filename.
TRACE(_T("Executable filename = %s\n"), AfxGetApp()->m_pszExeName); | 57.5 | 67 | 0.747826 | bobbrow |
5f7a9c797738783fd2ab6b6edf2c15f5c2023d2b | 588 | hpp | C++ | src/moistureMeasurement.hpp | umiko/MoistureMeter | 89b617e57bf5934ccd4d0fdfa2eda12c4385edf1 | [
"MIT"
] | null | null | null | src/moistureMeasurement.hpp | umiko/MoistureMeter | 89b617e57bf5934ccd4d0fdfa2eda12c4385edf1 | [
"MIT"
] | null | null | null | src/moistureMeasurement.hpp | umiko/MoistureMeter | 89b617e57bf5934ccd4d0fdfa2eda12c4385edf1 | [
"MIT"
] | null | null | null | //AUTHOR:
//umiko(https://github.com/umiko)
//Permission to copy and modify is granted under the MIT license
//
//DESCRIPTION:
//A struct to save the last measurement taken, so it can be supplied at a later time again
#ifndef MOISTUREMEASUREMENT_CPP
#define MOISTUREMEASUREMENT_CPP
#include <Arduino.h>
class moistureMeasurement
{
private:
public:
static int m_measurement_count;
int m_rawValue{0};
int m_baseline{0};
moistureMeasurement();
moistureMeasurement(int rawValue, int baseline);
~moistureMeasurement();
float getMoistureInPercentage();
void print();
};
#endif | 23.52 | 90 | 0.765306 | umiko |
5f81a2abcc92a1c85e45e4f6f0eef014ce0282ea | 141 | hh | C++ | host/device-reference.hh | free-audio/clap-host | 4602d26b91a526ac80933bdc9f6fcafdf2423bbf | [
"MIT"
] | 24 | 2021-12-01T13:36:25.000Z | 2022-03-17T10:12:29.000Z | host/device-reference.hh | free-audio/clap-host | 4602d26b91a526ac80933bdc9f6fcafdf2423bbf | [
"MIT"
] | 9 | 2021-11-02T14:39:54.000Z | 2022-03-19T11:04:54.000Z | host/device-reference.hh | free-audio/clap-host | 4602d26b91a526ac80933bdc9f6fcafdf2423bbf | [
"MIT"
] | 4 | 2021-11-02T09:01:50.000Z | 2022-02-04T20:00:35.000Z | #pragma once
#include <QString>
struct DeviceReference {
QString _api = "(none)";
QString _name = "(noname)";
int _index = 0;
};
| 14.1 | 30 | 0.624113 | free-audio |
5f81c6c8c4ea9f912d51ed641b32741f6feecb1c | 2,784 | hpp | C++ | accumulate.hpp | dean985/itertools | 842715b5fe7db5c74f65da642aa06ae365bb68c2 | [
"MIT"
] | null | null | null | accumulate.hpp | dean985/itertools | 842715b5fe7db5c74f65da642aa06ae365bb68c2 | [
"MIT"
] | 2 | 2020-06-18T11:35:37.000Z | 2020-06-18T11:35:45.000Z | accumulate.hpp | dean985/itertools | 842715b5fe7db5c74f65da642aa06ae365bb68c2 | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
namespace itertools
{
typedef struct
{
template <typename T>
T operator()(T a, T b)
{
return a + b;
}
} add;
template <typename Container,typename Ftor = add>
class accumulate
{
Ftor _fnctor = [](int x, int y){return x*y;};
Container _container;
public:
accumulate(Container cont, Ftor func) : _fnctor(func), _container(cont) {}
accumulate(Container cont):_fnctor(add()), _container(cont) { }
class iterator
{
typename Container::iterator _iter;
typename Container::iterator _current;
typename Container::iterator _end;
Ftor ftor;
typename std::decay<decltype(*_iter)>::type sum;
public:
explicit iterator(typename Container::iterator iter,
typename Container::iterator end,
Ftor functor) : _iter(iter), _end(end), _current(_iter), ftor(functor)
{
if(_iter != _end)
sum = *iter;
}
iterator(iterator ©) = default;
iterator &operator=(const iterator &it)
{
this->_iter = it->_iter;
this->_end = it->_end;
this->ftor = it->ftor;
return *this;
}
iterator &operator++()
{
std::not_equal_to neq;
++_current;
if((neq(_current, _end)) )
{
sum = ftor(sum, (*_current));
}
return (*this);
}
iterator operator++(int a)
{
iterator temp(*this);
operator++();
return temp;
}
bool operator==(const iterator &it)
{
return (it._iter == this->_current) ;
}
bool operator!=(const iterator &it)
{
// std::cout<<"in !="<<std::endl;
return it._iter != this->_current;
}
decltype(*_iter) operator*()//// I need to make it template
{// i need to put here somthing that will return
return sum;
}
};
iterator begin()
{
return iterator(_container.begin(), _container.end(), _fnctor);
}
iterator end()
{
return iterator(_container.end(), _container.end(), _fnctor);
}
};
} // namespace itertools | 27.029126 | 91 | 0.431753 | dean985 |
5f83b93ffc743d1c6cb8c993a3e37548387c905c | 5,903 | cpp | C++ | source/octree/linear-octree.cpp | triplu-zero/monte-carlo-ray-tracer | 8b36d5154204fc67e13376ad15b8bac33065c2d1 | [
"MIT"
] | 149 | 2020-03-06T00:39:43.000Z | 2022-03-31T07:28:36.000Z | source/octree/linear-octree.cpp | triplu-zero/monte-carlo-ray-tracer | 8b36d5154204fc67e13376ad15b8bac33065c2d1 | [
"MIT"
] | 4 | 2020-07-27T15:33:09.000Z | 2022-02-24T11:34:40.000Z | source/octree/linear-octree.cpp | triplu-zero/monte-carlo-ray-tracer | 8b36d5154204fc67e13376ad15b8bac33065c2d1 | [
"MIT"
] | 17 | 2020-03-23T16:05:36.000Z | 2022-02-21T02:38:31.000Z | #include "linear-octree.hpp"
#include <glm/gtx/norm.hpp>
#include "../common/constexpr-math.hpp"
#include "../common/util.hpp"
template <class Data>
LinearOctree<Data>::LinearOctree(Octree<Data> &octree_root)
{
size_t octree_size = 0, data_size = 0;
octreeSize(octree_root, octree_size, data_size);
if (octree_size == 0 || data_size == 0) return;
uint32_t df_idx = root_idx;
uint64_t data_idx = 0;
compact(&octree_root, df_idx, data_idx, true);
}
template <class Data>
std::vector<SearchResult<Data>> LinearOctree<Data>::knnSearch(const glm::dvec3& p, size_t k, double radius_est) const
{
std::vector<SearchResult<Data>> result;
if (linear_tree.empty()) return result;
if (k > ordered_data.size()) k = ordered_data.size();
result.reserve(k);
double min_distance2 = -1.0;
double max_distance2 = pow2(radius_est);
double distance2 = linear_tree[root_idx].BB.distance2(p);
auto to_visit = reservedPriorityQueue<KNNode>(64);
KNNode current(root_idx, distance2);
while (true)
{
if (current.octant != null_idx)
{
if (linear_tree[current.octant].leaf)
{
uint64_t end_idx = linear_tree[current.octant].start_data + linear_tree[current.octant].num_data;
for (uint64_t i = linear_tree[current.octant].start_data; i < end_idx; i++)
{
double distance2 = glm::distance2(ordered_data[i].pos(), p);
if (distance2 <= max_distance2 && distance2 > min_distance2)
{
to_visit.emplace(distance2, i);
}
}
}
else
{
uint32_t child_octant = current.octant + 1;
while (child_octant != null_idx)
{
const auto& node = linear_tree[child_octant];
distance2 = node.BB.distance2(p);
if (distance2 <= max_distance2 && node.BB.max_distance2(p) > min_distance2)
{
to_visit.emplace(child_octant, distance2);
}
child_octant = node.next_sibling;
}
}
}
else
{
result.emplace_back(ordered_data[current.data], current.distance2);
if (result.size() == k) return result;
}
if (to_visit.empty())
{
// Maximum search sphere doesn't contain k points. Increase radius and
// traverse octree again, ignoring the already found closest points.
max_distance2 *= 2.0;
if (!result.empty()) min_distance2 = result.back().distance2;
current = KNNode(root_idx, linear_tree[root_idx].BB.distance2(p));
}
else
{
current = to_visit.top();
to_visit.pop();
}
}
}
template <class Data>
std::vector<SearchResult<Data>> LinearOctree<Data>::radiusSearch(const glm::dvec3& p, double radius) const
{
std::vector<SearchResult<Data>> result;
if (linear_tree.empty()) return result;
recursiveRadiusSearch(root_idx, p, pow2(radius), result);
return result;
}
template <class Data>
void LinearOctree<Data>::recursiveRadiusSearch(const uint32_t current, const glm::dvec3& p, double radius2, std::vector<SearchResult<Data>>& result) const
{
if (linear_tree[current].leaf)
{
uint64_t end_idx = linear_tree[current].start_data + linear_tree[current].num_data;
for (uint64_t i = linear_tree[current].start_data; i < end_idx; i++)
{
double distance2 = glm::distance2(ordered_data[i].pos(), p);
if (distance2 <= radius2)
{
result.emplace_back(ordered_data[i], distance2);
}
}
}
else
{
uint32_t child_octant = current + 1;
while (child_octant != null_idx)
{
if (linear_tree[child_octant].BB.distance2(p) <= radius2)
{
recursiveRadiusSearch(child_octant, p, radius2, result);
}
child_octant = linear_tree[child_octant].next_sibling;
}
}
}
template <class Data>
void LinearOctree<Data>::octreeSize(const Octree<Data> &octree_root, size_t &size, size_t &data_size) const
{
if (octree_root.leaf() && octree_root.data_vec.empty()) return;
size++;
data_size += octree_root.data_vec.size();
if (!octree_root.leaf())
{
for (const auto &octant : octree_root.octants)
{
octreeSize(*octant, size, data_size);
}
}
}
template <class Data>
BoundingBox LinearOctree<Data>::compact(Octree<Data> *node, uint32_t &df_idx, uint64_t &data_idx, bool last)
{
uint32_t idx = df_idx++;
linear_tree.emplace_back();
linear_tree[idx].leaf = (uint8_t)node->leaf();
linear_tree[idx].start_data = data_idx;
linear_tree[idx].num_data = (uint16_t)node->data_vec.size();
BoundingBox BB;
for (auto&& data : node->data_vec) BB.merge(data.pos());
ordered_data.insert(ordered_data.end(), node->data_vec.begin(), node->data_vec.end());
data_idx += node->data_vec.size();
node->data_vec.clear();
node->data_vec.shrink_to_fit();
if (!node->leaf())
{
std::vector<size_t> use;
for (size_t i = 0; i < node->octants.size(); i++)
{
if (!(node->octants[i]->leaf() && node->octants[i]->data_vec.empty()))
{
use.push_back(i);
}
}
for (const auto &i : use)
{
BB.merge(compact(node->octants[i].get(), df_idx, data_idx, i == use.back()));
}
}
node->octants.clear();
node->octants.shrink_to_fit();
linear_tree[idx].next_sibling = last ? null_idx : df_idx;
linear_tree[idx].BB = BB;
return BB;
}
| 31.566845 | 154 | 0.580891 | triplu-zero |
5f84f5c1e5e2bacec64ab1c2ad6891b75f2c5ec7 | 3,397 | cpp | C++ | source/LinearizedImplicitEuler.cpp | sergeneren/BubbleH | e018e5a008e101221a4f8a3bbb25e7ec03fc9662 | [
"BSD-3-Clause-Clear"
] | 52 | 2019-10-06T17:25:39.000Z | 2022-01-20T23:01:13.000Z | source/LinearizedImplicitEuler.cpp | sergeneren/BubbleH | e018e5a008e101221a4f8a3bbb25e7ec03fc9662 | [
"BSD-3-Clause-Clear"
] | 1 | 2019-10-08T18:44:41.000Z | 2019-10-09T07:48:31.000Z | source/LinearizedImplicitEuler.cpp | sergeneren/BubbleH | e018e5a008e101221a4f8a3bbb25e7ec03fc9662 | [
"BSD-3-Clause-Clear"
] | 10 | 2019-10-07T16:33:24.000Z | 2020-10-21T01:09:47.000Z | #include "LinearizedImplicitEuler.h"
#include "VS3D.h"
// TODO: Save space by creating dx, dv, rhs, A only once.
LinearizedImplicitEuler::LinearizedImplicitEuler()
: SceneStepper()
{}
LinearizedImplicitEuler::~LinearizedImplicitEuler()
{}
bool LinearizedImplicitEuler::stepScene( VS3D& scene, scalar dt )
{
const int ndof = scene.constrainedPositions().size() * 3;
const VecXd& x = Eigen::Map<VecXd>((double*) &scene.constrainedPositions()[0], ndof);
const VecXd& v = Eigen::Map<VecXd>((double*) &scene.constrainedVelocities()[0], ndof);
const VecXd& m = Eigen::Map<VecXd>((double*) &scene.constrainedMass()[0], ndof);
assert(x.size() == v.size());
assert( ndof % 3 == 0 );
int nprts = scene.constrainedPositions().size();
assert( 3 * nprts == ndof );
// We specify the current iterate as a change from last timestep's solution
// Linearizing about the previous timestep's solution implies dx = dt*v0
VectorXs dx = dt*v;
// Linearizing about the previous timestep's solution implies dv = 0
VectorXs dv = VectorXs::Zero(ndof);
scene.preCompute(dx, dv, dt);
// RHS of linear system is force. rhs == f
SparseXs A(ndof,ndof);
TripletXs tri_A;
SparseXs Av(ndof, ndof);
TripletXs tri_Av;
SparseXs M(ndof, ndof);
TripletXs mm;
SparseXs C(ndof, ndof);
TripletXs cc;
for(int i = 0; i < ndof; ++i) {
if(scene.constrainedFixed()[i / 3]) {
mm.push_back(Triplets(i, i, 1.0));
} else {
mm.push_back(Triplets(i, i, m(i)));
cc.push_back(Triplets(i, i, 1.0));
}
}
M.setFromTriplets(mm.begin(), mm.end());
C.setFromTriplets(cc.begin(), cc.end());
tri_A.clear();
scene.accumulateddUdxdx(tri_A);
tri_Av.clear();
scene.accumulateddUdxdv(tri_Av);
// lhs == -df/dx
A.setFromTriplets(tri_A.begin(), tri_A.end());
A *= dt;
SparseXs B = A;
// lhs == -h*df/dx
Av.setFromTriplets(tri_Av.begin(), tri_Av.end());
// lhs == -h*df/dv -h^2*df/dx
// lhs == -df/dv -h*df/dx
A += Av;
// lhs == -h*df/dv -h^2*df/dx
A *= dt;
// For scripted DoFs, zero out the rows/cols of fixed degrees of freedom
A = C * A;
// lhs == M -h*df/dv -h^2*df/dx
A += M;
Eigen::SimplicialLDLT<SparseXs> solver(A);
VectorXs rhs = VectorXs::Zero(ndof);
scene.accumulateGradU(rhs,dx,dv);
rhs *= -1.0;
// rhs == f - hessE * v
rhs -= C * (B * v);
// rhs == h*f
rhs *= dt;
// For scripted DoFs, zero the elements of fixed degrees of freedom
zeroFixedDoFs( scene, rhs );
// Change in velocity returned by linear solve
VectorXs dqdot = solver.solve(rhs);
Eigen::Map<VecXd>((double*) &scene.constrainedVelocities()[0], ndof) += dqdot;
Eigen::Map<VecXd>((double*) &scene.constrainedPositions()[0], ndof) += dt * Eigen::Map<VecXd>((double*) &scene.constrainedVelocities()[0], ndof);
return true;
}
std::string LinearizedImplicitEuler::getName() const
{
return "Linearized Implicit Euler";
}
void LinearizedImplicitEuler::zeroFixedDoFs( const VS3D& scene, VectorXs& vec )
{
int nprts = scene.constrainedPositions().size();
for( int i = 0; i < nprts; ++i ) if( scene.constrainedFixed()[i] ) vec.segment<3>(3 * i).setZero();
}
| 28.308333 | 149 | 0.600236 | sergeneren |
5f86049f22b9d449118b81ec1a272d8b8a360ade | 1,433 | cpp | C++ | android-30/java/util/logging/ErrorManager.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/java/util/logging/ErrorManager.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/java/util/logging/ErrorManager.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../lang/Exception.hpp"
#include "../../../JString.hpp"
#include "./ErrorManager.hpp"
namespace java::util::logging
{
// Fields
jint ErrorManager::CLOSE_FAILURE()
{
return getStaticField<jint>(
"java.util.logging.ErrorManager",
"CLOSE_FAILURE"
);
}
jint ErrorManager::FLUSH_FAILURE()
{
return getStaticField<jint>(
"java.util.logging.ErrorManager",
"FLUSH_FAILURE"
);
}
jint ErrorManager::FORMAT_FAILURE()
{
return getStaticField<jint>(
"java.util.logging.ErrorManager",
"FORMAT_FAILURE"
);
}
jint ErrorManager::GENERIC_FAILURE()
{
return getStaticField<jint>(
"java.util.logging.ErrorManager",
"GENERIC_FAILURE"
);
}
jint ErrorManager::OPEN_FAILURE()
{
return getStaticField<jint>(
"java.util.logging.ErrorManager",
"OPEN_FAILURE"
);
}
jint ErrorManager::WRITE_FAILURE()
{
return getStaticField<jint>(
"java.util.logging.ErrorManager",
"WRITE_FAILURE"
);
}
// QJniObject forward
ErrorManager::ErrorManager(QJniObject obj) : JObject(obj) {}
// Constructors
ErrorManager::ErrorManager()
: JObject(
"java.util.logging.ErrorManager",
"()V"
) {}
// Methods
void ErrorManager::error(JString arg0, java::lang::Exception arg1, jint arg2) const
{
callMethod<void>(
"error",
"(Ljava/lang/String;Ljava/lang/Exception;I)V",
arg0.object<jstring>(),
arg1.object(),
arg2
);
}
} // namespace java::util::logging
| 19.364865 | 84 | 0.677599 | YJBeetle |
5f9546f9a266b3fce0de657ba183711f056e1543 | 1,336 | cpp | C++ | Contributor Corner/Mercy/print bracket number/bracket.cpp | hitu1304/interview-corner | 97503d1967c646f731275ae3665f142814c6a9d7 | [
"MIT"
] | 39 | 2020-11-01T13:58:48.000Z | 2021-02-12T08:39:37.000Z | Contributor Corner/Mercy/print bracket number/bracket.cpp | hitu1304/interview-corner | 97503d1967c646f731275ae3665f142814c6a9d7 | [
"MIT"
] | 86 | 2020-09-25T07:20:40.000Z | 2021-02-18T20:36:29.000Z | Contributor Corner/Mercy/print bracket number/bracket.cpp | hitu1304/interview-corner | 97503d1967c646f731275ae3665f142814c6a9d7 | [
"MIT"
] | 43 | 2020-12-18T03:32:42.000Z | 2021-02-19T18:08:19.000Z | #include <bits/stdc++.h>
using namespace std;
// function to print the bracket number
void printBracketNumber(string exp, int n)
{
// used to print the bracket number
// for the left bracket
int left_bnum = 1;
// used to obtain the bracket number
// for the right bracket
stack<int> right_bnum;
// traverse the given expression 'exp'
for (int i = 0; i < n; i++) {
// if current character is a left bracket
if (exp[i] == '(') {
// print 'left_bnum',
cout << left_bnum << " ";
// push 'left_bum' on to the stack 'right_bnum'
right_bnum.push(left_bnum);
// increment 'left_bnum' by 1
left_bnum++;
}
// else if current character is a right bracket
else if(exp[i] == ')') {
// print the top element of stack 'right_bnum'
// it will be the right bracket number
cout << right_bnum.top() << " ";
// pop the top element from the stack
right_bnum.pop();
}
}
}
int main()
{
string exp = "(a+(b*c))+(d/e)";
int n = exp.size();
printBracketNumber(exp, n);
return 0;
}
| 24.740741 | 60 | 0.480539 | hitu1304 |
5f98d36504125aa4f7d3690db1a51afc184288c4 | 6,406 | cpp | C++ | core/impl/file/file_obj_mesh.cpp | auyunli/enhance | ca99530c80b42842e713ed4b62e40d12e56ee24a | [
"BSD-2-Clause"
] | null | null | null | core/impl/file/file_obj_mesh.cpp | auyunli/enhance | ca99530c80b42842e713ed4b62e40d12e56ee24a | [
"BSD-2-Clause"
] | null | null | null | core/impl/file/file_obj_mesh.cpp | auyunli/enhance | ca99530c80b42842e713ed4b62e40d12e56ee24a | [
"BSD-2-Clause"
] | null | null | null | #include <fstream>
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
#include <cmath>
#include <tuple>
#include <regex>
#include <cassert>
#include "file_obj_mesh.hpp"
#include "renderable_info.hpp"
renderable_info_tris file_obj_mesh::calc_renderable_info_tris( file_obj_mesh::data_mesh & dm ){
renderable_info_tris ret {};
//add vertex and normals for rendering
for( auto & t : dm._tris ){
for( int i = 0; i < 3; ++i ){
int vert_index = t._vert_indices[ i ];
auto & v = dm._verts[ vert_index ];
ret._pos.push_back( v._pos[0] );
ret._pos.push_back( v._pos[1] );
ret._pos.push_back( v._pos[2] );
ret._normal.push_back( v._normal[0] );
ret._normal.push_back( v._normal[1] );
ret._normal.push_back( v._normal[2] );
ret._uv.push_back( v._tex_coords[0] );
ret._uv.push_back( v._tex_coords[1] );
}
}
return std::move(ret);
}
std::pair<bool, file_obj_mesh::data_mesh> file_obj_mesh::process( std::string file_path ){
std::fstream input;
input.open( file_path, std::fstream::in );
std::string current;
std::stringstream ss;
size_t count_normals = 0;
size_t count_verts = 0;
size_t count_tris = 0;
size_t count_tc = 0;
std::vector<std::string> vTextureName;
int objectCount = 0;
int triangleCount = 0;
std::string result_obj_name;
file_obj_mesh::data_mesh dm {};
std::vector<file_obj_mesh::norm> normals {};
std::vector<file_obj_mesh::texturecoord> textures {};
while (getline(input, current))
{
// object name
std::regex reg_obj_name("^o (\\w+)");
std::smatch match_obj_name;
if (std::regex_search( current, match_obj_name, reg_obj_name ) && match_obj_name.size() > 1 ) {
result_obj_name = match_obj_name.str(1);
// std::cout << "Object Name: " << result_obj_name << std::endl;
continue;
}
//vertices
std::regex reg_vert_coord("^v ([+-]?\\d+(?:\\.\\d+)?) ([+-]?\\d+(?:\\.\\d+)?) ([+-]?\\d+(?:\\.\\d+)?)");
std::smatch match_vert_coord;
std::string result_vert_coord;
if (std::regex_search( current, match_vert_coord, reg_vert_coord ) && match_vert_coord.size() > 3 ) {
file_obj_mesh::vert v;
v._index = count_verts++;
for( int i = 0; i < 3; ++i )
v._pos[i] = stod( match_vert_coord.str( i + 1 ) );
// std::cout << "Vertice Coord: " << v._pos[0] << ", " << v._pos[1] <<", " << v._pos[2] << std::endl;
dm._verts.push_back(v);
continue;
}
//normals
std::regex reg_vert_norm("^vn ([+-]?\\d+(?:\\.\\d+)?) ([+-]?\\d+(?:\\.\\d+)?) ([+-]?\\d+(?:\\.\\d+)?)");
std::smatch match_vert_norm;
std::string result_vert_norm;
if (std::regex_search( current, match_vert_norm, reg_vert_norm ) && match_vert_norm.size() > 3 ) {
file_obj_mesh::norm n {};
n._index = count_normals++;
for( int i = 0; i < 3; ++i )
n._normal[i] = stod( match_vert_norm.str( i + 1 ) );
// std::cout << "Vertice Normal: " << n._normal[0] << ", " << n._normal[1] <<", " << n._normal[2] << std::endl;
normals.push_back( n );
continue;
}
//texture coordinates
std::regex reg_tc("^vt ([+-]?\\d+(?:\\.\\d+)?) ([+-]?\\d+(?:\\.\\d+)?)");
std::smatch match_tc;
std::string result_tc;
if (std::regex_search( current, match_tc, reg_tc ) && match_tc.size() > 2 ) {
file_obj_mesh::texturecoord tc {};
tc._index = count_tc++;
for( int i = 0; i < 2; ++i )
tc._tc[i] = stod( match_tc.str( i + 1 ) );
// std::cout << "Texture Coord: " << tc._tc[0] << ", " << tc._tc[1] << std::endl;
textures.push_back( tc );
continue;
}
//triangle faces
std::regex reg_face("^f (\\d+)//(\\d+) (\\d+)//(\\d+) (\\d+)//(\\d+)"); // v_coord, v_normal
std::regex reg_face_2("^f (\\d+)/(?:\\d+)/(\\d+) (\\d+)/(?:\\d+)/(\\d+) (\\d+)/(?:\\d+)/(\\d+)"); // v_coord, v_texturecoord, v_normal
std::smatch match_face;
std::string result_face;
if (std::regex_search( current, match_face, reg_face ) && match_face.size() > 6 ){
file_obj_mesh::tri t {};
t._index = count_tris++;
for( int i = 0; i < 3; ++i )
t._vert_indices[ i ] = stoi( match_face.str( 1 + i * 2 ) ) - 1;
dm._tris.push_back( t );
//get normals and copy into vert structure
for( int i = 0; i < 3; ++i ){
int index_norm = stoi( match_face.str( 2 + i * 2 ) ) - 1;
if( index_norm < 0 || index_norm >= normals.size() ){
assert( 0 && "triangle normal index out of range." );
return { false, {} };
}
int index_vert = t._vert_indices[i];
if( index_vert < 0 || index_vert >= dm._verts.size() ){
assert( 0 && "triangle vert index out of range." );
return { false, {} };
}
file_obj_mesh::vert & v = dm._verts[ index_vert ];
for( int j = 0; j < 3; ++j ){
v._normal[j] = normals[ index_norm ]._normal[j];
}
}
continue;
}
if (std::regex_search( current, match_face, reg_face_2 ) && match_face.size() > 9 ) {
tri t {};
t._index = count_tris++;
for( int i = 0; i < 3; ++i )
t._vert_indices[ i ] = stoi( match_face.str( 1 + i * 3 ) ) - 1;
dm._tris.push_back( t );
for( int i = 0; i < 3; ++i ){
//get normals and copy into vert structure
int index_norm = stoi( match_face.str( 3 + i * 3 ) ) - 1;
if( index_norm < 0 || index_norm >= normals.size() ){
assert( 0 && "triangle normal index out of range." );
return { false, {} };
}
int index_vert = t._vert_indices[i];
if( index_vert < 0 || index_vert >= dm._verts.size() ){
assert( 0 && "triangle vert index out of range." );
return { false, {} };
}
vert & v = dm._verts[ index_vert ];
for( int j = 0; j < 3; ++j ){
v._normal[j] = normals[ index_norm ]._normal[j];
}
//get texture coordinate indices and copy into vert structure
int index_tc = stoi( match_face.str( 2 + i * 3 ) );
if( index_tc < 0 || index_tc >= textures.size() ){
assert( 0 && "triangle texture index out of range." );
return { false, {} };
}
file_obj_mesh::texturecoord & tc = textures[ index_tc ];
for( int j = 0; j < 2; ++j ){
v._tex_coords[j] = tc._tc[j];
}
}
continue;
}
}
input.close();
dm._numverts = dm._verts.size();
dm._numtris = dm._tris.size();
return { true, std::move(dm) };
}
| 35.787709 | 135 | 0.559319 | auyunli |
5f9e63dab889a49fe82ceaa575f866b943cf2ae3 | 644 | hpp | C++ | higan/gb/cartridge/mbc3/mbc3.hpp | 13824125580/higan | fbdd3f980b65412c362096579869ae76730e4118 | [
"Intel",
"ISC"
] | 38 | 2018-04-05T05:00:05.000Z | 2022-02-06T00:02:02.000Z | higan/gb/cartridge/mbc3/mbc3.hpp | 13824125580/higan | fbdd3f980b65412c362096579869ae76730e4118 | [
"Intel",
"ISC"
] | 1 | 2018-04-29T19:45:14.000Z | 2018-04-29T19:45:14.000Z | higan/gb/cartridge/mbc3/mbc3.hpp | 13824125580/higan | fbdd3f980b65412c362096579869ae76730e4118 | [
"Intel",
"ISC"
] | 8 | 2018-04-16T22:37:46.000Z | 2021-02-10T07:37:03.000Z | struct MBC3 : Mapper {
auto second() -> void;
auto read(uint16 address) -> uint8;
auto write(uint16 address, uint8 data) -> void;
auto power() -> void;
auto serialize(serializer& s) -> void;
struct IO {
struct ROM {
uint8 bank = 0x01;
} rom;
struct RAM {
uint1 enable;
uint8 bank;
} ram;
struct RTC {
uint1 halt = true;
uint1 latch;
uint8 second;
uint8 minute;
uint8 hour;
uint9 day;
uint1 dayCarry;
uint8 latchSecond;
uint8 latchMinute;
uint8 latchHour;
uint9 latchDay;
uint1 latchDayCarry;
} rtc;
} io;
} mbc3;
| 18.941176 | 49 | 0.569876 | 13824125580 |
5fa14f0d066969b5eed836ed5f70579eebf75663 | 1,612 | cpp | C++ | src/BitmapReader.cpp | antenous/image | 7743a31d87bae1b76efdd4023f21d0f861093057 | [
"BSD-3-Clause"
] | null | null | null | src/BitmapReader.cpp | antenous/image | 7743a31d87bae1b76efdd4023f21d0f861093057 | [
"BSD-3-Clause"
] | null | null | null | src/BitmapReader.cpp | antenous/image | 7743a31d87bae1b76efdd4023f21d0f861093057 | [
"BSD-3-Clause"
] | null | null | null | /*
* BitmapReader.cpp
*
* Created on: Dec 17, 2017
* Author: Antero Nousiainen
*/
#include "BitmapReader.hpp"
using namespace image;
namespace
{
template<typename T>
void read(std::istream & stream, T & t, std::streamsize count = sizeof(T))
{
stream.read(reinterpret_cast<char*>(&t), count);
}
inline void skipPadding(std::istream & from, uint8_t padding)
{
from.seekg(padding, from.cur);
}
void read(std::istream & from, Bitmap::Data & data, int32_t height, int32_t width, uint8_t padding)
{
data.resize(height*width);
for (int32_t row(0), firstInRow(0); row < height; ++row, firstInRow += width, skipPadding(from, padding))
read(from, data[firstInRow], width*sizeof(Bitmap::Data::value_type));
}
Bitmap readBitmap(std::istream & from)
{
Bitmap bmp;
read(from, bmp.magic);
if (!bmp)
throw BitmapReader::InvalidType();
read(from, bmp.header.file);
read(from, bmp.header.info);
read(from, bmp.data, bmp.height(), bmp.width(), bmp.padding());
return bmp;
}
}
BitmapReader::BadFile::BadFile() :
std::invalid_argument("bad file")
{}
BitmapReader::InvalidType::InvalidType() :
std::runtime_error("invalid type")
{}
Bitmap BitmapReader::read(std::istream & from)
{
if (!from)
throw BitmapReader::BadFile();
from.exceptions(std::istream::failbit | std::istream::badbit);
try
{
return readBitmap(from);
}
catch (const std::istream::failure &)
{
throw BadFile();
}
}
| 22.082192 | 113 | 0.603598 | antenous |
5fa3d390d814fdc6c5f3be91a0f2cb7433526079 | 167,382 | cpp | C++ | src/magic/actmagic.cpp | PegasusEpsilon/Barony | 6311f7e5da4835eaea65a95b5cc258409bb0dfa4 | [
"FTL",
"Zlib",
"MIT"
] | 373 | 2016-06-28T06:56:46.000Z | 2022-03-23T02:32:54.000Z | src/magic/actmagic.cpp | PegasusEpsilon/Barony | 6311f7e5da4835eaea65a95b5cc258409bb0dfa4 | [
"FTL",
"Zlib",
"MIT"
] | 361 | 2016-07-06T19:09:25.000Z | 2022-03-26T14:14:19.000Z | src/magic/actmagic.cpp | PegasusEpsilon/Barony | 6311f7e5da4835eaea65a95b5cc258409bb0dfa4 | [
"FTL",
"Zlib",
"MIT"
] | 129 | 2016-06-29T09:02:49.000Z | 2022-01-23T09:56:06.000Z | /*-------------------------------------------------------------------------------
BARONY
File: actmagic.cpp
Desc: behavior function for magic balls
Copyright 2013-2016 (c) Turning Wheel LLC, all rights reserved.
See LICENSE for details.
-------------------------------------------------------------------------------*/
#include "../main.hpp"
#include "../game.hpp"
#include "../stat.hpp"
#include "../entity.hpp"
#include "../interface/interface.hpp"
#include "../sound.hpp"
#include "../items.hpp"
#include "../monster.hpp"
#include "../net.hpp"
#include "../collision.hpp"
#include "../paths.hpp"
#include "../player.hpp"
#include "magic.hpp"
#include "../scores.hpp"
void actMagiclightBall(Entity* my)
{
Entity* caster = NULL;
if (!my)
{
return;
}
my->skill[2] = -10; // so the client sets the behavior of this entity
if (clientnum != 0 && multiplayer == CLIENT)
{
my->removeLightField();
//Light up the area.
my->light = lightSphereShadow(my->x / 16, my->y / 16, 8, 192);
if ( flickerLights )
{
//Magic light ball will never flicker if this setting is disabled.
lightball_flicker++;
}
if (lightball_flicker > 5)
{
lightball_lighting = (lightball_lighting == 1) + 1;
if (lightball_lighting == 1)
{
my->removeLightField();
my->light = lightSphereShadow(my->x / 16, my->y / 16, 8, 192);
}
else
{
my->removeLightField();
my->light = lightSphereShadow(my->x / 16, my->y / 16, 8, 174);
}
lightball_flicker = 0;
}
lightball_timer--;
return;
}
my->yaw += .01;
if ( my->yaw >= PI * 2 )
{
my->yaw -= PI * 2;
}
/*if (!my->parent) { //This means that it doesn't have a caster. In other words, magic light staff.
return;
})*/
//list_t *path = NULL;
pathnode_t* pathnode = NULL;
//TODO: Follow player around (at a distance -- and delay before starting to follow).
//TODO: Circle around player's head if they stand still for a little bit. Continue circling even if the player walks away -- until the player is far enough to trigger move (or if the player moved for a bit and then stopped, then update position).
//TODO: Don't forget to cast flickering light all around it.
//TODO: Move out of creatures' way if they collide.
/*if (!my->children) {
list_RemoveNode(my->mynode); //Delete the light spell.
return;
}*/
if (!my->children.first)
{
list_RemoveNode(my->mynode); //Delete the light spell.C
return;
}
node_t* node = NULL;
spell_t* spell = NULL;
node = my->children.first;
spell = (spell_t*)node->element;
if (!spell)
{
list_RemoveNode(my->mynode);
return; //We need the source spell!
}
caster = uidToEntity(spell->caster);
if (caster)
{
Stat* stats = caster->getStats();
if (stats)
{
if (stats->HP <= 0)
{
my->removeLightField();
list_RemoveNode(my->mynode); //Delete the light spell.
return;
}
}
}
else if (spell->caster >= 1) //So no caster...but uidToEntity returns NULL if entity is already dead, right? And if the uid is supposed to point to an entity, but it doesn't...it means the caster has died.
{
my->removeLightField();
list_RemoveNode(my->mynode);
return;
}
// if the spell has been unsustained, remove it
if ( !spell->magicstaff && !spell->sustain )
{
int i = 0;
int player = -1;
for (i = 0; i < MAXPLAYERS; ++i)
{
if (players[i]->entity == caster)
{
player = i;
}
}
if (player > 0 && multiplayer == SERVER)
{
strcpy( (char*)net_packet->data, "UNCH");
net_packet->data[4] = player;
SDLNet_Write32(spell->ID, &net_packet->data[5]);
net_packet->address.host = net_clients[player - 1].host;
net_packet->address.port = net_clients[player - 1].port;
net_packet->len = 9;
sendPacketSafe(net_sock, -1, net_packet, player - 1);
}
my->removeLightField();
list_RemoveNode(my->mynode);
return;
}
if (magic_init)
{
my->removeLightField();
if (lightball_timer <= 0)
{
if ( spell->sustain )
{
//Attempt to sustain the magic light.
if (caster)
{
//Deduct mana from caster. Cancel spell if not enough mana (simply leave sustained at false).
bool deducted = caster->safeConsumeMP(1); //Consume 1 mana every duration / mana seconds
if (deducted)
{
lightball_timer = spell->channel_duration / getCostOfSpell(spell);
}
else
{
int i = 0;
int player = -1;
for (i = 0; i < MAXPLAYERS; ++i)
{
if (players[i]->entity == caster)
{
player = i;
}
}
if (player > 0 && multiplayer == SERVER)
{
strcpy( (char*)net_packet->data, "UNCH");
net_packet->data[4] = player;
SDLNet_Write32(spell->ID, &net_packet->data[5]);
net_packet->address.host = net_clients[player - 1].host;
net_packet->address.port = net_clients[player - 1].port;
net_packet->len = 9;
sendPacketSafe(net_sock, -1, net_packet, player - 1);
}
my->removeLightField();
list_RemoveNode(my->mynode);
return;
}
}
}
}
//TODO: Make hovering always smooth. For example, when transitioning from ceiling to no ceiling, don't just have it jump to a new position. Figure out away to transition between the two.
if (lightball_hoverangle > 360)
{
lightball_hoverangle = 0;
}
if (map.tiles[(int)((my->y / 16) * MAPLAYERS + (my->x / 16) * MAPLAYERS * map.height)])
{
//Ceiling.
my->z = lightball_hover_basez + ((lightball_hover_basez + LIGHTBALL_HOVER_HIGHPEAK + lightball_hover_basez + LIGHTBALL_HOVER_LOWPEAK) / 2) * sin(lightball_hoverangle * (12.568f / 360.0f)) * 0.1f;
}
else
{
//No ceiling. //TODO: Float higher?
//my->z = lightball_hover_basez - 4 + ((lightball_hover_basez + LIGHTBALL_HOVER_HIGHPEAK - 4 + lightball_hover_basez + LIGHTBALL_HOVER_LOWPEAK - 4) / 2) * sin(lightball_hoverangle * (12.568f / 360.0f)) * 0.1f;
my->z = lightball_hover_basez + ((lightball_hover_basez + LIGHTBALL_HOVER_HIGHPEAK + lightball_hover_basez + LIGHTBALL_HOVER_LOWPEAK) / 2) * sin(lightball_hoverangle * (12.568f / 360.0f)) * 0.1f;
}
lightball_hoverangle += 1;
//Lightball moving.
//messagePlayer(0, "*");
Entity* parent = uidToEntity(my->parent);
if ( !parent )
{
return;
}
double distance = sqrt(pow(my->x - parent->x, 2) + pow(my->y - parent->y, 2));
if ( distance > MAGICLIGHT_BALL_FOLLOW_DISTANCE || my->path)
{
lightball_player_lastmove_timer = 0;
if (lightball_movement_timer > 0)
{
lightball_movement_timer--;
}
else
{
//messagePlayer(0, "****Moving.");
double tangent = atan2(parent->y - my->y, parent->x - my->x);
lineTraceTarget(my, my->x, my->y, tangent, 1024, IGNORE_ENTITIES, false, parent);
if ( !hit.entity || hit.entity == parent ) //Line of sight to caster?
{
if (my->path != NULL)
{
list_FreeAll(my->path);
my->path = NULL;
}
//double tangent = atan2(parent->y - my->y, parent->x - my->x);
my->vel_x = cos(tangent) * ((distance - MAGICLIGHT_BALL_FOLLOW_DISTANCE) / MAGICLIGHTBALL_DIVIDE_CONSTANT);
my->vel_y = sin(tangent) * ((distance - MAGICLIGHT_BALL_FOLLOW_DISTANCE) / MAGICLIGHTBALL_DIVIDE_CONSTANT);
my->x += (my->vel_x < MAGIC_LIGHTBALL_SPEEDLIMIT) ? my->vel_x : MAGIC_LIGHTBALL_SPEEDLIMIT;
my->y += (my->vel_y < MAGIC_LIGHTBALL_SPEEDLIMIT) ? my->vel_y : MAGIC_LIGHTBALL_SPEEDLIMIT;
//} else if (!map.tiles[(int)(OBSTACLELAYER + (my->y / 16) * MAPLAYERS + (my->x / 16) * MAPLAYERS * map.height)]) { //If not in wall..
}
else
{
//messagePlayer(0, "******Pathfinding.");
//Caster is not in line of sight. Calculate a move path.
/*if (my->children->first != NULL) {
list_RemoveNode(my->children->first);
my->children->first = NULL;
}*/
if (!my->path)
{
//messagePlayer(0, "[Light ball] Generating path.");
list_t* path = generatePath((int)floor(my->x / 16), (int)floor(my->y / 16), (int)floor(parent->x / 16), (int)floor(parent->y / 16), my, parent);
if ( path != NULL )
{
my->path = path;
}
else
{
//messagePlayer(0, "[Light ball] Failed to generate path (%s line %d).", __FILE__, __LINE__);
}
}
if (my->path)
{
double total_distance = 0; //Calculate the total distance to the player to get the right move speed.
double prevx = my->x;
double prevy = my->y;
if (my->path != NULL)
{
for (node = my->path->first; node != NULL; node = node->next)
{
if (node->element)
{
pathnode = (pathnode_t*)node->element;
//total_distance += sqrt(pow(pathnode->y - prevy, 2) + pow(pathnode->x - prevx, 2) );
total_distance += sqrt(pow(prevx - pathnode->x, 2) + pow(prevy - pathnode->y, 2) );
prevx = pathnode->x;
prevy = pathnode->y;
}
}
}
else if (my->path) //If the path has been traversed, reset it.
{
list_FreeAll(my->path);
my->path = NULL;
}
total_distance -= MAGICLIGHT_BALL_FOLLOW_DISTANCE;
if (my->path != NULL)
{
if (my->path->first != NULL)
{
pathnode = (pathnode_t*)my->path->first->element;
//double distance = sqrt(pow(pathnode->y * 16 + 8 - my->y, 2) + pow(pathnode->x * 16 + 8 - my->x, 2) );
//double distance = sqrt(pow((my->y) - ((pathnode->y + 8) * 16), 2) + pow((my->x) - ((pathnode->x + 8) * 16), 2));
double distance = sqrt(pow(((pathnode->y * 16) + 8) - (my->y), 2) + pow(((pathnode->x * 16) + 8) - (my->x), 2));
if (distance <= 4)
{
list_RemoveNode(pathnode->node); //TODO: Make sure it doesn't get stuck here. Maybe remove the node only if it's the last one?
if (!my->path->first)
{
list_FreeAll(my->path);
my->path = NULL;
}
}
else
{
double target_tangent = atan2((pathnode->y * 16) + 8 - my->y, (pathnode->x * 16) + 8 - my->x);
if (target_tangent > my->yaw) //TODO: Do this yaw thing for all movement.
{
my->yaw = (target_tangent >= my->yaw + MAGIC_LIGHTBALL_TURNSPEED) ? my->yaw + MAGIC_LIGHTBALL_TURNSPEED : target_tangent;
}
else if (target_tangent < my->yaw)
{
my->yaw = (target_tangent <= my->yaw - MAGIC_LIGHTBALL_TURNSPEED) ? my->yaw - MAGIC_LIGHTBALL_TURNSPEED : target_tangent;
}
my->vel_x = cos(my->yaw) * (total_distance / MAGICLIGHTBALL_DIVIDE_CONSTANT);
my->vel_y = sin(my->yaw) * (total_distance / MAGICLIGHTBALL_DIVIDE_CONSTANT);
my->x += (my->vel_x < MAGIC_LIGHTBALL_SPEEDLIMIT) ? my->vel_x : MAGIC_LIGHTBALL_SPEEDLIMIT;
my->y += (my->vel_y < MAGIC_LIGHTBALL_SPEEDLIMIT) ? my->vel_y : MAGIC_LIGHTBALL_SPEEDLIMIT;
}
}
} //else assertion error, hehehe
}
else //Path failed to generate. Fallback on moving straight to the player.
{
//messagePlayer(0, "**************NO PATH WHEN EXPECTED PATH.");
my->vel_x = cos(tangent) * ((distance) / MAGICLIGHTBALL_DIVIDE_CONSTANT);
my->vel_y = sin(tangent) * ((distance) / MAGICLIGHTBALL_DIVIDE_CONSTANT);
my->x += (my->vel_x < MAGIC_LIGHTBALL_SPEEDLIMIT) ? my->vel_x : MAGIC_LIGHTBALL_SPEEDLIMIT;
my->y += (my->vel_y < MAGIC_LIGHTBALL_SPEEDLIMIT) ? my->vel_y : MAGIC_LIGHTBALL_SPEEDLIMIT;
}
} /*else {
//In a wall. Get out of it.
double tangent = atan2(parent->y - my->y, parent->x - my->x);
my->vel_x = cos(tangent) * ((distance) / 100);
my->vel_y = sin(tangent) * ((distance) / 100);
my->x += my->vel_x;
my->y += my->vel_y;
}*/
}
}
else
{
lightball_movement_timer = LIGHTBALL_MOVE_DELAY;
/*if (lightball_player_lastmove_timer < LIGHTBALL_CIRCLE_TIME) {
lightball_player_lastmove_timer++;
} else {
//TODO: Orbit the player. Maybe.
my->x = parent->x + (lightball_orbit_length * cos(lightball_orbit_angle));
my->y = parent->y + (lightball_orbit_length * sin(lightball_orbit_angle));
lightball_orbit_angle++;
if (lightball_orbit_angle > 360) {
lightball_orbit_angle = 0;
}
}*/
if (my->path != NULL)
{
list_FreeAll(my->path);
my->path = NULL;
}
if (map.tiles[(int)(OBSTACLELAYER + (my->y / 16) * MAPLAYERS + (my->x / 16) * MAPLAYERS * map.height)]) //If the ball has come to rest in a wall, move its butt.
{
double tangent = atan2(parent->y - my->y, parent->x - my->x);
my->vel_x = cos(tangent) * ((distance) / MAGICLIGHTBALL_DIVIDE_CONSTANT);
my->vel_y = sin(tangent) * ((distance) / MAGICLIGHTBALL_DIVIDE_CONSTANT);
my->x += my->vel_x;
my->y += my->vel_y;
}
}
//Light up the area.
my->light = lightSphereShadow(my->x / 16, my->y / 16, 8, 192);
if ( flickerLights )
{
//Magic light ball will never flicker if this setting is disabled.
lightball_flicker++;
}
if (lightball_flicker > 5)
{
lightball_lighting = (lightball_lighting == 1) + 1;
if (lightball_lighting == 1)
{
my->removeLightField();
my->light = lightSphereShadow(my->x / 16, my->y / 16, 8, 192);
}
else
{
my->removeLightField();
my->light = lightSphereShadow(my->x / 16, my->y / 16, 8, 174);
}
lightball_flicker = 0;
}
lightball_timer--;
}
else
{
//Init the lightball. That is, shoot out from the player.
//Move out from the player.
my->vel_x = cos(my->yaw) * 4;
my->vel_y = sin(my->yaw) * 4;
double dist = clipMove(&my->x, &my->y, my->vel_x, my->vel_y, my);
unsigned int distance = sqrt(pow(my->x - lightball_player_startx, 2) + pow(my->y - lightball_player_starty, 2));
if (distance > MAGICLIGHT_BALL_FOLLOW_DISTANCE * 2 || dist != sqrt(my->vel_x * my->vel_x + my->vel_y * my->vel_y))
{
magic_init = 1;
my->sprite = 174; //Go from black ball to white ball.
lightball_lighting = 1;
lightball_movement_timer = 0; //Start off at 0 so that it moves towards the player as soon as it's created (since it's created farther away from the player).
}
}
}
void actMagicMissile(Entity* my) //TODO: Verify this function.
{
if (!my || !my->children.first || !my->children.first->element)
{
return;
}
spell_t* spell = (spell_t*)my->children.first->element;
if (!spell)
{
return;
}
//node_t *node = NULL;
spellElement_t* element = NULL;
node_t* node = NULL;
int i = 0;
int c = 0;
Entity* entity = NULL;
double tangent;
Entity* parent = uidToEntity(my->parent);
if (magic_init)
{
my->removeLightField();
if ( multiplayer != CLIENT )
{
//Handle the missile's life.
MAGIC_LIFE++;
if (MAGIC_LIFE >= MAGIC_MAXLIFE)
{
my->removeLightField();
list_RemoveNode(my->mynode);
return;
}
if ( spell->ID == SPELL_CHARM_MONSTER || spell->ID == SPELL_ACID_SPRAY )
{
Entity* caster = uidToEntity(spell->caster);
if ( !caster )
{
my->removeLightField();
list_RemoveNode(my->mynode);
return;
}
}
node = spell->elements.first;
//element = (spellElement_t *) spell->elements->first->element;
element = (spellElement_t*)node->element;
Sint32 entityHealth = 0;
double dist = 0.f;
bool hitFromAbove = false;
if ( (parent && parent->behavior == &actMagicTrapCeiling) || my->actmagicIsVertical == MAGIC_ISVERTICAL_Z )
{
// moving vertically.
my->z += my->vel_z;
hitFromAbove = my->magicFallingCollision();
if ( !hitFromAbove )
{
// nothing hit yet, let's keep trying...
}
}
else if ( my->actmagicIsOrbiting != 0 )
{
int turnRate = 4;
if ( parent && my->actmagicIsOrbiting == 1 )
{
my->yaw += 0.1;
my->x = parent->x + my->actmagicOrbitDist * cos(my->yaw);
my->y = parent->y + my->actmagicOrbitDist * sin(my->yaw);
}
else if ( my->actmagicIsOrbiting == 2 )
{
my->yaw += 0.2;
turnRate = 4;
my->x = my->actmagicOrbitStationaryX + my->actmagicOrbitStationaryCurrentDist * cos(my->yaw);
my->y = my->actmagicOrbitStationaryY + my->actmagicOrbitStationaryCurrentDist * sin(my->yaw);
my->actmagicOrbitStationaryCurrentDist =
std::min(my->actmagicOrbitStationaryCurrentDist + 0.5, static_cast<real_t>(my->actmagicOrbitDist));
}
hitFromAbove = my->magicOrbitingCollision();
my->z += my->vel_z * my->actmagicOrbitVerticalDirection;
if ( my->actmagicIsOrbiting == 2 )
{
// we don't change direction, upwards we go!
// target speed is actmagicOrbitVerticalSpeed.
my->vel_z = std::min(my->actmagicOrbitVerticalSpeed, my->vel_z / 0.95);
my->roll += (PI / 8) / (turnRate / my->vel_z) * my->actmagicOrbitVerticalDirection;
my->roll = std::max(my->roll, -PI / 4);
}
else if ( my->z > my->actmagicOrbitStartZ )
{
if ( my->actmagicOrbitVerticalDirection == 1 )
{
my->vel_z = std::max(0.01, my->vel_z * 0.95);
my->roll -= (PI / 8) / (turnRate / my->vel_z) * my->actmagicOrbitVerticalDirection;
}
else
{
my->vel_z = std::min(my->actmagicOrbitVerticalSpeed, my->vel_z / 0.95);
my->roll += (PI / 8) / (turnRate / my->vel_z) * my->actmagicOrbitVerticalDirection;
}
}
else
{
if ( my->actmagicOrbitVerticalDirection == 1 )
{
my->vel_z = std::min(my->actmagicOrbitVerticalSpeed, my->vel_z / 0.95);
my->roll += (PI / 8) / (turnRate / my->vel_z) * my->actmagicOrbitVerticalDirection;
}
else
{
my->vel_z = std::max(0.01, my->vel_z * 0.95);
my->roll -= (PI / 8) / (turnRate / my->vel_z) * my->actmagicOrbitVerticalDirection;
}
}
if ( my->actmagicIsOrbiting == 1 )
{
if ( (my->z > my->actmagicOrbitStartZ + 4) && my->actmagicOrbitVerticalDirection == 1 )
{
my->actmagicOrbitVerticalDirection = -1;
}
else if ( (my->z < my->actmagicOrbitStartZ - 4) && my->actmagicOrbitVerticalDirection != 1 )
{
my->actmagicOrbitVerticalDirection = 1;
}
}
}
else
{
if ( my->actmagicIsVertical == MAGIC_ISVERTICAL_XYZ )
{
// moving vertically and horizontally, check if we hit the floor
my->z += my->vel_z;
hitFromAbove = my->magicFallingCollision();
dist = clipMove(&my->x, &my->y, my->vel_x, my->vel_y, my);
if ( !hitFromAbove && my->z > -5 )
{
// if we didn't hit the floor, process normal horizontal movement collision if we aren't too high
if ( dist != sqrt(my->vel_x * my->vel_x + my->vel_y * my->vel_y) )
{
hitFromAbove = true;
}
}
if ( my->actmagicProjectileArc > 0 )
{
real_t z = -1 - my->z;
if ( z > 0 )
{
my->pitch = -atan(z * 0.1 / sqrt(my->vel_x * my->vel_x + my->vel_y * my->vel_y));
}
else
{
my->pitch = -atan(z * 0.15 / sqrt(my->vel_x * my->vel_x + my->vel_y * my->vel_y));
}
if ( my->actmagicProjectileArc == 1 )
{
//messagePlayer(0, "z: %f vel: %f", my->z, my->vel_z);
my->vel_z = my->vel_z * 0.9;
if ( my->vel_z > -0.1 )
{
//messagePlayer(0, "arc down");
my->actmagicProjectileArc = 2;
my->vel_z = 0.01;
}
}
else if ( my->actmagicProjectileArc == 2 )
{
//messagePlayer(0, "z: %f vel: %f", my->z, my->vel_z);
my->vel_z = std::min(0.8, my->vel_z * 1.2);
}
}
}
else
{
dist = clipMove(&my->x, &my->y, my->vel_x, my->vel_y, my); //normal flat projectiles
}
}
if ( hitFromAbove || (my->actmagicIsVertical != MAGIC_ISVERTICAL_XYZ && dist != sqrt(my->vel_x * my->vel_x + my->vel_y * my->vel_y)) )
{
node = element->elements.first;
//element = (spellElement_t *) element->elements->first->element;
element = (spellElement_t*)node->element;
//if (hit.entity != NULL) {
Stat* hitstats = nullptr;
int player = -1;
if ( hit.entity )
{
hitstats = hit.entity->getStats();
if ( hit.entity->behavior == &actPlayer )
{
bool skipMessage = false;
if ( !(svFlags & SV_FLAG_FRIENDLYFIRE) && my->actmagicTinkerTrapFriendlyFire == 0 )
{
if ( parent && (parent->behavior == &actMonster || parent->behavior == &actPlayer) && parent->checkFriend(hit.entity) )
{
skipMessage = true;
}
}
player = hit.entity->skill[2];
if ( my->actmagicCastByTinkerTrap == 1 )
{
skipMessage = true;
}
if ( !skipMessage )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 255, 0, 0);
messagePlayerColor(player, color, language[376]);
}
if ( hitstats )
{
entityHealth = hitstats->HP;
}
}
if ( parent && hitstats )
{
if ( parent->behavior == &actPlayer )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 0, 255, 0);
if ( strcmp(element->name, spellElement_charmMonster.name) )
{
if ( my->actmagicCastByTinkerTrap == 1 )
{
//messagePlayerMonsterEvent(parent->skill[2], color, *hitstats, language[3498], language[3499], MSG_COMBAT);
}
else
{
messagePlayerMonsterEvent(parent->skill[2], color, *hitstats, language[378], language[377], MSG_COMBAT);
}
}
}
}
}
// Handling reflecting the missile
int reflection = 0;
if ( hitstats )
{
if ( !strcmp(map.name, "Hell Boss") && hit.entity->behavior == &actPlayer )
{
/* no longer in use */
/*bool founddevil = false;
node_t* tempNode;
for ( tempNode = map.creatures->first; tempNode != nullptr; tempNode = tempNode->next )
{
Entity* tempEntity = (Entity*)tempNode->element;
if ( tempEntity->behavior == &actMonster )
{
Stat* stats = tempEntity->getStats();
if ( stats )
{
if ( stats->type == DEVIL )
{
founddevil = true;
break;
}
}
}
}
if ( !founddevil )
{
reflection = 3;
}*/
}
else if ( parent &&
( (hit.entity->getRace() == LICH_ICE && parent->getRace() == LICH_FIRE)
|| ( (hit.entity->getRace() == LICH_FIRE || hitstats->leader_uid == parent->getUID()) && parent->getRace() == LICH_ICE)
|| (parent->getRace() == LICH_ICE) && !strncmp(hitstats->name, "corrupted automaton", 19)
)
)
{
reflection = 3;
}
if ( !reflection )
{
reflection = hit.entity->getReflection();
}
if ( my->actmagicCastByTinkerTrap == 1 )
{
reflection = 0;
}
if ( reflection == 3 && hitstats->shield && hitstats->shield->type == MIRROR_SHIELD && hitstats->defending )
{
if ( my->actmagicIsVertical == MAGIC_ISVERTICAL_Z )
{
reflection = 0;
}
// calculate facing angle to projectile, need to be facing projectile to reflect.
else if ( player >= 0 && players[player] && players[player]->entity )
{
real_t yawDiff = my->yawDifferenceFromPlayer(player);
if ( yawDiff < (6 * PI / 5) )
{
reflection = 0;
}
else
{
reflection = 3;
if ( parent && (parent->behavior == &actMonster || parent->behavior == &actPlayer) )
{
my->actmagicMirrorReflected = 1;
my->actmagicMirrorReflectedCaster = parent->getUID();
}
}
}
}
}
if ( reflection )
{
spell_t* spellIsReflectingMagic = hit.entity->getActiveMagicEffect(SPELL_REFLECT_MAGIC);
playSoundEntity(hit.entity, 166, 128);
if ( hit.entity )
{
if ( hit.entity->behavior == &actPlayer )
{
if ( !strcmp(element->name, spellElement_charmMonster.name) )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 0, 255, 0);
messagePlayerMonsterEvent(parent->skill[2], color, *hitstats, language[378], language[377], MSG_COMBAT);
}
if ( !spellIsReflectingMagic )
{
messagePlayer(player, language[379]);
}
else
{
messagePlayer(player, language[2475]);
}
}
}
if ( parent )
{
if ( parent->behavior == &actPlayer )
{
messagePlayer(parent->skill[2], language[379]);
}
}
if ( hit.side == HORIZONTAL )
{
my->vel_x *= -1;
my->yaw = atan2(my->vel_y, my->vel_x);
}
else if ( hit.side == VERTICAL )
{
my->vel_y *= -1;
my->yaw = atan2(my->vel_y, my->vel_x);
}
else if ( hit.side == 0 )
{
my->vel_x *= -1;
my->vel_y *= -1;
my->yaw = atan2(my->vel_y, my->vel_x);
}
if ( hit.entity )
{
if ( (parent && parent->behavior == &actMagicTrapCeiling) || my->actmagicIsVertical == MAGIC_ISVERTICAL_Z )
{
// this missile came from the ceiling, let's redirect it..
my->x = hit.entity->x + cos(hit.entity->yaw);
my->y = hit.entity->y + sin(hit.entity->yaw);
my->yaw = hit.entity->yaw;
my->z = -1;
my->vel_x = 4 * cos(hit.entity->yaw);
my->vel_y = 4 * sin(hit.entity->yaw);
my->vel_z = 0;
my->pitch = 0;
}
my->parent = hit.entity->getUID();
}
// Only degrade the equipment if Friendly Fire is ON or if it is (OFF && target is an enemy)
bool bShouldEquipmentDegrade = false;
if ( (svFlags & SV_FLAG_FRIENDLYFIRE) )
{
// Friendly Fire is ON, equipment should always degrade, as hit will register
bShouldEquipmentDegrade = true;
}
else
{
// Friendly Fire is OFF, is the target an enemy?
if ( parent != nullptr && (parent->checkFriend(hit.entity)) == false )
{
// Target is an enemy, equipment should degrade
bShouldEquipmentDegrade = true;
}
}
if ( bShouldEquipmentDegrade )
{
// Reflection of 3 does not degrade equipment
if ( rand() % 2 == 0 && hitstats && reflection < 3 )
{
// set armornum to the relevant equipment slot to send to clients
int armornum = 5 + reflection;
if ( (player >= 0 && players[player]->isLocalPlayer()) || player < 0 )
{
if ( reflection == 1 )
{
if ( hitstats->cloak->count > 1 )
{
newItem(hitstats->cloak->type, hitstats->cloak->status, hitstats->cloak->beatitude, hitstats->cloak->count - 1, hitstats->cloak->appearance, hitstats->cloak->identified, &hitstats->inventory);
}
}
else if ( reflection == 2 )
{
if ( hitstats->amulet->count > 1 )
{
newItem(hitstats->amulet->type, hitstats->amulet->status, hitstats->amulet->beatitude, hitstats->amulet->count - 1, hitstats->amulet->appearance, hitstats->amulet->identified, &hitstats->inventory);
}
}
else if ( reflection == -1 )
{
if ( hitstats->shield->count > 1 )
{
newItem(hitstats->shield->type, hitstats->shield->status, hitstats->shield->beatitude, hitstats->shield->count - 1, hitstats->shield->appearance, hitstats->shield->identified, &hitstats->inventory);
}
}
}
if ( reflection == 1 )
{
hitstats->cloak->count = 1;
hitstats->cloak->status = static_cast<Status>(std::max(static_cast<int>(BROKEN), hitstats->cloak->status - 1));
if ( hitstats->cloak->status != BROKEN )
{
messagePlayer(player, language[380]);
}
else
{
messagePlayer(player, language[381]);
playSoundEntity(hit.entity, 76, 64);
}
}
else if ( reflection == 2 )
{
hitstats->amulet->count = 1;
hitstats->amulet->status = static_cast<Status>(std::max(static_cast<int>(BROKEN), hitstats->amulet->status - 1));
if ( hitstats->amulet->status != BROKEN )
{
messagePlayer(player, language[382]);
}
else
{
messagePlayer(player, language[383]);
playSoundEntity(hit.entity, 76, 64);
}
}
else if ( reflection == -1 )
{
hitstats->shield->count = 1;
hitstats->shield->status = static_cast<Status>(std::max(static_cast<int>(BROKEN), hitstats->shield->status - 1));
if ( hitstats->shield->status != BROKEN )
{
messagePlayer(player, language[384]);
}
else
{
messagePlayer(player, language[385]);
playSoundEntity(hit.entity, 76, 64);
}
}
if ( player > 0 && multiplayer == SERVER )
{
strcpy((char*)net_packet->data, "ARMR");
net_packet->data[4] = armornum;
if ( reflection == 1 )
{
net_packet->data[5] = hitstats->cloak->status;
}
else if ( reflection == 2 )
{
net_packet->data[5] = hitstats->amulet->status;
}
else
{
net_packet->data[5] = hitstats->shield->status;
}
net_packet->address.host = net_clients[player - 1].host;
net_packet->address.port = net_clients[player - 1].port;
net_packet->len = 6;
sendPacketSafe(net_sock, -1, net_packet, player - 1);
}
}
}
if ( spellIsReflectingMagic )
{
int spellCost = getCostOfSpell(spell);
bool unsustain = false;
if ( spellCost >= hit.entity->getMP() ) //Unsustain the spell if expended all mana.
{
unsustain = true;
}
hit.entity->drainMP(spellCost);
spawnMagicEffectParticles(hit.entity->x, hit.entity->y, hit.entity->z / 2, 174);
playSoundEntity(hit.entity, 166, 128); //TODO: Custom sound effect?
if ( unsustain )
{
spellIsReflectingMagic->sustain = false;
if ( hitstats )
{
hit.entity->setEffect(EFF_MAGICREFLECT, false, 0, true);
messagePlayer(player, language[2476]);
}
}
}
return;
}
// Test for Friendly Fire, if Friendly Fire is OFF, delete the missile
if ( !(svFlags & SV_FLAG_FRIENDLYFIRE) )
{
if ( !strcmp(element->name, spellElement_telePull.name)
|| !strcmp(element->name, spellElement_shadowTag.name)
|| my->actmagicTinkerTrapFriendlyFire == 1 )
{
// these spells can hit allies no penalty.
}
else if ( parent && parent->checkFriend(hit.entity) )
{
my->removeLightField();
list_RemoveNode(my->mynode);
return;
}
}
// Alerting the hit Entity
if ( hit.entity )
{
// alert the hit entity if it was a monster
if ( hit.entity->behavior == &actMonster && parent != nullptr )
{
if ( parent->behavior == &actMagicTrap || parent->behavior == &actMagicTrapCeiling )
{
if ( parent->behavior == &actMagicTrap )
{
if ( static_cast<int>(parent->y / 16) == static_cast<int>(hit.entity->y / 16) )
{
// avoid y axis.
int direction = 1;
if ( rand() % 2 == 0 )
{
direction = -1;
}
if ( hit.entity->monsterSetPathToLocation(hit.entity->x / 16, (hit.entity->y / 16) + 1 * direction, 0) )
{
hit.entity->monsterState = MONSTER_STATE_HUNT;
serverUpdateEntitySkill(hit.entity, 0);
}
else if ( hit.entity->monsterSetPathToLocation(hit.entity->x / 16, (hit.entity->y / 16) - 1 * direction, 0) )
{
hit.entity->monsterState = MONSTER_STATE_HUNT;
serverUpdateEntitySkill(hit.entity, 0);
}
else
{
monsterMoveAside(hit.entity, hit.entity);
}
}
else if ( static_cast<int>(parent->x / 16) == static_cast<int>(hit.entity->x / 16) )
{
int direction = 1;
if ( rand() % 2 == 0 )
{
direction = -1;
}
// avoid x axis.
if ( hit.entity->monsterSetPathToLocation((hit.entity->x / 16) + 1 * direction, hit.entity->y / 16, 0) )
{
hit.entity->monsterState = MONSTER_STATE_HUNT;
serverUpdateEntitySkill(hit.entity, 0);
}
else if ( hit.entity->monsterSetPathToLocation((hit.entity->x / 16) - 1 * direction, hit.entity->y / 16, 0) )
{
hit.entity->monsterState = MONSTER_STATE_HUNT;
serverUpdateEntitySkill(hit.entity, 0);
}
else
{
monsterMoveAside(hit.entity, hit.entity);
}
}
else
{
monsterMoveAside(hit.entity, hit.entity);
}
}
else
{
monsterMoveAside(hit.entity, hit.entity);
}
}
else
{
bool alertTarget = true;
bool alertAllies = true;
if ( parent->behavior == &actMonster && parent->monsterAllyIndex != -1 )
{
if ( hit.entity->behavior == &actMonster && hit.entity->monsterAllyIndex != -1 )
{
// if a player ally + hit another ally, don't aggro back
alertTarget = false;
}
}
if ( !strcmp(element->name, spellElement_telePull.name) || !strcmp(element->name, spellElement_shadowTag.name) )
{
alertTarget = false;
alertAllies = false;
}
if ( my->actmagicCastByTinkerTrap == 1 )
{
if ( entityDist(hit.entity, parent) > TOUCHRANGE )
{
// don't alert if bomb thrower far away.
alertTarget = false;
alertAllies = false;
}
}
if ( alertTarget && hit.entity->monsterState != MONSTER_STATE_ATTACK && (hitstats->type < LICH || hitstats->type >= SHOPKEEPER) )
{
hit.entity->monsterAcquireAttackTarget(*parent, MONSTER_STATE_PATH, true);
}
if ( parent->behavior == &actPlayer || parent->monsterAllyIndex != -1 )
{
if ( hit.entity->behavior == &actPlayer || (hit.entity->behavior == &actMonster && hit.entity->monsterAllyIndex != -1) )
{
// if a player ally + hit another ally or player, don't alert other allies.
alertAllies = false;
}
}
// alert other monsters too
Entity* ohitentity = hit.entity;
for ( node = map.creatures->first; node != nullptr && alertAllies; node = node->next )
{
entity = (Entity*)node->element;
if ( entity->behavior == &actMonster && entity != ohitentity )
{
Stat* buddystats = entity->getStats();
if ( buddystats != nullptr )
{
if ( hit.entity && hit.entity->checkFriend(entity) ) //TODO: hit.entity->checkFriend() without first checking if it's NULL crashes because hit.entity turns to NULL somewhere along the line. It looks like ohitentity preserves that value though, so....uh...ya, I don't know.
{
if ( entity->monsterState == MONSTER_STATE_WAIT )
{
tangent = atan2( entity->y - ohitentity->y, entity->x - ohitentity->x );
lineTrace(ohitentity, ohitentity->x, ohitentity->y, tangent, 1024, 0, false);
if ( hit.entity == entity )
{
entity->monsterAcquireAttackTarget(*parent, MONSTER_STATE_PATH);
}
}
}
}
}
}
hit.entity = ohitentity;
}
}
}
// check for magic resistance...
// resistance stacks diminishingly
//TODO: EFFECTS[EFF_MAGICRESIST]
int resistance = 0;
if ( hit.entity )
{
resistance = hit.entity->getMagicResistance();
}
if ( resistance > 0 )
{
if ( parent )
{
if ( parent->behavior == &actPlayer )
{
messagePlayer(parent->skill[2], language[386]);
}
}
}
real_t spellbookDamageBonus = (my->actmagicSpellbookBonus / 100.f);
if ( my->actmagicCastByMagicstaff == 0 && my->actmagicCastByTinkerTrap == 0 )
{
spellbookDamageBonus += getBonusFromCasterOfSpellElement(parent, element);
}
if (!strcmp(element->name, spellElement_force.name))
{
if (hit.entity)
{
if (hit.entity->behavior == &actMonster || hit.entity->behavior == &actPlayer)
{
Entity* parent = uidToEntity(my->parent);
playSoundEntity(hit.entity, 28, 128);
int damage = element->damage;
damage += (spellbookDamageBonus * damage);
//damage += ((element->mana - element->base_mana) / static_cast<double>(element->overload_multiplier)) * element->damage;
damage *= hit.entity->getDamageTableMultiplier(*hitstats, DAMAGE_TABLE_MAGIC);
damage /= (1 + (int)resistance);
hit.entity->modHP(-damage);
for (i = 0; i < damage; i += 2) //Spawn a gib for every two points of damage.
{
Entity* gib = spawnGib(hit.entity);
serverSpawnGibForClient(gib);
}
if (parent)
{
parent->killedByMonsterObituary(hit.entity);
}
// update enemy bar for attacker
if ( !strcmp(hitstats->name, "") )
{
if ( hitstats->type < KOBOLD ) //Original monster count
{
updateEnemyBar(parent, hit.entity, language[90 + hitstats->type], hitstats->HP, hitstats->MAXHP);
}
else if ( hitstats->type >= KOBOLD ) //New monsters
{
updateEnemyBar(parent, hit.entity, language[2000 + (hitstats->type - KOBOLD)], hitstats->HP, hitstats->MAXHP);
}
}
else
{
updateEnemyBar(parent, hit.entity, hitstats->name, hitstats->HP, hitstats->MAXHP);
}
if ( hitstats->HP <= 0 && parent)
{
parent->awardXP( hit.entity, true, true );
}
}
else if (hit.entity->behavior == &actDoor)
{
int damage = element->damage;
damage += (spellbookDamageBonus * damage);
damage /= (1 + (int)resistance);
hit.entity->doorHandleDamageMagic(damage, *my, parent);
my->removeLightField();
list_RemoveNode(my->mynode);
return;
}
else if ( hit.entity->behavior == &actChest )
{
int damage = element->damage;
damage += (spellbookDamageBonus * damage);
damage /= (1 + (int)resistance);
hit.entity->chestHandleDamageMagic(damage, *my, parent);
my->removeLightField();
list_RemoveNode(my->mynode);
return;
}
else if (hit.entity->behavior == &actFurniture )
{
int damage = element->damage;
damage += (spellbookDamageBonus * damage);
damage /= (1 + (int)resistance);
hit.entity->furnitureHealth -= damage;
if ( hit.entity->furnitureHealth < 0 )
{
if ( parent )
{
if ( parent->behavior == &actPlayer )
{
switch ( hit.entity->furnitureType )
{
case FURNITURE_CHAIR:
messagePlayer(parent->skill[2], language[388]);
updateEnemyBar(parent, hit.entity, language[677], hit.entity->furnitureHealth, hit.entity->furnitureMaxHealth);
break;
case FURNITURE_TABLE:
messagePlayer(parent->skill[2], language[389]);
updateEnemyBar(parent, hit.entity, language[676], hit.entity->furnitureHealth, hit.entity->furnitureMaxHealth);
break;
case FURNITURE_BED:
messagePlayer(parent->skill[2], language[2508], language[2505]);
updateEnemyBar(parent, hit.entity, language[2505], hit.entity->furnitureHealth, hit.entity->furnitureMaxHealth);
break;
case FURNITURE_BUNKBED:
messagePlayer(parent->skill[2], language[2508], language[2506]);
updateEnemyBar(parent, hit.entity, language[2506], hit.entity->furnitureHealth, hit.entity->furnitureMaxHealth);
break;
case FURNITURE_PODIUM:
messagePlayer(parent->skill[2], language[2508], language[2507]);
updateEnemyBar(parent, hit.entity, language[2507], hit.entity->furnitureHealth, hit.entity->furnitureMaxHealth);
break;
default:
break;
}
}
}
}
playSoundEntity(hit.entity, 28, 128);
}
}
}
else if (!strcmp(element->name, spellElement_magicmissile.name))
{
spawnExplosion(my->x, my->y, my->z);
if (hit.entity)
{
if (hit.entity->behavior == &actMonster || hit.entity->behavior == &actPlayer)
{
Entity* parent = uidToEntity(my->parent);
playSoundEntity(hit.entity, 28, 128);
int damage = element->damage;
damage += (spellbookDamageBonus * damage);
//damage += ((element->mana - element->base_mana) / static_cast<double>(element->overload_multiplier)) * element->damage;
if ( my->actmagicIsOrbiting == 2 )
{
spawnExplosion(my->x, my->y, my->z);
if ( parent && my->actmagicOrbitCastFromSpell == 1 )
{
// cast through amplify magic effect
damage /= 2;
}
damage = damage - rand() % ((damage / 8) + 1);
}
damage *= hit.entity->getDamageTableMultiplier(*hitstats, DAMAGE_TABLE_MAGIC);
damage /= (1 + (int)resistance);
hit.entity->modHP(-damage);
for (i = 0; i < damage; i += 2) //Spawn a gib for every two points of damage.
{
Entity* gib = spawnGib(hit.entity);
serverSpawnGibForClient(gib);
}
// write the obituary
if ( parent )
{
parent->killedByMonsterObituary(hit.entity);
}
// update enemy bar for attacker
if ( !strcmp(hitstats->name, "") )
{
if ( hitstats->type < KOBOLD ) //Original monster count
{
updateEnemyBar(parent, hit.entity, language[90 + hitstats->type], hitstats->HP, hitstats->MAXHP);
}
else if ( hitstats->type >= KOBOLD ) //New monsters
{
updateEnemyBar(parent, hit.entity, language[2000 + (hitstats->type - KOBOLD)], hitstats->HP, hitstats->MAXHP);
}
}
else
{
updateEnemyBar(parent, hit.entity, hitstats->name, hitstats->HP, hitstats->MAXHP);
}
if ( hitstats->HP <= 0 && parent)
{
parent->awardXP( hit.entity, true, true );
}
}
else if ( hit.entity->behavior == &actDoor )
{
int damage = element->damage;
damage += (spellbookDamageBonus * damage);
//damage += ((element->mana - element->base_mana) / static_cast<double>(element->overload_multiplier)) * element->damage;
damage /= (1 + (int)resistance);
hit.entity->doorHandleDamageMagic(damage, *my, parent);
if ( my->actmagicProjectileArc > 0 )
{
Entity* caster = uidToEntity(spell->caster);
spawnMagicTower(caster, my->x, my->y, spell->ID, nullptr);
}
if ( !(my->actmagicIsOrbiting == 2) )
{
my->removeLightField();
list_RemoveNode(my->mynode);
}
else
{
spawnExplosion(my->x, my->y, my->z);
}
return;
}
else if ( hit.entity->behavior == &actChest )
{
int damage = element->damage;
damage += (spellbookDamageBonus * damage);
damage /= (1 + (int)resistance);
hit.entity->chestHandleDamageMagic(damage, *my, parent);
if ( my->actmagicProjectileArc > 0 )
{
Entity* caster = uidToEntity(spell->caster);
spawnMagicTower(caster, my->x, my->y, spell->ID, nullptr);
}
if ( !(my->actmagicIsOrbiting == 2) )
{
my->removeLightField();
list_RemoveNode(my->mynode);
}
else
{
spawnExplosion(my->x, my->y, my->z);
}
return;
}
else if (hit.entity->behavior == &actFurniture )
{
int damage = element->damage;
damage += (spellbookDamageBonus * damage);
damage /= (1 + (int)resistance);
hit.entity->furnitureHealth -= damage;
if ( hit.entity->furnitureHealth < 0 )
{
if ( parent )
{
if ( parent->behavior == &actPlayer )
{
switch ( hit.entity->furnitureType )
{
case FURNITURE_CHAIR:
messagePlayer(parent->skill[2], language[388]);
updateEnemyBar(parent, hit.entity, language[677], hit.entity->furnitureHealth, hit.entity->furnitureMaxHealth);
break;
case FURNITURE_TABLE:
messagePlayer(parent->skill[2], language[389]);
updateEnemyBar(parent, hit.entity, language[676], hit.entity->furnitureHealth, hit.entity->furnitureMaxHealth);
break;
case FURNITURE_BED:
messagePlayer(parent->skill[2], language[2508], language[2505]);
updateEnemyBar(parent, hit.entity, language[2505], hit.entity->furnitureHealth, hit.entity->furnitureMaxHealth);
break;
case FURNITURE_BUNKBED:
messagePlayer(parent->skill[2], language[2508], language[2506]);
updateEnemyBar(parent, hit.entity, language[2506], hit.entity->furnitureHealth, hit.entity->furnitureMaxHealth);
break;
case FURNITURE_PODIUM:
messagePlayer(parent->skill[2], language[2508], language[2507]);
updateEnemyBar(parent, hit.entity, language[2507], hit.entity->furnitureHealth, hit.entity->furnitureMaxHealth);
break;
default:
break;
}
}
}
}
playSoundEntity(hit.entity, 28, 128);
if ( my->actmagicProjectileArc > 0 )
{
Entity* caster = uidToEntity(spell->caster);
spawnMagicTower(caster, my->x, my->y, spell->ID, nullptr);
}
if ( !(my->actmagicIsOrbiting == 2) )
{
my->removeLightField();
list_RemoveNode(my->mynode);
}
else
{
spawnExplosion(my->x, my->y, my->z);
}
return;
}
}
}
else if (!strcmp(element->name, spellElement_fire.name))
{
if ( !(my->actmagicIsOrbiting == 2) )
{
spawnExplosion(my->x, my->y, my->z);
}
if (hit.entity)
{
// Attempt to set the Entity on fire
hit.entity->SetEntityOnFire();
if (hit.entity->behavior == &actMonster || hit.entity->behavior == &actPlayer)
{
//playSoundEntity(my, 153, 64);
playSoundEntity(hit.entity, 28, 128);
//TODO: Apply fire resistances/weaknesses.
int damage = element->damage;
damage += (spellbookDamageBonus * damage);
//damage += ((element->mana - element->base_mana) / static_cast<double>(element->overload_multiplier)) * element->damage;
if ( my->actmagicIsOrbiting == 2 )
{
spawnExplosion(my->x, my->y, my->z);
if ( parent && my->actmagicOrbitCastFromSpell == 0 )
{
if ( parent->behavior == &actParticleDot )
{
damage = parent->skill[1];
}
else if ( parent->behavior == &actPlayer )
{
Stat* playerStats = parent->getStats();
if ( playerStats )
{
int skillLVL = playerStats->PROFICIENCIES[PRO_ALCHEMY] / 20;
damage = (14 + skillLVL * 1.5);
}
}
else
{
damage = 14;
}
}
else if ( parent && my->actmagicOrbitCastFromSpell == 1 )
{
// cast through amplify magic effect
damage /= 2;
}
else
{
damage = 14;
}
damage = damage - rand() % ((damage / 8) + 1);
}
damage *= hit.entity->getDamageTableMultiplier(*hitstats, DAMAGE_TABLE_MAGIC);
if ( parent )
{
Stat* casterStats = parent->getStats();
if ( casterStats && casterStats->type == LICH_FIRE && parent->monsterLichAllyStatus == LICH_ALLY_DEAD )
{
damage *= 2;
}
}
int oldHP = hitstats->HP;
damage /= (1 + (int)resistance);
hit.entity->modHP(-damage);
//for (i = 0; i < damage; i += 2) { //Spawn a gib for every two points of damage.
Entity* gib = spawnGib(hit.entity);
serverSpawnGibForClient(gib);
//}
// write the obituary
if ( parent )
{
if ( my->actmagicIsOrbiting == 2
&& parent->behavior == &actParticleDot
&& parent->skill[1] > 0 )
{
if ( hitstats && hitstats->obituary && !strcmp(hitstats->obituary, language[3898]) )
{
// was caused by a flaming boulder.
hit.entity->setObituary(language[3898]);
}
else
{
// blew the brew (alchemy)
hit.entity->setObituary(language[3350]);
}
}
else
{
parent->killedByMonsterObituary(hit.entity);
}
}
if ( hitstats )
{
hitstats->burningInflictedBy = static_cast<Sint32>(my->parent);
}
// update enemy bar for attacker
if ( !strcmp(hitstats->name, "") )
{
if ( hitstats->type < KOBOLD ) //Original monster count
{
updateEnemyBar(parent, hit.entity, language[90 + hitstats->type], hitstats->HP, hitstats->MAXHP);
}
else if ( hitstats->type >= KOBOLD ) //New monsters
{
updateEnemyBar(parent, hit.entity, language[2000 + (hitstats->type - KOBOLD)], hitstats->HP, hitstats->MAXHP);
}
}
else
{
updateEnemyBar(parent, hit.entity, hitstats->name, hitstats->HP, hitstats->MAXHP);
}
if ( oldHP > 0 && hitstats->HP <= 0 )
{
if ( parent )
{
if ( my->actmagicIsOrbiting == 2 && my->actmagicOrbitCastFromSpell == 0 && parent->behavior == &actPlayer )
{
if ( hitstats->type == LICH || hitstats->type == LICH_ICE || hitstats->type == LICH_FIRE )
{
if ( client_classes[parent->skill[2]] == CLASS_BREWER )
{
steamAchievementClient(parent->skill[2], "BARONY_ACH_SECRET_WEAPON");
}
}
steamStatisticUpdateClient(parent->skill[2], STEAM_STAT_BOMBARDIER, STEAM_STAT_INT, 1);
}
if ( my->actmagicCastByTinkerTrap == 1 && parent->behavior == &actPlayer && hitstats->type == MINOTAUR )
{
steamAchievementClient(parent->skill[2], "BARONY_ACH_TIME_TO_PLAN");
}
parent->awardXP( hit.entity, true, true );
}
else
{
if ( achievementObserver.checkUidIsFromPlayer(my->parent) >= 0 )
{
steamAchievementClient(achievementObserver.checkUidIsFromPlayer(my->parent), "BARONY_ACH_TAKING_WITH");
}
}
}
}
else if (hit.entity->behavior == &actDoor)
{
int damage = element->damage;
damage += (spellbookDamageBonus * damage);
damage /= (1 + (int)resistance);
hit.entity->doorHandleDamageMagic(damage, *my, parent);
if ( my->actmagicProjectileArc > 0 )
{
Entity* caster = uidToEntity(spell->caster);
spawnMagicTower(caster, my->x, my->y, spell->ID, nullptr);
}
if ( !(my->actmagicIsOrbiting == 2) )
{
my->removeLightField();
list_RemoveNode(my->mynode);
}
else
{
spawnExplosion(my->x, my->y, my->z);
}
return;
}
else if (hit.entity->behavior == &actChest)
{
int damage = element->damage;
damage += (spellbookDamageBonus * damage);
damage /= (1+(int)resistance);
hit.entity->chestHandleDamageMagic(damage, *my, parent);
if ( my->actmagicProjectileArc > 0 )
{
Entity* caster = uidToEntity(spell->caster);
spawnMagicTower(caster, my->x, my->y, spell->ID, nullptr);
}
if ( !(my->actmagicIsOrbiting == 2) )
{
my->removeLightField();
list_RemoveNode(my->mynode);
}
else
{
spawnExplosion(my->x, my->y, my->z);
}
return;
}
else if (hit.entity->behavior == &actFurniture )
{
int damage = element->damage;
damage += (spellbookDamageBonus * damage);
damage /= (1 + (int)resistance);
hit.entity->furnitureHealth -= damage;
if ( hit.entity->furnitureHealth < 0 )
{
if ( parent )
{
if ( parent->behavior == &actPlayer )
{
switch ( hit.entity->furnitureType )
{
case FURNITURE_CHAIR:
messagePlayer(parent->skill[2], language[388]);
updateEnemyBar(parent, hit.entity, language[677], hit.entity->furnitureHealth, hit.entity->furnitureMaxHealth);
break;
case FURNITURE_TABLE:
messagePlayer(parent->skill[2], language[389]);
updateEnemyBar(parent, hit.entity, language[676], hit.entity->furnitureHealth, hit.entity->furnitureMaxHealth);
break;
case FURNITURE_BED:
messagePlayer(parent->skill[2], language[2508], language[2505]);
updateEnemyBar(parent, hit.entity, language[2505], hit.entity->furnitureHealth, hit.entity->furnitureMaxHealth);
break;
case FURNITURE_BUNKBED:
messagePlayer(parent->skill[2], language[2508], language[2506]);
updateEnemyBar(parent, hit.entity, language[2506], hit.entity->furnitureHealth, hit.entity->furnitureMaxHealth);
break;
case FURNITURE_PODIUM:
messagePlayer(parent->skill[2], language[2508], language[2507]);
updateEnemyBar(parent, hit.entity, language[2507], hit.entity->furnitureHealth, hit.entity->furnitureMaxHealth);
break;
default:
break;
}
}
}
}
playSoundEntity(hit.entity, 28, 128);
if ( my->actmagicProjectileArc > 0 )
{
Entity* caster = uidToEntity(spell->caster);
spawnMagicTower(caster, my->x, my->y, spell->ID, nullptr);
}
if ( !(my->actmagicIsOrbiting == 2) )
{
my->removeLightField();
list_RemoveNode(my->mynode);
}
else
{
spawnExplosion(my->x, my->y, my->z);
}
return;
}
}
}
else if (!strcmp(element->name, spellElement_confuse.name))
{
if (hit.entity)
{
if (hit.entity->behavior == &actMonster || hit.entity->behavior == &actPlayer)
{
playSoundEntity(hit.entity, 174, 64);
hitstats->EFFECTS[EFF_CONFUSED] = true;
hitstats->EFFECTS_TIMERS[EFF_CONFUSED] = (element->duration * (((element->mana) / static_cast<double>(element->base_mana)) * element->overload_multiplier));
hitstats->EFFECTS_TIMERS[EFF_CONFUSED] /= (1 + (int)resistance);
// If the Entity hit is a Player, update their status to be Slowed
if ( hit.entity->behavior == &actPlayer )
{
serverUpdateEffects(hit.entity->skill[2]);
}
hit.entity->skill[1] = 0; //Remove the monster's target.
if ( parent )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 0, 255, 0);
if ( parent->behavior == &actPlayer )
{
messagePlayerMonsterEvent(parent->skill[2], color, *hitstats, language[391], language[390], MSG_COMBAT);
}
}
Uint32 color = SDL_MapRGB(mainsurface->format, 255, 0, 0);
if ( player >= 0 )
{
messagePlayerColor(player, color, language[392]);
}
spawnMagicEffectParticles(hit.entity->x, hit.entity->y, hit.entity->z, my->sprite);
}
}
}
else if (!strcmp(element->name, spellElement_cold.name))
{
playSoundEntity(my, 197, 128);
if (hit.entity)
{
if (hit.entity->behavior == &actMonster || hit.entity->behavior == &actPlayer)
{
playSoundEntity(hit.entity, 28, 128);
hitstats->EFFECTS[EFF_SLOW] = true;
hitstats->EFFECTS_TIMERS[EFF_SLOW] = (element->duration * (((element->mana) / static_cast<double>(element->base_mana)) * element->overload_multiplier));
hitstats->EFFECTS_TIMERS[EFF_SLOW] /= (1 + (int)resistance);
// If the Entity hit is a Player, update their status to be Slowed
if ( hit.entity->behavior == &actPlayer )
{
serverUpdateEffects(hit.entity->skill[2]);
}
int damage = element->damage;
damage += (spellbookDamageBonus * damage);
//messagePlayer(0, "damage: %d", damage);
if ( my->actmagicIsOrbiting == 2 )
{
if ( parent && my->actmagicOrbitCastFromSpell == 0 )
{
if ( parent->behavior == &actParticleDot )
{
damage = parent->skill[1];
}
else if ( parent->behavior == &actPlayer )
{
Stat* playerStats = parent->getStats();
if ( playerStats )
{
int skillLVL = playerStats->PROFICIENCIES[PRO_ALCHEMY] / 20;
damage = (18 + skillLVL * 1.5);
}
}
else
{
damage = 18;
}
}
else if ( parent && my->actmagicOrbitCastFromSpell == 1 )
{
// cast through amplify magic effect
damage /= 2;
}
else
{
damage = 18;
}
damage = damage - rand() % ((damage / 8) + 1);
}
//damage += ((element->mana - element->base_mana) / static_cast<double>(element->overload_multiplier)) * element->damage;
int oldHP = hitstats->HP;
damage *= hit.entity->getDamageTableMultiplier(*hitstats, DAMAGE_TABLE_MAGIC);
damage /= (1 + (int)resistance);
hit.entity->modHP(-damage);
Entity* gib = spawnGib(hit.entity);
serverSpawnGibForClient(gib);
// write the obituary
if ( parent )
{
parent->killedByMonsterObituary(hit.entity);
}
// update enemy bar for attacker
if ( !strcmp(hitstats->name, "") )
{
if ( hitstats->type < KOBOLD ) //Original monster count
{
updateEnemyBar(parent, hit.entity, language[90 + hitstats->type], hitstats->HP, hitstats->MAXHP);
}
else if ( hitstats->type >= KOBOLD ) //New monsters
{
updateEnemyBar(parent, hit.entity, language[2000 + (hitstats->type - KOBOLD)], hitstats->HP, hitstats->MAXHP);
}
}
else
{
updateEnemyBar(parent, hit.entity, hitstats->name, hitstats->HP, hitstats->MAXHP);
}
if ( parent )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 0, 255, 0);
if ( parent->behavior == &actPlayer )
{
messagePlayerMonsterEvent(parent->skill[2], color, *hitstats, language[394], language[393], MSG_COMBAT);
}
}
Uint32 color = SDL_MapRGB(mainsurface->format, 255, 0, 0);
if ( player >= 0 )
{
messagePlayerColor(player, color, language[395]);
}
spawnMagicEffectParticles(hit.entity->x, hit.entity->y, hit.entity->z, my->sprite);
if ( oldHP > 0 && hitstats->HP <= 0 )
{
if ( parent )
{
parent->awardXP(hit.entity, true, true);
if ( my->actmagicIsOrbiting == 2 && my->actmagicOrbitCastFromSpell == 0 && parent->behavior == &actPlayer )
{
if ( hitstats->type == LICH || hitstats->type == LICH_ICE || hitstats->type == LICH_FIRE )
{
if ( client_classes[parent->skill[2]] == CLASS_BREWER )
{
steamAchievementClient(parent->skill[2], "BARONY_ACH_SECRET_WEAPON");
}
}
steamStatisticUpdateClient(parent->skill[2], STEAM_STAT_BOMBARDIER, STEAM_STAT_INT, 1);
}
if ( my->actmagicCastByTinkerTrap == 1 && parent->behavior == &actPlayer && hitstats->type == MINOTAUR )
{
steamAchievementClient(parent->skill[2], "BARONY_ACH_TIME_TO_PLAN");
}
}
else
{
if ( achievementObserver.checkUidIsFromPlayer(my->parent) >= 0 )
{
steamAchievementClient(achievementObserver.checkUidIsFromPlayer(my->parent), "BARONY_ACH_TAKING_WITH");
}
}
}
}
}
}
else if (!strcmp(element->name, spellElement_slow.name))
{
if (hit.entity)
{
if (hit.entity->behavior == &actMonster || hit.entity->behavior == &actPlayer)
{
playSoundEntity(hit.entity, 396 + rand() % 3, 64);
hitstats->EFFECTS[EFF_SLOW] = true;
hitstats->EFFECTS_TIMERS[EFF_SLOW] = (element->duration * (((element->mana) / static_cast<double>(element->base_mana)) * element->overload_multiplier));
hitstats->EFFECTS_TIMERS[EFF_SLOW] /= (1 + (int)resistance);
// If the Entity hit is a Player, update their status to be Slowed
if ( hit.entity->behavior == &actPlayer )
{
serverUpdateEffects(hit.entity->skill[2]);
}
// update enemy bar for attacker
if ( parent )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 0, 255, 0);
if ( parent->behavior == &actPlayer )
{
messagePlayerMonsterEvent(parent->skill[2], color, *hitstats, language[394], language[393], MSG_COMBAT);
}
}
Uint32 color = SDL_MapRGB(mainsurface->format, 255, 0, 0);
if ( player >= 0 )
{
messagePlayerColor(player, color, language[395]);
}
spawnMagicEffectParticles(hit.entity->x, hit.entity->y, hit.entity->z, my->sprite);
}
}
}
else if (!strcmp(element->name, spellElement_sleep.name))
{
if (hit.entity)
{
if (hit.entity->behavior == &actMonster || hit.entity->behavior == &actPlayer)
{
playSoundEntity(hit.entity, 174, 64);
int effectDuration = 0;
if ( parent && parent->behavior == &actMagicTrapCeiling )
{
effectDuration = 200 + rand() % 150; // 4 seconds + 0 to 3 seconds.
}
else
{
effectDuration = 600 + rand() % 300; // 12 seconds + 0 to 6 seconds.
if ( hitstats )
{
effectDuration = std::max(0, effectDuration - ((hitstats->CON % 10) * 50)); // reduce 1 sec every 10 CON.
}
}
effectDuration /= (1 + (int)resistance);
bool magicTrapReapplySleep = true;
if ( parent && (parent->behavior == &actMagicTrap || parent->behavior == &actMagicTrapCeiling) )
{
if ( hitstats && hitstats->EFFECTS[EFF_ASLEEP] )
{
// check to see if we're reapplying the sleep effect.
int preventSleepRoll = rand() % 4 - resistance;
if ( hit.entity->behavior == &actPlayer || (preventSleepRoll <= 0) )
{
magicTrapReapplySleep = false;
//messagePlayer(0, "Target already asleep!");
}
}
}
if ( magicTrapReapplySleep )
{
if ( hit.entity->setEffect(EFF_ASLEEP, true, effectDuration, false) )
{
hitstats->OLDHP = hitstats->HP;
if ( hit.entity->behavior == &actPlayer )
{
serverUpdateEffects(hit.entity->skill[2]);
Uint32 color = SDL_MapRGB(mainsurface->format, 255, 0, 0);
messagePlayerColor(hit.entity->skill[2], color, language[396]);
}
if ( parent )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 0, 255, 0);
if ( parent->behavior == &actPlayer )
{
messagePlayerMonsterEvent(parent->skill[2], color, *hitstats, language[398], language[397], MSG_COMBAT);
}
}
}
else
{
if ( parent )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 0, 255, 0);
if ( parent->behavior == &actPlayer )
{
messagePlayerMonsterEvent(parent->skill[2], color, *hitstats, language[2905], language[2906], MSG_COMBAT);
}
}
}
}
spawnMagicEffectParticles(hit.entity->x, hit.entity->y, hit.entity->z, my->sprite);
}
}
}
else if (!strcmp(element->name, spellElement_lightning.name))
{
playSoundEntity(my, 173, 128);
if (hit.entity)
{
if (hit.entity->behavior == &actMonster || hit.entity->behavior == &actPlayer)
{
Entity* parent = uidToEntity(my->parent);
playSoundEntity(my, 173, 64);
playSoundEntity(hit.entity, 28, 128);
int damage = element->damage;
damage += (spellbookDamageBonus * damage);
if ( my->actmagicIsOrbiting == 2 )
{
if ( parent && my->actmagicOrbitCastFromSpell == 0 )
{
if ( parent->behavior == &actParticleDot )
{
damage = parent->skill[1];
}
else if ( parent->behavior == &actPlayer )
{
Stat* playerStats = parent->getStats();
if ( playerStats )
{
int skillLVL = playerStats->PROFICIENCIES[PRO_ALCHEMY] / 20;
damage = (22 + skillLVL * 1.5);
}
}
else
{
damage = 22;
}
}
else if ( parent && my->actmagicOrbitCastFromSpell == 1 )
{
// cast through amplify magic effect
damage /= 2;
}
else
{
damage = 22;
}
damage = damage - rand() % ((damage / 8) + 1);
}
//damage += ((element->mana - element->base_mana) / static_cast<double>(element->overload_multiplier)) * element->damage;
int oldHP = hitstats->HP;
damage *= hit.entity->getDamageTableMultiplier(*hitstats, DAMAGE_TABLE_MAGIC);
damage /= (1 + (int)resistance);
hit.entity->modHP(-damage);
// write the obituary
if (parent)
{
parent->killedByMonsterObituary(hit.entity);
}
// update enemy bar for attacker
if ( !strcmp(hitstats->name, "") )
{
if ( hitstats->type < KOBOLD ) //Original monster count
{
updateEnemyBar(parent, hit.entity, language[90 + hitstats->type], hitstats->HP, hitstats->MAXHP);
}
else if ( hitstats->type >= KOBOLD ) //New monsters
{
updateEnemyBar(parent, hit.entity, language[2000 + (hitstats->type - KOBOLD)], hitstats->HP, hitstats->MAXHP);
}
}
else
{
updateEnemyBar(parent, hit.entity, hitstats->name, hitstats->HP, hitstats->MAXHP);
}
if ( oldHP > 0 && hitstats->HP <= 0 && parent)
{
parent->awardXP( hit.entity, true, true );
if ( my->actmagicIsOrbiting == 2 && my->actmagicOrbitCastFromSpell == 0 && parent->behavior == &actPlayer )
{
if ( hitstats->type == LICH || hitstats->type == LICH_ICE || hitstats->type == LICH_FIRE )
{
if ( client_classes[parent->skill[2]] == CLASS_BREWER )
{
steamAchievementClient(parent->skill[2], "BARONY_ACH_SECRET_WEAPON");
}
}
steamStatisticUpdateClient(parent->skill[2], STEAM_STAT_BOMBARDIER, STEAM_STAT_INT, 1);
}
}
}
else if ( hit.entity->behavior == &actDoor )
{
int damage = element->damage;
damage += (spellbookDamageBonus * damage);
//damage += ((element->mana - element->base_mana) / static_cast<double>(element->overload_multiplier)) * element->damage;
damage /= (1 + (int)resistance);
hit.entity->doorHandleDamageMagic(damage, *my, parent);
if ( my->actmagicProjectileArc > 0 )
{
Entity* caster = uidToEntity(spell->caster);
spawnMagicTower(caster, my->x, my->y, spell->ID, nullptr);
}
if ( !(my->actmagicIsOrbiting == 2) )
{
my->removeLightField();
list_RemoveNode(my->mynode);
}
return;
}
else if ( hit.entity->behavior == &actChest )
{
int damage = element->damage;
damage += (spellbookDamageBonus * damage);
damage /= (1 + (int)resistance);
hit.entity->chestHandleDamageMagic(damage, *my, parent);
if ( my->actmagicProjectileArc > 0 )
{
Entity* caster = uidToEntity(spell->caster);
spawnMagicTower(caster, my->x, my->y, spell->ID, nullptr);
}
if ( !(my->actmagicIsOrbiting == 2) )
{
my->removeLightField();
list_RemoveNode(my->mynode);
}
return;
}
else if (hit.entity->behavior == &actFurniture )
{
int damage = element->damage;
damage += (spellbookDamageBonus * damage);
damage /= (1 + (int)resistance);
hit.entity->furnitureHealth -= damage;
if ( hit.entity->furnitureHealth < 0 )
{
if ( parent )
{
if ( parent->behavior == &actPlayer )
{
switch ( hit.entity->furnitureType )
{
case FURNITURE_CHAIR:
messagePlayer(parent->skill[2], language[388]);
updateEnemyBar(parent, hit.entity, language[677], hit.entity->furnitureHealth, hit.entity->furnitureMaxHealth);
break;
case FURNITURE_TABLE:
messagePlayer(parent->skill[2], language[389]);
updateEnemyBar(parent, hit.entity, language[676], hit.entity->furnitureHealth, hit.entity->furnitureMaxHealth);
break;
case FURNITURE_BED:
messagePlayer(parent->skill[2], language[2508], language[2505]);
updateEnemyBar(parent, hit.entity, language[2505], hit.entity->furnitureHealth, hit.entity->furnitureMaxHealth);
break;
case FURNITURE_BUNKBED:
messagePlayer(parent->skill[2], language[2508], language[2506]);
updateEnemyBar(parent, hit.entity, language[2506], hit.entity->furnitureHealth, hit.entity->furnitureMaxHealth);
break;
case FURNITURE_PODIUM:
messagePlayer(parent->skill[2], language[2508], language[2507]);
updateEnemyBar(parent, hit.entity, language[2507], hit.entity->furnitureHealth, hit.entity->furnitureMaxHealth);
break;
default:
break;
}
}
}
}
playSoundEntity(hit.entity, 28, 128);
if ( my->actmagicProjectileArc > 0 )
{
Entity* caster = uidToEntity(spell->caster);
spawnMagicTower(caster, my->x, my->y, spell->ID, nullptr);
}
}
}
}
else if (!strcmp(element->name, spellElement_locking.name))
{
if ( hit.entity )
{
if (hit.entity->behavior == &actDoor)
{
if ( parent && parent->behavior == &actPlayer && MFLAG_DISABLEOPENING )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 255, 0, 255);
messagePlayerColor(parent->skill[2], 0xFFFFFFFF, language[3096], language[3097]);
messagePlayerColor(parent->skill[2], color, language[3101]); // disabled locking spell.
}
else
{
playSoundEntity(hit.entity, 92, 64);
hit.entity->skill[5] = 1; //Lock the door.
if ( parent )
{
if ( parent->behavior == &actPlayer )
{
messagePlayer(parent->skill[2], language[399]);
}
}
}
}
else if (hit.entity->behavior == &actChest)
{
//Lock chest
playSoundEntity(hit.entity, 92, 64);
if ( !hit.entity->chestLocked )
{
if ( parent && parent->behavior == &actPlayer && MFLAG_DISABLEOPENING )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 255, 0, 255);
messagePlayerColor(parent->skill[2], 0xFFFFFFFF, language[3096], language[3099]);
messagePlayerColor(parent->skill[2], color, language[3100]); // disabled locking spell.
}
else
{
hit.entity->lockChest();
if ( parent )
{
if ( parent->behavior == &actPlayer )
{
messagePlayer(parent->skill[2], language[400]);
}
}
}
}
}
else
{
if ( parent )
if ( parent->behavior == &actPlayer )
{
messagePlayer(parent->skill[2], language[401]);
}
if ( player >= 0 )
{
messagePlayer(player, language[401]);
}
}
spawnMagicEffectParticles(hit.entity->x, hit.entity->y, hit.entity->z, my->sprite);
}
}
else if (!strcmp(element->name, spellElement_opening.name))
{
if (hit.entity)
{
if (hit.entity->behavior == &actDoor)
{
if ( MFLAG_DISABLEOPENING || hit.entity->doorDisableOpening == 1 )
{
if ( parent && parent->behavior == &actPlayer )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 255, 0, 255);
messagePlayerColor(parent->skill[2], 0xFFFFFFFF, language[3096], language[3097]);
messagePlayerColor(parent->skill[2], color, language[3101]); // disabled opening spell.
}
}
else
{
// Open the Door
playSoundEntity(hit.entity, 91, 64); // "UnlockDoor.ogg"
hit.entity->doorLocked = 0; // Unlocks the Door
hit.entity->doorPreventLockpickExploit = 1;
if ( !hit.entity->skill[0] && !hit.entity->skill[3] )
{
hit.entity->skill[3] = 1 + (my->x > hit.entity->x); // Opens the Door
playSoundEntity(hit.entity, 21, 96); // "UnlockDoor.ogg"
}
else if ( hit.entity->skill[0] && !hit.entity->skill[3] )
{
hit.entity->skill[3] = 1 + (my->x < hit.entity->x); // Opens the Door
playSoundEntity(hit.entity, 21, 96); // "UnlockDoor.ogg"
}
if ( parent )
{
if ( parent->behavior == &actPlayer)
{
messagePlayer(parent->skill[2], language[402]);
}
}
}
}
else if ( hit.entity->behavior == &actGate )
{
if ( MFLAG_DISABLEOPENING || hit.entity->gateDisableOpening == 1 )
{
if ( parent && parent->behavior == &actPlayer )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 255, 0, 255);
messagePlayerColor(parent->skill[2], 0xFFFFFFFF, language[3096], language[3098]);
messagePlayerColor(parent->skill[2], color, language[3102]); // disabled opening spell.
}
}
else
{
// Open the Gate
if ( (hit.entity->skill[28] != 2 && hit.entity->gateInverted == 0)
|| (hit.entity->skill[28] != 1 && hit.entity->gateInverted == 1) )
{
if ( hit.entity->gateInverted == 1 )
{
hit.entity->skill[28] = 1; // Depowers the Gate
}
else
{
hit.entity->skill[28] = 2; // Powers the Gate
}
if ( parent )
{
if ( parent->behavior == &actPlayer )
{
messagePlayer(parent->skill[2], language[403]); // "The spell opens the gate!"
}
}
}
}
}
else if ( hit.entity->behavior == &actChest )
{
// Unlock the Chest
if ( hit.entity->chestLocked )
{
if ( MFLAG_DISABLEOPENING )
{
if ( parent && parent->behavior == &actPlayer )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 255, 0, 255);
messagePlayerColor(parent->skill[2], 0xFFFFFFFF, language[3096], language[3099]);
messagePlayerColor(parent->skill[2], color, language[3100]); // disabled opening spell.
}
}
else
{
playSoundEntity(hit.entity, 91, 64); // "UnlockDoor.ogg"
hit.entity->unlockChest();
if ( parent )
{
if ( parent->behavior == &actPlayer)
{
messagePlayer(parent->skill[2], language[404]); // "The spell unlocks the chest!"
}
}
}
}
}
else if ( hit.entity->behavior == &actPowerCrystalBase )
{
Entity* childentity = nullptr;
if ( hit.entity->children.first )
{
childentity = static_cast<Entity*>((&hit.entity->children)->first->element);
if ( childentity != nullptr )
{
//Unlock crystal
if ( childentity->crystalSpellToActivate )
{
playSoundEntity(hit.entity, 151, 128);
childentity->crystalSpellToActivate = 0;
// send the clients the updated skill.
serverUpdateEntitySkill(childentity, 10);
if ( parent )
{
if ( parent->behavior == &actPlayer )
{
messagePlayer(parent->skill[2], language[2358]);
}
}
}
}
}
}
else
{
if ( parent )
{
if ( parent->behavior == &actPlayer )
{
messagePlayer(parent->skill[2], language[401]); // "No telling what it did..."
}
}
if ( player >= 0 )
{
messagePlayer(player, language[401]); // "No telling what it did..."
}
}
spawnMagicEffectParticles(hit.entity->x, hit.entity->y, hit.entity->z, my->sprite);
}
}
else if (!strcmp(element->name, spellElement_dig.name))
{
if ( !hit.entity )
{
if ( hit.mapx >= 1 && hit.mapx < map.width - 1 && hit.mapy >= 1 && hit.mapy < map.height - 1 )
{
magicDig(parent, my, 8, 4);
}
}
else
{
if ( hit.entity->behavior == &actBoulder )
{
if ( hit.entity->sprite == 989 || hit.entity->sprite == 990 )
{
magicDig(parent, my, 0, 1);
}
else
{
magicDig(parent, my, 8, 4);
}
}
else
{
if ( parent )
if ( parent->behavior == &actPlayer )
{
messagePlayer(parent->skill[2], language[401]);
}
if ( player >= 0 )
{
messagePlayer(player, language[401]);
}
}
}
}
else if ( !strcmp(element->name, spellElement_stoneblood.name) )
{
if ( hit.entity )
{
if ( hit.entity->behavior == &actMonster || hit.entity->behavior == &actPlayer )
{
playSoundEntity(hit.entity, 172, 64); //TODO: Paralyze spell sound.
int effectDuration = (element->duration * (((element->mana) / static_cast<double>(element->base_mana)) * element->overload_multiplier));
effectDuration /= (1 + (int)resistance);
if ( hit.entity->setEffect(EFF_PARALYZED, true, effectDuration, false) )
{
if ( hit.entity->behavior == &actPlayer )
{
serverUpdateEffects(hit.entity->skill[2]);
}
// update enemy bar for attacker
if ( parent )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 0, 255, 0);
if ( parent->behavior == &actPlayer )
{
messagePlayerMonsterEvent(parent->skill[2], color, *hitstats, language[2421], language[2420], MSG_COMBAT);
}
}
Uint32 color = SDL_MapRGB(mainsurface->format, 255, 0, 0);
if ( player >= 0 )
{
messagePlayerColor(player, color, language[2422]);
}
}
else
{
if ( parent )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 0, 255, 0);
if ( parent->behavior == &actPlayer )
{
messagePlayerMonsterEvent(parent->skill[2], color, *hitstats, language[2905], language[2906], MSG_COMBAT);
}
}
}
spawnMagicEffectParticles(hit.entity->x, hit.entity->y, hit.entity->z, my->sprite);
}
}
}
else if ( !strcmp(element->name, spellElement_bleed.name) )
{
playSoundEntity(my, 173, 128);
if ( hit.entity )
{
if ( hit.entity->behavior == &actMonster || hit.entity->behavior == &actPlayer )
{
Entity* parent = uidToEntity(my->parent);
playSoundEntity(my, 173, 64);
playSoundEntity(hit.entity, 28, 128);
int damage = element->damage;
damage += (spellbookDamageBonus * damage);
//damage += ((element->mana - element->base_mana) / static_cast<double>(element->overload_multiplier)) * element->damage;
damage *= hit.entity->getDamageTableMultiplier(*hitstats, DAMAGE_TABLE_MAGIC);
if ( parent )
{
Stat* casterStats = parent->getStats();
if ( casterStats && casterStats->type == LICH_FIRE && parent->monsterLichAllyStatus == LICH_ALLY_DEAD )
{
damage *= 2;
}
}
damage /= (1 + (int)resistance);
hit.entity->modHP(-damage);
// write the obituary
if ( parent )
{
parent->killedByMonsterObituary(hit.entity);
}
int bleedDuration = (element->duration * (((element->mana) / static_cast<double>(element->base_mana)) * element->overload_multiplier));
bleedDuration /= (1 + (int)resistance);
if ( hit.entity->setEffect(EFF_BLEEDING, true, bleedDuration, true) )
{
if ( parent )
{
hitstats->bleedInflictedBy = static_cast<Sint32>(my->parent);
}
}
hitstats->EFFECTS[EFF_SLOW] = true;
hitstats->EFFECTS_TIMERS[EFF_SLOW] = (element->duration * (((element->mana) / static_cast<double>(element->base_mana)) * element->overload_multiplier));
hitstats->EFFECTS_TIMERS[EFF_SLOW] /= 4;
hitstats->EFFECTS_TIMERS[EFF_SLOW] /= (1 + (int)resistance);
if ( hit.entity->behavior == &actPlayer )
{
serverUpdateEffects(hit.entity->skill[2]);
}
// update enemy bar for attacker
if ( parent )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 0, 255, 0);
if ( parent->behavior == &actPlayer )
{
messagePlayerMonsterEvent(parent->skill[2], color, *hitstats, language[2424], language[2423], MSG_COMBAT);
}
}
// write the obituary
if ( parent )
{
parent->killedByMonsterObituary(hit.entity);
}
// update enemy bar for attacker
if ( !strcmp(hitstats->name, "") )
{
if ( hitstats->type < KOBOLD ) //Original monster count
{
updateEnemyBar(parent, hit.entity, language[90 + hitstats->type], hitstats->HP, hitstats->MAXHP);
}
else if ( hitstats->type >= KOBOLD ) //New monsters
{
updateEnemyBar(parent, hit.entity, language[2000 + (hitstats->type - KOBOLD)], hitstats->HP, hitstats->MAXHP);
}
}
else
{
updateEnemyBar(parent, hit.entity, hitstats->name, hitstats->HP, hitstats->MAXHP);
}
if ( hitstats->HP <= 0 && parent )
{
parent->awardXP(hit.entity, true, true);
if ( hit.entity->behavior == &actMonster )
{
bool tryBloodVial = false;
if ( gibtype[hitstats->type] == 1 || gibtype[hitstats->type] == 2 )
{
for ( c = 0; c < MAXPLAYERS; ++c )
{
if ( players[c]->entity && players[c]->entity->playerRequiresBloodToSustain() )
{
tryBloodVial = true;
break;
}
}
if ( tryBloodVial )
{
Item* blood = newItem(FOOD_BLOOD, EXCELLENT, 0, 1, gibtype[hitstats->type] - 1, true, &hitstats->inventory);
}
}
}
}
Uint32 color = SDL_MapRGB(mainsurface->format, 255, 0, 0);
if ( player >= 0 )
{
messagePlayerColor(player, color, language[2425]);
}
spawnMagicEffectParticles(hit.entity->x, hit.entity->y, hit.entity->z, my->sprite);
for ( int gibs = 0; gibs < 10; ++gibs )
{
Entity* gib = spawnGib(hit.entity);
serverSpawnGibForClient(gib);
}
}
}
}
else if ( !strcmp(element->name, spellElement_dominate.name) )
{
Entity *caster = uidToEntity(spell->caster);
if ( caster )
{
if ( spellEffectDominate(*my, *element, *caster, parent) )
{
//Success
}
}
}
else if ( !strcmp(element->name, spellElement_acidSpray.name) )
{
Entity* caster = uidToEntity(spell->caster);
if ( caster )
{
spellEffectAcid(*my, *element, parent, resistance);
}
}
else if ( !strcmp(element->name, spellElement_poison.name) )
{
Entity* caster = uidToEntity(spell->caster);
if ( caster )
{
spellEffectPoison(*my, *element, parent, resistance);
}
}
else if ( !strcmp(element->name, spellElement_sprayWeb.name) )
{
Entity* caster = uidToEntity(spell->caster);
if ( caster )
{
spellEffectSprayWeb(*my, *element, parent, resistance);
}
}
else if ( !strcmp(element->name, spellElement_stealWeapon.name) )
{
Entity* caster = uidToEntity(spell->caster);
if ( caster )
{
spellEffectStealWeapon(*my, *element, parent, resistance);
}
}
else if ( !strcmp(element->name, spellElement_drainSoul.name) )
{
Entity* caster = uidToEntity(spell->caster);
if ( caster )
{
spellEffectDrainSoul(*my, *element, parent, resistance);
}
}
else if ( !strcmp(element->name, spellElement_charmMonster.name) )
{
Entity* caster = uidToEntity(spell->caster);
if ( caster )
{
spellEffectCharmMonster(*my, *element, parent, resistance, static_cast<bool>(my->actmagicCastByMagicstaff));
}
}
else if ( !strcmp(element->name, spellElement_telePull.name) )
{
Entity* caster = uidToEntity(spell->caster);
if ( caster )
{
spellEffectTeleportPull(my, *element, parent, hit.entity, resistance);
}
}
else if ( !strcmp(element->name, spellElement_shadowTag.name) )
{
Entity* caster = uidToEntity(spell->caster);
if ( caster )
{
spellEffectShadowTag(*my, *element, parent, resistance);
}
}
else if ( !strcmp(element->name, spellElement_demonIllusion.name) )
{
Entity* caster = uidToEntity(spell->caster);
if ( caster )
{
spellEffectDemonIllusion(*my, *element, parent, hit.entity, resistance);
}
}
if ( hitstats )
{
if ( player >= 0 )
{
entityHealth -= hitstats->HP;
if ( entityHealth > 0 )
{
// entity took damage, shake screen.
if ( multiplayer == SERVER && player > 0 )
{
strcpy((char*)net_packet->data, "SHAK");
net_packet->data[4] = 10; // turns into .1
net_packet->data[5] = 10;
net_packet->address.host = net_clients[player - 1].host;
net_packet->address.port = net_clients[player - 1].port;
net_packet->len = 6;
sendPacketSafe(net_sock, -1, net_packet, player - 1);
}
else if (player == 0 || (splitscreen && player > 0) )
{
cameravars[player].shakex += .1;
cameravars[player].shakey += 10;
}
}
}
else
{
if ( parent && parent->behavior == &actPlayer )
{
if ( hitstats->HP <= 0 )
{
if ( hitstats->type == SCARAB )
{
// killed a scarab with magic.
steamAchievementEntity(parent, "BARONY_ACH_THICK_SKULL");
}
if ( my->actmagicMirrorReflected == 1 && static_cast<Uint32>(my->actmagicMirrorReflectedCaster) == hit.entity->getUID() )
{
// killed a monster with it's own spell with mirror reflection.
steamAchievementEntity(parent, "BARONY_ACH_NARCISSIST");
}
if ( stats[parent->skill[2]] && stats[parent->skill[2]]->playerRace == RACE_INSECTOID && stats[parent->skill[2]]->appearance == 0 )
{
if ( !achievementObserver.playerAchievements[parent->skill[2]].gastricBypass )
{
if ( achievementObserver.playerAchievements[parent->skill[2]].gastricBypassSpell.first == spell->ID )
{
Uint32 oldTicks = achievementObserver.playerAchievements[parent->skill[2]].gastricBypassSpell.second;
if ( parent->ticks - oldTicks < TICKS_PER_SECOND * 5 )
{
steamAchievementEntity(parent, "BARONY_ACH_GASTRIC_BYPASS");
achievementObserver.playerAchievements[parent->skill[2]].gastricBypass = true;
}
}
}
}
}
}
}
}
if ( my->actmagicProjectileArc > 0 )
{
Entity* caster = uidToEntity(spell->caster);
spawnMagicTower(caster, my->x, my->y, spell->ID, nullptr);
}
if ( !(my->actmagicIsOrbiting == 2) )
{
my->removeLightField();
if ( my->mynode )
{
list_RemoveNode(my->mynode);
}
}
return;
}
}
//Go down two levels to the next element. This will need to get re-written shortly.
node = spell->elements.first;
element = (spellElement_t*)node->element;
//element = (spellElement_t *)spell->elements->first->element;
//element = (spellElement_t *)element->elements->first->element; //Go down two levels to the second element.
node = element->elements.first;
element = (spellElement_t*)node->element;
if (!strcmp(element->name, spellElement_fire.name) || !strcmp(element->name, spellElement_lightning.name))
{
//Make the ball light up stuff as it travels.
my->light = lightSphereShadow(my->x / 16, my->y / 16, 8, 192);
if ( flickerLights )
{
//Magic light ball will never flicker if this setting is disabled.
lightball_flicker++;
}
my->skill[2] = -11; // so clients know to create a light field
if (lightball_flicker > 5)
{
lightball_lighting = (lightball_lighting == 1) + 1;
if (lightball_lighting == 1)
{
my->removeLightField();
my->light = lightSphereShadow(my->x / 16, my->y / 16, 8, 192);
}
else
{
my->removeLightField();
my->light = lightSphereShadow(my->x / 16, my->y / 16, 8, 174);
}
lightball_flicker = 0;
}
}
else
{
my->skill[2] = -12; // so clients know to simply spawn particles
}
// spawn particles
spawnMagicParticle(my);
}
else
{
//Any init stuff that needs to happen goes here.
magic_init = 1;
my->skill[2] = -7; // ordinarily the client won't do anything with this entity
if ( my->actmagicIsOrbiting == 1 || my->actmagicIsOrbiting == 2 )
{
MAGIC_MAXLIFE = my->actmagicOrbitLifetime;
}
else if ( my->actmagicIsVertical != MAGIC_ISVERTICAL_NONE )
{
MAGIC_MAXLIFE = 512;
}
}
}
void actMagicClient(Entity* my)
{
my->removeLightField();
my->light = lightSphereShadow(my->x / 16, my->y / 16, 8, 192);
if ( flickerLights )
{
//Magic light ball will never flicker if this setting is disabled.
lightball_flicker++;
}
my->skill[2] = -11; // so clients know to create a light field
if (lightball_flicker > 5)
{
lightball_lighting = (lightball_lighting == 1) + 1;
if (lightball_lighting == 1)
{
my->removeLightField();
my->light = lightSphereShadow(my->x / 16, my->y / 16, 8, 192);
}
else
{
my->removeLightField();
my->light = lightSphereShadow(my->x / 16, my->y / 16, 8, 174);
}
lightball_flicker = 0;
}
// spawn particles
spawnMagicParticle(my);
}
void actMagicClientNoLight(Entity* my)
{
spawnMagicParticle(my); // simply spawn particles
}
void actMagicParticle(Entity* my)
{
my->x += my->vel_x;
my->y += my->vel_y;
my->z += my->vel_z;
if ( my->sprite == 943 || my->sprite == 979 )
{
my->scalex -= 0.05;
my->scaley -= 0.05;
my->scalez -= 0.05;
}
my->scalex -= 0.05;
my->scaley -= 0.05;
my->scalez -= 0.05;
if ( my->scalex <= 0 )
{
my->scalex = 0;
my->scaley = 0;
my->scalez = 0;
list_RemoveNode(my->mynode);
return;
}
}
Entity* spawnMagicParticle(Entity* parentent)
{
if ( !parentent )
{
return nullptr;
}
Entity* entity;
entity = newEntity(parentent->sprite, 1, map.entities, nullptr); //Particle entity.
entity->x = parentent->x + (rand() % 50 - 25) / 20.f;
entity->y = parentent->y + (rand() % 50 - 25) / 20.f;
entity->z = parentent->z + (rand() % 50 - 25) / 20.f;
entity->scalex = 0.7;
entity->scaley = 0.7;
entity->scalez = 0.7;
entity->sizex = 1;
entity->sizey = 1;
entity->yaw = parentent->yaw;
entity->pitch = parentent->pitch;
entity->roll = parentent->roll;
entity->flags[NOUPDATE] = true;
entity->flags[PASSABLE] = true;
entity->flags[BRIGHT] = true;
entity->flags[UNCLICKABLE] = true;
entity->flags[NOUPDATE] = true;
entity->flags[UPDATENEEDED] = false;
entity->behavior = &actMagicParticle;
if ( multiplayer != CLIENT )
{
entity_uids--;
}
entity->setUID(-3);
return entity;
}
Entity* spawnMagicParticleCustom(Entity* parentent, int sprite, real_t scale, real_t spreadReduce)
{
if ( !parentent )
{
return nullptr;
}
Entity* entity;
entity = newEntity(sprite, 1, map.entities, nullptr); //Particle entity.
int size = 50 / spreadReduce;
entity->x = parentent->x + (rand() % size - size / 2) / 20.f;
entity->y = parentent->y + (rand() % size - size / 2) / 20.f;
entity->z = parentent->z + (rand() % size - size / 2) / 20.f;
entity->scalex = scale;
entity->scaley = scale;
entity->scalez = scale;
entity->sizex = 1;
entity->sizey = 1;
entity->yaw = parentent->yaw;
entity->pitch = parentent->pitch;
entity->roll = parentent->roll;
entity->flags[NOUPDATE] = true;
entity->flags[PASSABLE] = true;
entity->flags[BRIGHT] = true;
entity->flags[UNCLICKABLE] = true;
entity->flags[NOUPDATE] = true;
entity->flags[UPDATENEEDED] = false;
entity->behavior = &actMagicParticle;
if ( multiplayer != CLIENT )
{
entity_uids--;
}
entity->setUID(-3);
return entity;
}
void spawnMagicEffectParticles(Sint16 x, Sint16 y, Sint16 z, Uint32 sprite)
{
int c;
if ( multiplayer == SERVER )
{
for ( c = 1; c < MAXPLAYERS; c++ )
{
if ( client_disconnected[c] )
{
continue;
}
strcpy((char*)net_packet->data, "MAGE");
SDLNet_Write16(x, &net_packet->data[4]);
SDLNet_Write16(y, &net_packet->data[6]);
SDLNet_Write16(z, &net_packet->data[8]);
SDLNet_Write32(sprite, &net_packet->data[10]);
net_packet->address.host = net_clients[c - 1].host;
net_packet->address.port = net_clients[c - 1].port;
net_packet->len = 14;
sendPacketSafe(net_sock, -1, net_packet, c - 1);
}
}
// boosty boost
for ( c = 0; c < 10; c++ )
{
Entity* entity = newEntity(sprite, 1, map.entities, nullptr); //Particle entity.
entity->x = x - 5 + rand() % 11;
entity->y = y - 5 + rand() % 11;
entity->z = z - 10 + rand() % 21;
entity->scalex = 0.7;
entity->scaley = 0.7;
entity->scalez = 0.7;
entity->sizex = 1;
entity->sizey = 1;
entity->yaw = (rand() % 360) * PI / 180.f;
entity->flags[PASSABLE] = true;
entity->flags[BRIGHT] = true;
entity->flags[NOUPDATE] = true;
entity->flags[UNCLICKABLE] = true;
entity->behavior = &actMagicParticle;
entity->vel_z = -1;
if ( multiplayer != CLIENT )
{
entity_uids--;
}
entity->setUID(-3);
}
}
void createParticle1(Entity* caster, int player)
{
Entity* entity = newEntity(-1, 1, map.entities, nullptr); //Particle entity.
entity->sizex = 0;
entity->sizey = 0;
entity->x = caster->x;
entity->y = caster->y;
entity->z = -7;
entity->vel_z = 0.3;
entity->yaw = (rand() % 360) * PI / 180.0;
entity->skill[0] = 50;
entity->skill[1] = player;
entity->fskill[0] = 0.03;
entity->light = lightSphereShadow(entity->x / 16, entity->y / 16, 3, 192);
entity->behavior = &actParticleCircle;
entity->flags[PASSABLE] = true;
entity->flags[INVISIBLE] = true;
entity->setUID(-3);
}
void createParticleCircling(Entity* parent, int duration, int sprite)
{
if ( !parent )
{
return;
}
Entity* entity = newEntity(sprite, 1, map.entities, nullptr); //Particle entity.
entity->sizex = 1;
entity->sizey = 1;
entity->x = parent->x;
entity->y = parent->y;
entity->focalx = 8;
entity->z = -7;
entity->vel_z = 0.15;
entity->yaw = (rand() % 360) * PI / 180.0;
entity->skill[0] = duration;
entity->skill[1] = -1;
//entity->scalex = 0.01;
//entity->scaley = 0.01;
entity->fskill[0] = -0.1;
entity->behavior = &actParticleCircle;
entity->flags[PASSABLE] = true;
entity->setUID(-3);
real_t tmp = entity->yaw;
entity = newEntity(sprite, 1, map.entities, nullptr); //Particle entity.
entity->sizex = 1;
entity->sizey = 1;
entity->x = parent->x;
entity->y = parent->y;
entity->focalx = 8;
entity->z = -7;
entity->vel_z = 0.15;
entity->yaw = tmp + (2 * PI / 3);
entity->particleDuration = duration;
entity->skill[1] = -1;
//entity->scalex = 0.01;
//entity->scaley = 0.01;
entity->fskill[0] = -0.1;
entity->behavior = &actParticleCircle;
entity->flags[PASSABLE] = true;
entity->setUID(-3);
entity = newEntity(sprite, 1, map.entities, nullptr); //Particle entity.
entity->sizex = 1;
entity->sizey = 1;
entity->x = parent->x;
entity->y = parent->y;
entity->focalx = 8;
entity->z = -7;
entity->vel_z = 0.15;
entity->yaw = tmp - (2 * PI / 3);
entity->particleDuration = duration;
entity->skill[1] = -1;
//entity->scalex = 0.01;
//entity->scaley = 0.01;
entity->fskill[0] = -0.1;
entity->behavior = &actParticleCircle;
entity->flags[PASSABLE] = true;
entity->setUID(-3);
entity = newEntity(sprite, 1, map.entities, nullptr); //Particle entity.
entity->sizex = 1;
entity->sizey = 1;
entity->x = parent->x;
entity->y = parent->y;
entity->focalx = 16;
entity->z = -12;
entity->vel_z = 0.2;
entity->yaw = tmp;
entity->particleDuration = duration;
entity->skill[1] = -1;
//entity->scalex = 0.01;
//entity->scaley = 0.01;
entity->fskill[0] = 0.1;
entity->behavior = &actParticleCircle;
entity->flags[PASSABLE] = true;
entity->setUID(-3);
entity = newEntity(sprite, 1, map.entities, nullptr); //Particle entity.
entity->sizex = 1;
entity->sizey = 1;
entity->x = parent->x;
entity->y = parent->y;
entity->focalx = 16;
entity->z = -12;
entity->vel_z = 0.2;
entity->yaw = tmp + (2 * PI / 3);
entity->particleDuration = duration;
entity->skill[1] = -1;
//entity->scalex = 0.01;
//entity->scaley = 0.01;
entity->fskill[0] = 0.1;
entity->behavior = &actParticleCircle;
entity->flags[PASSABLE] = true;
entity->setUID(-3);
entity = newEntity(sprite, 1, map.entities, nullptr); //Particle entity.
entity->sizex = 1;
entity->sizey = 1;
entity->x = parent->x;
entity->y = parent->y;
entity->focalx = 16;
entity->z = -12;
entity->vel_z = 0.2;
entity->yaw = tmp - (2 * PI / 3);
entity->particleDuration = duration;
entity->skill[1] = -1;
//entity->scalex = 0.01;
//entity->scaley = 0.01;
entity->fskill[0] = 0.1;
entity->behavior = &actParticleCircle;
entity->flags[PASSABLE] = true;
entity->setUID(-3);
}
#define PARTICLE_LIFE my->skill[0]
#define PARTICLE_CASTER my->skill[1]
void actParticleCircle(Entity* my)
{
if ( PARTICLE_LIFE < 0 )
{
list_RemoveNode(my->mynode);
return;
}
else
{
--PARTICLE_LIFE;
my->yaw += my->fskill[0];
if ( my->fskill[0] < 0.4 && my->fskill[0] > (-0.4) )
{
my->fskill[0] = my->fskill[0] * 1.05;
}
my->z += my->vel_z;
if ( my->focalx > 0.05 )
{
if ( my->vel_z == 0.15 )
{
my->focalx = my->focalx * 0.97;
}
else
{
my->focalx = my->focalx * 0.97;
}
}
my->scalex *= 0.995;
my->scaley *= 0.995;
my->scalez *= 0.995;
}
}
void createParticleDot(Entity* parent)
{
if ( !parent )
{
return;
}
for ( int c = 0; c < 50; c++ )
{
Entity* entity = newEntity(576, 1, map.entities, nullptr); //Particle entity.
entity->sizex = 1;
entity->sizey = 1;
entity->x = parent->x + (-4 + rand() % 9);
entity->y = parent->y + (-4 + rand() % 9);
entity->z = 7.5 + rand()%50;
entity->vel_z = -1;
//entity->yaw = (rand() % 360) * PI / 180.0;
entity->skill[0] = 10 + rand()% 50;
entity->behavior = &actParticleDot;
entity->flags[PASSABLE] = true;
entity->flags[NOUPDATE] = true;
entity->flags[UNCLICKABLE] = true;
if ( multiplayer != CLIENT )
{
entity_uids--;
}
entity->setUID(-3);
}
}
Entity* createParticleAestheticOrbit(Entity* parent, int sprite, int duration, int effectType)
{
if ( !parent )
{
return nullptr;
}
Entity* entity = newEntity(sprite, 1, map.entities, nullptr); //Particle entity.
entity->sizex = 1;
entity->sizey = 1;
entity->actmagicOrbitDist = 6;
entity->yaw = parent->yaw;
entity->x = parent->x + entity->actmagicOrbitDist * cos(entity->yaw);
entity->y = parent->y + entity->actmagicOrbitDist * sin(entity->yaw);
entity->z = parent->z;
entity->skill[1] = effectType;
entity->parent = parent->getUID();
//entity->vel_z = -1;
//entity->yaw = (rand() % 360) * PI / 180.0;
entity->skill[0] = duration;
entity->fskill[0] = entity->x;
entity->fskill[1] = entity->y;
entity->behavior = &actParticleAestheticOrbit;
entity->flags[PASSABLE] = true;
entity->flags[NOUPDATE] = true;
entity->flags[BRIGHT] = true;
entity->flags[UNCLICKABLE] = true;
if ( multiplayer != CLIENT )
{
entity_uids--;
}
entity->setUID(-3);
return entity;
}
void createParticleRock(Entity* parent)
{
if ( !parent )
{
return;
}
for ( int c = 0; c < 5; c++ )
{
Entity* entity = newEntity(78, 1, map.entities, nullptr); //Particle entity.
entity->sizex = 1;
entity->sizey = 1;
entity->x = parent->x + (-4 + rand() % 9);
entity->y = parent->y + (-4 + rand() % 9);
entity->z = 7.5;
entity->yaw = c * 2 * PI / 5;//(rand() % 360) * PI / 180.0;
entity->roll = (rand() % 360) * PI / 180.0;
entity->vel_x = 0.2 * cos(entity->yaw);
entity->vel_y = 0.2 * sin(entity->yaw);
entity->vel_z = 3;// 0.25 - (rand() % 5) / 10.0;
entity->skill[0] = 50; // particle life
entity->skill[1] = 0; // particle direction, 0 = upwards, 1 = downwards.
entity->behavior = &actParticleRock;
entity->flags[PASSABLE] = true;
entity->flags[NOUPDATE] = true;
entity->flags[UNCLICKABLE] = true;
if ( multiplayer != CLIENT )
{
entity_uids--;
}
entity->setUID(-3);
}
}
void actParticleRock(Entity* my)
{
if ( PARTICLE_LIFE < 0 || my->z > 10 )
{
list_RemoveNode(my->mynode);
}
else
{
--PARTICLE_LIFE;
my->x += my->vel_x;
my->y += my->vel_y;
my->roll += 0.1;
if ( my->vel_z < 0.01 )
{
my->skill[1] = 1; // start moving downwards
my->vel_z = 0.1;
}
if ( my->skill[1] == 0 ) // upwards motion
{
my->z -= my->vel_z;
my->vel_z *= 0.7;
}
else // downwards motion
{
my->z += my->vel_z;
my->vel_z *= 1.1;
}
}
return;
}
void actParticleDot(Entity* my)
{
if ( PARTICLE_LIFE < 0 )
{
list_RemoveNode(my->mynode);
}
else
{
--PARTICLE_LIFE;
my->z += my->vel_z;
//my->z -= 0.01;
}
return;
}
void actParticleAestheticOrbit(Entity* my)
{
if ( PARTICLE_LIFE < 0 )
{
list_RemoveNode(my->mynode);
}
else
{
Entity* parent = uidToEntity(my->parent);
if ( !parent )
{
list_RemoveNode(my->mynode);
return;
}
Stat* stats = parent->getStats();
if ( my->skill[1] == PARTICLE_EFFECT_SPELLBOT_ORBIT )
{
my->yaw = parent->yaw;
my->x = parent->x + 2 * cos(parent->yaw);
my->y = parent->y + 2 * sin(parent->yaw);
my->z = parent->z - 1.5;
Entity* particle = spawnMagicParticle(my);
if ( particle )
{
particle->x = my->x + (-10 + rand() % 21) / (50.f);
particle->y = my->y + (-10 + rand() % 21) / (50.f);
particle->z = my->z + (-10 + rand() % 21) / (50.f);
particle->scalex = my->scalex;
particle->scaley = my->scaley;
particle->scalez = my->scalez;
}
//spawnMagicParticle(my);
}
else if ( my->skill[1] == PARTICLE_EFFECT_SPELL_WEB_ORBIT )
{
if ( my->sprite == 863 && !stats->EFFECTS[EFF_WEBBED] )
{
list_RemoveNode(my->mynode);
return;
}
my->yaw += 0.2;
spawnMagicParticle(my);
my->x = parent->x + my->actmagicOrbitDist * cos(my->yaw);
my->y = parent->y + my->actmagicOrbitDist * sin(my->yaw);
}
--PARTICLE_LIFE;
}
return;
}
void actParticleTest(Entity* my)
{
if ( PARTICLE_LIFE < 0 )
{
list_RemoveNode(my->mynode);
return;
}
else
{
--PARTICLE_LIFE;
my->x += my->vel_x;
my->y += my->vel_y;
my->z += my->vel_z;
//my->z -= 0.01;
}
}
void createParticleErupt(Entity* parent, int sprite)
{
if ( !parent )
{
return;
}
real_t yaw = 0;
int numParticles = 8;
for ( int c = 0; c < 8; c++ )
{
Entity* entity = newEntity(sprite, 1, map.entities, nullptr); //Particle entity.
entity->sizex = 1;
entity->sizey = 1;
entity->x = parent->x;
entity->y = parent->y;
entity->z = 7.5; // start from the ground.
entity->yaw = yaw;
entity->vel_x = 0.2;
entity->vel_y = 0.2;
entity->vel_z = -2;
entity->skill[0] = 100;
entity->skill[1] = 0; // direction.
entity->fskill[0] = 0.1;
entity->behavior = &actParticleErupt;
entity->flags[PASSABLE] = true;
entity->flags[NOUPDATE] = true;
entity->flags[UNCLICKABLE] = true;
if ( multiplayer != CLIENT )
{
entity_uids--;
}
entity->setUID(-3);
yaw += 2 * PI / numParticles;
}
}
Entity* createParticleSapCenter(Entity* parent, Entity* target, int spell, int sprite, int endSprite)
{
if ( !parent || !target )
{
return nullptr;
}
// spawns the invisible 'center' of the magic particle
Entity* entity = newEntity(sprite, 1, map.entities, nullptr); //Particle entity.
entity->sizex = 1;
entity->sizey = 1;
entity->x = target->x;
entity->y = target->y;
entity->parent = (parent->getUID());
entity->yaw = parent->yaw + PI; // face towards the caster.
entity->skill[0] = 45;
entity->skill[2] = -13; // so clients know my behavior.
entity->skill[3] = 0; // init
entity->skill[4] = sprite; // visible sprites.
entity->skill[5] = endSprite; // sprite to spawn on return to caster.
entity->skill[6] = spell;
entity->behavior = &actParticleSapCenter;
if ( target->sprite == 977 )
{
// boomerang.
entity->yaw = target->yaw;
entity->roll = target->roll;
entity->pitch = target->pitch;
entity->z = target->z;
}
entity->flags[INVISIBLE] = true;
entity->flags[PASSABLE] = true;
entity->flags[UPDATENEEDED] = true;
entity->flags[UNCLICKABLE] = true;
return entity;
}
void createParticleSap(Entity* parent)
{
real_t speed = 0.4;
if ( !parent )
{
return;
}
for ( int c = 0; c < 4; c++ )
{
// 4 particles, in an 'x' pattern around parent sprite.
int sprite = parent->sprite;
if ( parent->sprite == 977 )
{
if ( c > 0 )
{
continue;
}
// boomerang return.
sprite = parent->sprite;
}
if ( parent->skill[6] == SPELL_STEAL_WEAPON || parent->skill[6] == SHADOW_SPELLCAST )
{
sprite = parent->sprite;
}
else if ( parent->skill[6] == SPELL_DRAIN_SOUL )
{
if ( c == 0 || c == 3 )
{
sprite = parent->sprite;
}
else
{
sprite = 599;
}
}
else if ( parent->skill[6] == SPELL_SUMMON )
{
sprite = parent->sprite;
}
else if ( parent->skill[6] == SPELL_FEAR )
{
sprite = parent->sprite;
}
else if ( multiplayer == CLIENT )
{
// client won't receive the sprite skill data in time, fix for this until a solution is found!
if ( sprite == 598 )
{
if ( c == 0 || c == 3 )
{
// drain HP particle
sprite = parent->sprite;
}
else
{
// drain MP particle
sprite = 599;
}
}
}
Entity* entity = newEntity(sprite, 1, map.entities, nullptr); //Particle entity.
entity->sizex = 1;
entity->sizey = 1;
entity->x = parent->x;
entity->y = parent->y;
entity->z = 0;
entity->scalex = 0.9;
entity->scaley = 0.9;
entity->scalez = 0.9;
if ( sprite == 598 || sprite == 599 )
{
entity->scalex = 0.5;
entity->scaley = 0.5;
entity->scalez = 0.5;
}
entity->parent = (parent->getUID());
entity->yaw = parent->yaw;
if ( c == 0 )
{
entity->vel_z = -speed;
entity->vel_x = speed * cos(entity->yaw + PI / 2);
entity->vel_y = speed * sin(entity->yaw + PI / 2);
entity->yaw += PI / 3;
entity->pitch -= PI / 6;
entity->fskill[2] = -(PI / 3) / 25; // yaw rate of change.
entity->fskill[3] = (PI / 6) / 25; // pitch rate of change.
}
else if ( c == 1 )
{
entity->vel_z = -speed;
entity->vel_x = speed * cos(entity->yaw - PI / 2);
entity->vel_y = speed * sin(entity->yaw - PI / 2);
entity->yaw -= PI / 3;
entity->pitch -= PI / 6;
entity->fskill[2] = (PI / 3) / 25; // yaw rate of change.
entity->fskill[3] = (PI / 6) / 25; // pitch rate of change.
}
else if ( c == 2 )
{
entity->vel_x = speed * cos(entity->yaw + PI / 2);
entity->vel_y = speed * sin(entity->yaw + PI / 2);
entity->vel_z = speed;
entity->yaw += PI / 3;
entity->pitch += PI / 6;
entity->fskill[2] = -(PI / 3) / 25; // yaw rate of change.
entity->fskill[3] = -(PI / 6) / 25; // pitch rate of change.
}
else if ( c == 3 )
{
entity->vel_x = speed * cos(entity->yaw - PI / 2);
entity->vel_y = speed * sin(entity->yaw - PI / 2);
entity->vel_z = speed;
entity->yaw -= PI / 3;
entity->pitch += PI / 6;
entity->fskill[2] = (PI / 3) / 25; // yaw rate of change.
entity->fskill[3] = -(PI / 6) / 25; // pitch rate of change.
}
entity->skill[3] = c; // particle index
entity->fskill[0] = entity->vel_x; // stores the accumulated x offset from center
entity->fskill[1] = entity->vel_y; // stores the accumulated y offset from center
entity->skill[0] = 200; // lifetime
entity->skill[1] = 0; // direction outwards
entity->behavior = &actParticleSap;
entity->flags[PASSABLE] = true;
entity->flags[NOUPDATE] = true;
if ( multiplayer != CLIENT )
{
entity_uids--;
}
entity->setUID(-3);
if ( sprite == 977 ) // boomerang
{
entity->z = parent->z;
entity->scalex = 1.f;
entity->scaley = 1.f;
entity->scalez = 1.f;
entity->skill[0] = 175;
entity->fskill[2] = -((PI / 3) + (PI / 6)) / (150); // yaw rate of change over 3 seconds
entity->fskill[3] = 0.f;
entity->focalx = 2;
entity->focalz = 0.5;
entity->pitch = parent->pitch;
entity->yaw = parent->yaw;
entity->roll = parent->roll;
entity->vel_x = 1 * cos(entity->yaw);
entity->vel_y = 1 * sin(entity->yaw);
int x = entity->x / 16;
int y = entity->y / 16;
if ( !map.tiles[(MAPLAYERS - 1) + y * MAPLAYERS + x * MAPLAYERS * map.height] )
{
// no ceiling, bounce higher.
entity->vel_z = -0.4;
entity->skill[3] = 1; // high bounce.
}
else
{
entity->vel_z = -0.08;
}
entity->yaw += PI / 3;
}
}
}
void createParticleDropRising(Entity* parent, int sprite, double scale)
{
if ( !parent )
{
return;
}
for ( int c = 0; c < 50; c++ )
{
// shoot drops to the sky
Entity* entity = newEntity(sprite, 1, map.entities, nullptr); //Particle entity.
entity->sizex = 1;
entity->sizey = 1;
entity->x = parent->x - 4 + rand() % 9;
entity->y = parent->y - 4 + rand() % 9;
entity->z = 7.5 + rand() % 50;
entity->vel_z = -1;
//entity->yaw = (rand() % 360) * PI / 180.0;
entity->particleDuration = 10 + rand() % 50;
entity->scalex *= scale;
entity->scaley *= scale;
entity->scalez *= scale;
entity->behavior = &actParticleDot;
entity->flags[PASSABLE] = true;
entity->flags[NOUPDATE] = true;
entity->flags[UNCLICKABLE] = true;
if ( multiplayer != CLIENT )
{
entity_uids--;
}
entity->setUID(-3);
}
}
Entity* createParticleTimer(Entity* parent, int duration, int sprite)
{
Entity* entity = newEntity(-1, 1, map.entities, nullptr); //Timer entity.
entity->sizex = 1;
entity->sizey = 1;
if ( parent )
{
entity->x = parent->x;
entity->y = parent->y;
entity->parent = (parent->getUID());
}
entity->behavior = &actParticleTimer;
entity->particleTimerDuration = duration;
entity->flags[INVISIBLE] = true;
entity->flags[PASSABLE] = true;
entity->flags[NOUPDATE] = true;
if ( multiplayer != CLIENT )
{
entity_uids--;
}
entity->setUID(-3);
return entity;
}
void actParticleErupt(Entity* my)
{
if ( PARTICLE_LIFE < 0 )
{
list_RemoveNode(my->mynode);
return;
}
else
{
// particles jump up from the ground then back down again.
--PARTICLE_LIFE;
my->x += my->vel_x * cos(my->yaw);
my->y += my->vel_y * sin(my->yaw);
my->scalex *= 0.99;
my->scaley *= 0.99;
my->scalez *= 0.99;
spawnMagicParticle(my);
if ( my->skill[1] == 0 ) // rising
{
my->z += my->vel_z;
my->vel_z *= 0.8;
my->pitch = std::min<real_t>(my->pitch + my->fskill[0], PI / 2);
my->fskill[0] = std::max<real_t>(my->fskill[0] * 0.85, 0.05);
if ( my->vel_z > -0.02 )
{
my->skill[1] = 1;
}
}
else // falling
{
my->pitch = std::min<real_t>(my->pitch + my->fskill[0], 15 * PI / 16);
my->fskill[0] = std::min<real_t>(my->fskill[0] * (1 / 0.99), 0.1);
my->z -= my->vel_z;
my->vel_z *= (1 / 0.8);
my->vel_z = std::max<real_t>(my->vel_z, -0.8);
}
}
}
void actParticleTimer(Entity* my)
{
if ( PARTICLE_LIFE < 0 )
{
if ( multiplayer != CLIENT )
{
if ( my->particleTimerEndAction == PARTICLE_EFFECT_INCUBUS_TELEPORT_STEAL )
{
// teleport to random location spell.
Entity* parent = uidToEntity(my->parent);
if ( parent )
{
createParticleErupt(parent, my->particleTimerEndSprite);
if ( parent->teleportRandom() )
{
// teleport success.
if ( multiplayer == SERVER )
{
serverSpawnMiscParticles(parent, PARTICLE_EFFECT_ERUPT, my->particleTimerEndSprite);
}
}
}
}
else if ( my->particleTimerEndAction == PARTICLE_EFFECT_INCUBUS_TELEPORT_TARGET )
{
// teleport to target spell.
Entity* parent = uidToEntity(my->parent);
Entity* target = uidToEntity(static_cast<Uint32>(my->particleTimerTarget));
if ( parent && target )
{
createParticleErupt(parent, my->particleTimerEndSprite);
if ( parent->teleportAroundEntity(target, my->particleTimerVariable1) )
{
// teleport success.
if ( multiplayer == SERVER )
{
serverSpawnMiscParticles(parent, PARTICLE_EFFECT_ERUPT, my->particleTimerEndSprite);
}
}
}
}
else if ( my->particleTimerEndAction == PARTICLE_EFFECT_TELEPORT_PULL )
{
// teleport to target spell.
Entity* parent = uidToEntity(my->parent);
Entity* target = uidToEntity(static_cast<Uint32>(my->particleTimerTarget));
if ( parent && target )
{
real_t oldx = target->x;
real_t oldy = target->y;
my->flags[PASSABLE] = true;
int tx = static_cast<int>(std::floor(my->x)) >> 4;
int ty = static_cast<int>(std::floor(my->y)) >> 4;
if ( !target->isBossMonster() &&
target->teleport(tx, ty) )
{
// teleport success.
if ( parent->behavior == &actPlayer )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 0, 255, 0);
if ( target->getStats() )
{
messagePlayerMonsterEvent(parent->skill[2], color, *(target->getStats()), language[3450], language[3451], MSG_COMBAT);
}
}
if ( target->behavior == &actPlayer )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 255, 255, 255);
messagePlayerColor(target->skill[2], color, language[3461]);
}
real_t distance = sqrt((target->x - oldx) * (target->x - oldx) + (target->y - oldy) * (target->y - oldy)) / 16.f;
//real_t distance = (entityDist(parent, target)) / 16;
createParticleErupt(target, my->particleTimerEndSprite);
int durationToStun = 0;
if ( distance >= 2 )
{
durationToStun = 25 + std::min((distance - 4) * 10, 50.0);
}
if ( target->behavior == &actMonster )
{
if ( durationToStun > 0 && target->setEffect(EFF_DISORIENTED, true, durationToStun, false) )
{
int numSprites = std::min(3, durationToStun / 25);
for ( int i = 0; i < numSprites; ++i )
{
spawnFloatingSpriteMisc(134, target->x + (-4 + rand() % 9) + cos(target->yaw) * 2,
target->y + (-4 + rand() % 9) + sin(target->yaw) * 2, target->z + rand() % 4);
}
}
target->monsterReleaseAttackTarget();
target->lookAtEntity(*parent);
target->monsterLookDir += (PI - PI / 4 + (rand() % 10) * PI / 40);
}
else if ( target->behavior == &actPlayer )
{
durationToStun = std::max(50, durationToStun);
target->setEffect(EFF_DISORIENTED, true, durationToStun, false);
int numSprites = std::min(3, durationToStun / 50);
for ( int i = 0; i < numSprites; ++i )
{
spawnFloatingSpriteMisc(134, target->x + (-4 + rand() % 9) + cos(target->yaw) * 2,
target->y + (-4 + rand() % 9) + sin(target->yaw) * 2, target->z + rand() % 4);
}
Uint32 color = SDL_MapRGB(mainsurface->format, 255, 255, 255);
messagePlayerColor(target->skill[2], color, language[3462]);
}
if ( multiplayer == SERVER )
{
serverSpawnMiscParticles(target, PARTICLE_EFFECT_ERUPT, my->particleTimerEndSprite);
}
}
}
}
else if ( my->particleTimerEndAction == PARTICLE_EFFECT_PORTAL_SPAWN )
{
Entity* parent = uidToEntity(my->parent);
if ( parent )
{
parent->flags[INVISIBLE] = false;
serverUpdateEntityFlag(parent, INVISIBLE);
playSoundEntity(parent, 164, 128);
}
spawnExplosion(my->x, my->y, 0);
}
else if ( my->particleTimerEndAction == PARTICLE_EFFECT_SUMMON_MONSTER
|| my->particleTimerEndAction == PARTICLE_EFFECT_DEVIL_SUMMON_MONSTER )
{
playSoundEntity(my, 164, 128);
spawnExplosion(my->x, my->y, -4.0);
bool forceLocation = false;
if ( my->particleTimerEndAction == PARTICLE_EFFECT_DEVIL_SUMMON_MONSTER &&
!map.tiles[static_cast<int>(my->y / 16) * MAPLAYERS + static_cast<int>(my->x / 16) * MAPLAYERS * map.height] )
{
if ( my->particleTimerVariable1 == SHADOW || my->particleTimerVariable1 == CREATURE_IMP )
{
forceLocation = true;
}
}
Entity* monster = summonMonster(static_cast<Monster>(my->particleTimerVariable1), my->x, my->y, forceLocation);
if ( monster )
{
Stat* monsterStats = monster->getStats();
if ( my->parent != 0 && uidToEntity(my->parent) )
{
if ( uidToEntity(my->parent)->getRace() == LICH_ICE )
{
//monsterStats->leader_uid = my->parent;
switch ( monsterStats->type )
{
case AUTOMATON:
strcpy(monsterStats->name, "corrupted automaton");
monsterStats->EFFECTS[EFF_CONFUSED] = true;
monsterStats->EFFECTS_TIMERS[EFF_CONFUSED] = -1;
break;
default:
break;
}
}
else if ( uidToEntity(my->parent)->getRace() == DEVIL )
{
monsterStats->LVL = 5;
if ( my->particleTimerVariable2 >= 0
&& players[my->particleTimerVariable2] && players[my->particleTimerVariable2]->entity )
{
monster->monsterAcquireAttackTarget(*(players[my->particleTimerVariable2]->entity), MONSTER_STATE_ATTACK);
}
}
}
}
}
else if ( my->particleTimerEndAction == PARTICLE_EFFECT_SPELL_SUMMON )
{
//my->removeLightField();
}
else if ( my->particleTimerEndAction == PARTICLE_EFFECT_SHADOW_TELEPORT )
{
// teleport to target spell.
Entity* parent = uidToEntity(my->parent);
if ( parent )
{
if ( parent->monsterSpecialState == SHADOW_TELEPORT_ONLY )
{
//messagePlayer(0, "Resetting shadow's monsterSpecialState!");
parent->monsterSpecialState = 0;
serverUpdateEntitySkill(parent, 33); // for clients to keep track of animation
}
}
Entity* target = uidToEntity(static_cast<Uint32>(my->particleTimerTarget));
if ( parent )
{
bool teleported = false;
createParticleErupt(parent, my->particleTimerEndSprite);
if ( target )
{
teleported = parent->teleportAroundEntity(target, my->particleTimerVariable1);
}
else
{
teleported = parent->teleportRandom();
}
if ( teleported )
{
// teleport success.
if ( multiplayer == SERVER )
{
serverSpawnMiscParticles(parent, PARTICLE_EFFECT_ERUPT, my->particleTimerEndSprite);
}
}
}
}
else if ( my->particleTimerEndAction == PARTICLE_EFFECT_LICHFIRE_TELEPORT_STATIONARY )
{
// teleport to fixed location spell.
node_t* node;
int c = 0 + rand() % 3;
Entity* target = nullptr;
for ( node = map.entities->first; node != nullptr; node = node->next )
{
target = (Entity*)node->element;
if ( target->behavior == &actDevilTeleport )
{
if ( (c == 0 && target->sprite == 72)
|| (c == 1 && target->sprite == 73)
|| (c == 2 && target->sprite == 74) )
{
break;
}
}
}
Entity* parent = uidToEntity(my->parent);
if ( parent && target )
{
createParticleErupt(parent, my->particleTimerEndSprite);
if ( parent->teleport(target->x / 16, target->y / 16) )
{
// teleport success.
if ( multiplayer == SERVER )
{
serverSpawnMiscParticles(parent, PARTICLE_EFFECT_ERUPT, my->particleTimerEndSprite);
}
}
}
}
else if ( my->particleTimerEndAction == PARTICLE_EFFECT_LICH_TELEPORT_ROAMING )
{
bool teleported = false;
// teleport to target spell.
node_t* node;
Entity* parent = uidToEntity(my->parent);
Entity* target = nullptr;
if ( parent )
{
for ( node = map.entities->first; node != nullptr; node = node->next )
{
target = (Entity*)node->element;
if ( target->behavior == &actDevilTeleport
&& target->sprite == 128 )
{
break; // found specified center of map
}
}
if ( target )
{
createParticleErupt(parent, my->particleTimerEndSprite);
teleported = parent->teleport((target->x / 16) - 11 + rand() % 23, (target->y / 16) - 11 + rand() % 23);
if ( teleported )
{
// teleport success.
if ( multiplayer == SERVER )
{
serverSpawnMiscParticles(parent, PARTICLE_EFFECT_ERUPT, my->particleTimerEndSprite);
}
}
}
}
}
else if ( my->particleTimerEndAction == PARTICLE_EFFECT_LICHICE_TELEPORT_STATIONARY )
{
// teleport to fixed location spell.
node_t* node;
Entity* target = nullptr;
for ( node = map.entities->first; node != nullptr; node = node->next )
{
target = (Entity*)node->element;
if ( target->behavior == &actDevilTeleport
&& target->sprite == 128 )
{
break;
}
}
Entity* parent = uidToEntity(my->parent);
if ( parent && target )
{
createParticleErupt(parent, my->particleTimerEndSprite);
if ( parent->teleport(target->x / 16, target->y / 16) )
{
// teleport success.
if ( multiplayer == SERVER )
{
serverSpawnMiscParticles(parent, PARTICLE_EFFECT_ERUPT, my->particleTimerEndSprite);
}
parent->lichIceCreateCannon();
}
}
}
}
my->removeLightField();
list_RemoveNode(my->mynode);
return;
}
else
{
--PARTICLE_LIFE;
if ( my->particleTimerPreDelay <= 0 )
{
// shoot particles for the duration of the timer, centered at caster.
if ( my->particleTimerCountdownAction == PARTICLE_TIMER_ACTION_SHOOT_PARTICLES )
{
Entity* parent = uidToEntity(my->parent);
// shoot drops to the sky
if ( parent && my->particleTimerCountdownSprite != 0 )
{
Entity* entity = newEntity(my->particleTimerCountdownSprite, 1, map.entities, nullptr); //Particle entity.
entity->sizex = 1;
entity->sizey = 1;
entity->x = parent->x - 4 + rand() % 9;
entity->y = parent->y - 4 + rand() % 9;
entity->z = 7.5;
entity->vel_z = -1;
entity->yaw = (rand() % 360) * PI / 180.0;
entity->particleDuration = 10 + rand() % 30;
entity->behavior = &actParticleDot;
entity->flags[PASSABLE] = true;
entity->flags[NOUPDATE] = true;
entity->flags[UNCLICKABLE] = true;
if ( multiplayer != CLIENT )
{
entity_uids--;
}
entity->setUID(-3);
}
}
// fire once off.
else if ( my->particleTimerCountdownAction == PARTICLE_TIMER_ACTION_SPAWN_PORTAL )
{
Entity* parent = uidToEntity(my->parent);
if ( parent && my->particleTimerCountdownAction < 100 )
{
playSoundEntityLocal(parent, 167, 128);
createParticleDot(parent);
createParticleCircling(parent, 100, my->particleTimerCountdownSprite);
my->particleTimerCountdownAction = 0;
}
}
// fire once off.
else if ( my->particleTimerCountdownAction == PARTICLE_TIMER_ACTION_SUMMON_MONSTER )
{
if ( my->particleTimerCountdownAction < 100 )
{
my->light = lightSphereShadow(my->x / 16, my->y / 16, 5, 92);
playSoundEntityLocal(my, 167, 128);
createParticleDropRising(my, 680, 1.0);
createParticleCircling(my, 70, my->particleTimerCountdownSprite);
my->particleTimerCountdownAction = 0;
}
}
// fire once off.
else if ( my->particleTimerCountdownAction == PARTICLE_TIMER_ACTION_DEVIL_SUMMON_MONSTER )
{
if ( my->particleTimerCountdownAction < 100 )
{
my->light = lightSphereShadow(my->x / 16, my->y / 16, 5, 92);
playSoundEntityLocal(my, 167, 128);
createParticleDropRising(my, 593, 1.0);
createParticleCircling(my, 70, my->particleTimerCountdownSprite);
my->particleTimerCountdownAction = 0;
}
}
// continually fire
else if ( my->particleTimerCountdownAction == PARTICLE_TIMER_ACTION_SPELL_SUMMON )
{
if ( multiplayer != CLIENT && my->particleTimerPreDelay != -100 )
{
// once-off hack :)
spawnExplosion(my->x, my->y, -1);
playSoundEntity(my, 171, 128);
my->particleTimerPreDelay = -100;
createParticleErupt(my, my->particleTimerCountdownSprite);
serverSpawnMiscParticles(my, PARTICLE_EFFECT_ERUPT, my->particleTimerCountdownSprite);
}
}
// fire once off.
else if ( my->particleTimerCountdownAction == PARTICLE_EFFECT_TELEPORT_PULL_TARGET_LOCATION )
{
createParticleDropRising(my, my->particleTimerCountdownSprite, 1.0);
my->particleTimerCountdownAction = 0;
}
}
else
{
--my->particleTimerPreDelay;
}
}
}
void actParticleSap(Entity* my)
{
real_t decel = 0.9;
real_t accel = 0.9;
real_t z_accel = accel;
real_t z_decel = decel;
real_t minSpeed = 0.05;
if ( PARTICLE_LIFE < 0 )
{
list_RemoveNode(my->mynode);
return;
}
else
{
if ( my->sprite == 977 ) // boomerang
{
if ( my->skill[3] == 1 )
{
// specific for the animation I want...
// magic numbers that take approximately 75 frames (50% of travel time) to go outward or inward.
// acceleration is a little faster to overshoot into the right hand side.
decel = 0.9718;
accel = 0.9710;
z_decel = decel;
z_accel = z_decel;
}
else
{
decel = 0.95;
accel = 0.949;
z_decel = 0.9935;
z_accel = z_decel;
}
Entity* particle = spawnMagicParticleCustom(my, (rand() % 2) ? 943 : 979, 1, 10);
if ( particle )
{
particle->focalx = 2;
particle->focaly = -2;
particle->focalz = 2.5;
}
if ( PARTICLE_LIFE < 100 && my->ticks % 6 == 0 )
{
if ( PARTICLE_LIFE < 70 )
{
playSoundEntityLocal(my, 434 + rand() % 10, 64);
}
else
{
playSoundEntityLocal(my, 434 + rand() % 10, 32);
}
}
//particle->flags[SPRITE] = true;
}
else
{
spawnMagicParticle(my);
}
Entity* parent = uidToEntity(my->parent);
if ( parent )
{
my->x = parent->x + my->fskill[0];
my->y = parent->y + my->fskill[1];
}
else
{
list_RemoveNode(my->mynode);
return;
}
if ( my->skill[1] == 0 )
{
// move outwards diagonally.
if ( abs(my->vel_z) > minSpeed )
{
my->fskill[0] += my->vel_x;
my->fskill[1] += my->vel_y;
my->vel_x *= decel;
my->vel_y *= decel;
my->z += my->vel_z;
my->vel_z *= z_decel;
my->yaw += my->fskill[2];
my->pitch += my->fskill[3];
}
else
{
my->skill[1] = 1;
my->vel_x *= -1;
my->vel_y *= -1;
my->vel_z *= -1;
}
}
else if ( my->skill[1] == 1 )
{
// move inwards diagonally.
if ( (abs(my->vel_z) < 0.08 && my->skill[3] == 0) || (abs(my->vel_z) < 0.4 && my->skill[3] == 1) )
{
my->fskill[0] += my->vel_x;
my->fskill[1] += my->vel_y;
my->vel_x /= accel;
my->vel_y /= accel;
my->z += my->vel_z;
my->vel_z /= z_accel;
my->yaw += my->fskill[2];
my->pitch += my->fskill[3];
}
else
{
// movement completed.
my->skill[1] = 2;
}
}
my->scalex *= 0.99;
my->scaley *= 0.99;
my->scalez *= 0.99;
if ( my->sprite == 977 )
{
my->scalex = 1.f;
my->scaley = 1.f;
my->scalez = 1.f;
my->roll -= 0.5;
my->pitch = std::max(my->pitch - 0.015, 0.0);
}
--PARTICLE_LIFE;
}
}
void actParticleSapCenter(Entity* my)
{
// init
if ( my->skill[3] == 0 )
{
// for clients and server spawn the visible arcing particles.
my->skill[3] = 1;
createParticleSap(my);
}
if ( multiplayer == CLIENT )
{
return;
}
Entity* parent = uidToEntity(my->parent);
if ( parent )
{
// if reached the caster, delete self and spawn some particles.
if ( my->sprite == 977 && PARTICLE_LIFE > 1 )
{
// store these in case parent dies.
// boomerang doesn't check for collision until end of life.
my->fskill[4] = parent->x;
my->fskill[5] = parent->y;
}
else if ( entityInsideEntity(my, parent) || (my->sprite == 977 && PARTICLE_LIFE == 0) )
{
if ( my->skill[6] == SPELL_STEAL_WEAPON )
{
if ( my->skill[7] == 1 )
{
// found stolen item.
Item* item = newItemFromEntity(my);
if ( parent->behavior == &actPlayer )
{
itemPickup(parent->skill[2], item);
}
else if ( parent->behavior == &actMonster )
{
parent->addItemToMonsterInventory(item);
Stat *myStats = parent->getStats();
if ( myStats )
{
node_t* weaponNode = itemNodeInInventory(myStats, static_cast<ItemType>(-1), WEAPON);
if ( weaponNode )
{
swapMonsterWeaponWithInventoryItem(parent, myStats, weaponNode, false, true);
if ( myStats->type == INCUBUS )
{
parent->monsterSpecialState = INCUBUS_TELEPORT_STEAL;
parent->monsterSpecialTimer = 100 + rand() % MONSTER_SPECIAL_COOLDOWN_INCUBUS_TELEPORT_RANDOM;
}
}
}
}
item = nullptr;
}
playSoundEntity(parent, 168, 128);
spawnMagicEffectParticles(parent->x, parent->y, parent->z, my->skill[5]);
}
else if ( my->skill[6] == SPELL_DRAIN_SOUL )
{
parent->modHP(my->skill[7]);
parent->modMP(my->skill[8]);
if ( parent->behavior == &actPlayer )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 0, 255, 0);
messagePlayerColor(parent->skill[2], color, language[2445]);
}
playSoundEntity(parent, 168, 128);
spawnMagicEffectParticles(parent->x, parent->y, parent->z, 169);
}
else if ( my->skill[6] == SHADOW_SPELLCAST )
{
parent->shadowSpecialAbility(parent->monsterShadowInitialMimic);
playSoundEntity(parent, 166, 128);
spawnMagicEffectParticles(parent->x, parent->y, parent->z, my->skill[5]);
}
else if ( my->skill[6] == SPELL_SUMMON )
{
parent->modMP(my->skill[7]);
/*if ( parent->behavior == &actPlayer )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 0, 255, 0);
messagePlayerColor(parent->skill[2], color, language[774]);
}*/
playSoundEntity(parent, 168, 128);
spawnMagicEffectParticles(parent->x, parent->y, parent->z, 169);
}
else if ( my->skill[6] == SPELL_FEAR )
{
playSoundEntity(parent, 168, 128);
spawnMagicEffectParticles(parent->x, parent->y, parent->z, 174);
Entity* caster = uidToEntity(my->skill[7]);
if ( caster )
{
spellEffectFear(nullptr, spellElement_fear, caster, parent, 0);
}
}
else if ( my->sprite == 977 ) // boomerang
{
Item* item = newItemFromEntity(my);
if ( parent->behavior == &actPlayer )
{
item->ownerUid = parent->getUID();
Item* pickedUp = itemPickup(parent->skill[2], item);
Uint32 color = SDL_MapRGB(mainsurface->format, 0, 255, 0);
messagePlayerColor(parent->skill[2], color, language[3746], items[item->type].name_unidentified);
achievementObserver.awardAchievementIfActive(parent->skill[2], parent, AchievementObserver::BARONY_ACH_IF_YOU_LOVE_SOMETHING);
if ( pickedUp )
{
if ( parent->skill[2] == 0 || (parent->skill[2] > 0 && splitscreen) )
{
// pickedUp is the new inventory stack for server, free the original items
free(item);
item = nullptr;
if ( multiplayer != CLIENT && !stats[parent->skill[2]]->weapon )
{
useItem(pickedUp, parent->skill[2]);
}
auto& hotbar_t = players[parent->skill[2]]->hotbar;
if ( hotbar_t.magicBoomerangHotbarSlot >= 0 )
{
auto& hotbar = hotbar_t.slots();
hotbar[hotbar_t.magicBoomerangHotbarSlot].item = pickedUp->uid;
for ( int i = 0; i < NUM_HOTBAR_SLOTS; ++i )
{
if ( i != hotbar_t.magicBoomerangHotbarSlot
&& hotbar[i].item == pickedUp->uid )
{
hotbar[i].item = 0;
}
}
}
}
else
{
free(pickedUp); // item is the picked up items (item == pickedUp)
}
}
}
else if ( parent->behavior == &actMonster )
{
parent->addItemToMonsterInventory(item);
Stat *myStats = parent->getStats();
if ( myStats )
{
node_t* weaponNode = itemNodeInInventory(myStats, static_cast<ItemType>(-1), WEAPON);
if ( weaponNode )
{
swapMonsterWeaponWithInventoryItem(parent, myStats, weaponNode, false, true);
}
}
}
playSoundEntity(parent, 431 + rand() % 3, 92);
item = nullptr;
}
list_RemoveNode(my->mynode);
return;
}
// calculate direction to caster and move.
real_t tangent = atan2(parent->y - my->y, parent->x - my->x);
real_t dist = sqrt(pow(my->x - parent->x, 2) + pow(my->y - parent->y, 2));
real_t speed = dist / std::max(PARTICLE_LIFE, 1);
my->vel_x = speed * cos(tangent);
my->vel_y = speed * sin(tangent);
my->x += my->vel_x;
my->y += my->vel_y;
}
else
{
if ( my->skill[6] == SPELL_SUMMON )
{
real_t dist = sqrt(pow(my->x - my->skill[8], 2) + pow(my->y - my->skill[9], 2));
if ( dist < 4 )
{
spawnMagicEffectParticles(my->skill[8], my->skill[9], 0, my->skill[5]);
Entity* caster = uidToEntity(my->skill[7]);
if ( caster && caster->behavior == &actPlayer && stats[caster->skill[2]] )
{
// kill old summons.
for ( node_t* node = stats[caster->skill[2]]->FOLLOWERS.first; node != nullptr; node = node->next )
{
Entity* follower = nullptr;
if ( (Uint32*)(node)->element )
{
follower = uidToEntity(*((Uint32*)(node)->element));
}
if ( follower && follower->monsterAllySummonRank != 0 )
{
Stat* followerStats = follower->getStats();
if ( followerStats && followerStats->HP > 0 )
{
follower->setMP(followerStats->MAXMP * (followerStats->HP / static_cast<float>(followerStats->MAXHP)));
follower->setHP(0);
}
}
}
Monster creature = SKELETON;
Entity* monster = summonMonster(creature, my->skill[8], my->skill[9]);
if ( monster )
{
Stat* monsterStats = monster->getStats();
monster->yaw = my->yaw - PI;
if ( monsterStats )
{
int magicLevel = 1;
magicLevel = std::min(7, 1 + (stats[caster->skill[2]]->playerSummonLVLHP >> 16) / 5);
monster->monsterAllySummonRank = magicLevel;
strcpy(monsterStats->name, "skeleton knight");
forceFollower(*caster, *monster);
monster->setEffect(EFF_STUNNED, true, 20, false);
bool spawnSecondAlly = false;
if ( (caster->getINT() + stats[caster->skill[2]]->PROFICIENCIES[PRO_MAGIC]) >= SKILL_LEVEL_EXPERT )
{
spawnSecondAlly = true;
}
//parent->increaseSkill(PRO_LEADERSHIP);
monster->monsterAllyIndex = caster->skill[2];
if ( multiplayer == SERVER )
{
serverUpdateEntitySkill(monster, 42); // update monsterAllyIndex for clients.
}
// change the color of the hit entity.
monster->flags[USERFLAG2] = true;
serverUpdateEntityFlag(monster, USERFLAG2);
if ( monsterChangesColorWhenAlly(monsterStats) )
{
int bodypart = 0;
for ( node_t* node = (monster)->children.first; node != nullptr; node = node->next )
{
if ( bodypart >= LIMB_HUMANOID_TORSO )
{
Entity* tmp = (Entity*)node->element;
if ( tmp )
{
tmp->flags[USERFLAG2] = true;
serverUpdateEntityFlag(tmp, USERFLAG2);
}
}
++bodypart;
}
}
if ( spawnSecondAlly )
{
Entity* monster = summonMonster(creature, my->skill[8], my->skill[9]);
if ( monster )
{
if ( multiplayer != CLIENT )
{
spawnExplosion(monster->x, monster->y, -1);
playSoundEntity(monster, 171, 128);
createParticleErupt(monster, 791);
serverSpawnMiscParticles(monster, PARTICLE_EFFECT_ERUPT, 791);
}
Stat* monsterStats = monster->getStats();
monster->yaw = my->yaw - PI;
if ( monsterStats )
{
strcpy(monsterStats->name, "skeleton sentinel");
magicLevel = 1;
if ( stats[caster->skill[2]] )
{
magicLevel = std::min(7, 1 + (stats[caster->skill[2]]->playerSummon2LVLHP >> 16) / 5);
}
monster->monsterAllySummonRank = magicLevel;
forceFollower(*caster, *monster);
monster->setEffect(EFF_STUNNED, true, 20, false);
monster->monsterAllyIndex = caster->skill[2];
if ( multiplayer == SERVER )
{
serverUpdateEntitySkill(monster, 42); // update monsterAllyIndex for clients.
}
if ( caster && caster->behavior == &actPlayer )
{
steamAchievementClient(caster->skill[2], "BARONY_ACH_SKELETON_CREW");
}
// change the color of the hit entity.
monster->flags[USERFLAG2] = true;
serverUpdateEntityFlag(monster, USERFLAG2);
if ( monsterChangesColorWhenAlly(monsterStats) )
{
int bodypart = 0;
for ( node_t* node = (monster)->children.first; node != nullptr; node = node->next )
{
if ( bodypart >= LIMB_HUMANOID_TORSO )
{
Entity* tmp = (Entity*)node->element;
if ( tmp )
{
tmp->flags[USERFLAG2] = true;
serverUpdateEntityFlag(tmp, USERFLAG2);
}
}
++bodypart;
}
}
}
}
}
}
}
}
list_RemoveNode(my->mynode);
return;
}
// calculate direction to caster and move.
real_t tangent = atan2(my->skill[9] - my->y, my->skill[8] - my->x);
real_t speed = dist / PARTICLE_LIFE;
my->vel_x = speed * cos(tangent);
my->vel_y = speed * sin(tangent);
my->x += my->vel_x;
my->y += my->vel_y;
}
else if ( my->skill[6] == SPELL_STEAL_WEAPON )
{
Entity* entity = newEntity(-1, 1, map.entities, nullptr); //Item entity.
entity->flags[INVISIBLE] = true;
entity->flags[UPDATENEEDED] = true;
entity->x = my->x;
entity->y = my->y;
entity->sizex = 4;
entity->sizey = 4;
entity->yaw = my->yaw;
entity->vel_x = (rand() % 20 - 10) / 10.0;
entity->vel_y = (rand() % 20 - 10) / 10.0;
entity->vel_z = -.5;
entity->flags[PASSABLE] = true;
entity->flags[USERFLAG1] = true; // speeds up game when many items are dropped
entity->behavior = &actItem;
entity->skill[10] = my->skill[10];
entity->skill[11] = my->skill[11];
entity->skill[12] = my->skill[12];
entity->skill[13] = my->skill[13];
entity->skill[14] = my->skill[14];
entity->skill[15] = my->skill[15];
entity->itemOriginalOwner = my->itemOriginalOwner;
entity->parent = 0;
// no parent, no target to travel to.
list_RemoveNode(my->mynode);
return;
}
else if ( my->sprite == 977 )
{
// calculate direction to caster and move.
real_t tangent = atan2(my->fskill[5] - my->y, my->fskill[4] - my->x);
real_t dist = sqrt(pow(my->x - my->fskill[4], 2) + pow(my->y - my->fskill[5], 2));
real_t speed = dist / std::max(PARTICLE_LIFE, 1);
if ( dist < 4 || (abs(my->fskill[5]) < 0.001 && abs(my->fskill[4]) < 0.001) )
{
// reached goal, or goal not set then spawn the item.
Entity* entity = newEntity(-1, 1, map.entities, nullptr); //Item entity.
entity->flags[INVISIBLE] = true;
entity->flags[UPDATENEEDED] = true;
entity->x = my->x;
entity->y = my->y;
entity->sizex = 4;
entity->sizey = 4;
entity->yaw = my->yaw;
entity->vel_x = (rand() % 20 - 10) / 10.0;
entity->vel_y = (rand() % 20 - 10) / 10.0;
entity->vel_z = -.5;
entity->flags[PASSABLE] = true;
entity->flags[USERFLAG1] = true; // speeds up game when many items are dropped
entity->behavior = &actItem;
entity->skill[10] = my->skill[10];
entity->skill[11] = my->skill[11];
entity->skill[12] = my->skill[12];
entity->skill[13] = my->skill[13];
entity->skill[14] = my->skill[14];
entity->skill[15] = my->skill[15];
entity->itemOriginalOwner = 0;
entity->parent = 0;
list_RemoveNode(my->mynode);
return;
}
my->vel_x = speed * cos(tangent);
my->vel_y = speed * sin(tangent);
my->x += my->vel_x;
my->y += my->vel_y;
}
else
{
// no parent, no target to travel to.
list_RemoveNode(my->mynode);
return;
}
}
if ( PARTICLE_LIFE < 0 )
{
list_RemoveNode(my->mynode);
return;
}
else
{
--PARTICLE_LIFE;
}
}
void createParticleExplosionCharge(Entity* parent, int sprite, int particleCount, double scale)
{
if ( !parent )
{
return;
}
for ( int c = 0; c < particleCount; c++ )
{
// shoot drops to the sky
Entity* entity = newEntity(sprite, 1, map.entities, nullptr); //Particle entity.
entity->sizex = 1;
entity->sizey = 1;
entity->x = parent->x - 3 + rand() % 7;
entity->y = parent->y - 3 + rand() % 7;
entity->z = 0 + rand() % 190;
if ( parent && parent->behavior == &actPlayer )
{
entity->z /= 2;
}
entity->vel_z = -1;
entity->yaw = (rand() % 360) * PI / 180.0;
entity->particleDuration = entity->z + 10;
/*if ( rand() % 5 > 0 )
{
entity->vel_x = 0.5*cos(entity->yaw);
entity->vel_y = 0.5*sin(entity->yaw);
entity->particleDuration = 6;
entity->z = 0;
entity->vel_z = 0.5 *(-1 + rand() % 3);
}*/
entity->scalex *= scale;
entity->scaley *= scale;
entity->scalez *= scale;
entity->behavior = &actParticleExplosionCharge;
entity->flags[PASSABLE] = true;
entity->flags[NOUPDATE] = true;
entity->flags[UNCLICKABLE] = true;
entity->parent = parent->getUID();
if ( multiplayer != CLIENT )
{
entity_uids--;
}
entity->setUID(-3);
}
int radius = STRIKERANGE * 2 / 3;
real_t arc = PI / 16;
int randScale = 1;
for ( int c = 0; c < 128; c++ )
{
// shoot drops to the sky
Entity* entity = newEntity(670, 1, map.entities, nullptr); //Particle entity.
entity->sizex = 1;
entity->sizey = 1;
entity->yaw = 0 + c * arc;
entity->x = parent->x + (radius * cos(entity->yaw));// - 2 + rand() % 5;
entity->y = parent->y + (radius * sin(entity->yaw));// - 2 + rand() % 5;
entity->z = radius + 150;
entity->particleDuration = entity->z + rand() % 3;
entity->vel_z = -1;
if ( parent && parent->behavior == &actPlayer )
{
entity->z /= 2;
}
randScale = 1 + rand() % 3;
entity->scalex *= (scale / randScale);
entity->scaley *= (scale / randScale);
entity->scalez *= (scale / randScale);
entity->behavior = &actParticleExplosionCharge;
entity->flags[PASSABLE] = true;
entity->flags[NOUPDATE] = true;
entity->flags[UNCLICKABLE] = true;
entity->parent = parent->getUID();
if ( multiplayer != CLIENT )
{
entity_uids--;
}
entity->setUID(-3);
if ( c > 0 && c % 16 == 0 )
{
radius -= 2;
}
}
}
void actParticleExplosionCharge(Entity* my)
{
if ( PARTICLE_LIFE < 0 || (my->z < -4 && rand() % 4 == 0) || (ticks % 14 == 0 && uidToEntity(my->parent) == nullptr) )
{
list_RemoveNode(my->mynode);
}
else
{
--PARTICLE_LIFE;
my->yaw += 0.1;
my->x += my->vel_x;
my->y += my->vel_y;
my->z += my->vel_z;
my->scalex /= 0.99;
my->scaley /= 0.99;
my->scalez /= 0.99;
//my->z -= 0.01;
}
return;
}
bool Entity::magicFallingCollision()
{
hit.entity = nullptr;
if ( z <= -5 || fabs(vel_z) < 0.01 )
{
// check if particle stopped or too high.
return false;
}
if ( z >= 7.5 )
{
return true;
}
if ( actmagicIsVertical == MAGIC_ISVERTICAL_Z )
{
std::vector<list_t*> entLists = TileEntityList.getEntitiesWithinRadiusAroundEntity(this, 1);
for ( std::vector<list_t*>::iterator it = entLists.begin(); it != entLists.end(); ++it )
{
list_t* currentList = *it;
node_t* node;
for ( node = currentList->first; node != nullptr; node = node->next )
{
Entity* entity = (Entity*)node->element;
if ( entity )
{
if ( entity == this )
{
continue;
}
if ( entityInsideEntity(this, entity) && !entity->flags[PASSABLE] && (entity->getUID() != this->parent) )
{
hit.entity = entity;
//hit.side = HORIZONTAL;
return true;
}
}
}
}
}
return false;
}
bool Entity::magicOrbitingCollision()
{
hit.entity = nullptr;
if ( this->actmagicIsOrbiting == 2 )
{
if ( this->ticks == 5 && this->actmagicOrbitHitTargetUID4 != 0 )
{
// hit this target automatically
Entity* tmp = uidToEntity(actmagicOrbitHitTargetUID4);
if ( tmp )
{
hit.entity = tmp;
return true;
}
}
if ( this->z < -8 || this->z > 3 )
{
return false;
}
else if ( this->ticks >= 12 && this->ticks % 4 != 0 ) // check once every 4 ticks, after the missile is alive for a bit
{
return false;
}
}
else if ( this->z < -10 )
{
return false;
}
if ( this->actmagicIsOrbiting == 2 )
{
if ( this->actmagicOrbitStationaryHitTarget >= 3 )
{
return false;
}
}
Entity* caster = uidToEntity(parent);
std::vector<list_t*> entLists = TileEntityList.getEntitiesWithinRadiusAroundEntity(this, 1);
for ( std::vector<list_t*>::iterator it = entLists.begin(); it != entLists.end(); ++it )
{
list_t* currentList = *it;
node_t* node;
for ( node = currentList->first; node != NULL; node = node->next )
{
Entity* entity = (Entity*)node->element;
if ( entity == this )
{
continue;
}
if ( entity->behavior != &actMonster
&& entity->behavior != &actPlayer
&& entity->behavior != &actDoor
&& entity->behavior != &::actChest
&& entity->behavior != &::actFurniture )
{
continue;
}
if ( caster && !(svFlags & SV_FLAG_FRIENDLYFIRE) && caster->checkFriend(entity) )
{
continue;
}
if ( actmagicIsOrbiting == 2 )
{
if ( static_cast<Uint32>(actmagicOrbitHitTargetUID1) == entity->getUID()
|| static_cast<Uint32>(actmagicOrbitHitTargetUID2) == entity->getUID()
|| static_cast<Uint32>(actmagicOrbitHitTargetUID3) == entity->getUID()
|| static_cast<Uint32>(actmagicOrbitHitTargetUID4) == entity->getUID() )
{
// we already hit these guys.
continue;
}
}
if ( entityInsideEntity(this, entity) && !entity->flags[PASSABLE] && (entity->getUID() != this->parent) )
{
hit.entity = entity;
if ( hit.entity->behavior == &actMonster || hit.entity->behavior == &actPlayer )
{
if ( actmagicIsOrbiting == 2 )
{
if ( actmagicOrbitHitTargetUID4 != 0 && caster && caster->behavior == &actPlayer )
{
if ( actmagicOrbitHitTargetUID1 == 0
&& actmagicOrbitHitTargetUID2 == 0
&& actmagicOrbitHitTargetUID3 == 0
&& hit.entity->behavior == &actMonster )
{
steamStatisticUpdateClient(caster->skill[2], STEAM_STAT_VOLATILE, STEAM_STAT_INT, 1);
}
}
++actmagicOrbitStationaryHitTarget;
if ( actmagicOrbitHitTargetUID1 == 0 )
{
actmagicOrbitHitTargetUID1 = entity->getUID();
}
else if ( actmagicOrbitHitTargetUID2 == 0 )
{
actmagicOrbitHitTargetUID2 = entity->getUID();
}
else if ( actmagicOrbitHitTargetUID3 == 0 )
{
actmagicOrbitHitTargetUID3 = entity->getUID();
}
}
}
return true;
}
}
}
return false;
}
void Entity::castFallingMagicMissile(int spellID, real_t distFromCaster, real_t angleFromCasterDirection, int heightDelay)
{
spell_t* spell = getSpellFromID(spellID);
Entity* entity = castSpell(getUID(), spell, false, true);
if ( entity )
{
entity->x = x + distFromCaster * cos(yaw + angleFromCasterDirection);
entity->y = y + distFromCaster * sin(yaw + angleFromCasterDirection);
entity->z = -25 - heightDelay;
double missile_speed = 4 * ((double)(((spellElement_t*)(spell->elements.first->element))->mana)
/ ((spellElement_t*)(spell->elements.first->element))->overload_multiplier);
entity->vel_x = 0.0;
entity->vel_y = 0.0;
entity->vel_z = 0.5 * (missile_speed);
entity->pitch = PI / 2;
entity->actmagicIsVertical = MAGIC_ISVERTICAL_Z;
spawnMagicEffectParticles(entity->x, entity->y, 0, 174);
playSoundEntity(entity, spellGetCastSound(spell), 128);
}
}
Entity* Entity::castOrbitingMagicMissile(int spellID, real_t distFromCaster, real_t angleFromCasterDirection, int duration)
{
spell_t* spell = getSpellFromID(spellID);
Entity* entity = castSpell(getUID(), spell, false, true);
if ( entity )
{
if ( spellID == SPELL_FIREBALL )
{
entity->sprite = 671;
}
else if ( spellID == SPELL_MAGICMISSILE )
{
entity->sprite = 679;
}
entity->yaw = angleFromCasterDirection;
entity->x = x + distFromCaster * cos(yaw + entity->yaw);
entity->y = y + distFromCaster * sin(yaw + entity->yaw);
entity->z = -2.5;
double missile_speed = 4 * ((double)(((spellElement_t*)(spell->elements.first->element))->mana)
/ ((spellElement_t*)(spell->elements.first->element))->overload_multiplier);
entity->vel_x = 0.0;
entity->vel_y = 0.0;
entity->actmagicIsOrbiting = 1;
entity->actmagicOrbitDist = distFromCaster;
entity->actmagicOrbitStartZ = entity->z;
entity->z += 4 * sin(angleFromCasterDirection);
entity->roll += (PI / 8) * (1 - abs(sin(angleFromCasterDirection)));
entity->actmagicOrbitVerticalSpeed = 0.1;
entity->actmagicOrbitVerticalDirection = 1;
entity->actmagicOrbitLifetime = duration;
entity->vel_z = entity->actmagicOrbitVerticalSpeed;
playSoundEntity(entity, spellGetCastSound(spell), 128);
//spawnMagicEffectParticles(entity->x, entity->y, 0, 174);
}
return entity;
}
Entity* castStationaryOrbitingMagicMissile(Entity* parent, int spellID, real_t centerx, real_t centery,
real_t distFromCenter, real_t angleFromCenterDirection, int duration)
{
spell_t* spell = getSpellFromID(spellID);
if ( !parent )
{
Entity* entity = newEntity(-1, 1, map.entities, nullptr); //Particle entity.
entity->sizex = 1;
entity->sizey = 1;
entity->x = centerx;
entity->y = centery;
entity->z = 15;
entity->vel_z = 0;
//entity->yaw = (rand() % 360) * PI / 180.0;
entity->skill[0] = 100;
entity->skill[1] = 10;
entity->behavior = &actParticleDot;
entity->flags[PASSABLE] = true;
entity->flags[NOUPDATE] = true;
entity->flags[UNCLICKABLE] = true;
entity->flags[INVISIBLE] = true;
parent = entity;
}
Stat* stats = parent->getStats();
bool amplify = false;
if ( stats )
{
amplify = stats->EFFECTS[EFF_MAGICAMPLIFY];
stats->EFFECTS[EFF_MAGICAMPLIFY] = false; // temporary skip amplify effects otherwise recursion.
}
Entity* entity = castSpell(parent->getUID(), spell, false, true);
if ( stats )
{
stats->EFFECTS[EFF_MAGICAMPLIFY] = amplify;
}
if ( entity )
{
if ( spellID == SPELL_FIREBALL )
{
entity->sprite = 671;
}
else if ( spellID == SPELL_COLD )
{
entity->sprite = 797;
}
else if ( spellID == SPELL_LIGHTNING )
{
entity->sprite = 798;
}
else if ( spellID == SPELL_MAGICMISSILE )
{
entity->sprite = 679;
}
entity->yaw = angleFromCenterDirection;
entity->x = centerx;
entity->y = centery;
entity->z = 4;
double missile_speed = 4 * ((double)(((spellElement_t*)(spell->elements.first->element))->mana)
/ ((spellElement_t*)(spell->elements.first->element))->overload_multiplier);
entity->vel_x = 0.0;
entity->vel_y = 0.0;
entity->actmagicIsOrbiting = 2;
entity->actmagicOrbitDist = distFromCenter;
entity->actmagicOrbitStationaryCurrentDist = 0.0;
entity->actmagicOrbitStartZ = entity->z;
//entity->roll -= (PI / 8);
entity->actmagicOrbitVerticalSpeed = -0.3;
entity->actmagicOrbitVerticalDirection = 1;
entity->actmagicOrbitLifetime = duration;
entity->actmagicOrbitStationaryX = centerx;
entity->actmagicOrbitStationaryY = centery;
entity->vel_z = -0.1;
playSoundEntity(entity, spellGetCastSound(spell), 128);
//spawnMagicEffectParticles(entity->x, entity->y, 0, 174);
}
return entity;
}
void createParticleFollowerCommand(real_t x, real_t y, real_t z, int sprite)
{
Entity* entity = newEntity(sprite, 1, map.entities, nullptr); //Particle entity.
//entity->sizex = 1;
//entity->sizey = 1;
entity->x = x;
entity->y = y;
entity->z = 7.5;
entity->vel_z = -0.8;
//entity->yaw = (rand() % 360) * PI / 180.0;
entity->skill[0] = 50;
entity->behavior = &actParticleFollowerCommand;
entity->flags[PASSABLE] = true;
entity->flags[NOUPDATE] = true;
entity->flags[UNCLICKABLE] = true;
if ( multiplayer != CLIENT )
{
entity_uids--;
}
entity->setUID(-3);
// boosty boost
for ( int c = 0; c < 10; c++ )
{
entity = newEntity(sprite, 1, map.entities, nullptr); //Particle entity.
entity->x = x - 4 + rand() % 9;
entity->y = y - 4 + rand() % 9;
entity->z = z - 0 + rand() % 11;
entity->scalex = 0.7;
entity->scaley = 0.7;
entity->scalez = 0.7;
entity->sizex = 1;
entity->sizey = 1;
entity->yaw = (rand() % 360) * PI / 180.f;
entity->flags[PASSABLE] = true;
entity->flags[BRIGHT] = true;
entity->flags[NOUPDATE] = true;
entity->flags[UNCLICKABLE] = true;
entity->behavior = &actMagicParticle;
entity->vel_z = -1;
if ( multiplayer != CLIENT )
{
entity_uids--;
}
entity->setUID(-3);
}
}
void actParticleFollowerCommand(Entity* my)
{
if ( PARTICLE_LIFE < 0 )
{
list_RemoveNode(my->mynode);
return;
}
else
{
--PARTICLE_LIFE;
my->z += my->vel_z;
my->yaw += my->vel_z * 2;
if ( my->z < -3 )
{
my->vel_z *= 0.9;
}
}
}
void actParticleShadowTag(Entity* my)
{
if ( PARTICLE_LIFE < 0 )
{
// once off, fire some erupt dot particles at end of life.
real_t yaw = 0;
int numParticles = 8;
for ( int c = 0; c < 8; c++ )
{
Entity* entity = newEntity(871, 1, map.entities, nullptr); //Particle entity.
entity->sizex = 1;
entity->sizey = 1;
entity->x = my->x;
entity->y = my->y;
entity->z = -10 + my->fskill[0];
entity->yaw = yaw;
entity->vel_x = 0.2;
entity->vel_y = 0.2;
entity->vel_z = -0.02;
entity->skill[0] = 100;
entity->skill[1] = 0; // direction.
entity->fskill[0] = 0.1;
entity->behavior = &actParticleErupt;
entity->flags[PASSABLE] = true;
entity->flags[NOUPDATE] = true;
entity->flags[UNCLICKABLE] = true;
if ( multiplayer != CLIENT )
{
entity_uids--;
}
entity->setUID(-3);
yaw += 2 * PI / numParticles;
}
if ( multiplayer != CLIENT )
{
Uint32 casterUid = static_cast<Uint32>(my->skill[2]);
Entity* caster = uidToEntity(casterUid);
Entity* parent = uidToEntity(my->parent);
if ( caster && caster->behavior == &actPlayer
&& parent )
{
// caster is alive, notify they lost their mark
Uint32 color = SDL_MapRGB(mainsurface->format, 255, 255, 255);
if ( parent->getStats() )
{
messagePlayerMonsterEvent(caster->skill[2], color, *(parent->getStats()), language[3466], language[3467], MSG_COMBAT);
parent->setEffect(EFF_SHADOW_TAGGED, false, 0, true);
}
}
}
my->removeLightField();
list_RemoveNode(my->mynode);
return;
}
else
{
--PARTICLE_LIFE;
my->removeLightField();
my->light = lightSphereShadow(my->x / 16, my->y / 16, 3, 92);
Entity* parent = uidToEntity(my->parent);
if ( parent )
{
my->x = parent->x;
my->y = parent->y;
}
if ( my->skill[1] >= 50 ) // stop changing size
{
real_t maxspeed = .03;
real_t acceleration = 0.95;
if ( my->skill[3] == 0 )
{
// once off, store the normal height of the particle.
my->skill[3] = 1;
my->vel_z = -maxspeed;
}
if ( my->skill[1] % 5 == 0 )
{
Uint32 casterUid = static_cast<Uint32>(my->skill[2]);
Entity* caster = uidToEntity(casterUid);
if ( caster && caster->creatureShadowTaggedThisUid == my->parent && parent )
{
// caster is alive, and they have still marked the parent this particle is following.
}
else
{
PARTICLE_LIFE = 0;
}
}
if ( PARTICLE_LIFE > 0 && PARTICLE_LIFE < TICKS_PER_SECOND )
{
if ( parent && parent->getStats() && parent->getStats()->EFFECTS[EFF_SHADOW_TAGGED] )
{
++PARTICLE_LIFE;
}
}
// bob up and down movement.
if ( my->skill[3] == 1 )
{
my->vel_z *= acceleration;
if ( my->vel_z > -0.005 )
{
my->skill[3] = 2;
my->vel_z = -0.005;
}
my->z += my->vel_z;
}
else if ( my->skill[3] == 2 )
{
my->vel_z /= acceleration;
if ( my->vel_z < -maxspeed )
{
my->skill[3] = 3;
my->vel_z = -maxspeed;
}
my->z -= my->vel_z;
}
else if ( my->skill[3] == 3 )
{
my->vel_z *= acceleration;
if ( my->vel_z > -0.005 )
{
my->skill[3] = 4;
my->vel_z = -0.005;
}
my->z -= my->vel_z;
}
else if ( my->skill[3] == 4 )
{
my->vel_z /= acceleration;
if ( my->vel_z < -maxspeed )
{
my->skill[3] = 1;
my->vel_z = -maxspeed;
}
my->z += my->vel_z;
}
my->yaw += 0.01;
}
else
{
my->z += my->vel_z;
my->yaw += my->vel_z * 2;
if ( my->scalex < 0.5 )
{
my->scalex += 0.02;
}
else
{
my->scalex = 0.5;
}
my->scaley = my->scalex;
my->scalez = my->scalex;
if ( my->z < -3 + my->fskill[0] )
{
my->vel_z *= 0.9;
}
}
// once off, fire some erupt dot particles at start.
if ( my->skill[1] == 0 )
{
real_t yaw = 0;
int numParticles = 8;
for ( int c = 0; c < 8; c++ )
{
Entity* entity = newEntity(871, 1, map.entities, nullptr); //Particle entity.
entity->sizex = 1;
entity->sizey = 1;
entity->x = my->x;
entity->y = my->y;
entity->z = -10 + my->fskill[0];
entity->yaw = yaw;
entity->vel_x = 0.2;
entity->vel_y = 0.2;
entity->vel_z = -0.02;
entity->skill[0] = 100;
entity->skill[1] = 0; // direction.
entity->fskill[0] = 0.1;
entity->behavior = &actParticleErupt;
entity->flags[PASSABLE] = true;
entity->flags[NOUPDATE] = true;
entity->flags[UNCLICKABLE] = true;
if ( multiplayer != CLIENT )
{
entity_uids--;
}
entity->setUID(-3);
yaw += 2 * PI / numParticles;
}
}
++my->skill[1];
}
}
void createParticleShadowTag(Entity* parent, Uint32 casterUid, int duration)
{
if ( !parent )
{
return;
}
Entity* entity = newEntity(870, 1, map.entities, nullptr); //Particle entity.
entity->parent = parent->getUID();
entity->x = parent->x;
entity->y = parent->y;
entity->z = 7.5;
entity->fskill[0] = parent->z;
entity->vel_z = -0.8;
entity->scalex = 0.1;
entity->scaley = 0.1;
entity->scalez = 0.1;
entity->yaw = (rand() % 360) * PI / 180.0;
entity->skill[0] = duration;
entity->skill[1] = 0;
entity->skill[2] = static_cast<Sint32>(casterUid);
entity->skill[3] = 0;
entity->behavior = &actParticleShadowTag;
entity->flags[PASSABLE] = true;
entity->flags[NOUPDATE] = true;
entity->flags[UNCLICKABLE] = true;
if ( multiplayer != CLIENT )
{
entity_uids--;
}
entity->setUID(-3);
}
void createParticleCharmMonster(Entity* parent)
{
if ( !parent )
{
return;
}
Entity* entity = newEntity(685, 1, map.entities, nullptr); //Particle entity.
//entity->sizex = 1;
//entity->sizey = 1;
entity->parent = parent->getUID();
entity->x = parent->x;
entity->y = parent->y;
entity->z = 7.5;
entity->vel_z = -0.8;
entity->scalex = 0.1;
entity->scaley = 0.1;
entity->scalez = 0.1;
entity->yaw = (rand() % 360) * PI / 180.0;
entity->skill[0] = 45;
entity->behavior = &actParticleCharmMonster;
entity->flags[PASSABLE] = true;
entity->flags[NOUPDATE] = true;
entity->flags[UNCLICKABLE] = true;
if ( multiplayer != CLIENT )
{
entity_uids--;
}
entity->setUID(-3);
}
void actParticleCharmMonster(Entity* my)
{
if ( PARTICLE_LIFE < 0 )
{
real_t yaw = 0;
int numParticles = 8;
for ( int c = 0; c < 8; c++ )
{
Entity* entity = newEntity(576, 1, map.entities, nullptr); //Particle entity.
entity->sizex = 1;
entity->sizey = 1;
entity->x = my->x;
entity->y = my->y;
entity->z = -10;
entity->yaw = yaw;
entity->vel_x = 0.2;
entity->vel_y = 0.2;
entity->vel_z = -0.02;
entity->skill[0] = 100;
entity->skill[1] = 0; // direction.
entity->fskill[0] = 0.1;
entity->behavior = &actParticleErupt;
entity->flags[PASSABLE] = true;
entity->flags[NOUPDATE] = true;
entity->flags[UNCLICKABLE] = true;
if ( multiplayer != CLIENT )
{
entity_uids--;
}
entity->setUID(-3);
yaw += 2 * PI / numParticles;
}
list_RemoveNode(my->mynode);
return;
}
else
{
--PARTICLE_LIFE;
Entity* parent = uidToEntity(my->parent);
if ( parent )
{
my->x = parent->x;
my->y = parent->y;
}
my->z += my->vel_z;
my->yaw += my->vel_z * 2;
if ( my->scalex < 0.8 )
{
my->scalex += 0.02;
}
else
{
my->scalex = 0.8;
}
my->scaley = my->scalex;
my->scalez = my->scalex;
if ( my->z < -3 )
{
my->vel_z *= 0.9;
}
}
}
void spawnMagicTower(Entity* parent, real_t x, real_t y, int spellID, Entity* autoHitTarget, bool castedSpell)
{
bool autoHit = false;
if ( autoHitTarget && (autoHitTarget->behavior == &actPlayer || autoHitTarget->behavior == &actMonster) )
{
autoHit = true;
if ( parent )
{
if ( !(svFlags & SV_FLAG_FRIENDLYFIRE) && parent->checkFriend(autoHitTarget) )
{
autoHit = false; // don't hit friendlies
}
}
}
Entity* orbit = castStationaryOrbitingMagicMissile(parent, spellID, x, y, 16.0, 0.0, 40);
if ( orbit )
{
if ( castedSpell )
{
orbit->actmagicOrbitCastFromSpell = 1;
}
if ( autoHit )
{
orbit->actmagicOrbitHitTargetUID4 = autoHitTarget->getUID();
}
}
orbit = castStationaryOrbitingMagicMissile(parent, spellID, x, y, 16.0, 2 * PI / 3, 40);
if ( orbit )
{
if ( castedSpell )
{
orbit->actmagicOrbitCastFromSpell = 1;
}
if ( autoHit )
{
orbit->actmagicOrbitHitTargetUID4 = autoHitTarget->getUID();
}
}
orbit = castStationaryOrbitingMagicMissile(parent, spellID, x, y, 16.0, 4 * PI / 3, 40);
if ( orbit )
{
if ( castedSpell )
{
orbit->actmagicOrbitCastFromSpell = 1;
}
if ( autoHit )
{
orbit->actmagicOrbitHitTargetUID4 = autoHitTarget->getUID();
}
}
spawnMagicEffectParticles(x, y, 0, 174);
spawnExplosion(x, y, -4 + rand() % 8);
}
void magicDig(Entity* parent, Entity* projectile, int numRocks, int randRocks)
{
if ( !hit.entity )
{
if ( map.tiles[(int)(OBSTACLELAYER + hit.mapy * MAPLAYERS + hit.mapx * MAPLAYERS * map.height)] != 0 )
{
if ( parent && parent->behavior == &actPlayer && MFLAG_DISABLEDIGGING )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 255, 0, 255);
messagePlayerColor(parent->skill[2], color, language[2380]); // disabled digging.
playSoundPos(hit.x, hit.y, 66, 128); // strike wall
}
else
{
if ( projectile )
{
playSoundEntity(projectile, 66, 128);
playSoundEntity(projectile, 67, 128);
}
// spawn several rock items
if ( randRocks <= 0 )
{
randRocks = 1;
}
int i = numRocks + rand() % randRocks;
for ( int c = 0; c < i; c++ )
{
Entity* rock = newEntity(-1, 1, map.entities, nullptr); //Rock entity.
rock->flags[INVISIBLE] = true;
rock->flags[UPDATENEEDED] = true;
rock->x = hit.mapx * 16 + 4 + rand() % 8;
rock->y = hit.mapy * 16 + 4 + rand() % 8;
rock->z = -6 + rand() % 12;
rock->sizex = 4;
rock->sizey = 4;
rock->yaw = rand() % 360 * PI / 180;
rock->vel_x = (rand() % 20 - 10) / 10.0;
rock->vel_y = (rand() % 20 - 10) / 10.0;
rock->vel_z = -.25 - (rand() % 5) / 10.0;
rock->flags[PASSABLE] = true;
rock->behavior = &actItem;
rock->flags[USERFLAG1] = true; // no collision: helps performance
rock->skill[10] = GEM_ROCK; // type
rock->skill[11] = WORN; // status
rock->skill[12] = 0; // beatitude
rock->skill[13] = 1; // count
rock->skill[14] = 0; // appearance
rock->skill[15] = 1; // identified
}
if ( map.tiles[(int)(OBSTACLELAYER + hit.mapy * MAPLAYERS + hit.mapx * MAPLAYERS * map.height)] >= 41
&& map.tiles[(int)(OBSTACLELAYER + hit.mapy * MAPLAYERS + hit.mapx * MAPLAYERS * map.height)] <= 49 )
{
steamAchievementEntity(parent, "BARONY_ACH_BAD_REVIEW");
}
map.tiles[(int)(OBSTACLELAYER + hit.mapy * MAPLAYERS + hit.mapx * MAPLAYERS * map.height)] = 0;
// send wall destroy info to clients
for ( int c = 1; c < MAXPLAYERS; c++ )
{
if ( client_disconnected[c] == true )
{
continue;
}
strcpy((char*)net_packet->data, "WALD");
SDLNet_Write16((Uint16)hit.mapx, &net_packet->data[4]);
SDLNet_Write16((Uint16)hit.mapy, &net_packet->data[6]);
net_packet->address.host = net_clients[c - 1].host;
net_packet->address.port = net_clients[c - 1].port;
net_packet->len = 8;
sendPacketSafe(net_sock, -1, net_packet, c - 1);
}
generatePathMaps();
}
}
}
else if ( hit.entity->behavior == &actBoulder )
{
int i = numRocks + rand() % 4;
// spawn several rock items //TODO: This should really be its own function.
int c;
for ( c = 0; c < i; c++ )
{
Entity* entity = newEntity(-1, 1, map.entities, nullptr); //Rock entity.
entity->flags[INVISIBLE] = true;
entity->flags[UPDATENEEDED] = true;
entity->x = hit.entity->x - 4 + rand() % 8;
entity->y = hit.entity->y - 4 + rand() % 8;
entity->z = -6 + rand() % 12;
entity->sizex = 4;
entity->sizey = 4;
entity->yaw = rand() % 360 * PI / 180;
entity->vel_x = (rand() % 20 - 10) / 10.0;
entity->vel_y = (rand() % 20 - 10) / 10.0;
entity->vel_z = -.25 - (rand() % 5) / 10.0;
entity->flags[PASSABLE] = true;
entity->behavior = &actItem;
entity->flags[USERFLAG1] = true; // no collision: helps performance
entity->skill[10] = GEM_ROCK; // type
entity->skill[11] = WORN; // status
entity->skill[12] = 0; // beatitude
entity->skill[13] = 1; // count
entity->skill[14] = 0; // appearance
entity->skill[15] = false; // identified
}
double ox = hit.entity->x;
double oy = hit.entity->y;
boulderLavaOrArcaneOnDestroy(hit.entity, hit.entity->sprite, nullptr);
// destroy the boulder
playSoundEntity(hit.entity, 67, 128);
list_RemoveNode(hit.entity->mynode);
if ( parent )
{
if ( parent->behavior == &actPlayer )
{
messagePlayer(parent->skill[2], language[405]);
}
}
// on sokoban, destroying boulders spawns scorpions
if ( !strcmp(map.name, "Sokoban") )
{
Entity* monster = nullptr;
if ( rand() % 2 == 0 )
{
monster = summonMonster(INSECTOID, ox, oy);
}
else
{
monster = summonMonster(SCORPION, ox, oy);
}
if ( monster )
{
int c;
for ( c = 0; c < MAXPLAYERS; c++ )
{
Uint32 color = SDL_MapRGB(mainsurface->format, 255, 128, 0);
messagePlayerColor(c, color, language[406]);
}
}
boulderSokobanOnDestroy(false);
}
}
} | 29.783274 | 282 | 0.577248 | PegasusEpsilon |
5fbabb6d06829191d76a03b0657e53f2ef2c679f | 4,178 | cpp | C++ | Common/Parse.cpp | d0liver/realpolitik | 3aa6d7238f3eb77494637861813206295f44f6e0 | [
"Artistic-1.0"
] | null | null | null | Common/Parse.cpp | d0liver/realpolitik | 3aa6d7238f3eb77494637861813206295f44f6e0 | [
"Artistic-1.0"
] | null | null | null | Common/Parse.cpp | d0liver/realpolitik | 3aa6d7238f3eb77494637861813206295f44f6e0 | [
"Artistic-1.0"
] | null | null | null | //---------------------------------------------------------------------------------
// Copyright (C) 2001 James M. Van Verth
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the Clarified Artistic License.
// In addition, to meet copyright restrictions you must also own at
// least one copy of any of the following board games:
// Diplomacy, Deluxe Diplomacy, Colonial Diplomacy or Machiavelli.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// Clarified Artistic License for more details.
//
// You should have received a copy of the Clarified Artistic License
// along with this program; if not, write to the Open Source Initiative
// at www.opensource.org
//---------------------------------------------------------------------------------
#include <ctype.h>
#include "MapData.h"
#include "Parse.h"
#include "Game.h"
/* #include "order.h"
#include "fails.h"
*/
int
emptyline (char *s)
{
if (s == NULL)
return 1;
while (isspace(*s)) s++;
if (*s == '\000')
return 1;
return 0;
}
void
uppercase (char *s)
{
if (s == NULL)
return;
for (; *s; s++)
if (islower(*s))
*s = toupper(*s);
}
void
capitalize(char *s)
{
if (s == NULL)
return;
if (islower(*s))
*s = toupper(*s);
s++;
for (; *s; s++)
if (isupper(*s))
*s = tolower(*s);
}
bool
strnsame(char *s1, char *s2, int n)
{
bool same;
if (*s1 == NULL || *s2 == NULL)
return false;
same = 1;
for (; *s1 && *s2 && n; s1++, s2++, n--)
{
if (*s1 != *s2 && toupper(*s1) != *s2 && *s1 != toupper(*s2))
{
same = 0;
break;
}
}
if (n != 0)
return 0;
return same;
}
char *
samestring(const char *line, const char *key)
{
if (line == NULL || key == NULL)
return NULL;
while (*line != '\0' &&
(*line == *key || toupper(*line) == *key || *line == toupper(*key)))
{ line++; key++; }
if ( *key == '\0' )
return (char*)line;
else
return NULL;
}
void
appendtabs (char *s)
{
if (s == NULL)
return;
/* strncat(s, "\t\t\t\t\t", 5 - (strlen(s))/TABLEN); */
}
/* return pointer to beginning of next word in string s */
/* assumes there might be leading blanks */
char *
skipword (char *s)
{
if (s == NULL)
return s;
s = skipspace(s); /* skip leading blanks */
while (isgraph(*s)) s++; /* skip word */
s = skipspace(s); /* skip trailing blanks */
if (s == NULL || *s == '\0') /* fell off the end? */
return NULL;
return s;
}
char *
skipspace (char *s)
{
if (s == NULL)
return s;
while (isspace(*s) || *s == ',' || *s == '.' || *s == ':') s++;
if (*s == '\0')
return NULL;
return s;
}
/* returns length of next word in string */
/* assumes no leading blanks */
short
wordlen (char *s)
{
char *sp = s;
if (s == NULL)
return 0;
while (isgraph(*sp)) sp++;
return sp-s;
}
/* returns pointer to remainder of s if it's a comment */
/* skips leading blanks */
char *
findcomment (char *s)
{
s = skipspace(s);
if (s == NULL)
return NULL;
if (*s == '#')
return s+1;
else if (*s == '/' && *(s+1) == '/')
return s+2;
else
return NULL;
}
/* return text stripped of tabs and deal with comments */
/* affects original text where comments are concerned. */
char *
striptext (char *orig)
{
char *copy, *comment = NULL;
copy = skipspace(orig);
if (wordlen(copy) == 0)
return NULL;
while (*copy)
{
/* strip tab */
if (*copy == '\t')
*copy = ' ';
/* deal w/comment */
else if ((comment = findcomment(copy)) != NULL)
{
*copy = '\0'; /* order is everything up to this comment */
break;
}
copy++;
}
return comment;
}
| 19.895238 | 84 | 0.497367 | d0liver |
5fbd79ada3d0d2bc36c3c2ed324f781e626e4c5e | 2,069 | cpp | C++ | src/ext/transport/FastRTPS/FastRTPSTransport.cpp | r-kurose/OpenRTM-aist | 258c922c55a97c6d1265dbf45e1e8b2ea29b2d86 | [
"RSA-MD"
] | 15 | 2019-01-08T15:34:04.000Z | 2022-03-01T08:36:17.000Z | src/ext/transport/FastRTPS/FastRTPSTransport.cpp | r-kurose/OpenRTM-aist | 258c922c55a97c6d1265dbf45e1e8b2ea29b2d86 | [
"RSA-MD"
] | 448 | 2018-12-27T03:13:56.000Z | 2022-03-24T09:57:03.000Z | src/ext/transport/FastRTPS/FastRTPSTransport.cpp | r-kurose/OpenRTM-aist | 258c922c55a97c6d1265dbf45e1e8b2ea29b2d86 | [
"RSA-MD"
] | 31 | 2018-12-26T04:34:22.000Z | 2021-11-25T04:39:51.000Z | // -*- C++ -*-
/*!
* @file FastRTPSOutPort.cpp
* @brief FastRTPSOutPort class
* @date $Date: 2019-01-31 03:08:03 $
* @author Nobuhiko Miyamoto <[email protected]>
*
* Copyright (C) 2019
* Nobuhiko Miyamoto
* Robot Innovation Research Center,
* National Institute of
* Advanced Industrial Science and Technology (AIST), Japan
*
* All rights reserved.
*
*
*/
#include "FastRTPSTransport.h"
#include "FastRTPSOutPort.h"
#include "FastRTPSInPort.h"
#include "FastRTPSManager.h"
namespace FastRTPSRTC
{
ManagerActionListener::ManagerActionListener()
{
}
ManagerActionListener::~ManagerActionListener()
{
}
void ManagerActionListener::preShutdown()
{
}
void ManagerActionListener::postShutdown()
{
RTC::FastRTPSManager::shutdown_global();
}
void ManagerActionListener::postReinit()
{
}
void ManagerActionListener::preReinit()
{
}
}
extern "C"
{
/*!
* @if jp
* @brief モジュール初期化関数
* @else
* @brief Module initialization
* @endif
*/
void FastRTPSTransportInit(RTC::Manager* manager)
{
{
RTC::InPortProviderFactory& factory(RTC::InPortProviderFactory::instance());
factory.addFactory("fast-rtps",
::coil::Creator< ::RTC::InPortProvider,
::RTC::FastRTPSInPort>,
::coil::Destructor< ::RTC::InPortProvider,
::RTC::FastRTPSInPort>);
}
{
RTC::InPortConsumerFactory& factory(RTC::InPortConsumerFactory::instance());
factory.addFactory("fast-rtps",
::coil::Creator< ::RTC::InPortConsumer,
::RTC::FastRTPSOutPort>,
::coil::Destructor< ::RTC::InPortConsumer,
::RTC::FastRTPSOutPort>);
}
FastRTPSRTC::ManagerActionListener *listener = new FastRTPSRTC::ManagerActionListener();
manager->addManagerActionListener(listener);
}
}
| 21.778947 | 92 | 0.58144 | r-kurose |
5fbffc8f4e6528e19ec06dd7271bb63304fe0285 | 504 | cpp | C++ | EU4toV2/Source/V2World/Output/outLeader.cpp | GregB76/EU4toVic2 | 0a8822101a36a16036fdc315e706d113d9231101 | [
"MIT"
] | 42 | 2018-12-22T03:59:43.000Z | 2022-02-03T10:45:42.000Z | EU4toV2/Source/V2World/Output/outLeader.cpp | IhateTrains/EU4toVic2 | 061f5e1a0bc1a1f3b54bdfe471b501260149b56b | [
"MIT"
] | 336 | 2018-12-22T17:15:27.000Z | 2022-03-02T11:19:32.000Z | EU4toV2/Source/V2World/Output/outLeader.cpp | klorpa/EU4toVic2 | e3068eb2aa459f884c1929f162d0047a4cb5f4d4 | [
"MIT"
] | 56 | 2018-12-22T19:13:23.000Z | 2022-01-01T23:08:53.000Z | #include "output.h"
std::ostream& V2::operator<<(std::ostream& output, const Leader& leader)
{
output << "leader = {\n";
output << "\tname=\"" << leader.name << "\"\n";
output << "\tdate=\"" << leader.activationDate << "\"\n";
if (leader.isLand)
{
output << "\ttype=land\n";
}
else
{
output << "\ttype=sea\n";
}
output << "\tpersonality=\"" << leader.personality << "\"\n";
output << "\tbackground=\"" << leader.background << "\"\n";
output << "}\n";
output << "\n";
return output;
}
| 21.913043 | 72 | 0.553571 | GregB76 |
5fc60f95819d5eb5ddbd3d505bc52540009782ec | 10,658 | cpp | C++ | pluginLite/sysutils.cpp | XULPlayer/XULPlayer-legacy | 1ab0ad2a196373d81d350bf45c03f690a0bfb8a2 | [
"MIT"
] | 3 | 2017-11-29T07:11:24.000Z | 2020-03-03T19:23:33.000Z | pluginLite/sysutils.cpp | XULPlayer/XULPlayer-legacy | 1ab0ad2a196373d81d350bf45c03f690a0bfb8a2 | [
"MIT"
] | null | null | null | pluginLite/sysutils.cpp | XULPlayer/XULPlayer-legacy | 1ab0ad2a196373d81d350bf45c03f690a0bfb8a2 | [
"MIT"
] | 1 | 2018-07-12T12:48:52.000Z | 2018-07-12T12:48:52.000Z | #include <windows.h>
#include <stdio.h>
#include <comdef.h> // for using bstr_t class
#include <vector>
#include <tchar.h>
#define SYSTEM_OBJECT_INDEX 2 // 'System' object
#define PROCESS_OBJECT_INDEX 230 // 'Process' object
#define PROCESSOR_OBJECT_INDEX 238 // 'Processor' object
#define TOTAL_PROCESSOR_TIME_COUNTER_INDEX 240 // '% Total processor time' counter (valid in WinNT under 'System' object)
#define PROCESSOR_TIME_COUNTER_INDEX 6 // '% processor time' counter (for Win2K/XP)
#define TOTALBYTES 100*1024
#define BYTEINCREMENT 10*1024
template <class T>
class CPerfCounters
{
public:
CPerfCounters()
{
}
~CPerfCounters()
{
}
T GetCounterValue(PERF_DATA_BLOCK **pPerfData, DWORD dwObjectIndex, DWORD dwCounterIndex, LPCTSTR pInstanceName = NULL)
{
QueryPerformanceData(pPerfData, dwObjectIndex, dwCounterIndex);
PPERF_OBJECT_TYPE pPerfObj = NULL;
T lnValue = {0};
// Get the first object type.
pPerfObj = FirstObject( *pPerfData );
// Look for the given object index
for( DWORD i=0; i < (*pPerfData)->NumObjectTypes; i++ )
{
if (pPerfObj->ObjectNameTitleIndex == dwObjectIndex)
{
lnValue = GetCounterValue(pPerfObj, dwCounterIndex, pInstanceName);
break;
}
pPerfObj = NextObject( pPerfObj );
}
return lnValue;
}
T GetCounterValueForProcessID(PERF_DATA_BLOCK **pPerfData, DWORD dwObjectIndex, DWORD dwCounterIndex, DWORD dwProcessID)
{
QueryPerformanceData(pPerfData, dwObjectIndex, dwCounterIndex);
PPERF_OBJECT_TYPE pPerfObj = NULL;
T lnValue = {0};
// Get the first object type.
pPerfObj = FirstObject( *pPerfData );
// Look for the given object index
for( DWORD i=0; i < (*pPerfData)->NumObjectTypes; i++ )
{
if (pPerfObj->ObjectNameTitleIndex == dwObjectIndex)
{
lnValue = GetCounterValueForProcessID(pPerfObj, dwCounterIndex, dwProcessID);
break;
}
pPerfObj = NextObject( pPerfObj );
}
return lnValue;
}
protected:
class CBuffer
{
public:
CBuffer(UINT Size)
{
m_Size = Size;
m_pBuffer = (LPBYTE) malloc( Size*sizeof(BYTE) );
}
~CBuffer()
{
free(m_pBuffer);
}
void *Realloc(UINT Size)
{
m_Size = Size;
m_pBuffer = (LPBYTE) realloc( m_pBuffer, Size );
return m_pBuffer;
}
void Reset()
{
memset(m_pBuffer,NULL,m_Size);
}
operator LPBYTE ()
{
return m_pBuffer;
}
UINT GetSize()
{
return m_Size;
}
public:
LPBYTE m_pBuffer;
private:
UINT m_Size;
};
//
// The performance data is accessed through the registry key
// HKEY_PEFORMANCE_DATA.
// However, although we use the registry to collect performance data,
// the data is not stored in the registry database.
// Instead, calling the registry functions with the HKEY_PEFORMANCE_DATA key
// causes the system to collect the data from the appropriate system
// object managers.
//
// QueryPerformanceData allocates memory block for getting the
// performance data.
//
//
void QueryPerformanceData(PERF_DATA_BLOCK **pPerfData, DWORD dwObjectIndex, DWORD dwCounterIndex)
{
//
// Since i want to use the same allocated area for each query,
// i declare CBuffer as static.
// The allocated is changed only when RegQueryValueEx return ERROR_MORE_DATA
//
static CBuffer Buffer(TOTALBYTES);
DWORD BufferSize = Buffer.GetSize();
LONG lRes;
TCHAR keyName[32];
_stprintf(keyName, _T("%d"), dwObjectIndex);
Buffer.Reset();
while( (lRes = RegQueryValueEx( HKEY_PERFORMANCE_DATA,
keyName,
NULL,
NULL,
Buffer,
&BufferSize )) == ERROR_MORE_DATA )
{
// Get a buffer that is big enough.
BufferSize += BYTEINCREMENT;
Buffer.Realloc(BufferSize);
}
*pPerfData = (PPERF_DATA_BLOCK) Buffer.m_pBuffer;
}
//
// GetCounterValue gets performance object structure
// and returns the value of given counter index .
// This functions iterates through the counters of the input object
// structure and looks for the given counter index.
//
// For objects that have instances, this function returns the counter value
// of the instance pInstanceName.
//
T GetCounterValue(PPERF_OBJECT_TYPE pPerfObj, DWORD dwCounterIndex, LPCTSTR pInstanceName)
{
PPERF_COUNTER_DEFINITION pPerfCntr = NULL;
PPERF_INSTANCE_DEFINITION pPerfInst = NULL;
PPERF_COUNTER_BLOCK pCounterBlock = NULL;
// Get the first counter.
pPerfCntr = FirstCounter( pPerfObj );
for( DWORD j=0; j < pPerfObj->NumCounters; j++ )
{
if (pPerfCntr->CounterNameTitleIndex == dwCounterIndex)
break;
// Get the next counter.
pPerfCntr = NextCounter( pPerfCntr );
}
if( pPerfObj->NumInstances == PERF_NO_INSTANCES )
{
pCounterBlock = (PPERF_COUNTER_BLOCK) ((LPBYTE) pPerfObj + pPerfObj->DefinitionLength);
}
else
{
pPerfInst = FirstInstance( pPerfObj );
// Look for instance pInstanceName
_bstr_t bstrInstance;
_bstr_t bstrInputInstance = pInstanceName;
for( int k=0; k < pPerfObj->NumInstances; k++ )
{
bstrInstance = (wchar_t *)((PBYTE)pPerfInst + pPerfInst->NameOffset);
if (!_tcsicmp((LPCTSTR)bstrInstance, (LPCTSTR)bstrInputInstance))
{
pCounterBlock = (PPERF_COUNTER_BLOCK) ((LPBYTE) pPerfInst + pPerfInst->ByteLength);
break;
}
// Get the next instance.
pPerfInst = NextInstance( pPerfInst );
}
}
if (pCounterBlock)
{
T *lnValue = NULL;
lnValue = (T*)((LPBYTE) pCounterBlock + pPerfCntr->CounterOffset);
return *lnValue;
}
return -1;
}
T GetCounterValueForProcessID(PPERF_OBJECT_TYPE pPerfObj, DWORD dwCounterIndex, DWORD dwProcessID)
{
int PROC_ID_COUNTER = 784;
BOOL bProcessIDExist = FALSE;
PPERF_COUNTER_DEFINITION pPerfCntr = NULL;
PPERF_COUNTER_DEFINITION pTheRequestedPerfCntr = NULL;
PPERF_COUNTER_DEFINITION pProcIDPerfCntr = NULL;
PPERF_INSTANCE_DEFINITION pPerfInst = NULL;
PPERF_COUNTER_BLOCK pCounterBlock = NULL;
// Get the first counter.
pPerfCntr = FirstCounter( pPerfObj );
for( DWORD j=0; j < pPerfObj->NumCounters; j++ )
{
if (pPerfCntr->CounterNameTitleIndex == PROC_ID_COUNTER)
{
pProcIDPerfCntr = pPerfCntr;
if (pTheRequestedPerfCntr)
break;
}
if (pPerfCntr->CounterNameTitleIndex == dwCounterIndex)
{
pTheRequestedPerfCntr = pPerfCntr;
if (pProcIDPerfCntr)
break;
}
// Get the next counter.
pPerfCntr = NextCounter( pPerfCntr );
}
if( pPerfObj->NumInstances == PERF_NO_INSTANCES )
{
pCounterBlock = (PPERF_COUNTER_BLOCK) ((LPBYTE) pPerfObj + pPerfObj->DefinitionLength);
}
else
{
pPerfInst = FirstInstance( pPerfObj );
for( int k=0; k < pPerfObj->NumInstances; k++ )
{
pCounterBlock = (PPERF_COUNTER_BLOCK) ((LPBYTE) pPerfInst + pPerfInst->ByteLength);
if (pCounterBlock)
{
int processID = 0;
processID = *(T*)((LPBYTE) pCounterBlock + pProcIDPerfCntr->CounterOffset);
if (processID == dwProcessID)
{
bProcessIDExist = TRUE;
break;
}
}
// Get the next instance.
pPerfInst = NextInstance( pPerfInst );
}
}
if (bProcessIDExist && pCounterBlock)
{
T *lnValue = NULL;
lnValue = (T*)((LPBYTE) pCounterBlock + pTheRequestedPerfCntr->CounterOffset);
return *lnValue;
}
return -1;
}
/*****************************************************************
* *
* Functions used to navigate through the performance data. *
* *
*****************************************************************/
PPERF_OBJECT_TYPE FirstObject( PPERF_DATA_BLOCK PerfData )
{
return( (PPERF_OBJECT_TYPE)((PBYTE)PerfData + PerfData->HeaderLength) );
}
PPERF_OBJECT_TYPE NextObject( PPERF_OBJECT_TYPE PerfObj )
{
return( (PPERF_OBJECT_TYPE)((PBYTE)PerfObj + PerfObj->TotalByteLength) );
}
PPERF_COUNTER_DEFINITION FirstCounter( PPERF_OBJECT_TYPE PerfObj )
{
return( (PPERF_COUNTER_DEFINITION) ((PBYTE)PerfObj + PerfObj->HeaderLength) );
}
PPERF_COUNTER_DEFINITION NextCounter( PPERF_COUNTER_DEFINITION PerfCntr )
{
return( (PPERF_COUNTER_DEFINITION)((PBYTE)PerfCntr + PerfCntr->ByteLength) );
}
PPERF_INSTANCE_DEFINITION FirstInstance( PPERF_OBJECT_TYPE PerfObj )
{
return( (PPERF_INSTANCE_DEFINITION)((PBYTE)PerfObj + PerfObj->DefinitionLength) );
}
PPERF_INSTANCE_DEFINITION NextInstance( PPERF_INSTANCE_DEFINITION PerfInst )
{
PPERF_COUNTER_BLOCK PerfCntrBlk;
PerfCntrBlk = (PPERF_COUNTER_BLOCK)((PBYTE)PerfInst + PerfInst->ByteLength);
return( (PPERF_INSTANCE_DEFINITION)((PBYTE)PerfCntrBlk + PerfCntrBlk->ByteLength) );
}
};
typedef enum
{
WINNT, WIN2K_XP, WIN9X, UNKNOWN
}PLATFORM;
PLATFORM GetPlatform()
{
OSVERSIONINFO osvi;
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
if (!GetVersionEx(&osvi))
return UNKNOWN;
switch (osvi.dwPlatformId)
{
case VER_PLATFORM_WIN32_WINDOWS:
return WIN9X;
case VER_PLATFORM_WIN32_NT:
if (osvi.dwMajorVersion == 4)
return WINNT;
else
return WIN2K_XP;
}
return UNKNOWN;
}
bool m_bFirstTime = true;
LONGLONG m_lnOldValue ;
LARGE_INTEGER m_OldPerfTime100nSec;
float GetCpuUsage()
{
static PLATFORM Platform = GetPlatform();
static DWORD dwObjectIndex = (Platform == WINNT ? SYSTEM_OBJECT_INDEX : PROCESSOR_OBJECT_INDEX);
static DWORD dwCpuUsageIndex = (Platform == WINNT ? TOTAL_PROCESSOR_TIME_COUNTER_INDEX : PROCESSOR_TIME_COUNTER_INDEX);
static TCHAR *szInstance = (Platform == WINNT ? "" : "_Total");
// Cpu usage counter is 8 byte length.
CPerfCounters<LONGLONG> PerfCounters;
// Note:
// ====
// On windows NT, cpu usage counter is '% Total processor time'
// under 'System' object. However, in Win2K/XP Microsoft moved
// that counter to '% processor time' under '_Total' instance
// of 'Processor' object.
// Read 'INFO: Percent Total Performance Counter Changes on Windows 2000'
// Q259390 in MSDN.
int CpuUsage = 0;
LONGLONG lnNewValue = 0;
PPERF_DATA_BLOCK pPerfData = NULL;
LARGE_INTEGER NewPerfTime100nSec = {0};
lnNewValue = PerfCounters.GetCounterValue(&pPerfData, dwObjectIndex, dwCpuUsageIndex, szInstance);
NewPerfTime100nSec = pPerfData->PerfTime100nSec;
if (m_bFirstTime)
{
m_bFirstTime = false;
m_lnOldValue = lnNewValue;
m_OldPerfTime100nSec = NewPerfTime100nSec;
return 0;
}
LONGLONG lnValueDelta = lnNewValue - m_lnOldValue;
double DeltaPerfTime100nSec = (double)NewPerfTime100nSec.QuadPart - (double)m_OldPerfTime100nSec.QuadPart;
m_lnOldValue = lnNewValue;
m_OldPerfTime100nSec = NewPerfTime100nSec;
float a = 100 - (float)(lnValueDelta / DeltaPerfTime100nSec) * 100;
return a;
} | 25.806295 | 122 | 0.693751 | XULPlayer |
5fc7c5022bb2cd702c6add7ffa1a3a2714535c8d | 15,209 | cpp | C++ | Merrymen/WeaponCS.cpp | Mertank/ToneArm | 40c62b0de89ac506bea6674e43578bf4e2631f93 | [
"Zlib",
"BSD-2-Clause"
] | null | null | null | Merrymen/WeaponCS.cpp | Mertank/ToneArm | 40c62b0de89ac506bea6674e43578bf4e2631f93 | [
"Zlib",
"BSD-2-Clause"
] | null | null | null | Merrymen/WeaponCS.cpp | Mertank/ToneArm | 40c62b0de89ac506bea6674e43578bf4e2631f93 | [
"Zlib",
"BSD-2-Clause"
] | null | null | null | /*
------------------------------------------------------------------------------------------
Copyright (c) 2014 Vinyl Games Studio
Author: Mikhail Kutuzov
Date: 5/15/2014 4:14:48 PM
------------------------------------------------------------------------------------------
*/
#include "WeaponCS.h"
#include "Character.h"
#include "GameScene.h"
#include "ShootingHelperSP.h"
#include "../ToneArmEngine/RayCasting.h"
#include "../ToneArmEngine/Engine.h"
#include "../ToneArmEngine/EngineModule.h"
#include "../ToneArmEngine/CachedResourceLoader.h"
#include "../ToneArmEngine/InitializationFileResource.h"
#include "../ToneArmEngine/SoundModule.h"
#include "../ToneArmEngine/ParticleEmitterNode.h"
#include "../ToneArmEngine/ParticleEmitterNodePool.h"
using namespace merrymen;
//
// allocates a Weapon object and calls Init() on it
//
WeaponCS* WeaponCS::Create(const WeaponID& id, Character* const owner, const char* modelFile, char** const soundFiles, const char* iniFile, const char* category) {
WeaponCS* weapon = new WeaponCS();
if (weapon && weapon->Init(id, owner, modelFile, soundFiles, iniFile, category)) {
return weapon;
}
delete weapon;
return nullptr;
}
//
// default constructor
//
WeaponCS::WeaponCS() :
m_owner(nullptr),
m_model(nullptr),
m_emitter(nullptr),
m_stats(nullptr),
m_projectileStats(nullptr),
m_cooldownTimer(1.0f),
m_reloadTimer(-1.0f),
m_active(false),
m_shooting(false),
m_reloading(false),
m_emitterNodePool( NULL )
{}
//
// destructor
//
WeaponCS::~WeaponCS() {
delete m_stats;
delete m_projectileStats;
}
//
// initializes the weapon data with the passed values
//
bool WeaponCS::Init(const WeaponID& id, Character* const owner, const char* modelFile, char** soundFiles, const char* iniFile, const char* category) {
if (Node::Init()) {
m_id = id;
m_owner = owner;
// initialize weapon's stats
CachedResourceLoader* loader = Engine::GetInstance()->GetModuleByType<CachedResourceLoader>(EngineModuleType::RESOURCELOADER);
std::shared_ptr<InitializationFileResource> ini = loader->LoadResource<InitializationFileResource>(iniFile);
m_stats = new WeaponStats<WeaponCS>(this, *ini->GetCategory(category));
m_projectileStats = new ProjectileStats();
// initialize sounds
m_sounds.insert(std::pair<WeaponSoundTypes, const char*>(WeaponSoundTypes::ShotSound, soundFiles[0]));
m_sounds.insert(std::pair<WeaponSoundTypes, const char*>(WeaponSoundTypes::LoadSound, soundFiles[1]));
m_sounds.insert(std::pair<WeaponSoundTypes, const char*>(WeaponSoundTypes::CockSound, soundFiles[2]));
m_sounds.insert(std::pair<WeaponSoundTypes, const char*>(WeaponSoundTypes::TriggerClickSound, soundFiles[3]));
// create model
m_model = ModelNode::Create( modelFile );
m_model->SetVisible(false);
m_model->SetPosition(glm::vec3(0.0f, 15.0f, 50.0f));
AddChild(m_model);
// TODO: initialize the emitter with respect to the type of the weapon
m_emitter = vgs::ParticleEmitterNode::CreateWithSettings(ParticleEmitterSettings(75, 0.1f, 0.05f, 750, 90.0f, glm::vec3(0.85f, 0.75f, 0.0f), 0, 5.0f, 300.0f, 100.0f));
if (id == WeaponID::Pistol) {
m_emitter->SetPosition( glm::vec3( -0.898f, 0.3085f, -0.3122f ) * 35.0f);
}
else if (id == WeaponID::Shotgun) {
m_emitter->SetPosition( glm::vec3( -0.898f, 0.3085f, -0.3122f ) * 70.0f);
}
else if (id == WeaponID::SniperRifle) {
m_emitter->SetPosition( glm::vec3( -0.898f, 0.3085f, -0.3122f ) * 85.0f);
}
m_emitter->SetRotation( glm::vec3( 67.0f, -116.0f, -83.0f ) );
m_model->AddChild(m_emitter);
m_emitterNodePool = ParticleEmitterNodePool::CreateEmitterPool( 10 );
AddChild( m_emitterNodePool );
return true;
}
return false;
}
//
// Weapon object updates it's state
//
void WeaponCS::Update(float dt) {
if (!m_owner->IsOnline() && IsActive()) {
UpdateStats(dt);
}
// cooldown goes on
if (m_cooldownTimer > 0.0f) {
m_cooldownTimer -= dt;
}
// reloading timer
if (IsReloading()) {
m_reloadTimer -= dt;
}
// auto-reload?
if (m_stats->Ammo <= 0 && m_reloadTimer <= -1.0f && !m_owner->IsSprinting()) {
Reload();
}
Node::Update(dt);
}
//
// weapon updates it's timers and stats
//
void WeaponCS::UpdateStats(float dt) {
if (m_stats->Update(dt)) {
m_owner->SetStatsChanged(true);
}
}
//
// casts rays to check which objects were hit
//
void WeaponCS::DoRayCasting(std::multimap<ClientEntity*, float>& hitEntities, std::vector<glm::vec3>& impactPoints) {
RayCasting::ColliderResult shotResultPtr;
glm::vec3 shotImpactPoint;
// prepare data for ray casting
std::vector<ColliderComponent*> geometryColliders;
ShootingHelperSP helper = ShootingHelperSP();
helper.PreapareGeometryData(this->GetOwner(), geometryColliders, false);
GameScene* gs = static_cast<GameScene*>(Engine::GetRunningScene());
std::vector<Character*> targets = gs->GetPlayers();
glm::vec3 shotOrigin = this->GetAbsoluteWorldPosition() + m_owner->GetForward() * WEAPON_LENGTH, shotDirection;
// cast as many rays as there are projectiles in one shot
for (int i = 0; i < m_projectileStats->ProjectilesPerShot; i++) {
// calculate shot direction for that particular projectile
glm::vec3 shotDirection = helper.CalculateShotDirection(this->GetOwner(), this->GetWeaponStats());
if (targets.size() > 1) {
// cast a ray to each target
for (auto target : targets) {
bool hitSomething = false;
bool hitTheTarget = false;
// check what the ray cast from the weapon's position actually hits (target, geometry or nothing)
if (target != this->GetOwner() && !target->IsDead()) {
ColliderComponent* collider = target->GetComponentOfType<ColliderComponent>();
shotResultPtr = RayCasting::RayCastShot(shotOrigin, shotDirection, geometryColliders, collider);
if (shotResultPtr) {
ColliderComponent* collider = shotResultPtr.get()->Object;
// hit someone
if (collider->GetOwner()->GetRTTI().DerivesFrom(ClientEntity::rtti)) {
hitEntities.insert(std::pair<ClientEntity*, float>(target, glm::distance(shotOrigin, shotImpactPoint)));
}
// hit a wall
else {
impactPoints.push_back(shotResultPtr.get()->Intersection);
}
}
}
}
}
else {
std::shared_ptr<RayCasting::RayCastResult<ColliderComponent>> hitObject = RayCasting::RayCastFirst(geometryColliders, shotOrigin, shotDirection);
if (hitObject.get()) {
impactPoints.push_back(hitObject.get()->Intersection);
}
}
}
geometryColliders.clear();
targets.clear();
}
//
// method that causes damage
//
void WeaponCS::Shoot() {
std::multimap<ClientEntity*, float> hitEntities;
std::vector<glm::vec3> impactPoints;
// cast rays to check which objects were hit
DoRayCasting(hitEntities, impactPoints);
// deal damage to the characters which were hit
if (hitEntities.size() > 0) {
for (std::multimap<ClientEntity*, float>::iterator hitEntitiesItr = hitEntities.begin(); hitEntitiesItr != hitEntities.end(); ++hitEntitiesItr) {
int count = hitEntities.count(hitEntitiesItr->first);
Damage dmg = Damage::CalculateDamage(count, this->GetWeaponStats().Damage, hitEntitiesItr->second, this->GetWeaponStats().AimingDistance, this->GetProjectileStats());
hitEntitiesItr->first->TakeDamage(dmg, this->GetProjectileStats().Type);
std::multimap<ClientEntity*, float>::iterator currentItr = hitEntitiesItr;
std::advance(hitEntitiesItr, count - 1);
hitEntities.erase(currentItr, hitEntitiesItr);
}
}
// play shot impact effects on the geometry hit by the shot
for (auto impactPoint : impactPoints) {
PlayShotImpactEffects(impactPoint);
}
hitEntities.clear();
impactPoints.clear();
}
//
// handles a shooting command received from the owner
//
void WeaponCS::HandleShootCommand() {
bool canShoot = false;
if (m_stats->ShootingType == ShootingType::Automatic) {
if (m_stats->Ammo > 0 && m_cooldownTimer <= 0.0f && (!IsReloading() || m_stats->LoadingUnit == LoadingUnit::Bullet)) {
canShoot = true;
}
}
// if a weapon is semi-automatic we need to make sure that the fire button was released at least once since the moment of the most recent shot
else if (m_stats->ShootingType == ShootingType::Semi_automatic) {
if (!IsShooting() && m_stats->Ammo > 0 && m_cooldownTimer <= 0.0f && (!IsReloading() || m_stats->LoadingUnit == LoadingUnit::Bullet)) {
canShoot = true;
}
}
// if we have enough ammo, the cooldown has passed and the weapon is not being reloaded a new shot can be performed
if (canShoot) {
Shoot();
// stop reloading
if (IsReloading()) {
StopReloading();
}
m_stats->Ammo--;
m_owner->SetStatsChanged(true);
// start cooldown
m_cooldownTimer = m_stats->Cooldown;
PlayShootingEffects();
m_owner->PlayShootAnimation();
}
else if (m_stats->Ammo == 0 && m_cooldownTimer <= 0.0f && !IsShooting()) {
m_cooldownTimer = m_stats->Cooldown;
if (!IsReloading()) {
PlayWeaponSound(WeaponSoundTypes::TriggerClickSound);
}
}
}
//
// method that handles reloading commands from the owner
//
void WeaponCS::Reload() {
if (!IsReloading() && m_stats->Ammo < m_stats->ClipSize && m_stats->TotalAmmo > 0) {
int bulletsToLoad = 1;
// set the reload timer to a proper value
if (m_stats->LoadingUnit == LoadingUnit::Clip) {
m_reloadTimer = m_stats->ReloadTime;
}
else if (m_stats->LoadingUnit == LoadingUnit::Bullet) {
bulletsToLoad = m_stats->TotalAmmo >= m_stats->ClipSize - m_stats->Ammo ? m_stats->ClipSize - m_stats->Ammo : m_stats->TotalAmmo;
m_reloadTimer = (m_stats->ReloadTime / m_stats->ClipSize) * bulletsToLoad;
}
// stop aiming
if (m_owner->IsAiming()) {
m_owner->SetAiming(false);
}
// give the player some feedback
PlayWeaponSound(WeaponSoundTypes::LoadSound);
m_owner->PlayReloadAnimation(bulletsToLoad);
m_reloading = true;
}
}
//
// describes what needs to happen once the reloading process is finished
//
void WeaponCS::FinishReloading() {
m_reloadTimer = -1.0f;
m_reloading = false;
m_owner->SetStatsChanged(true);
// let the player sprint again if the sprint button was held all the time during reloading
if (m_owner->IsSprintInterrupted()) {
m_owner->SetSprintInterrupted(false);
}
// play sound
PlayWeaponSound(WeaponSoundTypes::CockSound);
// play animation
m_owner->PlayCockAnimation();
}
//
// interrupts reloading
//
void WeaponCS::StopReloading() {
m_reloadTimer = -1.0f;
// play some sounds
SoundModule* sMod = Engine::GetInstance()->GetModuleByType<SoundModule>(EngineModuleType::SOUNDER);
if (sMod)
{
sMod->StopUniqueSound(m_sounds.at(WeaponSoundTypes::LoadSound));
}
SetReloading(false);
}
//
// stops/plays reloading sound depending on whether or not hte weapon is still active (sets the m_active value too of course)
//
void WeaponCS::SetActive(const bool active) {
if (IsReloading()) {
// stop reloading sound and restart the timer
if (!active) {
StopReloading();
}
// play the reload sound, the reloading will start automatically in the UpdateStats
else {
PlayWeaponSound(WeaponSoundTypes::LoadSound);
}
}
m_active = active;
}
//
// plays particle effects on the weapon
//
void WeaponCS::PlayShootingEffects() {
if(m_model->IsVisible()) {
m_emitter->Emit(true, 0);
}
PlayWeaponSound(WeaponSoundTypes::ShotSound);
}
//
// plays particle effects on the projectile impact point
//
void WeaponCS::PlayShotImpactEffects() {
std::multimap<ClientEntity*, float> hitEntities;
std::vector<glm::vec3> impactPoints;
// cast rays to check which objects were hit
DoRayCasting(hitEntities, impactPoints);
// play shot impact effects on the geometry hit by the shot
for (auto impactPoint : impactPoints) {
PlayShotImpactEffects(impactPoint);
}
hitEntities.clear();
impactPoints.clear();
}
//
// plays particle effects on the projectile impact point
//
void WeaponCS::PlayShotImpactEffects(const glm::vec3& impactPoint) {
// get an emitter
ParticleEmitterNode* emitter = m_emitterNodePool->GetEmitterNode();
// set its parent properly
GameScene* gs = static_cast<GameScene*>(Engine::GetRunningScene());
if (gs) {
Node* parent = emitter->GetParent();
if (parent && parent != gs) {
emitter->RemoveFromParent();
}
gs->AddChild(emitter);
}
// make the emitter look "pretty"
emitter->SetEmitterSettings(ParticleEmitterSettings(300, 0.1f, 0.05f, 3000, 180.0f, glm::vec3(0.33f, 0.33f, 0.33f), 0, 4.0f, 200.0f, 50.0f));
// set position of the emitter
emitter->SetPosition(impactPoint - m_owner->GetForward());
// rotate the emitter
glm::vec3 direction = m_owner->GetAbsoluteWorldPosition() - impactPoint;
direction.y = 0.0f;
emitter->SetDirection( glm::normalize( direction ) );
emitter->Emit(true, 0);
}
//
// plays the sound of the shot or the sound of a trigger click if the clip is empty
//
void WeaponCS::PlayWeaponSound(const WeaponSoundTypes& soundType) {
// play sound
GameScene* gs = static_cast<GameScene*>(Engine::GetRunningScene());
if (gs) {
Character* localCharacter = gs->GetLocalCharacter();
if (!localCharacter)
{
return;
}
float distance = glm::distance(GetAbsoluteWorldPosition(), localCharacter->GetAbsoluteWorldPosition());
float volume = SoundModule::CalculateVolume(distance);
SoundModule* sMod = Engine::GetInstance()->GetModuleByType<SoundModule>(EngineModuleType::SOUNDER);
if (!sMod)
{
std::cout << "Couldn't find sound module in Weapon::PlayWeaponSound" << std::endl;
return;
}
if (soundType == WeaponSoundTypes::ShotSound) {
sMod->PlaySound(m_sounds.at(soundType), volume);
}
else if (GetOwner() == localCharacter) {
// if reloading sound needs to be played the duration might need to be adjusted
if (soundType == WeaponSoundTypes::LoadSound) {
if (m_stats->LoadingUnit == LoadingUnit::Clip) {
sMod->PlaySound(m_sounds.at(soundType), volume);
}
else if (m_stats->LoadingUnit == LoadingUnit::Bullet) {
// adjust the duration of the sound with respect to the number of projectiles that need to be loaded
unsigned short bulletsToLoad = m_stats->TotalAmmo >= m_stats->ClipSize - m_stats->Ammo ? m_stats->ClipSize - m_stats->Ammo : m_stats->TotalAmmo;
float duration = (m_stats->ReloadTime / m_stats->ClipSize) * bulletsToLoad;
sMod->PlaySound(m_sounds.at(soundType), volume, duration);
}
}
// there's no need in playing more than one sound of this type at the same time, so PlayUniqueSound()
else if (soundType == WeaponSoundTypes::TriggerClickSound) {
sMod->PlayUniqueSound(m_sounds.at(soundType), volume);
}
else if (soundType == WeaponSoundTypes::CockSound) {
sMod->StopUniqueSound(m_sounds.at(WeaponSoundTypes::LoadSound));
sMod->PlayUniqueSound(m_sounds.at(soundType), volume);
}
}
}
}
//
// changes visibility of the weapon's model
//
void WeaponCS::SetVisible(const bool value) {
if (m_model) {
m_model->SetVisible(value);
}
}
//
// reinitializes some member variables
//
void WeaponCS::Reset() {
m_stats->Ammo = m_stats->ClipSize;
m_stats->TotalAmmo = m_stats->MaxAmmo;
m_cooldownTimer = -1.0f;
m_reloadTimer = -1.0f;
m_shooting = false;
m_reloading = false;
m_owner->SetStatsChanged(true);
} | 27.062278 | 169 | 0.700243 | Mertank |
5fd39842abda1a0200ca32e1f96fef3c75824d1f | 10,470 | cc | C++ | wrspice/devlib/mos/mossetm.cc | wrcad/xictools | f46ba6d42801426739cc8b2940a809b74f1641e2 | [
"Apache-2.0"
] | 73 | 2017-10-26T12:40:24.000Z | 2022-03-02T16:59:43.000Z | wrspice/devlib/mos/mossetm.cc | chris-ayala/xictools | 4ea72c118679caed700dab3d49a8d36445acaec3 | [
"Apache-2.0"
] | 12 | 2017-11-01T10:18:22.000Z | 2022-03-20T19:35:36.000Z | wrspice/devlib/mos/mossetm.cc | chris-ayala/xictools | 4ea72c118679caed700dab3d49a8d36445acaec3 | [
"Apache-2.0"
] | 34 | 2017-10-06T17:04:21.000Z | 2022-02-18T16:22:03.000Z |
/*========================================================================*
* *
* Distributed by Whiteley Research Inc., Sunnyvale, California, USA *
* http://wrcad.com *
* Copyright (C) 2017 Whiteley Research Inc., all rights reserved. *
* Author: Stephen R. Whiteley, except as indicated. *
* *
* As fully as possible recognizing licensing terms and conditions *
* imposed by earlier work from which this work was derived, if any, *
* this work is released under the Apache License, Version 2.0 (the *
* "License"). You may not use this file except in compliance with *
* the License, and compliance with inherited licenses which are *
* specified in a sub-header below this one if applicable. A copy *
* of the License is provided with this distribution, or you may *
* obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* See the License for the specific language governing permissions *
* and limitations under the License. *
* *
* 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 NON- *
* INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED *
* OR STEPHEN R. WHITELEY 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. *
* *
*========================================================================*
* XicTools Integrated Circuit Design System *
* *
* WRspice Circuit Simulation and Analysis Tool: Device Library *
* *
*========================================================================*
$Id:$
*========================================================================*/
/***************************************************************************
JSPICE3 adaptation of Spice3f2 - Copyright (c) Stephen R. Whiteley 1992
Copyright 1990 Regents of the University of California. All rights reserved.
Authors: 1985 Thomas L. Quarles
1989 Takayasu Sakurai
1993 Stephen R. Whiteley
****************************************************************************/
#include "mosdefs.h"
int
MOSdev::setModl(int param, IFdata *data, sGENmodel *genmod)
{
sMOSmodel *model = static_cast<sMOSmodel*>(genmod);
IFvalue *value = &data->v;
switch (param) {
case MOS_MOD_LEVEL:
model->MOSlevel = value->iValue;
model->MOSlevelGiven = true;
break;
case MOS_MOD_TNOM:
model->MOStnom = value->rValue+CONSTCtoK;
model->MOStnomGiven = true;
break;
case MOS_MOD_VTO:
model->MOSvt0 = value->rValue;
model->MOSvt0Given = true;
break;
case MOS_MOD_KP:
model->MOStransconductance = value->rValue;
model->MOStransconductanceGiven = true;
break;
case MOS_MOD_GAMMA:
model->MOSgamma = value->rValue;
model->MOSgammaGiven = true;
break;
case MOS_MOD_PHI:
model->MOSphi = value->rValue;
model->MOSphiGiven = true;
break;
case MOS_MOD_RD:
model->MOSdrainResistance = value->rValue;
model->MOSdrainResistanceGiven = true;
break;
case MOS_MOD_RS:
model->MOSsourceResistance = value->rValue;
model->MOSsourceResistanceGiven = true;
break;
case MOS_MOD_CBD:
model->MOScapBD = value->rValue;
model->MOScapBDGiven = true;
break;
case MOS_MOD_CBS:
model->MOScapBS = value->rValue;
model->MOScapBSGiven = true;
break;
case MOS_MOD_IS:
model->MOSjctSatCur = value->rValue;
model->MOSjctSatCurGiven = true;
break;
case MOS_MOD_PB:
model->MOSbulkJctPotential = value->rValue;
model->MOSbulkJctPotentialGiven = true;
break;
case MOS_MOD_CGSO:
model->MOSgateSourceOverlapCapFactor = value->rValue;
model->MOSgateSourceOverlapCapFactorGiven = true;
break;
case MOS_MOD_CGDO:
model->MOSgateDrainOverlapCapFactor = value->rValue;
model->MOSgateDrainOverlapCapFactorGiven = true;
break;
case MOS_MOD_CGBO:
model->MOSgateBulkOverlapCapFactor = value->rValue;
model->MOSgateBulkOverlapCapFactorGiven = true;
break;
case MOS_MOD_CJ:
model->MOSbulkCapFactor = value->rValue;
model->MOSbulkCapFactorGiven = true;
break;
case MOS_MOD_MJ:
model->MOSbulkJctBotGradingCoeff = value->rValue;
model->MOSbulkJctBotGradingCoeffGiven = true;
break;
case MOS_MOD_CJSW:
model->MOSsideWallCapFactor = value->rValue;
model->MOSsideWallCapFactorGiven = true;
break;
case MOS_MOD_MJSW:
model->MOSbulkJctSideGradingCoeff = value->rValue;
model->MOSbulkJctSideGradingCoeffGiven = true;
break;
case MOS_MOD_JS:
model->MOSjctSatCurDensity = value->rValue;
model->MOSjctSatCurDensityGiven = true;
break;
case MOS_MOD_TOX:
model->MOSoxideThickness = value->rValue;
model->MOSoxideThicknessGiven = true;
break;
case MOS_MOD_LD:
model->MOSlatDiff = value->rValue;
model->MOSlatDiffGiven = true;
break;
case MOS_MOD_RSH:
model->MOSsheetResistance = value->rValue;
model->MOSsheetResistanceGiven = true;
break;
case MOS_MOD_U0:
model->MOSsurfaceMobility = value->rValue;
model->MOSsurfaceMobilityGiven = true;
break;
case MOS_MOD_FC:
model->MOSfwdCapDepCoeff = value->rValue;
model->MOSfwdCapDepCoeffGiven = true;
break;
case MOS_MOD_NSS:
model->MOSsurfaceStateDensity = value->rValue;
model->MOSsurfaceStateDensityGiven = true;
break;
case MOS_MOD_NSUB:
model->MOSsubstrateDoping = value->rValue;
model->MOSsubstrateDopingGiven = true;
break;
case MOS_MOD_TPG:
model->MOSgateType = value->iValue;
model->MOSgateTypeGiven = true;
break;
case MOS_MOD_NMOS:
if(value->iValue) {
model->MOStype = 1;
model->MOStypeGiven = true;
}
break;
case MOS_MOD_PMOS:
if(value->iValue) {
model->MOStype = -1;
model->MOStypeGiven = true;
}
break;
case MOS_MOD_KF:
model->MOSfNcoef = value->rValue;
model->MOSfNcoefGiven = true;
break;
case MOS_MOD_AF:
model->MOSfNexp = value->rValue;
model->MOSfNexpGiven = true;
break;
case MOS_MOD_LAMBDA:
/* levels 1 and 2 */
model->MOSlambda = value->rValue;
model->MOSlambdaGiven = true;
break;
case MOS_MOD_UEXP:
/* level 2 */
model->MOScritFieldExp = value->rValue;
model->MOScritFieldExpGiven = true;
break;
case MOS_MOD_NEFF:
/* level 2 */
model->MOSchannelCharge = value->rValue;
model->MOSchannelChargeGiven = true;
break;
case MOS_MOD_UCRIT:
/* level 2 */
model->MOScritField = value->rValue;
model->MOScritFieldGiven = true;
break;
case MOS_MOD_NFS:
/* levels 2 and 3 */
model->MOSfastSurfaceStateDensity = value->rValue;
model->MOSfastSurfaceStateDensityGiven = true;
break;
case MOS_MOD_DELTA:
/* levels 2 and 3 */
model->MOSnarrowFactor = value->rValue;
model->MOSnarrowFactorGiven = true;
break;
case MOS_MOD_VMAX:
/* levels 2 and 3 */
model->MOSmaxDriftVel = value->rValue;
model->MOSmaxDriftVelGiven = true;
break;
case MOS_MOD_XJ:
/* levels 2 and 3 */
model->MOSjunctionDepth = value->rValue;
model->MOSjunctionDepthGiven = true;
break;
case MOS_MOD_ETA:
/* level 3 */
model->MOSeta = value->rValue;
model->MOSetaGiven = true;
break;
case MOS_MOD_THETA:
/* level 3 */
model->MOStheta = value->rValue;
model->MOSthetaGiven = true;
break;
case MOS_MOD_KAPPA:
/* level 3 */
model->MOSkappa = value->rValue;
model->MOSkappaGiven = true;
break;
case MOS_MOD_KV:
/* level 6 */
model->MOSkv = value->rValue;
model->MOSkvGiven = true;
break;
case MOS_MOD_NV:
/* level 6 */
model->MOSnv = value->rValue;
model->MOSnvGiven = true;
break;
case MOS_MOD_KC:
/* level 6 */
model->MOSkc = value->rValue;
model->MOSkcGiven = true;
break;
case MOS_MOD_NC:
/* level 6 */
model->MOSnc = value->rValue;
model->MOSncGiven = true;
break;
case MOS_MOD_GAMMA1:
/* level 6 */
model->MOSgamma1 = value->rValue;
model->MOSgamma1Given = true;
break;
case MOS_MOD_SIGMA:
/* level 6 */
model->MOSsigma = value->rValue;
model->MOSsigmaGiven = true;
break;
case MOS_MOD_LAMDA0:
/* level 6 */
model->MOSlamda0 = value->rValue;
model->MOSlamda0Given = true;
break;
case MOS_MOD_LAMDA1:
/* level 6 */
model->MOSlamda1 = value->rValue;
model->MOSlamda1Given = true;
break;
default:
return (E_BADPARM);
}
return (OK);
}
| 35.979381 | 77 | 0.533715 | wrcad |
5fd4e83c4342a0a31ee949f1b9e89980fd360f03 | 11,966 | cpp | C++ | src/QtAudio/CiosAudio/CaDebug.cpp | Vladimir-Lin/QtAudio | 5c58e86cda1a88f03c4dde53883a979bec37b504 | [
"MIT"
] | null | null | null | src/QtAudio/CiosAudio/CaDebug.cpp | Vladimir-Lin/QtAudio | 5c58e86cda1a88f03c4dde53883a979bec37b504 | [
"MIT"
] | null | null | null | src/QtAudio/CiosAudio/CaDebug.cpp | Vladimir-Lin/QtAudio | 5c58e86cda1a88f03c4dde53883a979bec37b504 | [
"MIT"
] | null | null | null | /*****************************************************************************
* *
* CIOS Audio Core *
* *
* Version : 1.5.11 *
* Author : Brian Lin <[email protected]> *
* Skpye : wolfram_lin *
* Lastest update : 2014/12/18 *
* Site : http://ciosaudio.sourceforge.net *
* License : LGPLv3 *
* *
* Documents are separated, you will receive the full document when you *
* download the source code. It is all-in-one, there is no comment in the *
* source code. *
* *
*****************************************************************************/
#include "CiosAudioPrivate.hpp"
#if _MSC_VER
#define VSNPRINTF _vsnprintf
#define LOG_BUF_SIZE 2048
#else
#define VSNPRINTF vsnprintf
#endif
#ifdef DONT_USE_NAMESPACE
#else
namespace CAC_NAMESPACE {
#endif
typedef struct CaHostErrorInfo {
CaHostApiTypeId hostApiType ; /**< the host API which returned the error code */
long errorCode ; /**< the error code returned */
const char * errorText ; /**< a textual description of the error if available, otherwise a zero-length string */
} CaHostErrorInfo ;
#define CA_LAST_HOST_ERROR_TEXT_LENGTH_ 1024
static char lastHostErrorText_[ CA_LAST_HOST_ERROR_TEXT_LENGTH_ + 1 ] = {0};
static CaHostErrorInfo lastHostErrorInfo_ = {
(CaHostApiTypeId)-1 ,
0 ,
lastHostErrorText_ } ;
void SetLastHostErrorInfo ( CaHostApiTypeId hostApiType ,
long errorCode ,
const char * errorText )
{
lastHostErrorInfo_ . hostApiType = hostApiType ;
lastHostErrorInfo_ . errorCode = errorCode ;
if ( NULL == errorText ) return ;
::strncpy( lastHostErrorText_ ,
errorText ,
CA_LAST_HOST_ERROR_TEXT_LENGTH_ ) ;
}
Debugger:: Debugger (void)
{
}
Debugger::~Debugger (void)
{
}
const char * Debugger::lastError (void)
{
return lastHostErrorText_ ;
}
void Debugger::printf(const char * format,...)
{
// Optional logging into Output console of Visual Studio
#if defined(_MSC_VER) && defined(ENABLE_MSVC_DEBUG_OUTPUT)
char buf [ LOG_BUF_SIZE ] ;
va_list ap ;
va_start ( ap , format ) ;
VSNPRINTF ( buf , sizeof(buf) , format , ap ) ;
buf[sizeof(buf)-1] = 0 ;
OutputDebugStringA ( buf ) ;
va_end ( ap ) ;
#else
va_list ap ;
va_start ( ap , format ) ;
vfprintf ( stderr , format , ap ) ;
va_end ( ap ) ;
fflush ( stderr ) ;
#endif
}
const char * Debugger::Error(CaError errorCode)
{
const char * result = NULL ;
switch ( errorCode ) {
case NoError :
result = "Success" ;
break ;
case NotInitialized :
result = "CIOS Audio Core not initialized" ;
break ;
case UnanticipatedHostError :
result = "Unanticipated host error" ;
break ;
case InvalidChannelCount :
result = "Invalid number of channels" ;
break ;
case InvalidSampleRate :
result = "Invalid sample rate" ;
break ;
case InvalidDevice :
result = "Invalid device" ;
break ;
case InvalidFlag :
result = "Invalid flag" ;
break ;
case SampleFormatNotSupported :
result = "Sample format not supported" ;
break ;
case BadIODeviceCombination :
result = "Illegal combination of I/O devices" ;
break ;
case InsufficientMemory :
result = "Insufficient memory" ;
break ;
case BufferTooBig :
result = "Buffer too big" ;
break ;
case BufferTooSmall :
result = "Buffer too small" ;
break ;
case NullCallback :
result = "No callback routine specified" ;
break ;
case BadStreamPtr :
result = "Invalid stream pointer" ;
break ;
case TimedOut :
result = "Wait timed out" ;
break ;
case InternalError :
result = "Internal CIOS Audio error" ;
break ;
case DeviceUnavailable :
result = "Device unavailable" ;
break ;
case IncompatibleStreamInfo :
result = "Incompatible host API specific stream info" ;
break ;
case StreamIsStopped :
result = "Stream is stopped" ;
break ;
case StreamIsNotStopped :
result = "Stream is not stopped" ;
break ;
case InputOverflowed :
result = "Input overflowed" ;
break ;
case OutputUnderflowed :
result = "Output underflowed" ;
break ;
case HostApiNotFound :
result = "Host API not found" ;
break ;
case InvalidHostApi :
result = "Invalid host API" ;
break ;
case CanNotReadFromACallbackStream :
result = "Can't read from a callback stream" ;
break ;
case CanNotWriteToACallbackStream :
result = "Can't write to a callback stream" ;
break ;
case CanNotReadFromAnOutputOnlyStream :
result = "Can't read from an output only stream" ;
break ;
case CanNotWriteToAnInputOnlyStream :
result = "Can't write to an input only stream" ;
break ;
case IncompatibleStreamHostApi :
result = "Incompatible stream host API" ;
break ;
case BadBufferPtr :
result = "Bad buffer pointer" ;
break ;
default :
if( errorCode > 0 ) result = "Invalid error code (value greater than zero)" ;
else result = "Invalid error code" ;
break ;
} ;
return result ;
}
#ifdef DONT_USE_NAMESPACE
#else
}
#endif
| 60.434343 | 120 | 0.272606 | Vladimir-Lin |
5fde1048e3ba09396e3eb85d31727a63a0b41224 | 5,841 | hh | C++ | cc/record.hh | skepner/dtra2 | 5aeeb66cd8e42217976ae0ad481dcc42549e6bf0 | [
"MIT"
] | null | null | null | cc/record.hh | skepner/dtra2 | 5aeeb66cd8e42217976ae0ad481dcc42549e6bf0 | [
"MIT"
] | null | null | null | cc/record.hh | skepner/dtra2 | 5aeeb66cd8e42217976ae0ad481dcc42549e6bf0 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include "date.hh"
// ----------------------------------------------------------------------
namespace xlnt
{
class cell;
}
namespace dtra
{
inline namespace v2
{
class Directory;
// --------------------------------------------------
class Record
{
public:
void importer_default(const xlnt::cell& cell);
void exporter_default(xlnt::cell& cell) const;
std::string csv_exporter_default() const { return {}; }
void allow_zero_date(bool allow_zero_date);
std::string validate(const Directory& locations, const Directory& birds);
std::pair<std::string, bool> merge(const Record& rec, bool resolve_conflict_with_merge_in);
static std::string new_record_id();
void reset_record_id() { record_id_ = new_record_id(); }
static constexpr const char* re_sample_id = "^(217|DT)-[0-9]+$";
static constexpr const char* sample_id_message = "expected: 217-xxxxx, DT-xxxxx";
static constexpr const char* re_ct = "^[<>]?[0-9]+(\\.[0-9][0-9]?)?$";
static constexpr const char* ct_message = "expected: valid CT Value";
static constexpr const char* re_h_status = "^(P|N)$";
static constexpr const char* h_status_message = "expected: P or N";
static constexpr const char* re_pathotype = "^(LPAI|HPAI)$";
static constexpr const char* pathotype_message = "expected: LPAI or HPAI";
static constexpr const char* re_egg_passage = "^(0|1)$";
static constexpr const char* egg_passage_message = "expected: 0 or 1";
static std::string new_record_id_;
field::Uppercase sample_id_{re_sample_id, sample_id_message, field::can_be_empty::no};
field::Date collection_date_{field::can_be_empty::no};
field::Text species_;
field::Uppercase age_{"^[HAU]$", "expected: H, A, U", field::can_be_empty::no};
field::Uppercase sex_{"^[MFU]$", "expected Sex: M, F, U", field::can_be_empty::no};
field::Text ring_number_;
field::Uppercase host_identifier_{re_sample_id, sample_id_message};
field::Text host_species_;
field::Text host_common_name_;
field::Uppercase health_{"^[HSDU]$", "expected: H(ealthy), S(ick), D(ead), U(undetermined)"};
field::Uppercase capture_method_status_{"^(A|K|O|M|P|Z|F|U|OT.*)$", "expected: A, K, O, M, P, Z, F, OT-<text>, U"}; // see bottom of record.cc
field::Uppercase behavior_{"^(W|D|CW|U)$", "expected: W(ild), D(omestic), CW (captive-wild), U(known)"};
field::Text location_{field::can_be_empty::no};
field::Text province_;
field::Text country_;
field::Float latitude_{-90, 90};
field::Float longitude_{-180, 180};
field::Uppercase sample_material_{"^(TS|OP|C|F|COP|B|SR|TT|CF|TB|TO|L|S|W|O[- ].+|X.*)$", "expected: TS, OP, C, F, COP, B, SR, TT, CF, TB, TO, L, S, W, O -<text>, X-<text>"}; // see bottom of record.cc
field::Uppercase test_for_influenza_virus_; // {"^RRT-PCR +MA( *,? *RRT-PCR +H5( *,? *RRT-PCR +H7)?)?$", "expected: RRT-PCR MA, RRT-PCR H5, RRT-PCR H7"}
field::Date date_of_testing_;
field::Uppercase pool_id_{"^[0-9\\.]+$", "expected: numeric value"};
field::Uppercase influenza_test_result_{"^(P|N)$", "expected: P, N"};
field::Uppercase ma_ct_value_{re_ct, ct_message};
field::Uppercase h5_status_{re_h_status, h_status_message};
field::Uppercase h5_ct_value_{re_ct, ct_message};
field::Uppercase h5_pathotype_{re_pathotype, pathotype_message};
field::Uppercase h7_status_{re_h_status, h_status_message};
field::Uppercase h7_ct_value_{re_ct, ct_message};
field::Uppercase h7_pathotype_{re_pathotype, pathotype_message};
field::Uppercase h9_status_{re_h_status, h_status_message};
field::Uppercase h9_ct_value_{re_ct, ct_message};
field::Text emc_id_;
field::Text ahvla_id_;
field::Uppercase first_egg_passage_{re_egg_passage, egg_passage_message};
field::Uppercase second_egg_passage_{re_egg_passage, egg_passage_message};
field::Uppercase passage_isolation_{"^(E1|E2|NOT *PERFORMED|NEGATIVE)$", "expected: E1, E2, not performed"};
field::Uppercase virus_pathotype_{"^(LPAI|HPAI|NOT *IDENTIFIABLE)$", "expected: LPAI, HPAI, notidentifiable"};
field::Uppercase haemagglutinin_subtype_{"^((H[1-9]|H1[0-6])(/(H[1-9]|H1[0-6]))*|MIXED|H +NOT +DETERMINED)$", "expected: H1-H16, mixed, H not determined"};
field::Uppercase neuraminidase_subtype_{"^(N[1-9](/N[1-9])*|MIXED|N +NOT +DETERMINED)$", "expected: N1-N9, mixed, N not determined"};
field::Uppercase serology_sample_id_{re_sample_id, sample_id_message};
field::Date serology_testing_date_;
field::Uppercase serology_status_{"^(\\+|-|\\*)$", "expected: +, -, *"};
field::Text record_id_;
private:
void validate_hostspecies_commonname(const Directory& birds, std::vector<std::string>& reports);
void check_dates(std::vector<std::string>& reports);
void update_locations(const Directory& locations, std::vector<std::string>& reports);
void update_behavior(std::vector<std::string>& reports);
};
} // namespace v2
} // namespace dtra
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
| 54.588785 | 213 | 0.588255 | skepner |
5fe35e13763aab39c3aa3d34251ef07e01a67fae | 921 | cpp | C++ | HDUOJ/1020.cpp | Accelerator404/Algorithm-Demonstration | e40a499c23a56d363c743c76ac967d9c4247a4be | [
"Apache-2.0"
] | 1 | 2019-09-18T23:45:27.000Z | 2019-09-18T23:45:27.000Z | HDUOJ/1020.cpp | Accelerator404/Algorithm-Demonstration | e40a499c23a56d363c743c76ac967d9c4247a4be | [
"Apache-2.0"
] | null | null | null | HDUOJ/1020.cpp | Accelerator404/Algorithm-Demonstration | e40a499c23a56d363c743c76ac967d9c4247a4be | [
"Apache-2.0"
] | 1 | 2019-09-18T23:45:28.000Z | 2019-09-18T23:45:28.000Z | #include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
using namespace std;
//to_string要求C++11
int main()
{
int N;
cin >> N;
for(int i=1;i <= N;i++){
char target;
string input,output;
int count = 0;
cin >> input;
for(int j = 0;j < input.length();j++){
if(j == 0){
target = input[j];
count++;
}
else if(target != input[j]){
if(count>1){
output.append(to_string(count));
}
output+=target;
count = 0;
target = input[j];
count++;
}
else{
count++;
}
}
if(count>1){
output.append(to_string(count));
}
output+=target;
cout << output << endl;
}
return 0;
}
| 20.931818 | 52 | 0.394137 | Accelerator404 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.