text
stringlengths 8
6.88M
|
|---|
#include <stdio.h>
#include <stdint.h>
#include "platform.h"
#include "imgui_support.h"
using namespace render;
static render::ContextPtr g_context;
static render::TexturePtr g_FontTexture;
static render::ShaderPtr g_FixedShader;
static StopWatch g_timer;
ImFont *g_font_awesome;
// Functions
void ImGuiSupport_NewFrame()
{
ImGuiIO &io = ImGui::GetIO();
if (g_context)
{
Size2D size = g_context->GetDisplaySize();
float scale = g_context->GetDisplayScale();
io.DisplaySize.x = size.width / scale;
io.DisplaySize.y = size.height / scale;
io.DisplayFramebufferScale = ImVec2(scale, scale);
}
io.DeltaTime = g_timer.GetElapsedSeconds();
g_timer.Restart();
ImGui::NewFrame();
}
static void ImGui_ImplRender_SetupRenderState(render::ContextPtr context, ImDrawData* draw_data)
{
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
// setup viewport
context->SetViewport(0, 0, fb_width, fb_height);
context->SetBlend(BLEND_SRCALPHA, BLEND_INVSRCALPHA);
float L = draw_data->DisplayPos.x;
float T = draw_data->DisplayPos.y;
float R = L + draw_data->DisplaySize.x;
float B = T + draw_data->DisplaySize.y;
Matrix44 ortho_projection = MatrixOrthoLH(L, R, B, T, 0, 1.0f);
context->SetTransform(ortho_projection);
context->SetShader(g_FixedShader);
}
static void ConvertVertexData(Vertex *dest, const ImDrawVert *src, int count)
{
for (int i=0; i < count; i++)
{
const auto &sv = src[i];
Vertex &v = dest[i];
v.x = sv.pos.x;
v.y = sv.pos.y;
v.z = 0.0f;
v.Diffuse = sv.col;
v.tu = sv.uv.x;
v.tv = sv.uv.y;
v.rad = v.ang = 0.0f;
}
}
static void ConvertVertexData(std::vector<Vertex> &ov, const ImVector<ImDrawVert> &src)
{
ov.resize(src.Size);
ConvertVertexData(ov.data(), src.Data, src.Size);
}
// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so.
static void ImGui_ImplRender_RenderDrawData(render::ContextPtr context, ImDrawData* draw_data)
{
PROFILE_FUNCTION_CAT("ui");
// Will project scissor/clipping rectangles into framebuffer space
ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
int fb_width = (int)(draw_data->DisplaySize.x * clip_scale.x);
int fb_height = (int)(draw_data->DisplaySize.y * clip_scale.y);
if (fb_width <= 0 || fb_height <= 0)
return;
// Setup desired GL state
ImGui_ImplRender_SetupRenderState(context, draw_data);
auto sampler = g_FixedShader->GetSampler(0);
std::vector<Vertex> vertexData;
int max = 0;
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
max = std::max(max, cmd_list->VtxBuffer.Size);
}
vertexData.reserve(max);
// Render command lists
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
ConvertVertexData(vertexData, cmd_list->VtxBuffer);
context->UploadVertexData(vertexData);
// context->UploadVertexData(cmd_list->VtxBuffer.Size, (UIVertex *)cmd_list->VtxBuffer.Data);
context->UploadIndexData(cmd_list->IdxBuffer.Size, cmd_list->IdxBuffer.Data);
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback != NULL)
{
// User callback, registered via ImDrawList::AddCallback()
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
ImGui_ImplRender_SetupRenderState(context, draw_data);
else
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
// Project scissor/clipping rectangles into framebuffer space
ImVec4 clip_rect;
clip_rect.x = (pcmd->ClipRect.x - clip_off.x) * clip_scale.x;
clip_rect.y = (pcmd->ClipRect.y - clip_off.y) * clip_scale.y;
clip_rect.z = (pcmd->ClipRect.z - clip_off.x) * clip_scale.x;
clip_rect.w = (pcmd->ClipRect.w - clip_off.y) * clip_scale.y;
if (clip_rect.x < fb_width && clip_rect.y < fb_height && clip_rect.z >= 0.0f && clip_rect.w >= 0.0f)
{
// Apply scissor/clipping rectangle
context->SetScissorRect(
(int)clip_rect.x,
(int)clip_rect.y,
(int)(clip_rect.z - clip_rect.x),
(int)(clip_rect.w - clip_rect.y)
);
// Bind texture, Draw
TexturePtr tex = pcmd->TextureId ? pcmd->TextureId->GetSharedPtr() : nullptr;
if (sampler)
sampler->SetTexture( tex, SAMPLER_WRAP, SAMPLER_LINEAR);
context->DrawIndexed(PRIMTYPE_TRIANGLELIST, pcmd->IdxOffset, pcmd->ElemCount);
}
}
}
}
context->SetScissorDisable();
}
static void ImGui_ImplRender_CreateFontsTexture(render::ContextPtr context)
{
// Build texture atlas
ImGuiIO& io = ImGui::GetIO();
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
auto fmt = context->IsSupported(PixelFormat::BGRA8Unorm) ? PixelFormat::BGRA8Unorm : PixelFormat::RGBA8Unorm;
g_FontTexture = context->CreateTexture("imgui_font", width, height, fmt, pixels);
// Store our identifier
io.Fonts->TexID = g_FontTexture.get();
// io.Fonts->ClearTexData();
}
static ShaderPtr LoadShaderFromFile(render::ContextPtr context, std::string rootDir, std::string path)
{
std::string code;
if (!FileReadAllText(path, code))
{
return nullptr;
}
auto shader = context->CreateShader("ui");
shader->CompileAndLink({
ShaderSource{ShaderType::Vertex, path, code, "VS", "vs_1_1", "hlsl"},
ShaderSource{ShaderType::Fragment, path, code, "PS", "ps_3_0", "hlsl"}
});
return shader;
}
static void ImGui_ImplRender_Init(render::ContextPtr context, std::string assetDir)
{
g_context = context;
// Setup back-end capabilities flags
ImGuiIO& io = ImGui::GetIO();
io.BackendRendererName = "imgui_impl_custom_render";
ImGui_ImplRender_CreateFontsTexture(context);
std::string rootDir = PathCombine(assetDir, "shaders");;
std::string shaderPath = PathCombine(rootDir, "imgui.fx");
g_FixedShader = LoadShaderFromFile(context, rootDir, shaderPath);
}
static void ImGui_ImplRender_Shutdown()
{
ImGuiIO& io = ImGui::GetIO();
io.Fonts->TexID = nullptr;
g_FontTexture = nullptr;
g_FixedShader = nullptr;
g_context = nullptr;
}
static ImFont* ImGuiSupport_AddFontFromFile(const std::string &path, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL)
{
PROFILE_FUNCTION_CAT("ui");
// IMGUI_API ImFont* AddFontFromMemoryTTF(void* font_data, int font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after destruction of the atlas. Set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed.
std::vector<uint8_t> data;
if (!FileReadAllBytes(path, data))
{
return nullptr;
}
void * font_data = ImGui::MemAlloc(data.size());
memcpy(font_data, data.data(), data.size());
std::string name = PathGetFileName(path);
ImFontConfig cfg = *font_cfg;
strncpy(cfg.Name, name.c_str(), sizeof(cfg.Name));
ImGuiIO& io = ImGui::GetIO();
return io.Fonts->AddFontFromMemoryTTF(font_data, (int)data.size(), size_pixels, &cfg, glyph_ranges);
}
void ImGuiSupport_Init(render::ContextPtr context, std::string assetDir)
{
PROFILE_FUNCTION_CAT("ui");
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
// io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Keyboard Controls
// io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Keyboard Controls
//
// io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports;
// io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports;
#ifdef EMSCRIPTEN
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
// For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file.
// You may manually call LoadIniSettingsFromMemory() to load settings from your own storage.
// io.IniFilename = NULL;
#endif
io.KeyMap[ImGuiKey_Tab] = KEYCODE_TAB;
io.KeyMap[ImGuiKey_LeftArrow] = KEYCODE_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = KEYCODE_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = KEYCODE_UP;
io.KeyMap[ImGuiKey_DownArrow] = KEYCODE_DOWN;
io.KeyMap[ImGuiKey_PageUp] = KEYCODE_PAGEUP;
io.KeyMap[ImGuiKey_PageDown] = KEYCODE_PAGEDOWN;
io.KeyMap[ImGuiKey_Home] = KEYCODE_HOME;
io.KeyMap[ImGuiKey_End] = KEYCODE_END;
io.KeyMap[ImGuiKey_Insert] = KEYCODE_INSERT;
io.KeyMap[ImGuiKey_Delete] = KEYCODE_DELETE;
io.KeyMap[ImGuiKey_Backspace] = KEYCODE_BACKSPACE;
io.KeyMap[ImGuiKey_Space] = KEYCODE_SPACE;
io.KeyMap[ImGuiKey_Enter] = KEYCODE_RETURN;
io.KeyMap[ImGuiKey_Escape] = KEYCODE_ESCAPE;
io.KeyMap[ImGuiKey_A] = KEYCODE_A;
io.KeyMap[ImGuiKey_C] = KEYCODE_C;
io.KeyMap[ImGuiKey_V] = KEYCODE_V;
io.KeyMap[ImGuiKey_X] = KEYCODE_X;
io.KeyMap[ImGuiKey_Y] = KEYCODE_Y;
io.KeyMap[ImGuiKey_Z] = KEYCODE_Z;
// Setup Dear ImGui style
ImGui::StyleColorsDark();
// ImGui::StyleColorsClassic();
// SetupImGuiStyle(true, 1.0f);
// ImGuiStyleColor_OSX();
// ImGuiStyleColor_Custom1();
// Load Fonts
// - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
// - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
// - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
// - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
// - Read 'misc/fonts/README.txt' for more instructions and details.
// - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
#if 1
{
std::string fontName;
float fontSize;
//
// fontName = "Roboto-Regular.ttf"; fontSize = 12;
// fontName = "ProggyTiny.ttf"; fontSize = 12;
// fontName = "ProggyClean.ttf"; fontSize = 18;
fontName = "Cousine-Regular.ttf"; fontSize = 14;
std::string fontPath = PathCombine(PathCombine(assetDir, "fonts"), fontName);
ImFontConfig font_config;
font_config.PixelSnapH = false;
font_config.OversampleH = 2;
font_config.OversampleV = 1;
ImGuiSupport_AddFontFromFile(fontPath, fontSize, &font_config);
}
#else
io.Fonts->AddFontDefault();
#endif
{
std::string fontName = "FontAwesome.ttf";
float fontSize = 32.0f;
std::string fontPath = PathCombine(PathCombine(assetDir, "fonts"), fontName);
ImFontConfig icons_config;
icons_config.MergeMode = true;
icons_config.PixelSnapH = true;
icons_config.OversampleH = 1;
icons_config.OversampleV = 1;
static const ImWchar ranges[] =
{
ICON_MIN_FA, ICON_MAX_FA,
0,
};
g_font_awesome = ImGuiSupport_AddFontFromFile(fontPath, fontSize, &icons_config, ranges);
}
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
//IM_ASSERT(font != NULL);
// Setup Platform/Renderer bindings
ImGui_ImplRender_Init( context, assetDir);
}
void ImGuiSupport_Render()
{
PROFILE_FUNCTION_CAT("ui");
ImGui::Render();
ImGui_ImplRender_RenderDrawData(g_context, ImGui::GetDrawData() );
}
void ImGuiSupport_Shutdown()
{
ImGui_ImplRender_Shutdown();
ImGui::DestroyContext();
}
namespace ImGui {
static float _values_getter(void* data, int idx)
{
auto func = (std::function<float (int idx)> *)data;
return (*func)(idx);
}
void PlotHistogram(const char* label, std::function<float (int idx)> value_func, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)
{
ImGui::PlotHistogram(label, _values_getter, &value_func, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
}
}
|
#pragma once
#include "D3DIncludes.hpp"
#include "Types.hpp"
namespace engine
{
class Device
{
public:
Device() {}
~Device() {}
Bool Create(ComPtr<IDXGIAdapter>& adapter, bool debug);
// One GPU
ComPtr<ID3D12CommandQueue> CreateDirectCommandQueue();
ComPtr<ID3D12CommandList> CreateCommandList();
ComPtr<ID3D12CommandList> CreateCommandList(ComPtr<ID3D12CommandAllocator>& commandAllocator, ComPtr<ID3D12PipelineState>& pipelineState);
ComPtr<ID3D12CommandAllocator> CreateCommandAllocator();
ComPtr<ID3D12PipelineState> CreatePipelineState();
ComPtr<ID3D12DescriptorHeap> CreateRenderTargetDescriptorHeap(Uint32 bufferNum);
ComPtr<ID3D12DescriptorHeap> CreateDepthStencilDescriptorHeap();
Uint32 GetRenderTargetDescriptorSize();
Uint32 GetDepthStencilDescriptorSize();
private:
ComPtr<ID3D12Debug> m_debugController;
ComPtr<ID3D12Device1> m_device;
};
}
|
#include "Plane.h"
#include <cmath>
bool Plane::intersects(Ray* ray) {
double a = normal.x;
double b = normal.y;
double c = normal.z;
double e = ray->vector->x;
double g = ray->vector->y;
double i = ray->vector->z;
double denominator = a*e + b*g + c*i;
if(denominator == 0) {
return false;
}
return true;
}
double Plane::intersectsWhen(Ray* ray) {
double a = normal.x;
double b = normal.y;
double c = normal.z;
double d = dotBoi;
double e = ray->vector->x;
double f = ray->point->x;
double g = ray->vector->y;
double h = ray->point->y;
double i = ray->vector->z;
double j = ray->point->z;
double numerator = a*f + b*h + c*j + d;
double denominator = a*e + b*g + c*i;
double ans = -1 * numerator / denominator;
if(ans > 0) {
return -1;
}
return (-1) * ans * (double)(ray->vector->mag());
}
|
#include <QApplication>
#include "MainWindow.hpp"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setOrganizationName("MAI 221_222 2012");
a.setApplicationName("Schedule");
MainWindow w;
w.show();
return a.exec();
}
|
#include <stdio.h>
#include <stdlib.h>
#include<sys/types.h>
int main() {
int pid = fork();
if (pid == 0) {
printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(),
getppid());
}
else {
printf("This is the parent process. My pid is %d and my parent's id is %d.\n", pid,getpid());
}
return 0;
}
|
#include "KSGlobalLocker.h"
#include <mutex>
KS_UTIL_BEGIN
static std::mutex ResourcesLocker;
inline void LockResources(void)
{
ResourcesLocker.lock();
}
inline void UnlockResources(void)
{
ResourcesLocker.unlock();
}
inline bool TryLockResources(void)
{
return ResourcesLocker.try_lock();
}
KS_UTIL_END
|
//@@author A0112218W
#include "Command_Set.h"
ALREADY_COMPLETE_EXCEPTION::ALREADY_COMPLETE_EXCEPTION(int index) : std::exception() {
sprintf_s(_message, MESSAGE_SET_COMPLETE_NO_CHANGE.c_str(), index);
}
const char* ALREADY_COMPLETE_EXCEPTION::what(void) const throw() {
return _message;
}
SetCompleteCommand::SetCompleteCommand(size_t index) : Command(CommandTokens::PrimaryCommandType::MarkAsComplete) {
_type2 = CommandTokens::SecondaryCommandType::Index;
_index = index;
}
UIFeedback SetCompleteCommand::execute(RunTimeStorage* runTimeStorage) {
checkIsValidForExecute(runTimeStorage);
UIFeedback feedback;
try {
Task& taskToSet = runTimeStorage->find(_index);
_setIndex = runTimeStorage->find(taskToSet);
std::string feedbackMessage;
char buffer[255];
if (taskToSet.isComplete()) {
throw ALREADY_COMPLETE_EXCEPTION(_index);
}
taskToSet.toggleComplete();
postExecutionAction(runTimeStorage);
sprintf_s(buffer, MESSAGE_SET_COMPLETE_SUCCESS.c_str(), _index);
feedbackMessage = std::string(buffer);
feedback = UIFeedback(runTimeStorage->refreshTasksToDisplay(), feedbackMessage);
} catch (INDEX_NOT_FOUND_EXCEPTION e) {
throw COMMAND_EXECUTION_EXCEPTION(e.what());
} catch (ALREADY_COMPLETE_EXCEPTION e) {
throw COMMAND_EXECUTION_EXCEPTION(e.what());
}
return feedback;
}
UIFeedback SetCompleteCommand::undo() {
checkIsValidForUndo();
Task& taskToSet = _runTimeStorageExecuted->getEntry(_setIndex);
assert(taskToSet.isComplete());
taskToSet.toggleComplete();
std::vector<Task> tasksToDisplay = _runTimeStorageExecuted->refreshTasksToDisplay();
postUndoAction();
return UIFeedback(tasksToDisplay, MESSAGE_SET_UNDO);
}
bool SetCompleteCommand::canUndo() {
return true;
}
|
// This file has been generated by Py++.
#ifndef TypedPropertyFloat_hpp__pyplusplus_wrapper
#define TypedPropertyFloat_hpp__pyplusplus_wrapper
void register_TypedPropertyFloat_class();
#endif//TypedPropertyFloat_hpp__pyplusplus_wrapper
|
#pragma once
#include <string>
#include <cstdarg>
#include <cstdio>
#include "utils/iTypes.h"
#include "core/concurrent/iLockable.h"
typedef enum e_debug_level
{
SILENT =-1,
NO_DEBUG = 0,
LOW_LEVEL = 1,
MEDIUM_LEVEL = 2,
HIGH_LEVEL = 3,
MAX_LEVEL = 4,
DISABLE = 5
} e_debug;
#define LOGGER Logger::getInstance ()
#define LOGMSG Logger::getInstance ()->print
namespace Comm
{
#ifdef USE_THREADS
class Logger : private Lockable
#else
class Logger
#endif
{
public:
typedef struct tagLogSession
{
unsigned int threadId;
char sessionId[32];
}LogSession;
public:
static Logger* getInstance ();
static void finalize ();
protected:
Logger (const Logger&);
Logger (const e_debug &debug = NO_DEBUG,
const std::string &log_file = "", FILE *pFP = NULL);
public:
virtual ~Logger ();
protected:
Logger& operator=(const Logger& rLogger);
private:
void openLogFile ();
void closeLogFile ();
public:
void setDebugLevel (e_debug debug);
void setLogFile (const std::string &file);
std::string& getLogFile();
void setLogPath( const std::string &path );
void setSessionId(const std::string &id);
std::string getSessionId();
void setMoudleName(const std::string &module_name);
void makeLog(char* buffer, e_debug debug, const char* format, va_list ap );
void print (e_debug debug, const char *msg, va_list ap);
void print (e_debug debug, const char *msg, ...);
private:
static Logger* mspInstance;
private:
e_debug m_debug_level;
std::string m_log_file;
std::string m_log_path;
FILE* mpFP;
std::string m_module_name;
public:
static const uint32 MSG_BUFF_SIZE = BUFSIZ;
static const uint32 DATE_BUFF_SIZE = 32;
#ifndef HAVE_SYS_SYSCALL_H
#ifdef _LP64
static const uint32 GETTID_SYSCALL_ID = 186;
#else
static const uint32 GETTID_SYSCALL_ID = 224;
#endif
#endif
};
}
|
// Copyright ⓒ 2020 Valentyn Bondarenko. All rights reserved.
#include <StdAfx.hpp>
#include <Build.hpp>
namespace be::utils
{
uint Build::build_id(const Date& build_date, const string& current_date)
{
Date current{ };
string month_string = ""s;
std::stringstream buffer;
buffer << current_date;
buffer >> month_string;
buffer >> current.day;
buffer >> current.year;
string month_id[12] =
{
"Jan"s,"Feb"s,"Mar"s,"Apr"s,"May"s,"Jun"s,"Jul"s,"Aug"s,"Sep"s,"Oct"s,"Nov"s,"Dec"s
};
current.month = 1;
for (const auto& month : month_id)
if (month != month_string)
{
current.month++;
continue;
}
else
break;
auto day_count = [](const Date& date)
{
auto const years = date.year;
auto const extra_day_count = ((years % 400 == 0) || ((years % 4 == 0) && (years % 100 != 0))) ? 1 : 0;
auto const years_minus_1 = static_cast<uint>(years) - 1;
auto result = years_minus_1 * 365 + years_minus_1 / 4 - years_minus_1 / 100 + years_minus_1 / 400;
auto const months = date.month;
if (months > 1) result += 31;
if (months > 2) result += 28 + extra_day_count;
if (months > 3) result += 31;
if (months > 4) result += 30;
if (months > 5) result += 31;
if (months > 6) result += 30;
if (months > 7) result += 31;
if (months > 8) result += 31;
if (months > 9) result += 30;
if (months > 10) result += 31;
if (months > 11) result += 30;
return (result + date.day - 1);
};
auto start_days = day_count(build_date);
auto stop_days = day_count(current);
return (stop_days - start_days);
}
uint Build::calculate_build_id(string current_date)
{
// start development date (03.05.2020).
constexpr auto start_dev_day = 3;
constexpr auto start_dev_month = 5;
constexpr auto start_dev_year = 2020;
return build_id(Date{ start_dev_day, start_dev_month, start_dev_year }, current_date);
}
}
|
#pragma once
#include <set>
#include <array>
#include <queue>
#include <atomic>
#include <thread>
#include <unordered_set>
#include "Buffer.h"
#include "Comparators.h"
const int CHUNK_SIZE = 16;
template <class T, size_t... S>
struct ArrayHelper;
template <class T, size_t X, size_t Y, size_t Z>
struct ArrayHelper<T, X, Y, Z> {
using type = std::array<std::array<std::array<T, Z>, Y>, X>;
};
template <class T, size_t N>
struct ArrayHelper<T, N> {
using type = std::array<std::array<std::array<T, N>, N>, N>;
};
template<class T, size_t... A>
using Array3D = typename ArrayHelper<T, A...>::type;
extern std::map<glm::vec3, std::map<glm::vec3, std::pair<int, int>, VectorComparator>, ChunkPosComparator> ChangedBlocks;
extern std::map<glm::vec2, std::map<glm::vec2, int, VectorComparator>, VectorComparator> TopBlocks;
namespace Chunks {
void Load_Structures();
void Seed(int seed);
void Delete(glm::vec3 chunk);
};
struct Block;
struct LightNode {
glm::vec3 Chunk;
glm::vec3 Tile;
int LightLevel;
bool Down;
LightNode(glm::vec3 chunk, glm::vec3 tile, int lightLevel = 0, bool down = false) {
Chunk = chunk;
Tile = tile;
LightLevel = lightLevel;
Down = down;
}
};
class Chunk {
public:
Buffer buffer;
glm::vec3 Position;
Data VBOData;
std::queue<LightNode> LightQueue;
std::queue<LightNode> LightRemovalQueue;
std::map<glm::ivec3, std::pair<unsigned int, unsigned int>, VectorComparator> ExtraOffsets;
std::atomic_bool Meshed = ATOMIC_VAR_INIT(false);
std::atomic_bool Visible = ATOMIC_VAR_INIT(true);
std::atomic_bool Generated = ATOMIC_VAR_INIT(false);
std::atomic_bool DataUploaded = ATOMIC_VAR_INIT(false);
Chunk(glm::vec3 position) {
Position = position;
}
inline int Get_Type(glm::uvec3 pos) { return BlockMap[pos.x][pos.y][pos.z]; }
inline void Set_Type(glm::uvec3 pos, int value) { BlockMap[pos.x][pos.y][pos.z] = value; }
inline unsigned char Get_Air(glm::uvec3 pos) { return SeesAir[pos.x][pos.y][pos.z]; }
inline unsigned char& Get_Air_Ref(glm::uvec3 pos) { return SeesAir[pos.x][pos.y][pos.z]; }
inline int Get_Data(glm::vec3 pos) { return DataMap.count(pos) ? DataMap[pos] : 0; }
inline void Set_Data(glm::vec3 pos, int data) { DataMap[pos] = data; }
void Set_Extra_Texture(glm::ivec3 pos, int texture);
void Generate();
void Light(bool flag = true);
void Mesh();
void Draw(bool transparentPass = false);
void Remove_Multiblock(glm::ivec3 position, const Block* block);
void Add_Multiblock(glm::ivec3 position, const Block* block);
void Remove_Block(glm::ivec3 position, bool checkMulti = true);
void Add_Block(glm::ivec3 position, int blockType, int blockData, bool checkMulti = true);
inline int Get_Light(glm::uvec3 pos) {
return LightMap[pos.x][pos.y][pos.z];
}
inline void Set_Light(glm::uvec3 pos, int value) {
LightMap[pos.x][pos.y][pos.z] = static_cast<unsigned char>(value);
}
inline bool Top_Exists(glm::ivec3 tile) {
return TopBlocks.count(Position.xz()) && TopBlocks[Position.xz()].count(tile.xz());
}
inline int Get_Top(glm::ivec3 tile) {
return TopBlocks[Position.xz()][tile.xz()];
}
inline void Set_Top(glm::ivec3 tile, int value) {
TopBlocks[Position.xz()][tile.xz()] = value;
}
private:
bool ContainsChangedBlocks = false;
bool ContainsTransparentBlocks = false;
void Update_Air(glm::ivec3 pos, glm::bvec3 inChunk);
void Update_Transparency(glm::ivec3 pos);
void Generate_Block(glm::ivec3 pos);
void Generate_Tree(glm::vec3 tile);
void Check_Ore(glm::ivec3 pos, glm::dvec3 noisePos);
float GetAO(glm::vec3 block, int face, int offset);
Array3D<int, CHUNK_SIZE> BlockMap = {0};
Array3D<unsigned char, CHUNK_SIZE> LightMap = {0};
Array3D<unsigned char, CHUNK_SIZE> SeesAir = {0};
std::unordered_set<glm::vec3, VectorHasher> Blocks;
std::map<glm::vec3, int, VectorComparator> DataMap;
std::set<glm::vec3, VectorComparator> TransparentBlocks;
};
std::vector<std::pair<glm::vec3, glm::vec3>> Get_Neighbors(glm::vec3 chunk, glm::vec3 tile);
std::pair<glm::vec3, glm::vec3> Get_Chunk_Pos(glm::vec3 worldPos);
bool Is_Block(glm::vec3 pos);
bool Exists(glm::vec3 chunk);
inline glm::vec3 Get_World_Pos(glm::vec3 chunk, glm::vec3 tile) {
return glm::fma(glm::vec3(static_cast<float>(CHUNK_SIZE)), chunk, tile);
}
|
/**
* @file MoleculeLJ.h
*
* @date 17 Jan 2018
* @author tchipevn
*/
#pragma once
#include <vector>
#include "autopas/particles/Particle.h"
namespace autopas {
/**
* lennard jones molecule class
*/
class MoleculeLJ : public Particle {
public:
MoleculeLJ() = default;
/**
* constructor of a lennard jones molecule
* @param r position of the molecule
* @param v velocity of the molecule
* @param id id of the molecule
*/
explicit MoleculeLJ(std::array<double, 3> r, std::array<double, 3> v, unsigned long id) : Particle(r, v, id) {}
~MoleculeLJ() override = default;
/**
* get epsilon (characteristic energy of the lj potential)
* @return epsilon
*/
static double getEpsilon() { return EPSILON; }
/**
* set epsilon (characteristic energy of the lj potential)
* @param epsilon
*/
static void setEpsilon(double epsilon) { EPSILON = epsilon; }
/**
* get sigma (characteristic length of the lj potential)
* @return sigma
*/
static double getSigma() { return SIGMA; }
/**
* set sigma (characteristic length of the lj potential)
* @param sigma
*/
static void setSigma(double sigma) { SIGMA = sigma; }
private:
static double EPSILON, SIGMA;
};
} // namespace autopas
|
#include <iostream>
using namespace std;
float square1(float num){
return num * num;
}
float square2(float *num){
return *num * *num;
}
void Fibonacci(int n, int i = 0, int f1 = 0, int f2 = 1){
if (i <= n ) {
if (i == 0) {
cout << 0 << ' ';
Fibonacci(n, i+1, 0, 1);
}
else if (i == 1) {
cout << 1 << ' ';
Fibonacci(n, i+1, 0, 1);
}
else {
cout << f1 + f2 << ' ';
Fibonacci(n, i+1, f2, f1 + f2);
}
}
}
void Maximum(){
float a, b, c;
cin >> a;
cin >> b;
cin >> c;
float max = a;
if (b > max) {
max = b;
}
if (c > max) {
max = c;
}
cout << max << endl;
}
int factorial (int x) {
if (x > 1) {
return factorial(x - 1) * x;
}
else {
return 1;
}
}
int main() {
// Maximum();
float num = 2.5;
// cout << square1(num) << endl;
// cout << square2(&num) << endl;
// Fibonacci(10);
cout << factorial(4);
return 0;
}
|
#include "AppDelegate.h"
#include "OpeningMenuScene.h"
#include "LevelDemoScene.h"
#include "TransitionScene.h"
#include "global.h"
#include "EntityModel.h"
#include <fstream>
USING_NS_CC;
AppDelegate::AppDelegate() {
}
AppDelegate::~AppDelegate()
{
}
//if you want a different context,just modify the value of glContextAttrs
//it will takes effect on all platforms
void AppDelegate::initGLContextAttrs()
{
//set OpenGL context attributions,now can only set six attributions:
//red,green,blue,alpha,depth,stencil
GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};
GLView::setGLContextAttrs(glContextAttrs);
}
bool CreateAllTheSounds(std::wstring &error);
bool AppDelegate::applicationDidFinishLaunching() {
LoadXML(xmlLoader);
// initialize director
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
if(!glview) {
glview = GLViewImpl::create("My Game");
director->setOpenGLView(glview);
}
sqlite3* rawConnec = nullptr;
std::string path = /*FileUtils::getInstance()->getWritablePath() +*/ "C:/duckloon/duckloon/proj.win32/my.db";
CCLOG("The db path %s", path.c_str());
sqlite3_open(path.c_str(), &rawConnec);
std::shared_ptr<sqlite3> db(rawConnec, sqlite3_close);
std::shared_ptr<IEntityModel> entityModel = std::make_shared<EntityModel>(db);
std::shared_ptr<Entity> foundModel = entityModel->findEntityById(1);
// turn on display FPS
director->setDisplayStats(true);
// set FPS. the default value is 1.0/60 if you don't call this
director->setAnimationInterval(1.0 / 60);
//FMOD setup
std::wstring error;
if (!InitFMOD(::g_FMODInitparams, error))
{
return -1;
}
if (!CreateAllTheSounds(error))
{
return -1;
}
FMOD::Channel *channel;
g_FMODResult = g_FMODInitparams.system->playSound(FMOD_CHANNEL_REUSE, g_Sounds["Sound/Duckloon_Menu_MUSIC_MIX.mp3"], false, &g_channels["BGM"]);
std::wstringstream ssErrors;
if (!FMODERRORCHECK(g_FMODResult, error))
{
ssErrors << error << std::endl;
error = ssErrors.str();
CCLOG("Playing sound: %s\n", error);
return false;
}
// create a scene. it's an autorelease object
auto scene = OpeningMenu::createScene();
//auto scene = LevelDemo::createScene();
//auto scene = Transition::createScene();
// run
director->runWithScene(scene);
return true;
}
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground() {
Director::getInstance()->stopAnimation();
// if you use SimpleAudioEngine, it must be pause
// SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground() {
Director::getInstance()->startAnimation();
// if you use SimpleAudioEngine, it must resume here
// SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}
bool CreateAllTheSounds(std::wstring &error)
{
FMOD_RESULT FMODResult;
std::wstringstream ssErrors;
std::string fileName = "Sound.txt";
std::string soundsDir = "Sound/";
std::ifstream myFile((soundsDir + fileName).c_str());
//Check if file is open
if (!myFile.is_open()) return false;
std::string temp;
FMOD::Sound* sound;
bool bKeepReading = true;
//Read in the file
while (bKeepReading)
{
myFile >> temp;
if (temp == "#SOUND") //Found a Streaming Sound
{
myFile >> temp;
FMODResult = ::g_FMODInitparams.system->createStream((soundsDir + temp).c_str(), FMOD_DEFAULT, 0, &sound);
g_Sounds[(soundsDir + temp).c_str()] = sound;
//FMOD::Channel *channel;
//g_channels[(soundsDir + temp).c_str()] = channel;
if (!FMODERRORCHECK(FMODResult, error))
{
ssErrors << error << std::endl;
error = ssErrors.str();
return false;
}
}
else if (temp == "#END") bKeepReading = false;
}
//FMODResult = ::g_FMODInitparams.system->playSound(FMOD_CHANNEL_FREE, g_bgMusic[0], false, &(g_channels[0]));
return true;
}
|
/*
The MIT License (MIT)
Copyright 2016 Luca Beldi
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 abstractmodelserialiser_h__
#define abstractmodelserialiser_h__
#include "model_serialisation_global.h"
#include <QObject>
class AbstractModelSerialiserPrivate;
class QAbstractItemModel;
class QIODevice;
class QT_MODEL_SERIALISATION_EXPORT AbstractModelSerialiser
{
Q_GADGET
Q_PROPERTY(QAbstractItemModel* model READ model WRITE setModel)
Q_PROPERTY(const QAbstractItemModel* constModel READ constModel WRITE setModel)
Q_DECLARE_PRIVATE(AbstractModelSerialiser)
public:
AbstractModelSerialiser(QAbstractItemModel* model = Q_NULLPTR);
AbstractModelSerialiser(const QAbstractItemModel* model);
AbstractModelSerialiser(const AbstractModelSerialiser& other);
AbstractModelSerialiser& operator=(const AbstractModelSerialiser& other);
#ifdef Q_COMPILER_RVALUE_REFS
AbstractModelSerialiser(AbstractModelSerialiser&& other) Q_DECL_NOEXCEPT;
AbstractModelSerialiser& operator=(AbstractModelSerialiser&& other);
#endif // Q_COMPILER_RVALUE_REFS
virtual ~AbstractModelSerialiser() = 0;
virtual QAbstractItemModel* model() const;
virtual const QAbstractItemModel* constModel() const;
void setModel(QAbstractItemModel* val);
void setModel(const QAbstractItemModel* val);
Q_INVOKABLE virtual bool saveModel(QIODevice* destination) const = 0;
Q_INVOKABLE virtual bool saveModel(QByteArray* destination) const = 0;
Q_INVOKABLE virtual bool loadModel(QIODevice* source) = 0;
Q_INVOKABLE virtual bool loadModel(const QByteArray& source) = 0;
protected:
AbstractModelSerialiserPrivate* d_ptr;
AbstractModelSerialiser(AbstractModelSerialiserPrivate& d);
};
#endif // abstractmodelserialiser_h__
|
#include <windows.h>
#include <dbghelp.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#pragma comment(lib, "dbghelp.lib")
int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow
) {
ULONG cbSize;
TCHAR szMyPath[MAX_PATH];
HMODULE hModule;
PIMAGE_IMPORT_DESCRIPTOR pImageImportDescriptor = NULL;
PIMAGE_THUNK_DATA pFirstThunk = NULL;
PIMAGE_THUNK_DATA pOriginalFirstThunk = NULL;
GetModuleFileName(NULL, szMyPath, _countof(szMyPath));
hModule = GetModuleHandle((LPCSTR)szMyPath);
pImageImportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)ImageDirectoryEntryToData(hModule, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, &cbSize);
while (pImageImportDescriptor->Name != NULL) {
pFirstThunk = (PIMAGE_THUNK_DATA)((PBYTE)hModule + pImageImportDescriptor->FirstThunk);
pOriginalFirstThunk = (PIMAGE_THUNK_DATA)((PBYTE)hModule + pImageImportDescriptor->OriginalFirstThunk);
LPCSTR pszDllName = (LPCSTR)((PBYTE)hModule + pImageImportDescriptor->Name);
MessageBox(NULL, pszDllName, "will show imports func addr from this dll", MB_OK | MB_ICONINFORMATION);
while (pFirstThunk->u1.Function != NULL) {
std::stringstream ss;
ss << "0x" << std::hex << pFirstThunk->u1.Function << std::endl;
PIMAGE_IMPORT_BY_NAME pImageImportByName = (PIMAGE_IMPORT_BY_NAME)((PBYTE)hModule + pOriginalFirstThunk->u1.AddressOfData);
LPCSTR pszFuncName = (LPCSTR)&pImageImportByName->Name[0];
MessageBox(NULL, ss.str().c_str(), pszFuncName, MB_OK);
pFirstThunk++;
pOriginalFirstThunk++;
}
pImageImportDescriptor++;
}
CloseHandle(hModule);
return 0;
}
|
/**
* @file TCPConnectedClient.h
* Defines the TCPConnectedClient class.
* @date Jan 21, 2014
* @author: Alper Sinan Akyurek
*/
#ifndef TCPCONNECTEDCLIENT_H_
#define TCPCONNECTEDCLIENT_H_
#include "SocketBase.h"
#include "IPAddress.h"
/**
* Manages the connection to a connected client on the server side. When a client is accepted, an instance of the class is initialized to furthur maintain the connection.
*/
class TCPConnectedClient : public SocketBase<SOCK_STREAM>
{
public:
/**
* Initializes the class with a ready socket and address.
@param socketId Handle to the socket.
@param clientAddress IPAddress of the connected client.
*/
TCPConnectedClient( const TSocketId socketId, IPAddress & clientAddress );
/**
* Copies the contents of another instance.
@param copy Instance to be copied.
*/
TCPConnectedClient( const TCPConnectedClient & copy );
/**
* Not used.
*/
~TCPConnectedClient( void );
/**
* Sends data to the connected client.
*
* @param buffer Buffer, holding the data to be sent.
* @param length Length of the data to be sent.
*
* @return Actual number of bytes sent.
*/
TNumberOfBytes
SendData( const TBuffer buffer, const TNumberOfBytes length );
/**
* Receives data from the connected client. This is a blocking call.
*
* @param buffer Buffer, where the received data will be stored int.
* @param receptionLength Length of the buffer and the maximum receivable data size.
*
* @return The actual number of bytes received.
*/
TNumberOfBytes
ReceiveData( TBuffer buffer, const TNumberOfBytes receptionLength );
/**
* Returns the IP address of the client.
*
* @return IP address of the client.
*/
IPAddress
GetClientAddress( void ) const;
private:
/**
* Defines the base class for rapid development.
*/
typedef SocketBase<SOCK_STREAM> TBaseType;
private:
/**
* IP Address of the client.
*/
IPAddress m_clientAddress;
};
#endif /* TCPCONNECTEDCLIENT_H_ */
|
#pragma once
#pragma warning (disable: 4996 4091 4101 4018 4309 4099 4102 4800 4244 4482 4305 4005)
#define WIN32_LEAN_AND_MEAN
#include <string.h>
#include <cstdio>
#include <cstdarg>
#include <map>
#include <fstream>
#include <string>
#include <algorithm>
#include <ctime>
#include <sstream>
#include <windows.h>
#include <iostream>
#include <time.h>
#include <conio.h>
#include <stdio.h>
#include <tchar.h>
#include <math.h>
#include <stdlib.h>
#include <direct.h>
#include <fcntl.h>
#include <io.h>
#include <vector>
#include <rpc.h>
#include <rpcdce.h>
#include <stdio.h>
#include <iomanip>
#include <cstdlib>
#include <tlhelp32.h>
#include <process.h>
#include <shellapi.h>
#include <WinSock2.h>
#include <vector>
#include <gl\gl.h>
#include <gl\glu.h>
#include <psapi.h>
#pragma comment(lib,"OpenGL32.lib")
#pragma comment(lib,"Detours.lib")
#pragma comment(lib,"user32.lib")
#pragma comment(lib,"GLu32.lib")
#pragma comment(lib,"GLaux.lib")
#pragma comment (lib,"psapi.lib")
#pragma comment(lib,"WS2_32.lib")
#include "Fog.h"
#include "Customs.h"
#include "detours.h"
#include "Functions.h"
#include "Protocol.h"
#include "Packets.h"
#include "Offsets.h"
#include "HealthBar.h"
#include "MiniMap.h"
#include "Jewels.h"
#include "ExpBar.h"
#include "Models.h"
#include "Camera.h"
#include "glaux.h"
#include "Dump.h"
#include "Npc.h"
LRESULT CALLBACK KeyboardProc(int, WPARAM, LPARAM);
LRESULT CALLBACK MouseProc(int, WPARAM, LPARAM);
BOOL MouseSetHook(BOOL);
BOOL KeyboardSetHook(BOOL);
|
#ifndef ROSE_PATHS_H
#define ROSE_PATHS_H
// DQ (4/21/2009): If this is not set then set it here.
// For most of ROSE usage this is set in sage3.h, but initial
// construction or ROSETTA used to generate ROSE requires
// it as well.
#if !defined(_FILE_OFFSET_BITS)
#define _FILE_OFFSET_BITS 64
#endif
// DQ (4/21/2009): This must be set before sys/stat.h is included by any other header file.
// Use of _FILE_OFFSET_BITS macro is required on 32-bit systems to control the size of "struct stat"
#if !(defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64))
#error "The _FILE_OFFSET_BITS macro should be set before any sys/stat.h is included by any other header file!"
#endif
#include <string>
extern const std::string ROSE_GFORTRAN_PATH;
extern const std::string ROSE_AUTOMAKE_TOP_SRCDIR;
extern const std::string ROSE_AUTOMAKE_TOP_BUILDDIR;
extern const std::string ROSE_AUTOMAKE_PREFIX;
extern const std::string ROSE_AUTOMAKE_DATADIR;
extern const std::string ROSE_AUTOMAKE_BINDIR;
extern const std::string ROSE_AUTOMAKE_INCLUDEDIR;
extern const std::string ROSE_AUTOMAKE_INFODIR;
extern const std::string ROSE_AUTOMAKE_LIBDIR;
extern const std::string ROSE_AUTOMAKE_LIBEXECDIR;
extern const std::string ROSE_AUTOMAKE_LOCALSTATEDIR;
extern const std::string ROSE_AUTOMAKE_MANDIR;
extern const std::string ROSE_AUTOMAKE_ABSOLUTE_PATH_TOP_SRCDIR;
/* Additional interesting data to provide */
extern const std::string ROSE_CONFIGURE_DATE;
extern const std::string ROSE_AUTOMAKE_BUILD_OS;
extern const std::string ROSE_AUTOMAKE_BUILD_CPU;
extern const std::string ROSE_OFP_VERSION_STRING;
/* Numeric form of ROSE version -- assuming ROSE version x.y.zL (where */
/* x, y, and z are numbers, and L is a single lowercase letter from a to j), */
/* the numeric value is x * 1000000 + y * 10000 + z * 100 + (L - 'a') */
extern const int ROSE_NUMERIC_VERSION;
// DQ (5/2/2009): This is temporary while we work out the details of the new Graph IR nodes.
// #define USING_GRAPH_IR_NODES_FOR_BACKWARD_COMPATABILITY 0
//#ifdef ROSE_USE_NEW_GRAPH_NODES
//#ifndef ROSE_USING_GRAPH_IR_NODES_FOR_BACKWARD_COMPATABILITY
//#warning "ROSE_USING_GRAPH_IR_NODES_FOR_BACKWARD_COMPATABILITY IS NOT SET"
//#endif
//#endif
#endif /* ROSE_PATHS_H */
|
#pragma once
#include <ScaleType.h>
class MetaScale : public ScaleType {
private:
void normalize();
public:
MetaScale() = default;
MetaScale(const ScaleType& copy) : ScaleType(copy) {}
template<typename ratio, uint32_t ref>
MetaScale(const Scale<ratio, ref>& scale) : ScaleType(scale) {}
MetaScale operator*(const MetaScale& b) const;
MetaScale operator/(const MetaScale& b) const;
MetaScale& operator*=(const MetaScale& b);
MetaScale& operator/=(const MetaScale& b);
};
|
//
// NaturesAttendants.cpp
// Boids
//
// Created by chenyanjie on 3/31/15.
//
//
#include "NaturesAttendants.h"
#include "../../scene/BattleLayer.h"
#include "../../Utils.h"
#include "../UnitNodeComponent.h"
using namespace cocos2d;
NaturesAttendants::NaturesAttendants() {
}
NaturesAttendants::~NaturesAttendants() {
}
NaturesAttendants* NaturesAttendants::create( UnitNode* owner, const cocos2d::ValueMap& data, const cocos2d::ValueMap& params ) {
NaturesAttendants* ret = new NaturesAttendants();
if( ret && ret->init( owner, data, params ) ) {
ret->autorelease();
return ret;
}
else {
CC_SAFE_DELETE( ret );
return nullptr;
}
}
bool NaturesAttendants::init( UnitNode* owner, const cocos2d::ValueMap& data, const cocos2d::ValueMap& params ) {
if( !SkillNode::init( owner ) ) {
return false;
}
_could_interupt = false;
int level = data.at( "level" ).asInt();
_heal = data.at( "hp" ).asValueVector().at( level - 1 ).asFloat();
_range = data.at( "range" ).asFloat();
_count = data.at( "count" ).asValueVector().at( level - 1 ).asInt();
_duration = data.at( "duration" ).asFloat();
_elapse = 0;
_interval = data.at( "interval" ).asFloat();
_heal_elapse = 0;
_init_speed = data.at( "init_speed" ).asFloat();
_accel = data.at( "accel" ).asFloat();
return true;
}
void NaturesAttendants::updateFrame( float delta ) {
if( !_should_recycle ) {
_elapse += delta;
_heal_elapse += delta;
if( _elapse > _duration ) {
this->end();
}
else {
if( _heal_elapse >= _interval ) {
_heal_elapse = 0;
Vector<UnitNode*> candidates = _owner->getBattleLayer()->getAliveAllyInRange( _owner->getTargetCamp(), _owner->getPosition(), _range );
for( auto unit : candidates ) {
DamageCalculate* calculator = DamageCalculate::create( SKILL_NAME_NATURESATTENDANTS, _heal );
ValueMap result = calculator->calculateDamageWithoutMiss( _owner->getTargetData(), unit->getTargetData() );
result["cri"] = Value( false );
unit->takeHeal( result, _owner->getDeployId() );
}
}
}
}
}
void NaturesAttendants::begin() {
SkillNode::begin();
std::string resource = "effects/enchantress_skill_1/charge";
spine::SkeletonAnimation* skeleton = ArmatureManager::getInstance()->createArmature( resource );
std::string name = Utils::stringFormat( "%s_%d", SKILL_NAME_NATURESATTENDANTS, BulletNode::getNextBulletId() );
UnitNodeSpineComponent* component = UnitNodeSpineComponent::create( skeleton, name, true );
component->setPosition( Point::ZERO );
_owner->addUnitComponent( component, component->getName(), eComponentLayer::OverObject );
component->setAnimation( 0, "animation", false );
for( int i = 0; i < _count; ++i ) {
resource = "effects/enchantress_skill_1/spirit";
skeleton = ArmatureManager::getInstance()->createArmature( resource );
name = Utils::stringFormat( "%s_%d", SKILL_NAME_NATURESATTENDANTS, BulletNode::getNextBulletId() );
ValueMap spirit_data;
spirit_data["duration"] = Value( _duration );
spirit_data["init_speed"] = Value( _init_speed );
spirit_data["accelerate"] = Value( _accel );
spirit_data["range"] = Value( _range );
spirit_data["interval"] = Value( _interval );
TimeLimitWanderSpineComponent* spirit_component = TimeLimitWanderSpineComponent::create( spirit_data, _owner, skeleton, name, true );
spirit_component->setAnimation( 0, "animation", true );
_owner->getBattleLayer()->addToEffectLayer( spirit_component, _owner->getHitPos(), 0 );
_effects.pushBack( spirit_component );
}
}
void NaturesAttendants::end() {
SkillNode::end();
for( auto effect : _effects ) {
effect->setShouldRecycle( true );
}
}
|
#pragma once
#include "Client.h"
#include "OutputMemoryBitStream.h"
#include "InputMemoryBitStream.h"
enum PacketType {HELLO, WELCOME, NEWPLAYER, DISCONNECT, ACK, PING, ACKPING, ACKMOVE, SHOOT, GAMEOVER, GAMESTART, GOAL, NOTWELCOME, MOVE, MOVEBALL};
const int commandBits = 4;
const int maxBufferSize = 1300;
const int playerSizeBits = 3;
const int coordsbits = 10;
const int criticalBits=8;
const int deltaMoveBits = 8;
const int subdividedSteps = 25;
void RemoveNonAckMovesUntilId(std::vector<AccumMove>*aMoves, int id) {
int index = -1;
for (int i = 0; i < aMoves->size(); i++) {
if (aMoves->at(i).idMove==id) {
index = i;
}
}
if (index > -1) {
aMoves->erase(aMoves->begin(), aMoves->begin() + index);
}
}
ServerClient* GetServerClientWithIpPort(unsigned short port, std::string ip, std::vector<ServerClient*>*aClients) {
int playerSize = 0;
for (int i = 0; i < aClients->size(); i++) {
if (aClients->at(i)->GetIP() == ip&&aClients->at(i)->GetPort() == port) {
return aClients->at(i);
playerSize++;
}
}
std::cout << "JUGADORES PROCESADOS-> " << playerSize << std::endl;
return nullptr;
}
Client* GetClientWithId(int id, std::vector<Client*>aClients) {
for (int i = 0; i < aClients.size(); i++) {
if (aClients[i]->id == id) {
return aClients[i];
}
}
return nullptr;
}
//ServerClient* GetClientWithId(int id, std::vector<ServerClient*>*aClients) {
//
// for (int i = 0; i < aClients->size(); i++) {
// //if (aClients->at(i)->GetID() == id) {
// // return aClients->at(i);
// //}
// }
//}
//Client* GetClientWithId(int id, std::vector<Client*>*aClients) {
//
// for (int i = 0; i < aClients->size(); i++) {
// if (aClients->at(i)->id == id) {
// return aClients->at(i);
// }
// }
//}
int GetIndexServerClientWithId(int id, std::vector<ServerClient*>*aClients) {
for (int i = 0; i < aClients->size(); i++) {
if (aClients->at(i)->id == id) {
return i;
}
}
return -1;
}
int GetIndexClientWithId(int id, std::vector<Client*>*aClients) {
for (int i = 0; i < aClients->size(); i++) {
if (aClients->at(i)->id == id) {
return i;
}
}
return -1;
}
|
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
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.
==============================================================================*/
// Transform pass for LSTMs.
#ifndef TENSORFLOW_COMPILER_MLIR_LITE_TRANSFORMS_PREPARE_QUANTIZE_LSTM
#define TENSORFLOW_COMPILER_MLIR_LITE_TRANSFORMS_PREPARE_QUANTIZE_LSTM
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include "llvm/Support/Casting.h"
#include "llvm/Support/MathExtras.h"
#include "mlir/Dialect/Quant/FakeQuantSupport.h" // from @llvm-project
#include "mlir/Dialect/Quant/QuantOps.h" // from @llvm-project
#include "mlir/Dialect/Quant/QuantTypes.h" // from @llvm-project
#include "mlir/IR/Attributes.h" // from @llvm-project
#include "mlir/IR/PatternMatch.h" // from @llvm-project
#include "mlir/IR/StandardTypes.h" // from @llvm-project
#include "mlir/IR/TypeUtilities.h" // from @llvm-project
#include "mlir/IR/Value.h" // from @llvm-project
#include "mlir/Support/LogicalResult.h" // from @llvm-project
#include "tensorflow/compiler/mlir/lite/ir/tfl_ops.h"
#include "tensorflow/compiler/mlir/lite/quantization/quantization_config.h"
#include "tensorflow/compiler/mlir/lite/quantization/quantization_utils.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "tensorflow/lite/tools/optimize/operator_property.h"
//===----------------------------------------------------------------------===//
// The prepare-quantize Pass for LSTM.
//
namespace mlir {
namespace TFL {
// Calculates the minimum power of two that is not less than the value.
inline double power_of_two_bound(double value) {
return std::pow(2, std::ceil(std::log2(value)));
}
namespace operator_property = ::tflite::optimize::operator_property;
// Quantize recurrent input of LSTM with 16 bits.
template <typename SourceOp, typename Q, typename DQ>
struct ConvertLstmStatsToQDQs : public OpRewritePattern<SourceOp> {
public:
ConvertLstmStatsToQDQs(MLIRContext* context,
const QuantizationSpecs& quant_specs)
: OpRewritePattern<SourceOp>(context, /*benefit=*/2),
quant_specs(quant_specs) {}
LogicalResult matchAndRewrite(SourceOp op,
PatternRewriter& rewriter) const override {
operator_property::OpVariant lstm_variant;
if (llvm::isa<TFL::LSTMOp>(op.getOperation())) {
lstm_variant.op_code = tflite::BuiltinOperator_LSTM;
} else if (llvm::isa<TFL::UnidirectionalSequenceLSTMOp>(
op.getOperation())) {
lstm_variant.op_code =
tflite::BuiltinOperator_UNIDIRECTIONAL_SEQUENCE_LSTM;
} else {
op.emitError("ConvertLstmStatsToQDQs pass only supports LSTMs.");
return failure();
}
lstm_variant.use_projection =
!op.projection_weights().getType().template isa<NoneType>();
lstm_variant.use_peephole =
!op.cell_to_output_weights().getType().template isa<NoneType>();
lstm_variant.use_peephole =
!op.cell_to_output_weights().getType().template isa<NoneType>();
lstm_variant.use_layer_norm =
!op.forget_layer_norm_coefficients().getType().template isa<NoneType>();
auto lstm_property = operator_property::GetOperatorProperty(lstm_variant);
// Same with the ordering of //tensorflow/compiler/mlir/lite/ir/tfl_ops.td
const std::vector<std::string> intermediate_attributes = {
"input_to_input_intermediate", "input_to_forget_intermediate",
"input_to_cell_intermediate", "input_to_output_intermediate",
"effective_hidden_scale_intermediate"};
for (auto& enumerated_intermediates : lstm_property.intermediates) {
int index = enumerated_intermediates.first;
auto& tensor_property = enumerated_intermediates.second;
// intermediate tensors 0, 1, 2, 3 are only used with layer normalization.
if (!lstm_variant.use_layer_norm && index != 4) {
continue;
}
// intermediate tensor 4 is only used with projection.
if (!lstm_variant.use_projection && index == 4) {
continue;
}
TypeAttr attr =
op.template getAttrOfType<TypeAttr>(intermediate_attributes[index]);
if (!attr) {
op.emitError()
<< op.getOperationName()
<< " requires quantization values for intermediate tensor "
<< intermediate_attributes[index];
return failure();
}
auto quantized_type =
QuantizedType::getQuantizedElementType(attr.getValue());
if (!quantized_type) {
op.emitError() << intermediate_attributes[index]
<< " is not quantized.";
return failure();
}
auto calibrated_type =
quantized_type.dyn_cast<quant::CalibratedQuantizedType>();
if (!calibrated_type) {
int num_storage_bits = quantized_type.getStorageTypeIntegralWidth();
if (tensor_property.number_of_bits != num_storage_bits) {
op.emitError() << intermediate_attributes[index]
<< " is expected to be quantized with "
<< tensor_property.number_of_bits << " bits, but got "
<< num_storage_bits << " bits instead.";
return failure();
}
continue; // skip if it is already quantized.
}
quant::UniformQuantizedType qtype;
if (tensor_property.number_of_bits == 8) {
qtype = quant::fakeQuantAttrsToType(
op.getLoc(), tensor_property.number_of_bits,
calibrated_type.getMin(), calibrated_type.getMax(),
/*narrowRange=*/false, calibrated_type.getExpressedType(),
/*isSigned=*/quant_specs.IsSignedInferenceType());
} else if (tensor_property.number_of_bits == 16) {
double max = std::max(std::abs(calibrated_type.getMin()),
std::abs(calibrated_type.getMax()));
qtype = quant::fakeQuantAttrsToType(
op.getLoc(), tensor_property.number_of_bits, -max, max,
/*narrowRange=*/true, calibrated_type.getExpressedType(),
/*isSigned=*/true);
} else {
op.emitError() << "Unsupported quantization bits: "
<< tensor_property.number_of_bits;
return failure();
}
op.setAttr(intermediate_attributes[index],
TypeAttr::get(qtype.castFromExpressedType(
qtype.castToExpressedType(attr.getValue()))));
}
quant::StatisticsOp stats_op = llvm::dyn_cast_or_null<quant::StatisticsOp>(
op.input_cell_state().getDefiningOp());
// Recurrent input is be used within an LSTM, and thus should have one use.
if (!stats_op || !stats_op.getResult().hasOneUse()) {
return failure();
}
auto stats = stats_op.layerStats().dyn_cast<DenseFPElementsAttr>();
if (!stats) {
return failure();
}
double max = std::max(
std::abs(FloatAttr::getValueAsDouble(stats.getValue<APFloat>({0}))),
std::abs(FloatAttr::getValueAsDouble(stats.getValue<APFloat>({1}))));
double bound = power_of_two_bound(max);
Type expressed = stats_op.getType().cast<ShapedType>().getElementType();
// Set flags to 1 for signed type.
quant::QuantizedType quant_type = UniformQuantizedType::getChecked(
quant::QuantizationFlags::Signed,
IntegerType::get(16, expressed.getContext()), expressed,
/*scale=*/bound / 32768.0, /*zeroPoint=*/0, llvm::minIntN(16),
llvm::maxIntN(16), op.getLoc());
rewriter.setInsertionPointAfter(stats_op);
Type result_type = quant_type.castFromExpressedType(stats_op.getType());
auto q = rewriter.create<Q>(stats_op.getLoc(), result_type, stats_op.arg());
rewriter.replaceOpWithNewOp<DQ>(stats_op, stats_op.getType(), q);
return success();
}
private:
QuantizationSpecs quant_specs;
};
} // namespace TFL
} // namespace mlir
#endif // TENSORFLOW_COMPILER_MLIR_LITE_TRANSFORMS_PREPARE_QUANTIZE_LSTM
|
#include <iostream>
#include <list>
#include <forward_list>
#include <string>
#include <vector>
#include <set>
#include <map>
#include "merge.h"
template<typename T>
void print(const T &t) {
for (auto el : t) {
cout << el << " ";
}
cout << endl;
}
template<typename T>
void print(const map<T, T> &t) {
for (auto el : t) {
cout << el.first << ":" << el.second << " ";
}
cout << endl;
}
int main() {
vector<int> v1 = {1, 2, 3};
vector<int> v2 = {3, 4, 5};
vector<int> v = merge<int>(v1, v2);
cout << "Vector: ";
print(v);
//---------------------------------------
set<int> s1 = {1, 2, 3};
set<int> s2 = {3, 4, 5};
set<int> s = merge<int>(s1, s2);
cout << "Set: ";
print(s);
//---------------------------------------
forward_list<int> l1 = {1, 2, 3};
forward_list<int> l2 = {3, 4, 5};
forward_list<int> l = merge<int>(l1, l2);
l.reverse();
cout << "List: ";
print(l);
//---------------------------------------
map<int, int> m1 = {{1,10}, {2,20}, {3,30}};
map<int, int> m2 = {{3,30}, {4,40}, {5,50}};
map<int, int> m = merge<pair<int, int>>(m1, m2);
cout << "Map: ";
print(m);
//---------------------------------------
vector<int> v3 = {1, 2, 3};
set<int> s3 = {3, 4, 5};
list<int> l3 = {5, 6, 7};
vector<int> vs = merge<int>(v3, s3);
vector<int> vsl = merge<int>(vs, l3);
cout << "Vector, Set, List: ";
print(vsl);
}
|
#include "genogram.h"
using namespace gen;
struct gen::node{
// Payload
std::string name;
std::string gender;
time_t birth;
time_t death;
bool visited;
// Structure
edge* edges;
node* prev;
node* next;
};
struct gen::edge{
node* name;
relKind kind;
edge* next;
};
//***************************************************************************** AUXILIARY SECTION
// Find if a node exists in the Genogram and returns the pointer
node* findNode(std::string name, Genogram& g){
Genogram aux=g;
while(aux){
if(aux->name==name){
return aux;
}
aux=aux->next;
}
return emptyGen;
}
// Find if an edge already exists
bool findEdgeNode(edge* edgeNode, edge* edgeToCheck){
while(edgeToCheck){
if(edgeNode->name==edgeToCheck->name)return true;
edgeToCheck=edgeToCheck->next;
}
return false;
}
// Check if the type of relation exists in the edges list (useful for partner existence check)
bool checkRelKindExists(node* nodeToCheck, relKind kind){
edge* edgeNode=nodeToCheck->edges;
while(edgeNode){
if(edgeNode->kind==kind){
return true;
}
edgeNode=edgeNode->next;
}
return false;
}
// Check if a person already has two parents assigned (used by addRel)
bool checkParentAlreadySetted(node* son, std::string genderOfParentToCheck){
edge* edgeNode=son->edges;
while(edgeNode){
if(edgeNode->kind==PARENT){
if(edgeNode->name->gender==genderOfParentToCheck){
return true;
}
}
edgeNode=edgeNode->next;
}
return false;
}
// Create a string from a timestamp
std::string getStringFromTimestamp(time_t date){
tm* parsedTime={0};
char buffer[11]=""; // 11 is hardcoded as I expect date to be (dd/mm/yyyy\0) -> 11 chars
parsedTime = localtime(&date);
strftime(buffer,sizeof(buffer),"%d/%m/%Y",parsedTime);
std::string resultDateAsString(buffer);
return resultDateAsString;
}
// Create a timestamp from a string
time_t getTimestampFromString(std::string date){
tm parsedTime={0};
strptime(date.c_str(),"%d/%m/%Y",&parsedTime);
time_t resultDateAsTimestamp = mktime(&parsedTime);
return resultDateAsTimestamp;
}
// Add edgeNode to a node based on kind and birth date (unique)
void addOrderedByKindAndBirth(node* label, node* dstNode, relKind kind){
edge* newEdgeNode=new edge;
newEdgeNode->name=label;
newEdgeNode->kind=kind;
newEdgeNode->next=nullptr;
if(findEdgeNode(newEdgeNode, dstNode->edges))throw "Figlio/a già esistente! (Metodo errato per aggiunta figlio a coppia)";
if(newEdgeNode->kind!=CHILD||!dstNode->edges){
newEdgeNode->next=dstNode->edges;
dstNode->edges=newEdgeNode;
return;
}
edge* edgeNode=dstNode->edges;
edge* prev=edgeNode;
while(edgeNode){
if(edgeNode->kind==CHILD){
if(edgeNode->name->birth > newEdgeNode->name->birth){
if(prev==edgeNode){
prev=newEdgeNode;
}else{
prev->next=newEdgeNode;
}
newEdgeNode->next=edgeNode;
return;
}
}
prev=edgeNode;
edgeNode=edgeNode->next;
}
prev->next=newEdgeNode;
}
// Add a relation (aux function used for addRelMother, addRelFather, addRelChildToCouple)
void addRel(std::string parentName, std::string sonName, bool areCouple, Genogram& g){
if(parentName==sonName)throw "Il cappio non è ammesso in questo grafo!";
Genogram aux=g;
node* partner=nullptr;
node* parent=nullptr;
node* son=nullptr;
while(aux){
if(aux->name==parentName){
parent=aux;
if(areCouple){
edge* tmp=aux->edges;
while(tmp){
if(tmp->kind==PARTNER){
partner=tmp->name;
}
tmp=tmp->next;
}
}
}else if(aux->name==sonName){
son=aux;
}
aux=aux->next;
}
if(!son||!parent)throw "Una o entrambe queste persone non sono nel Genogramma!";
if(checkParentAlreadySetted(son, parent->gender))throw "La modifica dei genitori non è possibile!";
if(son->birth<parent->birth)throw "Non è possibile inserire un figlio nato prima di un genitore!";
if(!partner&&areCouple)throw "Questa persona non ha un partner associato!";
if(areCouple){
addOrderedByKindAndBirth(son,partner,CHILD);
addOrderedByKindAndBirth(partner,son,PARENT);
}
addOrderedByKindAndBirth(son,parent,CHILD);
addOrderedByKindAndBirth(parent,son,PARENT);
}
void setDate(std::string name, std::string date, bool isBirth, Genogram& g){
node* person=findNode(name,g);
if(!person)throw "Persona non presente nel genogramma!";
time_t actualDate=getTimestampFromString(date);
if(isBirth){
person->birth=actualDate;
return;
}
person->death=actualDate;
}
void subDelRel(node* person, node* nameToDelete){
edge* aux=person->edges;
edge* prev=nullptr;
while(aux->name->name!=nameToDelete->name){
prev=aux;
aux=aux->next;
}
if(!prev){
person->edges=aux->next;
}else{
prev->next=aux->next;
}
delete(aux);
}
void deleteNode(node* nodeToDelete, Genogram& g){
edge* aux=nodeToDelete->edges;
edge* nextNode=aux;
while(aux){
nextNode=aux->next;
if(aux->kind==CHILD){
deleteNode(aux->name,g);
}else{
subDelRel(aux->name,nodeToDelete);
}
aux=nextNode;
}
if(nodeToDelete->next){
nodeToDelete->next->prev=nodeToDelete->prev;
}
if(nodeToDelete->prev){
nodeToDelete->prev->next=nodeToDelete->next;
}else{
g=nodeToDelete->next;
}
delete(nodeToDelete);
}
bool areParentsBiological(Genogram& g){
Genogram aux=g;
node* mother=nullptr;
node* father=nullptr;
int count=0;
while(aux){
edge* edgeNode=aux->edges;
while(edgeNode){
if(edgeNode->kind==PARENT){
count++;
if(edgeNode->name->gender=="M"){
father=edgeNode->name;
}else if(edgeNode->name->gender=="F"){
mother=edgeNode->name;
}
}
edgeNode=edgeNode->next;
}
if(count==2&&(!mother||!father))return false;
count=0;
aux=aux->next;
}
return true;
}
bool descendantsBirthIsCorrect(Genogram& g){
Genogram aux=g;
while(aux){
edge* edgeNode=aux->edges;
while(edgeNode){
if(edgeNode->kind==CHILD&&edgeNode->name->birth<aux->birth)return false;
edgeNode=edgeNode->next;
}
aux=aux->next;
}
return true;
}
void isConnected(Genogram& g){
g->visited=true;
edge* tmp=g->edges;
while(tmp){
g=tmp->name;
if(!g->visited){
isConnected(g);
}
tmp=tmp->next;
}
}
//***************************************************************************** END AUXILIARY SECTION
//***************************************************************************** IMPLEMENTATION SECTION
// Init Genogram
node* gen::createEmptyGen(){
return emptyGen;
}
// Check if Genogram is empty
bool gen::isEmpty(const Genogram& g){
return (g==emptyGen);
}
// Add person to node list
void gen::addPerson(std::string name, std::string gender, std::string birth, std::string death, Genogram& g){
if(findNode(name,g))throw "La persona inserita esiste!";
time_t birthDate = getTimestampFromString(birth);
time_t deathDate = getTimestampFromString(death);
if(deathDate!=-1&&deathDate<birthDate)throw "La data di morte inserita è anteriore alla data di nascita";
node* aux = new node;
aux->name = name;
aux->gender = gender;
aux->birth = birthDate;
aux->death = deathDate;
aux->visited = false;
aux->edges = nullptr;
aux->prev = nullptr;
aux->next = g;
if(!isEmpty(g)){
g->prev=aux;
}
g=aux;
return;
}
// Add mother relation to a child and vice versa
void gen::addRelMother(std::string motherName, std::string sonName, Genogram& g){
addRel(motherName, sonName, false, g);
}
// Add father relation to a child and vice versa
void gen::addRelFather(std::string fatherName, std::string sonName, Genogram& g){
addRel(fatherName, sonName, false, g);
}
// Add child to a couple
void gen::addRelChildToCouple(std::string parentName, std::string sonName, Genogram& g){
addRel(parentName, sonName, true, g);
}
// Add couple relation to two people if they are not already related with anyone
void gen::addRelCouple(std::string name1, std::string name2, Genogram& g){
if(name1==name2)throw "Il cappio non è ammesso in questo grafo!";
Genogram aux=g;
node* firstNode=nullptr;
node* secondNode=nullptr;
while(aux){
if(aux->name==name1){
firstNode=aux;
}else if(aux->name==name2){
secondNode=aux;
}
aux=aux->next;
}
if(!firstNode||!secondNode)throw "Una delle due persone non esiste nel Genogramma!";
if(checkRelKindExists(firstNode,PARTNER)||checkRelKindExists(secondNode,PARTNER)){
throw "Una delle due persone ha già un partner associato!";
}
addOrderedByKindAndBirth(firstNode,secondNode,PARTNER);
addOrderedByKindAndBirth(secondNode,firstNode,PARTNER);
}
// Set Birth of a person
void gen::setBirthDate(std::string name, std::string birth, Genogram& g){
setDate(name, birth, true, g);
}
// Set Death of a person
void gen::setDeathDate(std::string name, std::string death, Genogram& g){
setDate(name, death, false, g);
}
// Delete person from genogram
void gen::deletePerson(std::string name, Genogram& g){
Genogram aux=g;
node* nodeToDelete=findNode(name,aux);
if(!nodeToDelete)throw "Persona non presente nel genogramma!";
deleteNode(nodeToDelete,aux);
g=aux;
}
// Check if Genogram is Valid
bool gen::isValid(Genogram& g){
if(isEmpty(g))throw "Il genogramma è vuoto";
if(!areParentsBiological(g))throw "I genitori biologici non possono essere dello stesso sesso!";
if(!descendantsBirthIsCorrect(g))throw "Qualche discendente è nato prima di qualche suo antenato!";
Genogram aux=g;
isConnected(aux);
Genogram tmp=g;
while(tmp){
if(!tmp->visited)return false;
// Re-init all nodes to false
tmp->visited=false;
tmp=tmp->next;
}
return true;
}
//***************************************************************************** END IMPLEMENTATION SECTION
//***************************************************************************** PRINT AND READ FUNCTIONS
// Read genogram from file
void readGenogramFromFile(std::string fileName, gen::Genogram& g){
std::fstream inputFile;
inputFile.open(fileName, std::ios::in);
std::string fileLine;
std::string arr[5];
std::string check;
while(getline(inputFile,fileLine)){
std::istringstream ss(fileLine);
int i=0;
while(ss >> check){
arr[i]=check;
i++;
}
if(arr[0]=="P"){
gen::addPerson(arr[1],arr[2],arr[3],arr[4],g);
}else if(arr[0]=="R"){
if(arr[2]=="M"){
gen::addRelMother(arr[1],arr[3],g);
}else if(arr[2]=="F"){
gen::addRelFather(arr[1],arr[3],g);
}else{
gen::addRelCouple(arr[1],arr[3],g);
}
}
}
}
// Print elements in graph
void printGenogram(const gen::Genogram& g){
Genogram aux=g;
node* mother=nullptr;
node* father=nullptr;
while(aux){
std::cout << "_____________________________" << std::endl;
std::cout << aux->name << " " << aux->gender << " ";
std::cout << "nato/a: ";
if(aux->birth != -1){
std::cout << getStringFromTimestamp(aux->birth);
}
std::cout << " morto/a: ";
if(aux->death != -1){
std::cout << getStringFromTimestamp(aux->death);
}
std::cout << std::endl;
edge* edgeNode=aux->edges;
while(edgeNode){
if(edgeNode->kind==PARENT){
if(edgeNode->name->gender == "M"){
father=edgeNode->name;
}else{
mother=edgeNode->name;
}
}
edgeNode=edgeNode->next;
}
std::cout << "madre: ";
if(mother){
std::cout << mother->name;
}
std::cout << std::endl;
std::cout << "padre: ";
if(father){
std::cout << father->name;
}
std::cout << std::endl;
std::cout << "in coppia con: ";
edge* tmp=aux->edges;
while(tmp){
if(tmp->kind==PARTNER){
std::cout << tmp->name->name;
}
tmp=tmp->next;
}
std::cout << std::endl;
std::cout << "figli: ";
edge* child=aux->edges;
while(child){
if(child->kind==CHILD){
std::cout << child->name->name << " ";
}
child=child->next;
}
std::cout << std::endl;
father=nullptr;
mother=nullptr;
aux=aux->next;
}
return;
}
//***************************************************************************** END PRINT AND READ FUNCTIONS
|
#include "server_t.h"
server_t* listening_server;
int main(int argc, char** argv)
{
if(argc < 2)
{
std::cout << "usage: " << argv[0] << " <port number> \n";
return 0;
}
int port_selection;
errno = 0;
port_selection = (int)strtol(argv[1],NULL,10);
if(errno)
{
std::cout << "errno set to " << errno << " \n";
return 0;
}
listening_server = new server_t(port_selection);
if(!listening_server->errors())
{
listening_server->main_loop();
}
else
{
std::cout << "errors occured \n";
}
}
|
#ifndef TENSOR_H
#define TENSOR_H
#include "cnn.hpp"
class Batch
{
public:
Batch();
Batch(const int& nums,
const int& rows,
const int& cols,
const int& channels)
{
nums_ = nums;
channels_ = channels;
rows_ = rows;
cols_ = cols;
size_ = nums *
channels *
rows *
cols;
value_ = new real_t[size_];
memset(value_,0,sizeof(real_t) * size_);
gradient_ = new real_t[size_];
memset(gradient_,0,sizeof(real_t) * size_);
}
void Init(const int& nums,
const int& rows,
const int& cols,
const int& channels)
{
size_ = nums *
channels *
rows *
cols;
value_ = new real_t[size_];
memset(value_,0,sizeof(real_t) * size_);
gradient_ = new real_t[size_];
memset(gradient_,0,sizeof(real_t) * size_);
}
virtual ~Batch()
{
if(value_)
delete[] value_;
if(gradient_)
delete[] gradient_;
}
//getters of dimensions
int get_nums() const
{
return nums_;
}
int get_rows() const
{
return rows_;
}
int get_cols() const
{
return cols_;
}
int get_channels() const
{
return channels_;
}
int get_size() const
{
return size_;
}
//setters of value and gradient
real_t* value() const
{
return value_;
}
real_t* gradient() const
{
return gradient_;
}
//setters of dimensions
void set_value(real_t* value)
{
value_ = value;
}
void set_nums(const int& nums)
{
nums_ = nums;
}
void set_channels(const int& channels)
{
channels_ = channels;
}
void set_rows(const int& rows)
{
rows_ = rows;
}
void set_cols(const int& cols)
{
cols_ = cols;
}
void set_dimensions(const int& nums,
const int& rows,
const int& cols,
const int& channels)
{
nums_ = nums;
rows_ = rows;
cols_ = cols;
channels_ = channels;
}
//get the address of value or gradient buuffer of certain offset
real_t* data_ptr(int num,
int col,
int row,
int channel)
{
return (value_ +
num * cols_ * rows_ * channels_ +
col * rows_ * channels_ +
row * channels_ +
channel);
}
real_t* data_ptr(int idx)
{
return (value_ + idx);
}
real_t* grad_ptr(int num,
int col,
int row,
int channel)
{
return (gradient_ +
num * cols_ * rows_ * channels_ +
col * rows_ * channels_ +
row * channels_ +
channel);
}
real_t* grad_ptr(int idx)
{
return (gradient_ + idx);
}
private:
int nums_;
int channels_;
int rows_;
int cols_;
int size_;
real_t* value_;
real_t* gradient_;
};
#endif // TENSOR_H
|
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a, num, sum=0, sum1=0;
int r;
int n;
cout << "Enter a number" << endl;
cin >> n;
num = n;
while(num>0)
{
a=num%10;
if(a!=0)
{
sum = sum *10 + a;
}
num=num/10;
}
while (sum>0)
{
r=sum%10;
sum1 = sum1 * 10+r;
sum=sum/10;
}
cout << sum1;
}
|
#include "Game.h"
void Game::StartGame()
{
while (true) {
printf("*****生命游戏*****\n\n");
printf("1.开始演变\n\n");
printf("2.设置模式\n\n");
printf("3.设置速度\n\n");
printf("4.游戏介绍\n\n");
printf("5.退出游戏\n\n");
printf(">>");
int choose = 0;
cin >> choose;
switch (choose)
{
case 1:
StartEvolution();
break;
case 2:
SetPatternMode();
break;
case 3:
SetEvolutionSpeed();
break;
case 4:
IntroduceGame();
break;
case 5:
return;
default:
break;
}
system("cls");
}
}
void Game::StartEvolution() {
Evolution evolution(initPattern.getPattern(patternMode));
vector<vector<bool>> pattern = evolution.pattern;
Draw draw(MapLength);
bool IfStable = false;
while (true) {
if (!IfStable) {
draw.DrawPattern(pattern);
pattern = evolution.getEvolutionResult(IfStable);
if (pattern.size() > MapLength) return;
}
Sleep(evolutionSpeed);
while (_kbhit()) {
char hitChar = _getch();
if (hitChar == 13) return;
switch (hitChar) {
case 'a':
evolutionSpeed += 100;
if (evolutionSpeed > 500) evolutionSpeed = 500;
break;
case 'd':
if (evolutionSpeed > 100)evolutionSpeed -= 100;
break;
default:
break;
}
cout <<hitChar<<","<< evolutionSpeed << endl;
}
}
}
void Game::SetPatternMode() {
system("cls");
cout << "以下是初始\"细胞自动机\"选项:\n" << endl;
const vector<string> patternNames = initPattern.patternNames;
for (int i = 0; i < (int)patternNames.size(); ++i) {
cout << i + 1 << "." << patternNames[i].c_str() <<"\n"<< endl;
}
cout << to_string(patternNames.size() + 1)<<".自定义模式\n\n";
cout << "选择:";
int selectedMode = 0;
cin>> selectedMode;
if (selectedMode > 0 && selectedMode <= (int)patternNames.size()) {
patternMode = selectedMode;
}
else if(selectedMode == patternNames.size() + 1){
patternMode = selectedMode;
initPattern.setCustomPattern(CustomPattern());
}
}
vector<vector<bool>> Game::CustomPattern() {
system("cls");
cout << "输入矩阵长度(小于" << MapLength << ");";
int inputSize;
cin >> inputSize;
if (inputSize < 3) inputSize = 3;
if (inputSize > MapLength) inputSize = MapLength;
vector<vector<bool> > pattern(inputSize, vector<bool>(inputSize, false));
while (true) {
cout << "请输入坐标X" << endl;
int x, y;
cin >> x;
cout << "请输入坐标Y" << endl;
cin >> y;
if(!(x<0||y<0||x>=inputSize||y>=inputSize)) pattern[x][y] = true;
cout << "按任意键继续输入, q键结束输入" << endl;
while (!_kbhit()) {};
char inputChar = _getch();
if (inputChar == 'q') {
cout << "\n";
break;
}
}
return pattern;
}
void Game::SetEvolutionSpeed() {
system("cls");
cout << "设置细胞演化的周期(单位:毫秒):" ;
int getTime = 500;
cin >> getTime;
if (getTime <= 0) getTime = 10;
evolutionSpeed = getTime;
}
void Game::IntroduceGame() {
system("cls");
printf("生命游戏是John Conway 发现的一种游戏,游戏深受世界编程人士的喜爱。\n\n");
printf("游戏规则如下:\n\n");
printf("1.如果一个细胞周围有3个细胞为生(一个细胞周围共有8个细胞),则该细胞为生;\n\n");
printf("2.如果一个细胞周围有2个细胞为生,则该细胞的生死状态保持不变;\n\n");
printf("3.在其它情况下,该细胞为死。\n\n");
printf("软件版本:1.01半UI版\n\n");
printf("软件作者:俞世超,刘金宗\n\n");
printf("按回车退出\n");
while (true) {
if (_kbhit()) {
char hitChar = _getch();
if (hitChar == 13) break;
}
}
}
void Game::PrintPattern(vector<vector<bool>> &pattern) {
system("cls");
for (int i = 0; i < (int)pattern.size(); ++i) {
for (int j = 0; j < (int)pattern.size(); ++j) {
if (pattern[i][j]) printf("国");
else printf("..");
}
cout << "\n";
}
cout << "\n";
cout << "\n按回车键回到主界面" << endl;
}
|
/*
* PathPlanner.cpp
*
* Created on: Jun 12, 2015
* Author: colman
*/
#include "PathPlanner.h"
#include "robot.h"
#include "Behavior.h"
#include "wayPoint.h"
#include "Position.h"
Area* world;
std::vector<ANode*> OpenList;
std::vector<ANode*> CloseList;
ANode* first;
ANode* target;
Behavior** PathPlanner::getBhvLst()
{
return _bhvlst;
}
void PathPlanner::initBehavior(Robot* robot)
{
// Creating behaviors
_bhvlst = new Behavior*[4];
_bhvlst[0] = new GoForward(robot);
_bhvlst[1] = new TurnRight(robot);
_bhvlst[2] = new TurnLeft(robot);
_bhvlst[3] = new TurnInPlace(robot);
// Connecting behaviors
_bhvlst[0]->addNext(_bhvlst[1]);
_bhvlst[0]->addNext(_bhvlst[2]);
_bhvlst[0]->addNext(_bhvlst[3]);
_bhvlst[1]->addNext(_bhvlst[0]);
_bhvlst[1]->addNext(_bhvlst[2]);
_bhvlst[1]->addNext(_bhvlst[3]);
_bhvlst[2]->addNext(_bhvlst[0]);
_bhvlst[2]->addNext(_bhvlst[1]);
_bhvlst[2]->addNext(_bhvlst[3]);
_bhvlst[3]->addNext(_bhvlst[0]);
_bhvlst[3]->addNext(_bhvlst[1]);
_bhvlst[3]->addNext(_bhvlst[2]);
// Init the start behavior
_starBeh = _bhvlst[0];
}
void PathPlanner::InitPathPlanner(int xStart, int yStart, int xTarget, int yTarget,int gridHeight, int gridWidth, std::vector<vector<int> > worldVector)
{
world = new Area(gridHeight, gridWidth,worldVector);
world->setFirst(xStart, yStart);
world->setGoal(xTarget, yTarget);
first = new ANode(xStart, yStart, First);
target = new ANode(xTarget, yTarget, Goal);
// for check
/*
vector<vector<int> > worldVector1;
worldVector1.resize(7);
for (int i = 0; i< 7; i++)
{
worldVector1[i].resize(6);
for(int j = 0; j < 6; j++)
{
worldVector1[i][j] = 0;
}
}
worldVector1[2][3] = 1;
worldVector1[4][1] = 1;
worldVector1[4][3] = 1;
worldVector1[5][3] = 1;
worldVector1[3][1] = 1;
int xStart1 = 1;
int yStart1 = 2;
int xTarget1 = 4;
int yTarget1= 6;
world = new Area(gridHeight,gridWidth ,worldVector1);
first = new ANode(xStart1, yStart1, First);
target = new ANode(xTarget1, yTarget1, Goal);
world->setFirst(xStart1, yStart1);
world->setGoal(xTarget1, yTarget1);*/
CalcMovementCost();
}
/*
* checking whether a relationship between variables is diagonally(14) or straight(10)
*/
int getDistanceBetween(ANode n1, ANode n2)
{
if ((n1.x == n2.x) || (n1.y == n2.y))
return STRAIGHT;
else
return DIAGONAL;
}
/*
* Calculate heuristic value
*/
int getEstimatedDistanceToGoal(ANode start, ANode finish)
{
return (abs(start.x - finish.x) + abs(start.y - finish.y));
}
PositionState OldPositionState = none;
PositionState GetNodeState(ANode node)
{
PositionState currentPosition;
if (node.x == node.parent->x && node.y - node.parent->y == 1)
currentPosition = Up;
else if (node.x == node.parent->x && node.y - node.parent->y == -1)
{
currentPosition = Down;
}
else if (node.x - node.parent->x == 1 && node.y == node.parent->y)
{
currentPosition = Left;
}
else if (node.x - node.parent->x == -1 && node.y == node.parent->y )
{
currentPosition = Right;
}
else if (node.x - node.parent->x == -1 && node.y - node.parent->y ==1)
{
currentPosition = UpRight;
}
else if (node.x - node.parent->x == 1 && node.y - node.parent->y == 1)
{
currentPosition = UpLeft;
}
else if (node.x - node.parent->x ==1 && node.y - node.parent->y == -1)
{
currentPosition = DownLeft;
}
else if (node.x - node.parent->x == -1 && node.y - node.parent->y == -1)
{
currentPosition = DownRight;
}
return currentPosition;
}
PositionState ChangeState(PositionState* _state)
{
if ((*_state) == Up)
{
return Down;
}
else if ((*_state) == Down)
{
return Up;
}
else if ((*_state) == Left)
{
return Right;
}
else if ((*_state) == Right)
{
return Left;
}
else if ((*_state) == UpRight)
{
return DownLeft;
}
else if ((*_state) == UpLeft)
{
return DownRight;
}
else if ((*_state) == DownRight)
{
return UpLeft;
}
else if ((*_state) == DownLeft)
{
return UpRight;
}
return none;
}
void ChangeNodeState(vector<wayPoint*> PathResult, int size)
{
PositionState first = *PathResult[0]->_state;
for (int i = 0; i< size -1;i++)
{
*(PathResult[i]->_state) = ChangeState(PathResult[i + 1]->_state);
}
*(PathResult[(int)PathResult.size() - 1]->_state )= first;
}
void PathPlanner::TraceBack(ANode* node)
{
wayPoint* ps;
PositionState currentPosition;
ps = new wayPoint();
ps->_position = new Position();
ps->_position->_x = node->x;
ps->_position->_y = node->y;
ps->_state = new PositionState();
OldPositionState = GetNodeState(*node);
*(ps->_state) = OldPositionState;
wayPoints.push_back(ps);
node = (node->parent);
while (!(node->parent == NULL))
{
ps = new wayPoint();
ps->_position = new Position();
ps->_position->_x = node->x;
ps->_position->_y = node->y;
currentPosition = GetNodeState(*node);
ps->_state = new PositionState();
*(ps->_state) = currentPosition;
if (OldPositionState != currentPosition)
{
wayPoints.push_back(ps);
}
OldPositionState = currentPosition;
node = (node->parent);
}
ps = new wayPoint();
ps->_position = new Position();
ps->_state = new PositionState();
ps->_position->_x = node->x;
ps->_position->_y = node->y;
*(ps->_state) = none;
wayPoints.push_back(ps);
std::reverse(wayPoints.begin(), wayPoints.end());
ChangeNodeState(wayPoints, wayPoints.size());
}
/*
* this struct is for sort function
*/
struct sortStruct
{
bool operator() (ANode* first,ANode* second) { return ((first->gValue + first->hValue) < (second->gValue + second->hValue));}
} myobject;
/*
* get vector and node and check if the node exist in the vector
*/
bool IsExist(vector<ANode*> data, ANode value)
{
for (int index = 0; index<data.size();index++)
{
if (data[index]->equals(value))
return true;
}
return false;
}
/*
* openlist: node that we still don't check his neighbors
* closelist : node that we insert all(?) his neighbors to openlist
*/
void PathPlanner::CalcMovementCost()
{
int newCost;
ANode* current;
ANode* currentNeighbor;
OpenList.clear();
CloseList.clear();
OpenList.push_back(first);
while ((int)OpenList.size() != 0)
{
current = OpenList[0]; // get the value with min f value(g+h)
// check if the current node is the target - finish algo
if (current->equals(*target))
break;
// remove the current node from openlist
OpenList.erase(OpenList.begin());
// push the current node to close list
CloseList.push_back(current);
vector<ANode> currentNeighbors = world->getNeighborsList(*current);
newCost = 0;
bool isBetter = false;
for(int i = 0; i < (int)currentNeighbors.size(); i++)
{
int neighborX = currentNeighbors[i].x;
int neighborY = currentNeighbors[i].y;
isBetter = false;
currentNeighbor = world->GetPNode(neighborX, neighborY);
if (IsExist(CloseList, *currentNeighbor))
continue;
if (!currentNeighbor->IsNodeObstacle())
{
newCost = current->gValue + getDistanceBetween(*current, currentNeighbors[i]);
// check if current is in open list
// TODO think double code
if (!IsExist(OpenList, currentNeighbors[i]))
{
OpenList.push_back(currentNeighbor);
world->map[neighborY][neighborX]->parent = current;
world->map[neighborY][neighborX]->gValue = newCost;
world->map[neighborY][neighborX]->hValue =getEstimatedDistanceToGoal(*currentNeighbor, *target);
std::sort(OpenList.begin(), OpenList.end(), myobject);
}
else if (newCost < current->gValue)
{
world->map[neighborY][neighborX]->parent = current;
world->map[neighborY][neighborX]->gValue = newCost;
world->map[neighborY][neighborX]->hValue =getEstimatedDistanceToGoal(*currentNeighbor, *target);
}
}
}
}
if (!ANode::IsNull(current))
TraceBack(current);
}
void PathPlanner::CalculateMovement()
{}
|
#include "stdafx.h"
#include "AssimpImporter.h"
#include "Common/Helpers.h"
#include "../D3DBase.h"
#include "../IScene.h"
#include "../TextureManager.h"
#include "../VertexTypes.h"
#include "../ImmutableMeshGeometry.h"
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
using namespace Common;
using namespace DirectX;
using namespace GraphicsEngine;
void AssimpImporter::Import(Graphics* graphics, const D3DBase& d3dBase, TextureManager& textureManager, IScene* scene, const std::wstring& filename, AssimpImporter::ImportInfo& importInfo)
{
using namespace Assimp;
// Create importer:
Importer importer;
// Import scene from file:
auto flags =
aiProcess_CalcTangentSpace |
aiProcess_Triangulate |
aiProcess_GenSmoothNormals |
aiProcess_SplitLargeMeshes |
aiProcess_ConvertToLeftHanded |
aiProcess_SortByPType;
auto importedScene = importer.ReadFile(Helpers::WStringToString(filename), flags);
// Check if the report failed:
if (!importedScene)
{
auto errorMessage = L"Error while importing file: " + Helpers::StringToWString(importer.GetErrorString());
ThrowEngineException(errorMessage.c_str());
}
return ConvertToMeshData(graphics, d3dBase, textureManager, scene, filename, importedScene, importInfo);
}
std::string AssimpImporter::BuildMeshName(const std::wstring& filename, const std::string& meshName)
{
return Helpers::WStringToString(filename) + "/Mesh:" + meshName;
}
void AssimpImporter::ConvertToMeshData(Graphics* graphics, const D3DBase& d3dBase, TextureManager& textureManager, IScene* scene, const std::wstring& filename, const aiScene* importedScene, AssimpImporter::ImportInfo& importInfo)
{
auto name = Helpers::WStringToString(filename);
AddGeometry(d3dBase, name, scene, filename, importedScene, importInfo);
AddMaterials(d3dBase, textureManager, scene, importedScene);
}
void AssimpImporter::AddGeometry(const D3DBase& d3dBase, const std::string& name, IScene* scene, const std::wstring& filename, const aiScene* importedScene, AssimpImporter::ImportInfo& importInfo)
{
auto geometry = std::make_unique<ImmutableMeshGeometry>();
geometry->SetName(name);
// Count vertices and indices:
m_vertexCount = 0;
m_indexCount = 0;
for (unsigned int meshIndex = 0; meshIndex < importedScene->mNumMeshes; ++meshIndex)
{
auto mesh = importedScene->mMeshes[meshIndex];
m_vertexCount += mesh->mNumVertices;
m_indexCount += mesh->mNumFaces * 3;
}
// Create vertices and indices vectors:
std::vector<VertexTypes::DefaultVertexType> vertices;
vertices.reserve(m_vertexCount);
std::vector<uint32_t> indices;
indices.reserve(m_indexCount);
uint32_t baseVertexLocation = 0;
uint32_t startIndexLocation = 0;
for (unsigned int meshIndex = 0; meshIndex < importedScene->mNumMeshes; ++meshIndex)
{
auto mesh = importedScene->mMeshes[meshIndex];
// Add vertices:
{
for (unsigned int i = 0; i < mesh->mNumVertices; ++i)
{
VertexTypes::DefaultVertexType vertex;
const auto& vertexPosition = mesh->mVertices[i];
vertex.Position = XMFLOAT3(vertexPosition.x, vertexPosition.y, vertexPosition.z);
const auto& normals = mesh->mNormals[i];
vertex.Normal = XMFLOAT3(normals.x, normals.y, normals.z);
if (mesh->mTextureCoords[0] == nullptr)
{
//OutputDebugString(std::wstring(L"Model " + Helpers::StringToWString(name) + L" loaded with no textures").c_str());
}
else
{
const auto& textureCoordinates = mesh->mTextureCoords[0][i];
vertex.TextureCoordinates = XMFLOAT2(textureCoordinates.x, textureCoordinates.y);
const auto& tangentU = mesh->mTangents[i];
vertex.Tangent = XMFLOAT3(tangentU.x, tangentU.y, tangentU.z);
}
vertices.push_back(vertex);
}
}
// Add indices:
{
for (unsigned int i = 0; i < mesh->mNumFaces; ++i)
{
const auto& face = mesh->mFaces[i];
indices.push_back(face.mIndices[0]);
indices.push_back(face.mIndices[1]);
indices.push_back(face.mIndices[2]);
}
}
// Create submesh:
SubmeshGeometry submesh;
submesh.IndexCount = static_cast<UINT>(indices.size()) - startIndexLocation;
submesh.StartIndexLocation = startIndexLocation;
submesh.BaseVertexLocation = baseVertexLocation;
submesh.Bounds = MeshGeometry::CreateBoundingBoxFromMesh(vertices);
geometry->AddSubmesh(mesh->mName.C_Str(), std::move(submesh));
// Assign material to mesh:
aiString materialName;
importedScene->mMaterials[mesh->mMaterialIndex]->Get(AI_MATKEY_NAME, materialName);
importInfo.MaterialByMesh.emplace(BuildMeshName(filename, mesh->mName.C_Str()), materialName.C_Str());
// Increment location variables:
baseVertexLocation += mesh->mNumVertices;
startIndexLocation += mesh->mNumFaces * 3;
}
// Create vertex and index buffer:
auto device = d3dBase.GetDevice();
geometry->CreateVertexBuffer(device, vertices, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
geometry->CreateIndexBuffer(device, indices, DXGI_FORMAT_R32_UINT);
scene->AddImmutableGeometry(std::move(geometry));
}
void AssimpImporter::AddMaterials(const D3DBase& d3dBase, TextureManager& textureManager, IScene* scene, const aiScene* importedScene)
{
for (unsigned int i = 0; i < importedScene->mNumMaterials; ++i)
{
auto importedMaterial = importedScene->mMaterials[i];
auto renderMaterial = std::make_unique<Material>();
// Set name:
aiString name;
importedMaterial->Get(AI_MATKEY_NAME, name);
renderMaterial->Name = name.C_Str();
// Set diffuse map:
aiString texturePath;
importedMaterial->GetTexture(aiTextureType_DIFFUSE, 0, &texturePath);
/*if(texturePath.length != 0)
{
auto texturePathStr = "Models/" + std::string(texturePath.C_Str());
textureManager.Create(d3dBase.GetDevice(), texturePathStr, Helpers::StringToWString(texturePathStr));
renderMaterial->DiffuseMap = &textureManager[texturePathStr];
}*/
// Set diffuse albedo:
aiColor4D diffuseColor;
importedMaterial->Get(AI_MATKEY_COLOR_DIFFUSE, diffuseColor);
renderMaterial->DiffuseAlbedo = XMFLOAT4(diffuseColor.r, diffuseColor.g, diffuseColor.b, diffuseColor.a);
// Set fresnel factor:
float reflectivity;
if (importedMaterial->Get(AI_MATKEY_REFLECTIVITY, reflectivity) == aiReturn_FAILURE)
reflectivity = 0.2f;
renderMaterial->FresnelR0 = XMFLOAT3(reflectivity, reflectivity, reflectivity);
// Set roughness:
float shininess;
importedMaterial->Get(AI_MATKEY_SHININESS, shininess);
renderMaterial->Roughness = 1.0f - (shininess / 256.0f);
// Set material transform:
renderMaterial->MaterialTransform = MathHelper::Identity4x4();
// Add material to the scene:
scene->AddMaterial(std::move(renderMaterial));
}
}
|
//
// OSUtil.h
// SMFrameWork
//
// Created by SteveMac on 2018. 6. 20..
//
#ifndef OSUtil_h
#define OSUtil_h
#include <cocos2d.h>
#include <string>
class OSUtil {
public:
static std::string getAppDisplayName();
static std::string getAppVersionName();
static std::string getAppBuildVersion();
// -1 : app newest, 0 : latest version, 1: need update
static int compareVersion(const std::string& targetVersion);
static std::string getCountryCode();
static std::string getLanguageCode();
static const std::string& getPlatform();
static bool openAppMarket();
static bool openURL(const std::string& url);
static bool openDeviceSettings();
static void setTintColor(const cocos2d::Color4F& tintColor);
static std::vector<std::string> getSystemFontList();
static bool isScreenShortRatio();
bool isPushNotificationEnabled();
static void showShareView(const std::string& imageUrl, const std::string& text);
// permision for asset
static bool canAcceessibleFile();
static bool canAcceessibleCamera();
static bool canAcceessibleGPS();
static bool canAcceessiblePhoneCall();
static bool canAcceessibleContact();
static void askAccessPermissionFile(const std::function<void(bool)>& completeBlock);
static void askAccessPermissionCamera(const std::function<void(bool)>& completeBlock);
static void askAccessPermissionGPS(const std::function<void(bool)>& completeBlock);
static void askAccessPermissionPhoneCall(const std::function<void(bool)>& completeBlock);
static void askAccessPermissionContact(const std::function<void(bool)>& completeBlock);
static void getLocationInfo(const std::function<void(float, float, std::string)>& completeBlock, bool bWithAddress=true);
// for android
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
static void getLL();
#endif
public:
OSUtil() : _locationOnceFlag(false), _address(""), _latitude(0), _longitude(0) {
};
virtual ~OSUtil(){};
static OSUtil * getInstance() {
static OSUtil * instance = nullptr;
if (instance==nullptr) {
instance = new OSUtil();
}
return instance;
}
bool getLocationOnceFlag() {return _locationOnceFlag;}
void setLocationOnceFlag(bool bFlag) {_locationOnceFlag=bFlag;}
std::string getTargetName();
std::string getBundleID();
std::string getAddress() {return _address;}
float getLatitude() {return _latitude;}
float getLongitude() {return _longitude;}
private:
bool _locationOnceFlag;
std::mutex _mutex;
std::condition_variable _cond;
bool _pushEnable;
std::string _address;
float _latitude;
float _longitude;
};
#endif /* OSUtil_h */
|
#ifndef PERSON_H
#define PERSON_H
#include <string>
class Person{
public:
Person(string fn, string ln, int ag);
~Person();
private:
string FName;
string LName;
int age;
};
#endif // PERSON_H
|
#include <iostream>
#include <string.h>
using namespace std;
struct nod{
char info;
nod* next;
}*prim,*ultim;
void push(){
if(ultim==NULL)
{
nod *p = new nod;
p->info='(';
p->next=NULL;
prim=ultim=p;
}
else
{
nod *p = new nod;
p->info='(';
p->next=prim;
prim=p;
}
}
int pop()
{
nod *p = prim;
if(prim==NULL)
return -1;
else if(prim==ultim)
{
prim=ultim=NULL;
}
else
{
p=p->next;
delete(prim);
prim=p;
}
}
void afisare()
{
nod *p = prim;
cout<<"-varf- ";
while(p!=NULL)
{
cout<<p->info<<" ";
p=p->next;
}
cout<<" -baza-"<<endl<<endl;
}
int main()
{
int l,i;
char x[20];
cin>>x;
l=strlen(x);
for(i=0;i<l;i++)
if(x[i]=='(')
push();
else if(x[i]==')')
if(pop()==-1)
{
cout<<"incorect";
break;
}
if(i==l)afisare();
}
|
#include <iostream>
using namespace std;
char l[15];
int lcs_length(char *a, char *b){
int m =3, n = 5; //toy(3) story(5)
for(int i = m; i >= 0; i--){
for(int j = n; j >= 0; j--){
if(a[i] == '\0' || b[j] == '\0') l[i,j] = 0;
else if(a[i] == b[j]) l[i,j] = 1 + l[i+1,j+1];
else l[i,j] = max(l[i+1,j],l[i,j+1]);
}
}
return l[0,0];
}
int main(){
char a[] = "toy", b[]="story";
cout << "The longest common subsequence is " << lcs_length(a,b) << endl;
return 0;
}
|
/***************************************************************************
Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
2010-2020 DADI ORISTAR TECHNOLOGY DEVELOPMENT(BEIJING)CO.,LTD
FileName: QTAccessFile.h
Description: This object contains an interface for finding and parsing qtaccess files.
Comment: copy from Darwin Streaming Server 5.5.5
Author: taoyunxing@dadimedia.com
Version: v1.0.0.1
CreateDate: 2010-08-16
LastUpdate: 2010-08-16
****************************************************************************/
#ifndef _QT_ACCESS_FILE_H_
#define _QT_ACCESS_FILE_H_
#include <stdlib.h>
#include "SafeStdLib.h"
#include "StrPtrLen.h"
#include "OSHeaders.h"
#include "OSMutex.h"
#include "QTSS.h"
class OSMutex;
class QTAccessFile
{
public:
/* mask of whitespace (include \t,\n,\r,' ') and '>' */
static UInt8 sWhitespaceAndGreaterThanMask[];
static void Initialize();
static char * GetUserNameCopy(QTSS_UserProfileObject inUserProfile);
//GetGroupsArrayCopy
//
// GetGroupsArrayCopy allocates outGroupCharPtrArray. Caller must "delete [] outGroupCharPtrArray" when done.
static char* GetAccessFile_Copy( const char* movieRootDir, const char* dirPath);
//AccessAllowed
//
// This routine is used to get the Realm to send back to a user and to check if a user has access
// userName: may be null.
// accessFileBufPtr:If accessFileBufPtr is NULL or contains a NULL PTR or 0 LEN then false is returned
// ioRealmNameStr: ioRealmNameStr and ioRealmNameStr->Ptr may be null.
// To get a returned ioRealmNameStr value the ioRealmNameStr and ioRealmNameStr->Ptr must be non-NULL
// valid pointers. The ioRealmNameStr.Len should be set to the ioRealmNameStr->Ptr's allocated len.
// numGroups: The number of groups in the groupArray. Use GetGroupsArrayCopy to create the groupArray.
static Bool16 AccessAllowed ( char *userName, char**groupArray, UInt32 numGroups,
StrPtrLen *accessFileBufPtr,QTSS_ActionFlags inFlags,StrPtrLen* ioRealmNameStr
);
static void SetAccessFileName(const char *inQTAccessFileName); //makes a copy and stores it
static char* GetAccessFileName() { return sQTAccessFileName; }; // a reference. Don't delete!
// allocates memory for outUsersFilePath and outGroupsFilePath - remember to delete
// returns the auth scheme
static QTSS_AuthScheme FindUsersAndGroupsFilesAndAuthScheme(char* inAccessFilePath, QTSS_ActionFlags inAction, char** outUsersFilePath, char** outGroupsFilePath);
static QTSS_Error AuthorizeRequest(QTSS_StandardRTSP_Params* inParams, Bool16 allowNoAccessFiles, QTSS_ActionFlags noAction, QTSS_ActionFlags authorizeAction);
private:
/* file name to access */
static char* sQTAccessFileName; // managed by the QTAccess module
static Bool16 sAllocatedName;
static OSMutex* sAccessFileMutex;
};
#endif //_QT_ACCESS_FILE_H_
|
//
// Myplane.cpp
// Fighters
//
// Created by zhutun on 15/5/25.
// Copyright (c) 2015年 zhutun. All rights reserved.
//
#include "Myplane.h"
#include "GTexture.h"
#include <SFML/System.hpp>
#include "Bullet.h"
Myplane::Myplane(Sky* mySky):Plane(mySky)
{
this->setTexture(this->texture);
this->setPosition(450,1450);
}
Myplane::~Myplane()
{
}
void Myplane::fire(){
static int i=0;
if(i>this->fireDensity){
this->FIRE.play();
Bullet *bulletL=new Bullet();
Bullet *bulletR=new Bullet();
bulletL->setSpeed(this->BulletSpeed+upspeed);
bulletR->setSpeed(this->BulletSpeed+upspeed);
bulletL->setPosition(this->getPosition().x+10,this->getPosition().y);
bulletR->setPosition(this->getPosition().x+80,this->getPosition().y);
this->mySky->addBullet(bulletL,1);
this->mySky->addBullet(bulletR,1);
i=0;
}else{
i++;
}
}
void Myplane::attack(int upspeed) {
this->upspeed=upspeed;
this->fireDensity-=upspeed;
}
void Myplane::setfireDensity(int de){
this->fireDensity=de;
}
void Myplane::addScore(int score)
{
this->score+=score;
}
int Myplane::getScore()
{
return score;
}
void Myplane::clearScore()
{
this->score=0;
}
int Myplane::getlife(){
return this->life;
}
void Myplane::addlife(){
this->life++;
}
bool Myplane::dead(){
this->BOOM.play();
life--;
this->state=1;
return life==0;
}
void Myplane::myplanestate()
{
sf::Sprite boomImg;
switch (this->state) {
case 0:
break;
case 1:
this->BOOM.play();
state++;
// break;
case 2:
boomImg.setTexture(GTexture::MYPLANE_BOOM1);
boomImg.setPosition(this->getPosition().x, this->getPosition().y);
//this->mySky->window->clear();
this->mySky->window->draw(boomImg);
this->mySky->window->display();
state++;
// break;
case 3:
boomImg.setTexture(GTexture::MYPLANE_BOOM2);
boomImg.setPosition(this->getPosition().x, this->getPosition().y);
//this->mySky->window->clear();
this->mySky->window->draw(boomImg);
this->mySky->window->display();
state++;
// break;
case 4:
boomImg.setTexture(GTexture::MYPLANE_BOOM3);
boomImg.setPosition(this->getPosition().x, this->getPosition().y);
//this->mySky->window->clear();
this->mySky->window->draw(boomImg);
this->mySky->window->display();
state++;
// break;
case 5:
boomImg.setTexture(GTexture::MYPLANE_BOOM4);
boomImg.setPosition(this->getPosition().x, this->getPosition().y);
//this->mySky->window->clear();
this->mySky->window->draw(boomImg);
this->mySky->window->display();
break;
}
}
void Myplane::setshield(bool shield){
this->shield=shield;
}
void Myplane::gameagain(){
this->score=0;
this->life=3;
this->setPosition(450, 1450);
this->setSpeed(10);
}
|
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main() {
string str1 = "i.like.this.program.very.much";
string::size_type pos = str1.find_first_of(".");
while(pos!=string::npos) {
str1[pos]=' ';
pos = str1.find_first_of(".",pos+1);
}
int count=0;
cout<<str1<<endl;
stringstream ss;
stack<string> str2;
ss<<str1;
string temp;
str1="";
while(!ss.eof()){
ss>>temp;
str2.push(temp);
}
string str3;
while(!str2.empty()) {
str3 = str3 + str2.top()+".";
// cout<<str2.top()<<endl;
str2.pop();
}
str3.pop_back();
cout<<str3;
}
|
// MFCApplication1Dlg.cpp: archivo de implementación
//
#include "pch.h"
#include "framework.h"
#include "MFCApplication1.h"
#include "MFCApplication1Dlg.h"
#include "afxdialogex.h"
#include "iostream"
#include "string"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// Cuadro de diálogo CAboutDlg utilizado para el comando Acerca de
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// Datos del cuadro de diálogo
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ABOUTBOX };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // Compatibilidad con DDX/DDV
// Implementación
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// Cuadro de diálogo de CMFCApplication1Dlg
CMFCApplication1Dlg::CMFCApplication1Dlg(CWnd* pParent /*= nullptr*/)
: CDialogEx(IDD_MFCAPPLICATION1_DIALOG, pParent)
, pantalla0(0)
, pantalla(_T(""))
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CMFCApplication1Dlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Text(pDX, IDC_PANTALLA1_STATIC, pantalla0);
DDX_Text(pDX, IDC_PANTALLA_EDIT1, pantalla);
}
BEGIN_MESSAGE_MAP(CMFCApplication1Dlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_B1_BUTTON, &CMFCApplication1Dlg::OnBnClickedB1Button)
ON_BN_CLICKED(IDC_0_BUTTON, &CMFCApplication1Dlg::OnBnClicked0Button)
ON_BN_CLICKED(IDC_2_BUTTON, &CMFCApplication1Dlg::OnBnClicked2Button)
ON_BN_CLICKED(IDC_3_BUTTON, &CMFCApplication1Dlg::OnBnClicked3Button)
ON_BN_CLICKED(IDC_4_BUTTON, &CMFCApplication1Dlg::OnBnClicked4Button)
ON_BN_CLICKED(IDC_5_BUTTON, &CMFCApplication1Dlg::OnBnClicked5Button)
ON_BN_CLICKED(IDC_6_BUTTON, &CMFCApplication1Dlg::OnBnClicked6Button)
ON_BN_CLICKED(IDC_7_BUTTON, &CMFCApplication1Dlg::OnBnClicked7Button)
ON_BN_CLICKED(IDC_8_BUTTON, &CMFCApplication1Dlg::OnBnClicked8Button)
ON_BN_CLICKED(IDC_9_BUTTON, &CMFCApplication1Dlg::OnBnClicked9Button)
ON_BN_CLICKED(IDC_SUM_BUTTON, &CMFCApplication1Dlg::OnBnClickedSumButton)
ON_BN_CLICKED(IDC_BUTTON17, &CMFCApplication1Dlg::OnBnClickedButton17)
ON_BN_CLICKED(IDC_MUL_BUTTON, &CMFCApplication1Dlg::OnBnClickedMulButton)
ON_BN_CLICKED(IDC_DIV_BUTTON, &CMFCApplication1Dlg::OnBnClickedDivButton)
END_MESSAGE_MAP()
// Controladores de mensajes de CMFCApplication1Dlg
BOOL CMFCApplication1Dlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// Agregar el elemento de menú "Acerca de..." al menú del sistema.
// IDM_ABOUTBOX debe estar en el intervalo de comandos del sistema.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != nullptr)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Establecer el icono para este cuadro de diálogo. El marco de trabajo realiza esta operación
// automáticamente cuando la ventana principal de la aplicación no es un cuadro de diálogo
SetIcon(m_hIcon, TRUE); // Establecer icono grande
SetIcon(m_hIcon, FALSE); // Establecer icono pequeño
// TODO: agregar aquí inicialización adicional
return TRUE; // Devuelve TRUE a menos que establezca el foco en un control
}
void CMFCApplication1Dlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
// Si agrega un botón Minimizar al cuadro de diálogo, necesitará el siguiente código
// para dibujar el icono. Para aplicaciones MFC que utilicen el modelo de documentos y vistas,
// esta operación la realiza automáticamente el marco de trabajo.
void CMFCApplication1Dlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // Contexto de dispositivo para dibujo
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Centrar icono en el rectángulo de cliente
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Dibujar el icono
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
// El sistema llama a esta función para obtener el cursor que se muestra mientras el usuario arrastra
// la ventana minimizada.
HCURSOR CMFCApplication1Dlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
long op1, op2, contador = 0;
int sumop1, sumop2, resultadosum;
int mulop1, mulop2, resultadomul;
int divop1, divop2, resultadodiv;
int CodOp;
void CMFCApplication1Dlg::OnBnClickedB1Button()
{
// Aqui va todo lo del boton 1
UpdateData(TRUE);
if (contador== 0)
{
pantalla = "1";
pantalla0 = 1;
}
else
{
op2 = pantalla0 * 10;
op1 = op2+1;
pantalla0 = op1;
CString cadena;
cadena.Format(L"%d", op1);
pantalla = cadena;
}
contador++;
UpdateData(FALSE);
}
void CMFCApplication1Dlg::OnBnClicked0Button()
{
// TODO: Agregue aquí su código de controlador de notificación de control
UpdateData(TRUE);
if (contador == 0) {
pantalla = "0";
pantalla0 = 0;
}
else
{
op2 = pantalla0 * 10;
op1 = op2;
pantalla0 = op1;
CString cadena;
cadena.Format(L"%d", op1);
pantalla = cadena;
}
UpdateData(FALSE);
}
void CMFCApplication1Dlg::OnBnClicked2Button()
{
// Aqui va todo lo del boton 2
UpdateData(TRUE);
if (contador == 0)
{
pantalla = "2";
pantalla0 = 2;
}
else
{
op2 = pantalla0 * 10;
op1 = op2 + 2;
pantalla0 = op1;
CString cadena;
cadena.Format(L"%d", op1);
pantalla = cadena;
}
contador++;
UpdateData(FALSE);
}
void CMFCApplication1Dlg::OnBnClicked3Button()
{
// Aqui va todo lo del boton 3
UpdateData(TRUE);
if (contador == 0)
{
pantalla = "3";
pantalla0 = 3;
}
else
{
op2 = pantalla0 * 10;
op1 = op2 + 3;
pantalla0 = op1;
CString cadena;
cadena.Format(L"%d", op1);
pantalla = cadena;
}
contador++;
UpdateData(FALSE);
}
void CMFCApplication1Dlg::OnBnClicked4Button()
{
// Aqui va todo lo del boton 2
UpdateData(TRUE);
if (contador == 0)
{
pantalla = "4";
pantalla0 = 4;
}
else
{
op2 = pantalla0 * 10;
op1 = op2 + 4;
pantalla0 = op1;
CString cadena;
cadena.Format(L"%d", op1);
pantalla = cadena;
}
contador++;
UpdateData(FALSE);
}
void CMFCApplication1Dlg::OnBnClicked5Button()
{
// Aqui va todo lo del boton 2
UpdateData(TRUE);
if (contador == 0)
{
pantalla = "5";
pantalla0 = 5;
}
else
{
op2 = pantalla0 * 10;
op1 = op2 + 5;
pantalla0 = op1;
CString cadena;
cadena.Format(L"%d", op1);
pantalla = cadena;
}
contador++;
UpdateData(FALSE);
}
void CMFCApplication1Dlg::OnBnClicked6Button()
{
// Aqui va todo lo del boton 2
UpdateData(TRUE);
if (contador == 0)
{
pantalla = "6";
pantalla0 = 6;
}
else
{
op2 = pantalla0 * 10;
op1 = op2 + 6;
pantalla0 = op1;
CString cadena;
cadena.Format(L"%d", op1);
pantalla = cadena;
}
contador++;
UpdateData(FALSE);
}
void CMFCApplication1Dlg::OnBnClicked7Button()
{
// Aqui va todo lo del boton 7
UpdateData(TRUE);
if (contador == 0)
{
pantalla = "7";
pantalla0 = 7;
}
else
{
op2 = pantalla0 * 10;
op1 = op2 + 7;
pantalla0 = op1;
CString cadena;
cadena.Format(L"%d", op1);
pantalla = cadena;
}
contador++;
UpdateData(FALSE);
}
void CMFCApplication1Dlg::OnBnClicked8Button()
{
// Aqui va todo lo del boton 8
UpdateData(TRUE);
if (contador == 0)
{
pantalla = "8";
pantalla0 = 8;
}
else
{
op2 = pantalla0 * 10;
op1 = op2 + 8;
pantalla0 = op1;
CString cadena;
cadena.Format(L"%d", op1);
pantalla = cadena;
}
contador++;
UpdateData(FALSE);
}
void CMFCApplication1Dlg::OnBnClicked9Button()
{
// Aqui va todo lo del boton 9
UpdateData(TRUE);
if (contador == 0)
{
pantalla = "9";
pantalla0 = 9;
}
else
{
op2 = pantalla0 * 10;
op1 = op2 + 9;
pantalla0 = op1;
CString cadena;
cadena.Format(L"%d", op1);
pantalla = cadena;
}
contador++;
UpdateData(FALSE);
}
void CMFCApplication1Dlg::OnBnClickedSumButton()
{
CodOp = 1;
sumop1 = op1;
sumop2 = op2;
resultadosum = pantalla0;
contador = 0;
CString cadena;
cadena.Format(L"%d +", resultadosum);
pantalla = cadena;
UpdateData(FALSE);
}
void CMFCApplication1Dlg::OnBnClickedMulButton()
{
CodOp = 3;
mulop1 = op1;
mulop2 = op2;
resultadomul = pantalla0;
contador = 0;
CString cadena;
cadena.Format(L"%d *", resultadosum);
pantalla = cadena;
UpdateData(FALSE);
}
void CMFCApplication1Dlg::OnBnClickedDivButton()
{
CodOp = 4;
divop1 = op1;
divop2 = op2;
resultadodiv = pantalla0;
contador = 0;
CString cadena;
cadena.Format(L"%d +¿/", resultadosum);
pantalla = cadena;
UpdateData(FALSE);
}
|
//**************************************************************************
//**
//** 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 "../../common/Common.h"
#include "../../common/strings.h"
#include "../../common/file_formats/bsp29.h"
#include "../../common/message_utils.h"
/*
=============================================================================
The PVS must include a small area around the client to allow head bobbing
or other small motion on the client side. Otherwise, a bob might cause an
entity that should be visible to not show up, especially when the bob
crosses a waterline.
=============================================================================
*/
static byte qh_fatpvs[ BSP29_MAX_MAP_LEAFS / 8 ];
// because there can be a lot of nails, there is a special
// network protocol for them
enum { MAX_NAILS = 32 };
static qhedict_t* nails[ MAX_NAILS ];
static int numnails;
enum { MAX_MISSILES_H2 = 32 };
static qhedict_t* missiles[ MAX_MISSILES_H2 ];
static qhedict_t* ravens[ MAX_MISSILES_H2 ];
static qhedict_t* raven2s[ MAX_MISSILES_H2 ];
static int nummissiles;
static int numravens;
static int numraven2s;
// Calculates a PVS that is the inclusive or of all leafs within 8 pixels of the
// given point.
static byte* SVQH_FatPVS( const vec3_t org ) {
vec3_t mins, maxs;
for ( int i = 0; i < 3; i++ ) {
mins[ i ] = org[ i ] - 8;
maxs[ i ] = org[ i ] + 8;
}
int leafs[ 64 ];
int count = CM_BoxLeafnums( mins, maxs, leafs, 64 );
if ( count < 1 ) {
common->FatalError( "SVQH_FatPVS: count < 1" );
}
// convert leafs to clusters
for ( int i = 0; i < count; i++ ) {
leafs[ i ] = CM_LeafCluster( leafs[ i ] );
}
int fatbytes = ( CM_NumClusters() + 31 ) >> 3;
Com_Memcpy( qh_fatpvs, CM_ClusterPVS( leafs[ 0 ] ), fatbytes );
// or in all the other leaf bits
for ( int i = 1; i < count; i++ ) {
byte* pvs = CM_ClusterPVS( leafs[ i ] );
for ( int j = 0; j < fatbytes; j++ ) {
qh_fatpvs[ j ] |= pvs[ j ];
}
}
return qh_fatpvs;
}
static void SVQ1_WriteEntity( qhedict_t* ent, int e, QMsg* msg ) {
int bits = 0;
for ( int i = 0; i < 3; i++ ) {
float miss = ent->GetOrigin()[ i ] - ent->q1_baseline.origin[ i ];
if ( miss < -0.1 || miss > 0.1 ) {
bits |= Q1U_ORIGIN1 << i;
}
}
if ( ent->GetAngles()[ 0 ] != ent->q1_baseline.angles[ 0 ] ) {
bits |= Q1U_ANGLE1;
}
if ( ent->GetAngles()[ 1 ] != ent->q1_baseline.angles[ 1 ] ) {
bits |= Q1U_ANGLE2;
}
if ( ent->GetAngles()[ 2 ] != ent->q1_baseline.angles[ 2 ] ) {
bits |= Q1U_ANGLE3;
}
if ( ent->GetMoveType() == QHMOVETYPE_STEP ) {
bits |= Q1U_NOLERP; // don't mess up the step animation
}
if ( ent->q1_baseline.colormap != ent->GetColorMap() ) {
bits |= Q1U_COLORMAP;
}
if ( ent->q1_baseline.skinnum != ent->GetSkin() ) {
bits |= Q1U_SKIN;
}
if ( ent->q1_baseline.frame != ent->GetFrame() ) {
bits |= Q1U_FRAME;
}
if ( ent->q1_baseline.effects != ent->GetEffects() ) {
bits |= Q1U_EFFECTS;
}
if ( ent->q1_baseline.modelindex != ent->v.modelindex ) {
bits |= Q1U_MODEL;
}
if ( e >= 256 ) {
bits |= Q1U_LONGENTITY;
}
if ( bits >= 256 ) {
bits |= Q1U_MOREBITS;
}
//
// write the message
//
msg->WriteByte( bits | Q1U_SIGNAL );
if ( bits & Q1U_MOREBITS ) {
msg->WriteByte( bits >> 8 );
}
if ( bits & Q1U_LONGENTITY ) {
msg->WriteShort( e );
} else {
msg->WriteByte( e );
}
if ( bits & Q1U_MODEL ) {
msg->WriteByte( ent->v.modelindex );
}
if ( bits & Q1U_FRAME ) {
msg->WriteByte( ent->GetFrame() );
}
if ( bits & Q1U_COLORMAP ) {
msg->WriteByte( ent->GetColorMap() );
}
if ( bits & Q1U_SKIN ) {
msg->WriteByte( ent->GetSkin() );
}
if ( bits & Q1U_EFFECTS ) {
msg->WriteByte( ent->GetEffects() );
}
if ( bits & Q1U_ORIGIN1 ) {
msg->WriteCoord( ent->GetOrigin()[ 0 ] );
}
if ( bits & Q1U_ANGLE1 ) {
msg->WriteAngle( ent->GetAngles()[ 0 ] );
}
if ( bits & Q1U_ORIGIN2 ) {
msg->WriteCoord( ent->GetOrigin()[ 1 ] );
}
if ( bits & Q1U_ANGLE2 ) {
msg->WriteAngle( ent->GetAngles()[ 1 ] );
}
if ( bits & Q1U_ORIGIN3 ) {
msg->WriteCoord( ent->GetOrigin()[ 2 ] );
}
if ( bits & Q1U_ANGLE3 ) {
msg->WriteAngle( ent->GetAngles()[ 2 ] );
}
}
void SVQ1_WriteEntitiesToClient( qhedict_t* clent, QMsg* msg ) {
// find the client's PVS
vec3_t org;
VectorAdd( clent->GetOrigin(), clent->GetViewOfs(), org );
byte* pvs = SVQH_FatPVS( org );
// send over all entities (excpet the client) that touch the pvs
qhedict_t* ent = NEXT_EDICT( sv.qh_edicts );
for ( int e = 1; e < sv.qh_num_edicts; e++, ent = NEXT_EDICT( ent ) ) {
// ignore if not touching a PV leaf
if ( ent != clent ) { // clent is ALLWAYS sent
// ignore ents without visible models
if ( !ent->v.modelindex || !*PR_GetString( ent->GetModel() ) ) {
continue;
}
int i;
for ( i = 0; i < ent->num_leafs; i++ ) {
int l = CM_LeafCluster( ent->LeafNums[ i ] );
if ( pvs[ l >> 3 ] & ( 1 << ( l & 7 ) ) ) {
break;
}
}
if ( i == ent->num_leafs ) {
continue; // not visible
}
}
if ( msg->maxsize - msg->cursize < 16 ) {
common->Printf( "packet overflow\n" );
return;
}
// send an update
SVQ1_WriteEntity( ent, e, msg );
}
}
void SVH2_PrepareClientEntities( client_t* client, qhedict_t* clent, QMsg* msg ) {
enum
{
CLIENT_FRAME_INIT = 255,
CLIENT_FRAME_RESET = 254,
ENT_CLEARED = 2,
CLEAR_LIMIT = 2
};
int client_num = client - svs.clients;
h2client_state2_t* state = &sv.h2_states[ client_num ];
h2client_frames_t* reference = &state->frames[ 0 ];
if ( client->h2_last_sequence != client->h2_current_sequence ) {
// Old sequence
client->h2_current_frame++;
if ( client->h2_current_frame > H2MAX_FRAMES + 1 ) {
client->h2_current_frame = H2MAX_FRAMES + 1;
}
} else if ( client->h2_last_frame == CLIENT_FRAME_INIT ||
client->h2_last_frame == 0 ||
client->h2_last_frame == H2MAX_FRAMES + 1 ) {
// Reference expired in current sequence
client->h2_current_frame = 1;
client->h2_current_sequence++;
} else if ( client->h2_last_frame >= 1 && client->h2_last_frame <= client->h2_current_frame ) {
// Got a valid frame
*reference = state->frames[ client->h2_last_frame ];
for ( int i = 0; i < reference->count; i++ ) {
if ( reference->states[ i ].flags & ENT_CLEARED ) {
int e = reference->states[ i ].number;
qhedict_t* ent = QH_EDICT_NUM( e );
if ( ent->h2_baseline.ClearCount[ client_num ] < CLEAR_LIMIT ) {
ent->h2_baseline.ClearCount[ client_num ]++;
} else if ( ent->h2_baseline.ClearCount[ client_num ] == CLEAR_LIMIT ) {
ent->h2_baseline.ClearCount[ client_num ] = 3;
reference->states[ i ].flags &= ~ENT_CLEARED;
}
}
}
client->h2_current_frame = 1;
client->h2_current_sequence++;
} else {
// Normal frame advance
client->h2_current_frame++;
if ( client->h2_current_frame > H2MAX_FRAMES + 1 ) {
client->h2_current_frame = H2MAX_FRAMES + 1;
}
}
bool DoPlayer = false;
bool DoMonsters = false;
bool DoMissiles = false;
bool DoMisc = false;
if ( svh2_update_player->integer ) {
DoPlayer = ( client->h2_current_sequence % ( svh2_update_player->integer ) ) == 0;
}
if ( svh2_update_monsters->integer ) {
DoMonsters = ( client->h2_current_sequence % ( svh2_update_monsters->integer ) ) == 0;
}
if ( svh2_update_missiles->integer ) {
DoMissiles = ( client->h2_current_sequence % ( svh2_update_missiles->integer ) ) == 0;
}
if ( svh2_update_misc->integer ) {
DoMisc = ( client->h2_current_sequence % ( svh2_update_misc->integer ) ) == 0;
}
h2client_frames_t* build = &state->frames[ client->h2_current_frame ];
Com_Memset( build, 0, sizeof ( *build ) );
client->h2_last_frame = CLIENT_FRAME_RESET;
short NumToRemove = 0;
msg->WriteByte( h2svc_reference );
msg->WriteByte( client->h2_current_frame );
msg->WriteByte( client->h2_current_sequence );
// find the client's PVS
vec3_t org;
if ( clent->GetCameraMode() ) {
qhedict_t* ent = PROG_TO_EDICT( clent->GetCameraMode() );
VectorCopy( ent->GetOrigin(), org );
} else {
VectorAdd( clent->GetOrigin(), clent->GetViewOfs(), org );
}
byte* pvs = SVQH_FatPVS( org );
// send over all entities (excpet the client) that touch the pvs
int position = 0;
short RemoveList[ MAX_CLIENT_STATES_H2 ];
qhedict_t* ent = NEXT_EDICT( sv.qh_edicts );
for ( int e = 1; e < sv.qh_num_edicts; e++, ent = NEXT_EDICT( ent ) ) {
bool DoRemove = false;
// don't send if flagged for NODRAW and there are no lighting effects
if ( ent->GetEffects() == H2EF_NODRAW ) {
DoRemove = true;
goto skipA;
}
// ignore if not touching a PV leaf
if ( ent != clent ) { // clent is ALWAYS sent
// ignore ents without visible models
if ( !ent->v.modelindex || !*PR_GetString( ent->GetModel() ) ) {
DoRemove = true;
goto skipA;
}
int i;
for ( i = 0; i < ent->num_leafs; i++ ) {
int l = CM_LeafCluster( ent->LeafNums[ i ] );
if ( pvs[ l >> 3 ] & ( 1 << ( l & 7 ) ) ) {
break;
}
}
if ( i == ent->num_leafs ) {
DoRemove = true;
goto skipA;
}
}
skipA:
bool IgnoreEnt = false;
int flagtest = ( int )ent->GetFlags();
if ( !DoRemove ) {
if ( flagtest & QHFL_CLIENT ) {
if ( !DoPlayer ) {
IgnoreEnt = true;
}
} else if ( flagtest & QHFL_MONSTER ) {
if ( !DoMonsters ) {
IgnoreEnt = true;
}
} else if ( ent->GetMoveType() == QHMOVETYPE_FLYMISSILE ||
ent->GetMoveType() == H2MOVETYPE_BOUNCEMISSILE ||
ent->GetMoveType() == QHMOVETYPE_BOUNCE ) {
if ( !DoMissiles ) {
IgnoreEnt = true;
}
} else {
if ( !DoMisc ) {
IgnoreEnt = true;
}
}
}
int bits = 0;
while ( position <reference->count&&
e> reference->states[ position ].number ) {
position++;
}
bool FoundInList;
h2entity_state_t* ref_ent;
h2entity_state_t build_ent;
if ( position < reference->count && reference->states[ position ].number == e ) {
FoundInList = true;
if ( DoRemove ) {
RemoveList[ NumToRemove ] = e;
NumToRemove++;
continue;
} else {
ref_ent = &reference->states[ position ];
}
} else {
if ( DoRemove || IgnoreEnt ) {
continue;
}
ref_ent = &build_ent;
build_ent.number = e;
build_ent.origin[ 0 ] = ent->h2_baseline.origin[ 0 ];
build_ent.origin[ 1 ] = ent->h2_baseline.origin[ 1 ];
build_ent.origin[ 2 ] = ent->h2_baseline.origin[ 2 ];
build_ent.angles[ 0 ] = ent->h2_baseline.angles[ 0 ];
build_ent.angles[ 1 ] = ent->h2_baseline.angles[ 1 ];
build_ent.angles[ 2 ] = ent->h2_baseline.angles[ 2 ];
build_ent.modelindex = ent->h2_baseline.modelindex;
build_ent.frame = ent->h2_baseline.frame;
build_ent.colormap = ent->h2_baseline.colormap;
build_ent.skinnum = ent->h2_baseline.skinnum;
build_ent.effects = ent->h2_baseline.effects;
build_ent.scale = ent->h2_baseline.scale;
build_ent.drawflags = ent->h2_baseline.drawflags;
build_ent.abslight = ent->h2_baseline.abslight;
build_ent.flags = 0;
FoundInList = false;
}
h2entity_state_t* set_ent = &build->states[ build->count ];
build->count++;
if ( ent->h2_baseline.ClearCount[ client_num ] < CLEAR_LIMIT ) {
Com_Memset( ref_ent,0,sizeof ( *ref_ent ) );
ref_ent->number = e;
}
*set_ent = *ref_ent;
if ( IgnoreEnt ) {
continue;
}
// send an update
for ( int i = 0; i < 3; i++ ) {
float miss = ent->GetOrigin()[ i ] - ref_ent->origin[ i ];
if ( miss < -0.1 || miss > 0.1 ) {
bits |= H2U_ORIGIN1 << i;
set_ent->origin[ i ] = ent->GetOrigin()[ i ];
}
}
if ( ent->GetAngles()[ 0 ] != ref_ent->angles[ 0 ] ) {
bits |= H2U_ANGLE1;
set_ent->angles[ 0 ] = ent->GetAngles()[ 0 ];
}
if ( ent->GetAngles()[ 1 ] != ref_ent->angles[ 1 ] ) {
bits |= H2U_ANGLE2;
set_ent->angles[ 1 ] = ent->GetAngles()[ 1 ];
}
if ( ent->GetAngles()[ 2 ] != ref_ent->angles[ 2 ] ) {
bits |= H2U_ANGLE3;
set_ent->angles[ 2 ] = ent->GetAngles()[ 2 ];
}
if ( ent->GetMoveType() == QHMOVETYPE_STEP ) {
bits |= H2U_NOLERP; // don't mess up the step animation
}
if ( ref_ent->colormap != ent->GetColorMap() ) {
bits |= H2U_COLORMAP;
set_ent->colormap = ent->GetColorMap();
}
if ( ref_ent->skinnum != ent->GetSkin() ||
ref_ent->drawflags != ent->GetDrawFlags() ) {
bits |= H2U_SKIN;
set_ent->skinnum = ent->GetSkin();
set_ent->drawflags = ent->GetDrawFlags();
}
if ( ref_ent->frame != ent->GetFrame() ) {
bits |= H2U_FRAME;
set_ent->frame = ent->GetFrame();
}
if ( ref_ent->effects != ent->GetEffects() ) {
bits |= H2U_EFFECTS;
set_ent->effects = ent->GetEffects();
}
if ( flagtest & 0xff000000 ) {
common->Error( "Invalid flags setting for class %s", PR_GetString( ent->GetClassName() ) );
return;
}
int temp_index = ent->v.modelindex;
if ( ( ( int )ent->GetFlags() & H2FL_CLASS_DEPENDENT ) && ent->GetModel() ) {
char NewName[ MAX_QPATH ];
String::Cpy( NewName, PR_GetString( ent->GetModel() ) );
NewName[ String::Length( NewName ) - 5 ] = client->h2_playerclass + 48;
temp_index = SVQH_ModelIndex( NewName );
}
if ( ref_ent->modelindex != temp_index ) {
bits |= H2U_MODEL;
set_ent->modelindex = temp_index;
}
if ( ref_ent->scale != ( ( int )( ent->GetScale() * 100.0 ) & 255 ) ||
ref_ent->abslight != ( ( int )( ent->GetAbsLight() * 255.0 ) & 255 ) ) {
bits |= H2U_SCALE;
set_ent->scale = ( ( int )( ent->GetScale() * 100.0 ) & 255 );
set_ent->abslight = ( int )( ent->GetAbsLight() * 255.0 ) & 255;
}
if ( ent->h2_baseline.ClearCount[ client_num ] < CLEAR_LIMIT ) {
bits |= H2U_CLEAR_ENT;
set_ent->flags |= ENT_CLEARED;
}
if ( !bits && FoundInList ) {
if ( build->count >= MAX_CLIENT_STATES_H2 ) {
break;
}
continue;
}
if ( e >= 256 ) {
bits |= H2U_LONGENTITY;
}
if ( bits >= 256 ) {
bits |= H2U_MOREBITS;
}
if ( bits >= 65536 ) {
bits |= H2U_MOREBITS2;
}
//
// write the message
//
msg->WriteByte( bits | H2U_SIGNAL );
if ( bits & H2U_MOREBITS ) {
msg->WriteByte( bits >> 8 );
}
if ( bits & H2U_MOREBITS2 ) {
msg->WriteByte( bits >> 16 );
}
if ( bits & H2U_LONGENTITY ) {
msg->WriteShort( e );
} else {
msg->WriteByte( e );
}
if ( bits & H2U_MODEL ) {
msg->WriteShort( temp_index );
}
if ( bits & H2U_FRAME ) {
msg->WriteByte( ent->GetFrame() );
}
if ( bits & H2U_COLORMAP ) {
msg->WriteByte( ent->GetColorMap() );
}
if ( bits & H2U_SKIN ) {// Used for skin and drawflags
msg->WriteByte( ent->GetSkin() );
msg->WriteByte( ent->GetDrawFlags() );
}
if ( bits & H2U_EFFECTS ) {
msg->WriteByte( ent->GetEffects() );
}
if ( bits & H2U_ORIGIN1 ) {
msg->WriteCoord( ent->GetOrigin()[ 0 ] );
}
if ( bits & H2U_ANGLE1 ) {
msg->WriteAngle( ent->GetAngles()[ 0 ] );
}
if ( bits & H2U_ORIGIN2 ) {
msg->WriteCoord( ent->GetOrigin()[ 1 ] );
}
if ( bits & H2U_ANGLE2 ) {
msg->WriteAngle( ent->GetAngles()[ 1 ] );
}
if ( bits & H2U_ORIGIN3 ) {
msg->WriteCoord( ent->GetOrigin()[ 2 ] );
}
if ( bits & H2U_ANGLE3 ) {
msg->WriteAngle( ent->GetAngles()[ 2 ] );
}
if ( bits & H2U_SCALE ) { // Used for scale and abslight
msg->WriteByte( ( int )( ent->GetScale() * 100.0 ) & 255 );
msg->WriteByte( ( int )( ent->GetAbsLight() * 255.0 ) & 255 );
}
if ( build->count >= MAX_CLIENT_STATES_H2 ) {
break;
}
}
msg->WriteByte( h2svc_clear_edicts );
msg->WriteByte( NumToRemove );
for ( int i = 0; i < NumToRemove; i++ ) {
msg->WriteShort( RemoveList[ i ] );
}
}
static bool SVQW_AddNailUpdate( qhedict_t* ent ) {
if ( ent->v.modelindex != svqw_nailmodel &&
ent->v.modelindex != svqw_supernailmodel ) {
return false;
}
if ( numnails == MAX_NAILS ) {
return true;
}
nails[ numnails ] = ent;
numnails++;
return true;
}
static void SVQW_EmitNailUpdate( QMsg* msg ) {
if ( !numnails ) {
return;
}
msg->WriteByte( qwsvc_nails );
msg->WriteByte( numnails );
for ( int n = 0; n < numnails; n++ ) {
qhedict_t* ent = nails[ n ];
int x = ( int )( ent->GetOrigin()[ 0 ] + 4096 ) >> 1;
int y = ( int )( ent->GetOrigin()[ 1 ] + 4096 ) >> 1;
int z = ( int )( ent->GetOrigin()[ 2 ] + 4096 ) >> 1;
int p = ( int )( 16 * ent->GetAngles()[ 0 ] / 360 ) & 15;
int yaw = ( int )( 256 * ent->GetAngles()[ 1 ] / 360 ) & 255;
byte bits[ 6 ]; // [48 bits] xyzpy 12 12 12 4 8
bits[ 0 ] = x;
bits[ 1 ] = ( x >> 8 ) | ( y << 4 );
bits[ 2 ] = ( y >> 4 );
bits[ 3 ] = z;
bits[ 4 ] = ( z >> 8 ) | ( p << 4 );
bits[ 5 ] = yaw;
for ( int i = 0; i < 6; i++ ) {
msg->WriteByte( bits[ i ] );
}
}
}
static bool SVHW_AddMissileUpdate( qhedict_t* ent ) {
if ( ent->v.modelindex == svhw_magicmissmodel ) {
if ( nummissiles == MAX_MISSILES_H2 ) {
return true;
}
missiles[ nummissiles ] = ent;
nummissiles++;
return true;
}
if ( ent->v.modelindex == svhw_ravenmodel ) {
if ( numravens == MAX_MISSILES_H2 ) {
return true;
}
ravens[ numravens ] = ent;
numravens++;
return true;
}
if ( ent->v.modelindex == svhw_raven2model ) {
if ( numraven2s == MAX_MISSILES_H2 ) {
return true;
}
raven2s[ numraven2s ] = ent;
numraven2s++;
return true;
}
return false;
}
static void SVHW_EmitMissileUpdate( QMsg* msg ) {
if ( !nummissiles ) {
return;
}
msg->WriteByte( hwsvc_packmissile );
msg->WriteByte( nummissiles );
for ( int n = 0; n < nummissiles; n++ ) {
qhedict_t* ent = missiles[ n ];
int x = ( int )( ent->GetOrigin()[ 0 ] + 4096 ) >> 1;
int y = ( int )( ent->GetOrigin()[ 1 ] + 4096 ) >> 1;
int z = ( int )( ent->GetOrigin()[ 2 ] + 4096 ) >> 1;
int type;
if ( fabs( ent->GetScale() - 0.1 ) < 0.05 ) {
type = 1; //assume ice mace
} else {
type = 2; //assume magic missile
}
byte bits[ 5 ]; // [40 bits] xyz type 12 12 12 4
bits[ 0 ] = x;
bits[ 1 ] = ( x >> 8 ) | ( y << 4 );
bits[ 2 ] = ( y >> 4 );
bits[ 3 ] = z;
bits[ 4 ] = ( z >> 8 ) | ( type << 4 );
for ( int i = 0; i < 5; i++ ) {
msg->WriteByte( bits[ i ] );
}
}
}
static void SVHW_EmitRavenUpdate( QMsg* msg ) {
if ( ( !numravens ) && ( !numraven2s ) ) {
return;
}
msg->WriteByte( hwsvc_nails ); //svc nails overloaded for ravens
msg->WriteByte( numravens );
for ( int n = 0; n < numravens; n++ ) {
qhedict_t* ent = ravens[ n ];
int x = ( int )( ent->GetOrigin()[ 0 ] + 4096 ) >> 1;
int y = ( int )( ent->GetOrigin()[ 1 ] + 4096 ) >> 1;
int z = ( int )( ent->GetOrigin()[ 2 ] + 4096 ) >> 1;
int p = ( int )( 16 * ent->GetAngles()[ 0 ] / 360 ) & 15;
int frame = ( int )( ent->GetFrame() ) & 7;
int yaw = ( int )( 32 * ent->GetAngles()[ 1 ] / 360 ) & 31;
byte bits[ 6 ]; // [48 bits] xyzpy 12 12 12 4 8
bits[ 0 ] = x;
bits[ 1 ] = ( x >> 8 ) | ( y << 4 );
bits[ 2 ] = ( y >> 4 );
bits[ 3 ] = z;
bits[ 4 ] = ( z >> 8 ) | ( p << 4 );
bits[ 5 ] = yaw | ( frame << 5 );
for ( int i = 0; i < 6; i++ ) {
msg->WriteByte( bits[ i ] );
}
}
msg->WriteByte( numraven2s );
for ( int n = 0; n < numraven2s; n++ ) {
qhedict_t* ent = raven2s[ n ];
int x = ( int )( ent->GetOrigin()[ 0 ] + 4096 ) >> 1;
int y = ( int )( ent->GetOrigin()[ 1 ] + 4096 ) >> 1;
int z = ( int )( ent->GetOrigin()[ 2 ] + 4096 ) >> 1;
int p = ( int )( 16 * ent->GetAngles()[ 0 ] / 360 ) & 15;
int yaw = ( int )( 256 * ent->GetAngles()[ 1 ] / 360 ) & 255;
byte bits[ 6 ]; // [48 bits] xyzpy 12 12 12 4 8
bits[ 0 ] = x;
bits[ 1 ] = ( x >> 8 ) | ( y << 4 );
bits[ 2 ] = ( y >> 4 );
bits[ 3 ] = z;
bits[ 4 ] = ( z >> 8 ) | ( p << 4 );
bits[ 5 ] = yaw;
for ( int i = 0; i < 6; i++ ) {
msg->WriteByte( bits[ i ] );
}
}
}
static void SVHW_EmitPackedEntities( QMsg* msg ) {
SVHW_EmitMissileUpdate( msg );
SVHW_EmitRavenUpdate( msg );
}
// Writes part of a packetentities message.
// Can delta from either a baseline or a previous packet_entity
static void SVQW_WriteDelta( q1entity_state_t* from, q1entity_state_t* to, QMsg* msg, bool force ) {
// send an update
int bits = 0;
for ( int i = 0; i < 3; i++ ) {
float miss = to->origin[ i ] - from->origin[ i ];
if ( miss < -0.1 || miss > 0.1 ) {
bits |= QWU_ORIGIN1 << i;
}
}
if ( to->angles[ 0 ] != from->angles[ 0 ] ) {
bits |= QWU_ANGLE1;
}
if ( to->angles[ 1 ] != from->angles[ 1 ] ) {
bits |= QWU_ANGLE2;
}
if ( to->angles[ 2 ] != from->angles[ 2 ] ) {
bits |= QWU_ANGLE3;
}
if ( to->colormap != from->colormap ) {
bits |= QWU_COLORMAP;
}
if ( to->skinnum != from->skinnum ) {
bits |= QWU_SKIN;
}
if ( to->frame != from->frame ) {
bits |= QWU_FRAME;
}
if ( to->effects != from->effects ) {
bits |= QWU_EFFECTS;
}
if ( to->modelindex != from->modelindex ) {
bits |= QWU_MODEL;
}
if ( bits & 511 ) {
bits |= QWU_MOREBITS;
}
if ( to->flags & QWU_SOLID ) {
bits |= QWU_SOLID;
}
//
// write the message
//
if ( !to->number ) {
common->Error( "Unset entity number" );
}
if ( to->number >= 512 ) {
common->Error( "Entity number >= 512" );
}
if ( !bits && !force ) {
return; // nothing to send!
}
int i = to->number | ( bits & ~511 );
if ( i & QWU_REMOVE ) {
common->FatalError( "QWU_REMOVE" );
}
msg->WriteShort( i );
if ( bits & QWU_MOREBITS ) {
msg->WriteByte( bits & 255 );
}
if ( bits & QWU_MODEL ) {
msg->WriteByte( to->modelindex );
}
if ( bits & QWU_FRAME ) {
msg->WriteByte( to->frame );
}
if ( bits & QWU_COLORMAP ) {
msg->WriteByte( to->colormap );
}
if ( bits & QWU_SKIN ) {
msg->WriteByte( to->skinnum );
}
if ( bits & QWU_EFFECTS ) {
msg->WriteByte( to->effects );
}
if ( bits & QWU_ORIGIN1 ) {
msg->WriteCoord( to->origin[ 0 ] );
}
if ( bits & QWU_ANGLE1 ) {
msg->WriteAngle( to->angles[ 0 ] );
}
if ( bits & QWU_ORIGIN2 ) {
msg->WriteCoord( to->origin[ 1 ] );
}
if ( bits & QWU_ANGLE2 ) {
msg->WriteAngle( to->angles[ 1 ] );
}
if ( bits & QWU_ORIGIN3 ) {
msg->WriteCoord( to->origin[ 2 ] );
}
if ( bits & QWU_ANGLE3 ) {
msg->WriteAngle( to->angles[ 2 ] );
}
}
// Writes part of a packetentities message.
// Can delta from either a baseline or a previous packet_entity
static void SVHW_WriteDelta( h2entity_state_t* from, h2entity_state_t* to, QMsg* msg, bool force, qhedict_t* ent, client_t* client ) {
// send an update
int bits = 0;
for ( int i = 0; i < 3; i++ ) {
float miss = to->origin[ i ] - from->origin[ i ];
if ( miss < -0.1 || miss > 0.1 ) {
bits |= HWU_ORIGIN1 << i;
}
}
if ( to->angles[ 0 ] != from->angles[ 0 ] ) {
bits |= HWU_ANGLE1;
}
if ( to->angles[ 1 ] != from->angles[ 1 ] ) {
bits |= HWU_ANGLE2;
}
if ( to->angles[ 2 ] != from->angles[ 2 ] ) {
bits |= HWU_ANGLE3;
}
if ( to->colormap != from->colormap ) {
bits |= HWU_COLORMAP;
}
if ( to->skinnum != from->skinnum ) {
bits |= HWU_SKIN;
}
if ( to->drawflags != from->drawflags ) {
bits |= HWU_DRAWFLAGS;
}
if ( to->frame != from->frame ) {
bits |= HWU_FRAME;
}
if ( to->effects != from->effects ) {
bits |= HWU_EFFECTS;
}
int temp_index = to->modelindex;
if ( ( ( int )ent->GetFlags() & H2FL_CLASS_DEPENDENT ) && ent->GetModel() ) {
char NewName[ MAX_QPATH ];
String::Cpy( NewName, PR_GetString( ent->GetModel() ) );
if ( client->h2_playerclass <= 0 || client->h2_playerclass > MAX_PLAYER_CLASS ) {
NewName[ String::Length( NewName ) - 5 ] = '1';
} else {
NewName[ String::Length( NewName ) - 5 ] = client->h2_playerclass + 48;
}
temp_index = SVQH_ModelIndex( NewName );
}
if ( temp_index != from->modelindex ) {
bits |= HWU_MODEL;
if ( temp_index > 255 ) {
bits |= HWU_MODEL16;
}
}
if ( to->scale != from->scale ) {
bits |= HWU_SCALE;
}
if ( to->abslight != from->abslight ) {
bits |= HWU_ABSLIGHT;
}
if ( to->wpn_sound ) { //not delta'ed, sound gets cleared after send
bits |= HWU_SOUND;
}
if ( bits & 0xff0000 ) {
bits |= HWU_MOREBITS2;
}
if ( bits & 511 ) {
bits |= HWU_MOREBITS;
}
//
// write the message
//
if ( !to->number ) {
common->Error( "Unset entity number" );
}
if ( to->number >= 512 ) {
common->Error( "Entity number >= 512" );
}
if ( !bits && !force ) {
return; // nothing to send!
}
int i = to->number | ( bits & ~511 );
if ( i & HWU_REMOVE ) {
common->FatalError( "HWU_REMOVE" );
}
msg->WriteShort( i & 0xffff );
if ( bits & HWU_MOREBITS ) {
msg->WriteByte( bits & 255 );
}
if ( bits & HWU_MOREBITS2 ) {
msg->WriteByte( ( bits >> 16 ) & 0xff );
}
if ( bits & HWU_MODEL ) {
if ( bits & HWU_MODEL16 ) {
msg->WriteShort( temp_index );
} else {
msg->WriteByte( temp_index );
}
}
if ( bits & HWU_FRAME ) {
msg->WriteByte( to->frame );
}
if ( bits & HWU_COLORMAP ) {
msg->WriteByte( to->colormap );
}
if ( bits & HWU_SKIN ) {
msg->WriteByte( to->skinnum );
}
if ( bits & HWU_DRAWFLAGS ) {
msg->WriteByte( to->drawflags );
}
if ( bits & HWU_EFFECTS ) {
msg->WriteLong( to->effects );
}
if ( bits & HWU_ORIGIN1 ) {
msg->WriteCoord( to->origin[ 0 ] );
}
if ( bits & HWU_ANGLE1 ) {
msg->WriteAngle( to->angles[ 0 ] );
}
if ( bits & HWU_ORIGIN2 ) {
msg->WriteCoord( to->origin[ 1 ] );
}
if ( bits & HWU_ANGLE2 ) {
msg->WriteAngle( to->angles[ 1 ] );
}
if ( bits & HWU_ORIGIN3 ) {
msg->WriteCoord( to->origin[ 2 ] );
}
if ( bits & HWU_ANGLE3 ) {
msg->WriteAngle( to->angles[ 2 ] );
}
if ( bits & HWU_SCALE ) {
msg->WriteByte( to->scale );
}
if ( bits & HWU_ABSLIGHT ) {
msg->WriteByte( to->abslight );
}
if ( bits & HWU_SOUND ) {
msg->WriteShort( to->wpn_sound );
}
}
// Writes a delta update of a qwpacket_entities_t to the message.
static void SVQW_EmitPacketEntities( client_t* client, qwpacket_entities_t* to, QMsg* msg ) {
// this is the frame that we are going to delta update from
qwpacket_entities_t* from;
int oldmax;
if ( client->qh_delta_sequence != -1 ) {
qwclient_frame_t* fromframe = &client->qw_frames[ client->qh_delta_sequence & UPDATE_MASK_QW ];
from = &fromframe->entities;
oldmax = from->num_entities;
msg->WriteByte( qwsvc_deltapacketentities );
msg->WriteByte( client->qh_delta_sequence );
} else {
oldmax = 0; // no delta update
from = NULL;
msg->WriteByte( qwsvc_packetentities );
}
int newindex = 0;
int oldindex = 0;
while ( newindex < to->num_entities || oldindex < oldmax ) {
int newnum = newindex >= to->num_entities ? 9999 : to->entities[ newindex ].number;
int oldnum = oldindex >= oldmax ? 9999 : from->entities[ oldindex ].number;
if ( newnum == oldnum ) {
// delta update from old position
SVQW_WriteDelta( &from->entities[ oldindex ], &to->entities[ newindex ], msg, false );
oldindex++;
newindex++;
continue;
}
if ( newnum < oldnum ) {
// this is a new entity, send it from the baseline
qhedict_t* ent = QH_EDICT_NUM( newnum );
SVQW_WriteDelta( &ent->q1_baseline, &to->entities[ newindex ], msg, true );
newindex++;
continue;
}
if ( newnum > oldnum ) {
// the old entity isn't present in the new message
msg->WriteShort( oldnum | QWU_REMOVE );
oldindex++;
continue;
}
}
msg->WriteShort( 0 ); // end of packetentities
}
// Writes a delta update of a hwpacket_entities_t to the message.
static void SVHW_EmitPacketEntities( client_t* client, hwpacket_entities_t* to, QMsg* msg ) {
// this is the frame that we are going to delta update from
hwpacket_entities_t* from;
int oldmax;
if ( client->qh_delta_sequence != -1 ) {
hwclient_frame_t* fromframe = &client->hw_frames[ client->qh_delta_sequence & UPDATE_MASK_HW ];
from = &fromframe->entities;
oldmax = from->num_entities;
msg->WriteByte( hwsvc_deltapacketentities );
msg->WriteByte( client->qh_delta_sequence );
} else {
oldmax = 0; // no delta update
from = NULL;
msg->WriteByte( hwsvc_packetentities );
}
int newindex = 0;
int oldindex = 0;
while ( newindex < to->num_entities || oldindex < oldmax ) {
int newnum = newindex >= to->num_entities ? 9999 : to->entities[ newindex ].number;
int oldnum = oldindex >= oldmax ? 9999 : from->entities[ oldindex ].number;
if ( newnum == oldnum ) {
// delta update from old position
SVHW_WriteDelta( &from->entities[ oldindex ], &to->entities[ newindex ], msg, false, QH_EDICT_NUM( newnum ), client );
oldindex++;
newindex++;
continue;
}
if ( newnum < oldnum ) {
// this is a new entity, send it from the baseline
qhedict_t* ent = QH_EDICT_NUM( newnum );
SVHW_WriteDelta( &ent->h2_baseline, &to->entities[ newindex ], msg, true, ent, client );
newindex++;
continue;
}
if ( newnum > oldnum ) {
// the old entity isn't present in the new message
msg->WriteShort( oldnum | HWU_REMOVE );
oldindex++;
continue;
}
}
msg->WriteShort( 0 ); // end of packetentities
}
static void SVQW_WritePlayersToClient( client_t* client, qhedict_t* clent, byte* pvs, QMsg* msg ) {
client_t* cl = svs.clients;
for ( int j = 0; j < MAX_CLIENTS_QHW; j++,cl++ ) {
if ( cl->state != CS_ACTIVE ) {
continue;
}
qhedict_t* ent = cl->qh_edict;
// ZOID visibility tracking
if ( ent != clent &&
!( client->qh_spec_track && client->qh_spec_track - 1 == j ) ) {
if ( cl->qh_spectator ) {
continue;
}
// ignore if not touching a PV leaf
int i;
for ( i = 0; i < ent->num_leafs; i++ ) {
int l = CM_LeafCluster( ent->LeafNums[ i ] );
if ( pvs[ l >> 3 ] & ( 1 << ( l & 7 ) ) ) {
break;
}
}
if ( i == ent->num_leafs ) {
continue; // not visible
}
}
int pflags = QWPF_MSEC | QWPF_COMMAND;
if ( ent->v.modelindex != svqw_playermodel ) {
pflags |= QWPF_MODEL;
}
for ( int i = 0; i < 3; i++ ) {
if ( ent->GetVelocity()[ i ] ) {
pflags |= QWPF_VELOCITY1ND << i;
}
}
if ( ent->GetEffects() ) {
pflags |= QWPF_EFFECTS;
}
if ( ent->GetSkin() ) {
pflags |= QWPF_SKINNUM;
}
if ( ent->GetHealth() <= 0 ) {
pflags |= QWPF_DEAD;
}
if ( ent->GetMins()[ 2 ] != -24 ) {
pflags |= QWPF_GIB;
}
if ( cl->qh_spectator ) { // only sent origin and velocity to spectators
pflags &= QWPF_VELOCITY1ND | QWPF_VELOCITY2 | QWPF_VELOCITY3;
} else if ( ent == clent ) {// don't send a lot of data on personal entity
pflags &= ~( QWPF_MSEC | QWPF_COMMAND );
if ( ent->GetWeaponFrame() ) {
pflags |= QWPF_WEAPONFRAME;
}
}
if ( client->qh_spec_track && client->qh_spec_track - 1 == j &&
ent->GetWeaponFrame() ) {
pflags |= QWPF_WEAPONFRAME;
}
msg->WriteByte( qwsvc_playerinfo );
msg->WriteByte( j );
msg->WriteShort( pflags );
for ( int i = 0; i < 3; i++ ) {
msg->WriteCoord( ent->GetOrigin()[ i ] );
}
msg->WriteByte( ent->GetFrame() );
if ( pflags & QWPF_MSEC ) {
int msec = sv.qh_time - 1000 * cl->qh_localtime;
if ( msec > 255 ) {
msec = 255;
}
msg->WriteByte( msec );
}
if ( pflags & QWPF_COMMAND ) {
qwusercmd_t cmd = cl->qw_lastUsercmd;
if ( ent->GetHealth() <= 0 ) { // don't show the corpse looking around...
cmd.angles[ 0 ] = 0;
cmd.angles[ 1 ] = ent->GetAngles()[ 1 ];
cmd.angles[ 0 ] = 0;
}
cmd.buttons = 0; // never send buttons
cmd.impulse = 0; // never send impulses
qwusercmd_t nullcmd;
Com_Memset( &nullcmd, 0, sizeof ( nullcmd ) );
MSGQW_WriteDeltaUsercmd( msg, &nullcmd, &cmd );
}
for ( int i = 0; i < 3; i++ ) {
if ( pflags & ( QWPF_VELOCITY1ND << i ) ) {
msg->WriteShort( ent->GetVelocity()[ i ] );
}
}
if ( pflags & QWPF_MODEL ) {
msg->WriteByte( ent->v.modelindex );
}
if ( pflags & QWPF_SKINNUM ) {
msg->WriteByte( ent->GetSkin() );
}
if ( pflags & QWPF_EFFECTS ) {
msg->WriteByte( ent->GetEffects() );
}
if ( pflags & QWPF_WEAPONFRAME ) {
msg->WriteByte( ent->GetWeaponFrame() );
}
}
}
#ifdef MGNET
/*
=============
float cardioid_rating (qhedict_t *targ , qhedict_t *self)
Determines how important a visclient is- based on offset from
forward angle and distance. Resultant pattern is a somewhat
extended 3-dimensional cleaved cardioid with each point on
the surface being equal in priority(0) and increasing linearly
towards equal priority(1) along a straight line to the center.
=============
*/
static float cardioid_rating( qhedict_t* targ, qhedict_t* self ) {
vec3_t vec,spot1,spot2;
vec3_t forward,right,up;
float dot,dist;
AngleVectors( self->GetVAngle(),forward,right,up );
VectorAdd( self->GetOrigin(),self->GetViewOfs(),spot1 );
VectorSubtract( targ->v.absmax,targ->v.absmin,spot2 );
VectorMA( targ->v.absmin,0.5,spot2,spot2 );
VectorSubtract( spot2,spot1,vec );
dist = VectorNormalize( vec );
dot = DotProduct( vec,forward ); //from 1 to -1
if ( dot < -0.3 ) { //see only from -125 to 125 degrees
return false;
}
if ( dot > 0 ) {//to front of perpendicular plane to forward
dot *= 31; //much more distance leniency in front, max dist = 2048 directly in front
}
dot = ( dot + 1 ) * 64; //64 = base distance if along the perpendicular plane, max is 2048 straight ahead
if ( dist >= dot ) {//too far away for that angle to be important
return false;
}
//from 0.000000? to almost 1
return 1 - ( dist / dot ); //The higher this number is, the more important it is to send this ent
}
static int MAX_VISCLIENTS = 2;
#endif
static void SVHW_WritePlayersToClient( client_t* client, qhedict_t* clent, byte* pvs, QMsg* msg ) {
#ifdef MGNET
int k, l;
int visclient[ MAX_CLIENTS_QHW ];
int forcevisclient[ MAX_CLIENTS_QHW ];
int cl_v_priority[ MAX_CLIENTS_QHW ];
int cl_v_psort[ MAX_CLIENTS_QHW ];
int totalvc,num_eliminated;
int numvc = 0;
int forcevc = 0;
#endif
client_t* cl = svs.clients;
for ( int j = 0; j < MAX_CLIENTS_QHW; j++,cl++ ) {
if ( cl->state != CS_ACTIVE ) {
continue;
}
qhedict_t* ent = cl->qh_edict;
// ZOID visibility tracking
int invis_level = false;
if ( ent != clent &&
!( client->qh_spec_track && client->qh_spec_track - 1 == j ) ) {
if ( ( int )ent->GetEffects() & H2EF_NODRAW ) {
if ( hw_dmMode->value == HWDM_SIEGE && clent->GetPlayerClass() == CLASS_DWARF ) {
invis_level = false;
} else {
invis_level = true; //still can hear
}
}
#ifdef MGNET
//could be invisiblenow and still sent, cull out by other methods as well
if ( cl->qh_spectator )
#else
else if ( cl->qh_spectator )
#endif
{
invis_level = 2;//no vis or weaponsound
} else {
// ignore if not touching a PV leaf
int i;
for ( i = 0; i < ent->num_leafs; i++ ) {
int l = CM_LeafCluster( ent->LeafNums[ i ] );
if ( pvs[ l >> 3 ] & ( 1 << ( l & 7 ) ) ) {
break;
}
}
if ( i == ent->num_leafs ) {
invis_level = 2;//no vis or weaponsound
}
}
}
if ( invis_level == true ) {//ok to send weaponsound
if ( ent->GetWpnSound() ) {
msg->WriteByte( hwsvc_player_sound );
msg->WriteByte( j );
for ( int i = 0; i < 3; i++ ) {
msg->WriteCoord( ent->GetOrigin()[ i ] );
}
msg->WriteShort( ent->GetWpnSound() );
}
}
if ( invis_level > 0 ) {
continue;
}
#ifdef MGNET
if ( !cl->skipsend && ent != clent ) { //don't count self
visclient[ numvc ] = j;
numvc++;
} else { //Self, or Wasn't sent last time, must send this frame
cl->skipsend = false;
forcevisclient[ forcevc ] = j;
forcevc++;
continue;
}
}
totalvc = numvc + forcevc;
if ( totalvc > MAX_VISCLIENTS ) { //You have more than 5 clients in your view, cull some out
//prioritize by
//line of sight (20%)
//distance (50%)
//dot off v_forward (30%)
//put this in "priority" then sort by priority
//and send the highest priority
//number of highest priority sent depends on how
//many are forced through because they were skipped
//last send. Ideally, no more than 5 are sent.
for ( j = 0; j<numvc&& totalvc>MAX_VISCLIENTS; j++ ) { //priority 1 - if behind, cull out
for ( k = 0, cl = svs.clients; k < visclient[ j ]; k++, cl++ )
;
// cl=svs.clients+visclient[j];
ent = cl->edict;
cl_v_priority[ j ] = cardioid_rating( ent,clent );
if ( !cl_v_priority[ j ] ) {//% they won't be sent, l represents how many were forced through
cl->skipsend = true;
totalvc--;
}
}
if ( totalvc > MAX_VISCLIENTS ) { //still more than 5 inside cardioid, sort by priority
//and drop those after 5
//CHECK this make sure it works
for ( i = 0; i < numvc; i++ ) //do this as many times as there are visclients
for ( j = 0; j < numvc - 1 - i; j++ ) //go through the list
if ( cl_v_priority[ j ] < cl_v_priority[ j + 1 ] ) {
k = cl_v_psort[ j ]; //store lower one
cl_v_psort[ j ] = cl_v_psort[ j + 1 ]; //put next one in it's spot
cl_v_psort[ j + 1 ] = k; //put lower one next
}
num_eliminated = 0;
while ( totalvc > MAX_VISCLIENTS ) {//eliminate all over 5 unless not sent last time
if ( !cl->skipsend ) {
cl = svs.clients + cl_v_psort[ numvc - num_eliminated ];
cl->skipsend = true;
num_eliminated++;
totalvc--;
}
}
}
//Alternate Possibilities: ...?
//priority 2 - if too many numleafs away, cull out
//priority 3 - don't send those farthest away, flag for re-send next time
//priority 4 - flat percentage based on how many over 5
/* if(rand()%10<(numvc + l - 5))
{//% they won't be sent, l represents how many were forced through
cl->skipsend = true;
numvc--;
}*/
//priority 5 - send less info on clients
}
for ( j = 0, l = 0, k = 0, cl = svs.clients; j < MAX_CLIENTS_QHW; j++,cl++ ) {
//priority 1 - if behind, cull out
if ( forcevisclient[ l ] == j && l <= forcevc ) {
l++;
} else if ( visclient[ k ] == j && k <= numvc ) {
k++;//clent is always forced
} else {
continue; //not in PVS or forced
}
if ( cl->skipsend ) { //still 2 bytes, but what ya gonna do?
msg->WriteByte( hwsvc_playerskipped );
msg->WriteByte( j );
continue;
}
qhedict_t* ent = cl->edict;
#endif
int pflags = HWPF_MSEC | HWPF_COMMAND;
bool playermodel = false;
if ( ent->v.modelindex != svhw_playermodel[ 0 ] && //paladin
ent->v.modelindex != svhw_playermodel[ 1 ] && //crusader
ent->v.modelindex != svhw_playermodel[ 2 ] && //necro
ent->v.modelindex != svhw_playermodel[ 3 ] && //assassin
ent->v.modelindex != svhw_playermodel[ 4 ] && //succ
ent->v.modelindex != svhw_playermodel[ 5 ] ) { //dwarf
pflags |= HWPF_MODEL;
} else {
playermodel = true;
}
for ( int i = 0; i < 3; i++ ) {
if ( ent->GetVelocity()[ i ] ) {
pflags |= HWPF_VELOCITY1 << i;
}
}
if ( ( ( long )ent->GetEffects() & 0xff ) ) {
pflags |= HWPF_EFFECTS;
}
if ( ( ( long )ent->GetEffects() & 0xff00 ) ) {
pflags |= HWPF_EFFECTS2;
}
if ( ent->GetSkin() ) {
if ( hw_dmMode->value == HWDM_SIEGE && playermodel && ent->GetSkin() == 1 ) {
;
}
//in siege, don't send skin if 2nd skin and using
//playermodel, it will know on other side- saves
//us 1 byte per client per frame!
else {
pflags |= HWPF_SKINNUM;
}
}
if ( ent->GetHealth() <= 0 ) {
pflags |= HWPF_DEAD;
}
if ( ent->GetHull() == HWHULL_CROUCH ) {
pflags |= HWPF_CROUCH;
}
if ( cl->qh_spectator ) { // only sent origin and velocity to spectators
pflags &= HWPF_VELOCITY1 | HWPF_VELOCITY2 | HWPF_VELOCITY3;
} else if ( ent == clent ) {// don't send a lot of data on personal entity
pflags &= ~( HWPF_MSEC | HWPF_COMMAND );
if ( ent->GetWeaponFrame() ) {
pflags |= HWPF_WEAPONFRAME;
}
}
if ( ent->GetDrawFlags() ) {
pflags |= HWPF_DRAWFLAGS;
}
if ( ent->GetScale() != 0 && ent->GetScale() != 1.0 ) {
pflags |= HWPF_SCALE;
}
if ( ent->GetAbsLight() != 0 ) {
pflags |= HWPF_ABSLIGHT;
}
if ( ent->GetWpnSound() ) {
pflags |= HWPF_SOUND;
}
msg->WriteByte( hwsvc_playerinfo );
msg->WriteByte( j );
msg->WriteShort( pflags );
for ( int i = 0; i < 3; i++ ) {
msg->WriteCoord( ent->GetOrigin()[ i ] );
}
msg->WriteByte( ent->GetFrame() );
if ( pflags & HWPF_MSEC ) {
int msec = sv.qh_time - 1000 * cl->qh_localtime;
if ( msec > 255 ) {
msec = 255;
}
msg->WriteByte( msec );
}
if ( pflags & HWPF_COMMAND ) {
hwusercmd_t cmd = cl->hw_lastUsercmd;
if ( ent->GetHealth() <= 0 ) { // don't show the corpse looking around...
cmd.angles[ 0 ] = 0;
cmd.angles[ 1 ] = ent->GetAngles()[ 1 ];
cmd.angles[ 0 ] = 0;
}
cmd.buttons = 0; // never send buttons
cmd.impulse = 0; // never send impulses
MSGHW_WriteUsercmd( msg, &cmd, false );
}
for ( int i = 0; i < 3; i++ ) {
if ( pflags & ( HWPF_VELOCITY1 << i ) ) {
msg->WriteShort( ent->GetVelocity()[ i ] );
}
}
//rjr
if ( pflags & HWPF_MODEL ) {
msg->WriteShort( ent->v.modelindex );
}
if ( pflags & HWPF_SKINNUM ) {
msg->WriteByte( ent->GetSkin() );
}
if ( pflags & HWPF_EFFECTS ) {
msg->WriteByte( ( ( long )ent->GetEffects() & 0xff ) );
}
if ( pflags & HWPF_EFFECTS2 ) {
msg->WriteByte( ( ( long )ent->GetEffects() & 0xff00 ) >> 8 );
}
if ( pflags & HWPF_WEAPONFRAME ) {
msg->WriteByte( ent->GetWeaponFrame() );
}
if ( pflags & HWPF_DRAWFLAGS ) {
msg->WriteByte( ent->GetDrawFlags() );
}
if ( pflags & HWPF_SCALE ) {
msg->WriteByte( ( int )( ent->GetScale() * 100.0 ) & 255 );
}
if ( pflags & HWPF_ABSLIGHT ) {
msg->WriteByte( ( int )( ent->GetAbsLight() * 100.0 ) & 255 );
}
if ( pflags & HWPF_SOUND ) {
msg->WriteShort( ent->GetWpnSound() );
}
}
}
// Encodes the current state of the world as
// a qwsvc_packetentities messages and possibly
// a qwsvc_nails message and
// qwsvc_playerinfo messages
void SVQW_WriteEntitiesToClient( client_t* client, QMsg* msg ) {
// this is the frame we are creating
qwclient_frame_t* frame = &client->qw_frames[ client->netchan.incomingSequence & UPDATE_MASK_QW ];
// find the client's PVS
qhedict_t* clent = client->qh_edict;
vec3_t org;
VectorAdd( clent->GetOrigin(), clent->GetViewOfs(), org );
byte* pvs = SVQH_FatPVS( org );
// send over the players in the PVS
SVQW_WritePlayersToClient( client, clent, pvs, msg );
// put other visible entities into either a packet_entities or a nails message
qwpacket_entities_t* pack = &frame->entities;
pack->num_entities = 0;
numnails = 0;
qhedict_t* ent = QH_EDICT_NUM( MAX_CLIENTS_QHW + 1 );
for ( int e = MAX_CLIENTS_QHW + 1; e < sv.qh_num_edicts; e++, ent = NEXT_EDICT( ent ) ) {
// ignore ents without visible models
if ( !ent->v.modelindex || !*PR_GetString( ent->GetModel() ) ) {
continue;
}
// ignore if not touching a PV leaf
int i;
for ( i = 0; i < ent->num_leafs; i++ ) {
int l = CM_LeafCluster( ent->LeafNums[ i ] );
if ( pvs[ l >> 3 ] & ( 1 << ( l & 7 ) ) ) {
break;
}
}
if ( i == ent->num_leafs ) {
continue; // not visible
}
if ( SVQW_AddNailUpdate( ent ) ) {
continue; // added to the special update list
}
// add to the packetentities
if ( pack->num_entities == QWMAX_PACKET_ENTITIES ) {
continue; // all full
}
q1entity_state_t* state = &pack->entities[ pack->num_entities ];
pack->num_entities++;
state->number = e;
state->flags = 0;
VectorCopy( ent->GetOrigin(), state->origin );
VectorCopy( ent->GetAngles(), state->angles );
state->modelindex = ent->v.modelindex;
state->frame = ent->GetFrame();
state->colormap = ent->GetColorMap();
state->skinnum = ent->GetSkin();
state->effects = ent->GetEffects();
}
// encode the packet entities as a delta from the
// last packetentities acknowledged by the client
SVQW_EmitPacketEntities( client, pack, msg );
// now add the specialized nail update
SVQW_EmitNailUpdate( msg );
}
// Encodes the current state of the world as
// a hwsvc_packetentities messages and possibly
// a hwsvc_nails message and
// hwsvc_playerinfo messages
void SVHW_WriteEntitiesToClient( client_t* client, QMsg* msg ) {
// this is the frame we are creating
hwclient_frame_t* frame = &client->hw_frames[ client->netchan.incomingSequence & UPDATE_MASK_HW ];
// find the client's PVS
qhedict_t* clent = client->qh_edict;
vec3_t org;
VectorAdd( clent->GetOrigin(), clent->GetViewOfs(), org );
byte* pvs = SVQH_FatPVS( org );
// send over the players in the PVS
SVHW_WritePlayersToClient( client, clent, pvs, msg );
// put other visible entities into either a packet_entities or a nails message
hwpacket_entities_t* pack = &frame->entities;
pack->num_entities = 0;
nummissiles = 0;
numravens = 0;
numraven2s = 0;
qhedict_t* ent = QH_EDICT_NUM( MAX_CLIENTS_QHW + 1 );
for ( int e = MAX_CLIENTS_QHW + 1; e < sv.qh_num_edicts; e++, ent = NEXT_EDICT( ent ) ) {
// ignore ents without visible models
if ( !ent->v.modelindex || !*PR_GetString( ent->GetModel() ) ) {
continue;
}
if ( ( int )ent->GetEffects() & H2EF_NODRAW ) {
continue;
}
// ignore if not touching a PV leaf
int i;
for ( i = 0; i < ent->num_leafs; i++ ) {
int l = CM_LeafCluster( ent->LeafNums[ i ] );
if ( pvs[ l >> 3 ] & ( 1 << ( l & 7 ) ) ) {
break;
}
}
if ( i == ent->num_leafs ) {
continue; // not visible
}
if ( SVHW_AddMissileUpdate( ent ) ) {
continue; // added to the special update list
}
// add to the packetentities
if ( pack->num_entities == HWMAX_PACKET_ENTITIES ) {
continue; // all full
}
h2entity_state_t* state = &pack->entities[ pack->num_entities ];
pack->num_entities++;
state->number = e;
state->flags = 0;
VectorCopy( ent->GetOrigin(), state->origin );
VectorCopy( ent->GetAngles(), state->angles );
state->modelindex = ent->v.modelindex;
state->frame = ent->GetFrame();
state->colormap = ent->GetColorMap();
state->skinnum = ent->GetSkin();
state->effects = ent->GetEffects();
state->scale = ( int )( ent->GetScale() * 100.0 ) & 255;
state->drawflags = ent->GetDrawFlags();
state->abslight = ( int )( ent->GetAbsLight() * 255.0 ) & 255;
//clear sound so it doesn't send twice
state->wpn_sound = ent->GetWpnSound();
}
// encode the packet entities as a delta from the
// last packetentities acknowledged by the client
SVHW_EmitPacketEntities( client, pack, msg );
// now add the specialized nail update
SVHW_EmitPackedEntities( msg );
}
void SVHW_WriteInventory( client_t* host_client, qhedict_t* ent, QMsg* msg ) {
int sc1, sc2;
if ( host_client->h2_send_all_v ) {
sc1 = sc2 = 0xffffffff;
host_client->h2_send_all_v = false;
} else {
sc1 = sc2 = 0;
if ( ent->GetHealth() != host_client->h2_old_v.health ) {
sc1 |= SC1_HEALTH;
}
if ( ent->GetLevel() != host_client->h2_old_v.level ) {
sc1 |= SC1_LEVEL;
}
if ( ent->GetIntelligence() != host_client->h2_old_v.intelligence ) {
sc1 |= SC1_INTELLIGENCE;
}
if ( ent->GetWisdom() != host_client->h2_old_v.wisdom ) {
sc1 |= SC1_WISDOM;
}
if ( ent->GetStrength() != host_client->h2_old_v.strength ) {
sc1 |= SC1_STRENGTH;
}
if ( ent->GetDexterity() != host_client->h2_old_v.dexterity ) {
sc1 |= SC1_DEXTERITY;
}
if ( ent->GetTeleportTime() > sv.qh_time * 0.001f ) {
sc1 |= SC1_TELEPORT_TIME;
}
if ( ent->GetBlueMana() != host_client->h2_old_v.bluemana ) {
sc1 |= SC1_BLUEMANA;
}
if ( ent->GetGreenMana() != host_client->h2_old_v.greenmana ) {
sc1 |= SC1_GREENMANA;
}
if ( ent->GetExperience() != host_client->h2_old_v.experience ) {
sc1 |= SC1_EXPERIENCE;
}
if ( ent->GetCntTorch() != host_client->h2_old_v.cnt_torch ) {
sc1 |= SC1_CNT_TORCH;
}
if ( ent->GetCntHBoost() != host_client->h2_old_v.cnt_h_boost ) {
sc1 |= SC1_CNT_H_BOOST;
}
if ( ent->GetCntSHBoost() != host_client->h2_old_v.cnt_sh_boost ) {
sc1 |= SC1_CNT_SH_BOOST;
}
if ( ent->GetCntManaBoost() != host_client->h2_old_v.cnt_mana_boost ) {
sc1 |= SC1_CNT_MANA_BOOST;
}
if ( ent->GetCntTeleport() != host_client->h2_old_v.cnt_teleport ) {
sc1 |= SC1_CNT_TELEPORT;
}
if ( ent->GetCntTome() != host_client->h2_old_v.cnt_tome ) {
sc1 |= SC1_CNT_TOME;
}
if ( ent->GetCntSummon() != host_client->h2_old_v.cnt_summon ) {
sc1 |= SC1_CNT_SUMMON;
}
if ( ent->GetCntInvisibility() != host_client->h2_old_v.cnt_invisibility ) {
sc1 |= SC1_CNT_INVISIBILITY;
}
if ( ent->GetCntGlyph() != host_client->h2_old_v.cnt_glyph ) {
sc1 |= SC1_CNT_GLYPH;
}
if ( ent->GetCntHaste() != host_client->h2_old_v.cnt_haste ) {
sc1 |= SC1_CNT_HASTE;
}
if ( ent->GetCntBlast() != host_client->h2_old_v.cnt_blast ) {
sc1 |= SC1_CNT_BLAST;
}
if ( ent->GetCntPolyMorph() != host_client->h2_old_v.cnt_polymorph ) {
sc1 |= SC1_CNT_POLYMORPH;
}
if ( ent->GetCntFlight() != host_client->h2_old_v.cnt_flight ) {
sc1 |= SC1_CNT_FLIGHT;
}
if ( ent->GetCntCubeOfForce() != host_client->h2_old_v.cnt_cubeofforce ) {
sc1 |= SC1_CNT_CUBEOFFORCE;
}
if ( ent->GetCntInvincibility() != host_client->h2_old_v.cnt_invincibility ) {
sc1 |= SC1_CNT_INVINCIBILITY;
}
if ( ent->GetArtifactActive() != host_client->h2_old_v.artifact_active ) {
sc1 |= SC1_ARTIFACT_ACTIVE;
}
if ( ent->GetArtifactLow() != host_client->h2_old_v.artifact_low ) {
sc1 |= SC1_ARTIFACT_LOW;
}
if ( ent->GetMoveType() != host_client->h2_old_v.movetype ) {
sc1 |= SC1_MOVETYPE;
}
if ( ent->GetCameraMode() != host_client->h2_old_v.cameramode ) {
sc1 |= SC1_CAMERAMODE;
}
if ( ent->GetHasted() != host_client->h2_old_v.hasted ) {
sc1 |= SC1_HASTED;
}
if ( ent->GetInventory() != host_client->h2_old_v.inventory ) {
sc1 |= SC1_INVENTORY;
}
if ( ent->GetRingsActive() != host_client->h2_old_v.rings_active ) {
sc1 |= SC1_RINGS_ACTIVE;
}
if ( ent->GetRingsLow() != host_client->h2_old_v.rings_low ) {
sc2 |= SC2_RINGS_LOW;
}
if ( ent->GetArmorAmulet() != host_client->h2_old_v.armor_amulet ) {
sc2 |= SC2_AMULET;
}
if ( ent->GetArmorBracer() != host_client->h2_old_v.armor_bracer ) {
sc2 |= SC2_BRACER;
}
if ( ent->GetArmorBreastPlate() != host_client->h2_old_v.armor_breastplate ) {
sc2 |= SC2_BREASTPLATE;
}
if ( ent->GetArmorHelmet() != host_client->h2_old_v.armor_helmet ) {
sc2 |= SC2_HELMET;
}
if ( ent->GetRingFlight() != host_client->h2_old_v.ring_flight ) {
sc2 |= SC2_FLIGHT_T;
}
if ( ent->GetRingWater() != host_client->h2_old_v.ring_water ) {
sc2 |= SC2_WATER_T;
}
if ( ent->GetRingTurning() != host_client->h2_old_v.ring_turning ) {
sc2 |= SC2_TURNING_T;
}
if ( ent->GetRingRegeneration() != host_client->h2_old_v.ring_regeneration ) {
sc2 |= SC2_REGEN_T;
}
if ( ent->GetPuzzleInv1() != host_client->h2_old_v.puzzle_inv1 ) {
sc2 |= SC2_PUZZLE1;
}
if ( ent->GetPuzzleInv2() != host_client->h2_old_v.puzzle_inv2 ) {
sc2 |= SC2_PUZZLE2;
}
if ( ent->GetPuzzleInv3() != host_client->h2_old_v.puzzle_inv3 ) {
sc2 |= SC2_PUZZLE3;
}
if ( ent->GetPuzzleInv4() != host_client->h2_old_v.puzzle_inv4 ) {
sc2 |= SC2_PUZZLE4;
}
if ( ent->GetPuzzleInv5() != host_client->h2_old_v.puzzle_inv5 ) {
sc2 |= SC2_PUZZLE5;
}
if ( ent->GetPuzzleInv6() != host_client->h2_old_v.puzzle_inv6 ) {
sc2 |= SC2_PUZZLE6;
}
if ( ent->GetPuzzleInv7() != host_client->h2_old_v.puzzle_inv7 ) {
sc2 |= SC2_PUZZLE7;
}
if ( ent->GetPuzzleInv8() != host_client->h2_old_v.puzzle_inv8 ) {
sc2 |= SC2_PUZZLE8;
}
if ( ent->GetMaxHealth() != host_client->h2_old_v.max_health ) {
sc2 |= SC2_MAXHEALTH;
}
if ( ent->GetMaxMana() != host_client->h2_old_v.max_mana ) {
sc2 |= SC2_MAXMANA;
}
if ( ent->GetFlags() != host_client->h2_old_v.flags ) {
sc2 |= SC2_FLAGS;
}
}
byte test;
if ( !sc1 && !sc2 ) {
goto end;
}
msg->WriteByte( hwsvc_update_inv );
test = 0;
if ( sc1 & 0x000000ff ) {
test |= 1;
}
if ( sc1 & 0x0000ff00 ) {
test |= 2;
}
if ( sc1 & 0x00ff0000 ) {
test |= 4;
}
if ( sc1 & 0xff000000 ) {
test |= 8;
}
if ( sc2 & 0x000000ff ) {
test |= 16;
}
if ( sc2 & 0x0000ff00 ) {
test |= 32;
}
if ( sc2 & 0x00ff0000 ) {
test |= 64;
}
if ( sc2 & 0xff000000 ) {
test |= 128;
}
msg->WriteByte( test );
if ( test & 1 ) {
msg->WriteByte( sc1 & 0xff );
}
if ( test & 2 ) {
msg->WriteByte( ( sc1 >> 8 ) & 0xff );
}
if ( test & 4 ) {
msg->WriteByte( ( sc1 >> 16 ) & 0xff );
}
if ( test & 8 ) {
msg->WriteByte( ( sc1 >> 24 ) & 0xff );
}
if ( test & 16 ) {
msg->WriteByte( sc2 & 0xff );
}
if ( test & 32 ) {
msg->WriteByte( ( sc2 >> 8 ) & 0xff );
}
if ( test & 64 ) {
msg->WriteByte( ( sc2 >> 16 ) & 0xff );
}
if ( test & 128 ) {
msg->WriteByte( ( sc2 >> 24 ) & 0xff );
}
if ( sc1 & SC1_HEALTH ) {
msg->WriteShort( ent->GetHealth() );
}
if ( sc1 & SC1_LEVEL ) {
msg->WriteByte( ent->GetLevel() );
}
if ( sc1 & SC1_INTELLIGENCE ) {
msg->WriteByte( ent->GetIntelligence() );
}
if ( sc1 & SC1_WISDOM ) {
msg->WriteByte( ent->GetWisdom() );
}
if ( sc1 & SC1_STRENGTH ) {
msg->WriteByte( ent->GetStrength() );
}
if ( sc1 & SC1_DEXTERITY ) {
msg->WriteByte( ent->GetDexterity() );
}
if ( sc1 & SC1_BLUEMANA ) {
msg->WriteByte( ent->GetBlueMana() );
}
if ( sc1 & SC1_GREENMANA ) {
msg->WriteByte( ent->GetGreenMana() );
}
if ( sc1 & SC1_EXPERIENCE ) {
msg->WriteLong( ent->GetExperience() );
}
if ( sc1 & SC1_CNT_TORCH ) {
msg->WriteByte( ent->GetCntTorch() );
}
if ( sc1 & SC1_CNT_H_BOOST ) {
msg->WriteByte( ent->GetCntHBoost() );
}
if ( sc1 & SC1_CNT_SH_BOOST ) {
msg->WriteByte( ent->GetCntSHBoost() );
}
if ( sc1 & SC1_CNT_MANA_BOOST ) {
msg->WriteByte( ent->GetCntManaBoost() );
}
if ( sc1 & SC1_CNT_TELEPORT ) {
msg->WriteByte( ent->GetCntTeleport() );
}
if ( sc1 & SC1_CNT_TOME ) {
msg->WriteByte( ent->GetCntTome() );
}
if ( sc1 & SC1_CNT_SUMMON ) {
msg->WriteByte( ent->GetCntSummon() );
}
if ( sc1 & SC1_CNT_INVISIBILITY ) {
msg->WriteByte( ent->GetCntInvisibility() );
}
if ( sc1 & SC1_CNT_GLYPH ) {
msg->WriteByte( ent->GetCntGlyph() );
}
if ( sc1 & SC1_CNT_HASTE ) {
msg->WriteByte( ent->GetCntHaste() );
}
if ( sc1 & SC1_CNT_BLAST ) {
msg->WriteByte( ent->GetCntBlast() );
}
if ( sc1 & SC1_CNT_POLYMORPH ) {
msg->WriteByte( ent->GetCntPolyMorph() );
}
if ( sc1 & SC1_CNT_FLIGHT ) {
msg->WriteByte( ent->GetCntFlight() );
}
if ( sc1 & SC1_CNT_CUBEOFFORCE ) {
msg->WriteByte( ent->GetCntCubeOfForce() );
}
if ( sc1 & SC1_CNT_INVINCIBILITY ) {
msg->WriteByte( ent->GetCntInvincibility() );
}
if ( sc1 & SC1_ARTIFACT_ACTIVE ) {
msg->WriteByte( ent->GetArtifactActive() );
}
if ( sc1 & SC1_ARTIFACT_LOW ) {
msg->WriteByte( ent->GetArtifactLow() );
}
if ( sc1 & SC1_MOVETYPE ) {
msg->WriteByte( ent->GetMoveType() );
}
if ( sc1 & SC1_CAMERAMODE ) {
msg->WriteByte( ent->GetCameraMode() );
}
if ( sc1 & SC1_HASTED ) {
msg->WriteFloat( ent->GetHasted() );
}
if ( sc1 & SC1_INVENTORY ) {
msg->WriteByte( ent->GetInventory() );
}
if ( sc1 & SC1_RINGS_ACTIVE ) {
msg->WriteByte( ent->GetRingsActive() );
}
if ( sc2 & SC2_RINGS_LOW ) {
msg->WriteByte( ent->GetRingsLow() );
}
if ( sc2 & SC2_AMULET ) {
msg->WriteByte( ent->GetArmorAmulet() );
}
if ( sc2 & SC2_BRACER ) {
msg->WriteByte( ent->GetArmorBracer() );
}
if ( sc2 & SC2_BREASTPLATE ) {
msg->WriteByte( ent->GetArmorBreastPlate() );
}
if ( sc2 & SC2_HELMET ) {
msg->WriteByte( ent->GetArmorHelmet() );
}
if ( sc2 & SC2_FLIGHT_T ) {
msg->WriteByte( ent->GetRingFlight() );
}
if ( sc2 & SC2_WATER_T ) {
msg->WriteByte( ent->GetRingWater() );
}
if ( sc2 & SC2_TURNING_T ) {
msg->WriteByte( ent->GetRingTurning() );
}
if ( sc2 & SC2_REGEN_T ) {
msg->WriteByte( ent->GetRingRegeneration() );
}
if ( sc2 & SC2_PUZZLE1 ) {
msg->WriteString2( PR_GetString( ent->GetPuzzleInv1() ) );
}
if ( sc2 & SC2_PUZZLE2 ) {
msg->WriteString2( PR_GetString( ent->GetPuzzleInv2() ) );
}
if ( sc2 & SC2_PUZZLE3 ) {
msg->WriteString2( PR_GetString( ent->GetPuzzleInv3() ) );
}
if ( sc2 & SC2_PUZZLE4 ) {
msg->WriteString2( PR_GetString( ent->GetPuzzleInv4() ) );
}
if ( sc2 & SC2_PUZZLE5 ) {
msg->WriteString2( PR_GetString( ent->GetPuzzleInv5() ) );
}
if ( sc2 & SC2_PUZZLE6 ) {
msg->WriteString2( PR_GetString( ent->GetPuzzleInv6() ) );
}
if ( sc2 & SC2_PUZZLE7 ) {
msg->WriteString2( PR_GetString( ent->GetPuzzleInv7() ) );
}
if ( sc2 & SC2_PUZZLE8 ) {
msg->WriteString2( PR_GetString( ent->GetPuzzleInv8() ) );
}
if ( sc2 & SC2_MAXHEALTH ) {
msg->WriteShort( ent->GetMaxHealth() );
}
if ( sc2 & SC2_MAXMANA ) {
msg->WriteByte( ent->GetMaxMana() );
}
if ( sc2 & SC2_FLAGS ) {
msg->WriteFloat( ent->GetFlags() );
}
end:
host_client->h2_old_v.movetype = ent->GetMoveType();
host_client->h2_old_v.health = ent->GetHealth();
host_client->h2_old_v.max_health = ent->GetMaxHealth();
host_client->h2_old_v.bluemana = ent->GetBlueMana();
host_client->h2_old_v.greenmana = ent->GetGreenMana();
host_client->h2_old_v.max_mana = ent->GetMaxMana();
host_client->h2_old_v.armor_amulet = ent->GetArmorAmulet();
host_client->h2_old_v.armor_bracer = ent->GetArmorBracer();
host_client->h2_old_v.armor_breastplate = ent->GetArmorBreastPlate();
host_client->h2_old_v.armor_helmet = ent->GetArmorHelmet();
host_client->h2_old_v.level = ent->GetLevel();
host_client->h2_old_v.intelligence = ent->GetIntelligence();
host_client->h2_old_v.wisdom = ent->GetWisdom();
host_client->h2_old_v.dexterity = ent->GetDexterity();
host_client->h2_old_v.strength = ent->GetStrength();
host_client->h2_old_v.experience = ent->GetExperience();
host_client->h2_old_v.ring_flight = ent->GetRingFlight();
host_client->h2_old_v.ring_water = ent->GetRingWater();
host_client->h2_old_v.ring_turning = ent->GetRingTurning();
host_client->h2_old_v.ring_regeneration = ent->GetRingRegeneration();
host_client->h2_old_v.puzzle_inv1 = ent->GetPuzzleInv1();
host_client->h2_old_v.puzzle_inv2 = ent->GetPuzzleInv2();
host_client->h2_old_v.puzzle_inv3 = ent->GetPuzzleInv3();
host_client->h2_old_v.puzzle_inv4 = ent->GetPuzzleInv4();
host_client->h2_old_v.puzzle_inv5 = ent->GetPuzzleInv5();
host_client->h2_old_v.puzzle_inv6 = ent->GetPuzzleInv6();
host_client->h2_old_v.puzzle_inv7 = ent->GetPuzzleInv7();
host_client->h2_old_v.puzzle_inv8 = ent->GetPuzzleInv8();
host_client->h2_old_v.flags = ent->GetFlags();
host_client->h2_old_v.flags2 = ent->GetFlags2();
host_client->h2_old_v.rings_active = ent->GetRingsActive();
host_client->h2_old_v.rings_low = ent->GetRingsLow();
host_client->h2_old_v.artifact_active = ent->GetArtifactActive();
host_client->h2_old_v.artifact_low = ent->GetArtifactLow();
host_client->h2_old_v.hasted = ent->GetHasted();
host_client->h2_old_v.inventory = ent->GetInventory();
host_client->h2_old_v.cnt_torch = ent->GetCntTorch();
host_client->h2_old_v.cnt_h_boost = ent->GetCntHBoost();
host_client->h2_old_v.cnt_sh_boost = ent->GetCntSHBoost();
host_client->h2_old_v.cnt_mana_boost = ent->GetCntManaBoost();
host_client->h2_old_v.cnt_teleport = ent->GetCntTeleport();
host_client->h2_old_v.cnt_tome = ent->GetCntTome();
host_client->h2_old_v.cnt_summon = ent->GetCntSummon();
host_client->h2_old_v.cnt_invisibility = ent->GetCntInvisibility();
host_client->h2_old_v.cnt_glyph = ent->GetCntGlyph();
host_client->h2_old_v.cnt_haste = ent->GetCntHaste();
host_client->h2_old_v.cnt_blast = ent->GetCntBlast();
host_client->h2_old_v.cnt_polymorph = ent->GetCntPolyMorph();
host_client->h2_old_v.cnt_flight = ent->GetCntFlight();
host_client->h2_old_v.cnt_cubeofforce = ent->GetCntCubeOfForce();
host_client->h2_old_v.cnt_invincibility = ent->GetCntInvincibility();
host_client->h2_old_v.cameramode = ent->GetCameraMode();
}
|
#include "SDL/SDL.h"
#include "SDL_image/SDL_image.h"
#include "SDL_rotozoom.h"
#include <string>
#include "global.h"
#include <math.h>
class Tile{
protected:
axis base;
SDL_Surface *tile;
int direction;
public:
Tile(){}
Tile(std::string filename, axis base, int direction);
void show(SDL_Surface * track);
virtual int surface_check(axis cor){ return 2;}
};
class Straight : public Tile{
public:
Straight(){}
Straight(std::string filename, axis base, int direction): Tile(filename, base, direction){}
virtual int surface_check(axis cor);
};
class Corner : public Tile{
public:
Corner(){}
Corner(std::string filename, axis base, int direction): Tile(filename, base, direction){}
virtual int surface_check(axis cor);
};
Tile::Tile(std::string filename, axis _base,int _direction){
direction = _direction;
base = _base;
tile = load_image(filename);
tile = rotozoomSurface(tile, direction, 1, 0);
}
void Tile::show(SDL_Surface * track){
if(direction == 90)
apply_surface(base.x, base.y-1, tile, track);
else if(direction == 180)
apply_surface(base.x-2, base.y-2, tile, track);
else if(direction == 270)
apply_surface(base.x-2, base.y-2, tile, track);
apply_surface(base.x, base.y, tile, track);
}
int Straight::surface_check( axis cor){
int t = 0;
if(direction%180 == 0)
t = cor.x - base.x;
else if(direction % 180 == 90)
t = cor.y - base.y;
if( t> 30 && t< 130)
return 2; //ontrack
else if( t> 20 && t< 140)
return 1; //on grass
else
return 0; //hit wall
}
int Corner::surface_check( axis cor){
axis apex;
apex.x = base.x;
apex.y = base.y;
if(direction == 0){
apex.x += 160;
apex.y += 160;
}
else if(direction == 90){
apex.x += 160;
}
else if(direction == 270){
apex.y += 160;
}
double t;
t = sqrt((cor.x-apex.x)*(cor.x-apex.x)+(cor.y-apex.y)*(cor.y-apex.y));
if( t> 30 && t< 130)
return 2; //ontrack
else if( t> 20 && t< 145)
return 1; //on grass
else
return 0; //hit wall
}
|
#include "TestScanManagement.h"
#include "TestDataFile.h"
#include "../EngineLayer/CommonParameters.h"
#include "../TaskLayer/MetaMorpheusTask.h"
#include "../EngineLayer/Ms2ScanWithSpecificMass.h"
using namespace EngineLayer;
using namespace MassSpectrometry;
using namespace MzLibUtil;
using namespace NUnit::Framework;
using namespace TaskLayer;
namespace Test
{
void TestScanManagement::TestGetCombinedMs2Scans()
{
auto myMsDataFile = new TestDataFile(5);
bool DoPrecursorDeconvolution = true;
bool UseProvidedPrecursorInfo = true;
double DeconvolutionIntensityRatio = 4;
int DeconvolutionMaxAssumedChargeState = 10;
Tolerance *DeconvolutionMassTolerance = new PpmTolerance(5);
CommonParameters tempVar();
auto listOfSortedms2Scans = MetaMorpheusTask::GetMs2Scans(myMsDataFile, L"", &tempVar).OrderBy([&] (std::any b)
{
b::PrecursorMass;
})->ToArray();
//Write prime code to combine MS2MS3
std::unordered_map<int, double> listOfScanPrecusor;
std::vector<MsDataScan*> ListOfSortedMsScans;
std::vector<Ms2ScanWithSpecificMass*> test;
for (auto ms2scan : myMsDataFile->GetAllScansList().Where([&] (std::any x)
{
delete DeconvolutionMassTolerance;
//C# TO C++ CONVERTER TODO TASK: A 'delete myMsDataFile' statement was not added since myMsDataFile was passed to a method or constructor. Handle memory management manually.
return x::MsnOrder != 1;
}))
{
if (ms2scan->MsnOrder == 2 && !listOfScanPrecusor.Contains(KeyValuePair<int, double>(ms2scan::OneBasedPrecursorScanNumber->Value, ms2scan::SelectedIonMZ->Value)))
{
if (ms2scan::OneBasedPrecursorScanNumber.HasValue)
{
listOfScanPrecusor.emplace(ms2scan::OneBasedPrecursorScanNumber->Value, ms2scan::SelectedIonMZ->Value);
std::vector<int> currentScanMS2OneBasedScanNumber;
currentScanMS2OneBasedScanNumber.push_back(ms2scan::OneBasedScanNumber);
auto mz2 = ms2scan::MassSpectrum::XArray::ToList();
auto intensities2 = ms2scan::MassSpectrum::YArray::ToList();
for (int i = 1; i < 7; i++)
{
if (ms2scan::OneBasedScanNumber + i <= myMsDataFile->NumSpectra)
{
auto x = myMsDataFile->GetOneBasedScan(ms2scan::OneBasedScanNumber + i);
//var x = myMsDataFile.OfType<IMsDataScanWithPrecursor<IMzSpectrum<IMzPeak>>>().ElementAt(i);
if (x->MsnOrder == 2 && x->SelectedIonMZ == ms2scan::SelectedIonMZ)
{
currentScanMS2OneBasedScanNumber.push_back(x->OneBasedScanNumber);
mz2.AddRange(x->MassSpectrum.XArray.ToList());
intensities2.AddRange(x->MassSpectrum.YArray.ToList());
}
if (x->MsnOrder == 3 && std::find(currentScanMS2OneBasedScanNumber.begin(), currentScanMS2OneBasedScanNumber.end(), x->OneBasedPrecursorScanNumber->Value) != currentScanMS2OneBasedScanNumber.end())
{
mz2.AddRange(x->MassSpectrum.XArray.ToList());
intensities2.AddRange(x->MassSpectrum.YArray.ToList());
}
}
}
auto MassSpectrum2 = new MzSpectrum(mz2.ToArray(), intensities2.ToArray(), false);
MsDataScan tempVar2(MassSpectrum2, ms2scan::OneBasedScanNumber, ms2scan::MsnOrder, ms2scan::IsCentroid, Polarity::Positive, ms2scan::RetentionTime, ms2scan::ScanWindowRange, ms2scan::ScanFilter, ms2scan::MzAnalyzer, ms2scan::TotalIonCurrent, ms2scan::InjectionTime, nullptr, L"", ms2scan::SelectedIonMZ, ms2scan::SelectedIonChargeStateGuess, ms2scan::SelectedIonIntensity, ms2scan::IsolationMz, nullptr, ms2scan::DissociationType, ms2scan::OneBasedPrecursorScanNumber, ms2scan::SelectedIonMonoisotopicGuessMz);
ListOfSortedMsScans.push_back(&tempVar2);
//C# TO C++ CONVERTER TODO TASK: A 'delete MassSpectrum2' statement was not added since MassSpectrum2 was passed to a method or constructor. Handle memory management manually.
}
}
}
for (auto ms2scan : ListOfSortedMsScans.Where([&] (std::any x)
{
delete DeconvolutionMassTolerance;
//C# TO C++ CONVERTER TODO TASK: A 'delete myMsDataFile' statement was not added since myMsDataFile was passed to a method or constructor. Handle memory management manually.
return x::MsnOrder != 1;
}))
{
Ms2ScanWithSpecificMass tempVar3(ms2scan, ms2scan::SelectedIonMonoisotopicGuessMz->Value, ms2scan::SelectedIonChargeStateGuess->Value, L"", new CommonParameters());
test.push_back(&tempVar3);
}
auto testToArray = test.OrderBy([&] (std::any b)
{
b::PrecursorMass;
})->ToArray();
//Using function to combine MS2MS3
//var listOfSortedms2Scans2 = MetaMorpheusTask.GetCombinedMs2Scans(myMsDataFile, null, DoPrecursorDeconvolution, UseProvidedPrecursorInfo, DeconvolutionIntensityRatio, DeconvolutionMaxAssumedChargeState, DeconvolutionMassTolerance).OrderBy(b => b.PrecursorMass).ToArray();
//Assert.AreEqual(5, myMsDataFile.NumSpectra);
//Assert.AreEqual(1, listOfSortedms2Scans2.Count());
delete DeconvolutionMassTolerance;
//C# TO C++ CONVERTER TODO TASK: A 'delete myMsDataFile' statement was not added since myMsDataFile was passed to a method or constructor. Handle memory management manually.
}
}
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <memory>
#include "Settings.h"
#include "Application.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void displayXY(uint plotId, float x, float y);
private slots:
void on_seqNumSpinBox_valueChanged(int newValue);
void on_plotTrajectoryButton_clicked();
void on_clearPlotsButton_clicked();
void on_scatterPlotRadioButton_clicked();
void on_linePlotRadioButton_clicked();
void on_orientationCheckBox_clicked(bool checked);
void on_fixedSourceCheckBox_clicked(bool checked);
void on_fixedTargetCheckBox_clicked(bool checked);
signals:
void plotTypeChanged(PlotType);
void orientationEnabled(bool);
void fixedTargetSelected(bool);
void fixedSourceSelected(bool);
private:
Ui::MainWindow * _ui;
std::unique_ptr<Application> _application; ///< The main application
};
#endif // MAINWINDOW_H
|
/*!
* \file
* \author David Saxon
* \brief Inline definitions for UTF-8 implementations of the
* compute_byte_length function.
*
* \copyright Copyright (c) 2018, The Arcane Initiative
* All rights reserved.
*
* \license BSD 3-Clause License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder 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 DEUS_UNICODEVIEWIMPL_UTF8COMPUTEBYTELENGTH_INL_
#define DEUS_UNICODEVIEWIMPL_UTF8COMPUTEBYTELENGTH_INL_
#include <cstring>
namespace deus
{
DEUS_VERSION_NS_BEGIN
namespace utf8_inl
{
DEUS_FORCE_INLINE void compute_byte_length_naive(
const char* in_data,
std::size_t& out_byte_length)
{
out_byte_length = 0;
for(const char* c = in_data; (*c) != '\0'; ++c, ++out_byte_length);
// final increment for null pointer
++out_byte_length;
}
DEUS_FORCE_INLINE void compute_byte_length_strlen(
const char* in_data,
std::size_t& out_byte_length)
{
out_byte_length = 0;
out_byte_length = strlen(in_data) + 1;
}
} // namespace utf8_inl
DEUS_VERSION_NS_END
} // namespace deus
#endif
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <cstring>
#include <queue>
#include <sstream>
using namespace std;
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
/*
思路1:
因为是单链表,所以从第一个公共节点之后都是两个链表共享的节点,两个链表会有相同的结尾节点。
先获取两个链表各自的长度,然后获取长度的差值。
*/
class Solution {
public:
int getLen(ListNode* p){
int len = 0;
while(p != NULL){
++len;
p = p->next;
} return len;
}
ListNode* FindFirstCommonNode( ListNode* p1, ListNode* p2) {
int len1 = getLen(p1), len2 = getLen(p2);
if(len1 > len2){
swap(len1, len2);
swap(p1, p2);
}
int diff = len2-len1;
while(diff--){
p2 = p2->next;
}
while(p1 != p2){
p1 = p1->next;
p2 = p2->next;
} return p1;
}
};
/*
思路2:
哈希法,用哈希表记录链表p1节点
返回遍历p2时遇到的第一个哈希表中保存的节点
*/
/*
参考牛客网链接:https://www.nowcoder.com/questionTerminal/6ab1d9a29e88450685099d45c9e31e46
思路3:
记链表L1的长度为 a+c, 链表L2的长度为b+c, 两个链表的公共节点的长度为c.
如果每次遍历一个链表到结尾NULL时改去遍历另一个链表。就类似于把两个链表拼接起来,变成(L1+L2)与(L2+L1)
那么两个遍历的指针会在遍历a+b+c个节点之后相遇。
缺陷:如果有循环链表,该方法无效是个死循环。
验证:
(1) 两个链表长度不同有公共交点:可以在第二次遍历返回正确结果.
(2) 两个链表长度相同有公共交点: 可以在第一次遍历返回正确结果
(3) 两个链表没有公共交点,长度相同:第一遍返回NULL.
(4) 两个链表没有公共交点,长度不同: ? 貌似是走一个最小公倍数之后停在NULL处返回
(4) 空链表的影响
*/
/*
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode *pHead1, ListNode *pHead2) {
ListNode *p1 = pHead1;
ListNode *p2 = pHead2;
while(p1!=p2){
p1 = (p1==NULL ? pHead2 : p1->next);
p2 = (p2==NULL ? pHead1 : p2->next);
}
return p1;
}
};
*/
int main(){
return 0;
}
|
/**
* 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 {
public:
void inorderTraverse(TreeNode * root, int k, int &count, int &res) {
if(root == nullptr) return;
// if I increase count here, count will ony remember the number of node other than the order
inorderTraverse(root -> left, k, count, res);
// Count must be added here, since count is used to remember the order instead of the number of node
count++;
if(count == k) {
res = root -> val;
}
inorderTraverse(root -> right, k, count,res);
}
int kthSmallest(TreeNode* root, int k) {
int res = INT_MIN;
int count = 0;
inorderTraverse(root, k, count, res);
return res;
}
};
|
#include "NumberOne.h"
#include "../../Components/Activator.h"
#include "../../Components/AirFreshener.h"
#include "../../Components/LightSensor.h"
#include "../../Components/RGBLED.h"
#include "../../Utilities/Time.h"
#include "../../Program.h"
#include "InUse.h"
namespace Stickuino {
namespace States {
namespace Normal {
NumberOne::NumberOne(
Components::AirFreshener& airFreshener,
Components::LightSensor& lightSensor,
Components::Activator& motionSensor,
Components::RGBLED& statusLED
) :
State("#1"),
airFreshener_(airFreshener),
lightSensor_(lightSensor),
motionSensor_(motionSensor),
statusLED_(statusLED) {
}
void NumberOne::preLoop(volatile int& interrupt) {
// Detect activity
// If there is activity, reset the counter
if (motionSensor_.isActive()) {
lastActivity_ = millis();
}
// Check if usage stopped, which is when there has been no activity for 15 seconds, the lights turned off or the door opened
if (Utilities::Time::calculateDuration(lastActivity_) >= 15000 || lightSensor_.getLightValue() < 200 || interrupt == 1) {
// Reset interrupt
if (interrupt == 1) {
interrupt = -1;
}
program.setStatus("End #1");
airFreshener_.spray(1);
static_cast<InUse*>(getParent())->exit();
}
}
void NumberOne::enabled() {
program.setStatus("Start #1");
// Reset variables
lastActivity_ = millis();
// Set status LED
statusLED_.setRGB(255, 165, 0); // Orange
}
}
}
}
|
/* ============================================================================
* Copyright (c) 2009-2016 BlueQuartz Software, LLC
*
* 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 BlueQuartz Software, the US Air Force, 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.
*
* The code contained herein was partially funded by the followig contracts:
* United States Air Force Prime Contract FA8650-07-D-5800
* United States Air Force Prime Contract FA8650-10-D-5210
* United States Prime Contract Navy N00173-07-C-2068
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#pragma once
#include "SIMPLib/Common/SIMPLibSetGetMacros.h"
#include "SIMPLib/Filtering/AbstractFilter.h"
#include "SIMPLib/Filtering/ComparisonInputsAdvanced.h"
#include "SIMPLib/Filtering/ComparisonSet.h"
#include "SIMPLib/Filtering/ComparisonValue.h"
#include "SIMPLib/SIMPLib.h"
/**
* @brief The MultiThresholdObjects2 class. See [Filter documentation](@ref multithresholdobjects2) for details.
*/
class SIMPLib_EXPORT MultiThresholdObjects2 : public AbstractFilter
{
Q_OBJECT
PYB11_CREATE_BINDINGS(MultiThresholdObjects2 SUPERCLASS AbstractFilter)
PYB11_PROPERTY(QString DestinationArrayName READ getDestinationArrayName WRITE setDestinationArrayName)
PYB11_PROPERTY(ComparisonInputsAdvanced SelectedThresholds READ getSelectedThresholds WRITE setSelectedThresholds)
public:
SIMPL_SHARED_POINTERS(MultiThresholdObjects2)
SIMPL_FILTER_NEW_MACRO(MultiThresholdObjects2)
SIMPL_TYPE_MACRO_SUPER_OVERRIDE(MultiThresholdObjects2, AbstractFilter)
~MultiThresholdObjects2() override;
SIMPL_FILTER_PARAMETER(QString, DestinationArrayName)
Q_PROPERTY(QString DestinationArrayName READ getDestinationArrayName WRITE setDestinationArrayName)
SIMPL_FILTER_PARAMETER(ComparisonInputsAdvanced, SelectedThresholds)
Q_PROPERTY(ComparisonInputsAdvanced SelectedThresholds READ getSelectedThresholds WRITE setSelectedThresholds)
/**
* @brief getCompiledLibraryName Reimplemented from @see AbstractFilter class
*/
const QString getCompiledLibraryName() const override;
/**
* @brief getBrandingString Returns the branding string for the filter, which is a tag
* used to denote the filter's association with specific plugins
* @return Branding string
*/
const QString getBrandingString() const override;
/**
* @brief getFilterVersion Returns a version string for this filter. Default
* value is an empty string.
* @return
*/
const QString getFilterVersion() const override;
/**
* @brief newFilterInstance Reimplemented from @see AbstractFilter class
*/
AbstractFilter::Pointer newFilterInstance(bool copyFilterParameters) const override;
/**
* @brief getGroupName Reimplemented from @see AbstractFilter class
*/
const QString getGroupName() const override;
/**
* @brief getSubGroupName Reimplemented from @see AbstractFilter class
*/
const QString getSubGroupName() const override;
/**
* @brief getUuid Return the unique identifier for this filter.
* @return A QUuid object.
*/
const QUuid getUuid() override;
/**
* @brief getHumanLabel Reimplemented from @see AbstractFilter class
*/
const QString getHumanLabel() const override;
/**
* @brief setupFilterParameters Reimplemented from @see AbstractFilter class
*/
void setupFilterParameters() override;
/**
* @brief readFilterParameters Reimplemented from @see AbstractFilter class
*/
void readFilterParameters(AbstractFilterParametersReader* reader, int index) override;
/**
* @brief execute Reimplemented from @see AbstractFilter class
*/
void execute() override;
/**
* @brief preflight Reimplemented from @see AbstractFilter class
*/
void preflight() override;
signals:
/**
* @brief updateFilterParameters Emitted when the Filter requests all the latest Filter parameters
* be pushed from a user-facing control (such as a widget)
* @param filter Filter instance pointer
*/
void updateFilterParameters(AbstractFilter* filter);
/**
* @brief parametersChanged Emitted when any Filter parameter is changed internally
*/
void parametersChanged();
/**
* @brief preflightAboutToExecute Emitted just before calling dataCheck()
*/
void preflightAboutToExecute();
/**
* @brief preflightExecuted Emitted just after calling dataCheck()
*/
void preflightExecuted();
protected:
MultiThresholdObjects2();
/**
* @brief dataCheck Checks for the appropriate parameter values and availability of arrays
*/
void dataCheck();
/**
* @brief Initializes all the private instance variables.
*/
void initialize();
/**
* @brief Creates and returns a DataArray<bool> for the given AttributeMatrix and the number of tuples
*/
void createBoolArray(int64_t& numItems, BoolArrayType::Pointer& thresholdArrayPtr);
/**
* @brief Merges two DataArray<bool>s of a given size using a union operator AND / OR and inverts the second DataArray if requested
* @param numItems Number of values in both DataArrays
* @param currentArray DataArray<bool> to merge values into
* @param unionOperator Union operator used to merge into currentArray
* @param newArray DataArray<bool> of values to merge into the currentArray
* @param inverse Should newArray have its boolean values flipped before being merged in
*/
void insertThreshold(int64_t numItems, BoolArrayType::Pointer currentArray, int unionOperator, const BoolArrayType::Pointer newArray, bool inverse);
/**
* @brief Flips the boolean values for a DataArray<bool>
* @param numItems Number of tuples in the DataArray
* @param thresholdArray DataArray to invert
*/
void invertThreshold(int64_t numItems, BoolArrayType::Pointer thresholdArray);
/**
* @brief Performs a check on a ComparisonSet and either merges the result into the DataArray passed in or replaces the DataArray
* @param comparisonSet The set of comparisons used for setting the threshold
* @param inputThreshold DataArray<bool> merged into or replaced after finding the ComparisonSet's threshould output
* @param err Return any error code given
* @param replaceInput Specifies whether or not the result gets merged into inputThreshold or replaces it
* @param inverse Specifies whether or not the results need to be flipped before merging or replacing inputThreshold
*/
void thresholdSet(ComparisonSet::Pointer comparisonSet, BoolArrayType::Pointer& inputThreshold, int32_t& err, bool replaceInput = false, bool inverse = false);
/**
* @brief Performs a check on a single ComparisonValue and either merges the result into the DataArray passed in or replaces the DataArray
* @param comparisonValue The comparison operator and value used for caluculating the threshold
* @param inputThreshold DataArray<bool> merged into or replaced after finding the ComparisonSet's threshould output
* @param err Return any error code given
* @param replaceInput Specifies whether or not the result gets merged into inputThreshold or replaces it
* @param inverse Specifies whether or not the results need to be flipped before merging or replacing inputThreshold
*/
void thresholdValue(ComparisonValue::Pointer comparisonValue, BoolArrayType::Pointer& inputThreshold, int32_t& err, bool replaceInput = false, bool inverse = false);
private:
DEFINE_DATAARRAY_VARIABLE(bool, Destination)
public:
MultiThresholdObjects2(const MultiThresholdObjects2&) = delete; // Copy Constructor Not Implemented
MultiThresholdObjects2(MultiThresholdObjects2&&) = delete; // Move Constructor Not Implemented
MultiThresholdObjects2& operator=(const MultiThresholdObjects2&) = delete; // Copy Assignment Not Implemented
MultiThresholdObjects2& operator=(MultiThresholdObjects2&&) = delete; // Move Assignment Not Implemented
};
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Web::Http {
struct HttpProgress;
}
namespace Windows::Web::Http {
struct HttpProgress;
}
namespace ABI::Windows::Web::Http {
struct IHttpBufferContentFactory;
struct IHttpClient;
struct IHttpClientFactory;
struct IHttpContent;
struct IHttpCookie;
struct IHttpCookieFactory;
struct IHttpCookieManager;
struct IHttpFormUrlEncodedContentFactory;
struct IHttpMethod;
struct IHttpMethodFactory;
struct IHttpMethodStatics;
struct IHttpMultipartContent;
struct IHttpMultipartContentFactory;
struct IHttpMultipartFormDataContent;
struct IHttpMultipartFormDataContentFactory;
struct IHttpRequestMessage;
struct IHttpRequestMessageFactory;
struct IHttpResponseMessage;
struct IHttpResponseMessageFactory;
struct IHttpStreamContentFactory;
struct IHttpStringContentFactory;
struct IHttpTransportInformation;
struct HttpBufferContent;
struct HttpClient;
struct HttpCookie;
struct HttpCookieCollection;
struct HttpCookieManager;
struct HttpFormUrlEncodedContent;
struct HttpMethod;
struct HttpMultipartContent;
struct HttpMultipartFormDataContent;
struct HttpRequestMessage;
struct HttpResponseMessage;
struct HttpStreamContent;
struct HttpStringContent;
struct HttpTransportInformation;
}
namespace Windows::Web::Http {
struct IHttpBufferContentFactory;
struct IHttpClient;
struct IHttpClientFactory;
struct IHttpContent;
struct IHttpCookie;
struct IHttpCookieFactory;
struct IHttpCookieManager;
struct IHttpFormUrlEncodedContentFactory;
struct IHttpMethod;
struct IHttpMethodFactory;
struct IHttpMethodStatics;
struct IHttpMultipartContent;
struct IHttpMultipartContentFactory;
struct IHttpMultipartFormDataContent;
struct IHttpMultipartFormDataContentFactory;
struct IHttpRequestMessage;
struct IHttpRequestMessageFactory;
struct IHttpResponseMessage;
struct IHttpResponseMessageFactory;
struct IHttpStreamContentFactory;
struct IHttpStringContentFactory;
struct IHttpTransportInformation;
struct HttpBufferContent;
struct HttpClient;
struct HttpCookie;
struct HttpCookieCollection;
struct HttpCookieManager;
struct HttpFormUrlEncodedContent;
struct HttpMethod;
struct HttpMultipartContent;
struct HttpMultipartFormDataContent;
struct HttpRequestMessage;
struct HttpResponseMessage;
struct HttpStreamContent;
struct HttpStringContent;
struct HttpTransportInformation;
}
namespace Windows::Web::Http {
template <typename T> struct impl_IHttpBufferContentFactory;
template <typename T> struct impl_IHttpClient;
template <typename T> struct impl_IHttpClientFactory;
template <typename T> struct impl_IHttpContent;
template <typename T> struct impl_IHttpCookie;
template <typename T> struct impl_IHttpCookieFactory;
template <typename T> struct impl_IHttpCookieManager;
template <typename T> struct impl_IHttpFormUrlEncodedContentFactory;
template <typename T> struct impl_IHttpMethod;
template <typename T> struct impl_IHttpMethodFactory;
template <typename T> struct impl_IHttpMethodStatics;
template <typename T> struct impl_IHttpMultipartContent;
template <typename T> struct impl_IHttpMultipartContentFactory;
template <typename T> struct impl_IHttpMultipartFormDataContent;
template <typename T> struct impl_IHttpMultipartFormDataContentFactory;
template <typename T> struct impl_IHttpRequestMessage;
template <typename T> struct impl_IHttpRequestMessageFactory;
template <typename T> struct impl_IHttpResponseMessage;
template <typename T> struct impl_IHttpResponseMessageFactory;
template <typename T> struct impl_IHttpStreamContentFactory;
template <typename T> struct impl_IHttpStringContentFactory;
template <typename T> struct impl_IHttpTransportInformation;
}
namespace Windows::Web::Http {
enum class HttpCompletionOption
{
ResponseContentRead = 0,
ResponseHeadersRead = 1,
};
enum class HttpProgressStage
{
None = 0,
DetectingProxy = 10,
ResolvingName = 20,
ConnectingToServer = 30,
NegotiatingSsl = 40,
SendingHeaders = 50,
SendingContent = 60,
WaitingForResponse = 70,
ReceivingHeaders = 80,
ReceivingContent = 90,
};
enum class HttpResponseMessageSource
{
None = 0,
Cache = 1,
Network = 2,
};
enum class HttpStatusCode
{
None = 0,
Continue = 100,
SwitchingProtocols = 101,
Processing = 102,
Ok = 200,
Created = 201,
Accepted = 202,
NonAuthoritativeInformation = 203,
NoContent = 204,
ResetContent = 205,
PartialContent = 206,
MultiStatus = 207,
AlreadyReported = 208,
IMUsed = 226,
MultipleChoices = 300,
MovedPermanently = 301,
Found = 302,
SeeOther = 303,
NotModified = 304,
UseProxy = 305,
TemporaryRedirect = 307,
PermanentRedirect = 308,
BadRequest = 400,
Unauthorized = 401,
PaymentRequired = 402,
Forbidden = 403,
NotFound = 404,
MethodNotAllowed = 405,
NotAcceptable = 406,
ProxyAuthenticationRequired = 407,
RequestTimeout = 408,
Conflict = 409,
Gone = 410,
LengthRequired = 411,
PreconditionFailed = 412,
RequestEntityTooLarge = 413,
RequestUriTooLong = 414,
UnsupportedMediaType = 415,
RequestedRangeNotSatisfiable = 416,
ExpectationFailed = 417,
UnprocessableEntity = 422,
Locked = 423,
FailedDependency = 424,
UpgradeRequired = 426,
PreconditionRequired = 428,
TooManyRequests = 429,
RequestHeaderFieldsTooLarge = 431,
InternalServerError = 500,
NotImplemented = 501,
BadGateway = 502,
ServiceUnavailable = 503,
GatewayTimeout = 504,
HttpVersionNotSupported = 505,
VariantAlsoNegotiates = 506,
InsufficientStorage = 507,
LoopDetected = 508,
NotExtended = 510,
NetworkAuthenticationRequired = 511,
};
enum class HttpVersion
{
None = 0,
Http10 = 1,
Http11 = 2,
Http20 = 3,
};
}
}
|
/**
* $Source: /backup/cvsroot/project/pnids/zdk/zls/zlang/CASTPrinter.cpp,v $
*
* $Date: 2001/11/14 19:03:08 $
*
* $Revision: 1.3 $
*
* $Name: $
*
* $Author: zls $
*
* Copyright(C) since 1998 by Albert Zheng - 郑立松, All Rights Reserved.
*
* lisong.zheng@gmail.com
*
* $State: Exp $
*/
#include <cassert>
#include <cstdio>
#include <zls/zlang/CASTPrinter.hpp>
// Begin namespace 'zlang::'
ZLS_BEGIN_NAMESPACE(zlang)
#define For_each_kid(t,top) \
for(t=((top && is_nonleaf(top)) ? top->getFirstChild() : (antlr::RefAST)NULL ); \
t; \
t = t->getNextSibling())
/*
* pr_name
*
Print the character string associated with an ANTLR tree node.
*/
void CASTPrinter::pr_name( antlr::RefAST node )
{
std::string str;
str = node->getText();
printf("%s ", str.c_str());
} // pr_name
/*
* pr_indent
*
Print indentation for a node.
*/
void CASTPrinter::pr_indent(void)
{
const size_t BUFSIZE = 127;
char buf[ BUFSIZE+1 ];
int i;
for (i = 0; i < indent_level && i < BUFSIZE; i++) {
buf[i] = ' ';
}
buf[i] = '\0';
printf("%s", buf );
} // pr_indent
void CASTPrinter::pr_open_angle(void)
{
if ( indent_level )
printf("\n");
pr_indent();
printf("<");
indent_level += INDENT;
} // pr_open_angle
/*
* pr_close_angle
*
Print the ">" bracket to show the close of a tree production.
*/
void CASTPrinter::pr_close_angle(bool first)
{
assert( indent_level > 0 );
indent_level -= INDENT;
if (!first) {
printf("\n");
pr_indent();
}
printf("> ");
} // pr_close_angle
/*
* pr_leaves
*
Print the leaves of an AST node
*/
void CASTPrinter::pr_leaves( antlr::RefAST top )
{
antlr::RefAST t;
For_each_kid(t, top) {
if (is_nonleaf( t ))
pr_top( t );
else
pr_name( t );
}
} // pr_leaves
/*
* pr_top
*
Recursively print a tree (or a sub-tree) from the top down.
*/
void CASTPrinter::pr_top( antlr::RefAST top )
{
antlr::RefAST tmp;
bool first = true;
pr_open_angle();
pr_name( top );
if (is_nonleaf( top )) {
For_each_kid( tmp, top ) {
if (is_nonleaf( tmp ))
first = false;
}
pr_leaves( top );
}
pr_close_angle( first );
} // pr_top
/*
* pr_tree
*
Main entry point for tree print.
*/
void CASTPrinter::pr_tree( antlr::RefAST top )
{
antlr::RefAST t;
for (t = top; t != 0; t = t->getNextSibling()) {
indent_level = 0;
pr_top( t );
printf("\n");
}
} // pr_tree
ZLS_END_NAMESPACE
|
/***************************************************************************
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
class ResourceContainer;
enum class ResourceEnumFlags : uint16_t;
enum class ResourceSaveLocation : uint16_t;
enum class ResourceSourceFlags : int;
// Encapsulates operations that only depend on gamefolder and SCI version.
// We can carry this to a background thread, for instace, and not have to
// interact with the ResourceMap object.
class ResourceRecency;
class ResourceBlob;
extern const std::string GameSection;
extern const std::string LanguageKey;
extern const std::string LanguageValueStudio;
extern const std::string LanguageValueSCI;
extern const std::string CodepageKey;
enum class ResourceSaveLocation : uint16_t
{
Default,
Package,
Patch,
};
class GameFolderHelper
{
public:
GameFolderHelper() {}
GameFolderHelper(const GameFolderHelper &orig) = default;
GameFolderHelper &operator=(const GameFolderHelper &other) = default;
std::string GetScriptFileName(const std::string &name) const;
std::string GetScriptFileName(uint16_t wScript) const;
std::string GetScriptObjectFileName(const std::string &title) const;
std::string GetScriptObjectFileName(uint16_t wScript) const;
std::string GetScriptDebugFileName(uint16_t wScript) const;
std::string GetScriptSymbolFileName(uint16_t wScript) const;
std::string GameFolderHelper::GetSrcFolder(const std::string *prefix = nullptr) const;
std::string GameFolderHelper::GetMsgFolder(const std::string *prefix = nullptr) const;
std::string GameFolderHelper::GetPicClipsFolder() const;
std::string GameFolderHelper::GetSubFolder(const std::string &subFolder) const;
std::string GameFolderHelper::GetLipSyncFolder() const;
std::string GameFolderHelper::GetPolyFolder(const std::string *prefix = nullptr) const;
std::string GetGameIniFileName() const;
std::string GetIniString(const std::string §ionName, const std::string &keyName, PCSTR pszDefault = "") const;
bool GetIniBool(const std::string §ionName, const std::string &keyName, bool value = false) const;
bool DoesSectionExistWithEntries(const std::string §ionName);
static std::string GetIncludeFolder();
static std::string GetHelpFolder();
void SetIniString(const std::string §ionName, const std::string &keyName, const std::string &value) const;
LangSyntax GetDefaultGameLanguage() const { return Language; }
ScriptId GetScriptId(const std::string &name) const;
std::string FigureOutName(ResourceType type, int iResourceNum, uint32_t base36Number) const;
std::unique_ptr<ResourceContainer> Resources(ResourceTypeFlags types, ResourceEnumFlags enumFlags, ResourceRecency *pRecency = nullptr, int mapContext = -1) const;
std::unique_ptr<ResourceBlob> GameFolderHelper::MostRecentResource(ResourceType type, int number, ResourceEnumFlags flags, uint32_t base36Number = NoBase36, int mapContext = -1) const;
bool DoesResourceExist(ResourceType type, int number, std::string *retrieveName, ResourceSaveLocation location) const;
bool GetUseSierraAspectRatio(bool defaultValue) const;
void SetUseSierraAspectRatio(bool useSierra) const;
bool GetUndither() const;
void SetUndither(bool undither) const;
bool GetNoDbugStr() const;
void SetNoDbugStr(bool dbugStr) const;
int GetCodepage() const;
void SetCodepage(int codepage) const;
bool GetGenerateDebugInfo() const;
ResourceSaveLocation GetResourceSaveLocation(ResourceSaveLocation location) const;
void SetResourceSaveLocation(ResourceSaveLocation location) const;
ResourceEnumFlags GetDefaultEnumFlags() const;
ResourceSourceFlags GetDefaultSaveSourceFlags() const;
bool IsResourceCompatible(const ResourceBlob &resource) const;
// Members
SCIVersion Version;
std::string GameFolder;
LangSyntax Language;
private:
std::string _GetSubfolder(const char *key, const std::string *prefix = nullptr) const;
};
|
#include <irtkImage.h>
#include <irtkTransformation.h>
// Input transformation
char *dofout_name = NULL;
// Output transformation
char *image_in_nameX = NULL;
char *image_in_nameY = NULL;
char *image_in_nameZ = NULL;
void usage()
{
cerr << "Usage: ffd2images [imageInX] [imageInY] [imageInZ] [dofout] \n" << endl;
exit(1);
}
bool sameSizeImages(irtkRealImage *a, irtkRealImage *b){
if (a->GetX() != b->GetX() || a->GetY() != b->GetY() || a->GetZ() != b->GetZ() ){
return false;
}
return true;
}
int main(int argc, char **argv)
{
int i, j, k;
double x, y, z;
double x1, y1, z1, x2, y2, z2;
double xsize, ysize, zsize;
double xaxis[3], yaxis[3], zaxis[3];
irtkRealImage *cpsX, *cpsY, *cpsZ;
irtkMultiLevelFreeFormTransformation *mffd;
irtkBSplineFreeFormTransformation *affd;
// Check command line
if (argc != 5){
usage();
}
// Parse file names
image_in_nameX = argv[1];
argc--;
argv++;
image_in_nameY = argv[1];
argc--;
argv++;
image_in_nameZ = argv[1];
argc--;
argv++;
dofout_name = argv[1];
argc--;
argv++;
// Read images.
cpsX = new irtkRealImage(image_in_nameX);
cpsY = new irtkRealImage(image_in_nameY);
cpsZ = new irtkRealImage(image_in_nameZ);
if (( ! sameSizeImages(cpsX , cpsY) ) || ( ! sameSizeImages(cpsX , cpsZ))){
cerr << "Images must have same dimensions." << endl;
exit(1);
}
x1 = 0;
y1 = 0;
z1 = 0;
x2 = cpsX->GetX() - 1;
y2 = cpsX->GetY() - 1;
z2 = cpsX->GetZ() - 1;
cpsX->ImageToWorld(x1, y1, z1);
cpsX->ImageToWorld(x2, y2, z2);
cpsX->GetPixelSize(&xsize, &ysize, &zsize);
cpsX->GetOrientation(xaxis, yaxis, zaxis);
affd = new irtkBSplineFreeFormTransformation(x1, y1, z1, x2, y2, z2, xsize, ysize, zsize, xaxis, yaxis, zaxis);
for (i = 0; i < cpsX->GetX(); i++){
for (j = 0; j < cpsX->GetY(); j++){
for (k = 0; k < cpsX->GetZ(); k++){
x = cpsX->Get(i, j, k);
y = cpsY->Get(i, j, k);
z = cpsZ->Get(i, j, k);
affd->Put(i, j, k, x, y, z);
}
}
}
mffd = new irtkMultiLevelFreeFormTransformation;
mffd->PushLocalTransformation(affd);
mffd->irtkTransformation::Write(dofout_name);
}
|
#pragma once
#include <Transformation.h>
#include <EventID.h>
#include <EventType.h>
#include <MetaFilter.h>
#include <boost/graph/adjacency_list.hpp>
#include <ostream>
#include <utility>
class CompositeTransformation : public AbstractConfiguredTransformation {
public:
class ConfiguredTransformation : public AbstractConfiguredTransformation {
private:
TransformationPtr mTPtr;
public:
using TransPtr = Transformation::TransPtr;
ConfiguredTransformation() = default;
ConfiguredTransformation(TransformationPtr tPtr, const EventType& out,
const EventType& provided = EventType(),
const MetaFilter& filter = MetaFilter())
: mTPtr(tPtr) {
mFilter = filter;
mOut = out;
mIn = tPtr->in(out, provided, mFilter);
}
TransformationPtr trans() const { return mTPtr; }
TransPtr create(const AbstractPolicy& policy) const {
return mTPtr->create(mOut, mIn, policy, mFilter);
}
bool operator==(const ConfiguredTransformation& b) const;
};
using Graph = boost::adjacency_list< boost::vecS, boost::vecS, boost::bidirectionalS,
ConfiguredTransformation, EventType>;
using Vertex = Graph::vertex_descriptor;
using VertexResult = std::pair<Vertex, bool>;
using VertexList = std::vector<Vertex>;
using TransPtr = Transformation::TransPtr;
using EventTypes = Transformer::EventTypes;
using EventIDs = Transformation::EventIDs;
using TransList = std::vector<TransformationPtr>;
private:
Graph mGraph;
Vertex mRoot;
public:
CompositeTransformation() = default;
CompositeTransformation(TransformationPtr tPtr, const EventType& goal,
const EventType& provided, const MetaFilter& filter = MetaFilter());
VertexResult add(CompositeTransformation&& cT);
VertexResult add(TransformationPtr tPtr, const EventType& goal,
const EventType& provided, const MetaFilter& filter);
VertexResult add(TransformationPtr tPtr, const EventType& goal,
const EventType& provided = EventType());
VertexResult add(TransformationPtr tPtr, Vertex v, const EventType& goal,
const EventType& provided = EventType());
EventIDs inIDs() const;
EventTypes allIn() const;
bool addIn(const EventType&);
TransPtr create(const AbstractPolicy& policy) const;
bool check() const;
const Graph& graph() const { return mGraph; }
Vertex root() const { return mRoot; }
TransList path(Vertex v) const;
VertexResult find(TransformationPtr tPtr) const;
VertexList find(const EventType& eT) const;
bool contains(TransformationPtr tPtr) const { return find(tPtr).second; }
bool operator==(const CompositeTransformation& b) const;
};
std::ostream& operator<<(std::ostream& o, const CompositeTransformation& t);
|
#include <cutils/properties.h>
#include <string>
void inputhook_vendor_touchrotate(int32_t *width, int32_t *height, int32_t *orientation)
{
int32_t tmp = 0;
char stbMode[PROP_VALUE_MAX];
property_get("persist.tegra.stb.mode", stbMode, "0");
if (stbMode[0] != '0') {
tmp = *width;
*width = *height;
*height = tmp;
*orientation = (*orientation + 1) % 4;
}
}
|
#include <iostream>
using namespace std;
double dzielenie(double a, double b){
if(b!=0){
return a/b;
}
else{
cout << "Nie dziel przez 0!";
return 0;
}
}
double mnozenie(double a, double b){
return a*b;
}
double odejmowanie(double a, double b){
return a-b;
}
double dodawanie(double a, double b){
return a+b;
}
|
/*
Name: Mohit Kishorbhai Sheladiya
Student ID: 117979203
Student Email: mksheladiya@myseneca.ca
Date: 21/02/03
*/
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <iomanip>
#include <cstring>
#include "Item.h"
using namespace std;
namespace sdds {
void Item::setName(const char* name) {
strncpy(m_itemName, name, 20);
m_itemName[20] = '\0';
//for (int i = 0; i < 20; i++) {
// if (name != NULL) {
// m_itemName[i] = name[i];
// }
//}
}
void Item::setEmpty() {
m_price = 0.00;
m_itemName[0] = '\0';
}
void Item::set(const char* name, double price, bool taxed) {
setEmpty();
if (name != nullptr && price > 0) {
setName(name);
m_price = price;
m_taxed = taxed;
}
}
double Item::price()const {
return m_price;
}
double Item::tax()const {
double taxrate = 0;
if (m_taxed) {
taxrate = (m_price * 0.13);
}
else {
taxrate = 0;
}
return taxrate;
}
bool Item::isValid()const {
if (m_price != 0 && m_itemName != NULL) {
return true;
}
else
return false;
}
void Item::display()const {
bool a = isValid();
if (a) {
cout << "| ";
cout << left << setfill('.') << setw(20) << m_itemName;
cout << " | ";
cout.setf(ios::right);
cout.width(7);
cout << fixed << setprecision(2) << setfill(' ');
cout << m_price;
cout << " | ";
if (m_taxed == true) {
cout << "Yes";
}
else {
cout << "No ";
}
cout << " |";
cout << endl;
}
else {
cout << "| xxxxxxxxxxxxxxxxxxxx | xxxxxxx | xxx |";
cout << endl;
}
}
}
|
#include "ZobObject.h"
#include "DirectZob.h"
ZobObject::ZobObject(Type t, SubType s, std::string& name, Mesh* mesh, ZobObject* parent /*= NULL*/):ZOBGUID(t,s)
{
m_name = name;
m_parent = parent;
m_mesh = mesh;
m_translation = Vector3(0, 0, 0);
m_rotation = Vector3(0, 0, 0);
m_scale = Vector3(1, 1, 1);
if (parent != NULL)
{
parent->AddChildReference(this);
}
m_renderOptions.LightMode(RenderOptions::eLightMode_gouraud);
m_renderOptions.ZBuffered(true);
std::string l = "Added new ZobObject ";
l.append(m_name);
DirectZob::LogInfo(l.c_str());
}
ZobObject::~ZobObject()
{
for (int i = 0; i < m_children.size(); i++)
{
delete m_children.at(i);
}
if (m_parent != NULL)
{
m_parent->RemoveChildReference(this);
}
std::string l = "Deleted ZobObject ";
l.append(m_name);
DirectZob::LogInfo(l.c_str());
}
void ZobObject::SetMesh(std::string name)
{
Mesh* m = DirectZob::GetInstance()->GetMeshManager()->GetMesh(name);
m_mesh = m;
}
const std::string ZobObject::GetMeshName() const
{
if (m_mesh)
{
return m_mesh->GetName();
}
return "";
}
void ZobObject::Update(const Matrix4x4& parentMatrix, const Matrix4x4& parentRotationMatrix)
{
m_modelMatrix.Identity();
m_rotationMatrix.Identity();
Vector3 t = m_translation;
parentRotationMatrix.Mul(&t);
t.Add(&parentMatrix.GetTranslation());
m_modelMatrix.SetTranslation(&t);
m_modelMatrix.SetRotation(&m_rotation);
m_modelMatrix.SetScale(&m_scale);
m_modelMatrix.Mul(&parentMatrix);
m_rotationMatrix.SetRotation(&m_rotation);
m_rotationMatrix.Mul(&parentRotationMatrix);
for (int i = 0; i < m_children.size(); i++)
{
m_children.at(i)->Update(m_modelMatrix, m_rotationMatrix);
}
}
void ZobObject::Draw(const Camera* camera, Core::Engine* engine)
{
if (m_mesh)
{
m_mesh->Draw(m_modelMatrix, m_rotationMatrix, camera, engine, GetId(), m_renderOptions);
}
for (int i = 0; i < m_children.size(); i++)
{
m_children.at(i)->Draw(camera, engine);
}
}
int ZobObject::GetChildPosition(const ZobObject* z)
{
for (int i=0; i<m_children.size(); i++)
{
if (m_children.at(i) == z)
{
return i;
}
}
return -1;
}
void ZobObject::RemoveChildReference(const ZobObject* z)
{
int i = GetChildPosition(z);
if (i >= 0)
{
std::swap(m_children.at(i), m_children.at(m_children.size()-1));
m_children.pop_back();
}
}
void ZobObject::AddChildReference(ZobObject* z)
{
m_children.push_back(z);
}
ZobObject* ZobObject::GetChild(const std::string& name)
{
for (std::vector<ZobObject*>::const_iterator iter = m_children.begin(); iter != m_children.end(); iter++)
{
if ((*iter)->GetName() == name)
{
return (*iter);
}
}
return NULL;
}
ZobObject* ZobObject::GetChild(const int i)
{
if (i >= 0 && i < m_children.size())
{
return m_children.at(i);
}
return NULL;
}
const void ZobObject::GetFullNodeName(std::string& fullname) const
{
std::string s = GetName();
std::string s2 = "";
const ZobObject* z = this;
while (z->GetParent())
{
z = z->GetParent();
s2 = z->GetName();
s2.append("/");
s2.append(s);
s = s2;
}
fullname = s;
}
void ZobObject::SetParent(ZobObject* p)
{
ZobObject* parent = GetParent();
if (p != NULL && p!= this && p != parent)
{
if (!HasChild(p))
{
parent->RemoveChildReference(this);
p->AddChildReference(this);
m_parent = p;
}
else
{
DirectZob::LogWarning("trying to reparent an object with one of its descendants !");
}
}
}
bool ZobObject::HasChild(const ZobObject* o)
{
if (o == this)
{
return true;
}
else
{
bool bRet = false;
for (int i = 0; i < m_children.size(); i++)
{
bRet |= m_children.at(i)->HasChild(o);
}
return bRet;
}
}
void ZobObject::SetLightingMode(RenderOptions::eLightMode l)
{
m_renderOptions.LightMode(l);
}
|
// server.cpp
// defines and implements functionality for a NICU baby warmer C&C server
// stdlib includes
#include <chrono>
#include <cstring>
#include <iostream>
#include <queue>
#include <string>
#include <vector>
// custom includes
#include "../../shared/msg_util.hpp"
#include "../include/pool.hpp"
#include <zmqpp/zmqpp.hpp>
// IO defines
#define COUT std::cout
#define ENDL std::endl
#define CIN std::cin
// MAGIC NUMBERS
// maximum number of clients allowed
#define MAX_CLIENT_COUNT 50
// time for server to be alive - in seconds
#define ALIVE_TIME 300
// endpoint for zmq comms
const std::string ENDPOINT = "tcp://127.0.0.1:55555";
// client struct
// needs to be constant size for pool allocator to work right
struct client
{
// client identifier
char ident[17];
// client's current temp
double curr_temp;
// last 10 temps received from client
double last_temps[10];
// client's out-of-bounds state
bool is_oob;
// zero arg constructor
client() {}
// constructor
client(double in_curr_temp, bool in_is_oob)
: curr_temp(in_curr_temp)
, is_oob(in_is_oob)
{}
// set identifier
// returns true if successful, false if not
bool set_ident(const std::string id)
{
// check that id is correct length (16 chars)
if (id.length() != 16)
{
return false;
}
// copy contents of id into ident
strcpy(ident, id.c_str());
return true;
}
// update temps
// put input temp at front of last temps and shift everything else
void update_temps(double new_temp)
{
// add every element onto queue
std::queue<double> holds;
for (int i = 0; i < 10; i++)
{
holds.push(last_temps[i]);
}
// place new temp in both required locations
curr_temp = new_temp;
last_temps[0] = new_temp;
// iterate through and put other temps back
for (int i = 1; i < 10; i++)
{
last_temps[i] = holds.front();
holds.pop();
}
}
};
// main
int main(void)
{
COUT << "--------------------" << ENDL << "Server startup:" << ENDL;
// initialize fixed pool of memory
pool nicu_pool = pool((MAX_CLIENT_COUNT * sizeof(client)), sizeof(client));
nicu_pool.init();
COUT << "client pool initialization - complete" << ENDL;
// initialize var to keep track of how many clients are active
int current_client_count = 0;
// also a vector to hold on to actual memory positions
std::vector<client*> clients;
// hold start time
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
// die
bool die = false;
// initialize two payloads
// one for us to reuse as sender, one for us to recompose messages into
payload self = payload("COMM", "SERVER_WARMER_00", 0.0);
payload recvd = payload("TEMP", "PLACEHOLDER_0000", 0.0);
// set up zmq server
// create context
zmqpp::context context;
COUT << "zeromq context initialization - complete" << ENDL;
// generate socket
zmqpp::socket_type type = zmqpp::socket_type::reply;
zmqpp::socket socket(context, type);
// bind to socket
socket.bind(ENDPOINT); // ENDPOINT defined in MAGIC up top
COUT << "zeromq socket bound to endpoint - " << ENDPOINT << ENDL;
// main active loop
COUT << "entering main loop..." << ENDL << "--------------------" << ENDL;
while (!die)
{
// receive from socket we've bound to
// this is a blocking op, so it'll wait here until something comes in
zmqpp::message recv_msg;
socket.receive(recv_msg, zmqpp::socket::normal);
// put message contents into string
std::string recv_str;
recv_msg >> recv_str; // contents of serialized payload from client
// once something has arrived, figure out what it is
// aka stick it back into a payload struct
recvd.type = recv_str.substr(0, 4);
recvd.identifier = recv_str.substr(4, 16);
recvd.temperature = std::stod(recv_str.substr(20));
// set die if told to kill by killer.cpp
if (recvd.type == "KILL" and recvd.identifier == "KILLER_KILLER_00")
{
die = true;
}
// figure out if that client has been seen before
bool seen = false;
client* curr_client;
for (size_t i = 0; i < clients.size(); i++)
{
// get a pointer to the current struct in the pool
client* check = (client*)clients.at(i);
// check if it's been seen
if (strcmp(check->ident, recvd.identifier.c_str()))
{
seen = true;
curr_client = check;
}
}
// if not seen, make a new one and increment count
if (!seen)
{
curr_client = (client*)nicu_pool.alloc(sizeof(client));
// add that to clients list
clients.push_back(curr_client);
current_client_count++;
}
// update values of curr_client
curr_client->update_temps(recvd.temperature);
// build proper payload based on client state
if (!die)
{
self.type = "COMM";
// if temp oob
if ((curr_client->curr_temp < 97.9) || (curr_client->curr_temp > 100.4))
{
// respond with target
self.temperature = 99.15;
// set curr_client to oob
curr_client->is_oob = true;
}
// if temp normal, respond with basic
else
{
// respond with basic
self.temperature = 0;
// reset oob if previously oob
if (curr_client->is_oob)
{
curr_client->is_oob = false;
}
}
}
// otherwise build a kill payload
else
{
self.type = "KILL";
nicu_pool.free((void*)curr_client);
current_client_count--;
}
// send out the correct response
// build response
zmqpp::message send_msg;
send_msg << self.serialize();
socket.send(send_msg, zmqpp::socket::normal);
// report what's happened to the user
COUT << "---------------------|" << ENDL;
COUT << "Receieved from client: " << recvd.identifier << ENDL;
COUT << "Client message type : " << recvd.type << ENDL;
COUT << "Client's current temp: " << recvd.temperature << ENDL;
COUT << "Out of bounds : " << (((recvd.temperature < 97.9) || (recvd.temperature > 100.4)) ? "Yes" : "No") << ENDL;
COUT << "Response type : " << self.type << ENDL;
COUT << "Response content : " << self.temperature << ENDL;
COUT << "---------------------|" << ENDL;
// if it's been more than a certain amount of time, kill the clients and exit
std::chrono::steady_clock::time_point current = std::chrono::steady_clock::now();
if (std::chrono::duration_cast<std::chrono::seconds>(current - start).count() > ALIVE_TIME)
{
die = true;
}
// if current_client_count == 0 and die == true, break
if ((die == true) && (current_client_count == 0))
{
break;
}
}
// if we get here, shut things down and return
socket.unbind(ENDPOINT);
socket.close();
context.terminate();
// let the user know we're done
COUT << ENDL << "zeromq context destruction complete - exiting" << ENDL;
return 0;
}
// output debugging
// COUT << recvd.type << " " << recvd.identifier << " " << recvd.temperature << ENDL;
|
// github.com/andy489
#include <iostream>
using namespace std;
#define MIN 0
#define MAX 1000000000
#define mxN 100000
int getMax(int *arr, int size) {
int currentMax(0);
for (int i = 0; i < size; ++i)
if (currentMax < arr[i])
currentMax = arr[i];
return currentMax;
}
bool driesForTime(int *clothes, int size, int dryer, int time) {
int accumulated = 0;
for (int i = 0; i < size; ++i)
if (clothes[i] > time) {
accumulated += (clothes[i] - time) / (dryer - 1) + ((clothes[i] - time) % (dryer - 1) != 0);
if (accumulated > time)
return false;
}
return true;
}
int minDry(int *clothes, int size, int dryer) {
if (dryer < 2)
return getMax(clothes, size);
int low(MIN), high(MAX), tempMin(MAX);
while (low < high) {
int mid = (low + high) / 2;
if (driesForTime(clothes, size, dryer, mid))
tempMin = mid, high = mid - 1;
else
low = mid + 1;
}
return driesForTime(clothes, size, dryer, low) ? low : tempMin;
}
int main() {
int N, K;
cin >> N >> K;
int clothes[mxN];
int i(0);
for (i; i < N; ++i)
cin >> clothes[i];
return cout << minDry(clothes, N, K), 0;
}
|
#include <irtkImage.h>
#include <irtkHistogram.h>
#include <irtkImageFunction.h>
#include <irtkTransformation.h>
char *target_name = NULL, *source_name = NULL;
char *output_name = NULL;
char *dof_name = NULL;
void usage(){
cout << "csvHist_2D [target] [source] <options>" << endl;
cout << "Write the histogram of an image to a file in csv format." << endl;
cout << "Options:" << endl;
cout << " <-f outputFile>" << endl;
cout << " <-Tp padding>" << endl;
cout << " <-bins binCount | -width binWidth>" << endl;
cout << " <-dofin dof>" << endl;
cout << "If padding is given, all values <= padding are ignored." << endl;
cout << "Only one of -bins or -width should be set, not both." << endl;
exit(1);
}
int main(int argc, char **argv){
irtkHistogram_2D<int> hist;
irtkRealImage target, source;
irtkTransformation *transformation = NULL;
irtkInterpolateImageFunction *interpolator = NULL;
irtkRealPixel tmin = 0, tmax = 0;
irtkRealPixel smin = 0, smax = 0;
irtkRealPixel tval, sval;
int i, j, k, nBins = 0;
int binx, biny;
double padding = -1 * FLT_MAX;
int xdim, ydim, zdim;
double x, y, z;
double x1, y1, z1, x2, y2, z2;
bool ok;
double width = -1.0;
double widthX, widthY;
// Read arguments
if (argc < 3){
usage();
}
target_name = argv[1];
argc--;
argv++;
source_name = argv[1];
argc--;
argv++;
while (argc > 1){
ok = false;
if ((ok == false) && (strcmp(argv[1], "-dofin") == 0)){
argc--;
argv++;
dof_name = argv[1];
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-f") == 0)){
argc--;
argv++;
output_name = argv[1];
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Tp") == 0)){
argc--;
argv++;
padding = atof(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-bins") == 0)){
argc--;
argv++;
nBins = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-width") == 0)){
argc--;
argv++;
width = atof(argv[1]);
argc--;
argv++;
ok = true;
}
if (ok == false){
cerr << "Can not parse argument " << argv[1] << endl;
usage();
}
}
if (dof_name != NULL){
// Read transformation
transformation = irtkTransformation::New(dof_name);
} else {
transformation = new irtkRigidTransformation;
}
// Initialise histogram.
target.Read(target_name);
source.Read(source_name);
interpolator = new irtkLinearInterpolateImageFunction;
interpolator->SetInput(&source);
interpolator->Initialize();
// Calculate the source image domain in which we can interpolate
interpolator->Inside(x1, y1, z1, x2, y2, z2);
xdim = target.GetX();
ydim = target.GetY();
zdim = target.GetZ();
tmin = FLT_MAX;
smin = FLT_MAX;
tmax = -1.0 * FLT_MAX;
smax = -1.0 * FLT_MAX;
// What are the min and max values corresponding to the unpadded region
// in the target?
for (k = 0; k < zdim; ++k){
for (j = 0; j < ydim; ++j){
for (i = 0; i < xdim; ++i){
x = i;
y = j;
z = k;
tval = target.Get(i, j, k);
if (tval > padding){
target.ImageToWorld(x, y, z);
transformation->Transform(x, y, z);
source.WorldToImage(x, y, z);
if ((x > x1) && (x < x2) &&
(y > y1) && (y < y2) &&
(z > z1) && (z < z2)){
if (tval > tmax)
tmax = tval;
if (tval < tmin)
tmin = tval;
sval = interpolator->EvaluateInside(x, y, z);
if (sval > smax)
smax = sval;
if (sval < smin)
smin = sval;
}
}
}
}
}
// Set up the histogram.
cerr << "tmax " << tmax << " tmin " << tmin << endl;
cerr << "smax " << smax << " smin " << smin << endl;
hist.PutMin(floor(tmin), floor(smin));
hist.PutMax(floor(tmax) + 1, floor(smax) + 1);
if (width > 0){
if (nBins > 0){
// Both width and bins have been set.
cerr << "Only one of -bins or -width should be set" << endl;
exit(1);
} else {
// Width only set.
hist.PutWidth(width, width);
hist.GetNumberOfBins(&binx, &biny);
cerr << "Histogram assigned width " << width << ", using " << binx;
cerr << " x " << biny << " bins." << endl;
}
} else {
// Width not set.
if (nBins > 0){
// Bins only set.
hist.PutNumberOfBins(nBins, nBins);
hist.GetWidth(&widthX, &widthY);
cerr << "Histogram assigned " << nBins << " bins, using widths ";
cerr << widthX << " x " << widthY << endl;
} else {
// Neither set.
hist.GetWidth(&widthX, &widthY);
hist.GetNumberOfBins(&binx, &biny);
cerr << "Histogram uses " << binx << " x " << biny << " bins with widths ";
cerr << widthX << " x " << widthY << endl;
}
}
// Populate histogram.
hist.Reset();
for (k = 0; k < zdim; ++k){
for (j = 0; j < ydim; ++j){
for (i = 0; i < xdim; ++i){
x = i;
y = j;
z = k;
tval = target.Get(i, j, k);
if (tval > padding){
target.ImageToWorld(x, y, z);
transformation->Transform(x, y, z);
source.WorldToImage(x, y, z);
if ((x > x1) && (x < x2) &&
(y > y1) && (y < y2) &&
(z > z1) && (z < z2)){
sval = interpolator->EvaluateInside(x, y, z);
hist.AddSample(tval, sval);
}
}
}
}
}
cerr << hist.NumberOfSamples() << endl;
if (output_name != NULL){
// Write histogram.
ofstream fileOut(output_name);
if(!fileOut){
cerr << "Can't open file " << output_name << endl;
exit(1);
}
hist.GetNumberOfBins(&binx, &biny);
for (i = 0; i < binx - 1; ++i){
fileOut << hist.BinToValX(i) << ",";
}
fileOut << hist.BinToValX(i) << endl;
for (j = 0; j < biny - 1; ++j){
fileOut << hist.BinToValY(j) << ",";
}
fileOut << hist.BinToValY(j) << endl;
for (j = 0; j < biny; ++j){
for (i = 0; i < binx - 1; ++i){
fileOut << hist(i, j) << ",";
}
// Avoid trailing comma.
fileOut << hist(i, j) << endl;
}
fileOut.close();
} else {
// write to std out.
for (i = 0; i < binx - 1; ++i){
cout << hist.BinToValX(i) << ",";
}
cout << hist.BinToValX(i) << endl;
for (j = 0; j < biny - 1; ++j){
cout << hist.BinToValY(j) << ",";
}
cout << hist.BinToValY(j) << endl;
for (j = 0; j < biny; ++j){
for (i = 0; i < binx - 1; ++i){
cout << hist(i, j) << ",";
}
// Avoid trailing comma.
cout << hist(i, j) << endl;
}
}
}
|
//
// Created by 邓岩 on 2019/5/19.
//
/*
* 大臣的旅费
问题描述
很久以前,T王国空前繁荣。为了更好地管理国家,王国修建了大量的快速路,用于连接首都和王国内的各大城市。
为节省经费,T国的大臣们经过思考,制定了一套优秀的修建方案,使得任何一个大城市都能从首都直接或者通过其他大城市间接到达。同时,如果不重复经过大城市,从首都到达每个大城市的方案都是唯一的。
J是T国重要大臣,他巡查于各大城市之间,体察民情。所以,从一个城市马不停蹄地到另一个城市成了J最常做的事情。他有一个钱袋,用于存放往来城市间的路费。
聪明的J发现,如果不在某个城市停下来修整,在连续行进过程中,他所花的路费与他已走过的距离有关,在走第x千米到第x+1千米这一千米中(x是整数),他花费的路费是x+10这么多。也就是说走1千米花费11,走2千米要花费23。
J大臣想知道:他从某一个城市出发,中间不休息,到达另一个城市,所有可能花费的路费中最多是多少呢?
输入格式
输入的第一行包含一个整数n,表示包括首都在内的T王国的城市数
城市从1开始依次编号,1号城市为首都。
接下来n-1行,描述T国的高速路(T国的高速路一定是n-1条)
每行三个整数Pi, Qi, Di,表示城市Pi和城市Qi之间有一条高速路,长度为Di千米。
输出格式
输出一个整数,表示大臣J最多花费的路费是多少。
样例输入1
5
1 2 2
1 3 1
2 4 5
2 5 4
样例输出1
135
输出格式
大臣J从城市4到城市5要花费135的路费。
*/
# include <iostream>
# include <vector>
# include <algorithm>
using namespace std;
vector<int> ret;
int n;
int step[100000];
vector<pair<int, int> > v[100000];
int sum, mx;
int idx;
void dfs(int x) {
if (v[x].size() == 1 && step[v[x][0].first] == 1) {
if (sum > mx) {
mx = sum;
idx = x;
}
return;
}
for (int i = 0; i < v[x].size(); i++) {
if (step[v[x][i].first] == 0) {
sum += v[x][i].second;
step[v[x][i].first] = 1;
dfs(v[x][i].first);
sum -= v[x][i].second;
step[v[x][i].first] = 0;
}
}
}
int main(void)
{
int s, r = 0;
int from, to, cost;
cin >> n;
for (int i = 1; i < n; i++) {
cin >> from >> to >> cost;
v[from].push_back({to, cost});
v[to].push_back({from, cost});
}
step[1] = 1;
dfs(1);
step[1] = 0;
sum = 0;
mx = 0;
step[idx] = 1;
dfs(idx);
cout << (11 + 10 + mx) * mx / 2 << endl;
return 0;
}
|
//
// Created by matan on 1/20/20.
//
#ifndef SOLID_SERVER_REDO_CLIENTHANDLER_H
#define SOLID_SERVER_REDO_CLIENTHANDLER_H
#define DEFAULT_CAP 5
#include "IHandler.h"
using namespace std;
template<class Problem, class Solution, class Var>
class ClientHandler : public IHandler {
protected:
virtual Problem makeProblem(ifstream &inputStream) = 0;
virtual void writeSolution(ofstream &outputStream, Solution solution) = 0;
virtual void writeSolution(string solution, ofstream &outputStream) = 0;
virtual string solutionToString(Solution solution) = 0;
};
#endif //SOLID_SERVER_REDO_CLIENTHANDLER_H
|
/**
* Copyright 2017
*
* This file is part of On-line POMDP Planning Toolkit (OPPT).
* OPPT is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License published by the Free Software Foundation,
* either version 2 of the License, or (at your option) any later version.
*
* OPPT 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 OPPT.
* If not, see http://www.gnu.org/licenses/.
*/
#include "oppt/robotHeaders/RobotImpl/RobotImpl.hpp"
#include "oppt/robotHeaders/RobotImpl/RobotImplSDFParser.hpp"
#include "oppt/robotHeaders/RobotImpl/RobotImplSpaceInformationFactory.hpp"
#include "oppt/opptCore/EnvironmentInfo.hpp"
#include "oppt/plugin/Plugin.hpp"
#include "oppt/opptCore/CollisionObject.hpp"
#include "oppt/opptCore/CollisionRequest.hpp"
#ifdef USE_RVIZ
#include "oppt/viewerPublisher/ViewerPublisher.hpp"
#endif
namespace oppt
{
RobotImpl::RobotImpl(const std::string &worldFile,
const std::string &robotName,
const std::string &configFile,
const std::string &prefix,
unsigned int& threadId):
Robot(worldFile, robotName, configFile, prefix, threadId),
worldFile_(worldFile),
collisionLinks_(),
linkVisualGeometryMap_(),
dof_(0),
robotConfigOptions_()
{
std::unique_ptr <options::OptionParser> robotConfigParser =
RobotConfigOptions::makeParser(configFile);
robotConfigParser->setOptions(&robotConfigOptions_);
robotConfigParser->parseCfgFile(configFile);
robotConfigParser->finalize();
serializer_.reset(new RobotImplSerializer(worldFile));
// Default implementation of a discrete collision function
discreteCollisionFunction_ = [this](const RobotStateSharedPtr & state) {
RobotStateSharedPtr denormalizedState = stateSpace_->denormalizeState(state);
CollisionRequest collisionRequest;
collisionRequest.enableContact = true;
createRobotCollisionObjects(denormalizedState);
return environmentInfo_->getScene()->makeDiscreteCollisionReport(&collisionRequest);
};
// Default implementation of a continuous collision function
continuousCollisionFunction_ = [this](const RobotStateSharedPtr & state1,
const RobotStateSharedPtr & state2,
const unsigned int& numIterations) {
RobotStateSharedPtr denormalizedState1 = stateSpace_->denormalizeState(state1);
RobotStateSharedPtr denormalizedState2 = stateSpace_->denormalizeState(state2);
CollisionRequest collisionRequest;
collisionRequest.tfGoal = VectorFCLTransform3f(collisionLinks_.size());
collisionRequest.numIterations = numIterations;
// Get the goal transforms
createRobotCollisionObjects(denormalizedState2);
unsigned int idx = 0;
for (auto& robotCollisionObject : robotCollisionObjects_) {
// Unfortunately, we need to copy the transformation object here
FCLTransform3f tf = robotCollisionObject->getFCLCollisionObject()->getTransform();
fcl::Vec3f vec = tf.getTranslation();
fcl::Vec3f vec2(vec[0], vec[1], vec[2]);
fcl::Quaternion3f quat = tf.getQuatRotation();
fcl::Quaternion3f quat2(quat.getW(), quat.getX(), quat.getY(), quat.getZ());
FCLTransform3f tf2(quat2, vec2);
collisionRequest.tfGoal[idx] = tf2;
idx++;
}
createRobotCollisionObjects(denormalizedState1);
return environmentInfo_->getScene()->makeContinuousCollisionReport(&collisionRequest);
};
// Default implementation of a dirty collision function
dirtyCollisionFunction_ = [this](void *const data) {
auto linkPoses = gazeboInterface_->getLinksCollisionWorldPosesDirty(collisionLinks_);
for (size_t i = 0; i != linkPoses.size(); ++i) {
fcl::Quaternion3f fclQuat(linkPoses[i].orientation.w(),
linkPoses[i].orientation.x(),
linkPoses[i].orientation.y(),
linkPoses[i].orientation.z());
fcl::Vec3f translationVector(linkPoses[i].position.x(),
linkPoses[i].position.y(),
linkPoses[i].position.z());
fcl::Transform3f trans(fclQuat, translationVector);
robotCollisionObjects_[i]->getFCLCollisionObject()->setTransform(trans);
if (robotCollisionObjects_[i]->getFCLCollisionObject()->collisionGeometry())
robotCollisionObjects_[i]->getFCLCollisionObject()->computeAABB();
}
CollisionRequest collisionRequest;
collisionRequest.enableContact = false;
return environmentInfo_->getScene()->makeDiscreteCollisionReport(&collisionRequest);
};
}
bool RobotImpl::init()
{
RobotImplSDFParser sdfParser;
VectorGeometryUniquePtr robotLinkCollisionGeometries = std::move(sdfParser.parseCollisionGeometries(robotName_, worldFile_));
VectorGeometryUniquePtr invariantRobotCollisionGeometries;
VectorString collisionInvariantLinks = robotConfigOptions_.collisionInvariantLinks;
std::unordered_map<std::string, std::vector<GeometryUniquePtr>> linkCollisionGeometryMap;
for (auto& geometry : robotLinkCollisionGeometries) {
bool contains = false;
for (auto& collisionInvariantLink : collisionInvariantLinks) {
if (geometry->getName().find(collisionInvariantLink) != std::string::npos) {
contains = true;
}
}
VectorString elems;
split(geometry->getName(), "::", elems);
if (elems.size() < 2)
ERROR("Link has no parent model");
std::string linkName = elems[0] + "::" + elems[1];
if (!contains) {
if (linkCollisionGeometryMap.find(linkName) == linkCollisionGeometryMap.end())
linkCollisionGeometryMap[linkName] = std::vector<GeometryUniquePtr>();
linkCollisionGeometryMap.at(linkName).push_back(std::move(geometry));
} else {
invariantRobotCollisionGeometries.push_back(std::move(geometry));
}
}
VectorGeometryUniquePtr robotLinkVisualGeometries = sdfParser.parseVisualGeometries(robotName_, worldFile_);
for (auto& geometry : robotLinkVisualGeometries) {
linkVisualGeometryMap_[geometry->getName()] = std::move(geometry);
}
for (auto &collisionEntry : linkCollisionGeometryMap) {
for (auto &collisionGeometry : collisionEntry.second) {
OpptCollisionObjectUniquePtr opptCollisionObject(new OpptCollisionObject(std::move(collisionGeometry)));
robotCollisionObjects_.push_back(std::move(opptCollisionObject));
}
}
// Make the collision objects for the collision invariant links
for (auto &linkGeometry : invariantRobotCollisionGeometries) {
OpptCollisionObjectUniquePtr opptCollisionObject(new OpptCollisionObject(std::move(linkGeometry)));
invariantRobotCollisionObjects_.push_back(std::move(opptCollisionObject));
}
if (gazeboInterface_) {
VectorString robotLinksInWorld = gazeboInterface_->getRobotLinkNames();
for (auto& link : collisionInvariantLinks) {
if (!contains(robotLinksInWorld, link))
ERROR("link '" + link + "' not defined in your robot model");
}
//TODO: Filter out dimensionless links
collisionLinks_ = VectorString();
for (auto &entry : linkCollisionGeometryMap) {
collisionLinks_.push_back(entry.first);
}
gazeboInterface_->setCollisionCheckedLinks(collisionLinks_);
static_cast<RobotImplSerializer*>(serializer_.get())->setWorld(gazeboInterface_->getWorld());
}
return true;
}
VectorString RobotImpl::getCollisionCheckedLinks() const {
return collisionLinks_;
}
bool RobotImpl::makeStateSpace(StateSpaceInfo& stateSpaceInfo)
{
const StateSpaceInformationPtr stateSpaceInformation =
SpaceInformationFactory::makeStateSpaceInformation(&robotConfigOptions_, gazeboInterface_);
VectorFloat lowerLimits, upperLimits;
if (gazeboInterface_) {
gazeboInterface_->setStateSpaceInformation(stateSpaceInformation);
gazeboInterface_->getStateLimits(lowerLimits, upperLimits);
}
stateSpaceInfo.spaceVariables = stateSpaceInformation->orderedVariables;
// Limits for additional dimensions
for (auto& lowerUpper : stateSpaceInformation->lowerUpperLimitsAdditional) {
lowerLimits.push_back(lowerUpper[0]);
upperLimits.push_back(lowerUpper[1]);
}
stateSpaceInfo.numDimensions = lowerLimits.size();
stateSpace_ = std::make_shared<VectorStateSpace>(stateSpaceInfo);
if (stateSpace_->getNumDimensions() == 0)
WARNING("The state space has zero dimensions. "
"Have you forgotten to specify states in your robot configuration file?");
DistanceMetric distanceMetric = oppt::EuclideanMetric();
stateSpace_->setDistanceMetric(distanceMetric);
stateSpace_->as<VectorStateSpace>()->makeStateLimits(lowerLimits, upperLimits);
dof_ = stateSpaceInformation->jointPositions.size();
dof_ += stateSpaceInformation->containedLinkPositionsX.size();
dof_ += stateSpaceInformation->containedLinkPositionsY.size();
dof_ += stateSpaceInformation->containedLinkPositionsZ.size();
dof_ += 6 * stateSpaceInformation->containedLinkPoses.size();
serializer_->as<RobotImplSerializer>()->setStateSpace(stateSpace_.get());
//static_cast<RobotImplIntegrator*>(integrator.get())->setStateSpace(stateSpace_);
return true;
}
bool RobotImpl::makeActionSpace(ActionSpaceInfo& actionSpaceInfo)
{
const ActionSpaceInformationPtr actionSpaceInformation =
SpaceInformationFactory::makeActionSpaceInformation(&robotConfigOptions_, gazeboInterface_);
VectorFloat lowerLimits, upperLimits;
if (gazeboInterface_) {
gazeboInterface_->setActionSpaceInformation(actionSpaceInformation);
gazeboInterface_->getActionLimits(lowerLimits, upperLimits);
}
actionSpaceInfo.spaceVariables = actionSpaceInformation->orderedVariables;
// Limits for position increment controlled joints
for (auto& lowerUpper : actionSpaceInformation->lowerUpperLimitsJointPositionIncrements) {
lowerLimits.push_back(lowerUpper.first);
upperLimits.push_back(lowerUpper.second);
}
// Limits for additional dimensions
for (auto& lowerUpper : actionSpaceInformation->lowerUpperLimitsAdditional) {
lowerLimits.push_back(lowerUpper.first);
upperLimits.push_back(lowerUpper.second);
}
actionSpaceInfo.numDimensions = lowerLimits.size();
actionSpace_ = std::make_shared<oppt::ContinuousVectorActionSpace>(actionSpaceInfo);
actionSpace_->as<ContinuousVectorActionSpace>()->makeActionLimits(lowerLimits, upperLimits);
if (actionSpace_->getNumDimensions() == 0)
WARNING("The action space has zero dimensions. "
"Have you forgotten to specify actions in your robot configuration file?");
return true;
}
bool RobotImpl::makeObservationSpace(ObservationSpaceInfo& observationSpaceInfo)
{
const ObservationSpaceInformationPtr observationSpaceInformation =
SpaceInformationFactory::makeObservationSpaceInformation(&robotConfigOptions_, gazeboInterface_);
VectorFloat lowerLimits, upperLimits;
if (gazeboInterface_) {
gazeboInterface_->setObservationSpaceInformation(observationSpaceInformation);
gazeboInterface_->getObservationLimits(lowerLimits, upperLimits, robotConfigOptions_.ignoreGazeboSensors);
}
observationSpaceInfo.spaceVariables = observationSpaceInformation->orderedVariables;
// Limits for additional dimensions
for (auto& lowerUpper : observationSpaceInformation->lowerUpperLimitsAdditional) {
lowerLimits.push_back(lowerUpper[0]);
upperLimits.push_back(lowerUpper[1]);
}
observationSpaceInfo.numDimensions = lowerLimits.size();
if (gazeboInterface_)
gazeboInterface_->setObservationSpaceDimension(observationSpaceInfo.numDimensions);
observationSpace_ = std::make_shared<VectorObservationSpace>(observationSpaceInfo);
if (observationSpace_->getNumDimensions() == 0)
WARNING("The observation space has zero dimensions. "
"Have you forgotten to specify observations in your robot configuration file?");
observationSpace_->as<VectorObservationSpace>()->makeObservationLimits(lowerLimits, upperLimits);
return true;
}
void RobotImpl::createRobotCollisionObjects(const oppt::RobotStateSharedPtr& state) const
{
auto linkPoses = gazeboInterface_->getLinksCollisionWorldPoses(state, collisionLinks_);
for (size_t i = 0; i != linkPoses.size(); ++i) {
fcl::Quaternion3f fclQuat(linkPoses[i].orientation.w(),
linkPoses[i].orientation.x(),
linkPoses[i].orientation.y(),
linkPoses[i].orientation.z());
fcl::Vec3f translationVector(linkPoses[i].position.x(),
linkPoses[i].position.y(),
linkPoses[i].position.z());
FCLTransform3f trans(fclQuat, translationVector);
robotCollisionObjects_[i]->getFCLCollisionObject()->setTransform(trans);
if (robotCollisionObjects_[i]->getFCLCollisionObject()->collisionGeometry())
robotCollisionObjects_[i]->getFCLCollisionObject()->computeAABB();
}
}
CollisionReportSharedPtr RobotImpl::makeDiscreteCollisionReportDirty() const
{
if (!dirtyCollisionFunction_)
ERROR("No oppt::DirtyCollisionFunction defined");
return dirtyCollisionFunction_(nullptr);
}
unsigned int RobotImpl::getDOF() const
{
return dof_;
}
void RobotImpl::updateViewer(const oppt::RobotStateSharedPtr& state,
const std::vector<oppt::RobotStateSharedPtr>& particles,
const FloatType& particleOpacity,
const bool& keepParticles,
const bool& deleteExistingParticles)
{
#ifdef USE_RVIZ
if (viewer_ && viewer_->viewerRunning()) {
//state->getGazeboWorldState();
RobotStateSharedPtr denormalizedState = stateSpace_->denormalizeState(state);
VectorFloat stateVec = denormalizedState->as<VectorState>()->asVector();
VectorGeometryUniquePtr copiedRobotGeometries;
VectorGeometryPtr robotGeometries;
VectorString visualNames(linkVisualGeometryMap_.size());
size_t k = 0;
for (auto& linkGeomEntry : linkVisualGeometryMap_) {
visualNames[k] = linkGeomEntry.first;
k++;
}
std::vector<geometric::Pose> visualPoses;
gazeboInterface_->getRobotVisualPoses(stateVec, visualNames, visualPoses, denormalizedState->getGazeboWorldState());
for (size_t i = 0; i < visualNames.size(); i++) {
const GeometrySharedPtr geomInMap = linkVisualGeometryMap_.at(visualNames[i]);
GeometryUniquePtr geom = std::move(geomInMap->shallowCopy());
geom->setWorldPose(visualPoses[i]);
robotGeometries.push_back(geom.get());
copiedRobotGeometries.push_back(std::move(geom));
}
std::vector<std::vector<geometric::Pose>> particlePoses(particles.size());
for (size_t i = 0; i < particles.size(); i++) {
std::vector<geometric::Pose> particlePose;
denormalizedState = stateSpace_->denormalizeState(particles[i]);
stateVec = denormalizedState->as<VectorState>()->asVector();
gazeboInterface_->getRobotVisualPoses(stateVec, visualNames, visualPoses, denormalizedState->getGazeboWorldState());
for (size_t j = 0; j != visualNames.size(); j++) {
particlePose.push_back(visualPoses[j]);
}
particlePoses.push_back(particlePose);
}
static_cast<ViewerPublisher*>(viewer_.get())->drawGeometries(robotGeometries,
particlePoses,
particleOpacity,
keepParticles,
deleteExistingParticles);
// Make sure that the world state is the same as before updating the viewer
gazeboInterface_->setWorldState(state->getGazeboWorldState().get());
}
#endif
}
void RobotImpl::setEnvironmentInfo(oppt::EnvironmentInfoSharedPtr& environmentInfo)
{
Robot::setEnvironmentInfo(environmentInfo);
if (gazeboInterface_)
gazeboInterface_->setInteractive(environmentInfo->isInteractive());
}
void RobotImpl::initEnvironmentCallbacks()
{
if (environmentInfo_->isInteractive()) {
std::function<void(oppt::Body *const)> addBodyFn =
std::bind(&RobotImpl::addBodyCallback, this, std::placeholders::_1);
std::function<void(std::string)> removeBodyFn =
std::bind(&RobotImpl::removeBodyCallback, this, std::placeholders::_1);
std::function<void(const std::string&, const geometric::Pose&)> changePoseFn =
std::bind(&RobotImpl::changeBodyPoseCallback, this, std::placeholders::_1, std::placeholders::_2);
environmentInfo_->getScene()->setAddBodyCallback(addBodyFn);
environmentInfo_->getScene()->setRemoveBodyCallback(removeBodyFn);
environmentInfo_->getScene()->setChangeBodyPoseCallback(changePoseFn);
}
}
void RobotImpl::registerOnAddBodyCallback(std::function<void(const std::string&)>& callback)
{
if (environmentInfo_->isInteractive() and gazeboInterface_)
gazeboInterface_->registerOnAddBodyCallback(callback);
}
void RobotImpl::registerOnRemoveBodyCallback(std::function<void(const std::string&)>& callback)
{
if (environmentInfo_->isInteractive() and gazeboInterface_)
gazeboInterface_->registerOnRemoveBodyCallback(callback);
}
void RobotImpl::registerOnPoseChangedCallback(std::function < void(const std::string&,
const geometric::Pose&) >& callback)
{
if (environmentInfo_->isInteractive() and gazeboInterface_)
gazeboInterface_->registerOnPoseChangedCallback(callback);
}
void RobotImpl::addBodyCallback(Body *const body)
{
std::string sdfString = body->toSDFString();
gazeboInterface_->addBodyFromSDFString(sdfString);
}
void RobotImpl::removeBodyCallback(std::string name)
{
gazeboInterface_->removeBody(name);
}
void RobotImpl::changeBodyPoseCallback(const std::string& name, const geometric::Pose& poseVec)
{
gazeboInterface_->changeModelPose(name, poseVec);
}
void RobotImpl::setCollisionsAllowed(const bool& collisionsAllowed) const
{
Robot::setCollisionsAllowed(collisionsAllowed);
if (!collisionsAllowed and gazeboInterface_)
gazeboInterface_->setDirtyCollisionFunction(dirtyCollisionFunction_);
}
void RobotImpl::setDirtyCollisionFunction(DirtyCollisionFunction dirtyCollisionFunction)
{
dirtyCollisionFunction_ = dirtyCollisionFunction;
if (gazeboInterface_)
gazeboInterface_->setDirtyCollisionFunction(dirtyCollisionFunction_);
}
}
|
#ifndef CLIENT_HPP
#define CLIENT_HPP
#include <sys/socket.h> // Core BSD socket functions and data structures
#include <sys/fcntl.h> // for the non-blocking socket
#include <arpa/inet.h> // for manipulating IP addresses, for inet_addr()
#include <unistd.h> // for close()
#include <iostream>
#include <vector>
#include <string>
#include <cerrno> // for errno
#include <cstring> // for std::memset() and std::strerror()
#include <QtConcurrent>
#include <QObject>
#include <QMetaType>
class Client : public QObject
{
Q_OBJECT
public:
explicit Client(QObject* parent = nullptr);
Client( const std::string ip, const int port = 2025 );
~Client();
std::string getUsername() { return username; }
bool create_socket();
bool connect_to_server();
bool execute_register( std::string full_name, std::string login, std::string password );
bool execute_login( std::string login, std::string password );
public:
void send_global_message( std::string message );
void send_private_message( std::vector<std::string> dest_names, std::string message );
private:
void recv_thread();
private:
const std::string ip_addres;
const int port_number;
std::string username;
int socket_desc;
struct sockaddr_in server_addr;
signals:
void login_success();
void register_success();
void online_user( QString new_online_user );
void offline_user( QString gone_offline_user );
void global_message_received( QString sender, QString message );
void private_message_received( QString sender, QString message );
// capturing an internal signals, here recv_thread() is starting immediately
private slots:
void on_login_register_success();
};
#endif // CLIENT_HPP
|
#include <iostream>
using namespace std;
int main(){
int num = 0;
for(int i = 100 ; i < 100000 ; i++){
int w = i;
int flag1 = false,flag2 = false;
int temp1 = w%10;
w = w/10;
int temp2 = w%10;
while(temp2<temp1){
w = w/10;
temp1 = temp2;
temp2 = w%10;
flag1 = true;
}
while(temp2>temp1){
w = w/10;
temp1 = temp2;
temp2 = w%10;
flag2 = true;
}
if(w==0&&flag1==true&&flag2==true){
num++;
cout << i << endl;
}
}
cout << num;
return 0;
}
|
#include "MainWindow.hpp"
#include "ui_MainWindow.h"
#include <QDebug>
#include <QDir>
#include <QDesktopServices>
#include <QMessageBox>
#include "EditGroup.hpp"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
for (int i = 0; i<5; ++i)
m_course[i] = new QStringListModel(this);
m_courseView[0] = ui->course1List;
m_courseView[1] = ui->course2List;
m_courseView[2] = ui->course3List;
m_courseView[3] = ui->course4List;
m_courseView[4] = ui->course5List;
for (int i = 0; i<5; ++i)
{
m_courseView[i]->setModel(m_course[i]);
connect(m_courseView[i], SIGNAL(doubleClicked(QModelIndex)), this, SLOT(groupClicked(QModelIndex)));
}
connect(ui->subjectListEdit, SIGNAL(back()), this, SLOT(showCourses()));
load();
}
void MainWindow::groupClicked(const QModelIndex &index)
{
groupClicked(index.data().toString());
}
void MainWindow::groupClicked(const QString &group)
{
Q_ASSERT(m_groupByName.contains(group));
Group &group_ = m_groupByName[group];
ui->stack->setCurrentWidget(ui->subjects);
ui->subjectListEdit->setGroup(group_);
}
void MainWindow::repack()
{
QStringList course[5];
foreach (const Group &group, m_groupByName.values())
{
course[group.course()-1].append(group.name());
}
for (int i = 0; i<5; ++i)
m_course[i]->setStringList(course[i]);
}
void MainWindow::showAddGroupDialog()
{
EditGroup *editGroup = new EditGroup(m_groupByName, QString(), this);
editGroup->exec();
editGroup->deleteLater();
repack();
}
void MainWindow::removeGroups()
{
for (int i = 0; i<5; ++i)
{
QModelIndexList selected = m_courseView[i]->selectionModel()->selectedIndexes();
foreach (const QModelIndex &index, selected)
{
m_groupByName.remove(index.data().toString());
}
}
repack();
}
void MainWindow::showCourses()
{
ui->stack->setCurrentWidget(ui->courses);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::closeEvent(QCloseEvent *)
{
save();
}
QString MainWindow::storageDir()
{
return QDesktopServices::storageLocation(QDesktopServices::DataLocation);
}
QString MainWindow::storage()
{
return storageDir()+QDir::separator()+"db.data";
}
static const quint64 magic = 0xf35dde19df793d6bULL;
void MainWindow::load()
{
QFile db(storage());
if (db.exists())
{
const bool ret = db.open(QIODevice::ReadOnly);
Q_ASSERT(ret);
QDataStream input(&db);
quint64 fmagic;
input>>fmagic;
if (fmagic==::magic)
{
input>>m_groupByName;
repack();
}
}
}
void MainWindow::save()
{
qDebug()<<storage();
QFile db(storage());
QDir dir = QDir::rootPath();
dir.mkpath(storageDir());
const bool ret = db.open(QIODevice::WriteOnly);
Q_ASSERT(ret);
QDataStream output(&db);
output<<magic;
output<<m_groupByName;
}
void MainWindow::clearDB()
{
int ret = QMessageBox::question(
this, trUtf8("Очистка"),
trUtf8("Вы уверены, что хотите очистить базу данных? Данные будут утеряны безвозвратно!"),
QMessageBox::Ok, QMessageBox::Cancel);
if (ret==QMessageBox::Ok)
{
m_groupByName.clear();
repack();
}
}
|
#ifndef _HS_SFM_BUNDLE_ADJUSTMENT_CAMERA_SHARED_NORMAL_EQUATION_SOLVER_HPP_
#define _HS_SFM_BUNDLE_ADJUSTMENT_CAMERA_SHARED_NORMAL_EQUATION_SOLVER_HPP_
#include "hs_sfm/bundle_adjustment/camera_shared_vector_function.hpp"
#include "hs_sfm/bundle_adjustment/camera_shared_augmented_normal_matrix.hpp"
#include "hs_sfm/bundle_adjustment/camera_shared_gradient.hpp"
namespace hs
{
namespace sfm
{
namespace ba
{
template <typename _Scalar>
class CameraSharedNormalEquationSolver
{
public:
typedef _Scalar Scalar;
typedef int Err;
typedef CameraSharedVectorFunction<Scalar> VectorFunction;
typedef CameraSharedAugmentedNormalMatrix<Scalar> AugmentedNormalMatrix;
typedef CameraSharedGradient<Scalar> Gradient;
typedef typename VectorFunction::XVector DeltaXVector;
private:
typedef typename VectorFunction::XVector XVector;
typedef typename VectorFunction::YVector YVector;
typedef typename VectorFunction::Index Index;
static const Index params_per_point_ = VectorFunction::params_per_point_;
static const Index params_per_key_ = VectorFunction::params_per_key_;
static const Index extrinsic_params_per_image_ =
VectorFunction::extrinsic_params_per_image_;
typedef typename AugmentedNormalMatrix::NormalMatrix NormalMatrix;
typedef typename NormalMatrix::PointBlock PointBlock;
typedef typename NormalMatrix::ImageBlock ImageBlock;
typedef typename NormalMatrix::CameraBlock CameraBlock;
typedef typename NormalMatrix::PointImageBlock PointImageBlock;
typedef typename NormalMatrix::PointCameraBlock PointCameraBlock;
typedef typename NormalMatrix::ImageCameraBlock ImageCameraBlock;
typedef typename Gradient::PointSegment PointSegment;
typedef EIGEN_MATRIX(Scalar, extrinsic_params_per_image_, params_per_point_)
ImagePointBlock;
typedef EIGEN_MATRIX(Scalar, Eigen::Dynamic, params_per_point_)
CameraPointBlock;
typedef EIGEN_STD_VECTOR(ImagePointBlock) ImagePointBlockContainer;
typedef EIGEN_STD_VECTOR(CameraPointBlock) CameraPointBlockContainer;
typedef typename ImagePointBlockContainer::size_type BlockIdx;
enum
{
EigenDefaultMajor =
#if defined(EIGEN_DEFAULT_TO_ROW_MAJOR)
Eigen::RowMajor
#else
Eigen::ColMajor
#endif
};
typedef EIGEN_SPARSE_MATRIX(BlockIdx, EigenDefaultMajor, Index)
SparseBlockMap;
typedef Eigen::Triplet<BlockIdx, Index> BlockTriplet;
typedef std::vector<BlockTriplet> BlockTripletContainer;
public:
typedef EIGEN_SPARSE_MATRIX(Scalar, EigenDefaultMajor, Index)
ReducedMatrix;
typedef Eigen::Triplet<Scalar, Index> ReducedTriplet;
typedef std::vector<ReducedTriplet> ReducedTripletContainer;
typedef EIGEN_VECTOR(Scalar, Eigen::Dynamic) ReducedRHS;
public:
Err operator() (const AugmentedNormalMatrix& augmented_normal_matrix,
const Gradient& gradient,
DeltaXVector& delta_x) const
{
const NormalMatrix& normal_matrix =
augmented_normal_matrix.normal_matrix_ref();
const FixMask& fix_mask = normal_matrix.fix_mask();
if (!fix_mask[FIX_POINTS])
{
if (!fix_mask[FIX_IMAGES] || !fix_mask[FIX_CAMERAS])
{
ReducedMatrix reduced_matrix;
ReducedRHS reduced_rhs;
if (ComputeReducedSystem(augmented_normal_matrix, gradient,
reduced_matrix, reduced_rhs) != 0) return -1;
Index number_of_points = Index(normal_matrix.number_of_points());
Index x_size = normal_matrix.GetXSize();
delta_x.resize(x_size);
if (SolveReducedSystem(reduced_matrix, reduced_rhs,
number_of_points * params_per_point_,
delta_x) != 0)
return -1;
if (BackSubstitution(augmented_normal_matrix, gradient, delta_x) != 0)
return -1;
return 0;
}
else
{
return SolvePointsOnly(augmented_normal_matrix, gradient, delta_x);
}
}
else
{
return SolveImagesCamerasOnly(augmented_normal_matrix, gradient, delta_x);
}
}
Err ComputeReducedSystem(const AugmentedNormalMatrix& augmented_normal_matrix,
const Gradient& gradient,
ReducedMatrix& reduced_matrix,
ReducedRHS& reduced_rhs) const
{
const NormalMatrix& normal_matrix =
augmented_normal_matrix.normal_matrix_ref();
const FixMask& fix_mask = normal_matrix.fix_mask();
if (fix_mask[FIX_POINTS] ||
(fix_mask[FIX_IMAGES] && fix_mask[FIX_CAMERAS])) return -1;
Scalar mu = augmented_normal_matrix.mu();
Index number_of_points = Index(normal_matrix.number_of_points());
Index number_of_images = Index(normal_matrix.number_of_images());
Index number_of_cameras = Index(normal_matrix.number_of_cameras());
Index camera_params_size = normal_matrix.camera_params_size();
Index cameras_begin =
fix_mask[FIX_IMAGES] ? 0 : number_of_images * extrinsic_params_per_image_;
Index reduced_size =
cameras_begin +
(fix_mask[FIX_CAMERAS] ? 0 : number_of_cameras * camera_params_size);
ImagePointBlockContainer weighted_image_point_blocks;
BlockTripletContainer image_point_triplets;
CameraPointBlockContainer weighted_camera_point_blocks;
BlockTripletContainer camera_point_triplets;
for (Index point_id = 0; point_id < number_of_points; point_id++)
{
PointBlock point_block = normal_matrix.GetPointBlock(point_id);
for (Index i = 0; i < params_per_point_; i++)
{
point_block(i, i) += mu;
}
PointBlock point_inverse = point_block.inverse();
if (!fix_mask[FIX_IMAGES])
{
for (Index image_id = 0; image_id < number_of_images; image_id++)
{
const PointImageBlock* point_image_block =
normal_matrix.GetPointImageBlock(point_id, image_id);
if (point_image_block != NULL)
{
ImagePointBlock weighted_image_point_block =
(*point_image_block).transpose() * point_inverse;
weighted_image_point_blocks.push_back(weighted_image_point_block);
image_point_triplets.push_back(
BlockTriplet(image_id, point_id,
weighted_image_point_blocks.size()));
}
}//for (Index image_id = 0; image_id < number_of_images; image_id++)
}
if (!fix_mask[FIX_CAMERAS])
{
for (Index camera_id = 0; camera_id < number_of_cameras; camera_id++)
{
const PointCameraBlock* point_camera_block =
normal_matrix.GetPointCameraBlock(point_id, camera_id);
if (point_camera_block != NULL)
{
CameraPointBlock weighted_camera_point_block =
(*point_camera_block).transpose() * point_inverse;
weighted_camera_point_blocks.push_back(weighted_camera_point_block);
camera_point_triplets.push_back(
BlockTriplet(camera_id, point_id,
weighted_camera_point_blocks.size()));
}
}//for (Index camera_id = 0; camera_id < number_of_cameras; camera_id++)
}
}//for (Index point_id = 0; point_id < number_of_points; point_id++
SparseBlockMap image_point_map(number_of_images, number_of_points);
SparseBlockMap camera_point_map(number_of_cameras, number_of_points);
if (!fix_mask[FIX_IMAGES])
{
image_point_map.setFromTriplets(image_point_triplets.begin(),
image_point_triplets.end());
}
if (!fix_mask[FIX_CAMERAS])
{
camera_point_map.setFromTriplets(camera_point_triplets.begin(),
camera_point_triplets.end());
}
ReducedTripletContainer reduced_triplets;
if (!fix_mask[FIX_IMAGES])
{
for (Index weighted_image_id = 0; weighted_image_id < number_of_images;
weighted_image_id++)
{
for (Index image_id = weighted_image_id;
image_id < number_of_images; image_id++)
{
ImageBlock image_block = ImageBlock::Zero();
if (weighted_image_id == image_id)
{
image_block = normal_matrix.GetImageBlock(image_id);
for (Index i = 0; i < extrinsic_params_per_image_; i++)
{
image_block(i, i) += mu;
}
}
bool exist = false;
for (Index point_id = 0; point_id < number_of_points; point_id++)
{
BlockIdx weighted_image_point_id =
image_point_map.coeff(weighted_image_id, point_id);
const PointImageBlock* point_image_block =
normal_matrix.GetPointImageBlock(point_id, image_id);
if (weighted_image_point_id > 0 && point_image_block != NULL)
{
const ImagePointBlock& weighted_image_point_block =
weighted_image_point_blocks[weighted_image_point_id - 1];
image_block -= weighted_image_point_block * (*point_image_block);
exist = true;
}
}// for (Index point_id = 0; point_id < number_of_points; point_id++)
if (exist)
{
if (weighted_image_id == image_id)
{
for (Index i = 0; i < extrinsic_params_per_image_; i++)
{
for (Index j = 0; j < extrinsic_params_per_image_; j++)
{
reduced_triplets.push_back(
ReducedTriplet(image_id * extrinsic_params_per_image_ + i,
image_id * extrinsic_params_per_image_ + j,
image_block(i, j)));
}// for (Index j = 0; j < extrinsic_params_per_image_; j++)
}// for (Index i = 0; i < extrinsic_params_per_image_; i++)
}// if (weighted_image_id == image_id)
else
{
for (Index i = 0; i < extrinsic_params_per_image_; i++)
{
for (Index j = 0; j < extrinsic_params_per_image_; j++)
{
Index row_id =
weighted_image_id * extrinsic_params_per_image_ + i;
Index col_id =
image_id * extrinsic_params_per_image_ + j;
reduced_triplets.push_back(
ReducedTriplet(row_id, col_id, image_block(i, j)));
reduced_triplets.push_back(
ReducedTriplet(col_id, row_id, image_block(i, j)));
}// for (Index j = 0; j < extrinsic_params_per_image_; j++)
}// for (Index i = 0; i < extrinsic_params_per_image_; i++)
}
}// if (exist)
}
}
}// if (!fix_mask[FIX_IMAGES])
if (!fix_mask[FIX_CAMERAS])
{
for (Index weighted_camera_id = 0;
weighted_camera_id < number_of_cameras; weighted_camera_id++)
{
for (Index camera_id = weighted_camera_id;
camera_id < number_of_cameras; camera_id++)
{
CameraBlock camera_block = CameraBlock::Zero(camera_params_size,
camera_params_size);
if (weighted_camera_id == camera_id)
{
camera_block = normal_matrix.GetCameraBlock(camera_id);
for (Index i = 0; i < camera_params_size; i++)
{
camera_block(i, i) += mu;
}
}
bool exist = false;
for (Index point_id = 0; point_id < number_of_points; point_id++)
{
BlockIdx weighted_camera_point_id =
camera_point_map.coeff(weighted_camera_id, point_id);
const PointCameraBlock* point_camera_block =
normal_matrix.GetPointCameraBlock(point_id, camera_id);
if (weighted_camera_point_id > 0 && point_camera_block != NULL)
{
const CameraPointBlock& weighted_camera_point_block =
weighted_camera_point_blocks[weighted_camera_point_id - 1];
camera_block -= weighted_camera_point_block * (*point_camera_block);
exist = true;
}
}//for (Index point_id = 0; point_id < number_of_points; point_id++)
if (exist)
{
if (weighted_camera_id == camera_id)
{
for (Index i = 0; i < camera_params_size; i++)
{
for (Index j = 0; j < camera_params_size; j++)
{
Index row_id =
cameras_begin + camera_id * camera_params_size + i;
Index col_id =
cameras_begin + camera_id * camera_params_size + j;
reduced_triplets.push_back(
ReducedTriplet(row_id, col_id, camera_block(i, j)));
}//for (Index j = 0; j < camera_params_size; j++)
}// for (Index i = 0; i < camera_params_size; i++)
}// if (weighted_camera_id == camera_id)
else
{
for (Index i = 0; i < camera_params_size; i++)
{
for (Index j = 0; j < camera_params_size; j++)
{
Index row_id =
cameras_begin + weighted_camera_id * camera_params_size + i;
Index col_id =
cameras_begin + camera_id * camera_params_size + j;
reduced_triplets.push_back(
ReducedTriplet(row_id, col_id, camera_block(i, j)));
reduced_triplets.push_back(
ReducedTriplet(col_id, row_id, camera_block(i, j)));
}//for (Index j = 0; j < camera_params_size; j++)
}// for (Index i = 0; i < camera_params_size; i++)
}
}// if (exist)
}
}
}// if (!fix_mask[FIX_CAMERAS])
if (!fix_mask[FIX_CAMERAS] && !fix_mask[FIX_IMAGES])
{
for (Index image_id = 0; image_id < number_of_images; image_id++)
{
for (Index camera_id = 0; camera_id < number_of_cameras; camera_id++)
{
ImageCameraBlock image_camera_block =
ImageCameraBlock::Zero(extrinsic_params_per_image_,
camera_params_size);
const ImageCameraBlock* image_camera_block_ptr =
normal_matrix.GetImageCameraBlock(image_id, camera_id);
if (image_camera_block_ptr != NULL)
{
image_camera_block = *image_camera_block_ptr;
}
bool exist = false;
for (Index point_id = 0; point_id < number_of_points; point_id++)
{
const PointCameraBlock* point_camera_block =
normal_matrix.GetPointCameraBlock(point_id, camera_id);
BlockIdx weighted_image_point_id =
image_point_map.coeff(image_id, point_id);
if (weighted_image_point_id > 0 && point_camera_block != NULL)
{
const ImagePointBlock& weighted_image_point_block =
weighted_image_point_blocks[weighted_image_point_id - 1];
image_camera_block -= weighted_image_point_block *
(*point_camera_block);
exist = true;
}// if (weighted_point_camera_id > 0 && point_image_block != NULL)
}// for (Index point_id = 0; point_id < number_of_points; point_id++)
if (exist)
{
for (Index i = 0; i < extrinsic_params_per_image_; i++)
{
for (Index j = 0; j < camera_params_size; j++)
{
Index row_id = image_id * extrinsic_params_per_image_ + i;
Index col_id = cameras_begin +
camera_id * camera_params_size + j;
reduced_triplets.push_back(
ReducedTriplet(row_id, col_id, image_camera_block(i, j)));
reduced_triplets.push_back(
ReducedTriplet(col_id, row_id, image_camera_block(i, j)));
}//for (Index j = 0; j < camera_params_size; j++)
}//for (Index i = 0; i < extrinsic_params_per_image_; i++)
}
}//for (Index camera_id = 0; camera_id < number_of_cameras; camera_id++)
}//for (Index image_id = 0; image_id < number_of_images; image_id++)
}
reduced_matrix.resize(reduced_size, reduced_size);
reduced_matrix.setFromTriplets(reduced_triplets.begin(),
reduced_triplets.end());
reduced_rhs.resize(reduced_size);
if (!fix_mask[FIX_IMAGES])
{
for (Index image_id = 0; image_id < number_of_images; image_id++)
{
reduced_rhs.segment(image_id * extrinsic_params_per_image_,
extrinsic_params_per_image_) =
gradient.GetImageSegment(image_id);
for (Index point_id = 0; point_id < number_of_points; point_id++)
{
BlockIdx weighted_image_point_id =
image_point_map.coeff(image_id, point_id);
if (weighted_image_point_id > 0)
{
const ImagePointBlock& weighted_image_point_block =
weighted_image_point_blocks[weighted_image_point_id - 1];
reduced_rhs.segment(image_id * extrinsic_params_per_image_,
extrinsic_params_per_image_) -=
weighted_image_point_block * gradient.GetPointSegment(point_id);
}
}// for (Index point_id = 0; point_id < number_of_points; point_id++)
}// for (Index image_id = 0; image_id < number_of_images; image_id++)
}
if (!fix_mask[FIX_CAMERAS])
{
for (Index camera_id = 0; camera_id < number_of_cameras; camera_id++)
{
reduced_rhs.segment(cameras_begin + camera_id * camera_params_size,
camera_params_size) =
gradient.GetCameraSegment(camera_id);
for (Index point_id; point_id < number_of_points; point_id++)
{
BlockIdx weighted_camera_point_id =
camera_point_map.coeff(camera_id, point_id);
if (weighted_camera_point_id > 0)
{
const CameraPointBlock& weighted_camera_point_block =
weighted_camera_point_blocks[weighted_camera_point_id - 1];
reduced_rhs.segment(cameras_begin + camera_id * camera_params_size,
camera_params_size) -=
weighted_camera_point_block * gradient.GetPointSegment(point_id);
}
}// for (Index point_id; point_id < number_of_points; point_id++)
}// for (Index camera_id = 0; camera_id < number_of_cameras; camera_id++)
}
return 0;
}
Err SolveReducedSystem(const ReducedMatrix& reduced_matrix,
const ReducedRHS& reduced_rhs,
Index reduced_system_begin,
DeltaXVector& delta_x) const
{
Eigen::SimplicialLDLT<ReducedMatrix> solver;
solver.compute(reduced_matrix);
if (solver.info() != Eigen::Success)
{
return -1;
}
delta_x.segment(reduced_system_begin, reduced_rhs.rows()) =
solver.solve(reduced_rhs);
if (solver.info() != Eigen::Success)
{
return -1;
}
return 0;
}
Err BackSubstitution(const AugmentedNormalMatrix& augmented_normal_matrix,
const Gradient& gradient,
DeltaXVector& delta_x) const
{
const NormalMatrix& normal_matrix =
augmented_normal_matrix.normal_matrix_ref();
const FixMask& fix_mask = normal_matrix.fix_mask();
if (fix_mask[FIX_POINTS] ||
(fix_mask[FIX_IMAGES] && fix_mask[FIX_CAMERAS])) return -1;
Scalar mu = augmented_normal_matrix.mu();
Index number_of_points = Index(normal_matrix.number_of_points());
Index number_of_images = Index(normal_matrix.number_of_images());
Index number_of_cameras = Index(normal_matrix.number_of_cameras());
Index camera_params_size = normal_matrix.camera_params_size();
Index cameras_begin =
fix_mask[FIX_IMAGES] ? 0 : number_of_images * extrinsic_params_per_image_;
Index reduced_size =
cameras_begin +
(fix_mask[FIX_CAMERAS] ? 0 : number_of_cameras * camera_params_size);
for (Index point_id = 0; point_id < number_of_points; point_id++)
{
PointBlock point_block = normal_matrix.GetPointBlock(point_id);
for (Index i = 0; i < params_per_point_; i++)
{
point_block(i, i) += mu;
}
PointBlock point_block_inverse = point_block.inverse();
PointSegment point_segment = point_block_inverse *
gradient.GetPointSegment(point_id);
if (!fix_mask[FIX_IMAGES])
{
for (Index image_id = 0; image_id < number_of_images; image_id++)
{
const PointImageBlock* point_image_block =
normal_matrix.GetPointImageBlock(point_id, image_id);
if (point_image_block != NULL)
{
point_segment -=
point_block_inverse * (*point_image_block) *
delta_x.segment(number_of_points * params_per_point_ +
image_id * extrinsic_params_per_image_,
extrinsic_params_per_image_);
}
}
}
if (!fix_mask[FIX_CAMERAS])
{
for (Index camera_id = 0; camera_id < number_of_cameras; camera_id++)
{
const PointCameraBlock* point_camera_block =
normal_matrix.GetPointCameraBlock(point_id, camera_id);
if (point_camera_block != NULL)
{
point_segment -=
point_block_inverse * (*point_camera_block) *
delta_x.segment(number_of_points * params_per_point_ +
cameras_begin +
camera_id * camera_params_size,
camera_params_size);
}
}
}
delta_x.segment(point_id * params_per_point_, params_per_point_) =
point_segment;
}
return 0;
}
Err SolvePointsOnly(const AugmentedNormalMatrix& augmented_normal_matrix,
const Gradient& gradient,
DeltaXVector& delta_x) const
{
const NormalMatrix& normal_matrix =
augmented_normal_matrix.normal_matrix_ref();
const FixMask& fix_mask = normal_matrix.fix_mask();
if (!(!fix_mask[FIX_POINTS] &&
fix_mask[FIX_IMAGES] &&
fix_mask[FIX_CAMERAS])) return -1;
Index x_size = normal_matrix.GetXSize();
delta_x.resize(x_size);
Scalar mu = augmented_normal_matrix.mu();
Index number_of_points = Index(normal_matrix.number_of_points());
for (Index point_id = 0; point_id < number_of_points; point_id++)
{
PointBlock point_block = normal_matrix.GetPointBlock(point_id);
for (Index i = 0; i < params_per_point_; i++)
{
point_block(i, i) += mu;
}
PointBlock point_inverse = point_block.inverse();
delta_x.segment(point_id * params_per_point_, params_per_point_) =
point_inverse *
gradient.GetPointSegment(point_id);
}
return 0;
}
Err SolveImagesCamerasOnly(
const AugmentedNormalMatrix& augmented_normal_matrix,
const Gradient& gradient,
DeltaXVector& delta_x) const
{
const NormalMatrix& normal_matrix =
augmented_normal_matrix.normal_matrix_ref();
const FixMask& fix_mask = normal_matrix.fix_mask();
if (!fix_mask[FIX_POINTS] ||
(fix_mask[FIX_IMAGES] && fix_mask[FIX_CAMERAS])) return -1;
Index x_size = normal_matrix.GetXSize();
delta_x.resize(x_size);
Scalar mu = augmented_normal_matrix.mu();
Index number_of_images = Index(normal_matrix.number_of_images());
Index number_of_cameras = Index(normal_matrix.number_of_cameras());
Index camera_params_size = normal_matrix.camera_params_size();
Index cameras_begin =
fix_mask[FIX_IMAGES] ? 0 : number_of_images * extrinsic_params_per_image_;
ReducedTripletContainer reduced_triplets;
if (!fix_mask[FIX_IMAGES])
{
for (Index image_id = 0; image_id < number_of_images; image_id++)
{
ImageBlock image_block = normal_matrix.GetImageBlock(image_id);
for (Index i = 0; i < extrinsic_params_per_image_; i++)
{
image_block(i, i) += mu;
}
for (Index i = 0; i < extrinsic_params_per_image_; i++)
{
for (Index j = 0; j < extrinsic_params_per_image_; j++)
{
Index row_id = image_id * extrinsic_params_per_image_ + i;
Index col_id = image_id * extrinsic_params_per_image_ + j;
reduced_triplets.push_back(
ReducedTriplet(row_id, col_id, image_block(i, j)));
}
}
}// for (Index image_id = 0; image_id < number_of_images; image_id++)
}// if (!fix_mask[FIX_IMAGES])
if (!fix_mask[FIX_CAMERAS])
{
for (Index camera_id = 0; camera_id < number_of_cameras; camera_id++)
{
CameraBlock camera_block = normal_matrix.GetCameraBlock(camera_id);
for (Index i = 0; i < camera_params_size; i++)
{
camera_block(i, i) += mu;
}
for (Index i = 0; i < camera_params_size; i++)
{
for (Index j = 0; j < camera_params_size; j++)
{
Index row_id = cameras_begin + camera_id * camera_params_size + i;
Index col_id = cameras_begin + camera_id * camera_params_size + j;
reduced_triplets.push_back(
ReducedTriplet(row_id, col_id, camera_block(i, j)));
}
}
}
}// if (!fix_mask[FIX_CAMERAS])
if (!fix_mask[FIX_IMAGES] && !fix_mask[FIX_CAMERAS])
{
for (Index image_id = 0; image_id < number_of_images; image_id++)
{
for (Index camera_id = 0; camera_id < number_of_cameras; camera_id++)
{
const ImageCameraBlock* image_camera_block_ptr =
normal_matrix.GetImageCameraBlock(image_id, camera_id);
if (image_camera_block_ptr != NULL)
{
for (Index i = 0; i < extrinsic_params_per_image_; i++)
{
for (Index j = 0; j < camera_params_size; j++)
{
Index row_id = image_id * extrinsic_params_per_image_ + i;
Index col_id = cameras_begin +
camera_id * camera_params_size + j;
reduced_triplets.push_back(
ReducedTriplet(row_id, col_id,
(*image_camera_block_ptr)(i, j)));
reduced_triplets.push_back(
ReducedTriplet(col_id, row_id,
(*image_camera_block_ptr)(i, j)));
}
}
}// if (image_camera_block_ptr != NULL)
}//for (Index camera_id = 0; camera_id < number_of_cameras; camera_id++)
}//for (Index image_id = 0; image_id < number_of_images; image_id++)
}// if (!fix_mask[FIX_IMAGES] && !fix_mask[FIX_CAMERAS])
ReducedMatrix reduced_matrix(x_size, x_size);
reduced_matrix.setFromTriplets(reduced_triplets.begin(),
reduced_triplets.end());
ReducedRHS reduced_rhs(x_size);
if (!fix_mask[FIX_IMAGES])
{
for (Index image_id = 0; image_id < number_of_images; image_id++)
{
reduced_rhs.segment(image_id * extrinsic_params_per_image_,
extrinsic_params_per_image_) =
gradient.GetImageSegment(image_id);
}
}
if (!fix_mask[FIX_CAMERAS])
{
for (Index camera_id = 0; camera_id < number_of_cameras; camera_id++)
{
reduced_rhs.segment(
cameras_begin + camera_id * camera_params_size,
camera_params_size) = gradient.GetCameraSegment(camera_id);
}
}
Eigen::SimplicialLDLT<ReducedMatrix> solver;
solver.compute(reduced_matrix);
if (solver.info() != Eigen::Success)
{
return -1;
}
delta_x = solver.solve(reduced_rhs);
if (solver.info() != Eigen::Success)
{
return -1;
}
return 0;
}
};
}
}
}
#endif
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
QDate lock(2010,06,17);
if(QDate::currentDate() > lock){
ui->setupUi(this);
QString loc = QCoreApplication::applicationDirPath()+"/setting2.db";
QFile setting_f(":/Rc/DB/setting2.db");
QFile setti(loc);
if(setti.exists()){
db1 = QSqlDatabase::addDatabase("QSQLITE","setting");
db1.setDatabaseName(loc);
if( db1.open()){
}
else{
ui->statusBar->showMessage("Error Error",2000000);
}
}else {
QFile::copy(":/Rc/DB/setting2.db",loc);
QFile::setPermissions(loc,QFileDevice::WriteOther);
db1 = QSqlDatabase::addDatabase("QSQLITE","setting");
db1.setDatabaseName(loc);
if( db1.open()){
}
else{
ui->statusBar->showMessage("Error Error",2000000);
}
}
QSqlQuery qry(db1);
qry.prepare("SELECT * FROM db_default");
if( qry.exec() ){
while (qry.next())
{
type = qry.value(0).toString();
}
}
else{
qDebug() << "Error hhhhhh into the table:\n" << qry.lastError();
}
if (type == "File Based"){
QSqlQuery qry1(db1);
qry1.prepare("SELECT * FROM file_data");
if( qry1.exec() ){
while (qry1.next())
{
loc_data = qry1.value(1).toString();
}
}
else{
qDebug() << "Error inserting into the table:\n" << qry1.lastError();
}
db = QSqlDatabase::addDatabase("QSQLITE","test");
db.setDatabaseName(loc_data);
}
else {
QSqlQuery qry1(db1);
qry1.prepare("SELECT * FROM server_data");
if( qry1.exec() ){
while (qry1.next())
{
server_host = qry1.value(0).toString();
server_user = qry1.value(1).toString();
server_pass = qry1.value(2).toString();
}
}
else{
qDebug() << "Error inserting into the table:\n" << qry1.lastError();
}
QSqlQuery qry2(db1);
qry2.prepare("SELECT * FROM version");
if( qry2.exec() ){
while (qry2.next())
{
version = qry2.value(0).toInt();
}
}
else{
qDebug() << "Error inserting into the table:\n" << qry1.lastError();
}
db = QSqlDatabase::addDatabase("QMYSQL","test");
db.setHostName(server_host);
db.setUserName(server_user);
db.setPassword(server_pass);
if(version == 0){
db.setDatabaseName("fatora_db");
}else if (version == 1) {
db.setDatabaseName("fatora_db_2");
}
}
//this->setStyleSheet(QString::fromUtf8("font: 14pt FreeMono;"));
sell_wind = new sell_win;
buy_wind = new buy_Win;
categ = new cat_rege;
class_regi = new class_rege;
reges = new rege;
sett = new setting_window;
sea_regi = new sea_rege;
supp = new supp_rege;
custom = new custom_rege;
payment = new payments;
cash_rege = new cash_depo_rege;
storage_reg = new storage_rege;
expen = new expenses;
moni = new monitor;
repo = new reportmanager;
supp_rep = new supplier_report;
custom_rep = new customer_report;
reges_cut = new rege_cut;
buy_wind_cut = new buy_win_cut;
sell_wind_cut = new sell_win_cut;
emp_rege = new employee_rege;
emp_man = new employee_man;
data_shit = new data_sheet;
ui->tabWidget->hide();
connect(reges,SIGNAL(addeditems()),buy_wind,SLOT(update_itemsList()));
connect(reges_cut,SIGNAL(addeditems()),buy_wind_cut,SLOT(update_itemsList()));
connect(reges,SIGNAL(addeditems()),sell_wind,SLOT(update_itemsList()));
connect(reges_cut,SIGNAL(addeditems()),sell_wind_cut,SLOT(update_itemsList()));
connect(supp,SIGNAL(addeditems()),buy_wind,SLOT(update_List()));
connect(supp,SIGNAL(addeditems()),buy_wind_cut,SLOT(update_List()));
connect(custom,SIGNAL(addeditems()),sell_wind,SLOT(update_List()));
connect(custom,SIGNAL(addeditems()),sell_wind_cut,SLOT(update_List()));
connect(supp,SIGNAL(addeditems()),payment,SLOT(update_List()));
connect(custom,SIGNAL(addeditems()),payment,SLOT(update_List()));
connect(categ,SIGNAL(addeditems()),reges,SLOT(update_combo()));
connect(sea_regi,SIGNAL(addeditems()),reges,SLOT(update_combo()));
connect(class_regi,SIGNAL(addeditems()),reges,SLOT(update_combo()));
connect(supp,SIGNAL(addeditems()),reges,SLOT(update_combo()));
connect(categ,SIGNAL(addeditems()),reges_cut,SLOT(update_combo()));
connect(sea_regi,SIGNAL(addeditems()),reges_cut,SLOT(update_combo()));
connect(class_regi,SIGNAL(addeditems()),reges_cut,SLOT(update_combo()));
connect(supp,SIGNAL(addeditems()),reges_cut,SLOT(update_combo()));
// ui->quickWidget->setSource(QUrl(QStringLiteral("qrc:/Rc/Xml/123.qml")));
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::closeEvent(QCloseEvent *e){
if (QMessageBox::question(this, tr("Close?!!!"),
tr("Are You Sure You WANT TO QUIT!!!"), QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes)
{
if (QMessageBox::question(this, tr("backup?!!!"),
tr("Do u want to backup database!!!"), QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes)
{
if(version == 0){
QProcess dumpProcess(this);
QStringList args;
args <<"-uroot"<<"-p0102588220" <<"-hlocalhost"<<"fatora_db";
dumpProcess.setStandardOutputFile("dump-"+QDate::currentDate().toString()+".sql");
dumpProcess.start("mysqldump", args);
dumpProcess.waitForFinished();
qDebug()<< dumpProcess.exitStatus();
}
else if (version == 1) {
QProcess dumpProcess(this);
QStringList args;
args <<"-uroot"<<"-p0102588220" <<"-hlocalhost"<<"fatora_db_2";
dumpProcess.setStandardOutputFile("dump-"+QDate::currentDate().toString()+".sql");
dumpProcess.start("mysqldump", args);
dumpProcess.waitForFinished();
}
}
qApp->closeAllWindows();
e->accept();
}
else{
e->ignore();
}
}
void MainWindow::on_actionCustomer_triggered()
{
if(ui->tabWidget->isHidden()){
ui->tabWidget->show();
}
ui->tabWidget->currentWidget();
ui->tabWidget->addTab(custom,"customers");
ui->tabWidget->setCurrentWidget(custom);
}
void MainWindow::on_actionSupplier_triggered()
{
if(ui->tabWidget->isHidden()){
ui->tabWidget->show();
}
ui->tabWidget->currentWidget();
ui->tabWidget->addTab(supp,"suppliers");
ui->tabWidget->setCurrentWidget(supp);
}
void MainWindow::on_actionSeason_triggered()
{
if(ui->tabWidget->isHidden()){
ui->tabWidget->show();
}
ui->tabWidget->currentWidget();
ui->tabWidget->addTab(sea_regi,"season");
ui->tabWidget->setCurrentWidget(sea_regi);
}
void MainWindow::on_actionSales_Return_triggered()
{
if(ui->tabWidget->isHidden()){
ui->tabWidget->show();
}
ui->tabWidget->currentWidget();
if(version == 0){
ui->tabWidget->addTab(sell_wind,"sales");
ui->tabWidget->setCurrentWidget(sell_wind);
}else if (version == 1) {
ui->tabWidget->addTab(sell_wind_cut,"sales");
ui->tabWidget->setCurrentWidget(sell_wind_cut);
}
}
void MainWindow::on_actionBuy_Return_triggered()
{
if(ui->tabWidget->isHidden()){
ui->tabWidget->show();
}
ui->tabWidget->currentWidget();
if(version == 0){
ui->tabWidget->addTab(buy_wind,"buy");
ui->tabWidget->setCurrentWidget(buy_wind);
}else if (version == 1) {
ui->tabWidget->addTab(buy_wind_cut,"buy");
ui->tabWidget->setCurrentWidget(buy_wind_cut);
}
}
void MainWindow::on_actionCategory_triggered()
{
if(ui->tabWidget->isHidden()){
ui->tabWidget->show();
}
ui->tabWidget->currentWidget();
ui->tabWidget->addTab(categ,"category");
ui->tabWidget->setCurrentWidget(categ);
}
void MainWindow::on_actionClass_triggered()
{
if(ui->tabWidget->isHidden()){
ui->tabWidget->show();
}
ui->tabWidget->currentWidget();
ui->tabWidget->addTab(class_regi,"class");
ui->tabWidget->setCurrentWidget(class_regi);
}
void MainWindow::on_actionItems_triggered()
{
if(ui->tabWidget->isHidden()){
ui->tabWidget->show();
}
ui->tabWidget->currentWidget();
if(version == 0){
ui->tabWidget->addTab(reges,"item register");
ui->tabWidget->setCurrentWidget(reges);
}
else if (version == 1) {
ui->tabWidget->addTab(reges_cut,"item register");
ui->tabWidget->setCurrentWidget(reges_cut);
}
}
void MainWindow::on_actionsetting_triggered()
{
if(ui->tabWidget->isHidden()){
ui->tabWidget->show();
}
ui->tabWidget->currentWidget();
ui->tabWidget->addTab(sett,"setting");
ui->tabWidget->setCurrentWidget(sett);
}
void MainWindow::on_action_triggered()
{
if(ui->tabWidget->isHidden()){
ui->tabWidget->show();
}
ui->tabWidget->currentWidget();
ui->tabWidget->addTab(payment,"payments");
ui->tabWidget->setCurrentWidget(payment);
}
void MainWindow::on_action_2_triggered()
{
if(ui->tabWidget->isHidden()){
ui->tabWidget->show();
}
ui->tabWidget->currentWidget();
ui->tabWidget->addTab(cash_rege,"cash deposite register");
ui->tabWidget->setCurrentWidget(cash_rege);
}
void MainWindow::on_action_3_triggered()
{
if(ui->tabWidget->isHidden()){
ui->tabWidget->show();
}
ui->tabWidget->currentWidget();
ui->tabWidget->addTab(storage_reg,"storage register");
ui->tabWidget->setCurrentWidget(storage_reg);
}
void MainWindow::on_tabWidget_tabCloseRequested(int index)
{
ui->tabWidget->removeTab( index);
if(ui->tabWidget->count()==0){
ui->tabWidget->hide();
}
}
void MainWindow::on_action_4_triggered()
{
if(ui->tabWidget->isHidden()){
ui->tabWidget->show();
}
ui->tabWidget->currentWidget();
ui->tabWidget->addTab(expen,"مصروفات");
ui->tabWidget->setCurrentWidget(expen);
}
void MainWindow::on_action_5_triggered()
{
if(ui->tabWidget->isHidden()){
ui->tabWidget->show();
}
ui->tabWidget->currentWidget();
ui->tabWidget->addTab(moni,"تقرير يومي");
ui->tabWidget->setCurrentWidget(moni);
moni->getstat(0);
moni->getTable();
}
void MainWindow::on_actiontest_triggered()
{
if(ui->tabWidget->isHidden()){
ui->tabWidget->show();
}
ui->tabWidget->currentWidget();
ui->tabWidget->addTab(repo,"تقارير ");
ui->tabWidget->setCurrentWidget(repo);
}
void MainWindow::on_action_6_triggered()
{
if(ui->tabWidget->isHidden()){
ui->tabWidget->show();
}
ui->tabWidget->currentWidget();
ui->tabWidget->addTab(supp_rep,"تقرير مورد ");
ui->tabWidget->setCurrentWidget(supp_rep);
}
void MainWindow::on_action_7_triggered()
{
if(ui->tabWidget->isHidden()){
ui->tabWidget->show();
}
ui->tabWidget->currentWidget();
ui->tabWidget->addTab(emp_rege,"تكويد الموظفين ");
ui->tabWidget->setCurrentWidget(emp_rege);
}
void MainWindow::on_action_8_triggered()
{
if(ui->tabWidget->isHidden()){
ui->tabWidget->show();
}
ui->tabWidget->currentWidget();
ui->tabWidget->addTab(emp_man,"ادارة الموظفين ");
ui->tabWidget->setCurrentWidget(emp_man);
}
void MainWindow::on_action_9_triggered()
{
if(ui->tabWidget->isHidden()){
ui->tabWidget->show();
}
ui->tabWidget->currentWidget();
ui->tabWidget->addTab(data_shit,"قائيمة الالصناف ");
ui->tabWidget->setCurrentWidget(data_shit);
}
void MainWindow::on_action_10_triggered()
{
if(ui->tabWidget->isHidden()){
ui->tabWidget->show();
}
ui->tabWidget->currentWidget();
ui->tabWidget->addTab(custom_rep,"تقرير عملاء ");
ui->tabWidget->setCurrentWidget(custom_rep);
}
|
/*********************************************************
** Author: Carlos Carrillo *
** Date: 11/03/2015 *
** Description: This is the class specification file *
* of a class called Blue. This class is a derived *
* class from the Creature class. The subclass overides *
* the virtual member function attacks() in order to *
* calculate the battle scores for the Blue warrior. *
********************************************************/
//Blue.hpp
#ifndef BLUE_HPP
#define BLUE_HPP
#include "Creature.hpp"
class Blue : public Creature
{
public:
//method to calculate attack
double attacks (double attackRollScore, double defenseRollScore);
Blue(double strength, int aquiles):Creature(strength, aquiles) {}
};
#endif
|
/***********************************************************************
created: 30th July 2013
author: Lukas Meindl
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 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/svg/SVGData.h"
#include "CEGUI/svg/SVGBasicShape.h"
#include "CEGUI/ResourceProvider.h"
#include "CEGUI/System.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/Logger.h"
#include "CEGUI/SharedStringStream.h"
// for the XML parsing part.
#include "CEGUI/XMLParser.h"
#include "CEGUI/XMLAttributes.h"
namespace CEGUI
{
//----------------------------------------------------------------------------//
// Internal Strings holding XML element and attribute names
const String ImagesetSchemaName("Imageset.xsd");
//SVG elements and attributes
const String SVGElement( "svg" );
const String SVGElementAttributeVersion( "version" );
const String SVGElementAttributeWidth( "width" );
const String SVGElementAttributeHeight( "height" );
//SVG Basic Shapes
const String SVGRectElement( "rect" );
const String SVGCircleElement( "circle" );
const String SVGEllipseElement( "ellipse" );
const String SVGLineElement( "line" );
const String SVGPolylineElement( "polyline" );
const String SVGPolygonElement( "polygon" );
// SVG graphics elements paint attributes
const String SVGGraphicsElementAttributeFill( "fill" );
const String SVGGraphicsElementAttributeFillRule( "fill-rule" );
const String SVGGraphicsElementAttributeFillOpacity( "fill-opacity" );
const String SVGGraphicsElementAttributeStroke( "stroke" );
const String SVGGraphicsElementAttributeStrokeWidth( "stroke-width" );
const String SVGGraphicsElementAttributeStrokeLinecap( "stroke-linecap" );
const String SVGGraphicsElementAttributeStrokeLinejoin( "stroke-linejoin" );
const String SVGGraphicsElementAttributeStrokeMiterLimit( "stroke-miterlimit" );
const String SVGGraphicsElementAttributeStrokeDashArray( "stroke-dasharray" );
const String SVGGraphicsElementAttributeStrokeDashOffset( "stroke-dashoffset" );
const String SVGGraphicsElementAttributeStrokeOpacity( "stroke-opacity" );
// SVG transform attribute
const String SVGTransformAttribute( "transform" );
// SVG 'rect' element attributes
const String SVGRectAttributeXPos( "x" );
const String SVGRectAttributeYPos( "y" );
const String SVGRectAttributeWidth( "width" );
const String SVGRectAttributeHeight( "height" );
const String SVGRectAttributeRoundedX( "rx" );
const String SVGRectAttributeRoundedY( "ry" );
// SVG 'circle' element attributes
const String SVGCircleAttributeCX( "cx" );
const String SVGCircleAttributeCY( "cy" );
const String SVGCircleAttributeRadius( "r" );
// SVG 'ellipse' element attributes
const String SVGEllipseAttributeCX( "cx" );
const String SVGEllipseAttributeCY( "cy" );
const String SVGEllipseAttributeRX( "rx" );
const String SVGEllipseAttributeRY( "ry" );
// SVG 'polyline' element attributes
const String SVGPolylineAttributePoints( "points" );
// SVG 'polyline' element attributes
const String SVGLineAttributeX1( "x1" );
const String SVGLineAttributeY1( "y1" );
const String SVGLineAttributeX2( "x2" );
const String SVGLineAttributeY2( "y2" );
//----------------------------------------------------------------------------//
SVGData::SVGData(const String& name)
: d_name(name)
, d_width(0.f)
, d_height(0.f)
{
}
//----------------------------------------------------------------------------//
SVGData::SVGData(const String& name,
const String& filename,
const String& resourceGroup) :
d_name(name)
{
loadFromFile(filename, resourceGroup);
}
//----------------------------------------------------------------------------//
SVGData::~SVGData()
{
destroyShapes();
}
//----------------------------------------------------------------------------//
const String& SVGData::getName() const
{
return d_name;
}
//----------------------------------------------------------------------------//
void SVGData::loadFromFile(const String& file_name,
const String& resource_group)
{
System::getSingleton().getXMLParser()->parseXMLFile(
*this, file_name,
"", resource_group, false);
}
//----------------------------------------------------------------------------//
void SVGData::addShape(SVGBasicShape* svg_shape)
{
d_svgBasicShapes.push_back(svg_shape);
}
//----------------------------------------------------------------------------//
void SVGData::destroyShapes()
{
for (auto shape : d_svgBasicShapes)
delete shape;
d_svgBasicShapes.clear();
}
//----------------------------------------------------------------------------//
const std::vector<SVGBasicShape*>& SVGData::getShapes() const
{
return d_svgBasicShapes;
}
//----------------------------------------------------------------------------//
float SVGData::getWidth() const
{
return d_width;
}
//----------------------------------------------------------------------------//
void SVGData::setWidth(float width)
{
d_width = width;
}
//----------------------------------------------------------------------------//
float SVGData::getHeight() const
{
return d_height;
}
//----------------------------------------------------------------------------//
void SVGData::setHeight(float height)
{
d_height = height;
}
//----------------------------------------------------------------------------//
void SVGData::elementStartLocal(const String& element,
const XMLAttributes& attributes)
{
// handle SVG document fragment element
if (element == SVGElement)
{
elementSVGStart(attributes);
}
// handle SVG 'rect' element
else if(element == SVGRectElement)
{
elementSVGRect(attributes);
}
// handle SVG 'circle' fragment element
else if(element == SVGCircleElement)
{
elementSVGCircle(attributes);
}
// handle SVG 'ellipse' element
else if(element == SVGEllipseElement)
{
elementSVGEllipse(attributes);
}
// handle SVG 'line' element
else if(element == SVGLineElement)
{
elementSVGLine(attributes);
}
// handle SVG 'polyline' element
else if(element == SVGPolylineElement)
{
elementSVGPolyline(attributes);
}
// handle SVG document fragment element
else if(element == SVGPolygonElement)
{
elementSVGPolygon(attributes);
}
}
//----------------------------------------------------------------------------//
void SVGData::elementSVGStart(const XMLAttributes& attributes)
{
// Get the SVG version
const String version(
attributes.getValueAsString(SVGElementAttributeVersion));
// Todo: Currently we only support pixels as units and interpret everything as
// such, probably some default conversion from inch/mm to pixels should happen
const String width(
attributes.getValueAsString(SVGElementAttributeWidth));
d_width = parseLengthDataType(width).d_value;
const String height(
attributes.getValueAsString(SVGElementAttributeHeight));
d_height = parseLengthDataType(height).d_value;
}
//----------------------------------------------------------------------------//
void SVGData::elementSVGRect(const XMLAttributes& attributes)
{
SVGPaintStyle paint_style = parsePaintStyle(attributes);
glm::mat3x3 transform = parseTransform(attributes);
const String xString(
attributes.getValueAsString(SVGRectAttributeXPos, "0"));
float x = parseLengthDataType(xString).d_value;
const String yString(
attributes.getValueAsString(SVGRectAttributeYPos, "0"));
float y = parseLengthDataType(yString).d_value;
const String widthString(
attributes.getValueAsString(SVGRectAttributeWidth, "0"));
float width = parseLengthDataType(widthString).d_value;
const String heightString(
attributes.getValueAsString(SVGRectAttributeHeight, "0"));
float height = parseLengthDataType(heightString).d_value;
const String rxString(
attributes.getValueAsString(SVGRectAttributeRoundedX, "0"));
float rx = parseLengthDataType(rxString).d_value;
const String ryString(
attributes.getValueAsString(SVGRectAttributeRoundedY, "0"));
float ry = parseLengthDataType(ryString).d_value;
SVGRect* rect = new SVGRect(paint_style, transform, x, y, width, height, rx, ry);
addShape(rect);
}
//----------------------------------------------------------------------------//
void SVGData::elementSVGCircle(const XMLAttributes& attributes)
{
SVGPaintStyle paint_style = parsePaintStyle(attributes);
glm::mat3x3 transform = parseTransform(attributes);
const String cxString(
attributes.getValueAsString(SVGCircleAttributeCX, "0"));
float cx = parseLengthDataType(cxString).d_value;
const String cyString(
attributes.getValueAsString(SVGCircleAttributeCY, "0"));
float cy = parseLengthDataType(cyString).d_value;
const String radiusString(
attributes.getValueAsString(SVGCircleAttributeRadius, "0"));
float radius = parseLengthDataType(radiusString).d_value;
SVGCircle* circle = new SVGCircle(paint_style, transform, cx, cy, radius);
addShape(circle);
}
//----------------------------------------------------------------------------//
void SVGData::elementSVGEllipse(const XMLAttributes& attributes)
{
SVGPaintStyle paint_style = parsePaintStyle(attributes);
glm::mat3x3 transform = parseTransform(attributes);
const String cxString(
attributes.getValueAsString(SVGEllipseAttributeCX, "0"));
float cx = parseLengthDataType(cxString).d_value;
const String cyString(
attributes.getValueAsString(SVGEllipseAttributeCY, "0"));
float cy = parseLengthDataType(cyString).d_value;
const String rxString(
attributes.getValueAsString(SVGEllipseAttributeRX, "0"));
float rx = parseLengthDataType(rxString).d_value;
const String ryString(
attributes.getValueAsString(SVGEllipseAttributeRY, "0"));
float ry = parseLengthDataType(ryString).d_value;
SVGEllipse* ellipse = new SVGEllipse(paint_style, transform, cx, cy, rx, ry);
addShape(ellipse);
}
//----------------------------------------------------------------------------//
void SVGData::elementSVGLine(const XMLAttributes& attributes)
{
SVGPaintStyle paint_style = parsePaintStyle(attributes);
glm::mat3x3 transform = parseTransform(attributes);
const String x1String(
attributes.getValueAsString(SVGLineAttributeX1, "0"));
float x1 = parseLengthDataType(x1String).d_value;
const String y1String(
attributes.getValueAsString(SVGLineAttributeY1, "0"));
float y1 = parseLengthDataType(y1String).d_value;
const String x2String(
attributes.getValueAsString(SVGLineAttributeX2, "0"));
float x2 = parseLengthDataType(x2String).d_value;
const String y2String(
attributes.getValueAsString(SVGLineAttributeY2, "0"));
float y2 = parseLengthDataType(y2String).d_value;
SVGLine* line = new SVGLine(paint_style, transform,
x1, y1, x2, y2);
addShape(line);
}
//----------------------------------------------------------------------------//
void SVGData::elementSVGPolyline(const XMLAttributes& attributes)
{
SVGPaintStyle paint_style = parsePaintStyle(attributes);
glm::mat3x3 transform = parseTransform(attributes);
const String pointsString(
attributes.getValueAsString(SVGPolylineAttributePoints, ""));
std::vector<glm::vec2> points;
parsePointsString(pointsString, points);
SVGPolyline* polyline = new SVGPolyline(paint_style, transform, points);
addShape(polyline);
}
//----------------------------------------------------------------------------//
void SVGData::elementSVGPolygon(const XMLAttributes& attributes)
{
SVGPaintStyle paint_style = parsePaintStyle(attributes);
glm::mat3x3 transform = parseTransform(attributes);
const String pointsString(
attributes.getValueAsString(SVGPolylineAttributePoints, ""));
std::vector<glm::vec2> points;
parsePointsString(pointsString, points);
SVGPolygon* polygon = new SVGPolygon(paint_style, transform, points);
addShape(polygon);
}
//----------------------------------------------------------------------------//
void SVGData::elementEndLocal(const String& /*element*/)
{
}
//----------------------------------------------------------------------------//
SVGData::SVGLength SVGData::parseLengthDataType(const String& length_string)
{
SVGLength length;
String unitString;
std::stringstream& strStream = SharedStringstream::GetPreparedStream(length_string);
strStream >> length.d_value;
if(strStream.fail())
throw SVGParsingException(
"SVG file parsing was aborted because of an invalid value of an SVG"
" 'length' type (float value): " + length_string);
strStream >> unitString;
if(unitString.empty())
return length;
else if(unitString.length() == 2)
{
if(unitString.compare("in") == 0)
length.d_unit = SvgLengthUnit::In;
else if(unitString.compare("cm") == 0)
length.d_unit = SvgLengthUnit::Cm;
else if(unitString.compare("mm") == 0)
length.d_unit = SvgLengthUnit::Mm;
else if(unitString.compare("pt") == 0)
length.d_unit = SvgLengthUnit::Pt;
else if(unitString.compare("pc") == 0)
length.d_unit = SvgLengthUnit::Pc;
else if(unitString.compare("px") == 0)
length.d_unit = SvgLengthUnit::Px;
}
else if(unitString.length() == 1)
{
if(unitString.compare("%") == 0)
length.d_unit = SvgLengthUnit::Percent;
}
else
// Parse error
throw SVGParsingException(
"SVG file parsing was aborted because of an invalid value of an SVG 'length' type");
return length;
}
//----------------------------------------------------------------------------//
SVGPaintStyle SVGData::parsePaintStyle(const XMLAttributes& attributes)
{
SVGPaintStyle paint_style;
//TODO: unsupported/unspecified values should be inherited from the parents if possible, this
// however would require adding an additional bool to every attribute member variable to check if
// it is to be inherited or not
const String fillString(
attributes.getValueAsString(SVGGraphicsElementAttributeFill));
parsePaintStyleFill(fillString, paint_style);
const String fillRuleString(
attributes.getValueAsString(SVGGraphicsElementAttributeFillRule));
parsePaintStyleFillRule(fillRuleString, paint_style);
const String fillOpacityString(
attributes.getValueAsString(SVGGraphicsElementAttributeFillOpacity));
parsePaintStyleFillOpacity(fillOpacityString, paint_style);
const String strokeString(
attributes.getValueAsString(SVGGraphicsElementAttributeStroke));
parsePaintStyleStroke(strokeString, paint_style);
const String strokeWidthString(
attributes.getValueAsString(SVGGraphicsElementAttributeStrokeWidth, "1"));
parsePaintStyleStrokeWidth(strokeWidthString, paint_style);
const String strokeLinecapString(
attributes.getValueAsString(SVGGraphicsElementAttributeStrokeLinecap, "butt"));
parsePaintStyleStrokeLinecap(strokeLinecapString, paint_style);
const String strokeLinejoinString(
attributes.getValueAsString(SVGGraphicsElementAttributeStrokeLinejoin, "miter"));
parsePaintStyleStrokeLinejoin(strokeLinejoinString, paint_style);
const String strokeMiterLimitString(
attributes.getValueAsString(SVGGraphicsElementAttributeStrokeMiterLimit, "4"));
parsePaintStyleMiterlimitString(strokeMiterLimitString, paint_style);
const String strokeDashArrayString(
attributes.getValueAsString(SVGGraphicsElementAttributeStrokeDashArray));
parsePaintStyleStrokeDashArray(strokeDashArrayString, paint_style);
const String strokeDashOffsetString(
attributes.getValueAsString(SVGGraphicsElementAttributeStrokeDashOffset));
parsePaintStyleStrokeDashOffset(strokeDashOffsetString, paint_style);
const String strokeOpacityString(
attributes.getValueAsString(SVGGraphicsElementAttributeStrokeOpacity));
parsePaintStyleStrokeOpacity(strokeOpacityString, paint_style);
return paint_style;
}
//----------------------------------------------------------------------------//
glm::vec3 SVGData::parseColour(const CEGUI::String& colour_string)
{
if(colour_string.at(0) == '#')
{
if(colour_string.size() == 7)
{
const CEGUI::String modifiedColourStr = colour_string.substr(1,7);
return parseRgbHexColour(modifiedColourStr, colour_string);
}
else if(colour_string.size() == 4)
{
CEGUI::String modifiedColourStr = CEGUI::String("") +
colour_string[1] + colour_string[1] +
colour_string[2] + colour_string[2] +
colour_string[3] + colour_string[3];
return parseRgbHexColour(modifiedColourStr, colour_string);
}
}
else if(colour_string.compare("rgb(") > 0)
{
CEGUI::String rgbColours = colour_string.substr(4, colour_string.length() - 5);
std::stringstream& strStream = SharedStringstream::GetPreparedStream(rgbColours);
int r, g, b;
strStream >> r >> mandatoryChar<','> >> g >> mandatoryChar<','> >> b;
if (strStream.fail())
throw SVGParsingException("SVG file parsing was aborted because of an invalid "
"rgb-colour value: " + colour_string);
return glm::vec3(r / 255.0f, g / 255.0f, b / 255.0f);
}
// SVG's default colours
else if(colour_string.compare("black") == 0)
return glm::vec3(0.0f, 0.0f, 0.0f);
else if(colour_string.compare("green") == 0)
return glm::vec3(0.0f, 128.0f / 255.0f, 0.0f);
else if(colour_string.compare("silver") == 0)
return glm::vec3(192.0f / 255.0f, 192.0f / 255.0f, 192.0f / 255.0f);
else if(colour_string.compare("lime") == 0)
return glm::vec3(0.0f, 1.0f, 0.0f);
else if(colour_string.compare("gray") == 0)
return glm::vec3(128.0f / 255.0f, 128.0f / 255.0f, 128.0f / 255.0f);
else if(colour_string.compare("olive") == 0)
return glm::vec3(128.0f / 255.0f, 128.0f / 255.0f, 0.f);
else if(colour_string.compare("white") == 0)
return glm::vec3(1.0f, 1.0f, 1.0f);
else if(colour_string.compare("yellow") == 0)
return glm::vec3(1.0f, 1.0f, 0.0f);
else if(colour_string.compare("maroon") == 0)
return glm::vec3(128.0f / 255.0f, 0.0f, 0.0f);
else if(colour_string.compare("navy") == 0)
return glm::vec3(0.0f, 0.0f, 128.0f / 255.0f);
else if(colour_string.compare("red") == 0)
return glm::vec3(1.0f, 0.0f, 0.0f);
else if(colour_string.compare("blue") == 0)
return glm::vec3(0.0f, 0.0f, 1.0f);
else if(colour_string.compare("purple") == 0)
return glm::vec3(128.0f / 255.0f, 0.0f, 128.0f / 255.0f);
else if(colour_string.compare("teal") == 0)
return glm::vec3(0.0f, 128.0f / 255.0f, 128.0f / 255.0f);
else if(colour_string.compare("fuchsia") == 0)
return glm::vec3(1.0f, 0.0f, 1.0f);
else if(colour_string.compare("aqua") == 0)
return glm::vec3(0.0f, 1.0f, 1.0f);
// No matching format was found, let's throw an error.
throw SVGParsingException("SVG file parsing was aborted because of an invalid colour value");
return glm::vec3();
}
glm::vec3 SVGData::parseRgbHexColour(const CEGUI::String& colourString,
const CEGUI::String& origString)
{
glm::vec3 colour;
int value;
std::stringstream& strStream = SharedStringstream::GetPreparedStream();
strStream << std::hex;
#if (CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_ASCII)
std::string currentSubStr = colourString.substr(0, 2);
#elif (CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_UTF_8)
std::string currentSubStr = colourString.getString().substr(0, 2);
#elif CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_UTF_32
std::string currentSubStr = String::convertUtf32ToUtf8(colourString.substr(0, 2).getString());
#endif
strStream.clear();
strStream.str(currentSubStr);
strStream >> value;
if (strStream.fail())
throw SVGParsingException("SVG file parsing was aborted because of an invalid "
"colour value: " + origString);
colour.x = value / 255.0f;
#if (CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_ASCII)
currentSubStr = colourString.substr(2, 2);
#elif(CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_UTF_8)
currentSubStr = colourString.getString().substr(2, 2);
#elif CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_UTF_32
currentSubStr = String::convertUtf32ToUtf8(colourString.substr(2, 2).getString());
#endif
strStream.clear();
strStream.str(currentSubStr);
strStream >> value;
if (strStream.fail())
throw SVGParsingException("SVG file parsing was aborted because of an invalid "
"colour value: " + origString);
colour.y = value / 255.0f;
#if (CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_ASCII)
currentSubStr = colourString.substr(4, 2);
#elif (CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_UTF_8)
currentSubStr = colourString.getString().substr(4, 2);
#elif CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_UTF_32
currentSubStr = String::convertUtf32ToUtf8(colourString.substr(4, 2).getString());
#endif
strStream.clear();
strStream.str(currentSubStr);
strStream >> value;
if (strStream.fail())
throw SVGParsingException("SVG file parsing was aborted because of an invalid "
"colour value: " + origString);
colour.z = value / 255.0f;
strStream << std::dec;
return colour;
}
//----------------------------------------------------------------------------//
std::vector<float> SVGData::parseListOfLengths(const String& list_of_lengths_string)
{
std::vector<float> list_of_lengths;
std::stringstream& sstream = SharedStringstream::GetPreparedStream(list_of_lengths_string);
float currentValue;
sstream >> currentValue;
while (!sstream.fail())
{
list_of_lengths.push_back(currentValue);
sstream >> mandatoryChar<','> >> currentValue;
}
return list_of_lengths;
}
//----------------------------------------------------------------------------//
void SVGData::parsePaintStyleFill(const String& fillString, SVGPaintStyle& paint_style)
{
if (fillString.compare("none") == 0)
paint_style.d_fill.d_none = true;
else if(fillString.empty())
{
// Inherit value or use default
paint_style.d_fill.d_none = false;
paint_style.d_fill.d_colour = parseColour("black");
}
else
{
paint_style.d_fill.d_none = false;
paint_style.d_fill.d_colour = parseColour(fillString);
}
}
//----------------------------------------------------------------------------//
void SVGData::parsePaintStyleFillRule(const String& fillRuleString, SVGPaintStyle& paint_style)
{
if(fillRuleString.empty())
// Inherit value or use default
paint_style.d_fillRule = PolygonFillRule::NonZero;
else if(fillRuleString.compare("nonzero"))
paint_style.d_fillRule = PolygonFillRule::NonZero;
else if(fillRuleString.compare("evenodd"))
paint_style.d_fillRule = PolygonFillRule::EvenOdd;
}
//----------------------------------------------------------------------------//
void SVGData::parsePaintStyleFillOpacity(const String& fillOpacityString, SVGPaintStyle& paint_style)
{
if(fillOpacityString.empty())
// Inherit value or use default
paint_style.d_fillOpacity = 1.0f;
else
{
std::stringstream& sstream = SharedStringstream::GetPreparedStream(fillOpacityString);
sstream >> paint_style.d_fillOpacity;
if(sstream.fail())
throw SVGParsingException("SVG file parsing was aborted because of an invalid "
"fill opacity value: " + fillOpacityString);
//! Clamp value in each case without throwing a warning if the values are below 0 or above 1
paint_style.d_fillOpacity = std::min( std::max(0.0f, paint_style.d_fillOpacity), 1.0f );
}
}
//----------------------------------------------------------------------------//
void SVGData::parsePaintStyleStroke(const String& strokeString, SVGPaintStyle& paint_style)
{
if (strokeString.compare("none") == 0 || strokeString.empty())
paint_style.d_stroke.d_none = true;
else
{
paint_style.d_stroke.d_none = false;
paint_style.d_stroke.d_colour = parseColour(strokeString);
}
}
//----------------------------------------------------------------------------//
void SVGData::parsePaintStyleStrokeWidth(const String& strokeWidthString, SVGPaintStyle& paint_style)
{
std::stringstream& sstream = SharedStringstream::GetPreparedStream(strokeWidthString);
sstream >> paint_style.d_strokeWidth;
if(sstream.fail())
throw SVGParsingException(
"SVG file parsing was aborted because of an invalid value for the SVG 'stroke-width' "
"type : " + strokeWidthString);
if(paint_style.d_strokeWidth < 0.0f)
{
paint_style.d_strokeWidth = 1.0f;
Logger::getSingleton().logEvent("SVGData::parsePaintStyle - An unsupported value for "
"stroke-width was specified in the SVG file. The value was "
"set to the initial value '1'. String: " +
strokeWidthString, LoggingLevel::Error);
}
}
//----------------------------------------------------------------------------//
void SVGData::parsePaintStyleStrokeLinecap(const String& strokeLinecapString, SVGPaintStyle& paint_style)
{
if(strokeLinecapString.compare("butt") == 0)
paint_style.d_strokeLinecap = SVGPaintStyle::SvgLinecap::Butt;
else if(strokeLinecapString.compare("round") == 0)
paint_style.d_strokeLinecap = SVGPaintStyle::SvgLinecap::Round;
else if(strokeLinecapString.compare("square") == 0)
paint_style.d_strokeLinecap = SVGPaintStyle::SvgLinecap::Square;
else
throw SVGParsingException(
"SVG file parsing was aborted because of an invalid value for the SVG 'linecap' type");
}
//----------------------------------------------------------------------------//
void SVGData::parsePaintStyleStrokeLinejoin(const String& strokeLinejoinString, SVGPaintStyle& paint_style)
{
if(strokeLinejoinString.compare("miter") == 0)
paint_style.d_strokeLinejoin = SVGPaintStyle::SVGLinejoin::Miter;
else if(strokeLinejoinString.compare("round") == 0)
paint_style.d_strokeLinejoin = SVGPaintStyle::SVGLinejoin::Round;
else if(strokeLinejoinString.compare("bevel") == 0)
paint_style.d_strokeLinejoin = SVGPaintStyle::SVGLinejoin::Bevel;
else
throw SVGParsingException(
"SVG file parsing was aborted because of an invalid value for the SVG 'linejoin' type");
}
//----------------------------------------------------------------------------//
void SVGData::parsePaintStyleMiterlimitString(const String& strokeMiterLimitString, SVGPaintStyle& paint_style)
{
std::stringstream& sstream = SharedStringstream::GetPreparedStream(strokeMiterLimitString);
sstream >> paint_style.d_strokeMiterlimit;
if (sstream.fail())
throw SVGParsingException(
"SVG file parsing was aborted because of an invalid value for the SVG "
"'stroke-miterlimit' type : " + strokeMiterLimitString);
if(paint_style.d_strokeMiterlimit < 1.0f)
{
paint_style.d_strokeMiterlimit = 4.0f;
Logger::getSingleton().logEvent("SVGData::parsePaintStyle - An unsupported value for "
"stroke-miterlimit was specified in the SVG file. The "
" value was set to the initial value '4'. String: " +
strokeMiterLimitString, LoggingLevel::Error);
}
}
//----------------------------------------------------------------------------//
void SVGData::parsePaintStyleStrokeDashArray(const String& strokeDashArrayString, SVGPaintStyle& paint_style)
{
if(strokeDashArrayString.compare("none") == 0)
{
paint_style.d_strokeDashArrayNone = true;
paint_style.d_strokeDashArray.clear();
}
else
{
paint_style.d_strokeDashArray = parseListOfLengths(strokeDashArrayString);
const size_t dashArraySize = paint_style.d_strokeDashArray.size();
paint_style.d_strokeDashArrayNone = dashArraySize != 0;
//! If an odd number of values is provided, then the list of values shall be repeated to yield an even number of values
if(paint_style.d_strokeDashArrayNone == false && (dashArraySize % 2) == 1)
paint_style.d_strokeDashArray.insert( paint_style.d_strokeDashArray.end(), paint_style.d_strokeDashArray.begin(), paint_style.d_strokeDashArray.end() );
}
}
//----------------------------------------------------------------------------//
void SVGData::parsePaintStyleStrokeOpacity(const String& strokeOpacityString, SVGPaintStyle& paint_style)
{
if(strokeOpacityString.empty())
paint_style.d_strokeOpacity = 1.0f;
else
{
std::stringstream& sstream = SharedStringstream::GetPreparedStream(strokeOpacityString);
sstream >> paint_style.d_strokeOpacity;
if (sstream.fail())
throw SVGParsingException(
"SVG file parsing was aborted because of an invalid value for the SVG "
"'stroke-opacity' type : " + strokeOpacityString);
//! Clamp value without ever throwing a warning
paint_style.d_strokeOpacity = std::min( std::max(0.0f, paint_style.d_strokeOpacity), 1.0f );
}
}
//----------------------------------------------------------------------------//
void SVGData::parsePaintStyleStrokeDashOffset(const String& strokeDashOffsetString, SVGPaintStyle& paint_style)
{
if(strokeDashOffsetString.empty())
paint_style.d_strokeDashOffset = 0.0f;
else
{
std::stringstream& sstream = SharedStringstream::GetPreparedStream(strokeDashOffsetString);
sstream >> paint_style.d_strokeDashOffset;
if (sstream.fail())
throw SVGParsingException(
"SVG file parsing was aborted because of an invalid value for the SVG "
"'stroke-opacity' type : " + strokeDashOffsetString);
}
}
//----------------------------------------------------------------------------//
glm::mat3x3 SVGData::parseTransform(const XMLAttributes& attributes)
{
const String transformString(attributes.getValueAsString(SVGTransformAttribute));
std::stringstream& sstream = SharedStringstream::GetPreparedStream(transformString);
// Unity matrix is our default/basis
glm::mat3x3 currentMatrix(1.0f);
sstream >> MandatoryString("matrix") >> mandatoryChar<'('>;
if(!sstream.fail())
{
float matrixValues[6];
int i = 0;
while( (i < 6) && !sstream.fail() )
{
// We allow either comma or spaces as separators
sstream >> optionalChar<','>;
sstream >> matrixValues[i];
++i;
}
//If we parsed the expected amount of matrix elements we will multiply the matrix to our transformation
if(i == 6)
{
currentMatrix *= glm::mat3x3(matrixValues[0], matrixValues[2], matrixValues[4],
matrixValues[1], matrixValues[3], matrixValues[5],
0.0f, 0.0f, 1.0f);
}
else
{
throw SVGParsingException(
"SVG file parsing was aborted because of an invalid value for the SVG "
"'transform' type : " + transformString);
}
}
return currentMatrix;
}
//----------------------------------------------------------------------------//
void SVGData::parsePointsString(const String& pointsString, std::vector<glm::vec2>& points)
{
std::stringstream& sstream = SharedStringstream::GetPreparedStream(pointsString);
while(true)
{
glm::vec2 currentPoint;
sstream >> currentPoint.x;
//Check if a new pair can be read, if not then break the loop, the input so far is assumed
//to be valid
if(sstream.fail())
{
break;
}
sstream >> mandatoryChar<','>;
if (sstream.fail())
{
throw SVGParsingException("SVG file parsing was aborted because of an invalid value "
"for the SVG 'points' type (missing comma separator): " +
pointsString);
//Clearing the invalid list of points
points.clear();
}
sstream >> currentPoint.y;
if (sstream.fail())
{
throw SVGParsingException("SVG file parsing was aborted because of an invalid value "
"for the SVG 'points' type (missing second value of the pair"
"): " + pointsString);
//Clearing the invalid list of points
points.clear();
}
points.push_back(currentPoint);
}
}
//----------------------------------------------------------------------------//
}
|
// Copyright 2020 JD.com, Inc. Galileo Authors. All Rights Reserved.
//
// 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 "service/query_service.h"
#include <brpc/controller.h>
#include <bthread/bthread.h>
#include <glog/logging.h>
#include "common/message.h"
#include "common/packer.h"
#include "service/graph.h"
namespace galileo {
namespace service {
struct AsyncJob {
std::shared_ptr<Graph> graph;
const galileo::proto::QueryRequest* request;
galileo::proto::QueryResponse* response;
google::protobuf::Closure* done;
void Run();
void RunAndDelete() {
Run();
delete this;
}
};
#define UNPACK_WITH_CHECK(DATA) \
{ \
bool ret = request_packer.UnPack(&DATA); \
assert(ret); \
if (!ret) { \
LOG(ERROR) << " UnPack error"; \
return; \
} \
}
void AsyncJob::Run() {
brpc::ClosureGuard done_guard(done);
if (graph == nullptr) {
LOG(ERROR) << " Call init first";
return;
}
std::string pack_content;
galileo::common::Packer response_packer(&pack_content);
galileo::common::OperatorType op_type =
(galileo::common::OperatorType)(request->op_type());
galileo::common::Packer request_packer(
const_cast<galileo::proto::QueryRequest*>(request)->mutable_data());
bool op_ret = false;
switch (op_type) {
case galileo::common::SAMPLE_VERTEX: {
galileo::common::EntityRequest entity_request;
UNPACK_WITH_CHECK(entity_request.types_);
UNPACK_WITH_CHECK(entity_request.counts_);
op_ret = graph->SampleVertex(entity_request, &response_packer);
} break;
case galileo::common::SAMPLE_EDGE: {
galileo::common::EntityRequest entity_request;
UNPACK_WITH_CHECK(entity_request.types_);
UNPACK_WITH_CHECK(entity_request.counts_);
op_ret = graph->SampleEdge(entity_request, &response_packer);
} break;
case galileo::common::SAMPLE_NEIGHBOR:
case galileo::common::GET_TOPK_NEIGHBOR:
case galileo::common::GET_NEIGHBOR: {
galileo::common::NeighborRequest neighbor_request;
UNPACK_WITH_CHECK(neighbor_request.ids_);
UNPACK_WITH_CHECK(neighbor_request.edge_types_);
UNPACK_WITH_CHECK(neighbor_request.cnt);
UNPACK_WITH_CHECK(neighbor_request.need_weight_);
op_ret =
graph->QueryNeighbors(op_type, neighbor_request, &response_packer);
} break;
case galileo::common::GET_VERTEX_FEATURE: {
galileo::common::VertexFeatureRequest vertex_feature_request;
UNPACK_WITH_CHECK(vertex_feature_request.ids_);
UNPACK_WITH_CHECK(vertex_feature_request.features_);
UNPACK_WITH_CHECK(vertex_feature_request.max_dims_);
op_ret =
graph->GetVertexFeature(vertex_feature_request, &response_packer);
} break;
case galileo::common::GET_EDGE_FEATURE: {
galileo::common::EdgeFeatureRequest edge_feature_request;
UNPACK_WITH_CHECK(edge_feature_request.ids_);
UNPACK_WITH_CHECK(edge_feature_request.features_);
UNPACK_WITH_CHECK(edge_feature_request.max_dims_);
op_ret = graph->GetEdgeFeature(edge_feature_request, &response_packer);
} break;
default:
op_ret = false;
LOG(ERROR) << " Operator type is not support.op:" << op_type;
break;
}
if (op_ret) {
response_packer.PackEnd();
} else {
pack_content.clear();
}
response->set_data(std::move(pack_content));
}
static void* process_thread(void* args) {
AsyncJob* job = static_cast<AsyncJob*>(args);
job->RunAndDelete();
return NULL;
}
bool QueryService::Init(const galileo::service::GraphConfig& config) {
if (graph_) {
LOG(ERROR) << " Aleady init query service";
return false;
}
graph_ = std::make_shared<Graph>();
return graph_->Init(config);
}
const galileo::common::ShardMeta QueryService::QueryShardMeta() {
return graph_->QueryShardMeta();
}
void QueryService::Query(::google::protobuf::RpcController* cntl,
const galileo::proto::QueryRequest* request,
galileo::proto::QueryResponse* response,
::google::protobuf::Closure* done) {
if (!cntl || !done) {
LOG(ERROR) << " Controller or done is null";
return;
}
brpc::ClosureGuard done_guard(done);
AsyncJob* job = new AsyncJob;
job->graph = graph_;
job->request = request;
job->response = response;
job->done = done;
bthread_t th;
int res = bthread_start_background(&th, NULL, process_thread, job);
if (res != 0) {
LOG(ERROR) << "Start backgroud bthread fail.res:" << res;
}
done_guard.release();
}
} // namespace service
} // namespace galileo
|
#ifndef PROP1_H
#define PROP1_H
#include <QGraphicsRectItem>
#include <QObject>
class Prop1: public QObject,public QGraphicsRectItem
{
Q_OBJECT
public:
Prop1();
public slots:
void touch();
};
#endif // PROP1_H
|
/******************************************************************************
* "THE HUG-WARE LICENSE": *
* tastytea <tastytea@tastytea.de> wrote this file. As long as you retain *
* this notice you can do whatever you want with this stuff. If we meet *
* some day, and you think this stuff is worth it, you can give me a hug. *
******************************************************************************/
#include "../include/helpfulbot.hpp"
#include "../include/builtin_features.hpp"
#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <fstream>
#include <stdlib.h>
#include <sys/types.h>
#include <new>
#include <memory>
#ifndef NO_GETTEXT
#include <libintl.h>
#include <locale>
#endif
#include <QCoreApplication>
#include <QString>
#include <QDir>
#include <QXmppConfiguration.h>
#include <QXmppMessage.h>
#include <QXmppRosterManager.h>
#include <QXmppVersionManager.h>
#include <libconfig.h++>
using std::endl;
HelpfulBot::HelpfulBot(QObject *parent)
: QXmppClient(parent)
{
bool check;
Q_UNUSED(check);
check = connect(this, SIGNAL(messageReceived(QXmppMessage)),
SLOT(messageReceived(QXmppMessage)));
Q_ASSERT(check);
check = connect(this, SIGNAL(disconnected()),
SLOT(disconnected()));
Q_ASSERT(check);
check = connect(this, SIGNAL(error(QXmppClient::Error)),
SLOT(error(QXmppClient::Error)));
Q_ASSERT(check);
#ifndef NO_GETTEXT
setlocale(LC_ALL, "");
bindtextdomain("helpfulbot", "/usr/share/locale");
textdomain("helpfulbot");
#endif
features.push_back(featureptr(new HelpfulBotFeatures::Help(this)));
features.push_back(featureptr(new HelpfulBotFeatures::Info(this)));
features.push_back(featureptr(new HelpfulBotFeatures::Feedback(this)));
features.push_back(featureptr(new HelpfulBotFeatures::Remind(this)));
}
HelpfulBot::~HelpfulBot() {}
bool HelpfulBot::readconfig(cfgmap &data)
{
libconfig::Config cfg;
std::string filename;
if (getenv("XDG_CONFIG_HOME") != NULL)
{
filename = std::string(getenv("XDG_CONFIG_HOME"));
}
else
{
filename = std::string(getenv("HOME")) + "/.config";
}
filename += "/helpfulbot.cfg";
//Read config file. On error report and return false
try
{
cfg.readFile(filename.c_str());
try
{
std::string value;
cfg.lookupValue("jid", value);
data.insert(cfgpair("jid", value));
cfg.lookupValue("password", value);
data.insert(cfgpair("password", value));
}
catch(const libconfig::SettingNotFoundException &e)
{
qWarning("Setting not found in configuration file.");
}
}
catch(const libconfig::FileIOException &e)
{
qcerr << _("I/O error while reading configuration file.") << endl;
qcerr << _("Create »") << QString::fromLocal8Bit(getenv("HOME")) + "/.config/helpfulbot.cfg" <<
_("« with the contents:") << endl;
qcerr << "jid = \"user@server.tld\"" << endl << "password = \"secret\"" << endl;
return false;
}
catch(const libconfig::ParseException &e)
{
qcerr << _("Parse error at ") << e.getFile() << ":" << e.getLine()
<< " - " << e.getError() << "\n";
return false;
}
return true;
}
bool HelpfulBot::connect_from_config()
{
cfgmap data;
if (readconfig(data))
{
connectToServer(QString::fromStdString(data["jid"]),
QString::fromStdString(data["password"]));
return true;
}
else
{
qcerr << _("ERROR reading config.") << endl;
return false;
}
}
bool HelpfulBot::connectToServer(const QString &jid, const QString &password)
{
QXmppConfiguration config;
try
{
config.setJid(jid);
config.setPassword(password);
config.setResource("helpfulbot-" + version);
config.setStreamSecurityMode(QXmppConfiguration::TLSRequired);
config.setAutoAcceptSubscriptions(true);
connectToServer(config);
}
catch (short e)
{ // FIXME: Better error checking & reporting
qcerr << _("ERROR connecting to server") << endl;
return false;
}
this->versionManager().setClientName("helpfulbot");
this->versionManager().setClientVersion(version);
return true;
}
void HelpfulBot::messageReceived(const QXmppMessage &message)
{ // cmd = up to first ' ', args = after first ' '
QString cmd = message.body().section(" ", 0, 0);
QString args = message.body().mid(cmd.length() + 1);
bool msg_handled = false;
std::vector<featureptr>::iterator it;
for (it = features.begin(); it != features.end(); ++it)
{
if (cmd.startsWith(QString::fromStdString((*it)->command()), Qt::CaseInsensitive))
{
(*it)->handle_message(message);
msg_handled = true;
}
}
if (msg_handled == false)
{
if (message.body() != "")
{
sendPacket(QXmppMessage("", message.from(), _("I do not understand you. :-(")));
// first element of features is HelpfulBotFeatures::Help
features[0]->handle_message(message);
}
}
}
const QString HelpfulBot::get_admin()
{
return _admin;
}
void HelpfulBot::set_admin(const QString &jid)
{
_admin = jid;
}
QString HelpfulBot::get_barejid(const QString &jid)
{
return jid.section("/", 0, 0);
}
void HelpfulBot::error(const QXmppClient::Error &type)
{
QString output = "";
switch (type)
{
case NoError:
qcerr << "NoError" << endl;
break;
case SocketError:
qcerr << "SocketError: ";
#ifdef OLD_QXMPP // < 0.8.1
switch (socketError())
{ // https://doc.qt.io/qt-4.8/qabstractsocket.html#SocketError-enum
case QAbstractSocket::ConnectionRefusedError:
qcerr << _("Connection refused");
break;
case QAbstractSocket::RemoteHostClosedError:
qcerr << _("The remote host closed the connection");
break;
case QAbstractSocket::HostNotFoundError:
qcerr << _("Host not found");
break;
case QAbstractSocket::SslHandshakeFailedError:
qcerr << _("SSL handshake failed");
break;
default:
qcerr << socketError();
break;
}
#else
qcerr << ": " << socketErrorString();
#endif
qcerr << endl;
break;
case KeepAliveError:
qcerr << "KeepAliveError" << endl;
break;
case XmppStreamError:
qcerr << "XmppStreamError: ";
switch (xmppStreamError())
{ // http://doc.qxmpp.org/qxmpp-0.9.1/group__Stanzas.html
case QXmppStanza::Error::Conflict:
qcerr << _("Conflict (Most likely replaced by new connection)");
break;
case QXmppStanza::Error::NotAuthorized:
qcerr << _("Not authorized");
break;
case QXmppStanza::Error::InternalServerError:
qcerr << _("Internal server error");
break;
default:
qcerr << xmppStreamError();
break;
}
qcerr << endl;
break;
}
}
void HelpfulBot::quit(const uint8_t &exitcode)
{
features.clear();
QCoreApplication::exit(exitcode);
}
void HelpfulBot::disconnected()
{
qcout << _("Disconnected. Exiting...") << endl;
quit(1);
}
|
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <functional>
#include <iterator>
using namespace std;
struct Permutation
{
std::vector<size_t> perm;
unsigned size, count;
void operator ++ ()
{
auto getI = [&] {
for (size_t i = size - 2; i >= 0; --i)
{
if (perm[i] < perm[i + 1])
{
return i;
}
}
return size;
};
auto getL = [&] (size_t i) {
for (size_t l = size - 1; l > 0; --l)
{
if ((perm[l] > perm[i]) && (l != i))
{
return l;
}
}
return size;
};
auto i = getI();
auto l = getL(i);
swap(perm[i], perm[l]);
reverse(perm.begin() + i + 1, perm.end());
}
void printNextPerms(ostream & out)
{
while (count-- > 0)
{
++(*this);
printPerm(out);
}
}
void printPerm(ostream & out)
{
ostream_iterator<size_t> outIt(out, " ");
copy(perm.begin(), perm.end(), outIt);
out << endl;
}
};
Permutation readPermutation(istream & in)
{
Permutation permutation;
if (!(in >> permutation.size >> permutation.count))
{
throw invalid_argument("first line incorrect");
}
size_t number;
for (unsigned i = 0; (i < permutation.size) && in && (in >> number);)
{
permutation.perm.push_back(number);
}
if (permutation.perm.size() != permutation.size)
{
throw invalid_argument("Not enought parts");
}
return permutation;
}
int main()
{
ifstream in("input.txt");
ofstream out("output.txt");
try
{
auto permutation = readPermutation(in);
permutation.printNextPerms(out);
}
catch (exception const& e)
{
cout << e.what() << endl;
return 1;
}
return 0;
}
|
#include "graphics\Singularity.Graphics.h"
namespace Singularity
{
namespace Graphics
{
#pragma region Static Methods
void GraphicsDevice::DrawMesh(Mesh* mesh, Vector3 position, Quaternion rotation, Material* material, unsigned layer, Camera* camera)
{
}
void GraphicsDevice::DrawTexture(RECT screenRect, Texture2D* texture, Material* material)
{
}
void GraphicsDevice::Blit(Texture2D* source, Material* material, unsigned pass)
{
}
#pragma endregion
}
}
|
//! Bismillahi-Rahamanirahim.
/** ========================================**
** @Author: Md. Abu Farhad ( RUET, CSE'15)
** @Category:
/** ========================================**/
#include<bits/stdc++.h>
#include<stdio.h>
using namespace std;
#define ll long long
#define pb push_back
#define fr(i,n) for (ll i=0;i<n;i++)
#define fr1(i,n) for(ll i=1;i<=n;i++)
#define scl(x) scanf("%lld",&x)
#define pfl(x) printf("%lld\n",x)
#define pn printf("\n")
#define debug printf("I am here\n")
#define mp make_pair
#define ppb pop_back
#define ps printf(" ")
#define dsort(a) sort(a,a+n,greater<int>())
#define asort(a) sort(a,a+n)
#define mod 10000007
#define mx (1<<28)
#define Pi 2*acos(0.0)
string s,s1,s2,s3,c;
int main()
{
char str1[1300], str2[1300];
ll m,n,i,l,j;
cin>>n;
getline(cin,c);
while(n--)
{
gets(str1);
ll flag=0;
ll len = strlen(str1);
for(i=0; i < len ; i++)
{
if(str1[i] != str1[len-i-1])
{
flag = 1;
break;
}
}
ll cnt=0;
fr(i,len)
{
if(str1[i]==str1[i+1])
cnt++;
}
//cout<<len<<" "<<cnt<<endl;
if(cnt+1==len)
{
cout<<"-1"<<endl;
}
else if (flag == 1 && (cnt+1)!=len)
{
cout<<str1<<endl;
}
else
{
ll l=strlen(str1);
cout<<str1[l-1];
for(i=0; i<l-1; i++) cout<<str1[i];
cout<<endl;
}
}
}
|
#include "ProductEntry.h"
ProductEntry::ProductEntry(): ProductType() {}
ProductEntry::ProductEntry(const ProductType& type, const Amount amount):
ProductType(type), amount_(amount) {}
ProductEntry::ProductEntry(const BarCode barcode,
const std::string title,
const Price price,
const Amount amount):
ProductType(barcode, title, price), amount_(amount) {}
Amount ProductEntry::amount() const
{
return amount_;
}
Price ProductEntry::totalPrice() const
{
return (unsigned int)amount_ * (const double)price_;
}
|
#pragma once
//#include "nginx.hpp"
#include "ngx_unset_value.hpp"
class NgxValue final
{
public:
NgxValue() = default;
~NgxValue() = default;
public:
template <typename T>
static bool invalid(const T& v)
{
return v == static_cast<T>(NgxUnsetValue::get());
}
template <typename T, typename U>
static void init(T& x, const U& v)
{
if (invalid(x))
{
x = v;
}
}
template <typename T, typename U, typename V>
static void merge(T& c, const U& p, const V& d)
{
if (invalid(c))
{
c = invalid(p) ? d : p;
}
}
//重载merge,实现ngx_str_t的条件赋值操作
static void merge(ngx_str_t& c, const ngx_str_t& p, const ngx_str_t& d)
{
if (!c.data)
{
c = p.data ? p : d;
}
}
//可变参数置为未初始化状态
template <typename T, typename ... Args>
static void unset(T& v, Args& ... args)
{
v = NgxUnsetValue::get();
unset(args...);
}
//递归终结函数
static void unset()
{}
};
|
#ifndef PERSISTENCEHANDLERTESTBASE_H
#define PERSISTENCEHANDLERTESTBASE_H
#include "Utilities/Definitions.h"
#include "Utilities/MappedFileDataPersistenceHandler.h"
#include "Utilities/CodeTimer.h"
namespace UnitTesting
{
using float3 = Utilities::_storage3D<float>;
class PersistenceHandlerTestBase
{
public:
PersistenceHandlerTestBase();
virtual ~PersistenceHandlerTestBase();
virtual void operator()() = 0;
protected:
void SetupTestData(size_t numberOfBlocks);
void CompareData(std::vector<float3> &originalData,
std::vector<float3> &storedData);
Utilities::CodeTimer<boost::chrono::microseconds> _timer;
std::vector<float3> _testData;
size_t _dimX, _dimY, _dimZ;
size_t _numberOfBlocks;
private:
};
}
#endif // PERSISTENCEHANDLERTESTBASE_H
|
#ifndef _EasyTcpClient_hpp_
#define _EasyTcpClient_hpp_
#include "util.h"
#include "MessageHeader.hpp"
#define BUF_SIZE 4096
class EasyTcpClient
{
SOCKET sock;
public:
EasyTcpClient()
{
sock = INVALID_SOCKET;
}
virtual ~EasyTcpClient()
{
close();
LOG << "~EasyTcpClient()";
}
void InitSocket()
{
#ifdef _WIN32
WSADATA wsaData;
WSAStartup(MAKEWORD(2,2), &wsaData);
#endif
if( INVALID_SOCKET != sock)
{
LOG << "sock already open\n";
close();
}
sock = socket(AF_INET, SOCK_STREAM, 0);
if( INVALID_SOCKET == sock)
{
LOG << "socket() failed.\n";
}
else
{
LOG << "socket() succeed.\n";
}
}
int connect(const char* ip, unsigned short port)
{
if (INVALID_SOCKET == sock)
{
InitSocket();
}
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
#ifdef _WIN32
addr.sin_addr.S_un.S_addr = inet_addr(ip);
#else
addr.sin_addr.s_addr = inet_addr(ip);
#endif
int ret = ::connect(sock, (sockaddr*)&addr, sizeof(sockaddr_in));
if(SOCKET_ERROR == ret)
{
LOG << "connect() failed.\n";
}
else
{
LOG << "connect() succeed.\n";
}
return ret;
}
void close()
{
if(INVALID_SOCKET != sock)
{
#ifdef _WIN32
closesocket(sock);
WSACleanup();
#else
close(sock);
#endif
sock = INVALID_SOCKET;
}
}
bool isRun()
{
return sock != INVALID_SOCKET;
}
int nCount = 0;
bool onRun()
{
if( isRun())
{
fd_set fdReads;
FD_ZERO(&fdReads);
FD_SET(sock, &fdReads);
// timeval t{0, 0};
int ret = select(sock, &fdReads, 0, 0, 0);//&t);
LOG << "select() ret=" <<ret << "\tcount="<< nCount++ << endl;
if(ret < 0)
{
LOG << "select() failed.\n";
close();
return false;
}
if(FD_ISSET(sock, &fdReads))
{
FD_CLR(sock, &fdReads);
if( -1 == recvData(sock))
{
close();
return false;
}
}
}
return true;
}
#define RECV_BUFF_SIZE 10240
char szRecv[RECV_BUFF_SIZE];
char szMsgBuf[RECV_BUFF_SIZE*10];
int lastPos = 0;
int recvData(SOCKET s)
{
int nLen = recv(s, szRecv, RECV_BUFF_SIZE, 0);
LOG << "recv len=" << nLen << endl;
if(nLen <= 0)
{
LOG << "recv()<=0 \n";
return -1;
}
memcpy(szMsgBuf+lastPos, szRecv, nLen);
lastPos += nLen;
while(lastPos >= sizeof(DataHeader))
{
DataHeader *pHeader = (DataHeader*)szMsgBuf;
if(lastPos >= pHeader->len)
{
int nSize = lastPos - pHeader->len;
onMsg(pHeader);
memcpy(szMsgBuf, szMsgBuf+pHeader->len, nSize);
lastPos = nSize;
}
else
{
break;
}
}
return 0;
}
void onMsg(DataHeader *header)
{
switch (header->cmd)
{
case CMD_LOGIN_RESULT:
{
LoginResult *loginRet = (LoginResult*)header;
LOG << "recv: login result-" << loginRet->len << endl;
}
break;
case CMD_LOGOUT_RESULT:
{
LogoutResult *logoutRet = (LogoutResult*)header;
LOG << "recv: logout result-" << logoutRet->len << endl;
}
break;
case CMD_NEW_USER_JOIN:
{
NewUserJoin *userJoin = (NewUserJoin*)header;
LOG << "recv: newUser username-" << userJoin->len << endl;
}
break;
default:
LOG << "recv: unknown result-" << header->cmd << endl;
break;
}
}
int sendData(DataHeader *header)
{
if(isRun() && header)
{
return send(sock, (const char*)header, header->len, 0);
}
return SOCKET_ERROR;
}
};
#endif
|
#ifndef LOG_H
#define LOG_H
#define LCD
#include <Arduino.h>
#ifdef LCD
#include "Adafruit_LiquidCrystal.h"
#endif
#ifdef __arm__
// should use uinstd.h to define sbrk but Due causes a conflict
extern "C" char *sbrk(int incr);
#else // __ARM__
extern char *__brkval;
#endif // __arm__
class Log
{
private:
uint8_t lcd_latch_pin;
uint8_t lcd_clock_pin;
uint8_t lcd_data_pin;
unsigned long heartbeat_interval;
bool heartbeat_on;
int heartbeat_durration;
unsigned long heartbeat_on_at;
unsigned long heartbeat_off_at;
#ifdef LCD
Adafruit_LiquidCrystal lcd;
#endif
int current_row;
int max_row;
int message_num;
public:
// Date(int year, int month, int day)
// {
// setDate(year, month, day);
// }
// Default Contructor
Log();
#ifdef LCD
Log(Adafruit_LiquidCrystal lcd);
#else
Log(void* lcd_void);
#endif
// void setDate(int year, int month, int day)
// {
// m_year = year;
// m_month = month;
// m_day = day;
// }
// int getYear() { return m_year; }
// int getMonth() { return m_month; }
// int getDay() { return m_day; }
int freeMemory();
void check_heartbeat() ;
void print_log_pre(bool force, bool heartbeat);
void print_log(char* msg, bool force, bool heartbeat);
void print_log(const char* msg, bool force, bool heartbeat);
void print_log(int msg, bool force, bool heartbeat);
void print_log(byte msg, bool force, bool heartbeat);
void heartbeat_log(const char* log_msg, bool force);
void heartbeat_log(char* log_msg, bool force);
void heartbeat_log(int log_msg, bool force) ;
void heartbeat_log(byte log_msg, bool force);
void heartbeat_log(char log_msg, bool force);
void heartbeat_log(const char* msg);
void heartbeat_log(char* msg);
void heartbeat_log(char msg);
void heartbeat_log(int msg);
void heartbeat_log(byte msg);
void print_lcd_pre();
void print_lcd(const char*& msg, bool new_line);
void print_lcd(char* msg, bool new_line);
void print_lcd(char msg, bool new_line);
void print_lcd(int msg, bool new_line);
void print_lcd(byte msg, bool new_line);
void lcd_log(const char*& log_msg, bool new_line = true);
void lcd_log(char* log_msg, bool new_line = true);
void lcd_log(int log_msg, bool new_line = true);
void lcd_log(byte log_msg, bool new_line = true);
void lcd_log(char log_msg, bool new_line = true);
// void lcd_log(char* log_msg);
// void lcd_log(int log_msg);
// void lcd_log(byte log_msg);
// void lcd_log(char log_msg);
};
#endif
|
// 230. Kth Smallest Element in a BST
// Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
// Note:
// You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
// Example 1:
// Input: root = [3,1,4,null,2], k = 1
// 3
// / \
// 1 4
// \
// 2
// Output: 1
// Example 2:
// Input: root = [5,3,6,2,4,null,null,1], k = 3
// 5
// / \
// 3 6
// / \
// 2 4
// /
// 1
// Output: 3
// Follow up:
// What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
// TEST CASES
// [5,3,6,2,4,null,null,1]
// 3
// [3,1,4,null,2]
// 1
// [41,37,44,24,39,42,48,1,35,38,40,null,43,46,49,0,2,30,36,null,null,null,null,null,null,45,47,null,null,null,null,null,4,29,32,null,null,null,null,null,null,3,9,26,null,31,34,null,null,7,11,25,27,null,null,33,null,6,8,10,16,null,null,null,28,null,null,5,null,null,null,null,null,15,19,null,null,null,null,12,null,18,20,null,13,17,null,null,22,null,14,null,null,21,23]
// 25
#include <stack>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
// ITERATIVE SOLUTION
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
stack<TreeNode*> s;
s.push(root);
while ( root || !s.empty() ){
while ( root ){ // GO LEFT ALL THE WAY
s.push(root);
root = root->left;
}
root = s.top();
s.pop();
k--;
if ( k == 0 )
return root->val;
root = root->right;
}
return -1;
}
};
// // Binary Tree Recursive Tree inorder Solution. Passed.
// class Solution {
// public:
// vector<int> arr;
// int index;
// void infix(TreeNode* root){
// if ( root->left )
// infix(root->left);
// arr.push_back(root->val);
// if (arr.size() == index)
// return;
// if ( root->right )
// infix(root->right);
// }
// int kthSmallest(TreeNode* root, int k) {
// index = k;
// infix(root);
// return arr[k-1];
// }
// };
|
#include "Point.cpp"
using namespace std;
const double INF = 0x3f3f3f3f;
bool cmpx(P a, P b) { return a.x < b.x; }
bool cmpy(P a, P b) { return a.y < b.y; }
pair<P, P> DnC(vector<P> &p, int L, int R) {
if (R - L <= 1) return make_pair(P(-INF, -INF), P(INF, INF));
int M = (L + R) >> 1;
pair<P, P> l = DnC(p, L, M);
pair<P, P> r = DnC(p, M, R);
}
pair<P, P> closestPair(vector<P> &p) {
sort(p.begin(), p.end(), cmpx);
return DnC(p, 0, p.size());
}
int main() {
}
|
#include <SFML/Graphics.hpp>
using namespace sf;
class LineGraph
{
public:
LineGraph(Vector2f _position, Color _lineColor, Color _dotColor, int _yMin, int _yMax, Texture* _smallNumbers);
void draw(RenderWindow* window); //draws the graph (axes, lines)
void update(float value); //Shifts all values 1 to the left, deletes 0th value, appends new value, deafult val = 0
void setPosition(Vector2f val) { position = val; }
protected:
private:
float values[50];
Vector2f position;
Color lineColor;
Color dotColor;
int yMin;
int yMax;
Texture* smallNumbersTexture;
};
|
//
// SimpleAiActionManager.hpp
// demo_ddz
//
// Created by 谢小凡 on 2018/3/4.
//
#ifndef SimpleAiActionManager_hpp
#define SimpleAiActionManager_hpp
#include "UICard.hpp"
#include "CardTypeHelper.hpp"
#include "CardTypeDefine.hpp"
// 底牌种类定义
enum class RestCTName
{
DoubleKing, // 双王
Three, // 三张
Flush, // 同花
Straight, // 顺子
SingleKing, // 单王
Pair, // 对子
Common // 常规
};
class SimpleAiActionManager
{
public:
using NumVec = std::vector<int>;
using CardVec = std::vector<UICard*>;
public:
static SimpleAiActionManager* getInstance();
void destroyInstance();
// identify rest_card
RestCTName identifyRestCard(const CardVec& vec);
int getRestCardMutiple(const RestCTName& name);
// ai action
bool doActionCall(int id);
bool doActionRob(int id);
int doActionBet(int id);
bool doActionDouble(int id);
CardType doActionPlay(int id);
CardType doActionPlay(CardVec& vec, int id);
const std::vector<NumVec>& getPlaySeqVec(int id);
NumVec getPlayNumVec(int id);
void setPreId(int id) { _pre_id = id; }
void setCurIdx(size_t idx) { _cur_index = idx; }
// _num_map operate
void initNumMap(const std::map<int, CardVec>& card_map);
void addNumData(const CardVec& vec, int id);
void rmNumData(const CardVec& vec, int id);
void clearAllNumData();
// helper function
void sortCardVec(CardVec& vec, const CardType& ct);
CardType identityCardType(const CardVec& vec);
void buildPlaySeqVec(int id);
void initPlaySeqVec();
protected:
int _pre_id;
CardType _pre_type;
std::map<int, NumVec> _num_map;
std::vector<NumVec> _play_seq_vec;
size_t _cur_index;
};
#endif /* SimpleAiActionManager_hpp */
|
#include <iostream>
#include<cstdlib>
#include<cmath>
//这是一个数据结构的课程设计,要求算出输入文件中的一些公式,这里我就把它做成一个支持文件格式的批处理计算器(这名字咋样哈哈,但是不支持负数计算)
//总的来说,犯的最大的错误就是用stack的top,pop等操作,没想到考虑其为空,所以导致各种崩溃,再一个,写程序先下逻辑,后具体到函数,即使暂时用注释代替也好
//免得到时候纠结于函数实现的细节,而忘了整体逻辑,导致逻辑上的失误和遗漏操作。
#include<stack>
#include<fstream>
using namespace std;
int IsOperator(char c); //判断是不是运算符
int OperatorPro(char Oc); //判断运算符的优先级
float ChartoFloat(stack<char>& CC); //char转换成float,针对多位数
float Compute(float a,float b, char c); //用取出的数字和运算符做运算
void PushWaitData(stack<char>& COperatorStack, stack<float>& CDataStack); //取出优先级低的运算符计算,后结果入栈
int main()
{
// char shic = '8';
// int a = (int)shic;
// cout << "a is : " << a << endl; //56,48+8我是验证一下,有种可以直接转换成8的错觉
ifstream fin;
ofstream fout;
char tempc;
stack<char> OperatorStack;
stack<char> Datatemp;
stack<float> DataStack;
fin.open("input.txt");
fout.open("result.txt",ios_base::out | ios_base::app);
if(!fin.is_open())
{
cout <<"there is no such file !" << endl;
exit(EXIT_FAILURE);
}
while(1)
{
tempc = fin.get();
if(fin.eof()) break;
if ('\n' == tempc)
fout << ": "; //只是为了让格式好看点
else
fout << tempc;
if(IsOperator(tempc) == 0) //判断如果是数字的话,包括小数点
{
Datatemp.push(tempc);
}
if (IsOperator(tempc) == 1) //判断如果是运算符
{
if (!Datatemp.empty())
{ //这里问题是如何处理多位数的问题
DataStack.push(ChartoFloat(Datatemp)); //这里应该用引用传递,因为copy这里是不是还得清空元素(改成引用了,不用了,其函数内有pop)
}
//按理说这里,为空时返回肯定少于,为什么还得判断(因为后面有栈的.top动作,为空就崩溃)
if ( OperatorStack.empty()|| OperatorPro(tempc) >= OperatorPro(OperatorStack.top()) ) //如果运算符的级别高于栈定的级别则压入
{ //上面变成>=时,避免了全是+++(同级别连续运算符)类型造成的崩溃,原因是没=就进入else里Pushdata了,连续几个+++就调用了,(未考虑边界(=)问题)
if (')' == tempc) //是右括号时特殊
{
cout << "it is ) " << endl; //这是检测是否查到( 一开始总是不对,居然是因为输入是中文(,检测的是英文的(, 这里要求用英文,否则除了这里得判断,判断优先级也得判断
while(OperatorStack.size()!= 0 && OperatorStack.top() != '(')
{
try{
PushWaitData(OperatorStack,DataStack);
}
catch(const char* es)
{
fout << es << endl;
continue;
}
}
if (OperatorStack.size()!= 0) OperatorStack.pop(); //推出‘(’
}
else
{
OperatorStack.push(tempc);
}
}
else //如果优先级小于的话则要出栈运算,直到碰到大于
{
if (OperatorStack.top() == '(')
{
cout << "it is ( " << endl;
OperatorStack.push(tempc); //'('优先级是7 但是不能把前面的都计算了是不
}
else
{
while(OperatorStack.size() != 0 && OperatorPro(tempc) <= OperatorPro(OperatorStack.top()) )//这里多个运算符时一直崩溃,把判断0放到另一个判断条件前后就好了,因为判断的执行顺序,
//如果先判断优先级,top无值就会崩溃,把判0提前后不满足就不执行后面的判断了,细节
{
try{
PushWaitData(OperatorStack,DataStack);
}
catch(const char* es)
{
fout << es << endl;
continue;
}
cout << "OperateStack size after pushwait :" << OperatorStack.size() << endl;
}
OperatorStack.push(tempc); //把级别比其高的出栈后,把现有运算符压入(上面就纠结了好久就忘了这个,所以编程习惯,要先写上,再具体分析上面的函数,纠结过后就不会因为细节忘了逻辑了)
}
}
}
if('\n' == tempc) //原本这里为了防止只有换行符崩溃的情形加了检查operat是否为空(错了,其实应该检查datastack,关于opera的操作前面都由有检查),造成了漏下只有一个数字没有运算符的情形
{
cout << "in huan hang " << endl;
cout << Datatemp.empty() << endl;
if (!Datatemp.empty())
{
DataStack.push(ChartoFloat(Datatemp)); // 处理最后一个数字,前面是碰到运算符处理,不适用于最后一个数字(没考虑边界问题)
}
cout << " DataStack.size():" <<DataStack.size() << endl;
cout << " Operator.size():" <<OperatorStack.size() << endl;
while ((DataStack.size() > 1)&&(!OperatorStack.empty())) //加了大于1的判读是为了防止操作符数目大于数据个数时的错误输入导致崩溃(data为空的pop,top),其错误信息在下面的排空operator中输出
{
try{
PushWaitData(OperatorStack,DataStack);
}
catch(const char* s)
{
fout << s ;
continue;
}
}
while(!DataStack.empty()) //有空换行符崩溃是这里datastack为空而调了top,改到这里判断,考虑到只有一个数无运算符的情形if改成while是判断一行多个空格的数无操作符的情形,免得留在栈中影响下面的结果),否则其实运算过后这里肯定有一个数的
{
fout << "The line result is : " << DataStack.top(); //这里是否也能把运算过程输出来(通过上面读字符串时直接输出解决)
DataStack.pop(); //全部推空,确保不影响下一行的计算
}
if (!OperatorStack.empty())
{
fout << "Bad input :";
while(!OperatorStack.empty()) //如果有运算符多的,必须排空,否则影响下行的计算
{
fout << OperatorStack.top() << " ";
OperatorStack.pop();
}
}
fout << endl; //最后一个换行就好了
}
}
fin.close();
fout.close();
return 0;
}
void PushWaitData(stack<char>& COperatorStack, stack<float>& CDataStack)
{
cout << "in Pushwait Data " << endl;//为了检查运行到哪里崩溃的笨法
char oc = COperatorStack.top();
COperatorStack.pop(); //两个连续pop出错了。因为先前忘了推进最后一个数,而出了这个程序后还有个pop
float oa,ob;
if (CDataStack.empty())
{
return ; //排查到((()))时加上的,其实应该对于有运算符而数据不够的情形应该都适合 ,比如前面排除的+++
}
else
{
oa = CDataStack.top();
CDataStack.pop();
}
if (CDataStack.empty())
{
return;
}
else{
ob = CDataStack.top();
CDataStack.pop();
}
cout << "ob: oa: oc :" << ob << " " << oa << " " << oc << endl;
cout << "compute result: " << Compute(ob,oa,oc) << endl;
CDataStack.push(Compute(ob,oa,oc)); //注意这里oa,ob的顺序,oa是后来的数
cout << "out Pushwait" << endl;
}
float Compute(float a, float b, char c)
{
float result = 0.0;
switch (c) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
if (0 == b) {throw "bad input cause a/b b = 0!";}
result = a / b; //除数不能为0(这里可以用抛出异常来解决),先用-999999表示异常,成功
break;
case '%':
if((a - (int)a) != 0 || ( b-(int)b ) != 0) throw "bad input cause float % !";
else
{
result = (float)((int)a%(int)b); //浮点数不能取余咋办?(也加上判断来抛出异常?)
break;
}
case '^':
result = pow(a,b);
break;
default:
break;
}
return result;
}
float ChartoFloat(stack<char>& CC)
{
int n = CC.size();
cout << "Dataemp size is :" << n << endl;
int flag = 0; // 标记小数点的位置
float Tdata = 0.0;
char* tempcdata = new char[n];
for(int i = 0 ; i < n; i++)
{
*(tempcdata + i ) = CC.top();
CC.pop();
if ('.' == *(tempcdata + i))
flag = i;
}
for (int i = 0; i < flag ; ++i) //找出小数点的位置后,小数点前乘和小数点后乘
Tdata += ((int)(tempcdata[i] - '0')) * pow(0.1,double(flag - i)); //这里转换用这样么??
for (int i = flag ; i < n; ++i)
Tdata += ((int)(tempcdata[i] -'0')) * pow(10.0,double(i - flag));
cout << "Tdata is : " << Tdata << endl;
return Tdata;
}
int IsOperator(char c)
{
if ( '(' == c ||')' == c ||'+' == c ||'-' == c ||'*' == c ||'/' == c ||'^' == c ||'%' == c )
return 1;
else
{
//是数字或者小数点
if('.' == c ||'0' == c ||'1' == c ||'2' == c ||'3' == c ||'4' == c ||'5' == c ||'6' == c ||'7' == c ||'8' == c ||'9' == c )
return 0;
else return -1; //其他的返回-1
}
}
int OperatorPro(char Oc)
{
//其实这里我在想用switch还是用if效率高
if ('(' == Oc) return 6;
if (')' == Oc) return 5;
if ('^' == Oc) return 3;
if ('%' == Oc) return 2;
if ('*' == Oc) return 2;
if ('/' == Oc) return 2;
if ('+' == Oc) return 1;
if ('-' == Oc) return 1;
return 0;
}
|
#include <FastCG/World/Transform.h>
#include <FastCG/World/FlyController.h>
#include <FastCG/Input/MouseButton.h>
#include <FastCG/Input/Key.h>
#include <FastCG/Input/InputSystem.h>
#include <FastCG/Core/Math.h>
namespace FastCG
{
FASTCG_IMPLEMENT_COMPONENT(FlyController, Behaviour);
void FlyController::OnUpdate(float time, float deltaTime)
{
auto *pTransform = GetGameObject()->GetTransform();
auto &rotation = pTransform->GetWorldRotation();
if (InputSystem::GetMouseButton(MouseButton::RIGHT_BUTTON) == MouseButtonState::PRESSED)
{
if (mRightMouseButtonPressed)
{
auto mousePosition = InputSystem::GetMousePosition();
if (mousePosition != mLastMousePosition)
{
if (rotation != mRotation)
{
const auto halfDegToRad = 0.5f * MathF::DEGREES_TO_RADIANS;
auto euler = glm::degrees(glm::eulerAngles(rotation));
// FIXME: can't map non-multiple of PI rotations around the Z axis for now
assert(fmod(euler.z, 180) == 0);
mTheta = euler.x;
if (euler.z == 180)
{
mTheta -= 180;
}
mTheta *= halfDegToRad;
if (mTheta < 0)
{
mTheta = -mTheta;
}
mPhi = euler.y;
if (euler.z == 180)
{
mPhi += 180;
}
mPhi *= halfDegToRad;
if (mPhi < 0)
{
mPhi = -mPhi;
}
}
auto delta = deltaTime * mTurnSpeed;
auto thetaDelta = (mousePosition.y - (float)mLastMousePosition.y) * delta;
auto phiDelta = (mousePosition.x - (float)mLastMousePosition.x) * delta;
mTheta = fmod(mTheta + thetaDelta, MathF::TWO_PI);
mPhi = fmod(mPhi + phiDelta, MathF::TWO_PI);
// Based on: https://github.com/moble/quaternionic/blob/main/quaternionic/converters.py
float cosTheta = cos(mTheta);
float sinTheta = sin(mTheta);
float cosPhi = cos(mPhi);
float sinPhi = sin(mPhi);
mRotation = glm::quat{-cosTheta * cosPhi, sinTheta * cosPhi, cosTheta * sinPhi, sinTheta * sinPhi};
pTransform->SetRotation(mRotation);
mLastMousePosition = mousePosition;
}
}
else
{
mRightMouseButtonPressed = true;
mLastMousePosition = InputSystem::GetMousePosition();
}
}
else
{
mRightMouseButtonPressed = false;
}
auto position = pTransform->GetWorldPosition();
if (InputSystem::GetKey(Key::PAGE_UP) || InputSystem::GetKey(Key::LETTER_Q))
{
pTransform->SetPosition(position + (rotation * glm::vec3(0, -1, 0) * mMoveSpeed * deltaTime));
}
else if (InputSystem::GetKey(Key::PAGE_DOWN) || InputSystem::GetKey(Key::LETTER_E))
{
pTransform->SetPosition(position + (rotation * glm::vec3(0, 1, 0) * mMoveSpeed * deltaTime));
}
if (InputSystem::GetKey(Key::LEFT_ARROW) || InputSystem::GetKey(Key::LETTER_A))
{
pTransform->SetPosition(position + (rotation * glm::vec3(-1, 0, 0) * mMoveSpeed * deltaTime));
}
else if (InputSystem::GetKey(Key::RIGHT_ARROW) || InputSystem::GetKey(Key::LETTER_D))
{
pTransform->SetPosition(position + (rotation * glm::vec3(1, 0, 0) * mMoveSpeed * deltaTime));
}
if (InputSystem::GetKey(Key::UP_ARROW) || InputSystem::GetKey(Key::LETTER_W))
{
pTransform->SetPosition(position + (rotation * glm::vec3(0, 0, -1) * mMoveSpeed * deltaTime));
}
else if (InputSystem::GetKey(Key::DOWN_ARROW) || InputSystem::GetKey(Key::LETTER_S))
{
pTransform->SetPosition(position + (rotation * glm::vec3(0, 0, 1) * mMoveSpeed * deltaTime));
}
}
}
|
/*
** Copyright (c) 2013, Xin YUAN, courses of Zhejiang University
** All rights reserved.
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the 2-Clause BSD License.
**
** Author contact information:
** yxxinyuan@zju.edu.cn
**
*/
/*
This file contains classes for global variables of _os_window.
Author: Lijuan Mei
*/
////////////////////////////////////////////////////////////////////////////////
// internal
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// static variables
RECT _os_window::m_rcDefault = { CW_USEDEFAULT, CW_USEDEFAULT, 0, 0 };
////////////////////////////////////////////////////////////////////////////////
|
#include<iostream>
#include<string>
using namespace std;
int Atoi(char ch)
{
if('0'<=ch && ch<='9')
{
return (int)ch-(int)'0';
}
if('A'<=ch && ch<='F')
{
return (int)ch-(int)'A'+10;
}
return -1;
}
int main()
{
string m;
int n;
int base=1;
cin >>m>>n;
int ans=0;
for(int i=m.size()-1;i>=0;i--)
{
ans+=Atoi(m[i])*base;
base*=n;
}
cout <<ans<<endl;
return 0;
}
|
/*
CSCN7103021W-Negussie
*/
//#include <iostream>
//#include "Customer.h"
//#include "SaveLoad.h"
//#include "Users.h"
//#include "Inventory.h"
//#include "Lists.h"
//#include "Node.cpp"
//#include "Lists.cpp"
//#include "TransactionHistory.h"
//#include "Validation.h"
//using namespace std;
//int main(void){
// initializeElementsUserArray();
// //---------------------------------------------------------------------
// //Testing Integration for Customer and Save/Load
// //---------------------------------------------------------------------
// //CUS-SVLD-001
// char firstName[] = "John";
// char lastName[] = "Doe";
// ofstream outputFile("Customer.txt"); //ofstream with file name created
// Customer JohnDoe (firstName,lastName,30); //Customer object created
// JohnDoe.save(outputFile);
// outputFile.close();
// //Expectations: Customer.txt file will be created, and in file Customer John Doe
// // and its contents will be present
// //RESULT: PASSED
// //CUS-SVLD-002
// ifstream inputFile("Customer.txt"); //ifstream with file name
// Customer EmptyCustomer; //Empty Customer created
// printf("\nBEFORE LOAD:\n");
// EmptyCustomer.printCustomer(); //printing Customer prior to file load
// EmptyCustomer.load(inputFile); //load object info from file into Customer object
// inputFile.close();
// printf("\nAFTER LOAD:\n");
// EmptyCustomer.printCustomer();
// //Expectations: Contents of John Doe object that was saved to Customer.txt file will
// // be placed into Empty Customer object. Validated by contents printed out Empty Customer print call
// //RESULT: PASSED
// //---------------------------------------------------------------------
// //Testing Integration for Users and Save/Load
// //---------------------------------------------------------------------
// //USR-SAV-001
// //Load input into variables
// char username[] = "Eazaz";
// char password[] = "Password1";
// char userID[] = "EazazJ1";
// //Create and open "Users.txt" file to save Users into
// outputFile.open("Users.txt");
// //Create a user of type Admin
// Admin Eazaz(username, password, userID);
// //Save the Admin object to the file "Users.txt"
// Eazaz.save(outputFile);
// outputFile.close();
// //Expectations: Users.txt file will be created, and in file User Eazaz
// // and its contents will be present
// // RESULT: PASSED
// //USR-SAV-002
// //Open "Users.txt" file to load objects from
// inputFile.open("Users.txt");
// //Create empty object to load User object from "Users.txt" file into
// Admin EazazLoaded;
// printf("\nBEFORE LOAD:\n");
// EazazLoaded.displayUser();
// //Load the User object from file into empty User Object
// EazazLoaded.load(inputFile);
// inputFile.close();
// printf("\nAFTER LOAD:\n");
// EazazLoaded.displayUser();
// //Expectations: Contents of Eazaz object that was saved to Users.txt file will
// // be placed into Empty Admin object. Validated by contents printed out
// //Results: PASSED
// //---------------------------------------------------------------------
// //Testing Integration for Inventory and Save/Load
// //---------------------------------------------------------------------
// //INV-SVLD-001
// char myMake[MAX_LEN] = "Ford";
// char myModel[MAX_LEN] = "Escape";
// char myVIN[MAX_LEN] = "ABC123";
// outputFile.open("Inventory.txt"); //ofstream with file name created
// Inventory myInventory(myMake, myModel, myVIN, SUV, 25999, 19999);
// myInventory.save(outputFile);
// outputFile.close();
// //Expectations: Inventory.txt file will be created, and in file Inventory object "myInventory"
// // and its contents will be present
// //RESULT: PASSED
// //INV-SVLD-002
// inputFile.open("Inventory.txt");
// //Create empty object to load Inventory object from "Inventory.txt" file into
// Inventory emptyInventory;
// printf("\nBEFORE LOAD:\n");
// emptyInventory.printInventory();
// //Load the User object from file into empty User Object
// emptyInventory.load(inputFile);
// inputFile.close();
// printf("\nAFTER LOAD:\n");
// emptyInventory.printInventory();
// //Expectations: Contents of myInventory object that was saved to Inventory.txt file will
// // be placed into Empty Inventory object. Validated by contents printed out
// //Results: PASSED
// //---------------------------------------------------------------------
// //Testing Integration for Customer and List
// //---------------------------------------------------------------------
// //CUS-LST-001
// Lists<Customer> myCustomerList;
// Customer* newCustomer = new Customer(firstName,lastName,30);
// myCustomerList.addToList(newCustomer);
// // PASSED with Bugs 4/13/2021 5:54pm ->RAISED ISSUE
// // PASSED 4/13/2021
// //---------------------------------------------------------------------
// //Testing Integration for User and List
// //---------------------------------------------------------------------
// //USR-LST-001
// Lists<Users> myUserList;
// Users* newUser = new Admin(username, password, userID);
// myUserList.addToList(newUser);
// newUser->displayUser();
// //PASSED
// //---------------------------------------------------------------------
// //Testing Integration for Inventory and List
// //---------------------------------------------------------------------
// //INV-LST-001
// Lists<Inventory> myInventoryList;
// Inventory* newInventory = new Inventory(myMake, myModel, myVIN, SUV, 25999, 19999);
// myInventoryList.addToList(newInventory);
// //PASSED
// //---------------------------------------------------------------------
// //Testing Integration for Transaction History with Customer, User, Inventory
// //---------------------------------------------------------------------
// // CUS-TH-001 USR-TH-001 INV-TH-001
// TransactionHistory myTransactionHistory(firstName, newInventory, newCustomer, newUser);
// myTransactionHistory.printTransaction();
// //PASSED
// //---------------------------------------------------------------------
// //Testing Integration for Transaction History with lists
// //---------------------------------------------------------------------
// //TH-LISTS-001
// Lists<TransactionHistory> myTransactionHistoryList;
// myTransactionHistoryList.addToList(new TransactionHistory(firstName, newInventory, newCustomer, newUser));
// myTransactionHistoryList.addToList(new TransactionHistory(lastName, newInventory, newCustomer, newUser));
// //PASSED
// //TH-SVLD-001
// outputFile.open("TransactionHistory.txt");
// myTransactionHistory.save(outputFile);
// outputFile.close();
// //PASSED
// //TH-SVLD-002
// inputFile.open("TransactionHistory.txt");
// char emptyBlank [30] = "";
// TransactionHistory emptyTransactionHistory(emptyBlank, new Inventory, new Customer, new Users);
// emptyTransactionHistory.printTransaction();
// emptyTransactionHistory.load(inputFile);
// inputFile.close();
// emptyTransactionHistory.printTransaction();
// //PASSED
// //---------------------------------------------------------------------
// //Testing Integration of LIST-SAV
// //---------------------------------------------------------------------
// //LIST-SAV-001
// myCustomerList.addToList(new Customer(firstName, lastName, 45));
// myCustomerList.addToList(new Customer);
// myCustomerList.save("myCustomerList.txt");
// //PASSED
// //LIST-SAV-002
// Lists<Customer> emptyCustomer;
// emptyCustomer.load("myCustomerList.txt");
// //PASSED
// //---------------------------------------------------------------------
// //Testing integration of Lists and Customer
// //---------------------------------------------------------------------
// //CUS-LST-002
// cout << "\nNumber before:" << myCustomerList.getNumOfItems() << endl;
// myCustomerList.removeFromList(1);
// cout << "Number after:" << myCustomerList.getNumOfItems() << endl;
// //PASSED
// //---------------------------------------------------------------------
// //Testing integration of Lists and Users
// //---------------------------------------------------------------------
// //USR-LST-002
// cout << "\nNumber before:" << myUserList.getNumOfItems() << endl;
// //myUserList.removeFromList(1); //check later
// cout << "Number after:" << myUserList.getNumOfItems() << endl;
// //PASSED
// //---------------------------------------------------------------------
// //Testing integration of Lists and Inventory
// //---------------------------------------------------------------------
// //INV-LST-002
// cout << "\nNumber before:" << myInventoryList.getNumOfItems() << endl;
// myInventoryList.removeFromList(1);
// cout << "Number after:" << myInventoryList.getNumOfItems() << endl;
// //PASSED
// //---------------------------------------------------------------------
// //Testing integration of Lists and Transaction history
// //---------------------------------------------------------------------
// //TH-LST-002
// cout << "\nNumber before:" << myTransactionHistoryList.getNumOfItems() << endl;
// myTransactionHistoryList.removeFromList(1);
// cout << "Number after:" << myTransactionHistoryList.getNumOfItems() << endl;
// //PASSED
// //---------------------------------------------------------------------
// //Testing integration of 2dArray and Save/Load
// //---------------------------------------------------------------------
// //VER-SAV-001
// cout << "Display Array:" << endl;
// displayArray();
// saveArray();
// //Passed
// //---------------------------------------------------------------------
// //Testing integration of 2dArray and Save/Load
// //---------------------------------------------------------------------
// //VER-SAV-001
// char me[] = "WOWIDK";
// Eazaz.changeUsername(me);
// cout << "Display Changed Array:" << endl;
// displayArray();
// loadArray();
// cout << "Display Loaded Array:" << endl;
// displayArray();
// //PASSED
// //---------------------------------------------------------------------
// //Testing integration of Validation
// //---------------------------------------------------------------------
// //VLD-MAIN-001
// string a = "Hel lo1";
// if (doesStringOnlyContain(a, NUMBER+LETTER+SPACE))
// cout << "String contains all number,letter and spaces." << endl;
// else
// cout << "String doesn't contain all number,letter and spaces." << endl;
// //PASSED
// return 0;
//}
|
#include<bits/stdc++.h>
using namespace std;
bool ifPossible(int a, int b, int c, int x, int y)
{
if((a+b+c) != (x+y)) //Check if enough stones are present
return false;
if(a <= x) //As smallest of existing pile must be smaller than smaller
return true;
else
return false;
}
int main()
{
fstream fin("Input.txt", ios::in);
int Testcases;
fin>>Testcases;
std::vector<int> v;
int temp;
int x;
int y;
int a;
int b;
int c;
while(Testcases--){
//Input size of three piles.
for(int i = 0 ; i<3; ++i){
fin >> temp;
v.push_back(temp);
}
//Arrange in acending order.
std::sort(v.begin(), v.end());
a = v.at(0);
b = v.at(1);
c = v.at(2);
v.clear();
//Input required sizes.
fin >> x >> y;
//Assume x <= y, if not, do so.
if(x > y) {
swap(x,y);
}
//Check if not possible to make piles
ifPossible(a, b, c, x, y) ? cout<<"YES" : cout<<"NO";
cout<<endl;
}
//int k = x - a; //Stones required to increase height of a to height of x;
}
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define pb push_back
#define mp make_pair
vector<ll> v1,v2;
int main(){
int n,m;ll x;
cin >> n;
for(int i=0;i<n;i++){
cin >> x;
v1.pb(x);
}
sort(v1.begin(),v1.end());
cin >> m;
for(int i=0;i<m;i++){
cin >> x;
v2.pb(x);
}
ll xx,yy,aa,bb;
ll d,ans=-20000000;
int idx;
sort(v2.begin(),v2.end());
vector<ll>::iterator it=v2.begin();
for(int i=0;i<n;i++){
d=v1[i];
it=lower_bound(v2.begin(),v2.end(),d);
idx=it-v2.begin();
xx=(3*(n-i))+(2*i);
yy=(3*(m-idx))+2*idx;
if(xx-yy>ans){ans=xx-yy;aa=xx;bb=yy;}
else if((xx-yy==ans)&& xx>aa ){aa=xx;bb=yy;}
}
if(2*(n-m)>ans){aa=2*n;bb=2*m;}
cout << aa<<":"<<bb<< endl;
return 0;
}
|
#include <cmath>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <set>
#include <stack>
#include <sstream>
#include <string>
using namespace std;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/* Solution */
const int MOD = 1000000007;
class Solution {
public:
int numSub1(string s)
{
long long ans = 0;
int i = 0;
while (i < s.size())
{
if (s[i] == '0')
{
i++;
continue;
}
int j = i;
while (j + 1 < s.size() && s[j + 1] == '1')
{
j++;
}
long long len = j - i + 1;
ans = (ans + ((len + 1) * len) / 2) % MOD;
i = j + 1;
}
return ans;
}
int numSub(string s)
{
long long ans = 0;
long long seq = 0;
for (char c : s)
{
seq = c == '0' ? 0 : seq + 1;
ans = (ans + seq) % MOD;
}
return ans;
}
};
int main()
{
Solution sol;
// string s = "0110111";
// string s = "101";
// string s = "111111";
string s = "000";
cout << sol.numSub(s) << endl;
}
|
#include "Context.h"
#include "ResourceManager.h"
#include "ActionScopeManager.h"
#include "PrimitiveRenderObjects.h"
#include "GameMapManager.h"
#include <iostream>
Context::Context(string_t name)
{
_name = name;
_keys_combined = std::list<sf::Keyboard::Key>();
_music = NULL;
_inner_elements = std::list<Context*>();
_inner_element_lookup = std::unordered_map<string_t, Context*>();
has_lingering_mouseclick_handler = false;
has_lingering_mousedown_handler = false;
_music_thing = TEXT("");
}
Context::~Context()
{
}
void Context::add_inner_element(string_t name, Context * element)
{
_inner_element_lookup[name] = element;
_inner_elements.push_back(element);
}
bool Context::handle_mouseclick(int x, int y)
{
ActionScopeManager::set_scope(this);
if(InteractionBase::handle_mouseclick(x, y)) return true;
for (auto element : _inner_elements)
{
if (element->handle_mouseclick(x, y)) return true;
}
return false;
}
bool Context::handle_mousedown(int x, int y)
{
ActionScopeManager::set_scope(this);
if(InteractionBase::handle_mousedown(x, y)) return true;
for (auto element : _inner_elements)
{
if (element->handle_mousedown(x, y)) return true;
}
return false;
}
bool Context::handle_keypress(sf::Keyboard::Key key)
{
ActionScopeManager::set_scope(this);
if(InteractionBase::handle_keypress(key)) return true;
for (auto element : _inner_elements)
{
if (element->handle_keypress(key)) return true;
}
return false;
}
bool Context::handle_keyheld(sf::Keyboard::Key key)
{
ActionScopeManager::set_scope(this);
if(InteractionBase::handle_keyheld(key)) return true;
for (auto element : _inner_elements)
{
if (element->handle_keyheld(key)) return true;
}
return false;
}
bool Context::handle_named_event(string_t event_name)
{
ActionScopeManager::set_scope(this);
if(InteractionBase::handle_named_event(event_name)) return true;
for (auto element : _inner_elements)
{
if (element->handle_named_event(event_name)) return true;
}
return false;
}
void Context::render(sf::RenderWindow& window)
{
ActionScopeManager::set_scope(this);
for (auto draw : _draw_list)
{
draw->render(window);
}
for (auto element : _inner_elements)
{
element->render(window);
}
}
const std::list<sf::Keyboard::Key> Context::Keys()
{
_keys_combined.clear();
for(auto key : InteractionBase::Keys())
_keys_combined.push_back((key));
for (auto element : _inner_elements)
for (auto key : element->Keys())
_keys_combined.push_back(key);
_keys_combined.unique();
return _keys_combined;
}
ScriptScope * Context::build_context(ScriptRaw * raw)
{
auto scope = new ScriptScope();
scope->scope_target = raw->vals->vals;
scope->statements = NULL; //error b/c this doesn't make sense, there shouldn't be actions in the def-scope of context
scope->defs[TEXT("def_attrib")] = [&](ScriptRaw* attrib_raw){
string_t attrib_name = attrib_raw->vals->vals;
if (attrib_name == TEXT("sprite"))
{
string_t sprite_name = attrib_raw->vals->next->vals;
auto x = attrib_raw->vals->next->next->vali();
auto y = attrib_raw->vals->next->next->next->vali();
auto draw_thing = new SpriteRenderObject(sprite_name);
draw_thing->set_position((float)x, (float)y);
_draw_list.push_back(draw_thing);
}
else if (attrib_name == TEXT("text"))
{
string_t text_name = attrib_raw->vals->next->vals;
auto x = attrib_raw->vals->next->next->vali();
auto y = attrib_raw->vals->next->next->next->vali();
auto draw_thing = new TextRenderObject(text_name);
draw_thing->set_position((float)x, (float)y);
if (attrib_raw->vals->next->next->next->next != NULL && attrib_raw->vals->next->next->next->next->vals != TEXT(""))
{
draw_thing->set_font_size(attrib_raw->vals->next->next->next->next->vali());
}
_draw_list.push_back(draw_thing);
}
else if(attrib_name == TEXT("map"))
{
string_t map_name = attrib_raw->vals->next->vals;
_draw_list.push_back(GameMapManager::get_map(map_name));
}
else if (attrib_name == TEXT("music"))
{
_music_thing = attrib_raw->vals->next->vals;
}
else if (attrib_name == TEXT("value"))
{
//TODO
}
else if (attrib_name == TEXT("hide_nonfocused"))
{
_only_handle_when_top_context = true;
}
return (ScriptScope*)NULL;
};
scope->defs[TEXT("def_handler")] = [&](ScriptRaw* handler_raw){
string_t event_name = handler_raw->vals->vals;
if (event_name.find(TEXT("mouse")) == 0)
{
auto local_scope = new ScriptScope();
auto handler_statements = std::shared_ptr<script_statement_list_t>(new script_statement_list_t());
local_scope->statements = handler_statements.get();
auto handler = [handler_statements](MouseEvent){
for (auto stmt : *handler_statements)
{
stmt.first(stmt.second);
}
return true;
};
if (handler_raw->vals->next == NULL || handler_raw->vals->next->vals == TEXT(""))
{
if (event_name == TEXT("mouseclick")) lingering_mouseclick_handler = handler;
else if (event_name == TEXT("mousedown")) lingering_mousedown_handler = handler;
if (event_name == TEXT("mouseclick")) has_lingering_mouseclick_handler = true;
else if (event_name == TEXT("mousedown")) has_lingering_mousedown_handler = true;
if (_draw_list.size() != 1) return (ScriptScope*)NULL; //error bad def
}
else
{
sf::IntRect rect;
auto x1 = handler_raw->vals->next->vali();
auto y1 = handler_raw->vals->next->next->vali();
auto x2 = handler_raw->vals->next->next->next->vali();
auto y2 = handler_raw->vals->next->next->next->next->vali();
auto topleft = sf::Vector2i(x1, y1);
auto bottomright = sf::Vector2i(x2, y2);
rect = sf::IntRect(topleft, bottomright - topleft);
if (event_name == TEXT("mouseclick"))
{
add_mouseclick_handler(rect, handler);
}
else if (event_name == TEXT("mousedown"))
{
add_mousedown_handler(rect, handler);
}
}
return local_scope;
}
else if (event_name.find(TEXT("key")) == 0)
{
auto key = (sf::Keyboard::Key)handler_raw->vals->next->vali();
auto local_scope = new ScriptScope();
auto handler_statements = std::shared_ptr<script_statement_list_t>(new script_statement_list_t());
local_scope->statements = handler_statements.get();
auto handler = [handler_statements](){
for (auto stmt : *handler_statements)
{
stmt.first(stmt.second);
}
return true;
};
if (event_name == TEXT("keypress"))
{
add_keypress_handler(key, handler);
}
else if (event_name == TEXT("keyheld"))
{
add_keyheld_handler(key, handler);
}
return local_scope;
}
else
{
auto local_scope = new ScriptScope();
auto handler_statements = std::shared_ptr<script_statement_list_t>(new script_statement_list_t());
local_scope->statements = handler_statements.get();
auto handler = [handler_statements](){
for (auto stmt : *handler_statements)
{
stmt.first(stmt.second);
}
return true;
};
add_named_event_handler(event_name, handler);
return local_scope;
}
};
scope->defs[TEXT("def_element")] = [&](ScriptRaw * element_raw){
auto inner_name = _name + TEXT(".") + element_raw->vals->vals;
auto inner_element = new Context(inner_name);
auto build_thing = inner_element->build_context(element_raw);
add_inner_element(inner_name, inner_element);
return build_thing;
};
return scope;
}
void Context::prep()
{
_context_dimensions = sf::FloatRect(0,0,0,0);
for (auto thing : _draw_list)
{
thing->prep();
_context_dimensions = thing->get_bounds();
}
if (has_lingering_mouseclick_handler)
{
auto rect = _context_dimensions;
rect.left /= ResourceManager::scaling_factor().x;
rect.top /= ResourceManager::scaling_factor().y;
rect.width /= ResourceManager::scaling_factor().x;
rect.height /= ResourceManager::scaling_factor().y;
add_mouseclick_handler((sf::IntRect)rect, lingering_mouseclick_handler);
has_lingering_mouseclick_handler = false;
}
if (has_lingering_mousedown_handler)
{
auto rect = _context_dimensions;
rect.left /= ResourceManager::scaling_factor().x;
rect.top /= ResourceManager::scaling_factor().y;
rect.width /= ResourceManager::scaling_factor().x;
rect.height /= ResourceManager::scaling_factor().y;
add_mousedown_handler((sf::IntRect)rect, lingering_mousedown_handler);
has_lingering_mousedown_handler = false;
}
for (auto element : _inner_elements)
{
element->prep();
}
if (_music_thing != TEXT(""))
{
if (_music != NULL)
{
_music->stop();
delete _music;
}
_music = ResourceManager::get_music(_music_thing);
_music->setLoop(true);
_music->setVolume(0);
_music->play();
}
}
void Context::step_scale(float val)
{
for (auto thing : _draw_list) thing->set_scale(val, val);
for (auto inner : _inner_elements) inner->step_scale(val);
}
void Context::step_scalex(float val)
{
for (auto thing : _draw_list) thing->set_scale(val, thing->get_scale().y);
for (auto inner : _inner_elements) inner->step_scalex(val);
}
void Context::step_scaley(float val)
{
for (auto thing : _draw_list)thing->set_scale(thing->get_scale().x, val);
for (auto inner : _inner_elements) inner->step_scaley(val);
}
void Context::step_opacity(float val)
{
for (auto thing : _draw_list)
{
auto cc = thing->get_color();
thing->set_color(sf::Color(cc.r, cc.g, cc.b, (sf::Uint8)(255 * val)));
}
for (auto inner : _inner_elements) inner->step_opacity(val);
}
void Context::step_volume(float val)
{
_music->setVolume(val * ResourceManager::music_volume());
}
std::function<void(float)> Context::get_step(string_t attrib)
{
if (attrib == TEXT("scale"))
{
return[&](float val){ step_scale(val); };
}
else if (attrib == TEXT("scale_x"))
{
return[&](float val){ step_scalex(val); };
}
else if (attrib == TEXT("scale_y"))
{
return[&](float val){ step_scaley(val); };
}
else if (attrib == TEXT("opacity"))
{
return[&](float val){step_opacity(val); };
}
else if (attrib == TEXT("volume"))
{
return[&](float val){step_volume(val); };
}
return[](float){};
}
const string_t& Context::get_name()
{
return _name;
}
Context * Context::get_inner_element(string_t name)
{
if (_inner_element_lookup.find(name) != _inner_element_lookup.end())
{
return _inner_element_lookup[name];
}
else
{
for (auto context : _inner_elements)
{
if (name.find(context->_name) == 0)
{
return _inner_element_lookup[context->_name];
}
}
}
return NULL;
}
|
#pragma once
#include <iostream>
#include <ctime>
#include "Pet.h"
using namespace std;
class Purchase
{
public:
int purchaseId;
string custName, custPhNo, custEmail;
double totalAmount = 0;
string purchaseTimeStamp;
Purchase* next = NULL;
Pet* pets = NULL;
~Purchase()
{
while (pets != NULL)
{
Pet* next = pets->next;
delete(&pets);
pets = next;
}
}
};
|
#include <iostream>
int main()
{
using namespace std;
float y, w, z = 0.05e-5, m = 6;
const double e = 2.71828;
y = cos(5*m)/pow(sin(0.4*m),2);
w = 4 * z * y - 7 * pow(e, -2 * y);
cout.unsetf(ios::dec);
cout.setf(ios::oct);
cout << "y=" << y << '\n';
cout << "w=" << w;
}
|
//
// Compiler/AST/ExpressionIdentifier.h
//
// Brian T. Kelley <brian@briantkelley.com>
// Copyright (c) 2007, 2008, 2011, 2012, 2014 Brian T. Kelley
//
// Chris Leahy <leahycm@gmail.com>
// Copyright (c) 2007 Chris Leahy
//
// This software is licensed as described in the file LICENSE, which you should have received as part of this distribution.
//
#ifndef COMPILER_AST_EXPRESSIONIDENTIFIER_H
#define COMPILER_AST_EXPRESSIONIDENTIFIER_H
#include "Compiler/AST/Expression.h"
namespace Compiler { namespace AST {
class ExpressionIdentifier : public Expression {
public:
ExpressionIdentifier();
public: // MARK: -- Source Information --
std::string GetName() const {
return m_name;
}
void SetName(std::string name) {
m_name = name;
}
public: // MARK: -- Structural Information --
Kind GetKind() const override;
public: // MARK: -- Verification --
void ResolveTypes(const Context& context) override;
void ResolveNullTypes(const Context& context) override;
void Verify(const Context& context, Compiler::Diagnostics::IReporting& reporter) const override;
public: // MARK: -- Accessors --
void Accept(IExpressionVisitor& visitor) const override;
private:
bool IsNull() const;
private:
std::string m_name;
bool m_unknownEvaluationType;
};
} /*namespace AST*/ } /*namespace Compiler*/
#endif // COMPILER_AST_EXPRESSIONIDENTIFIER_H
|
//
// Compiler/AST/Variable.cpp
//
// Brian T. Kelley <brian@briantkelley.com>
// Copyright (c) 2007, 2008, 2011, 2012, 2014 Brian T. Kelley
//
// Chris Leahy <leahycm@gmail.com>
// Copyright (c) 2007 Chris Leahy
//
// This software is licensed as described in the file LICENSE, which you should have received as part of this distribution.
//
#include "Compiler/AST/Variable.h"
using namespace Compiler::AST;
Variable::Variable() :
m_fileRange(Compiler::Diagnostics::FileRange::Empty),
m_name(Type::UndefinedName),
m_class(),
m_type(Type(Type::UndefinedName))
{ }
|
#include<bits/stdc++.h>
using namespace std;
void flip(vector<int>& arr,int index,int n)
{
int i = 0;
int j= index;
while( i < n && j >=0 && i < j)
{
swap(arr[i],arr[j]);
i++;
j--;
}
return ;
}
void solve(vector<int>& arr,int n)
{
if(n==0)
{
return ;
}
vector<int> output;
for(int i=n-1;i>=0;i--)
{
if(arr[i]==i+1)
{
continue;
}
// we will find the index of largest elemnt.
int j;
for(j=0;j<n;j++)
{
if(arr[j]==i+1)
{
break;
}
}
if(j!=0)
{
flip(arr,j,n);
output.push_back(j+1);
}
flip(arr,i,n);
output.push_back(i+1);
}
for(int i=0;i<n;i++)
{
cout << arr[i] << " ";
}
cout << endl;
for(int i=0;i<output.size();i++)
{
cout << output[i] << " ";
}
cout << endl;
}
int main()
{
int n;
cin >> n;
vector<int> arr;
for(int i=0;i<n;i++)
{
int val;
cin >> val;
arr.push_back(val);
}
solve(arr,n);
return 0;
}
|
///////////////////////////////////////////////////////////////////////
// Screen.cpp
///////////////////////////////////////////////////////////////////////
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <string>
#include <vector>
#include "../Text/Text.hpp"
#include "ConfigScreen.hpp"
#include "Screen.hpp"
///////////////////////////////////////////////////////////////////////
mr::Screen::Screen(std::string thePath) :
mButton()
{
mConfig.load(thePath);
}
///////////////////////////////////////////////////////////////////////
mr::Screen::Screen() :
mr::Screen::Screen("")
{
}
///////////////////////////////////////////////////////////////////////
mr::Screen::~Screen()
{
}
///////////////////////////////////////////////////////////////////////
void mr::Screen::load(std::string thePath)
{
if(!mConfig.load()) if(!mConfig.load(thePath)) exit(1);
if(!mTexture.loadFromFile(mConfig.getPathMenuNone())) exit(1);
mSprite.setTexture(mTexture);
mr::Text tTxt(thePath);
for(int i = 0; i < 4; i++) //@todo remember to correct this value (4)
mButton.push_back(tTxt);
}
///////////////////////////////////////////////////////////////////////
void mr::Screen::loadTexture(std::string thePath)
{
if(!mTexture.loadFromFile(thePath)) return;
mSprite.setTexture(mTexture);
}
///////////////////////////////////////////////////////////////////////
int mr::Screen::eventButtons(sf::RenderWindow& theWindow, sf::Event& theEvent)
{
int i = 0;
for(; i < static_cast<int>(mButton.size()); i++)
{
if(mButton[i].isPressed(theWindow))
{
return i;
}
}
return -1;
}
///////////////////////////////////////////////////////////////////////
mr::ConfigScreen& mr::Screen::getConfig()
{
return mConfig;
}
///////////////////////////////////////////////////////////////////////
void mr::Screen::draw(sf::RenderTarget& theTarget, sf::RenderStates theStates) const
{
theStates.transform = mSprite.getTransform();
theStates.texture = &mTexture;
theTarget.draw(mSprite, theStates); //background
for(uint i = 0; i < mButton.size(); i++)
{
theTarget.draw(mButton[i], theStates); //buttons
}
}
///////////////////////////////////////////////////////////////////////
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.