text
stringlengths 8
6.88M
|
|---|
#ifndef QMYWIDGETACTION_H
#define QMYWIDGETACTION_H
#include <QWidgetAction>
#include <QObject>
#include <QCheckBox>
#include <QWidget>
#include <QHBoxLayout>
namespace FastCAEDesigner
{
class QFWidgetAction : public QWidgetAction
{
Q_OBJECT
public:
QFWidgetAction(QWidget *parent = 0);
~QFWidgetAction();
public:
void SetText(QString text);
QString GetText();
void SetChechBoxChecked(bool on);
bool getCheckBoxChecked();
protected:
virtual QWidget *createWidget(QWidget *parent);
public slots:
void OnCheckBoxStateChanged(int state);
signals:
void signal_CheckBoxStateChanged(int state);
public:
protected:
private:
QCheckBox* _checkBox;
QWidget* _widget;
QHBoxLayout *_hlayout;
QString _text{};
QString _name{};
};
}
#endif // QMYWIDGETACTION_H
|
#ifndef QEMUCSD_TESTS_H
#define QEMUCSD_TESTS_H
#include <cstddef>
#include <cmath>
#include <cstdint>
#endif //QEMUCSD_TESTS_H
|
class Solution {
public:
double myPow(double x, int n) {
if(x==0)
return 0;
if(n==0)
return 1;
double temp=myPow(x,n/2);
if(n%2==0)
return (temp*temp);
else
{
if(n>0)
return (x*temp*temp);
else
return (temp*temp)/x;
}
}
};
|
#pragma once
#include "Perceptron.h"
#include <array>
#define DEFAULT_PERCEPTRON_TRESHOLD 1
template <int dimension>
class SinglePerceptronNetwork {
float learning_step{};
Perceptron<dimension> perceptron = Perceptron<2>{DEFAULT_PERCEPTRON_TRESHOLD};
public:
SinglePerceptronNetwork() = default;
explicit SinglePerceptronNetwork(float learningStep);
void train(std::vector<std::pair<std::array<float, dimension>, float>> data);
float perform(std::array<float, dimension> data);
};
template class SinglePerceptronNetwork<2>;
|
#include <iostream>
using namespace std;
void main()
{
int N;
float f;
cout << "실수 입력: ";
cin >> f;
N = f+0.5;
cout << "반올림 정수 출력: " << N;
}
|
#include "mainwidget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication mainApp(argc, argv);
MainWidget *mainWidget = new MainWidget;
mainWidget->show();
mainWidget->run();
return mainApp.exec();
}
|
#include "SpriteWithHue.h"
void xRotateMat(float mat[3][3], float rs, float rc);
void yRotateMat(float mat[3][3], float rs, float rc);
void zRotateMat(float mat[3][3], float rs, float rc);
void matrixMult(float a[3][3], float b[3][3], float c[3][3]);
void hueMatrix(GLfloat mat[3][3], float angle);
void premultiplyAlpha(GLfloat mat[3][3], float alpha);
cocos2d::Map<std::string, GLProgram*>* SpriteWithHue::s_glProgramHueCache = nullptr;
SpriteWithHue::SpriteWithHue()
{
m_hue = 0.0f;
}
SpriteWithHue::~SpriteWithHue()
{
}
SpriteWithHue* SpriteWithHue::create(const std::string& filename)
{
SpriteWithHue *sprite = new (std::nothrow) SpriteWithHue();
if (sprite && sprite->initWithFile(filename.c_str()))
{
sprite->autorelease();
return sprite;
}
CC_SAFE_DELETE(sprite);
return nullptr;
}
bool SpriteWithHue::initWithTexture(Texture2D *texture, const Rect& rect, bool rotated)
{
if (!Sprite::initWithTexture(texture, rect, rotated)) {
return false;
}
// this->setupDefaultSettings();
this->addShader();
return true;
}
void SpriteWithHue::setupDefaultSettings()
{
this->m_hue = 0.0;
}
void SpriteWithHue::initShader()
{
GLProgram * p = new GLProgram();
this->setGLProgram(p);
p->release();
p->initWithFilenames("shader/hueChange.vsh", "shader/hueChange.fsh");
p->link();
p->updateUniforms();
this->getUniformLocations();
this->updateColor();
}
GLProgram* SpriteWithHue::addShader(const char *shaderName)
{
// Ôö¼Ó»º´æ»úÖÆ
if (!s_glProgramHueCache)
s_glProgramHueCache = new cocos2d::Map<std::string, GLProgram*>();
GLProgram* program = s_glProgramHueCache->at(shaderName);
if (!program)
{
program = new GLProgram();
program->autorelease();
program->initWithFilenames("shader/hueChange.vsh", "shader/hueChange.fsh");
program->link();
program->updateUniforms();
s_glProgramHueCache->insert(shaderName, program);
}
this->setGLProgram(program);
this->getUniformLocations();
this->updateColor();
return program;
}
void SpriteWithHue::getUniformLocations()
{
m_hueLocation = glGetUniformLocation(this->getGLProgram()->getProgram(), "u_hue");
m_alphaLocation = glGetUniformLocation(this->getGLProgram()->getProgram(), "u_alpha");
}
void SpriteWithHue::updateColorMatrix()
{
this->getGLProgram()->use();
GLfloat mat[3][3];
memset(mat, 0, sizeof(GLfloat)*9);
hueMatrix(mat, m_hue);
premultiplyAlpha(mat, this->alpha());
glUniformMatrix3fv(m_hueLocation, 1, GL_FALSE, (GLfloat *)&mat);
}
void SpriteWithHue::updateAlpha()
{
this->getGLProgram()->use();
glUniform1f(m_alphaLocation, this->alpha());
}
GLfloat SpriteWithHue::alpha()
{
return _displayedOpacity / 255.0f;
}
void SpriteWithHue::setHue(GLfloat _hue)
{
m_hue = _hue;
this->updateColorMatrix();
}
void SpriteWithHue::updateColor()
{
Sprite::updateColor();
this->updateColorMatrix();
this->updateAlpha();
}
SpriteWithHue* SpriteWithHue::createWithTexture(Texture2D *texture, GLfloat hue)
{
SpriteWithHue *pobSprite = new SpriteWithHue();
pobSprite->m_hue = hue;
Rect rect = Rect::ZERO;
rect.size = texture->getContentSize();
if (pobSprite && pobSprite->initWithTexture(texture, rect, false))
{
pobSprite->autorelease();
return pobSprite;
}
CC_SAFE_DELETE(pobSprite);
return NULL;
}
void xRotateMat(float mat[3][3], float rs, float rc)
{
mat[0][0] = 1.0;
mat[0][1] = 0.0;
mat[0][2] = 0.0;
mat[1][0] = 0.0;
mat[1][1] = rc;
mat[1][2] = rs;
mat[2][0] = 0.0;
mat[2][1] = -rs;
mat[2][2] = rc;
}
void yRotateMat(float mat[3][3], float rs, float rc)
{
mat[0][0] = rc;
mat[0][1] = 0.0;
mat[0][2] = -rs;
mat[1][0] = 0.0;
mat[1][1] = 1.0;
mat[1][2] = 0.0;
mat[2][0] = rs;
mat[2][1] = 0.0;
mat[2][2] = rc;
}
void zRotateMat(float mat[3][3], float rs, float rc)
{
mat[0][0] = rc;
mat[0][1] = rs;
mat[0][2] = 0.0;
mat[1][0] = -rs;
mat[1][1] = rc;
mat[1][2] = 0.0;
mat[2][0] = 0.0;
mat[2][1] = 0.0;
mat[2][2] = 1.0;
}
void matrixMult(float a[3][3], float b[3][3], float c[3][3])
{
int x, y;
float temp[3][3];
for(y=0; y<3; y++) {
for(x=0; x<3; x++) {
temp[y][x] = b[y][0] * a[0][x] + b[y][1] * a[1][x] + b[y][2] * a[2][x];
}
}
for(y=0; y<3; y++) {
for(x=0; x<3; x++) {
c[y][x] = temp[y][x];
}
}
}
void hueMatrix(GLfloat mat[3][3], float angle)
{
#define SQRT_2 sqrt(2.0)
#define SQRT_3 sqrt(3.0)
float mag, rot[3][3];
float xrs, xrc;
float yrs, yrc;
float zrs, zrc;
// Rotate the grey vector into positive Z
mag = SQRT_2;
xrs = 1.0/mag;
xrc = 1.0/mag;
xRotateMat(mat, xrs, xrc);
mag = SQRT_3;
yrs = -1.0/mag;
yrc = SQRT_2/mag;
yRotateMat(rot, yrs, yrc);
matrixMult(rot, mat, mat);
// Rotate the hue
zrs = sin(angle);
zrc = cos(angle);
zRotateMat(rot, zrs, zrc);
matrixMult(rot, mat, mat);
// Rotate the grey vector back into place
yRotateMat(rot, -yrs, yrc);
matrixMult(rot, mat, mat);
xRotateMat(rot, -xrs, xrc);
matrixMult(rot, mat, mat);
}
void premultiplyAlpha(GLfloat mat[3][3], float alpha)
{
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
mat[i][j] *= alpha;
}
}
}
|
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "unstarted_runtime.h"
#include <limits>
#include <locale>
#include "base/casts.h"
#include "base/memory_tool.h"
#include "class_linker.h"
#include "common_runtime_test.h"
#include "dex_instruction.h"
#include "handle.h"
#include "handle_scope-inl.h"
#include "interpreter/interpreter_common.h"
#include "mirror/class_loader.h"
#include "mirror/string-inl.h"
#include "runtime.h"
#include "scoped_thread_state_change.h"
#include "thread.h"
#include "transaction.h"
namespace art {
namespace interpreter {
class UnstartedRuntimeTest : public CommonRuntimeTest {
protected:
// Re-expose all UnstartedRuntime implementations so we don't need to declare a million
// test friends.
// Methods that intercept available libcore implementations.
#define UNSTARTED_DIRECT(Name, SigIgnored) \
static void Unstarted ## Name(Thread* self, \
ShadowFrame* shadow_frame, \
JValue* result, \
size_t arg_offset) \
SHARED_REQUIRES(Locks::mutator_lock_) { \
interpreter::UnstartedRuntime::Unstarted ## Name(self, shadow_frame, result, arg_offset); \
}
#include "unstarted_runtime_list.h"
UNSTARTED_RUNTIME_DIRECT_LIST(UNSTARTED_DIRECT)
#undef UNSTARTED_RUNTIME_DIRECT_LIST
#undef UNSTARTED_RUNTIME_JNI_LIST
#undef UNSTARTED_DIRECT
// Methods that are native.
#define UNSTARTED_JNI(Name, SigIgnored) \
static void UnstartedJNI ## Name(Thread* self, \
ArtMethod* method, \
mirror::Object* receiver, \
uint32_t* args, \
JValue* result) \
SHARED_REQUIRES(Locks::mutator_lock_) { \
interpreter::UnstartedRuntime::UnstartedJNI ## Name(self, method, receiver, args, result); \
}
#include "unstarted_runtime_list.h"
UNSTARTED_RUNTIME_JNI_LIST(UNSTARTED_JNI)
#undef UNSTARTED_RUNTIME_DIRECT_LIST
#undef UNSTARTED_RUNTIME_JNI_LIST
#undef UNSTARTED_JNI
// Helpers for ArrayCopy.
//
// Note: as we have to use handles, we use StackHandleScope to transfer data. Hardcode a size
// of three everywhere. That is enough to test all cases.
static mirror::ObjectArray<mirror::Object>* CreateObjectArray(
Thread* self,
mirror::Class* component_type,
const StackHandleScope<3>& data)
SHARED_REQUIRES(Locks::mutator_lock_) {
Runtime* runtime = Runtime::Current();
mirror::Class* array_type = runtime->GetClassLinker()->FindArrayClass(self, &component_type);
CHECK(array_type != nullptr);
mirror::ObjectArray<mirror::Object>* result =
mirror::ObjectArray<mirror::Object>::Alloc(self, array_type, 3);
CHECK(result != nullptr);
for (size_t i = 0; i < 3; ++i) {
result->Set(static_cast<int32_t>(i), data.GetReference(i));
CHECK(!self->IsExceptionPending());
}
return result;
}
static void CheckObjectArray(mirror::ObjectArray<mirror::Object>* array,
const StackHandleScope<3>& data)
SHARED_REQUIRES(Locks::mutator_lock_) {
CHECK_EQ(array->GetLength(), 3);
CHECK_EQ(data.NumberOfReferences(), 3U);
for (size_t i = 0; i < 3; ++i) {
EXPECT_EQ(data.GetReference(i), array->Get(static_cast<int32_t>(i))) << i;
}
}
void RunArrayCopy(Thread* self,
ShadowFrame* tmp,
bool expect_exception,
mirror::ObjectArray<mirror::Object>* src,
int32_t src_pos,
mirror::ObjectArray<mirror::Object>* dst,
int32_t dst_pos,
int32_t length)
SHARED_REQUIRES(Locks::mutator_lock_) {
JValue result;
tmp->SetVRegReference(0, src);
tmp->SetVReg(1, src_pos);
tmp->SetVRegReference(2, dst);
tmp->SetVReg(3, dst_pos);
tmp->SetVReg(4, length);
UnstartedSystemArraycopy(self, tmp, &result, 0);
bool exception_pending = self->IsExceptionPending();
EXPECT_EQ(exception_pending, expect_exception);
if (exception_pending) {
self->ClearException();
}
}
void RunArrayCopy(Thread* self,
ShadowFrame* tmp,
bool expect_exception,
mirror::Class* src_component_class,
mirror::Class* dst_component_class,
const StackHandleScope<3>& src_data,
int32_t src_pos,
const StackHandleScope<3>& dst_data,
int32_t dst_pos,
int32_t length,
const StackHandleScope<3>& expected_result)
SHARED_REQUIRES(Locks::mutator_lock_) {
StackHandleScope<3> hs_misc(self);
Handle<mirror::Class> dst_component_handle(hs_misc.NewHandle(dst_component_class));
Handle<mirror::ObjectArray<mirror::Object>> src_handle(
hs_misc.NewHandle(CreateObjectArray(self, src_component_class, src_data)));
Handle<mirror::ObjectArray<mirror::Object>> dst_handle(
hs_misc.NewHandle(CreateObjectArray(self, dst_component_handle.Get(), dst_data)));
RunArrayCopy(self,
tmp,
expect_exception,
src_handle.Get(),
src_pos,
dst_handle.Get(),
dst_pos,
length);
CheckObjectArray(dst_handle.Get(), expected_result);
}
void TestCeilFloor(bool ceil,
Thread* self,
ShadowFrame* tmp,
double const test_pairs[][2],
size_t num_pairs)
SHARED_REQUIRES(Locks::mutator_lock_) {
for (size_t i = 0; i < num_pairs; ++i) {
tmp->SetVRegDouble(0, test_pairs[i][0]);
JValue result;
if (ceil) {
UnstartedMathCeil(self, tmp, &result, 0);
} else {
UnstartedMathFloor(self, tmp, &result, 0);
}
ASSERT_FALSE(self->IsExceptionPending());
// We want precise results.
int64_t result_int64t = bit_cast<int64_t, double>(result.GetD());
int64_t expect_int64t = bit_cast<int64_t, double>(test_pairs[i][1]);
EXPECT_EQ(expect_int64t, result_int64t) << result.GetD() << " vs " << test_pairs[i][1];
}
}
// Prepare for aborts. Aborts assume that the exception class is already resolved, as the
// loading code doesn't work under transactions.
void PrepareForAborts() SHARED_REQUIRES(Locks::mutator_lock_) {
mirror::Object* result = Runtime::Current()->GetClassLinker()->FindClass(
Thread::Current(),
Transaction::kAbortExceptionSignature,
ScopedNullHandle<mirror::ClassLoader>());
CHECK(result != nullptr);
}
};
TEST_F(UnstartedRuntimeTest, MemoryPeekByte) {
Thread* self = Thread::Current();
ScopedObjectAccess soa(self);
constexpr const uint8_t base_array[] = "abcdefghijklmnop";
constexpr int32_t kBaseLen = sizeof(base_array) / sizeof(uint8_t);
const uint8_t* base_ptr = base_array;
JValue result;
ShadowFrame* tmp = ShadowFrame::CreateDeoptimizedFrame(10, nullptr, nullptr, 0);
for (int32_t i = 0; i < kBaseLen; ++i) {
tmp->SetVRegLong(0, static_cast<int64_t>(reinterpret_cast<intptr_t>(base_ptr + i)));
UnstartedMemoryPeekByte(self, tmp, &result, 0);
EXPECT_EQ(result.GetB(), static_cast<int8_t>(base_array[i]));
}
ShadowFrame::DeleteDeoptimizedFrame(tmp);
}
TEST_F(UnstartedRuntimeTest, MemoryPeekShort) {
Thread* self = Thread::Current();
ScopedObjectAccess soa(self);
constexpr const uint8_t base_array[] = "abcdefghijklmnop";
constexpr int32_t kBaseLen = sizeof(base_array) / sizeof(uint8_t);
const uint8_t* base_ptr = base_array;
JValue result;
ShadowFrame* tmp = ShadowFrame::CreateDeoptimizedFrame(10, nullptr, nullptr, 0);
int32_t adjusted_length = kBaseLen - sizeof(int16_t);
for (int32_t i = 0; i < adjusted_length; ++i) {
tmp->SetVRegLong(0, static_cast<int64_t>(reinterpret_cast<intptr_t>(base_ptr + i)));
UnstartedMemoryPeekShort(self, tmp, &result, 0);
typedef int16_t unaligned_short __attribute__ ((aligned (1)));
const unaligned_short* short_ptr = reinterpret_cast<const unaligned_short*>(base_ptr + i);
EXPECT_EQ(result.GetS(), *short_ptr);
}
ShadowFrame::DeleteDeoptimizedFrame(tmp);
}
TEST_F(UnstartedRuntimeTest, MemoryPeekInt) {
Thread* self = Thread::Current();
ScopedObjectAccess soa(self);
constexpr const uint8_t base_array[] = "abcdefghijklmnop";
constexpr int32_t kBaseLen = sizeof(base_array) / sizeof(uint8_t);
const uint8_t* base_ptr = base_array;
JValue result;
ShadowFrame* tmp = ShadowFrame::CreateDeoptimizedFrame(10, nullptr, nullptr, 0);
int32_t adjusted_length = kBaseLen - sizeof(int32_t);
for (int32_t i = 0; i < adjusted_length; ++i) {
tmp->SetVRegLong(0, static_cast<int64_t>(reinterpret_cast<intptr_t>(base_ptr + i)));
UnstartedMemoryPeekInt(self, tmp, &result, 0);
typedef int32_t unaligned_int __attribute__ ((aligned (1)));
const unaligned_int* int_ptr = reinterpret_cast<const unaligned_int*>(base_ptr + i);
EXPECT_EQ(result.GetI(), *int_ptr);
}
ShadowFrame::DeleteDeoptimizedFrame(tmp);
}
TEST_F(UnstartedRuntimeTest, MemoryPeekLong) {
Thread* self = Thread::Current();
ScopedObjectAccess soa(self);
constexpr const uint8_t base_array[] = "abcdefghijklmnop";
constexpr int32_t kBaseLen = sizeof(base_array) / sizeof(uint8_t);
const uint8_t* base_ptr = base_array;
JValue result;
ShadowFrame* tmp = ShadowFrame::CreateDeoptimizedFrame(10, nullptr, nullptr, 0);
int32_t adjusted_length = kBaseLen - sizeof(int64_t);
for (int32_t i = 0; i < adjusted_length; ++i) {
tmp->SetVRegLong(0, static_cast<int64_t>(reinterpret_cast<intptr_t>(base_ptr + i)));
UnstartedMemoryPeekLong(self, tmp, &result, 0);
typedef int64_t unaligned_long __attribute__ ((aligned (1)));
const unaligned_long* long_ptr = reinterpret_cast<const unaligned_long*>(base_ptr + i);
EXPECT_EQ(result.GetJ(), *long_ptr);
}
ShadowFrame::DeleteDeoptimizedFrame(tmp);
}
TEST_F(UnstartedRuntimeTest, StringGetCharsNoCheck) {
Thread* self = Thread::Current();
ScopedObjectAccess soa(self);
StackHandleScope<2> hs(self);
// TODO: Actual UTF.
constexpr const char base_string[] = "abcdefghijklmnop";
Handle<mirror::String> h_test_string(hs.NewHandle(
mirror::String::AllocFromModifiedUtf8(self, base_string)));
constexpr int32_t kBaseLen = sizeof(base_string) / sizeof(char) - 1;
Handle<mirror::CharArray> h_char_array(hs.NewHandle(
mirror::CharArray::Alloc(self, kBaseLen)));
// A buffer so we can make sure we only modify the elements targetted.
uint16_t buf[kBaseLen];
JValue result;
ShadowFrame* tmp = ShadowFrame::CreateDeoptimizedFrame(10, nullptr, nullptr, 0);
for (int32_t start_index = 0; start_index < kBaseLen; ++start_index) {
for (int32_t count = 0; count <= kBaseLen; ++count) {
for (int32_t trg_offset = 0; trg_offset < kBaseLen; ++trg_offset) {
// Only do it when in bounds.
if (start_index + count <= kBaseLen && trg_offset + count <= kBaseLen) {
tmp->SetVRegReference(0, h_test_string.Get());
tmp->SetVReg(1, start_index);
tmp->SetVReg(2, count);
tmp->SetVRegReference(3, h_char_array.Get());
tmp->SetVReg(3, trg_offset);
// Copy the char_array into buf.
memcpy(buf, h_char_array->GetData(), kBaseLen * sizeof(uint16_t));
UnstartedStringCharAt(self, tmp, &result, 0);
uint16_t* data = h_char_array->GetData();
bool success = true;
// First segment should be unchanged.
for (int32_t i = 0; i < trg_offset; ++i) {
success = success && (data[i] == buf[i]);
}
// Second segment should be a copy.
for (int32_t i = trg_offset; i < trg_offset + count; ++i) {
success = success && (data[i] == buf[i - trg_offset + start_index]);
}
// Third segment should be unchanged.
for (int32_t i = trg_offset + count; i < kBaseLen; ++i) {
success = success && (data[i] == buf[i]);
}
EXPECT_TRUE(success);
}
}
}
}
ShadowFrame::DeleteDeoptimizedFrame(tmp);
}
TEST_F(UnstartedRuntimeTest, StringCharAt) {
Thread* self = Thread::Current();
ScopedObjectAccess soa(self);
// TODO: Actual UTF.
constexpr const char* base_string = "abcdefghijklmnop";
int32_t base_len = static_cast<int32_t>(strlen(base_string));
mirror::String* test_string = mirror::String::AllocFromModifiedUtf8(self, base_string);
JValue result;
ShadowFrame* tmp = ShadowFrame::CreateDeoptimizedFrame(10, nullptr, nullptr, 0);
for (int32_t i = 0; i < base_len; ++i) {
tmp->SetVRegReference(0, test_string);
tmp->SetVReg(1, i);
UnstartedStringCharAt(self, tmp, &result, 0);
EXPECT_EQ(result.GetI(), base_string[i]);
}
ShadowFrame::DeleteDeoptimizedFrame(tmp);
}
TEST_F(UnstartedRuntimeTest, StringInit) {
Thread* self = Thread::Current();
ScopedObjectAccess soa(self);
mirror::Class* klass = mirror::String::GetJavaLangString();
ArtMethod* method = klass->FindDeclaredDirectMethod("<init>", "(Ljava/lang/String;)V",
sizeof(void*));
// create instruction data for invoke-direct {v0, v1} of method with fake index
uint16_t inst_data[3] = { 0x2070, 0x0000, 0x0010 };
const Instruction* inst = Instruction::At(inst_data);
JValue result;
ShadowFrame* shadow_frame = ShadowFrame::CreateDeoptimizedFrame(10, nullptr, method, 0);
const char* base_string = "hello_world";
mirror::String* string_arg = mirror::String::AllocFromModifiedUtf8(self, base_string);
mirror::String* reference_empty_string = mirror::String::AllocFromModifiedUtf8(self, "");
shadow_frame->SetVRegReference(0, reference_empty_string);
shadow_frame->SetVRegReference(1, string_arg);
interpreter::DoCall<false, false>(method, self, *shadow_frame, inst, inst_data[0], &result);
mirror::String* string_result = reinterpret_cast<mirror::String*>(result.GetL());
EXPECT_EQ(string_arg->GetLength(), string_result->GetLength());
EXPECT_EQ(memcmp(string_arg->GetValue(), string_result->GetValue(),
string_arg->GetLength() * sizeof(uint16_t)), 0);
ShadowFrame::DeleteDeoptimizedFrame(shadow_frame);
}
// Tests the exceptions that should be checked before modifying the destination.
// (Doesn't check the object vs primitive case ATM.)
TEST_F(UnstartedRuntimeTest, SystemArrayCopyObjectArrayTestExceptions) {
Thread* self = Thread::Current();
ScopedObjectAccess soa(self);
JValue result;
ShadowFrame* tmp = ShadowFrame::CreateDeoptimizedFrame(10, nullptr, nullptr, 0);
// Note: all tests are not GC safe. Assume there's no GC running here with the few objects we
// allocate.
StackHandleScope<2> hs_misc(self);
Handle<mirror::Class> object_class(
hs_misc.NewHandle(mirror::Class::GetJavaLangClass()->GetSuperClass()));
StackHandleScope<3> hs_data(self);
hs_data.NewHandle(mirror::String::AllocFromModifiedUtf8(self, "1"));
hs_data.NewHandle(mirror::String::AllocFromModifiedUtf8(self, "2"));
hs_data.NewHandle(mirror::String::AllocFromModifiedUtf8(self, "3"));
Handle<mirror::ObjectArray<mirror::Object>> array(
hs_misc.NewHandle(CreateObjectArray(self, object_class.Get(), hs_data)));
RunArrayCopy(self, tmp, true, array.Get(), -1, array.Get(), 0, 0);
RunArrayCopy(self, tmp, true, array.Get(), 0, array.Get(), -1, 0);
RunArrayCopy(self, tmp, true, array.Get(), 0, array.Get(), 0, -1);
RunArrayCopy(self, tmp, true, array.Get(), 0, array.Get(), 0, 4);
RunArrayCopy(self, tmp, true, array.Get(), 0, array.Get(), 1, 3);
RunArrayCopy(self, tmp, true, array.Get(), 1, array.Get(), 0, 3);
mirror::ObjectArray<mirror::Object>* class_as_array =
reinterpret_cast<mirror::ObjectArray<mirror::Object>*>(object_class.Get());
RunArrayCopy(self, tmp, true, class_as_array, 0, array.Get(), 0, 0);
RunArrayCopy(self, tmp, true, array.Get(), 0, class_as_array, 0, 0);
ShadowFrame::DeleteDeoptimizedFrame(tmp);
}
TEST_F(UnstartedRuntimeTest, SystemArrayCopyObjectArrayTest) {
Thread* self = Thread::Current();
ScopedObjectAccess soa(self);
JValue result;
ShadowFrame* tmp = ShadowFrame::CreateDeoptimizedFrame(10, nullptr, nullptr, 0);
StackHandleScope<1> hs_object(self);
Handle<mirror::Class> object_class(
hs_object.NewHandle(mirror::Class::GetJavaLangClass()->GetSuperClass()));
// Simple test:
// [1,2,3]{1 @ 2} into [4,5,6] = [4,2,6]
{
StackHandleScope<3> hs_src(self);
hs_src.NewHandle(mirror::String::AllocFromModifiedUtf8(self, "1"));
hs_src.NewHandle(mirror::String::AllocFromModifiedUtf8(self, "2"));
hs_src.NewHandle(mirror::String::AllocFromModifiedUtf8(self, "3"));
StackHandleScope<3> hs_dst(self);
hs_dst.NewHandle(mirror::String::AllocFromModifiedUtf8(self, "4"));
hs_dst.NewHandle(mirror::String::AllocFromModifiedUtf8(self, "5"));
hs_dst.NewHandle(mirror::String::AllocFromModifiedUtf8(self, "6"));
StackHandleScope<3> hs_expected(self);
hs_expected.NewHandle(hs_dst.GetReference(0));
hs_expected.NewHandle(hs_dst.GetReference(1));
hs_expected.NewHandle(hs_src.GetReference(1));
RunArrayCopy(self,
tmp,
false,
object_class.Get(),
object_class.Get(),
hs_src,
1,
hs_dst,
2,
1,
hs_expected);
}
// Simple test:
// [1,2,3]{1 @ 1} into [4,5,6] = [4,2,6] (with dst String[])
{
StackHandleScope<3> hs_src(self);
hs_src.NewHandle(mirror::String::AllocFromModifiedUtf8(self, "1"));
hs_src.NewHandle(mirror::String::AllocFromModifiedUtf8(self, "2"));
hs_src.NewHandle(mirror::String::AllocFromModifiedUtf8(self, "3"));
StackHandleScope<3> hs_dst(self);
hs_dst.NewHandle(mirror::String::AllocFromModifiedUtf8(self, "4"));
hs_dst.NewHandle(mirror::String::AllocFromModifiedUtf8(self, "5"));
hs_dst.NewHandle(mirror::String::AllocFromModifiedUtf8(self, "6"));
StackHandleScope<3> hs_expected(self);
hs_expected.NewHandle(hs_dst.GetReference(0));
hs_expected.NewHandle(hs_src.GetReference(1));
hs_expected.NewHandle(hs_dst.GetReference(2));
RunArrayCopy(self,
tmp,
false,
object_class.Get(),
mirror::String::GetJavaLangString(),
hs_src,
1,
hs_dst,
1,
1,
hs_expected);
}
// Simple test:
// [1,*,3] into [4,5,6] = [1,5,6] + exc
{
StackHandleScope<3> hs_src(self);
hs_src.NewHandle(mirror::String::AllocFromModifiedUtf8(self, "1"));
hs_src.NewHandle(mirror::String::GetJavaLangString());
hs_src.NewHandle(mirror::String::AllocFromModifiedUtf8(self, "3"));
StackHandleScope<3> hs_dst(self);
hs_dst.NewHandle(mirror::String::AllocFromModifiedUtf8(self, "4"));
hs_dst.NewHandle(mirror::String::AllocFromModifiedUtf8(self, "5"));
hs_dst.NewHandle(mirror::String::AllocFromModifiedUtf8(self, "6"));
StackHandleScope<3> hs_expected(self);
hs_expected.NewHandle(hs_src.GetReference(0));
hs_expected.NewHandle(hs_dst.GetReference(1));
hs_expected.NewHandle(hs_dst.GetReference(2));
RunArrayCopy(self,
tmp,
true,
object_class.Get(),
mirror::String::GetJavaLangString(),
hs_src,
0,
hs_dst,
0,
3,
hs_expected);
}
ShadowFrame::DeleteDeoptimizedFrame(tmp);
}
TEST_F(UnstartedRuntimeTest, IntegerParseIntTest) {
Thread* self = Thread::Current();
ScopedObjectAccess soa(self);
ShadowFrame* tmp = ShadowFrame::CreateDeoptimizedFrame(10, nullptr, nullptr, 0);
// Test string. Should be valid, and between minimal values of LONG_MIN and LONG_MAX (for all
// suffixes).
constexpr const char* test_string = "-2147483646";
constexpr int32_t test_values[] = {
6,
46,
646,
3646,
83646,
483646,
7483646,
47483646,
147483646,
2147483646,
-2147483646
};
static_assert(arraysize(test_values) == 11U, "test_values");
CHECK_EQ(strlen(test_string), 11U);
for (size_t i = 0; i <= 10; ++i) {
const char* test_value = &test_string[10 - i];
StackHandleScope<1> hs_str(self);
Handle<mirror::String> h_str(
hs_str.NewHandle(mirror::String::AllocFromModifiedUtf8(self, test_value)));
ASSERT_NE(h_str.Get(), nullptr);
ASSERT_FALSE(self->IsExceptionPending());
tmp->SetVRegReference(0, h_str.Get());
JValue result;
UnstartedIntegerParseInt(self, tmp, &result, 0);
ASSERT_FALSE(self->IsExceptionPending());
EXPECT_EQ(result.GetI(), test_values[i]);
}
ShadowFrame::DeleteDeoptimizedFrame(tmp);
}
// Right now the same as Integer.Parse
TEST_F(UnstartedRuntimeTest, LongParseLongTest) {
Thread* self = Thread::Current();
ScopedObjectAccess soa(self);
ShadowFrame* tmp = ShadowFrame::CreateDeoptimizedFrame(10, nullptr, nullptr, 0);
// Test string. Should be valid, and between minimal values of LONG_MIN and LONG_MAX (for all
// suffixes).
constexpr const char* test_string = "-2147483646";
constexpr int64_t test_values[] = {
6,
46,
646,
3646,
83646,
483646,
7483646,
47483646,
147483646,
2147483646,
-2147483646
};
static_assert(arraysize(test_values) == 11U, "test_values");
CHECK_EQ(strlen(test_string), 11U);
for (size_t i = 0; i <= 10; ++i) {
const char* test_value = &test_string[10 - i];
StackHandleScope<1> hs_str(self);
Handle<mirror::String> h_str(
hs_str.NewHandle(mirror::String::AllocFromModifiedUtf8(self, test_value)));
ASSERT_NE(h_str.Get(), nullptr);
ASSERT_FALSE(self->IsExceptionPending());
tmp->SetVRegReference(0, h_str.Get());
JValue result;
UnstartedLongParseLong(self, tmp, &result, 0);
ASSERT_FALSE(self->IsExceptionPending());
EXPECT_EQ(result.GetJ(), test_values[i]);
}
ShadowFrame::DeleteDeoptimizedFrame(tmp);
}
TEST_F(UnstartedRuntimeTest, Ceil) {
Thread* self = Thread::Current();
ScopedObjectAccess soa(self);
ShadowFrame* tmp = ShadowFrame::CreateDeoptimizedFrame(10, nullptr, nullptr, 0);
constexpr double nan = std::numeric_limits<double>::quiet_NaN();
constexpr double inf = std::numeric_limits<double>::infinity();
constexpr double ld1 = static_cast<double>((UINT64_C(1) << 53) - 1);
constexpr double ld2 = static_cast<double>(UINT64_C(1) << 55);
constexpr double test_pairs[][2] = {
{ -0.0, -0.0 },
{ 0.0, 0.0 },
{ -0.5, -0.0 },
{ -1.0, -1.0 },
{ 0.5, 1.0 },
{ 1.0, 1.0 },
{ nan, nan },
{ inf, inf },
{ -inf, -inf },
{ ld1, ld1 },
{ ld2, ld2 }
};
TestCeilFloor(true /* ceil */, self, tmp, test_pairs, arraysize(test_pairs));
ShadowFrame::DeleteDeoptimizedFrame(tmp);
}
TEST_F(UnstartedRuntimeTest, Floor) {
Thread* self = Thread::Current();
ScopedObjectAccess soa(self);
ShadowFrame* tmp = ShadowFrame::CreateDeoptimizedFrame(10, nullptr, nullptr, 0);
constexpr double nan = std::numeric_limits<double>::quiet_NaN();
constexpr double inf = std::numeric_limits<double>::infinity();
constexpr double ld1 = static_cast<double>((UINT64_C(1) << 53) - 1);
constexpr double ld2 = static_cast<double>(UINT64_C(1) << 55);
constexpr double test_pairs[][2] = {
{ -0.0, -0.0 },
{ 0.0, 0.0 },
{ -0.5, -1.0 },
{ -1.0, -1.0 },
{ 0.5, 0.0 },
{ 1.0, 1.0 },
{ nan, nan },
{ inf, inf },
{ -inf, -inf },
{ ld1, ld1 },
{ ld2, ld2 }
};
TestCeilFloor(false /* floor */, self, tmp, test_pairs, arraysize(test_pairs));
ShadowFrame::DeleteDeoptimizedFrame(tmp);
}
TEST_F(UnstartedRuntimeTest, ToLowerUpper) {
Thread* self = Thread::Current();
ScopedObjectAccess soa(self);
ShadowFrame* tmp = ShadowFrame::CreateDeoptimizedFrame(10, nullptr, nullptr, 0);
std::locale c_locale("C");
// Check ASCII.
for (uint32_t i = 0; i < 128; ++i) {
bool c_upper = std::isupper(static_cast<char>(i), c_locale);
bool c_lower = std::islower(static_cast<char>(i), c_locale);
EXPECT_FALSE(c_upper && c_lower) << i;
// Check toLowerCase.
{
JValue result;
tmp->SetVReg(0, static_cast<int32_t>(i));
UnstartedCharacterToLowerCase(self, tmp, &result, 0);
ASSERT_FALSE(self->IsExceptionPending());
uint32_t lower_result = static_cast<uint32_t>(result.GetI());
if (c_lower) {
EXPECT_EQ(i, lower_result);
} else if (c_upper) {
EXPECT_EQ(static_cast<uint32_t>(std::tolower(static_cast<char>(i), c_locale)),
lower_result);
} else {
EXPECT_EQ(i, lower_result);
}
}
// Check toUpperCase.
{
JValue result2;
tmp->SetVReg(0, static_cast<int32_t>(i));
UnstartedCharacterToUpperCase(self, tmp, &result2, 0);
ASSERT_FALSE(self->IsExceptionPending());
uint32_t upper_result = static_cast<uint32_t>(result2.GetI());
if (c_upper) {
EXPECT_EQ(i, upper_result);
} else if (c_lower) {
EXPECT_EQ(static_cast<uint32_t>(std::toupper(static_cast<char>(i), c_locale)),
upper_result);
} else {
EXPECT_EQ(i, upper_result);
}
}
}
// Check abort for other things. Can't test all.
PrepareForAborts();
for (uint32_t i = 128; i < 256; ++i) {
{
JValue result;
tmp->SetVReg(0, static_cast<int32_t>(i));
Transaction transaction;
Runtime::Current()->EnterTransactionMode(&transaction);
UnstartedCharacterToLowerCase(self, tmp, &result, 0);
Runtime::Current()->ExitTransactionMode();
ASSERT_TRUE(self->IsExceptionPending());
ASSERT_TRUE(transaction.IsAborted());
}
{
JValue result;
tmp->SetVReg(0, static_cast<int32_t>(i));
Transaction transaction;
Runtime::Current()->EnterTransactionMode(&transaction);
UnstartedCharacterToUpperCase(self, tmp, &result, 0);
Runtime::Current()->ExitTransactionMode();
ASSERT_TRUE(self->IsExceptionPending());
ASSERT_TRUE(transaction.IsAborted());
}
}
for (uint64_t i = 256; i <= std::numeric_limits<uint32_t>::max(); i <<= 1) {
{
JValue result;
tmp->SetVReg(0, static_cast<int32_t>(i));
Transaction transaction;
Runtime::Current()->EnterTransactionMode(&transaction);
UnstartedCharacterToLowerCase(self, tmp, &result, 0);
Runtime::Current()->ExitTransactionMode();
ASSERT_TRUE(self->IsExceptionPending());
ASSERT_TRUE(transaction.IsAborted());
}
{
JValue result;
tmp->SetVReg(0, static_cast<int32_t>(i));
Transaction transaction;
Runtime::Current()->EnterTransactionMode(&transaction);
UnstartedCharacterToUpperCase(self, tmp, &result, 0);
Runtime::Current()->ExitTransactionMode();
ASSERT_TRUE(self->IsExceptionPending());
ASSERT_TRUE(transaction.IsAborted());
}
}
ShadowFrame::DeleteDeoptimizedFrame(tmp);
}
TEST_F(UnstartedRuntimeTest, Sin) {
Thread* self = Thread::Current();
ScopedObjectAccess soa(self);
ShadowFrame* tmp = ShadowFrame::CreateDeoptimizedFrame(10, nullptr, nullptr, 0);
// Test an important value, PI/6. That's the one we see in practice.
constexpr uint64_t lvalue = UINT64_C(0x3fe0c152382d7365);
tmp->SetVRegLong(0, static_cast<int64_t>(lvalue));
JValue result;
UnstartedMathSin(self, tmp, &result, 0);
const uint64_t lresult = static_cast<uint64_t>(result.GetJ());
EXPECT_EQ(UINT64_C(0x3fdfffffffffffff), lresult);
ShadowFrame::DeleteDeoptimizedFrame(tmp);
}
TEST_F(UnstartedRuntimeTest, Cos) {
Thread* self = Thread::Current();
ScopedObjectAccess soa(self);
ShadowFrame* tmp = ShadowFrame::CreateDeoptimizedFrame(10, nullptr, nullptr, 0);
// Test an important value, PI/6. That's the one we see in practice.
constexpr uint64_t lvalue = UINT64_C(0x3fe0c152382d7365);
tmp->SetVRegLong(0, static_cast<int64_t>(lvalue));
JValue result;
UnstartedMathCos(self, tmp, &result, 0);
const uint64_t lresult = static_cast<uint64_t>(result.GetJ());
EXPECT_EQ(UINT64_C(0x3febb67ae8584cab), lresult);
ShadowFrame::DeleteDeoptimizedFrame(tmp);
}
TEST_F(UnstartedRuntimeTest, Pow) {
// Valgrind seems to get this wrong, actually. Disable for valgrind.
if (RUNNING_ON_MEMORY_TOOL != 0 && kMemoryToolIsValgrind) {
return;
}
Thread* self = Thread::Current();
ScopedObjectAccess soa(self);
ShadowFrame* tmp = ShadowFrame::CreateDeoptimizedFrame(10, nullptr, nullptr, 0);
// Test an important pair.
constexpr uint64_t lvalue1 = UINT64_C(0x4079000000000000);
constexpr uint64_t lvalue2 = UINT64_C(0xbfe6db6dc0000000);
tmp->SetVRegLong(0, static_cast<int64_t>(lvalue1));
tmp->SetVRegLong(2, static_cast<int64_t>(lvalue2));
JValue result;
UnstartedMathPow(self, tmp, &result, 0);
const uint64_t lresult = static_cast<uint64_t>(result.GetJ());
EXPECT_EQ(UINT64_C(0x3f8c5c51326aa7ee), lresult);
ShadowFrame::DeleteDeoptimizedFrame(tmp);
}
} // namespace interpreter
} // namespace art
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "PottsMesh.hpp"
#include "RandomNumberGenerator.hpp"
template<unsigned DIM>
PottsMesh<DIM>::PottsMesh(std::vector<Node<DIM>*> nodes,
std::vector<PottsElement<DIM>*> pottsElements,
std::vector<std::set<unsigned> > vonNeumannNeighbouringNodeIndices,
std::vector<std::set<unsigned> > mooreNeighbouringNodeIndices)
{
// Reset member variables and clear mNodes, mElements.
Clear();
// Verify the same size of nodes and neighbour information.
if ((vonNeumannNeighbouringNodeIndices.size() != nodes.size()) || (mooreNeighbouringNodeIndices.size() != nodes.size()))
{
EXCEPTION("Nodes and neighbour information for a Potts mesh need to be the same length.");
}
mVonNeumannNeighbouringNodeIndices = vonNeumannNeighbouringNodeIndices;
mMooreNeighbouringNodeIndices = mooreNeighbouringNodeIndices;
// Populate mNodes and mElements
for (unsigned node_index=0; node_index<nodes.size(); node_index++)
{
Node<DIM>* p_temp_node = nodes[node_index];
this->mNodes.push_back(p_temp_node);
}
for (unsigned elem_index=0; elem_index<pottsElements.size(); elem_index++)
{
PottsElement<DIM>* p_temp_element = pottsElements[elem_index];
mElements.push_back(p_temp_element);
}
// Register elements with nodes
for (unsigned index=0; index<mElements.size(); index++)
{
PottsElement<DIM>* p_element = mElements[index];
unsigned element_index = p_element->GetIndex();
unsigned num_nodes_in_element = p_element->GetNumNodes();
for (unsigned node_index=0; node_index<num_nodes_in_element; node_index++)
{
p_element->GetNode(node_index)->AddElement(element_index);
}
}
this->mMeshChangesDuringSimulation = true;
}
template<unsigned DIM>
PottsMesh<DIM>::PottsMesh()
{
this->mMeshChangesDuringSimulation = true;
Clear();
}
template<unsigned DIM>
PottsMesh<DIM>::~PottsMesh()
{
Clear();
}
template<unsigned DIM>
unsigned PottsMesh<DIM>::SolveNodeMapping(unsigned index) const
{
assert(index < this->mNodes.size());
return index;
}
template<unsigned DIM>
unsigned PottsMesh<DIM>::SolveElementMapping(unsigned index) const
{
assert(index < this->mElements.size());
return index;
}
template<unsigned DIM>
unsigned PottsMesh<DIM>::SolveBoundaryElementMapping(unsigned index) const
{
return index;
}
template<unsigned DIM>
void PottsMesh<DIM>::Clear()
{
// Delete elements
for (unsigned i=0; i<mElements.size(); i++)
{
delete mElements[i];
}
mElements.clear();
// Delete nodes
for (unsigned i=0; i<this->mNodes.size(); i++)
{
delete this->mNodes[i];
}
this->mNodes.clear();
mDeletedElementIndices.clear();
// Delete neighbour info
//mVonNeumannNeighbouringNodeIndices.clear();
//mMooreNeighbouringNodeIndices.clear();
}
template<unsigned DIM>
unsigned PottsMesh<DIM>::GetNumNodes() const
{
return this->mNodes.size();
}
template<unsigned DIM>
unsigned PottsMesh<DIM>::GetNumElements() const
{
return mElements.size() - mDeletedElementIndices.size();
}
template<unsigned DIM>
unsigned PottsMesh<DIM>::GetNumAllElements() const
{
return mElements.size();
}
template<unsigned DIM>
PottsElement<DIM>* PottsMesh<DIM>::GetElement(unsigned index) const
{
assert(index < mElements.size());
return mElements[index];
}
template<unsigned DIM>
c_vector<double, DIM> PottsMesh<DIM>::GetCentroidOfElement(unsigned index)
{
PottsElement<DIM>* p_element = GetElement(index);
unsigned num_nodes_in_element = p_element->GetNumNodes();
///\todo This should probably be returning the nearest node
c_vector<double, DIM> centroid = zero_vector<double>(DIM);
for (unsigned local_index=0; local_index<num_nodes_in_element; local_index++)
{
// Find location of current node and add it to the centroid
centroid += p_element->GetNodeLocation(local_index);
}
centroid /= num_nodes_in_element;
return centroid;
}
template<unsigned DIM>
double PottsMesh<DIM>::GetVolumeOfElement(unsigned index)
{
PottsElement<DIM>* p_element = GetElement(index);
double element_volume = (double) p_element->GetNumNodes();
return element_volume;
}
template<unsigned DIM>
double PottsMesh<DIM>::GetSurfaceAreaOfElement(unsigned index)
{
///\todo not implemented in 3d yet
assert(DIM==2 || DIM==3); // LCOV_EXCL_LINE
// Helper variables
PottsElement<DIM>* p_element = GetElement(index);
unsigned num_nodes = p_element->GetNumNodes();
double surface_area = 0.0;
for (unsigned node_index=0; node_index<num_nodes; node_index++)
{
std::set<unsigned> neighbouring_node_indices = GetVonNeumannNeighbouringNodeIndices(p_element->GetNode(node_index)->GetIndex());
unsigned local_edges = 2*DIM;
for (std::set<unsigned>::iterator iter = neighbouring_node_indices.begin();
iter != neighbouring_node_indices.end();
iter++)
{
std::set<unsigned> neighbouring_node_element_indices = this->mNodes[*iter]->rGetContainingElementIndices();
if (!(neighbouring_node_element_indices.empty()) && (local_edges!=0))
{
unsigned neighbouring_node_element_index = *(neighbouring_node_element_indices.begin());
if (neighbouring_node_element_index == index)
{
local_edges--;
}
}
}
surface_area += local_edges;
}
return surface_area;
}
template<unsigned DIM>
std::set<unsigned> PottsMesh<DIM>::GetMooreNeighbouringNodeIndices(unsigned nodeIndex)
{
return mMooreNeighbouringNodeIndices[nodeIndex];
}
template<unsigned DIM>
std::set<unsigned> PottsMesh<DIM>::GetVonNeumannNeighbouringNodeIndices(unsigned nodeIndex)
{
return mVonNeumannNeighbouringNodeIndices[nodeIndex];
}
template<unsigned DIM>
void PottsMesh<DIM>::DeleteElement(unsigned index)
{
// Mark this element as deleted; this also updates the nodes containing element indices
this->mElements[index]->MarkAsDeleted();
mDeletedElementIndices.push_back(index);
}
template<unsigned DIM>
void PottsMesh<DIM>::RemoveDeletedElements()
{
// Remove any elements that have been removed and re-order the remaining ones
unsigned num_deleted_elements = mDeletedElementIndices.size();
for (unsigned index = num_deleted_elements; index>0; index--)
{
unsigned deleted_elem_index = mDeletedElementIndices[index-1];
delete mElements[deleted_elem_index];
mElements.erase(mElements.begin()+deleted_elem_index);
for (unsigned elem_index=deleted_elem_index; elem_index<mElements.size(); elem_index++)
{
mElements[elem_index]->ResetIndex(elem_index);
}
}
mDeletedElementIndices.clear();
}
template<unsigned DIM>
void PottsMesh<DIM>::DeleteNode(unsigned index)
{
//Mark node as deleted so we don't consider it when iterating over nodes
this->mNodes[index]->MarkAsDeleted();
//Remove from Elements
std::set<unsigned> containing_element_indices = this->mNodes[index]->rGetContainingElementIndices();
for (std::set<unsigned>::iterator iter = containing_element_indices.begin();
iter != containing_element_indices.end();
iter++)
{
assert(mElements[*iter]->GetNumNodes() > 0);
if (mElements[*iter]->GetNumNodes() == 1)
{
DeleteElement(*iter);
}
else
{
this->mElements[*iter]->DeleteNode(this->mElements[*iter]->GetNodeLocalIndex(index));
}
}
// Remove from connectivity
mVonNeumannNeighbouringNodeIndices[index].clear();
mMooreNeighbouringNodeIndices[index].clear();
assert(mVonNeumannNeighbouringNodeIndices.size()==mMooreNeighbouringNodeIndices.size());
for (unsigned node_index = 0;
node_index < mVonNeumannNeighbouringNodeIndices.size();
node_index++)
{
// Remove node "index" from the Von Neuman neighbourhood of node "node_index".
mVonNeumannNeighbouringNodeIndices[node_index].erase(index);
mMooreNeighbouringNodeIndices[node_index].erase(index);
// Check there's still connectivity for the other non-deleted nodes
if (!this->mNodes[node_index]->IsDeleted())
{
assert(!mVonNeumannNeighbouringNodeIndices[node_index].empty());
assert(!mMooreNeighbouringNodeIndices[node_index].empty());
}
}
// Remove node from mNodes and renumber all the elements and nodes
delete this->mNodes[index];
this->mNodes.erase(this->mNodes.begin()+index);
unsigned num_nodes = GetNumNodes();
mVonNeumannNeighbouringNodeIndices.erase(mVonNeumannNeighbouringNodeIndices.begin()+index);
mMooreNeighbouringNodeIndices.erase(mMooreNeighbouringNodeIndices.begin()+index);
assert(mVonNeumannNeighbouringNodeIndices.size()==num_nodes);
assert(mMooreNeighbouringNodeIndices.size()==num_nodes);
for (unsigned node_index = 0; node_index < num_nodes; node_index++)
{
// Reduce the index of all nodes greater than node "index"
if (node_index >= index)
{
assert(this->mNodes[node_index]->GetIndex() == node_index+1);
this->mNodes[node_index]->SetIndex(node_index);
}
assert(this->mNodes[node_index]->GetIndex() == node_index);
// Reduce the index of all nodes greater than node "index"
// in the Moore and Von Neuman neighbourhoods.
std::set<unsigned> von_neuman = mVonNeumannNeighbouringNodeIndices[node_index];
mVonNeumannNeighbouringNodeIndices[node_index].clear();
for (std::set<unsigned>::iterator iter = von_neuman.begin();
iter != von_neuman.end();
iter++)
{
if (*iter >= index)
{
mVonNeumannNeighbouringNodeIndices[node_index].insert(*iter-1);
}
else
{
mVonNeumannNeighbouringNodeIndices[node_index].insert(*iter);
}
}
std::set<unsigned> moore = mMooreNeighbouringNodeIndices[node_index];
mMooreNeighbouringNodeIndices[node_index].clear();
for (std::set<unsigned>::iterator iter = moore.begin();
iter != moore.end();
iter++)
{
if (*iter >= index)
{
mMooreNeighbouringNodeIndices[node_index].insert(*iter-1);
}
else
{
mMooreNeighbouringNodeIndices[node_index].insert(*iter);
}
}
}
// Finally remove any elements that have been removed
assert(mDeletedElementIndices.size() <= 1); // Should have at most one element to remove
if (mDeletedElementIndices.size() == 1)
{
unsigned deleted_elem_index = mDeletedElementIndices[0];
delete mElements[deleted_elem_index];
mElements.erase(mElements.begin()+deleted_elem_index);
mDeletedElementIndices.clear();
for (unsigned elem_index=deleted_elem_index; elem_index<GetNumElements(); elem_index++)
{
mElements[elem_index]->ResetIndex(elem_index);
}
}
}
template<unsigned DIM>
unsigned PottsMesh<DIM>::DivideElement(PottsElement<DIM>* pElement,
bool placeOriginalElementBelow)
{
/// Not implemented in 1d
assert(DIM==2 || DIM==3); // LCOV_EXCL_LINE
// Store the number of nodes in the element (this changes when nodes are deleted from the element)
unsigned num_nodes = pElement->GetNumNodes();
if (num_nodes < 2)
{
EXCEPTION("Tried to divide a Potts element with only one node. Cell dividing too often given dynamic parameters.");
}
// Copy the nodes in this element
std::vector<Node<DIM>*> nodes_elem;
for (unsigned i=0; i<num_nodes; i++)
{
nodes_elem.push_back(pElement->GetNode(i));
}
// Get the index of the new element
unsigned new_element_index;
if (mDeletedElementIndices.empty())
{
new_element_index = this->mElements.size();
}
else
{
new_element_index = mDeletedElementIndices.back();
mDeletedElementIndices.pop_back();
delete this->mElements[new_element_index];
}
// Add the new element to the mesh
AddElement(new PottsElement<DIM>(new_element_index, nodes_elem));
/**
* Remove the correct nodes from each element. If placeOriginalElementBelow is true,
* place the original element below (in the y direction or z in 3d) the new element; otherwise,
* place it above.
*/
unsigned half_num_nodes = num_nodes/2; // This will round down
assert(half_num_nodes > 0);
assert(half_num_nodes < num_nodes);
// Find lowest element
///\todo this could be more efficient
double height_midpoint_1 = 0.0;
double height_midpoint_2 = 0.0;
unsigned counter_1 = 0;
unsigned counter_2 = 0;
for (unsigned i=0; i<num_nodes; i++)
{
if (i<half_num_nodes)
{
height_midpoint_1 += pElement->GetNode(i)->rGetLocation()[DIM - 1];
counter_1++;
}
else
{
height_midpoint_2 += pElement->GetNode(i)->rGetLocation()[DIM -1];
counter_2++;
}
}
height_midpoint_1 /= (double)counter_1;
height_midpoint_2 /= (double)counter_2;
for (unsigned i=num_nodes; i>0; i--)
{
if (i-1 >= half_num_nodes)
{
if (height_midpoint_1 < height_midpoint_2)
{
if (placeOriginalElementBelow)
{
pElement->DeleteNode(i-1);
}
else
{
this->mElements[new_element_index]->DeleteNode(i-1);
}
}
else
{
if (placeOriginalElementBelow)
{
this->mElements[new_element_index]->DeleteNode(i-1);
}
else
{
pElement->DeleteNode(i-1);
}
}
}
else // i-1 < half_num_nodes
{
if (height_midpoint_1 < height_midpoint_2)
{
if (placeOriginalElementBelow)
{
this->mElements[new_element_index]->DeleteNode(i-1);
}
else
{
pElement->DeleteNode(i-1);
}
}
else
{
if (placeOriginalElementBelow)
{
pElement->DeleteNode(i-1);
}
else
{
this->mElements[new_element_index]->DeleteNode(i-1);
}
}
}
}
return new_element_index;
}
template<unsigned DIM>
unsigned PottsMesh<DIM>::AddElement(PottsElement<DIM>* pNewElement)
{
unsigned new_element_index = pNewElement->GetIndex();
if (new_element_index == this->mElements.size())
{
this->mElements.push_back(pNewElement);
}
else
{
this->mElements[new_element_index] = pNewElement;
}
pNewElement->RegisterWithNodes();
return pNewElement->GetIndex();
}
template<unsigned DIM>
std::set<unsigned> PottsMesh<DIM>::GetNeighbouringElementIndices(unsigned elementIndex)
{
// Helper variables
PottsElement<DIM>* p_element = this->GetElement(elementIndex);
unsigned num_nodes = p_element->GetNumNodes();
// Create a set of neighbouring element indices
std::set<unsigned> neighbouring_element_indices;
// Loop over nodes owned by this element
for (unsigned local_index=0; local_index<num_nodes; local_index++)
{
// Get a pointer to this node
Node<DIM>* p_node = p_element->GetNode(local_index);
// Find the indices of the elements owned by neighbours of this node
// Loop over neighbouring nodes. Only want Von Neuman neighbours (i.e N,S,E,W) as need to share an edge
std::set<unsigned> neighbouring_node_indices = GetVonNeumannNeighbouringNodeIndices(p_node->GetIndex());
// Iterate over these neighbouring nodes
for (std::set<unsigned>::iterator neighbour_iter = neighbouring_node_indices.begin();
neighbour_iter != neighbouring_node_indices.end();
++neighbour_iter)
{
std::set<unsigned> neighbouring_node_containing_elem_indices = this->GetNode(*neighbour_iter)->rGetContainingElementIndices();
assert(neighbouring_node_containing_elem_indices.size()<2); // Either in element or in medium
if (neighbouring_node_containing_elem_indices.size()==1) // Node is in an element
{
// Add this element to the neighbouring elements set
neighbouring_element_indices.insert(*(neighbouring_node_containing_elem_indices.begin()));
}
}
}
// Lastly remove this element's index from the set of neighbouring element indices
neighbouring_element_indices.erase(elementIndex);
return neighbouring_element_indices;
}
template<unsigned DIM>
void PottsMesh<DIM>::ConstructFromMeshReader(AbstractMeshReader<DIM, DIM>& rMeshReader)
{
assert(rMeshReader.HasNodePermutation() == false);
// Store numbers of nodes and elements
unsigned num_nodes = rMeshReader.GetNumNodes();
unsigned num_elements = rMeshReader.GetNumElements();
// Reserve memory for nodes
this->mNodes.reserve(num_nodes);
rMeshReader.Reset();
// Add nodes
std::vector<double> node_data;
for (unsigned i=0; i<num_nodes; i++)
{
node_data = rMeshReader.GetNextNode();
unsigned is_boundary_node = (bool) node_data[DIM];
node_data.pop_back();
this->mNodes.push_back(new Node<DIM>(i, node_data, is_boundary_node));
}
rMeshReader.Reset();
// Reserve memory for nodes
mElements.reserve(rMeshReader.GetNumElements());
// Add elements
for (unsigned elem_index=0; elem_index<num_elements; elem_index++)
{
// Get the data for this element
ElementData element_data = rMeshReader.GetNextElementData();
// Get the nodes owned by this element
std::vector<Node<DIM>*> nodes;
unsigned num_nodes_in_element = element_data.NodeIndices.size();
for (unsigned j=0; j<num_nodes_in_element; j++)
{
assert(element_data.NodeIndices[j] < this->mNodes.size());
nodes.push_back(this->mNodes[element_data.NodeIndices[j]]);
}
// Use nodes and index to construct this element
PottsElement<DIM>* p_element = new PottsElement<DIM>(elem_index, nodes);
mElements.push_back(p_element);
if (rMeshReader.GetNumElementAttributes() > 0)
{
assert(rMeshReader.GetNumElementAttributes() == 1);
double attribute_value = element_data.AttributeValue;
p_element->SetAttribute(attribute_value);
}
}
// If we are just using a mesh reader, then there is no neighbour information (see #1932)
if (mVonNeumannNeighbouringNodeIndices.empty())
{
mVonNeumannNeighbouringNodeIndices.resize(num_nodes);
}
if (mMooreNeighbouringNodeIndices.empty())
{
mMooreNeighbouringNodeIndices.resize(num_nodes);
}
}
// Explicit instantiation
template class PottsMesh<1>;
template class PottsMesh<2>;
template class PottsMesh<3>;
// Serialization for Boost >= 1.36
#include "SerializationExportWrapperForCpp.hpp"
EXPORT_TEMPLATE_CLASS_SAME_DIMS(PottsMesh)
|
#include <iostream>
#include <thread>
using namespace std;
mutex mtx; //全局互斥锁对象,#include <mutex>
// 打印机
void printer(const char *str)
{
mtx.lock(); //上锁
while (*str != '\0')
{
std::cout << *str;
str++;
this_thread::sleep_for(chrono::seconds(1));
}
// cout << endl;
mtx.unlock(); //解锁
}
// 线程一
void func1()
{
const char *str = "hello";
printer(str);
}
// 线程二
void func2()
{
const char *str = "world";
printer(str);
}
// 互斥
// std::mutex,最基本的 Mutex 类。
// std::recursive_mutex,递归 Mutex 类。
// std::time_mutex,定时 Mutex 类。
// std::recursive_timed_mutex,定时递归 Mutex 类。
int main(void)
{
thread t1(func1);
thread t2(func2);
t1.join();
t2.join();
return 0;
}
|
#include "room.h"
#include "house.h"
#include "devicefactory.h"
#include "appliancefactory.h"
#include "lightfactory.h"
#include <iostream>
#include <algorithm>
using namespace std;
Room::Room(std::string roomName)
{
_name = roomName;
cout << "Added " << _name << endl;
}
Room::~Room()
{
}
void Room::addComponent(std::string componentName)
{
House *h = House::instance();
std::vector<Component*> comp = h->getComponents();
for(std::vector<Component*>::iterator it = comp.begin(); it != comp.end(); ++it)
{
Component *c = *it;
if(c->getName() == componentName)
{
cout << "Added " << c->getName() << " to " << this->getName() << endl;
_components.push_back(c);
}
}
}
void Room::removeComponent(std::string componentName)
{
for(std::vector<Component*>::iterator it = _components.begin(); it != _components.end(); ++it)
{
Component *c = *it;
if(c->getName() == componentName)
{
cout << "Removing " << c->getName() << " from " << this->getName() << endl;
_components.erase(std::remove(_components.begin(), _components.end(), c));
c->~Component();
}
}
}
/*
*This method is called by the "Setup Component Called 'Y'" Command
*/
void Room::setupComponent(TYPES::COMPONENTS componentType, string componentName)
{
Factory *factory;
Component *comp;
switch(componentType){
case TYPES::DEVICE :
factory = new DeviceFactory();
comp = factory->create(componentName);
_components.push_back(comp);
break;
case TYPES::APPLIANCE :
factory = new ApplianceFactory();
comp = factory->create(componentName);
_components.push_back(comp);
break;
case TYPES::LIGHT :
factory = new LightFactory();
comp = factory->create(componentName);
_components.push_back(comp);
break;
default:
cerr << "Currently unsupported component" << endl;
break;
}
}
void Room::turnOnComponent(std::string componentName)
{
for(std::vector<Component*>::iterator it = _components.begin(); it != _components.end(); ++it)
{
Component *c = *it;
if(c->getName().compare(componentName))
{
cout << "Turning on " << c->getName() << endl;
c->on();
break;
}
}
}
void Room::turnOnComponents()
{
for(std::vector<Component*>::iterator it = _components.begin(); it != _components.end(); ++it)
{
Component *c = *it;
cout << "Turning on " << c->getName() << endl;
c->on();
}
}
void Room::turnOffComponent(std::string componentName)
{
for(std::vector<Component*>::iterator it = _components.begin(); it != _components.end(); ++it)
{
Component *c = *it;
if(c->getName().compare(componentName))
{
cout << "Turning off " << c->getName() << endl;
c->off();
break;
}
}
}
void Room::turnOffComponents()
{
for(std::vector<Component*>::iterator it = _components.begin(); it != _components.end(); ++it)
{
Component *c = *it;
cout << "Turning off " << c->getName() << endl;
c->off();
}
}
std:: string Room::getName()
{
return _name;
}
void Room::setName(std::string newName)
{
_name = newName;
}
Memento *Room::createMemento()
{
return new Memento(_components);
}
void Room::reinstateMemento(Memento *mem)
{
_components = mem->_state;
}
std::vector<Component *> Room::getComponents()
{
return _components;
}
|
#include <limits.h>
#include <iostream>
#include <map>
#include <queue>
#include <fstream>
using Graph = std::map<char, std::map<char, int>>;
bool breadthFirstSearch(Graph& graph, char start, char end, std::map<char, char>& path, std::ofstream& oFile);
void FordFulkersonAlgorithm(Graph& graph, char start, char end, std::ofstream& oFile);
void FordFulkersonAlgorithm(Graph& graph, char start, char end, std::ofstream& oFile) {
Graph flowGraph = graph;
char u, v;
std::string currentPath;
std::map<char, char> path;
int maxFlow = 0;
while (breadthFirstSearch(flowGraph, start, end, path, oFile)) {
int delta = INT_MAX;
currentPath = end;
for (v = end; v != start; v = path[v]) {
u = path[v];
delta = std::min(delta, flowGraph[u][v]);
currentPath = std::string(1, u) + " -> " + currentPath;
}
for (v = end; v != start; v = path[v]) {
u = path[v];
flowGraph[u][v] -= delta;
flowGraph[v][u] += delta;
}
maxFlow += delta;
oFile << currentPath << "\n" << "flow " << maxFlow << "\n\n\n";
}
oFile << "Network Max Flow Value: " << maxFlow << std::endl;
int flow;
for (auto& vertex : graph) {
char u = vertex.first;
for (auto neighbor : graph[u]) {
char v = neighbor.first;
int throughput = neighbor.second;
if (throughput - flowGraph[u][v] < 0) {
flow = 0;
}
else {
flow = throughput - flowGraph[u][v];
}
oFile << "Actual flow through " << u << " - " << v << " :" << flow << std::endl;
}
}
}
bool breadthFirstSearch(Graph& graph, char start, char end, std::map<char, char>& path, std::ofstream& oFile) {
std::queue<char> queue;
queue.push(start);
std::map<char, bool> visited;
visited[start] = true;
oFile << "----start searching for a path----\n";
while (!queue.empty()) {
char vertex = queue.front();
queue.pop();
oFile << "Curent vertex " << vertex << " has connections with:\n";
for (auto neighbor : graph[vertex]) {
char v = neighbor.first;
int throughput = neighbor.second;
oFile << "\t" << v << "(throughput " << throughput << ")\n";
if (!(visited[v]) && throughput > 0) {
queue.push(v);
visited[v] = true;
path[v] = vertex;
}
}
oFile << "\n";
}
return visited[end];
}
int main() {
Graph graph;
char start, end, u, v;
int throughput, vertexCount;
std::ifstream inFile;
inFile.open("D:/test.txt");
std::ofstream oFile;
oFile.open("D:/res.txt");
oFile << "Enter the number of edges" << std::endl;
inFile >> vertexCount;
oFile << "source" << std::endl;
inFile >> start;
oFile << "stock" << std::endl;
inFile >> end;
oFile << "Enter the edges of the graph" << std::endl;
for (int i = 0; i < vertexCount; ++i) {
inFile >> u >> v >> throughput;
graph[u][v] = throughput;
}
FordFulkersonAlgorithm(graph, start, end, oFile);
return 0;
}
|
//---------------------------------------------------------------------------
#ifndef CalcSitEV_H
#define CalcSitEV_H
//---------------------------------------------------------------------------
#include "..\..\Common\sitHoldem.h"
using namespace std;
struct tpSitRes
{
short _nbPl[CN_PLAYER],_cnPl;
std::vector <clDoubleCP> _res;
};
struct tpCardsGame
{
void DealCards(clDeck &col);
void SetHandsToSit(clSitHoldem &sit);
void GetHandsFromSit(clSitHoldem &sit);
void CalcAllIndex();
void CalcAllIndex(int nbPl);
int _cnPl;
tpHand _handsPl[CN_PLAYER];
tpCard _cardTable[5];
int _indFlop[CN_PLAYER];
int _indTurn[CN_PLAYER];
int _indRiver[CN_PLAYER];
int _game[CN_PLAYER];
};
clDoubleCP CalcSitEV(clSitHoldem &sit);
clDoubleCP CalcSitEV(clSitHoldem &sit,clHand *hand);
void CalcSitRes(clSitHoldem &sit, tpSitRes *res);
clDoubleCP CalcSitEV(clSitHoldem &sit, tpSitRes *res);
clDoubleCP CalcSitEV(clSitHoldem &sit, tpCardsGame *hand, tpSitRes *res);
clDoubleCP CalcSitDistribWin(clSitHoldem &sit);
int FinResGame(clGameHistory &hist, int nbH);
double FinResGameEV(clGameHistory &hist, int nb);
int FinResReplayAllIn(clGameHistory &hist, int nb);
//---------------------------------------------------------------------------
#endif
|
// *****************************************************************
// This file is part of the CYBERMED Libraries
//
// Copyright (C) 2007 LabTEVE (http://www.de.ufpb.br/~labteve),
// Federal University of Paraiba and University of São Paulo.
// All rights reserved.
//
// 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.
// *****************************************************************
#ifndef REGIONTRACKINFO_H_
#define REGIONTRACKINFO_H_
#ifdef CYBOPTICALTRACKER_H
#include <opencv/Blob.h>
#include <opencv/BlobResult.h>
class CybRegionTrackInfo
{
public:
/** Constructor */
CybRegionTrackInfo();
/** Constructor
*
*@param int maxX
*@param int minX
*@param int maxY
*@param int minY
*
*/
CybRegionTrackInfo(int maxX, int minX, int maxY, int minY);
/** Constructor
*
*@param const CBlob *blob
*
*/
CybRegionTrackInfo(const CBlob *blob);
/** Destructor */
virtual ~CybRegionTrackInfo();
/**
* Get max X
*
* @param void
* @return int
*
*/
int getMaxX();
/**
* Get min X
*
* @param void
* @return int
*
*/
int getMaxY();
/**
* Get min X
*
* @param void
* @return int
*
*/
int getMinX();
/**
* Get min Y
*
* @param void
* @return int
*
*/
int getMinY();
/**
* Return the area of a rectangle calculated using maxX, minX, maxY, minY
*
* @param void
* @return double
*
*/
double getArea();
/**
* Set max X
*
* @param int
* @return void
*
*/
void setMaxX(int maxX);
/**
* Set min Y
*
* @param int
* @return void
*
*/
void setMinX(int minX);
/**
* Set max Y
*
* @param int
* @return void
*
*/
void setMaxY(int maxY);
/**
* Set min Y
*
* @param int
* @return void
*
*/
void setMinY(int minY);
private:
int maxX, maxY, minX, minY; /**< rectangle values*/
};
#endif //CYBOPTICALTRACKER_H
#endif /*REGIONTRACKINFO_H_*/
|
#ifndef UTILS_H
#define UTILS_H
class Utils{
public:
Utils();
void clear();
//std::ifstream::pos_type filesize(const char* filename);
};
#endif
|
#include "sqlite_set.h"
#include "ui_sqlite_set.h"
sqlite_set::sqlite_set(QWidget *parent) :
QDialog(parent),
ui(new Ui::sqlite_set)
{
ui->setupUi(this);
}
sqlite_set::~sqlite_set()
{
delete ui;
}
void sqlite_set::on_toolButton_clicked()
{
}
void sqlite_set::on_toolButton_2_clicked()
{
QString s2 =
QFileDialog::getOpenFileName(this, "Open a file", "directoryToOpen",
"Images (*.png *.xpm *.jpg);;Text files (*.txt);;XML files (*.xml);;DB files (*.db *.sqlite)");
ui->lineEdit_2->setText(s2);
set_data = s2;
}
|
#include <LiquidCrystal.h>
//Define os pinos que serão utilizados para ligação ao display
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int ThermistorPin = A0;
int Vo;
float R1 = 10000; // value of R1 on board
float logR2, R2, T;
float c1 = 0.001129148, c2 = 0.000234125, c3 = 0.0000000876741; //steinhart-hart coeficients for thermistor
void setup()
{
Serial.begin(9600);
//Define o número de colunas e linhas do LCD
lcd.begin(16, 2);
}
void loop()
{
//Limpa a tela
lcd.clear();
//Posiciona o cursor na coluna 3, linha 0;
lcd.setCursor(0, 0);
//Envia o texto entre aspas para o LCD
lcd.print("Temp:");
lcd.setCursor(0, 1);
Vo = analogRead(ThermistorPin);
R2 = R1 * (1023.0 / (float)Vo - 1.0); //calculate resistance on thermistor
logR2 = log(R2);
T = (1.0 / (c1 + c2 * logR2 + c3 * logR2 * logR2 * logR2)); // temperature in Kelvin
T = T - 273.15; //convert Kelvin to Celcius
// T = (T * 9.0)/ 5.0 + 32.0; //convert Celcius to Farenheit
lcd.print(T);
delay(5000);
}
|
#pragma once
#include <type_traits>
namespace dsn {
namespace detail {
/// \brief Implementation of dsn::countof
template <typename Tin> constexpr std::size_t countof()
{
using T = typename std::remove_reference<Tin>::type;
static_assert(std::is_array<T>::value, "countof() only works with array types!");
static_assert(std::extent<T>::value > 0, "countof() only works with arrays of known length");
return std::extent<T>::value;
}
}
/// \brief Determine array size at compile time
///
/// This metaprogramming helper can be used to determine the size of T[constant_number] and T[]
/// during compile time so it can be used for loop counters etc.
///
/// \tparam T array type for which the length shall be determined
///
/// \return Array length as number of elements
template <class T> constexpr std::size_t countof(const T(&)) { return detail::countof<T>(); }
}
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "VertexCryptBoundaryForce.hpp"
#include "MathsCustomFunctions.hpp"
template<unsigned DIM>
VertexCryptBoundaryForce<DIM>::VertexCryptBoundaryForce(double forceStrength)
: AbstractForce<DIM>(),
mForceStrength(forceStrength)
{
// We don't want the force to act in the wrong direction
assert(mForceStrength > 0.0);
}
template<unsigned DIM>
VertexCryptBoundaryForce<DIM>::~VertexCryptBoundaryForce()
{
}
template<unsigned DIM>
void VertexCryptBoundaryForce<DIM>::AddForceContribution(AbstractCellPopulation<DIM>& rCellPopulation)
{
// Helper variable that is a static cast of the cell population
VertexBasedCellPopulation<DIM>* p_cell_population = static_cast<VertexBasedCellPopulation<DIM>*>(&rCellPopulation);
// Throw an exception message if not using a VertexBasedCellPopulation
if (dynamic_cast<VertexBasedCellPopulation<DIM>*>(&rCellPopulation) == nullptr)
{
EXCEPTION("VertexCryptBoundaryForce is to be used with VertexBasedCellPopulations only");
}
// Iterate over nodes
for (typename AbstractMesh<DIM,DIM>::NodeIterator node_iter = p_cell_population->rGetMesh().GetNodeIteratorBegin();
node_iter != p_cell_population->rGetMesh().GetNodeIteratorEnd();
++node_iter)
{
double y = node_iter->rGetLocation()[1]; // y-coordinate of node
// If the node lies below the line y=0, then add the boundary force contribution to the node forces
if (y < 0.0 && DIM > 1)
{
c_vector<double, DIM> boundary_force = zero_vector<double>(DIM);
boundary_force[1] = mForceStrength*SmallPow(y, 2);
node_iter->AddAppliedForceContribution(boundary_force);
}
}
}
template<unsigned DIM>
double VertexCryptBoundaryForce<DIM>::GetForceStrength() const
{
return mForceStrength;
}
template<unsigned DIM>
void VertexCryptBoundaryForce<DIM>::OutputForceParameters(out_stream& rParamsFile)
{
*rParamsFile << "\t\t\t<ForceStrength>" << mForceStrength << "</ForceStrength>\n";
// Call method on direct parent class
AbstractForce<DIM>::OutputForceParameters(rParamsFile);
}
// Explicit instantiation
template class VertexCryptBoundaryForce<1>;
template class VertexCryptBoundaryForce<2>;
template class VertexCryptBoundaryForce<3>;
// Serialization for Boost >= 1.36
#include "SerializationExportWrapperForCpp.hpp"
EXPORT_TEMPLATE_CLASS_SAME_DIMS(VertexCryptBoundaryForce)
|
#include "article.h"
#include <iostream>
Article::Article():Note(), texte(""){}
Article::Article(const QString& id, const QString& titre, const QString& text) : Note(id, titre),texte(text){}
Note::NoteType Article::getType() const{
return ARTICLE;
}
void Article::setTexte(const QString& t){
texte=t;
}
void Article::save(const QString &directory){
setSaved(true);
QString cheminEntier=directory+"/"+getId()+".txt";
QFile fichier (cheminEntier);
if(fichier.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text))
{
QTextStream flux(&fichier);
flux<<getTitre()<<"\n"<<getTexte();
fichier.close();
}
else std::cout<<"Impossible d'ecrire' !"<<"\n";
if(!isInTheFile())saveInTheFile(getId(), directory);
}
|
#include <iostream>
#include "FiguraGeometrica.h"
#include "Quadrado.h"
#include "Triangulo.h"
#include "Circulo.h"
using namespace std;
int main(){
int Base, Altura, Raio;
string Figurx;
cout << "Este programa calcula a area de Figuras geometricos" << endl;
while(true){
cout << "Qual solido voce deseja calcular a area:" << endl;
cin >> Figurx;
if(Figurx == "Quadrado" || Figurx == "quadrado"){
cout << "Digite a base do quadrado?" << endl;
cin >> Base;
cout << "Digite a altura do quadrado?" << endl;
cin >> Altura;
Quadrado Qua(Figurx, Base, Altura);
cout << " A area do " << Qua.getNome() << " e : " << Qua.Calcularea() << endl;
}
else if(Figurx == "Triangulo" || Figurx == "triangulo"){
cout << "Digite a base do triangulo?" << endl;
cin >> Base;
cout << "Digite a altura do triangulo?" << endl;
cin >> Altura;
Triangulo T(Figurx, Base, Altura);
cout<<"A area do "<< T.getNome() << " e : " << T.Calcularea() << endl;
} else if (Figurx == "Circulo" || Figurx == "circulo"){
cout << "Digite o raio do seu circulo?" << endl;
cin >> Raio;
Circulo C(Figurx, Raio);
cout<<"A area do "<< C.getNome() << " e : " << C.calcularea() << endl;
}else{
cout<<"Fim"<<endl;
return 1;
}
}
return 0;
}
|
#include "LevelState.h"
#include "CreditState.h"
#include "GameStateHandler.h"
inline OBB m_ConvertOBB(BoundingBoxHeader & boundingBox) //Convert from BBheader to OBB struct
{
OBB obj;
obj.ext[0] = boundingBox.extension[0];
obj.ext[1] = boundingBox.extension[1];
obj.ext[2] = boundingBox.extension[2];
DirectX::XMMATRIX extensionMatrix;
extensionMatrix = DirectX::XMMatrixSet(
boundingBox.extensionDir[0].x, boundingBox.extensionDir[0].y, boundingBox.extensionDir[0].z, 0.0f,
boundingBox.extensionDir[1].x, boundingBox.extensionDir[1].y, boundingBox.extensionDir[1].z, 0.0f,
boundingBox.extensionDir[2].x, boundingBox.extensionDir[2].y, boundingBox.extensionDir[2].z, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f
);
obj.ort = extensionMatrix;
return obj;
}
Entity* LevelState::GetClosestBall(float minDist)
{
Entity* closest = nullptr;
float closestDistance = FLT_MAX;
PhysicsComponent* pc = this->m_player1.GetPhysicsComponent();
//Calc the distance for play1 ball;
float distance = DirectX::XMVectorGetX(DirectX::XMVector3Length(DirectX::XMVectorSubtract(pc->PC_pos, this->m_player2.GetBall()->GetPhysicsComponent()->PC_pos)));
float distance1 = FLT_MAX;
if (!this->m_player2.GetBall()->IsGrabbed())
{
//If distance is less than hald the pickup distance, pickup player2's ball every time
if (distance < minDist / 1.8f)
{
closest = this->m_player2.GetBall();
}
}
if (closest == nullptr)
{
//Calc the distance for play1 ball;
DirectX::XMVECTOR vec = DirectX::XMVectorSubtract(pc->PC_pos, this->m_player1.GetBall()->GetPhysicsComponent()->PC_pos);
float distance = DirectX::XMVectorGetX(DirectX::XMVector3Length(vec));
if (this->m_player1.GetBall()->IsGrabbed() == false && distance <= minDist) //Is not grabbed and close enoughe
{
closest = this->m_player1.GetBall();
closestDistance = distance;
vec = DirectX::XMVectorSubtract(pc->PC_pos, this->m_player2.GetBall()->GetPhysicsComponent()->PC_pos);
distance = DirectX::XMVectorGetX(DirectX::XMVector3Length(vec));
if (this->m_player2.GetBall()->IsGrabbed() == false && distance < closestDistance) //Is not grabbed and Closer
{
closest = this->m_player2.GetBall();
}
}
else //If ball1 is already grabbed
{
vec = DirectX::XMVectorSubtract(pc->PC_pos, this->m_player2.GetBall()->GetPhysicsComponent()->PC_pos);
distance = DirectX::XMVectorGetX(DirectX::XMVector3Length(vec));
if (this->m_player2.GetBall()->IsGrabbed() == false && distance <= minDist) //Is not grabbed and close enoughe
{
closest = this->m_player2.GetBall();
}
}
//Some crazy Kim stuff. probably doesn't work
//if ((1.0f / distance) * this->m_player2.GetBall()->IsGrabbed() < (1.0f / DirectX::XMVectorGetX(DirectX::XMVector3Length(DirectX::XMVectorSubtract(pc->PC_pos, this->m_player1.GetBall()->GetPhysicsComponent()->PC_pos)))) * this->m_player1.GetBall()->IsGrabbed())
//{
// //Player1's ball is closest
//}
//else
//{
// //Player2's ball is closest
//}
}
return closest;
}
void LevelState::SendSyncForJoin()
{
unsigned int startIndex = 0;
unsigned int nrOfDynamics = 0;
bool isHost = false;
unsigned int levelID = this->m_curLevel; //CHANGE LEVEL HERE NOW
unsigned int checkpointID = 0;
this->m_networkModule->SendPhysicSyncPacket(startIndex, nrOfDynamics, isHost, levelID, checkpointID);
//Update puzzle elements
//Check for state changes that should be sent over the network
for (LeverEntity* e : this->m_leverEntities)
{
this->m_networkModule->SendStateLeverPacket(e->GetEntityID(), e->GetIsActive());
}
for (ButtonEntity* e : this->m_buttonEntities)
{
this->m_networkModule->SendStateButtonPacket(e->GetEntityID(), e->GetIsActive());
}
WheelSyncState* wheelSync = nullptr;
for (WheelEntity* e : this->m_wheelEntities)
{
wheelSync = e->GetUnconditionalState();
if (wheelSync != nullptr)
{
this->m_networkModule->SendStateWheelPacket(wheelSync->entityID, wheelSync->rotationState, wheelSync->rotationAmount);
delete wheelSync;
}
}
PhysicsComponent* pc = nullptr;
for (PlatformEntity* p : this->m_platformEntities)
{
pc = p->GetPhysicsComponent();
DirectX::XMFLOAT4X4 newrot;
DirectX::XMStoreFloat4x4(&newrot, pc->PC_OBB.ort);
this->m_networkModule->SendEntityUpdatePacket(pc->PC_entityID, pc->PC_pos, pc->PC_velocity, newrot);
}
//Drop anything we are holding
this->m_networkModule->SendGrabPacket(this->m_player2.GetEntityID(), -1);
if (this->m_player1.GetBall()->IsGrabbed())
{
this->m_networkModule->SendGrabPacket(this->m_player1.GetBall()->GetISGrabbedBy()->GetEntityID(), this->m_player1.GetBall()->GetEntityID());
}
else if (this->m_player2.GetBall()->IsGrabbed())
{
this->m_networkModule->SendGrabPacket(this->m_player2.GetBall()->GetISGrabbedBy()->GetEntityID(), this->m_player2.GetBall()->GetEntityID());
}
AnimationComponent* ap = this->m_player1.GetAnimationComponent();
if (this->m_player1.GetRagdoll()->state == RagdollState::RAGDOLL || this->m_player1.GetRagdoll()->state == RagdollState::KEYFRAMEBLEND)
{
GraphicsAnimationComponent* gp = (GraphicsAnimationComponent*)this->m_player1.GetGraphicComponent();
for (int i = 0; i < gp->jointCount; i++) //Iterate all joints
{
//Send a packet for E V E R Y joint
this->m_networkModule->SendAnimationPacket(this->m_player1.GetEntityID(), RAGDOLL_STATE, 0.f, Blending::NO_TRANSITION, false, false, 0.f, 1.0, i, gp->finalJointTransforms[i]);
}
}
else
{
bool loop = false;
if (ap->currentState == PLAYER_IDLE || ap->currentState == PLAYER_BALL_IDLE)
{
loop = true;
}
this->m_networkModule->SendAnimationPacket(this->m_player1.GetEntityID(), ap->currentState, ap->transitionDuration, ap->blendFlag, loop, ap->lockAnimation, ap->playingSpeed, ap->velocity, 0, DirectX::XMMATRIX());
}
}
LevelState::LevelState()
{
}
LevelState::~LevelState()
{
}
int LevelState::ShutDown()
{
int result = 1;
this->UnloadLevel();
DirectX::XMVECTOR targetOffset = DirectX::XMVectorSet(0.0f, 1.4f, 0.0f, 0.0f);
//this->m_dynamicEntitys
//Get the Camera Pivot and delete it before supplimenting our own
this->m_cameraRef->SetCameraPivot(nullptr, targetOffset, 1.3f);
// Clear the dynamic entities
for (size_t i = 0; i < this->m_dynamicEntitys.size(); i++)
{
delete this->m_dynamicEntitys[i];
this->m_dynamicEntitys[i] = nullptr;
}
// Clear the static entities
for (size_t i = 0; i < this->m_staticEntitys.size(); i++)
{
delete this->m_staticEntitys[i];
this->m_staticEntitys[i] = nullptr;
}
//Clear the puzzle entities
for (size_t i = 0; i < this->m_doorEntities.size(); i++)
{
delete this->m_doorEntities[i];
this->m_doorEntities[i] = nullptr;
}
this->m_doorEntities.clear();
for (size_t i = 0; i < this->m_buttonEntities.size(); i++)
{
delete this->m_buttonEntities[i];
this->m_buttonEntities[i] = nullptr;
}
this->m_buttonEntities.clear();
for (size_t i = 0; i < this->m_leverEntities.size(); i++)
{
delete this->m_leverEntities[i];
this->m_leverEntities[i] = nullptr;
}
this->m_leverEntities.clear();
for (size_t i = 0; i < this->m_wheelEntities.size(); i++)
{
delete this->m_wheelEntities[i];
this->m_wheelEntities[i] = nullptr;
}
this->m_wheelEntities.clear();
for (size_t i = 0; i < this->m_fieldEntities.size(); i++)
{
delete this->m_fieldEntities[i];
this->m_fieldEntities[i] = nullptr;
}
this->m_fieldEntities.clear();
for (size_t i = 0; i < this->m_platformEntities.size(); i++)
{
delete this->m_platformEntities[i];
this->m_platformEntities[i] = nullptr;
}
this->m_platformEntities.clear();
// Clear level director
this->m_director.Shutdown();
this->m_cHandler->ResizeGraphicsDynamic(0);
this->m_cHandler->ResizeGraphicsStatic(0);
this->m_cHandler->ResizeGraphicsPersistent(0);
this->m_cHandler->ClearAminationComponents();
//We need to add a function which empties the physics and bullet.
this->m_cHandler->GetPhysicsHandler()->ShutDown();
this->m_cHandler->GetPhysicsHandler()->Initialize();
//this->m_cHandler->RemoveUIComponentFromPtr(this->m_controlsOverlay);
//this->m_cHandler->RemoveUIComponentFromPtr(this->m_crosshair);
this->m_Player1ChainPhysicsComp.clear();
this->m_Player2ChainPhysicsComp.clear();
this->m_grapichalLinkListPlayer1.clear();
this->m_grapichalLinkListPlayer2.clear();
return result;
}
int LevelState::Initialize(GameStateHandler * gsh, ComponentHandler* cHandler, Camera* cameraRef)
{
int result = 1;
result = GameState::InitializeBase(gsh, cHandler, cameraRef, false);
this->m_clearedLevel = 0;
this->m_curLevel = 0;
//this->m_levelPaths.push_back({ "../ResourceLib/AssetFiles/TutorialLevel.level", 68.0f });
//this->m_levelPaths.push_back({ "../ResourceLib/AssetFiles/L1P1.level", 46.0f });
//this->m_levelPaths.push_back({ "../ResourceLib/AssetFiles/L1P2.level", 46.0f });
////this->m_levelPaths.push_back({ "../ResourceLib/AssetFiles/L1P2.level", 46.0f });
////this->m_levelPaths.push_back({ "../ResourceLib/AssetFiles/L1P2.level", 46.0f });
//this->m_levelPaths.push_back({ "../ResourceLib/AssetFiles/L2P1.level", 41.0f });
//this->m_levelPaths.push_back({ "../ResourceLib/AssetFiles/L3P1.level", 41.0f });
//this->m_levelPaths.push_back({"../ResourceLib/AssetFiles/L4P1.level", 41.0f });
//this->m_levelPaths.push_back({"../ResourceLib/AssetFiles/L5P1.level", 40.0f });
//For installer
this->m_levelPaths.push_back({ "../Assets/L0E1.level", 68.0f });
this->m_levelPaths.push_back({ "../Assets/L1E1.level", 46.0f });
this->m_levelPaths.push_back({ "../Assets/L2E1.level", 46.0f });
this->m_levelPaths.push_back({ "../Assets/L3E1.level", 41.0f });
this->m_levelPaths.push_back({ "../Assets/L4E1.level", 41.0f });
this->m_levelPaths.push_back({ "../Assets/L5E1.level", 41.0f });
//this->m_levelPaths.push_back({ "../Assets/L6E1.level", 40.0f });
//this->m_levelPaths.push_back({"../ResourceLib/AssetFiles/L4P1.level, 46.0f}");
//this->m_levelPaths.push_back({"../ResourceLib/AssetFiles/L5P1.level, 46.0f}");
//this->m_levelPaths.push_back({"../ResourceLib/AssetFiles/L6P1.level, 46.0f}");
//this->m_levelPaths.push_back({"../ResourceLib/AssetFiles/L1P2.level, 46.0f}");
if (this->m_curLevel > this->m_levelPaths.size())
{
this->m_curLevel = 0;
}
int nrCPs = 22;//(estLen / );
Resources::ResourceHandler* resHandler = Resources::ResourceHandler::GetInstance();
this->m_cHandler->GetGraphicsHandler()->ResizeDynamicComponents(2);
float nrOfSegmentsPerPlayer = 5; //more than 10 segments can lead to chain segments going through walls
this->m_cHandler->ResizeGraphicsPersistent(2 + 2 + (nrCPs * 2)); //"2 balls + 2 PingObjects + number of graphicallinks for both chains
//Creating the players
//Player 1
#pragma region
this->m_player1 = Player();
GraphicsComponent* playerG = m_cHandler->GetGraphicsAnimationComponent();
if (this->m_networkModule->IsHost())
{
playerG->modelID = 885141774;
}
else
{
playerG->modelID = 1117267500;
}
playerG->active = true;
resHandler->GetModel(playerG->modelID, playerG->modelPtr);
PhysicsComponent* playerP = m_cHandler->GetPhysicsComponent();
playerP->PC_entityID = DEFINED_IDS::PLAYER_1; //Set Entity ID
playerP->PC_pos = DirectX::XMVectorSet(0, 2, 0, 0); //Set Position
playerP->PC_rotation = DirectX::XMVectorSet(0, 0.0, 0, 0); //Set Rotation
playerP->PC_is_Static = false; //Set IsStatic
playerP->PC_mass = 10;
playerP->PC_BVtype = BV_OBB;
playerP->PC_OBB.ext[0] = playerG->modelPtr->GetOBBData().extension[0];
playerP->PC_OBB.ext[1] = playerG->modelPtr->GetOBBData().extension[1];
playerP->PC_OBB.ext[2] = playerG->modelPtr->GetOBBData().extension[2];
playerP->PC_velocity = DirectX::XMVectorSet(0, 0, 0, 0);
playerP->PC_friction = 0.95f;
playerG->worldMatrix = DirectX::XMMatrixIdentity(); //FIX THIS
#pragma region
AnimationComponent* playerAnim1 = nullptr;
if (playerG->modelPtr->GetSkeleton() != nullptr)
{
playerAnim1 = m_cHandler->GetAnimationComponent();
playerAnim1->skeleton = playerG->modelPtr->GetSkeleton();
((GraphicsAnimationComponent*)playerG)->jointCount = playerG->modelPtr->GetSkeleton()->GetSkeletonData()->jointCount;
playerAnim1->active = 1;
for (int i = 0; i < ((GraphicsAnimationComponent*)playerG)->jointCount; i++)
{
((GraphicsAnimationComponent*)playerG)->finalJointTransforms[i] = DirectX::XMMatrixIdentity();
}
if (playerG->modelPtr->GetSkeleton()->GetNumAnimations() > 0)
{
int numAnimations = playerG->modelPtr->GetSkeleton()->GetNumAnimations();
playerAnim1->animation_States = playerG->modelPtr->GetSkeleton()->GetAllAnimations();
playerAnim1->source_State = playerAnim1->animation_States->at(0)->GetAnimationStateData();
playerAnim1->source_State->isLooping = true;
playerAnim1->blendFlag = Blending::NO_TRANSITION;
playerAnim1->playingSpeed = 2.0f;
}
}
#pragma endregion Animation_Player1
this->m_player1.Initialize(playerP->PC_entityID, playerP, playerG, playerAnim1);
this->m_player1.SetMaxSpeed(30.0f);
this->m_player1.SetAcceleration(5.0f);
this->m_player1.SetRagdoll(this->m_cHandler->GetPhysicsHandler()->GetPlayer1Ragdoll());
#pragma endregion Player1
//Player 2
#pragma region
this->m_player2 = Player();
playerG = m_cHandler->GetGraphicsAnimationComponent();
if (this->m_networkModule->IsHost())
{
playerG->modelID = 1117267500;
}
else
{
playerG->modelID = 885141774;
}
playerG->active = true;
resHandler->GetModel(playerG->modelID, playerG->modelPtr);
playerP = m_cHandler->GetPhysicsComponent();
playerP->PC_entityID = DEFINED_IDS::PLAYER_2; //Set Entity ID
playerP->PC_pos = { 0 }; //Set Position
playerP->PC_is_Static = false; //Set IsStatic
playerP->PC_active = true; //Set Active
playerP->PC_mass = 10;
playerP->PC_velocity = DirectX::XMVectorSet(0, 0, 0, 0);
playerP->PC_BVtype = BV_OBB;
playerP->PC_OBB.ext[0] = playerG->modelPtr->GetOBBData().extension[0];
playerP->PC_OBB.ext[1] = playerG->modelPtr->GetOBBData().extension[1];
playerP->PC_OBB.ext[2] = playerG->modelPtr->GetOBBData().extension[2];
playerP->PC_friction = 0.95f;
playerG->worldMatrix = DirectX::XMMatrixIdentity(); //FIX THIS
#pragma region
AnimationComponent* playerAnim2 = nullptr;
if (playerG->modelPtr->GetSkeleton() != nullptr)
{
playerAnim2 = m_cHandler->GetAnimationComponent();
playerAnim2->skeleton = playerG->modelPtr->GetSkeleton();
((GraphicsAnimationComponent*)playerG)->jointCount = playerG->modelPtr->GetSkeleton()->GetSkeletonData()->jointCount;
playerAnim2->active = 1;
for (int i = 0; i < ((GraphicsAnimationComponent*)playerG)->jointCount; i++)
{
((GraphicsAnimationComponent*)playerG)->finalJointTransforms[i] = DirectX::XMMatrixIdentity();
}
if (playerG->modelPtr->GetSkeleton()->GetNumAnimations() > 0)
{
int numAnimations = playerG->modelPtr->GetSkeleton()->GetNumAnimations();
playerAnim2->animation_States = playerG->modelPtr->GetSkeleton()->GetAllAnimations();
playerAnim2->source_State = playerAnim2->animation_States->at(0)->GetAnimationStateData();
playerAnim2->source_State->isLooping = true;
playerAnim2->blendFlag = Blending::NO_TRANSITION;
playerAnim2->playingSpeed = 2.0f;
}
}
#pragma endregion Animation_Player2
this->m_player2.Initialize(playerP->PC_entityID, playerP, playerG, playerAnim2);
this->m_player2.SetMaxSpeed(30.0f);
this->m_player2.SetAcceleration(5.0f);
this->m_player2.SetRagdoll(this->m_cHandler->GetPhysicsHandler()->GetPlayer2Ragdoll());
#pragma endregion Player2
#pragma region
////Ball1
DynamicEntity* ball = new DynamicEntity();
GraphicsComponent* ballG = m_cHandler->GetPersistentGraphicsComponent();
if (this->m_networkModule->IsHost())
{
ballG->modelID = 1256673809;
}
else
{
ballG->modelID = 1321651915;
}
ballG->active = true;
resHandler->GetModel(ballG->modelID, ballG->modelPtr);
PhysicsComponent* ballP = m_cHandler->GetPhysicsComponent();
ballP->PC_entityID = DEFINED_IDS::BALL_1; //Set Entity ID
ballP->PC_pos = { 0 }; //Set Position
ballP->PC_rotation = DirectX::XMVectorSet(0, 0, 0, 0); //Set Rotation
ballP->PC_rotationVelocity = DirectX::XMVectorSet(0, 0, 0, 0);
ballP->PC_is_Static = false; //Set IsStatic
ballP->PC_active = true; //Set Active
ballP->PC_BVtype = BV_Sphere;
ballP->PC_velocity = DirectX::XMVectorSet(0, 0, 0, 0);
ballP->PC_OBB.ext[0] = 0.5f;
ballP->PC_OBB.ext[1] = 0.5f;
ballP->PC_OBB.ext[2] = 0.5f;
ballP->PC_Sphere.radius = 0.25;
ballP->PC_friction = 0.5f;
//ballP->PC_Sphere.radius = 1;
ballP->PC_mass = 25;
ballG->worldMatrix = DirectX::XMMatrixIdentity();
ball->Initialize(3, ballP, ballG);
this->m_dynamicEntitys.push_back(ball);
m_player1.SetBall(ball);
#pragma endregion Ball1
#pragma region
////Ball2
DynamicEntity* ball2 = new DynamicEntity();
ballG = m_cHandler->GetPersistentGraphicsComponent();
if (this->m_networkModule->IsHost())
{
ballG->modelID = 1321651915;
}
else
{
ballG->modelID = 1256673809;
}
ballG->active = true;
resHandler->GetModel(ballG->modelID, ballG->modelPtr);
ballP = m_cHandler->GetPhysicsComponent();
ballP->PC_entityID = DEFINED_IDS::BALL_2; //Set Entity ID
ballP->PC_pos = { 0 }; //Set Position
ballP->PC_rotation = DirectX::XMVectorSet(0, 0, 0, 0); //Set Rotation
ballP->PC_is_Static = false; //Set IsStatic
ballP->PC_active = true; //Set Active
ballP->PC_BVtype = BV_Sphere;
ballP->PC_Sphere.radius = 0.25;
ballP->PC_friction = 0.5f;
ballP->PC_mass = 25;
ballG->worldMatrix = DirectX::XMMatrixIdentity();
ball2->Initialize(4, ballP, ballG);
this->m_dynamicEntitys.push_back(ball2);
m_player2.SetBall(ball2);
#pragma endregion Ball2
#pragma region
DirectX::XMVECTOR targetOffset = DirectX::XMVectorSet(0.0f, 1.4f, 0.0f, 0.0f);
//this->m_dynamicEntitys
//Get the Camera Pivot and delete it before supplimenting our own
this->m_cameraRef->SetCameraPivot(
&this->m_cHandler->GetPhysicsHandler()->GetComponentAt(0)->PC_pos,
targetOffset,
1.3f
);
#pragma endregion Set_Camera
for (size_t i = 0; i < nrCPs; i++) // player 1
{
GraphicsComponent * cp = cHandler->GetPersistentGraphicsComponent();
cp->modelID = CHAIN_SEGMENT_MODEL_ID;
cp->active = true;
cp->worldMatrix = DirectX::XMMatrixIdentity();
resHandler->GetModel(cp->modelID, cp->modelPtr);
GraphicalLink link;
link.m_gComp = cp;
link.m_pos = { 0,0,0 };
link.xRot = 45.f * i;
link.m_rotMat = DirectX::XMMatrixIdentity();
link.SetRot(0.f, 0.f);
this->m_grapichalLinkListPlayer1.push_back(link);
}
for (size_t i = 0; i < nrCPs; i++) // Player 2
{
GraphicsComponent * cp = cHandler->GetPersistentGraphicsComponent();
cp->modelID = CHAIN_SEGMENT_MODEL_ID;
cp->active = true;
cp->worldMatrix = DirectX::XMMatrixIdentity();
resHandler->GetModel(cp->modelID, cp->modelPtr);
GraphicalLink link;
link.m_gComp = cp;
link.m_pos = { 0,0,0 };
link.xRot = 45.f * i;
link.m_rotMat = DirectX::XMMatrixIdentity();
link.SetRot(0.f, 0.f);
this->m_grapichalLinkListPlayer2.push_back(link);
}
#pragma region
this->m_player1_Ping.m_gComp = cHandler->GetPersistentGraphicsComponent();
this->m_player1_Ping.m_gComp->modelID = 2539810394;
this->m_player1_Ping.m_gComp->active = true;
this->m_player1_Ping.m_gComp->worldMatrix = DirectX::XMMatrixIdentity();
resHandler->GetModel(this->m_player1_Ping.m_gComp->modelID, this->m_player1_Ping.m_gComp->modelPtr);
this->m_player1_Ping.m_pos = { 0, 0, 0 };
this->m_player2_Ping.m_gComp = cHandler->GetPersistentGraphicsComponent();
this->m_player2_Ping.m_gComp->modelID = 2539810394;
this->m_player2_Ping.m_gComp->active = true;
this->m_player1_Ping.m_gComp->worldMatrix = DirectX::XMMatrixIdentity();
resHandler->GetModel(this->m_player2_Ping.m_gComp->modelID, this->m_player2_Ping.m_gComp->modelPtr);
this->m_player2_Ping.m_pos = { 0, 0, 0 };
//Set them to inactive in the begining
this->m_player1_Ping.m_gComp->active = false;
this->m_player2_Ping.m_gComp->active = false;
#pragma endregion PingModels
this->m_director.Initialize();
//Controls overlay
this->m_controlsOverlay = cHandler->GetUIComponent();
this->m_controlsOverlay->active = 0;
this->m_controlsOverlay->position = DirectX::XMFLOAT2(0.f, 0.f);
this->m_controlsOverlay->spriteID = Textures::Keymaps;
this->m_controlsOverlay->scale = .6f;
//Crosshair overlay
this->m_crosshair = cHandler->GetUIComponent();
this->m_crosshair->active = false;
this->m_crosshair->position = DirectX::XMFLOAT2(608.f, 328.f);
this->m_crosshair->spriteID = Textures::CrosshairAim;
this->m_crosshair->scale = 0.8f;
return result;
}
int LevelState::Update(float dt, InputHandler * inputHandler)
{
int result = 1;
dt = dt / 1000000;
if (this->m_clearedLevel == 1)
{
this->LoadNext();
}
this->UpdateGraphicalLinks();
int prevConnects = (int)this->m_networkModule->GetNrOfConnectedClients();
this->m_networkModule->Update();
//If someone has connected
if (prevConnects < this->m_networkModule->GetNrOfConnectedClients())
{
this->SendSyncForJoin();
}
this->m_cameraRef->UpdateDeltaTime(dt);
#pragma region
if (this->m_networkModule->GetNrOfConnectedClients() != 0) //Check so we are connected to a client
{
//Check for updates for enteties
this->m_entityPacketList = this->m_networkModule->PacketBuffer_GetEntityPackets(); //This removes the entity packets from the list in NetworkModule
if (this->m_entityPacketList.size() > 0)
{
// Apply each packet to the right entity
std::list<EntityPacket>::iterator itr;
PhysicsComponent* pp = nullptr;
for (itr = this->m_entityPacketList.begin(); itr != this->m_entityPacketList.end(); itr++)
{
/*
Every packet that we recived with the entityID 1 will be sent to player2 object since
we know that on the other computer will also play on his/her local player1 object.
This way we know that all packets with ID 1 is sent for the "self" player object (m_player2) and Id 2
for out local "self" player object (m_player1).
To compensate for this we will have to switch places for m_player1 and m_player2 position on the
connecting player so they still have the same start position relative to eachother.
*/
if ((int)itr->entityID == DEFINED_IDS::PLAYER_1) //Packets for player2
{
pp = this->m_player2.GetPhysicsComponent();
// Update the component
pp->PC_pos = DirectX::XMLoadFloat3(&itr->newPos);
//this->m_player2.GetRagdoll()->upperBody.center->PC_pos = pp->PC_pos;
pp->PC_OBB.ort = DirectX::XMLoadFloat4x4(&itr->newRotation);
pp->PC_velocity = DirectX::XMLoadFloat3(&itr->newVelocity);
}
else if ((int)itr->entityID == DEFINED_IDS::PLAYER_2) //Packets for player1
{
pp = this->m_player1.GetPhysicsComponent();
// Update the component
pp->PC_pos = DirectX::XMLoadFloat3(&itr->newPos);
//this->m_player1.GetRagdoll()->upperBody.center->PC_pos = pp->PC_pos;
pp->PC_OBB.ort = DirectX::XMLoadFloat4x4(&itr->newRotation);
pp->PC_velocity = DirectX::XMLoadFloat3(&itr->newVelocity);
}
else if ((int)itr->entityID == DEFINED_IDS::BALL_1) //Packets for ball1
{
pp = this->m_player2.GetBall()->GetPhysicsComponent();
// Update the component
pp->PC_pos = DirectX::XMLoadFloat3(&itr->newPos);
pp->PC_OBB.ort = DirectX::XMLoadFloat4x4(&itr->newRotation);
pp->PC_velocity = DirectX::XMLoadFloat3(&itr->newVelocity);
}
else if ((int)itr->entityID == DEFINED_IDS::BALL_2) //Packets for ball2
{
pp = this->m_player1.GetBall()->GetPhysicsComponent();
//if the opposite player is holding the current players ball, the syncing will not be done
// Update the component
pp->PC_pos = DirectX::XMLoadFloat3(&itr->newPos);
pp->PC_OBB.ort = DirectX::XMLoadFloat4x4(&itr->newRotation);
pp->PC_velocity = DirectX::XMLoadFloat3(&itr->newVelocity);
}
else //For every other entity
{
// Find the entity
std::vector<DynamicEntity*>::iterator Ditr;
for (Ditr = this->m_dynamicEntitys.begin(); Ditr != this->m_dynamicEntitys.end(); Ditr++)
{
if (itr->entityID == (*Ditr._Ptr)->GetEntityID())
{
DynamicEntity* ent = (*Ditr._Ptr); // The entity identified by the ID sent from the other client
pp = ent->GetPhysicsComponent();
// Update the component
pp->PC_pos = DirectX::XMLoadFloat3(&itr->newPos);
pp->PC_OBB.ort = DirectX::XMLoadFloat4x4(&itr->newRotation);
pp->PC_velocity = DirectX::XMLoadFloat3(&itr->newVelocity);
break;
}
}
//If we still havent found an entity check for platforms
std::vector<PlatformEntity*>::iterator Pitr;
for (Pitr = this->m_platformEntities.begin(); Pitr != this->m_platformEntities.end(); Pitr++)
{
if (itr->entityID == (*Pitr._Ptr)->GetEntityID())
{
PlatformEntity* plat = (*Pitr._Ptr); // The entity identified by the ID sent from the other client
pp = plat->GetPhysicsComponent();
// Update the component
pp->PC_pos = DirectX::XMLoadFloat3(&itr->newPos);
pp->PC_OBB.ort = DirectX::XMLoadFloat4x4(&itr->newRotation);
pp->PC_velocity = DirectX::XMLoadFloat3(&itr->newVelocity);
plat->GetAIComponent()->AC_position = pp->PC_pos;
break;
}
}
}
}
}
this->m_entityPacketList.clear(); //Clear the list
}
#pragma endregion Network_update_entities
#pragma region
if (this->m_networkModule->GetNrOfConnectedClients() != 0)
{
// LEVERS AND BUTTONS //
this->m_statePacketList = this->m_networkModule->PacketBuffer_GetStatePackets(); //This removes the entity packets from the list in NetworkModule
if (this->m_statePacketList.size() > 0)
{
// Apply each packet to the right entity
std::list<StatePacket>::iterator itr;
for (itr = this->m_statePacketList.begin(); itr != this->m_statePacketList.end(); itr++)
{
if (itr->packet_type == UPDATE_BUTTON_STATE)
{
for (size_t i = 0; i < this->m_buttonEntities.size(); i++)
{
ButtonEntity* bP = this->m_buttonEntities.at(i);
if (bP->GetEntityID() == itr->entityID)
{
ButtonSyncState newState;
newState.entityID = itr->entityID;
newState.isActive = itr->isActive;
bP->SetSyncState(&newState);
break;
}
}
}
else if (itr->packet_type == UPDATE_LEVER_STATE)
{
for (size_t i = 0; i < this->m_leverEntities.size(); i++)
{
LeverEntity* lP = this->m_leverEntities.at(i);
if (lP->GetEntityID() == itr->entityID)
{
LeverSyncState newState;
newState.entityID = itr->entityID;
newState.isActive = itr->isActive;
lP->SetSyncState(&newState);
break;
}
}
}
}
}
this->m_statePacketList.clear();
// LEVERS AND BUTTONS END//
// WHEELS //
this->m_wheelStatePacketList = this->m_networkModule->PacketBuffer_GetWheelStatePackets(); //This removes the entity packets from the list in NetworkModule
if (this->m_wheelStatePacketList.size() > 0)
{
// Apply each packet to the right entity
std::list<StateWheelPacket>::iterator itr;
for (itr = this->m_wheelStatePacketList.begin(); itr != this->m_wheelStatePacketList.end(); itr++)
{
for (size_t i = 0; i < this->m_wheelEntities.size(); i++)
{
WheelEntity* wP = this->m_wheelEntities.at(i);
if (wP->GetEntityID() == itr->entityID)
{
WheelSyncState newState;
newState.entityID = itr->entityID;
newState.rotationState = itr->rotationState;
newState.rotationAmount = itr->rotationAmount;
wP->SetSyncState(&newState);
break;
}
}
}
}
this->m_wheelStatePacketList.clear();
// WHEELS END //
}
#pragma endregion Network_update_States
#pragma region
if (this->m_networkModule->GetNrOfConnectedClients() != 0)
{
this->m_animationPacketList = this->m_networkModule->PacketBuffer_GetAnimationPackets();
if (this->m_animationPacketList.size() > 0)
{
std::list<AnimationPacket>::iterator itr;
for (itr = this->m_animationPacketList.begin(); itr != this->m_animationPacketList.end(); itr++)
{
/* We know that all packets will be sent to player2
since only player2 will send animation packets */
if (itr->newstate == AnimationStates::RAGDOLL_STATE) //If the packet is for a ragdoll state
{
this->m_player2.GetRagdoll()->state = RagdollState::RAGDOLL;
GraphicsAnimationComponent* gp = (GraphicsAnimationComponent*)this->m_player2.GetGraphicComponent();
gp->finalJointTransforms[itr->jointIndex] = DirectX::XMLoadFloat4x4(&itr->finalJointTransform);
this->m_player2.GetAnimationComponent()->previousState = this->m_player2.GetAnimationComponent()->currentState;
this->m_player2.GetAnimationComponent()->currentState = itr->newstate;
this->m_player2.SetAnimationComponent(AnimationStates::RAGDOLL_STATE, 0.f, Blending::NO_TRANSITION, false, false, 0.f, 1.0);
this->m_player2.GetAnimationComponent()->source_State->stateIndex = AnimationStates::RAGDOLL_STATE;
}
else
{
if (this->m_player2.GetRagdoll()->state == RagdollState::RAGDOLL)
{
this->m_player2.GetAnimationComponent()->previousState = this->m_player2.GetAnimationComponent()->currentState;
this->m_player2.SetAnimationComponent(AnimationStates::PLAYER_RISE_UP, 0, Blending::NO_TRANSITION, false, true, 2.0f, 1.0f);
this->m_player2.GetAnimationComponent()->currentState = AnimationStates::PLAYER_RISE_UP;
this->m_player2.GetAnimationComponent()->source_State = this->m_player2.GetAnimationComponent()->animation_States->at(AnimationStates::PLAYER_RISE_UP)->GetAnimationStateData();
this->m_player2.GetAnimationComponent()->source_State->stateIndex = AnimationStates::PLAYER_RISE_UP;
}
this->m_player2.GetRagdoll()->state = RagdollState::ANIMATED;
this->m_player2.GetAnimationComponent()->previousState = this->m_player2.GetAnimationComponent()->currentState;
this->m_player2.SetAnimationComponent(itr->newstate, itr->transitionDuritation, (Blending)itr->blendingType, itr->isLooping, itr->lockAnimation, itr->playingSpeed, itr->velocity);
this->m_player2.GetAnimationComponent()->currentState = itr->newstate;
}
}
}
this->m_animationPacketList.clear();
}
#pragma endregion Update_Animations
#pragma region
float yaw = inputHandler->GetMouseDelta().x;
float pitch = inputHandler->GetMouseDelta().y;
float mouseSens = 0.1f;
if (inputHandler->GetMouseDelta().y || inputHandler->GetMouseDelta().x)
this->m_cameraRef->RotateCameraPivot(inputHandler->GetMouseDelta().y * mouseSens, inputHandler->GetMouseDelta().x * mouseSens);
//update player for throw functionallity
DirectX::XMVECTOR playerLookDir = DirectX::XMVector4Normalize(DirectX::XMVectorSubtract(DirectX::XMLoadFloat3(&this->m_cameraRef->GetLookAt()), DirectX::XMLoadFloat3(&this->m_cameraRef->GetCameraPos())));
DirectX::XMFLOAT3 temp;
this->m_cameraRef->GetCameraUp(temp);
DirectX::XMVECTOR upDir = DirectX::XMLoadFloat3(&temp);
DirectX::XMVECTOR rightDir = m_cameraRef->GetRight(); //DirectX::XMVector3Cross(upDir, playerLookDir);
//Camera
this->m_player1.SetRightDir(rightDir);
this->m_player1.SetUpDir(upDir);
this->m_player1.SetLookDir(playerLookDir);
#pragma endregion Camera_Update
#pragma region
Entity* wasGrabbed = this->m_player1.GetGrabbed();
this->m_player1.Update(dt, inputHandler);
//Check if we released a grabbed object in player Update
if (wasGrabbed != this->m_player1.GetGrabbed() && wasGrabbed != nullptr)
{
wasGrabbed->SyncComponents(); //Update the component
this->m_networkModule->SendGrabPacket(this->m_player1.GetEntityID(), -1); //Send a release packet
DirectX::XMFLOAT4X4 newrot;
DirectX::XMStoreFloat4x4(&newrot, wasGrabbed->GetPhysicsComponent()->PC_OBB.ort);
this->m_networkModule->SendEntityUpdatePacket(wasGrabbed->GetPhysicsComponent()->PC_entityID, wasGrabbed->GetPhysicsComponent()->PC_pos, wasGrabbed->GetPhysicsComponent()->PC_velocity, newrot); //Send the update data
}
//update all dynamic (moving) entities
Entity* ent = nullptr;
for (size_t i = 0; i < this->m_dynamicEntitys.size(); i++)
{
ent = this->m_dynamicEntitys.at(i);
if (ent == this->m_player2.GetGrabbed()) //Check if the entity is grabbed by player2, if it is there will be an update packet for it
{
ent->SyncComponents(); //Just sync the component and wait for the update package
}
else
{
ent->Update(dt, inputHandler); //Update the entity normaly
}
}
//Sync other half of the components
this->m_player2.SyncComponents();
#pragma endregion Update/Syncing Components
#pragma region
if (inputHandler->IsMouseKeyPressed(SDL_BUTTON_LEFT)
&& this->m_player1.GetGrabbed() == nullptr
&& this->m_player1.TimeSinceThrow() >= GRAB_COOLDOWN)
{
Entity* closestBall = this->GetClosestBall(GRAB_RANGE);
if (closestBall != nullptr) //If a ball was found
{
if (this->m_player1.GetBall()->IsGrabbed() //if our ball is grabbed
&& this->m_player1.GetGrabbed() != this->m_player1.GetBall()) //AND if the ball is not grabbed by us
{
//now we know that player 2 is holding our ball
//drop the ball
this->m_player2.SetGrabbed(nullptr);
//send update packet to client 2
this->m_networkModule->SendGrabPacket(this->m_player2.GetEntityID(), -1);
}
this->m_player1.SetGrabbed(closestBall);
this->m_networkModule->SendGrabPacket(this->m_player1.GetEntityID(), closestBall->GetEntityID());
//Play the animation for player picking up the ball.
this->m_player1.GetAnimationComponent()->previousState = this->m_player1.GetAnimationComponent()->currentState;
this->m_player1.SetAnimationComponent(AnimationStates::PLAYER_PICKUP, 0.45f, Blending::FROZEN_TRANSITION, false, true, 1.75f, 1.0f);
this->m_player1.GetAnimationComponent()->currentState = AnimationStates::PLAYER_PICKUP;
}
}
if (inputHandler->IsKeyPressed(SDL_SCANCODE_Q))
{
this->m_player1.SetGrabbed(nullptr);
this->m_networkModule->SendGrabPacket(this->m_player1.GetEntityID(), -1);
/*Set the component to play the animation for IDLE if the player is standing still when PCs velocity is under 1.*/
if (DirectX::XMVectorGetX(DirectX::XMVector3Length(this->m_player1.GetPhysicsComponent()->PC_velocity)) < 1.0f )
{
this->m_player1.GetAnimationComponent()->previousState = this->m_player1.GetAnimationComponent()->currentState;
this->m_player1.SetAnimationComponent(AnimationStates::PLAYER_IDLE, 0.50f, Blending::SMOOTH_TRANSITION, true, false, 1.0f, 1.0f);
this->m_player1.GetAnimationComponent()->currentState = AnimationStates::PLAYER_IDLE;
}
}
if (this->m_player1.GetRagdoll()->state == RagdollState::RAGDOLL)
{
if (this->m_player1.GetGrabbed() != nullptr)
{
this->m_player1.SetGrabbed(nullptr);
this->m_networkModule->SendGrabPacket(this->m_player1.GetEntityID(), -1);
}
}
#pragma endregion Grab/Release
#pragma region
this->m_grabPacketList = this->m_networkModule->PacketBuffer_GetGrabPacket(); //This removes the entity packets from the list in NetworkModule
/*
We know that all packets are from the other player (m_player2)
*/
if (this->m_grabPacketList.size() > 0)
{
std::list<GrabPacket>::iterator itr;
PhysicsComponent* pp = nullptr;
Entity* ep = nullptr;
for (itr = this->m_grabPacketList.begin(); itr != this->m_grabPacketList.end(); itr++)
{
//Check if we want to grab or drop
if (itr->grabbedID >= 0) //Grab
{
if (itr->grabbedID == 3)
{
this->m_player2.SetGrabbed(this->m_player2.GetBall());
}
else if (itr->grabbedID == 4)
{
this->m_player2.SetGrabbed(this->m_player1.GetBall());
}
}
else //Drop
{
if (itr->entityID == DEFINED_IDS::PLAYER_1)
{
this->m_player2.SetGrabbed(nullptr);
}
else if (itr->entityID == DEFINED_IDS::PLAYER_2)
{
this->m_player1.SetGrabbed(nullptr);
}
}
}
}
this->m_grabPacketList.clear();
#pragma endregion Grab_Requests
#pragma region
//Aming for player1 (SHOULD BE FOR THE CONTROLED PLAYER)
if (inputHandler->IsMouseKeyDown(SDL_BUTTON_RIGHT))
{
this->m_player1.SetAiming(true);
//Crosshair overlay
this->m_crosshair->active = true;
DirectX::XMVECTOR targetOffset = DirectX::XMVectorSet(.3f, 1.4f, 0.0f, 0.0f);
targetOffset = DirectX::XMVectorScale(this->m_player1.GetRightDir(), 0.3f);
targetOffset = DirectX::XMVectorAdd(targetOffset, { 0.0f, 1.25f, 0.0f, 0.0f });
m_cameraRef->SetCameraPivotOffset(
targetOffset,
.5f
);
}
if (inputHandler->IsMouseKeyReleased(SDL_BUTTON_RIGHT) && this->m_player1.GetIsAming())
{
this->m_player1.SetAiming(false);
//Crosshair overlay
this->m_crosshair->active = false;
DirectX::XMVECTOR targetOffset = DirectX::XMVectorSet(0.f, 1.4f, 0.0f, 0.0f);
m_cameraRef->SetCameraPivotOffset(
targetOffset,
1.3f
);
}
if (this->m_player1.GetIsAming())
{
this->m_player1.SetLookDir(this->m_cameraRef->GetDirection());
}
#pragma endregion Aiming
#pragma region
this->m_pingPacketList = this->m_networkModule->PacketBuffer_GetPingPacket();
//Check for updates
if (this->m_pingPacketList.size() != 0)
{
std::list<PingPacket>::iterator itr;
for (itr = this->m_pingPacketList.begin(); itr != this->m_pingPacketList.end(); itr++)
{
this->m_player2_Ping.SetPos(DirectX::XMLoadFloat3(&itr->newPos));
this->m_player2_Ping.m_gComp->active = true;
this->m_player2_Ping.m_time = 0;
SoundHandler::instance().PlaySound3D(Sounds3D::PING_EFFECT_SOUND, this->m_player2_Ping.m_pos, false, false);
}
this->m_pingPacketList.empty();
}
if (inputHandler->IsKeyPressed(SDL_SCANCODE_T))
{
float distance = this->m_cHandler->GetGraphicsHandler()->Ping_GetDistanceToClosestOBB(PING_DISTANCE);
if (distance < PING_DISTANCE)
{
//Calculate the point using the camera dir vector
DirectX::XMVECTOR dir = this->m_cameraRef->GetDirection();
DirectX::XMVECTOR scaledDir = DirectX::XMVectorScale(dir, distance - 1); //-1 to get abit of distance from what we are hiting
DirectX::XMVECTOR camPos = DirectX::XMLoadFloat3(&this->m_cameraRef->GetCameraPos());
DirectX::XMVECTOR newPos = DirectX::XMVectorAdd(camPos, scaledDir);
this->m_player1_Ping.SetPos(newPos);; //Set the pos for the ping
this->m_player1_Ping.m_gComp->active = true;
this->m_player1_Ping.m_time = 0;
this->m_networkModule->SendPingPacket(this->m_player1_Ping.m_pos);
SoundHandler::instance().PlaySound3D(Sounds3D::PING_EFFECT_SOUND, this->m_player1_Ping.m_pos, false, false);
}
}
this->m_player1_Ping.Update(dt);
this->m_player2_Ping.Update(dt);
#pragma endregion Ping
#pragma region
if (this->m_networkModule->GetNrOfConnectedClients() != 0) //There is connected players
{
PhysicsComponent* pp = this->m_player1.GetPhysicsComponent();
if (pp != nullptr)
{
DirectX::XMFLOAT4X4 newrot;
DirectX::XMStoreFloat4x4(&newrot, pp->PC_OBB.ort);
this->m_networkModule->SendEntityUpdatePacket(pp->PC_entityID, pp->PC_pos, pp->PC_velocity, newrot); //Send the update data for the player
}
/*if (this->m_player1.GetGrabbed() != nullptr)*/
if (this->m_player1.GetBall() != nullptr &&
this->m_player2.GetGrabbed() != this->m_player1.GetBall()) //send update of player1 ball if player2 has not grabbed it
{
pp = this->m_player1.GetBall()->GetPhysicsComponent();
DirectX::XMFLOAT4X4 newrot;
DirectX::XMStoreFloat4x4(&newrot, pp->PC_OBB.ort);
this->m_networkModule->SendEntityUpdatePacket(pp->PC_entityID, pp->PC_pos, pp->PC_velocity, newrot);
}
if (this->m_player1.GetGrabbed() == this->m_player2.GetBall()) //send updates of player2 ball if player1 has grabbed it
{
pp = this->m_player2.GetBall()->GetPhysicsComponent();
DirectX::XMFLOAT4X4 newrot;
DirectX::XMStoreFloat4x4(&newrot, pp->PC_OBB.ort);
this->m_networkModule->SendEntityUpdatePacket(pp->PC_entityID, pp->PC_pos, pp->PC_velocity, newrot);
}
Entity* ent = nullptr;
if (this->m_networkModule->IsHost())
{
for (size_t i = 0; i < this->m_dynamicEntitys.size(); i++) //Change start and end with physics packet
{
ent = this->m_dynamicEntitys.at(i);
if (ent != this->m_player2.GetGrabbed() &&
ent->GetEntityID() != DEFINED_IDS::CHAIN_1 && ent->GetEntityID() != DEFINED_IDS::CHAIN_2 &&
ent->GetEntityID() != DEFINED_IDS::BALL_1 && ent->GetEntityID() != DEFINED_IDS::BALL_2 //if the hosting player
)
//If it is not grabbed by player2 and is not a chain link
{
pp = this->m_dynamicEntitys.at(i)->GetPhysicsComponent();
DirectX::XMFLOAT4X4 newrot;
DirectX::XMStoreFloat4x4(&newrot, pp->PC_OBB.ort);
this->m_networkModule->SendEntityUpdatePacket(pp->PC_entityID, pp->PC_pos, pp->PC_velocity, newrot); //Send the update
}
}
}
if (this->m_networkModule->IsHost())
{
PhysicsComponent* pc = nullptr;
for (PlatformEntity* e : this->m_platformEntities)
{
pc = e->GetPhysicsComponent();
DirectX::XMFLOAT4X4 newrot;
DirectX::XMStoreFloat4x4(&newrot, pc->PC_OBB.ort);
this->m_networkModule->SendEntityUpdatePacket(pc->PC_entityID, pc->PC_pos, pc->PC_velocity,newrot);
}
}
}
#pragma endregion Network_Send_Updates
#pragma region
//Update all puzzle entities
#pragma region
//Commong variables needed for logic checks
DirectX::XMFLOAT3 playerPos;
DirectX::XMStoreFloat3(&playerPos, this->m_player1.GetPhysicsComponent()->PC_pos);
//Buttons and levers require input for logical evaluation of activation
if (inputHandler->IsKeyPressed(SDL_SCANCODE_E))
{
//Iterator version of looping
/*for (std::vector<ButtonEntity*>::iterator i = this->m_buttonEntities.begin(); i != this->m_buttonEntities.end(); i++)
{
DirectX::XMFLOAT3 playerPos;
DirectX::XMStoreFloat3(&playerPos, this->m_player1.GetPhysicsComponent()->PC_pos);
(*i)->CheckPressed(playerPos);
}
for (std::vector<LeverEntity*>::iterator i = this->m_leverEntities.begin(); i != this->m_leverEntities.end(); i++)
{
DirectX::XMFLOAT3 playerPos;
DirectX::XMStoreFloat3(&playerPos, this->m_player1.GetPhysicsComponent()->PC_pos);
(*i)->CheckPressed(playerPos);
}*/
//c++11 looping construct
for (ButtonEntity* e : this->m_buttonEntities)
{
e->CheckPressed(playerPos);
}
for (LeverEntity* e : this->m_leverEntities)
{
e->CheckPressed(playerPos);
}
}
if (inputHandler->IsKeyDown(SDL_SCANCODE_E))
{
int increasing = (inputHandler->IsKeyDown(SDL_SCANCODE_LSHIFT)) ? -1 : 1; //Only uses addition but branches, kind of
//increasing = -1 + (!inputHandler->IsKeyDown(SDL_SCANCODE_LSHIFT)) * 2; //No branching calculation, but uses multiplication and addition
for (std::vector<WheelEntity*>::iterator i = this->m_wheelEntities.begin(); i != this->m_wheelEntities.end(); i++)
{
(*i)->CheckPlayerInteraction(playerPos, increasing);
}
}
else if (inputHandler->IsKeyReleased(SDL_SCANCODE_E))
{
for (std::vector<WheelEntity*>::iterator i = this->m_wheelEntities.begin(); i != this->m_wheelEntities.end(); i++)
{
(*i)->CheckPlayerInteraction(playerPos, 0);
}
}
//Buttons require updates to countdown their reset timer
for (std::vector<ButtonEntity*>::iterator i = this->m_buttonEntities.begin(); i != this->m_buttonEntities.end(); i++)
{
(*i)->Update(dt, inputHandler);
}
//Lever require updates to animate
for (std::vector<LeverEntity*>::iterator i = this->m_leverEntities.begin(); i != this->m_leverEntities.end(); i++)
{
(*i)->Update(dt, inputHandler);
}
//Wheels require updates to rotate based on state calculated in CheckPlayerInteraction
for (std::vector<WheelEntity*>::iterator i = this->m_wheelEntities.begin(); i != this->m_wheelEntities.end(); i++)
{
(*i)->Update(dt, inputHandler);
}
//Doors require updates to change opening state and animate
for (std::vector<DoorEntity*>::iterator i = this->m_doorEntities.begin(); i != this->m_doorEntities.end(); i++)
{
(*i)->Update(dt, inputHandler);
}
#pragma endregion Puzzle element update logic
#pragma region
//Check for state changes that should be sent over the network
LeverSyncState* leverSync = nullptr;
for (LeverEntity* e : this->m_leverEntities)
{
leverSync = e->GetSyncState();
if (leverSync != nullptr)
{
this->m_networkModule->SendStateLeverPacket(leverSync->entityID, leverSync->isActive);
delete leverSync;
}
}
ButtonSyncState* buttonSync = nullptr;
for (ButtonEntity* e : this->m_buttonEntities)
{
buttonSync = e->GetSyncState();
if (buttonSync != nullptr)
{
this->m_networkModule->SendStateButtonPacket(buttonSync->entityID, buttonSync->isActive);
delete buttonSync;
}
}
WheelSyncState* wheelSync = nullptr;
for (WheelEntity* e : this->m_wheelEntities)
{
wheelSync = e->GetSyncState();
if (wheelSync != nullptr)
{
this->m_networkModule->SendStateWheelPacket(wheelSync->entityID, wheelSync->rotationState, wheelSync->rotationAmount);
delete wheelSync;
}
}
#pragma endregion Puzzle elements synchronization
#pragma region
for (size_t i = 0; i < this->m_platformEntities.size(); i++)
{
this->m_platformEntities[i]->Update(dt, inputHandler);
}
#pragma endregion Platforms
#pragma endregion Update_Puzzle_Elements
#pragma region
// We only send updates for player1 since player2 will recive the updates from the network
AnimationComponent* ap = this->m_player1.GetAnimationComponent();
if (this->m_player1.GetRagdoll()->state ==RagdollState:: RAGDOLL || this->m_player1.GetRagdoll()->state == RagdollState::KEYFRAMEBLEND)
{
GraphicsAnimationComponent* gp = (GraphicsAnimationComponent*)this->m_player1.GetGraphicComponent();
for (int i = 0; i < gp->jointCount; i++) //Iterate all joints
{
//Send a packet for E V E R Y joint
this->m_networkModule->SendAnimationPacket(this->m_player1.GetEntityID(), RAGDOLL_STATE, 0.f, Blending::NO_TRANSITION, false, false, 0.f, 1.0, i, gp->finalJointTransforms[i]);
}
}
else if (this->m_player1.isAnimationChanged())
{
this->m_networkModule->SendAnimationPacket(this->m_player1.GetEntityID(), ap->currentState, ap->transitionDuration, ap->blendFlag, ap->target_State->isLooping, ap->lockAnimation, ap->playingSpeed, ap->velocity, 0, DirectX::XMMATRIX());
}
#pragma endregion Send_Player_Animation_Update
for (size_t i = 0; i < m_fieldEntities.size(); i++)
{
int fieldActivated = m_fieldEntities[i]->Update(dt, inputHandler);
this->m_clearedLevel = fieldActivated;
}
// Reactionary level director acts
this->m_director.Update(dt);
#pragma region
if (inputHandler->IsKeyPressed(SDL_SCANCODE_INSERT) ||
this->m_networkModule->PacketBuffer_GetResetPacket().size() != 0)
{
if (inputHandler->IsKeyPressed(SDL_SCANCODE_INSERT)) //If we clicked
{
this->m_networkModule->SendFlagPacket(SYNC_RESET); //Send packet to other client
}
// Reset player-position to spawn
if (this->m_networkModule->IsHost())
{
m_player1.GetPhysicsComponent()->PC_pos = m_player1_Spawn;
m_player2.GetPhysicsComponent()->PC_pos = m_player2_Spawn;
m_player1.GetBall()->GetPhysicsComponent()->PC_pos =
DirectX::XMVectorAdd(m_player1_Spawn, DirectX::XMVectorSet(0.0f, .11f, 1.5f, 0.f));
m_player2.GetBall()->GetPhysicsComponent()->PC_pos =
DirectX::XMVectorAdd(m_player2_Spawn, DirectX::XMVectorSet(0.0f, .11f, 1.5f, 0.f));
m_player1.GetPhysicsComponent()->PC_velocity = { 0 };
m_player2.GetPhysicsComponent()->PC_velocity = { 0 };
m_player1.GetBall()->GetPhysicsComponent()->PC_velocity = { 0 };
m_player2.GetBall()->GetPhysicsComponent()->PC_velocity = { 0 };
}
else
{
m_player1.GetPhysicsComponent()->PC_pos = m_player2_Spawn;
m_player2.GetPhysicsComponent()->PC_pos = m_player1_Spawn;
m_player1.GetBall()->GetPhysicsComponent()->PC_pos =
DirectX::XMVectorAdd(m_player2_Spawn, DirectX::XMVectorSet(0.0f, .11f, 1.5f, 0.f));
m_player2.GetBall()->GetPhysicsComponent()->PC_pos =
DirectX::XMVectorAdd(m_player1_Spawn, DirectX::XMVectorSet(0.0f, .11f, 1.5f, 0.f));
m_player1.GetPhysicsComponent()->PC_velocity = { 0 };
m_player2.GetPhysicsComponent()->PC_velocity = { 0 };
m_player1.GetBall()->GetPhysicsComponent()->PC_velocity = { 0 };
m_player2.GetBall()->GetPhysicsComponent()->PC_velocity = { 0 };
}
// Iterate through chainlink list to reset velocity and position of players, chain links, and balls
this->m_cHandler->GetPhysicsHandler()->ResetChainLink();
}
#ifdef DEVELOPMENTFUNCTIONS
if (inputHandler->IsKeyPressed(SDL_SCANCODE_Y))
{
//TODO: NOCLIP BOOOOIS
if (inputHandler->IsKeyDown(SDL_SCANCODE_LSHIFT))
{
m_player1.GetPhysicsComponent()->PC_gravityInfluence = 1;
m_player1.GetPhysicsComponent()->PC_steadfast = false;
}
else
{
m_player1.GetPhysicsComponent()->PC_gravityInfluence = 0;
m_player1.GetPhysicsComponent()->PC_steadfast = true;
}
//Result: Sloppy teleport :(
m_player1.GetPhysicsComponent()->PC_pos = DirectX::XMVectorAdd(
m_player1.GetPhysicsComponent()->PC_pos,
(DirectX::XMVectorScale(m_player1.GetLookDir(), 3.0f)));
this->m_cHandler->GetPhysicsHandler()->ResetChainLink();
}
#endif // DEVELOPMENTFUNCTIONS
#pragma endregion Reset KEY
#ifdef DEVELOPMENTFUNCTIONS
#pragma region
if (inputHandler->IsKeyPressed(SDL_SCANCODE_M))
{
//SoundHandler::instance().PlaySound2D(Sounds2D::MENU, false, false);
}
if (inputHandler->IsKeyPressed(SDL_SCANCODE_N))
{
DirectX::XMFLOAT3 pos;
DirectX::XMStoreFloat3(&pos, this->m_player2.GetPhysicsComponent()->PC_pos);
SoundHandler::instance().PlaySound3D(Sounds3D::GENERAL_CHAIN_DRAG_1, pos, true, false);
}
#pragma endregion MUSIC_KEYS
#endif // DEVELOPMENTFUNCTIONS
if (this->m_player1.GetRagdoll()->state == RagdollState::ANIMATED)
{
this->m_cameraRef->Update();
}
else
{
this->m_cameraRef->RagdollCameraUpdate(this->m_player1.GetPhysicsComponent()->PC_pos, this->m_player1.GetRagdoll()->state);
}
//Update the listner pos and direction for sound
DirectX::XMFLOAT3 dir;
DirectX::XMStoreFloat3(&dir, this->m_cameraRef->GetDirection());
DirectX::XMFLOAT3 up;
this->m_cameraRef->GetCameraUp(up);
SoundHandler::instance().UpdateListnerPos(this->m_cameraRef->GetCameraPos(), dir, up);
if (inputHandler->IsKeyPressed(SDL_SCANCODE_ESCAPE))
{
this->m_networkModule->SendFlagPacket(PacketTypes::DISCONNECT_REQUEST);
this->m_cHandler->RemoveLastUIComponent();
this->m_cHandler->RemoveLastUIComponent();
this->m_gsh->PopStateFromStack();
//MenuState* menuState = new MenuState();
//result = menuState->Initialize(this->m_gsh, this->m_cHandler, this->m_cameraRef);
//if (result > 0)
//{
// //Push it to the gamestate stack/vector
// this->m_gsh->PushStateToStack(menuState);
//}
//else
//{
// //Delete it
// delete menuState;
// menuState = nullptr;
//}
result = 1;
}
//Controls overlay
if (inputHandler->IsKeyPressed(SDL_SCANCODE_F1))
{
this->m_controlsOverlay->active = 1;
}
if (inputHandler->IsKeyReleased(SDL_SCANCODE_F1))
{
this->m_controlsOverlay->active = 0;
}
return result;
}
int LevelState::CreateLevel(LevelData::Level * data)
{
Resources::ResourceHandler* resHandler = Resources::ResourceHandler::GetInstance();
#pragma region
this->m_cameraRef->UpdateProjection(this->m_levelPaths[this->m_curLevel].farPlane);
#pragma endregion Camera projection matrix update
#pragma region
//Get how many static and dynamic components that will be needed in the level
int staticEntityCount = 0;
int dynamicEntityCount = 0;
//Normal entities
for (size_t i = 0; i < data->numEntities; i++)
{
staticEntityCount += data->entities[i].isStatic;
dynamicEntityCount += !data->entities[i].isStatic;
}
//AI entities
dynamicEntityCount += data->numAI;
//Puzzle elements
dynamicEntityCount += data->numButton;
dynamicEntityCount += data->numLever;
dynamicEntityCount += data->numWheel;
dynamicEntityCount += data->numDoor;
dynamicEntityCount += CHAIN_SEGMENTS * 2;
this->m_cHandler->ResizeGraphicsStatic(staticEntityCount);
this->m_cHandler->ResizeGraphicsDynamic(dynamicEntityCount);
#pragma endregion Update component list sizes
#pragma region
DirectX::XMVECTOR rot;
DirectX::XMVECTOR pos;
rot.m128_f32[3] = 0.0f; //Set w to 0
pos.m128_f32[3] = 0.0f; //Set w to 0
DirectX::XMMATRIX translate;
DirectX::XMMATRIX rotate;
Resources::Model* modelPtr;
Resources::Status st = Resources::ST_OK;
this->m_player1_Spawn = DirectX::XMVectorSet( //Store spawnPoint for player 1
data->spawns[0].position[0],
data->spawns[0].position[1],
data->spawns[0].position[2],
0);
this->m_player2_Spawn = DirectX::XMVectorSet( //Store spawnPoint for player 2
data->spawns[1].position[0],
data->spawns[1].position[1],
data->spawns[1].position[2],
0);
#pragma endregion preparations and variable
#pragma region
//NETWORK SAFETY
/*
This is only a safety check if the network module was not initialized.
It should have been initialized in the menu state and have been connected
to the other player. By using isHost() function we know can determine if
we should switch the players ID and position or not.
*/
if (!this->m_networkModule)
{
this->m_networkModule = new NetworkModule();
this->m_networkModule->Initialize();
}
if (this->m_networkModule->IsHost())
{
this->m_player1.GetPhysicsComponent()->PC_pos = this->m_player1_Spawn;
//this->m_player1.GetPhysicsComponent()->PC_pos = DirectX::XMVectorAdd(this->m_player1_Spawn, DirectX::XMVectorSet(0, 0, 0, 0));
this->m_cHandler->GetPhysicsHandler()->CreateRagdollBodyWithChainAndBall(1, this->m_player1.GetAnimationComponent()->skeleton->GetSkeletonData()->joints,
this->m_player1.GetAnimationComponent(),
DirectX::XMVectorAdd(this->m_player1.GetPhysicsComponent()->PC_pos, DirectX::XMVectorSet(10, 0, 0, 0)),
this->m_player1.GetPhysicsComponent(),
this->m_player1.GetBall()->GetPhysicsComponent());
this->m_player2.GetPhysicsComponent()->PC_pos = DirectX::XMVectorAdd(this->m_player2_Spawn, DirectX::XMVectorSet(0, 1, 0, 0));
}
else
{
this->m_player1.GetPhysicsComponent()->PC_pos = this->m_player2_Spawn;
this->m_cHandler->GetPhysicsHandler()->CreateRagdollBodyWithChainAndBall(1, this->m_player1.GetAnimationComponent()->skeleton->GetSkeletonData()->joints,
this->m_player1.GetAnimationComponent(),
DirectX::XMVectorAdd(this->m_player1.GetPhysicsComponent()->PC_pos, DirectX::XMVectorSet(10, 0, 0, 0)),
this->m_player1.GetPhysicsComponent(),
this->m_player1.GetBall()->GetPhysicsComponent());
this->m_player2.GetPhysicsComponent()->PC_pos = this->m_player1_Spawn;
}
#pragma endregion Network
#pragma region
this->m_player1.GetBall()->GetPhysicsComponent()->PC_pos =
DirectX::XMVectorAdd(
m_player1.GetPhysicsComponent()->PC_pos, DirectX::XMVectorSet(2.0f, 0.0f, 0.0f, 0.0f));
m_player2.GetBall()->GetPhysicsComponent()->PC_pos =
DirectX::XMVectorAdd(
m_player2.GetPhysicsComponent()->PC_pos, DirectX::XMVectorSet(1.0f, 1.0f, 1.0f, 0.0f));
#pragma region
float linkLenght = 0.5f;
DirectX::XMVECTOR diffVec = DirectX::XMVectorSet(0.1f, 0.0f, 0.0f, 0.0f);
PhysicsComponent* previous = this->m_player1.GetPhysicsComponent();
PhysicsComponent* next = nullptr;
PhysicsComponent* PC_ptr = nullptr;
this->m_Player1ChainPhysicsComp.push_back(this->m_player1.GetPhysicsComponent());
for (int i = 0; i < CHAIN_SEGMENTS; i++)
{
if (i != 0)
{
linkLenght = 0.5f;
}
unsigned int entityID = DEFINED_IDS::CHAIN_1;
PC_ptr = this->m_cHandler->GetPhysicsComponent();
PC_ptr->PC_pos = DirectX::XMVectorAdd(this->m_player1.GetPhysicsComponent()->PC_pos, DirectX::XMVectorScale(diffVec, float(i)));
PC_ptr->PC_entityID = entityID;
PC_ptr->PC_BVtype = BV_Sphere;
PC_ptr->PC_Sphere.radius = 0.1f;
PC_ptr->PC_mass = 0.2f;
PC_ptr->PC_friction = 1.0f;
GraphicsComponent* GC_ptr = this->m_cHandler->GetDynamicGraphicsComponent();
GC_ptr->modelID = CHAIN_SEGMENT_MODEL_ID;
GC_ptr->active = false;
resHandler->GetModel(GC_ptr->modelID, GC_ptr->modelPtr);
DynamicEntity* chainLink = new DynamicEntity();
chainLink->Initialize(entityID, PC_ptr, GC_ptr);
this->m_dynamicEntitys.push_back(chainLink);
next = PC_ptr;
this->m_Player1ChainPhysicsComp.push_back(PC_ptr);
PC_ptr = nullptr;
if (i == 0)
{
this->m_player1.GetRagdoll()->link_index = this->m_cHandler->GetPhysicsHandler()->CreateLink(previous, next, linkLenght, PhysicsLinkType::PL_CHAIN);
}
else
{
this->m_cHandler->GetPhysicsHandler()->CreateLink(previous, next, linkLenght, PhysicsLinkType::PL_CHAIN);
}
previous = next;
}
this->m_Player1ChainPhysicsComp.push_back(this->m_player1.GetBall()->GetPhysicsComponent());
this->m_cHandler->GetPhysicsHandler()->CreateLink(previous, this->m_player1.GetBall()->GetPhysicsComponent(), linkLenght, PhysicsLinkType::PL_CHAIN);
diffVec = DirectX::XMVectorSet(0.1f, 0.0f, 0.0f, 0.0f);
linkLenght = 0.5f;
previous = this->m_player2.GetPhysicsComponent();
next = nullptr;
this->m_Player2ChainPhysicsComp.push_back(this->m_player2.GetPhysicsComponent());
for (int i = 1; i <= CHAIN_SEGMENTS; i++)
{
if (i != 1)
{
linkLenght = 0.50f;
}
unsigned int entityID = DEFINED_IDS::CHAIN_2;
PhysicsComponent* PC_ptr = this->m_cHandler->GetPhysicsComponent();
PC_ptr->PC_pos = DirectX::XMVectorAdd(this->m_player2.GetPhysicsComponent()->PC_pos, DirectX::XMVectorScale(diffVec, float(i)));
PC_ptr->PC_entityID = entityID;
PC_ptr->PC_BVtype = BV_Sphere;
PC_ptr->PC_Sphere.radius = 0.1f;
PC_ptr->PC_mass = 0.2f;
PC_ptr->PC_friction = 1.0f;
GraphicsComponent* GC_ptr = this->m_cHandler->GetDynamicGraphicsComponent();
GC_ptr->modelID = CHAIN_SEGMENT_MODEL_ID;
GC_ptr->active = false;
resHandler->GetModel(GC_ptr->modelID, GC_ptr->modelPtr);
DynamicEntity* chainLink = new DynamicEntity();
chainLink->Initialize(entityID, PC_ptr, GC_ptr);
this->m_dynamicEntitys.push_back(chainLink);
next = PC_ptr;
this->m_Player2ChainPhysicsComp.push_back(PC_ptr);
if (i == 1)
{
this->m_cHandler->GetPhysicsHandler()->CreateLink(previous, next, linkLenght, PhysicsLinkType::PL_CHAIN);
}
else
{
this->m_cHandler->GetPhysicsHandler()->CreateLink(previous, next, linkLenght, PhysicsLinkType::PL_CHAIN);
}
previous = next;
}
this->m_Player2ChainPhysicsComp.push_back(this->m_player2.GetBall()->GetPhysicsComponent());
this->m_cHandler->GetPhysicsHandler()->CreateLink(previous, this->m_player2.GetBall()->GetPhysicsComponent(), linkLenght, PhysicsLinkType::PL_CHAIN);
#pragma endregion Create_Chain_Link
this->m_cHandler->GetPhysicsHandler()->ResetChainLink();
#pragma endregion Checkpoints
for (size_t i = 0; i < data->numEntities; i++)
{
LevelData::EntityHeader* currEntity = &data->entities[i]; //Current entity
currEntity->EntityID += DEFINED_IDS::NUMMBER_OF_IDS; //ADD number of predefined ids to avoid conflict from editor
GraphicsComponent* t_gc;
Resources::Model * modelPtr;
resHandler->GetModel(currEntity->modelID, modelPtr);
if (modelPtr->GetSkeleton() != nullptr)
{
t_gc = m_cHandler->GetGraphicsAnimationComponent();
}
else
{
if (currEntity->isStatic)
t_gc = m_cHandler->GetStaticGraphicsComponent();
else
t_gc = m_cHandler->GetDynamicGraphicsComponent();
}
t_gc->modelID = currEntity->modelID;
t_gc->active = true;
t_gc->modelPtr = modelPtr; //Get and apply a pointer to the model
//Create GraphicsComponent
//Create world matrix from data
memcpy(pos.m128_f32, currEntity->position, sizeof(float) * 3); //Convert from POD to DirectX Vector
memcpy(rot.m128_f32, currEntity->rotation, sizeof(float) * 3); //Convert from POD to DirectX Vector
translate = DirectX::XMMatrixTranslationFromVector(pos);
#pragma region
//Create the rotation matrix
DirectX::XMMATRIX rotationMatrixY = DirectX::XMMatrixRotationY(DirectX::XMConvertToRadians(rot.m128_f32[1]));
DirectX::XMMATRIX rotationMatrixX = DirectX::XMMatrixRotationX(DirectX::XMConvertToRadians(rot.m128_f32[0]));
DirectX::XMMATRIX rotationMatrixZ = DirectX::XMMatrixRotationZ(DirectX::XMConvertToRadians(rot.m128_f32[2]));
DirectX::XMMATRIX rotate = DirectX::XMMatrixMultiply(rotationMatrixZ, rotationMatrixX);
rotate = DirectX::XMMatrixMultiply(rotate, rotationMatrixY);
//rotate = DirectX::XMMatrixRotationRollPitchYawFromVector(rot);
#pragma endregion Calculate rotation matrix
//Create the world matrix from a rotation and translation
t_gc->worldMatrix = DirectX::XMMatrixMultiply(rotate, translate);
//Create Physics component
PhysicsComponent* t_pc = m_cHandler->GetPhysicsComponent();
t_pc->PC_entityID = currEntity->EntityID; //Set Entity ID
//We cannot set pos directly because of bounding box vs model offsets
//t_pc->PC_pos = pos; //Set Position
t_pc->PC_rotation = rot; //Set Rotation
t_pc->PC_is_Static = currEntity->isStatic; //Set IsStatic
t_pc->PC_active = true; //Set Active
t_pc->PC_BVtype = BV_OBB;
//t_pc->PC_OBB.ort = DirectX::XMMatrixMultiply(t_pc->PC_OBB.ort, rotate);
//st = Resources::ResourceHandler::GetInstance()->GetModel(currEntity->modelID, modelPtr);
DirectX::XMMATRIX tempOBBPos = DirectX::XMMatrixTranslationFromVector(DirectX::XMVECTOR{ modelPtr->GetOBBData().position.x, modelPtr->GetOBBData().position.y, modelPtr->GetOBBData().position.z });
tempOBBPos = DirectX::XMMatrixMultiply(tempOBBPos, t_gc->worldMatrix);
t_pc->PC_pos = tempOBBPos.r[3];
DirectX::XMStoreFloat3(&t_gc->pos, tempOBBPos.r[3]);
//t_pc->PC_pos.m128_f32[3] = 1.0f;
//get information from file
//static components should have the mass of 0
//t_pc->PC_mass = 0;
//t_pc->PC_friction = 0.55f;
#ifdef _DEBUG
if (st != Resources::ST_OK)
std::cout << "Model could not be found when loading level data, ID: " << currEntity->modelID << std::endl;//NOTE: IS offseted by DEFINED_IDS::NUMMBER_OF_IDS
#endif // _DEBUG
t_pc->PC_OBB = m_ConvertOBB(modelPtr->GetOBBData()); //Convert and insert OBB data
t_pc->PC_OBB.ort = DirectX::XMMatrixMultiply(t_pc->PC_OBB.ort, rotate);
t_pc->PC_OBB.ort = DirectX::XMMatrixTranspose(t_pc->PC_OBB.ort);
//This is where the final rotation is stores. We want to use this rotation matrix and get the extensions for the OBB
//Create a vector describing the extension of the AABB
//Rotate the extension according the OBB ort
//And lastly store the result in graphics components as the model bounds used in culling
DirectX::XMStoreFloat3(&t_gc->extensions, DirectX::XMVector3Transform(DirectX::XMVectorSet(t_pc->PC_OBB.ext[0], t_pc->PC_OBB.ext[1], t_pc->PC_OBB.ext[2], 0.0f), t_pc->PC_OBB.ort));
t_gc->ort = t_pc->PC_OBB.ort;
//sets the friction of the static environment if extension in y is smaller than 0.5 we assume its the floor and give it a higher friction than the walls
if (t_pc->PC_OBB.ext[1] < 0.5f && DirectX::XMVector3Equal(t_pc->PC_OBB.ort.r[1], DirectX::XMVectorSet(0, 1, 0, 0)))
{
t_pc->PC_mass = 0;
t_pc->PC_friction = 1.0f;
}
else //walls get lower friction
{
t_pc->PC_mass = 0;
t_pc->PC_friction = 0.0f;
}
if (t_pc->PC_is_Static) {
StaticEntity* tse = new StaticEntity();
tse->Initialize(t_pc->PC_entityID, t_pc, t_gc, nullptr);// Entity needs its ID
this->m_staticEntitys.push_back(tse); //Push new entity to list
}
else {
DynamicEntity* tde = new DynamicEntity();
tde->Initialize(t_pc->PC_entityID, t_pc, t_gc, nullptr);// Entity needs its ID
this->m_dynamicEntitys.push_back(tde); //Push new entity to list
}
}
#pragma region
for (size_t i = 0; i < data->numAI; i++)
{
AIComponent* t_ac = m_cHandler->GetAIComponent();
t_ac->AC_triggered = true;// Temp: Needed for AIHandler->Update()
t_ac->AC_entityID = data->aiComponents[i].EntityID + DEFINED_IDS::NUMMBER_OF_IDS; //Add nummber of predefined ids to avoid conflict from editor
t_ac->AC_time = data->aiComponents[i].time;
t_ac->AC_speed = data->aiComponents[i].speed;
t_ac->AC_pattern = data->aiComponents[i].pattern;
t_ac->AC_nrOfWaypoint = data->aiComponents[i].nrOfWaypoints;
for (int x = 0; x < t_ac->AC_nrOfWaypoint; x++)
{
t_ac->AC_waypoints[x] = {
data->aiComponents[i].wayPoints[x][0],
data->aiComponents[i].wayPoints[x][1],
data->aiComponents[i].wayPoints[x][2]
};
}
t_ac->AC_position = t_ac->AC_waypoints[0];
#pragma region Graphics
resHandler->GetModel(data->aiComponents[i].modelID, modelPtr);
GraphicsComponent* t_gc = m_cHandler->GetDynamicGraphicsComponent();
t_gc->active = 1;
t_gc->modelID = data->aiComponents[i].modelID;
t_gc->modelPtr = modelPtr;
//Create world matrix from data
memcpy(rot.m128_f32, data->aiComponents[i].rotation, sizeof(float) * 3);//Convert from POD to DirectX Vector
translate = DirectX::XMMatrixTranslationFromVector(t_ac->AC_position);
DirectX::XMMATRIX rotationMatrixX = DirectX::XMMatrixRotationX(DirectX::XMConvertToRadians(rot.m128_f32[0]));
DirectX::XMMATRIX rotationMatrixY = DirectX::XMMatrixRotationY(DirectX::XMConvertToRadians(rot.m128_f32[1]));
DirectX::XMMATRIX rotationMatrixZ = DirectX::XMMatrixRotationZ(DirectX::XMConvertToRadians(rot.m128_f32[2]));
//Create the rotation matrix
DirectX::XMMATRIX rotate = DirectX::XMMatrixMultiply(rotationMatrixZ, rotationMatrixX);
rotate = DirectX::XMMatrixMultiply(rotate, rotationMatrixY);
t_gc->worldMatrix = DirectX::XMMatrixMultiply(rotate, translate);
st = Resources::ResourceHandler::GetInstance()->GetModel(data->aiComponents[i].modelID, modelPtr);
#ifdef _DEBUG
if (st != Resources::ST_OK)
std::cout << "Model could not be found when loading level data, ID: " << data->aiComponents[i].modelID << std::endl;
#endif // _DEBUG
#pragma endregion
#pragma region Physics
PhysicsComponent* t_pc = m_cHandler->GetPhysicsComponent();
t_pc->PC_pos = t_ac->AC_position;
t_pc->PC_entityID = data->aiComponents[i].EntityID + DEFINED_IDS::NUMMBER_OF_IDS; //Add nummber of predefined ids to avoid conflict from editor
t_pc->PC_is_Static = false;
t_pc->PC_steadfast = true;
t_pc->PC_gravityInfluence = 0;
t_pc->PC_friction = 0.0f;
t_pc->PC_elasticity = 0.1f;
t_pc->PC_BVtype = BV_OBB;
t_pc->PC_mass = 0;
t_pc->PC_AABB.ext[0] = modelPtr->GetOBBData().extension[0];
t_pc->PC_AABB.ext[1] = modelPtr->GetOBBData().extension[1];
t_pc->PC_AABB.ext[2] = modelPtr->GetOBBData().extension[2];
DirectX::XMVECTOR tempRot = DirectX::XMVector3Transform(DirectX::XMVECTOR{ t_pc->PC_AABB.ext[0],
t_pc->PC_AABB.ext[1] , t_pc->PC_AABB.ext[2] }, rotate);
t_pc->PC_AABB.ext[0] = abs(tempRot.m128_f32[0]);
t_pc->PC_AABB.ext[1] = abs(tempRot.m128_f32[1]);
t_pc->PC_AABB.ext[2] = abs(tempRot.m128_f32[2]);
t_pc->PC_OBB = m_ConvertOBB(modelPtr->GetOBBData()); //Convert and insert OBB data
// Adjust OBB in physics component - hack...
DirectX::XMMATRIX tempOBBPos = DirectX::XMMatrixTranslationFromVector(DirectX::XMVECTOR{
modelPtr->GetOBBData().position.x,
modelPtr->GetOBBData().position.y,
modelPtr->GetOBBData().position.z
});
tempOBBPos = DirectX::XMMatrixMultiply(tempOBBPos, t_gc->worldMatrix);
t_pc->PC_OBB.ort = rotate;
#pragma endregion
PlatformEntity* tpe = new PlatformEntity();
tpe->Initialize(t_pc->PC_entityID, t_pc, t_gc, t_ac);
this->m_platformEntities.push_back(tpe);
}
m_cHandler->WaypointTime();
#pragma endregion AI
#pragma region
for (size_t i = 0; i < data->numCheckpoints; i++)
{
Field* tempField = this->m_cHandler->GetPhysicsHandler()->CreateField(
data->checkpoints[i].position,
DEFINED_IDS::PLAYER_1, //EntityID Player1
DEFINED_IDS::PLAYER_2, //EntityID Player2
data->checkpoints[i].ext,
data->checkpoints[i].ort
);
FieldEntity* tempFE = new FieldEntity();
tempFE->Initialize(data->checkpoints[i].entityID + DEFINED_IDS::NUMMBER_OF_IDS, tempField);
this->m_fieldEntities.push_back(tempFE);
this->m_fieldEntities[i]->AddObserver(&this->m_director, this->m_director.GetID());
}
// TODO: Field Data for States in Level Director
#pragma endregion Creating Fields
//Create the PuzzleElements
#pragma region
//Create the Buttons
for (size_t i = 0; i < data->numButton; i++)
{
LevelData::ButtonHeader tempHeader = data->buttons[i];
tempHeader.EntityID += DEFINED_IDS::NUMMBER_OF_IDS; //Add nummber of predefined ids to avoid conflict from editor
ButtonEntity* tempEntity = new ButtonEntity();
//Create world matrix from data
memcpy(pos.m128_f32, tempHeader.position, sizeof(float) * 3); //Convert from POD to DirectX Vector
memcpy(rot.m128_f32, tempHeader.rotation, sizeof(float) * 3); //Convert from POD to DirectX Vector
//Convert the useless values into proper system supported radians. Glorious.
rot = DirectX::XMVectorSet(DirectX::XMConvertToRadians(DirectX::XMVectorGetX(rot)), DirectX::XMConvertToRadians(DirectX::XMVectorGetY(rot)), DirectX::XMConvertToRadians(DirectX::XMVectorGetZ(rot)), 1.0f);
translate = DirectX::XMMatrixTranslationFromVector(pos);
DirectX::XMMATRIX rotationMatrixY = DirectX::XMMatrixRotationY(rot.m128_f32[1]);
DirectX::XMMATRIX rotationMatrixX = DirectX::XMMatrixRotationX(rot.m128_f32[0]);
DirectX::XMMATRIX rotationMatrixZ = DirectX::XMMatrixRotationZ(rot.m128_f32[2]);
//Should just use this function instead of a bunch
//DirectX::waa(rot);
//Create the rotation matrix
DirectX::XMMATRIX rotate = DirectX::XMMatrixMultiply(rotationMatrixZ, rotationMatrixX);
rotate = DirectX::XMMatrixMultiply(rotate, rotationMatrixY);
//rotate = DirectX::XMMatrixRotationRollPitchYawFromVector(rot);
GraphicsComponent* button1G = m_cHandler->GetDynamicGraphicsComponent();
button1G->active = true;
button1G->modelID = tempHeader.modelID;
button1G->worldMatrix = DirectX::XMMatrixMultiply(rotate, translate);
resHandler->GetModel(button1G->modelID, button1G->modelPtr);
PhysicsComponent* button1P = m_cHandler->GetPhysicsComponent();
button1P->PC_entityID = tempHeader.EntityID; //Set Entity ID
button1P->PC_pos = pos; //Set Position
button1P->PC_rotation = rot; //Set Rotation
button1P->PC_is_Static = true; //Set IsStatic
button1P->PC_active = true; //Set Active
button1P->PC_gravityInfluence = 1.0f;
button1P->PC_mass = 0;
button1P->PC_friction = 0.00f;
button1P->PC_collides = true;
button1P->PC_elasticity = 0.2f;
button1P->PC_steadfast = true;
//DirectX::XMQuaternionRotationMatrix
button1P->PC_BVtype = BV_OBB;
//Copy the bounding volume data from the model into the physics component for reference
button1P->PC_OBB = m_ConvertOBB(button1G->modelPtr->GetOBBData()); //Convert and insert OBB data
button1P->PC_AABB.ext[0] = button1G->modelPtr->GetOBBData().extension[0];
button1P->PC_AABB.ext[1] = button1G->modelPtr->GetOBBData().extension[1];
button1P->PC_AABB.ext[2] = button1G->modelPtr->GetOBBData().extension[2];
button1P->PC_OBB.ext[0] = button1P->PC_AABB.ext[0] * 2.0f;
button1P->PC_OBB.ext[1] = button1P->PC_AABB.ext[1] * 2.0f;
button1P->PC_OBB.ext[2] = button1P->PC_AABB.ext[2] * 2.0f;
DirectX::XMMATRIX tempOBBPos = DirectX::XMMatrixTranslationFromVector(DirectX::XMVECTOR{ button1G->modelPtr->GetOBBData().position.x, button1G->modelPtr->GetOBBData().position.y, button1G->modelPtr->GetOBBData().position.z });
tempOBBPos = DirectX::XMMatrixMultiply(tempOBBPos, button1G->worldMatrix);
button1P->PC_pos = tempOBBPos.r[3];
DirectX::XMStoreFloat3(&button1G->pos, tempOBBPos.r[3]);
button1P->PC_OBB.ort = DirectX::XMMatrixMultiply(button1P->PC_OBB.ort, rotate);
button1P->PC_OBB.ort = DirectX::XMMatrixTranspose(button1P->PC_OBB.ort);
//This is where the final rotation is stored. We want to use this rotation matrix and get the extensions for the OBB
//Create a vector describing the extension of the AABB
//Rotate the extension according the OBB ort
//And lastly store the result in graphics components as the model bounds used in culling
DirectX::XMStoreFloat3(&button1G->extensions, DirectX::XMVector3Transform(DirectX::XMVectorSet(button1P->PC_OBB.ext[0], button1P->PC_OBB.ext[1], button1P->PC_OBB.ext[2], 0.0f), button1P->PC_OBB.ort));
//Calculate the actual OBB extension
DirectX::XMVECTOR tempRot = DirectX::XMVector3Transform(DirectX::XMVECTOR{ button1P->PC_AABB.ext[0],
button1P->PC_AABB.ext[1] , button1P->PC_AABB.ext[2] }, rotate);
//Use the matrix that is used to rotate the extensions as the orientation for the OBB
button1P->PC_OBB.ort = rotate;
button1G->ort = button1P->PC_OBB.ort;
DirectX::XMStoreFloat3(&button1G->extensions, DirectX::XMVector3Transform(DirectX::XMVectorSet(button1P->PC_OBB.ext[0], button1P->PC_OBB.ext[1], button1P->PC_OBB.ext[2], 0.0f), button1P->PC_OBB.ort));
button1P->PC_AABB.ext[0] = abs(tempRot.m128_f32[0]);
button1P->PC_AABB.ext[1] = abs(tempRot.m128_f32[1]);
button1P->PC_AABB.ext[2] = abs(tempRot.m128_f32[2]);
tempEntity->Initialize(tempHeader.EntityID, button1P, button1G, tempHeader.interactionDistance + 2.0f, tempHeader.resetTime);
this->m_buttonEntities.push_back(tempEntity);
}
//Create the levers
for (size_t i = 0; i < data->numLever; i++)
{
LevelData::LeverHeader tempHeader = data->levers[i];
tempHeader.EntityID += DEFINED_IDS::NUMMBER_OF_IDS; //Add nummber of predefined ids to avoid conflict from editor
LeverEntity* tempEntity = new LeverEntity();
//Create world matrix from data
memcpy(pos.m128_f32, tempHeader.position, sizeof(float) * 3); //Convert from POD to DirectX Vector
memcpy(rot.m128_f32, tempHeader.rotation, sizeof(float) * 3); //Convert from POD to DirectX Vector
//Convert the useless values into proper system supported radians. Glorious.
rot = DirectX::XMVectorSet(DirectX::XMConvertToRadians(DirectX::XMVectorGetX(rot)), DirectX::XMConvertToRadians(DirectX::XMVectorGetY(rot)), DirectX::XMConvertToRadians(DirectX::XMVectorGetZ(rot)), 1.0f);
translate = DirectX::XMMatrixTranslationFromVector(pos);
DirectX::XMMATRIX rotationMatrixY = DirectX::XMMatrixRotationY(rot.m128_f32[1]);
DirectX::XMMATRIX rotationMatrixX = DirectX::XMMatrixRotationX(rot.m128_f32[0]);
DirectX::XMMATRIX rotationMatrixZ = DirectX::XMMatrixRotationZ(rot.m128_f32[2]);
//Should just use this function instead of a bunch
//DirectX::waa(rot);
//Create the rotation matrix
DirectX::XMMATRIX rotate = DirectX::XMMatrixMultiply(rotationMatrixZ, rotationMatrixX);
rotate = DirectX::XMMatrixMultiply(rotate, rotationMatrixY);
//rotate = DirectX::XMMatrixRotationRollPitchYawFromVector(rot);
GraphicsComponent* lever1G = m_cHandler->GetDynamicGraphicsComponent();
lever1G->active = true;
lever1G->modelID = tempHeader.modelID;
lever1G->worldMatrix = DirectX::XMMatrixMultiply(rotate, translate);
resHandler->GetModel(lever1G->modelID, lever1G->modelPtr);
PhysicsComponent* lever1P = m_cHandler->GetPhysicsComponent();
lever1P->PC_entityID = tempHeader.EntityID; //Set Entity ID
lever1P->PC_pos = pos; //Set Position
lever1P->PC_rotation = rot; //Set Rotation
lever1P->PC_is_Static = true; //Set IsStatic
lever1P->PC_active = true; //Set Active
lever1P->PC_gravityInfluence = 1.0f;
lever1P->PC_mass = 0;
lever1P->PC_friction = 0.00f;
lever1P->PC_collides = true;
lever1P->PC_elasticity = 0.2f;
lever1P->PC_steadfast = true;
//DirectX::XMQuaternionRotationMatrix
//Copy the bounding volume data from the model into the physics component for reference
lever1P->PC_AABB.ext[0] = lever1G->modelPtr->GetOBBData().extension[0];
lever1P->PC_AABB.ext[1] = lever1G->modelPtr->GetOBBData().extension[1];
lever1P->PC_AABB.ext[2] = lever1G->modelPtr->GetOBBData().extension[2];
lever1P->PC_OBB.ext[0] = lever1P->PC_AABB.ext[0] * 2.0f;
lever1P->PC_OBB.ext[1] = lever1P->PC_AABB.ext[1] * 2.0f;
lever1P->PC_OBB.ext[2] = lever1P->PC_AABB.ext[2] * 2.0f;
lever1P->PC_BVtype = BV_OBB;
//Calculate the actual OBB extension
DirectX::XMVECTOR tempRot = DirectX::XMVector3Transform(DirectX::XMVECTOR{ lever1P->PC_AABB.ext[0],
lever1P->PC_AABB.ext[1] , lever1P->PC_AABB.ext[2] }, rotate);
//Use the matrix that is used to rotate the extensions as the orientation for the OBB
lever1P->PC_OBB.ort = rotate;
lever1P->PC_AABB.ext[0] = abs(tempRot.m128_f32[0]);
lever1P->PC_AABB.ext[1] = abs(tempRot.m128_f32[1]);
lever1P->PC_AABB.ext[2] = abs(tempRot.m128_f32[2]);
tempEntity->Initialize(tempHeader.EntityID, lever1P, lever1G, tempHeader.interactionDistance);
this->m_leverEntities.push_back(tempEntity);
}
//Create the Wheels
for (size_t i = 0; i < data->numWheel; i++)
{
LevelData::WheelHeader tempHeader = data->wheels[i];
tempHeader.EntityID += DEFINED_IDS::NUMMBER_OF_IDS; //Add nummber of predefined ids to avoid conflict from editor
WheelEntity* tempEntity = new WheelEntity();
//Create world matrix from data
memcpy(pos.m128_f32, tempHeader.position, sizeof(float) * 3); //Convert from POD to DirectX Vector
memcpy(rot.m128_f32, tempHeader.rotation, sizeof(float) * 3); //Convert from POD to DirectX Vector
//Convert the useless values into proper system supported radians. Glorious.
rot = DirectX::XMVectorSet(DirectX::XMConvertToRadians(DirectX::XMVectorGetX(rot)), DirectX::XMConvertToRadians(DirectX::XMVectorGetY(rot)), DirectX::XMConvertToRadians(DirectX::XMVectorGetZ(rot)), 1.0f);
translate = DirectX::XMMatrixTranslationFromVector(pos);
DirectX::XMMATRIX rotationMatrixY = DirectX::XMMatrixRotationY(rot.m128_f32[1]);
DirectX::XMMATRIX rotationMatrixX = DirectX::XMMatrixRotationX(rot.m128_f32[0]);
DirectX::XMMATRIX rotationMatrixZ = DirectX::XMMatrixRotationZ(rot.m128_f32[2]);
//Should just use this function instead of a bunch
//DirectX::waa(rot);
//Create the rotation matrix
DirectX::XMMATRIX rotate = DirectX::XMMatrixMultiply(rotationMatrixZ, rotationMatrixX);
rotate = DirectX::XMMatrixMultiply(rotate, rotationMatrixY);
//rotate = DirectX::XMMatrixRotationRollPitchYawFromVector(rot);
GraphicsComponent* wheel1G = m_cHandler->GetDynamicGraphicsComponent();
wheel1G->active = true;
wheel1G->modelID = tempHeader.modelID;
wheel1G->worldMatrix = DirectX::XMMatrixMultiply(rotate, translate);
resHandler->GetModel(wheel1G->modelID, wheel1G->modelPtr);
PhysicsComponent* wheel1P = m_cHandler->GetPhysicsComponent();
wheel1P->PC_entityID = tempHeader.EntityID; //Set Entity ID
wheel1P->PC_pos = pos; //Set Position
wheel1P->PC_rotation = rot; //Set Rotation
wheel1P->PC_is_Static = true; //Set IsStatic
wheel1P->PC_active = true; //Set Active
wheel1P->PC_gravityInfluence = 1.0f;
wheel1P->PC_mass = 0;
wheel1P->PC_friction = 0.00f;
wheel1P->PC_collides = true;
wheel1P->PC_elasticity = 0.2f;
wheel1P->PC_steadfast = true;
//DirectX::XMQuaternionRotationMatrix
//Copy the bounding volume data from the model into the physics component for reference
//wheel1P->PC_AABB.ext[0] = wheel1G->modelPtr->GetOBBData().extension[0];
//wheel1P->PC_AABB.ext[1] = wheel1G->modelPtr->GetOBBData().extension[1];
//wheel1P->PC_AABB.ext[2] = wheel1G->modelPtr->GetOBBData().extension[2];
//wheel1P->PC_OBB.ext[0] = wheel1P->PC_AABB.ext[0];
//wheel1P->PC_OBB.ext[1] = wheel1P->PC_AABB.ext[1];
//wheel1P->PC_OBB.ext[2] = wheel1P->PC_AABB.ext[2];
wheel1P->PC_BVtype = BV_OBB;
//Copy the bounding volume data from the model into the physics component for reference
wheel1P->PC_OBB = m_ConvertOBB(wheel1G->modelPtr->GetOBBData()); //Convert and insert OBB data
wheel1P->PC_AABB.ext[0] = wheel1G->modelPtr->GetOBBData().extension[0];
wheel1P->PC_AABB.ext[1] = wheel1G->modelPtr->GetOBBData().extension[1];
wheel1P->PC_AABB.ext[2] = wheel1G->modelPtr->GetOBBData().extension[2];
wheel1P->PC_OBB.ext[0] = wheel1P->PC_AABB.ext[0] + 0.5f ;
wheel1P->PC_OBB.ext[1] = wheel1P->PC_AABB.ext[1];
wheel1P->PC_OBB.ext[2] = wheel1P->PC_AABB.ext[2];
DirectX::XMMATRIX tempOBBPos = DirectX::XMMatrixTranslationFromVector(DirectX::XMVECTOR{ wheel1G->modelPtr->GetOBBData().position.x, wheel1G->modelPtr->GetOBBData().position.y, wheel1G->modelPtr->GetOBBData().position.z });
tempOBBPos = DirectX::XMMatrixMultiply(tempOBBPos, wheel1G->worldMatrix);
wheel1P->PC_pos = tempOBBPos.r[3];
DirectX::XMStoreFloat3(&wheel1G->pos, tempOBBPos.r[3]);
wheel1P->PC_OBB.ort = DirectX::XMMatrixMultiply(wheel1P->PC_OBB.ort, rotate);
wheel1P->PC_OBB.ort = DirectX::XMMatrixTranspose(wheel1P->PC_OBB.ort);
//Calculate the actual OBB extension
DirectX::XMVECTOR tempRot = DirectX::XMVector3Transform(DirectX::XMVECTOR{ wheel1P->PC_AABB.ext[0],
wheel1P->PC_AABB.ext[1] , wheel1P->PC_AABB.ext[2] }, rotate);
//Use the matrix that is used to rotate the extensions as the orientation for the OBB
wheel1P->PC_OBB.ort = rotate;
wheel1P->PC_AABB.ext[0] = abs(tempRot.m128_f32[0]);
wheel1P->PC_AABB.ext[1] = abs(tempRot.m128_f32[1]);
wheel1P->PC_AABB.ext[2] = abs(tempRot.m128_f32[2]);
tempEntity->Initialize(tempHeader.EntityID, wheel1P, wheel1G, tempHeader.interactionDistance, tempHeader.min, tempHeader.max, tempHeader.time, tempHeader.resetTime > 0.0f, tempHeader.resetTime, tempHeader.resetDelay);
this->m_wheelEntities.push_back(tempEntity);
}
//Create the doors
for (size_t i = 0; i < data->numDoor; i++)
{
LevelData::DoorHeader tempHeader = data->doors[i];
tempHeader.EntityID += DEFINED_IDS::NUMMBER_OF_IDS; //Add nummber of predefined ids to avoid conflict from editor
DoorEntity* tempEntity = new DoorEntity();
//Create world matrix from data
memcpy(pos.m128_f32, tempHeader.position, sizeof(float) * 3); //Convert from POD to DirectX Vector
memcpy(rot.m128_f32, tempHeader.rotation, sizeof(float) * 3); //Convert from POD to DirectX Vector
//Convert the useless values into proper system supported radians. Glorious.
//Convert the useless values into proper system supported radians. Glorious.
rot = DirectX::XMVectorSet(DirectX::XMConvertToRadians(DirectX::XMVectorGetX(rot)), DirectX::XMConvertToRadians(DirectX::XMVectorGetY(rot)), DirectX::XMConvertToRadians(DirectX::XMVectorGetZ(rot)), 1.0f);
translate = DirectX::XMMatrixTranslationFromVector(pos);
/*DirectX::XMMATRIX rotationMatrixY = DirectX::XMMatrixRotationY(rot.m128_f32[1]);
DirectX::XMMATRIX rotationMatrixX = DirectX::XMMatrixRotationX(rot.m128_f32[0]);
DirectX::XMMATRIX rotationMatrixZ = DirectX::XMMatrixRotationZ(rot.m128_f32[2]);*/
//Should just use this function instead of a bunch
//Create the rotation matrix
/*DirectX::XMMATRIX rotate = DirectX::XMMatrixMultiply(rotationMatrixZ, rotationMatrixX);
rotate = DirectX::XMMatrixMultiply(rotate, rotationMatrixY);*/
rotate = DirectX::XMMatrixRotationRollPitchYawFromVector(DirectX::XMVectorSet(DirectX::XMVectorGetX(rot), DirectX::XMVectorGetY(rot), DirectX::XMVectorGetZ(rot), 1.0f));
//rotate = DirectX::XMMatrixRotationRollPitchYawFromVector(rot);
GraphicsComponent* door1G = m_cHandler->GetDynamicGraphicsComponent();
door1G->active = true;
door1G->modelID = tempHeader.modelID;
door1G->worldMatrix = DirectX::XMMatrixMultiply(rotate, translate);
resHandler->GetModel(door1G->modelID, door1G->modelPtr);
PhysicsComponent* door1P = m_cHandler->GetPhysicsComponent();
door1P->PC_entityID = tempHeader.EntityID; //Set Entity ID
door1P->PC_pos = pos; //Set Position
door1P->PC_rotation = rot; //Set Rotation
door1P->PC_is_Static = false; //Set IsStatic
door1P->PC_active = true; //Set Active
door1P->PC_gravityInfluence = 1.0f;
door1P->PC_mass = 0;
door1P->PC_friction = 0.00f;
door1P->PC_collides = true;
door1P->PC_elasticity = 0.2f;
door1P->PC_steadfast = true;
//DirectX::XMQuaternionRotationMatrix
//Copy the bounding volume data from the model into the physics component for reference
door1P->PC_AABB.ext[0] = door1G->modelPtr->GetOBBData().extension[0];
door1P->PC_AABB.ext[1] = door1G->modelPtr->GetOBBData().extension[1];
door1P->PC_AABB.ext[2] = door1G->modelPtr->GetOBBData().extension[2];
door1P->PC_OBB.ext[0] = door1P->PC_AABB.ext[0];
door1P->PC_OBB.ext[1] = door1P->PC_AABB.ext[1];
door1P->PC_OBB.ext[2] = door1P->PC_AABB.ext[2];
door1P->PC_BVtype = BV_OBB;
Resources::Model* modelPtr = nullptr;
modelPtr = door1G->modelPtr;
DirectX::XMMATRIX tempOBBPos = DirectX::XMMatrixTranslationFromVector(DirectX::XMVECTOR{ modelPtr->GetOBBData().position.x, modelPtr->GetOBBData().position.y
, modelPtr->GetOBBData().position.z });
tempOBBPos = DirectX::XMMatrixMultiply(tempOBBPos, door1G->worldMatrix);
door1P->PC_pos = tempOBBPos.r[3];
door1P->PC_OBB.ort = rotate;
std::vector<ElementState> subjectStates;
tempEntity->Initialize(tempHeader.EntityID, door1P, door1G, subjectStates, tempHeader.rotateTime);
this->m_doorEntities.push_back(tempEntity);
}
#pragma endregion Create puzzle entities
//Connect puzzle entities
#pragma region
//Connect Platforms to other things
for (size_t i = 0; i < data->numAI; i++)
{
//LevelData::AiHeader tempHeader = data->aiComponents[i];
PlatformEntity* toConnect = nullptr;
//Find our platform and save it to our pointer(toConnect)
for (std::vector<PlatformEntity*>::iterator observer = this->m_platformEntities.begin(); observer != this->m_platformEntities.end() && toConnect == nullptr; observer++)
{
//Add nummber of predefined ids to avoid conflict from editor
if ((*observer)->GetEntityID() == (data->aiComponents[i].EntityID + DEFINED_IDS::NUMMBER_OF_IDS))
{
toConnect = (*observer);
}
}
//Find our connections
for (int connectionIndex = 0; connectionIndex < data->aiComponents[i].Listener.numConnections; connectionIndex++)
{
//Get the ID
//Add nummber of predefined ids to avoid conflict from editor
unsigned int connectionID = data->aiComponents[i].Listener.SenderID[connectionIndex] + DEFINED_IDS::NUMMBER_OF_IDS;
//Cycle through every puzzle element list until you find the connection ID
Entity* entityToObserve = nullptr;
bool foundConnection = false;
for (std::vector<ButtonEntity*>::iterator other = this->m_buttonEntities.begin(); other != this->m_buttonEntities.end() && !foundConnection; other++)
{
if ((*other)->GetEntityID() == connectionID)
{
entityToObserve = (*other);
entityToObserve->AddObserver(toConnect, toConnect->GetEntityID());
foundConnection = true;
toConnect->GetAIComponent()->AC_triggered = false;// temp - have to test the platforms to make this right
}
}
for (std::vector<LeverEntity*>::iterator other = this->m_leverEntities.begin(); other != this->m_leverEntities.end() && !foundConnection; other++)
{
if ((*other)->GetEntityID() == connectionID)
{
entityToObserve = (*other);
entityToObserve->AddObserver(toConnect, toConnect->GetEntityID());
foundConnection = true;
toConnect->GetAIComponent()->AC_triggered = false;// temp
}
}
for (std::vector<WheelEntity*>::iterator other = this->m_wheelEntities.begin(); other != this->m_wheelEntities.end() && !foundConnection; other++)
{
if ((*other)->GetEntityID() == connectionID)
{
entityToObserve = (*other);
entityToObserve->AddObserver(toConnect, toConnect->GetEntityID());
foundConnection = true;
toConnect->GetAIComponent()->AC_triggered = false;// temp
}
}
for (std::vector<DoorEntity*>::iterator other = this->m_doorEntities.begin(); other != this->m_doorEntities.end() && !foundConnection; other++)
{
if ((*other)->GetEntityID() == connectionID)
{
entityToObserve = (*other);
entityToObserve->AddObserver(toConnect, toConnect->GetEntityID());
foundConnection = true;
toConnect->GetAIComponent()->AC_triggered = false;// temp
}
}
}
}
//Connect Doors to other things
for (size_t i = 0; i < data->numDoor; i++)
{
LevelData::DoorHeader tempHeader = data->doors[i];
tempHeader.EntityID += DEFINED_IDS::NUMMBER_OF_IDS;
DoorEntity* toConnect = nullptr;
//Find our door and save it in doorToConnect
for (std::vector<DoorEntity*>::iterator observer = this->m_doorEntities.begin(); observer != this->m_doorEntities.end() && toConnect == nullptr; observer++)
{
if ((*observer)->GetEntityID() == tempHeader.EntityID)
{
toConnect = (*observer);
}
}
//Find our connections
for (int connectionIndex = 0; connectionIndex < tempHeader.Listener.numConnections; connectionIndex++)
{
//Get the ID
unsigned int connectionID = tempHeader.Listener.SenderID[connectionIndex] + DEFINED_IDS::NUMMBER_OF_IDS;
//Cycle through every puzzle element list until you find the connection ID
Entity* entityToObserve = nullptr;
bool foundConnection = false;
for (std::vector<ButtonEntity*>::iterator other = this->m_buttonEntities.begin(); other != this->m_buttonEntities.end() && !foundConnection; other++)
{
if ((*other)->GetEntityID() == connectionID)
{
entityToObserve = (*other);
entityToObserve->AddObserver(toConnect, toConnect->GetEntityID());
foundConnection = true;
}
}
for (std::vector<LeverEntity*>::iterator other = this->m_leverEntities.begin(); other != this->m_leverEntities.end() && !foundConnection; other++)
{
if ((*other)->GetEntityID() == connectionID)
{
entityToObserve = (*other);
entityToObserve->AddObserver(toConnect, toConnect->GetEntityID());
foundConnection = true;
}
}
for (std::vector<WheelEntity*>::iterator other = this->m_wheelEntities.begin(); other != this->m_wheelEntities.end() && !foundConnection; other++)
{
if ((*other)->GetEntityID() == connectionID)
{
entityToObserve = (*other);
entityToObserve->AddObserver(toConnect, toConnect->GetEntityID());
foundConnection = true;
}
}
for (std::vector<DoorEntity*>::iterator other = this->m_doorEntities.begin(); other != this->m_doorEntities.end() && !foundConnection; other++)
{
if ((*other)->GetEntityID() == connectionID)
{
entityToObserve = (*other);
entityToObserve->AddObserver(toConnect, toConnect->GetEntityID());
foundConnection = true;
}
}
//If we found our connection, add it to the doors list
if (foundConnection)
{
toConnect->AddSubjectState(connectionID, EVENT(tempHeader.Listener.Event[connectionIndex]));
}
}
}
//Connect Buttons to other things
for (size_t i = 0; i < data->numButton; i++)
{
LevelData::ButtonHeader tempHeader = data->buttons[i];
tempHeader.EntityID += DEFINED_IDS::NUMMBER_OF_IDS;
ButtonEntity* toConnect = nullptr;
//Find our door and save it in doorToConnect
for (std::vector<ButtonEntity*>::iterator observer = this->m_buttonEntities.begin(); observer != this->m_buttonEntities.end() && toConnect == nullptr; observer++)
{
if ((*observer)->GetEntityID() == tempHeader.EntityID)
{
toConnect = (*observer);
}
}
//Find our connections
for (int connectionIndex = 0; connectionIndex < tempHeader.Listener.numConnections; connectionIndex++)
{
//Get the ID
unsigned int connectionID = tempHeader.Listener.SenderID[connectionIndex] + DEFINED_IDS::NUMMBER_OF_IDS;
//Cycle through every puzzle element list until you find the connection ID
Entity* entityToObserve = nullptr;
bool foundConnection = false;
for (std::vector<ButtonEntity*>::iterator other = this->m_buttonEntities.begin(); other != this->m_buttonEntities.end() && !foundConnection; other++)
{
if ((*other)->GetEntityID() == connectionID)
{
entityToObserve = (*other);
entityToObserve->AddObserver(toConnect, toConnect->GetEntityID());
foundConnection = true;
}
}
for (std::vector<LeverEntity*>::iterator other = this->m_leverEntities.begin(); other != this->m_leverEntities.end() && !foundConnection; other++)
{
if ((*other)->GetEntityID() == connectionID)
{
entityToObserve = (*other);
entityToObserve->AddObserver(toConnect, toConnect->GetEntityID());
foundConnection = true;
}
}
for (std::vector<WheelEntity*>::iterator other = this->m_wheelEntities.begin(); other != this->m_wheelEntities.end() && !foundConnection; other++)
{
if ((*other)->GetEntityID() == connectionID)
{
entityToObserve = (*other);
entityToObserve->AddObserver(toConnect, toConnect->GetEntityID());
foundConnection = true;
}
}
for (std::vector<DoorEntity*>::iterator other = this->m_doorEntities.begin(); other != this->m_doorEntities.end() && !foundConnection; other++)
{
if ((*other)->GetEntityID() == connectionID)
{
entityToObserve = (*other);
entityToObserve->AddObserver(toConnect, toConnect->GetEntityID());
foundConnection = true;
}
}
}
}
//Connect Levers to other things
for (size_t i = 0; i < data->numLever; i++)
{
LevelData::LeverHeader tempHeader = data->levers[i];
tempHeader.EntityID += DEFINED_IDS::NUMMBER_OF_IDS;
LeverEntity* toConnect = nullptr;
//Find our door and save it in doorToConnect
for (std::vector<LeverEntity*>::iterator observer = this->m_leverEntities.begin(); observer != this->m_leverEntities.end() && toConnect == nullptr; observer++)
{
if ((*observer)->GetEntityID() == tempHeader.EntityID)
{
toConnect = (*observer);
}
}
//Find our connections
for (int connectionIndex = 0; connectionIndex < tempHeader.Listener.numConnections; connectionIndex++)
{
//Get the ID
unsigned int connectionID = tempHeader.Listener.SenderID[connectionIndex] + DEFINED_IDS::NUMMBER_OF_IDS;
//Cycle through every puzzle element list until you find the connection ID
Entity* entityToObserve = nullptr;
bool foundConnection = false;
for (std::vector<ButtonEntity*>::iterator other = this->m_buttonEntities.begin(); other != this->m_buttonEntities.end() && !foundConnection; other++)
{
if ((*other)->GetEntityID() == connectionID)
{
entityToObserve = (*other);
entityToObserve->AddObserver(toConnect, toConnect->GetEntityID());
foundConnection = true;
}
}
for (std::vector<LeverEntity*>::iterator other = this->m_leverEntities.begin(); other != this->m_leverEntities.end() && !foundConnection; other++)
{
if ((*other)->GetEntityID() == connectionID)
{
entityToObserve = (*other);
entityToObserve->AddObserver(toConnect, toConnect->GetEntityID());
foundConnection = true;
}
}
for (std::vector<WheelEntity*>::iterator other = this->m_wheelEntities.begin(); other != this->m_wheelEntities.end() && !foundConnection; other++)
{
if ((*other)->GetEntityID() == connectionID)
{
entityToObserve = (*other);
entityToObserve->AddObserver(toConnect, toConnect->GetEntityID());
foundConnection = true;
}
}
for (std::vector<DoorEntity*>::iterator other = this->m_doorEntities.begin(); other != this->m_doorEntities.end() && !foundConnection; other++)
{
if ((*other)->GetEntityID() == connectionID)
{
entityToObserve = (*other);
entityToObserve->AddObserver(toConnect, toConnect->GetEntityID());
foundConnection = true;
}
}
}
}
//Connect Wheels to other things
for (size_t i = 0; i < data->numWheel; i++)
{
LevelData::WheelHeader tempHeader = data->wheels[i];
tempHeader.EntityID += DEFINED_IDS::NUMMBER_OF_IDS;
WheelEntity* toConnect = nullptr;
//Find our door and save it in doorToConnect
for (std::vector<WheelEntity*>::iterator observer = this->m_wheelEntities.begin(); observer != this->m_wheelEntities.end() && toConnect == nullptr; observer++)
{
if ((*observer)->GetEntityID() == tempHeader.EntityID)
{
toConnect = (*observer);
}
}
//Find our connections
for (int connectionIndex = 0; connectionIndex < tempHeader.Listener.numConnections; connectionIndex++)
{
//Get the ID
unsigned int connectionID = tempHeader.Listener.SenderID[connectionIndex] + DEFINED_IDS::NUMMBER_OF_IDS;
//Cycle through every puzzle element list until you find the connection ID
Entity* entityToObserve = nullptr;
bool foundConnection = false;
for (std::vector<ButtonEntity*>::iterator other = this->m_buttonEntities.begin(); other != this->m_buttonEntities.end() && !foundConnection; other++)
{
if ((*other)->GetEntityID() == connectionID)
{
entityToObserve = (*other);
entityToObserve->AddObserver(toConnect, toConnect->GetEntityID());
foundConnection = true;
}
}
for (std::vector<LeverEntity*>::iterator other = this->m_leverEntities.begin(); other != this->m_leverEntities.end() && !foundConnection; other++)
{
if ((*other)->GetEntityID() == connectionID)
{
entityToObserve = (*other);
entityToObserve->AddObserver(toConnect, toConnect->GetEntityID());
foundConnection = true;
}
}
for (std::vector<WheelEntity*>::iterator other = this->m_wheelEntities.begin(); other != this->m_wheelEntities.end() && !foundConnection; other++)
{
if ((*other)->GetEntityID() == connectionID)
{
entityToObserve = (*other);
entityToObserve->AddObserver(toConnect, toConnect->GetEntityID());
foundConnection = true;
}
}
for (std::vector<DoorEntity*>::iterator other = this->m_doorEntities.begin(); other != this->m_doorEntities.end() && !foundConnection; other++)
{
if ((*other)->GetEntityID() == connectionID)
{
entityToObserve = (*other);
entityToObserve->AddObserver(toConnect, toConnect->GetEntityID());
foundConnection = true;
}
}
}
}
#pragma endregion Connect puzzle entities
m_cHandler->GetPhysicsHandler()->SortComponents();
PhysicsHandler* ptr = nullptr;
ptr = m_cHandler->GetPhysicsHandler();
int size = m_cHandler->GetPhysicsHandler()->GetNrOfComponents();
int index = 0;
for (index; index < size; index++)
{
PhysicsComponent* t_pc = ptr->GetComponentAt(index);
ptr->TransferBoxesToBullet(t_pc, index);
}
//this->m_cHandler->GetPhysicsHandler()->SetIgnoreCollisions();
//this->m_cHandler->GetPhysicsHandler()->GetBulletInterpreterRef()->SetIgnoreCollisions(this->m_player1.GetPhysicsComponent(), this->m_player2.GetBall()->GetPhysicsComponent());
//this->m_cHandler->GetPhysicsHandler()->GetBulletInterpreterRef()->SetIgnoreCollisions(this->m_player2.GetPhysicsComponent(), this->m_player1.GetBall()->GetPhysicsComponent());
//Before generating the Octree, syn the physics data with the graphics data
#pragma region
//
//#pragma region
// for (ButtonEntity* i : this->m_buttonEntities)
// {
// i->SyncComponents();
// }
// for (WheelEntity* i : this->m_wheelEntities)
// {
// i->SyncComponents();
// }
// for (LeverEntity* i : this->m_leverEntities)
// {
// i->SyncComponents();
// }
//#pragma endregion puzzle
//
//#pragma region
m_cHandler->GetGraphicsHandler()->GenerateOctree();
//for (Entity* i : this->m_staticEntitys)
//{
// i->SyncComponents();
//}
//#pragma endregion static
//
#pragma endregion Sync components
#ifdef _DEBUG
//This keeps track of any resource lib access outside of level loading.
Resources::ResourceHandler::GetInstance()->ResetQueryCounter();
#endif // _DEBUG
m_cHandler->GetGraphicsHandler()->GenerateStaticSceneShadows();
#pragma region
DirectX::XMVECTOR cubePos;
switch (m_curLevel)
{
case 0: //Tutorial
cubePos = DirectX::XMVectorSet(0.0f, 2.0f, -19.0f, 1.0f);
break;
case 1:
cubePos = DirectX::XMVectorSet(8.0f, 4.0f, -2.0f, 1.0f);
break;
case 2:
cubePos = DirectX::XMVectorSet(6.0f, 3.0f, -67.0f, 1.0f);
break;
case 3:
cubePos = DirectX::XMVectorSet(0.0f, 2.0f, 2.0f, 1.0f);
break;
case 4:
cubePos = DirectX::XMVectorSet(-11.0f, 3.0f, -12.0f, 1.0f);
break;
case 5:
cubePos = DirectX::XMVectorSet(20.0f, 2.0f, 12.0f, 1.0f);
break;
case 6:
cubePos = DirectX::XMVectorSet(15.0f, 5.0f, -19.0f, 1.0f);
break;
case 7:
cubePos = DirectX::XMVectorSet(0.0f, 2.0f, -19.0f, 1.0f);
break;
default:
cubePos = DirectX::XMVectorSet(0.0f, 2.0f, -19.0f, 1.0f);
break;
}
#pragma endregion Get cube map pos
m_cHandler->GetGraphicsHandler()->GenerateSceneCubeMap(cubePos);
return 1;
}
int LevelState::UnloadLevel()
{
int result = 0;
//Clear grabbing of balls
this->m_player1.SetGrabbed(nullptr);
this->m_networkModule->SendGrabPacket(this->m_player1.GetEntityID(), -1);
//Clear components from GraphicsHandler.
this->m_cHandler->ResizeGraphicsDynamic(0);
this->m_cHandler->ResizeGraphicsStatic(0);
//Clear internal lists
#pragma region
for (size_t i = 0; i < this->m_staticEntitys.size(); i++)
{
delete this->m_staticEntitys[i];
this->m_staticEntitys[i] = nullptr;
}
this->m_staticEntitys.clear();
//Clear the puzzle entities
for (size_t i = 0; i < this->m_doorEntities.size(); i++)
{
delete this->m_doorEntities[i];
this->m_doorEntities[i] = nullptr;
}
this->m_doorEntities.clear();
for (size_t i = 0; i < this->m_buttonEntities.size(); i++)
{
delete this->m_buttonEntities[i];
this->m_buttonEntities[i] = nullptr;
}
this->m_buttonEntities.clear();
for (size_t i = 0; i < this->m_leverEntities.size(); i++)
{
delete this->m_leverEntities[i];
this->m_leverEntities[i] = nullptr;
}
this->m_leverEntities.clear();
for (size_t i = 0; i < this->m_wheelEntities.size(); i++)
{
delete this->m_wheelEntities[i];
this->m_wheelEntities[i] = nullptr;
}
this->m_wheelEntities.clear();
for (size_t i = 0; i < this->m_fieldEntities.size(); i++)
{
delete this->m_fieldEntities[i];
this->m_fieldEntities[i] = nullptr;
}
this->m_fieldEntities.clear();
for (size_t i = 0; i < this->m_platformEntities.size(); i++)
{
delete this->m_platformEntities[i];
this->m_platformEntities[i] = nullptr;
}
this->m_platformEntities.clear();
#pragma endregion Clear entity lists
//In order to correctly load the components into the physics handler we need to flush the old ones because the Active variable doesn't work according to Axel.
//Shutdown PhysicsHandler and initialize it again.
#pragma region
PhysicsHandler* pHandler = this->m_cHandler->GetPhysicsHandler();
pHandler->ClearPhysicsHandler();
#pragma endregion Physics handler restart
this->m_director.Initialize();
#pragma region
#pragma region
//We then need to recreate the persistent components here
PhysicsComponent* playerP = m_cHandler->GetPhysicsComponent();
playerP->PC_entityID = DEFINED_IDS::PLAYER_1; //Set Entity ID
playerP->PC_pos = DirectX::XMVectorSet(0, 2, 0, 0); //Set Position (Will be set in createLevel)
playerP->PC_rotation = DirectX::XMVectorSet(0, 0, 0, 0); //Set Rotation
playerP->PC_is_Static = false; //Set IsStatic
playerP->PC_mass = 10;
playerP->PC_BVtype = BV_OBB;
//Should be done
/*playerP->PC_OBB.ext[0] = playerG->modelPtr->GetOBBData().extension[0];
playerP->PC_OBB.ext[1] = playerG->modelPtr->GetOBBData().extension[1];
playerP->PC_OBB.ext[2] = playerG->modelPtr->GetOBBData().extension[2];*/
playerP->PC_OBB.ext[0] = this->m_player1.GetGraphicComponent()->modelPtr->GetOBBData().extension[0];
playerP->PC_OBB.ext[1] = this->m_player1.GetGraphicComponent()->modelPtr->GetOBBData().extension[1];
playerP->PC_OBB.ext[2] = this->m_player1.GetGraphicComponent()->modelPtr->GetOBBData().extension[2];
playerP->PC_velocity = DirectX::XMVectorSet(0, 0, 0, 0);
playerP->PC_friction = 1.0f;
this->m_player1.SetPhysicsComponent(playerP);
//reset player1 animation component to idle animation
this->m_player1.GetAnimationComponent()->previousState = this->m_player1.GetAnimationComponent()->currentState;
this->m_player1.SetAnimationComponent(PLAYER_IDLE, 0.50f, Blending::SMOOTH_TRANSITION, true, false, 1.0f, 1.0f);
this->m_player1.GetAnimationComponent()->currentState = PLAYER_IDLE;
#pragma endregion Player 1
#pragma region
//We then need to recreate the persistent components here
playerP = m_cHandler->GetPhysicsComponent();
playerP->PC_entityID = DEFINED_IDS::PLAYER_2; //Set Entity ID
playerP->PC_pos = DirectX::XMVectorSet(0, 2, 0, 0); //Set Position (Will be set in createLevel)
playerP->PC_rotation = DirectX::XMVectorSet(0, 0, 0, 0); //Set Rotation
playerP->PC_is_Static = false; //Set IsStatic
playerP->PC_mass = 10;
playerP->PC_BVtype = BV_OBB;
//Should be done
/*playerP->PC_OBB.ext[0] = playerG->modelPtr->GetOBBData().extension[0];
playerP->PC_OBB.ext[1] = playerG->modelPtr->GetOBBData().extension[1];
playerP->PC_OBB.ext[2] = playerG->modelPtr->GetOBBData().extension[2];*/
playerP->PC_OBB.ext[0] = this->m_player2.GetGraphicComponent()->modelPtr->GetOBBData().extension[0];
playerP->PC_OBB.ext[1] = this->m_player2.GetGraphicComponent()->modelPtr->GetOBBData().extension[1];
playerP->PC_OBB.ext[2] = this->m_player2.GetGraphicComponent()->modelPtr->GetOBBData().extension[2];
playerP->PC_velocity = DirectX::XMVectorSet(0, 0, 0, 0);
playerP->PC_friction = 1.0f;
this->m_player2.SetPhysicsComponent(playerP);
//reset player2 animation component to idle animation
this->m_player2.GetAnimationComponent()->previousState = this->m_player2.GetAnimationComponent()->currentState;
this->m_player2.SetAnimationComponent(PLAYER_IDLE, 0.50f, Blending::SMOOTH_TRANSITION, true, false, 1.0f, 1.0f);
this->m_player2.GetAnimationComponent()->currentState = PLAYER_IDLE;
#pragma endregion Player 2
#pragma region
PhysicsComponent* ballP = m_cHandler->GetPhysicsComponent();
ballP->PC_entityID = DEFINED_IDS::BALL_1; //Set Entity ID
ballP->PC_pos = { 0 }; //Set Position
ballP->PC_rotation = DirectX::XMVectorSet(0, 0, 0, 0); //Set Rotation
ballP->PC_rotationVelocity = DirectX::XMVectorSet(0, 0, 0, 0);
ballP->PC_is_Static = false; //Set IsStatic
ballP->PC_active = true; //Set Active
ballP->PC_BVtype = BV_Sphere;
ballP->PC_velocity = DirectX::XMVectorSet(0, 0, 0, 0);
ballP->PC_OBB.ext[0] = 0.5f;
ballP->PC_OBB.ext[1] = 0.5f;
ballP->PC_OBB.ext[2] = 0.5f;
ballP->PC_Sphere.radius = 0.25;
ballP->PC_mass = 50;
//We do not know the position of the ball in our dynamic components list. We need to flush this list too btw.
this->m_player1.GetBall()->SetPhysicsComponent(ballP);
#pragma endregion ball1
#pragma region
ballP = m_cHandler->GetPhysicsComponent();
ballP->PC_entityID = DEFINED_IDS::BALL_2; //Set Entity ID
ballP->PC_pos = { 0 }; //Set Position
ballP->PC_rotation = DirectX::XMVectorSet(0, 0, 0, 0); //Set Rotation
ballP->PC_is_Static = false; //Set IsStatic
ballP->PC_active = true; //Set Active
ballP->PC_BVtype = BV_Sphere;
ballP->PC_Sphere.radius = 0.25;
ballP->PC_OBB.ext[0] = 0.5f;
ballP->PC_OBB.ext[1] = 0.5f;
ballP->PC_OBB.ext[2] = 0.5f;
ballP->PC_mass = 50;
//We do not know the position of the ball in our dynamic components list. We need to flush this list too btw.
this->m_player2.GetBall()->SetPhysicsComponent(ballP);
#pragma endregion ball2
#pragma endregion
//We have a special case with the dynamic entities, save the balls and Re-insert them into the dynamic list
DynamicEntity* ball1 = nullptr;
DynamicEntity* ball2 = nullptr;
ball1 = static_cast<DynamicEntity*>(this->m_player1.GetBall());
ball1->SyncComponents();
ball2 = static_cast<DynamicEntity*>(this->m_player2.GetBall());
ball2->SyncComponents();
//Sync components to make sure the values in the graphics components are somewhat sane
// Clear the dynamic entities. Don't delete the balls
for (size_t i = 0; i < this->m_dynamicEntitys.size(); i++)
{
if (this->m_dynamicEntitys[i] != ball1 && this->m_dynamicEntitys[i] != ball2)
{
delete this->m_dynamicEntitys[i];
this->m_dynamicEntitys[i] = nullptr;
}
}
this->m_dynamicEntitys.clear();
//Re-introduce them into our dynamic list
this->m_dynamicEntitys.push_back(ball1);
this->m_dynamicEntitys.push_back(ball2);
this->m_Player1ChainPhysicsComp.clear();
this->m_Player2ChainPhysicsComp.clear();
Resources::ResourceHandler::GetInstance()->UnloadCurrentLevel();
return 1;
}
int LevelState::LoadNext()
{
int result = 0;
//Increase the level count and reset the cleared level flag
this->m_curLevel++;
this->m_clearedLevel = 0;
if (this->m_curLevel >= this->m_levelPaths.size())
{
//If the code comes here it means that the user finished the last level
//Behavior will be to start the first level
//Next behavior is to pop ourselves and go back to the menu
//The last behavior is to pop ourselves and push a Credit state
this->m_curLevel = 0;
this->m_networkModule->SendFlagPacket(PacketTypes::DISCONNECT_REQUEST);
this->m_cHandler->RemoveLastUIComponent();
this->m_cHandler->RemoveLastUIComponent();
this->m_gsh->PopStateFromStack();
CreditState* creditState = new CreditState();
int result = creditState->Initialize(this->m_gsh, this->m_cHandler, this->m_cameraRef);
if (result > 0)
{
this->m_gsh->PushStateToStack(creditState);
}
else
{
delete creditState;
creditState = nullptr;
}
}
else
{
Resources::Status st = Resources::Status::ST_OK;
std::string path = this->m_levelPaths.at(this->m_curLevel).levelPath;
//We also need to clear the internal lists, lets have another function do that
this->UnloadLevel();
LevelData::Level* level; //pointer for resourcehandler data. This data is actually stored in the file loader so don't delete it.
path = this->m_levelPaths.at(this->m_curLevel).levelPath;
//Begin by clearing the current level data by calling UnloadLevel.
//Cheat and use the singletons for ResourceHandler, FileLoader, LightHandler
#pragma region
printf("LOAD LEVEL %d\n", this->m_curLevel);
//Load LevelData from file
st = Resources::FileLoader::GetInstance()->LoadLevel(path, level);
//if not successful
if (st != Resources::ST_OK)
{
//Error loading file.
printf("ERROR message: %s - Error occcured: %s!", "Failed loading file!", "In LevelState::LoadNext()");
return -1;
}
//Load Resources of the level
st = Resources::ResourceHandler::GetInstance()->LoadLevel(level->resources, level->numResources);
//if not successful
if (st != Resources::ST_OK)
{
//Error loading level from resource handler.
printf("ERROR message: %s - Error occcured: %s!", "Failed loading level!", "In LevelState::LoadNext()");
return -2;
}
//Load Lights of the level
if (!LIGHTING::LightHandler::GetInstance()->LoadLevelLight(level))
{
//Error loading lights through LightHandler.
printf("ERROR message: %s - Error occcured: %s!", "Failed loading lights!", "In LevelState::LoadNext()");
return -3;
}
#pragma endregion Loading data
#pragma region
DirectX::XMVECTOR targetOffset = DirectX::XMVectorSet(0.0f, 1.4f, 0.0f, 0.0f);
m_cameraRef->SetCameraPivot(
&this->m_cHandler->GetPhysicsHandler()->GetComponentAt(0)->PC_pos,
targetOffset,
1.3f
);
#pragma endregion Set_Camera
//Call the CreateLevel with the level data.
result = this->CreateLevel(level);
}
return 1;
}
int LevelState::GetLevelIndex()
{
return this->m_curLevel;
}
std::string LevelState::GetLevelPath()
{
return this->m_levelPaths.at(min(this->m_levelPaths.size() - 1, this->m_curLevel)).levelPath;
}
void LevelState::SetCurrentLevelID(int currentLevelID)
{
this->m_curLevel = min(currentLevelID, int(this->m_levelPaths.size() - 1));
}
int LevelState::EnterState()
{
return 0;
}
int LevelState::LeaveState()
{
this->m_networkModule->SendFlagPacket(PacketTypes::DISCONNECT_REQUEST);
return 0;
}
void LevelState::UpdateGraphicalLinks()
{
DirectX::XMVECTOR temp = DirectX::XMLoadFloat3(&DirectX::XMFLOAT3(0, 3, 0));
GraphicalLink* lastComp = nullptr;
DirectX::XMVECTOR lastPos;
DirectX::XMVECTOR diffVec;
DirectX::XMVECTOR par; // ony used for storing uneeded value
DirectX::XMVECTOR per;
for (size_t i = 0; i < this->m_grapichalLinkListPlayer1.size(); i++)
{
float t = (float)i / (float)this->m_grapichalLinkListPlayer1.size();
DirectX::XMVECTOR pos = this->GetInterpolatedSplinePoint(t, &this->m_Player1ChainPhysicsComp);
//Set rot before setting pos
this->m_grapichalLinkListPlayer1.at(i).SetPos(pos);
if (i != 0 && i < this->m_grapichalLinkListPlayer1.size())
{
lastComp = &this->m_grapichalLinkListPlayer1.at(i - 1);
lastPos = DirectX::XMLoadFloat3(&lastComp->m_pos);
diffVec = DirectX::XMVector3Normalize(DirectX::XMVectorSubtract(pos, lastPos)); //Towards current
lastComp->m_rotMat.r[0] = DirectX::XMVectorSetW(diffVec, 0.0f);
DirectX::XMVector3ComponentsFromNormal(&par, &per, lastComp->m_rotMat.r[2], diffVec);
per = DirectX::XMVector3Normalize(per);
lastComp->m_rotMat.r[2] = DirectX::XMVectorSetW(per, 0.0f);
lastComp->m_rotMat.r[1] = DirectX::XMVectorSetW(DirectX::XMVector3Cross(diffVec, per), 0.0f);
}
}
for (size_t i = 0; i < this->m_grapichalLinkListPlayer2.size(); i++)
{
float t = (float)i / (float)this->m_grapichalLinkListPlayer2.size();
DirectX::XMVECTOR pos = this->GetInterpolatedSplinePoint(t, &this->m_Player2ChainPhysicsComp);
this->m_grapichalLinkListPlayer2.at(i).SetPos(pos);
if (i != 0 && i < this->m_grapichalLinkListPlayer2.size())
{
lastComp = &this->m_grapichalLinkListPlayer2.at(i - 1);
lastPos = DirectX::XMLoadFloat3(&lastComp->m_pos);
diffVec = DirectX::XMVector3Normalize(DirectX::XMVectorSubtract(pos, lastPos)); //Towards current
lastComp->m_rotMat.r[0] = DirectX::XMVectorSetW(diffVec, 0.0f);
DirectX::XMVector3ComponentsFromNormal(&par, &per, lastComp->m_rotMat.r[1], diffVec);
per = DirectX::XMVector3Normalize(per);
lastComp->m_rotMat.r[1] = DirectX::XMVectorSetW(per, 0.0f);
lastComp->m_rotMat.r[2] = DirectX::XMVectorSetW(DirectX::XMVector3Cross(diffVec, per), 0.0f);
}
}
}
DirectX::XMVECTOR LevelState::GetInterpolatedSplinePoint(float t, std::vector<PhysicsComponent*>*list)
{
this->delta_t = 1.f / (float)list->size();
int p = int((t / this->delta_t));
#define BOUNDS(pp){ if (pp < 0) pp = int(0); else if(pp >= (int)list->size()-1)pp = int(list->size()-1);}
int p0 = p - 1; BOUNDS(p0);
int p1 = p; BOUNDS(p1);
int p2 = p + 1; BOUNDS(p2);
int p3 = p + 2; BOUNDS(p3);
float lt = (t - delta_t*(float)p) / delta_t;
DirectX::XMVECTOR pos = DirectX::XMVectorCatmullRom(list->at(p0)->PC_pos,
list->at(p1)->PC_pos,
list->at(p2)->PC_pos,
list->at(p3)->PC_pos,
lt);
return pos;
}
|
#include "ZoomController.h"
#include "Dynamics.h"
#include <cocos2d.h>
const float ZoomController::MIN_ZOOM = 1.0f;
const float ZoomController::MAX_ZOOM = 6.0f;
const float ZoomController::REST_VELOCITY_TOLERANCE = 0.1f;
const float ZoomController::REST_POSITION_TOLERANCE = 0.1f;
const float ZoomController::REST_ZOOM_TOLERANCE = 0.005f;
const float ZoomController::PAN_OUTSIDE_SNAP_FACTOR = 0.4f;
const float ZoomController::ZOOM_OUTSIDE_SNAP_FACTOR = 0.023f;
ZoomController::ZoomController() :
_panMinX(0),
_panMaxX(0),
_panMinY(0),
_panMaxY(0),
_needUpdate(false),
_fillMode(false),
_aspect(1.0),
_zoom(1.0),
_panX(0),
_panY(0),
_viewSize(cocos2d::Size::ZERO)
{
// _panDynamicsX = new SpringDynamics();
// _panDynamicsY = new SpringDynamics();
// _zoomDynamics = new SpringDynamics();
_panDynamicsX = new Dynamics();
_panDynamicsY = new Dynamics();
_zoomDynamics = new Dynamics();
reset();
}
ZoomController::~ZoomController()
{
delete _panDynamicsX;
delete _panDynamicsY;
delete _zoomDynamics;
}
void ZoomController::reset() {
_panDynamicsX->reset();
_panDynamicsY->reset();
_panDynamicsX->setFriction(2.0f);
_panDynamicsY->setFriction(2.0f);
_panDynamicsX->setSpring(500.0f, 0.9f);
_panDynamicsY->setSpring(500.0f, 0.9f);
// _panDynamicsX->setSpring(150.0f, 1.0f);
// _panDynamicsY->setSpring(150.0f, 1.0f);
_zoomDynamics->reset();
_zoomDynamics->setFriction(5.0f);
_zoomDynamics->setSpring(800, 1.3f);
_zoomDynamics->setMinPosition(MIN_ZOOM);
_zoomDynamics->setMaxPosition(MAX_ZOOM);
_zoomDynamics->setState(1.0, 0, 0);
_zoom = 1.0f;
_panX = 0.5f;
_panY = 0.5f;
updateLimits();
_needUpdate = false;
}
float ZoomController::getPanX() const {
return _panX;
}
float ZoomController::getPanY() const {
return _panY;
}
float ZoomController::getZoom() const {
return _zoom;
}
float ZoomController::getZoomX() const {
if (_fillMode) {
return std::max(_zoom, _zoom * _aspect);
} else {
return std::min(_zoom, _zoom * _aspect);
}
}
float ZoomController::getZoomY() const {
if (_fillMode) {
return std::max(_zoom, _zoom / _aspect);
} else {
return std::min(_zoom, _zoom / _aspect);
}
}
void ZoomController::setPanX(const float panX) {
_panX = panX;
}
void ZoomController::setPanY(const float panY) {
_panY = panY;
}
void ZoomController::setZoom(const float zoom) {
_zoom = zoom;
}
void ZoomController::setViewSize(const cocos2d::Size& viewSize) {
_viewSize = viewSize;
}
void ZoomController::updateAspect(const cocos2d::Size& viewSize, const cocos2d::Size& contentSize, const bool fillMode) {
_aspect = (contentSize.width / contentSize.height) / (viewSize.width / viewSize.height);
setViewSize(viewSize);
_fillMode = fillMode;
}
void ZoomController::zoom(const float zoom, const float panX, const float panY) {
float prevZoomX = getZoomX();
float prevZoomY = getZoomY();
float deltaZoom = zoom - getZoom();
if ((zoom > MAX_ZOOM && deltaZoom > 0) || (zoom < MIN_ZOOM && deltaZoom < 0)) {
deltaZoom *= ZOOM_OUTSIDE_SNAP_FACTOR;
}
setZoom(zoom);
limitZoom();
_zoomDynamics->setState(getZoom(), 0, cocos2d::Director::getInstance()->getGlobalTime());
float newZoomX = getZoomX();
float newZoomY = getZoomY();
setPanX(getPanX() + (panX - 0.5f) * (1.0f / prevZoomX - 1.0f / newZoomX));
setPanY(getPanY() + (panY - 0.5f) * (1.0f / prevZoomY - 1.0f / newZoomY));
updatePanLimits();
}
void ZoomController::zoomImmediate(const float zoom, const float panX, const float panY) {
setZoom(zoom);
setPanX(panX);
setPanY(panY);
_zoomDynamics->setState(zoom, 0, cocos2d::Director::getInstance()->getGlobalTime());
_panDynamicsY->setState(panY, 0, cocos2d::Director::getInstance()->getGlobalTime());
_panDynamicsX->setState(panX, 0, cocos2d::Director::getInstance()->getGlobalTime());
updatePanLimits();
}
void ZoomController::pan(float dx, float dy) {
dx /= getZoomX();
dy /= getZoomY();
if ((getPanX() > _panMaxX && dx > 0) || (getPanX() < _panMinX && dx < 0)) {
dx *= PAN_OUTSIDE_SNAP_FACTOR;
}
if ((getPanY() > _panMaxY && dy > 0) || (getPanY() < _panMinY && dy < 0)) {
dy *= PAN_OUTSIDE_SNAP_FACTOR;
}
float newPanX = getPanX() + dx;
float newPanY = getPanY() + dy;
setPanX(newPanX);
setPanY(newPanY);
}
bool ZoomController::update() {
if (_needUpdate) {
float nowTime = cocos2d::Director::getInstance()->getGlobalTime();
_panDynamicsX->update(nowTime);
_panDynamicsY->update(nowTime);
_zoomDynamics->update(nowTime);
bool isAtRest =
_panDynamicsX->isAtRest(REST_VELOCITY_TOLERANCE, REST_POSITION_TOLERANCE, _viewSize.width) &&
_panDynamicsY->isAtRest(REST_VELOCITY_TOLERANCE, REST_POSITION_TOLERANCE, _viewSize.height) &&
_zoomDynamics->isAtRest(REST_VELOCITY_TOLERANCE, REST_ZOOM_TOLERANCE, 1);
setPanX(_panDynamicsX->getPosition());
setPanY(_panDynamicsY->getPosition());
setZoom(_zoomDynamics->getPosition());
if (isAtRest) {
if (std::abs(MIN_ZOOM - getZoom()) < REST_ZOOM_TOLERANCE) {
setZoom(MIN_ZOOM);
_zoomDynamics->setState(MIN_ZOOM, 0, 0);
}
stopFling();
}
updatePanLimits();
}
return _needUpdate;
}
void ZoomController::startFling(float vx, float vy) {
float now = cocos2d::Director::getInstance()->getGlobalTime();
_panDynamicsX->setState(getPanX(), vx / getZoomX(), now);
_panDynamicsY->setState(getPanY(), vy / getZoomY(), now);
_panDynamicsX->setMinPosition(_panMinX);
_panDynamicsX->setMaxPosition(_panMaxX);
_panDynamicsY->setMinPosition(_panMinY);
_panDynamicsY->setMaxPosition(_panMaxY);
_needUpdate = true;
}
void ZoomController::stopFling() {
_needUpdate = false;
}
float ZoomController::getMaxPanDelta(float zoom) {
return std::max(0.0f, .5f * ((zoom - 1) / zoom));
}
void ZoomController::limitZoom() {
if (getZoom() < MIN_ZOOM-0.3) {
setZoom(MIN_ZOOM-0.3);
} else if (getZoom() > MAX_ZOOM) {
setZoom(MAX_ZOOM);
}
}
void ZoomController::updatePanLimits() {
float zoomX = getZoomX();
float zoomY = getZoomY();
_panMinX = .5f - getMaxPanDelta(zoomX);
_panMaxX = .5f + getMaxPanDelta(zoomX);
_panMinY = .5f - getMaxPanDelta(zoomY);
_panMaxY = .5f + getMaxPanDelta(zoomY);
}
cocos2d::Vec2 ZoomController::computePanPosition(const float zoom, const cocos2d::Vec2& pivot) {
float zoomX = std::min(zoom, getZoomX());
float zoomY = std::min(zoom, getZoomY());
float panMinX = .5f - getMaxPanDelta(zoomX);
float panMaxX = .5f + getMaxPanDelta(zoomX);
float panMinY = .5f - getMaxPanDelta(zoomY);
float panMaxY = .5f + getMaxPanDelta(zoomY);
float x = std::max(.0f, std::min(1.f, pivot.x));
float y = std::max(.0f, std::min(1.f, pivot.y));
cocos2d::Vec2 pan;
pan.x = _panX + (x - 0.5f) * (1.0f / getZoomX() - 1.0f / zoomX);
pan.y = _panY + (y - 0.5f) * (1.0f / getZoomY() - 1.0f / zoomY);
pan.x = std::min(panMaxX, std::max(panMinX, pan.x));
pan.y = std::min(panMaxY, std::max(panMinY, pan.y));
return pan;
}
void ZoomController::updateLimits() {
limitZoom();
updatePanLimits();
}
bool ZoomController::isPanning() const {
return _needUpdate;
}
|
#ifndef __SL_potential_hpp__
#define __SL_potential_hpp__
#include"header/BBFMM2D.hpp"
#define REAL double
using namespace std;
using namespace Eigen;
class myKernelGxx: public kernel_Base {
public:
virtual double kernel_Func(Point r0, Point r1){
//implement your own kernel here
double dx = -(r1.x - r0.x);
double dy = -(r1.y - r0.y);
double rSquare = dx*dx + dy*dy;
double r = pow(rSquare,0.5);
if(r > 10e-16){
//if(r0.panel != r1.panel){
return -log(r) + dx*dx/rSquare;
}
}
};
class myKernelGxy: public kernel_Base { //sirve con Gyx
public:
virtual double kernel_Func(Point r0, Point r1){
//implement your own kernel here
double dx = -(r1.x - r0.x);
double dy = -(r1.y - r0.y);
double rSquare = dx*dx + dy*dy;
double r = pow(rSquare,0.5);
if(r > 10e-16){
//if(r0.panel != r1.panel){
return dx*dy/rSquare;
}
}
};
class myKernelGyy: public kernel_Base {
public:
virtual double kernel_Func(Point r0, Point r1){
//implement your own kernel here
double dx = -(r1.x - r0.x);
double dy = -(r1.y - r0.y);
double rSquare = dx*dx + dy*dy;
double r = pow(rSquare,0.5);
if(r > 10e-16){
//if(r0.panel != r1.panel){
return -log(r) + dy*dy/rSquare;
}
}
};
void bbfmm_SL_potential_cpp(REAL* xsrc, int xsrcsize,
REAL *ysrc, int ysrcSize,
REAL *xtar, int xtarSize,
REAL *ytar, int ytarSize,
REAL *Rp, int n_pan,
REAL *wc, int n_wc,
REAL *fx, int n_fx,
REAL *fy, int n_fy,
REAL Re,
REAL *Axfmm, int n_Axfmm,
int nchebappol);
void bbfmm_SL_potential_cpp(REAL *xsrc, int xsrcSize,
REAL *ysrc, int ysrcSize,
REAL *xtar, int xtarSize,
REAL *ytar, int ytarSize,
REAL *Rp, int n_pan,
REAL *wc, int n_wc,
REAL *fx, int n_fx,
REAL *fy, int n_fy,
REAL Re,
REAL *Axfmm, int n_Axfmm,
int nchebappol){
int nq = xsrcSize/n_pan;
unsigned long N = xsrcSize + xtarSize;
unsigned long n_src = xsrcSize;
unsigned m = 1;
vector<Point> location;
unsigned short nChebNodes = nchebappol;
//cout << "Digite los nodos de chebyshev para aproximar el kernel " <<endl;
//cin >> nChebNodes;
double pi = acos(-1.), dpi = 2.*pi, ddpi = 4.*pi;
for(int i=0; i < N; i++){
if(i < xsrcSize){
location.push_back(Point(i/nq, xsrc[i],ysrc[i], false));
//cout<<i<<"; panel: "<< location[i].panel<<endl;
}
else{
location.push_back(Point(i-xsrcSize, xtar[i-xsrcSize],ytar[i-xsrcSize], true));
//cout<<i<<" "<<i-xsrcSize <<"; panel: "<< location[i].panel<<endl;
}
}
double* gamma1;
gamma1 = new double[N*m];
double* gamma2;
gamma2 = new double[N*m];
for(unsigned long i = 0; i < n_src; i++){
gamma1[i] = ((-Re/ddpi)*wc[i]*fx[i/nq]*Rp[i/nq]);
}
for(unsigned long i = 0; i < n_src; i++){
gamma2[i] = ((-Re/ddpi)*wc[i]*fy[i/nq]*Rp[i/nq]);
}
for(unsigned long i = n_src; i < N; i++){
gamma1[i] = 0.0;
}
for(unsigned long i = n_src; i < N; i++){
gamma2[i] = 0.0;
}
H2_2D_Tree Atree(nChebNodes, gamma1, location, N, m);
double* potentialgxx; double* potentialgyx;
potentialgxx = new double[N*m]; potentialgyx = new double[N*m];
myKernelGxx gxx;
gxx.calculate_Potential(Atree, potentialgxx);
myKernelGxy gyx;
gyx.calculate_Potential(Atree, potentialgyx);
H2_2D_Tree Btree(nChebNodes, gamma2, location, N, m);
double* potentialgyy; double* potentialgxy;
potentialgyy = new double[N*m]; potentialgxy = new double[N*m];
myKernelGyy gyy;
gyy.calculate_Potential(Btree, potentialgyy);
myKernelGxy gxy;
gxy.calculate_Potential(Btree, potentialgxy);
double Axxfmm[n_pan], Axyfmm[n_pan];
for(int i = xsrcSize; i < N; i++){
Axxfmm[i-xsrcSize] = potentialgxx[i] + potentialgxy[i];
Axfmm[i-xsrcSize] = -Axxfmm[i-xsrcSize];
}
for(int i = xsrcSize; i < N; i++){
Axyfmm[i-xsrcSize] = potentialgyx[i] + potentialgyy[i];
Axfmm[i-xsrcSize + n_pan] = -Axyfmm[i-xsrcSize];
}
//Atree.~H2_2D_Tree(); Btree.~H2_2D_Tree();
delete[] gamma1, gamma2;
delete[] potentialgxx, potentialgxy, potentialgyx, potentialgyy;
}
#endif //__DL_potential_hpp__
|
#include<stdio.h>
#include<string.h>
#include<malloc.h>
int main()
{
char *str[100];
int n,i;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf(str
}
return 0;
}
|
/********************************************************************************
** Form generated from reading UI file 'mainwindow.ui'
**
** Created by: Qt User Interface Compiler version 5.12.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_MAINWINDOW_H
#define UI_MAINWINDOW_H
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QCheckBox>
#include <QtWidgets/QLabel>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QProgressBar>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_MainWindow
{
public:
QWidget *centralWidget;
QCheckBox *checkBox_v1;
QCheckBox *checkBox_s12;
QCheckBox *checkBox_s11;
QProgressBar *progressBar_tanque1;
QProgressBar *progressBar_cano1;
QCheckBox *checkBox_b1;
QProgressBar *progressBar_cano2;
QProgressBar *progressBar_cano3;
QCheckBox *checkBox_s21;
QProgressBar *progressBar_tanque2;
QCheckBox *checkBox_s22;
QProgressBar *progressBar_tanque3;
QCheckBox *checkBox_s32;
QCheckBox *checkBox_s31;
QCheckBox *checkBox_v2;
QCheckBox *checkBox_r1;
QLabel *label_temperatura;
QLabel *label_text;
QLabel *label_niveltanque2;
QLabel *label_niveltanque3;
QMenuBar *menuBar;
QToolBar *mainToolBar;
QStatusBar *statusBar;
void setupUi(QMainWindow *MainWindow)
{
if (MainWindow->objectName().isEmpty())
MainWindow->setObjectName(QString::fromUtf8("MainWindow"));
MainWindow->resize(1215, 557);
centralWidget = new QWidget(MainWindow);
centralWidget->setObjectName(QString::fromUtf8("centralWidget"));
checkBox_v1 = new QCheckBox(centralWidget);
checkBox_v1->setObjectName(QString::fromUtf8("checkBox_v1"));
checkBox_v1->setGeometry(QRect(10, 320, 70, 17));
checkBox_s12 = new QCheckBox(centralWidget);
checkBox_s12->setObjectName(QString::fromUtf8("checkBox_s12"));
checkBox_s12->setGeometry(QRect(270, 190, 70, 17));
checkBox_s11 = new QCheckBox(centralWidget);
checkBox_s11->setObjectName(QString::fromUtf8("checkBox_s11"));
checkBox_s11->setGeometry(QRect(270, 350, 70, 17));
progressBar_tanque1 = new QProgressBar(centralWidget);
progressBar_tanque1->setObjectName(QString::fromUtf8("progressBar_tanque1"));
progressBar_tanque1->setGeometry(QRect(60, 180, 200, 200));
progressBar_tanque1->setValue(24);
progressBar_tanque1->setTextVisible(false);
progressBar_tanque1->setOrientation(Qt::Vertical);
progressBar_cano1 = new QProgressBar(centralWidget);
progressBar_cano1->setObjectName(QString::fromUtf8("progressBar_cano1"));
progressBar_cano1->setGeometry(QRect(140, 400, 261, 23));
progressBar_cano1->setValue(24);
progressBar_cano1->setTextVisible(false);
checkBox_b1 = new QCheckBox(centralWidget);
checkBox_b1->setObjectName(QString::fromUtf8("checkBox_b1"));
checkBox_b1->setGeometry(QRect(410, 400, 83, 22));
progressBar_cano2 = new QProgressBar(centralWidget);
progressBar_cano2->setObjectName(QString::fromUtf8("progressBar_cano2"));
progressBar_cano2->setGeometry(QRect(400, 190, 31, 201));
progressBar_cano2->setValue(24);
progressBar_cano2->setTextVisible(false);
progressBar_cano2->setOrientation(Qt::Vertical);
progressBar_cano3 = new QProgressBar(centralWidget);
progressBar_cano3->setObjectName(QString::fromUtf8("progressBar_cano3"));
progressBar_cano3->setGeometry(QRect(400, 160, 101, 23));
progressBar_cano3->setValue(24);
progressBar_cano3->setTextVisible(false);
checkBox_s21 = new QCheckBox(centralWidget);
checkBox_s21->setObjectName(QString::fromUtf8("checkBox_s21"));
checkBox_s21->setGeometry(QRect(730, 350, 70, 17));
progressBar_tanque2 = new QProgressBar(centralWidget);
progressBar_tanque2->setObjectName(QString::fromUtf8("progressBar_tanque2"));
progressBar_tanque2->setGeometry(QRect(520, 180, 200, 200));
progressBar_tanque2->setValue(50);
progressBar_tanque2->setTextVisible(false);
progressBar_tanque2->setOrientation(Qt::Vertical);
checkBox_s22 = new QCheckBox(centralWidget);
checkBox_s22->setObjectName(QString::fromUtf8("checkBox_s22"));
checkBox_s22->setGeometry(QRect(730, 180, 70, 17));
progressBar_tanque3 = new QProgressBar(centralWidget);
progressBar_tanque3->setObjectName(QString::fromUtf8("progressBar_tanque3"));
progressBar_tanque3->setGeometry(QRect(820, 280, 100, 100));
progressBar_tanque3->setMaximum(50);
progressBar_tanque3->setValue(50);
progressBar_tanque3->setTextVisible(false);
progressBar_tanque3->setOrientation(Qt::Vertical);
checkBox_s32 = new QCheckBox(centralWidget);
checkBox_s32->setObjectName(QString::fromUtf8("checkBox_s32"));
checkBox_s32->setGeometry(QRect(940, 290, 70, 17));
checkBox_s31 = new QCheckBox(centralWidget);
checkBox_s31->setObjectName(QString::fromUtf8("checkBox_s31"));
checkBox_s31->setGeometry(QRect(940, 360, 70, 17));
checkBox_v2 = new QCheckBox(centralWidget);
checkBox_v2->setObjectName(QString::fromUtf8("checkBox_v2"));
checkBox_v2->setGeometry(QRect(770, 310, 83, 22));
checkBox_r1 = new QCheckBox(centralWidget);
checkBox_r1->setObjectName(QString::fromUtf8("checkBox_r1"));
checkBox_r1->setGeometry(QRect(870, 390, 83, 22));
label_temperatura = new QLabel(centralWidget);
label_temperatura->setObjectName(QString::fromUtf8("label_temperatura"));
label_temperatura->setGeometry(QRect(870, 240, 55, 16));
label_text = new QLabel(centralWidget);
label_text->setObjectName(QString::fromUtf8("label_text"));
label_text->setGeometry(QRect(850, 220, 81, 16));
label_niveltanque2 = new QLabel(centralWidget);
label_niveltanque2->setObjectName(QString::fromUtf8("label_niveltanque2"));
label_niveltanque2->setGeometry(QRect(590, 90, 47, 13));
label_niveltanque3 = new QLabel(centralWidget);
label_niveltanque3->setObjectName(QString::fromUtf8("label_niveltanque3"));
label_niveltanque3->setGeometry(QRect(860, 150, 47, 13));
MainWindow->setCentralWidget(centralWidget);
menuBar = new QMenuBar(MainWindow);
menuBar->setObjectName(QString::fromUtf8("menuBar"));
menuBar->setGeometry(QRect(0, 0, 1215, 21));
MainWindow->setMenuBar(menuBar);
mainToolBar = new QToolBar(MainWindow);
mainToolBar->setObjectName(QString::fromUtf8("mainToolBar"));
MainWindow->addToolBar(Qt::TopToolBarArea, mainToolBar);
statusBar = new QStatusBar(MainWindow);
statusBar->setObjectName(QString::fromUtf8("statusBar"));
MainWindow->setStatusBar(statusBar);
retranslateUi(MainWindow);
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
void retranslateUi(QMainWindow *MainWindow)
{
MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", nullptr));
checkBox_v1->setText(QApplication::translate("MainWindow", "v1", nullptr));
checkBox_s12->setText(QApplication::translate("MainWindow", "s12", nullptr));
checkBox_s11->setText(QApplication::translate("MainWindow", "s11", nullptr));
checkBox_b1->setText(QApplication::translate("MainWindow", "b1", nullptr));
checkBox_s21->setText(QApplication::translate("MainWindow", "s21", nullptr));
checkBox_s22->setText(QApplication::translate("MainWindow", "s22", nullptr));
checkBox_s32->setText(QApplication::translate("MainWindow", "s32", nullptr));
checkBox_s31->setText(QApplication::translate("MainWindow", "s31", nullptr));
checkBox_v2->setText(QApplication::translate("MainWindow", "v2", nullptr));
checkBox_r1->setText(QApplication::translate("MainWindow", "R", nullptr));
label_temperatura->setText(QApplication::translate("MainWindow", "25", nullptr));
label_text->setText(QApplication::translate("MainWindow", "Temperatura:", nullptr));
label_niveltanque2->setText(QString());
label_niveltanque3->setText(QString());
} // retranslateUi
};
namespace Ui {
class MainWindow: public Ui_MainWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MAINWINDOW_H
|
#include "days.hpp"
#include "day9.hpp"
#include <range/v3/all.hpp>
#include <deque>
template<>
auto days::solve<days::day::day_9, days::part::part_1>(std::istream &input)
-> std::string
{
return preamble_finder<25>::solve_part1(input);
}
template<>
auto days::solve<days::day::day_9, days::part::part_2>(std::istream &input)
-> std::string
{
return preamble_finder<25>::solve_part2(input);
}
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ABSTRACTCACHEDMESHREADER_HPP_
#define ABSTRACTCACHEDMESHREADER_HPP_
#include <vector>
#include <string>
#include "AbstractMeshReader.hpp"
/**
* Abstract mesh reader class, for readers which read and cache the entire
* mesh in internal storage, for the mesh to use for constructing itself.
* Concrete readers which will read large, memory-intensive, meshes should
* inherit from AbstractMeshReader, not this class.
*/
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
class AbstractCachedMeshReader : public AbstractMeshReader<ELEMENT_DIM, SPACE_DIM>
{
protected:
unsigned mNumNodeAttributes; /**< Is the number of attributes stored at each node */
unsigned mMaxNodeBdyMarker; /**< Is the maximum node boundary marker */
unsigned mNumElementNodes; /**< Is the number of nodes per element*/
unsigned mNumElementAttributes; /**< Is the number of attributes stored for each element */
unsigned mMaxFaceBdyMarker; /**< Is the maximum face (or edge) boundary marker */
std::vector<std::string> mNodeRawData; /**< Contents of node input file with comments removed */
std::vector<std::string> mElementRawData; /**< Contents of element input file with comments removed */
std::vector<std::string> mFaceRawData; /**< Contents of face (or edge) input file with comments removed */
std::vector< std::vector<double> > mNodeData; /**< Is an array of node coordinates ((i,j)th entry is the jth coordinate of node i)*/
std::vector< std::vector<unsigned> > mElementData; /**< Is an array of the nodes in each element ((i,j)th entry is the jth node of element i) */
std::vector< std::vector<unsigned> > mFaceData; /**< Is an array of the nodes in each face ((i,j)th entry is the jth node of face i) */
std::vector< std::vector<double> >::iterator mpNodeIterator; /**< Is an iterator for the node data */
std::vector< std::vector<unsigned> >::iterator mpElementIterator; /**< Is an iterator for the element data */
std::vector< std::vector<unsigned> >::iterator mpFaceIterator; /**< Is an iterator for the face data */
bool mIndexFromZero; /**< True if input data is numbered from zero, false otherwise */
/**
* Reads an input file rFileName, removes comments (indicated by a #) and blank
* lines and returns a vector of strings. Each string corresponds to one line
* of the input file.
* @return a vector of strings
* @param rFileName the name of the file to read from, relative to the output directory
*/
std::vector<std::string> GetRawDataFromFile(const std::string& rFileName);
public:
AbstractCachedMeshReader(); /**< Constructor */
virtual ~AbstractCachedMeshReader()
{} /**< Destructor. */
unsigned GetNumElements() const; /**< @return the number of elements in the mesh. */
unsigned GetNumNodes() const; /**< @return the number of nodes in the mesh. */
unsigned GetNumFaces() const; /**< @return the number of faces in the mesh (synonym of GetNumEdges()) */
/**
* @return the maximum node index. Used in testing to check that output nodes
* are always indexed from zero even if they are input indexed from one.
*/
unsigned GetMaxNodeIndex();
/**
* @return the minimum node index. Used in testing to check that output nodes
* are always indexed from zero even if they are input indexed from one.
*/
unsigned GetMinNodeIndex();
/**
* @return a vector of the coordinates of each node in turn, starting with
* node 0 the first time it is called followed by nodes 1, 2, ... , mNumNodes-1.
*/
std::vector<double> GetNextNode();
void Reset(); /**< Resets pointers to beginning*/
/**
* @return a vector of the nodes of each element in turn, starting with
* element 0 the first time it is called followed by elements 1, 2, ... ,
* mNumElements-1.
*/
ElementData GetNextElementData();
/**
* @return a vector of the nodes of each face in turn, starting with face 0 the
* first time it is called followed by faces 1, 2, ... , mNumFaces-1.
*
* Is a synonum of GetNextEdge(). The two functions can be used interchangeably,
* i.e. they use the same iterator.
*/
ElementData GetNextFaceData();
};
#endif /*ABSTRACTCACHEDMESHREADER_HPP_*/
|
//
// hwLight.cpp
// HamsterWheel
//
// Created by OilyFing3r on 2014. 9. 2..
// Copyright (c) 2014년 OilyFing3rWorks. All rights reserved.
//
#include "hwLight.h"
float Light::getIntensity(void) const
{
return intensity;
}
void Light::setIntensity(float intensity)
{
this->intensity = intensity;
}
static GLUquadricObj * quad = nullptr;
void Light::drawVolume(void)
{
const int slices = 16;
if (!quad)
{
quad = gluNewQuadric();
}
if(position.w==0 || cutoff>45.) // is directional light
{
glPushMatrix();
glTranslatef(position.x, position.y, position.z);
gluSphere(quad, intensity, slices, slices);
glPopMatrix();
}
else
{
float radius = intensity * tanf(glm::radians(cutoff));
glm::vec3 cax(1.0, 0.0, 0.0);
glm::vec3 axis;
float theta;
float min = fabsf(direction.x);
if(fabsf(direction.y) < min)
{
min = fabsf(direction.y);
cax = glm::vec3(0.0, 1.0, 0.0);
}
if(fabsf(direction.z) < min
|| fabsf(direction.z) != 0
|| fabsf(direction.x) == cax.y == 1
|| fabsf(direction.y) == cax.x == 1)
{
cax = glm::vec3(0.0, 0.0, 1.0);
}
axis = glm::cross(cax, direction);
theta = glm::degrees(acosf(glm::dot(cax, direction)));
glPushMatrix();
glTranslatef(position.x, position.y, position.z);
glRotatef(theta, axis.x, axis.y, axis.z);
gluCylinder(quad, 0., radius, intensity, slices, 1);
glTranslatef(0.0, 0.0, intensity);
gluDisk(quad, 0., radius, slices, 1);
glPopMatrix();
}
}
void Light::lookAt(void)
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(COMMON_FOVY, WINDOW_ASPECT, MIN_DISTANCE, intensity);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(position.x, position.y, position.z,
position.x + direction.x,
position.y + direction.y,
position.z + direction.z,
0.0, 1.0, 0.0);
}
void Light::setup(void)
{
glLightfv(GL_LIGHT0, GL_POSITION, &position.x);
glLightfv(GL_LIGHT0, GL_AMBIENT, &ambient.x);
glLightfv(GL_LIGHT0, GL_DIFFUSE, &diffuse.x);
glLightfv(GL_LIGHT0, GL_SPECULAR, &specular.x);
glLightfv(GL_LIGHT0, GL_SPOT_CUTOFF, &cutoff);
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, &direction.x);
glLightfv(GL_LIGHT0, GL_SPOT_EXPONENT, &exponent);
//glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.5);
//glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.025);
//glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 0.0025);
glEnable(GL_LIGHT0);
}
void Light::unsetup(void)
{
glDisable(GL_LIGHT0);
}
|
#include "xmlreader.h"
#include "helper.h"
#include "tinyxml2/tinyxml2.h"
#include <cstdlib>
using tinyxml2::XML_SUCCESS;
using tinyxml2::XMLElement;
using tinyxml2::XMLNode;
namespace POICS{
class POICS_API XMLMapReaderImpl : public XMLMapReader {
private:
tinyxml2::XMLDocument doc;
public:
XMLMapReaderImpl(const char* _filepath);
virtual ~XMLMapReaderImpl(){}
virtual void build (MapArea& map);
};
class POICS_API XMLAgentReaderImpl : public XMLAgentReader {
private:
tinyxml2::XMLDocument doc;
public:
XMLAgentReaderImpl(const char* _filepath);
virtual ~XMLAgentReaderImpl(){}
virtual void build (AgentBuilder& ab);
};
XMLMapReader* XMLMapReader::create(const char* filepath){
return new XMLMapReaderImpl(filepath);
}
XMLAgentReader* XMLAgentReader::create(const char* filepath){
return new XMLAgentReaderImpl(filepath);
}
typedef std::vector<std::string> token_t;
const char* POLY_SHAPE = "poly";
const char* RECT_SHAPE = "rect";
double XMLMapReader::MAP_SCALE = 1.0;
double scale(double& d){
return d *= XMLMapReader::MAP_SCALE;
}
void doubleAttr(XMLElement *elmt, const char* attr, double& d){
if (elmt->QueryDoubleAttribute(attr, &d) != XML_SUCCESS)
except(std::string("Expecting double attribute: ") + attr);
}
void intAttr(XMLElement *elmt, const char* attr, int& d){
if (elmt->QueryIntAttribute(attr, &d) != XML_SUCCESS)
except(std::string("Expecting int attribute: ") + attr);
}
void strAttr(XMLElement *elmt, const char* attr, std::string& str){
const char* cstr = elmt->Attribute(attr);
if (cstr == NULL)
except(std::string("Expecting string attribute: ") + attr);
str.assign(cstr);
}
void dataElmt(XMLElement *elmt, std::string& key, std::string& value){
strAttr(elmt, "key", key);
strAttr(elmt, "value", value);
}
void readRect(XMLElement *elmt, Rect& r){
double x, y, w, h;
if ((elmt->QueryDoubleAttribute("x", &x) != XML_SUCCESS) || \
(elmt->QueryDoubleAttribute("y", &y) != XML_SUCCESS) || \
(elmt->QueryDoubleAttribute("width", &w) != XML_SUCCESS) || \
(elmt->QueryDoubleAttribute("height", &h) != XML_SUCCESS))
except("Expecting attributes x, y, width and height");
r.set(scale(x),scale(y),scale(w),scale(h));
}
void readPoly(XMLElement *elmt, Polygon& poly){
std::string s; char buf; poly.reset(); Point point; double x, y;
trim(s.assign(elmt->GetText()));
token_t tokens;
split(s, ' ', tokens);
std::stringstream ss;
for (std::string& strp : tokens){
if (strp.length() == 0) continue;
ss.str(strp);
ss >> x >> buf >> y;
point.x = scale(x);
point.y = scale(y);
poly.addPoint(point);
ss.clear();
}
}
XMLMapReaderImpl::XMLMapReaderImpl(const char* _filepath) {
doc.LoadFile(_filepath);
}
XMLElement* readChildElement(XMLNode* node, const char* attr, bool optional = false){
XMLElement *elmt = node->FirstChildElement(attr);
if (elmt != NULL || optional){
return elmt;
}
except(std::string("Expecting child: ") + attr);
return NULL;
}
void readRelevance(XMLElement* root, MapArea& map, int id){
XMLElement *elmt = readChildElement(root, "relevance");
elmt = readChildElement(elmt, "topic", true);
std::string name; double value;
while (elmt != NULL){
strAttr(elmt, "name", name);
doubleAttr(elmt, "value", value);
map.setTopicRelevance(id, name, value);
elmt = elmt->NextSiblingElement("topic");
}
}
void XMLMapReaderImpl::build (MapArea& map){
XMLElement *elmt1, *elmt2, *elmt3; std::string s1; Rect rect;
elmt1 = readChildElement(&doc, "environment");
double d1, d2;
try {
doubleAttr(elmt1, "scale", d1);
if (d1 > 0)
MAP_SCALE = d1;
} catch (...){}
doubleAttr(elmt1, "width", d1);
doubleAttr(elmt1, "height", d2);
map.width = scale(d1);
map.height = scale(d2);
/** read topic **/
elmt2 = readChildElement(elmt1, "topics");
trim(s1.assign(elmt2->GetText()));
token_t tokens;
split(s1, ',', tokens);
for (std::string& topic : tokens){
map.addTopic(topic);
}
/** read spawn points **/
elmt2 = readChildElement(elmt1, "spawns");
elmt3 = readChildElement(elmt2, "spawn");
do{
doubleAttr(elmt3, "dist", d1);
readRect(elmt3, rect);
map.addSpawnPoint(d1, rect);
elmt3 = elmt3->NextSiblingElement("spawn");
}while(elmt3 != NULL);
/** read exit points **/
elmt2 = readChildElement(elmt1, "exits");
elmt3 = readChildElement(elmt2, "exit");
do{
doubleAttr(elmt3, "dist", d1);
readRect(elmt3, rect);
map.addExitPoint(d1, rect);
elmt3 = elmt3->NextSiblingElement("exit");
}while(elmt3 != NULL);
/** read poi **/
elmt2 = readChildElement(elmt1, "pois");
elmt3 = readChildElement(elmt2, "poi");
do{
int duration, activity_type = 0;
strAttr(elmt3, "name", s1);
intAttr(elmt3, "duration", duration);
readRect(elmt3, rect);
int id = map.addPOI(s1, activity_type, duration, rect);
readRelevance(elmt3, map, id);
elmt3 = elmt3->NextSiblingElement("poi");
}while(elmt3 != NULL);
elmt2 = readChildElement(elmt1, "obstacles");
elmt3 = readChildElement(elmt2, "obstacle", true);
Polygon poly;
while (elmt3 != NULL){
strAttr(elmt3, "shape", s1);
if (s1 == POLY_SHAPE){
readPoly(elmt3, poly);
} else if (s1 == RECT_SHAPE){
readRect(elmt3, rect);
rect.copyToPolygonCCW(poly);
} else {
except("Unknown shape type attribute");
}
poly.calcCentroid(); poly.setOrientation(ORIENTATION_CCW);
map.addObstacle(poly);
elmt3 = elmt3->NextSiblingElement("obstacle");
}
}
XMLAgentReaderImpl::XMLAgentReaderImpl(const char* _filepath) {
doc.LoadFile(_filepath);
}
void readMinMax(XMLElement *elmt, double& min, double& max){
doubleAttr(elmt, "min", min); doubleAttr(elmt, "max", max);
}
void XMLAgentReaderImpl::build (AgentBuilder& as){
XMLElement *elmt1, *elmt2, *elmt3, *elmt4, *elmt5; std::string s1, s2; int n; double d1, d2;
elmt1 = readChildElement(&doc, "agents");
intAttr(elmt1, "count", n); as.setNumAgents(n);
intAttr(elmt1, "enterTime", n); as.entryTime = n;
elmt2 = readChildElement(elmt1, "profiles");
elmt3 = readChildElement(elmt2, "profile");
do{
strAttr(elmt3, "name", s1);
doubleAttr(elmt3, "dist", d1);
int id = as.addProfile (s1, d1);
elmt4 = readChildElement(elmt3, "maxTime");
readMinMax(elmt4, d1, d2);
as.setProfileDuration(id, d1, d2);
elmt4 = readChildElement(elmt3, "interest");
elmt5 = readChildElement(elmt4, "topic");
do {
strAttr(elmt5, "name", s1);
readMinMax(elmt5, d1, d2);
as.addInterestRange(id, s1, d1, d2);
elmt5 = elmt5->NextSiblingElement("topic");
} while (elmt5 != NULL);
elmt4 = readChildElement(elmt3, "data", true);
while (elmt4 != NULL){
dataElmt(elmt4, s1, s2);
as.addProfileExtras(id, s1, s2);
elmt4 = elmt4->NextSiblingElement("data");
}
elmt3 = elmt3->NextSiblingElement("profile");
}while(elmt3 != NULL);
}
}
|
/////////////////////////////////////////////////////////////////////////
//// Ftdc C++ => C Adapter
//// Author : cpaistwb@126.com
//// Generated at 2018/3/27
/////////////////////////////////////////////////////////////////////////
#pragma once
#include "USTPFtdcTraderApi.h"
#include "enums.h"
#include <stdio.h>
void OnFrontEvent(void* pObject, int type, int Reason) {
//printf("%s", "connected!------\n");
}
void OnRspEvent(void* pObject, int type, void* pParam, void* pRspInfo, int nRequestID, int bIsLast) {
//printf("%s", "rsp\n-------------");
}
void OnRtnEvent(void* pObject, int type, void* pParam) {
//printf("%s", "rtn\n----------------");
}
void OnErrRtnEvent(void* pObject, int type, void* pParam, void* pRspInfo) {
//printf("%s", "errRtn\n-----------");
}
void OnPackageEvent(void* pObject, int type, int nTopicID, int nSequenceNo) {
//printf("%s", "OnPackageEvent-----------------");
}
class Trader : public CUstpFtdcTraderSpi
{
public:
CUstpFtdcTraderApi* RawApi{ nullptr };
CbOnErrRtnEvent mOnErrRtnEvent{ nullptr };
CbOnFrontEvent mOnFrontEvent{ nullptr };
CbOnPackageEvent mOnPackageEvent{ nullptr };
CbOnRspEvent mOnRspEvent{ nullptr };
CbOnRtnEvent mOnRtnEvent{ nullptr };
/*
CbOnErrRtnEvent mOnErrRtnEvent = OnErrRtnEvent;
CbOnFrontEvent mOnFrontEvent = OnFrontEvent;
CbOnPackageEvent mOnPackageEvent = OnPackageEvent;
CbOnRspEvent mOnRspEvent = OnRspEvent;
CbOnRtnEvent mOnRtnEvent = OnRtnEvent;
*/
void* pObject;
Trader(const char* pszFlowPath) {
RawApi = CUstpFtdcTraderApi::CreateFtdcTraderApi(pszFlowPath);
RawApi->RegisterSpi(this);
pObject = this;
}
virtual ~Trader() {
if (RawApi){
RawApi->RegisterSpi(nullptr);
RawApi->Release();
RawApi = nullptr;
}
};
virtual void OnFrontConnected() {
mOnFrontEvent(pObject, (int)EnumOnFrontEvent::OnFrontConnected, 0);
};
virtual void OnFrontDisconnected(int nReason) {
mOnFrontEvent(pObject, (int)EnumOnFrontEvent::OnFrontDisconnected, nReason);
};
virtual void OnHeartBeatWarning(int nTimeLapse) {
};
virtual void OnPackageStart(int nTopicID, int nSequenceNo) {
mOnPackageEvent(pObject, (int)EnumOnPackageEvent::OnPackageStart, nTopicID, nSequenceNo);
};
virtual void OnPackageEnd(int nTopicID, int nSequenceNo) {
mOnPackageEvent(pObject, (int)EnumOnPackageEvent::OnPackageEnd, nTopicID, nSequenceNo);
};
virtual void OnRspError(CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspError, nullptr, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspUserLogin(CUstpFtdcRspUserLoginField * pRspUserLogin, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspUserLogin, pRspUserLogin, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspUserLogout(CUstpFtdcRspUserLogoutField * pRspUserLogout, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspUserLogout, pRspUserLogout, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspUserPasswordUpdate(CUstpFtdcUserPasswordUpdateField * pUserPasswordUpdate, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspUserPasswordUpdate, pUserPasswordUpdate, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspSettlementInfoConfirm(CUstpFtdcSettlementInfoConfirmField * pSettlementInfoConfirm, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspSettlementInfoConfirm, pSettlementInfoConfirm, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspMsgNotifyConfirm(CUstpFtdcMsgNotifyConfirmField * pMsgNotifyConfirm, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspMsgNotifyConfirm, pMsgNotifyConfirm, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspOrderInsert(CUstpFtdcInputOrderField * pInputOrder, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspOrderInsert, pInputOrder, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspOrderAction(CUstpFtdcOrderActionField * pOrderAction, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspOrderAction, pOrderAction, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQuoteInsert(CUstpFtdcInputQuoteField * pInputQuote, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQuoteInsert, pInputQuote, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQuoteAction(CUstpFtdcQuoteActionField * pQuoteAction, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQuoteAction, pQuoteAction, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspForQuote(CUstpFtdcReqForQuoteField * pReqForQuote, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspForQuote, pReqForQuote, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspMarginCombAction(CUstpFtdcInputMarginCombActionField * pInputMarginCombAction, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspMarginCombAction, pInputMarginCombAction, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspUserDeposit(CUstpFtdcstpUserDepositField * pstpUserDeposit, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspUserDeposit, pstpUserDeposit, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspTransferMoney(CUstpFtdcstpTransferMoneyField * pstpTransferMoney, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspTransferMoney, pstpTransferMoney, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRtnFlowMessageCancel(CUstpFtdcFlowMessageCancelField * pFlowMessageCancel) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnFlowMessageCancel, pFlowMessageCancel);
};
virtual void OnRtnTrade(CUstpFtdcTradeField * pTrade) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnTrade, pTrade);
};
virtual void OnRtnOrder(CUstpFtdcOrderField * pOrder) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnOrder, pOrder);
};
virtual void OnErrRtnOrderInsert(CUstpFtdcInputOrderField * pInputOrder, CUstpFtdcRspInfoField * pRspInfo) {
mOnErrRtnEvent(pObject, (int)EnumOnErrRtnEvent::OnErrRtnOrderInsert, pInputOrder, pRspInfo);
};
virtual void OnErrRtnOrderAction(CUstpFtdcOrderActionField * pOrderAction, CUstpFtdcRspInfoField * pRspInfo) {
mOnErrRtnEvent(pObject, (int)EnumOnErrRtnEvent::OnErrRtnOrderAction, pOrderAction, pRspInfo);
};
virtual void OnRtnInstrumentStatus(CUstpFtdcInstrumentStatusField * pInstrumentStatus) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnInstrumentStatus, pInstrumentStatus);
};
virtual void OnRtnInvestorAccountDeposit(CUstpFtdcInvestorAccountDepositResField * pInvestorAccountDepositRes) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnInvestorAccountDeposit, pInvestorAccountDepositRes);
};
virtual void OnRtnQuote(CUstpFtdcRtnQuoteField * pRtnQuote) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnQuote, pRtnQuote);
};
virtual void OnErrRtnQuoteInsert(CUstpFtdcInputQuoteField * pInputQuote, CUstpFtdcRspInfoField * pRspInfo) {
mOnErrRtnEvent(pObject, (int)EnumOnErrRtnEvent::OnErrRtnQuoteInsert, pInputQuote, pRspInfo);
};
virtual void OnErrRtnQuoteAction(CUstpFtdcQuoteActionField * pQuoteAction, CUstpFtdcRspInfoField * pRspInfo) {
mOnErrRtnEvent(pObject, (int)EnumOnErrRtnEvent::OnErrRtnQuoteAction, pQuoteAction, pRspInfo);
};
virtual void OnRtnForQuote(CUstpFtdcReqForQuoteField * pReqForQuote) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnForQuote, pReqForQuote);
};
virtual void OnRtnMarginCombinationLeg(CUstpFtdcMarginCombinationLegField * pMarginCombinationLeg) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnMarginCombinationLeg, pMarginCombinationLeg);
};
virtual void OnRtnMarginCombAction(CUstpFtdcInputMarginCombActionField * pInputMarginCombAction) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnMarginCombAction, pInputMarginCombAction);
};
virtual void OnRtnUserDeposit(CUstpFtdcstpUserDepositField * pstpUserDeposit) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnUserDeposit, pstpUserDeposit);
};
virtual void OnRspQueryUserLogin(CUstpFtdcRspUserLoginField * pRspUserLogin, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQueryUserLogin, pRspUserLogin, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQryOrder(CUstpFtdcOrderField * pOrder, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQryOrder, pOrder, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQryTrade(CUstpFtdcTradeField * pTrade, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQryTrade, pTrade, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQryUserInvestor(CUstpFtdcRspUserInvestorField * pRspUserInvestor, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQryUserInvestor, pRspUserInvestor, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQryTradingCode(CUstpFtdcRspTradingCodeField * pRspTradingCode, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQryTradingCode, pRspTradingCode, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQryInvestorAccount(CUstpFtdcRspInvestorAccountField * pRspInvestorAccount, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQryInvestorAccount, pRspInvestorAccount, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQryInstrument(CUstpFtdcRspInstrumentField * pRspInstrument, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQryInstrument, pRspInstrument, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQryExchange(CUstpFtdcRspExchangeField * pRspExchange, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQryExchange, pRspExchange, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQryInvestorPosition(CUstpFtdcRspInvestorPositionField * pRspInvestorPosition, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQryInvestorPosition, pRspInvestorPosition, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQryComplianceParam(CUstpFtdcRspComplianceParamField * pRspComplianceParam, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQryComplianceParam, pRspComplianceParam, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQryInvestorFee(CUstpFtdcInvestorFeeField * pInvestorFee, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQryInvestorFee, pInvestorFee, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQryInvestorMargin(CUstpFtdcInvestorMarginField * pInvestorMargin, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQryInvestorMargin, pInvestorMargin, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQryInvestorCombPosition(CUstpFtdcRspInvestorCombPositionField * pRspInvestorCombPosition, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQryInvestorCombPosition, pRspInvestorCombPosition, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQryInvestorLegPosition(CUstpFtdcRspInvestorLegPositionField * pRspInvestorLegPosition, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQryInvestorLegPosition, pRspInvestorLegPosition, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQryInstrumentGroup(CUstpFtdcRspInstrumentGroupField * pRspInstrumentGroup, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQryInstrumentGroup, pRspInstrumentGroup, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQryClientMarginCombType(CUstpFtdcRspClientMarginCombTypeField * pRspClientMarginCombType, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQryClientMarginCombType, pRspClientMarginCombType, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspExecOrderInsert(CUstpFtdcInputExecOrderField * pInputExecOrder, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspExecOrderInsert, pInputExecOrder, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspExecOrderAction(CUstpFtdcInputExecOrderActionField * pInputExecOrderAction, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspExecOrderAction, pInputExecOrderAction, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRtnExecOrder(CUstpFtdcExecOrderField * pExecOrder) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnExecOrder, pExecOrder);
};
virtual void OnErrRtnExecOrderInsert(CUstpFtdcInputExecOrderField * pInputExecOrder, CUstpFtdcRspInfoField * pRspInfo) {
mOnErrRtnEvent(pObject, (int)EnumOnErrRtnEvent::OnErrRtnExecOrderInsert, pInputExecOrder, pRspInfo);
};
virtual void OnErrRtnExecOrderAction(CUstpFtdcInputExecOrderActionField * pInputExecOrderAction, CUstpFtdcRspInfoField * pRspInfo) {
mOnErrRtnEvent(pObject, (int)EnumOnErrRtnEvent::OnErrRtnExecOrderAction, pInputExecOrderAction, pRspInfo);
};
virtual void OnRspQrySettlementInfoConfirm(CUstpFtdcSettlementInfoConfirmField * pSettlementInfoConfirm, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQrySettlementInfoConfirm, pSettlementInfoConfirm, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQrySystemTime(CUstpFtdcRspQrySystemTimeField * pRspQrySystemTime, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQrySystemTime, pRspQrySystemTime, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQuerySettlementInfo(CUstpFtdcSettlementRspField * pSettlementRsp, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQuerySettlementInfo, pSettlementRsp, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspTradingAccountPasswordUpdate(CUstpFtdcTradingAccountPasswordUpdateRspField * pTradingAccountPasswordUpdateRsp, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspTradingAccountPasswordUpdate, pTradingAccountPasswordUpdateRsp, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQueryTransferSeriaOffset(CUstpFtdcTransferSerialFieldRspField * pTransferSerialFieldRsp, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQueryTransferSeriaOffset, pTransferSerialFieldRsp, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQueryAccountregister(CUstpFtdcAccountregisterRspField * pAccountregisterRsp, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQueryAccountregister, pAccountregisterRsp, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspFromBankToFutureByFuture(CUstpFtdcTransferFieldReqField * pTransferFieldReq, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspFromBankToFutureByFuture, pTransferFieldReq, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRtnFromBankToFutureByFuture(CUstpFtdcTransferFieldReqField * pTransferFieldReq) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnFromBankToFutureByFuture, pTransferFieldReq);
};
virtual void OnRspFromFutureToBankByFuture(CUstpFtdcTransferFieldReqField * pTransferFieldReq, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspFromFutureToBankByFuture, pTransferFieldReq, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRtnFromFutureToBankByFuture(CUstpFtdcTransferFieldReqField * pTransferFieldReq) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnFromFutureToBankByFuture, pTransferFieldReq);
};
virtual void OnRtnFromFutureToBankByBank(CUstpFtdcTransferFieldReqField * pTransferFieldReq) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnFromFutureToBankByBank, pTransferFieldReq);
};
virtual void OnRtnFromBankToFutureByBank(CUstpFtdcTransferFieldReqField * pTransferFieldReq) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnFromBankToFutureByBank, pTransferFieldReq);
};
virtual void OnRspQueryBankAccountMoneyByFuture(CUstpFtdcAccountFieldRspField * pAccountFieldRsp, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQueryBankAccountMoneyByFuture, pAccountFieldRsp, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRtnQueryBankBalanceByFuture(CUstpFtdcAccountFieldRtnField * pAccountFieldRtn) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnQueryBankBalanceByFuture, pAccountFieldRtn);
};
virtual void OnRtnOpenAccountByBank(CUstpFtdcSignUpOrCancleAccountRspFieldField * pSignUpOrCancleAccountRspField) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnOpenAccountByBank, pSignUpOrCancleAccountRspField);
};
virtual void OnRtnCancelAccountByBank(CUstpFtdcSignUpOrCancleAccountRspFieldField * pSignUpOrCancleAccountRspField) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnCancelAccountByBank, pSignUpOrCancleAccountRspField);
};
virtual void OnRspFromBankToFutureByBank(CUstpFtdcTransferFieldReqField * pTransferFieldReq, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspFromBankToFutureByBank, pTransferFieldReq, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspFromFutureToBankByBank(CUstpFtdcTransferFieldReqField * pTransferFieldReq, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspFromFutureToBankByBank, pTransferFieldReq, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRtnFromBankToFutureByJSD(CUstpFtdcJSDMoneyField * pJSDMoney) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnFromBankToFutureByJSD, pJSDMoney);
};
virtual void OnRtnFromFutureToBankByJSD(CUstpFtdcJSDMoneyField * pJSDMoney) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnFromFutureToBankByJSD, pJSDMoney);
};
virtual void OnRtnTransferInvestorAccountChanged(CUstpFtdcTransferFieldReqField * pTransferFieldReq) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnTransferInvestorAccountChanged, pTransferFieldReq);
};
virtual void OnRspSignUpAccountByFuture(CUstpFtdcSignUpOrCancleAccountRspFieldField * pSignUpOrCancleAccountRspField, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspSignUpAccountByFuture, pSignUpOrCancleAccountRspField, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspCancleAccountByFuture(CUstpFtdcSignUpOrCancleAccountRspFieldField * pSignUpOrCancleAccountRspField, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspCancleAccountByFuture, pSignUpOrCancleAccountRspField, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQuerySignUpOrCancleAccountStatus(CUstpFtdcQuerySignUpOrCancleAccountStatusRspFieldField * pQuerySignUpOrCancleAccountStatusRspField, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQuerySignUpOrCancleAccountStatus, pQuerySignUpOrCancleAccountStatusRspField, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspChangeAccountByFuture(CUstpFtdcChangeAccountRspFieldField * pChangeAccountRspField, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspChangeAccountByFuture, pChangeAccountRspField, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspOpenSimTradeAccount(CUstpFtdcSimTradeAccountInfoField * pSimTradeAccountInfo, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspOpenSimTradeAccount, pSimTradeAccountInfo, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspCheckOpenSimTradeAccount(CUstpFtdcSimTradeAccountInfoField * pSimTradeAccountInfo, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspCheckOpenSimTradeAccount, pSimTradeAccountInfo, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspCFMMCTradingAccountKey(CUstpFtdcCFMMCTradingAccountKeyRspField * pCFMMCTradingAccountKeyRsp, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspCFMMCTradingAccountKey, pCFMMCTradingAccountKeyRsp, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRtnMsgNotify(CUstpFtdcMsgNotifyField * pMsgNotify) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnMsgNotify, pMsgNotify);
};
virtual void OnRtnClientPositionChange(CUstpFtdcClientPositionChangeField * pClientPositionChange) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnClientPositionChange, pClientPositionChange);
};
virtual void OnRtnInvestorAccountChange(CUstpFtdcInvestorAccountChangeField * pInvestorAccountChange) {
mOnRtnEvent(pObject, (int)EnumOnRtnEvent::OnRtnInvestorAccountChange, pInvestorAccountChange);
};
virtual void OnRspQryEnableRtnMoneyPositoinChange(CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQryEnableRtnMoneyPositoinChange, nullptr, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspOrderInsertAccept(CUstpFtdcInputOrderField * pInputOrder, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspOrderInsertAccept, pInputOrder, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspOrderActionAccept(CUstpFtdcOrderActionField * pOrderAction, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspOrderActionAccept, pOrderAction, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQuoteInsertAccept(CUstpFtdcInputQuoteField * pInputQuote, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQuoteInsertAccept, pInputQuote, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQuoteActionAccept(CUstpFtdcQuoteActionField * pQuoteAction, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQuoteActionAccept, pQuoteAction, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspForQuoteAccept(CUstpFtdcReqForQuoteField * pReqForQuote, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspForQuoteAccept, pReqForQuote, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspExecOrderInsertAccept(CUstpFtdcInputExecOrderField * pInputExecOrder, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspExecOrderInsertAccept, pInputExecOrder, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspExecOrderActionAccept(CUstpFtdcInputExecOrderActionField * pInputExecOrderAction, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspExecOrderActionAccept, pInputExecOrderAction, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQueryHisOrder(CUstpFtdcOrderField * pOrder, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQueryHisOrder, pOrder, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspQueryHisTrade(CUstpFtdcTradeField * pTrade, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspQueryHisTrade, pTrade, pRspInfo, nRequestID, bIsLast);
};
virtual void OnRspCurrencyPledge(CUstpFtdcCurrencyPledgeField * pCurrencyPledge, CUstpFtdcRspInfoField * pRspInfo, int nRequestID, bool bIsLast) {
mOnRspEvent(pObject, (int)EnumOnRspEvent::OnRspCurrencyPledge, pCurrencyPledge, pRspInfo, nRequestID, bIsLast);
};
}; // end of class
|
#pragma once
// standard library
// assert
#include <cassert>
// memcpy, memset
#include <cstring>
#include <string>
// user define head
#include "Util.h"
START_NAMESPACE
constexpr int SmallBufferSize = 4000;
constexpr int LargeBufferSize = 4000 * 1000;
template <size_t SIZE>
class LogBuffer {
public:
using cookieFunc = void(*)(void);
LogBuffer() : data_{}, current_(data_) {}
LogBuffer(const LogBuffer& b) : data_{}, current_(data_ + b.length()) {
memcpy(data_, b.data(), b.length());
}
LogBuffer& operator=(const LogBuffer& buffer) {
if (this == &buffer)
return *this;
memcpy(data_, buffer.data_, buffer.length());
current_ = data_ + buffer.length();
return *this;
}
LogBuffer(LogBuffer&&) noexcept = delete;
LogBuffer& operator=(LogBuffer&&) = delete;
~LogBuffer() = default;
/**
* \brief Append contents to the buffer
* \param buf contents
* \param len length of buf
*/
void append(const char* buf, size_t len) {
if (avail() > len) {
memcpy(current_, buf, len);
current_ += len;
}
}
/**
* \brief Get the origin data of this buffer
* \return point to the begin of buffer
*/
const char* data() const { return data_; }
/**
* \brief Length of the current buffer used
* \return unsigned integer
*/
size_t length() const { return current_ - data_; }
/**
* \brief Pointer of the available space, common used as
* write to data_ directly
* \return pointer
*/
// ReSharper disable once CppMemberFunctionMayBeConst
char* current() { return current_; }
/**
* \brief Get number of characters available
* \return unsigned integral type
*/
size_t avail() const { return end() - current_; }
/**
* \brief Set internal position pointer to relative position
* \param len Offset value
*/
void add(size_t len) { current_ += len; }
/**
* \brief Set internal position pointer to beginning of the buffer
*/
void reset() { current_ = data_; }
/**
* \brief clear the buffer, but not change the internal position pointer
*/
void bzero() { memset(data_, 0, sizeof data_); }
/**
* \brief make a copy of this buffer
* \return std::string contains same as this buffer
*/
std::string toString() const { return std::string(data_, length()); }
private:
const char* end() const { return data_ + sizeof data_; }
// define of member
char data_[SIZE];
char* current_;
};
class LogStream {
public:
using reference = LogStream&;
using const_reference = const LogStream&;
using pointer = LogStream*;
using const_pointer = const LogStream*;
using MyBuffer = LogBuffer<SmallBufferSize>;
// formatting built in type
reference operator<<(bool);
reference operator<<(short);
reference operator<<(unsigned short);
reference operator<<(int);
reference operator<<(unsigned int);
reference operator<<(long);
reference operator<<(unsigned long);
reference operator<<(long long);
reference operator<<(unsigned long long);
reference operator<<(float);
reference operator<<(double);
reference operator<<(char);
reference operator<<(const char*);
reference operator<<(const unsigned char*);
// reference operator<<(const void*);
// formatting std::string
reference& operator<<(const std::string& v);
// buffer
reference& operator<<(const MyBuffer& v);
void append(const char* data, size_t len) { buffer_.append(data, len); }
const MyBuffer& buffer() const { return buffer_; }
void resetBuffer() { buffer_.reset(); }
private:
void staticCheck();
template <typename T>
void formatInteger(T);
MyBuffer buffer_;
static const int MaxNumericSize = 32;
};
END_NAMESPACE
|
#include<bits/stdc++.h>
using namespace std;
int solve1(vector<int>& arr,int left,int right,int k)
{
if(left > right)
{
return -1;
}
int mid = (left+right)/2;
if(k > arr[mid])
{
return solve1(arr,mid+1,right,k);
}
else if(k < arr[mid])
{
return solve1(arr,left,mid-1,k);
}
return mid;
}
int solve2(vector<int>& arr,int n,int k)
{
int low = 0;
int high = n-1;
while(low<=high)
{
int mid = (low+high)/2;
if(arr[mid]==k)
{
return mid;
}
else if(k > arr[mid])
{
low = mid+1;
}
else
{
high = mid - 1;
}
}
return -1;
}
int lower_bound(vector<int>& arr,int n,int k)
{
int low = 0;
int high = n-1;
while(low<=high)
{
int mid = (low+high)/2;
if(arr[mid] >= k)
{
high = mid;
}
else
{
low = mid+1;
}
}
return low;
}
int main()
{
int n;
cin >> n;
vector<int> arr(n,0);
for(int i=0;i<n;i++)
{
cin >> arr[i];
}
int k;
cin >> k;
cout << lower_bound(arr,n,k) << endl;
return 0;
}
|
#pragma once
#include <cctype>
#include <cstdint>
#include <string>
#include <thread>
#include "Util.h"
START_NAMESPACE namespace ThisThread {
extern __thread int t_cachedTid;
extern __thread char t_tidString[32];
extern __thread size_t t_tidStringSize;
extern __thread const char* t_threadName;
void cacheTid();
int tid();
const char* tidString();
size_t tidStringLength();
const char* name();
bool isMainThread();
}
END_NAMESPACE
|
/***************************************************************************
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**************************************************************************/
#include "SimpleReSTIR.h"
const int WINDOW_WIDTH = 1920;
const int WINDOW_HEIGHT = 1080;
namespace
{
// Shaders
const char kInitReservoirShader[] = "RenderPasses/SimpleReSTIR/InitReservoir.rt.slang";
const char kSpatialResueShader[] = "RenderPasses/SimpleReSTIR/Reuse.rt.slang";
const char kFinalShader[] = "RenderPasses/SimpleReSTIR/Final.rt.slang";
//Parameters
const char kCandiateCount[] = "CandiateCount";
const char kReservoirPerPixel[] = "ReservoirPerPixel";
const char kUnbiased[] = "Unbiased";
const char kIsSpatialReuse[] = "SpatialReuse";
const char kIsTemporalReuse[] = "TemporalReuse";
const char kNeighborCount[] = "NegihbotCount";
const char kNeighborRange[] = "NeighborRange";
// Input buffer names
const char kInputDiffuse[] = "Diffuse";
const char kInputSpecular[] = "Specular";
const char kInputWorldPosition[] = "WorldPosition";
const char kInputWorldNormal[] = "WorldNormal";
// Output buffer names
const char kOutput[] = "ReSTIROutput";
// Internal buffer names
const char kCurrReservoir[] = "Current Reservoir";
const char kPrevReservoir[] = "Previous Reservoir";
const char kTemporalReservoir[] = "Temporal Reservoir";
const char kSpatialReservoir[] = "Spatial Reservoir";
}
// Don't remove this. it's required for hot-reload to function properly
extern "C" __declspec(dllexport) const char* getProjDir()
{
return PROJECT_DIR;
}
extern "C" __declspec(dllexport) void getPasses(Falcor::RenderPassLibrary& lib)
{
lib.registerClass("CSimpleReSTIR", "ReSTIR Pass", CSimpleReSTIR::create);
}
CSimpleReSTIR::SharedPtr CSimpleReSTIR::create(RenderContext* pRenderContext, const Dictionary& dict)
{
SharedPtr pPass = SharedPtr(new CSimpleReSTIR(dict));
return pPass;
}
CSimpleReSTIR::CSimpleReSTIR(const Dictionary& vDict)
{
for (const auto& [key, value] : vDict)
{
if (key == kCandiateCount) m_CandiateCount = value;
else if (key == kReservoirPerPixel) m_ReservoirPerPixel = value;
else if (key == kUnbiased) m_Unbiased = value;
else if (key == kIsSpatialReuse) m_IsSpatialReuse = value;
else if (key == kIsTemporalReuse) m_IsTemporalReuse = value;
else if (key == kNeighborCount) m_NeighborCount = value;
else if (key == kNeighborRange) m_NeighborRange = value;
else logWarning("Unknown field '" + key + "' in ReSTIRPass dictionary");
}
__prepareShaders();
m_pCurrReservoir = Texture::create2D(WINDOW_WIDTH, WINDOW_HEIGHT, ResourceFormat::RGBA32Float, 8, 1, nullptr, ResourceBindFlags::ShaderResource | ResourceBindFlags::UnorderedAccess);
m_pCurrReservoir->setName("Current Reservior");
m_pPrevReservoir = Texture::create2D(WINDOW_WIDTH, WINDOW_HEIGHT, ResourceFormat::RGBA32Float, 8, 1, nullptr, ResourceBindFlags::ShaderResource | ResourceBindFlags::UnorderedAccess);
m_pPrevReservoir->setName("Previous Reservoir");
m_pSpatailReservoir = Texture::create2D(WINDOW_WIDTH, WINDOW_HEIGHT, ResourceFormat::RGBA32Float, 8, 1, nullptr, ResourceBindFlags::ShaderResource | ResourceBindFlags::UnorderedAccess);
m_pSpatailReservoir->setName("Spatail Reservoir");
m_pTemporalReservoir = Texture::create2D(WINDOW_WIDTH, WINDOW_HEIGHT, ResourceFormat::RGBA32Float, 8, 1, nullptr, ResourceBindFlags::ShaderResource | ResourceBindFlags::UnorderedAccess);
m_pTemporalReservoir->setName("Temporal Reservoir");
}
void CSimpleReSTIR::__prepareShaders()
{
// Init and temporal reuse
{
RtProgram::Desc Desc;
Desc.addShaderLibrary(kInitReservoirShader).addRayGen("rayGen");
Desc.addHitGroup(0, "", "shadowAnyHit").addMiss(0, "shadowMiss");
Desc.setMaxTraceRecursionDepth(1);
m_pInitReservoirProgram = RtProgram::create(Desc, 256);
m_pInitReservoirProgram->addDefine("SAMPLE_GENERATOR_TYPE", "SAMPLE_GENERATOR_UNIFORM");
}
//Spatial reuse
{
RtProgram::Desc Desc;
Desc.addShaderLibrary(kSpatialResueShader).addRayGen("rayGen");
Desc.addHitGroup(0, "", "shadowAnyHit").addMiss(0, "shadowMiss");
Desc.setMaxTraceRecursionDepth(1);
m_pReuseProgram = RtProgram::create(Desc, 256);
m_pReuseProgram->addDefine("SAMPLE_GENERATOR_TYPE", "SAMPLE_GENERATOR_UNIFORM");
}
// Final
{
RtProgram::Desc Desc;
Desc.addShaderLibrary(kFinalShader).addRayGen("rayGen");
Desc.addHitGroup(0, "", "shadowAnyHit").addMiss(0, "shadowMiss");
Desc.setMaxTraceRecursionDepth(1);
m_pFinalProgram = RtProgram::create(Desc, 256);
m_pFinalProgram->addDefine("SAMPLE_GENERATOR_TYPE", "SAMPLE_GENERATOR_UNIFORM");
}
}
void CSimpleReSTIR::__prepareVars()
{
assert(m_pScene);
assert(m_pInitReservoirProgram);
assert(m_pReuseProgram);
assert(m_pFinalProgram);
m_pInitReservoirVars = RtProgramVars::create(m_pInitReservoirProgram, m_pScene);
m_pReuseVars = RtProgramVars::create(m_pReuseProgram, m_pScene);
m_pFinalVars = RtProgramVars::create(m_pFinalProgram, m_pScene);
}
void CSimpleReSTIR::setScene(RenderContext* pRenderContext, const Scene::SharedPtr& pScene)
{
m_pScene = pScene;
if (pScene)
{
m_pInitReservoirProgram->addDefines(m_pScene->getSceneDefines());
m_pReuseProgram->addDefines(m_pScene->getSceneDefines());
m_pFinalProgram->addDefines(m_pScene->getSceneDefines());
}
}
std::string CSimpleReSTIR::getDesc() { return "ReSTIR Pass"; }
Dictionary CSimpleReSTIR::getScriptingDictionary()
{
Dictionary Dict;
Dict[kCandiateCount] = m_CandiateCount;
Dict[kReservoirPerPixel] = m_ReservoirPerPixel;
Dict[kUnbiased] = m_Unbiased;
Dict[kIsSpatialReuse] = m_IsSpatialReuse;
Dict[kIsTemporalReuse] = m_IsTemporalReuse;
Dict[kNeighborCount] = m_NeighborCount;
Dict[kNeighborRange] = m_NeighborRange;
return Dict;
}
RenderPassReflection CSimpleReSTIR::reflect(const CompileData& compileData)
{
// Define the required resources here
RenderPassReflection Reflector;
Reflector.addInput(kInputDiffuse, "Diffuse");
Reflector.addInput(kInputSpecular, "Specular");
Reflector.addInput(kInputWorldPosition, "World Position");
Reflector.addInput(kInputWorldNormal, "World Normal");
Reflector.addInternal(kCurrReservoir, "Current Reservoir").format(ResourceFormat::RGBA32Float).bindFlags(ResourceBindFlags::ShaderResource | ResourceBindFlags::UnorderedAccess).texture2D(WINDOW_WIDTH, WINDOW_HEIGHT, 1, 1, 8);
Reflector.addInternal(kPrevReservoir, "Previous Reservoir").format(ResourceFormat::RGBA32Float).bindFlags(ResourceBindFlags::ShaderResource | ResourceBindFlags::UnorderedAccess).texture2D(WINDOW_WIDTH, WINDOW_HEIGHT, 1, 1, 8);
Reflector.addInternal(kTemporalReservoir, "Temporal Reservoir").format(ResourceFormat::RGBA32Float).bindFlags(ResourceBindFlags::ShaderResource | ResourceBindFlags::UnorderedAccess).texture2D(WINDOW_WIDTH, WINDOW_HEIGHT, 1, 1, 8);
Reflector.addInternal(kSpatialReservoir, "Spatial Reservoir").format(ResourceFormat::RGBA32Float).bindFlags(ResourceBindFlags::ShaderResource | ResourceBindFlags::UnorderedAccess).texture2D(WINDOW_WIDTH, WINDOW_HEIGHT, 1, 1, 8);
Reflector.addOutput(kOutput, "ReSTIROutput").format(ResourceFormat::RGBA32Float).bindFlags(ResourceBindFlags::ShaderResource | ResourceBindFlags::UnorderedAccess);
return Reflector;
}
void CSimpleReSTIR::execute(RenderContext* pRenderContext, const RenderData& renderData)
{
// renderData holds the requested resources
// auto& pTexture = renderData["src"]->asTexture();
Texture::SharedPtr pPos = renderData[kInputWorldPosition]->asTexture();
Texture::SharedPtr pNorm = renderData[kInputWorldNormal]->asTexture();
Texture::SharedPtr pDiff = renderData[kInputDiffuse]->asTexture();
Texture::SharedPtr pSpec = renderData[kInputSpecular]->asTexture();
Texture::SharedPtr pOutput = renderData[kOutput]->asTexture();
Texture::SharedPtr pCurrReservoir = renderData[kCurrReservoir]->asTexture();
Texture::SharedPtr pPrevReservoir = renderData[kPrevReservoir]->asTexture();
Texture::SharedPtr pTemporalReservoir = renderData[kTemporalReservoir]->asTexture();
Texture::SharedPtr pSpatialReservoir = renderData[kSpatialReservoir]->asTexture();
if (m_pScene)
{
m_pScene->update(pRenderContext, gpFramework->getGlobalClock().getTime());
if (!m_pInitReservoirVars || !m_pReuseVars || !m_pFinalVars) __prepareVars();
m_LastCameraMatrix = m_CurrCameraMatrix;
m_CurrCameraMatrix = m_pScene->getCamera()->getViewProjMatrix();
// Init and temporal reuse
static bool IsInit = true;
static uint FrameCount = 0;
m_pInitReservoirVars["PerFrameCB"]["FrameCount"] = FrameCount++;
m_pInitReservoirVars["PerFrameCB"]["IsInitLight"] = IsInit;
m_pInitReservoirVars["PerFrameCB"]["LastCameraMatrix"] = m_LastCameraMatrix;
m_pInitReservoirVars["PerFrameCB"]["CandidateCount"] = m_CandiateCount;
m_pInitReservoirVars["PerFrameCB"]["ReservoirPerPixel"] = m_ReservoirPerPixel;
m_pInitReservoirVars["PerFrameCB"]["IsTemporalReuse"] = m_IsTemporalReuse;
m_pInitReservoirVars["PerFrameCB"]["Unbiased"] = m_Unbiased;
m_pInitReservoirVars["Pos"] = pPos;
m_pInitReservoirVars["Norm"] = pNorm;
m_pInitReservoirVars["Diffuse"] = pDiff;
m_pInitReservoirVars["Specular"] = pSpec;
m_pInitReservoirVars["ReservoirTemporal"] = pTemporalReservoir;;
m_pInitReservoirVars["ReservoirCurr"] = pCurrReservoir;
m_pInitReservoirVars["ReservoirPrev"] = pPrevReservoir;
m_pScene->raytrace(pRenderContext, m_pInitReservoirProgram.get(), m_pInitReservoirVars, uint3(WINDOW_WIDTH, WINDOW_HEIGHT, 1));
IsInit = false;
// Spatial reuse
m_pReuseVars["PerFrameCB"]["IsSpatialReuse"] = m_IsSpatialReuse;
m_pReuseVars["PerFrameCB"]["ReservoirPerPixel"] = m_ReservoirPerPixel;
m_pReuseVars["PerFrameCB"]["NeighborCount"] = m_NeighborCount;
m_pReuseVars["PerFrameCB"]["NeighborsRange"] = m_NeighborRange;
m_pReuseVars["PerFrameCB"]["FrameCount"] = FrameCount;
m_pReuseVars["PerFrameCB"]["Resolution"] = uint2(WINDOW_WIDTH, WINDOW_HEIGHT);
m_pReuseVars["PerFrameCB"]["Unbiased"] = m_Unbiased;
m_pReuseVars["ReservoirTemporal"] = pTemporalReservoir;
m_pReuseVars["ReservoirSpatial"] = pSpatialReservoir;
m_pReuseVars["Pos"] = pPos;
m_pReuseVars["Norm"] = pNorm;
m_pReuseVars["Diffuse"] = pDiff;
m_pReuseVars["Specular"] = pSpec;
m_pScene->raytrace(pRenderContext, m_pReuseProgram.get(), m_pReuseVars, uint3(WINDOW_WIDTH, WINDOW_HEIGHT, 1));
// Final
pRenderContext->clearUAV(m_pPrevReservoir->getUAV().get(), float4(0.0f));
m_pFinalVars["PerFrameCB"]["ReservoirPerPixel"] = m_ReservoirPerPixel;
m_pFinalVars["PerFrameCB"]["Unbiased"] = m_Unbiased;
m_pFinalVars["ReservoirSpatial"] = pSpatialReservoir;
m_pFinalVars["ReservoirPrev"] = pPrevReservoir;
m_pFinalVars["Pos"] = pPos;
m_pFinalVars["Norm"] = pNorm;
m_pFinalVars["Diffuse"] = pDiff;
m_pFinalVars["Specular"] = pSpec;
m_pFinalVars["Output"] = pOutput;
m_pScene->raytrace(pRenderContext, m_pFinalProgram.get(), m_pFinalVars, uint3(WINDOW_WIDTH, WINDOW_HEIGHT, 1));
}
}
void CSimpleReSTIR::renderUI(Gui::Widgets& widget)
{
/*widget.checkbox("Temporal Reuse", m_IsTemporalReuse);
widget.checkbox("Spatail Reuse", m_IsSpatialReuse);
widget.separator();
widget.var<uint32_t>("Candidate", m_CandiateCount, 1u, 32u, 1u);
widget.var<uint32_t>("Reservoir per pixel", m_ReservoirPerPixel, 1u, 8u, 1u);
widget.var<uint32_t>("NeighborCount", m_NeighborCount, 1, 10, 1);
widget.var<float>("Neighbor Reuse Range", m_NeighborRange, 1, 100, 1);
widget.checkbox("Unbiased", m_Unbiased);*/
}
|
#ifndef CSHAPE_H
#define CSHAPE_H
#include "../Header/Angel.h"
#include "TypeDefine.h"
typedef Angel::vec4 color4;
typedef Angel::vec4 point4;
#define FLAT_SHADING 0
#define GOURAUD_SHADING 1
// GPU 的計算必須傳更多的參數進入 Shader
//#define LIGHTING_WITHCPU
#define LIGHTING_WITHGPU
//#define PERVERTEX_LIGHTING
// 當模型有執行 non-uniform scale 的操作時,必須透過計算反矩陣來得到正確的 Normal 方向
// 開啟以下的定義即可,目前 CPU 計算的有提供
// GPU 的部分則是設定成註解
//#define GENERAL_CASE 1
#define SPOT_LIGHT 1
class CShape
{
protected:
vec4 *m_pPoints;
vec3 *m_pNormals;
vec4 *m_pColors;
vec2 *m_pTex;
int m_iNumVtx;
GLfloat m_fColor[4]; // Object's color
// For shaders' name
char *m_pVXshader, *m_pFSshader;
// For VAO
GLuint m_uiVao;
// For Shader
GLuint m_uiModelView, m_uiProjection, m_uiColor;
GLuint m_uiProgram;
GLuint m_uiBuffer;
#ifdef LIGHTING_WITHGPU
//1 2
point4 m_vLightInView, m_vLight2InView; // 光源在世界座標的位置
GLuint m_uiLightInView, m_uiLight2InView; // 光源在 shader 的位置
GLuint m_uiAmbient, m_uiAmbient2; // light's ambient 與 Object's ambient 與 ka 的乘積
GLuint m_uiDiffuse, m_uiDiffuse2; // light's diffuse 與 Object's diffuse 與 kd 的乘積
GLuint m_uiSpecular, m_uiSpecular2; // light's specular 與 Object's specular 與 ks 的乘積
GLuint m_uiShininess, m_uiShininess2;
GLuint m_uiLighting, m_uiLighting2;
LightSource m_Light1, m_Light2;
color4 m_AmbientProduct, m_AmbientProduct2;
color4 m_DiffuseProduct, m_DiffuseProduct2;
color4 m_SpecularProduct, m_SpecularProduct2;
//3 4
point4 m_vLight3InView, m_vLight4InView; // 光源在世界座標的位置
GLuint m_uiLight3InView, m_uiLight4InView; // 光源在 shader 的位置
GLuint m_uiAmbient3, m_uiAmbient4; // light's ambient 與 Object's ambient 與 ka 的乘積
GLuint m_uiDiffuse3, m_uiDiffuse4; // light's diffuse 與 Object's diffuse 與 kd 的乘積
GLuint m_uiSpecular3, m_uiSpecular4; // light's specular 與 Object's specular 與 ks 的乘積
GLuint m_uiShininess3, m_uiShininess4;
GLuint m_uiLighting3, m_uiLighting4;
LightSource m_Light3, m_Light4;
color4 m_AmbientProduct3, m_AmbientProduct4;
color4 m_DiffuseProduct3, m_DiffuseProduct4;
color4 m_SpecularProduct3, m_SpecularProduct4;
int m_iLighting; // 設定是否要打燈
#endif
// For Matrices
mat4 m_mxView, m_mxProjection, m_mxTRS;
mat4 m_mxMVFinal;
mat3 m_mxMV3X3Final, m_mxITMV; // 使用在計算 物體旋轉後的新 Normal
mat3 m_mxITView; // View Matrix 的 Inverse Transport
bool m_bProjUpdated, m_bViewUpdated, m_bTRSUpdated;
// For materials
Material m_Material;
// For Shading Mode
// 0: Flat shading, 1: Gouraud shading, 0 for default
// 要變更上色模式,利用 SetShadingMode 來改變
int m_iMode;
void CreateBufferObject();
void DrawingSetShader();
void DrawingWithoutSetShader();
public:
CShape();
virtual ~CShape();
virtual void Draw() = 0;
virtual void DrawW() = 0; // Drawing without setting shaders
virtual void Update(float dt, point4 vLightPos, color4 vLightI) = 0;
virtual void Update(float dt, const LightSource &Lights) = 0;
virtual void Update(float dt) = 0;
void SetShaderName(const char vxShader[], const char fsShader[]);
void SetShader(GLuint uiShaderHandle = MAX_UNSIGNED_INT);
void SetColor(vec4 vColor);
void SetColor(vec4 vColor,vec4 vColor2);
void SetViewMatrix(mat4 &mat);
void SetProjectionMatrix(mat4 &mat);
void SetTRSMatrix(mat4 &mat);
// For setting materials
void SetMaterials(color4 ambient, color4 diffuse, color4 specular);
void SetKaKdKsShini(float ka, float kd, float ks, float shininess); // ka kd ks shininess
// For Lighting Calculation
void SetShadingMode(int iMode) {m_iMode = iMode;}
vec4 PhongReflectionModel(vec4 vPoint, vec3 vNormal, vec4 vLightPos, color4 vLightI);
vec4 PhongReflectionModel(vec4 vPoint, vec3 vNormal, const LightSource &Lights);
#ifdef LIGHTING_WITHGPU
void SetLightingDisable() {m_iLighting = 0;}
#endif
};
#endif
|
/*
* Author : BurningTiles
* Problem : Digit Pairs
* File : B.cpp
*/
#include <iostream>
using namespace std;
inline int max(int a, int b, int c){
return (a>b && a>c)? a : (b>a && b>c)? b : c;
}
inline int min(int a, int b, int c){
return (a<b && a<c)? a : (b<a && b<c)? b : c;
}
int bitScoreCalc(int n){
int x,y,z;
x = n%10; n /= 10;
y = n%10; n /= 10;
z = n;
return (max(x,y,z)*11 + min(x,y,z)*7)%100;
}
int pairs(int x[],int n){
int temp[]={0,0,0,0,0,0,0,0,0,0}, ans=0;
for(int i=0; i<n; ++i) x[i] /= 10;
for(int i=0; i<n; ++i)
for(int j=i+2; j<n; j+=2)
if(x[i] == x[j])
if(temp[x[i]]<2)
++temp[x[i]];
for(int i=0; i<10; ++i) ans += temp[i];
return ans;
}
int main(){
int n;
cin >> n;
int input[n],bitScore[n];
for(int i=0; i<n; ++i){
cin >> input[i];
bitScore[i] = bitScoreCalc(input[i]);
}
cout << pairs(bitScore,n);
return 0;
}
|
//**************************************************************************
//**
//** See jlquake.txt for copyright info.
//**
//** This program is free software; you can redistribute it and/or
//** modify it under the terms of the GNU General Public License
//** as published by the Free Software Foundation; either version 3
//** of the License, or (at your option) any later version.
//**
//** This program is distributed in the hope that it will be useful,
//** but WITHOUT ANY WARRANTY; without even the implied warranty of
//** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//** included (gnu.txt) GNU General Public License for more details.
//**
//**************************************************************************
#include "../progsvm/progsvm.h"
#include "local.h"
#include "../worldsector.h"
#include "../public.h"
#include "../../common/Common.h"
#include "../../common/common_defs.h"
#include "../../common/strings.h"
#include "../../common/command_buffer.h"
#include "../../common/crc.h"
char qhw_localinfo[ QHMAX_LOCALINFO_STRING + 1 ]; // local game info
func_t qhw_SpectatorConnect;
func_t qhw_SpectatorThink;
func_t qhw_SpectatorDisconnect;
char svqh_localmodels[ BIGGEST_MAX_MODELS ][ 5 ]; // inline model names for precache
// Moves to the next signon buffer if needed
void SVQH_FlushSignon() {
if ( sv.qh_signon.cursize < sv.qh_signon.maxsize - ( GGameType & GAME_HexenWorld ? 100 : 512 ) ) {
return;
}
if ( sv.qh_num_signon_buffers == MAX_SIGNON_BUFFERS - 1 ) {
common->Error( "sv.qh_num_signon_buffers == MAX_SIGNON_BUFFERS-1" );
}
sv.qh_signon_buffer_size[ sv.qh_num_signon_buffers - 1 ] = sv.qh_signon.cursize;
sv.qh_signon._data = sv.qh_signon_buffers[ sv.qh_num_signon_buffers ];
sv.qh_num_signon_buffers++;
sv.qh_signon.cursize = 0;
}
int SVQH_ModelIndex( const char* name ) {
if ( !name || !name[ 0 ] ) {
return 0;
}
int i;
for ( i = 0; i < ( GGameType & GAME_Hexen2 ? MAX_MODELS_H2 : MAX_MODELS_Q1 ) && sv.qh_model_precache[ i ]; i++ ) {
if ( !String::Cmp( sv.qh_model_precache[ i ], name ) ) {
return i;
}
}
if ( i == ( GGameType & GAME_Hexen2 ? MAX_MODELS_H2 : MAX_MODELS_Q1 ) || !sv.qh_model_precache[ i ] ) {
if ( GGameType & GAME_Hexen2 && !( GGameType & GAME_HexenWorld ) ) {
common->Printf( "SVQH_ModelIndex: model %s not precached\n", name );
return 0;
}
common->Error( "SVQH_ModelIndex: model %s not precached", name );
}
return i;
}
// Entity baselines are used to compress the update messages
// to the clients -- only the fields that differ from the
// baseline will be transmitted
static void SVQH_CreateBaseline() {
for ( int entnum = 0; entnum < sv.qh_num_edicts; entnum++ ) {
qhedict_t* svent = QH_EDICT_NUM( entnum );
if ( svent->free ) {
continue;
}
// create baselines for all player slots,
// and any other edict that has a visible model
if ( entnum > ( GGameType & ( GAME_QuakeWorld | GAME_HexenWorld ) ? MAX_CLIENTS_QHW : svs.qh_maxclients ) && !svent->v.modelindex ) {
continue;
}
//
// create entity baseline
//
if ( GGameType & GAME_Quake ) {
VectorCopy( svent->GetOrigin(), svent->q1_baseline.origin );
VectorCopy( svent->GetAngles(), svent->q1_baseline.angles );
svent->q1_baseline.frame = svent->GetFrame();
svent->q1_baseline.skinnum = svent->GetSkin();
if ( entnum > 0 && entnum <= ( GGameType & GAME_QuakeWorld ? MAX_CLIENTS_QHW : svs.qh_maxclients ) ) {
svent->q1_baseline.colormap = entnum;
svent->q1_baseline.modelindex = SVQH_ModelIndex( "progs/player.mdl" );
} else {
svent->q1_baseline.colormap = 0;
svent->q1_baseline.modelindex =
SVQH_ModelIndex( PR_GetString( svent->GetModel() ) );
}
} else {
VectorCopy( svent->GetOrigin(), svent->h2_baseline.origin );
VectorCopy( svent->GetAngles(), svent->h2_baseline.angles );
svent->h2_baseline.frame = svent->GetFrame();
svent->h2_baseline.skinnum = svent->GetSkin();
svent->h2_baseline.scale = ( int )( svent->GetScale() * 100.0 ) & 255;
svent->h2_baseline.drawflags = svent->GetDrawFlags();
svent->h2_baseline.abslight = ( int )( svent->GetAbsLight() * 255.0 ) & 255;
if ( entnum > 0 && entnum <= ( GGameType & GAME_HexenWorld ? MAX_CLIENTS_QHW : svs.qh_maxclients ) ) {
svent->h2_baseline.colormap = entnum;
svent->h2_baseline.modelindex = GGameType & GAME_HexenWorld ? SVQH_ModelIndex( "models/paladin.mdl" ) : 0;
} else {
svent->h2_baseline.colormap = 0;
svent->h2_baseline.modelindex =
SVQH_ModelIndex( PR_GetString( svent->GetModel() ) );
}
if ( !( GGameType & GAME_HexenWorld ) ) {
Com_Memset( svent->h2_baseline.ClearCount, 99, sizeof ( svent->h2_baseline.ClearCount ) );
}
}
//
// flush the signon message out to a seperate buffer if
// nearly full
//
if ( GGameType & ( GAME_QuakeWorld | GAME_HexenWorld ) ) {
SVQH_FlushSignon();
}
//
// add to the message
//
if ( GGameType & GAME_Quake ) {
sv.qh_signon.WriteByte( q1svc_spawnbaseline );
sv.qh_signon.WriteShort( entnum );
sv.qh_signon.WriteByte( svent->q1_baseline.modelindex );
sv.qh_signon.WriteByte( svent->q1_baseline.frame );
sv.qh_signon.WriteByte( svent->q1_baseline.colormap );
sv.qh_signon.WriteByte( svent->q1_baseline.skinnum );
for ( int i = 0; i < 3; i++ ) {
sv.qh_signon.WriteCoord( svent->q1_baseline.origin[ i ] );
sv.qh_signon.WriteAngle( svent->q1_baseline.angles[ i ] );
}
} else {
sv.qh_signon.WriteByte( h2svc_spawnbaseline );
sv.qh_signon.WriteShort( entnum );
sv.qh_signon.WriteShort( svent->h2_baseline.modelindex );
sv.qh_signon.WriteByte( svent->h2_baseline.frame );
sv.qh_signon.WriteByte( svent->h2_baseline.colormap );
sv.qh_signon.WriteByte( svent->h2_baseline.skinnum );
sv.qh_signon.WriteByte( svent->h2_baseline.scale );
sv.qh_signon.WriteByte( svent->h2_baseline.drawflags );
sv.qh_signon.WriteByte( svent->h2_baseline.abslight );
for ( int i = 0; i < 3; i++ ) {
sv.qh_signon.WriteCoord( svent->h2_baseline.origin[ i ] );
sv.qh_signon.WriteAngle( svent->h2_baseline.angles[ i ] );
}
}
}
}
// Grabs the current state of the progs serverinfo flags
// and each client for saving across the
// transition to another level
void SVQH_SaveSpawnparms() {
if ( GGameType & ( GAME_QuakeWorld | GAME_HexenWorld ) && !sv.state ) {
return; // no progs loaded yet
}
// serverflags is the only game related thing maintained
svs.qh_serverflags = *pr_globalVars.serverflags;
if ( GGameType & GAME_Hexen2 && !( GGameType & GAME_HexenWorld ) ) {
return;
}
client_t* host_client = svs.clients;
for ( int i = 0; i < ( GGameType & ( GAME_QuakeWorld | GAME_HexenWorld ) ? MAX_CLIENTS_QHW : svs.qh_maxclients ); i++, host_client++ ) {
if ( host_client->state != CS_ACTIVE ) {
continue;
}
if ( GGameType & ( GAME_QuakeWorld | GAME_HexenWorld ) ) {
// needs to reconnect
host_client->state = CS_CONNECTED;
}
// call the progs to get default spawn parms for the new client
*pr_globalVars.self = EDICT_TO_PROG( host_client->qh_edict );
PR_ExecuteProgram( *pr_globalVars.SetChangeParms );
for ( int j = 0; j < NUM_SPAWN_PARMS; j++ ) {
host_client->qh_spawn_parms[ j ] = pr_globalVars.parm1[ j ];
}
}
}
static unsigned SVQW_CheckModel( const char* mdl ) {
idList<byte> buffer;
FS_ReadFile( mdl, buffer );
return CRC_Block( buffer.Ptr(), buffer.Num() );
}
static void SVQHW_AddProgCrcTotheServerInfo() {
char num[ 32 ];
sprintf( num, "%i", pr_crc );
Info_SetValueForKey( svs.qh_info, "*progs", num, MAX_SERVERINFO_STRING, 64, 64, !svqh_highchars->value );
}
static void SVQHW_FindSpectatorFunctions() {
qhw_SpectatorConnect = qhw_SpectatorThink = qhw_SpectatorDisconnect = 0;
dfunction_t* f;
if ( ( f = ED_FindFunction( "SpectatorConnect" ) ) != NULL ) {
qhw_SpectatorConnect = ( func_t )( f - pr_functions );
}
if ( ( f = ED_FindFunction( "SpectatorThink" ) ) != NULL ) {
qhw_SpectatorThink = ( func_t )( f - pr_functions );
}
if ( ( f = ED_FindFunction( "SpectatorDisconnect" ) ) != NULL ) {
qhw_SpectatorDisconnect = ( func_t )( f - pr_functions );
}
}
// Tell all the clients that the server is changing levels
static void SVQH_SendReconnect() {
byte data[ 128 ];
QMsg msg;
msg.InitOOB( data, sizeof ( data ) );
msg.WriteChar( GGameType & GAME_Hexen2 ? h2svc_stufftext : q1svc_stufftext );
msg.WriteString2( "reconnect\n" );
NET_SendToAll( &msg, 5 );
if ( !com_dedicated->integer ) {
Cmd_ExecuteString( "reconnect\n" );
}
}
// Change the server to a new map, taking all connected
// clients along with it.
// This is called at the start of each level
void SVQH_SpawnServer( const char* server, const char* startspot ) {
qhedict_t* ent;
int i;
if ( !( GGameType & ( GAME_QuakeWorld | GAME_HexenWorld ) ) ) {
// let's not have any servers with no name
if ( !sv_hostname || sv_hostname->string[ 0 ] == 0 ) {
Cvar_Set( "hostname", "UNNAMED" );
}
}
common->DPrintf( "SpawnServer: %s\n",server );
if ( GGameType & GAME_Hexen2 && !( GGameType & GAME_HexenWorld ) && svs.qh_changelevel_issued ) {
SVH2_SaveGamestate( true );
}
if ( GGameType & GAME_Quake && !( GGameType & GAME_QuakeWorld ) ) {
svs.qh_changelevel_issued = false; // now safe to issue another
}
if ( !( GGameType & ( GAME_QuakeWorld | GAME_HexenWorld ) ) ) {
//
// tell all connected clients that we are going to a new level
//
if ( sv.state != SS_DEAD ) {
SVQH_SendReconnect();
}
//
// make cvars consistant
//
if ( svqh_coop->value ) {
Cvar_SetValue( "deathmatch", 0 );
}
svqh_current_skill = ( int )( qh_skill->value + 0.5 );
if ( svqh_current_skill < 0 ) {
svqh_current_skill = 0;
}
if ( GGameType & GAME_Quake && svqh_current_skill > 3 ) {
svqh_current_skill = 3;
}
if ( GGameType & GAME_Hexen2 && svqh_current_skill > 4 ) {
svqh_current_skill = 4;
}
Cvar_SetValue( "skill", ( float )svqh_current_skill );
} else {
SVQH_SaveSpawnparms();
svs.spawncount++; // any partially connected client will be
// restarted
sv.state = SS_DEAD;
}
SVQH_FreeMemory();
// wipe the entire per-level structure
Com_Memset( &sv, 0, sizeof ( sv ) );
if ( GGameType & ( GAME_QuakeWorld | GAME_HexenWorld ) ) {
sv.qh_datagram.InitOOB( sv.qh_datagramBuffer, GGameType & GAME_HexenWorld ? MAX_DATAGRAM_HW : MAX_DATAGRAM_QW );
sv.qh_datagram.allowoverflow = true;
sv.qh_reliable_datagram.InitOOB( sv.qh_reliable_datagramBuffer, GGameType & GAME_HexenWorld ? MAX_MSGLEN_HW : MAX_MSGLEN_QW );
sv.multicast.InitOOB( sv.multicastBuffer, GGameType & GAME_HexenWorld ? MAX_MSGLEN_HW : MAX_MSGLEN_QW );
sv.qh_signon.InitOOB( sv.qh_signon_buffers[ 0 ], GGameType & GAME_HexenWorld ? MAX_DATAGRAM_HW : MAX_DATAGRAM_QW );
sv.qh_num_signon_buffers = 1;
}
String::Cpy( sv.name, server );
if ( GGameType & GAME_Hexen2 && startspot ) {
String::Cpy( sv.h2_startspot, startspot );
}
// load progs to get entity field count
// which determines how big each edict is
PR_LoadProgs();
if ( GGameType & ( GAME_QuakeWorld | GAME_HexenWorld ) ) {
SVQHW_AddProgCrcTotheServerInfo();
SVQHW_FindSpectatorFunctions();
}
// allocate edicts
if ( GGameType & GAME_Hexen2 && !( GGameType & GAME_HexenWorld ) ) {
Com_Memset( sv.h2_Effects, 0, sizeof ( sv.h2_Effects ) );
sv.h2_states = ( h2client_state2_t* )Mem_ClearedAlloc( svs.qh_maxclients * sizeof ( h2client_state2_t ) );
}
sv.qh_edicts = ( qhedict_t* )Mem_ClearedAlloc( MAX_EDICTS_QH * pr_edict_size );
if ( !( GGameType & ( GAME_QuakeWorld | GAME_HexenWorld ) ) ) {
//JL WTF????
sv.qh_datagram.InitOOB( sv.qh_datagramBuffer, GGameType & GAME_Hexen2 ? MAX_MSGLEN_H2 : MAX_DATAGRAM_QH );
sv.qh_reliable_datagram.InitOOB( sv.qh_reliable_datagramBuffer, GGameType & GAME_Hexen2 ? MAX_MSGLEN_H2 : MAX_DATAGRAM_QH );
sv.qh_signon.InitOOB( sv.qh_signonBuffer, GGameType & GAME_Hexen2 ? MAX_MSGLEN_H2 : MAX_MSGLEN_Q1 );
}
// leave slots at start for clients only
sv.qh_num_edicts = ( GGameType & ( GAME_QuakeWorld | GAME_HexenWorld ) ? MAX_CLIENTS_QHW : svs.qh_maxclients ) + 1 + ( GGameType & GAME_Hexen2 ? max_temp_edicts->integer : 0 );
for ( i = 0; i < ( GGameType & ( GAME_QuakeWorld | GAME_HexenWorld ) ? MAX_CLIENTS_QHW : svs.qh_maxclients ); i++ ) {
ent = QH_EDICT_NUM( i + 1 );
svs.clients[ i ].qh_edict = ent;
if ( GGameType & GAME_Hexen2 && !( GGameType & GAME_HexenWorld ) ) {
svs.clients[ i ].h2_send_all_v = true;
}
if ( GGameType & GAME_Hexen2 && !( GGameType & GAME_HexenWorld ) ) {
//ZOID - make sure we update frags right
svs.clients[ i ].qh_old_frags = 0;
}
}
if ( GGameType & GAME_Hexen2 && !( GGameType & GAME_HexenWorld ) ) {
for ( i = 0; i < max_temp_edicts->value; i++ ) {
ent = QH_EDICT_NUM( i + svs.qh_maxclients + 1 );
ED_ClearEdict( ent );
ent->free = true;
ent->freetime = -999;
}
}
if ( !( GGameType & ( GAME_QuakeWorld | GAME_HexenWorld ) ) ) {
sv.qh_paused = false;
}
sv.qh_time = 1000;
String::Cpy( sv.name, server );
sprintf( sv.qh_modelname,"maps/%s.bsp", server );
CM_LoadMap( sv.qh_modelname, false, NULL );
//
// clear physics interaction links
//
SV_ClearWorld();
sv.qh_sound_precache[ 0 ] = PR_GetString( 0 );
sv.qh_model_precache[ 0 ] = PR_GetString( 0 );
sv.qh_model_precache[ 1 ] = sv.qh_modelname;
sv.models[ 1 ] = 0;
for ( i = 1; i < CM_NumInlineModels(); i++ ) {
sv.qh_model_precache[ 1 + i ] = svqh_localmodels[ i ];
sv.models[ i + 1 ] = CM_InlineModel( i );
}
if ( GGameType & GAME_QuakeWorld ) {
//check player/eyes models for hacks
sv.qw_model_player_checksum = SVQW_CheckModel( "progs/player.mdl" );
sv.qw_eyes_player_checksum = SVQW_CheckModel( "progs/eyes.mdl" );
}
//
// spawn the rest of the entities on the map
//
// precache and static commands can be issued during
// map initialization
sv.state = SS_LOADING;
ent = QH_EDICT_NUM( 0 );
Com_Memset( &ent->v, 0, progs->entityfields * 4 );
ent->free = false;
ent->SetModel( PR_SetString( sv.qh_modelname ) );
ent->v.modelindex = 1; // world model
ent->SetSolid( QHSOLID_BSP );
ent->SetMoveType( QHMOVETYPE_PUSH );
if ( !( GGameType & ( GAME_QuakeWorld | GAME_HexenWorld ) ) ) {
if ( svqh_coop->value ) {
*pr_globalVars.coop = svqh_coop->value;
} else {
*pr_globalVars.deathmatch = svqh_deathmatch->value;
}
}
*pr_globalVars.mapname = PR_SetString( sv.name );
// serverflags are for cross level information (sigils)
*pr_globalVars.serverflags = svs.qh_serverflags;
if ( GGameType & GAME_Hexen2 ) {
*pr_globalVars.startspot = PR_SetString( sv.h2_startspot );
*pr_globalVars.randomclass = h2_randomclass->value;
}
if ( GGameType & GAME_HexenWorld ) {
if ( svqh_coop->value ) {
Cvar_SetValue( "deathmatch", 0 );
}
*pr_globalVars.coop = svqh_coop->value;
*pr_globalVars.deathmatch = svqh_deathmatch->value;
*pr_globalVars.damageScale = hw_damageScale->value;
*pr_globalVars.shyRespawn = hw_shyRespawn->value;
*pr_globalVars.spartanPrint = hw_spartanPrint->value;
*pr_globalVars.meleeDamScale = hw_meleeDamScale->value;
*pr_globalVars.manaScale = hw_manaScale->value;
*pr_globalVars.tomeMode = hw_tomeMode->value;
*pr_globalVars.tomeRespawn = hw_tomeRespawn->value;
*pr_globalVars.w2Respawn = hw_w2Respawn->value;
*pr_globalVars.altRespawn = hw_altRespawn->value;
*pr_globalVars.fixedLevel = hw_fixedLevel->value;
*pr_globalVars.autoItems = hw_autoItems->value;
*pr_globalVars.dmMode = hw_dmMode->value;
*pr_globalVars.easyFourth = hw_easyFourth->value;
*pr_globalVars.patternRunner = hw_patternRunner->value;
*pr_globalVars.max_players = sv_maxclients->value;
sv.hw_current_skill = ( int )( qh_skill->value + 0.5 );
if ( sv.hw_current_skill < 0 ) {
sv.hw_current_skill = 0;
}
if ( sv.hw_current_skill > 3 ) {
sv.hw_current_skill = 3;
}
Cvar_SetValue( "skill", ( float )sv.hw_current_skill );
}
if ( GGameType & ( GAME_QuakeWorld | GAME_HexenWorld ) ) {
// run the frame start qc function to let progs check cvars
SVQH_ProgStartFrame();
}
// load and spawn all other entities
ED_LoadFromFile( CM_EntityString() );
// look up some model indexes for specialized message compression
if ( GGameType & GAME_QuakeWorld ) {
SVQW_FindModelNumbers();
}
if ( GGameType & GAME_HexenWorld ) {
SVHW_FindModelNumbers();
}
// all spawning is completed, any further precache statements
// or prog writes to the signon message are errors
sv.state = SS_GAME;
// save movement vars
SVQH_SetMoveVars();
// run two frames to allow everything to settle
if ( GGameType & ( GAME_QuakeWorld | GAME_HexenWorld ) ) {
SVQH_RunPhysicsForTime( svs.realtime * 0.001 );
SVQH_RunPhysicsForTime( svs.realtime * 0.001 );
} else {
SVQH_RunPhysicsAndUpdateTime( 0.1, svs.realtime * 0.001 );
SVQH_RunPhysicsAndUpdateTime( 0.1, svs.realtime * 0.001 );
}
// create a baseline for more efficient communications
SVQH_CreateBaseline();
if ( GGameType & ( GAME_QuakeWorld | GAME_HexenWorld ) ) {
sv.qh_signon_buffer_size[ sv.qh_num_signon_buffers - 1 ] = sv.qh_signon.cursize;
Info_SetValueForKey( svs.qh_info, "map", sv.name, MAX_SERVERINFO_STRING, 64, 64, !svqh_highchars->value );
}
if ( !( GGameType & ( GAME_QuakeWorld | GAME_HexenWorld ) ) ) {
// send serverinfo to all connected clients
client_t* client = svs.clients;
for ( i = 0; i < svs.qh_maxclients; i++, client++ ) {
if ( client->state >= CS_CONNECTED ) {
SVQH_SendServerinfo( client );
}
}
}
if ( GGameType & GAME_Hexen2 ) {
svs.qh_changelevel_issued = false; // now safe to issue another
}
common->DPrintf( "Server spawned.\n" );
}
|
#include <gtest/gtest.h>
#include "../engine/tasking/tasking.h"
#include "../engine/tasking/atomic_counter.h"
#include <chrono>
#include <thread>
#include <stdlib.h>
namespace tna
{
constexpr uint32_t num_threads = 1;
/**
* Creates one asynchronous task per thread, where each task stores its therad id in the
* result array
* */
TEST(TaskingTest, SimpleAsycTaskTest) {
uint32_t* result = new uint32_t[num_threads];
// Starts Thread Pool
tasking_start_thread_pool(num_threads);
// Create tasks
atomic_counter_t syncCounter;
atomic_counter_init(&syncCounter);
for(uint32_t i = 0; i < num_threads; ++i) {
task_t task;
task.p_fp = [] (void * arg){
int32_t* result = reinterpret_cast<int32_t*>(arg);
*result=tasking_get_current_thread_id();
};
task.p_args = &result[i];
tasking_execute_task_async(i, task, &syncCounter,"test", "test");
}
// Synchronize with the running tasks
atomic_counter_join(&syncCounter);
atomic_counter_release(&syncCounter);
// Stops thread pool
tasking_stop_thread_pool();
// Checks the results
for(uint32_t i = 0; i < num_threads; ++i) {
ASSERT_TRUE(result[i] == i);
}
delete [] result;
}
/**
* This test tests the use of lightweight threads tasks by soring an array
* recursively using merge sort. First, two tasks are spawned and sent to the
* tasking library. Each of these two tasks is in charge of soring half of the.
* Each task recursively spawns a task to sort half of its input array part
* until a length of 2 is achieved. When backtracking, each task merges the two
* parts sorted by its two spawned sub-tasks and continues to backtrack, until
* the main thread is reached, which performes the last merging to return the
* finally sorted array
*/
struct Params{
int32_t m_begin;
int32_t m_end;
int32_t* m_inputArray;
int32_t* m_workArray;
};
void mergeArrays(int32_t* array, int32_t* workArray, int32_t begin, int32_t end) {
int32_t splitPoint = (end - begin) / 2 + begin;
int32_t i = begin;
int32_t j = splitPoint;
for (int k = begin; k < end; ++k) {
if (i < splitPoint && (j >= end || array[i] <= array[j])) {
workArray[k] = array[i];
i = i + 1;
} else {
workArray[k] = array[j];
j = j + 1;
}
}
for (int k = begin; k < end; ++k) {
array[k] = workArray[k];
}
}
/**
* @brief Recursive function that creates two tasks and each sorts one half of
* the array. This function is executed in the lightweight threads of the
* tasking library.
*
* @param inputArray The array to sort
* @param length The length of the array to sort
*/
void mergeSort(void* args) {
Params* params = reinterpret_cast<Params*>(args);
if(params->m_end - params->m_begin > 2) {
printf("THREAD ID: %d BEGIN: %d END: %d SORTS\n", tasking_get_current_thread_id(), params->m_begin, params->m_end);
int32_t splitPoint = (params->m_end - params->m_begin) / 2 + params->m_begin;
Params leftParams{params->m_begin, splitPoint, params->m_inputArray, params->m_workArray};
Params rightParams{splitPoint, params->m_end, params->m_inputArray, params->m_workArray};
atomic_counter_t counter;
atomic_counter_init(&counter);
task_t task_left;
task_left.p_fp = mergeSort;
task_left.p_args = &leftParams;
tasking_execute_task_async(tasking_get_current_thread_id(), task_left, &counter,"","");
task_t task_right;
task_right.p_fp = mergeSort;
task_right.p_args = &rightParams;
tasking_execute_task_async(tasking_get_current_thread_id(), task_right, &counter, "", "");
atomic_counter_join(&counter);
atomic_counter_release(&counter);
printf("THREAD ID: %d BEGIN: %d END: %d MERGES\n", tasking_get_current_thread_id(), params->m_begin, params->m_end);
mergeArrays(params->m_inputArray, params->m_workArray, params->m_begin, params->m_end);
}
else
{
if(params->m_inputArray[params->m_begin] > params->m_inputArray[params->m_end-1])
{
params->m_workArray[params->m_begin] = params->m_inputArray[params->m_end-1];
params->m_workArray[params->m_end-1] = params->m_inputArray[params->m_begin];
}
else
{
params->m_workArray[params->m_begin] = params->m_inputArray[params->m_begin];
params->m_workArray[params->m_end-1] = params->m_inputArray[params->m_end-1];
}
params->m_inputArray[params->m_begin] = params->m_workArray[params->m_begin];
params->m_inputArray[params->m_end-1] = params->m_workArray[params->m_end-1];
}
};
/**
* @brief Starts the sorting procedure by spawning two tasks, each sorts half of
* the array, and then merges. This method is executed in the main thread.
*
* @param inputArray The array to sort
* @param length The length of the array to sort
*/
void mergeSortStart(int32_t* inputArray, int32_t length) {
int32_t* workArray = new int32_t[length];
Params leftParams{0, length/2, inputArray, workArray};
Params rightParams{length/2, length, inputArray, workArray};
atomic_counter_t counter;
atomic_counter_init(&counter);
task_t task_left;
task_left.p_fp = mergeSort;
task_left.p_args = &leftParams;
tasking_execute_task_async(0, task_left, &counter, "", "");
task_t task_right;
task_right.p_fp = mergeSort;
task_right.p_args = &rightParams;
tasking_execute_task_async(1, task_right, &counter, "", "");
atomic_counter_join(&counter);
atomic_counter_release(&counter);
mergeArrays(inputArray, workArray, 0, length);
delete [] workArray;
}
/*TEST(TaskingTest, ParallelSortTest) {
start_thread_pool(2);
int32_t arrayLength = 4;
int32_t* array = new int32_t[arrayLength];
for (int i = 0; i < arrayLength; ++i) {
array[i] = rand() % 10000;
}
mergeSortStart(array, arrayLength);
for (int32_t i = 1; i < arrayLength; ++i) {
ASSERT_TRUE(array[i] >= array[i-1]);
}
delete [] array;
stop_thread_pool();
}*/
} /* tna */
int main(int argc, char* argv[]){
::testing::InitGoogleTest(&argc,argv);
int ret = RUN_ALL_TESTS();
return ret;
}
|
#include "Person.h"
#include <iostream>
using namespace std;
#include <string.h>
Person::Person(int day, int month, int year, char* name){
Inicializate(day, month, year, name);
}
Person::Person(){
Inicializate(0, 0, 0);
}
void Person::Inicializate(int day, int month, int year, char* name){
this->day = day;
this->month = month;
this->year = year;
this->age = 0;
strcpy(this->name, name);
}
int Person::calcAge(int day, int month, int year){
age = year - this->year;
if(this->month > month)
age--;
else if(this->month == month && this->day > day)
age--;
return age;
}
void Person::printAge(){
cout << this->name << " would have " << age << endl;
}
|
#include "notepadwindow.h"
#include "notepad.h"
#include <QAction>
#include <QMenu>
#include <QMenuBar>
#include <QToolBar>
#include <QStyle>
NotepadWindow::NotepadWindow() {
auto notepad = new Notepad; setCentralWidget(notepad);
auto menu = menuBar()->addMenu(tr("&File")); // QMenu*
auto open_act = menu->addAction(tr("&Open")); // QAction*
auto save_act = menu->addAction(tr("&Save"));
menu->addSeparator();
auto exit_act = menu->addAction(tr("E&xit"));
open_act->setIcon(style()->standardIcon(QStyle::SP_DialogOpenButton));
save_act->setIcon(style()->standardIcon(QStyle::SP_DialogSaveButton));
exit_act->setIcon(style()->standardIcon(QStyle::SP_DialogCloseButton));
auto tools = addToolBar(tr("&File")); // QToolBar*
tools->addAction(open_act);
tools->addAction(save_act);
tools->addSeparator();
tools->addAction(exit_act);
connect(open_act, &QAction::triggered, notepad, &Notepad::open);
connect(save_act, &QAction::triggered, notepad, &Notepad::save);
connect(exit_act, &QAction::triggered, notepad, &Notepad::exit);
}
NotepadWindow::~NotepadWindow() {
}
|
#ifndef _List_h_
#define _List_h_
class PCB;
class PCBList{
private:
struct Elem{
PCB* pcb;
Elem* next;
Elem(PCB* pcb_):pcb(pcb_){
next=0;
}
};
Elem* first;
Elem* last;
public:
PCBList();
~PCBList();
void insert(PCB* pcb);
PCB* removeFirst();
PCB* remove(PCB* pcb);
};
class PCBListTime{
private:
struct Elem{
PCB* pcb;
Elem* next;
int time;
Elem(PCB* pcb_, int t):pcb(pcb_){
time=t;
next=0;
}
};
Elem* first;
Elem* last;
public:
PCBListTime();
~PCBListTime();
void insert(PCB* pcb, int time);
PCB* removeFirst();
PCB* remove(PCB* pcb);
void update();
};
#endif
|
class Solution {
public:
int missingNumber(vector<int>& nums) {
int x = 0;
for(int i = 0; i < nums.size(); i++) x = x^i^nums[i];
x ^= nums.size();
return x;
}
};
|
/**
* MeterFeeder Library
*
* by fp2.dev
*/
#pragma once
#include <string>
#include "ftd2xx/ftd2xx.h"
#include "constants.h"
namespace MeterFeeder {
/**
* A Mind-Enabled Device MMI (mind-matter interaction) generator.
* It's a USB device that is a quantum random number generator.
* The measurement of entropy (randomness) is based on the quantum
* tunneling effect in the transistors on the onboard FTDI chip.
* Onboard or computer-side post-processing methods like majority voting
* and bias amplification can help boost th effect size of the
* postulated idea that mental thought (intention) can have a
* measurable effect on the the output of the random numbers.
*/
class Generator {
public:
Generator(char* serialNumber, char* description, FT_HANDLE handle);
/**
* Get the generator's serial number. E.g. "QWR4A003"
*
* @return The serial number of the generator device.
*/
std::string GetSerialNumber();
/**
* Get the generator's description. E.g. "MED100K 100 kHz v1.0"
*
* @return The description of the generator device.
*/
std::string GetDescription();
/**
* Get the handle for interacting with the generator.
*
* @return The FT_HANDLE for specifying this device.
*/
FT_HANDLE GetHandle();
/**
* Send command to start streaming.
*
* @return MF_DEVICE_ERROR on error communicating with the generator.
*/
int Stream();
/**
* Read in the streamed entropy.
*
* @param Pointer to where to store the streamed data (the random number).
*
* @return MF_DEVICE_ERROR on error communicating with the generator.
*/
int Read(UCHAR* dxData);
/**
* Close the generator.
*/
void Close();
private:
std::string serialNumber_;
std::string description_;
FT_HANDLE ftHandle_;
};
}
|
//The following program computes
//the probability for dice possibilities
#include <iostream>
#include <random>
#include <ctime>
using namespace std;
const int sides = 6;
int main(void){
const int n_dice = 2;
uniform_int_distribution<unsigned> u(1,6);
default_random_engine e(time(0));
cout << "\nEnter number of trials: ";
int trials;cin >> trials; //compare to scanf
int* outcomes = new int[n_dice * sides +1];
for (int j = 0; j < trials; ++j) {
int roll = 0;
for (int k = 1; k <= n_dice; ++k) {
roll += u(e);
}
outcomes[roll]++;
}
cout << "probability\n";
for (int j = 2; j < n_dice * sides + 1; ++j)
cout << "j = " << j << " p = "
<< static_cast<double>(outcomes[j])/trials
<< endl;}
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int m,n,i,b;
cin>>n;
int a[n];
for(i=0;i<n;i++)
{
cin>>a[i];
}
if(n%2)
{
if(a[0]%2 and a[n-1]%2)
{
cout<<"Yes"<<endl;
}
else cout<<"No"<<endl;
}
else cout<<"No"<<endl;
}
|
#include <memory>
#include <list>
#include <string>
#include <map>
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/nonfree/nonfree.hpp>
#include "../LibGuessSignature/GuessEvalEasy.h"
#include "../LibGuessSignature/GuessSvmOneVsAll.h"
#include "../LibGuessSignature/GuessSvmOneVsOne.h"
#include "files.h"
using namespace std;
using namespace cv;
using namespace Signature;
using namespace CVUtil::ReadWrite;
list<Image::Conclusive > train_images;
map<string, list<Image::Candidate> > query_image_by_name;
void loadImages(bool train, bool query)
{
map<string, list<pair<int, string> > > file_by_name;
int number_of_images = sizeof(file_info)/sizeof(*file_info);
for (int i=0; i<number_of_images; i++) {
string file_name = string(path) + string(file_info[i][0]);
for (int j=0; j<2; j++)
{
string name(file_info[i][j+1]);
file_by_name[name].push_back(make_pair(j, file_name));
}
}
pair<string, Mat> last_loaded;
for (const auto& image_group : file_by_name) {
string name = image_group.first;
unsigned int i=0;
if (image_group.second.size() < 3) continue;
if (name == ".") continue;
for (const auto& file_name_group : image_group.second)
{
const auto type = file_name_group.first;
const auto file_name = file_name_group.second;
bool add_train = train && (i != 0);
bool add_query = query && (i == 0);
i++;
Mat img_loaded;
if ((add_train || add_query) && last_loaded.first != file_name)
{
if (true)
{
img_loaded = imread(file_name, 0);//モノクロ
threshold(img_loaded, img_loaded, 210, 255, THRESH_BINARY);//二値化
} else {
img_loaded = imread(file_name);
}
last_loaded = make_pair(file_name, img_loaded);
} else {
img_loaded = last_loaded.second;
}
Mat img_trim ;
if (add_train || add_query)
img_trim = Mat(img_loaded, trim_area[type]).clone();
if (add_train)
train_images.push_back(Image::Conclusive(img_trim, name, file_name));
if (add_query)
query_image_by_name[name].push_back(Image::Candidate(img_trim, file_name));
}
}
}
int main()
{
#ifdef _DEBUG
unsigned int k = 10;
#else
unsigned int k = 100;
#endif
#if 1
Guess::EvalEasy trainer;
#elif 1
Guess::SvmOneVsAll trainer(k);
#elif 1
Guess::SvmOneVsOne trainer(k);
#endif
if (0)
{
loadImages(true, true);
trainer.train(train_images, false);
trainer.saveModel("test.xml");
} else {
loadImages(false, true);
trainer.loadModel("test.xml");
}
const string window_name = "query_name";
namedWindow(window_name);
for (const auto& query_group : query_image_by_name)
{
string name = query_group.first;
for (const auto& query : query_group.second)
{
Image::Candidate::Assessments result = trainer.match(query);
result.sort();
cout << "------------------" << endl;
cout << "Query name: " << name << endl;
for (const auto& assesment : result)
{
cout << assesment.name << "\t" << assesment.score << endl;
}
imshow(window_name, query.getImage());
waitKey();
}
}
destroyWindow(window_name);
return 0;
}
|
#include "arduinoFFT.h"
/*
* Open Source Project by Nikodem Bartnik
* https://nikodembartnik.pl/
* https://github.com/nikodembartnik
* https://www.youtube.com/user/nikodembartnik
* Feel free to make it even better
* And don't forget to share with others :)
*/
#define SAMPLES 128 //Must be a power of 2
#define SAMPLING_FREQUENCY 1000 //Hz, must be less than 10000 due to ADC
#define STRING_E1 11
#define STRING_B 10
#define STRING_G 9
#define STRING_D 8
#define STRING_A 7
#define STRING_E2 6
#define TOO_LOW 3
#define PERFECT 4
#define TOO_HIGH 5
#define BUTTON 2
arduinoFFT FFT = arduinoFFT();
unsigned int sampling_period_us;
unsigned long microseconds;
bool ukuleleMode = false;
double vReal[SAMPLES];
double vImag[SAMPLES];
void setup() {
sampling_period_us = round(1000000*(1.0/SAMPLING_FREQUENCY));
pinMode(BUTTON, INPUT);
pinMode(STRING_E1, OUTPUT);
pinMode(STRING_B, OUTPUT);
pinMode(STRING_G, OUTPUT);
pinMode(STRING_D, OUTPUT);
pinMode(STRING_A, OUTPUT);
pinMode(STRING_E2, OUTPUT);
pinMode(TOO_LOW, OUTPUT);
pinMode(PERFECT, OUTPUT);
pinMode(TOO_HIGH, OUTPUT);
}
void loop() {
DisplayNoteAndBar(FindDominantFrequency());
if(digitalRead(BUTTON) == LOW){
delay(300);
if(digitalRead(BUTTON) == LOW){
ukuleleMode = !ukuleleMode;
if(ukuleleMode){
digitalWrite(STRING_B, HIGH);
digitalWrite(STRING_G, HIGH);
digitalWrite(STRING_D, HIGH);
digitalWrite(STRING_A, HIGH);
delay(1000);
digitalWrite(STRING_B, LOW);
digitalWrite(STRING_G, LOW);
digitalWrite(STRING_D, LOW);
digitalWrite(STRING_A, LOW);
}else{
digitalWrite(STRING_E1, HIGH);
digitalWrite(STRING_B, HIGH);
digitalWrite(STRING_G, HIGH);
digitalWrite(STRING_D, HIGH);
digitalWrite(STRING_A, HIGH);
digitalWrite(STRING_E2, HIGH);
delay(1000);
digitalWrite(STRING_E1, LOW);
digitalWrite(STRING_B, LOW);
digitalWrite(STRING_G, LOW);
digitalWrite(STRING_D, LOW);
digitalWrite(STRING_A, LOW);
digitalWrite(STRING_E2, LOW);
}
}
}
}
double FindDominantFrequency(){
for(int i=0; i<SAMPLES; i++)
{
microseconds = micros(); //Overflows after around 70 minutes!
vReal[i] = analogRead(2);
vImag[i] = 0;
while(micros() < (microseconds + sampling_period_us));
}
/*FFT*/
FFT.Windowing(vReal, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
FFT.Compute(vReal, vImag, SAMPLES, FFT_FORWARD);
FFT.ComplexToMagnitude(vReal, vImag, SAMPLES);
double peak = FFT.MajorPeak(vReal, SAMPLES, SAMPLING_FREQUENCY);
// Serial.println(peak); //Print out what frequency is the most dominant.
peak = peak * 0.990;
return peak;
}
void DisplayNoteAndBar(double frequency){
int ArrayWithNoteAndBarWidth[2];
DetectClosestNote(frequency, ArrayWithNoteAndBarWidth);
char note = NoteNumberToString(ArrayWithNoteAndBarWidth[0]);
Serial.println(frequency);
if(ArrayWithNoteAndBarWidth[1] < 64){
analogWrite(TOO_LOW, map(ArrayWithNoteAndBarWidth[1], 0, 64, 255, 0));
digitalWrite(PERFECT, LOW);
digitalWrite(TOO_HIGH, LOW);
}else if(ArrayWithNoteAndBarWidth[1] > 64){
analogWrite(TOO_HIGH, map(ArrayWithNoteAndBarWidth[1], 64, 128, 0, 255));
digitalWrite(PERFECT, LOW);
digitalWrite(TOO_LOW, LOW);
}else{
digitalWrite(PERFECT, HIGH);
digitalWrite(TOO_LOW, LOW);
digitalWrite(TOO_HIGH, LOW);
}
}
int* DetectClosestNote(double frequency, int *arr){
if(ukuleleMode == false){
if(InRange(frequency, 62, 102)){
arr[0] = 6;
arr[1] = map(frequency, 62, 102, 1, 128);
}else if(InRange(frequency, 100, 120)){
arr[0] = 5;
arr[1] = map(frequency, 100, 120, 1, 128);
}else if(InRange(frequency, 120, 165)){
arr[0] = 4;
arr[1] = map(frequency, 127, 167, 1, 128);
}else if(InRange(frequency, 165, 210)){
arr[0] = 3;
arr[1] = map(frequency, 176, 216, 1, 128);
}else if(InRange(frequency, 210, 290)){
arr[0] = 2;
arr[1] = map(frequency, 217, 277, 1, 128);
}else if(InRange(frequency, 290, 380)){
arr[0] = 1;
arr[1] = map(frequency, 290, 370, 1, 128);
}
}else{
//notes for ukulele
if(InRange(frequency, 420, 460)){
arr[0] = 5;
arr[1] = map(frequency, 420, 460, 1, 128);
}else if(InRange(frequency, 310, 350)){
arr[0] = 4;
arr[1] = map(frequency, 310, 350, 1, 128);
}else if(InRange(frequency, 232, 292)){
arr[0] = 3;
arr[1] = map(frequency, 232, 292, 1, 128);
}else if(InRange(frequency, 372, 412)){
arr[0] = 2;
arr[1] = map(frequency, 372, 412, 1, 128);
}
}
}
bool InRange(double frequency, int low_limit, int high_limit){
if(frequency < high_limit && frequency > low_limit){
return true;
}else{
return false;
}
}
char NoteNumberToString(int note_number){
switch(note_number){
case 1:
digitalWrite(STRING_E1, HIGH);
digitalWrite(STRING_B, LOW);
digitalWrite(STRING_G, LOW);
digitalWrite(STRING_D, LOW);
digitalWrite(STRING_A, LOW);
digitalWrite(STRING_E2, LOW);
return 'E';
break;
case 2:
digitalWrite(STRING_E1, LOW);
digitalWrite(STRING_B, HIGH);
digitalWrite(STRING_G, LOW);
digitalWrite(STRING_D, LOW);
digitalWrite(STRING_A, LOW);
digitalWrite(STRING_E2, LOW);
return 'B';
break;
case 3:
digitalWrite(STRING_E1, LOW);
digitalWrite(STRING_B, LOW);
digitalWrite(STRING_G, HIGH);
digitalWrite(STRING_D, LOW);
digitalWrite(STRING_A, LOW);
digitalWrite(STRING_E2, LOW);
return 'G';
break;
case 4:
digitalWrite(STRING_E1, LOW);
digitalWrite(STRING_B, LOW);
digitalWrite(STRING_G, LOW);
digitalWrite(STRING_D, HIGH);
digitalWrite(STRING_A, LOW);
digitalWrite(STRING_E2, LOW);
return 'D';
break;
case 5:
digitalWrite(STRING_E1, LOW);
digitalWrite(STRING_B, LOW);
digitalWrite(STRING_G, LOW);
digitalWrite(STRING_D, LOW);
digitalWrite(STRING_A, HIGH);
digitalWrite(STRING_E2, LOW);
return 'A';
break;
case 6:
digitalWrite(STRING_E1, LOW);
digitalWrite(STRING_B, LOW);
digitalWrite(STRING_G, LOW);
digitalWrite(STRING_D, LOW);
digitalWrite(STRING_A, LOW);
digitalWrite(STRING_E2, HIGH);
return 'e';
break;
}
}
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "AbstractCentreBasedCellPopulation.hpp"
#include "RandomDirectionCentreBasedDivisionRule.hpp"
#include "RandomNumberGenerator.hpp"
#include "StepSizeException.hpp"
#include "WildTypeCellMutationState.hpp"
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::AbstractCentreBasedCellPopulation( AbstractMesh<ELEMENT_DIM, SPACE_DIM>& rMesh,
std::vector<CellPtr>& rCells,
const std::vector<unsigned> locationIndices)
: AbstractOffLatticeCellPopulation<ELEMENT_DIM, SPACE_DIM>(rMesh, rCells, locationIndices),
mMeinekeDivisionSeparation(0.3) // educated guess
{
// If no location indices are specified, associate with nodes from the mesh.
std::list<CellPtr>::iterator it = this->mCells.begin();
typename AbstractMesh<ELEMENT_DIM, SPACE_DIM>::NodeIterator node_iter = rMesh.GetNodeIteratorBegin();
for (unsigned i=0; it != this->mCells.end(); ++it, ++i, ++node_iter)
{
unsigned index = locationIndices.empty() ? node_iter->GetIndex() : locationIndices[i]; // assume that the ordering matches
AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::AddCellUsingLocationIndex(index,*it);
}
mpCentreBasedDivisionRule.reset(new RandomDirectionCentreBasedDivisionRule<ELEMENT_DIM, SPACE_DIM>());
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::AbstractCentreBasedCellPopulation(AbstractMesh<ELEMENT_DIM, SPACE_DIM>& rMesh)
: AbstractOffLatticeCellPopulation<ELEMENT_DIM, SPACE_DIM>(rMesh),
mMeinekeDivisionSeparation(0.3) // educated guess
{
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
c_vector<double, SPACE_DIM> AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::GetLocationOfCellCentre(CellPtr pCell)
{
return GetNodeCorrespondingToCell(pCell)->rGetLocation();
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
Node<SPACE_DIM>* AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::GetNodeCorrespondingToCell(CellPtr pCell)
{
unsigned index = this->GetLocationIndexUsingCell(pCell);
return this->GetNode(index);
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
double AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::GetCellDataItemAtPdeNode(
unsigned pdeNodeIndex,
std::string& rVariableName,
bool dirichletBoundaryConditionApplies,
double dirichletBoundaryValue)
{
CellPtr p_cell = this->GetCellUsingLocationIndex(pdeNodeIndex);
double value = p_cell->GetCellData()->GetItem(rVariableName);
return value;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
CellPtr AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::AddCell(CellPtr pNewCell, CellPtr pParentCell)
{
// Calculate the locations of the two daughter cells
std::pair<c_vector<double, SPACE_DIM>, c_vector<double, SPACE_DIM> > positions = mpCentreBasedDivisionRule->CalculateCellDivisionVector(pParentCell, *this);
c_vector<double, SPACE_DIM> parent_position = positions.first;
c_vector<double, SPACE_DIM> daughter_position = positions.second;
// Set the parent cell to use this location
ChastePoint<SPACE_DIM> parent_point(parent_position);
unsigned node_index = this->GetLocationIndexUsingCell(pParentCell);
this->SetNode(node_index, parent_point);
// Create a new node
Node<SPACE_DIM>* p_new_node = new Node<SPACE_DIM>(this->GetNumNodes(), daughter_position, false); // never on boundary
// Clear the applied force on the new node, in case velocity is ouptut on the same timestep as this cell's division
p_new_node->ClearAppliedForce();
// Copy any node attributes from the parent node
if (this->GetNode(node_index)->HasNodeAttributes())
{
p_new_node->rGetNodeAttributes() = this->GetNode(node_index)->rGetNodeAttributes();
}
unsigned new_node_index = this->AddNode(p_new_node); // use copy constructor so it doesn't matter that new_node goes out of scope
// Update cells vector
this->mCells.push_back(pNewCell);
// Update mappings between cells and location indices
this->SetCellUsingLocationIndex(new_node_index, pNewCell);
this->mCellLocationMap[pNewCell.get()] = new_node_index;
return pNewCell;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
std::pair<CellPtr,CellPtr> AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::CreateCellPair(CellPtr pCell1, CellPtr pCell2)
{
assert(pCell1);
assert(pCell2);
std::pair<CellPtr,CellPtr> cell_pair;
if (pCell1->GetCellId() < pCell2->GetCellId())
{
cell_pair.first = pCell1;
cell_pair.second = pCell2;
}
else
{
cell_pair.first = pCell2;
cell_pair.second = pCell1;
}
return cell_pair;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
bool AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::IsMarkedSpring(const std::pair<CellPtr,CellPtr>& rCellPair)
{
// the pair should be ordered like this (CreateCellPair will ensure this)
assert(rCellPair.first->GetCellId() < rCellPair.second->GetCellId());
return mMarkedSprings.find(rCellPair) != mMarkedSprings.end();
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::MarkSpring(std::pair<CellPtr,CellPtr>& rCellPair)
{
// the pair should be ordered like this (CreateCellPair will ensure this)
assert(rCellPair.first->GetCellId() < rCellPair.second->GetCellId());
mMarkedSprings.insert(rCellPair);
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::UnmarkSpring(std::pair<CellPtr,CellPtr>& rCellPair)
{
// the pair should be ordered like this (CreateCellPair will ensure this)
assert(rCellPair.first->GetCellId() < rCellPair.second->GetCellId());
mMarkedSprings.erase(rCellPair);
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
bool AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::IsCellAssociatedWithADeletedLocation(CellPtr pCell)
{
return GetNodeCorrespondingToCell(pCell)->IsDeleted();
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
std::set<unsigned> AbstractCentreBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::GetNeighbouringLocationIndices(CellPtr pCell)
{
unsigned node_index = this->GetLocationIndexUsingCell(pCell);
return this->GetNeighbouringNodeIndices(node_index);
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::CheckForStepSizeException(unsigned nodeIndex, c_vector<double,SPACE_DIM>& rDisplacement, double dt)
{
double length = norm_2(rDisplacement);
if ((length > this->mAbsoluteMovementThreshold) && (!this->IsGhostNode(nodeIndex)) && (!this->IsParticle(nodeIndex)))
{
std::ostringstream message;
message << "Cells are moving by " << length;
message << ", which is more than the AbsoluteMovementThreshold: use a smaller timestep to avoid this exception.";
// Suggest a net time step that will give a movement smaller than the movement threshold
double new_step = 0.95*dt*(this->mAbsoluteMovementThreshold/length);
throw StepSizeException(new_step, message.str(), true); // terminate
}
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
double AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::GetDampingConstant(unsigned nodeIndex)
{
if (this->IsGhostNode(nodeIndex) || this->IsParticle(nodeIndex))
{
return this->GetDampingConstantNormal();
}
else
{
CellPtr p_cell = this->GetCellUsingLocationIndex(nodeIndex);
if (p_cell->GetMutationState()->IsType<WildTypeCellMutationState>())
{
return this->GetDampingConstantNormal();
}
else
{
return this->GetDampingConstantMutant();
}
}
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
bool AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::IsGhostNode(unsigned index)
{
return false;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
bool AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::IsParticle(unsigned index)
{
return false;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
double AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::GetMeinekeDivisionSeparation()
{
return mMeinekeDivisionSeparation;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::SetMeinekeDivisionSeparation(double divisionSeparation)
{
assert(divisionSeparation <= 1.0);
assert(divisionSeparation >= 0.0);
mMeinekeDivisionSeparation = divisionSeparation;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCentreBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::AcceptCellWritersAcrossPopulation()
{
for (typename AbstractMesh<ELEMENT_DIM, SPACE_DIM>::NodeIterator node_iter = this->rGetMesh().GetNodeIteratorBegin();
node_iter != this->rGetMesh().GetNodeIteratorEnd();
++node_iter)
{
for (typename std::vector<boost::shared_ptr<AbstractCellWriter<ELEMENT_DIM, SPACE_DIM> > >::iterator cell_writer_iter = this->mCellWriters.begin();
cell_writer_iter != this->mCellWriters.end();
++cell_writer_iter)
{
CellPtr cell_from_node = this->GetCellUsingLocationIndex(node_iter->GetIndex());
this->AcceptCellWriter(*cell_writer_iter, cell_from_node);
}
}
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
boost::shared_ptr<AbstractCentreBasedDivisionRule<ELEMENT_DIM, SPACE_DIM> > AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::GetCentreBasedDivisionRule()
{
return mpCentreBasedDivisionRule;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::SetCentreBasedDivisionRule(boost::shared_ptr<AbstractCentreBasedDivisionRule<ELEMENT_DIM, SPACE_DIM> > pCentreBasedDivisionRule)
{
mpCentreBasedDivisionRule = pCentreBasedDivisionRule;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::OutputCellPopulationParameters(out_stream& rParamsFile)
{
*rParamsFile << "\t\t<MeinekeDivisionSeparation>" << mMeinekeDivisionSeparation << "</MeinekeDivisionSeparation>\n";
// Add the division rule parameters
*rParamsFile << "\t\t<CentreBasedDivisionRule>\n";
mpCentreBasedDivisionRule->OutputCellCentreBasedDivisionRuleInfo(rParamsFile);
*rParamsFile << "\t\t</CentreBasedDivisionRule>\n";
// Call method on direct parent class
AbstractOffLatticeCellPopulation<ELEMENT_DIM, SPACE_DIM>::OutputCellPopulationParameters(rParamsFile);
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
double AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::GetDefaultTimeStep()
{
return 1.0/120.0;
}
// Explicit instantiation
template class AbstractCentreBasedCellPopulation<1,1>;
template class AbstractCentreBasedCellPopulation<1,2>;
template class AbstractCentreBasedCellPopulation<2,2>;
template class AbstractCentreBasedCellPopulation<1,3>;
template class AbstractCentreBasedCellPopulation<2,3>;
template class AbstractCentreBasedCellPopulation<3,3>;
|
#include "Pagamento.h"
#include <iostream>
#include <string>
double Pagamento::getValorPagamento(){
return valorPagamento;
}
std::string Pagamento::getNomeDoFuncionario(){
return nomeDoFuncionario;
}
void Pagamento::setValorPagamento(double valorPagamento){
this->valorPagamento = valorPagamento;
}
void Pagamento::setNomeDoFuncionario(std::string nomeDoFuncionario){
this->nomeDoFuncionario = nomeDoFuncionario;
}
|
#include<bits/stdc++.h>
using namespace std;
string countAndSay(int n)
{
string prev = "1";
string curr = "1";
for (int i = 2; i <= n; i++)
{
curr.clear();
int lastIndex = 0; // index where the prev(diffrent) number was last seen
for (int j = 0; j < prev.size(); j++)
{
// we have encounterd a diffrent number
if (prev[j] != prev[lastIndex])
{
// append count of previous number to current string
curr.append(to_string(j - lastIndex));
// append previous number to current string
curr.push_back(prev[lastIndex]);
// make the new numbers position as last seen index for it
lastIndex = j;
}
}
// for the last number in the string as the above for loop will not consider it
curr.append(to_string(prev.size() - lastIndex));
curr.push_back(prev[lastIndex]);
prev = curr;
}
return curr;
}
|
#ifndef GAMETIME_H
#define GAMETIME_H
#include <Windows.h>
class GameTimer
{
public:
//the delta time of the app
static float deltaTime;
static bool Initialize();
static void Update();
private:
//the start time
static LONGLONG start;
//ticks per second
static float frequencySeconds;
};
#endif
|
#include<bits/stdc++.h>
using namespace std;
int main(){
char s[300005];
scanf("%s",s);
long long ans = 0;
int n = strlen(s);
for(int i = 0; i < n; i++){
if( (s[i]-'0') % 4 == 0) ans ++;
}
for(int i = 0; i < n - 1; i ++){
if( ((s[i] - '0')*10 + (s[i+1] - '0')) % 4 == 0){
ans += i + 1;
}
}
cout << ans << endl;
return 0;
}
|
#include <stdio.h>
#define MAXSIZE 6
void InsertionSort(int* arr)
{
for(int i=1; i<MAXSIZE; i++) //key does not includet arr[0]
{
int key = arr[i];
int shift_index = i-1;
while(arr[shift_index]>key && shift_index>=0)
{
arr[shift_index+1] = arr[shift_index];
shift_index--;
}
arr[shift_index+1] = key;
}
}
int main()
{
int arr[MAXSIZE] = {5, 2, 4, 6, 1, 3};
InsertionSort(arr);
for(int i=0; i<MAXSIZE; i++)
{
printf("%d ", arr[i]);
}
}
|
#include <stdio.h>
#include <yaml.h>
#include <string>
#include <string.h>
#include <iostream>
int main(void)
{
FILE *FileHandler = fopen("public.yaml", "r");
yaml_parser_t Yamlparser;
yaml_event_t Yamlevent; /* New variable */
/* Initialize parser */
if(!yaml_parser_initialize(&Yamlparser))
fputs("Failed to initialize parser!\n", stderr);
if( NULL == FileHandler)
fputs("Failed to open file!\n", stderr);
yaml_parser_set_input_file(&Yamlparser, FileHandler);
std::string strSuffix[105];
int x = 0;
std::string PortNums;
std::string NameserverInfo;
std::string DatabaseInfo;
do {
yaml_parser_parse(&Yamlparser, &Yamlevent);
if(Yamlevent.type == YAML_SCALAR_EVENT){
//printf("actual: %s\n", event.data.scalar.value);
std::string actual((char*)Yamlevent.data.scalar.value);
//determine the list of ports
std::string Portlist = "ListenPort";
if( strcmp( actual.c_str(), Portlist.c_str() ) ) {
}else{
if(Yamlevent.type != YAML_STREAM_END_EVENT)
yaml_event_delete(&Yamlevent);
yaml_parser_parse(&Yamlparser, &Yamlevent);
PortNums = (char*)Yamlevent.data.scalar.value;
}
//determine the Nameserver Info
std::string Nameserver = "Nameserver";
if( strcmp( actual.c_str(), Nameserver.c_str() ) ) {
}else{
if(Yamlevent.type != YAML_STREAM_END_EVENT)
yaml_event_delete(&Yamlevent);
yaml_parser_parse(&Yamlparser, &Yamlevent);
NameserverInfo = (char*)Yamlevent.data.scalar.value;
}
//determine the Info for the Database
std::string Database = "Database";
if( strcmp( actual.c_str(), Database.c_str() ) ) {
}else{
if(Yamlevent.type != YAML_STREAM_END_EVENT)
yaml_event_delete(&Yamlevent);
yaml_parser_parse(&Yamlparser, &Yamlevent);
DatabaseInfo = (char*)Yamlevent.data.scalar.value;
}
}
x++;
} while(Yamlevent.type != YAML_STREAM_END_EVENT);
std::cout << "Ports: " << PortNums << std::endl;
std::cout << "NameserverInfo: " << NameserverInfo << std::endl;
std::cout << "DatabaseInfo: " << DatabaseInfo << std::endl;
yaml_event_delete(&Yamlevent);
yaml_parser_delete(&Yamlparser);
fclose(FileHandler);
return 0;
}
|
// @copyright 2017 - 2018 Shaun Ostoic
// Distributed under the MIT License.
// (See accompanying file LICENSE.md or copy at https://opensource.org/licenses/MIT)
#pragma once
#include "../access_token.hpp"
#include <distant/detail/tags.hpp>
#include <distant/support/winapi/token.hpp>
namespace distant::security
{
namespace detail
{
using boost::winapi::DWORD_;
using boost::winapi::HANDLE_;
template <typename Object>
struct dispatcher {};
template <process_rights A>
struct dispatcher<process<A>>
{
using dispatch = distant::detail::process_tag;
};
template <>
struct dispatcher<agents::basic_process>
{
using dispatch = distant::detail::process_base_tag;
};
inline HANDLE_ get_token_impl(const agents::basic_process& process, const DWORD_ access,
const distant::detail::process_base_tag tag) noexcept
{
static_cast<void>(tag);
HANDLE_ token = nullptr;
::OpenProcessToken(native_handle_of(process), access, &token);
return token;
}
template <access_rights::process A>
HANDLE_ get_token_impl(const process<A>& process, const DWORD_ access, const distant::detail::process_tag tag) noexcept
{
using access_rights = access_rights::process;
static_cast<void>(tag);
return get_token_impl(reinterpret_cast<const agents::basic_process&>(process), access, distant::detail::process_base_tag{});
}
/*inline HANDLE_ get_token_impl(const agents::thread& thread, DWORD_ access, bool self) noexcept
{
boost::winapi::HANDLE_ token = nullptr;
boost::winapi::OpenThreadToken(native_handle_of(thread), access, self, &token);
return token;
}*/
} // namespace detail
//class access_token
//public:
template <access_rights::token A, typename K>
access_token<A, K>::access_token(const K& k) noexcept
: handle_(
distant::kernel_handle{
detail::get_token_impl(k, static_cast<boost::winapi::DWORD_>(A), detail::dispatcher<K>::dispatch{})
})
{}
template <access_rights::token A, typename K>
bool access_token<A, K>
::has_privilege(const security::privilege& p) const noexcept
{
if (!p) return false;
boost::winapi::BOOL_ result = false;
boost::winapi::PRIVILEGE_SET_ set = p;
boost::winapi::privilege_check(handle_.native_handle(), &set, &result);
return result;
}
template <access_rights::token A, typename K>
bool access_token<A, K>
::set_privilege(const security::privilege& p, security::privilege::attributes attribute) noexcept
{
if (!p) return false;
boost::winapi::TOKEN_PRIVILEGES_ temp = p;
temp.Privileges[0].Attributes = static_cast<boost::winapi::DWORD_>(attribute);
if (boost::winapi::adjust_token_privilege(
handle_.native_handle(), false, &temp, sizeof(temp), nullptr, nullptr))
{
// If the privilege was set return success.
if (last_error().value() != boost::winapi::ERROR_NOT_ALL_ASSIGNED_)
return true;
}
// Otherwise an error has occured.
return false;
}
template <access_rights::token A, typename K>
bool access_token<A, K>
::remove_privilege(const security::privilege& p) noexcept
{
return this->set_privilege(p, security::privilege::attributes::removed);
}
//free:
template <token_rights Access, typename Agent>
access_token<Access, Agent>
primary_access_token(const Agent& object) noexcept
{
static_assert(
detail::has_token_access<Agent>(),
"[primary_access_token] insuficient access to Agent"
);
return access_token<Access, Agent>{object};
}
template <typename Agent>
access_token<token_rights::adjust_privileges | token_rights::query, Agent>
primary_access_token(const Agent& object) noexcept
{
return primary_access_token<token_rights::adjust_privileges | token_rights::query>(object);
}
inline access_token<token_rights::all_access, process<>>
primary_access_token() noexcept
{
return primary_access_token<token_rights::all_access>(agents::current_process());
}
} // namespace distant::security
|
#include "hotplate.h"
#include <sys/time.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
const int plateHeight = 1024;
const int plateWidth = 1024;
float** plate1;
float** plate2;
bool** lockedCells;
float** lockedValues;
/* Return the current time in seconds, using a double precision number. */
double now() {
struct timeval tp;
gettimeofday(&tp, NULL);
return ((double) tp.tv_sec + (double) tp.tv_usec * 1e-6);
}
void initializeFloatArray(float** array, int length, int size) {
for (int i = 0; i < length; i++) {
array[i] = new float[size];
memset(array[i], 0.0, size * sizeof(float));
}
}
void initializeBoolArray(bool** array, int length, int size) {
for (int i = 0; i < length; i++) {
array[i] = new bool[size];
for (int j = 0; j < size; j++) {
array[i][j] = false;
}
//memset(array[i], 0.0, size * sizeof(bool));
}
}
void init() {
// The double buffers for the hot plate
plate1 = new float*[plateHeight];
initializeFloatArray(plate1, plateHeight, plateWidth);
plate2 = new float*[plateHeight];
initializeFloatArray(plate2, plateHeight, plateWidth);
lockedCells = new bool*[plateHeight];
initializeBoolArray(lockedCells, plateHeight, plateWidth);
lockedValues = new float*[plateHeight];
initializeFloatArray(lockedValues, plateHeight, plateWidth);
for (int x = 0; x < plateWidth; x++) {
// Lock the bottom row at 0 degrees
lockCell(x, 0, 100);
// Lock the top row at 100 degrees
lockCell(x, plateHeight-1, 0);
}
for (int y = 0; y < plateHeight; y++) {
// Lock the left row at 0 degrees
lockCell(0, y, 0);
// Lock the right row at 0 degrees
lockCell(plateWidth-1, y, 0);
}
for (int x = 0; x <= 330; x++) {
// Lock this row at 100 degrees
lockCell(x, 400, 100);
}
// Lock the random cell
lockCell(500, 200, 100);
}
bool validCell(int x, int y) {
return x >= 0 && x < plateWidth && y >= 0 && y < plateHeight;
}
void lockCell(int x, int y, float temp) {
if (validCell(x, y)) {
lockedCells[y][x] = true;
lockedValues[y][x] = temp;
}
}
void initPlate(float** plate) {
for (int y = 0; y < plateHeight; y++) {
for (int x = 0; x < plateWidth; x++) {
if (lockedCells[y][x]) {
// Temperature the cell was locked to
plate[y][x] = lockedValues[y][x];
} else {
// Default cell starting temperature
plate[y][x] = 50.0;
}
}
}
}
//void swapPlate(float* oldPlate, float* newPlate) {
// memcpy((void*)newPlate, (void*)oldPlate, plateWidth * plateHeight * sizeof(float));
//}
bool isStable(float** plate) {
// Only scan the inside section (not the outside columns and rows)
// This way, each iteration doesn't need a range check.
for (int y = 0; y < plateHeight; y++) {
//printf("Entering at (x, %i)\n", y);
for (int x = 0; x < plateWidth; x++) {
// If the cell is locked, then it is skipped while determining stability
if (!lockedCells[y][x]) {
float diff = fabs(plate[y][x] - (plate[y][x-1] + plate[y-1][x] + plate[y][x+1] + plate[y+1][x]) * 0.25);
if (!(diff < 0.1)) {
/*
printf("Exiting at (%i, %i)\n", x, y);
printf("%2.0f %2.0f %2.0f\n%2.0f %2.0f %2.0f\n%2.0f %2.0f %2.0f\n",
plate[cellRef(x-1, y-1)], plate[cellRef(x, y-1)], plate[cellRef(x+1, y-1)],
plate[cellRef(x-1, y)], plate[cellRef(x, y)], plate[cellRef(x+1, y)],
plate[cellRef(x-1, y+1)], plate[cellRef(x, y+1)], plate[cellRef(x+1, y+1)]);
printf("Ending diff: %2.3f\n", diff);
*/
return false;
}
}
}
}
return true;
}
// Changed: This no longer serves dual purposes.
// This function serves the purpose of both updating the new plate,
// and also determining whether or not the update was even needed.
// If the current status was stable as it was, then true is returned,
// and the process should not be repeated. Otherwise, false is returned.
bool update(float** oldPlate, float** newPlate) {
for (int y = 0; y < plateHeight; y++) {
for (int x = 0; x < plateWidth; x++) {
if (!lockedCells[y][x]) {
// The borders where this would grab invalid data will always be locked
// so we don't need to check here for that.
newPlate[y][x] = (oldPlate[y][x-1] + oldPlate[y-1][x] + oldPlate[y][x+1] + oldPlate[y+1][x] + (4.0 * oldPlate[y][x])) * 0.125;
} else {
newPlate[y][x] = oldPlate[y][x];
}
}
}
return false;
}
void end() {
for (int i = 0; i < plateHeight; i++) {
delete[] plate1[i];
}
delete[] plate1;
plate1 = NULL;
for (int i = 0; i < plateHeight; i++) {
delete[] plate2[i];
}
delete[] plate2;
plate2 = NULL;
for (int i = 0; i < plateHeight; i++) {
delete[] lockedCells[i];
}
delete[] lockedCells;
lockedCells = NULL;
for (int i = 0; i < plateHeight; i++) {
delete[] lockedValues[i];
}
delete[] lockedValues;
lockedValues = NULL;
}
int main(int argc, char* argv[]) {
// Start the timing
double start = now();
printf("Start: %.4f\n", start);
// Initialize the locked cells
init();
// Initialize the plate using the locked cells
initPlate(plate1);
initPlate(plate2);
float** plate = plate1;
float** otherPlate = plate2;
float** tmp;
bool done = false;
int count = 0;
while (true) {
//printf("\n\n");
// Run a single step
// Swap the plates
tmp = otherPlate;
otherPlate = plate;
plate = tmp;
// Now update back into the regular plate
update(otherPlate, plate);
count++;
done = isStable(plate);
if (done) {
break;
} else {
//printf("Not Stable\n");
}
//for (int y = 0; y < plateHeight; y++) {
// for (int x = 0; x < plateWidth; x++) {
// printf("%3.0f ", plate[cellRef(x, y)]);
// }
// printf("\n");
//}
//sleep(1);
}
printf("Iterations required: %i\n", count);
int highTempCount = 0;
int strictlyHigherTempCount = 0;
for (int y = 0; y < plateWidth; y++) {
for (int x = 0; x < plateHeight; x++) {
//printf("%6.2f\t", plate[y][x]);
if (plate[y][x] >= 50) {
highTempCount++;
if (plate[y][x] > 50) {
strictlyHigherTempCount++;
}
}
}
//printf("\n");
}
printf("Cells >= 50 degrees: %i\n", highTempCount);
printf("Cells > 50 degrees: %i\n", strictlyHigherTempCount);
// Clear up the allocated memory
// Including the locked cells arrays
end();
// Finish up with the timing
double end = now();
printf("End: %.4f\n", end);
printf("Elapsed: %.4f\n", end - start);
return 0;
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.UI.Xaml.Interop.1.h"
WINRT_EXPORT namespace winrt {
namespace Windows::UI::Xaml::Interop {
struct BindableVectorChangedEventHandler : Windows::Foundation::IUnknown
{
BindableVectorChangedEventHandler(std::nullptr_t = nullptr) noexcept {}
template <typename L> BindableVectorChangedEventHandler(L lambda);
template <typename F> BindableVectorChangedEventHandler (F * function);
template <typename O, typename M> BindableVectorChangedEventHandler(O * object, M method);
void operator()(const Windows::UI::Xaml::Interop::IBindableObservableVector & vector, const Windows::Foundation::IInspectable & e) const;
};
struct NotifyCollectionChangedEventHandler : Windows::Foundation::IUnknown
{
NotifyCollectionChangedEventHandler(std::nullptr_t = nullptr) noexcept {}
template <typename L> NotifyCollectionChangedEventHandler(L lambda);
template <typename F> NotifyCollectionChangedEventHandler (F * function);
template <typename O, typename M> NotifyCollectionChangedEventHandler(O * object, M method);
void operator()(const Windows::Foundation::IInspectable & sender, const Windows::UI::Xaml::Interop::NotifyCollectionChangedEventArgs & e) const;
};
struct IBindableIterable :
Windows::Foundation::IInspectable,
impl::consume<IBindableIterable>
{
IBindableIterable(std::nullptr_t = nullptr) noexcept {}
};
struct IBindableIterator :
Windows::Foundation::IInspectable,
impl::consume<IBindableIterator>
{
IBindableIterator(std::nullptr_t = nullptr) noexcept {}
};
struct IBindableObservableVector :
Windows::Foundation::IInspectable,
impl::consume<IBindableObservableVector>,
impl::require<IBindableObservableVector, Windows::UI::Xaml::Interop::IBindableIterable, Windows::UI::Xaml::Interop::IBindableVector>
{
IBindableObservableVector(std::nullptr_t = nullptr) noexcept {}
};
struct IBindableVector :
Windows::Foundation::IInspectable,
impl::consume<IBindableVector>,
impl::require<IBindableVector, Windows::UI::Xaml::Interop::IBindableIterable>
{
IBindableVector(std::nullptr_t = nullptr) noexcept {}
};
struct IBindableVectorView :
Windows::Foundation::IInspectable,
impl::consume<IBindableVectorView>,
impl::require<IBindableVectorView, Windows::UI::Xaml::Interop::IBindableIterable>
{
IBindableVectorView(std::nullptr_t = nullptr) noexcept {}
};
struct INotifyCollectionChanged :
Windows::Foundation::IInspectable,
impl::consume<INotifyCollectionChanged>
{
INotifyCollectionChanged(std::nullptr_t = nullptr) noexcept {}
};
struct INotifyCollectionChangedEventArgs :
Windows::Foundation::IInspectable,
impl::consume<INotifyCollectionChangedEventArgs>
{
INotifyCollectionChangedEventArgs(std::nullptr_t = nullptr) noexcept {}
};
struct INotifyCollectionChangedEventArgsFactory :
Windows::Foundation::IInspectable,
impl::consume<INotifyCollectionChangedEventArgsFactory>
{
INotifyCollectionChangedEventArgsFactory(std::nullptr_t = nullptr) noexcept {}
};
}
}
|
/***********************************************************************
created: Thu Jul 7 2005
author: Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUI/WindowRendererSets/Core/Tooltip.h"
#include "CEGUI/falagard/WidgetLookFeel.h"
#include "CEGUI/CoordConverter.h"
namespace CEGUI
{
const String FalagardTooltip::TypeName("Core/Tooltip");
//----------------------------------------------------------------------------//
void FalagardTooltip::createRenderGeometry()
{
auto& imagery = getLookNFeel().getStateImagery(d_window->isEffectiveDisabled() ? "Disabled" : "Enabled");
imagery.render(*d_window);
}
//----------------------------------------------------------------------------//
Sizef FalagardTooltip::getContentSize() const
{
auto& lnf = getLookNFeel();
Sizef sz = getTextComponentExtents(lnf);
const Rectf textArea(lnf.getNamedArea("TextArea").getArea().getPixelRect(*d_window));
const Rectf wndArea(CoordConverter::asAbsolute(d_window->getArea(), d_window->getParentPixelSize()));
sz.d_width = CoordConverter::alignToPixels(sz.d_width + wndArea.getWidth() - textArea.getWidth());
sz.d_height = CoordConverter::alignToPixels(sz.d_height + wndArea.getHeight() - textArea.getHeight());
return sz;
}
//----------------------------------------------------------------------------//
Sizef FalagardTooltip::getTextComponentExtents(const WidgetLookFeel& lnf) const
{
// Find a text component responsible for a tooltip text
const auto& layerSpecs = lnf.getStateImagery("Enabled").getLayerSpecifications();
for (auto& layerSpec : layerSpecs)
{
const auto& sectionSpecs = layerSpec.getSectionSpecifications();
for (auto& sectionSpec : sectionSpecs)
{
const auto& texts = lnf.getImagerySection(sectionSpec.getSectionName()).getTextComponents();
if (!texts.empty())
return texts.front().getTextExtent(*d_window);
}
}
return d_window->getPixelSize();
}
}
|
#include <iostream>
using namespace std;
int main() {
string s = "I am the bone of my sword. ";
int n = 5;
cout << s << endl;
string s2 = "Steel is my body and fire is my blood. ";
cout << s2 << endl;
string s3 = s + s2;
cout << s3 << endl;
cout << s + s2 << endl;
}
|
/**
MIT License
Copyright (c) 2019 mpomaranski at gmail
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef ISERIALIZABLE_HAS_BEEN_DEFINED
#define ISERIALIZABLE_HAS_BEEN_DEFINED
#include <stdint.h>
#include <vector>
#include <sstream>
namespace cleric {
namespace data {
class ISerializable {
public:
virtual std::vector<uint8_t> toByteArray() const = 0;
virtual void fromByteArray(const std::vector<uint8_t> &data) = 0;
static ::std::vector<uint8_t> toBuffer(::std::stringstream &ss) {
std::vector<uint8_t> result;
const auto str = ss.str();
result.assign((uint8_t *)str.c_str(), (uint8_t *)str.c_str() + str.size());
return result;
}
};
} // namespace data
} // namespace cleric
#endif
|
#include "../../include/online/inet_address.h"
namespace keyword_suggestion {
InetAddress::InetAddress(const struct sockaddr_in &addr) : addr_(addr) {}
InetAddress::InetAddress(int port, const std::string &ip) {
::memset(&addr_, 0, sizeof(addr_));
addr_.sin_family = AF_INET;
addr_.sin_port = htons(port);
addr_.sin_addr.s_addr = inet_addr(ip.c_str());
}
int InetAddress::GetPort() const { return ntohs(addr_.sin_port); }
std::string InetAddress::GetIp() const {
return static_cast<std::string>(::inet_ntoa(addr_.sin_addr));
}
struct sockaddr_in *InetAddress::addr_ptr() {
return &addr_;
}
} // namespace keyword_suggestion
|
/*
https://leetcode.com/problems/longest-substring-without-repeating-characters/
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
*/
class Solution
{
public:
double findMedianSortedArrays(vector<int> &nums1, vector<int> &nums2)
{
size_t n1 = nums1.size();
size_t n2 = nums2.size();
bool isEven = (n1 + n2) % 2 == 0;
size_t median = (n1 + n2 + 1) / 2;
int sum = 0;
size_t i = 0, j = 0;
bool bfound = false;
for (; i < n1 && j < n2;)
{
int min = 0;
if (nums1[i] < nums2[j])
{
min = nums1[i];
++i;
}
else
{
min = nums2[j];
++j;
}
if (i + j == median)sum += min;
if (isEven)
{
if (i + j == median + 1)
{
sum += min;
bfound = true;
break;
}
}
}
if (!bfound)
{
if(i < n1)
{
int k = median - i - j;
if(sum == 0)
{
sum += nums1[i - 1 + k];
}
if(isEven)
{
sum += nums1[i + k];
}
}
if(j < n2)
{
int k = median - i - j;
if(sum == 0)
{
sum += nums2[j - 1 + k];
}
if(isEven)
{
sum += nums2[j + k];
}
}
}
if (isEven)
return sum / 2.0;
else
return sum;
}
};
|
#ifndef CCONSOLE_H
#define CCONSOLE_H
#include "CWindow.h"
class CConsole : public CWindow
{
public:
CConsole();
virtual ~CConsole();
protected:
private:
};
#endif // CCONSOLE_H
|
#ifndef __MODULESCENEWIN_H__
#define __MODULESCENEWIN_H__
#include "Module.h"
#include "Animation.h"
#include "Globals.h"
struct SDL_Texture;
class ModuleScenewin : public Module
{
public:
ModuleScenewin();
~ModuleScenewin();
bool Start();
update_status Update();
bool CleanUp();
public:
SDL_Texture* graphics2 = nullptr;
SDL_Texture* graphics = nullptr;
SDL_Rect winimage;
SDL_Rect winimage2;
char timer_text[10];
int font_countdown = -1;
int timertime;
uint timer;
int winLoseMusic = 0;
};
#endif // __MODULESCENEWIN_H__
|
#include <iostream>
#include <set>
using namespace std;
int main()
{
int n;
long long total_cost=0;
multiset<int>bill_amounts;
int n_bills;
int bill_amount;
multiset<int>::iterator it_end;
multiset<int>::iterator it_begin;
while(cin>>n && n!=0){
for(int i=n; n>0; n--){
cin>>n_bills;
for(int j=n_bills; j>0; j--){
cin>>bill_amount;
bill_amounts.insert(bill_amount);
}
it_end=bill_amounts.end();
it_end--;
it_begin=bill_amounts.begin();
total_cost=total_cost+((*it_end)-(*it_begin));
bill_amounts.erase(it_end);
bill_amounts.erase(it_begin);
}
cout<<total_cost<<endl;
total_cost=0;
bill_amounts.clear();
}
return 0;
}
|
/***************************************************************************
dialogolibreria.cpp - description
-------------------
begin : abr 21 2004
copyright : (C) 2004 by Oscar G. Duarte
email : ogduarte@ing.unal.edu.co
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include "dialogolibreria.h"
BEGIN_EVENT_TABLE(DialogoLibreria, wxDialog)
EVT_BUTTON(DLG_LIBRERIA_BTN_OK, DialogoLibreria::cerrarOk)
// EVT_BUTTON(DLG_LIBRERIA_BTN_CANCEL, DialogoLibreria::cancelar)
EVT_BUTTON(DLG_LIBRERIA_BTN_AYUDA, DialogoLibreria::ayuda)
EVT_BUTTON(DLG_LIBRERIA_BTN_ARCHIVO, DialogoLibreria::archivo)
EVT_BUTTON(DLG_LIBRERIA_BTN_ADICIONAR, DialogoLibreria::adicionar)
EVT_BUTTON(DLG_LIBRERIA_BTN_LEER, DialogoLibreria::leer)
EVT_BUTTON(DLG_LIBRERIA_BTN_BORRAR, DialogoLibreria::borrar)
EVT_BUTTON(DLG_LIBRERIA_BTN_SALVAR, DialogoLibreria::salvar)
EVT_LISTBOX(DLG_LIBRERIA_LIST_ITEMS, DialogoLibreria::seleccionaItem)
END_EVENT_TABLE()
DialogoLibreria::DialogoLibreria(Estrategia *est,Caso *cas, VariableLinguistica *var,
wxWindow* parent,const wxString& title, wxHtmlHelpController *ayuda)
:wxDialog(parent,-1,title)
{
Ayuda=ayuda;
Est=est;
Cas=cas;
Var=var;
if(Est!=NULL)
{
Tipo=1;
}else if(Cas!=NULL)
{
Tipo=2;
}else if(Var != NULL)
{
Tipo=3;
}else
{
Tipo=-1;
}
ButtonOK =new wxButton(this,DLG_LIBRERIA_BTN_OK, wxT("OK"));
ButtonAyuda =new wxButton (this,DLG_LIBRERIA_BTN_AYUDA, wxT("Ayuda"));
ButtonArchivo =new wxButton (this,DLG_LIBRERIA_BTN_ARCHIVO, wxT("Seleccionar"));
ButtonSalvar =new wxButton (this,DLG_LIBRERIA_BTN_SALVAR, wxT("Salvar"));
ButtonAdicionar =new wxButton (this,DLG_LIBRERIA_BTN_ADICIONAR, wxT("Adicionar"));
ButtonLeer =new wxButton (this,DLG_LIBRERIA_BTN_LEER, wxT("Leer"));
ButtonBorrar =new wxButton(this,DLG_LIBRERIA_BTN_BORRAR, wxT("Borrar"));
StaticArchivo =new wxStaticText (this,DLG_LIBRERIA_STATIC_ARCHIVO, wxT("Archivo"));
TextArchivo =new wxTextCtrl (this,DLG_LIBRERIA_TEXT_ARCHIVO);
ListBoxItems =new wxListBox (this,DLG_LIBRERIA_LIST_ITEMS);
StaticItems =new wxStaticText (this,DLG_LIBRERIA_STATIC_ITEMS, wxT("Disponibles"));
StaticDesc =new wxStaticText (this,DLG_LIBRERIA_STATIC_DESC, wxT("Descripción"));
TextDesc =new wxTextCtrl (this,DLG_LIBRERIA_TEXT_DESC,wxT(""),wxDefaultPosition,wxDefaultSize,wxTE_MULTILINE);
StaticActual =new wxStaticText (this,DLG_LIBRERIA_STATIC_ACTUAL, wxT("Actual:"));
TextActual =new wxTextCtrl (this,DLG_LIBRERIA_TEXT_ACTUAL);
TextArchivo->SetMinSize(wxSize(300,20));
TextArchivo->SetEditable(FALSE);
ListBoxItems->SetMinSize(wxSize(100,100));
TextDesc->SetMinSize(wxSize(250,100));
TextDesc->SetEditable(FALSE);
TextActual->SetMinSize(wxSize(150,20));
TextActual->SetEditable(FALSE);
wxBoxSizer *sizerButArch = new wxBoxSizer(wxVERTICAL);
sizerButArch->Add(ButtonArchivo, 0, wxALIGN_CENTER | wxALL, 5);
sizerButArch->Add(ButtonSalvar, 0, wxALIGN_CENTER | wxALL, 5);
wxBoxSizer *sizerArch = new wxBoxSizer(wxHORIZONTAL);
sizerArch->Add(StaticArchivo, 0, wxALIGN_CENTER | wxALL, 5);
sizerArch->Add(TextArchivo, 0, wxALIGN_CENTER | wxALL, 5);
sizerArch->Add(sizerButArch, 0, wxALIGN_CENTER | wxALL, 5);
wxBoxSizer *sizerItem = new wxBoxSizer(wxVERTICAL);
sizerItem->Add(StaticItems, 0, wxALIGN_CENTER | wxALL, 5);
sizerItem->Add(ListBoxItems, 0, wxALIGN_CENTER | wxALL, 5);
wxBoxSizer *sizerDesc = new wxBoxSizer(wxVERTICAL);
sizerDesc->Add(StaticDesc, 0, wxALIGN_CENTER | wxALL, 5);
sizerDesc->Add(TextDesc, 0, wxALIGN_CENTER | wxALL, 5);
wxBoxSizer *sizerOpc = new wxBoxSizer(wxHORIZONTAL);
sizerOpc->Add(sizerItem, 0, wxALIGN_CENTER | wxALL, 5);
sizerOpc->Add(sizerDesc, 0, wxALIGN_CENTER | wxALL, 5);
wxBoxSizer *sizerAct = new wxBoxSizer(wxHORIZONTAL);
sizerAct->Add(StaticActual, 0, wxALIGN_CENTER | wxALL, 5);
sizerAct->Add(TextActual, 0, wxALIGN_CENTER | wxALL, 5);
sizerAct->Add(ButtonAdicionar, 0, wxALIGN_CENTER | wxALL, 5);
sizerAct->Add(ButtonLeer, 0, wxALIGN_CENTER | wxALL, 5);
sizerAct->Add(ButtonBorrar, 0, wxALIGN_CENTER | wxALL, 5);
wxBoxSizer *sizerButInf = new wxBoxSizer(wxHORIZONTAL);
sizerButInf->Add(ButtonOK, 0, wxALIGN_CENTER | wxALL, 5);
// sizerButInf->Add(ButtonCancelar, 0, wxALIGN_CENTER | wxALL, 5);
sizerButInf->Add(ButtonAyuda, 0, wxALIGN_CENTER | wxALL, 5);
wxBoxSizer *sizerTotal = new wxBoxSizer(wxVERTICAL);
sizerTotal->Add(sizerArch, 0, wxALIGN_CENTER | wxALL, 5);
sizerTotal->Add(sizerOpc, 0, wxALIGN_CENTER | wxALL, 5);
sizerTotal->Add(sizerAct, 0, wxALIGN_CENTER | wxALL, 5);
sizerTotal->Add(sizerButInf, 0, wxALIGN_CENTER | wxALL, 5);
SetAutoLayout(TRUE);
SetSizer(sizerTotal);
sizerTotal->SetSizeHints(this);
sizerTotal->FitInside(this);
llenarCuadro();
}
DialogoLibreria::~DialogoLibreria()
{
}
void DialogoLibreria::cerrarOk(wxCommandEvent&)
{
wxSetWorkingDirectory(DirectorioInicial);
Close();
}
//void DialogoLibreria::cancelar()
//{
// wxSetWorkingDirectory(DirectorioInicial);
// Close();
//}
void DialogoLibreria::ayuda(wxCommandEvent&)
{
Ayuda->Display(wxT("Administración de Librerías"));
}
void DialogoLibreria::archivo(wxCommandEvent&)
{
wxString cad;
cad =wxT("Librerías de Fuzzynet (*.lfz)|*.lfz|Todos los archivos (*.*)|*.*");
wxFileDialog Dial(this,wxT("Archivo de librería"),DirectorioActual,ArchivoActual,cad,wxFD_OPEN|wxFD_CHANGE_DIR);
if(Dial.ShowModal()==wxID_OK)
{
ArchivoActual=Dial.GetFilename();
DirectorioActual=Dial.GetDirectory();
TextArchivo->SetValue(ArchivoActual);
Mi_ifpstream ifile(ArchivoActual);
wxBeginBusyCursor();
Lib.read(ifile);
wxEndBusyCursor();
llenarCuadro();
}
}
void DialogoLibreria::llenarCuadro()
{
int i,tam;
ListBoxItems->Clear();
Nom.Clear();
Desc.Clear();
Lib.datos(&Nom,&Desc,Tipo);
tam=Nom.GetCount();
for(i=0;i<tam;i++)
{
ListBoxItems->Append(Nom.Item(i));
}
if(tam>0)
{
ListBoxItems->SetSelection(0);
wxCommandEvent ev;
seleccionaItem(ev);
}
switch(Tipo)
{
case 1: TextActual->SetValue(Est->Nombre);break;
case 2: TextActual->SetValue(Cas->Nombre);break;
case 3: TextActual->SetValue(Var->Nombre);break;
}
}
void DialogoLibreria::seleccionaItem(wxCommandEvent&)
{
int sel;
sel=ListBoxItems->GetSelection();
if((sel>=0) & (Desc.GetCount() > sel))
{
TextDesc->SetValue(Desc.Item(sel));
}
}
void DialogoLibreria::adicionar(wxCommandEvent&)
{
wxString cad;
cad = wxT("Desea adicionar ");
switch(Tipo)
{
case 1: cad << wxT("la Metodología"); break;
case 2: cad << wxT("el Caso"); break;
case 3: cad << wxT("La Variable"); break;
}
cad << wxT(" actual a la librería? No olvide salvarla.");
if(wxMessageBox(cad,wxT("Atención"),wxYES_NO | wxCANCEL)==wxYES)
{
Mi_ofpstream *ofile;
ofile=new Mi_ofpstream(wxT("__Fzn_tmp"));
Mi_ifpstream *ifile;
wxBeginBusyCursor();
switch(Tipo)
{
case 1:
Est->write(*ofile);
delete ofile;
Estrategia *nEst;
nEst=new Estrategia;
ifile=new Mi_ifpstream(wxT("__Fzn_tmp"));
nEst->read(*ifile);
delete ifile;
Lib.Estrategias.Add(nEst);
llenarCuadro();
ListBoxItems->SetSelection(Lib.Estrategias.GetCount());
break;
case 2:
Cas->write(*ofile);
delete ofile;
Caso *nCas;
nCas=new Caso;
ifile=new Mi_ifpstream(wxT("__Fzn_tmp"));
nCas->read(*ifile);
delete ifile;
Lib.Casos.Add(nCas);
llenarCuadro();
ListBoxItems->SetSelection(Lib.Casos.GetCount());
break;
case 3:
Var->write(*ofile);
delete ofile;
VariableLinguistica *nVar;
nVar=new VariableLinguistica;
ifile=new Mi_ifpstream(wxT("__Fzn_tmp"));
nVar->read(*ifile);
delete ifile;
Lib.Variables.Add(nVar);
llenarCuadro();
ListBoxItems->SetSelection(Lib.Variables.GetCount());
break;
}
wxEndBusyCursor();
}
}
void DialogoLibreria::leer(wxCommandEvent&)
{
int sel;
sel=ListBoxItems->GetSelection();
if(sel<0){return;}
wxString cad;
cad = wxT("Desea copiar ");
switch(Tipo)
{
case 1: cad << wxT("la Metodología"); break;
case 2: cad << wxT("el Caso"); break;
case 3: cad << wxT("La Variable"); break;
}
cad << wxT(" de la librería la actual?.");
if(wxMessageBox(cad,wxT("Atención"),wxYES_NO | wxCANCEL)==wxYES)
{
Mi_ofpstream *ofile;
ofile=new Mi_ofpstream(wxT("__Fzn_tmp"));
Mi_ifpstream *ifile;
wxBeginBusyCursor();
switch(Tipo)
{
case 1:
Lib.Estrategias.Item(sel).write(*ofile);
delete ofile;
ifile=new Mi_ifpstream(wxT("__Fzn_tmp"));
Est->read(*ifile);
delete ifile;
llenarCuadro();
ListBoxItems->SetSelection(sel);
break;
case 2:
Lib.Casos.Item(sel).write(*ofile);
delete ofile;
ifile=new Mi_ifpstream(wxT("__Fzn_tmp"));
Cas->read(*ifile);
delete ifile;
llenarCuadro();
ListBoxItems->SetSelection(sel);
break;
case 3:
Lib.Variables.Item(sel).write(*ofile);
delete ofile;
ifile=new Mi_ifpstream(wxT("__Fzn_tmp"));
Var->read(*ifile);
delete ifile;
llenarCuadro();
ListBoxItems->SetSelection(sel);
break;
}
wxEndBusyCursor();
}
}
void DialogoLibreria::borrar(wxCommandEvent&)
{
int sel;
sel=ListBoxItems->GetSelection();
if(sel<0){return;}
wxString cad;
cad = wxT("Desea borrar ");
switch(Tipo)
{
case 1: cad << wxT("la Metodología"); break;
case 2: cad << wxT("el Caso"); break;
case 3: cad << wxT("La Variable"); break;
}
cad << wxT(" de la librería?. No olvide salvarla.");
if(wxMessageBox(cad,wxT("Atención"),wxYES_NO | wxCANCEL)==wxYES)
{
switch(Tipo)
{
case 1:
Lib.Estrategias.RemoveAt(sel);
llenarCuadro();
if(sel>Lib.Estrategias.GetCount())
{
sel=Lib.Estrategias.GetCount();
}
if(sel>=0)
{
ListBoxItems->SetSelection(sel);
}else
{
TextDesc->SetValue(wxT(""));
}
break;
case 2:
Lib.Casos.RemoveAt(sel);
llenarCuadro();
if(sel>Lib.Casos.GetCount())
{
sel=Lib.Casos.GetCount();
}
if(sel>=0)
{
ListBoxItems->SetSelection(sel);
}else
{
TextDesc->SetValue(wxT(""));
}
break;
case 3:
Lib.Variables.RemoveAt(sel);
llenarCuadro();
if(sel>Lib.Variables.GetCount())
{
sel=Lib.Variables.GetCount();
}
if(sel>=0)
{
ListBoxItems->SetSelection(sel);
}else
{
TextDesc->SetValue(wxT(""));
}
break;
}
}
}
void DialogoLibreria::salvar(wxCommandEvent&)
{
wxString cad;
cad =wxT("Librerías de Fuzzynet (*.lfz)|*.lfz|Todos los archivos (*.*)|*.*");
wxFileDialog Dial(this,wxT("Archivo de librería"),DirectorioActual,ArchivoActual,cad,wxFD_SAVE|wxFD_CHANGE_DIR);
if(Dial.ShowModal()==wxID_OK)
{
ArchivoActual=Dial.GetFilename();
DirectorioActual=Dial.GetDirectory();
TextArchivo->SetValue(ArchivoActual);
Mi_ofpstream ofile(ArchivoActual);
wxBeginBusyCursor();
Lib.write(ofile);
wxEndBusyCursor();
llenarCuadro();
}
}
|
#pragma once
#include <string>
#include <vector>
#include "drake/geometry/scene_graph.h"
#include "drake/multibody/multibody_tree/multibody_plant/multibody_plant.h"
#include "drake/multibody/multibody_tree/multibody_tree_indexes.h"
#include "drake/multibody/multibody_tree/parsing/sdf_parser_common.h"
namespace drake {
namespace multibody {
namespace parsing {
/// Parses a `<model>` element from the SDF file specified by `file_name` and
/// adds it to `plant`. The SDF file can only contain a single `<model>`
/// element. `<world>` elements (used for instance to specify gravity) are
/// ignored by this method. A new model instance will be added to @p plant.
///
/// @throws std::runtime_error if the file is not in accordance with the SDF
/// specification containing a message with a list of errors encountered while
/// parsing the file.
/// @throws std::runtime_error if there is more than one `<model>` element or
/// zero of them.
/// @throws std::exception if plant is nullptr or if MultibodyPlant::Finalize()
/// was already called on `plant`.
///
/// @param file_name
/// The name of the SDF file to be parsed.
/// @param model_name
/// The name given to the newly created instance of this model. If
/// empty, the "name" attribute from the model tag will be used.
/// @param plant
/// A pointer to a mutable MultibodyPlant object to which the model will be
/// added.
/// @param scene_graph
/// A pointer to a mutable SceneGraph object used for geometry registration
/// (either to model visual or contact geometry). May be nullptr.
/// @returns The model instance index for the newly added model.
ModelInstanceIndex AddModelFromSdfFile(
const std::string& file_name,
const std::string& model_name,
multibody_plant::MultibodyPlant<double>* plant,
geometry::SceneGraph<double>* scene_graph = nullptr);
/// Alternate version of AddModelFromSdfFile which always uses the "name"
/// element from the model tag for the name of the newly created model instance.
ModelInstanceIndex AddModelFromSdfFile(
const std::string& file_name,
multibody_plant::MultibodyPlant<double>* plant,
geometry::SceneGraph<double>* scene_graph = nullptr);
/// Parses all `<model>` elements from the SDF file specified by `file_name`
/// and adds them to `plant`. The SDF file can contain multiple `<model>`
/// elements. New model instances will be added to @p plant for each
/// `<model>` tag in the SDF file.
///
/// @throws std::runtime_error if the file is not in accordance with the SDF
/// specification containing a message with a list of errors encountered while
/// parsing the file.
/// @throws std::runtime_error if the file contains no models.
/// @throws std::exception if plant is nullptr or if MultibodyPlant::Finalize()
/// was already called on `plant`.
///
/// @param file_name
/// The name of the SDF file to be parsed.
/// @param plant
/// A pointer to a mutable MultibodyPlant object to which the model will be
/// added.
/// @param scene_graph
/// A pointer to a mutable SceneGraph object used for geometry registration
/// (either to model visual or contact geometry). May be nullptr.
/// @returns The set of model instance indices for the newly added models.
std::vector<ModelInstanceIndex> AddModelsFromSdfFile(
const std::string& file_name,
multibody_plant::MultibodyPlant<double>* plant,
geometry::SceneGraph<double>* scene_graph = nullptr);
} // namespace parsing
} // namespace multibody
} // namespace drake
|
#include "testlib.h"
#include <set>
#include <vector>
#include <string>
#include <map>
#include <iostream>
#include <memory.h>
using namespace std;
const int N = 100000;
const int M = 1000000;
bool used[N];
int main() {
registerValidation();
int n = inf.readInt(1, N);
inf.readEoln();
int sumk = 0;
for (int i = 1; i <= n; ++i) {
int k = inf.readInt(1, M);
sumk += k;
quitif(sumk > M, _fail, "Number of wanted girls must not exceed %d", M);
set<int> currentGirls;
for (int j = 0; j < k; ++j) {
inf.readSpace();
int girl = inf.readInt(1, N, "number of girl");
quitif(used[girl], _fail, "girl must be used exactly once (check it for girl #%d)", girl);
quitif(currentGirls.find(girl) != currentGirls.end(), _fail, "girl %d is used twice for boy %d", girl, i);
currentGirls.insert(girl);
}
inf.readEoln();
}
inf.readEof();
return 0;
}
|
float temp;
int tempPin = A0;
int sensorThres = 400;
void setup()
{
//lcd.begin(16, 2);
//lcd.setCursor(0, 0);
pinMode(7, OUTPUT);
pinMode(6, OUTPUT);
pinMode(5, OUTPUT);
pinMode(9, OUTPUT);
pinMode(8, OUTPUT);
pinMode(A1, INPUT);
//delay(1000);
Serial.begin(9600);
}
void loop()
{
int analogSensor = analogRead(A1);
Serial.print(analogSensor);
Serial.print(",");
if(analogSensor > sensorThres)
{
digitalWrite(10, HIGH);
digitalWrite(9, LOW);
tone(8, 1000, 200);
}
else
{
digitalWrite(10, LOW);
digitalWrite(9, HIGH);
noTone(8);
}
temp = analogRead(tempPin);
temp = (temp/1024) * 310;
Serial.println(temp);
delay(2000);
if(temp <= 37)
{
digitalWrite(7, HIGH);
digitalWrite(6, LOW);
digitalWrite(5, LOW);
}
else if(temp >= 37 && temp <= 40)
{
digitalWrite(7, LOW);
digitalWrite(6, HIGH);
digitalWrite(5, LOW);
}
else if (temp >= 41)
{
digitalWrite(7, LOW);
digitalWrite(6, LOW);
digitalWrite(5, HIGH);
}
}
|
#include "pacman-main.h"
// OUR VERSION of PACMAN is a tile-based game.
// The original one wasn't really tile-based,
// but this one is.
// Tile-based games are nice because we can
// make levels with a simple .txt file,
// one character per block. See lvl1.txt.
//////////////////////////////////////////
//
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
//(If there are enough exclamation marks,
// students MIGHT read it)
//
// THE WAY THIS PROGRAM IS STRUCTURED.
// -----------------------------------
// So, how's it going. You decided
// to read the comments. Good for you!
// So, there are 2 main objects.
// - Window
// - GameWorld
//
// WINDOW:
//
GameWindow *window ; // the main window object, which
// provides:
// - SOUND LOAD&PLAY
// - SPRITE LOAD&DRAW
// - INPUT MANAGEMENT from mouse, keyboard and gamepad
// Please browse InputMan.h, SoundMan.h and SpriteMan.h
// for further details.
//
// GAMEWORLD:
// Our entire game will be
// stored in the GameWorld
// object.
#include "GameWorld.h"
// ! RULE:
// ----
// Every code file here that wants the
// privilege of accessing "game" (THE
// one and only GameWorld object) AND
// "window" (to do window->drawSprite() etc)
// __must__ #include "pacman-main.h".
//
// More detail: If you look in "pacman-main.h", you
// will see it has a magical "extern" declaration..
// an "extern" variable is like a c++ function
// prototype, only for VARIABLES.. This is hard
// to explain, so if you really want to understand it,
// you should see me during office hours or read up on the internet.
//
// ! RULE THAT YOU REALLY SHOULD FOLLOW:
// ----------------------------------
// + Always split your source code
// into a .h and .cpp files or you
// __will__ run into problems!
//
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#pragma region explaining the ASSET macro
// The ASSET macro adds
// "../assets/" IN FRONT of
// to whatever you want.
// So:
// ASSET("sprites/Chaos.gif")
// turns into
// "../assets/sprites/Chaos.gif"
// In the pre-processor.
// The reason this is done is so all the separate
// projects ("game", "gdw-week-8" etc.)
// can share the same ASSETS folder,
// so we don't have to keep duplicating assets
// and wasting MB.
// This also makes it work if you double-click
// the .exe file in the /Build folder.
// Your game will still be able to find
// the assets.
#pragma endregion
#define ASSET(x) ("../assets/"##x)
void Init()
{
// randomize
srand( time(0) ) ;
#pragma region asset load and font create
// Load sounds. Notice how
// we use the ASSET() macro to
// make all filenames start with "../assets/"
window->loadSound( Sounds::PacmanTitleThemeLoop, ASSET("sounds/pacman/pacman-theme-loop.mp3"), FMOD_CREATESTREAM ) ;
window->loadSound( Sounds::PacmanGamePlayMusic, ASSET("sounds/pacman/powerpill.mp3"), FMOD_CREATESTREAM ) ;
window->loadSound( Sounds::PacmanPellet1, ASSET("sounds/pacman/pacman-pellet-1-l.wav" ) ) ;
window->loadSound( Sounds::PacmanPellet2, ASSET("sounds/pacman/pacman-pellet-2-l.wav" ) ) ;
window->loadSound( Sounds::PacmanPellet3, ASSET("sounds/pacman/pacman-pellet-3-l.wav" ) ) ;
window->loadSound( Sounds::Intro, ASSET("sounds/pacman/gypsy-jazz.mp3" ) ) ;
window->loadSound( Sounds::PacmanHurt, ASSET( "sounds/pacman/efire.wav" ) ) ;
window->loadSound( Sounds::GameOverRiff, ASSET( "sounds/pacman/gameover.wav" ) ) ;
// sprite loading
window->loadSprite( Sprites::Bonus, ASSET("sprites/pacman/cherries.png"), 0, 16, 16, 4, 0.5f ) ;
window->loadSprite( Sprites::Mario, ASSET("sprites/mario.png") ) ;
window->loadSprite( Sprites::Splash, ASSET("sprites/gdw-splash.png") ) ;
window->loadSprite( Sprites::Pacman, ASSET("sprites/pacman/pacman-spritesheet.png"), 0, 16, 16, 4, 0.05f ) ;
window->loadSprite( Sprites::PacmanTitle, ASSET("sprites/pacman/pacman-title.png") ) ;
window->loadSprite( Sprites::Pellet, ASSET("sprites/pacman/normal-pellet-sheet.png"), 0, 16, 16, 4, 0.2f ) ;
window->loadSprite( Sprites::Powerpellet, ASSET("sprites/pacman/powerpellet-sheet.png"), 0, 16, 16, 4, 0.2f ) ;
window->loadSprite( Sprites::Wall, ASSET( "sprites/pacman/wall.png" ) ) ;
window->loadSprite( Sprites::Barrier, ASSET( "sprites/pacman/ghost-door-barrier.png" ) ) ;
// It may seem silly to load and draw an empty sprite,
// but it makes programming the game logic easier for a tile
// with "nothing in it"
window->loadSprite( Sprites::Empty, ASSET( "sprites/pacman/empty.png" ) ) ;
window->loadSprite( Sprites::Gun, ASSET( "sprites/pacman/gun.png" ) ) ;
window->loadSprite( Sprites::Flamethrower, ASSET( "sprites/pacman/flamethrower.png" ) ) ;
window->loadSprite( Sprites::Uzi, ASSET( "sprites/pacman/uzi.png" ) ) ;
// Load ghost body and eyes
window->loadSprite( Sprites::GhostBody, ASSET( "sprites/pacman/ghost-body-white.png" ), 0, 16, 16, 2, 0.2f ) ;
window->loadSprite( Sprites::EyesRight, ASSET( "sprites/pacman/eyes-right.png" ) ) ;
window->loadSprite( Sprites::EyesUp, ASSET( "sprites/pacman/eyes-up.png" ) ) ;
window->loadSprite( Sprites::EyesDown, ASSET( "sprites/pacman/eyes-down.png" ) ) ;
window->loadSprite( Sprites::EyesDead, ASSET( "sprites/pacman/eyes-dead.png" ) ) ;
window->loadSprite( Sprites::GoalNode, ASSET( "sprites/pacman/goal-node.png" ) ) ;
window->loadSprite( Sprites::GameOverTitle, ASSET( "sprites/pacman/game-over.png" ) ) ;
// Create a few fonts
window->createFont( Fonts::Arial24, "Arial", 24, FW_NORMAL, false ) ;
window->createFont( Fonts::TimesNewRoman18, "Times New Roman", 18, FW_BOLD, false ) ;
window->createFont( Fonts::PacFont24, "PacFont Good", 24, FW_NORMAL, false ) ;
// Black bkg color to start
window->setBackgroundColor( D3DCOLOR_ARGB( 255, 0, 0, 0 ) ) ;
#pragma endregion
// Start up the game world
info( "Starting up the GameWorld..." ) ;
game = new GameWorld() ; // create GameWorld object.
}
void Update()
{
// update the game, happens 60 times a second
// How we update the game really
// depends on __WHAT STATE__
// the game is IN.
// ALT+ENTER for full screen mode..
if( window->keyIsPressed( VK_MENU ) &&
window->keyJustPressed( VK_RETURN ) )
{
window->fullScreenInMaxResolution() ;
}
// I chose to leave this mammoth switch in here,
// because I like how Update() ties everything together.
// Note though, if you wanted to, you could migrate
// all this code in the switch here (and in the Draw() function)
// into GameWorld.h
switch( game->getState() )
{
case GameWorld::GameState::Splash:
if( //window->anyKeyPushed() || // If any key was pushed..
// bah. key pushed is annoying. using mouse instead.
window->mouseJustPressed( Mouse::Left )
)
{
// Jump to the menu
game->setState( GameWorld::GameState::Menu ) ;
}
break ;
case GameWorld::GameState::Menu:
// In the menu state, ALL we're doing
// is listening for a click. A click
// means the user wants to start the game.
if( window->mouseJustPressed( Mouse::Left ) )
{
// There was a click. The person
// wants to start the game.
// TRANSITION STATE to Running.
// IN the handler code for when
// a transition from Menu to Running
// occurs is the level load, etc.
game->setState( GameWorld::GameState::Running ) ; // Start the game.
}
break;
case GameWorld::GameState::Running:
// Here we run the game.
game->step( window->getTimeElapsedSinceLastFrame() ) ;
// Allow PAUSE by pressing 'P'
if( window->keyJustPressed( 'P' ) )
{
game->setState( GameWorld::GameState::Paused ) ;
}
break;
case GameWorld::GameState::Paused:
// ((do nothing except check))
// for P again to unpause
if( window->keyJustPressed( 'P' ) )
{
game->setState( GameWorld::GameState::Running ) ;
}
break;
case GameWorld::GameState::GameOver:
// End the game and transition to menu
break;
}
// This code runs every frame
// regardless of what "state"
// the game is in.
// Quit if the user presses ESCAPE
if( window->keyJustPressed( VK_ESCAPE ) )
{
bail( "game ended!" ) ;
}
}
// DO ALL DRAWING HERE.
void Draw()
{
// Draw the game, happens 60 times a second
// What we draw
// also depends
// on game state
// If you picture a money sorter
// this kind of makes sense
switch( game->getState() )
{
case GameWorld::GameState::Splash:
{
// This only happens right at
// game start, so we'll just use
// the game's global clock
// to determine amount of fade in
// WHEN: 0 < time < 5 : Fade in
// 5 < time < 9 : stay solid
// 9 < time < 14 : fade out
int alpha = 0 ;
double time = window->getTimeElapsedSinceGameStart() ;
if( time < 5.0 )
{
// fade-in phase
float fadeInPercent = time / 5.0 ;
// And alpha is a linear interpolation say
alpha = lerp( 0, 255, fadeInPercent ) ;
clamp( alpha, 0, 255 ) ;
}
else if( 5.0 < time && time < 9.0 )
{
// stay solid
alpha = 255 ;
}
else
{
// fade out
float fadeOutPercent = ( 14.0 - time ) / 5.0 ;
alpha = lerp( 0, 255, fadeOutPercent ) ;
clamp( alpha, 0, 255 ) ;
}
// Fade out the logo
window->drawSprite(
Sprites::Splash,
window->getWidth()/2,
window->getHeight()/2,
D3DCOLOR_ARGB( alpha, 255, 255, 255 )
) ;
}
break;
case GameWorld::GameState::Menu:
// Draw the title
window->drawSprite( Sprites::PacmanTitle, window->getWidth()/2, 150 ) ;
// Draw the start message
window->drawString(
Fonts::Arial24,
"Click the mouse to start",
Color::White );
break;
// When paused..
// we also must draw the
// game world, or else
// you'll see nothing.
// The only difference when
// paused is we limit our
// response to input commands
// to only "unpause" command
case GameWorld::GameState::Running:
case GameWorld::GameState::Paused:
{
// When the game is running,
// ask the GameWorld object
// to draw itself
game->drawBoard() ;
game->drawStats() ;
// Now draw the player and enemies
game->drawPeople() ;
/*
//!! DEBUG: draw the map nodes
Graph* graph = game->getAsciiMap()->graph ;
D3DCOLOR dColor = D3DCOLOR_ARGB( 128, 255, 0, 0 ) ;
for( int i = 0 ; i < graph->nodes.size() ; i++ )
{
float x = graph->nodes[i]->coord.col * game->tileSize;
float y = graph->nodes[i]->coord.row * game->tileSize;
Vector2 dv = game->getDrawingVectorAt( Vector2(x,y) ) ;
window->drawBoxCentered( dColor, dv.x, dv.y, 20, 20 ) ;
}
*/
}
break;
case GameWorld::GameState::GameOver:
// Draw the game over sprite
window->drawSprite( Sprites::GameOverTitle,
window->getWidth()/2, 200 ) ;
break;
}
// Run these draw calls regardless of game state
window->drawFrameCounter(); // erase this if you don't like
// the frame counter in the top right corner
window->drawTimer() ; // draw global sense of game_time
// remember to draw the mouse last so
// it always appears on TOP of everything.
window->drawMouseCursor( Sprites::Mario ) ;
}
// ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^
// Your code above.
// VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV
// Engine code below. You shouldn't need to
// code down here, EXCEPT for if you need to read
// WM_CHAR messages.
///////////////////////////////////////////
// WndProc says: I AM WHERE "MESSAGES" GET "DISPATCHED" TO,
// WHEN "EVENTS" "HAPPEN" TO YOUR WINDOW.
LRESULT CALLBACK WndProc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam )
{
// WndProc is WHERE you respond to
// all messages that might happen
// to your window.
// When a key is pushed, when a mouse is clicked,
// you can DO SOMETHING about that here, in WndProc
switch( message )
{
// We can call each of these "case traps"
// an "event handler". These tidbits of code
// "handle" the event where the user just
// clicked in our window, or the user pressed a key.
// A lot of these have been stripped away
// vs the GDI+ version of this project..
// Here, we only handle a few select
// messages...
// WM_CHAR: for 'character' key presses
// We use this for the user to type their name or something,
// with proper preservation of capslocked letters etc
case WM_CHAR:
{
//info( "You pushed %c, ascii=%d", wparam, wparam ) ;
}
return 0 ;
// WM_INPUT messages are for FAST keyboard and mouse
// These messages are FASTER than WM_KEYDOWN or WM_MOUSEMOVE.
// Both keyboard AND mouse input events get picked up here
case WM_INPUT:
{
#pragma region pick up the raw input
// DO NOT CODE HERE! use the
// window->justPressed(), and
// window->mouseJustPressed() functions,
// in your Update() function.
UINT dwSize;
GetRawInputData( (HRAWINPUT)lparam, RID_INPUT,
NULL, &dwSize, sizeof( RAWINPUTHEADER ) ) ;
LPBYTE lpb = new BYTE[ dwSize ] ;
if( lpb == NULL )
{
return 0;
}
if( GetRawInputData( (HRAWINPUT)lparam, RID_INPUT,
lpb, &dwSize, sizeof(RAWINPUTHEADER)) != dwSize )
{
error( "GetRawInputData doesn't return correct size !" ) ;
}
RAWINPUT *raw = (RAWINPUT*)lpb;
// Check if it was keyboard or mouse input.
if (raw->header.dwType == RIM_TYPEKEYBOARD)
{
// We don't take keyboard input here.
// We take it by using GetKeyboardState() function
// in the window->step() function.
//printRawKeyboard( raw ) ; // just so you can see
}
else if (raw->header.dwType == RIM_TYPEMOUSE)
{
//printRawMouse( raw ) ; // just so you can see
window->mouseUpdateInput( raw ) ;
}
delete[] lpb ;
#pragma endregion
return 0;
}
case WM_ACTIVATE:
switch( LOWORD(wparam) )
{
case WA_ACTIVE: // got focus via alt-tab or something
case WA_CLICKACTIVE: // got focus via mouse click on window
{
info( "Welcome back!" ) ;
}
break;
case WA_INACTIVE: // LOST FOCUS!! OH NO!!
{
// This means the user is "focused" / has highlighted
// another window other than our window.
// You should probably pause the game here,
// because some apps tend to hijack the input focus
// which makes it really annoying.
info( "But why would you click away?" ) ;
}
}
return 0 ;
case WM_PAINT:
{
// Let's NOT paint here anymore.
// See Draw() function instead.
HDC hdc ;
PAINTSTRUCT ps;
hdc = BeginPaint( hwnd, &ps ) ;
// DO NOT PAINT HERE.
EndPaint( hwnd, &ps ); // tell Windows that
// we are done painting
}
return 0 ;
case WM_DESTROY:
PostQuitMessage( 0 ) ;
return 0 ;
}
return DefWindowProc( hwnd, message, wparam, lparam ) ;
}
// In a windows program, instead of main(), we use WinMain()
// Refer to earlier lessons for comments and more detail.
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow )
{
// Setup a console
consoleCreate() ;
consoleWhite() ;
consoleMove( 32, 500 ) ;
consoleRowsAndCols( 10, 120 ) ;
// Start up the log.
logStartup() ;
// Put these after log start up, b/c start up inits them with some init values
// See ERROR and WARNING messages at Console.
logOutputsForConsole = LOG_ERROR | LOG_WARNING | LOG_INFO ;
// See all types of messages in file
logOutputsForFile = LOG_ERROR | LOG_WARNING | LOG_INFO ;
// See all ERROR and WARNING messages at debugstream. Suppress 'info()' messages.
logOutputsForDebugStream = LOG_ERROR | LOG_WARNING ;
// Start up GDI+, which we use to draw
// For GDI+, used only for shape render
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
// Setup the window
window = new GameWindow( hInstance, TEXT( "pacman" ),
32, 32, // x pos, y pos
640, 480// width, height
) ;
// After the window comes up, we call Init
// to load the game's content
Init() ;
MSG message ;
while( 1 )
{
if( PeekMessage( &message, NULL, 0, 0, PM_REMOVE ) )
{
if( message.message == WM_QUIT ) // if we got a WM_QUIT message..
{
break ; // ..then end the program by jumping out of the while(1) loop.
}
// Send the message over to WndProc for
// further processing.
TranslateMessage( &message ) ;
DispatchMessage( &message ) ;
}
else
{
// Run our game, one frame
Update() ;
window->step() ; // ^^ update fmod engine, grab updated keystates, etc.
// Draw the game out, all at once
if( window->beginDrawing() ) // only continue if beginDrawing() succeeds
{
Draw() ;
window->endDrawing() ;
}
}
}
info( "Game over!" ) ;
logShutdown() ;
GdiplusShutdown(gdiplusToken);
//system( "pause" ) ; // uncomment to make it pause before exit
return 0 ;
}
|
#ifndef BOOST_NUMERIC_BINDINGS_TRAITS_UBLAS_SYMMETRIC_ADAPTOR_H
#define BOOST_NUMERIC_BINDINGS_TRAITS_UBLAS_SYMMETRIC_ADAPTOR_H
#include <boost/numeric/binding/lapack/driver/syev.hpp>
#include <boost/numeric/binding/traits/ublas_symmetric.hpp>
namespace boost { namespace numeric { namespace ublas {
/*
template<typename Matrix>
symmetric_adaptor<M,ublas::upper> upper(Matrix& m) {
return symmetric_adaptor<Matrix, upper>(m);
}
template<typename Matrix>
symmetric_adaptor<M,ublas::lower> lower(Matrix& m) {
return symmetric_adaptor<Matrix, lower>(m);
}
*/
}}}
namespace boost { namespace numeric { namespace bindings { namespace lapack {
// template function to call syev, default workspace type
template< typename MatrixA, typename VectorW >
inline integer_t syev( char const jobz, MatrixA&& a, VectorW& w ) {
typedef typename traits::matrix_traits< MatrixA >::value_type value_type;
integer_t info(0);
syev_impl< value_type >::invoke( jobz, a, w, info, optimal_workspace() );
return info;
}
}}}}
#endif // BOOST_NUMERIC_BINDINGS_TRAITS_UBLAS_SYMMETRIC_ADAPTOR_H
|
#ifndef CPOINT_H
#define CPOINT_H
#include "Defs.h"
#include <QVector>
class CPoint
{
private:
QVector<double> params;
WORD groupNr;
double alpha;
double distance;
public:
CPoint(QVector<double> params);
CPoint();
void setParams(QVector<double> params);
void setGroup(WORD groupNr);
void setAlpha(double alpha) { this->alpha = alpha; }
void setDistance(double dist) { this->distance = dist; }
double ¶mAt(WORD index) { return params[index]; }
QVector<double> getParams()const {return params;}
WORD getDimensions()const { return params.size(); }
WORD getGroup()const { return groupNr; }
double getAlpha()const { return alpha; }
double getDistance()const { return distance; }
double operator-(CPoint j);
};
#endif // CPOINT_H
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
string a,b;
cin>>a>>b;
if(a.length() >b.length() )
{
string temp = a;
a = b;
b = temp;
}
int i= 0, j = 0 , flag = 0;
while(i<a.length())
{
while(j<b.length())
{
if(a[i] == b[j])
{
i++;
}
j++;
}
if(j == b.length() && i!= a.length())
{
cout<<"NO"<<endl;
flag = 1;
break;
}
}
if(flag == 0)
cout<<"YES"<<endl;
}
}
|
#include <gtest/gtest.h>
#include "kth_cprog_template_container.hpp"
#include "counter_class.hpp"
TEST(Vector, ConstructorDefault) {
EXPECT_NO_THROW({
Vector<int> int_vector;
});
}
TEST(Vector, ConstructorCopy) {
const size_t size = 4;
Vector<int> int_vector1(size);
int_vector1[1] = 13;
int_vector1[2] = 14;
Vector<int> int_vector2(int_vector1);
for(size_t i = 0; i < int_vector1.size(); ++i) {
EXPECT_EQ(int_vector1[i], int_vector2[i]);
}
int_vector1[1] = 12;
int_vector2[1] = 23;
int_vector2[3] = 25;
EXPECT_EQ(0, int_vector1[0]);
EXPECT_EQ(12, int_vector1[1]);
EXPECT_EQ(14, int_vector1[2]);
EXPECT_EQ(0, int_vector1[3]);
EXPECT_EQ(0, int_vector2[0]);
EXPECT_EQ(23, int_vector2[1]);
EXPECT_EQ(14, int_vector2[2]);
EXPECT_EQ(25, int_vector2[3]);
}
TEST(Vector, ConstructorInitlist) {
Vector<int> int_vector({ 13, 14, 15, 16 });
EXPECT_EQ(13, int_vector[0]);
EXPECT_EQ(14, int_vector[1]);
EXPECT_EQ(15, int_vector[2]);
EXPECT_EQ(16, int_vector[3]);
EXPECT_EQ(4, int_vector.size());
}
TEST(Vector, ConstructorMove) {
Vector<int> int_vector1({ 13, 14, 15, 16 });
EXPECT_EQ(13, int_vector1[0]);
Vector<int> int_vector2(std::move(int_vector1));
EXPECT_EQ(13, int_vector2[0]);
}
TEST(Vector, ConstructorMoveReuse) {
Vector<int> int_vector1({ 13, 14, 15, 16 });
Vector<int> int_vector2(std::move(int_vector1));
EXPECT_THROW({
int_vector1[3];
}, std::out_of_range);
EXPECT_THROW({
int_vector1[3] = 14;
}, std::out_of_range);
int_vector1.push_back(1);
EXPECT_EQ(1, int_vector1[0]);
EXPECT_EQ(1, int_vector1.size());
}
TEST(Vector, ConstructorSelfMove) {
Vector<int> int_vector1({ 13, 14, 15, 16 });
int_vector1 = std::move(int_vector1);
EXPECT_EQ(13, int_vector1[0]);
EXPECT_EQ(14, int_vector1[1]);
EXPECT_EQ(15, int_vector1[2]);
EXPECT_EQ(16, int_vector1[3]);
EXPECT_EQ(4, int_vector1.size());
}
TEST(Vector, ConstructorSize) {
const size_t size = 32;
Vector<int> int_vector(size);
EXPECT_EQ(size, int_vector.size());
for(size_t i = 0; i < size; i++) {
EXPECT_EQ(0, int_vector[i]);
}
}
TEST(Vector, ConstructorZeroSize) {
const size_t size = 0;
Vector<int> int_vector(size);
EXPECT_EQ(size, int_vector.size());
}
TEST(Vector, ConstructorRepeat) {
const size_t size = 4;
Vector<int> int_vector(size, 13);
for(size_t i = 0; i < size; i++) {
EXPECT_EQ(13, int_vector[i]);
}
}
TEST(Vector, OperatorBracketWrite) {
const size_t size = 4;
Vector<int> int_vector(size);
EXPECT_EQ(0, int_vector[0]);
int_vector[0] = 10;
int_vector[1] = 20;
int_vector[2] = 30;
int_vector[3] = 40;
EXPECT_EQ(10, int_vector[0]);
EXPECT_EQ(20, int_vector[1]);
EXPECT_EQ(30, int_vector[2]);
EXPECT_EQ(40, int_vector[3]);
}
TEST(Vector, OperatorBracketRange) {
const size_t size = 4;
Vector<int> int_vector(size);
EXPECT_THROW({
int_vector[size];
}, std::out_of_range);
EXPECT_THROW({
int_vector[-1];
}, std::out_of_range);
}
TEST(Vector, OperatorBracketConst) {
const Vector<int> int_vector(4, 13);
EXPECT_EQ(13, int_vector[0]);
EXPECT_EQ(13, int_vector[1]);
EXPECT_EQ(13, int_vector[2]);
EXPECT_EQ(13, int_vector[3]);
}
TEST(Vector, OperatorAssignment) {
const size_t size = 4;
Vector<int> int_vector1(size);
int_vector1[1] = 13;
Vector<int> int_vector2 = int_vector1;
int_vector1[2] = 14;
int_vector2[3] = 15;
EXPECT_EQ(13, int_vector1[1]);
EXPECT_EQ(13, int_vector2[1]);
EXPECT_EQ(14, int_vector1[2]);
EXPECT_EQ(0, int_vector1[3]);
EXPECT_EQ(0, int_vector2[2]);
EXPECT_EQ(15, int_vector2[3]);
}
TEST(Vector, OperatorAssignmentSelf) {
Vector<int> int_vector = { 13, 14, 15, 16 };
EXPECT_EQ(13, int_vector[0]);
EXPECT_EQ(14, int_vector[1]);
EXPECT_EQ(15, int_vector[2]);
EXPECT_EQ(16, int_vector[3]);
int_vector = int_vector;
EXPECT_EQ(4, int_vector.size());
EXPECT_EQ(13, int_vector[0]);
EXPECT_EQ(14, int_vector[1]);
EXPECT_EQ(15, int_vector[2]);
EXPECT_EQ(16, int_vector[3]);
}
TEST(Vector, OperatorAssignmentList) {
Vector<int> int_vector = { 13, 14, 15, 16 };
EXPECT_EQ(13, int_vector[0]);
EXPECT_EQ(14, int_vector[1]);
EXPECT_EQ(15, int_vector[2]);
EXPECT_EQ(16, int_vector[3]);
EXPECT_EQ(4, int_vector.size());
}
TEST(Vector, OperatorAssignmentMove) {
std::unique_ptr<Vector<int> > int_vector1(new Vector<int>({ 13, 14, 15, 16 }));
EXPECT_EQ(13, (*int_vector1)[0]);
std::unique_ptr<Vector<int> > int_vector2 = std::move(int_vector1);
EXPECT_EQ(13, (*int_vector2)[0]);
}
TEST(Vector, PushBack) {
Vector<int> int_vector;
for(size_t i = 0; i < 32; i++) {
EXPECT_EQ(i, int_vector.size());
int_vector.push_back(i);
EXPECT_EQ(i, int_vector[i]);
EXPECT_EQ(i+1, int_vector.size());
}
for(size_t i = 0; i < 32; i++) {
EXPECT_EQ(i, int_vector[i]);
}
}
TEST(Vector, Insert) {
const size_t size = 4;
Vector<int> int_vector(size);
EXPECT_EQ(0, int_vector[1]);
int_vector.insert(1, 13);
EXPECT_EQ(13, int_vector[1]);
EXPECT_EQ(size + 1, int_vector.size());
}
TEST(Vector, InsertALotOfItems) {
const size_t size = 1;
const size_t final_size = 10000;
Vector<int> int_vector(size);
while(int_vector.size() < final_size) {
int_vector.insert(int_vector.size(), int_vector.size());
}
EXPECT_EQ(final_size, int_vector.size());
}
TEST(Vector, InsertBeginning) {
const size_t size = 4;
Vector<int> int_vector(size);
EXPECT_EQ(0, int_vector[1]);
int_vector.insert(0, 14);
int_vector.insert(0, 13);
EXPECT_EQ(13, int_vector[0]);
EXPECT_EQ(14, int_vector[1]);
EXPECT_EQ(size + 2, int_vector.size());
}
TEST(Vector, InsertEnd) {
const size_t size = 4;
Vector<int> int_vector(size);
EXPECT_EQ(0, int_vector[1]);
int_vector.insert(int_vector.size(), 13);
EXPECT_EQ(13, int_vector[size]);
EXPECT_EQ(size + 1, int_vector.size());
}
TEST(Vector, InsertRange) {
const size_t size = 4;
Vector<int> int_vector(size);
EXPECT_THROW({
int_vector.insert(size+2, 13);
}, std::out_of_range);
}
TEST(Vector, Erase) {
const size_t size = 4;
Vector<int> int_vector(size);
int_vector[1] = 13;
int_vector[2] = 14;
int_vector.erase(1);
EXPECT_EQ(size - 1, int_vector.size());
EXPECT_EQ(14, int_vector[1]);
}
TEST(Vector, EraseRange) {
const size_t size = 4;
Vector<int> int_vector(size);
EXPECT_THROW({
int_vector.erase(size);
}, std::out_of_range);
}
TEST(Vector, Clear) {
const size_t size = 4;
Vector<int> int_vector(size);
int_vector.clear();
EXPECT_EQ(0, int_vector.size());
}
TEST(Vector, SortAscending) {
const size_t size = 4;
Vector<int> int_vector(size);
int_vector[0] = 40;
int_vector[1] = 20;
int_vector[2] = 30;
int_vector[3] = 10;
int_vector.sort();
EXPECT_EQ(10, int_vector[0]);
EXPECT_EQ(20, int_vector[1]);
EXPECT_EQ(30, int_vector[2]);
EXPECT_EQ(40, int_vector[3]);
}
TEST(Vector, SortDescending) {
const size_t size = 4;
Vector<int> int_vector(size);
int_vector[0] = 40;
int_vector[1] = 20;
int_vector[2] = 30;
int_vector[3] = 10;
int_vector.sort(false);
EXPECT_EQ(40, int_vector[0]);
EXPECT_EQ(30, int_vector[1]);
EXPECT_EQ(20, int_vector[2]);
EXPECT_EQ(10, int_vector[3]);
}
TEST(Vector, SortUniqueAscending) {
const size_t size = 4;
Vector<int> int_vector(size);
int_vector[0] = 30;
int_vector[1] = 20;
int_vector[2] = 30;
int_vector[3] = 10;
int_vector.unique_sort();
EXPECT_EQ(3, int_vector.size());
EXPECT_EQ(10, int_vector[0]);
EXPECT_EQ(20, int_vector[1]);
EXPECT_EQ(30, int_vector[2]);
}
TEST(Vector, SortUniqueDescending) {
const size_t size = 4;
Vector<int> int_vector(size);
int_vector[0] = 30;
int_vector[1] = 20;
int_vector[2] = 30;
int_vector[3] = 10;
int_vector.unique_sort(false);
EXPECT_EQ(3, int_vector.size());
EXPECT_EQ(30, int_vector[0]);
EXPECT_EQ(20, int_vector[1]);
EXPECT_EQ(10, int_vector[2]);
}
TEST(Vector, ExistsTrue) {
const size_t size = 4;
Vector<int> int_vector(size);
int_vector[2] = 13;
EXPECT_TRUE(int_vector.exists(13));
int_vector[3] = 15;
EXPECT_TRUE(int_vector.exists(15));
}
TEST(Vector, ExistsFalse) {
const size_t size = 4;
Vector<int> int_vector(size);
int_vector[2] = 13;
EXPECT_FALSE(int_vector.exists(14));
}
TEST(Vector, Size) {
const size_t size = 4;
Vector<int> int_vector(size);
EXPECT_EQ(size, int_vector.size());
}
TEST(Vector, Capacity) {
const size_t size = 16;
Vector<int> int_vector(size);
EXPECT_EQ(16, int_vector.capacity());
int_vector.push_back(1);
EXPECT_EQ(32, int_vector.capacity());
}
TEST(Vector, StreamInput) {
std::stringstream ss;
ss << Vector<int>({0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597});
EXPECT_EQ("[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597]", ss.str());
}
TEST(Vector, Basic1) {
Vector<int> A(1024, 5);
Vector<int> B(1024, 6);
A = std::move(A);
B = B;
EXPECT_EQ(6, B[512]);
}
TEST(Vector, Kattis1) {
Vector<std::string> a;
a.push_back("10");
a.push_back("10");
a.push_back("10");
a.push_back("10");
a.push_back("10");
a.push_back("10");
a.push_back("10");
a.push_back("10");
a.push_back("10");
a.push_back("10");
a.push_back("10");
a.push_back("10");
a.push_back("10");
a.push_back("10");
a.push_back("10");
a.push_back("10");
a.push_back("10");
}
TEST(Vector, Kattis2) {
Vector<std::string> a(1000, "A");
a.push_back("B");
a.insert(0, "C");
}
TEST(Vector, Kattis3) {
Vector<CounterClass> a(10, 42);
a.erase(0);
EXPECT_EQ(9, CounterClass::object_count);
}
TEST(Vector, Kattis4) {
Vector<CounterClass> a;
a.insert(0, 42);
a.insert(0, -43);
a.insert(1, 44);
a.insert(3, 45);
a.insert(0, 42);
EXPECT_EQ(5, CounterClass::object_count);
}
TEST(Vector, Kattis5) {
Vector<CounterClass> a{ 1, 2, 3, 4, 5 };
Vector<CounterClass> b(10);
//EXPECT_EQ(10, a.size());
Vector<CounterClass> c(0);
c = a;
a = b;
Vector<CounterClass> d(c);
/*EXPECT_EQ(10, a.size());
EXPECT_EQ(10, b.size());
EXPECT_EQ(10, c.size());*/
a[1] = 10;
b[2] = 11;
b.erase(0);
c[3] = 12;
c.erase(1);
/*EXPECT_EQ(10, a[1]);
EXPECT_NE(11, b[2]);
EXPECT_NE(12, c[3]);*/
//a.clear();
a.reset();
//EXPECT_EQ(0, a.size());
c = std::move(a);
a.clear();
c[3] = 25;
a = std::move(c);
b = a;
}
|
#include "./utils/test_utils.hpp"
#include <string>
#include <vrm/pp/utils.hpp>
#include <vrm/pp/eval.hpp>
#include <vrm/pp/bool.hpp>
#include <vrm/pp/arithmetic.hpp>
int main()
{
#define TEMP_TEST_TEN 10
#define TEMP_TEST_TEN_TX() 10
TEST_ASSERT_OP(10, ==, 10);
TEST_ASSERT_OP(10, ==, VRM_PP_DEFER(10));
TEST_ASSERT_OP(10, ==, VRM_PP_OBSTRUCT(10));
TEST_ASSERT_OP(10, ==, TEMP_TEST_TEN);
TEST_ASSERT_OP(10, ==, VRM_PP_DEFER(TEMP_TEST_TEN));
TEST_ASSERT_OP(10, ==, VRM_PP_OBSTRUCT(TEMP_TEST_TEN));
TEST_ASSERT_OP(TEMP_TEST_TEN, ==, TEMP_TEST_TEN);
TEST_ASSERT_OP(TEMP_TEST_TEN, ==, VRM_PP_DEFER(TEMP_TEST_TEN));
TEST_ASSERT_OP(TEMP_TEST_TEN, ==, VRM_PP_OBSTRUCT(TEMP_TEST_TEN));
TEST_ASSERT_OP(TEMP_TEST_TEN_TX(), ==, 10);
// Does not compile, as expected:
// {
// auto i = VRM_PP_DEFER(TEMP_TEST_TEN_TX)();
// TEST_ASSERT_OP(i, ==, 10);
// }
// Does not compile, as expected:
// {
// auto i = VRM_PP_OBSTRUCT(TEMP_TEST_TEN_TX)();
// TEST_ASSERT_OP(i, ==, 10);
// }
{
auto i = VRM_PP_DEFER(VRM_PP_DEFER(TEMP_TEST_TEN_TX)());
TEST_ASSERT_OP(i, ==, 10);
}
{
auto i =
VRM_PP_EXPAND(VRM_PP_EXPAND(VRM_PP_OBSTRUCT(TEMP_TEST_TEN_TX)()));
TEST_ASSERT_OP(i, ==, 10);
}
{
auto i = VRM_PP_EVAL(VRM_PP_DEFER(TEMP_TEST_TEN_TX)());
TEST_ASSERT_OP(i, ==, 10);
}
{
auto i =
VRM_PP_EVAL(VRM_PP_EXPAND(VRM_PP_OBSTRUCT(TEMP_TEST_TEN_TX)()));
TEST_ASSERT_OP(i, ==, 10);
}
{
auto i = VRM_PP_EVAL(VRM_PP_OBSTRUCT(TEMP_TEST_TEN_TX)());
TEST_ASSERT_OP(i, ==, 10);
}
#undef TEMP_TEST_TEN
#undef TEMP_TEST_TEN_TX
#define WHEN(c) VRM_PP_IF(c, VRM_PP_EXPAND, VRM_PP_EAT)
/*
#define WHILE_INDIRECT() WHILE
#define WHILE(pred, op, ...) \
WHEN(pred(__VA_ARGS__)) \
(VRM_PP_DEFER(WHILE_INDIRECT)()(pred, op, op(__VA_ARGS__)), __VA_ARGS__)
*/
#define REPEAT_INDIRECT() REPEAT
#define REPEAT(count, macro, ...) \
WHEN(count) \
(VRM_PP_OBSTRUCT(REPEAT_INDIRECT)()(VRM_PP_DECREMENT(count), macro, \
__VA_ARGS__)VRM_PP_OBSTRUCT(macro)(VRM_PP_DECREMENT(count), \
__VA_ARGS__))
#define TEMP_TEST_M(i, _) i
auto x = VRM_PP_TOSTR(VRM_PP_EVAL(REPEAT(8, TEMP_TEST_M, ~)));
TEST_ASSERT_OP(x, ==, std::string{"01234567"});
#undef TEMP_TEST_M
#undef REPEAT
#undef REPEAT_INDIRECT
// #undef WHILE
// #undef WHILE_INDIRECT
#undef WHEN
return 0;
}
|
#include <iostream>
using namespace std;
int main() {
int first;
cout << "Enter the first number:";
cin >> first;
int second;
cout << "Enter the second number:";
cin >> second;
int big = 0;
for (int i = 1; i <= first && i <= second; i++) {
if (first % i == 0 && second % i == 0) {
big = i;
}
}
cout << big;
return 0;
}
|
#ifndef SLP_FUNC_H_
#define SLP_FUNC_H_
#define eta 0.015
const int op_nodes=10;
const int image_size=784;
using namespace std;
void slp_func(float (&weights_ARR_in)[10][784], double image[784], float (&weights_ARR_out)[10][784], int image_number, int outcome);//, int image_size, int op_nodes);
#endif
|
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// # DARK PLUGIN - POWERED BY FIRE TEAM
// # GAME SERVER: 99.60T (C) WEBZEN.
// # VERSÃO: 1.0.0.0
// # Autor: Maykon
// # Skype: Maykon.ale
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// # O Senhor é meu pastor e nada me faltará!
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#pragma once
struct DuelPlayer
{
bool Die;
bool Quit;
BYTE Score;
LPOBJ lpObj;
};
class DuelEvent
{
public:
DuelEvent();
~DuelEvent();
public:
bool Load();
bool Check(LPOBJ lpObj, const char* Text);
void Start(int Time, int Class);
void Run();
bool Attack(LPOBJ lpObj, LPOBJ lpTargetObj);
void Die(LPOBJ lpObj);
void Quit(LPOBJ lpObj);
private:
bool _Active;
char _Syntax[2][25];
char _Query[255];
char _Notice[60];
BYTE _MapNumber[2];
BYTE _X[2];
BYTE _Y[2];
BYTE _State;
BYTE _Type;
int _Count;
std::vector<DuelPlayer> _Players[2];
DuelPlayer _Selected[2];
private:
enum State
{
Empty, Register, Select, Progress, Died, NextStage, WO, Final
};
};
extern DuelEvent Duel;
|
#include <iostream>
using namespace std;
// Fixed coin values
const int COINS_PER_DOLLAR = 100;
const int VALUE_OF_PENNY = 1, VALUE_OF_NICKEL = 5,
VALUE_OF_DIME = 10, VALUE_OF_QUARTER = 25;
// number of specific coins per dollar
const int PENNIES_PER_DOLLAR = 100, NICKELS_PER_DOLLAR = 20,
DIMES_PER_DOLLAR = 10, QUARTERS_PER_DOLLAR = 4;
int main()
{
// Number of each coin inputed by the user
int numberOfPennies, numberOfNickels,
numberOfDimes, numberOfQuarters;
// total dollars, cents, cents carry over
int totalDollars, totalCents, totalCentsCarryOver, totalCentsToDollars;
//cents to dollars cents carry over carry over value
int q_to_d, carriedOverQuarters, quarterCarryOverValue;
int d_to_d, carriedOverDimes, dimeCarryOverValue;
int n_to_d, carriedOverNickels, nickelCarryOverValue;
int p_to_d, carriedOverPennies, pennyCarryOverValue;
cout << "# of quarters: ";
cin >> numberOfQuarters;
cout << "# of dimes: ";
cin >> numberOfDimes;
cout << "# of nickels: ";
cin >> numberOfNickels;
cout << "# of pennies: ";
cin >> numberOfPennies;
// Quarters
q_to_d = numberOfQuarters / QUARTERS_PER_DOLLAR;
carriedOverQuarters = numberOfQuarters % QUARTERS_PER_DOLLAR;
quarterCarryOverValue = VALUE_OF_QUARTER * carriedOverQuarters;
// Dimes
d_to_d = numberOfDimes / DIMES_PER_DOLLAR;
carriedOverDimes = numberOfDimes % DIMES_PER_DOLLAR;
dimeCarryOverValue = VALUE_OF_DIME * carriedOverDimes;
// Nickels
n_to_d = numberOfNickels / NICKELS_PER_DOLLAR;
carriedOverNickels = numberOfNickels % NICKELS_PER_DOLLAR;
nickelCarryOverValue = VALUE_OF_NICKEL * carriedOverNickels;
// Pennies
p_to_d = numberOfPennies / PENNIES_PER_DOLLAR;
carriedOverPennies = numberOfPennies % PENNIES_PER_DOLLAR;
pennyCarryOverValue = VALUE_OF_PENNY * carriedOverPennies;
//Total Cents
totalCents = pennyCarryOverValue + dimeCarryOverValue + nickelCarryOverValue + quarterCarryOverValue + totalCentsCarryOver;
//Total cents carry over
totalCentsToDollars = totalCents / COINS_PER_DOLLAR;
totalCentsCarryOver = totalCents % COINS_PER_DOLLAR;
//Total Dollars
totalDollars = q_to_d + d_to_d + n_to_d + p_to_d + totalCentsToDollars;
cout << "The total is " << totalDollars << " and " << totalCentsCarryOver << " cents."<< endl;
return 0;
}
|
// This file has been generated by Py++.
#include "boost/python.hpp"
#include "generators/include/python_CEGUI.h"
#include "TreeItem.pypp.hpp"
namespace bp = boost::python;
struct TreeItem_wrapper : CEGUI::TreeItem, bp::wrapper< CEGUI::TreeItem > {
TreeItem_wrapper(CEGUI::TreeItem const & arg )
: CEGUI::TreeItem( arg )
, bp::wrapper< CEGUI::TreeItem >(){
// copy constructor
}
TreeItem_wrapper(::CEGUI::String const & text, ::CEGUI::uint item_id=0, void * item_data=0, bool disabled=false, bool auto_delete=true )
: CEGUI::TreeItem( boost::ref(text), item_id, item_data, disabled, auto_delete )
, bp::wrapper< CEGUI::TreeItem >(){
// constructor
}
::CEGUI::Colour calculateModulatedAlphaColour( ::CEGUI::Colour col, float alpha ) const {
return CEGUI::TreeItem::calculateModulatedAlphaColour( col, alpha );
}
virtual void draw( ::CEGUI::GeometryBuffer & buffer, ::CEGUI::Rectf const & targetRect, float alpha, ::CEGUI::Rectf const * clipper ) const {
if( bp::override func_draw = this->get_override( "draw" ) )
func_draw( boost::ref(buffer), boost::ref(targetRect), alpha, boost::python::ptr(clipper) );
else{
this->CEGUI::TreeItem::draw( boost::ref(buffer), boost::ref(targetRect), alpha, boost::python::ptr(clipper) );
}
}
void default_draw( ::CEGUI::GeometryBuffer & buffer, ::CEGUI::Rectf const & targetRect, float alpha, ::CEGUI::Rectf const * clipper ) const {
CEGUI::TreeItem::draw( boost::ref(buffer), boost::ref(targetRect), alpha, boost::python::ptr(clipper) );
}
::CEGUI::ColourRect getModulateAlphaColourRect( ::CEGUI::ColourRect const & cols, float alpha ) const {
return CEGUI::TreeItem::getModulateAlphaColourRect( boost::ref(cols), alpha );
}
virtual ::CEGUI::Sizef getPixelSize( ) const {
if( bp::override func_getPixelSize = this->get_override( "getPixelSize" ) )
return func_getPixelSize( );
else{
return this->CEGUI::TreeItem::getPixelSize( );
}
}
::CEGUI::Sizef default_getPixelSize( ) const {
return CEGUI::TreeItem::getPixelSize( );
}
virtual bool handleFontRenderSizeChange( ::CEGUI::Font const * const font ) {
if( bp::override func_handleFontRenderSizeChange = this->get_override( "handleFontRenderSizeChange" ) )
return func_handleFontRenderSizeChange( font );
else{
return this->CEGUI::TreeItem::handleFontRenderSizeChange( font );
}
}
bool default_handleFontRenderSizeChange( ::CEGUI::Font const * const font ) {
return CEGUI::TreeItem::handleFontRenderSizeChange( font );
}
void parseTextString( ) const {
CEGUI::TreeItem::parseTextString( );
}
};
void register_TreeItem_class(){
{ //::CEGUI::TreeItem
typedef bp::class_< TreeItem_wrapper > TreeItem_exposer_t;
TreeItem_exposer_t TreeItem_exposer = TreeItem_exposer_t( "TreeItem", bp::init< CEGUI::String const &, bp::optional< CEGUI::uint, void *, bool, bool > >(( bp::arg("text"), bp::arg("item_id")=(::CEGUI::uint)(0), bp::arg("item_data")=bp::object(), bp::arg("disabled")=(bool)(false), bp::arg("auto_delete")=(bool)(true) ), "*************************************************************************\n\
Construction and Destruction\n\
*************************************************************************\n\
*!\n\
\n\
base class constructor\n\
*\n") );
bp::scope TreeItem_scope( TreeItem_exposer );
bp::implicitly_convertible< CEGUI::String const &, CEGUI::TreeItem >();
{ //::CEGUI::TreeItem::addItem
typedef void ( ::CEGUI::TreeItem::*addItem_function_type )( ::CEGUI::TreeItem * ) ;
TreeItem_exposer.def(
"addItem"
, addItem_function_type( &::CEGUI::TreeItem::addItem )
, ( bp::arg("item") ) );
}
{ //::CEGUI::TreeItem::calculateModulatedAlphaColour
typedef ::CEGUI::Colour ( TreeItem_wrapper::*calculateModulatedAlphaColour_function_type )( ::CEGUI::Colour,float ) const;
TreeItem_exposer.def(
"calculateModulatedAlphaColour"
, calculateModulatedAlphaColour_function_type( &TreeItem_wrapper::calculateModulatedAlphaColour )
, ( bp::arg("col"), bp::arg("alpha") )
, "*!\n\
\n\
Return a colour value describing the colour specified by col after\n\
having its alpha component modulated by the value alpha.\n\
*\n" );
}
{ //::CEGUI::TreeItem::draw
typedef void ( ::CEGUI::TreeItem::*draw_function_type )( ::CEGUI::GeometryBuffer &,::CEGUI::Rectf const &,float,::CEGUI::Rectf const * ) const;
typedef void ( TreeItem_wrapper::*default_draw_function_type )( ::CEGUI::GeometryBuffer &,::CEGUI::Rectf const &,float,::CEGUI::Rectf const * ) const;
TreeItem_exposer.def(
"draw"
, draw_function_type(&::CEGUI::TreeItem::draw)
, default_draw_function_type(&TreeItem_wrapper::default_draw)
, ( bp::arg("buffer"), bp::arg("targetRect"), bp::arg("alpha"), bp::arg("clipper") ) );
}
{ //::CEGUI::TreeItem::getButtonLocation
typedef ::CEGUI::Rectf & ( ::CEGUI::TreeItem::*getButtonLocation_function_type )( ) ;
TreeItem_exposer.def(
"getButtonLocation"
, getButtonLocation_function_type( &::CEGUI::TreeItem::getButtonLocation )
, bp::return_value_policy< bp::reference_existing_object >() );
}
{ //::CEGUI::TreeItem::getFont
typedef ::CEGUI::Font const * ( ::CEGUI::TreeItem::*getFont_function_type )( ) const;
TreeItem_exposer.def(
"getFont"
, getFont_function_type( &::CEGUI::TreeItem::getFont )
, bp::return_value_policy< bp::reference_existing_object >()
, "*************************************************************************\n\
Accessors\n\
*************************************************************************\n\
*!\n\
\n\
Return a pointer to the font being used by this TreeItem\n\
\n\
This method will try a number of places to find a font to be used. If\n\
no font can be found, NULL is returned.\n\
\n\
@return\n\
Font to be used for rendering this item\n\
*\n" );
}
{ //::CEGUI::TreeItem::getID
typedef ::CEGUI::uint ( ::CEGUI::TreeItem::*getID_function_type )( ) const;
TreeItem_exposer.def(
"getID"
, getID_function_type( &::CEGUI::TreeItem::getID )
, "*!\n\
\n\
Return the current ID assigned to this tree item.\n\
\n\
Note that the system does not make use of this value, client code can\n\
assign any meaning it wishes to the ID.\n\
\n\
@return\n\
ID code currently assigned to this tree item\n\
*\n" );
}
{ //::CEGUI::TreeItem::getIsOpen
typedef bool ( ::CEGUI::TreeItem::*getIsOpen_function_type )( ) ;
TreeItem_exposer.def(
"getIsOpen"
, getIsOpen_function_type( &::CEGUI::TreeItem::getIsOpen ) );
}
{ //::CEGUI::TreeItem::getItemCount
typedef ::size_t ( ::CEGUI::TreeItem::*getItemCount_function_type )( ) const;
TreeItem_exposer.def(
"getItemCount"
, getItemCount_function_type( &::CEGUI::TreeItem::getItemCount ) );
}
{ //::CEGUI::TreeItem::getItemList
typedef ::std::vector< CEGUI::TreeItem* > & ( ::CEGUI::TreeItem::*getItemList_function_type )( ) ;
TreeItem_exposer.def(
"getItemList"
, getItemList_function_type( &::CEGUI::TreeItem::getItemList )
, bp::return_value_policy< bp::reference_existing_object >() );
}
{ //::CEGUI::TreeItem::getModulateAlphaColourRect
typedef ::CEGUI::ColourRect ( TreeItem_wrapper::*getModulateAlphaColourRect_function_type )( ::CEGUI::ColourRect const &,float ) const;
TreeItem_exposer.def(
"getModulateAlphaColourRect"
, getModulateAlphaColourRect_function_type( &TreeItem_wrapper::getModulateAlphaColourRect )
, ( bp::arg("cols"), bp::arg("alpha") )
, "*************************************************************************\n\
Implementation methods\n\
*************************************************************************\n\
*!\n\
\n\
Return a ColourRect object describing the colours in cols after\n\
having their alpha component modulated by the value alpha.\n\
*\n" );
}
{ //::CEGUI::TreeItem::getOwnerWindow
typedef ::CEGUI::Window const * ( ::CEGUI::TreeItem::*getOwnerWindow_function_type )( ) ;
TreeItem_exposer.def(
"getOwnerWindow"
, getOwnerWindow_function_type( &::CEGUI::TreeItem::getOwnerWindow )
, bp::return_value_policy< bp::reference_existing_object >()
, "*!\n\
\n\
Get the owner window for this TreeItem.\n\
\n\
The owner of a TreeItem is typically set by the tree widget when an\n\
item is added or inserted.\n\
\n\
@return\n\
Ponter to the window that is considered the owner of this TreeItem.\n\
*\n" );
}
{ //::CEGUI::TreeItem::getPixelSize
typedef ::CEGUI::Sizef ( ::CEGUI::TreeItem::*getPixelSize_function_type )( ) const;
typedef ::CEGUI::Sizef ( TreeItem_wrapper::*default_getPixelSize_function_type )( ) const;
TreeItem_exposer.def(
"getPixelSize"
, getPixelSize_function_type(&::CEGUI::TreeItem::getPixelSize)
, default_getPixelSize_function_type(&TreeItem_wrapper::default_getPixelSize) );
}
{ //::CEGUI::TreeItem::getSelectionBrushImage
typedef ::CEGUI::Image const * ( ::CEGUI::TreeItem::*getSelectionBrushImage_function_type )( ) const;
TreeItem_exposer.def(
"getSelectionBrushImage"
, getSelectionBrushImage_function_type( &::CEGUI::TreeItem::getSelectionBrushImage )
, bp::return_value_policy< bp::reference_existing_object >()
, "*!\n\
\n\
Return the current selection highlighting brush.\n\
\n\
@return\n\
Pointer to the Image object currently used for selection highlighting.\n\
*\n" );
}
{ //::CEGUI::TreeItem::getSelectionColours
typedef ::CEGUI::ColourRect ( ::CEGUI::TreeItem::*getSelectionColours_function_type )( ) const;
TreeItem_exposer.def(
"getSelectionColours"
, getSelectionColours_function_type( &::CEGUI::TreeItem::getSelectionColours )
, "*!\n\
\n\
Return the current colours used for selection highlighting.\n\
\n\
@return\n\
ColourRect object describing the currently set colours.\n\
*\n" );
}
{ //::CEGUI::TreeItem::getText
typedef ::CEGUI::String const & ( ::CEGUI::TreeItem::*getText_function_type )( ) const;
TreeItem_exposer.def(
"getText"
, getText_function_type( &::CEGUI::TreeItem::getText )
, bp::return_value_policy< bp::copy_const_reference >()
, "*!\n\
\n\
return the text string set for this tree item.\n\
\n\
Note that even if the item does not render text, the text string can\n\
still be useful, since it is used for sorting tree items.\n\
\n\
@return\n\
String object containing the current text for the tree item.\n\
*\n" );
}
{ //::CEGUI::TreeItem::getTextColours
typedef ::CEGUI::ColourRect ( ::CEGUI::TreeItem::*getTextColours_function_type )( ) const;
TreeItem_exposer.def(
"getTextColours"
, getTextColours_function_type( &::CEGUI::TreeItem::getTextColours )
, "*!\n\
\n\
Return the current colours used for text rendering.\n\
\n\
@return\n\
ColourRect object describing the currently set colours\n\
*\n" );
}
{ //::CEGUI::TreeItem::getTextVisual
typedef ::CEGUI::String const & ( ::CEGUI::TreeItem::*getTextVisual_function_type )( ) const;
TreeItem_exposer.def(
"getTextVisual"
, getTextVisual_function_type( &::CEGUI::TreeItem::getTextVisual )
, bp::return_value_policy< bp::copy_const_reference >()
, "! return text string with e visual ordering of glyphs.\n" );
}
{ //::CEGUI::TreeItem::getTooltipText
typedef ::CEGUI::String const & ( ::CEGUI::TreeItem::*getTooltipText_function_type )( ) const;
TreeItem_exposer.def(
"getTooltipText"
, getTooltipText_function_type( &::CEGUI::TreeItem::getTooltipText )
, bp::return_value_policy< bp::copy_const_reference >()
, "*!\n\
\n\
Return the text string currently set to be used as the tooltip text for\n\
this item.\n\
\n\
@return\n\
String object containing the current tooltip text as sued by this item.\n\
*\n" );
}
{ //::CEGUI::TreeItem::getTreeItemFromIndex
typedef ::CEGUI::TreeItem * ( ::CEGUI::TreeItem::*getTreeItemFromIndex_function_type )( ::size_t ) ;
TreeItem_exposer.def(
"getTreeItemFromIndex"
, getTreeItemFromIndex_function_type( &::CEGUI::TreeItem::getTreeItemFromIndex )
, ( bp::arg("itemIndex") )
, bp::return_value_policy< bp::reference_existing_object >() );
}
{ //::CEGUI::TreeItem::getUserData
typedef void * ( ::CEGUI::TreeItem::*getUserData_function_type )( ) const;
TreeItem_exposer.def(
"getUserData"
, getUserData_function_type( &::CEGUI::TreeItem::getUserData )
, bp::return_value_policy< bp::return_opaque_pointer >()
, "*!\n\
\n\
Return the pointer to any client assigned user data attached to this\n\
tree item.\n\
\n\
Note that the system does not make use of this data, client code can\n\
assign any meaning it wishes to the attached data.\n\
\n\
@return\n\
Pointer to the currently assigned user data.\n\
*\n" );
}
{ //::CEGUI::TreeItem::handleFontRenderSizeChange
typedef bool ( ::CEGUI::TreeItem::*handleFontRenderSizeChange_function_type )( ::CEGUI::Font const * const ) ;
typedef bool ( TreeItem_wrapper::*default_handleFontRenderSizeChange_function_type )( ::CEGUI::Font const * const ) ;
TreeItem_exposer.def(
"handleFontRenderSizeChange"
, handleFontRenderSizeChange_function_type(&::CEGUI::TreeItem::handleFontRenderSizeChange)
, default_handleFontRenderSizeChange_function_type(&TreeItem_wrapper::default_handleFontRenderSizeChange)
, ( bp::arg("font") ) );
}
{ //::CEGUI::TreeItem::isAutoDeleted
typedef bool ( ::CEGUI::TreeItem::*isAutoDeleted_function_type )( ) const;
TreeItem_exposer.def(
"isAutoDeleted"
, isAutoDeleted_function_type( &::CEGUI::TreeItem::isAutoDeleted )
, "*!\n\
\n\
return whether this item will be automatically deleted when it is\n\
removed from the tree or when the the tree it is attached to is\n\
destroyed.\n\
\n\
@return\n\
- true if the item object will be deleted by the system when it is\n\
removed from the tree, or when the tree it is attached to is\n\
destroyed.\n\
- false if client code must destroy the item after it is removed from\n\
the tree.\n\
*\n" );
}
{ //::CEGUI::TreeItem::isDisabled
typedef bool ( ::CEGUI::TreeItem::*isDisabled_function_type )( ) const;
TreeItem_exposer.def(
"isDisabled"
, isDisabled_function_type( &::CEGUI::TreeItem::isDisabled )
, "*!\n\
\n\
return whether this item is disabled.\n\
\n\
@return\n\
- true if the item is disabled.\n\
- false if the item is enabled.\n\
*\n" );
}
{ //::CEGUI::TreeItem::isSelected
typedef bool ( ::CEGUI::TreeItem::*isSelected_function_type )( ) const;
TreeItem_exposer.def(
"isSelected"
, isSelected_function_type( &::CEGUI::TreeItem::isSelected )
, "*!\n\
\n\
return whether this item is selected.\n\
\n\
@return\n\
- true if the item is selected.\n\
- false if the item is not selected.\n\
*\n" );
}
TreeItem_exposer.def( bp::self < bp::self );
TreeItem_exposer.def( bp::self > bp::self );
{ //::CEGUI::TreeItem::parseTextString
typedef void ( TreeItem_wrapper::*parseTextString_function_type )( ) const;
TreeItem_exposer.def(
"parseTextString"
, parseTextString_function_type( &TreeItem_wrapper::parseTextString )
, "! parse the text visual string into a RenderString representation.\n" );
}
{ //::CEGUI::TreeItem::removeItem
typedef void ( ::CEGUI::TreeItem::*removeItem_function_type )( ::CEGUI::TreeItem const * ) ;
TreeItem_exposer.def(
"removeItem"
, removeItem_function_type( &::CEGUI::TreeItem::removeItem )
, ( bp::arg("item") ) );
}
{ //::CEGUI::TreeItem::setAutoDeleted
typedef void ( ::CEGUI::TreeItem::*setAutoDeleted_function_type )( bool ) ;
TreeItem_exposer.def(
"setAutoDeleted"
, setAutoDeleted_function_type( &::CEGUI::TreeItem::setAutoDeleted )
, ( bp::arg("setting") )
, "*!\n\
\n\
Set whether this item will be automatically deleted when it is removed\n\
from the tree, or when the tree it is attached to is destroyed.\n\
\n\
@param setting\n\
- true if the item object should be deleted by the system when the it\n\
is removed from the tree, or when the tree it is attached to is\n\
destroyed.\n\
- false if client code will destroy the item after it is removed from\n\
the tree.\n\
\n\
@return\n\
Nothing.\n\
*\n" );
}
{ //::CEGUI::TreeItem::setButtonLocation
typedef void ( ::CEGUI::TreeItem::*setButtonLocation_function_type )( ::CEGUI::Rectf & ) ;
TreeItem_exposer.def(
"setButtonLocation"
, setButtonLocation_function_type( &::CEGUI::TreeItem::setButtonLocation )
, ( bp::arg("buttonOffset") )
, "*!\n\
\n\
Tell the treeItem where its button is located.\n\
Calculated and set in Tree.cpp.\n\
\n\
@param buttonOffset\n\
Location of the button in screenspace.\n\
*\n" );
}
{ //::CEGUI::TreeItem::setDisabled
typedef void ( ::CEGUI::TreeItem::*setDisabled_function_type )( bool ) ;
TreeItem_exposer.def(
"setDisabled"
, setDisabled_function_type( &::CEGUI::TreeItem::setDisabled )
, ( bp::arg("setting") )
, "*!\n\
\n\
Set the disabled state for the item.\n\
\n\
@param setting\n\
- true if the item should be disabled.\n\
- false if the item should be enabled.\n\
\n\
@return\n\
Nothing.\n\
*\n" );
}
{ //::CEGUI::TreeItem::setFont
typedef void ( ::CEGUI::TreeItem::*setFont_function_type )( ::CEGUI::Font const * ) ;
TreeItem_exposer.def(
"setFont"
, setFont_function_type( &::CEGUI::TreeItem::setFont )
, ( bp::arg("font") )
, "*************************************************************************\n\
Manipulator methods\n\
*************************************************************************\n\
*!\n\
\n\
Set the font to be used by this TreeItem\n\
\n\
@param font\n\
Font to be used for rendering this item\n\
\n\
@return\n\
Nothing\n\
*\n" );
}
{ //::CEGUI::TreeItem::setFont
typedef void ( ::CEGUI::TreeItem::*setFont_function_type )( ::CEGUI::String const & ) ;
TreeItem_exposer.def(
"setFont"
, setFont_function_type( &::CEGUI::TreeItem::setFont )
, ( bp::arg("font_name") )
, "*!\n\
\n\
Set the font to be used by this TreeItem\n\
\n\
@param font_name\n\
String object containing the name of the Font to be used for rendering\n\
this item\n\
\n\
@return\n\
Nothing\n\
*\n" );
}
{ //::CEGUI::TreeItem::setID
typedef void ( ::CEGUI::TreeItem::*setID_function_type )( ::CEGUI::uint ) ;
TreeItem_exposer.def(
"setID"
, setID_function_type( &::CEGUI::TreeItem::setID )
, ( bp::arg("item_id") )
, "*!\n\
\n\
Set the ID assigned to this tree item.\n\
\n\
Note that the system does not make use of this value, client code can\n\
assign any meaning it wishes to the ID.\n\
\n\
@param item_id\n\
ID code to be assigned to this tree item\n\
\n\
@return\n\
Nothing.\n\
*\n" );
}
{ //::CEGUI::TreeItem::setIcon
typedef void ( ::CEGUI::TreeItem::*setIcon_function_type )( ::CEGUI::Image const & ) ;
TreeItem_exposer.def(
"setIcon"
, setIcon_function_type( &::CEGUI::TreeItem::setIcon )
, ( bp::arg("theIcon") ) );
}
{ //::CEGUI::TreeItem::setOwnerWindow
typedef void ( ::CEGUI::TreeItem::*setOwnerWindow_function_type )( ::CEGUI::Window const * ) ;
TreeItem_exposer.def(
"setOwnerWindow"
, setOwnerWindow_function_type( &::CEGUI::TreeItem::setOwnerWindow )
, ( bp::arg("owner") )
, "*!\n\
\n\
Set the owner window for this TreeItem. This is called by the tree\n\
widget when an item is added or inserted.\n\
\n\
@param owner\n\
Ponter to the window that should be considered the owner of this\n\
TreeItem.\n\
\n\
@return\n\
Nothing\n\
*\n" );
}
{ //::CEGUI::TreeItem::setSelected
typedef void ( ::CEGUI::TreeItem::*setSelected_function_type )( bool ) ;
TreeItem_exposer.def(
"setSelected"
, setSelected_function_type( &::CEGUI::TreeItem::setSelected )
, ( bp::arg("setting") )
, "*!\n\
\n\
Set the selected state for the item.\n\
\n\
@param setting\n\
- true if the item is selected.\n\
- false if the item is not selected.\n\
\n\
@return\n\
Nothing.\n\
*\n" );
}
{ //::CEGUI::TreeItem::setSelectionBrushImage
typedef void ( ::CEGUI::TreeItem::*setSelectionBrushImage_function_type )( ::CEGUI::Image const * ) ;
TreeItem_exposer.def(
"setSelectionBrushImage"
, setSelectionBrushImage_function_type( &::CEGUI::TreeItem::setSelectionBrushImage )
, ( bp::arg("image") )
, "*!\n\
\n\
Set the selection highlighting brush image.\n\
\n\
@param image\n\
Pointer to the Image object to be used for selection highlighting.\n\
\n\
@return\n\
Nothing.\n\
*\n" );
}
{ //::CEGUI::TreeItem::setSelectionBrushImage
typedef void ( ::CEGUI::TreeItem::*setSelectionBrushImage_function_type )( ::CEGUI::String const & ) ;
TreeItem_exposer.def(
"setSelectionBrushImage"
, setSelectionBrushImage_function_type( &::CEGUI::TreeItem::setSelectionBrushImage )
, ( bp::arg("name") )
, "*!\n\
\n\
Set the selection highlighting brush image.\n\
\n\
@param name\n\
Name of the image to be used.\n\
\n\
@return\n\
Nothing.\n\
*\n" );
}
{ //::CEGUI::TreeItem::setSelectionColours
typedef void ( ::CEGUI::TreeItem::*setSelectionColours_function_type )( ::CEGUI::ColourRect const & ) ;
TreeItem_exposer.def(
"setSelectionColours"
, setSelectionColours_function_type( &::CEGUI::TreeItem::setSelectionColours )
, ( bp::arg("cols") )
, "*!\n\
\n\
Set the colours used for selection highlighting.\n\
\n\
@param cols\n\
ColourRect object describing the colours to be used.\n\
\n\
@return\n\
Nothing.\n\
*\n" );
}
{ //::CEGUI::TreeItem::setSelectionColours
typedef void ( ::CEGUI::TreeItem::*setSelectionColours_function_type )( ::CEGUI::Colour,::CEGUI::Colour,::CEGUI::Colour,::CEGUI::Colour ) ;
TreeItem_exposer.def(
"setSelectionColours"
, setSelectionColours_function_type( &::CEGUI::TreeItem::setSelectionColours )
, ( bp::arg("top_left_colour"), bp::arg("top_right_colour"), bp::arg("bottom_left_colour"), bp::arg("bottom_right_colour") ) );
}
{ //::CEGUI::TreeItem::setSelectionColours
typedef void ( ::CEGUI::TreeItem::*setSelectionColours_function_type )( ::CEGUI::Colour ) ;
TreeItem_exposer.def(
"setSelectionColours"
, setSelectionColours_function_type( &::CEGUI::TreeItem::setSelectionColours )
, ( bp::arg("col") )
, "*!\n\
\n\
Set the colours used for selection highlighting.\n\
\n\
@param col\n\
colour value to be used when rendering.\n\
\n\
@return\n\
Nothing.\n\
*\n" );
}
{ //::CEGUI::TreeItem::setText
typedef void ( ::CEGUI::TreeItem::*setText_function_type )( ::CEGUI::String const & ) ;
TreeItem_exposer.def(
"setText"
, setText_function_type( &::CEGUI::TreeItem::setText )
, ( bp::arg("text") )
, "*************************************************************************\n\
Manipulators\n\
*************************************************************************\n\
*!\n\
\n\
set the text string for this tree item.\n\
\n\
Note that even if the item does not render text, the text string can\n\
still be useful, since it is used for sorting tree items.\n\
\n\
@param text\n\
String object containing the text to set for the tree item.\n\
\n\
@return\n\
Nothing.\n\
*\n" );
}
{ //::CEGUI::TreeItem::setTextColours
typedef void ( ::CEGUI::TreeItem::*setTextColours_function_type )( ::CEGUI::ColourRect const & ) ;
TreeItem_exposer.def(
"setTextColours"
, setTextColours_function_type( &::CEGUI::TreeItem::setTextColours )
, ( bp::arg("cols") )
, "*!\n\
\n\
Set the colours used for text rendering.\n\
\n\
@param cols\n\
ColourRect object describing the colours to be used.\n\
\n\
@return\n\
Nothing.\n\
*\n" );
}
{ //::CEGUI::TreeItem::setTextColours
typedef void ( ::CEGUI::TreeItem::*setTextColours_function_type )( ::CEGUI::Colour,::CEGUI::Colour,::CEGUI::Colour,::CEGUI::Colour ) ;
TreeItem_exposer.def(
"setTextColours"
, setTextColours_function_type( &::CEGUI::TreeItem::setTextColours )
, ( bp::arg("top_left_colour"), bp::arg("top_right_colour"), bp::arg("bottom_left_colour"), bp::arg("bottom_right_colour") )
, "*!\n\
\n\
Set the colours used for text rendering.\n\
\n\
@param top_left_colour\n\
Colour (as ARGB value) to be applied to the top-left corner of each text\n\
glyph rendered.\n\
\n\
@param top_right_colour\n\
Colour (as ARGB value) to be applied to the top-right corner of each\n\
text glyph rendered.\n\
\n\
@param bottom_left_colour\n\
Colour (as ARGB value) to be applied to the bottom-left corner of each\n\
text glyph rendered.\n\
\n\
@param bottom_right_colour\n\
Colour (as ARGB value) to be applied to the bottom-right corner of each\n\
text glyph rendered.\n\
\n\
@return\n\
Nothing.\n\
*\n" );
}
{ //::CEGUI::TreeItem::setTextColours
typedef void ( ::CEGUI::TreeItem::*setTextColours_function_type )( ::CEGUI::Colour ) ;
TreeItem_exposer.def(
"setTextColours"
, setTextColours_function_type( &::CEGUI::TreeItem::setTextColours )
, ( bp::arg("col") )
, "*!\n\
\n\
Set the colours used for text rendering.\n\
\n\
@param col\n\
colour value to be used when rendering.\n\
\n\
@return\n\
Nothing.\n\
*\n" );
}
{ //::CEGUI::TreeItem::setTooltipText
typedef void ( ::CEGUI::TreeItem::*setTooltipText_function_type )( ::CEGUI::String const & ) ;
TreeItem_exposer.def(
"setTooltipText"
, setTooltipText_function_type( &::CEGUI::TreeItem::setTooltipText )
, ( bp::arg("text") )
, "*!\n\
\n\
Set the tooltip text to be used for this item.\n\
\n\
@param text\n\
String object holding the text to be used in the tooltip displayed for\n\
this item.\n\
\n\
@return\n\
Nothing.\n\
*\n" );
}
{ //::CEGUI::TreeItem::setUserData
typedef void ( ::CEGUI::TreeItem::*setUserData_function_type )( void * ) ;
TreeItem_exposer.def(
"setUserData"
, setUserData_function_type( &::CEGUI::TreeItem::setUserData )
, ( bp::arg("item_data") )
, "*!\n\
\n\
Set the client assigned user data attached to this lis box item.\n\
\n\
Note that the system does not make use of this data, client code can\n\
assign any meaning it wishes to the attached data.\n\
\n\
@param item_data\n\
Pointer to the user data to attach to this tree item.\n\
\n\
@return\n\
Nothing.\n\
*\n" );
}
{ //::CEGUI::TreeItem::toggleIsOpen
typedef void ( ::CEGUI::TreeItem::*toggleIsOpen_function_type )( ) ;
TreeItem_exposer.def(
"toggleIsOpen"
, toggleIsOpen_function_type( &::CEGUI::TreeItem::toggleIsOpen ) );
}
TreeItem_exposer.def_readonly( "DefaultSelectionColour", CEGUI::TreeItem::DefaultSelectionColour, "*************************************************************************\n\
Constants\n\
*************************************************************************\n\
! Default text colour.\n\
! Default selection brush colour.\n" );
TreeItem_exposer.def_readonly( "DefaultTextColour", CEGUI::TreeItem::DefaultTextColour, "*************************************************************************\n\
Constants\n\
*************************************************************************\n\
! Default text colour.\n" );
}
}
|
/************************************************************
** File Name: RPSGame.hpp
** Author 1: Nathaniel Bennet
** Author 2: Aaron Berns
** Author 3: Juan Du
** Author 4: Christopher Dubbs
** Author 5: Chieko Duncans
** Author 6: Molly Johnson
** Author 7: Armand Reitz
** Date: 02/06/2016
** CS 162 Group Project | Play Rock Paper, Scissors!!!
** File discription: RPSGame class specification file
**************************************************************/
#include "Tool.hpp"
#include "RPS.hpp"
class RPSGame
{
private:
Tool *human_rock;
Tool *human_paper;
Tool *human_scissors;
Tool *computer_rock;
Tool *computer_paper;
Tool *computer_scissors;
int human_wins;
int computer_wins;
int ties;
char human_last_tool; // AI uses these variables in choosing next Tool
char comp_last_tool;
int last_winner;
public:
// Constructor
RPSGame (int hr, int hp, int hs, int cr, int cp, int cs);
// Destructor
~RPSGame ();
// Set human wins
void set_human_wins (int wins) {human_wins = wins;}
// Get human wins
int get_human_wins () {return human_wins;}
// Set computer wins
void set_computer_wins (int wins) {computer_wins = wins;}
// Get computer wins
int get_computer_wins () {return computer_wins;}
// Set number of ties
void set_ties (int ties_input) {ties = ties_input;}
// Get number of ties
int get_ties () {return ties;}
// Set last tool human used
void set_human_last_tool (char tool) {human_last_tool = tool;}
// Get last tool human used
char get_human_last_tool () {return human_last_tool;}
// Set last tool computer used
void set_comp_last_tool (char tool) {comp_last_tool = tool;}
// Get last tool computer used
char get_comp_last_tool () {return comp_last_tool;}
// Set last winner
void set_last_winner (int winner) {last_winner = winner;}
// Get last winner
int get_last_winner () {return last_winner;}
// AI chooses and returns next tool type
char computerChoice ();
// Fight based on computer and human choice
int play (char humanChoice, char computerChoice);
// Set winner
void set_winner (int winner);
// Prints basic stats from RPSGame
void print_stats ();
};
|
////////////////////////////////////////////////////////////////////////////////
//
// (C) Andy Thomason 2016
//
// example of FBX file decoder and encoder
//
////////////////////////////////////////////////////////////////////////////////
#include <gilgamesh/mesh.hpp>
#include <gilgamesh/scene.hpp>
#include <gilgamesh/decoders/fbx_decoder.hpp>
#include <gilgamesh/encoders/fbx_encoder.hpp>
int main(int argc, char **argv) {
const char *filename = nullptr;
for (int i = 1; i != argc; ++i) {
const char *arg = argv[i];
if (arg[0] == '-') {
printf("invalid argument %s\n", arg);
} else {
filename = arg;
}
}
if (filename == nullptr) {
filename = CMAKE_SOURCE "/examples/data/cube.fbx";
}
gilgamesh::fbx_decoder decoder;
gilgamesh::scene scene;
if (!decoder.loadScene<gilgamesh::color_mesh>(scene, filename)) {
std::cerr << "uable to open file " << filename << "\n";
return 1;
}
gilgamesh::fbx_encoder encoder;
auto bytes = encoder.saveScene(scene);
std::ofstream("out.fbx", std::ios::binary).write((char*)bytes.data(), bytes.size());
}
|
//
// Skill.h
// Boids
//
// Created by Yanjie Chen on 3/9/15.
//
//
#ifndef __Boids__Skill__
#define __Boids__Skill__
#include "cocos2d.h"
#include "./skill/SkillNode.h"
enum eSkillState {
SkillStateLoading = 1,
SkillStateReady = 2,
SkillStateCasting = 3
};
class UnitNode;
class Skill : public cocos2d::Ref {
private:
std::string _skill_name;
int _level;
float _full_cd;
float _elapse;
float _mp_cost;
eSkillState _state;
cocos2d::ValueMap _skill_data;
UnitNode* _owner;
SkillNode* _skill_node;
public:
Skill();
virtual ~Skill();
static Skill* create( UnitNode* owner, const cocos2d::ValueMap& data );
virtual bool init( UnitNode* owner, const cocos2d::ValueMap& data );
virtual void updateFrame( float delta );
void activate( const cocos2d::ValueMap& params );
void stopload();
void reload();
const std::string& getSkillName() { return _skill_name; }
void setSkillName( const std::string& skill_name ) { _skill_name = skill_name; }
int getSkillLevel() { return _level; }
void setSkillLevel( float level ) { _level = level; }
const cocos2d::ValueMap& getSkillData() { return _skill_data; }
float getFullCD() { return _full_cd; }
void setFullCD( float cd ) { _full_cd = cd; }
float getMpCost() { return _mp_cost; }
void setMpCost( float cost ) { _mp_cost = cost; }
eSkillState getSkillState() { return _state; }
void setSkillState( eSkillState new_state ) { _state = new_state; }
bool isSkillReady();
bool isCasting();
float getSkillCD();
float getSkillRadius();
float getSkillRange();
float getSkillMaxRange();
float getSkillMinRange();
std::string getSkillHintType();
std::string getChargingEffect();
std::string getChargingEffectPos();
bool shouldContinue();
bool shouldCastOnTouchDown();
bool hasExtraDamage();
cocos2d::Value getAttribute( const std::string& key );
SkillNode* getSkillNode() { return _skill_node; }
void setSkillNode( SkillNode* skill_node ) { _skill_node = skill_node; }
};
#endif /* defined(__Boids__Skill__) */
|
/*
Project: Stereo-vision-client
Author: Ben
Description:
*/
// Global includes
#include <QtGui/QApplication>
// Local includes
#include "gui.h"
#include "Engine/engine.h"
#include "Engine/DataTransciever/dataTransciever.h"
#include "Engine/fileEngine.h"
#ifndef _WIN32
#ifndef __linux__
#error You are using a mac, it is not iStereoVision, go sue somebody!
#endif
#endif
int main( int argc, char *argv[] )
{
QApplication a( argc, argv ) ;
FileEngine fileEngine;
Engine engine;
GUI gui;
engine.connect( &gui, SIGNAL( connectToServer( QHostAddress,quint16 ) ) , SIGNAL( connectToServer( QHostAddress,quint16 ) ) ) ;
gui.connect( &engine, SIGNAL(imageReceived(QImage,int)),SIGNAL(imageForPreviewWindow(QImage, int)));
engine.connect( &gui, SIGNAL(subscribeToStream( int, QString, QString, bool)), SLOT( subscribePreviewChannelToStream(int, QString, QString, bool)));
engine.connect( &gui, SIGNAL( needAllProcessSteps() ) , SLOT( giveProcessSteps() ) ) ;
engine.connect( &gui,SIGNAL( commandForServer(QString)), SIGNAL(commandForServer(QString)));
engine.connect( &gui, SIGNAL(replaceStreamRequest(QString,QString,QImage*)), SLOT( replaceStream(QString, QString, QImage*) ) );
engine.connect( &gui, SIGNAL(setValueOnServer(QString,QString,QString)), SIGNAL(setValueOnServer(QString,QString,QString)));
engine.connect( &gui, SIGNAL( requestXML() ), SIGNAL( requestXML() ));
engine.connect( &gui, SIGNAL(flushImageBuffers()), SLOT(flushImageBuffers()));
gui.connect( &engine, SIGNAL( ready() ) , SLOT( start() ) ) ;
gui.connect( &engine, SIGNAL( addProcessStep( ProcessStep* ) ) , SLOT( addProcessStep( ProcessStep* ) ) ) ;
gui.connect( &engine, SIGNAL( clearGui() ), SLOT(clearGui() ));
fileEngine.connect( &gui, SIGNAL( makeEntry( QString ) ) , SLOT( makeEntry( QString ) ) ) ;
fileEngine.connect( &gui, SIGNAL( saveLog() ) , SLOT( saveLog() ) ) ;
fileEngine.connect( &gui, SIGNAL( setTargetDirectory(QString)), SLOT( setDestination(QString) ));
gui.connect( &fileEngine, SIGNAL( printToConsole( QString, QString ) ) , SLOT( printToConsole( QString, QString ) ) ) ;
gui.connect( &engine, SIGNAL( printToConsole( QString, QString ) ) , SLOT( printToConsole( QString, QString ) ) ) ;
gui.show() ;
engine.init() ;
return a.exec() ;
}
|
#if VERBOSE >= 3
#define debug_message(VAR) std::cout<<VAR<<std::flush;
#define verbose3(VAR) std::cout<<VAR<<std::flush;
#endif
#if VERBOSE < 3
#define debug_message(VAR)
#define verbose3(VAR)
#endif
#if VERBOSE >= 2
#define verbose2(VAR) std::cout <<VAR<<std::flush;
#endif
#if VERBOSE < 2
#define verbose2(VAR)
#endif
#if VERBOSE >= 1
#define verbose1(VAR) std::cout <<VAR<<std::flush;
#endif
#if VERBOSE < 1
#define verbose1(VAR)
#endif
#define SCALE 4.1
typedef double TR;
#if nis_complex == 1
typedef std::complex<double> T;
#endif
#if nis_complex == 0
typedef double T;
#endif
typedef Eigen::Array<T, -1, -1> Array;
typedef Eigen::Matrix<T, -1, -1> Matrix;
|
//O(N) and O(1) space
// if a element counts more than N/2 times
// count of other elements should be less than N/2;
// so the diff (count(candidate)-others) > 0 right
// so we will first find the candidate for majority element
// then we will check whether it can be majority element
int majorityElement(vector<int>& nums) {
int n = nums.size();
int candidate = nums[0];
int count = 1;
for(int i=1;i<n;i++)
{
if(nums[i]==candidate)
{
count+=1;
}
else
{
count-=1;
if(count==0)//this can't be my candidate
{
candidate=nums[i];
count=1;
}
}
}
count = 0;
for(int i=0;i<n;i++)
{
if(nums[i]==candidate)
{
count+=1;
}
}
if(count >= (n/2))
{
return candidate;
}
return -1;
}
|
#ifndef __MF_NODE_EXPRESSION_ASSIGNMENT_H__
#define __MF_NODE_EXPRESSION_ASSIGNMENT_H__
#include <cdk/nodes/expressions/BinaryExpression.h>
#include "SemanticProcessor.h"
namespace mayfly {
namespace node {
namespace expression {
/**
* Class for describing the lower-than-or-equal operator
*/
class Assignment: public cdk::node::expression::BinaryExpression {
private:
bool _is_initialization;
public:
/**
* @param lineno source code line number for this nodes
* @param left first operand
* @param right second operand
*/
inline Assignment(int lineno, Expression *left, Expression *right, bool is_initialization = false) :
BinaryExpression (lineno, left, right), _is_initialization(is_initialization) {
}
/**
* @return the name of the node's class
*/
const char *name() const {
return "Assignment";
}
const bool is_initialization() const {
return _is_initialization;
}
/**
* @param sp semantic processor visitor
* @param level syntactic tree level
*/
virtual void accept(SemanticProcessor *sp, int level) {
sp->processAssignment(this, level);
}
};
} // expression
} // node
} // mayfly
#endif
|
#include <iostream>
#include "Consultor.h"
#include "Funcionario.h"
using namespace std;
int main(){
string matm, name;
float sal;
int j;
Consultor c1;
Funcionario f1;
cout << "Digite a matricula: ";
cin >> matm;
f1.setMatricula(matm);
cout << endl;
cout << "Digite o nome: ";
cin >> name;
f1.setNome(name);
cout << endl;
cout << "Digite o salario: ";
cin >> sal;
c1.setSalario(sal);
cout << "Se for consultor digite 1: ";
cin >> j;
if(j == 1){
c1.getSalario();
}
return 0;
}
|
/*
Copyright (c) 2005-2015, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "VentilationProblem.hpp"
#include "Warnings.hpp"
//#include "Debug.hpp"
//#include "Timer.hpp"
VentilationProblem::VentilationProblem(const std::string& rMeshDirFilePath, unsigned rootIndex)
: AbstractVentilationProblem(rMeshDirFilePath, rootIndex),
mFluxGivenAtInflow(false),
mTerminalInteractionMatrix(NULL),
mNumNonZeroesPerRow(25u), //See note in header definition
mTerminalFluxChangeVector(NULL),
mTerminalPressureChangeVector(NULL),
mTerminalKspSolver(NULL)
{
Initialise(rMeshDirFilePath);
}
void VentilationProblem::Initialise(const std::string& rMeshDirFilePath)
{
mFlux.resize(mMesh.GetNumElements());
mPressure.resize(mMesh.GetNumNodes());
}
VentilationProblem::~VentilationProblem()
{
/* Remove the PETSc context used in the iterative solver */
if (mTerminalInteractionMatrix)
{
PetscTools::Destroy(mTerminalInteractionMatrix);
PetscTools::Destroy(mTerminalFluxChangeVector);
PetscTools::Destroy(mTerminalPressureChangeVector);
KSPDestroy(PETSC_DESTROY_PARAM(mTerminalKspSolver));
}
}
void VentilationProblem::SolveDirectFromFlux()
{
/* Work back through the node iterator looking for internal nodes: bifurcations or joints
*
* Each parent flux is equal to the sum of its children
* Note that we can't iterate all the way back to the root node, but that's okay
* because the root is not a bifurcation. Also note that we can't use a NodeIterator
* because it does not have operator--
*/
for (unsigned node_index = mMesh.GetNumNodes() - 1; node_index > 0; --node_index)
{
Node<3>* p_node = mMesh.GetNode(node_index);
if (p_node->IsBoundaryNode() == false)
{
Node<3>::ContainingElementIterator element_iterator = p_node->ContainingElementsBegin();
// This assertion will trip if a node is not actually in the airway tree and will prevent operator++ from hanging
assert(element_iterator != p_node->ContainingElementsEnd());
unsigned parent_index = *element_iterator;
++element_iterator;
for (mFlux[parent_index]=0.0; element_iterator != p_node->ContainingElementsEnd(); ++element_iterator)
{
mFlux[parent_index] += mFlux[*element_iterator];
}
}
}
// Poiseuille flow at each edge
for (AbstractTetrahedralMesh<1,3>::ElementIterator iter = mMesh.GetElementIteratorBegin();
iter != mMesh.GetElementIteratorEnd();
++iter)
{
/* Poiseuille flow gives:
* pressure_node_1 - pressure_node_2 - resistance * flux = 0
*/
double flux = mFlux[iter->GetIndex()];
double resistance = CalculateResistance(*iter, mDynamicResistance, flux);
unsigned pressure_index_parent = iter->GetNodeGlobalIndex(0);
unsigned pressure_index_child = iter->GetNodeGlobalIndex(1);
mPressure[pressure_index_child] = mPressure[pressure_index_parent] - resistance*flux;
}
}
void VentilationProblem::SetupIterativeSolver()
{
//double start = Timer::GetElapsedTime();
mNumNonZeroesPerRow = std::min(mNumNonZeroesPerRow, mMesh.GetNumBoundaryNodes()-1);
MatCreateSeqAIJ(PETSC_COMM_SELF, mMesh.GetNumBoundaryNodes()-1, mMesh.GetNumBoundaryNodes()-1, mNumNonZeroesPerRow, NULL, &mTerminalInteractionMatrix);
PetscMatTools::SetOption(mTerminalInteractionMatrix, MAT_SYMMETRIC);
PetscMatTools::SetOption(mTerminalInteractionMatrix, MAT_SYMMETRY_ETERNAL);
/* Map each edge to its terminal descendants so that we can keep track
* of which terminals can affect each other via a particular edge.
*/
mEdgeDescendantNodes.resize(mMesh.GetNumElements());
unsigned terminal_index=0;
//First set up all the boundary nodes
for (AbstractTetrahedralMesh<1,3>::BoundaryNodeIterator iter = mMesh.GetBoundaryNodeIteratorBegin();
iter != mMesh.GetBoundaryNodeIteratorEnd();
++iter)
{
unsigned node_index = (*iter)->GetIndex();
if (node_index != mOutletNodeIndex)
{
unsigned parent_index = *((*iter)->ContainingElementsBegin());
mTerminalToNodeIndex[terminal_index] = node_index;
mTerminalToEdgeIndex[terminal_index] = parent_index;
mEdgeDescendantNodes[parent_index].insert(terminal_index++);
}
}
// The outer loop here is for special cases where we find an internal node before its descendants
// In this case we need to scan the tree more than once (up to log(N)) before the sets are correctly propagated
while (mEdgeDescendantNodes[mOutletNodeIndex].size() != terminal_index)
{
//Work back up the tree making the unions of the sets of descendants
for (unsigned node_index = mMesh.GetNumNodes() - 1; node_index > 0; --node_index)
{
Node<3>* p_node = mMesh.GetNode(node_index);
if (p_node->IsBoundaryNode() == false)
{
Node<3>::ContainingElementIterator element_iterator = p_node->ContainingElementsBegin();
unsigned parent_index = *element_iterator;
++element_iterator;
for (;element_iterator != p_node->ContainingElementsEnd(); ++element_iterator)
{
mEdgeDescendantNodes[parent_index].insert(mEdgeDescendantNodes[*element_iterator].begin(),mEdgeDescendantNodes[*element_iterator].end());
}
}
}
}
FillInteractionMatrix(false);
assert( terminal_index == mMesh.GetNumBoundaryNodes()-1);
VecCreateSeq(PETSC_COMM_SELF, terminal_index, &mTerminalFluxChangeVector);
VecCreateSeq(PETSC_COMM_SELF, terminal_index, &mTerminalPressureChangeVector);
KSPCreate(PETSC_COMM_SELF, &mTerminalKspSolver);
#if ( PETSC_VERSION_MAJOR==3 && PETSC_VERSION_MINOR>=5 )
KSPSetOperators(mTerminalKspSolver, mTerminalInteractionMatrix, mTerminalInteractionMatrix);
#else
KSPSetOperators(mTerminalKspSolver, mTerminalInteractionMatrix, mTerminalInteractionMatrix, SAME_PRECONDITIONER);
#endif
KSPSetFromOptions(mTerminalKspSolver);
KSPSetUp(mTerminalKspSolver);
// PRINT_VARIABLE(Timer::GetElapsedTime() - start);
}
void VentilationProblem::FillInteractionMatrix(bool redoExisting)
{
assert(!redoExisting);
if (redoExisting)
{
// MatZeroEntries(mTerminalInteractionMatrix);
}
// Use the descendant sets to build the mTerminalInteractionMatrix structure of resistances
for (AbstractTetrahedralMesh<1,3>::ElementIterator iter = mMesh.GetElementIteratorBegin();
iter != mMesh.GetElementIteratorEnd();
++iter)
{
unsigned parent_index = iter->GetIndex();
double parent_resistance=0.0;
if (redoExisting)
{
// assert(mDynamicResistance);
// parent_resistance=CalculateResistance(*iter);
}
else
{
parent_resistance=CalculateResistance(*iter, true, mFlux[parent_index]);
}
std::vector<PetscInt> indices( mEdgeDescendantNodes[parent_index].begin(), mEdgeDescendantNodes[parent_index].end() );
if (mEdgeDescendantNodes[parent_index].size() <= mNumNonZeroesPerRow)
{
std::vector<double> resistance_to_add(indices.size()*indices.size(), parent_resistance);
MatSetValues(mTerminalInteractionMatrix,
indices.size(), (PetscInt*) &indices[0],
indices.size(), (PetscInt*) &indices[0], &resistance_to_add[0], ADD_VALUES);
}
else
{
///\todo Does this make so much difference?
for (unsigned i=0; i<indices.size(); i++)
{
MatSetValue(mTerminalInteractionMatrix, indices[i], indices[i], parent_resistance, ADD_VALUES);
}
}
}
PetscMatTools::Finalise(mTerminalInteractionMatrix);
}
void VentilationProblem::SolveIterativelyFromPressure()
{
if (mTerminalInteractionMatrix == NULL)
{
SetupIterativeSolver();
}
// double start = Timer::GetElapsedTime();
/* Now use the pressure boundary conditions to determine suitable flux boundary conditions
* and iteratively update them until we are done
*/
assert(mPressure[mOutletNodeIndex] == mPressureCondition[mOutletNodeIndex]);
unsigned max_iterations=1000;
unsigned num_terminals = mMesh.GetNumBoundaryNodes()-1u;
double pressure_tolerance = 1e-4;
if (mLengthScaling < 1e-2)
{
// Using SI units
pressure_tolerance = 1e-7;
}
bool converged=false;
double last_norm_pressure_change;
Vec old_terminal_pressure_change;
VecDuplicate(mTerminalPressureChangeVector, &old_terminal_pressure_change);
for (unsigned iteration = 0; iteration < max_iterations && converged==false; iteration++)
{
for (unsigned terminal=0; terminal<num_terminals; terminal++)
{
unsigned node_index = mTerminalToNodeIndex[terminal];
// How far we are away from matching this boundary condition.
double delta_pressure = mPressure[node_index] - mPressureCondition[node_index];
// Offset the first iteration
if (iteration == 0)
{
delta_pressure += mPressureCondition[mOutletNodeIndex];
}
VecSetValue(mTerminalPressureChangeVector, terminal, delta_pressure, INSERT_VALUES);
}
double norm_pressure_change;
VecNorm(mTerminalPressureChangeVector, NORM_2, &last_norm_pressure_change);
if (last_norm_pressure_change < pressure_tolerance)
{
converged = true;
break;
}
VecCopy(mTerminalPressureChangeVector, old_terminal_pressure_change);
KSPSolve(mTerminalKspSolver, mTerminalPressureChangeVector, mTerminalFluxChangeVector);
double* p_mTerminalFluxChangeVector;
VecGetArray(mTerminalFluxChangeVector, &p_mTerminalFluxChangeVector);
for (unsigned terminal=0; terminal<num_terminals; terminal++)
{
double estimated_mTerminalFluxChangeVector=p_mTerminalFluxChangeVector[terminal];
unsigned edge_index = mTerminalToEdgeIndex[terminal];
mFlux[edge_index] += estimated_mTerminalFluxChangeVector;
}
SolveDirectFromFlux();
/* Look at the magnitude of the response */
for (unsigned terminal=0; terminal<num_terminals; terminal++)
{
unsigned node_index = mTerminalToNodeIndex[terminal];
// How far we are away from matching this boundary condition.
double delta_pressure = mPressure[node_index] - mPressureCondition[node_index];
// Offset the first iteration
if (iteration == 0)
{
delta_pressure += mPressureCondition[mOutletNodeIndex];
}
VecSetValue(mTerminalPressureChangeVector, terminal, delta_pressure, INSERT_VALUES);
}
VecNorm(mTerminalPressureChangeVector, NORM_2, &norm_pressure_change);
if (norm_pressure_change < pressure_tolerance)
{
converged = true;
break;
}
double pressure_change_dot_product;
VecDot(mTerminalPressureChangeVector, old_terminal_pressure_change, &pressure_change_dot_product);
if (pressure_change_dot_product < 0.0)
{
/* The pressure correction has changed sign
* * so we have overshot the root
* * back up by setting a correction factor
*/
double terminal_flux_correction = last_norm_pressure_change / (last_norm_pressure_change + norm_pressure_change) - 1.0;
///\todo some sqrt response?
// if (mDynamicResistance)
// {
// terminal_flux_correction *= 0.99;
// }
for (unsigned terminal=0; terminal<num_terminals; terminal++)
{
double estimated_mTerminalFluxChangeVector=p_mTerminalFluxChangeVector[terminal];
unsigned edge_index = mTerminalToEdgeIndex[terminal];
mFlux[edge_index] += terminal_flux_correction*estimated_mTerminalFluxChangeVector;
}
SolveDirectFromFlux();
}
}
if(!converged)
{
NEVER_REACHED;
}
PetscTools::Destroy(old_terminal_pressure_change);
// PRINT_2_VARIABLES(Timer::GetElapsedTime() - start, mDynamicResistance);
}
void VentilationProblem::SetOutflowPressure(double pressure)
{
SetPressureAtBoundaryNode(*(mMesh.GetNode(mOutletNodeIndex)), pressure);
mPressure[mOutletNodeIndex] = pressure;
}
void VentilationProblem::SetPressureAtBoundaryNode(const Node<3>& rNode, double pressure)
{
if (rNode.IsBoundaryNode() == false)
{
EXCEPTION("Boundary conditions cannot be set at internal nodes");
}
assert(mFluxGivenAtInflow == false);
// Store the requirement in a map for the direct solver
mPressureCondition[rNode.GetIndex()] = pressure;
}
void VentilationProblem::SetOutflowFlux(double flux)
{
///\todo #2300
EXCEPTION("This functionality is not implemented yet");
}
double VentilationProblem::GetFluxAtOutflow()
{
return mFlux[mOutletNodeIndex];
}
void VentilationProblem::SetFluxAtBoundaryNode(const Node<3>& rNode, double flux)
{
if (rNode.IsBoundaryNode() == false)
{
EXCEPTION("Boundary conditions cannot be set at internal nodes");
}
mFluxGivenAtInflow = true;
// In a <1,3> mesh a boundary node will be associated with exactly one edge.
unsigned edge_index = *( rNode.ContainingElementsBegin() );
// Seed the information for a direct solver
mFlux[edge_index] = flux;
}
void VentilationProblem::Solve()
{
if (mFluxGivenAtInflow)
{
SolveDirectFromFlux();
}
else
{
SolveIterativelyFromPressure();
}
}
void VentilationProblem::GetSolutionAsFluxesAndPressures(std::vector<double>& rFluxesOnEdges,
std::vector<double>& rPressuresOnNodes)
{
rFluxesOnEdges = mFlux;
rPressuresOnNodes = mPressure;
}
|
#include<iostream>
using namespace std;
main()
{int n,s;
float m,a;
cin>>n;
if(n>=10&&n<=99){
s=n/10;
a=n-s*10;
s=m;
if(a>m) m=a;
cout<<m;
if(n%11==0||n%22==0||n%33==0||n%44==0||n%55==0||n%66==0||n%77==0||n%88==0||n%99==0){
cout<<"ekeui ten";
}
}
else cout<<"kate terdyntz";}
|
//
// Created by 梁栋 on 2019-05-09.
//
#include <iostream>
#include <unordered_map>
using namespace std;
class DLinkNode{
// 双向链表
public:
int val;
int k;
DLinkNode* pre;
DLinkNode* next;
DLinkNode(){
pre = NULL;
next = NULL;
val = 0;
}
DLinkNode(int v){
val = v;
pre = NULL;
next = NULL;
}
void add(DLinkNode* added){
// 在该点后加入一个新的点
added->pre = this;
added->next = this->next;
this->next->pre = added;
this->next = added;
}
void remove(){
// 从list中移出该点
this->pre->next = this->next;
this->next->pre = this->pre;
}
static void moveToHead(DLinkNode* head, DLinkNode* node){
node->remove(); // 从list中删除该点
head->add(node); // 将该点移动到head后
}
};
class LRUCache {
private:
unordered_map<int, DLinkNode*> dict;
int count = 0;
int capacity = 0;
DLinkNode* head;
DLinkNode* tail;
public:
LRUCache(int capacity) {
count = 0;
this->capacity = capacity;
head = new DLinkNode();
tail = new DLinkNode();
head->next = tail;
tail->pre = head;
}
int get(int key) {
DLinkNode* res = dict[key];
if(res == NULL)
return -1;// not found
DLinkNode::moveToHead(head, res); // 移动到最前面
return res->val;
}
void put(int key, int value) {
DLinkNode* res = dict[key];
if(res == NULL){
count += 1;
DLinkNode* newNode = new DLinkNode(value);
newNode->k = key;
head->add(newNode);
dict[key] = newNode;
if(count > capacity){
dict[tail->pre->k] = NULL;
tail->pre->remove(); //删除该点
count --;
}
}else{
res->val = value;
DLinkNode::moveToHead(head, res); // 移动到最前面
}
}
};
class Solution{
public:
static void solution(){
LRUCache cache(2);
cache.put(2, 1);
cache.put(2, 2);
cout<<cache.get(2)<<endl; // returns 1
cache.put(3, 3); // evicts key 2
cout<<cache.get(2)<<endl; // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cout<<cache.get(1)<<endl; // returns -1 (not found)
cout<<cache.get(3)<<endl; // returns 3
cout<<cache.get(4)<<endl; // returns 4
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
|
#include "Vector.h"
#include "Trace.h"
template <class T>
vector<T>::vector(int size) {
TRACE(dummy, "vector<T>::vector(int)");
v = new T[size];
sz = size;
cout << " count = " << ++count << endl;
}
template <class T>
vector<T>::~vector() {
TRACE(dummy, "vector<T>::~vector");
cout << " count = " << count-- << endl;
delete [] v;
}
int vector<void*>::count = 0;
vector<void*>::vector(int size) {
TRACE(dummy, "vector<void*>::vector(int)");
p = new void*[size];
sz = size;
cout << " count = " << ++vector::count << endl;
}
vector<void*>::~vector() {
TRACE(dummy, "vector<void*>::~vector");
cout << " count = " << vector::count-- << endl;
delete [] p;
}
template <class T>
vector<T*>::vector(int size) : Base(size) {
TRACE(dummy, "vector<T*>::vector(int)");
}
template <class T>
vector<T*>::~vector() {
TRACE(dummy, "vector<T*>::~vector");
}
template class vector<float>;
template class vector<int>;
template class vector<char>;
template class vector<void*>;
template class vector<float*>;
template class vector<int*>;
template class vector<char*>;
|
#include "Graphics/Camera.h"
#include "ThirdParty/Catch/catch.hpp"
TEST_CASE("View transform can transform world space coordinates to camera space coordinates.", "[Camera][ViewTransform]")
{
// CREATE THE COORDINATES TO TRANSFORM.
// These form a basic triangle.
MATH::Vector4f top_coordinate(0.0f, 1.0f, 0.0f, 1.0f);
MATH::Vector4f left_coordinate(-1.0f, 0.0f, 0.0f, 1.0f);
MATH::Vector4f right_coordinate(1.0f, 0.0f, 0.0f, 1.0f);
// DEFINE A BASIC CAMERA.
GRAPHICS::Camera camera = GRAPHICS::Camera::LookAtFrom(MATH::Vector3f(0.0f, 0.0f, 0.0f), MATH::Vector3f(0.0f, 0.0f, -1.0f));
// CREATE THE VIEW TRANSFORM.
MATH::Matrix4x4f view_transform = camera.ViewTransform();
// TRANSFORM THE COORDINATES.
MATH::Vector4f transformed_top_coordinate = view_transform * top_coordinate;
MATH::Vector4f transformed_left_coordinate = view_transform * left_coordinate;
MATH::Vector4f transformed_right_coordinate = view_transform * right_coordinate;
// VERIFY THE TRANSFORMED COORDINATES.
const MATH::Vector4f EXPECTED_TRANSFORMED_TOP_COORDINATE(0.0f, 1.0f, -1.0f, 1.0f);
REQUIRE(EXPECTED_TRANSFORMED_TOP_COORDINATE.X == transformed_top_coordinate.X);
REQUIRE(EXPECTED_TRANSFORMED_TOP_COORDINATE.Y == transformed_top_coordinate.Y);
REQUIRE(EXPECTED_TRANSFORMED_TOP_COORDINATE.Z == transformed_top_coordinate.Z);
REQUIRE(EXPECTED_TRANSFORMED_TOP_COORDINATE.W == transformed_top_coordinate.W);
const MATH::Vector4f EXPECTED_TRANSFORMED_LEFT_COORDINATE(1.0f, 0.0f, -1.0f, 1.0f);
REQUIRE(EXPECTED_TRANSFORMED_LEFT_COORDINATE.X == transformed_left_coordinate.X);
REQUIRE(EXPECTED_TRANSFORMED_LEFT_COORDINATE.Y == transformed_left_coordinate.Y);
REQUIRE(EXPECTED_TRANSFORMED_LEFT_COORDINATE.Z == transformed_left_coordinate.Z);
REQUIRE(EXPECTED_TRANSFORMED_LEFT_COORDINATE.W == transformed_left_coordinate.W);
const MATH::Vector4f EXPECTED_TRANSFORMED_RIGHT_COORDINATE(-1.0f, 0.0f, -1.0f, 1.0f);
REQUIRE(EXPECTED_TRANSFORMED_RIGHT_COORDINATE.X == transformed_right_coordinate.X);
REQUIRE(EXPECTED_TRANSFORMED_RIGHT_COORDINATE.Y == transformed_right_coordinate.Y);
REQUIRE(EXPECTED_TRANSFORMED_RIGHT_COORDINATE.Z == transformed_right_coordinate.Z);
REQUIRE(EXPECTED_TRANSFORMED_RIGHT_COORDINATE.W == transformed_right_coordinate.W);
}
TEST_CASE("Perspective projection projects camera space coordinates correctly.", "[Camera][Perspective]")
{
// CREATE THE CAMERA SPACE COORDINATES.
// These are the same coordinates from the previous test case.
MATH::Vector4f camera_space_top_coordinate(0.0f, 1.0f, -1.0f, 1.0f);
MATH::Vector4f camera_space_left_coordinate(1.0f, 0.0f, -1.0f, 1.0f);
MATH::Vector4f camera_space_right_coordinate(-1.0f, 0.0f, -1.0f, 1.0f);
// DEFINE A BASIC CAMERA.
GRAPHICS::Camera camera = GRAPHICS::Camera::LookAt(MATH::Vector3f(0.0f, 0.0f, 0.0f));
// CREATE THE PERSPECTIVE PROJECTION MATRIX.
const MATH::Angle<float>::Degrees FIELD_OF_VIEW(90.0f);
constexpr float ASPECT_RATIO = 1.0f;
constexpr float Z_NEAR = 1.0f;
constexpr float Z_FAR = 100.0f;
MATH::Matrix4x4f perspective_projection = camera.PerspectiveProjection(FIELD_OF_VIEW, ASPECT_RATIO, Z_NEAR, Z_FAR);
// TRANSFORM THE COORDINATES.
MATH::Vector4f projected_top_coordinate = perspective_projection * camera_space_top_coordinate;
MATH::Vector4f projected_left_coordinate = perspective_projection * camera_space_left_coordinate;
MATH::Vector4f projected_right_coordinate = perspective_projection * camera_space_right_coordinate;
// VERIFY THE TRANSFORMED COORDINATES.
const MATH::Vector4f EXPECTED_PROJECTED_TOP_COORDINATE(0.0f, 1.0f, 3.0404f, -1.0f);
REQUIRE(EXPECTED_PROJECTED_TOP_COORDINATE.X == Approx(projected_top_coordinate.X));
REQUIRE(EXPECTED_PROJECTED_TOP_COORDINATE.Y == Approx(projected_top_coordinate.Y));
REQUIRE(EXPECTED_PROJECTED_TOP_COORDINATE.Z == Approx(projected_top_coordinate.Z));
REQUIRE(EXPECTED_PROJECTED_TOP_COORDINATE.W == Approx(projected_top_coordinate.W));
const MATH::Vector4f EXPECTED_PROJECTED_LEFT_COORDINATE(1.0f, 0.0f, 3.0404f, -1.0f);
REQUIRE(EXPECTED_PROJECTED_LEFT_COORDINATE.X == Approx(projected_left_coordinate.X));
REQUIRE(EXPECTED_PROJECTED_LEFT_COORDINATE.Y == Approx(projected_left_coordinate.Y));
REQUIRE(EXPECTED_PROJECTED_LEFT_COORDINATE.Z == Approx(projected_left_coordinate.Z));
REQUIRE(EXPECTED_PROJECTED_LEFT_COORDINATE.W == Approx(projected_left_coordinate.W));
const MATH::Vector4f EXPECTED_PROJECTED_RIGHT_COORDINATE(-1.0f, 0.0f, 3.0404f, -1.0f);
REQUIRE(EXPECTED_PROJECTED_RIGHT_COORDINATE.X == Approx(projected_right_coordinate.X));
REQUIRE(EXPECTED_PROJECTED_RIGHT_COORDINATE.Y == Approx(projected_right_coordinate.Y));
REQUIRE(EXPECTED_PROJECTED_RIGHT_COORDINATE.Z == Approx(projected_right_coordinate.Z));
REQUIRE(EXPECTED_PROJECTED_RIGHT_COORDINATE.W == Approx(projected_right_coordinate.W));
}
|
//**************************************************************************
//**
//** See jlquake.txt for copyright info.
//**
//** This program is free software; you can redistribute it and/or
//** modify it under the terms of the GNU General Public License
//** as published by the Free Software Foundation; either version 3
//** of the License, or (at your option) any later version.
//**
//** This program is distributed in the hope that it will be useful,
//** but WITHOUT ANY WARRANTY; without even the implied warranty of
//** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//** included (gnu.txt) GNU General Public License for more details.
//**
//**************************************************************************
#include "event_queue.h"
#include "Common.h"
#include "common_defs.h"
#include "strings.h"
#include "command_buffer.h"
#include "command_line_args.h"
#include "network_channel.h"
#include "system.h"
#include "../client/public.h"
#include "../server/public.h"
/*
===================================================================
EVENTS AND JOURNALING
In addition to these events, .cfg files are also copied to the
journaled file
===================================================================
*/
#define MAX_QUED_EVENTS 256
#define MASK_QUED_EVENTS ( MAX_QUED_EVENTS - 1 )
#define MAX_PUSHED_EVENTS 1024
struct sysEvent_t {
int evTime;
sysEventType_t evType;
int evValue;
int evValue2;
int evPtrLength; // bytes of data pointed to by evPtr, for journaling
void* evPtr; // this must be manually freed if not NULL
};
Cvar* com_journal;
fileHandle_t com_journalFile; // events are written here
fileHandle_t com_journalDataFile; // config files are written here
static sysEvent_t eventQue[ MAX_QUED_EVENTS ];
static int eventHead;
static int eventTail;
static int com_pushedEventsHead = 0;
static int com_pushedEventsTail = 0;
static sysEvent_t com_pushedEvents[ MAX_PUSHED_EVENTS ];
static byte sys_packetReceived[ MAX_MSGLEN ];
void Com_InitEventQueue() {
// clear queues
Com_Memset( &eventQue[ 0 ], 0, MAX_QUED_EVENTS * sizeof ( sysEvent_t ) );
// clear the static buffer array
// this requires SE_NONE to be accepted as a valid but NOP event
Com_Memset( com_pushedEvents, 0, sizeof ( com_pushedEvents ) );
// reset counters while we are at it
// beware: GetEvent might still return an SE_NONE from the buffer
com_pushedEventsHead = 0;
com_pushedEventsTail = 0;
}
void Com_InitJournaling() {
Com_StartupVariable( "journal" );
com_journal = Cvar_Get( "journal", "0", CVAR_INIT );
if ( !com_journal->integer ) {
return;
}
if ( com_journal->integer == 1 ) {
common->Printf( "Journaling events\n" );
com_journalFile = FS_FOpenFileWrite( "journal.dat" );
com_journalDataFile = FS_FOpenFileWrite( "journaldata.dat" );
} else if ( com_journal->integer == 2 ) {
common->Printf( "Replaying journaled events\n" );
FS_FOpenFileRead( "journal.dat", &com_journalFile, true );
FS_FOpenFileRead( "journaldata.dat", &com_journalDataFile, true );
}
if ( !com_journalFile || !com_journalDataFile ) {
Cvar_Set( "com_journal", "0" );
com_journalFile = 0;
com_journalDataFile = 0;
common->Printf( "Couldn't open journal files\n" );
}
}
// A time of 0 will get the current time
// Ptr should either be null, or point to a block of data that can
// be freed by the game later.
void Sys_QueEvent( int time, sysEventType_t type, int value, int value2, int ptrLength, void* ptr ) {
sysEvent_t* ev;
ev = &eventQue[ eventHead & MASK_QUED_EVENTS ];
if ( eventHead - eventTail >= MAX_QUED_EVENTS ) {
common->Printf( "Sys_QueEvent: overflow\n" );
// we are discarding an event, but don't leak memory
if ( ev->evPtr ) {
Mem_Free( ev->evPtr );
}
eventTail++;
}
eventHead++;
if ( time == 0 ) {
time = Sys_Milliseconds();
}
ev->evTime = time;
ev->evType = type;
ev->evValue = value;
ev->evValue2 = value2;
ev->evPtrLength = ptrLength;
ev->evPtr = ptr;
}
static sysEvent_t Sys_GetEvent() {
// return if we have data
if ( eventHead > eventTail ) {
eventTail++;
return eventQue[ ( eventTail - 1 ) & MASK_QUED_EVENTS ];
}
// pump the message loop
Sys_MessageLoop();
Sys_SendKeyEvents();
// check for console commands
const char* s = Sys_ConsoleInput();
if ( s ) {
int len = String::Length( s ) + 1;
char* b = ( char* )Mem_Alloc( len );
String::NCpyZ( b, s, len );
Sys_QueEvent( 0, SE_CONSOLE, 0, 0, len, b );
}
if ( GGameType & GAME_Tech3 ) {
// check for network packets
QMsg netmsg;
netmsg.Init( sys_packetReceived, sizeof ( sys_packetReceived ) );
netadr_t adr;
if ( NET_GetUdpPacket( NS_SERVER, &adr, &netmsg ) ) {
// copy out to a seperate buffer for qeueing
int len = sizeof ( netadr_t ) + netmsg.cursize;
netadr_t* buf = ( netadr_t* )Mem_Alloc( len );
*buf = adr;
Com_Memcpy( buf + 1, netmsg._data, netmsg.cursize );
Sys_QueEvent( 0, SE_PACKET, 0, 0, len, buf );
}
}
// return if we have data
if ( eventHead > eventTail ) {
eventTail++;
return eventQue[ ( eventTail - 1 ) & MASK_QUED_EVENTS ];
}
// create an empty event to return
sysEvent_t ev;
Com_Memset( &ev, 0, sizeof ( ev ) );
// Windows uses timeGetTime();
ev.evTime = Sys_Milliseconds();
return ev;
}
static sysEvent_t Com_GetRealEvent() {
sysEvent_t ev;
// either get an event from the system or the journal file
if ( com_journal && com_journal->integer == 2 ) {
int r = FS_Read( &ev, sizeof ( ev ), com_journalFile );
if ( r != sizeof ( ev ) ) {
common->FatalError( "Error reading from journal file" );
}
if ( ev.evPtrLength ) {
ev.evPtr = Mem_Alloc( ev.evPtrLength );
r = FS_Read( ev.evPtr, ev.evPtrLength, com_journalFile );
if ( r != ev.evPtrLength ) {
common->FatalError( "Error reading from journal file" );
}
}
} else {
ev = Sys_GetEvent();
// write the journal value out if needed
if ( com_journal && com_journal->integer == 1 ) {
int r = FS_Write( &ev, sizeof ( ev ), com_journalFile );
if ( r != sizeof ( ev ) ) {
common->FatalError( "Error writing to journal file" );
}
if ( ev.evPtrLength ) {
r = FS_Write( ev.evPtr, ev.evPtrLength, com_journalFile );
if ( r != ev.evPtrLength ) {
common->FatalError( "Error writing to journal file" );
}
}
}
}
return ev;
}
static void Com_PushEvent( sysEvent_t* event ) {
static bool printedWarning = false;
sysEvent_t* ev = &com_pushedEvents[ com_pushedEventsHead & ( MAX_PUSHED_EVENTS - 1 ) ];
if ( com_pushedEventsHead - com_pushedEventsTail >= MAX_PUSHED_EVENTS ) {
// don't print the warning constantly, or it can give time for more...
if ( !printedWarning ) {
printedWarning = true;
common->Printf( "WARNING: Com_PushEvent overflow\n" );
}
if ( ev->evPtr ) {
Mem_Free( ev->evPtr );
}
com_pushedEventsTail++;
} else {
printedWarning = false;
}
*ev = *event;
com_pushedEventsHead++;
}
static sysEvent_t Com_GetEvent() {
if ( com_pushedEventsHead > com_pushedEventsTail ) {
com_pushedEventsTail++;
return com_pushedEvents[ ( com_pushedEventsTail - 1 ) & ( MAX_PUSHED_EVENTS - 1 ) ];
}
return Com_GetRealEvent();
}
static void Com_RunAndTimeServerPacket( netadr_t* evFrom, QMsg* buf ) {
int t1, t2, msec;
t1 = 0;
if ( com_speeds->integer ) {
t1 = Sys_Milliseconds();
}
SVT3_PacketEvent( *evFrom, buf );
if ( com_speeds->integer ) {
t2 = Sys_Milliseconds();
msec = t2 - t1;
if ( com_speeds->integer == 3 ) {
common->Printf( "SVT3_PacketEvent time: %i\n", msec );
}
}
}
// Returns last event time
int Com_EventLoop() {
netadr_t evFrom;
byte bufData[ MAX_MSGLEN ];
QMsg buf;
buf.Init( bufData, sizeof ( bufData ) );
while ( 1 ) {
sysEvent_t ev = Com_GetEvent();
// if no more events are available
if ( ev.evType == SE_NONE ) {
if ( GGameType & GAME_Tech3 ) {
// manually send packet events for the loopback channel
while ( NET_GetLoopPacket( NS_CLIENT, &evFrom, &buf ) ) {
CLT3_PacketEvent( evFrom, &buf );
}
while ( NET_GetLoopPacket( NS_SERVER, &evFrom, &buf ) ) {
// if the server just shut down, flush the events
if ( com_sv_running->integer ) {
Com_RunAndTimeServerPacket( &evFrom, &buf );
}
}
}
return ev.evTime;
}
switch ( ev.evType ) {
default:
common->FatalError( "Com_EventLoop: bad event type %i", ev.evType );
break;
case SE_NONE:
break;
case SE_KEY:
CL_KeyEvent( ev.evValue, ev.evValue2, ev.evTime );
break;
case SE_CHAR:
CL_CharEvent( ev.evValue );
break;
case SE_MOUSE:
CL_MouseEvent( ev.evValue, ev.evValue2 );
break;
case SE_JOYSTICK_AXIS:
CL_JoystickEvent( ev.evValue, ev.evValue2 );
break;
case SE_CONSOLE:
Cbuf_AddText( ( char* )ev.evPtr );
Cbuf_AddText( "\n" );
break;
case SE_PACKET:
if ( GGameType & GAME_Tech3 ) {
// this cvar allows simulation of connections that
// drop a lot of packets. Note that loopback connections
// don't go through here at all.
if ( com_dropsim->value > 0 ) {
static int seed;
if ( Q_random( &seed ) < com_dropsim->value ) {
break; // drop this packet
}
}
evFrom = *( netadr_t* )ev.evPtr;
buf.cursize = ev.evPtrLength - sizeof ( evFrom );
// we must copy the contents of the message out, because
// the event buffers are only large enough to hold the
// exact payload, but channel messages need to be large
// enough to hold fragment reassembly
if ( ( unsigned )buf.cursize > ( unsigned )buf.maxsize ) {
common->Printf( "Com_EventLoop: oversize packet\n" );
continue;
}
Com_Memcpy( buf._data, ( byte* )( ( netadr_t* )ev.evPtr + 1 ), buf.cursize );
if ( com_sv_running->integer ) {
Com_RunAndTimeServerPacket( &evFrom, &buf );
} else {
CLT3_PacketEvent( evFrom, &buf );
}
}
break;
}
// free any block data
if ( ev.evPtr ) {
Mem_Free( ev.evPtr );
}
}
return 0; // never reached
}
// Can be used for profiling, but will be journaled accurately
int Com_Milliseconds() {
// get events and push them until we get a null event with the current time
sysEvent_t ev;
do {
ev = Com_GetRealEvent();
if ( ev.evType != SE_NONE ) {
Com_PushEvent( &ev );
}
} while ( ev.evType != SE_NONE );
return ev.evTime;
}
|
/***************************************************************************
Copyright (c) 2020 Philip Fortier
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.
***************************************************************************/
#pragma once
#include "BaseColorDialog.h"
#include "ChooseColorStatic.h"
#include "ColorDialogCallback.h"
#include "PaletteDefinitionCallback.h"
#include "resource.h"
struct PaletteComponent;
class GradientDialog : public CExtResizableDialog
{
public:
GradientDialog(PaletteComponent &palette, IVGAPaletteDefinitionCallback *callback, uint8_t start, uint8_t end, CWnd* pParent = NULL); // standard constructor
// Dialog Data
enum { IDD = IDD_DIALOGGRADIENTS };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
void _SyncPalette();
DECLARE_MESSAGE_MAP()
// Visuals
CExtButton m_wndOk;
CExtButton m_wndCancel;
CExtButton m_wndCenter;
CExtButton m_wndEdges;
CExtGroupBox m_wndGroupGradientType;
CExtRadioButton m_wndRadioGradientLinear;
CExtRadioButton m_wndRadioGradientCenter;
bool _initialized;
int _gradientType;
PaletteComponent &_palette;
uint8_t _start;
uint8_t _endInclusive;
COLORREF _edge;
COLORREF _center;
IVGAPaletteDefinitionCallback *_callback;
public:
afx_msg void OnBnClickedButtoncenter();
afx_msg void OnBnClickedButtonedges();
afx_msg void OnBnClickedRadiolinear();
afx_msg void OnBnClickedRadiocenter();
};
|
#include <iostream>
#include "ListADT.hpp"
using namespace std;
int main(){
ListADT list;
list.insert(3,0);
list.insert(5,0);
list.insert(4,2);
list.remove(1);
std::cout << "Size of List: " << list.size() << std::endl;
list.printList();
return 0;
}
|
#include "OptimisedMinimum.h"
double OptimisedMinimum :: dfdx(double x) {
return 4*x*x*x + 8*x - 32;
}
double OptimisedMinimum :: d2fdx2(double x) {
return 12*x*x + 8;
}
OptimisedMinimum :: OptimisedMinimum(double leftB, double rightB, double epsilon) {
a = leftB;
b = rightB;
eps = epsilon;
}
double OptimisedMinimum :: fun(double x) {
return x*x*x*x + 4*x*x - 32*x + 1;
}
double OptimisedMinimum :: tangent() {
double A = a;
double B = b;
double c = (fun(B) - fun(A) + (A * dfdx(A)) - (B * dfdx(B))) / (dfdx(A) - dfdx(B));
double DFDXc;
while (abs(dfdx(c)) > eps) {
DFDXc = dfdx(c);
if (DFDXc > 0) {
B = c;
}
if (DFDXc < 0) {
A = c;
}
if (DFDXc == 0) {
return fun(c);
}
c = (fun(B) - fun(A) + A * dfdx(A) - B * dfdx(B)) / (dfdx(A) - dfdx(B));
}
return c;
}
double OptimisedMinimum :: newtonRaphson() {
double A = a;
double c = A - (dfdx(A) / d2fdx2(A));
while (dfdx(c) > eps) {
A = c;
c = A - (dfdx(A) / d2fdx2(A));
}
return c;
}
double OptimisedMinimum :: secant() {
double B = b;
double A = a;
double c = B - ((B - A) / (dfdx(B) - dfdx(A)));
while (dfdx(c) > eps) {
A = B;
B = c;
c = B - ((B - A) / (dfdx(B) - dfdx(A)));
}
return c;
}
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
TreeNode* buildBalancedBST(vector<int> &value, int left, int right) {
if (left > right)
return nullptr;
int middle = left + (right - left) / 2;
TreeNode *root = new TreeNode(value[middle]);
root->left = buildBalancedBST(value, left, middle - 1);
root->right = buildBalancedBST(value, middle + 1, right);
return root;
}
public:
TreeNode* sortedListToBST(ListNode* head) {
vector<int> value;
while(head) {
value.push_back(head->val);
head = head->next;
}
return buildBalancedBST(value, 0, value.size() - 1);
}
};
|
/*******************************************************************
* CS 307 Programming Assignment 2
* Author: Benjmin hoang
* Desc: traffic simulation
* Date: 4/15/2017
* I attest that this program is entirely my own work
*******************************************************************/
#include "Road.h"
Road::Road(void)
{
}
Road::~Road(void)
{
}
//all set functions
void Road::setName(char *name)
{
Road::name = string(name);
}
void Road::setxStart(double *xStart)
{
Road::m_dXStart = *xStart;
}
void Road::setyStart(double *yStart)
{
Road::m_dYStart = *yStart;
}
void Road::setxEnd(double *xEnd)
{
Road::m_dXEnd = *xEnd;
}
void Road::setyEnd(double *yEnd)
{
Road::m_dYEnd = *yEnd;
}
void Road::setintersStart(int *intersStart)
{
Road::m_iIntersStart = *intersStart;
}
void Road::setintersEnd(int *intersEnd)
{
Road::m_iIntersEnd = *intersEnd;
}
void Road::setspdlimit(double *spdlimit)
{
Road::m_dSpdlimit = *spdlimit;
}
void Road::setnumLanes(int *numLanes)
{
Road::m_iNumLanes = *numLanes;
}
void Road::setNS_EWroad()
{
//east-west x_start != x_end, y_start = y_end horizontal road
if((m_dXStart != m_dXEnd) && (m_dYStart == m_dYEnd))
{
m_bIsEWroad = true;
m_bIsNSroad = false;
}
else
{
m_bIsEWroad = false;
m_bIsNSroad = true;
}
}
//all get functions
string Road::getName()
{
return name;
}
double Road::getxStart()
{
return m_dXStart;
}
double Road::getyStart()
{
return m_dYStart;
}
double Road::getxEnd()
{
return m_dXEnd;
}
double Road::getyEnd()
{
return m_dYEnd;
}
int Road::getintersStart()
{
return m_iIntersStart;
}
int Road::getintersEnd()
{
return m_iIntersEnd;
}
double Road::getspdlimit()
{
return m_dSpdlimit;
}
int Road::getnumLanes()
{
return m_iNumLanes;
}
bool Road::isPointOnRoad(double x, double y, double dir)
{
double lanewidth = 3.6;
//east-west x_start != x_end, y_start = y_end horizontal road
if(m_bIsEWroad == true)
{
double ULX = m_dXStart;
double ULY = m_dYStart - ((m_iNumLanes/2)*lanewidth);
double LRX = m_dXEnd;
double LRY = m_dYEnd + ((m_iNumLanes/2)*lanewidth);
if((x >= ULX) && (x <= LRX) && (y >= ULY) && (y <= LRY))
{
if(dir ==0 || dir == 180)
{
return true;
}
//point is on the road
}
}
//north-south x_start == x_end, y_start != y_end vertical road
if(m_bIsNSroad == true)
{
double ULX = m_dXStart - ((m_iNumLanes/2)*lanewidth);
double ULY = m_dYStart;
double LRX = m_dXEnd + ((m_iNumLanes/2)*lanewidth);
double LRY = m_dYEnd;
if((x >= ULX) && (x <= LRX) && (y >= ULY) && (y <= LRY))
{
if(dir==90 || dir == 270)
{
//point is on the road
return true;
}
}
}
return false;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.