text
string
size
int64
token_count
int64
// // SneakyJoyStick.cpp // air // // Created by peter on 14-10-11. // Copyright (c) 2014ๅนด qiuyang. All rights reserved. // #include "SneakyJoystick.h" SneakyJoystick::~SneakyJoystick() { } bool SneakyJoystick::initWithRect(CCRect rect) { bool bRet = CCNode::init(); if (bRet) { stickPosition = CCPointZero; degrees = 0.0f; velocity = CCPointZero; autoCenter = true; isDPad = false; hasDeadzone = false; numberOfDirections = 4; this->joystickRadius = rect.size.width/2; this->thumbRadius = 32.0f; this->deadRadius = 0.0f; //Cocos node stuff setPosition(rect.origin); } return bRet; } void SneakyJoystick::onEnterTransitionDidFinish() { CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 1, true); } void SneakyJoystick::onExit() { CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this); } void SneakyJoystick::setIsDPad(bool b) { isDPad = b; if(isDPad) { hasDeadzone = true; this->deadRadius = 10.0f; } } void SneakyJoystick::setJoystickRadius(float r) { joystickRadius = r; joystickRadiusSq = r * r; } void SneakyJoystick::setThumbRadius(float r) { thumbRadius = r; thumbRadiusSq = r * r; } void SneakyJoystick::setDeadRadius(float r) { deadRadius = r; deadRadiusSq = r * r; } #pragma mark touch delegate bool SneakyJoystick::ccTouchBegan(CCTouch *touch, CCEvent *event) { CCPoint location = touch->getLocation(); location = this->convertToNodeSpace(location); //Do a fast rect check before doing a circle hit check: if(location.x < -joystickRadius || location.x > joystickRadius || location.y < -joystickRadius || location.y > joystickRadius) { return false; } else { float dSq = location.x*location.x + location.y*location.y; if(joystickRadiusSq > dSq) { this->updateVelocity(location); return true; } } return false; } void SneakyJoystick::ccTouchMoved(CCTouch *touch, CCEvent *event) { CCPoint location = touch->getLocation(); location = this->convertToNodeSpace(location); this->updateVelocity(location); } void SneakyJoystick::ccTouchEnded(CCTouch *touch, CCEvent *event) { CCPoint location = CCPointZero; if(!autoCenter){ CCPoint location = touch->getLocation(); location = this->convertToNodeSpace(location); } this->updateVelocity(location); } void SneakyJoystick::ccTouchCancelled(CCTouch *touch, CCEvent *event) { this->ccTouchEnded(touch, event); } #pragma mark private void SneakyJoystick::updateVelocity(CCPoint point) { // Calculate distance and angle from the center. float dx = point.x; float dy = point.y; float dSq = dx * dx + dy * dy; if(dSq <= deadRadiusSq) { velocity = CCPointZero; degrees = 0.0f; stickPosition = point; return; } float angle = atan2f(dy, dx); // in radians if(angle < 0) { angle += SJ_PI_X_2; } if(isDPad) { float anglePerSector = 360.0f / numberOfDirections * SJ_DEG2RAD; angle = roundf(angle / anglePerSector) * anglePerSector; } float cosAngle = cosf(angle); float sinAngle = sinf(angle); // NOTE: Velocity goes from -1.0 to 1.0. if (dSq > joystickRadiusSq || isDPad) { dx = cosAngle * joystickRadius; dy = sinAngle * joystickRadius; } velocity = CCPointMake(dx / joystickRadius, dy / joystickRadius); degrees = angle * SJ_RAD2DEG; // Update the thumb's position stickPosition = ccp(dx, dy); }
3,602
1,419
#pragma comment(lib,"D3D11.lib") #pragma comment(lib,"Dxgi.lib") // CreateSwapChainForHwnd #include "../stereokit.h" #include "d3d.h" namespace sk { /////////////////////////////////////////// ID3D11Device *d3d_device = nullptr; ID3D11DeviceContext *d3d_context = nullptr; ID3D11InfoQueue *d3d_info = nullptr; ID3D11DepthStencilState *d3d_depthstate = nullptr; ID3D11RasterizerState *d3d_rasterstate = nullptr; int d3d_screen_width = 640; int d3d_screen_height = 480; /////////////////////////////////////////// bool d3d_init(LUID *adapter_id) { UINT creation_flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; #ifdef _DEBUG creation_flags |= D3D11_CREATE_DEVICE_DEBUG; #endif // Find the right adapter to use: IDXGIAdapter1 *final_adapter = nullptr; if (adapter_id != nullptr) { IDXGIFactory1 *dxgi_factory; CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void **)(&dxgi_factory)); int curr = 0; IDXGIAdapter1 *curr_adapter = nullptr; while (dxgi_factory->EnumAdapters1(curr++, &curr_adapter) == S_OK) { DXGI_ADAPTER_DESC1 adapterDesc; curr_adapter->GetDesc1(&adapterDesc); if (memcmp(&adapterDesc.AdapterLuid, adapter_id, sizeof(adapter_id)) == 0) { log_diagf("Using graphics adapter: %ws", adapterDesc.Description); final_adapter = curr_adapter; break; } curr_adapter->Release(); } dxgi_factory->Release(); } D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0 }; if (FAILED(D3D11CreateDevice(final_adapter, final_adapter == nullptr ? D3D_DRIVER_TYPE_HARDWARE : D3D_DRIVER_TYPE_UNKNOWN, 0, creation_flags, featureLevels, _countof(featureLevels), D3D11_SDK_VERSION, &d3d_device, nullptr, &d3d_context))) return false; if (final_adapter != nullptr) final_adapter->Release(); // Hook into debug information ID3D11Debug *d3dDebug = nullptr; if (SUCCEEDED(d3d_device->QueryInterface(__uuidof(ID3D11Debug), (void**)&d3dDebug))) { d3d_info = nullptr; if (SUCCEEDED(d3dDebug->QueryInterface(__uuidof(ID3D11InfoQueue), (void**)&d3d_info))) { D3D11_MESSAGE_ID hide[] = { D3D11_MESSAGE_ID_SETPRIVATEDATA_CHANGINGPARAMS, (D3D11_MESSAGE_ID)351, (D3D11_MESSAGE_ID)49, // TODO: Figure out the Flip model for backbuffers! // Add more message IDs here as needed }; D3D11_INFO_QUEUE_FILTER filter = {}; filter.DenyList.NumIDs = _countof(hide); filter.DenyList.pIDList = hide; d3d_info->ClearStorageFilter(); d3d_info->AddStorageFilterEntries(&filter); } d3dDebug->Release(); } D3D11_DEPTH_STENCIL_DESC desc_depthstate = {}; desc_depthstate.DepthEnable = true; desc_depthstate.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; desc_depthstate.DepthFunc = D3D11_COMPARISON_LESS; desc_depthstate.StencilEnable = true; desc_depthstate.StencilReadMask = 0xFF; desc_depthstate.StencilWriteMask = 0xFF; desc_depthstate.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; desc_depthstate.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; desc_depthstate.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; desc_depthstate.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; desc_depthstate.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; desc_depthstate.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; desc_depthstate.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; desc_depthstate.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; d3d_device->CreateDepthStencilState(&desc_depthstate, &d3d_depthstate); d3d_context->OMSetDepthStencilState(d3d_depthstate, 1); D3D11_RASTERIZER_DESC desc_rasterizer = {}; desc_rasterizer.FillMode = D3D11_FILL_SOLID; desc_rasterizer.CullMode = D3D11_CULL_BACK; desc_rasterizer.FrontCounterClockwise = true; d3d_device->CreateRasterizerState(&desc_rasterizer, &d3d_rasterstate); d3d_context->RSSetState(d3d_rasterstate); d3d_context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); return true; } /////////////////////////////////////////// void d3d_shutdown() { if (d3d_context) { d3d_context->Release(); d3d_context = nullptr; } if (d3d_device ) { d3d_device->Release(); d3d_device = nullptr; } } /////////////////////////////////////////// void d3d_update() { #ifdef _DEBUG if (d3d_info == nullptr) return; for(size_t i = 0; i < d3d_info->GetNumStoredMessages(); i++) { SIZE_T size = 0; d3d_info->GetMessage(0, nullptr, &size); D3D11_MESSAGE * pMessage = (D3D11_MESSAGE*)malloc(size); if (SUCCEEDED(d3d_info->GetMessage(i, pMessage, &size)) && pMessage->Severity <= D3D11_MESSAGE_SEVERITY_WARNING) { const char *cat = "None"; switch(pMessage->Category) { case D3D11_MESSAGE_CATEGORY_APPLICATION_DEFINED: cat = "App"; break; case D3D11_MESSAGE_CATEGORY_MISCELLANEOUS: cat = "Misc"; break; case D3D11_MESSAGE_CATEGORY_INITIALIZATION: cat = "Init"; break; case D3D11_MESSAGE_CATEGORY_CLEANUP: cat = "Cleanup"; break; case D3D11_MESSAGE_CATEGORY_COMPILATION: cat = "Compile"; break; case D3D11_MESSAGE_CATEGORY_STATE_CREATION: cat = "State Create"; break; case D3D11_MESSAGE_CATEGORY_STATE_SETTING: cat = "State Set"; break; case D3D11_MESSAGE_CATEGORY_STATE_GETTING: cat = "State Get"; break; case D3D11_MESSAGE_CATEGORY_RESOURCE_MANIPULATION:cat = "Resource"; break; case D3D11_MESSAGE_CATEGORY_EXECUTION: cat = "Exec"; break; case D3D11_MESSAGE_CATEGORY_SHADER: cat = "Shader"; break; } log_ level; switch (pMessage->Severity) { case D3D11_MESSAGE_SEVERITY_MESSAGE: case D3D11_MESSAGE_SEVERITY_INFO: level = log_inform; break; case D3D11_MESSAGE_SEVERITY_WARNING: level = log_warning; break; case D3D11_MESSAGE_SEVERITY_CORRUPTION: case D3D11_MESSAGE_SEVERITY_ERROR: level = log_error; break; default: level = log_inform; } log_writef(level, "%s: [%d] %s", cat, pMessage->ID, pMessage->pDescription); } free(pMessage); } d3d_info->ClearStoredMessages(); #endif } } // namespace sk
6,169
2,708
//! @file //! @copyright See <a href="RichText-LICENSE.txt">RichText-LICENSE.txt</a>. #include "rich_text.hpp" #include <SFML/Graphics.hpp> #include <fmt/format.h> #include <map> namespace { struct format { sf::Font* font = nullptr; sf::Uint32 style_flags = sf::Text::Regular; sf::Color fill_color = sf::Color::White; sf::Color outline_color = sf::Color::White; float outline_thickness = 0; }; struct chunk { format format; sf::String text; }; enum class align { left, center, right }; struct line { std::vector<chunk> chunks; align alignment = align::left; }; std::map<std::string, sf::Font> _fonts; std::map<std::string, sf::Color> _colors = { // {"default", sf::Color::White}, {"black", sf::Color::Black}, {"blue", sf::Color::Blue}, {"cyan", sf::Color::Cyan}, {"green", sf::Color::Green}, {"magenta", sf::Color::Magenta}, {"red", sf::Color::Red}, {"white", sf::Color::White}, {"yellow", sf::Color::Yellow}}; auto color_from_hex(unsigned argb_hex) -> sf::Color { argb_hex |= 0xff000000; return sf::Color(argb_hex >> 16 & 0xff, argb_hex >> 8 & 0xff, argb_hex >> 0 & 0xff, argb_hex >> 24 & 0xff); } auto color_from_string(std::string const& source) -> sf::Color { auto result = _colors.find(source); if (result != _colors.end()) { return result->second; } try { return color_from_hex(std::stoi(source, 0, 16)); } catch (...) { // Conversion failed; use default color. return sf::Color::White; } } } namespace sfe { auto rich_text::add_color(sf::String const& name, sf::Color const& color) -> void { _colors[name] = color; } auto rich_text::add_color(sf::String const& name, unsigned argb_hex) -> void { _colors[name] = color_from_hex(argb_hex); } rich_text::rich_text(sf::String const& source, unsigned character_size) : _character_size(character_size) { set_source(source); } auto rich_text::get_source() const -> sf::String { return _source; } auto rich_text::set_source(sf::String const& source) -> void { _source = source; clear(); format current_format; std::vector<line> lines{line{{chunk{current_format}}}}; for (auto it = source.begin(); it != source.end(); ++it) { static auto apply_formatting = [&] { if (!lines.back().chunks.back().text.isEmpty()) { // Start a new chunk if the current chunk has text. lines.back().chunks.push_back(chunk{current_format}); } else { // Otherwise, update current chunk. lines.back().chunks.back().format = current_format; } }; switch (*it) { case '/': // Italic current_format.style_flags ^= sf::Text::Italic; apply_formatting(); break; case '*': // Bold current_format.style_flags ^= sf::Text::Bold; apply_formatting(); break; case '_': // Underline current_format.style_flags ^= sf::Text::Underlined; apply_formatting(); break; case '~': // Strikethrough current_format.style_flags ^= sf::Text::StrikeThrough; apply_formatting(); break; case '[': { // Tag ++it; // Find the end of the tag and advance the iterator. auto const tag_end = std::find(it, source.end(), sf::Uint32{']'}); if (tag_end == source.end()) { throw std::domain_error{"Missing ']' in tag."}; } // Split into command and argument. auto const command_end = std::find(it, tag_end, sf::Uint32{' '}); auto const command = sf::String::fromUtf32(it, command_end); auto const arg = sf::String::fromUtf32(command_end + 1, tag_end).toAnsiString(); // Handle the tag. if (command == "fill-color") { current_format.fill_color = color_from_string(arg); apply_formatting(); } else if (command == "outline-color") { current_format.outline_color = color_from_string(arg); apply_formatting(); } else if (command == "outline-thickness") { current_format.outline_thickness = std::stof(arg); apply_formatting(); } else if (command == "font") { // First = (font name, font) pair; second = whether insertion occurred. auto result = _fonts.try_emplace(arg); if (result.second) { // Cache miss. Need to load font. if (!result.first->second.loadFromFile(arg)) { throw std::runtime_error{fmt::format("Could not load font from \"{}\".", arg)}; } } current_format.font = &result.first->second; apply_formatting(); } else if (command == "align") { if (arg == "left") { lines.back().alignment = align::left; } else if (arg == "center") { lines.back().alignment = align::center; } else if (arg == "right") { lines.back().alignment = align::right; } else { throw std::domain_error{fmt::format("Invalid alignment: {}.", arg)}; } } // Advance the iterator to the end of the tag (it will be incremented past at the end by the // loop). it = tag_end; break; } case '\\': // Escape sequence ++it; if (it == source.end()) { throw std::domain_error{"Expected formatting control character after '\\'."}; } switch (*it) { case '/': case '*': case '_': case '~': case '[': case '\\': lines.back().chunks.back().text += *it; break; default: throw std::domain_error{ fmt::format("Cannot escape non-control character '{}'.", static_cast<char>(*it))}; } break; case '\n': // New line lines.push_back(line{{chunk{current_format}}}); break; default: lines.back().chunks.back().text += *it; break; } } // Build texts and formatting-stripped string and compute bounds. sf::Vector2f next_position{}; _bounds = {0, 0, 0, 0}; for (auto const& line : lines) { float line_spacing = 0; for (auto const& chunk : line.chunks) { // Construct text. if (chunk.format.font == nullptr) { throw std::domain_error{"Text missing font specification."}; } line_spacing = std::max(line_spacing, chunk.format.font->getLineSpacing(_character_size)); _texts.push_back({chunk.text, *chunk.format.font, _character_size}); _texts.back().setStyle(chunk.format.style_flags); _texts.back().setFillColor(chunk.format.fill_color); _texts.back().setOutlineColor(chunk.format.outline_color); _texts.back().setOutlineThickness(chunk.format.outline_thickness); // Round next_position to avoid text blurriness. _texts.back().setPosition(std::roundf(next_position.x), std::roundf(next_position.y)); // Move next position to the end of the text. next_position = _texts.back().findCharacterPos(chunk.text.getSize()); // Extend bounds. auto const text_bounds = _texts.back().getGlobalBounds(); auto const right = text_bounds.left + text_bounds.width; _bounds.width = std::max(_bounds.width, right - _bounds.left); auto const bottom = text_bounds.top + text_bounds.height; _bounds.height = std::max(_bounds.height, bottom - _bounds.top); } //! @todo Align line. if (&line != &lines.back()) { // Handle new lines. next_position = {0, next_position.y + line_spacing}; } } } auto rich_text::clear() -> void { _texts.clear(); _bounds = sf::FloatRect{}; } auto rich_text::get_character_size() const -> unsigned { return _character_size; } auto rich_text::set_character_size(unsigned size) -> void { _character_size = std::max(size, 1u); set_source(_source); } auto rich_text::get_local_bounds() const -> sf::FloatRect { return _bounds; } auto rich_text::get_global_bounds() const -> sf::FloatRect { return getTransform().transformRect(_bounds); } auto rich_text::draw(sf::RenderTarget& target, sf::RenderStates states) const -> void { states.transform *= getTransform(); for (auto const& text : _texts) { target.draw(text, states); } } }
7,849
3,234
// Copyright 2017 Kyle Mayes // // 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. template <class T, class I, class F> class FilterMap : public Iterator<T, FilterMap<T, I, F>> { I source; F f; template <class S> Option<T> impl(S&& source) { for (auto item : source) { auto option = std::invoke(f, item); if (option.is_some()) { return option; } } return {}; } protected: Bounds bounds_impl() const { return {0, source.bounds().upper}; } Option<T> next_impl() { return impl(source); } Option<T> next_back_impl() { return impl(source.as_ref().reverse()); } public: FilterMap(I source, F f) : source{std::move(source)}, f{std::move(f)} { } };
1,299
403
// Generated by Haxe 4.1.5 namespace hx { unsigned char __res_17[] = { 0x80, 0x00, 0x00, 0x80, 137,80,78,71,13,10,26,10,0,0, 0,13,73,72,68,82,0,0,0,11, 0,0,0,11,8,6,0,0,0,169, 172,119,38,0,0,0,25,116,69,88, 116,83,111,102,116,119,97,114,101,0, 65,100,111,98,101,32,73,109,97,103, 101,82,101,97,100,121,113,201,101,60, 0,0,0,84,73,68,65,84,120,218, 148,144,81,14,192,32,8,67,11,183, 220,5,185,102,183,37,83,153,86,221, 94,2,33,164,188,15,140,36,190,226, 105,142,171,184,168,176,100,190,7,91, 136,233,201,136,153,177,197,71,14,177, 67,109,93,16,226,96,8,151,32,196, 129,52,199,179,11,101,118,252,65,88, 102,188,254,188,229,20,96,0,3,5, 232,22,166,15,127,92,0,0,0,0, 73,69,78,68,174,66,96,130,0x00 }; }
700
658
// Copyright (c) FRC Team 3512. All Rights Reserved. #pragma once #include <rev/CANSparkMax.h> namespace frc3512 { enum class Usage { kAll, kPositionOnly, kVelocityOnly, kMinimal }; /** * This function allows reducing a Spark Max's CAN bus utilization by reducing * the periodic status frame period of nonessential frames from 20ms to 500ms. * * See * https://docs.revrobotics.com/sparkmax/operating-modes/control-interfaces#periodic-status-frames * for a description of the status frames. * * @param motor The motor to adjust the status frame periods on. * @param usage The status frame feedack to enable. kAll is the default * when a CANSparkMax is constructed. * @param enableFollowing Whether to enable motor following. */ void SetCANSparkMaxBusUsage(rev::CANSparkMax& motor, Usage usage, bool enableFollowing = false); } // namespace frc3512
907
281
#include <precompiled.h> /// /// MIT License /// Copyright (c) 2018-2019 Jongmin Yun /// /// 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. /// /// Header file #include <Dy/Meta/Descriptor/WidgetTextMetaInformation.h> #include <nlohmann/json.hpp> #include <Dy/Helper/Library/HelperJson.h> #include <Dy/Helper/Type/DColorRGB24.h> namespace dy { std::unique_ptr<PDyMetaWidgetTextDescriptor> PDyMetaWidgetTextDescriptor::CreateMetaInformation(_MIN_ const nlohmann::json& itemAtlas) { /* Template { { "Name": "WidgetName", "Type": "Text", "Parent": "", "ZOrder": 0, "Details": { "InitialPosition": { "X": 0, "Y": 0 }, "WidgetSize": { "X": 200, "Y": 100 }, "Origin": "Center_Center", "InitialString": "This is test for general UI.", "InitialColor": { "R": 1.0, "G": 1.0, "B": 1.0, "A": 1.0 }, "EdgeColor": { "R": 1.0, "G": 1.0, "B": 1.0 }, "FontSize": 10, "FontSpecifierName": "Arial", "IsUsingEdge": false, "Alignment": "Left" } } } */ static MDY_SET_IMMUTABLE_STRING(sHeader_InitialString, "InitialString"); static MDY_SET_IMMUTABLE_STRING(sHeader_InitialPosition, "InitialPosition"); static MDY_SET_IMMUTABLE_STRING(sHeader_InitialColor, "InitialColor"); static MDY_SET_IMMUTABLE_STRING(sHeader_FontSize, "FontSize"); static MDY_SET_IMMUTABLE_STRING(sHeader_FontSpecifierName, "FontSpecifierName"); static MDY_SET_IMMUTABLE_STRING(sHeader_IsUsingEdge, "IsUsingEdge"); using TPDyMWCBD = PDyMetaWidgetCommonBaseDesc; //! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //! FUNCTIONBODY โˆจ //! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Common auto instance = std::make_unique<PDyMetaWidgetTextDescriptor>(); instance->mUiObjectSpecifierName = json::GetValueFrom<std::string>(itemAtlas, TPDyMWCBD::sHeader_Name); instance->mComponentType = EDyWidgetComponentType::Text; instance->mParentSpecifierName = json::GetValueFrom<std::string>(itemAtlas, TPDyMWCBD::sHeader_Parent); json::GetValueFromTo(itemAtlas, "IsActivated", instance->mIsActivated); json::GetValueFromTo(itemAtlas, "ZOrder", instance->mZOrder); // Detail (TEXT) const auto& detailAtlas = itemAtlas[(TPDyMWCBD::sHeader_Details)]; const auto string = json::GetValueFrom<std::string>(detailAtlas, sHeader_InitialString); instance->mTextString = string; instance->mTextColor = json::GetValueFrom<DColorRGBA>(detailAtlas, sHeader_InitialColor);; instance->mFontSize = json::GetValueFrom<TU32>(detailAtlas, sHeader_FontSize); instance->mFontName = json::GetValueFrom<std::string>(detailAtlas, sHeader_FontSpecifierName); instance->mEdgeColor = json::GetValueFrom<DColorRGB>(detailAtlas, "EdgeColor"); instance->mIsUsingEdge = json::GetValueFrom<bool>(detailAtlas, sHeader_IsUsingEdge); instance->mInitialPosition = DIVec2{json::GetValueFrom<DVec2>(detailAtlas, sHeader_InitialPosition)}; instance->mOrigin = json::GetValueFrom<EDyOrigin>(detailAtlas, "Origin"); instance->mWidgetSize = json::GetValueFrom<DIVec2>(detailAtlas, "WidgetSize"); json::GetValueFromTo(detailAtlas, "Alignment", instance->mAlignment); return instance; } } /// ::dy namespace
3,779
1,361
#include "InterpolationTestsF16.h" #include <stdio.h> #include "Error.h" #define SNR_THRESHOLD 55 /* Reference patterns are generated with a double precision computation. */ #define REL_ERROR (5.0e-3) #define ABS_ERROR (5.0e-3) void InterpolationTestsF16::test_linear_interp_f16() { const float16_t *inp = input.ptr(); float16_t *outp = output.ptr(); unsigned long nb; for(nb = 0; nb < input.nbSamples(); nb++) { outp[nb] = arm_linear_interp_f16(&S,inp[nb]); } ASSERT_EMPTY_TAIL(output); ASSERT_SNR(output,ref,(float16_t)SNR_THRESHOLD); ASSERT_CLOSE_ERROR(output,ref,ABS_ERROR,REL_ERROR); } void InterpolationTestsF16::test_bilinear_interp_f16() { const float16_t *inp = input.ptr(); float16_t *outp = output.ptr(); float16_t x,y; unsigned long nb; for(nb = 0; nb < input.nbSamples(); nb += 2) { x = inp[nb]; y = inp[nb+1]; *outp++=arm_bilinear_interp_f16(&SBI,x,y); } ASSERT_EMPTY_TAIL(output); ASSERT_SNR(output,ref,(float16_t)SNR_THRESHOLD); ASSERT_CLOSE_ERROR(output,ref,ABS_ERROR,REL_ERROR); } #if 0 void InterpolationTestsF16::test_spline_square_f16() { const float16_t *inpX = inputX.ptr(); const float16_t *inpY = inputY.ptr(); const float16_t *outX = outputX.ptr(); float16_t *outp = output.ptr(); float16_t *buf = buffer.ptr(); // ((2*4-1)*sizeof(float16_t)) float16_t *coef = splineCoefs.ptr(); // ((3*(4-1))*sizeof(float16_t)) arm_spline_instance_f16 S; arm_spline_init_f16(&S, ARM_SPLINE_PARABOLIC_RUNOUT, inpX, inpY, 4, coef, buf); arm_spline_f16(&S, outX, outp, 20); ASSERT_EMPTY_TAIL(buffer); ASSERT_EMPTY_TAIL(splineCoefs); ASSERT_EMPTY_TAIL(output); ASSERT_SNR(output,ref,(float16_t)SNR_THRESHOLD); } void InterpolationTestsF16::test_spline_sine_f16() { const float16_t *inpX = inputX.ptr(); const float16_t *inpY = inputY.ptr(); const float16_t *outX = outputX.ptr(); float16_t *outp = output.ptr(); float16_t *buf = buffer.ptr(); // ((2*9-1)*sizeof(float16_t)) float16_t *coef = splineCoefs.ptr(); // ((3*(9-1))*sizeof(float16_t)) arm_spline_instance_f16 S; arm_spline_init_f16(&S, ARM_SPLINE_NATURAL, inpX, inpY, 9, coef, buf); arm_spline_f16(&S, outX, outp, 33); ASSERT_EMPTY_TAIL(buffer); ASSERT_EMPTY_TAIL(splineCoefs); ASSERT_EMPTY_TAIL(output); ASSERT_SNR(output,ref,(float16_t)SNR_THRESHOLD); } void InterpolationTestsF16::test_spline_ramp_f16() { const float16_t *inpX = inputX.ptr(); const float16_t *inpY = inputY.ptr(); const float16_t *outX = outputX.ptr(); float16_t *outp = output.ptr(); float16_t *buf = buffer.ptr(); // ((2*3-1)*sizeof(float16_t)) float16_t *coef = splineCoefs.ptr(); // ((3*(3-1))*sizeof(float16_t)) arm_spline_instance_f16 S; arm_spline_init_f16(&S, ARM_SPLINE_PARABOLIC_RUNOUT, inpX, inpY, 3, coef, buf); arm_spline_f16(&S, outX, outp, 30); ASSERT_EMPTY_TAIL(buffer); ASSERT_EMPTY_TAIL(splineCoefs); ASSERT_EMPTY_TAIL(output); ASSERT_SNR(output,ref,(float16_t)SNR_THRESHOLD); } #endif void InterpolationTestsF16::setUp(Testing::testID_t id,std::vector<Testing::param_t>& params,Client::PatternMgr *mgr) { const int16_t *pConfig; Testing::nbSamples_t nb=MAX_NB_SAMPLES; (void)params; switch(id) { case InterpolationTestsF16::TEST_LINEAR_INTERP_F16_1: input.reload(InterpolationTestsF16::INPUT_F16_ID,mgr,nb); y.reload(InterpolationTestsF16::YVAL_F16_ID,mgr,nb); ref.reload(InterpolationTestsF16::REF_LINEAR_F16_ID,mgr,nb); S.nValues=y.nbSamples(); /**< nValues */ /* Those values must be coherent with the ones in the Python script generating the patterns */ S.x1=0.0; /**< x1 */ S.xSpacing=1.0; /**< xSpacing */ S.pYData=y.ptr(); /**< pointer to the table of Y values */ break; case InterpolationTestsF16::TEST_BILINEAR_INTERP_F16_2: input.reload(InterpolationTestsF16::INPUTBI_F16_ID,mgr,nb); config.reload(InterpolationTestsF16::CONFIGBI_S16_ID,mgr,nb); y.reload(InterpolationTestsF16::YVALBI_F16_ID,mgr,nb); ref.reload(InterpolationTestsF16::REF_BILINEAR_F16_ID,mgr,nb); pConfig = config.ptr(); SBI.numRows = pConfig[1]; SBI.numCols = pConfig[0]; SBI.pData = y.ptr(); break; #if 0 case TEST_SPLINE_SQUARE_F16_3: inputX.reload(InterpolationTestsF16::INPUT_SPLINE_SQU_X_F16_ID,mgr,4); inputY.reload(InterpolationTestsF16::INPUT_SPLINE_SQU_Y_F16_ID,mgr,4); outputX.reload(InterpolationTestsF16::OUTPUT_SPLINE_SQU_X_F16_ID,mgr,20); ref.reload(InterpolationTestsF16::REF_SPLINE_SQU_F16_ID,mgr,20); splineCoefs.create(3*(4-1),InterpolationTestsF16::COEFS_SPLINE_F16_ID,mgr); buffer.create(2*4-1,InterpolationTestsF16::TEMP_SPLINE_F16_ID,mgr); output.create(20,InterpolationTestsF16::OUT_SAMPLES_F16_ID,mgr); break; case TEST_SPLINE_SINE_F16_4: inputX.reload(InterpolationTestsF16::INPUT_SPLINE_SIN_X_F16_ID,mgr,9); inputY.reload(InterpolationTestsF16::INPUT_SPLINE_SIN_Y_F16_ID,mgr,9); outputX.reload(InterpolationTestsF16::OUTPUT_SPLINE_SIN_X_F16_ID,mgr,33); ref.reload(InterpolationTestsF16::REF_SPLINE_SIN_F16_ID,mgr,33); splineCoefs.create(3*(9-1),InterpolationTestsF16::COEFS_SPLINE_F16_ID,mgr); buffer.create(2*9-1,InterpolationTestsF16::TEMP_SPLINE_F16_ID,mgr); output.create(33,InterpolationTestsF16::OUT_SAMPLES_F16_ID,mgr); break; case TEST_SPLINE_RAMP_F16_5: inputX.reload(InterpolationTestsF16::INPUT_SPLINE_RAM_X_F16_ID,mgr,3); inputY.reload(InterpolationTestsF16::INPUT_SPLINE_RAM_Y_F16_ID,mgr,3); outputX.reload(InterpolationTestsF16::OUTPUT_SPLINE_RAM_X_F16_ID,mgr,30); ref.reload(InterpolationTestsF16::REF_SPLINE_RAM_F16_ID,mgr,30); splineCoefs.create(3*(3-1),InterpolationTestsF16::COEFS_SPLINE_F16_ID,mgr); buffer.create(2*3-1,InterpolationTestsF16::TEMP_SPLINE_F16_ID,mgr); output.create(30,InterpolationTestsF16::OUT_SAMPLES_F16_ID,mgr); break; #endif } output.create(ref.nbSamples(),InterpolationTestsF16::OUT_SAMPLES_F16_ID,mgr); } void InterpolationTestsF16::tearDown(Testing::testID_t id,Client::PatternMgr *mgr) { (void)id; output.dump(mgr); }
7,052
2,982
#include "oaLoaderUtils.h" #include <math.h> #include <codecvt> #include <locale> #include "oaJoint.h" #include "rapidxml\rapidxml.hpp" #include "rapidxml\rapidxml_iterators.hpp" #include "rapidxml\rapidxml_print.hpp" #include "rapidxml\rapidxml_utils.hpp" #include "oaAnimationLoader.h" std::unordered_map<std::string, std::vector<oaAnimation>> oaAnimationLoader::animationIDs = std::unordered_map<std::string, std::vector<oaAnimation>>(); std::vector<oaAnimation>* oaAnimationLoader::loadAnimation(const char * filePath) { if (animationIDs.find(filePath) != animationIDs.end()) { return &animationIDs.at(filePath); } std::string fileExt = oaGetFileExtension(filePath); std::vector<oaAnimation>* animation; // OBJ parser if (fileExt == "dae") { animation = loadDAE( filePath ); // Format not supported } else { printf("File extension no supported: '%s'", fileExt.c_str()); return NULL; } // Format supported, file unsopported if (animation == NULL || animation->empty()) { printf("Unable to load '%s'\n", filePath); return NULL; } // All right, add to the list of meshes animationIDs.insert({ std::string(filePath), *animation }); printf("Animation loaded : %s\n", filePath); return &animationIDs.find(filePath)->second; } std::vector<oaAnimation>* oaAnimationLoader::loadDAE(const char * filePath) { using namespace rapidxml; std::vector<oaAnimation>* animations = new std::vector<oaAnimation>(); xml_document<wchar_t> doc; // Open file file<wchar_t> fileXml(filePath); doc.parse<0>(fileXml.data()); // 0 means default parse flags xml_node<wchar_t> *collada = doc.first_node(L"COLLADA"); xml_node<wchar_t> *up_axis = collada->first_node(L"asset")->first_node(L"up_axis"); // Get the model orientation, OpenGl is Y-Up oriented glm::mat4 orientation = glm::mat4(); if (up_axis) { if (wcscmp(up_axis->value(), L"Z_UP") == 0) { orientation = { 1, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1 }; } //else if (wcscmp(up_axis->value(), L"Y_UP") == 0) { // orientation = { 1, 0, 0, // 0, 1, 0, // 0, 0, 1, }; //} else if (wcscmp(up_axis->value(), L"X_UP") == 0) { orientation = { 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; } } xml_node<wchar_t> *library_animations = collada->first_node(L"library_animations"); xml_node<wchar_t> *animation = library_animations->first_node(L"animation"); while (animation) { xml_node<wchar_t> *source = animation->first_node(L"source"); oaAnimation currentAnimation; while (source) { if (auto technique_common = source->first_node(L"technique_common")) { if (auto accessor = technique_common->first_node(L"accessor")) { wchar_t* type = accessor->first_node(L"param")->first_attribute(L"name")->value(); if (wcscmp(L"TIME", type) == 0) { int keys = _wtoi(accessor->first_attribute(L"count")->value()); currentAnimation.size = keys; currentAnimation.keyTimes = new float[keys]; xml_node<wchar_t> *farray = source->first_node(L"float_array"); std::wistringstream iss(farray->value()); std::wstring s; for (int i = 0; i < keys; i++) { s.clear(); iss >> s; currentAnimation.keyTimes[i] = (float)_wtof(s.c_str()); } } if (wcscmp(L"TRANSFORM", type) == 0) { int keys = _wtoi(accessor->first_attribute(L"count")->value()); currentAnimation.transforms = new oaAnimation::JointTransforms[keys]; xml_node<wchar_t> *farray = source->first_node(L"float_array"); std::wistringstream iss(farray->value()); std::wstring s; for (int i = 0; i < keys; i++) { glm::mat4 transform; for (int j = 0; j < 4; j++) { s.clear(); iss >> s; transform[j][0] = (float)_wtof(s.c_str()); s.clear(); iss >> s; transform[j][1] = (float)_wtof(s.c_str()); s.clear(); iss >> s; transform[j][2] = (float)_wtof(s.c_str()); s.clear(); iss >> s; transform[j][3] = (float)_wtof(s.c_str()); } currentAnimation.transforms[i] = oaAnimation::JointTransforms(transform); } } } } source = source->next_sibling(L"source"); } if (auto channel = animation->first_node(L"channel")) { if (auto target = channel->first_attribute(L"target")) { currentAnimation.name = target->value(); } } animations->push_back(currentAnimation); animation = animation->next_sibling(L"animation"); } if (!animations || animations->empty()) { delete animations; return NULL; } return animations; }
4,737
2,043
/* PLIB - A Suite of Portable Game Libraries Copyright (C) 1998,2002 Steve Baker This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA For further information visit http://plib.sourceforge.net $Id: netBuffer.cxx 1568 2002-09-02 06:05:49Z sjbaker $ */ #include <ossimPlanet/netBuffer.h> void netBufferChannel::handleRead (void) { int max_read = in_buffer.getMaxLength() - in_buffer.getLength() ; if (max_read) { char* data = in_buffer.getData() + in_buffer.getLength() ; int num_read = recv (data, max_read) ; if (num_read > 0) { in_buffer.append (num_read) ; //ulSetError ( UL_DEBUG, "netBufferChannel: %d read", num_read ) ; } } if (in_buffer.getLength()) { handleBufferRead (in_buffer); } } void netBufferChannel::handleWrite (void) { if (out_buffer.getLength()) { if (isConnected()) { int length = out_buffer.getLength() ; if (length>512) length=512; int num_sent = netChannel::send ( out_buffer.getData(), length); if (num_sent > 0) { out_buffer.remove (0, num_sent); //ulSetError ( UL_DEBUG, "netBufferChannel: %d sent", num_sent ) ; } } } else if (should_close) { close(); } }
1,960
678
/* Copyright (c) 2017 Griefer@Work * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * */ #ifndef GUARD_DCC_UNIT_IMPORT_SOURCE_C_INL #define GUARD_DCC_UNIT_IMPORT_SOURCE_C_INL 1 #define DCC(x) x #include <dcc/common.h> #include <dcc/target.h> #include <dcc/compiler.h> #include <dcc/lexer.h> #include <dcc/assembler.h> #include <dcc/addr2line.h> #include "unit-import.h" DCC_DECL_BEGIN PRIVATE void load_std_sections(void) { unit.u_text = DCCUnit_NewSecs(".text",DCC_SYMFLAG_SEC_X|DCC_SYMFLAG_SEC_R); unit.u_data = DCCUnit_NewSecs(".data",DCC_SYMFLAG_SEC_R); unit.u_bss = DCCUnit_NewSecs(".bss",DCC_SYMFLAG_SEC_R|DCC_SYMFLAG_SEC_W); unit.u_string = DCCUnit_NewSecs(".string",DCC_SYMFLAG_SEC_R|DCC_SYMFLAG_SEC_M); /* NOTE: Symbols within '.dbgstr' cannot be merged! */ unit.u_dbgstr = DCCUnit_NewSecs(A2L_STRING_SECTION,DCC_SYMFLAG_SEC_R); } INTERN void DCCUNIT_IMPORTCALL DCCUnit_LoadSrc_C(struct DCCLibDef *__restrict def) { (void)def; compiler.c_flags |= (DCC_COMPILER_FLAG_NOCGEN); /*CURRENT.l_flags |= (TPPLEXER_FLAG_TERMINATE_STRING_LF);*/ /* Load standard sections. */ load_std_sections(); CURRENT.l_extokens &= (TPPLEXER_TOKEN_EQUALBINOP); CURRENT.l_extokens |= (TPPLEXER_TOKEN_LANG_C| TPPLEXER_TOKEN_TILDETILDE); /* Yield the initial token. */ TPPLexer_Yield(); /* Select the text section and begin compiling. */ DCCUnit_SetCurr(unit.u_text); DCCParse_AllGlobal(); DCCUnit_SetCurr(NULL); } INTERN void DCCUNIT_IMPORTCALL DCCUnit_LoadSrc_ASM(struct DCCLibDef *__restrict def) { (void)def; CURRENT.l_flags |= (TPPLEXER_FLAG_ASM_COMMENTS| /*TPPLEXER_FLAG_TERMINATE_STRING_LF|*/ TPPLEXER_FLAG_COMMENT_NOOWN_LF| TPPLEXER_FLAG_WANTLF); CURRENT.l_extokens = TPPLEXER_TOKEN_LANG_ASM; compiler.c_flags |= DCC_COMPILER_FLAG_INASM; load_std_sections(); /* Yield the initial token. */ TPPLexer_Yield(); /* Select the text section and begin compiling. */ DCCUnit_SetCurr(unit.u_text); while (TOK > 0) { unsigned long old_num = TOKEN.t_num; DCCParse_AsmInstr(); if (old_num == TOKEN.t_num) YIELD(); } DCCUnit_SetCurr(NULL); } DCC_DECL_END #endif /* !GUARD_DCC_UNIT_IMPORT_SOURCE_C_INL */
3,504
1,271
#include <nexus/fuzz_test.hh> #include <babel-serializer/compression/zstd.hh> FUZZ_TEST("zstd fuzzer")(tg::rng& rng) { auto cnt = uniform(rng, 0, 10); if (uniform(rng)) cnt = uniform(rng, 100, 1000); auto orig_data = cc::vector<std::byte>(cnt); for (auto& d : orig_data) d = uniform(rng); auto comp_data = babel::zstd::compress(orig_data); auto uncomp_data = babel::zstd::uncompress(comp_data); CHECK(orig_data == uncomp_data); }
480
207
#include "MessageBus.hpp" MessageBus g_bus; const string Topic = "Drive"; const string CallBackTopic = "DriveOK"; struct Subject { Subject() { g_bus.Attach([this]{DriveOK();},CallBackTopic); } void SendReq(const string& topic) { g_bus.SendReq<void, int>(50, topic); } void DriveOK() { cout<<"drive OK"<<endl; } }; struct Car { Car() { g_bus.Attach([this](int speed){Drive(speed);}, Topic); } void Drive(int speed) { cout<<"car drives "<<speed<<endl; g_bus.SendReq<void>(CallBackTopic); } }; struct Bus { Bus() { g_bus.Attach([this](int speed){Drive(speed);}); } void Drive(int speed) { cout<<"Bus drives "<<speed<<endl; g_bus.SendReq<void>(CallBackTopic); } }; struct Truck { Truck() { g_bus.Attach([this](int speed){Drive(speed);}); } void Drive(int speed) { cout<<"Truck drives "<<speed<<endl; g_bus.SendReq<void>(CallBackTopic); } }; void TestBus() { Subject subject; Car car; Bus bus; Truck truck; //subject.SendReq(Topic); for (int i = 0; i < 10000; i++) { subject.SendReq(""); } } int main() { TestBus(); return 0; }
1,271
497
#include "MessageCallbackMgr.h" CMessageCallbackMgr::CMessageCallbackMgr():m_nppMessageConstructor(NULL), m_sessionEventHandler(NULL) {} CMessageCallbackMgr::~CMessageCallbackMgr(){} int CMessageCallbackMgr::registerMessageCallback(int messageCode, DoMessageExecute onMessageFunc) { ACE_Guard<ACE_Mutex> guard(m_iMutex); m_mapDoExecuteFunc[messageCode] = onMessageFunc; return NPP_NOERROR; } DoMessageExecute CMessageCallbackMgr::getMessageCallbackByCode( int messageCode ) { ACE_Guard<ACE_Mutex> guard(m_iMutex); return m_mapDoExecuteFunc[messageCode]; } void CMessageCallbackMgr::setMessageConstructor( nppMessageConstructor defaultCreateMessage ) { m_nppMessageConstructor = defaultCreateMessage; } nppMessageConstructor CMessageCallbackMgr::getMessageConstructor() { return m_nppMessageConstructor; } void CMessageCallbackMgr::FireIoEventHandler( int sessionId, ENUM_IO_EVENT event ) { //throw std::exception("The method or operation is not implemented."); //we should give another thread to fire this kind of event return ; } void CMessageCallbackMgr::setIoEventHandler( IoEventHandler sessionEventHandler ) { m_sessionEventHandler = sessionEventHandler; } IoEventHandler CMessageCallbackMgr::getIoEventHandler() { return m_sessionEventHandler; }
1,361
419
#include "Game.hpp" #include <algorithm> #include "Utils.hpp" #include "SimpleEntity.hpp" #include "RenderUtils.hpp" #include "Math.hpp" #include "config.hpp" using namespace SpaceThing; using namespace Utils; void Game::initSession(irr::IrrlichtDevice* device) { session.device = device; session.driver = device->getVideoDriver(); session.smg = device->getSceneManager(); session.gui = device->getGUIEnvironment(); session.gc = session.smg->getGeometryCreator(); } void Game::nullSession() { session.device = nullptr; session.driver = nullptr; session.smg = nullptr; session.gui = nullptr; session.gc = nullptr; } static irr::f32 cameraPitch = Pi<irr::f32>; static irr::f32 cameraYaw = HalfPi<irr::f32>; static irr::f32 cameraRadius = 20; static irr::scene::ICameraSceneNode* camera = nullptr; void Game::acceptInput(const EventReceiver& receiver) { if (receiver.isDown(irr::KEY_KEY_Q)) running = false; irr::f32 dp = 0, dy = 0; static const irr::f32 d = Pi<irr::f32> / 32; static const irr::f32 r = 0.5; if (receiver.isDown(irr::KEY_KEY_A)) dy = -d; else if (receiver.isDown(irr::KEY_KEY_D)) dy = +d; if (receiver.isDown(irr::KEY_KEY_W)) dp = +d; else if (receiver.isDown(irr::KEY_KEY_S)) dp = -d; if (receiver.isDown(irr::KEY_KEY_R)) cameraRadius -= r; else if (receiver.isDown(irr::KEY_KEY_F)) cameraRadius += r; cameraRadius = std::clamp(cameraRadius, irr::f32(0.05), irr::f32(25)); cameraPitch += dp; cameraPitch = std::clamp(cameraPitch, -HalfPi<irr::f32>, HalfPi<irr::f32>); cameraYaw += dy; if (cameraYaw < 0) cameraYaw = Pi2<irr::f32>; else if (cameraYaw > Pi2<irr::f32>) cameraYaw = 0; const irr::core::vector3df origin(2.5, 2.5, 2.5); camera->setPosition(origin + irr::core::vector3df(std::cos(cameraYaw), std::sin(cameraPitch), std::sin(cameraYaw)) * cameraRadius); camera->setTarget(origin); } int Game::run() { EventReceiver receiver; IrrPtr<irr::IrrlichtDevice> device(irr::createDevice(VIDEO_DRIVER, {800, 600}, 32, false, false, false, &receiver)); initSession(device.get()); device->setWindowCaption(L"Space Thing"); camera = session.smg->addCameraSceneNode(); session.gui->addStaticText(L"Q to quit", {0, 0, 100, 10}) ->setOverrideColor({255, 255, 255, 255}); session.smg->addLightSceneNode(nullptr, {12.5, 10, 12.5}); world.add(new SimpleEntity(box({5, 5, 5}, {255, 255, 255, 255}))); while (running && device->run()) { session.driver->beginScene(true, true, {255, 8, 8, 10}); acceptInput(receiver); world.update(); session.smg->drawAll(); session.gui->drawAll(); session.driver->endScene(); } return 0; }
3,206
1,164
#include<bits/stdc++.h> using namespace std; int main(){ int n, sum; cin>>n>>sum; int coin[n]; for(int i = 0;i < n;i++) cin>>coin[i]; int t[n+1][sum+1]; for(int i = 0;i < sum+1;i++) t[0][i] = 0; for(int i = 0;i < n + 1;i++) t[i][0] = 1; for(int i = 1;i < n+1;i++) for(int j = 1;j < sum + 1;j++) if(coin[i-1] <= j) t[i][j] = t[i][j-coin[i-1]] + t[i-1][j]; else t[i][j] = t[i-1][j]; cout <<t[n][sum]; }
525
257
#include <QDebug> #include <QFile> #include <vector> #include <QRegExp> #include <math.h> #include "Coordinates.h" #include "Geohash.h" #include "Commons.h" #include "SensorController.h" std::vector<geopoint_t> CoordGetFromFile(const QString& filePath, int interested) { std::vector<geopoint_t> lstResult; QFile f(filePath); SensorData_t sd; if (!f.open(QFile::ReadOnly)) { qDebug() << "Open file " << filePath << " error : " << f.errorString(); return lstResult; } while (!f.atEnd()) { QString line = f.readLine(); int pi = SensorControllerParseDataString(line.toStdString().c_str(), &sd); if (pi != interested) continue; lstResult.push_back(geopoint_t(sd.gpsLat, sd.gpsLon)); } f.close(); return lstResult; } ////////////////////////////////////////////////////////////////////////// std::vector<geopoint_t> CoordFilterByGeoHash(std::vector<geopoint_t> &lstSrc, int precision, int minPointCount) { #define NOT_VALID_POINT_INDEX -1 struct AuxItem { double lon; double lat; int32_t index; int32_t count; }; std::vector<geopoint_t> lstRes; std::map<uint64_t, AuxItem> dctHashCount; typedef std::map<uint64_t, AuxItem>::iterator dctIter; int idx = 0; for (auto ci = lstSrc.begin(); ci != lstSrc.end(); ++ci) { uint64_t gh = GeohashEncodeU64(ci->Latitude, ci->Longitude, precision); dctIter it = dctHashCount.find(gh); if (it == dctHashCount.end()) { AuxItem ni; ni.count = 0; ni.lat = ni.lon = 0.0; ni.index = NOT_VALID_POINT_INDEX; auto ir = dctHashCount.insert(std::pair<uint64_t, AuxItem>(gh, ni)); if (!ir.second) continue; it = ir.first; } if (++it->second.count == minPointCount) it->second.index = idx++; it->second.lat += ci->Latitude; it->second.lon += ci->Longitude; } lstRes.reserve(idx); lstRes.resize(idx); for (auto it = dctHashCount.begin(); it != dctHashCount.end(); ++it) { if (it->second.index == NOT_VALID_POINT_INDEX) continue; geopoint_t np; np.Latitude = it->second.lat / it->second.count; np.Longitude = it->second.lon / it->second.count; lstRes[it->second.index] = np; } return lstRes; } ////////////////////////////////////////////////////////////////////////// static const double a = 6378137.0; // meter static const double f = 1 / 298.257223563; static const double b = (1 - f) * a; // meter //https://en.wikipedia.org/wiki/Great-circle_distance static double geoDistanceMeters(double lon1, double lat1, double lon2, double lat2) { #if COORDINATES_HIGH_ACCURACY==0 double deltaLon = Degree2Rad(lon2 - lon1); double deltaLat = Degree2Rad(lat2 - lat1); double a = pow(sin(deltaLat / 2.0), 2.0) + cos(Degree2Rad(lat1))* cos(Degree2Rad(lat2))* pow(sin(deltaLon / 2.0), 2.0); double c = 2.0 * atan2(sqrt(a), sqrt(1.0-a)); return EARTH_RADIUS * c; #else double f1 = Degree2Rad(lat1), l1 = Degree2Rad(lon1); double f2 = Degree2Rad(lat2), l2 = Degree2Rad(lon2); double L = l2 - l1; double tanU1 = (1-f) * tan(f1); double cosU1 = 1 / sqrt((1.0 + tanU1*tanU1)); double sinU1 = tanU1 * cosU1; double tanU2 = (1-f) * tan(f2); double cosU2 = 1 / sqrt((1.0 + tanU2*tanU2)); double sinU2 = tanU2 * cosU2; double sinl, cosl; double sinSqs, sins=0.0, coss=0.0, sig=0.0, sina, cosSqa=0, cos2sigM=0, C; double l = L, ll; int iterations = 1000; do { sinl = sin(l); cosl = cos(l); sinSqs = (cosU2*sinl) * (cosU2*sinl) + (cosU1*sinU2-sinU1*cosU2*cosl) * (cosU1*sinU2-sinU1*cosU2*cosl); if (sinSqs == 0) break; // co-incident points sins = sqrt(sinSqs); coss = sinU1*sinU2 + cosU1*cosU2*cosl; sig = atan2(sins, coss); sina = cosU1 * cosU2 * sinl / sins; cosSqa = 1 - sina*sina; cos2sigM = (cosSqa != 0) ? (coss - 2*sinU1*sinU2/cosSqa) : 0; // equatorial line: cosSqฮฑ=0 (ยง6) C = f/16*cosSqa*(4+f*(4-3*cosSqa)); ll = l; l = L + (1-C) * f * sina * (sig + C*sins*(cos2sigM+C*coss*(-1+2*cos2sigM*cos2sigM))); if (abs(l) > M_PI) return 0.0; } while (abs(l-ll) > 1e-12 && iterations--); if (!iterations) return 0.0; double uSq = cosSqa * (a*a - b*b) / (b*b); double A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq))); double B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq))); double dsig = B*sins*(cos2sigM+B/4*(coss*(-1+2*cos2sigM*cos2sigM)- B/6*cos2sigM*(-3+4*sins*sins)*(-3+4*cos2sigM*cos2sigM))); double s = b*A*(sig-dsig); return s; #endif } ////////////////////////////////////////////////////////////////////////// double CoordLongitudeToMeters(double lon) { double distance = geoDistanceMeters(lon, 0.0, 0.0, 0.0); return distance * (lon < 0.0 ? -1.0 : 1.0); } ////////////////////////////////////////////////////////////////////////// double CoordLatitudeToMeters(double lat) { double distance = geoDistanceMeters(0.0, lat, 0.0, 0.0); return distance * (lat < 0.0 ? -1.0 : 1.0); } ////////////////////////////////////////////////////////////////////////// static geopoint_t getPointAhead(geopoint_t point, double distance, double azimuthDegrees) { #if COORDINATES_HIGH_ACCURACY==0 geopoint_t res; double radiusFraction = distance / EARTH_RADIUS; double bearing = Degree2Rad(azimuthDegrees); double lat1 = Degree2Rad(point.Latitude); double lng1 = Degree2Rad(point.Longitude); double lat2_part1 = sin(lat1) * cos(radiusFraction); double lat2_part2 = cos(lat1) * sin(radiusFraction) * cos(bearing); double lat2 = asin(lat2_part1 + lat2_part2); double lng2_part1 = sin(bearing) * sin(radiusFraction) * cos(lat1); double lng2_part2 = cos(radiusFraction) - sin(lat1) * sin(lat2); double lng2 = lng1 + atan2(lng2_part1, lng2_part2); lng2 = fmod(lng2 + 3.0*M_PI, 2.0*M_PI) - M_PI; res.Latitude = Rad2Degree(lat2); res.Longitude = Rad2Degree(lng2); return res; #else double t1 = Degree2Rad(point.Latitude); double l1 = Degree2Rad(point.Longitude); double a1 = Degree2Rad(azimuthDegrees); double sina1 = sin(a1); double cosa1 = cos(a1); double tanU1 = (1-f) * tan(t1); double cosU1 = 1 / sqrt((1 + tanU1*tanU1)); double sinU1 = tanU1 * cosU1; double sig1 = atan2(tanU1, cosa1); double sina = cosU1 * sina1; double cosSqa = 1 - sina*sina; double uSq = cosSqa * (a*a - b*b) / (b*b); double A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq))); double B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq))); double cos2sigM, sinSig, cosSig, dsig; double sig = distance / (b*A); double ddsig; int iterations = 100; do { cos2sigM = cos(2*sig1 + sig); sinSig = sin(sig); cosSig = cos(sig); dsig = B*sinSig*(cos2sigM+B/4*(cosSig*(-1+2*cos2sigM*cos2sigM)- B/6*cos2sigM*(-3+4*sinSig*sinSig)*(-3+4*cos2sigM*cos2sigM))); ddsig = sig; sig = distance / (b*A) + dsig; } while (abs(sig-ddsig) > 1e-12 && iterations--); assert(iterations); //hack! double x = sinU1*sinSig - cosU1*cosSig*cosa1; double l = atan2(sinSig*sina1, cosU1*cosSig - sinU1*sinSig*cosa1); double C = f/16*cosSqa*(4+f*(4-3*cosSqa)); double L = l - (1-C) * f * sina * (sig + C*sinSig*(cos2sigM+C*cosSig*(-1+2*cos2sigM*cos2sigM))); double l2 = fmod((l1+L+3*M_PI) , (2*M_PI)) - M_PI; // normalise to -180..+180 geopoint_t res; res.Latitude = Rad2Degree(atan2(sinU1*cosSig + cosU1*sinSig*cosa1, (1-f)*sqrt(sina*sina + x*x))); res.Longitude = Rad2Degree(l2); return res; #endif } ////////////////////////////////////////////////////////////////////////// static geopoint_t pointPlusDistanceEast(geopoint_t point, double distance) { return getPointAhead(point, distance, 90.0); } static geopoint_t pointPlusDistanceNorth(geopoint_t point, double distance) { return getPointAhead(point, distance, 0.0); } ////////////////////////////////////////////////////////////////////////// geopoint_t CoordMetersToGeopoint(double lonMeters, double latMeters) { geopoint_t point = {0.0, 0.0}; geopoint_t pointEast = pointPlusDistanceEast(point, lonMeters); geopoint_t pointNorthEast = pointPlusDistanceNorth(pointEast, latMeters); return pointNorthEast; } ////////////////////////////////////////////////////////////////////////// double CoordDistanceBetweenPointsMeters(double lat1, double lon1, double lat2, double lon2) { return geoDistanceMeters(lon1, lat1, lon2, lat2); } ////////////////////////////////////////////////////////////////////////// double CoordCaclulateDistance(const std::vector<geopoint_t> &lst) { double distance = 0.0; double llon, llat; if (lst.empty() || lst.size() == 1) return 0.0; llon = lst[0].Longitude; llat = lst[0].Latitude; for (auto pp = lst.begin()+1; pp != lst.end(); ++pp) { distance += CoordDistanceBetweenPointsMeters(llat, llon, pp->Latitude, pp->Longitude); llat = pp->Latitude; llon = pp->Longitude; } return distance; } //////////////////////////////////////////////////////////////////////////
9,369
3,824
//===============================================================================================// /*! * \file MeshEdge.hpp * \author Loรฏc Corenthy * \version 1.0 */ //===============================================================================================// #pragma once #include <iostream> namespace miniGL { /*! * \brief Helper class to store a simple edge * \details Stores an edge by its vertices and forces a specific order between them */ class MeshEdge { public: /*! * \brief Constructor with vertices * @param pA is the index of the first vertex * @param pB is the index of the second vertex */ MeshEdge(unsigned int pA, unsigned int pB); /*! * \brief Display the indices */ void display(void) const; /*! * \brief Set the index associated to the first vertex * @param pIndex is the index associated to vertex "a" */ void a(unsigned int pIndex) noexcept; /*! * \brief Set the index associated to the second vertex * @param pIndex is the index associated to vertex "b" */ void b(unsigned int pIndex) noexcept; /*! * \brief Get the index associated to the first vertex * @return the index associated to vertex "a" */ unsigned int a(void) const noexcept; /*! * \brief Get the index associated to the second vertex * @return the index associated to vertex "b" */ unsigned int b(void) const noexcept; private: unsigned int mA; unsigned int mB; }; // class MeshEdge } // namespace miniGL
1,753
464
//----------------------------------*-C++-*----------------------------------// /** * @file WGPreconditioner.cc * @brief WGPreconditioner * @author Jeremy Roberts * @date Nov 11, 2012 */ //---------------------------------------------------------------------------// #include "WGPreconditioner.hh" namespace detran { //---------------------------------------------------------------------------// WGPreconditioner::WGPreconditioner(SP_input input, SP_material material, SP_mesh mesh, std::string name) : Base(name) , d_input(input) , d_material(material) , d_mesh(mesh) { // Preconditions Require(d_input); Require(d_material); Require(d_mesh); // Number of groups d_number_groups = d_material->number_groups(); // Size the solver and operator vectors d_solver.resize(d_number_groups); d_operator.resize(d_number_groups); } } // end namespace detran //---------------------------------------------------------------------------// // end of file WGPreconditioner.cc //---------------------------------------------------------------------------//
1,211
332
#ifndef OCTARGS_SUBPARSER_ARGUMENT_HPP_ #define OCTARGS_SUBPARSER_ARGUMENT_HPP_ #include "argument_base.hpp" #include "internal/subparser_argument_impl.hpp" namespace oct { namespace args { template <typename char_T, typename values_storage_T> class basic_parser; /// \brief Subparser argument /// /// Subparser argument is a 'virtual' argument that allows registering /// subparsers so it is possible to implement a command based user interface /// (e.g. like the one provided by "git" command). /// /// \tparam char_T char type (as in std::basic_string) /// \tparam values_storage_T type of class uses as a storage for parsed values /// \tparam data_T argument value data type template <typename char_T, typename values_storage_T, typename data_T = void> class basic_subparser_argument : public basic_argument_base<basic_subparser_argument, internal::basic_subparser_argument_impl, char_T, values_storage_T, data_T> { public: using char_type = char_T; using values_storage_type = values_storage_T; using data_type = data_T; using base_type = basic_argument_base<oct::args::basic_subparser_argument, internal::basic_subparser_argument_impl, char_T, values_storage_T, data_T>; using parser_type = basic_parser<char_type, values_storage_type>; using string_type = typename base_type::string_type; using argument_ptr_type = typename base_type::argument_ptr_type; explicit basic_subparser_argument(const argument_ptr_type& argument_ptr) : base_type(argument_ptr) { // noop } template <typename handler_ptr_T> explicit basic_subparser_argument(const argument_ptr_type& argument_ptr, const handler_ptr_T& handler_ptr) : base_type(argument_ptr, handler_ptr) { // noop } parser_type add_parser(const string_type& name) { return this->get_argument().add_parser(name); } }; } // namespace args } // namespace oct #endif // OCTARGS_SUBPARSER_ARGUMENT_HPP_
2,040
636
/* * This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT) * * Copyright (c) 2019 Grรฉgory Van den Borre * * More infos available: https://engine.yildiz-games.be * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "../includes/World.hpp" #include "../includes/KinematicMotionState.hpp" #include "../includes/DynamicMotionState.hpp" #include <algorithm> /** * @author Grรฉgory Van den Borre */ yz::World::World() { this->ghostPairCallback = new btGhostPairCallback(); this->broadphase = new btDbvtBroadphase(); this->broadphase->getOverlappingPairCache()->setInternalGhostPairCallback( this->ghostPairCallback); this->collisionConfiguration = new btDefaultCollisionConfiguration(); this->dispatcher = new btCollisionDispatcher(collisionConfiguration); this->solver = new btSequentialImpulseConstraintSolver; this->world = new btDiscreteDynamicsWorld(this->dispatcher, this->broadphase, this->solver, this->collisionConfiguration); } yz::World::~World() { for (int i = this->world->getNumCollisionObjects() - 1; i >= 0; i--) { btCollisionObject* obj = this->world->getCollisionObjectArray()[i]; btRigidBody* body = btRigidBody::upcast(obj); if (body && body->getMotionState()) { delete body->getMotionState(); } this->world->removeCollisionObject(obj); delete obj; } delete this->world; delete this->solver; delete this->dispatcher; delete this->collisionConfiguration; delete this->broadphase; delete this->ghostPairCallback; } yz::RigidBody* yz::World::createStaticBody( btCollisionShape* shape, const btVector3& position, const btVector3& direction, const long id) { btScalar mass = 0; btVector3 inertia(0, 0, 0); btTransform trans; trans.setIdentity(); trans.setOrigin(position); yz::RigidBody* body = new yz::RigidBody(mass, new btDefaultMotionState(trans), shape, inertia, new yz::NativeMovable()); body->setCollisionFlags( body->getCollisionFlags() | btCollisionObject::CF_STATIC_OBJECT); body->setActivationState(ISLAND_SLEEPING); this->ids[body] = id; world->addRigidBody(body); return body; } yz::RigidBody* yz::World::createKinematicBody( btCollisionShape* shape, const long id, const float x, const float y, const float z) { btScalar mass = 0; btVector3 inertia(0, 0, 0); btTransform transform; transform.setOrigin(btVector3(x, y, z)); yz::RigidBody* body = new yz::RigidBody(mass, new KinematicMotionState(transform), shape, inertia, new yz::NativeMovable()); body->setCollisionFlags(body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); body->setActivationState(DISABLE_DEACTIVATION); world->addRigidBody(body, body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT, btCollisionObject::CF_KINEMATIC_OBJECT | btCollisionObject::CO_GHOST_OBJECT); this->ids[body] = id; return body; } yz::RigidBody* yz::World::createDynamicBody( btCollisionShape* shape, const long id, const float x, const float y, const float z, const float mass) { btVector3 inertia(0, 0, 0); shape->calculateLocalInertia(mass, inertia); btTransform transform; transform.setOrigin(btVector3(x, y, z)); yz::DynamicMotionState* s = new yz::DynamicMotionState(transform); yz::RigidBody* body = new yz::RigidBody(mass, s, shape, inertia, s->getMovable()); world->addRigidBody(body); this->ids[body] = id; return body; } btGhostObject* yz::World::createGhostObject(btCollisionShape* shape, const long id, const float x, const float y, const float z) { btGhostObject* ghostObject = new btGhostObject(); ghostObject->setCollisionShape(shape); ghostObject->setWorldTransform(btTransform(btQuaternion(0, 0, 0, 1), btVector3(x, y, z))); this->world->addCollisionObject(ghostObject, btCollisionObject::CO_GHOST_OBJECT, btCollisionObject::CF_KINEMATIC_OBJECT); this->ghostIds[ghostObject] = id; return ghostObject; } void yz::World::removeGhost(btGhostObject* ghost) { ghost->activate(false); this->world->removeCollisionObject(ghost); long id = this->ghostIds[ghost]; this->ghostCollisionResult.erase( std::remove(this->ghostCollisionResult.begin(), this->ghostCollisionResult.end(), id), this->ghostCollisionResult.end()); this->ghostIds.erase(ghost); delete ghost; } std::vector<jlong> yz::World::update(const long time) { this->world->stepSimulation(time / 1000.0f, 7); this->ghostCollisionResult.clear(); btCollisionObjectArray& collisionObjects = this->world->getCollisionObjectArray(); for (int i = 0; i < this->world->getNumCollisionObjects(); i++) { btGhostObject* ghost = btGhostObject::upcast(collisionObjects.at(i)); if (ghost) { btAlignedObjectArray<btCollisionObject*> objsInsidePairCachingGhostObject; objsInsidePairCachingGhostObject.resize(0); for (int j = 0; j < ghost->getNumOverlappingObjects(); j++) { btCollisionObject* co = ghost->getOverlappingObject(j); if (co) { btRigidBody *pRigidBody = btRigidBody::upcast(co); if (pRigidBody) { jlong g = this->ghostIds[ghost]; jlong b = this->ids[pRigidBody]; if (b != g) { this->ghostCollisionResult.push_back(g); this->ghostCollisionResult.push_back(b); } } } } } } //Retrieve rigid to rigid collisions. int numManifolds = this->world->getDispatcher()->getNumManifolds(); std::vector<jlong> collisionList; for (int i = 0; i < numManifolds; i++) { btPersistentManifold* contactManifold = this->world->getDispatcher()->getManifoldByIndexInternal(i); int numContacts = contactManifold->getNumContacts(); if (numContacts > 0) { const btCollisionObject* firstCo = contactManifold->getBody0(); const btCollisionObject* secondCo = contactManifold->getBody1(); if (btRigidBody::upcast(firstCo) && btRigidBody::upcast(secondCo)) { jlong firstId = this->ids[firstCo]; jlong secondId = this->ids[secondCo]; if (firstId && secondId) { collisionList.push_back(firstId); collisionList.push_back(secondId); } } } } return collisionList; } long yz::World::rayCast(const btVector3& origin, const btVector3& end) const { btCollisionWorld::ClosestRayResultCallback result(origin, end); this->world->getCollisionWorld()->rayTest(origin, end, result); long id = this->ids.at(result.m_collisionObject); return id == 0 ? -1L : id; } long yz::World::rayCast( const btVector3& origin, const btVector3& end, btCollisionWorld::ClosestRayResultCallback& result) const { this->world->getCollisionWorld()->rayTest(origin, end, result); long id = this->ids.at(result.m_collisionObject); return id == 0 ? -1L : id; } void yz::World::rayCastPoint( const btVector3& origin, const btVector3& end, float* resultArray) const { btCollisionWorld::ClosestRayResultCallback result(origin, end); this->world->getCollisionWorld()->rayTest(origin, end, result); if (!result.hasHit()) { resultArray[0] = -1; resultArray[1] = 0; resultArray[2] = 0; resultArray[3] = 0; } else { btVector3 contact = result.m_hitPointWorld; resultArray[0] = this->ids.at(result.m_collisionObject); resultArray[1] = contact.getX(); resultArray[2] = contact.getY(); resultArray[3] = contact.getZ(); } }
9,079
2,999
#include "main.h" #include "run.h" #include "parseCode.h" using namespace std; void listCommands(vector<vector<string> >& commands); string toString(int x){ ostringstream oStream; oStream << x; return oStream.str(); } int intFromString(string& from){ int to = 0; istringstream tempStream(from); tempStream >> to; return to; } void listCommands(vector<vector<string> >& commands){ for (unsigned int i = 0 ; i < commands.size(); i++ ){ for (unsigned int j = 0; j < commands[i].size() ; j++ ){ if (j == 0){ cout << "command counter is:" << i << "\n"; cout << "command is:" << commands[i][j] << "\n"; } else if (j == 1){ cout << "targer memory is:" << commands[i][j] << "\n"; } else if (j == 2){ cout << "first variable is:" << commands[i][j] << "\n"; } else if (j == 3){ cout << "second variable is:" << commands[i][j] << "\n"; } } cout << "\n"; } } void loadCode(string& code,string& filePath){ code.clear(); ifstream inf{filePath, ifstream::binary}; if (!inf){ cerr << "No File at Path " << filePath << "\n"; } char ch{}; while (inf.get(ch)){ code += ch; } } int main(int argc, char *argv[]) { cout << "zil2\n" << endl; string code{}; string filePath{}; if (argc > 1){ filePath = argv[1]; } if (filePath == ""){ cout << "Empty Path\n"; cout << "Loading Default Path\n\n"; filePath = "tikTakToe.zil2"; } loadCode(code,filePath); //cout << code; map<string, int> data; map<string, char> dataType; map<string, string> dataString; vector<vector<string> > commands; parseCode(code, commands); //List Commands for debuging //listCommands(commands); run(commands, data, dataString, dataType); return 0; }
1,989
667
// // Win.cpp // IkasGame // // Created by Sergio Garcia on 11/2/15. // // #include "Win.h" #include "../Singletons/GameSettingsManager.h" #include "../Singletons/SceneManager.h" #include "../Singletons/SoundManager.h" #include "../Singletons/AppManager.h" #include "../Helpers/LanguageManager.h" #include "../Helpers/ScreenSizeManager.h" #include "../Helpers/ImageManager.h" #include "../CustomGUI/SpriteButton.h" Scene* Win::createScene() { SceneManager::getInstance()->saveCurrentScene(); auto *scene = Scene::create(); auto *layer = Win::create(); layer->setTag(2339); scene->addChild(layer); return scene; } bool Win::init() { if (!Layer::init()) { return false; } Rect visibleRect = ScreenSizeManager::getVisibleRect(); auto background = Sprite::create(ImageManager::getImage("background"), visibleRect); background->setPosition(ScreenSizeManager::getScreenPositionFromPercentage(50, 50)); background->setAnchorPoint(Point::ANCHOR_MIDDLE); this->addChild(background); auto buttonNextGamePlay = SpriteButton::create(ImageManager::getImage("play"), 1.0f, CC_CALLBACK_1(Win::loadNextGamePlay, this)); buttonNextGamePlay->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonNextGamePlay = ScreenSizeManager::getScreenPositionFromPercentage(50, 50); buttonNextGamePlay->setPosition(positionButtonNextGamePlay); this->addChild(buttonNextGamePlay); auto winTitle = Sprite::create(ImageManager::getImage("win-title")); winTitle->setScale(0.75f); Vec2 positionWinTitle = buttonNextGamePlay->getPosition(); positionWinTitle.y += buttonNextGamePlay->getBoundingBox().size.height / 2; positionWinTitle.y += ScreenSizeManager::getHeightFromPercentage(2); winTitle->setPosition(positionWinTitle); winTitle->setAnchorPoint(Point::ANCHOR_MIDDLE_BOTTOM); this->addChild(winTitle); auto labelResume = Label::createWithTTF(LanguageManager::getLocalizedText("Win", "resume"), MainRegularFont, 70); labelResume->setAlignment(TextHAlignment::CENTER); labelResume->setAnchorPoint(Point::ANCHOR_MIDDLE_TOP); labelResume->setTextColor(IkasGrayDark); Vec2 positionLabelResume = buttonNextGamePlay->getPosition(); positionLabelResume.y -= buttonNextGamePlay->getBoundingBox().size.height / 2; positionLabelResume.y -= ScreenSizeManager::getHeightFromPercentage(1); labelResume->setPosition(positionLabelResume); this->addChild(labelResume); auto buttonSoundSettings = SpriteButton::create(ImageManager::getImage(GameSettingsManager::getInstance()->getIsSFXOn() ? SoundEnableImage : SoundDisableImage), 0.30f, CC_CALLBACK_1(Win::switchSoundSettings, this)); buttonSoundSettings->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonSoundSettings = ScreenSizeManager::getScreenPositionFromPercentage(80, 15); buttonSoundSettings->setPosition(positionButtonSoundSettings); this->addChild(buttonSoundSettings); auto buttonHome = SpriteButton::create(ImageManager::getImage("home"), 0.30f, CC_CALLBACK_1(Win::returnHome, this)); buttonHome->setAnchorPoint(Point::ANCHOR_MIDDLE); Vec2 positionButtonHome = ScreenSizeManager::getScreenPositionFromPercentage(22, 15); buttonHome->setPosition(positionButtonHome); this->addChild(buttonHome); return true; } void Win::loadNextGamePlay(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); SceneManager::getInstance()->loadSavedScene(); AppManager::getInstance()->loadNextGamePlay(); } void Win::switchSoundSettings(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); GameSettingsManager::getInstance()->switchSFX(); GameSettingsManager::getInstance()->switchMusic(); SpriteButton *item = static_cast<SpriteButton*>(sender); item->setTexture(ImageManager::getImage(GameSettingsManager::getInstance()->getIsSFXOn() ? SoundEnableImage : SoundDisableImage)); } void Win::returnHome(Ref* sender) { SoundManager::getInstance()->sfxPlay("button"); AppManager::getInstance()->setGamePlayDelegate(NULL); SceneManager::getInstance()->runSceneWithType(SceneType::MAIN); SceneManager::getInstance()->removeSavedScene(); }
4,266
1,319
#include "../../../include/emp/base/vector.hpp" #include "../../../include/emp/config/command_line.hpp" #include "../../../include/emp/config/SettingConfig.hpp" #include "../../../include/emp/data/DataLog.hpp" #include "../../../include/emp/io/File.hpp" #include "../../../include/emp/datastructs/vector_utils.hpp" #include "../../../include/emp/math/stats.hpp" int main(int argc, char* argv[]) { emp::SettingConfig config; size_t num_bins = 40; config.AddSetting("num_bins", "How many bins in histogram?", 'b', num_bins) = 40; config.ProcessOptions(argc, argv); auto unused_args = config.GetUnusedArgs(); if (unused_args.size() != 1) { std::cout << "Must include a single filename for data." << std::endl; exit(1); } emp::File file(unused_args[0]); file.RemoveWhitespace(); // Clear out all whitespace in file. file.RemoveEmpty(); // Remove all now-empty lines from file. if (file.GetNumLines() == 0) { std::cout << "No data found. Exiting." << std::endl; exit(2); } std::cout << "Found data for " << file.GetNumLines() << " histograms." << std::endl; auto data = file.ToData<double>(); // Analyze base data. double min_val = data[0][0]; double max_val = min_val; double total_val = 0.0; size_t num_vals = 0; for (auto & row : data) { for (double val : row) { if (val < min_val) min_val = val; if (val > max_val) max_val = val; total_val += val; num_vals++; } } // Collect the full histogram. double full_span = (max_val - min_val) * 1.00001; double bin_width = full_span / (double) num_bins; emp::vector<size_t> bin_counts(num_bins, 0); for (auto & row : data) { for (double val : row) { size_t cur_bin = (size_t) ((val - min_val) / bin_width); bin_counts[cur_bin]++; } } size_t max_bin_count = 0; for (size_t count : bin_counts) if (count > max_bin_count) max_bin_count = count; while (file.GetNumLines()) { emp::DataLog<double> row = file.ExtractRowAs<double>(); std::cout << "MIN_VAL: " << min_val << std::endl; row.AsciiHistogram(); std::cout << "MAX_VAL: " << max_val << std::endl; } std::cout << "OVERALL COUNT: " << num_vals << std::endl; std::cout << "OVERALL MIN: " << min_val << std::endl; std::cout << "OVERALL MAX: " << max_val << std::endl; std::cout << "OVERALL MEAN: " << (total_val/(double) num_vals) << std::endl; emp::AsciiBarGraph(bin_counts); double scale = ((double) max_bin_count) / 80.0; if (scale < 1.0) scale = 1.0; for (size_t count : bin_counts) { for (size_t i = 0; i < (count/scale); i++) std::cout << "*"; std::cout << std::endl; } }
2,668
1,039
// Copyright (c) 2013, The Toft Authors. // All rights reserved. // // Author: Ye Shunping <yeshunping@gmail.com> // toft/storage/sharding/fingerprint_sharding.cc #include "utils/toft_storage_sharding_fingerprint_sharding.h" #include "utils/toft_hash_fingerprint.h" namespace bubblefs { namespace mytoft { FingerprintSharding::FingerprintSharding() { } FingerprintSharding::~FingerprintSharding() { } int FingerprintSharding::Shard(const std::string& key) { int shard_id = Fingerprint64(key) % (shard_num_); return shard_id; } MYTOFT_REGISTER_SHARDING_POLICY(FingerprintSharding); } // namespace mytoft } // namespace bubblefs
646
251
#include <iostream> #include <cstdlib> #include "denoiser.hpp" #include <eigen3/Eigen/Dense> std::istream& operator>>(std::istream& is, Eigen::VectorXd& v) { int size; is >> size; v.resize(size); for(int i = 0; i < size; ++i) { is >> v(i); } return is; } int main() { Denoiser den; while(true) { Eigen::Vector2d in_sample; std::cin >> in_sample(0) >> in_sample(1); if(std::cin.fail()) { break; } auto out_sample = den.GetSmp(in_sample); std::cout << out_sample(0) << ' ' << out_sample(1) << '\n'; }; return EXIT_SUCCESS; }
672
262
#include "StackFrame.h" using namespace ApplicationInsights::core; StackFrame::StackFrame() { } StackFrame::~StackFrame() { } void StackFrame::Serialize(Serializer& serializer) const { serializer.WritePropertyName(L"level"); serializer.WriteIntegerValue(m_level); serializer.WritePropertyName(L"method"); serializer.WriteStringValue(m_method); if (!m_assembly.empty()) { serializer.WritePropertyName(L"assembly"); serializer.WriteStringValue(m_assembly); } if (!m_fileName.empty()) { serializer.WritePropertyName(L"fileName"); serializer.WriteStringValue(m_fileName); } serializer.WritePropertyName(L"line"); serializer.WriteIntegerValue(m_line); }
754
236
๏ปฟ#include <QFileDialog> #include <QMessageBox> #include "mainwindow.h" #include "ui_mainwindow.h" #include "dialog.h" using namespace std; /************************************************* * @brief MainWindow ็ฑป็š„ๆž„้€ ๅ‡ฝๆ•ฐ *************************************************/ MainWindow::MainWindow() : ui(new Ui::MainWindow) { ui->setupUi(this); elidfont = new QFontMetrics(ui->pathLabel->font()); } /************************************************* * @brief MainWindow ็ฑป็š„ๆžๆž„ๅ‡ฝๆ•ฐ *************************************************/ MainWindow::~MainWindow() { delete ui; } /************************************************* * @brief ็ช—ไฝ“ๅคงๅฐๆ”นๅ˜ไบ‹ไปถ * @param size ๆŒ‡ๅ‘ QResizeEvent ็š„ๆŒ‡้’ˆ๏ผˆๆ— ็”จ๏ผ‰ *************************************************/ void MainWindow::resizeEvent(QResizeEvent *size) { // ๅฏ็”จ็œ็•ฅๆจกๅผ่พ“ๅ‡บ่ทฏๅพ„ ui->pathLabel->setText(elidfont->elidedText(path, Qt::ElideMiddle, ui->pathLabel->width())); } /************************************************* * @brief ๆ‰“ๅผ€ๆ–‡ไปถๆŒ‰้’ฎ็‚นๅ‡ปไบ‹ไปถ *************************************************/ void MainWindow::on_openFileButton_clicked() { // ๆ‰“ๅผ€ๆจกๅผๅฏน่ฏๆก†๏ผŒ้€‰ๆ‹ฉๆ–‡ไปถ QString fileName = QFileDialog::getOpenFileName(this, "Open File", filePath, "*.e00"); // ไฟๅญ˜ไธŠๆฌกๆ‰“ๅผ€็š„็›ฎๅฝ• filePath = fileName.section('/', -2); // ๆ–‡ไปถๆ ผๅผๆ ก้ชŒ if (fileName.section('.', -1) == "e00") { // ๅปบ็ซ‹ไฟกๅทๅ’Œๆงฝ็š„่ฟžๆŽฅ map = new QGeoMap(this); connect(map, SIGNAL(pathUpdated(QString)), this, SLOT(on_pathUpdated(QString))); // ่ฏปๅ–ๆ–‡ไปถๅนถ่งฃ็  if (map->loadMap(fileName.toStdString())) { // ๆ›ดๆ–ฐๆ ‡้ข˜ๆ ๆ–‡ๅญ— this->setWindowTitle(fileName.section('/', -1) + " - Navigator++"); // ๆธ…้™ค่ทฏๅพ„ path.clear(); ui->pathLabel->setText(""); // ๆธฒๆŸ“ๅ›พๅฝข ui->mapWidget->setMap(map); ui->mapWidget->resetOffset(); ui->mapWidget->update(); } else { // ้‡Šๆ”พๆ— ็”จๅ†…ๅญ˜ delete map; map = nullptr; } } else if (fileName.length()) { QMessageBox::critical(this, "Error", "Please choose a \".e00\" file", QMessageBox::Ok); } } /************************************************* * @brief ่ทฏๅพ„ๅˆ†ๆžๆŒ‰้’ฎ็‚นๅ‡ปไบ‹ไปถ *************************************************/ void MainWindow::on_analyzeButton_clicked() { // ๆฃ€ๆŸฅๆ˜ฏๅฆๅทฒๆ‰“ๅผ€ๅœฐๅ›พๆ–‡ไปถ if (map != nullptr) { Dialog dialog(map); dialog.exec(); } else { QMessageBox::information(this, "Notice", "Please open a map first", QMessageBox::Ok); } } /************************************************* * @brief ่ทฏๅพ„ๆ›ดๆ–ฐไบ‹ไปถ * @param path ๆ›ดๆ–ฐไน‹ๅŽ็š„่ทฏๅพ„ๅญ—็ฌฆไธฒ *************************************************/ void MainWindow::on_pathUpdated(QString path) { // ๆ›ดๆ–ฐ่ฆ่พ“ๅ‡บ็š„่ทฏๅพ„ๅญ—็ฌฆไธฒ this->path = path; // ๅฏ็”จ็œ็•ฅๆจกๅผ่พ“ๅ‡บ่ทฏๅพ„ๅญ—็ฌฆไธฒ ui->pathLabel->setText(elidfont->elidedText(path, Qt::ElideMiddle, ui->pathLabel->width())); // ็ป˜ๅˆถ่ทฏๅพ„ ui->mapWidget->update(); }
2,938
1,046
#pragma once #include <memory> #include <vector> #include "driving_corridor.hpp" #include "traffic_rules.hpp" #include "internal/point2d.hpp" namespace p3iv_types { struct Crossing { double begin; double end; }; class RouteOption { public: RouteOption() = default; RouteOption(const VectorPoint2d& right, const VectorPoint2d& center, const VectorPoint2d& left); RouteOption(const DrivingCorridor& drivingCorridor); void setDrivingCorridor(const DrivingCorridor& drivingCorridor); protected: std::string uuid; DrivingCorridor corridor; Crossing crossing; TrafficRules trafficRules; }; } // namespace p3iv_types
661
227
#include "batch.h" #include "nanocv/timer.h" #include "nanocv/logger.h" #include "nanocv/sampler.h" #include "nanocv/minimize.h" #include "nanocv/accumulator.h" #include "nanocv/log_search.hpp" namespace ncv { namespace { opt_state_t train_batch( trainer_data_t& data, optim::batch_optimizer optimizer, size_t iterations, scalar_t epsilon, timer_t& timer, trainer_result_t& result, bool verbose) { size_t iteration = 0; // construct the optimization problem auto fn_size = ncv::make_opsize(data); auto fn_fval = ncv::make_opfval(data); auto fn_grad = ncv::make_opgrad(data); auto fn_wlog = verbose ? ncv::make_opwlog() : nullptr; auto fn_elog = verbose ? ncv::make_opelog() : nullptr; auto fn_ulog = [&] (const opt_state_t& state) { const scalar_t tvalue = data.m_gacc.value(); const scalar_t terror_avg = data.m_gacc.avg_error(); const scalar_t terror_var = data.m_gacc.var_error(); // validation samples: loss value data.m_lacc.set_params(state.x); data.m_lacc.update(data.m_task, data.m_vsampler.get(), data.m_loss); const scalar_t vvalue = data.m_lacc.value(); const scalar_t verror_avg = data.m_lacc.avg_error(); const scalar_t verror_var = data.m_lacc.var_error(); // update the optimum state const auto ret = result.update( state.x, tvalue, terror_avg, terror_var, vvalue, verror_avg, verror_var, ++ iteration, scalars_t({ data.lambda() })); if (verbose) log_info() << "[train = " << tvalue << "/" << terror_avg << ", valid = " << vvalue << "/" << verror_avg << " (" << text::to_string(ret) << ")" << ", xnorm = " << state.x.lpNorm<Eigen::Infinity>() << ", gnorm = " << state.g.lpNorm<Eigen::Infinity>() << ", epoch = " << iteration << ", lambda = " << data.lambda() << ", calls = " << state.n_fval_calls() << "/" << state.n_grad_calls() << "] done in " << timer.elapsed() << "."; return ret != trainer_result_return_t::overfitting; }; // assembly optimization problem & optimize the model return ncv::minimize(fn_size, fn_fval, fn_grad, fn_wlog, fn_elog, fn_ulog, data.m_x0, optimizer, iterations, epsilon); } } trainer_result_t batch_train( const model_t& model, const task_t& task, const sampler_t& tsampler, const sampler_t& vsampler, size_t nthreads, const loss_t& loss, const string_t& criterion, optim::batch_optimizer optimizer, size_t iterations, scalar_t epsilon, bool verbose) { vector_t x0; model.save_params(x0); // setup acumulators accumulator_t lacc(model, nthreads, criterion, criterion_t::type::value); accumulator_t gacc(model, nthreads, criterion, criterion_t::type::vgrad); trainer_data_t data(task, tsampler, vsampler, loss, x0, lacc, gacc); // tune the regularization factor (if needed) const auto op = [&] (scalar_t lambda) { data.set_lambda(lambda); trainer_result_t result; timer_t timer; train_batch(data, optimizer, iterations, epsilon, timer, result, verbose); return result; }; if (data.m_lacc.can_regularize()) { return log10_min_search(op, -6.0, +0.0, 0.5, 4).first; } else { return op(0.0); } } }
4,849
1,294
// // Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. // #include <sys/types.h> #include <unistd.h> #include <boost/asio/ip/address.hpp> #include <boost/asio/ip/host_name.hpp> #include <boost/program_options.hpp> #include <boost/assign/list_of.hpp> #include <boost/uuid/random_generator.hpp> #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int_distribution.hpp> #include <io/event_manager.h> #include <net/address.h> #include <base/task.h> #include <base/logging.h> #include <base/timer.h> #include <sandesh/common/vns_constants.h> #include <sandesh/common/vns_types.h> #include <sandesh/common/flow_types.h> #include <ksync/ksync_types.h> namespace opt = boost::program_options; typedef std::map<SessionIpPortProtocol, SessionAggInfo> SessionAggMap; class MockGenerator { public: const static int kNumVRouterErrorMessagesPerSec; const static int kNumSessionSamplesPerSec; const static int kNumSessionSamplesInMessage; MockGenerator(std::string &hostname, std::string &module_name, std::string &node_type_name, std::string &instance_id, int http_server_port, int start_vn, int end_vn, int other_vn, int num_vns, int vm_iterations, std::vector<std::string> &collectors, std::vector<uint32_t> &ip_vns, int ip_start_index, int num_vrouter_error_messages_per_sec, int num_sessions_per_vm, int num_session_samples_per_sec, int num_session_samples_in_message, EventManager *evm) : hostname_(hostname), module_name_(module_name), node_type_name_(node_type_name), instance_id_(instance_id), http_server_port_(http_server_port), start_vn_(start_vn), end_vn_(end_vn), other_vn_(other_vn), num_vns_(num_vns), vm_iterations_(vm_iterations), collectors_(collectors), ip_vns_(ip_vns), ip_start_index_(ip_start_index), num_session_per_vm_(num_sessions_per_vm), num_session_samples_per_sec_(num_session_samples_per_sec), num_session_samples_in_message_(num_session_samples_in_message), num_vrouter_error_messages_per_sec_(num_vrouter_error_messages_per_sec), rgen_(std::time(0)), u_rgen_(&rgen_), evm_(evm) { } bool Run() { // Initialize Sandesh Sandesh::InitGenerator(module_name_, hostname_, node_type_name_, instance_id_, evm_, http_server_port_, collectors_, NULL); TaskScheduler *scheduler = TaskScheduler::GetInstance(); if (num_session_samples_per_sec_) { SendSessionTask *stask(new SendSessionTask(this, scheduler->GetTaskId("mockgen::SendSessionTask"), -1)); scheduler->Enqueue(stask); } if (num_vrouter_error_messages_per_sec_) { SendMessageTask *mtask(new SendMessageTask(this, scheduler->GetTaskId("mockgen::SendMessageTask"), -1)); scheduler->Enqueue(mtask); } return true; } private: class SendMessageTask : public Task { public: SendMessageTask(MockGenerator *mock_generator, int task_id, int task_instance) : Task(task_id, task_instance), mgen_(mock_generator) { } void SendVRouterError() { std::string str1("VRouter operation failed. Error <"); uint32_t error(2); std::string str2(":"); std::string error_msg("Entry not pressent"); std::string str3(">. Object <"); std::string obj_str("Flow: 333333 with Source IP: " "not present >. Object < Flow: 333333 with Source IP: " "10.0.0.6 Source Port: 3333 Destination IP: 10.0.0.10 " "Destination Port: 13333 Protocol 6"); std::string str4(">. Operation <"); std::string state_str("Change"); std::string str5(">. Message number :"); uint64_t msg_no(418940931); V_ROUTER_ERROR_LOG("", SandeshLevel::SYS_DEBUG, str1, error, str2, error_msg, str3, obj_str, str4, state_str, str5, msg_no); } bool Run() { uint64_t diff_time(0); for (int i = 0; i < mgen_->num_vrouter_error_messages_per_sec_; i++) { uint64_t stime(UTCTimestampUsec()); SendVRouterError(); diff_time += UTCTimestampUsec() - stime; if (diff_time >= 1000000) { LOG(ERROR, "Sent: " << i + 1 << " in " << diff_time/1000000 << " seconds, NOT sending at " << mgen_->num_vrouter_error_messages_per_sec_ << " rate"); return false; } } usleep(1000000 - diff_time); return false; } std::string Description() const { return "SendMessageTask"; } private: MockGenerator *mgen_; }; class SendSessionTask : public Task { public: SendSessionTask(MockGenerator *mock_generator, int task_id, int task_instance) : Task(task_id, task_instance), mgen_(mock_generator) { } bool Run() { if (mgen_->sessions_.empty()) { int other_vn = mgen_->other_vn_; for (int vn = mgen_->start_vn_; vn < mgen_->end_vn_; vn++) { for (int nvm = 0; nvm < mgen_->vm_iterations_; nvm++) { for (int nsession = 0; nsession < mgen_->num_session_per_vm_; nsession++) { SessionEndpoint end_point; end_point.set_vmi(to_string(mgen_->u_rgen_())); end_point.set_vn(mgen_->kVnPrefix + integerToString(vn)); end_point.set_remote_vn(mgen_->kVnPrefix + integerToString(other_vn)); end_point.set_is_client_session(mgen_->dClientSession( mgen_->rgen_)); end_point.set_deployment( mgen_->kDeployment[mgen_->dTagIdx(mgen_->rgen_)]); end_point.set_tier(mgen_->kTier[mgen_->dTagIdx( mgen_->rgen_)]); end_point.set_application( mgen_->kApplication[mgen_->dTagIdx(mgen_->rgen_)]); end_point.set_site(mgen_->kSite[mgen_->dTagIdx( mgen_->rgen_)]); end_point.set_remote_deployment( mgen_->kDeployment[mgen_->dTagIdx(mgen_->rgen_)]); end_point.set_remote_tier( mgen_->kTier[mgen_->dTagIdx(mgen_->rgen_)]); end_point.set_remote_application( mgen_->kApplication[mgen_->dTagIdx(mgen_->rgen_)]); end_point.set_remote_site(mgen_->kSite[mgen_->dTagIdx( mgen_->rgen_)]); end_point.set_is_si(mgen_->dClientSession(mgen_->rgen_)); std::vector<std::string> labels; std::vector<std::string> remote_labels; int nlabels(mgen_->dLabels(mgen_->rgen_)); int nremote_labels(mgen_->dLabels(mgen_->rgen_)); for (int i = 0; i < nlabels + 1; i++) { labels.push_back( mgen_->kLabels[mgen_->dLabels(mgen_->rgen_)]); } for (int i = 0; i < nremote_labels + 1; i++) { remote_labels.push_back( mgen_->kLabels[mgen_->dLabels(mgen_->rgen_)]); } end_point.set_labels( std::set<string>(labels.begin(),labels.end())); end_point.set_remote_labels( std::set<string>(remote_labels.begin(),remote_labels.end())); SessionAggMap sess_agg_map; int nsport = mgen_->dNPorts(mgen_->rgen_); for (int i = 0; i < nsport; i++) { IpAddress ipaddr(Ip4Address(mgen_->ip_vns_[vn] + mgen_->ip_start_index_ + nvm)); uint16_t protoIdx(mgen_->dProtocols(mgen_->rgen_)); uint16_t port = mgen_->kPorts[protoIdx]; uint16_t proto = mgen_->kProtocols[protoIdx]; SessionIpPortProtocol sess_ip_port_proto; sess_ip_port_proto.set_local_ip(ipaddr); sess_ip_port_proto.set_service_port(port); sess_ip_port_proto.set_protocol(proto); SessionAggInfo place_holder; sess_agg_map[sess_ip_port_proto]; } end_point.set_sess_agg_info(sess_agg_map); mgen_->sessions_.push_back(end_point); } } other_vn = (other_vn + 1) % mgen_->num_vns_; } } int lsession_cnt = 0; int last_lsession_cnt = 0; uint64_t diff_time = 0; std::vector<SessionEndpoint>::iterator begin(mgen_->sessions_.begin() + mgen_->session_counter_); for (std::vector<SessionEndpoint>::iterator it = begin; it != mgen_->sessions_.end(); ++it) { bool sent_message(false); uint64_t stime = UTCTimestampUsec(); SessionEndpoint &end_point(*it); SessionAggMap sess_agg_info_map; for (SessionAggMap::const_iterator it2 = end_point.get_sess_agg_info().begin(); it2 != end_point.get_sess_agg_info().end(); ++it2) { SessionAggInfo sess_agg_info; std::map<SessionIpPort, SessionInfo> session_map; int ncport = mgen_->dNPorts(mgen_->rgen_); for (int i = 0; i < ncport; i++) { uint16_t cport(mgen_->dPort(mgen_->rgen_)); int nips = mgen_->dIps(mgen_->rgen_); for (int j = 0; j < nips; j++) { int other_vn; stringToInteger(end_point.get_remote_vn() .substr(MockGenerator::kVnPrefix.length(), std::string::npos), other_vn); IpAddress ipaddr(Ip4Address(mgen_->ip_vns_[other_vn] + mgen_->ip_start_index_ + j)); SessionIpPort sess_ip_port; sess_ip_port.set_port(cport); sess_ip_port.set_ip(ipaddr); std::map<SessionIpPort, SessionInfo>::iterator iter = session_map.find(sess_ip_port); if (iter != session_map.end()) { continue; } SessionInfo session_val; SessionFlowInfo forward_flow_info; SessionFlowInfo reverse_flow_info; uint64_t forward_pkts(mgen_->dFlowPktsPerSec( mgen_->rgen_)); uint64_t reverse_pkts(mgen_->dFlowPktsPerSec( mgen_->rgen_)); // Send once in every 5 message as a logged message if (j % 5 !=0 ) { forward_flow_info.set_sampled_pkts(forward_pkts); forward_flow_info.set_sampled_bytes(forward_pkts * mgen_->dBytesPerPacket(mgen_->rgen_)); reverse_flow_info.set_sampled_pkts(reverse_pkts); reverse_flow_info.set_sampled_bytes(reverse_pkts * mgen_->dBytesPerPacket(mgen_->rgen_)); sess_agg_info.set_sampled_forward_pkts( sess_agg_info.get_sampled_forward_pkts() + forward_pkts); sess_agg_info.set_sampled_forward_bytes( sess_agg_info.get_sampled_forward_bytes() + forward_flow_info.get_sampled_bytes()); sess_agg_info.set_sampled_reverse_pkts( sess_agg_info.get_sampled_reverse_pkts() + reverse_pkts); sess_agg_info.set_sampled_reverse_bytes( sess_agg_info.get_sampled_reverse_bytes() + reverse_flow_info.get_sampled_bytes()); } else { forward_flow_info.set_logged_pkts(forward_pkts); forward_flow_info.set_logged_bytes(forward_pkts * mgen_->dBytesPerPacket(mgen_->rgen_)); reverse_flow_info.set_logged_pkts(reverse_pkts); reverse_flow_info.set_logged_bytes(reverse_pkts * mgen_->dBytesPerPacket(mgen_->rgen_)); sess_agg_info.set_logged_forward_pkts( sess_agg_info.get_logged_forward_pkts() + forward_pkts); sess_agg_info.set_logged_forward_bytes( sess_agg_info.get_logged_forward_bytes() + forward_flow_info.get_logged_bytes()); sess_agg_info.set_logged_reverse_pkts( sess_agg_info.get_logged_reverse_pkts() + reverse_pkts); sess_agg_info.set_logged_reverse_bytes( sess_agg_info.get_logged_reverse_bytes() + reverse_flow_info.get_logged_bytes()); } session_val.set_forward_flow_info(forward_flow_info); session_val.set_reverse_flow_info(reverse_flow_info); session_map[sess_ip_port] = session_val; } } sess_agg_info.set_sessionMap(session_map); sess_agg_info_map[it2->first] = sess_agg_info; } end_point.set_sess_agg_info(sess_agg_info_map); lsession_cnt++; mgen_->session_counter_++; SESSION_ENDPOINT_OBJECT_LOG("", SandeshLevel::SYS_NOTICE, std::vector<SessionEndpoint>(begin+last_lsession_cnt, it + 1)); sent_message = true; last_lsession_cnt = lsession_cnt; if (lsession_cnt == mgen_->num_session_samples_per_sec_) { if (!sent_message) { SESSION_ENDPOINT_OBJECT_LOG("", SandeshLevel::SYS_NOTICE, std::vector<SessionEndpoint>(begin+last_lsession_cnt, it + 1)); } diff_time += UTCTimestampUsec() - stime; usleep(1000000 - diff_time); return false; } diff_time += UTCTimestampUsec() - stime; if (diff_time >= 1000000) { if (lsession_cnt < mgen_->num_session_samples_per_sec_) { LOG(ERROR, "Sent: " << lsession_cnt << " in " << diff_time/1000000 << " seconds, NOT sending at " << mgen_->num_session_samples_per_sec_ << " rate"); return false; } } } mgen_->session_counter_ = 0; return false; } std::string Description() const { return "SendSessionTask"; } private: MockGenerator *mgen_; }; const static std::string kVnPrefix; const static std::string kVmPrefix; const static int kBytesPerPacket = 1024; const static int kOtherVnPktsPerSec = 1000; const static int kUveMsgIntvlInSec = 10; const static int kFlowMsgIntvlInSec = 1; const static int kFlowPktsPerSec = 100; const static int kMaxIps = 64; const static int kMaxPorts = 5; const static boost::random::uniform_int_distribution<> dBytesPerPacket; const static boost::random::uniform_int_distribution<> dOtherVnPktsPerSec; const static boost::random::uniform_int_distribution<> dFlowPktsPerSec; const static boost::random::uniform_int_distribution<> dDirection; const static boost::random::uniform_int_distribution<> dClientSession; const static boost::random::uniform_int_distribution<> dPort; const static boost::random::uniform_int_distribution<> dIps; const static boost::random::uniform_int_distribution<> dNPorts; const static boost::random::uniform_int_distribution<> dLabels; const static std::vector<int> kProtocols; const static boost::random::uniform_int_distribution<> dProtocols; const static boost::random::uniform_int_distribution<> dTagIdx; const static std::vector<string> kLabels; const static std::vector<std::string> kDeployment; const static std::vector<std::string> kTier; const static std::vector<std::string> kSite; const static std::vector<std::string> kApplication; const static std::vector<int> kPorts; const std::string hostname_; const std::string module_name_; const std::string node_type_name_; const std::string instance_id_; const int http_server_port_; const int start_vn_; const int end_vn_; const int other_vn_; const int num_vns_; const int vm_iterations_; const std::vector<std::string> collectors_; const std::vector<uint32_t> ip_vns_; const int ip_start_index_; const int num_session_per_vm_; const int num_session_samples_per_sec_; const int num_session_samples_in_message_; const int num_vrouter_error_messages_per_sec_; std::vector<SessionEndpoint> sessions_; static int session_counter_; boost::random::mt19937 rgen_; boost::uuids::random_generator u_rgen_; EventManager *evm_; friend class SendMessageTask; }; const std::string MockGenerator::kVnPrefix("default-domain:mock-gen-test:vn"); const std::string MockGenerator::kVmPrefix("vm"); const boost::random::uniform_int_distribution<> MockGenerator::dBytesPerPacket(1, MockGenerator::kBytesPerPacket); const boost::random::uniform_int_distribution<> MockGenerator::dOtherVnPktsPerSec(1, MockGenerator::kOtherVnPktsPerSec); const boost::random::uniform_int_distribution<> MockGenerator::dFlowPktsPerSec(1, MockGenerator::kFlowPktsPerSec); const boost::random::uniform_int_distribution<> MockGenerator::dDirection(0, 1); const boost::random::uniform_int_distribution<> MockGenerator::dClientSession(0, 1); const boost::random::uniform_int_distribution<> MockGenerator::dPort(0, 65535); const std::vector<int> MockGenerator::kProtocols = boost::assign::list_of (6)(17)(1); const boost::random::uniform_int_distribution<> MockGenerator::dProtocols(0, MockGenerator::kProtocols.size() - 1); const std::vector<int> MockGenerator::kPorts = boost::assign::list_of (443)(8080)(22); const std::vector<std::string> MockGenerator::kDeployment = boost::assign::list_of ("Dep1")("Dep2")("Dep3")("Dep4"); const std::vector<std::string> MockGenerator::kTier = boost::assign::list_of ("Tier1")("Tier2")("Tier3")("Tier4"); const std::vector<std::string> MockGenerator::kApplication = boost::assign::list_of ("App1")("App2")("App3")("App4"); const std::vector<std::string> MockGenerator::kSite = boost::assign::list_of ("Site1")("Site2")("Site3")("Site4"); const std::vector<std::string> MockGenerator::kLabels = boost::assign::list_of ("Label1")("Label2")("Label3")("Label4")("Label5"); const boost::random::uniform_int_distribution<> MockGenerator::dTagIdx(0, MockGenerator::kDeployment.size() - 1); const boost::random::uniform_int_distribution<> MockGenerator::dIps(1, MockGenerator::kMaxIps); const boost::random::uniform_int_distribution<> MockGenerator::dNPorts(1, MockGenerator::kMaxPorts); const boost::random::uniform_int_distribution<> MockGenerator::dLabels(0, MockGenerator::kLabels.size() - 1); int MockGenerator::session_counter_(0); const int MockGenerator::kNumVRouterErrorMessagesPerSec(50); const int MockGenerator::kNumSessionSamplesPerSec(0); const int MockGenerator::kNumSessionSamplesInMessage(0); int main(int argc, char *argv[]) { bool log_local(false), use_syslog(false), log_flow(false); std::string log_category; opt::options_description desc("Command line options"); desc.add_options() ("help", "help message") ("collectors", opt::value<std::vector<std::string> >()->multitoken( )->default_value(std::vector<std::string>(1, "127.0.0.1:8086"), "127.0.0.1:8086"), "List of Collectors addresses in ip:port format") ("num_instances_per_generator", opt::value<int>()->default_value(10), "Number of instances (virtual machines) per generator") ("num_networks", opt::value<int>()->default_value(100), "Number of virtual networks") ("num_sessions_per_instance", opt::value<int>()->default_value(10), "Number of sessions per instance") ("start_ip_address", opt::value<std::string>()->default_value("1.0.0.1"), "Start IP address to be used for instances") ("http_server_port", opt::value<int>()->default_value(-1), "HTTP server port") ("generator_id", opt::value<int>()->default_value(0), "Generator Id") ("num_generators", opt::value<int>()->default_value(1), "Number of generators") ("num_vrouter_errors_per_second", opt::value<int>()->default_value( MockGenerator::kNumVRouterErrorMessagesPerSec), "Number of VRouterErrror messages to send in one second") ("num_session_samples_per_second", opt::value<int>()->default_value( MockGenerator::kNumSessionSamplesPerSec), "Number of session messages to send in one second") ("num_session_samples_in_message", opt::value<int>()->default_value( MockGenerator::kNumSessionSamplesInMessage), "Number of session samples to send in one message") ("log_property_file", opt::value<std::string>()->default_value(""), "log4cplus property file name") ("log_files_count", opt::value<int>()->default_value(10), "Maximum log file roll over index") ("log_file_size", opt::value<long>()->default_value(10*1024*1024), "Maximum size of the log file") ("log_category", opt::value<std::string>()->default_value(log_category), "Category filter for local logging of sandesh messages") ("log_file", opt::value<std::string>()->default_value("<stdout>"), "Filename for the logs to be written to") ("log_level", opt::value<std::string>()->default_value("SYS_NOTICE"), "Severity level for local logging of sandesh messages") ("log_local", opt::bool_switch(&log_local), "Enable local logging of sandesh messages") ("use_syslog", opt::bool_switch(&use_syslog), "Enable logging to syslog") ("syslog_facility", opt::value<std::string>()->default_value( "LOG_LOCAL0"), "Syslog facility to receive log lines") ("log_flow", opt::bool_switch(&log_flow), "Enable local logging of flow sandesh messages") ("slo_destination", opt::value<std::vector<std::string> >()->multitoken( )->default_value(std::vector<std::string>(1, "collector"), "collector"), "List of destinations. valid values are collector, file, syslog") ("sampled_destination", opt::value<std::vector<std::string> >()->multitoken( )->default_value(std::vector<std::string>(1, "collector"), "collector"), "List of destinations. valid values are collector, file, syslog"); opt::variables_map var_map; opt::store(opt::parse_command_line(argc, argv, desc), var_map); opt::notify(var_map); if (var_map.count("help")) { std::cout << desc << std::endl; exit(0); } Module::type module(Module::VROUTER_AGENT); std::string moduleid(g_vns_constants.ModuleNames.find(module)->second); std::string log_property_file( var_map["log_property_file"].as<std::string>()); if (log_property_file.size()) { LoggingInit(log_property_file); } else { LoggingInit(var_map["log_file"].as<std::string>(), var_map["log_file_size"].as<long>(), var_map["log_files_count"].as<int>(), use_syslog, var_map["syslog_facility"].as<std::string>(), moduleid, SandeshLevelTolog4Level(Sandesh::StringToLevel( var_map["log_level"].as<std::string>()))); } Sandesh::SetLoggingParams(log_local, var_map["log_category"].as<std::string>(), var_map["log_level"].as<std::string>(), false, log_flow); std::vector<std::string> slo_destination( var_map["slo_destination"].as<std::vector<std::string> >()); std::vector<std::string> sample_destination( var_map["sampled_destination"].as<std::vector<std::string> >()); Sandesh::set_logger_appender(var_map["log_file"].as<std::string>(), var_map["log_file_size"].as<long>(), var_map["log_files_count"].as<int>(), var_map["syslog_facility"].as<std::string>(), slo_destination, moduleid, false); Sandesh::set_logger_appender(var_map["log_file"].as<std::string>(), var_map["log_file_size"].as<long>(), var_map["log_files_count"].as<int>(), var_map["syslog_facility"].as<std::string>(), sample_destination, moduleid, true); Sandesh::set_send_to_collector_flags(sample_destination, slo_destination); int gen_id(var_map["generator_id"].as<int>()); int ngens(var_map["num_generators"].as<int>()); int pid(getpid()); int num_instances(var_map["num_instances_per_generator"].as<int>()); int num_networks(var_map["num_networks"].as<int>()); NodeType::type node_type( g_vns_constants.Module2NodeType.find(module)->second); std::string node_type_name( g_vns_constants.NodeTypeNames.find(node_type)->second); int http_server_port(var_map["http_server_port"].as<int>()); std::vector<std::string> collectors( var_map["collectors"].as<std::vector<std::string> >()); boost::system::error_code ec; std::string hostname(boost::asio::ip::host_name(ec)); if (ec) { LOG(ERROR, "Hostname FAILED: " << ec); exit(1); } hostname += "-" + integerToString(pid); int gen_factor = num_networks / num_instances; if (gen_factor == 0) { LOG(ERROR, "Number of virtual networks(" << num_networks << ") should " "be greater than number of instances per generator(" << num_instances << ")"); exit(1); } int start_vn((gen_id % gen_factor) * num_instances); int end_vn(((gen_id % gen_factor) + 1) * num_instances); int other_vn_adj(num_networks / 2); int other_vn; if (gen_id >= other_vn_adj) { other_vn = gen_id - other_vn_adj; } else { other_vn = gen_id + other_vn_adj; } int instance_iterations((num_instances + num_networks - 1) / num_networks); int num_ips_per_vn(((ngens * num_instances) + num_networks - 1) / num_networks); std::string start_ip(var_map["start_ip_address"].as<std::string>()); boost::asio::ip::address_v4 start_ip_address( boost::asio::ip::address_v4::from_string(start_ip.c_str(), ec)); if (ec) { LOG(ERROR, "IP Address (" << start_ip << ") FAILED: " << ec); exit(1); } std::vector<uint32_t> ip_vns; for (int num = 0; num < num_networks; num++) { ip_vns.push_back(start_ip_address.to_ulong() + num_ips_per_vn * num); } int start_ip_index(gen_id * num_instances / num_networks); EventManager evm; int num_sessions_per_instance(var_map["num_sessions_per_instance"].as<int>()); int num_session_samples_per_sec( var_map["num_session_samples_per_second"].as<int>()); int num_session_samples_in_message( var_map["num_session_samples_in_message"].as<int>()); int num_vrouter_error_messages_per_sec( var_map["num_vrouter_errors_per_second"].as<int>()); std::string instance_id(integerToString(gen_id)); MockGenerator mock_generator(hostname, moduleid, node_type_name, instance_id, http_server_port, start_vn, end_vn, other_vn, num_networks, instance_iterations, collectors, ip_vns, start_ip_index, num_vrouter_error_messages_per_sec, num_sessions_per_instance, num_session_samples_per_sec, num_session_samples_in_message, &evm); mock_generator.Run(); evm.Run(); return 0; }
30,923
9,247
// Copyright 2022 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include "iree/compiler/Dialect/Flow/IR/PartitionableLoopsInterface.h" #include "iree/compiler/Dialect/Flow/Transforms/Passes.h" #include "iree/compiler/Dialect/Util/IR/UtilOps.h" #include "mlir/Dialect/Func/IR/FuncOps.h" #include "mlir/Transforms/GreedyPatternRewriteDriver.h" static const char kAttributeName[] = "__test_interface__"; namespace mlir { namespace iree_compiler { namespace IREE { namespace Flow { namespace { /// For ops that implement the `PartitionableLoopsInterface` that have the /// `__test_interface__` attribute set generates a `util.unfoldable_constant` /// with a value of type `tensor<axindex>`, where `a` is the number of loops and /// the value has zeros for non-partitionable loops and 1 for partitionable /// loops. struct TestPartitionableLoopsInterfacePattern : public OpInterfaceRewritePattern<PartitionableLoopsInterface> { using OpInterfaceRewritePattern< PartitionableLoopsInterface>::OpInterfaceRewritePattern; LogicalResult matchAndRewrite(PartitionableLoopsInterface interfaceOp, PatternRewriter &rewriter) const { if (!interfaceOp->hasAttr(kAttributeName)) { return failure(); } unsigned numLoops = interfaceOp.getNumLoops(); SmallVector<unsigned> partitionableLoops = interfaceOp.getPartitionableLoops(3); SmallVector<int64_t> loopInfo(numLoops, 0); for (auto partitionableLoop : partitionableLoops) { loopInfo[partitionableLoop] = 1; } auto type = RankedTensorType::get(numLoops, rewriter.getIndexType()); auto constantAttr = DenseIntElementsAttr::get(type, loopInfo); rewriter.create<Util::UnfoldableConstantOp>(interfaceOp.getLoc(), constantAttr); rewriter.updateRootInPlace( interfaceOp, [&] { interfaceOp->removeAttr(kAttributeName); }); return success(); } }; struct TestPartitionableLoopsInterfacePass : public PassWrapper<TestPartitionableLoopsInterfacePass, OperationPass<void>> { StringRef getArgument() const override { return "iree-flow-test-partitionable-loops-interface"; } StringRef getDescription() const override { return "Test the PartitionableLoopsInterface using operations that " "implement that interface."; } void getDependentDialects(DialectRegistry &registry) const override { registry.insert<FlowDialect>(); } void runOnOperation() override { RewritePatternSet patterns(&getContext()); patterns.add<TestPartitionableLoopsInterfacePattern>(patterns.getContext()); if (failed(applyPatternsAndFoldGreedily(getOperation(), std::move(patterns)))) { return signalPassFailure(); } } }; } // namespace std::unique_ptr<OperationPass<void>> createTestPartitionableLoopsInterfacePass() { return std::make_unique<TestPartitionableLoopsInterfacePass>(); } static PassRegistration<TestPartitionableLoopsInterfacePass> pass; } // namespace Flow } // namespace IREE } // namespace iree_compiler } // namespace mlir
3,316
964
#include "Cloud.h" #include "glew.h" #include <GL/gl.h> #include <GL/glu.h> #include "glut.h" #include <iostream> #include <glm/gtx/compatibility.hpp> #include "Core/Geometry/Vertex.h" #include "Core/Random.h" Cloud::Cloud(const glm::vec3& position, float radius, uint32_t count) :m_Position(position), m_Radius(radius), m_BallCount(count) { Core::Geometry* sphere = Core::Geometry::Create(Core::PrimitiveType::Icosphere); CloudDrawList = glGenLists(1); glNewList(CloudDrawList, GL_COMPILE); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); for (uint32_t i = 0; i < m_BallCount; i++) { glm::vec3 randomPositionInSphere = m_Position + glm::vec3( Core::Random::RandomRange(-m_Radius, m_Radius), Core::Random::RandomRange(-m_Radius, m_Radius), Core::Random::RandomRange(-m_Radius, m_Radius)); const float distance = glm::length(m_Position - randomPositionInSphere); // Bigger towards the center, lighter towards the center. glm::vec3 randomScale = glm::lerp(glm::vec3(.5f), glm::vec3(3.0f), 1.5f - distance / m_Radius); glm::vec3 randomColor = glm::lerp(m_DarkerColor, m_White, 1.0f - distance / m_Radius); glPushMatrix(); glColor3f(randomColor.r, randomColor.g, randomColor.b); glTranslatef(randomPositionInSphere.x, randomPositionInSphere.y, randomPositionInSphere.z); glScalef(randomScale.x, randomScale.y, randomScale.z); glBegin(GL_TRIANGLES); for (auto index : sphere->GetIndices()) { Core::Vertex vertex = sphere->GetVertices()[index]; glVertex3f(vertex.Position.x, vertex.Position.y, vertex.Position.z); glNormal3f(vertex.Normal.x, vertex.Normal.y, vertex.Normal.z); } glEnd(); glPopMatrix(); } glEndList(); delete sphere; } Cloud::~Cloud() { } void Cloud::Draw() { glCallList(CloudDrawList); }
1,770
723
#include<bits/stdc++.h> using namespace std; void smallerleft(int array[], int n){ stack<int> s; for(int i =0;i<n;i++){ while(!s.empty() && s.top() >= array[i]){ s.pop(); } if(s.empty()) cout<<"-1"<<" "; else cout<<s.top()<<" "; s.push(array[i]); } cout<<endl; } int main() { int t; cin>>t; while(t--){ int n; cin>>n; int array[100000]; for(int i =0;i<n;i++){ cin>>array[i]; } smallerleft(array, n); } return 0; }
641
245
// // TimeStamp.hpp // // Created by Vincent Moscaritolo on 5/6/21. // #ifndef TimeStamp_hpp #define TimeStamp_hpp #include <stdlib.h> #include <time.h> #include <string> namespace timestamp { class TimeStamp{ public: TimeStamp(bool isGMT = true); TimeStamp(std::string str); TimeStamp(time_t time) { _time = time;}; inline time_t getTime() { return _time; }; std::string RFC1123String(); std::string ISO8601String(); std::string logFileString(); std::string ClockString(bool isGMT = true); private: time_t _time; }; }; #endif /* TimeStamp_hpp */
574
237
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/ess/model/RecordLifecycleActionHeartbeatRequest.h> using AlibabaCloud::Ess::Model::RecordLifecycleActionHeartbeatRequest; RecordLifecycleActionHeartbeatRequest::RecordLifecycleActionHeartbeatRequest() : RpcServiceRequest("ess", "2014-08-28", "RecordLifecycleActionHeartbeat") { setMethod(HttpRequest::Method::Post); } RecordLifecycleActionHeartbeatRequest::~RecordLifecycleActionHeartbeatRequest() {} std::string RecordLifecycleActionHeartbeatRequest::getLifecycleActionToken()const { return lifecycleActionToken_; } void RecordLifecycleActionHeartbeatRequest::setLifecycleActionToken(const std::string& lifecycleActionToken) { lifecycleActionToken_ = lifecycleActionToken; setParameter("LifecycleActionToken", lifecycleActionToken); } int RecordLifecycleActionHeartbeatRequest::getHeartbeatTimeout()const { return heartbeatTimeout_; } void RecordLifecycleActionHeartbeatRequest::setHeartbeatTimeout(int heartbeatTimeout) { heartbeatTimeout_ = heartbeatTimeout; setParameter("HeartbeatTimeout", std::to_string(heartbeatTimeout)); } std::string RecordLifecycleActionHeartbeatRequest::getAccessKeyId()const { return accessKeyId_; } void RecordLifecycleActionHeartbeatRequest::setAccessKeyId(const std::string& accessKeyId) { accessKeyId_ = accessKeyId; setParameter("AccessKeyId", accessKeyId); } std::string RecordLifecycleActionHeartbeatRequest::getResourceOwnerAccount()const { return resourceOwnerAccount_; } void RecordLifecycleActionHeartbeatRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount) { resourceOwnerAccount_ = resourceOwnerAccount; setParameter("ResourceOwnerAccount", resourceOwnerAccount); } std::string RecordLifecycleActionHeartbeatRequest::getLifecycleHookId()const { return lifecycleHookId_; } void RecordLifecycleActionHeartbeatRequest::setLifecycleHookId(const std::string& lifecycleHookId) { lifecycleHookId_ = lifecycleHookId; setParameter("LifecycleHookId", lifecycleHookId); } std::string RecordLifecycleActionHeartbeatRequest::getOwnerAccount()const { return ownerAccount_; } void RecordLifecycleActionHeartbeatRequest::setOwnerAccount(const std::string& ownerAccount) { ownerAccount_ = ownerAccount; setParameter("OwnerAccount", ownerAccount); } long RecordLifecycleActionHeartbeatRequest::getOwnerId()const { return ownerId_; } void RecordLifecycleActionHeartbeatRequest::setOwnerId(long ownerId) { ownerId_ = ownerId; setParameter("OwnerId", std::to_string(ownerId)); }
3,193
989
#include "outDynasty.h" #include "CK3/Dynasties/Dynasty.h" std::ostream& CK3::operator<<(std::ostream& output, const Dynasty& dynasty) { // output ID, name and culture output << dynasty.ID << " = {\n"; output << "\tname = \"" << dynasty.name << "\"\n"; output << "\tculture = " << dynasty.culture << "\n"; output << "}\n"; return output; }
351
139
#include <iostream> #include <cmath> using namespace std; void print(int arr[], int size) { for (int i = 0; i < size; i++) { cout << arr[i] << "\t"; } cout << endl; } void merge(int arr[], int l, int r, int mid) { int leftSize = (int) ceil( (double) ((r - l + 1) / 2)); int rightSize = (r - l + 1) / 2; int *leftCopy = new int[leftSize]; int *rightCopy = new int[rightSize]; int i = l, j = mid + 1; for (int a = 0; a < leftSize; a++) { leftCopy[a] = arr[i++]; } for (int b = 0; b < rightSize; b++) { rightCopy[b] = arr[j++]; } i = l, j = mid + 1; int a = 0, b = 0; while (a < leftSize && b < leftSize) { if (leftCopy[a] < rightCopy[b]) { arr[i++] = leftCopy[a++]; } else { arr[j++] = rightCopy[b++]; } } while (a < leftSize) { arr[i++] = leftCopy[a++]; } while (b < rightSize) { arr[j++] = rightCopy[b++]; } } void mergeSort(int arr[], int l, int r) { if (l < r) { int mid = (r + l) / 2; mergeSort(arr, l, mid); mergeSort(arr, mid + 1, r); merge(arr, l, r, mid); } } int main() { int array[5]{ 1,2,3,4,5 }; mergeSort(array, 0, 4); print(array, 5); }
1,116
550
#include "tim/vx/ops/conv2d.h" #include "gtest/gtest.h" #include "test_utils.h" #include "tim/vx/context.h" #include "tim/vx/graph.h" #include "tim/vx/types.h" TEST(Conv2d, shape_4_2_1_1_float32_PaddingTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 2, 1, 1}); //whcn tim::vx::ShapeType weight_shape({2, 2, 1, 3}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {4, 2, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = { 1, 1, 1, 1, // row = 1 2, 2, 3, 2 // row = 2 }; // weight data oihw std::vector<float> weight_data = { 1, 2, 3, 4, //first 2x2 filter -1, 1, -1, 1, // second 2x2 filter -1, -1, 1, 1, // third 2x2 filter }; // bias data std::vector<float> bias_data = {1, 2, 3}; // nchw std::vector<float> golden = {// first channel 18, 22, 21, 8, 7, 9, 8, 3, 2, 3, 1, -1, // second channel 2, 3, 1, 0, 5, 6, 6, 4, -1, -2, -2, 1}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::SAME; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_2_2_2_float32_PointwiseTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 2, 2, 2}); //whcn tim::vx::ShapeType weight_shape({1, 1, 2, 1}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {4, 2, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = { 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2}; // weight data oihw std::vector<float> weight_data = { 1, 2 // first filter }; // bias data std::vector<float> bias_data = {0}; // nchw std::vector<float> golden = {1.5, 1.5, 1.5, 1.5, 3, 3, 3, 3, 1.5, 3, 4.5, 6, 1.5, 3, 4.5, 6}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::SAME; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_2_1_2_float32_SimpleTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 2, 1, 2}); //whcn tim::vx::ShapeType weight_shape({2, 2, 1, 3}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {2, 1, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = { // First batch 1, 1, 1, 1, // row = 1 2, 2, 2, 2, // row = 2 // Second batch 1, 2, 3, 4, // row = 1 1, 2, 3, 4, // row = 2 }; // weight data oihw std::vector<float> weight_data = {1, 2, 3, 4, -1, 1, -1, 1, -1, -1, 1, 1}; // bias data std::vector<float> bias_data = {1, 2, 3}; // nchw std::vector<float> golden = {18, 18, 2, 2, 5, 5, 17, 37, 4, 4, 3, 3}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::SAME; std::array<uint32_t, 2> stride({2, 2}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_2_2_2_float32_SimpleChannelsTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 2, 2, 2}); //whcn tim::vx::ShapeType weight_shape({2, 2, 2, 3}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {2, 1, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data std::vector<float> input_data = { 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2}; // weight data std::vector<float> weight_data = {1, 2, 3, 4, 1, 2, 3, 4, -1, 1, -1, 1, -1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, 1}; // bias data std::vector<float> bias_data = {1, 2, 3}; std::vector<float> golden = {18, 18, 2, 2, 5, 5, 17, 37, 4, 4, 3, 3}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::SAME; std::array<uint32_t, 2> stride({2, 2}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_6_3_1_1_float32_SimpleAnisotropicStridesTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({6, 3, 1, 1}); //whcn tim::vx::ShapeType weight_shape({2, 2, 1, 1}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {2, 2, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = {3, 2, 1, -1, -2, -3, 4, 3, 2, -2, -3, -4, 5, 4, 3, -3, -4, -5}; // weight data oihw std::vector<float> weight_data = { 1, 2, // 3, 4, // }; // bias data std::vector<float> bias_data = {-1}; // nchw std::vector<float> golden = { 30, -24, // 40, -34, // }; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({3, 1}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_3_1_1_float32_HandCalculatedTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 3, 1, 1}); //whcn tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {4, 3, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; // weight data oihw std::vector<float> weight_data = {1, 4, 7, 2, 5, 8, 3, 6, 9}; // bias data std::vector<float> bias_data = {0}; // nchw std::vector<float> golden = {105, 150, 183, 95, 235, 312, 357, 178, 187, 234, 261, 121}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::SAME; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_3_1_1_float32_HandCalculatedConstFilterTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 3, 1, 1}); //whcn tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {4, 3, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; // weight data oihw std::vector<float> weight_data = {1, 4, 7, 2, 5, 8, 3, 6, 9}; // bias data std::vector<float> bias_data = {0}; // nchw std::vector<float> golden = {105, 150, 183, 95, 235, 312, 357, 178, 187, 234, 261, 121}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::SAME; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_3_1_1_float32_HandCalculatedBiasTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 3, 1, 1}); //whcn tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {4, 3, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; // weight data oihw std::vector<float> weight_data = {1, 4, 7, 2, 5, 8, 3, 6, 9}; // bias data std::vector<float> bias_data = {10}; // nchw std::vector<float> golden = {115, 160, 193, 105, 245, 322, 367, 188, 197, 244, 271, 131}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::SAME; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_3_1_1_float32_HandCalculatedValidTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 3, 1, 1}); //whcn tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {2, 1, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; // weight data oihw std::vector<float> weight_data = {1, 4, 7, 2, 5, 8, 3, 6, 9}; // bias data std::vector<float> bias_data = {0}; // nchw std::vector<float> golden = {312, 357}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_2_2_2_float32_DisabledPointwiseMultifilterTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 2, 2, 2}); //whcn tim::vx::ShapeType weight_shape({1, 1, 2, 2}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {4, 2, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = { 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2}; // weight data oihw std::vector<float> weight_data = {1, 2, 2, 3}; // bias data std::vector<float> bias_data = {0}; // nchw std::vector<float> golden = { 1.5, 1.5, 1.5, 1.5, 3, 3, 3, 3, 2.5, 2.5, 2.5, 2.5, 5, 5, 5, 5, 1.5, 3, 4.5, 6, 1.5, 3, 4.5, 6, 2.5, 5, 7.5, 10, 2.5, 5, 7.5, 10}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_9_9_1_1_float32_SimpleDilationTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({9, 9, 1, 1}); //whcn tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {3, 3, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // weight data oihw std::vector<float> weight_data = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // bias data std::vector<float> bias_data = {0}; // nchw std::vector<float> golden = {5, 5, 5, 5, 5, 5, 5, 5, 5}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({3, 3}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_2_1_2_float32_StrideTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 2, 1, 2}); //whcn tim::vx::ShapeType weight_shape({2, 2, 1, 3}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {3, 1, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = {1, 1, 1, 1, 2, 2, 3, 2, 1, 2, 3, 4, 1, 2, 4, 4}; // weight data oihw std::vector<float> weight_data = {1, 2, 3, 4, -1, 1, -1, 1, -1, -1, 1, 1}; // bias data std::vector<float> bias_data = {1, 2, 3}; // nchw std::vector<float> golden = {18, 22, 21, 2, 3, 1, 5, 6, 6, 17, 31, 40, 4, 5, 3, 3, 4, 4}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_2_1_2_float32_InputAndFilterSameWidthHeightTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 2, 1, 2}); //whcn tim::vx::ShapeType weight_shape({4, 2, 1, 1}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {1, 1, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = {1, 1, 1, 1, 2, 2, 2, 2, 1, 2, 3, 4, 1, 2, 3, 4}; // weight data oihw std::vector<float> weight_data = {1, 2, 3, 4, -1, -1, 1, 1}; // bias data std::vector<float> bias_data = {0}; // nchw std::vector<float> golden = {10, 34}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_2_1_2_uint8_QuantizedTest1) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 2, 1, 2}); //whcn tim::vx::ShapeType weight_shape({2, 2, 1, 3}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {2, 1, weight_shape[3], input_shape[3]}); //whcn float input_min = -63.5, input_max = 64, weight_min = -63.5, weight_max = 64, output_min = -127, output_max = 128; std::pair<float, int32_t> scales_zp; scales_zp = QuantizationParams<u_int8_t>(input_min, input_max); std::vector<float> scales_input = {scales_zp.first}; std::vector<int32_t> zero_point_input = {scales_zp.second}; scales_zp = QuantizationParams<u_int8_t>(weight_min, weight_max); std::vector<float> scales_weight = {scales_zp.first}; std::vector<int32_t> zero_point_weight = {scales_zp.second}; std::vector<float> scales_bias = {scales_input[0] * scales_weight[0]}; std::vector<int32_t> zero_point_bias = {0}; scales_zp = QuantizationParams<u_int8_t>(output_min, output_max); std::vector<float> scales_output = {scales_zp.first}; std::vector<int32_t> zero_point_output = {scales_zp.second}; tim::vx::Quantization quant_input(tim::vx::QuantType::ASYMMETRIC, 2, scales_input, zero_point_input); tim::vx::Quantization quant_weight(tim::vx::QuantType::ASYMMETRIC, 2, scales_weight, zero_point_weight); tim::vx::Quantization quant_bias(tim::vx::QuantType::ASYMMETRIC, 2, scales_bias, zero_point_bias); tim::vx::Quantization quant_output(tim::vx::QuantType::ASYMMETRIC, 2, scales_output, zero_point_output); tim::vx::TensorSpec input_spec(tim::vx::DataType::UINT8, input_shape, tim::vx::TensorAttribute::INPUT, quant_input); tim::vx::TensorSpec weight_spec(tim::vx::DataType::UINT8, weight_shape, tim::vx::TensorAttribute::CONSTANT, quant_weight); tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape, tim::vx::TensorAttribute::CONSTANT, quant_bias); tim::vx::TensorSpec output_spec(tim::vx::DataType::UINT8, output_shape, tim::vx::TensorAttribute::OUTPUT, quant_output); // Input data nchw // min:-63.5 max:64 scale:0.5 Zp:-1 std::vector<float> input_data_float = {1, 1, 1, 1, 2, 2, 2, 2, 1, 2, 3, 4, 1, 2, 3, 4}; // weight data oihw // min:-63.5 max:64 scale:0.5 Zp:-1 std::vector<float> weight_data_float = {1, 2, 3, 4, -1, 1, -1, 1, -1, -1, 1, 1}; // bias data // scale:0.25 Zp:0 std::vector<float> bias_data_float = {1, 2, 3}; // golden data //min:-127 max:128 scale:1 Zp:-1 std::vector<float> golden_float = {18, 18, 2, 2, 5, 5, 17, 37, 4, 4, 3, 3}; std::vector<u_int8_t> input_data = Quantize<uint8_t>(input_data_float, scales_input[0], zero_point_input[0]); std::vector<u_int8_t> weight_data = Quantize<uint8_t>(weight_data_float, scales_weight[0], zero_point_input[0]); std::vector<int32_t> bias_data = Quantize<int32_t>(bias_data_float, scales_bias[0], zero_point_bias[0]); std::vector<u_int8_t> golden = Quantize<uint8_t>(golden_float, scales_output[0], zero_point_output[0]); auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({2, 2}); std::array<uint32_t, 2> dilation({1, 1}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<u_int8_t> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_2_1_2_uint8_QuantizedTest2) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 2, 1, 2}); //whcn tim::vx::ShapeType weight_shape({2, 2, 1, 3}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {2, 1, weight_shape[3], input_shape[3]}); //whcn float input_min = -128.5, input_max = 128, weight_min = -128.5, weight_max = 128, output_min = -127, output_max = 128; std::pair<float, int32_t> scales_zp; scales_zp = QuantizationParams<u_int8_t>(input_min, input_max); std::vector<float> scales_input = {scales_zp.first}; std::vector<int32_t> zero_point_input = {scales_zp.second}; scales_zp = QuantizationParams<u_int8_t>(weight_min, weight_max); std::vector<float> scales_weight = {scales_zp.first}; std::vector<int32_t> zero_point_weight = {scales_zp.second}; std::vector<float> scales_bias = {scales_input[0] * scales_weight[0]}; std::vector<int32_t> zero_point_bias = {0}; scales_zp = QuantizationParams<u_int8_t>(output_min, output_max); std::vector<float> scales_output = {scales_zp.first}; std::vector<int32_t> zero_point_output = {scales_zp.second}; tim::vx::Quantization quant_input(tim::vx::QuantType::ASYMMETRIC, 2, scales_input, zero_point_input); tim::vx::Quantization quant_weight(tim::vx::QuantType::ASYMMETRIC, 2, scales_weight, zero_point_weight); tim::vx::Quantization quant_bias(tim::vx::QuantType::ASYMMETRIC, 2, scales_bias, zero_point_bias); tim::vx::Quantization quant_output(tim::vx::QuantType::ASYMMETRIC, 2, scales_output, zero_point_output); tim::vx::TensorSpec input_spec(tim::vx::DataType::UINT8, input_shape, tim::vx::TensorAttribute::INPUT, quant_input); tim::vx::TensorSpec weight_spec(tim::vx::DataType::UINT8, weight_shape, tim::vx::TensorAttribute::CONSTANT, quant_weight); tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape, tim::vx::TensorAttribute::CONSTANT, quant_bias); tim::vx::TensorSpec output_spec(tim::vx::DataType::UINT8, output_shape, tim::vx::TensorAttribute::OUTPUT, quant_output); // Input data nchw // min:-128.5 max:128 scale:1.00588 Zp:0 std::vector<float> input_data_float = {1, 1, 1, 1, 2, 2, 2, 2, 1, 2, 3, 4, 1, 2, 3, 4}; // weight data oihw // min:-128.5 max:128 scale:1.00588 Zp:0 std::vector<float> weight_data_float = {1, 2, 3, 4, -1, 1, -1, 1, -1, -1, 1, 1}; // bias data // scale:1.0116 Zp:0 std::vector<float> bias_data_float = {1, 2, 3}; // golden data // min:-127 max:128 scale:1 Zp:-1 std::vector<float> golden_float = {18, 18, 2, 2, 5, 5, 17, 37, 4, 4, 3, 3}; std::vector<u_int8_t> input_data = Quantize<uint8_t>(input_data_float, scales_input[0], zero_point_input[0]); std::vector<u_int8_t> weight_data = Quantize<uint8_t>(weight_data_float, scales_weight[0], zero_point_input[0]); std::vector<int32_t> bias_data = Quantize<int32_t>(bias_data_float, scales_bias[0], zero_point_bias[0]); std::vector<u_int8_t> golden = Quantize<uint8_t>(golden_float, scales_output[0], zero_point_output[0]); auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({2, 2}); std::array<uint32_t, 2> dilation({1, 1}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<u_int8_t> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_6_3_1_1_uint8_AnisotropicStridesQuantizedTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({6, 3, 1, 1}); //whcn tim::vx::ShapeType weight_shape({2, 2, 1, 1}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {2, 2, weight_shape[3], input_shape[3]}); //whcn float input_min = -63.5, input_max = 64, weight_min = -63.5, weight_max = 64, output_min = -127, output_max = 128; std::pair<float, int32_t> scales_zp; scales_zp = QuantizationParams<u_int8_t>(input_min, input_max); std::vector<float> scales_input = {scales_zp.first}; std::vector<int32_t> zero_point_input = {scales_zp.second}; scales_zp = QuantizationParams<u_int8_t>(weight_min, weight_max); std::vector<float> scales_weight = {scales_zp.first}; std::vector<int32_t> zero_point_weight = {scales_zp.second}; std::vector<float> scales_bias = {scales_input[0] * scales_weight[0]}; std::vector<int32_t> zero_point_bias = {0}; scales_zp = QuantizationParams<u_int8_t>(output_min, output_max); std::vector<float> scales_output = {scales_zp.first}; std::vector<int32_t> zero_point_output = {scales_zp.second}; tim::vx::Quantization quant_input(tim::vx::QuantType::ASYMMETRIC, 2, scales_input, zero_point_input); tim::vx::Quantization quant_weight(tim::vx::QuantType::ASYMMETRIC, 2, scales_weight, zero_point_weight); tim::vx::Quantization quant_bias(tim::vx::QuantType::ASYMMETRIC, 2, scales_bias, zero_point_bias); tim::vx::Quantization quant_output(tim::vx::QuantType::ASYMMETRIC, 2, scales_output, zero_point_output); tim::vx::TensorSpec input_spec(tim::vx::DataType::UINT8, input_shape, tim::vx::TensorAttribute::INPUT, quant_input); tim::vx::TensorSpec weight_spec(tim::vx::DataType::UINT8, weight_shape, tim::vx::TensorAttribute::CONSTANT, quant_weight); tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape, tim::vx::TensorAttribute::CONSTANT, quant_bias); tim::vx::TensorSpec output_spec(tim::vx::DataType::UINT8, output_shape, tim::vx::TensorAttribute::OUTPUT, quant_output); // Input data nchw // min:-63.5 max:64 scale:0.5 Zp:-1 std::vector<float> input_data_float = {3, 2, 1, -1, -2, -3, 4, 3, 2, -2, -3, -4, 5, 4, 3, -3, -4, -5}; // weight data oihw // min:-63.5 max:64 scale:0.5 Zp:-1 std::vector<float> weight_data_float = {1, 2, 3, 4}; // bias data // scale:0.25 Zp:0 std::vector<float> bias_data_float = {-1}; // golden data //min:-127 max:128 scale:1 Zp:-1 std::vector<float> golden_float = {30, -24, 40, -34}; std::vector<u_int8_t> input_data = Quantize<uint8_t>(input_data_float, scales_input[0], zero_point_input[0]); std::vector<u_int8_t> weight_data = Quantize<uint8_t>(weight_data_float, scales_weight[0], zero_point_input[0]); std::vector<int32_t> bias_data = Quantize<int32_t>(bias_data_float, scales_bias[0], zero_point_bias[0]); std::vector<u_int8_t> golden = Quantize<uint8_t>(golden_float, scales_output[0], zero_point_output[0]); auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({3, 1}); std::array<uint32_t, 2> dilation({1, 1}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<u_int8_t> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_9_9_1_1_uint8_DilationQuantizedTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({9, 9, 1, 1}); //whcn tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {3, 3, weight_shape[3], input_shape[3]}); //whcn float input_min = -128, input_max = 127, weight_min = -128, weight_max = 127, output_min = 0, output_max = 255; std::pair<float, int32_t> scales_zp; scales_zp = QuantizationParams<u_int8_t>(input_min, input_max); std::vector<float> scales_input = {scales_zp.first}; std::vector<int32_t> zero_point_input = {scales_zp.second}; scales_zp = QuantizationParams<u_int8_t>(weight_min, weight_max); std::vector<float> scales_weight = {scales_zp.first}; std::vector<int32_t> zero_point_weight = {scales_zp.second}; std::vector<float> scales_bias = {scales_input[0] * scales_weight[0]}; std::vector<int32_t> zero_point_bias = {0}; scales_zp = QuantizationParams<u_int8_t>(output_min, output_max); std::vector<float> scales_output = {scales_zp.first}; std::vector<int32_t> zero_point_output = {scales_zp.second}; tim::vx::Quantization quant_input(tim::vx::QuantType::ASYMMETRIC, 2, scales_input, zero_point_input); tim::vx::Quantization quant_weight(tim::vx::QuantType::ASYMMETRIC, 2, scales_weight, zero_point_weight); tim::vx::Quantization quant_bias(tim::vx::QuantType::ASYMMETRIC, 2, scales_bias, zero_point_bias); tim::vx::Quantization quant_output(tim::vx::QuantType::ASYMMETRIC, 2, scales_output, zero_point_output); tim::vx::TensorSpec input_spec(tim::vx::DataType::UINT8, input_shape, tim::vx::TensorAttribute::INPUT, quant_input); tim::vx::TensorSpec weight_spec(tim::vx::DataType::UINT8, weight_shape, tim::vx::TensorAttribute::CONSTANT, quant_weight); tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape, tim::vx::TensorAttribute::CONSTANT, quant_bias); tim::vx::TensorSpec output_spec(tim::vx::DataType::UINT8, output_shape, tim::vx::TensorAttribute::OUTPUT, quant_output); // Input data nchw // min:-128 max:127 scale:1 Zp:0 std::vector<float> input_data_float = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // weight data oihw // min:-128 max:127 scale:1 Zp:0 std::vector<float> weight_data_float = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // bias data // scale:1 Zp:0 std::vector<float> bias_data_float = {0}; // golden data // min:0 max:255 scale:1 Zp:-128 std::vector<float> golden_float = {5, 5, 5, 5, 5, 5, 5, 5, 5}; std::vector<u_int8_t> input_data = Quantize<uint8_t>(input_data_float, scales_input[0], zero_point_input[0]); std::vector<u_int8_t> weight_data = Quantize<uint8_t>(weight_data_float, scales_weight[0], zero_point_input[0]); std::vector<int32_t> bias_data = Quantize<int32_t>(bias_data_float, scales_bias[0], zero_point_bias[0]); std::vector<u_int8_t> golden = Quantize<uint8_t>(golden_float, scales_output[0], zero_point_output[0]); auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({3, 3}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<u_int8_t> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_3_2_2_1_int8_QuantizedPerTensorTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({3, 2, 2, 1}); //whcn tim::vx::ShapeType weight_shape({2, 2, 2, 2}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {2, 1, weight_shape[3], input_shape[3]}); //whcn float input_min = -63.5, input_max = 64, weight_min = -63.5, weight_max = 64, output_min = -63.5, output_max = 64; std::pair<float, int32_t> scales_zp; scales_zp = QuantizationParams<int8_t>(input_min, input_max); std::vector<float> scales_input = {scales_zp.first}; std::vector<int32_t> zero_point_input = {scales_zp.second}; scales_zp = QuantizationParams<int8_t>(weight_min, weight_max); std::vector<float> scales_weight = {1}; std::vector<int32_t> zero_point_weight = {0}; std::vector<float> scales_bias = {scales_input[0] * scales_weight[0]}; std::vector<int32_t> zero_point_bias = {0}; scales_zp = QuantizationParams<int8_t>(output_min, output_max); std::vector<float> scales_output = {scales_zp.first}; std::vector<int32_t> zero_point_output = {scales_zp.second}; tim::vx::Quantization quant_input(tim::vx::QuantType::ASYMMETRIC, 2, scales_input, zero_point_input); tim::vx::Quantization quant_weight(tim::vx::QuantType::ASYMMETRIC, 2, scales_weight, zero_point_weight); tim::vx::Quantization quant_bias(tim::vx::QuantType::ASYMMETRIC, 2, scales_bias, zero_point_bias); tim::vx::Quantization quant_output(tim::vx::QuantType::ASYMMETRIC, 2, scales_output, zero_point_output); tim::vx::TensorSpec input_spec(tim::vx::DataType::INT8, input_shape, tim::vx::TensorAttribute::INPUT, quant_input); tim::vx::TensorSpec weight_spec(tim::vx::DataType::INT8, weight_shape, tim::vx::TensorAttribute::CONSTANT, quant_weight); tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape, tim::vx::TensorAttribute::CONSTANT, quant_bias); tim::vx::TensorSpec output_spec(tim::vx::DataType::INT8, output_shape, tim::vx::TensorAttribute::OUTPUT, quant_output); // Input data nchw // min:-63.5 max:64 scale:0.5 Zp:-1 std::vector<float> input_data_float = {3, 1, -2, 4, 2, -3, 2, -1, -3, 3, -2, -4}; std::vector<int8_t> input_data = Quantize<int8_t>(input_data_float, scales_input[0], zero_point_input[0]); // weight_float_data = {1, 3, 3, 5, 2, 4, 4, 6, 7, 5, 3, 1, 8, 6, 4, 2}; std::vector<int8_t> weight_data = {1, 3, 3, 5, 2, 4, 4, 6, 7, 5, 3, 1, 8, 6, 4, 2}; // bias data std::vector<float> bias_data_float = {3, -2}; std::vector<int32_t> bias_data = Quantize<int32_t>(bias_data_float, scales_bias[0], zero_point_bias[0]); // golden_int8_data = {61, -115, 111, -89} // min:-63.5 max:64 scale:0.5 Zp:-1 std::vector<float> golden_float = {31, -57, 56, -44}; std::vector<int8_t> golden = Quantize<int8_t>(golden_float, scales_output[0], zero_point_output[0]); auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({1, 1}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<int8_t> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_3_2_2_1_int8_QuantizedPerChannelTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({3, 2, 2, 1}); //whcn tim::vx::ShapeType weight_shape({2, 2, 2, 2}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {2, 1, weight_shape[3], input_shape[3]}); //whcn float input_min = -63.5, input_max = 64, weight_min = 0, weight_max = 0, output_min = -63.5, output_max = 64; std::pair<float, int32_t> scales_zp; scales_zp = QuantizationParams<int8_t>(input_min, input_max); std::vector<float> scales_input = {scales_zp.first}; std::vector<int32_t> zero_point_input = {scales_zp.second}; scales_zp = QuantizationParams<int8_t>(weight_min, weight_max); std::vector<float> scales_weight = {1, 2}; std::vector<int32_t> zero_point_weight = {0, 0}; std::vector<float> scales_bias = {scales_input[0] * scales_weight[0], scales_input[0] * scales_weight[1]}; std::vector<int32_t> zero_point_bias = {0, 0}; scales_zp = QuantizationParams<int8_t>(output_min, output_max); std::vector<float> scales_output = {scales_zp.first}; std::vector<int32_t> zero_point_output = {scales_zp.second}; tim::vx::Quantization quant_input(tim::vx::QuantType::ASYMMETRIC, 2, scales_input, zero_point_input); tim::vx::Quantization quant_weight(tim::vx::QuantType::SYMMETRIC_PER_CHANNEL, 3, scales_weight, zero_point_weight); tim::vx::Quantization quant_bias(tim::vx::QuantType::SYMMETRIC_PER_CHANNEL, 0, scales_bias, zero_point_bias); tim::vx::Quantization quant_output(tim::vx::QuantType::ASYMMETRIC, 2, scales_output, zero_point_output); tim::vx::TensorSpec input_spec(tim::vx::DataType::INT8, input_shape, tim::vx::TensorAttribute::INPUT, quant_input); tim::vx::TensorSpec weight_spec(tim::vx::DataType::INT8, weight_shape, tim::vx::TensorAttribute::CONSTANT, quant_weight); tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape, tim::vx::TensorAttribute::CONSTANT, quant_bias); tim::vx::TensorSpec output_spec(tim::vx::DataType::INT8, output_shape, tim::vx::TensorAttribute::OUTPUT, quant_output); // Input data nchw // min:-63.5 max:64 scale:0.5 Zp:-1 std::vector<float> input_data_float = {3, 1, -2, 4, 2, -3, 2, -1, -3, 3, -2, -4}; std::vector<int8_t> input_data = Quantize<int8_t>(input_data_float, scales_input[0], zero_point_input[0]); // weight_data_float = {1, 3, 3, 5, 2, 4, 4, 6, 7, 5, 3, 1, 8, 6, 4, 2}; std::vector<int8_t> weight_data = {1, 3, 3, 5, 2, 4, 4, 6, 4, 3, 2, 1, 4, 3, 2, 1}; // bias_data_float ={3, -2}; std::vector<int32_t> bias_data = {6, -2}; // golden data // min:-63.5 max:64 scale:0.5 Zp:-1 std::vector<float> golden_float = {31, -57, 64, -46}; std::vector<int8_t> golden = Quantize<int8_t>(golden_float, scales_output[0], zero_point_output[0]); auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({1, 1}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<int8_t> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_w_h_128_1_ksize_1_1_stride_2_int8_QuantizedPerChannelTest) { std::map<uint32_t, std::vector<uint32_t>> input_shape_list; input_shape_list[32] = {18, 20, 22, 26, 28, 30, 34, 36, 38, 42, 44, 46, 50, 52, 54, 58, 60, 62}; input_shape_list[63] = {18, 22, 26, 30, 34, 38, 42, 46, 50, 54, 58, 62}; input_shape_list[95] = {18, 20, 22, 26, 28, 30, 34, 36, 38, 42, 44, 46, 50, 52, 54, 58, 60, 62}; input_shape_list[96] = {18, 20, 22, 26, 28, 30, 34, 36, 38, 42, 44, 46, 50, 52, 54, 58, 60, 62}; tim::vx::ShapeType input_shape({2, 2, 128, 1}); //whcn tim::vx::ShapeType weight_shape({1, 1, 128, 256}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {1, 1, weight_shape[3], input_shape[3]}); //whcn std::vector<float> scales_input = {0.5}; std::vector<int32_t> zero_point_input = {-1}; std::vector<float> scales_weight(weight_shape[3]); std::vector<int32_t> zero_point_weight(weight_shape[3]); for (unsigned int i = 0; i < weight_shape[3]; i++) { scales_weight[i] = 1; zero_point_weight[i] = 0; } int32_t sizeofweight = scales_weight.size(); std::vector<float> scales_bias(sizeofweight); std::vector<int32_t> zero_point_bias(sizeofweight); for (int i = 0; i < sizeofweight; i++) { scales_bias[i] = scales_input[0] * scales_weight[i]; zero_point_bias[i] = 0; } std::vector<float> scales_output = {0.5}; std::vector<int32_t> zero_point_output = {-1}; tim::vx::Quantization quant_input(tim::vx::QuantType::ASYMMETRIC, 2, scales_input, zero_point_input); tim::vx::Quantization quant_weight(tim::vx::QuantType::SYMMETRIC_PER_CHANNEL, 3, scales_weight, zero_point_weight); tim::vx::Quantization quant_bias(tim::vx::QuantType::SYMMETRIC_PER_CHANNEL, 0, scales_bias, zero_point_bias); tim::vx::Quantization quant_output(tim::vx::QuantType::ASYMMETRIC, 2, scales_output, zero_point_output); uint32_t weight_size = weight_shape[0] * weight_shape[1] * weight_shape[2] * weight_shape[3]; std::vector<float> weight_data_float(weight_size); for (uint32_t i = 0; i < weight_size; i++) { weight_data_float[i] = 1; } std::vector<int8_t> weight_data = Quantize<int8_t>(weight_data_float, 1, 0); // bias_data std::vector<int32_t> bias_data(weight_shape[3]); for (uint32_t i = 0; i < weight_shape[3]; i++) { bias_data[i] = 2; } for (std::map<uint32_t, std::vector<uint32_t>>::iterator iter = input_shape_list.begin(); iter != input_shape_list.end(); iter++) { for (uint32_t j = 0; j < iter->second.size(); j++) { input_shape[0] = iter->first; input_shape[1] = iter->second[j]; output_shape[0] = (input_shape[0] + 1) / 2; output_shape[1] = (input_shape[1] + 1) / 2; tim::vx::TensorSpec input_spec(tim::vx::DataType::INT8, input_shape, tim::vx::TensorAttribute::INPUT, quant_input); tim::vx::TensorSpec weight_spec(tim::vx::DataType::INT8, weight_shape, tim::vx::TensorAttribute::CONSTANT, quant_weight); tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape, tim::vx::TensorAttribute::CONSTANT, quant_bias); tim::vx::TensorSpec output_spec(tim::vx::DataType::INT8, output_shape, tim::vx::TensorAttribute::OUTPUT, quant_output); uint32_t input_size = input_shape[0] * input_shape[1] * input_shape[2] * input_shape[3]; std::vector<float> input_data_float(input_size); for (uint32_t i = 0; i < input_size; i++) { input_data_float[i] = 1; } std::vector<int8_t> input_data = Quantize<int8_t>( input_data_float, scales_input[0], zero_point_input[0]); uint32_t golden_size = output_shape[0] * output_shape[1] * output_shape[2] * output_shape[3]; std::vector<float> golden_float(golden_size); for (uint32_t i = 0; i < golden_size; i++) { golden_float[i] = 129; } std::vector<int8_t> golden = Quantize<int8_t>(golden_float, scales_output[0], zero_point_output[0]); auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({2, 2}); std::array<uint32_t, 2> dilation({1, 1}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<int8_t> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } } }
63,953
25,818
//////////////////////////////////////////////////////////////////////////////////////////////////// ////// Blank Panel 8 HP module ///////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// #include "Ohmer.hpp" struct OhmerBlank8 : Module { enum ParamIds { NUM_PARAMS }; enum InputIds { NUM_INPUTS }; enum OutputIds { NUM_OUTPUTS }; enum LightIds { NUM_LIGHTS }; // Current selected plate model (color). int Theme = 0; // 0 = Classic (default), 1 = Stage Repro, 2 = Absolute Night, 3 = Dark Signature, 4 = Deepblue Signature, 5 = Carbon Signature. // Panel color (default is "Classic" beige model). NVGcolor panelBackgroundColor = nvgRGB(0xd2, 0xd2, 0xcd); OhmerBlank8() { config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS); } void process(const ProcessArgs &args) override { // DSP processing... // Depending current model (theme), set the relevant background color for panel. panelBackgroundColor = tblPanelBackgroundColor[Theme]; } json_t *dataToJson() override { json_t *rootJ = json_object(); json_object_set_new(rootJ, "Theme", json_integer(Theme)); return rootJ; } void dataFromJson(json_t *rootJ) override { json_t *ThemeJ = json_object_get(rootJ, "Theme"); if (ThemeJ) Theme = json_integer_value(ThemeJ); } }; ///////////////////////////////////////////////////// CONTEXT-MENU ////////////////////////////////////////////////////// struct OhmerBlank8ClassicMenu : MenuItem { OhmerBlank8 *module; void onAction(const event::Action &e) override { module->Theme = 0; // Model: default Classic (beige). } }; struct OhmerBlank8StageReproMenu : MenuItem { OhmerBlank8 *module; void onAction(const event::Action &e) override { module->Theme = 1; // Model: Stage Repro. } }; struct OhmerBlank8AbsoluteNightMenu : MenuItem { OhmerBlank8 *module; void onAction(const event::Action &e) override { module->Theme = 2; // Model: Absolute Night. } }; struct OhmerBlank8DarkSignatureMenu : MenuItem { OhmerBlank8 *module; void onAction(const event::Action &e) override { module->Theme = 3; // Model: Dark Signature. } }; struct OhmerBlank8DeepblueSignatureMenu : MenuItem { OhmerBlank8 *module; void onAction(const event::Action &e) override { module->Theme = 4; // Model: Deepblue Signature. } }; struct OhmerBlank8CarbonSignatureMenu : MenuItem { OhmerBlank8 *module; void onAction(const event::Action &e) override { module->Theme = 5; // Model: Carbon Signature. } }; struct OhmerBlank8SubMenuItems : MenuItem { OhmerBlank8 *module; Menu *createChildMenu() override { Menu *menu = new Menu; OhmerBlank8ClassicMenu *ohmerblank8menuitem1 = new OhmerBlank8ClassicMenu; ohmerblank8menuitem1->text = "Classic (default)"; ohmerblank8menuitem1->rightText = CHECKMARK(module->Theme == 0); ohmerblank8menuitem1->module = module; menu->addChild(ohmerblank8menuitem1); OhmerBlank8StageReproMenu *ohmerblank8menuitem2 = new OhmerBlank8StageReproMenu; ohmerblank8menuitem2->text = "Stage Repro"; ohmerblank8menuitem2->rightText = CHECKMARK(module->Theme == 1); ohmerblank8menuitem2->module = module; menu->addChild(ohmerblank8menuitem2); OhmerBlank8AbsoluteNightMenu *ohmerblank8menuitem3 = new OhmerBlank8AbsoluteNightMenu; ohmerblank8menuitem3->text = "Absolute Night"; ohmerblank8menuitem3->rightText = CHECKMARK(module->Theme == 2); ohmerblank8menuitem3->module = module; menu->addChild(ohmerblank8menuitem3); OhmerBlank8DarkSignatureMenu *ohmerblank8menuitem4 = new OhmerBlank8DarkSignatureMenu; ohmerblank8menuitem4->text = "Dark \"Signature\""; ohmerblank8menuitem4->rightText = CHECKMARK(module->Theme == 3); ohmerblank8menuitem4->module = module; menu->addChild(ohmerblank8menuitem4); OhmerBlank8DeepblueSignatureMenu *ohmerblank8menuitem5 = new OhmerBlank8DeepblueSignatureMenu; ohmerblank8menuitem5->text = "Deepblue \"Signature\""; ohmerblank8menuitem5->rightText = CHECKMARK(module->Theme == 4); ohmerblank8menuitem5->module = module; menu->addChild(ohmerblank8menuitem5); OhmerBlank8CarbonSignatureMenu *ohmerblank8menuitem6 = new OhmerBlank8CarbonSignatureMenu; ohmerblank8menuitem6->text = "Carbon \"Signature\""; ohmerblank8menuitem6->rightText = CHECKMARK(module->Theme == 5); ohmerblank8menuitem6->module = module; menu->addChild(ohmerblank8menuitem6); return menu; } }; ///////////////////////////////////////////////// PANEL BACKGROUND COLOR ///////////////////////////////////////////////// struct OhmerBlank8Background : TransparentWidget { OhmerBlank8 *module; OhmerBlank8Background() { } void draw(const DrawArgs &args) override { nvgBeginPath(args.vg); nvgRect(args.vg, 0.0, 0.0, box.size.x, box.size.y); if (module) nvgFillColor(args.vg, module->panelBackgroundColor); else nvgFillColor(args.vg, nvgRGB(0xd2, 0xd2, 0xcd)); nvgFill(args.vg); } }; ///////////////////////////////////////////////// MODULE WIDGET SECTION ///////////////////////////////////////////////// struct OhmerBlank8Widget : ModuleWidget { // Panel (transparent widget). OhmerBlank8Background *blankPanel; // Silver Torx screws. SvgScrew *topLeftScrewSilver; SvgScrew *topRightScrewSilver; SvgScrew *bottomLeftScrewSilver; SvgScrew *bottomRightScrewSilver; // Gold Torx screws. SvgScrew *topLeftScrewGold; SvgScrew *topRightScrewGold; SvgScrew *bottomLeftScrewGold; SvgScrew *bottomRightScrewGold; OhmerBlank8Widget(OhmerBlank8 *module) { setModule(module); // 8 HP module, no SVG panel loaded, but using transparent widget instead. box.size = Vec(8 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT); { blankPanel = new OhmerBlank8Background(); blankPanel->box.size = box.size; blankPanel->module = module; addChild(blankPanel); } // This 8 HP module uses 4 screws (may are silver or gold). // Top-left silver screw. topLeftScrewSilver = createWidget<Torx_Silver>(Vec(RACK_GRID_WIDTH, 0)); addChild(topLeftScrewSilver); // Top-right silver screw. topRightScrewSilver = createWidget<Torx_Silver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0)); addChild(topRightScrewSilver); // Bottom-left silver screw. bottomLeftScrewSilver = createWidget<Torx_Silver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)); addChild(bottomLeftScrewSilver); // Bottom-right silver screw. bottomRightScrewSilver = createWidget<Torx_Silver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)); addChild(bottomRightScrewSilver); // Top-left gold screw. topLeftScrewGold = createWidget<Torx_Gold>(Vec(RACK_GRID_WIDTH, 0)); addChild(topLeftScrewGold); // Top-right gold screw. topRightScrewGold = createWidget<Torx_Gold>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0)); addChild(topRightScrewGold); // Bottom-left gold screw. bottomLeftScrewGold = createWidget<Torx_Gold>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)); addChild(bottomLeftScrewGold); // Bottom-right gold screw. bottomRightScrewGold = createWidget<Torx_Gold>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)); addChild(bottomRightScrewGold); } void step() override { OhmerBlank8 *module = dynamic_cast<OhmerBlank8*>(this->module); if (module) { // Torx screws metal (silver, gold) are visible or hidden, depending selected model (from module's context-menu). // Silver Torx screws are visible only for non-"Signature" modules (Classic, Stage Repro or Absolute Night). topLeftScrewSilver->visible = (module->Theme < 3); topRightScrewSilver->visible = (module->Theme < 3); bottomLeftScrewSilver->visible = (module->Theme < 3); bottomRightScrewSilver->visible = (module->Theme < 3); // Gold Torx screws are visible only for "Signature" modules (Dark Signature, Deepblue Signature or Carbon Signature). topLeftScrewGold->visible = (module->Theme > 2); topRightScrewGold->visible = (module->Theme > 2); bottomLeftScrewGold->visible = (module->Theme > 2); bottomRightScrewGold->visible = (module->Theme > 2); } else { // Default panel theme is always "Classic" (beige, using silver screws, using silver button, LCD). // Other panels are, of course, hidden. // By default, silver screws are visible for default beige Classic panel... topLeftScrewSilver->visible = true; topRightScrewSilver->visible = true; bottomLeftScrewSilver->visible = true; bottomRightScrewSilver->visible = true; // ...and, of course, golden screws are hidden. topLeftScrewGold->visible = false; topRightScrewGold->visible = false; bottomLeftScrewGold->visible = false; bottomRightScrewGold->visible = false; } ModuleWidget::step(); } void appendContextMenu(Menu *menu) override { OhmerBlank8 *module = dynamic_cast<OhmerBlank8*>(this->module); menu->addChild(new MenuEntry); OhmerBlank8SubMenuItems *ohmerblank8submenuitems = new OhmerBlank8SubMenuItems; ohmerblank8submenuitems->text = "Model"; ohmerblank8submenuitems->rightText = RIGHT_ARROW; ohmerblank8submenuitems->module = module; menu->addChild(ohmerblank8submenuitems); } }; Model *modelBlankPanel8 = createModel<OhmerBlank8, OhmerBlank8Widget>("OhmerBlank8");
9,260
3,495
#include "AudioManager.h" #include "AudioPlayer.h" #include "glm/detail/func_geometric.inl" #include "Player.h" void AudioManager::AddFile(Sounds::Type sndType, const char* filepath) { //filepaths[sndType] = filepath; //auto ap = AudioPlayerFactory::createFromFile(filepath); AudioPlayer* ap = new AudioPlayer(filepath); if (ap == nullptr) throw; //ap->setFinishListener(this); audioPlayers[sndType] = ap; } AudioManager::AudioManager() { instance = this; AddFile(Jump1, "assets/Sounds/jump1.wav"); AddFile(Jump2, "assets/Sounds/jump2.wav"); AddFile(Jump3, "assets/Sounds/jump3.wav"); AddFile(PlayerDie, "assets/Sounds/laser6.wav"); AddFile(EnemyDie, "assets/Sounds/m_health.wav"); AddFile(Hit, "assets/Sounds/pl_pain6.wav"); AddFile(Shoot, "assets/Sounds/LaserZap04.wav"); AddFile(Ricochet, "assets/Sounds/bulletby02.wav"); AddFile(Ricochet2, "assets/Sounds/bulletby02.wav"); AddFile(Powerup, "assets/Sounds/powerUp8.wav"); AudioPlayer::Loaded(); } AudioManager::~AudioManager() { //filepaths.clear(); instance = nullptr; for (auto i = audioPlayers.begin(); i != audioPlayers.end();) { Sounds::Type sndtype = i->first; AudioPlayer* ap = audioPlayers[sndtype]; i = audioPlayers.erase(i); // update iterator delete ap; } } void AudioManager::Run() { } void Jelly::AudioManager::DoPlaySoundType3D(Sounds::Type sndType, float px, float py, float speed) const { if (sndType == Sounds::NONE) return; auto ppos = Player::instance->GetPosition(); auto pdiff = glm::vec2(ppos.x - px, ppos.y - py); auto dist = glm::length(pdiff); auto dx = (px - ppos.x); auto lr = clamp(static_cast<int>(std::round(dx * 30)), -100, 100); auto vol = clamp(static_cast<int>(std::round(100 - dist * 20)), 0, 100); auto ap = audioPlayers.at(sndType); ap->Play(vol * 0.01f, lr * 0.01f, speed); } void Jelly::AudioManager::DoPlaySoundType2D(Sounds::Type sndType, float speed) const { if (sndType == Sounds::NONE) return; auto ap = audioPlayers.at(sndType); ap->Play(1, 0, speed); }
2,162
848
#include "vm/vm.hpp" #include "capi/19/include/ruby/ruby.h" #include "capi/19/include/ruby/encoding.h" #include "builtin/bytearray.hpp" #include "builtin/encoding.hpp" #include "builtin/fixnum.hpp" #include "builtin/integer.hpp" #include "builtin/nativemethod.hpp" #include "builtin/object.hpp" #include "builtin/string.hpp" #include "capi/capi.hpp" #include <string.h> using namespace rubinius; using namespace rubinius::capi; namespace rubinius { namespace capi { } } extern "C" { VALUE rb_enc_str_new(const char *ptr, long len, rb_encoding *enc) { VALUE str = rb_str_new(ptr, len); rb_enc_associate(str, enc); return str; } VALUE rb_usascii_str_new(const char* ptr, long len) { return rb_enc_str_new(ptr, len, rb_usascii_encoding()); } VALUE rb_usascii_str_new2(const char* ptr) { return rb_enc_str_new(ptr, strlen(ptr), rb_usascii_encoding()); } VALUE rb_external_str_new_with_enc(const char* string, long size, rb_encoding* encoding) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); String* str = String::create(env->state(), string, size); str->taint(env->state()); Encoding* enc = Encoding::find(env->state(), encoding->name); if(enc == Encoding::usascii_encoding(env->state()) && !CBOOL(str->ascii_only_p(env->state()))) { str->encoding(env->state(), Encoding::ascii8bit_encoding(env->state())); } else { str->encoding(env->state(), enc); } // TODO: handle transcoding if necessary return env->get_handle(str); } VALUE rb_external_str_new(const char* string, long size) { return rb_external_str_new_with_enc(string, size, rb_default_external_encoding()); } VALUE rb_external_str_new_cstr(const char* string) { return rb_external_str_new_with_enc(string, strlen(string), rb_default_external_encoding()); } int rb_enc_str_coderange(VALUE string) { // TODO return ENC_CODERANGE_7BIT; } VALUE rb_locale_str_new_cstr(const char *ptr) { // TODO return rb_str_new2(ptr); } VALUE rb_locale_str_new(const char* ptr, long len) { // TODO return rb_str_new(ptr, len); } VALUE rb_str_conv_enc(VALUE str, rb_encoding *from, rb_encoding *to) { // TODO return str; } VALUE rb_str_export_to_enc(VALUE str, rb_encoding *enc) { // TODO return rb_str_conv_enc(str, rb_enc_get(str), enc); } }
2,388
927
/** * @file UnoTransport.cpp * @author Ashwin Natarajan * @brief This file contains the implementation of the protocol and methods specified in UnoTransport.hpp * @version 0.1 * @date 2020-08-30 * * @copyright MIT License Copyright (c) 2020 Ashwin N Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ #include "UnoTransport.hpp" #include <unistd.h> //for close, socket, etc #include <fcntl.h> //for fcntl to set sockets as non blocking #include <poll.h> //for poll() #include <assert.h> //for asserts #include <arpa/inet.h> //for IPv4 related stuff #include <vector> //std::vector #include <stdio.h> //for fprintf, perror, etc #include <sys/timerfd.h> //for timerfd #ifdef UNO_TRANSPORT_DEBUG #include <inttypes.h> //for format specifiers to fixed width integers #endif /**************************************************************************************************************************/ //debug specific macros #ifdef UNO_TRANSPORT_DEBUG #define ANSI_COLOR_RED "\x1b[31m" #define ANSI_COLOR_GREEN "\x1b[32m" #define ANSI_COLOR_YELLOW "\x1b[33m" #define ANSI_COLOR_BLUE "\x1b[34m" #define ANSI_COLOR_MAGENTA "\x1b[35m" #define ANSI_COLOR_CYAN "\x1b[36m" #define ANSI_COLOR_RESET "\x1b[0m" #define UNO_DBG_PREFIX ANSI_COLOR_RED "<====================>" #define UNO_DBG_SUFFIX "<====================>" ANSI_COLOR_RESET "\n" #endif #ifndef UNO_TRANSPORT_DEBUG #define NDEBUG //remove asserts if the debug macro is not set #endif /**************************************************************************************************************************/ //general purpose macros #define UNO_CLEAR_BIT(x,n) ((x) & ~(1UL << n)) #define UNO_SET_BIT(x,n) ((x) | (1UL << n) ) #define UNO_IS_BIT_SET(x,n) ((x) & (1UL <<n)) #define UNO_SEC_TO_NS(x) ((x) * 1000 * 1000 * 1000) #define UNO_MS_TO_NS(x) ((x) * 1000 * 1000) #define UNO_MS_TO_SEC(x) ((x) / 1000) #define UNO_NS_TO_SEC(x) ((x) / (1000 * 1000 * 1000)) /**************************************************************************************************************************/ //the version of this protocol #define UNO_TRANSPORT_PROTO_VER 1 /**************************************************************************************************************************/ //header fields lengths #define UNO_TRANSPORT_HDR_SEQ_LEN 2 #define UNO_TRANSPORT_HDR_RC_LEN 1 #define UNO_TRANSPORT_HDR_PROTO_VER_LEN 1 #define UNO_TRANSPORT_HDR_CMD_LEN 1 #define UNO_TRANSPORT_HDR_MSG_LEN_LEN 2 /**************************************************************************************************************************/ //header fields positions #define UNO_TRANSPORT_HDR_SEQ_POS 0 #define UNO_TRANSPORT_HDR_RC_POS 2 #define UNO_TRANSPORT_HDR_PROTO_VER_POS 3 #define UNO_TRANSPORT_HDR_CMD_POS 4 #define UNO_TRANSPORT_HDR_MSG_LEN_POS 5 /**************************************************************************************************************************/ //general purpose header related macros #define UNO_SEQ_ID_RESET 0 #define UNO_TRANSPORT_CTRL_MSG_MAX_SIZE (10) /**************************************************************************************************************************/ //the below are the bits that are supported in the control flag, the number is their position #define UNO_TRANSPORT_CMD_CONTROL_MSG (0) #define UNO_TRANSPORT_CMD_RELIABLE_MSG (1) #define UNO_TRANSPORT_CMD_ACK_MSG (2) #define UNO_TRANSPORT_CMD_SPL_MSG (3) //a special msg is one that will be passed to the app layer without any header //or connection validation, should be used for discovery, control msg flag must //not be set //In a control command, extra info will be placed on the data section of the message. // the first byte will be the command ID, followed by data specific to that command. // commands must be very simple /** * @brief The command ID for connection request. This command is used for both opening and closing connections There will be one byte of additional data byte 1 = mode 0 = conn open req 1 = conn close req by client 2 = conn close req by server (explicit, server wants the client gone) 3 = conn close req by server (timeout) * */ #define UNO_TRANSPORT_CTRL_CONN_REQ (1) #define UNO_TRANSPORT_CTRL_CONN_REQ_LEN (2) #define UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_OPEN (0) #define UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_CLIENT_REQ (1) #define UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_EXPL (2) #define UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_TO (3) /** * @brief The command ID for connection response. Additional data for connection response (if successful) There will be no additional data (msg len = 0) if the server is full bytes 1,2 = port number (in nwk byte order) bytes 3,4 = keepalive interval in ms (in nwk byte order) * */ #define UNO_TRANSPORT_CTRL_CONN_RSP (2) #define UNO_TRANSPORT_CTRL_CONN_RSP_LEN (5) /** * @brief The command ID for error status. Additional data: byte = status code, depends on command, full list to be populated here * */ #define UNO_TRANSPORT_CTRL_ERR_RSP (3) #define UNO_TRANSPORT_CTRL_ERR_RSP_LEN (2) /** * @brief The command ID for connection keep alive. There is no additioanl data for this * */ #define UNO_TRANSPORT_CTRL_KEEPALIVE (4) #define UNO_TRANSPORT_CTRL_KEEPALIVE_LEN (1) /** * @brief The command ID for the connection closed command. This will only be sent by the server There will be 1 byte of additional data byte 1 = reason 0 = close requested by client 1 = timedout 2 = explicit close notified by server (the caller doesn't like this client) * */ #define UNO_TRANSPORT_CTRL_CONN_CLOSED (5) #define UNO_TRANSPORT_CTRL_CONN_CLOSED_LEN (2) #define UNO_TRANSPORT_CTRL_CONN_CLOSED_OPT_REQ (0) #define UNO_TRANSPORT_CTRL_CONN_CLOSED_OPT_TIMEDOUT (1) #define UNO_TRANSPORT_CTRL_CONN_CLOSED_OPT_EXPL (2) /**************************************************************************************************************************/ /* HEADER FORMAT - drawn using the awesome website http://asciiflow.com/ +--------------------------------+----------+-------------------------------------+ | seq id |retry |proto.| cmd | msg len | data | | |count |Ver | | | | +------------------------+-------+----------+-------------------------------------+ 0 2 3 4 5 6 NOTE: all multibyte fields will be in nwk byte order */ /**************************************************************************************************************************/ /** * @brief This struct will hold the header in an easily accessible form. also supports serialisation and deserialisation * */ struct uno_hdr { public: uint16_t seq_id; //sequence id uint8_t rc; //retry count uint8_t proto_ver; //protocol version uint8_t cmd; //command flags uint16_t msg_len; //message length /** * @brief Construct a new uno hdr object with everything set to 0 * */ uno_hdr (void) { seq_id = 0; rc = 0; proto_ver = UNO_TRANSPORT_PROTO_VER; cmd = 0; msg_len = 0; } /** * @brief Construct a new uno hdr object by deserialising the given flag buffer containing the header * * @param hdr pointer to the buffer containing the header */ uno_hdr (const uint8_t *hdr) { deserialise (hdr); } /** * @brief Construct a new uno hdr object using the given paramters * * @param seq_id * @param cmd * @param msg_len */ uno_hdr (uint16_t seq_id, uint8_t cmd, uint16_t msg_len) { this->seq_id = seq_id; this->cmd = cmd; this->msg_len = msg_len; this->rc = 0; this->proto_ver = UNO_TRANSPORT_PROTO_VER; } /** * @brief Construct a new uno hdr object. copy the values of x into this * * @param x the object to copy from */ uno_hdr (const uno_hdr &x) { seq_id = x.seq_id; rc = x.rc; proto_ver = x.proto_ver; cmd = x.cmd; msg_len = x.msg_len; } /** * @brief serialise this struct into the given buffer * * @param hdr the buffer to which the data is to be serialised, which is assumed to be not nullptr and large enough */ void serialise (uint8_t *hdr) { //2 bytes seq_id in nwk byte order hdr[UNO_TRANSPORT_HDR_SEQ_POS+0] = (this->seq_id >> 8) & 0xFF; hdr[UNO_TRANSPORT_HDR_SEQ_POS+1] = (this->seq_id >> 0) & 0xFF; //1 byte reboot count hdr[UNO_TRANSPORT_HDR_RC_POS] = this->rc; //1 byte proto ver hdr[UNO_TRANSPORT_HDR_PROTO_VER_POS]= UNO_TRANSPORT_PROTO_VER; //1 byte cmd info hdr[UNO_TRANSPORT_HDR_CMD_POS] = this->cmd; //2 bytes msg len hdr[UNO_TRANSPORT_HDR_MSG_LEN_POS+0]= (this->msg_len >> 8) & 0xFF; hdr[UNO_TRANSPORT_HDR_MSG_LEN_POS+1]= (this->msg_len >> 0) & 0xFF; } /** * @brief deserialise from the given buffer into this hdr struct * * @param hdr the buffer containing the header, which is assumed to be not nullptr and large enough */ void deserialise (const uint8_t *hdr) { //2 byte seq in nwk byte order seq_id = 0; seq_id |= hdr[UNO_TRANSPORT_HDR_SEQ_POS+0] << 8; seq_id |= hdr[UNO_TRANSPORT_HDR_SEQ_POS+1] << 0; //1 byte reboot count rc = hdr[UNO_TRANSPORT_HDR_RC_POS]; //1 byte proto ver proto_ver= hdr[UNO_TRANSPORT_HDR_PROTO_VER_POS]; //1 byte cmd info cmd = hdr[UNO_TRANSPORT_HDR_CMD_POS]; //2 byte msg len - in nwk byte order msg_len = 0; msg_len |= hdr[UNO_TRANSPORT_HDR_MSG_LEN_POS+0] << 8; msg_len |= hdr[UNO_TRANSPORT_HDR_MSG_LEN_POS+1] << 0; } /** * @brief checks if this header is valid or out of order or duplicate * * @param exp_seq the expected sequence number * @return ret returns true if valid */ bool is_valid (uint16_t exp_seq) { return true; } }; /** * @brief This struct is the wrapper for the timer that will be used in this code. Currently, it uses the linux timerfd * */ struct uno_timer { public: int fd; bool is_armed; struct itimerspec last_config; /** * @brief Construct a new uno timer object. Creates the fd and initialises the fields * */ uno_timer (void) { //create the fd fd = timerfd_create (CLOCK_MONOTONIC, 0); if(fd == UNO_TRANSPORT_ERR) { //raise exception ; } is_armed = false; memset (&last_config, 0, sizeof(last_config)); } /** * @brief Destroy the uno timer object. Closes the fd and clears the fields * */ ~uno_timer (void) { is_armed = false; memset (&last_config, 0, sizeof(last_config)); close(fd); fd = UNO_TRANSPORT_ERR; } /** * @brief - sets the timer of this object * * @param timer_val - the const struct timespec structure containing the timer delay value * @return int - returns 0 on success, UNO_TRANSPORT_ERR on failure */ int arm_non_recurring (const struct timespec &timer_val) { assert (timer_val.tv_sec>0 && timer_val.tv_nsec>0); struct itimerspec val = {{0,},}; val.it_value.tv_sec = timer_val.tv_sec; val.it_value.tv_nsec = timer_val.tv_nsec; //arm the timer with the given value int ret = timerfd_settime (fd, 0, &val, NULL); if(ret == UNO_TRANSPORT_ERR) { perror("timerfd_settime"); } else { //update the fields of the struct is_armed = true; memcpy (&last_config, &val, sizeof(val)); } return ret; } /** * @brief - clears the timer of this object * * @return int - returns 0 on success, UNO_TRANSPORT_ERR on failure */ int disarm (void) { //just returned if not armed if(is_armed == false) { return 0; } struct itimerspec val = {{0,},}; //disarm the timer int ret = timerfd_settime (fd, 0, &val, NULL); if(ret == UNO_TRANSPORT_ERR) { perror("timerfd_settime"); } else { //update the fields of the struct is_armed = false; memcpy (&last_config, &val, sizeof(val)); } return ret; } }; /** * @brief the enum class of the msg types in the cmd field of the header * */ enum class _uno_msg_type { UNO_MSG_CTRL, UNO_MSG_ACK, UNO_MSG_DATA, UNO_MSG_SPL, UNO_MSG_UNKNOWN, }; /**************************************************************************************************************************/ //static function declarations - descriptions will be placed above the definitions static int _uno_create_client_fd (int broadcast); static int _uno_create_server_fd (uint16_t port); static ssize_t _uno_send (int fd, uint8_t *hdr, const void *msg, size_t len, const struct sockaddr_in *dst, uint16_t *seq); static ssize_t _uno_timed_recv (int fd, uint8_t *hdr, void *buffer, size_t buffer_size, int flags, struct sockaddr_in *src, int to_ms); static ssize_t _uno_recv (int fd, uint8_t *hdr, void *buffer, size_t buffer_size, int flags, struct sockaddr_in *src); static _uno_msg_type _uno_get_msg_type (uint8_t cmd); static void _create_new_connection (int fd, std::list<UnoConnection> &client_list, const struct sockaddr_in &src, uno_hdr &hdr, uint16_t ka_dur, uint8_t max_conn, const struct timespec &curr_time); static int _uno_get_port_from_fd (int fd); static int _uno_process_server_msg (int fd, uno_hdr &hdr, uint8_t *buffer, ssize_t bytes, std::list<UnoConnection> &client_list, uint16_t ka_dur, const struct sockaddr_in &src, uint8_t max_conn, const struct timespec &curr_time, bool &is_spl); static int _uno_process_client_msg (int fd, uno_hdr &hdr, uint8_t *buffer, ssize_t bytes, std::list<UnoConnection> &client_list, const struct sockaddr_in &src); static int _uno_send_server_full_rsp (int fd, const struct sockaddr_in &src, uno_hdr &hdr); static int _uno_send_conn_close (int fd, const struct sockaddr_in &dst, uint16_t *seq); static void _uno_close_connection_requested (int fd, std::list<UnoConnection> &client_list); static void _uno_close_connection_requested_iter (std::list<UnoConnection>::iterator iter, std::list<UnoConnection> &client_list); static std::list<UnoConnection>::iterator _find_client_in_list (std::list<UnoConnection> &client_list, const struct sockaddr_in &dst); static std::list<UnoConnection>::iterator _find_client_in_list (std::list<UnoConnection> &client_list, int fd); static int _uno_client_process_recv_msg (uno_hdr &hdr, uint8_t *buffer, ssize_t bytes, uint16_t &server_seq); static int _uno_send_reliable (int fd, uint8_t *hdr_ser, const void *msg, size_t len, const struct sockaddr_in &dst, uint16_t *seq, uint8_t max_retries, uint16_t retry_interval); static bool _uno_is_reliable_msg (uint8_t cmd_flags); static int _uno_send_ack (int fd, const struct sockaddr_in &dst, const uno_hdr &hdr); static bool _is_seq_valid (int fd, uint16_t inc_seq, uint16_t &saved_seq); static int _uno_send_conn_close_expl (int fd, const struct sockaddr_in &dst, uint16_t *seq); static int _uno_send_conn_close_to (int fd, const struct sockaddr_in &dst, uint16_t *seq); static std::list<UnoConnection>::iterator _uno_find_most_stale_connection (std::list<UnoConnection> &client_list); static void _uno_compute_timer_value (const struct timespec &last_msg_time, uint16_t keepalive_dur, const struct timespec &curr_time, struct timespec &_timer_val); /**************************************************************************************************************************/ //code specific to UnoConnection /** * @brief Construct a new Uno Connection object * * @param fd The fd of the already created socket * @param cli reference to the struct socakddr_in holding the client's IPv4 addr * @param hdr reference to the structure containing the deserialised header * @param ka_dur the keep alive interval * @param curr_time const reference to the struct containing the curr time, this value is used as the initial value for last_msg_time */ UnoConnection :: UnoConnection (int fd, const struct sockaddr_in &cli, uno_hdr &hdr, uint16_t ka_dur, const struct timespec &curr_time) { this->fd = _uno_create_client_fd (false); if(this->fd == UNO_TRANSPORT_ERR) { ; //throw exception here } //get the self addr info from the fd int temp = _uno_get_port_from_fd (this->fd); if(temp == UNO_TRANSPORT_ERR) { //throw exception here } self_port = (uint16_t) temp; //update in structures memcpy (&cli_addr, &cli, sizeof(cli_addr)); //send the new connection info to the client using the argument fd this->connected = true; this->send_connect_rsp (hdr, ka_dur); this->client_seq = 0; this->close_reason = _close_reason::CLOSE_REASON_UNKNOWN; //set the last msg time as the provided curr time memcpy (&(this->last_msg_time), &curr_time, sizeof(curr_time)); #ifdef UNO_TRANSPORT_DEBUG fprintf (stderr, UNO_DBG_PREFIX "created new connection fd=%d port=%" PRIu16 " tv_sec=%ld tv_nsec=%ld" UNO_DBG_SUFFIX, this->fd, self_port, this->last_msg_time.tv_sec, this->last_msg_time.tv_nsec); #endif } /** * @brief Construct a new Uno Connection object by copying the given one * * @param the object from which this one is to be copied from */ UnoConnection :: UnoConnection (const UnoConnection &cpy) { this->fd = cpy.fd; this->self_port = cpy.self_port; memcpy (&(this->cli_addr), &(cpy.cli_addr), sizeof(cpy.cli_addr)); this->client_seq = 0; memset(&(this->last_msg_time), 0, sizeof(this->last_msg_time)); this->connected = cpy.connected; this->close_reason = cpy.close_reason; } /** * @brief Destroy the Uno Connection object. Sends connection close req to the client if the client is still connected * */ UnoConnection :: ~UnoConnection (void) { #ifdef UNO_TRANSPORT_DEBUG fprintf(stderr, UNO_DBG_PREFIX "in UnoConnection destructor for fd=%d: connected=%d" UNO_DBG_SUFFIX, fd, connected); #endif if(this->connected) { assert (this->close_reason != _close_reason::CLOSE_REASON_UNKNOWN); switch(this->close_reason) { //no need to send anything if close was requested by client case _close_reason::CLOSE_REASON_REQUESTED_BY_CLIENT: break; //send explicit connection closure message case _close_reason::CLOSE_REASON_REQUESTED_BY_SERVER: _uno_send_conn_close_expl (this->fd, this->cli_addr, nullptr); break; //send connection timedout message case _close_reason::CLOSE_REASON_TIMEDOUT: _uno_send_conn_close_to (this->fd, this->cli_addr, nullptr); break; case _close_reason::CLOSE_REASON_UNKNOWN: assert (0); break; } this->connected = false; this->close_reason = _close_reason::CLOSE_REASON_UNKNOWN; } close (this->fd); this->fd = UNO_TRANSPORT_ERR; this->connected = false; memset (&(this->self_port), 0, sizeof(this->self_port)); memset (&(this->cli_addr), 0, sizeof(this->cli_addr)); this->client_seq = 0; memset(&(this->last_msg_time), 0, sizeof(this->last_msg_time)); } /** * @brief Sends a connection response to the device sending the connection request * * @param hdr info in the header struct * @param ka_dur the keepalive duration * @return int retuns number of bytes sent on success, UNO_TRANSPORT_ERR on failure */ int UnoConnection :: send_connect_rsp (uno_hdr &hdr, uint16_t ka_dur) { uint8_t data[UNO_TRANSPORT_CTRL_CONN_RSP_LEN] = {0,}; //cmd id data[0] = UNO_TRANSPORT_CTRL_CONN_RSP; //port number - in nwk byte order data[1] = (self_port >> 8) & 0xFF; data[2] = (self_port >> 0) & 0xFF; //keep alive - in nwk byte order data[3] = (ka_dur >> 8) & 0xFF; data[4] = (ka_dur >> 0) & 0xFF; hdr.msg_len = sizeof(data); uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN]; hdr.serialise(hdr_ser); return _uno_send (fd, hdr_ser, data, sizeof(data), &cli_addr, NULL); } /** * @brief Set the close reason variable * * @param reason */ void UnoConnection :: set_close_reason (_close_reason reason) { this->close_reason = reason; } /**************************************************************************************************************************/ //code specific to UnoTransportClient /** * @brief The default constructor for the client class, creates a UDP socket at a random port * * @return UnoTransportClient */ UnoTransportClient :: UnoTransportClient (void) { fd = _uno_create_client_fd (0); if(fd == UNO_TRANSPORT_ERR) { //raise exception here } #ifdef UNO_TRANSPORT_DEBUG fprintf (stderr, UNO_DBG_PREFIX "created client with fd = %d broadcast = 0" UNO_DBG_SUFFIX, fd); #endif seq = 0; memset (&addr, 0, sizeof(addr)); can_broadcast = false; connected = false; self_port = (uint16_t) _uno_get_port_from_fd (fd); } /** * @brief Constructor with capability to create a broadcast socket. * * @param broadcast set this to true if you want the socket to be able to broadcast * @return UnoTransportClient N/A */ UnoTransportClient :: UnoTransportClient (bool broadcast) { //create a socket with broadcast permissions int opt = (broadcast==true) ? (1) : (0); fd = _uno_create_client_fd (opt); if(fd == -1) { //raise exception here } #ifdef UNO_TRANSPORT_DEBUG fprintf (stderr, UNO_DBG_PREFIX "created client with fd = %d broadcast = %d" UNO_DBG_SUFFIX, fd, broadcast); #endif //initialise other fields seq = 0; memset (&addr, 0, sizeof(addr)); can_broadcast = broadcast; connected = false; self_port = (uint16_t) _uno_get_port_from_fd (fd); } /** * @brief Destructor for the client class, will close the socket and reset all other fields * * @return UnoTransportClient N/A */ UnoTransportClient :: ~UnoTransportClient (void) { //if connected, disconnect if(connected) { #ifdef UNO_TRANSPORT_DEBUG fprintf (stderr, UNO_DBG_PREFIX "closing connection in client destructor. fd=%d conn_port=%" PRIu16 UNO_DBG_SUFFIX, fd, ntohs(addr.sin_port)); #endif _uno_send_conn_close (fd, addr, &seq); } //close the socket if(fd != UNO_TRANSPORT_ERR) { close (fd); fd = UNO_TRANSPORT_ERR; } #ifdef UNO_TRANSPORT_DEBUG fprintf (stderr, UNO_DBG_PREFIX "destroyed client" UNO_DBG_SUFFIX); #endif //clear other fields seq = 0; memset (&addr, 0, sizeof(addr)); can_broadcast = false; connected = false; self_port = 0; } /** * @brief get the port number of the connection (on the server side) (TO BE REMOVED) * * @return uint16_t the port number value */ uint16_t UnoTransportClient :: _dbg_get_port (void) { return ntohs(this->addr.sin_port); } /** * @brief get the port number of the client side socket (TO BE REMOVED) * * @return uint16_t the port number */ uint16_t UnoTransportClient :: _dbg_get_self_port (void) { return self_port; } /** * @brief Connect to the specified server * * @param dst - reference to the struct sockaddr_in instance containing the server's IPv4 address * @param to_ms - the timeout in milliseconds * @return int - 0 if successful, UNO_TRANSPORT_ERR if failed */ int UnoTransportClient :: connect (const struct sockaddr_in &dst, int to_ms) { struct sockaddr_in src; uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,}; uint8_t cmd_flags = 0; //this is the data section for the connection request command uint8_t data[UNO_TRANSPORT_CTRL_CONN_REQ_LEN]; data[0] = UNO_TRANSPORT_CTRL_CONN_REQ; //command id data[1] = UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_OPEN; //command mode //set the control msg bit in the cmd field of the hdr and serialise the hdr cmd_flags = UNO_SET_BIT(cmd_flags, UNO_TRANSPORT_CMD_CONTROL_MSG); uno_hdr hdr (seq, cmd_flags, sizeof(data)); //send this msg out hdr.serialise (hdr_ser); int ret = _uno_send (this->fd, hdr_ser, data, sizeof(data), &dst, &seq); #ifdef UNO_TRANSPORT_DEBUG fprintf(stderr, UNO_DBG_PREFIX "sent connection req %d bytes to fd=%d port %hu" UNO_DBG_SUFFIX, ret, this->fd, ntohs(dst.sin_port)); #endif //todo - check source address, and continue waiting if interrupted by other message if(ret != UNO_TRANSPORT_ERR) { memset (&src, 0, sizeof(src)); memset (hdr_ser, 0, sizeof(hdr_ser)); uint8_t data[UNO_TRANSPORT_CTRL_MSG_MAX_SIZE] = {0,}; ret = _uno_timed_recv (this->fd, hdr_ser, data, sizeof(data), MSG_WAITALL, &src, to_ms); hdr.deserialise (hdr_ser); //process connection response if(_uno_get_msg_type(hdr.cmd) == _uno_msg_type::UNO_MSG_CTRL && data[0] == UNO_TRANSPORT_CTRL_CONN_RSP) { //if msg len is 1, then the server is full/connection refused if(hdr.msg_len == 1) { ret = UNO_TRANSPORT_CONN_REFUSED; #ifdef UNO_TRANSPORT_DEBUG fprintf(stderr, UNO_DBG_PREFIX "received conn refused" UNO_DBG_SUFFIX); #endif } else { //save the connection details memcpy (&(this->addr), &src, sizeof(src)); //2 byte port in nwk byte order, save port in nwk byte order memcpy (&(this->addr.sin_port), data+1, 2); //2 byte keepalive duration in nwk byte order this->keepalive_dur = 0; this->keepalive_dur |= (data[3] << 8); this->keepalive_dur |= (data[4] << 0); #ifdef UNO_TRANSPORT_DEBUG fprintf(stderr, UNO_DBG_PREFIX "received connection rsp %d bytes fd=%d port=%" PRIu16 " ka=%" PRIu16 UNO_DBG_SUFFIX, ret, this->fd, ntohs(this->addr.sin_port), this->keepalive_dur); #endif ret = 0; connected = true; } } } return ret; } /** * @brief Send a mesage to the server that this client is connected to * * @param msg - void pointer to the mesage * @param len - length of the message * @return int - returns UNO_TRANSPORT_ERR on failure, or number of bytes sent on success */ int UnoTransportClient :: send_msg (const void *msg, size_t len) { assert (msg!=nullptr); assert (len<=UNO_TRANSPORT_MTU); if(msg==nullptr || len > UNO_TRANSPORT_MTU) { return UNO_TRANSPORT_ERR; } if(this->connected==false) { return UNO_TRANSPORT_ERR; } uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,}; // uint8_t cmd_flags = 0; uno_hdr hdr (seq, 0, len); hdr.serialise (hdr_ser); int ret = _uno_send (this->fd, hdr_ser, msg, len, &addr, &seq); #ifdef UNO_TRANSPORT_DEBUG fprintf(stderr, UNO_DBG_PREFIX "send message of len=%d through fd=%d: ret=%d" UNO_DBG_SUFFIX, len, this->fd, ret); #endif return ret; } /** * @brief Sends the given message to the server, expects an ACK from the server. * * @param msg - void pointer to the message * @param len - length of the message * @return int - returns -> positive number of bytes on successful reliable send -> 0 if the message was sent successfully, but no ACK was received -> UNO_TRANSPORT_ERR on general failure */ int UnoTransportClient :: send_msg_reliable (const void *msg, size_t len) { assert (msg!=nullptr); assert (len<=UNO_TRANSPORT_MTU); if(msg==nullptr || len > UNO_TRANSPORT_MTU) { return UNO_TRANSPORT_ERR; } if(this->connected==false) { return UNO_TRANSPORT_ERR; } //need to set the reliable msg bit in the cmd section of the header uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,}; uint8_t cmd_flags = 0; cmd_flags = UNO_SET_BIT (cmd_flags, UNO_TRANSPORT_CMD_RELIABLE_MSG); uno_hdr hdr (seq, cmd_flags, len); hdr.serialise (hdr_ser); int ret; //send out the message ret = _uno_send_reliable (this->fd, hdr_ser, msg, len, addr, &seq, UNO_TRANSPORT_REL_MAX_RETRIES, UNO_TRANSPORT_REL_RETRY_INT_MS); #ifdef UNO_TRANSPORT_DEBUG fprintf(stderr, UNO_DBG_PREFIX "sen reliable message of len=%d through fd=%d: ret=%d" UNO_DBG_SUFFIX, len, this->fd, ret); #endif if(ret == UNO_TRANSPORT_CONN_CLOSE_RECVD) { //close the socket and clear all fields close(this->fd); memset (&(this->addr), 0, sizeof(this->addr)); this->seq = 0; this->server_seq = 0; this->connected = 0; this->can_broadcast = 0; this->self_port = 0; } return ret; } /** * @brief Receives a message from the connected server into the specified server * * @param buffer - The buffer where the message is to be written * @param buffer_size - The size of this buffer * @param to_ms - The timeout in milliseconds * @return int - The number of bytes received */ int UnoTransportClient :: recv_msg (void *buffer, size_t buffer_size, int to_ms) { if(buffer == nullptr || buffer_size == 0) { return UNO_TRANSPORT_ERR; } if(connected == false) { return UNO_TRANSPORT_CLIENT_NOT_CONN; } uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN]; bool exit_condition = false; ssize_t bytes; int ret = UNO_TRANSPORT_ERR; uno_hdr hdr; //loop until we get a message intended for the caller while(!exit_condition) { memset (hdr_ser, 0, sizeof(hdr_ser)); /* TODO - reduce to_ms after every iteration of the loop, the whole function should not take more than to_ms milliseconds. This current version will keep waiting to_ms milliseconds on every iteration */ bytes = _uno_timed_recv (this->fd, hdr_ser, buffer, buffer_size, MSG_WAITALL, NULL, to_ms); //timedout if(bytes == 0) { ret = 0; break; } //every message must be atleast UNO_TRANSPORT_HDR bytes long if(bytes < UNO_TRANSPORT_HDR_LEN) { //drop the messsage, continue continue; } //check the validity of the sequence number if(_is_seq_valid (this->fd, hdr.seq_id, server_seq) == false) { //drop the packet; continue; } //send ack if reliable message hdr.deserialise (hdr_ser); if(_uno_is_reliable_msg(hdr.cmd)) { _uno_send_ack (this->fd, addr, hdr); } //process the message, now that we know it has a valid fmt bytes = _uno_client_process_recv_msg (hdr, static_cast<uint8_t*>(buffer), bytes, server_seq); if(bytes == UNO_TRANSPORT_CONN_CLOSE_RECVD) { #ifdef UNO_TRANSPORT_DEBUG fprintf(stderr, UNO_DBG_PREFIX "received conn close req from server" UNO_DBG_SUFFIX); #endif ret = (int)bytes; exit_condition = true; //close the socket and clear all fields close(this->fd); memset (&(this->addr), 0, sizeof(this->addr)); this->seq = 0; this->server_seq = 0; this->connected = 0; this->can_broadcast = 0; this->self_port = 0; } //if unknown message, ignore and continue waiting else if (bytes == UNO_TRANSPORT_ERR) { continue; } //for positive bytes, this is a data message that is to be delivered to the caller else if (bytes > 0) { ret = (int) (bytes - UNO_TRANSPORT_HDR_LEN); } //ack messages should not be caught in this function, drop them else { // assert (false && "this should never happen"); continue; } exit_condition = true; } return ret; } /** * @brief - Sends a keepalive message to the server * * @return int - returns 0 on success, UNO_TRANSPORT_ERR on failure, UNO_TRANSPORT_CLIENT_NOT_CONN if not connected */ int UnoTransportClient :: send_keepalive (void) { if(connected == false) { return UNO_TRANSPORT_CLIENT_NOT_CONN; } uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,}; uint8_t cmd_flags = 0; //this is the data section for the connection request command uint8_t data[UNO_TRANSPORT_CTRL_KEEPALIVE_LEN]; data[0] = UNO_TRANSPORT_CTRL_KEEPALIVE; //command id //set the control msg bit in the cmd field of the hdr and serialise the hdr cmd_flags = UNO_SET_BIT(cmd_flags, UNO_TRANSPORT_CMD_CONTROL_MSG); uno_hdr hdr (seq, cmd_flags, sizeof(data)); //send this msg out hdr.serialise (hdr_ser); int ret = _uno_send (this->fd, hdr_ser, data, sizeof(data), &addr, &seq); #ifdef UNO_TRANSPORT_DEBUG fprintf(stderr, UNO_DBG_PREFIX "sent keepalive ret=%d, fd=%d port %hu" UNO_DBG_SUFFIX, ret, this->fd, ntohs(addr.sin_port)); #endif return (ret==UNO_TRANSPORT_ERR) ? (UNO_TRANSPORT_ERR) : (0); } /**************************************************************************************************************************/ //code specific to the UnoTransportServer class /** * @brief Construct a new Uno Transport Server object. Does not create a socket * */ UnoTransportServer :: UnoTransportServer(void) { //intialise all fields, don't create socket without port specified fd = UNO_TRANSPORT_ERR; seq = 0; keepalive_dur = UNO_TRANSPORT_KEEPALIVE_INT; max_conn = UNO_TRANSPORT_DFL_MAX_CONN; #ifdef UNO_TRANSPORT_DEBUG fprintf (stderr, UNO_DBG_PREFIX "created server WITHOUT socket" UNO_DBG_SUFFIX); #endif // client_list.reserve (max_conn); } /** * @brief Construct a new Uno Transport Server object. Creates a socket with the specified port * * @param port - the port number of this server socket */ UnoTransportServer :: UnoTransportServer(uint16_t port) { keepalive_dur = UNO_TRANSPORT_KEEPALIVE_INT; max_conn = UNO_TRANSPORT_DFL_MAX_CONN; create_socket (port); #ifdef UNO_TRANSPORT_DEBUG fprintf (stderr, UNO_DBG_PREFIX "created server at port=%hu" UNO_DBG_SUFFIX, port); #endif seq = 0; } /** * @brief Construct a new Uno Transport Server object. Creates a socket with the specified port * * @param port - the port number of this server socket * @param max_connections - the max number of connections supported by this socket */ UnoTransportServer :: UnoTransportServer (uint16_t port, uint8_t max_connections) { keepalive_dur = UNO_TRANSPORT_KEEPALIVE_INT; max_conn = max_connections; create_socket (port); #ifdef UNO_TRANSPORT_DEBUG fprintf (stderr, UNO_DBG_PREFIX "created server at port=%hu" UNO_DBG_SUFFIX, port); #endif seq = 0; } /** * @brief Destroy the Uno Transport Server object. Sends connection close message to all connected clients and closes the server side socket * */ UnoTransportServer :: ~UnoTransportServer(void) { //close the socket if(fd != UNO_TRANSPORT_ERR) { close (fd); fd = UNO_TRANSPORT_ERR; } #ifdef UNO_TRANSPORT_DEBUG fprintf (stderr, UNO_DBG_PREFIX "destroyed server" UNO_DBG_SUFFIX); #endif //clear other fields seq = 0; } /** * @brief Create a socket object at the specified port * * @param port - the port number of this server socket * @return int - the fd number */ int UnoTransportServer :: create_socket (uint16_t port) { fd = _uno_create_server_fd (port); if(fd == UNO_TRANSPORT_ERR) { return fd; } seq = 0; return 0; } /** * @brief Receives the incoming message in the specified buffer. Does not bother the caller with the protocol specific packets. Handles connection requests, acks, etc * * @param buffer - the buffer to store the incoming msg * @param buffer_size - the size of this buffer * @param src - optional pointer to the struct sockaddr_in object where the source address is to be filled in * @param is_spl - reference to the bool variable that will be set if the incoming message is a spl message * @return int - number of bytes received */ int UnoTransportServer :: recv_msg (void *buffer, size_t buffer_size, struct sockaddr_in *src_arg, bool &is_spl) { uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,}; struct sockaddr_in src = {0,}; std::vector<struct pollfd> pfds; ssize_t bytes; bool exit_condition=false; int success_count=0; int ret; uno_hdr hdr; struct timespec curr_time; uno_timer timer; static std::list<UnoConnection>::iterator _most_stale; struct timespec _timer_val; while(!exit_condition) { timer.disarm(); //clear all data structures pfds.clear(); //this can probably be optimised memset (&src, 0, sizeof(src)); memset (hdr_ser, 0, sizeof(hdr_ser)); //build the vector for poll //first fd is always the server fd pfds.push_back ({.fd = this->fd, .events = POLLIN}); //note down curr time - we use clock monotonic here because we're not bothered about the actual time clock_gettime (CLOCK_MONOTONIC, &curr_time); //find the connection that is going to timeout first _most_stale = _uno_find_most_stale_connection (client_list); if(_most_stale != client_list.end()) { //determine the time remaining till timeout memset (&_timer_val, 0, sizeof(_timer_val)); _uno_compute_timer_value (_most_stale->last_msg_time, keepalive_dur, curr_time, _timer_val); timer.arm_non_recurring (_timer_val); } //second fd will be the timer fd - it does nothing if it is not armed, so no issue pfds.push_back ({.fd = timer.fd, .events = POLLIN}); //add the other fd's after this for(auto iter=this->client_list.begin(); iter!=this->client_list.end(); ++iter) { pfds.push_back ({.fd = iter->fd, .events = POLLIN}); } #ifdef UNO_TRANSPORT_DEBUG fprintf (stderr, UNO_DBG_PREFIX "pollfd structure has %d fd's" UNO_DBG_SUFFIX, pfds.size()); #endif //poll on this set of fd's ret = poll (pfds.data(), pfds.size(), UNO_TRANSPORT_TIMEOUT_INFINITE); if(ret == UNO_TRANSPORT_ERR) { perror("poll"); exit_condition = true; } else if (ret == 0) { //this must never happen since we're polling for an indefinite time period assert (false && "This must never happen"); } else { //note down curr time - to minimise number of syscalls clock_gettime (CLOCK_MONOTONIC, &curr_time); //read from all fd's with data success_count = 0; int index=0; for(auto iter=pfds.begin(); iter!=pfds.end(), success_count!=ret; index++, iter++) { //ding ding ding, we have a winner!!! if((iter->revents) & POLLIN) { //check if this fd is the timer fd if(iter->fd == timer.fd) { assert (_most_stale != this->client_list.end()); //then close the most stale connection _most_stale->set_close_reason (_close_reason::CLOSE_REASON_TIMEDOUT); _uno_close_connection_requested_iter (_most_stale, client_list); break; } //receive data from this fd bytes = _uno_recv (iter->fd, hdr_ser, buffer, buffer_size, MSG_WAITALL, &src); success_count++; //the message must atleast by UNO_TRANSPORT_HDR_LEN bytes if(bytes < UNO_TRANSPORT_HDR_LEN) { //invalid msg, drop the packet continue; } //deserialise the header hdr.deserialise (hdr_ser); //check if reliable msg if(_uno_is_reliable_msg(hdr.cmd)) { _uno_send_ack (this->fd, src, hdr); } //check if fd that's ready is the server fd if(iter==pfds.begin()) { bytes = _uno_process_server_msg (iter->fd, hdr, static_cast<uint8_t*>(buffer), bytes, this->client_list, this->keepalive_dur, src, max_conn, curr_time, is_spl); } //else it must be one of the client conneciton fd's else { //find the client in the list auto _this_client = _find_client_in_list (this->client_list, iter->fd); //update the last message time memcpy (&(_this_client->last_msg_time), &curr_time, sizeof(curr_time)); //check the validity of the sequence number if(_is_seq_valid (iter->fd, hdr.seq_id, _this_client->client_seq) == false) { //drop the packet; continue; } bytes = _uno_process_client_msg (iter->fd, hdr, static_cast<uint8_t*>(buffer), bytes, this->client_list, src); } //since our process function returns positive values if the messages are data messages if(bytes > 0) { ret = (int) bytes; exit_condition = true; if(src_arg) { memcpy (src_arg, &src, sizeof(src)); } break; } } //end of if((iter->revents) & POLLIN) } //end of for loop } //end of else block } //end of while(1) loop return ret; } /** * @brief Sends the given message to the specified client, if connected * * @param msg - void pointer to the message * @param len - the length of the message * @param dst - const reference to the structure containing the destination * @return int - returns number of bytes sent on success, UNO_TRANSPORT_CLIENT_NOT_CONN if the client is not found in the client table, UNO_TRANSPORT_ERR on any general purpose failures */ int UnoTransportServer :: send_msg (const void *msg, size_t len, const struct sockaddr_in &dst) { if(msg==nullptr) { return UNO_TRANSPORT_ERR; } if(len == 0 ) { return len; } //check if we can find this destination address in the list auto iter = _find_client_in_list (client_list, dst); if(iter == client_list.end()) { return UNO_TRANSPORT_CLIENT_NOT_CONN; } //since this is a data message, no bits are to be set in the cmd_info section of the header uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,}; // uint8_t cmd_flags = 0; uno_hdr hdr (seq, 0, len); hdr.serialise (hdr_ser); //send this header and the message int ret = _uno_send (iter->fd, hdr_ser, msg, len, &dst, &seq); #ifdef UNO_TRANSPORT_DEBUG fprintf(stderr, UNO_DBG_PREFIX "send message of len=%d through fd=%d: ret=%d" UNO_DBG_SUFFIX, len, iter->fd, ret); #endif return ret; } /** * @brief Sends the given message to the given client (if connected), expects an ACK from the recipient. * * @param msg - void pointer to the message * @param len - length of the message * @return int - returns -> positive number of bytes on successful reliable send -> 0 if the message was sent successfully, but no ACK was received -> UNO_TRANSPORT_ERR on general failure */ int UnoTransportServer :: send_msg_reliable (const void *msg, size_t len, const struct sockaddr_in &dst) { if(msg==nullptr) { return UNO_TRANSPORT_ERR; } if(len == 0 ) { return len; } //check if we can find this destination address in the list auto iter = _find_client_in_list (client_list, dst); if(iter == client_list.end()) { return UNO_TRANSPORT_CLIENT_NOT_CONN; } //need to set the reliable msg bit in the cmd section of the header uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,}; uint8_t cmd_flags = 0; cmd_flags = UNO_SET_BIT (cmd_flags, UNO_TRANSPORT_CMD_RELIABLE_MSG); uno_hdr hdr (seq, cmd_flags, len); hdr.serialise (hdr_ser); //send this header and the message int ret = _uno_send_reliable (iter->fd, hdr_ser, msg, len, dst, &seq, UNO_TRANSPORT_REL_MAX_RETRIES, UNO_TRANSPORT_REL_RETRY_INT_MS); #ifdef UNO_TRANSPORT_DEBUG fprintf(stderr, UNO_DBG_PREFIX "send reliable message of len=%d through fd=%d: ret=%d" UNO_DBG_SUFFIX, len, iter->fd, ret); #endif if(ret == UNO_TRANSPORT_CONN_CLOSE_RECVD) { iter->set_close_reason (_close_reason::CLOSE_REASON_REQUESTED_BY_CLIENT); _uno_close_connection_requested_iter (iter, client_list); } return ret; } /** * @brief Sends the connection close requet to the specified client * * @param dst - reference to the structure containing the destination * @return int - returns 0 on success, UNO_TRANSPORT_CLIENT_NOT_CONN if the client is not found in the client table, UNO_TRANSPORT_ERR on any general purpose failures */ int UnoTransportServer ::close_connection (struct sockaddr_in &dst) { //first check if we can find this client in the client list auto iter = _find_client_in_list (client_list, dst); if(iter == client_list.end()) { return UNO_TRANSPORT_CLIENT_NOT_CONN; } int ret = _uno_send_conn_close_expl (iter->fd, dst, &seq); //close socket and cleanup iter->set_close_reason (_close_reason::CLOSE_REASON_REQUESTED_BY_SERVER); _uno_close_connection_requested_iter (iter, client_list); return ret; } /**************************************************************************************************************************/ /* STATIC FUNCTION DEFINITIONS */ /**************************************************************************************************************************/ /** * @brief This function creates a client specific socket * * @param opt - the option value for SO_BROADCAST * @return int - the fd value of the socket, returns UNO_TRANSPORT_ERR on failure */ static int _uno_create_client_fd (int opt) { struct sockaddr_in addr = {0,}; //create the socket int fd = socket (AF_INET, SOCK_DGRAM, 0); if(fd == -1) { perror("socket"); return fd; } //set the socket as non blocking since we can use this to discard data if(fcntl(fd, F_SETFL, O_NONBLOCK) == UNO_TRANSPORT_ERR) { perror("fcntl"); goto cleanup; } //set SO_BROADCAST if(setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &opt, sizeof(opt)) == UNO_TRANSPORT_ERR) { perror("setsockopt"); goto cleanup; } //bind to address - leave port as 0, the OS will select a random port addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl (INADDR_ANY); if(bind(fd, (const struct sockaddr*)&addr, sizeof(addr)) == UNO_TRANSPORT_ERR) { perror("bind"); goto cleanup; } return fd; //if error, close the socket to avoid fd leaks cleanup: close(fd); return UNO_TRANSPORT_ERR; } /** * @brief This function creates a server specific socket * * @param port - the port to which this socket is to be bound to * @return int - the fd of the socket, returns UNO_TRANSPORT_ERR on failure */ static int _uno_create_server_fd (uint16_t port) { struct sockaddr_in addr = {0,}; //create the socket int fd = socket (AF_INET, SOCK_DGRAM, 0); if(fd == UNO_TRANSPORT_ERR) { perror("socket"); return fd; } //set the socket as non blocking since we can use this to discard data if(fcntl(fd, F_SETFL, O_NONBLOCK) == UNO_TRANSPORT_ERR) { perror("fcntl"); goto cleanup; } //bind the socket addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl (INADDR_ANY); addr.sin_port = htons (port); if(bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == UNO_TRANSPORT_ERR) { perror("bind"); goto cleanup; } return fd; //close the fd before returning if failure cleanup: close(fd); return UNO_TRANSPORT_ERR; } /** * @brief THe local function for sending out a message with header and buffef, supports null buffer * * @param fd - The fd through which this has to be sent * @param hdr - uint8_t pointer to the structure containing the fixed length header * @param msg - the const void pointer to the buffer containing the message * @param len - the length of the message * @param dst - pointer to the struct containing the destination * @param seq - optional pointer to the uint16_t variable tracking the sequence id, will be incremented on successful send * @return ssize_t - number of bytes sent on success, UNO_TRANSPORT_ERR on failure */ static ssize_t _uno_send (int fd, uint8_t *hdr, const void *msg, size_t len, const struct sockaddr_in *dst, uint16_t *seq) { //initilase the io vector with the hdr and then the message //unfortunately, we need a const_cast here because of the way the sendmsg() API is. size_t iov_len = (msg==NULL) ? (1) : (2); //prepare the array of vectors, 1st one being the header, followed by the message struct iovec iov[] = { { .iov_base = hdr, .iov_len = UNO_TRANSPORT_HDR_LEN}, { .iov_base = const_cast<void*>(msg), .iov_len = len}, }; //add these vectors to the message struct msghdr msg_hdr = { .msg_name = (void*)dst, .msg_namelen= sizeof(*dst), .msg_iov = iov, .msg_iovlen = iov_len, }; ssize_t ret = sendmsg (fd, &msg_hdr, 0); if(ret == UNO_TRANSPORT_ERR) {perror("sendmsg");} else { //increment the sequence number, if required if(seq) (*seq)++; } return ret; } /** * @brief Waits for the specified number of milliseconds to receive the message. uses poll() for timeout. uses _uno_recv() for the actual socket recv * * @param fd - the fd through which the message is to be received * @param hdr - pointer to the buffer where the header is to be filled. * @param buffer - the buffer where the message is to be stored * @param buffer_size - the size of the provided buffer * @param flags - the syscall specific flags that are to be passed to _uno_recv() * @param src - the optional struct sockaddr_in where the source address is to be stored * @param to_ms - the timeout in milliseconds * @return ssize_t - returns the number of bytes received if successful, 0 if timedout, UNO_TRANSPORT_ERR if failed */ static ssize_t _uno_timed_recv (int fd, uint8_t *hdr, void *buffer, size_t buffer_size, int flags, struct sockaddr_in *src, int to_ms) { int ret; if(to_ms == 0) { //since it is a non blocking fd, if there is no data, the call will exit immediately ret = _uno_recv (fd, hdr, buffer, buffer_size, flags, src); } else { //poll on the specified fd struct pollfd pfd = {.fd = fd, .events = POLLIN}; ret = poll (&pfd, 1, to_ms); if(ret == UNO_TRANSPORT_ERR) { //this must never happen perror("poll"); return ret; } //data is ready to be read else if (ret>0) { ret = _uno_recv (fd, hdr, buffer, buffer_size, flags, src); } } return ret; } /** * @brief Receives the message into the given header buffer and message buffer provided using recvmsg() * * @param fd - the fd through which the data is to be received * @param hdr - uint8_t pointer to the buffer where the fixed length header is to be received * @param buffer - the buffer where the mesasge is to be received * @param buffer_size - the size of the message buffer * @param flags - flags to be passed to recvmsg() * @param src - optional pointer to the struct sockaddr_in where the source address is to be filled * @return ssize_t - returns number of bytes received if successful, UNO_TRANSPORT_ERR if failed */ static ssize_t _uno_recv (int fd, uint8_t *hdr, void *buffer, size_t buffer_size, int flags, struct sockaddr_in *src) { assert (fd > 2); //since fd's 0,1,2 are reserved struct iovec iov[] = {{.iov_base = hdr, .iov_len = UNO_TRANSPORT_HDR_LEN}, {.iov_base = buffer, .iov_len = buffer_size}}; struct msghdr msg = { .msg_name = (void*)src, .msg_namelen= sizeof(*src), .msg_iov = iov, .msg_iovlen = 2, }; ssize_t ret = recvmsg (fd, &msg, flags); if(ret == UNO_TRANSPORT_ERR) { perror("recvmsg"); } return ret; } /** * @brief Returns the enum class value of _uno_msg_type by examining the cmd field of the header * * @param cmd The uint8_t value of the cmd_flags * @return _uno_msg_type - the type of message that this is */ static _uno_msg_type _uno_get_msg_type (uint8_t cmd) { _uno_msg_type ret = _uno_msg_type :: UNO_MSG_UNKNOWN; //check ACK bit if(UNO_IS_BIT_SET(cmd, UNO_TRANSPORT_CMD_ACK_MSG)) { ret = _uno_msg_type :: UNO_MSG_ACK; } //check control bit else if(UNO_IS_BIT_SET(cmd, UNO_TRANSPORT_CMD_CONTROL_MSG)) { //ensure that spl bit is not set if(!(UNO_IS_BIT_SET(cmd, UNO_TRANSPORT_CMD_SPL_MSG))) { ret = _uno_msg_type :: UNO_MSG_CTRL; } } //check spl bit else if (UNO_IS_BIT_SET(cmd, UNO_TRANSPORT_CMD_SPL_MSG)) { //ensure that control bit is not set if(UNO_IS_BIT_SET(cmd, UNO_TRANSPORT_CMD_CONTROL_MSG)) { ret = _uno_msg_type :: UNO_MSG_SPL; } } else { ret = _uno_msg_type :: UNO_MSG_DATA; } assert (ret != _uno_msg_type::UNO_MSG_UNKNOWN); return ret; } /** * @brief Creates a new connection in the client list, or sends a server full message * * @param fd - The fd of the server * @param client_list - reference to the client list * @param src - reference to the sockaddr_in struct containing the source address * @param hdr - reference to the structure containing the header * @param ka_dur - the keepalive duration that is to be sent to the client * @param max_conn - the max connections supported * @param curr_time - const reference to the struct timespec containing this message's time */ static void _create_new_connection (int fd, std::list<UnoConnection> &client_list, const struct sockaddr_in &src, uno_hdr &hdr, uint16_t ka_dur, uint8_t max_conn, const struct timespec &curr_time) { bool found = false; int index = 0; //check if client already exists in the list - if so reuse the connection for(auto iter=client_list.begin(); iter!=client_list.end(); ++iter, index++) { if(memcmp(&src, &(*iter), sizeof(src)) == 0) { found = true; break; } } if(found) { //TODO //1. create a new connection and destroy the old one? //2. reuse the old connection } else { //add the client if the server has space if(client_list.size() < max_conn) { //the constructor will send the conection response client_list.emplace_back (fd, src, hdr, ka_dur, curr_time); } else { //send a server full response #ifdef UNO_TRANSPORT_DEBUG fprintf (stderr, UNO_DBG_PREFIX "sending conn refused msg" PRIu8 UNO_DBG_SUFFIX); #endif _uno_send_server_full_rsp (fd, src, hdr); } } } /** * @brief returns the port number of the given fd, in host byte order * * @param fd - the fd whose port needs to be determined * @return int - the port number if successful, UNO_TRANSPORT_ERR if failed */ static int _uno_get_port_from_fd (int fd) { struct sockaddr_in addr = {0,}; socklen_t len = sizeof(addr); int ret = UNO_TRANSPORT_ERR; if(getsockname(fd, (struct sockaddr*)&addr, &len) == UNO_TRANSPORT_ERR) { perror("getsockname"); } else { ret = (int)ntohs(addr.sin_port); } return ret; } /** * @brief processes incoming messages addressed to the server (not connections) * * @param fd - the fd of the server * @param hdr - rerference to the struct containing the header * @param buffer - the buffer containing the message * @param bytes - the length of the message (as returned by _uno_recv()) * @param client_list - reference to the client list of this server * @param ka_dur - the keepalive duration of this server * @param src - const reference to the struct containing the source address * @param max_conn - max connections supported by this server * @param is_spl - reference to the variable that will be set if the incoming msg is a spl message * @return int - returns -> a positive number is a data message and is intended for the caller (spl message) -> 0 if it is a control message intended for the server, and NOT the caller -> UNO_TRANSPORT_ERR if failed */ static int _uno_process_server_msg (int fd, uno_hdr &hdr, uint8_t *buffer, ssize_t bytes, std::list<UnoConnection> &client_list, uint16_t ka_dur, const struct sockaddr_in &src, uint8_t max_conn, const struct timespec &curr_time, bool &is_spl) { int ret = 0; is_spl = false; switch(_uno_get_msg_type (hdr.cmd)) { case _uno_msg_type :: UNO_MSG_CTRL: { #ifdef UNO_TRANSPORT_DEBUG fprintf (stderr, UNO_DBG_PREFIX "received control message. cmd_id = %" PRIu8 UNO_DBG_SUFFIX, buffer[0]); #endif //check command id switch(buffer[0]) { //incoming connection request, setup the new socket and sent connection rsp case UNO_TRANSPORT_CTRL_CONN_REQ: { //if switch(buffer[1]) { //process connection open request case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_OPEN: _create_new_connection (fd, client_list, src, hdr, ka_dur, max_conn, curr_time); ret = 0; break; //close connection request must not be coming to the server fd case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_CLIENT_REQ: case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_EXPL: case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_TO: default: ret = UNO_TRANSPORT_ERR; break; } break; } //should not be receiving conn response here, drop this packet case UNO_TRANSPORT_CTRL_CONN_RSP: //unknown control command, drop this packet default: ret = UNO_TRANSPORT_ERR; break; } } case _uno_msg_type :: UNO_MSG_ACK: break; case _uno_msg_type :: UNO_MSG_DATA: break; //spl msg is a message from an unconnected client that is intended for the caller case _uno_msg_type :: UNO_MSG_SPL: is_spl = true; ret = hdr.msg_len; break; case _uno_msg_type :: UNO_MSG_UNKNOWN: break; } //clear the buffer since it is the caller's buffer, not our own //bury the evidence if(ret <= 0) { memset (buffer, 0, bytes); } return ret; } /** * @brief processes incoming messages addressed to the connection (not the server) * * @param fd - the fd of the connection * @param hdr - reference to the struct containing the header * @param buffer - the buffer containing the message * @param bytes - the length of the message * @param client_list - reference to the list of clients of this server * @param src - const reference to the struct containing the source address * @return int - returns -> a positive number is a data message and is intended for the caller -> 0 if it is a control message intended for the server/connection, and NOT the caller -> UNO_TRANSPORT_ERR if failed */ static int _uno_process_client_msg (int fd, uno_hdr &hdr, uint8_t *buffer, ssize_t bytes, std::list<UnoConnection> &client_list, const struct sockaddr_in &src) { int ret = 0; switch(_uno_get_msg_type (hdr.cmd)) { case _uno_msg_type :: UNO_MSG_CTRL: { #ifdef UNO_TRANSPORT_DEBUG fprintf (stderr, UNO_DBG_PREFIX "received control message. cmd_id = %" PRIu8 UNO_DBG_SUFFIX, buffer[0]); #endif //check command id switch(buffer[0]) { //incoming connection request, setup the new socket and sent connection rsp case UNO_TRANSPORT_CTRL_CONN_REQ: { //check the options switch(buffer[1]) { //drop connection request since this is a connection fd, not the server fd case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_OPEN: ret = UNO_TRANSPORT_ERR; break; //process the close connection request from the client case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_CLIENT_REQ: #ifdef UNO_TRANSPORT_DEBUG fprintf (stderr, UNO_DBG_PREFIX "received close connection for fd=%d" UNO_DBG_SUFFIX, fd); #endif _uno_close_connection_requested (fd, client_list); ret = 0; break; //drop the below connection requests since these modes are reserved from server //to client case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_TO: case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_EXPL: default: ret = UNO_TRANSPORT_ERR; break; } break; } //keepalive message, don't do anything, just update the last msg time case UNO_TRANSPORT_CTRL_KEEPALIVE: ret = 0; break; //should not be receiving conn response here, drop this packet case UNO_TRANSPORT_CTRL_CONN_RSP: ret = UNO_TRANSPORT_ERR; break; //unknown control command, drop this packet default: ret = UNO_TRANSPORT_ERR; break; } } case _uno_msg_type :: UNO_MSG_ACK: break; //we need to pass the data message to the caller case _uno_msg_type :: UNO_MSG_DATA: ret = (int) hdr.msg_len; break; //spl messages are connectionless messages that are only supported in the server fd case _uno_msg_type :: UNO_MSG_SPL: ret = UNO_TRANSPORT_ERR; break; case _uno_msg_type :: UNO_MSG_UNKNOWN: break; } //clear the buffer since it is the caller's buffer, not our own if(ret <= 0) { memset (buffer, 0, bytes); } return ret; } /** * @brief Send a connection response message to the client saying that the server is full * * @param fd - fd through which the message is to be sent * @param src - const reference to the sockaddr_in struct containing the source address * @param hdr - reference to the header structure * @return int - returns number of bytes sent if successful, UNO_TRANSPORT_ERR if not successful */ static int _uno_send_server_full_rsp (int fd, const struct sockaddr_in &src, uno_hdr &hdr) { hdr.msg_len = 1; uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN]; hdr.serialise(hdr_ser); uint8_t data = UNO_TRANSPORT_CTRL_CONN_RSP; return _uno_send (fd, hdr_ser, &data, 1, &src, NULL); } /** * @brief Send a connection close message from the client. Called in destructor * * @param fd - The fd through which the message is to be sent * @param dst - const reference to the struct containing the destination address * @param seq - optional pointer to the uint16_t variable tracking the sequence number * @return int */ static int _uno_send_conn_close (int fd, const struct sockaddr_in &dst, uint16_t *seq) { uint16_t seq_id = (seq==nullptr) ? (0) : (*seq); uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,}; uint8_t cmd_flags = 0; //this is the data section for the connection request command uint8_t data[UNO_TRANSPORT_CTRL_CONN_REQ_LEN]; data[0] = UNO_TRANSPORT_CTRL_CONN_REQ; //command id data[1] = UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_CLIENT_REQ; //command mode //set the control msg bit in the cmd field of the hdr and serialise the hdr cmd_flags = UNO_SET_BIT(cmd_flags, UNO_TRANSPORT_CMD_CONTROL_MSG); cmd_flags = UNO_SET_BIT(cmd_flags, UNO_TRANSPORT_CMD_RELIABLE_MSG); uno_hdr hdr (seq_id, cmd_flags, sizeof(data)); //send this msg out hdr.serialise (hdr_ser); int ret = _uno_send_reliable (fd, hdr_ser, data, sizeof(data), dst, seq, UNO_TRANSPORT_REL_MAX_RETRIES, UNO_TRANSPORT_REL_RETRY_INT_MS); #ifdef UNO_TRANSPORT_DEBUG fprintf (stderr, UNO_DBG_PREFIX "send conn close cmd fd=%d, ret=%d" UNO_DBG_SUFFIX, fd, ret); #endif return ret; } /** * @brief closes the connection of the given fd when a close request is received * * @param fd - the fd of the connection to be closexd * @param client_list - reference to the client list */ static void _uno_close_connection_requested (int fd, std::list<UnoConnection> &client_list) { for(auto iter=client_list.begin(); iter!=client_list.end(); ++iter) { if(fd == iter->fd) { //found the client in the list iter->set_close_reason (_close_reason :: CLOSE_REASON_REQUESTED_BY_CLIENT); _uno_close_connection_requested_iter (iter, client_list); return; } } } /** * @brief closes the connection at the given iterator when a close request is received * * @param iter iterator of the node in the client list * @param client_list reference to the client list */ static void _uno_close_connection_requested_iter (std::list<UnoConnection>::iterator iter, std::list<UnoConnection> &client_list) { #ifdef UNO_TRANSPORT_DEBUG fprintf(stderr, UNO_DBG_PREFIX "closing conn of fd=%d" UNO_DBG_SUFFIX, iter->fd); #endif // iter->connected = false; client_list.erase (iter); } /** * @brief searches the list by IPv4 addr and returns the iterator of the node where the required client info is stored * * @param client_list reference to the client list * @param dst reference to the struct containing the IPv4 address * @return std::list<UnoConnection>::iterator - position of the client if found, client_list.end() if not found */ static std::list<UnoConnection>::iterator _find_client_in_list (std::list<UnoConnection> &client_list, const struct sockaddr_in &dst) { auto ret = client_list.end(); for(auto iter=client_list.begin(); iter!=client_list.end(); ++iter) { if(memcmp(&dst, &(iter->cli_addr), sizeof(dst)) == 0) { ret = iter; break; } } return ret; } /** * @brief searches the list by fd and returns the iterator of the node where the required client's info is stored * * @param client_list - reference to the client list * @param fd - fd of the client to be found * @return std::list<UnoConnection>::iterator - position of the client if found, client_list.end() if not found */ static std::list<UnoConnection>::iterator _find_client_in_list (std::list<UnoConnection> &client_list, int fd) { auto ret = client_list.end(); for(auto iter=client_list.begin(); iter!=client_list.end(); ++iter) { if(iter->fd == fd) { ret = iter; break; } } return ret; } /** * @brief processes the received message on the client side * * @param hdr - reference to the struct containing the header * @param buffer - pointer to the buffer containing the message * @param bytes - number of bytes of the total message (including header, arithmetic will be handled here) * @param server_seq - reference to the variable tracking the sequence numbers used by the server * @return int - returns -> positive number (number of bytes) if the message is a data message and should be passed to the caller -> 0 if the message is a control message and is not relevant to the caller -> UNO_TRANSPORT_CONN_CLOSE_RECVD if the server has closed the connection -> UNO_TRANSPORT_ERR for any other failure case */ static int _uno_client_process_recv_msg (uno_hdr &hdr, uint8_t *buffer, ssize_t bytes, uint16_t &server_seq) { int ret = 0; switch(_uno_get_msg_type (hdr.cmd)) { case _uno_msg_type :: UNO_MSG_CTRL: { #ifdef UNO_TRANSPORT_DEBUG fprintf (stderr, UNO_DBG_PREFIX "received control message. cmd_id = %" PRIu8 UNO_DBG_SUFFIX, buffer[0]); #endif //check command id switch(buffer[0]) { //incoming connection request, setup the new socket and sent connection rsp case UNO_TRANSPORT_CTRL_CONN_REQ: { //if switch(buffer[1]) { //drop connection request since this is a client, not a server (we don't take connections here) case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_CLIENT_REQ: case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_OPEN: ret = UNO_TRANSPORT_ERR; break; //process the close connection request - the server wants to close the connection case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_TO: case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_EXPL: ret = UNO_TRANSPORT_CONN_CLOSE_RECVD; break; default: ret = UNO_TRANSPORT_ERR; break; } break; } //should not be receiving conn response here, drop this packet case UNO_TRANSPORT_CTRL_CONN_RSP: //unknown control command, drop this packet default: ret = UNO_TRANSPORT_ERR; break; } } case _uno_msg_type :: UNO_MSG_ACK: //ACK packet, we coo' break; //we need to pass the data message to the caller case _uno_msg_type :: UNO_MSG_DATA: ret = (int) hdr.msg_len; break; //spl messages are connectionless messages that are only supported in the server fd case _uno_msg_type :: UNO_MSG_SPL: ret = UNO_TRANSPORT_ERR; break; case _uno_msg_type :: UNO_MSG_UNKNOWN: ret = UNO_TRANSPORT_ERR; break; } //clear the buffer since it is the caller's buffer, not our own if(ret <= 0) { memset (buffer, 0, bytes); } return ret; } /** * @brief function that performs reliable send according to this protocol * * @param fd - the fd through which the message is to be sent and the ACK is to be received * @param hdr_ser - pointer to the buffer containing the fixed length header * @param msg - pointer to the buffer containing the message * @param len - length of the message * @param dst - reference to the struct containing the IPv4 address of the destination * @param seq - optional pointer to the variable that is being used to track the sequence number of the sender * @param max_retries - the max retries if ACK is not received * @param retry_interval - the time to wait before every retry * @return int - returns -> positive number of bytes on successful reliable send -> 0 if the message was sent successfully, but no ACK was received -> UNO_TRANSPORT_CONN_CLOSE_RECVD if conn close msg is delivered -> UNO_TRANSPORT_ERR on general failure */ static int _uno_send_reliable (int fd, uint8_t *hdr_ser, const void *msg, size_t len, const struct sockaddr_in &dst, uint16_t *seq, uint8_t max_retries, uint16_t retry_interval) { //make sure that the reliable msg bit is set assert (_uno_is_reliable_msg(hdr_ser[UNO_TRANSPORT_HDR_CMD_POS])==true); int ret = 0; uint8_t hdr[UNO_TRANSPORT_HDR_LEN]; struct sockaddr_in src; int temp; uint8_t data[2]; //loop and perform all attempts for(int i=0; i<max_retries; i++) { memset (hdr, 0, sizeof(hdr)); memset (&src, 0, sizeof(src)); //send out the message temp = _uno_send (fd, hdr_ser, msg, len, &dst, NULL); if(temp == UNO_TRANSPORT_ERR) { ret = temp; break; } //recv the message temp = _uno_timed_recv (fd, hdr, data, sizeof(data), MSG_WAITALL, &src, retry_interval); if(temp == UNO_TRANSPORT_ERR) { break; } //if we received a response, check the response if(temp > 0) { //check if it is an ack response if(_uno_get_msg_type(hdr[UNO_TRANSPORT_HDR_CMD_POS]) == _uno_msg_type::UNO_MSG_ACK) { //TODO - validate seq id and msg len //successful ack, set ret as temp ret = temp; #ifdef UNO_TRANSPORT_DEBUG fprintf (stderr, UNO_DBG_PREFIX "received ack msg for seq=%" PRIu16 UNO_DBG_SUFFIX,(*seq)-1); #endif break; } //else check if this is a connection close msg if(_uno_get_msg_type(hdr[UNO_TRANSPORT_HDR_CMD_POS]) == _uno_msg_type::UNO_MSG_CTRL) { if(data[0] == UNO_TRANSPORT_CTRL_CONN_CLOSED) { ret = UNO_TRANSPORT_CONN_CLOSE_RECVD; break; } } } //else increment retry count and try again hdr_ser[UNO_TRANSPORT_HDR_RC_POS]++; } //end of for loop //update the sequence number if the send was successful (regardless of ACK) if(ret != UNO_TRANSPORT_ERR && (seq!=nullptr)) { (*seq)++; } return ret; } /** * @brief Checks if the given cmd_flags indicates that this message is a reliable msg * * @param cmd_flags The 8 bit value containing the cmd_flags * @return - self explanatory */ static bool _uno_is_reliable_msg (uint8_t cmd_flags) { if(UNO_IS_BIT_SET(cmd_flags,UNO_TRANSPORT_CMD_RELIABLE_MSG)) return true; else return false; } /** * @brief Sends the ACK to the specified node for the given header * * @param fd - the fd through which the data is to be sent * @param dst - const reference to the struct containing the destination IPv4 address * @param hdr - reference to the struct containing the header * @return int - number of bytes sent on success, UNO_TRANSPORT_ERR on failure */ static int _uno_send_ack (int fd, const struct sockaddr_in &dst, const uno_hdr &hdr) { //ack is the same header, but with msg len as 0 and ack bit as true //and with no data uno_hdr ack = hdr; ack.msg_len = 0; //make sure that the ACK bit is set uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN]; ack.cmd = UNO_SET_BIT(ack.cmd, UNO_TRANSPORT_CMD_ACK_MSG); ack.serialise (hdr_ser); //send out the message int ret = _uno_send (fd, hdr_ser, NULL, 0, &dst, NULL); #ifdef UNO_TRANSPORT_DEBUG fprintf (stderr, UNO_DBG_PREFIX "received reliable msg at fd=%d of len=%" PRIu16 ", sending ack ret= %d" UNO_DBG_SUFFIX, fd, hdr.msg_len, ret ); #endif return ret; } /** * @brief Checks if the sequence number is valid * * @param fd - the fd that is involved in this transaction (only for logging purpose) * @param inc_seq - the incoming sequence number * @param saved_seq - reference to the last saved sequence number (will be updated if this message is valid) * @return - self explanatory */ static bool _is_seq_valid (int fd, uint16_t inc_seq, uint16_t &saved_seq) { //if inc_seq is UNO_SEQ_ID_RESET (0), that means that the device is new or the sequence number has overflown if(inc_seq == UNO_SEQ_ID_RESET) { #ifdef UNO_TRANSPORT_DEBUG fprintf (stderr, UNO_DBG_PREFIX "WARN::seq id has been overflown/reset for fd=%d" UNO_DBG_SUFFIX, fd); #endif saved_seq = inc_seq; return true; } //incoming must always be greater than saved else if(inc_seq > saved_seq) { #ifdef UNO_TRANSPORT_DEBUG if((inc_seq-saved_seq) > 1) { fprintf (stderr, UNO_DBG_PREFIX "WARN::possible lost packetsinc_seq-saved_seq=%" PRIu16 " for fd=%d" UNO_DBG_SUFFIX, inc_seq-saved_seq, fd); } #endif saved_seq = inc_seq; return true; } else { //invalid sequence #ifdef UNO_TRANSPORT_DEBUG if(inc_seq == saved_seq) { fprintf (stderr, UNO_DBG_PREFIX "dropping duplicate packet with seq=%" PRIu16 " for fd=%d" UNO_DBG_SUFFIX, inc_seq, fd); } else { fprintf (stderr, UNO_DBG_PREFIX "dropping out of order packet with seq=%" PRIu16 " for fd=%d" " expected=%" PRIu16 UNO_DBG_SUFFIX, inc_seq, fd, saved_seq+1); } #endif return false; } } /** * @brief - Sends an explicit connection closure message from the server (caller asked for connection closure) * * @param fd - the fd through which the message is to be sent * @param dst - const reference to the struct containing the destination address * @param seq - optional pointer to the variable where the sequence id is being tracked, will be incremented if provided * @return int - returns number of bytes sent if successful, else UNO_TRANSPORT_ERR if failure */ static int _uno_send_conn_close_expl (int fd, const struct sockaddr_in &dst, uint16_t *seq) { uint16_t seq_id = (seq==nullptr) ? (0) : (*seq); uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,}; uint8_t cmd_flags = 0; //this is the data section for the connection request command uint8_t data[UNO_TRANSPORT_CTRL_CONN_REQ_LEN]; data[0] = UNO_TRANSPORT_CTRL_CONN_REQ; //command id data[1] = UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_EXPL; //command mode //set the control msg bit in the cmd field of the hdr and serialise the hdr cmd_flags = UNO_SET_BIT(cmd_flags, UNO_TRANSPORT_CMD_CONTROL_MSG); uno_hdr hdr (seq_id, cmd_flags, sizeof(data)); //send this msg out hdr.serialise (hdr_ser); int ret = _uno_send (fd, hdr_ser, data, sizeof(data), &dst, seq); #ifdef UNO_TRANSPORT_DEBUG fprintf(stderr, UNO_DBG_PREFIX "sent explicit connection close req %d bytes to fd=%d port %hu" UNO_DBG_SUFFIX, ret, fd, ntohs(dst.sin_port)); #endif return ret; } /** * @brief - Sends an explicit connection timedout message from the server (no data in the specified keepalive duration) * * @param fd - the fd through which the message is to be sent * @param dst - const reference to the struct containing the destination address * @param seq - optional pointer to the variable where the sequence id is being tracked, will be incremented if provided * @return int - returns number of bytes sent if successful, else UNO_TRANSPORT_ERR if failure */ static int _uno_send_conn_close_to (int fd, const struct sockaddr_in &dst, uint16_t *seq) { uint16_t seq_id = (seq==nullptr) ? (0) : (*seq); uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,}; uint8_t cmd_flags = 0; //this is the data section for the connection request command uint8_t data[UNO_TRANSPORT_CTRL_CONN_REQ_LEN]; data[0] = UNO_TRANSPORT_CTRL_CONN_REQ; //command id data[1] = UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_TO; //command mode //set the control msg bit in the cmd field of the hdr and serialise the hdr cmd_flags = UNO_SET_BIT(cmd_flags, UNO_TRANSPORT_CMD_CONTROL_MSG); uno_hdr hdr (seq_id, cmd_flags, sizeof(data)); //send this msg out hdr.serialise (hdr_ser); int ret = _uno_send (fd, hdr_ser, data, sizeof(data), &dst, seq); #ifdef UNO_TRANSPORT_DEBUG fprintf(stderr, UNO_DBG_PREFIX "sent timedout connection close req %d bytes to fd=%d port %hu" UNO_DBG_SUFFIX, ret, fd, ntohs(dst.sin_port)); #endif return ret; } /** * @brief - linearly searches through the list and finds the connection that is set to timeout the earliest * * @param client_list - reference to the client list * @return std::list<UnoConnection>::iterator - returns an iterator at the position in the client list */ static std::list<UnoConnection>::iterator _uno_find_most_stale_connection (std::list<UnoConnection> &client_list) { if(client_list.empty()) { return client_list.end(); } //initialise the oldest time struct timeval oldest; auto ret = client_list.begin(); memcpy (&oldest, &(ret->last_msg_time), sizeof(oldest)); //skip the first item since it is already stored in oldest auto iter=client_list.begin(); ++iter; //loop through the list for(; iter!=client_list.end(); ++iter) { //compare seconds field if(iter->last_msg_time.tv_sec < oldest.tv_sec) { //update oldest and ret memcpy (&oldest, &(iter->last_msg_time), sizeof(oldest)); ret = iter; } //if seconds are equal, compare nanoseconds field else if(iter->last_msg_time.tv_nsec < iter->last_msg_time.tv_nsec) { //update oldest and ret memcpy (&oldest, &(iter->last_msg_time), sizeof(oldest)); ret = iter; } //else ignore else { ; //left here for readability, the compiler will optimise this out } } return ret; } /** * @brief - computes the difference between 2 timespec structs. performs (end-start) * * @param start - const reference to the timespec containing the start time * @param end - const reference to the timespec containing the end time. * @param result - reference to the struct where the result of the difference will be stored */ static void __uno_timespec_diff (const struct timespec &start, const struct timespec &end, struct timespec &result) { assert (end.tv_sec >= start.tv_sec); //assumes end is greater than start, does not check, it is the caller's responsibility to ensure this if(end.tv_nsec < start.tv_nsec) { assert (end.tv_sec > start.tv_sec); result.tv_sec = end.tv_sec - start.tv_sec - 1; result.tv_nsec = end.tv_nsec - start.tv_nsec + UNO_SEC_TO_NS(1); } else { result.tv_sec = end.tv_sec - start.tv_sec; result.tv_nsec = end.tv_nsec - start.tv_nsec; } } /** * @brief - computes the sum between 2 timespec structs * * @param start - const reference to the timespec containing the start time * @param end - const reference to the timespec containing the end time * @param result - reference to the struct where the result will be stored */ static void __uno_timespec_sum (const struct timespec &start, const struct timespec &end, struct timespec &result) { result.tv_sec = start.tv_sec + end.tv_sec; result.tv_nsec = start.tv_nsec + end.tv_nsec; //now check for "overflow", if result.tv_nsec is greater than 10^9 if(result.tv_nsec > UNO_SEC_TO_NS(1)) { result.tv_sec++; result.tv_nsec = result.tv_nsec % UNO_SEC_TO_NS(1); } } /** * @brief - computes the value to be passed to timerfd_settime given the last message time, the keepalive duration (in ms), the current time * * @param last_msg_time - const reference to the struct containing the last message time * @param keepalive_dur_ms - the expected keepalive duration (in milliseconds) * @param curr_time - const reference to the timespec containing the curr time * @param timer_val - the timespec where the computed timer value is to be written */ static void _uno_compute_timer_value (const struct timespec &last_msg_time, uint16_t keepalive_dur_ms, const struct timespec &curr_time, struct timespec &timer_val) { //transform keepalive_dur_ms to struct timespec struct timespec _keep_alive = {0,}; _keep_alive.tv_sec = UNO_MS_TO_SEC(keepalive_dur_ms); if(keepalive_dur_ms % 1000) { _keep_alive.tv_nsec = UNO_MS_TO_NS(keepalive_dur_ms % 1000); } //compute expiry time struct timespec _expiry_time = {0,}; __uno_timespec_sum (last_msg_time, _keep_alive, _expiry_time); //now the timervalue is the difference between _expiry_time and curr_time __uno_timespec_diff (curr_time, _expiry_time, timer_val); }
88,979
29,035
#include "./INCLUDE/LKH.h" /* * The ReadPenalties function attempts to read node penalties (Pi-values) * from file. * * The first line of the file contains the number of nodes. * * Each of the following lines is of the form * <integer> <integer> * where the first integer is a node number, and the second integer * is the Pi-value associated with the node. * * If reading succeeds, the function returns 1; otherwise 0. * * The function is called from the CreateCandidateSet function. */ namespace LKH { static thread_local int PenaltiesRead = 0; void LKHAlg::freeReadPenalties() { PenaltiesRead = 0; } int LKHAlg::ReadPenalties() { int i, Id; Node *Na, *Nb = 0; if (PiFileName == 0) return 0; if (PenaltiesRead || !strcmp(PiFileName, "0")) return PenaltiesRead = 1; if (!(PiFile = fopen(PiFileName, "r"))) return 0; if (TraceLevel >= 1) printff("Reading PI_FILE: \"%s\" ... ", PiFileName); fscanint(PiFile, &i); if (i != Dimension) eprintf("PI_FILE \"%s\" does not match problem", PiFileName); fscanint(PiFile, &Id); assert(Id >= 1 && Id <= Dimension); FirstNode = Na = &NodeSet[Id]; fscanint(PiFile, &Na->Pi); for (i = 2; i <= Dimension; i++) { fscanint(PiFile, &Id); assert(Id >= 1 && Id <= Dimension); Nb = &NodeSet[Id]; fscanint(PiFile, &Nb->Pi); Nb->Pred = Na; Na->Suc = Nb; Na = Nb; } FirstNode->Pred = Nb; Nb->Suc = FirstNode; fclose(PiFile); if (TraceLevel >= 1) printff("done\n"); return PenaltiesRead = 1; } }
1,533
649
#include "Arduino.h" #include "PS4_Input.h" PS4_Input::PS4_Input(){ /* Constructor - initialise all members to zero. */ rightV = 0; rightH = 0; leftV = 0; leftH = 0; ps = 0; share = 0; options = 0; triangle = 0; square = 0; circle = 0; x = 0; up = 0; down = 0; left = 0; right = 0; l1 = 0; l2 = 0; l3 = 0; r1 = 0; r2 = 0; r3 = 0; } void PS4_Input::Start_Serial(){ /* Starts serial port "Serial2" - sets up serial port from which the PS4 inputs can be read. */ //Serial.begin(115200); Serial2.begin(115200); //Serial2.println("CM9_Ready!\n"); } String PS4_Input::Print_Out(){ /* Prints out current values of all the PS4 class members i.e. the current analogue values and button states. -> returns a String. */ char printout [400]; sprintf(printout, "PLAYSATION 4 BUTTON PRESS PRINT OUT : \nl3h : %d\nl3v : %d\nr3h : %d\nr3v : %d\n * *********DIGITAL BUTTONS : **********\nPS : %d\nSHARE : %d\nOPTIONS : %d\nTRIANGLE : %d\nSQUARE : %d\nX : %d\nCIRCLE : %d\nUP : %d\nDOWN : %d\nLEFT : %d\nRIGHT : %d\nL1 : %d\nR1 : %d\nL2 : %d\nR2 : %d\nR3 : %d\nL3 : %d\n",leftH,leftV,rightH,rightV,ps,share,options,triangle,square,x,circle,up,down,left,right,l1,r1,l2,r2,l3,r3); return (String)printout; } void PS4_Input::Reset_Bools(){ /* Reset Bools - resets all of the digital button values to 0 (or off) state. */ ps = 0; share = 0; options = 0; triangle = 0; square = 0; circle = 0; x = 0; up = 0; down = 0; left = 0; right = 0; l1 = 0; l2 = 0; l3 = 0; r1 = 0; r2 = 0; r3 = 0; } void PS4_Input::Reset_Analogues() { /* Resets the analogue values of the PS4 joysticks back to zero. */ rightV = 0; rightH = 0; leftV = 0; leftH = 0; } int PS4_Input::Get_Input(){ /* Processes the PS4 input - This functions reads the messages sent on the serial2 port. - One 'message' or one 'PS4 input' is determined by a "\n" end of line character. - In the case of analogue input, the message is dissected and analogue values are read and assigned to their appropriate analogue value PS4 class members - In the case of digital input, if the message contains the button type, the appropriate digital button PS4 class member is updated. -> Returns an int indicating a successful/unsuccessful read of PS4 input. */ int message_received = 0; int analogue_value = 0; if (Serial2.available() > 0){ // read the incoming string until '\n' character: message = Serial2.readStringUntil('\n'); //****************************************ANALOGUES**************************************** if ((message.indexOf("Analogues:") >= 0)) { //************************************LEFT ANALOG STICK************************************ analogue_value = message.substring(message.lastIndexOf("L_hor: ") + 7, message.indexOf(";")).toInt(); if (abs(analogue_value) > ANALOGUE_DEADZONE) { leftH = -analogue_value; // negative value -> switch directions on the left analogue } else leftH = 0; //left is negative, right is positive (after adding negative values) //update message to get rid of already read data message = message.substring(message.lastIndexOf("L_ver: ")); analogue_value = message.substring(message.lastIndexOf("L_ver: ") + 7, message.indexOf(";")).toInt(); if (abs(analogue_value) > ANALOGUE_DEADZONE) { leftV = analogue_value; } else leftV = 0; //up is negative, down is positive //update message to get rid of already read data message = message.substring(message.lastIndexOf("R_hor: ")); //****************************************************************************************** //************************************RIGHT ANALOG STICK************************************ analogue_value = message.substring(message.lastIndexOf("R_hor: ") + 7, message.indexOf(";")).toInt(); if (abs(analogue_value) > ANALOGUE_DEADZONE) { rightH = analogue_value; } else rightH = 0; //left is negative, right is positive //update message to get rid of already read data message = message.substring(message.lastIndexOf("R_ver: ")); analogue_value = message.substring(message.lastIndexOf("R_ver: ") + 7, message.indexOf(";")).toInt(); if (abs(analogue_value) > ANALOGUE_DEADZONE) { rightV = analogue_value; } else rightV = 0; //up is negative, down is positive //****************************************************************************************** } // end analogue //****************************************************************************************** //**************************************DIGITAL BUTTONS************************************** if ((message.indexOf("R3") >= 0)) { r3 = 1; } if ((message.indexOf("L3") >= 0)) { l3 = 1; } if((message.indexOf("R2") >= 0)){ r2 = 1; } if((message.indexOf("L2") >= 0)){ l2 = 1; } if((message.indexOf("R1") >= 0)){ r1 = 1; } if((message.indexOf("L1") >= 0)){ l1 = 1; } if((message.indexOf("RIGHT") >= 0)){ right = 1; } if((message.indexOf("LEFT") >= 0)){ left = 1; } if((message.indexOf("UP") >= 0)){ up = 1; } if((message.indexOf("DOWN") >= 0)){ down = 1; } if((message.indexOf("PS") >= 0)){ ps = 1; } if((message.indexOf("SHARE") >= 0)){ share = 1; } if((message.indexOf("OPTIONS") >= 0)){ options = 1; } if((message.indexOf("X") >= 0)){ x = 1; } if((message.indexOf("SQUARE") >= 0)){ square = 1; } if((message.indexOf("TRIANGLE") >= 0)){ triangle = 1; } if((message.indexOf("CIRCLE") >= 0)){ circle = 1; } //******************************************************************************************* message_received = 1; } // end -> if serial2 available return message_received; }
6,311
2,147
#include <QTest> #include "TestUtil.h" #include "settings/INIFile.h" class IniFileTest : public QObject { Q_OBJECT private slots: void initTestCase() { } void cleanupTestCase() { } void test_Escape_data() { QTest::addColumn<QString>("through"); QTest::newRow("unix path") << "/abc/def/ghi/jkl"; QTest::newRow("windows path") << "C:\\Program files\\terrible\\name\\of something\\"; QTest::newRow("Plain text") << "Lorem ipsum dolor sit amet."; QTest::newRow("Escape sequences") << "Lorem\n\t\n\\n\\tAAZ\nipsum dolor\n\nsit amet."; QTest::newRow("Escape sequences 2") << "\"\n\n\""; QTest::newRow("Hashtags") << "some data#something"; } void test_Escape() { QFETCH(QString, through); QString there = INIFile::escape(through); QString back = INIFile::unescape(there); QCOMPARE(back, through); } void test_SaveLoad() { QString a = "a"; QString b = "a\nb\t\n\\\\\\C:\\Program files\\terrible\\name\\of something\\#thisIsNotAComment"; QString filename = "test_SaveLoad.ini"; // save INIFile f; f.set("a", a); f.set("b", b); f.saveFile(filename); // load INIFile f2; f2.loadFile(filename); QCOMPARE(a, f2.get("a","NOT SET").toString()); QCOMPARE(b, f2.get("b","NOT SET").toString()); } }; QTEST_GUILESS_MAIN(IniFileTest) #include "INIFile_test.moc"
1,511
552
//+-------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1992 - 1992 // // File: memdebug.hxx // // Contents: Error code handler routines // // History: 19-Mar-92 DrewB Created // //--------------------------------------------------------------- #ifndef __MEMDEBUG_HXX__ #define __MEMDEBUG_HXX__ #if DBG == 1 #define ErrJmp(comp, label, errval, var) \ {\ var = errval;\ comp##DebugOut((DEB_IERROR, "Error %lX at %s:%d\n",\ (unsigned long)var, __FILE__, __LINE__));\ goto label;\ } #else #define ErrJmp(comp, label, errval, var) \ {\ var = errval;\ goto label;\ } #endif #define memErr(l, e) ErrJmp(mem, l, e, sc) #define memChkTo(l, e) if (FAILED(sc = (e))) memErr(l, sc) else 1 #define memHChkTo(l, e) if (FAILED(sc = GetScode(e))) memErr(l, sc) else 1 #define memChk(e) memChkTo(EH_Err, e) #define memHChk(e) memHChkTo(EH_Err, e) #define memMemTo(l, e) \ if ((e) == NULL) memErr(l, E_OUTOFMEMORY) else 1 #define memMem(e) memMemTo(EH_Err, e) #if DBG == 1 DECLARE_DEBUG(mem) #define memDebugOut(x) memInlineDebugOut x #define memAssert(x) Win4Assert(x) #define memVerify(x) Win4Assert(x) #else #define memDebugOut(x) #define memAssert(x) #define memVerify(x) (x) #endif #endif // #ifndef __MEMDEBUG_HXX__
1,376
600
#include "Texture.hpp" #include <algorithm> #include <utility> #include <iostream> #include <string> #include <cassert> #include <array> #include <SFML/Graphics.hpp> // For sf::Image #include "glm.hpp" #include "GLHelpers.h" using namespace en; namespace { int getNumMipmaps(Texture::Size size) { int i = 1; while (true) { size.x = std::max(1, size.x / 2); size.y = std::max(1, size.y / 2); if (size.x == 1 && size.y == 1) break; ++i; } return i; } } Texture::Texture(const std::string& filename, GLint internalFormat) { // Load from file using sf::Image, then put the data in an openGL buffer. sf::Image image; if (!image.loadFromFile(filename)) return; auto temp = image.getSize(); m_size = {temp.x, temp.y}; // 0, 0 in sf::Image is top left, but openGL expects 0,0 to be bottom left, flip to compensate. image.flipVertically(); glCheckError(); glGenTextures(1, &m_id); glBindTexture(GL_TEXTURE_2D, m_id); { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, m_size.x, m_size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsPtr()); glGenerateMipmap(GL_TEXTURE_2D); } glBindTexture(GL_TEXTURE_2D, 0); m_kind = Kind::Texture2D; } Texture::Texture(const std::array<std::string, 6>& cubeSidePaths, GLint internalFormat) { std::array<sf::Image, 6> images; for (GLuint i = 0; i < images.size(); ++i) if (!images[i].loadFromFile(cubeSidePaths[i])) return; glGenTextures(1, &m_id); glBindTexture(GL_TEXTURE_CUBE_MAP, m_id); { glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); for (GLuint i = 0; i < 6; ++i) { const sf::Image& image = images[i]; auto temp = image.getSize(); m_size = {temp.x, temp.y}; glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, internalFormat, m_size.x, m_size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsPtr()); } glGenerateMipmap(GL_TEXTURE_CUBE_MAP); } glBindTexture(GL_TEXTURE_CUBE_MAP, 0); m_kind = Kind::TextureCube; } Texture::Texture(Texture&& other) noexcept : m_id(std::exchange(other.m_id, 0)) {} Texture& Texture::operator=(Texture&& other) noexcept { m_id = std::exchange(other.m_id, 0); return *this; } Texture::~Texture() { glDeleteTextures(1, &m_id); } GLuint Texture::getId() const { return m_id; } bool Texture::isValid() const { return m_id != 0 && m_kind != Kind::None; } Texture::Kind Texture::getKind() const { return m_kind; } Texture::Size Texture::getSize() const { return m_size; }
3,393
1,337
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * *************************************************************/ #ifndef _FMTURL_HXX #define _FMTURL_HXX #include <svl/poolitem.hxx> #include "swdllapi.h" #include <hintids.hxx> #include <format.hxx> class ImageMap; class IntlWrapper; // URL, ServerMap und ClientMap class SW_DLLPUBLIC SwFmtURL: public SfxPoolItem { String sTargetFrameName; // in diesen Frame soll die URL String sURL; //Einfache URL String sName; // Name des Anchors ImageMap *pMap; //ClientSide Images sal_Bool bIsServerMap; //mit der URL eine ServerSideImageMap SwFmtURL& operator=( const SwFmtURL& ); public: SwFmtURL(); // @@@ copy construction allowed, but assigment is not? @@@ SwFmtURL( const SwFmtURL& ); virtual ~SwFmtURL(); // "pure virtual Methoden" vom SfxPoolItem virtual int operator==( const SfxPoolItem& ) const; virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const; virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres, SfxMapUnit eCoreMetric, SfxMapUnit ePresMetric, String &rText, const IntlWrapper* pIntl = 0 ) const; virtual sal_Bool QueryValue( com::sun::star::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const; virtual sal_Bool PutValue( const com::sun::star::uno::Any& rVal, sal_uInt8 nMemberId = 0 ); void SetTargetFrameName( const String& rStr ) { sTargetFrameName = rStr; } void SetURL( const String &rURL, sal_Bool bServerMap ); void SetMap( const ImageMap *pM ); //Pointer wird kopiert! const String &GetTargetFrameName()const { return sTargetFrameName; } const String &GetURL() const { return sURL; } sal_Bool IsServerMap() const { return bIsServerMap; } const ImageMap *GetMap() const { return pMap; } ImageMap *GetMap() { return pMap; } const String& GetName() const { return sName; } void SetName( const String& rNm ) { sName = rNm; } }; inline const SwFmtURL &SwAttrSet::GetURL(sal_Bool bInP) const { return (const SwFmtURL&)Get( RES_URL,bInP); } inline const SwFmtURL &SwFmt::GetURL(sal_Bool bInP) const { return aSet.GetURL(bInP); } #endif
3,032
1,048
#include <iostream> #include <vector> #include <functional> #include <math.h> #include "cost_functions.hpp" #include "vehicle.hpp" #include "path.hpp" #include "state_machine.hpp" #include "collision_detector.hpp" #include "utils.hpp" double speedCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path, const State &state, const double &weight) { double avg_speed = path.averageSpeed(CONTROLLER_UPDATE_RATE_SECONDS); double epislon = 0.001; if (avg_speed > MAX_SPEED_METERS_PER_SECOND + epislon) { return weight; } double diff = (MAX_SPEED_METERS_PER_SECOND - avg_speed) / MAX_SPEED_METERS_PER_SECOND; // double diff = (MAX_SPEED_METERS_PER_SECOND - avg_speed); // double diff = avg_speed / MAX_SPEED_METERS_PER_SECOND; // cout << "**** Speed diff " << diff << endl; return weight * (1 - exp(-abs(diff))); } double centerOfLaneDistCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path, const State &state, const double &weight) { double final_d = path.m_d[path.m_d.size() - 1]; int lane = calculateLane(final_d, DEFAULT_LANE_SPACING, DEFAULT_LANE_INSIDE_OFFSET); int lane_center = getLaneCenterFrenet(lane); double diff = lane_center - final_d; return weight * (1 - exp(-abs(diff))); } double laneChangeCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path, const State &state, const double &weight) { if (state.current_lane == state.future_lane) { // No penalty if staying on the same lane return 0.0; } // Weight penalty if switching lane return weight; } /** * @brief Cost function that increases the penalty the closer the car ahead is from the * ego vehicle * * @param ego * @param others * @param path * @param state * @param weight * @return double */ double distanceToClosestCarAheadCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path, const State &state, const double &weight) { // We are switching lanes and this is not a cancellable operation // if (state.d_state == LateralState::CHANGE_LANE_LEFT || state.d_state == LateralState::CHANGE_LANE_RIGHT) // { // return 0; // } // Find closest car ahead and get distance if (!ego.m_isInLane) { return weight; } // Find all vehicles ahead on the current lane std::vector<Vehicle> ahead = ego.ahead(others, state.future_lane); if (ahead.size() == 0) { return 0.0; } double min_distance = VEHICLE_DISTANCE_THRESHOLD_METERS; for (const Vehicle &v : ahead) { double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y); if (dist < min_distance) { min_distance = dist; } } // TODO We may also want to take speed into account double diff = (VEHICLE_DISTANCE_THRESHOLD_METERS - min_distance) / VEHICLE_DISTANCE_THRESHOLD_METERS; return weight * (1 - exp(-abs(diff))); } double longitudinalDistanceToClosestAdjacentCarFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path, const State &state, const double &weight) { // This cost function only applies to lane changes if (state.current_lane == state.future_lane && state.current_lane == ego.m_lane) { return 0.0; } double min_distance = VEHICLE_DISTANCE_THRESHOLD_METERS; for (const Vehicle &v : others) { if (v.m_isInLane && v.m_lane == state.future_lane) { // Other car is on different lane double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y); if (dist < min_distance) { min_distance = dist; } } } // cout << "**************** DISTANCE ADJACENT LANE = " << min_distance << endl; double diff = (VEHICLE_DISTANCE_THRESHOLD_METERS - min_distance); return weight * (1 - exp(-abs(diff))); } double distanceToClosestCarAheadFutureLaneCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path, const State &state, const double &weight) { // Since we are not planning to switch lanes there is no cost in this case if (state.d_state == LateralState::STAY_IN_LANE) { return 0.0; // return distanceToClosestCarAheadCostFunction(ego, others, path, state, weight); } // Find closest car ahead and get distance if (!ego.m_isInLane) { return weight; } std::vector<Vehicle> ahead = ego.ahead(others, state.future_lane); double min_distance = LANE_CHANGE_VEHICLE_AHEAD_DISTANCE_THRESHOLD_METERS; for (const Vehicle &v : ahead) { double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y); if (dist < min_distance) { min_distance = dist; } } double diff_ahead = (LANE_CHANGE_VEHICLE_AHEAD_DISTANCE_THRESHOLD_METERS - min_distance) / LANE_CHANGE_VEHICLE_AHEAD_DISTANCE_THRESHOLD_METERS; std::vector<Vehicle> behind = ego.behind(others, state.future_lane); min_distance = LANE_CHANGE_VEHICLE_BEHIND_DISTANCE_THRESHOLD_METERS; for (const Vehicle &v : behind) { double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y); if (dist < min_distance) { min_distance = dist; } } double diff_behind = (LANE_CHANGE_VEHICLE_BEHIND_DISTANCE_THRESHOLD_METERS - min_distance) / LANE_CHANGE_VEHICLE_BEHIND_DISTANCE_THRESHOLD_METERS; // cout << "*** DISTANCE RATIO AHEAD = " << diff_ahead << ", DISTANCE RATIO BEHIND = " << diff_behind << endl; double diff = diff_behind + diff_ahead; return weight * (1 - exp(-diff)); } /** * @brief Computes a cost function that penalises the future lane depending * on the average speed of all vehicles ahead * * @param ego * @param others * @param path * @param state * @param weight * @return double */ double averageLaneSpeedDiffCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path, const State &state, const double &weight) { // We are switching lanes and this is not a cancellable operation if (state.d_state == LateralState::CHANGE_LANE_LEFT || state.d_state == LateralState::CHANGE_LANE_RIGHT) { return 0; } // Not in lane so doesn't count if (!ego.m_isInLane) { return 0.0; } // Find all vehicles ahead std::vector<Vehicle> ahead = ego.ahead(others, state.future_lane); if (ahead.size() == 0) { return 0.0; } double speed_avg = 0.0; int count = 0; for (const Vehicle &v : ahead) { double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y); // Only look a bit ahead if (dist <= VEHICLE_DISTANCE_THRESHOLD_METERS * 1.5) { speed_avg += v.getSpeed(); ++count; } } if (count == 0) { return 0.0; } speed_avg /= (double)count; cout << "** Speed average of lane " << state.future_lane << ": " << speed_avg << endl; // It's OK if the future lane is very fast... as long as ego itself keeps within the speed limits if (speed_avg >= MAX_SPEED_METERS_PER_SECOND) { return 0.0; } // This time, let's get a ratio as it will produce a smoother result double diff = (MAX_SPEED_METERS_PER_SECOND - speed_avg) / MAX_SPEED_METERS_PER_SECOND; return weight * (1 - exp(-abs(diff))); } double speedDifferenceWithClosestCarAheadCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path, const State &state, const double &weight) { // TODO need to review this if (!ego.m_isInLane) { return 0.0; } std::vector<Vehicle> ahead = ego.ahead(others, state.current_lane); if (ahead.size() == 0) { return 0.0; } double min_distance = VEHICLE_DISTANCE_THRESHOLD_METERS; Vehicle closest_vehicle; for (const Vehicle &v : ahead) { // Other car must be ahead in the same lane if (v.m_s > ego.m_s) { double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y); if (dist < min_distance) { min_distance = dist; closest_vehicle = v; } } } if (min_distance >= VEHICLE_DISTANCE_THRESHOLD_METERS) { // No need to penalize if vehicle ahead is far enough... return 0.0; } double ego_speed = path.averageSpeed(1.0); double v_speed = closest_vehicle.getSpeed(); // cout << "** Future ego speed (future lane=" << state.future_lane << ", current lane=" << state.current_lane << ") : " << ego_speed // << " other vehicle (lane=" << closest_vehicle.lane << ") : " << v_speed << endl; // If ego is going faster than the vehicle ahead then we want to penalise it because it could lead to a collision if (ego_speed > v_speed) { return weight; } // Otherwise we just want ego to match the speed of the vehicle ahead double diff = v_speed - ego_speed; return weight * (1 - exp(-abs(diff))); } // TODO Compute the average speed of lanes double lanesAverageForwardSpeedCarsAhead(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path, const State &state, const double &weight) { // TODO need to review this if (!ego.m_isInLane) { return weight; } double min_distance = VEHICLE_DISTANCE_THRESHOLD_METERS; Vehicle closest_vehicle; for (const Vehicle &v : others) { // Other car must be ahead in the same lane if (v.m_isInLane && v.m_lane == state.future_lane && v.m_s > ego.m_s) { double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y); if (dist < min_distance) { min_distance = dist; closest_vehicle = v; } } } if (min_distance >= VEHICLE_DISTANCE_THRESHOLD_METERS) { // No need to penalize if vehicle ahead is far enough... return 0.0; } double ego_speed = path.averageSpeed(1.0); double v_speed = closest_vehicle.getSpeed(); // cout << "** Future ego speed (future lane=" << state.future_lane << ", current lane=" << state.current_lane << ") : " << ego_speed // << " other vehicle (lane=" << closest_vehicle.lane << ") : " << closest_vehicle.getSpeed() << endl; double diff = v_speed - ego_speed; return weight * (1 - exp(-abs(diff))); } double collisionTimeCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path, const State &state, const double &weight) { // TODO need to review this if (!ego.m_isInLane) { return weight; } double min_distance = VEHICLE_DISTANCE_THRESHOLD_METERS; Vehicle closest_vehicle; for (const Vehicle &v : others) { if (v.m_isInLane && (v.m_lane == state.current_lane || v.m_lane == state.future_lane) && v.m_s >= ego.m_s) { double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y); if (dist < min_distance) { min_distance = dist; closest_vehicle = v; } } } if (min_distance >= VEHICLE_DISTANCE_THRESHOLD_METERS) { // No need to penalize if vehicle ahead is far enough... return 0.0; } Collision collision = predictCollision(path, closest_vehicle, CONTROLLER_UPDATE_RATE_SECONDS); if (!collision.willCollide) { // If no collision foreseen then don't penalize return 0.0; } double ego_speed = path.averageSpeed(1.0); // cout << "** Collision with vehicle at timestep = " << collision.collision_timestep << endl; // Collision is far away so can be ignored for now if (collision.collision_timestep > COLLISION_MAX_TIMESTEP_THRESHOLD) { return 0.0; } double speed_ratio = ego_speed / MAX_SPEED_METERS_PER_SECOND; double timestep_ratio = (COLLISION_MAX_TIMESTEP_THRESHOLD - collision.collision_timestep) / COLLISION_MAX_TIMESTEP_THRESHOLD; cout << "*** SPEED RATIO = " << speed_ratio << endl; cout << "*** TIMESTEP RATIO = " << timestep_ratio << endl; // double diff = 75 - (collision.collision_timestep + 5 * speed_ratio); double diff = speed_ratio + timestep_ratio; cout << "*** TIMESTEP + SPEED RATIO = " << diff << endl; // Otherwise penalize as a factor of the time to collision - the further away in time the better return weight * (1 - exp(-abs(diff))); } /** * @brief Measures the distance to the goal at the end of our path * * @param ego * @param others * @param path * @param state * @param weight * @return double the distance to the goal at the end of our path */ double futureDistanceToGoalCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path, const State &state, const double &weight) { int traj_size = path.size(); double diff = MAX_TRACK_S - path.m_s[traj_size - 1]; // cout << "** DISTANCE TO GOAL = " << diff << endl; return weight * (1 - exp(-abs(diff / MAX_TRACK_S))); }
13,342
4,747
class Object0 {side=8;rank="";vehicle="Land_HBarrier_5_F";position[]={-4.32715,1.41943,0};dir=282.158;}; class Object1 {side=8;rank="";vehicle="Land_HBarrier_5_F";position[]={4.41309,1.22168,0};dir=261.111;}; class Object2 {side=8;rank="";vehicle="Land_HBarrier_5_F";position[]={5.28711,-4.24902,0};dir=261.111;}; class Object3 {side=8;rank="";vehicle="Land_HBarrier_5_F";position[]={-5.51807,-4.05078,0};dir=282.158;}; class Object4 {side=8;rank="";vehicle="Land_HBarrier_5_F";position[]={-2.09058,5.51855,0};dir=0.640371;}; class Object5 {side=8;rank="";vehicle="Land_Razorwire_F";position[]={-5.73682,2.41602,0};dir=283.253;}; class Object6 {side=8;rank="";vehicle="Land_Razorwire_F";position[]={5.40674,5.48145,0};dir=79.4694;}; class Object7 {side=8;rank="";vehicle="Land_Razorwire_F";position[]={2.37256,6.85742,0};dir=181.16;}; class Object8 {side=8;rank="";vehicle="Land_Razorwire_F";position[]={6.73804,-2.20117,0};dir=79.4694;}; class Object9 {side=8;rank="";vehicle="Land_Razorwire_F";position[]={-7.64673,-5.54297,0};dir=283.253;};
1,043
580
/** * Copyright 2021 Oleh Sharuda <oleh.sharuda@gmail.com> * * * 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. */ /*! \file * \brief Text tools utilities * \author Oleh Sharuda */ #include "texttools.hpp" #include <memory> #include <cassert> #include <unicode/errorcode.h> #include <cstdarg> namespace tools { // special array for faster decoding from text to buffer, 255 is not hex character, otherwise actual value const uint8_t SpecialCharacterTables::hex_val[] = {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}; const char SpecialCharacterTables::hex_upcase[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; const char SpecialCharacterTables::hex_lwcase[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; ICUHelper::ICUHelper () { UErrorCode status = U_ZERO_ERROR; conv_utf16_le = ucnv_open("UTF-16LE", &status); assert(U_SUCCESS(status)); conv_utf16_be = ucnv_open("UTF-16BE", &status); assert(U_SUCCESS(status)); conv_utf8 = ucnv_open("UTF8", &status); assert(U_SUCCESS(status)); conv_default = ucnv_open(nullptr, &status); assert(U_SUCCESS(status)); date_formatter = DateFormat::createDateTimeInstance(); } ICUHelper::~ICUHelper() { ucnv_close(conv_utf16_le); ucnv_close(conv_utf16_be); ucnv_close(conv_utf8); delete date_formatter; } icu::UnicodeString ICUHelper::make_unicode_string(const std::string& src, UErrorCode& err) { return icu::UnicodeString(src.c_str(), -1, conv_default, err); } icu::UnicodeString ICUHelper::make_unicode_string(const tools::u16_string& src, UConverter* convertor, UErrorCode& err) { icu::UnicodeString res = icu::UnicodeString((char*)src.c_str(), src.length()*sizeof(char16_t), convertor, err); return res; } void ICUHelper::make_string(icu::UnicodeString& us, std::string& dst, UErrorCode& err) { size_t len = count_chars((const char16_t*)us.getTerminatedBuffer(), conv_utf8, err); if (!U_SUCCESS(err)) { return; } std::unique_ptr<char[]> buffer(new char[len+1]); us.extract(buffer.get(), len, conv_utf8, err); if (!U_SUCCESS(err)) { return; } else if (err==U_STRING_NOT_TERMINATED_WARNING){ err = U_ZERO_ERROR; } // extract is not required to make string null terminated, terminate it buffer.get()[len] = 0; dst = (const char*)buffer.get(); } void ICUHelper::make_u16string(icu::UnicodeString& us, tools::u16_string& dst, UConverter* convertor, UErrorCode& err) { size_t len = count_chars((const char16_t*)us.getTerminatedBuffer(), convertor, err) / sizeof(char16_t); if (err!=U_ZERO_ERROR) { return; } std::unique_ptr<char16_t[]> buffer(new char16_t[len+1]); // convert to UTF16 us.extract((char*)buffer.get(), len*sizeof(char16_t), convertor, err); if (!U_SUCCESS(err)) { return; } else if (err==U_STRING_NOT_TERMINATED_WARNING){ err = U_ZERO_ERROR; } // extract is not required to make string null terminated, terminate it buffer.get()[len] = 0; dst = (const char16_t*)buffer.get(); } size_t ICUHelper::count_chars(const char16_t* s, UConverter* convertor, UErrorCode& err) { size_t res = ucnv_fromUChars(convertor, NULL, 0, (const UChar*)s, -1, &err); if(err==U_BUFFER_OVERFLOW_ERROR) { err=U_ZERO_ERROR; } else { res = 0; } return res; } bool ICUHelper::utf8_to_utf16(const std::string& src, u16_string& dst, bool little_endian) { UConverter* conv = little_endian ? conv_utf16_le : conv_utf16_be; UErrorCode err = U_ZERO_ERROR; icu::UnicodeString us(make_unicode_string(src, err)); make_u16string(us, dst, conv, err); return U_SUCCESS(err); } bool ICUHelper::utf16_to_utf8(const u16_string& src, std::string& dst, bool little_endian) { UConverter* conv = little_endian ? conv_utf16_le : conv_utf16_be; UErrorCode err = U_ZERO_ERROR; icu::UnicodeString us(make_unicode_string(src, conv, err)); make_string(us, dst, err); return U_SUCCESS(err); } bool ICUHelper::to_case(std::string& s, bool lowcase) { UErrorCode err = U_ZERO_ERROR; icu::UnicodeString us(make_unicode_string(s, err)); if (err!=U_ZERO_ERROR) { return false; } if (lowcase) { us.toLower(); } else { us.toUpper(); } make_string(us, s, err); return err==U_ZERO_ERROR; } bool ICUHelper::to_case(u16_string& s, bool lowcase, bool little_endian) { UConverter* conv = little_endian ? conv_utf16_le : conv_utf16_be; UErrorCode err = U_ZERO_ERROR; icu::UnicodeString us(make_unicode_string(s, conv, err)); if (err!=U_ZERO_ERROR) { return false; } if (lowcase) { us.toLower(); } else { us.toUpper(); } make_u16string(us, s, conv, err); return err==U_ZERO_ERROR; } void ICUHelper::utf16_to_wide(const u16_string& src, std::wstring& dst) { size_t slen = src.length(); if (slen) { dst = std::wstring(slen, L' '); for (size_t i = 0; i<slen; ++i) { dst[i] = (wchar_t)src[i]; } } else { dst.clear(); } } void ICUHelper::wide_to_utf16(const std::wstring& src, u16_string& dst) { size_t slen = src.length(); if (slen) { dst = u16_string(slen, L' '); for (size_t i = 0; i<slen; ++i) { dst[i] = (char16_t)src[i]; } } else { dst.clear(); } } std::wstring utf8_to_wstr(const std::string& s) { u16_string u16s; std::wstring res; g_unicode_ts.utf8_to_utf16(s, u16s, true); g_unicode_ts.utf16_to_wide(u16s, res); return res; } std::string wstr_to_utf8(const std::wstring& s) { u16_string u16s; std::string res; g_unicode_ts.wide_to_utf16(s, u16s); g_unicode_ts.utf16_to_utf8(u16s, res, true); return res; } std::unique_ptr<RegexPattern> ICUHelper::regex_pattern(const std::string& pattern, uint32_t flags) { UErrorCode err = U_ZERO_ERROR; UParseError pe; std::unique_ptr<RegexPattern> rpattern; icu::UnicodeString upattern(make_unicode_string(pattern, err)); if (err!=U_ZERO_ERROR) { return rpattern; } // Construct pattern rpattern.reset(RegexPattern::compile(upattern, flags, pe, err)); if (err!=U_ZERO_ERROR) { rpattern.reset(nullptr); } return rpattern; } bool ICUHelper::regex_groups(const RegexPattern& pattern, const std::string& s, std::vector<std::string>& groups) { UErrorCode err = U_ZERO_ERROR; icu::UnicodeString us(make_unicode_string(s, err)); if (err!=U_ZERO_ERROR) { return false; } // Create matcher std::unique_ptr<RegexMatcher> rm(pattern.matcher(us, err)); if (!rm || err!=U_ZERO_ERROR) { return false; } int32_t n_groups = rm->groupCount()+1; if (rm->matches(0, err)) { for (int32_t i=0; i<n_groups; ++i) { UnicodeString ug = rm->group(i, err); if (!U_SUCCESS(err)) { return false; } std::string g; make_string(ug, g, err); if (!U_SUCCESS(err)) { return false; } groups.push_back(g); } return true; } return false; } bool ICUHelper::regex_match(const RegexPattern& pattern, const std::string& s) { UErrorCode err = U_ZERO_ERROR; icu::UnicodeString us(make_unicode_string(s, err)); if (err!=U_ZERO_ERROR) { return false; } // Create matcher std::unique_ptr<RegexMatcher> rm(pattern.matcher(us, err)); if (!rm || err!=U_ZERO_ERROR) { return false; } return rm->matches(err); } bool ICUHelper::is_ascii(const std::string& s) { size_t len = s.length(); for (size_t i=0; i<len; ++i) { if ((uint8_t)s[i] > 0x7f) { return false; } } return true; } std::string ICUHelper::dtime_to_utf8(std::time_t t) { UErrorCode err = U_ZERO_ERROR; UnicodeString t_string; std::string res; t_string.remove(); date_formatter->format(static_cast<UDate>(t)*1000, t_string, NULL, err); assert(U_SUCCESS(err)); make_string(t_string, res, err); assert(U_SUCCESS(err)); return res; } template <class _Ch> std::string dump_string_hex(const std::basic_string<_Ch>& s, const std::string& separator) { size_t n_char = s.length(); size_t n_sep = separator.length(); size_t res_len = n_char>1 ? n_sep*n_char-1 : 0; res_len += (n_char+1)*sizeof(_Ch)*2; static const char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; std::string res; res.reserve(res_len); uint8_t* pbuf = (uint8_t*)s.c_str(); size_t buflen = n_char*sizeof(_Ch); for (size_t i=0; i<buflen; ++i) { if (i!=0 && i%sizeof(_Ch)==0) { res+=separator; } uint8_t b = pbuf[i]; char c0 = digits[b >> 4]; char c1 = digits[b & 0x0F]; res+=c0; res+=c1; } return res; } std::string buffer_to_hex(const uint8_t* buffer, size_t len, bool lwrcase, const char* separator) { const char* digit_set = lwrcase ? SpecialCharacterTables::hex_lwcase : SpecialCharacterTables::hex_upcase; size_t sep_len = separator!=nullptr ? strlen(separator) : 0; size_t res_len = len>1 ? sep_len*(len-1)+(len+1)*2: (len+1)*2; // length of separators std::string res; res.reserve(res_len); for (size_t i=0; i<len; ++i) { if (sep_len!=0 && i!=0) { res+=separator; } uint8_t b = buffer[i]; char c0 = digit_set[b >> 4]; char c1 = digit_set[b & 0x0F]; res+=c0; res+=c1; } return res; } std::vector<uint8_t> buffer_from_hex(const std::string& hex) { size_t slen = hex.length(); std::vector<uint8_t> result; if (slen%2!=0) { throw std::length_error("Hex buffer description must have even number of characters"); } result.resize(slen/2); for (size_t i=0;i<slen;) { uint8_t b0 = SpecialCharacterTables::hex_val[hex[i++]]; uint8_t b1 = SpecialCharacterTables::hex_val[hex[i++]]; if (b0>0x0F || b1>0x0F) { throw std::out_of_range("Is not hex character"); } result[(i/2)-1] = (b0 << 4) + b1; } return result; } std::string format_buffer(size_t bytes_per_line, const uint8_t* buffer, size_t buffer_len, const std::string& line_prefix, const std::string& text_separator) { size_t line_count = buffer_len/bytes_per_line; size_t tail_bytes = buffer_len%bytes_per_line; line_count+= (tail_bytes!=0); std::list<std::string> slist; size_t offset_length = 0; size_t t = buffer_len; for (size_t i=0; i<sizeof(size_t) && t!=0; i++, offset_length++) { t = t >> 8; } offset_length*=2; // get maximum width of the offset field // line has the following format (for bytes_per_line==4) // <prefix>XX XX XX XX XX<text_separator>.... for (size_t l=0; l<line_count; l++) { const uint8_t* start = buffer + l*bytes_per_line; size_t len = (l==line_count-1) ? tail_bytes : bytes_per_line; size_t pad = bytes_per_line - len; size_t offset = l*bytes_per_line; std::string offset_prefix = str_format("%*X",offset_length, offset); std::string hex =buffer_to_hex(start, len, true, " "); hex += std::string(pad*3, ' '); std::string ascii = buffer_to_ascii(start, len, '.'); ascii += std::string(pad, ' '); slist.push_back(line_prefix + offset_prefix + text_separator + hex + text_separator + ascii); } return join_strings(slist, "\n"); } std::string buffer_to_ascii(const uint8_t* buffer, size_t len, char unprintable_char) { std::string res; res.reserve(len); for (size_t i=0; i<len; i++) { uint8_t b = buffer[i]; res += (b>=0x20 && b<0x7F) ? (char)b : unprintable_char; } return res; } std::string str_format(const char *format, ... ) { std::vector<char> buffer; char* buf_ptr; va_list args1; va_start(args1, format); va_list args2; va_copy(args2, args1); int buflen = std::vsnprintf( nullptr, 0, format, args1 ); va_end(args1); if( buflen < 0 ) { throw std::runtime_error( "bad format" ); } buflen++; buffer.resize(buflen); buf_ptr = buffer.data(); std::vsnprintf( buf_ptr, buflen, format, args2 ); va_end(args2); // Terminate string buf_ptr[buflen-1] = '\0'; return std::string(buf_ptr); } }
15,266
6,749
// File implement/oglplus/enums/memory_barrier_bit_names.ipp // // Automatically generated file, DO NOT modify manually. // Edit the source 'source/enums/oglplus/memory_barrier_bit.txt' // or the 'source/enums/make_enum.py' script instead. // // Copyright 2010-2015 Matus Chochlik. // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // namespace enums { OGLPLUS_LIB_FUNC StrCRef ValueName_( MemoryBarrierBit*, GLbitfield value ) #if (!OGLPLUS_LINK_LIBRARY || defined(OGLPLUS_IMPLEMENTING_LIBRARY)) && \ !defined(OGLPLUS_IMPL_EVN_MEMORYBARRIERBIT) #define OGLPLUS_IMPL_EVN_MEMORYBARRIERBIT { switch(value) { #if defined GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT case GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT: return StrCRef("VERTEX_ATTRIB_ARRAY_BARRIER_BIT"); #endif #if defined GL_ELEMENT_ARRAY_BARRIER_BIT case GL_ELEMENT_ARRAY_BARRIER_BIT: return StrCRef("ELEMENT_ARRAY_BARRIER_BIT"); #endif #if defined GL_UNIFORM_BARRIER_BIT case GL_UNIFORM_BARRIER_BIT: return StrCRef("UNIFORM_BARRIER_BIT"); #endif #if defined GL_TEXTURE_FETCH_BARRIER_BIT case GL_TEXTURE_FETCH_BARRIER_BIT: return StrCRef("TEXTURE_FETCH_BARRIER_BIT"); #endif #if defined GL_SHADER_IMAGE_ACCESS_BARRIER_BIT case GL_SHADER_IMAGE_ACCESS_BARRIER_BIT: return StrCRef("SHADER_IMAGE_ACCESS_BARRIER_BIT"); #endif #if defined GL_COMMAND_BARRIER_BIT case GL_COMMAND_BARRIER_BIT: return StrCRef("COMMAND_BARRIER_BIT"); #endif #if defined GL_PIXEL_BUFFER_BARRIER_BIT case GL_PIXEL_BUFFER_BARRIER_BIT: return StrCRef("PIXEL_BUFFER_BARRIER_BIT"); #endif #if defined GL_TEXTURE_UPDATE_BARRIER_BIT case GL_TEXTURE_UPDATE_BARRIER_BIT: return StrCRef("TEXTURE_UPDATE_BARRIER_BIT"); #endif #if defined GL_BUFFER_UPDATE_BARRIER_BIT case GL_BUFFER_UPDATE_BARRIER_BIT: return StrCRef("BUFFER_UPDATE_BARRIER_BIT"); #endif #if defined GL_FRAMEBUFFER_BARRIER_BIT case GL_FRAMEBUFFER_BARRIER_BIT: return StrCRef("FRAMEBUFFER_BARRIER_BIT"); #endif #if defined GL_TRANSFORM_FEEDBACK_BARRIER_BIT case GL_TRANSFORM_FEEDBACK_BARRIER_BIT: return StrCRef("TRANSFORM_FEEDBACK_BARRIER_BIT"); #endif #if defined GL_ATOMIC_COUNTER_BARRIER_BIT case GL_ATOMIC_COUNTER_BARRIER_BIT: return StrCRef("ATOMIC_COUNTER_BARRIER_BIT"); #endif #if defined GL_SHADER_STORAGE_BARRIER_BIT case GL_SHADER_STORAGE_BARRIER_BIT: return StrCRef("SHADER_STORAGE_BARRIER_BIT"); #endif #if defined GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT case GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT: return StrCRef("CLIENT_MAPPED_BUFFER_BARRIER_BIT"); #endif #if defined GL_ALL_BARRIER_BITS case GL_ALL_BARRIER_BITS: return StrCRef("ALL_BARRIER_BITS"); #endif default:; } OGLPLUS_FAKE_USE(value); return StrCRef(); } #else ; #endif } // namespace enums
2,760
1,239
#include "test_thrust_cuda.cu"
31
15
#include <cstdio> #include <cstdlib> #include <cmath> struct List{ double elm; struct List *next; }; int get_array(List *data){ int i = 1; List *q = data; scanf("%lf", &data->elm); do{ List *p = (List*)malloc(sizeof(List)); scanf("%lf", &p->elm); q->next = p; p->next = nullptr; q = p; i++; }while(getchar() != '\n'); return i; } void print_array(List *data){ List *p = data; while(p!=nullptr){ printf("%lf ", p->elm); p = p->next; } printf("\n"); } double get_average(List *data, int num){ double sum = 0.0; List *p = data; while(p!= nullptr){ sum += p->elm; p = p->next; } return sum / num; } double get_A_uncertainty(List *data, int *num){ double ave = get_average(data, *num); double sum = 0.0; List *p = data; while(p!= nullptr){ sum += pow(p->elm - ave, 2); p = p->next; } sum = pow(sum / (*num-1), 0.5); int flag; do{ double judge = sum * 3; p = data; List *q; flag = 0; while(p != nullptr){ if((std::abs(p->elm - ave)) >= judge){ flag = 1; printf("\nOne bad value: %lf \n\n", p->elm); (*num)--; if(p == data) data = p->next; else { q->next = p->next; } } q = p; p = p->next; } if(flag){ p = data; ave = get_average(data, *num); sum = 0.0; while(p!= nullptr){ sum += pow(p->elm - ave, 2); p = p->next; } sum = pow(sum / (*num-1), 0.5); } }while(flag); sum = sum / pow(*num, 0.5); switch(*num){ case 2: sum *= 1.84; break; case 3: sum *= 1.32; break; case 4: sum *= 1.20; break; case 5: sum *= 1.14; break; default: break; } return sum; } double get_B_uncertainty(double equ){ double three_root = pow(3, 0.5); double val = equ / three_root; return val; } double get_uncertainty(double a, double b){ double val = a*a + b*b; val = pow(val, 0.5); return val; } int main(){ List *data = (List*)malloc(sizeof(List)); data->next = nullptr; puts("Please input the data split with spaces:"); int num = get_array(data); puts("PLease input the uncertainty of the equipment:"); double delta_equ; scanf("%lf", &delta_equ); double a = get_A_uncertainty(data, &num); double b = get_B_uncertainty(delta_equ); double uncertainty = get_uncertainty(a,b); printf("\na: %lf\nb: %lf\nfinal: %lf\n", a, b, uncertainty); puts("### Remember to take the effective number yourself. ###"); system("pause"); return 0; }
3,013
1,075
#include "EventFilter/CSCRawToDigi/interface/CSCDMBHeader2013.h" #include "DataFormats/CSCDigi/interface/CSCConstants.h" #include <iostream> CSCDMBHeader2013::CSCDMBHeader2013() { bzero(data(), sizeInWords() * 2); bits.ddu_code_1 = bits.ddu_code_2 = bits.ddu_code_3 = bits.ddu_code_4 = 0xA; bits.newddu_code_1 = bits.newddu_code_2 = bits.newddu_code_3 = bits.newddu_code_4 = 0x9; } CSCDMBHeader2013::CSCDMBHeader2013(const uint16_t* buf) { memcpy(data(), buf, sizeInWords() * 2); } unsigned CSCDMBHeader2013::cfebMovlp() const { return bits.cfeb_movlp; } unsigned CSCDMBHeader2013::dmbCfebSync() const { return bits.dmb_cfeb_sync; } unsigned CSCDMBHeader2013::activeDavMismatch() const { return bits.clct_dav_mismatch; } unsigned CSCDMBHeader2013::format_version() const { return bits.fmt_version; } unsigned CSCDMBHeader2013::cfebAvailable() const { return bits.cfeb_dav; } unsigned CSCDMBHeader2013::nalct() const { return bits.alct_dav; } unsigned CSCDMBHeader2013::nclct() const { return bits.tmb_dav; } unsigned CSCDMBHeader2013::crateID() const { return bits.dmb_crate; } unsigned CSCDMBHeader2013::dmbID() const { return bits.dmb_id; } unsigned CSCDMBHeader2013::bxn() const { return bits.dmb_bxn; } unsigned CSCDMBHeader2013::bxn12() const { return bits.dmb_bxn1; } unsigned CSCDMBHeader2013::l1a() const { return bits.dmb_l1a; } unsigned CSCDMBHeader2013::l1a24() const { return (bits.dmb_l1a_lowo | (bits.dmb_l1a_hiwo << 12)); } void CSCDMBHeader2013::setL1A(int l1a) { bits.dmb_l1a = l1a & 0x1F; } void CSCDMBHeader2013::setL1A24(int l1a) { bits.dmb_l1a_lowo = l1a & 0xFFF; bits.dmb_l1a_hiwo = (l1a >> 12) & 0xFFF; } void CSCDMBHeader2013::setBXN(int bxn) { bits.dmb_bxn1 = bxn & 0xFFF; bits.dmb_bxn = bxn & 0x1F; } void CSCDMBHeader2013::setCrateAddress(int crate, int dmbId) { this->bits.dmb_crate = crate; this->bits.dmb_id = dmbId; } unsigned CSCDMBHeader2013::sizeInWords() const { return 8; } /// counts from zero bool CSCDMBHeader2013::cfebAvailable(unsigned icfeb) { assert(icfeb < CSCConstants::MAX_CFEBS_RUN2); return (cfebAvailable() >> icfeb) & 1; } void CSCDMBHeader2013::addCFEB(int icfeb) { assert(icfeb < CSCConstants::MAX_CFEBS_RUN2); bits.cfeb_dav |= (1 << icfeb); bits.cfeb_clct_sent |= (1 << icfeb); } void CSCDMBHeader2013::addNCLCT() { bits.tmb_dav = bits.tmb_dav_copy = bits.tmb_dav_copy2 = 1; } void CSCDMBHeader2013::addNALCT() { bits.alct_dav = bits.alct_dav_copy = bits.alct_dav_copy2 = 1; } bool CSCDMBHeader2013::check() const { return (bits.ddu_code_1 == 0xA && bits.ddu_code_2 == 0xA && bits.ddu_code_3 == 0xA && bits.ddu_code_4 == 0xA && bits.newddu_code_1 == 0x9 && bits.newddu_code_2 == 0x9 && bits.newddu_code_3 == 0x9 && bits.newddu_code_4 == 0x9); }
2,773
1,305
// -*- C++ -*- //===-- uniform_real_distribution_test.cpp ---------------------------------===// // // Copyright (C) Intel Corporation // // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // // This file incorporates work covered by the following copyright and permission // notice: // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // //===----------------------------------------------------------------------===// // // Abstract: // // Test of uniform_real_distribution - comparison with std:: // Note not all types can be compared with std:: implementation is different #include "support/utils.h" #include <iostream> #if TEST_DPCPP_BACKEND_PRESENT #include <vector> #include <CL/sycl.hpp> #include <random> #include <oneapi/dpl/random> // Engine parameters #define a 40014u #define c 200u #define m 2147483563u #define seed 777 #define eps 0.00001 template<class RealType, class UIntType> int test(oneapi::dpl::internal::element_type_t<RealType> left, oneapi::dpl::internal::element_type_t<RealType> right, int nsamples) { sycl::queue queue(sycl::default_selector{}); // memory allocation std::vector<oneapi::dpl::internal::element_type_t<RealType>> std_samples(nsamples); std::vector<oneapi::dpl::internal::element_type_t<RealType>> dpstd_samples(nsamples); constexpr int num_elems = oneapi::dpl::internal::type_traits_t<RealType>::num_elems == 0 ? 1 : oneapi::dpl::internal::type_traits_t<RealType>::num_elems; // dpstd generation { sycl::buffer<oneapi::dpl::internal::element_type_t<RealType>, 1> dpstd_buffer(dpstd_samples.data(), nsamples); queue.submit([&](sycl::handler &cgh) { auto dpstd_acc = dpstd_buffer.template get_access<sycl::access::mode::write>(cgh); cgh.parallel_for<>(sycl::range<1>(nsamples / num_elems), [=](sycl::item<1> idx) { unsigned long long offset = idx.get_linear_id() * num_elems; oneapi::dpl::linear_congruential_engine<UIntType, a, c, m> engine(seed, offset); oneapi::dpl::uniform_real_distribution<RealType> distr(left, right); sycl::vec<oneapi::dpl::internal::element_type_t<RealType>, num_elems> res = distr(engine); res.store(idx.get_linear_id(), dpstd_acc.get_pointer()); }); }); queue.wait(); } // std generation std::linear_congruential_engine<oneapi::dpl::internal::element_type_t<UIntType>, a, c, m> std_engine(seed); std::uniform_real_distribution<oneapi::dpl::internal::element_type_t <RealType>> std_distr(left, right); for(int i = 0; i < nsamples; ++i) std_samples[i] = std_distr(std_engine); // comparison int err = 0; for(int i = 0; i < nsamples; ++i) { if(fabs(std_samples[i] - dpstd_samples[i]) > eps) { std::cout << "\nError: std_sample[" << i << "] = " << std_samples[i] << ", dpstd_samples[" << i << "] = " << dpstd_samples[i]; err++; } } if(err) { std::cout << "\tFailed" << std::endl; } else { std::cout << "\tPassed" << std::endl; } return err; } template<class RealType, class UIntType> int test_portion(oneapi::dpl::internal::element_type_t<RealType> left, oneapi::dpl::internal::element_type_t<RealType> right, int nsamples, unsigned int part) { sycl::queue queue(sycl::default_selector{}); // memory allocation std::vector<oneapi::dpl::internal::element_type_t<RealType>> std_samples(nsamples); std::vector<oneapi::dpl::internal::element_type_t<RealType>> dpstd_samples(nsamples); constexpr int num_elems = oneapi::dpl::internal::type_traits_t<RealType>::num_elems == 0 ? 1 : oneapi::dpl::internal::type_traits_t<RealType>::num_elems; int n_elems = (part >= num_elems) ? num_elems : part; // dpstd generation { sycl::buffer<oneapi::dpl::internal::element_type_t<RealType>, 1> dpstd_buffer(dpstd_samples.data(), nsamples); queue.submit([&](sycl::handler &cgh) { auto dpstd_acc = dpstd_buffer.template get_access<sycl::access::mode::write>(cgh); cgh.parallel_for<>(sycl::range<1>(nsamples / n_elems), [=](sycl::item<1> idx) { unsigned long long offset = idx.get_linear_id() * n_elems; oneapi::dpl::linear_congruential_engine<UIntType, a, c, m> engine(seed, offset); oneapi::dpl::uniform_real_distribution<RealType> distr(left, right); sycl::vec<oneapi::dpl::internal::element_type_t<RealType>, num_elems> res = distr(engine, part); for(int i = 0; i < n_elems; ++i) dpstd_acc.get_pointer()[offset + i] = res[i]; }); }); queue.wait_and_throw(); } // std generation std::linear_congruential_engine<oneapi::dpl::internal::element_type_t<UIntType>, a, c, m> std_engine(seed); std::uniform_real_distribution<oneapi::dpl::internal::element_type_t <RealType>> std_distr(left, right); for(int i = 0; i < nsamples; ++i) { std_samples[i] = std_distr(std_engine); } // comparison int err = 0; for(int i = 0; i < nsamples; ++i) { if (fabs(std_samples[i] - dpstd_samples[i]) > eps) { std::cout << "\nError: std_sample[" << i << "] = " << std_samples[i] << ", dpstd_samples[" << i << "] = " << dpstd_samples[i]; err++; } } if(err) { std::cout << "\tFailed" << std::endl; } else { std::cout << "\tPassed" << std::endl; } return err; } template<class RealType, class UIntType> int tests_set(int nsamples) { constexpr int nparams = 2; float left_array [nparams] = {0.0, -10.0}; float right_array [nparams] = {1.0, 10.0}; int err; // Test for all non-zero parameters for(int i = 0; i < nparams; ++i) { std::cout << "uniform_real_distribution test<type>, left = " << left_array[i] << ", right = " << right_array[i] << ", nsamples = " << nsamples; err = test<RealType, UIntType>(left_array[i], right_array[i], nsamples); if(err) { return 1; } } return 0; } template<class RealType, class UIntType> int tests_set_portion(int nsamples, unsigned int part) { constexpr int nparams = 2; float left_array [nparams] = {0.0, -10.0}; float right_array [nparams] = {1.0, 10.0}; int err; // Test for all non-zero parameters for(int i = 0; i < nparams; ++i) { std::cout << "uniform_real_distribution test<type>, left = " << left_array[i] << ", right = " << right_array[i] << ", nsamples = " << nsamples << ", part = " << part; err = test_portion<RealType, UIntType>(left_array[i], right_array[i], nsamples, part); if(err) { return 1; } } return 0; } #endif // TEST_DPCPP_BACKEND_PRESENT int main() { #if TEST_DPCPP_BACKEND_PRESENT constexpr int nsamples = 100; int err; // testing float and std::uint32_t std::cout << "-----------------------------" << std::endl; std::cout << "float, std::uint32_t type" << std::endl; std::cout << "-----------------------------" << std::endl; err = tests_set<float, std::uint32_t>(nsamples); err += tests_set<float, sycl::vec<std::uint32_t, 16>>(nsamples); if(err) { std::cout << "Test FAILED" << std::endl; return 1; } // testing float and std::uint64_t std::cout << "-----------------------------" << std::endl; std::cout << "float, std::uint64_t type" << std::endl; std::cout << "-----------------------------" << std::endl; err = tests_set<float, std::uint64_t>(nsamples); err += tests_set<float, sycl::vec<std::uint64_t, 16>>(nsamples); if(err) { std::cout << "Test FAILED" << std::endl; return 1; } // testing sycl::vec<float, 16> and std::uint32_t std::cout << "----------------------------------------" << std::endl; std::cout << "sycl::vec<float, 16>, std::uint32_t type" << std::endl; std::cout << "----------------------------------------" << std::endl; err = tests_set<sycl::vec<float, 16>, std::uint32_t>(160); err += tests_set_portion<sycl::vec<float, 16>, std::uint32_t>(160, 1); err += tests_set_portion<sycl::vec<float, 16>, std::uint32_t>(100, 5); err += tests_set_portion<sycl::vec<float, 16>, std::uint32_t>(160, 16); err += tests_set_portion<sycl::vec<float, 16>, std::uint32_t>(160, 17); if(err) { std::cout << "Test FAILED" << std::endl; return 1; } // testing sycl::vec<float, 16> and sycl::vec<uint32_t, 16> std::cout << "--------------------------------------------------" << std::endl; std::cout << "sycl::vec<float, 16>, sycl::vec<uint32_t, 16> type" << std::endl; std::cout << "--------------------------------------------------" << std::endl; err = tests_set<sycl::vec<float, 16>, sycl::vec<uint32_t, 16>>(160); err += tests_set_portion<sycl::vec<float, 16>, sycl::vec<uint32_t, 16>>(160, 1); err += tests_set_portion<sycl::vec<float, 16>, sycl::vec<uint32_t, 16>>(100, 5); err += tests_set_portion<sycl::vec<float, 16>, sycl::vec<uint32_t, 16>>(160, 16); err += tests_set_portion<sycl::vec<float, 16>, sycl::vec<uint32_t, 16>>(160, 17); if(err) { std::cout << "Test FAILED" << std::endl; return 1; } // testing sycl::vec<float, 8> and sycl::vec<uint32_t, 16> std::cout << "-------------------------------------------------" << std::endl; std::cout << "sycl::vec<float, 8>, sycl::vec<uint32_t, 16> type" << std::endl; std::cout << "-------------------------------------------------" << std::endl; err = tests_set<sycl::vec<float, 8>, sycl::vec<uint32_t, 16>>(160); err += tests_set_portion<sycl::vec<float, 8>, sycl::vec<uint32_t, 16>>(160, 1); err += tests_set_portion<sycl::vec<float, 8>, sycl::vec<uint32_t, 16>>(99, 3); err += tests_set_portion<sycl::vec<float, 8>, sycl::vec<uint32_t, 16>>(80, 8); err += tests_set_portion<sycl::vec<float, 8>, sycl::vec<uint32_t, 16>>(80, 9); if(err) { std::cout << "Test FAILED" << std::endl; return 1; } // testing sycl::vec<float, 3> and sycl::vec<uint32_t, 16> std::cout << "-------------------------------------------------" << std::endl; std::cout << "sycl::vec<float, 3>, sycl::vec<uint32_t, 16> type" << std::endl; std::cout << "-------------------------------------------------" << std::endl; err = tests_set<sycl::vec<float, 3>, sycl::vec<uint32_t, 16>>(99); err += tests_set_portion<sycl::vec<float, 3>, sycl::vec<uint32_t, 16>>(160, 1); err += tests_set_portion<sycl::vec<float, 3>, sycl::vec<uint32_t, 16>>(100, 2); err += tests_set_portion<sycl::vec<float, 3>, sycl::vec<uint32_t, 16>>(99, 3); err += tests_set_portion<sycl::vec<float, 3>, sycl::vec<uint32_t, 16>>(99, 4); if(err) { std::cout << "Test FAILED" << std::endl; return 1; } #endif // TEST_DPCPP_BACKEND_PRESENT return TestUtils::done(TEST_DPCPP_BACKEND_PRESENT); }
11,205
4,249
/* * Copyright 2020 Stefan Zobel * * 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 "ComplexFloatArray.h" #ifndef JEXCEPTION_INCLUDED_ #include "JException.h" #endif /* JEXCEPTION_INCLUDED_ */ #ifndef SLIMSTRING_INCLUDED_ #include "SlimString.h" #endif /* SLIMSTRING_INCLUDED_ */ #include <string.h> // for memcpy __GCC_DONT_EXPORT void floatCopy(long len, float* mixed, MKL_Complex8* complex) { if (len > 0 && mixed && complex) { memcpy(mixed, complex, len * sizeof(MKL_Complex8)); // cblas_scopy(len, &(complex[0].real), 2, &(mixed[0]), 2); // cblas_scopy(len, &(complex[0].imag), 2, &(mixed[1]), 2); } } ComplexFloatArray::ComplexFloatArray(FloatArray& array_, bool copy) : array(array_), complex_array_len(0), complex_array(NULL), isCopy(copy) { long length = array.length(); if (length > 0) { if (length % 2 != 0) { SlimString msg("complex arrays must have even length: "); msg.append(length); throw JException(msg); } length /= 2; complex_array_len = length; if (isCopy) { complex_array = (MKL_Complex8*) mkl_malloc(length * sizeof(MKL_Complex8), 64); if (!complex_array) { SlimString msg("couldn't allocate MKL_Complex8 array of length "); msg.append(length); throw JException(msg); } memcpy(complex_array, array.ptr(), length * sizeof(MKL_Complex8)); // float* mixed = array.ptr(); // cblas_scopy(length, &(mixed[0]), 2, &(complex_array[0].real), 2); // cblas_scopy(length, &(mixed[1]), 2, &(complex_array[0].imag), 2); } else { complex_array = (MKL_Complex8*) array.ptr(); } } } MKL_Complex8* ComplexFloatArray::ptr() { return complex_array; } long ComplexFloatArray::complexLength() { return complex_array_len; } bool ComplexFloatArray::hasCopy() { return isCopy; } ComplexFloatArray::~ComplexFloatArray() { if (isCopy && complex_array) { mkl_free(complex_array); } }
2,701
930
#pragma once #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> #include <boost/property_tree/info_parser.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/scope_exit.hpp> #include <locale> #include <string> namespace bunsan::property_tree { /*! * \brief Read info from filename with relative path bug fix * * \warning This function is not safe, * it should be used only from single thread. */ template <typename Ptree> void read_info(const std::string &filename, Ptree &pt, const std::locale &loc = std::locale()) { boost::filesystem::initial_path(); // initialize for future use BOOST_SCOPE_EXIT_ALL() { boost::filesystem::current_path(boost::filesystem::initial_path()); }; boost::filesystem::current_path( boost::filesystem::absolute(boost::filesystem::path(filename)) .parent_path()); boost::property_tree::info_parser::read_info( boost::filesystem::path(filename).filename().string(), pt, loc); } } // namespace bunsan::property_tree
1,046
325
#pragma once #include <tuple> #include <vector> #include "Constants.hh" #include "OPCode.hh" #include "Operand.hh" #include "Register.hh" #include "QuadSource.hh" #include "QuadDest.hh" class Quad { public: Quad(OPCode op_code, QuadDest dest, QuadSource src_a, QuadSource src_b) : m_op_code { op_code }, m_dest { dest }, m_src_a { src_a }, m_src_b { src_b } {} std::string to_string() const; std::tuple<std::string, std::string, std::string, std::string, std::string> to_string_segments() const; const std::vector<unsigned>& label_ids() const { return m_label_ids; } bool has_label() const { return m_has_label; } void add_label(unsigned label_id); OPCode opcode() const { return m_op_code; }; QuadDest dest() const { return m_dest; } QuadSource src_a() const { return m_src_a; } QuadSource src_b() const { return m_src_b; } private: std::vector<unsigned> m_label_ids {}; bool m_has_label { false }; OPCode m_op_code; QuadDest m_dest; QuadSource m_src_a; QuadSource m_src_b; };
1,095
403
#include "stdafx.h" #include "IpcClient.h" #include <grpc/grpc.h> #include <grpc++/channel.h> #include <grpc++/client_context.h> #include <grpc++/create_channel.h> #include <grpc++/security/credentials.h> #include "ProfilingConfig.h" #include "StringUtils.h" namespace ipc = profilerHostIpc; using grpc::ClientContext; std::unique_ptr<ClientContext> IpcClient::GetClientContext() const { auto context = std::make_unique<ClientContext>(); context->AddMetadata("pid", this->processId); return context; } IpcClient::IpcClient() { auto channel = CreateChannel("localhost:7777", grpc::InsecureChannelCredentials()); this->stub = ProfilerHostIpc::NewStub(channel); this->processId = std::to_string(GetCurrentProcessId()); } void IpcClient::GetProfilingConfig() const { ipc::Void request; ipc::ProfilingConfigMsg response; this->stub->GetProfilingConfig(this->GetClientContext().get(), request, &response); auto& config = ProfilingConfig::Get(); config.SetNamespaceToProfile(ToWstring(response.namespacetoprofile())); config.SetProfilerCoreDllPath(ToWstring(response.profilercoredllpath())); } void IpcClient::RegisterMethod(const MethodMetadata& method) const { ipc::MethodMetadataMsg request; ipc::Void response; request.set_assemblyname(ToString(method.assemblyName)); request.set_typename_(ToString(method.typeName)); request.set_signature(ToString(method.signature)); request.set_token(method.token); this->stub->RegisterMethod(this->GetClientContext().get(), request, &response); }
1,566
511
#include <iostream> #include <assert.h> #include <math.h> #include "loopexpr.h" #include "vars.h" #include "constant.h" using namespace std; LoopExpr::LoopExpr (string _cv, Expression *_frome, Expression *_toe, Expression *_stepe, Expression *_bodye):frome(_frome),toe(_toe),stepe(_stepe),bodye(_bodye),controlVar(_cv){}; LoopExpr::~LoopExpr() { delete frome; delete toe; delete stepe; delete bodye; } Value* LoopExpr::execute() { Value* garbage; Value *control = frome->execute(); Value* to = toe->execute(); while(!control->equals(to)) { setControlVariableTo(control); executeBodyAndDeleteGarbage(); garbage = control; control = makeStep(control); delete garbage; } setControlVariableTo(control); delete control; delete to; return bodye->execute(); } void LoopExpr::setControlVariableTo(Value* value) { SetExpression *set = new SetExpression(controlVar, new Constant(value->clone())); Value* garbage = set->execute(); delete garbage; delete set; } void LoopExpr::executeBodyAndDeleteGarbage() { Value* garbage = bodye->execute(); delete garbage; } Value* LoopExpr::makeStep(Value* currentControlValue) { Value* stepValue = stepe->execute(); Value* newControlValue = currentControlValue->plus(stepValue); delete stepValue; return newControlValue; } void LoopExpr::print (ostream &out) { out << getID () << "[label=\"LOOP:" << controlVar << "\"];" << endl; out << getID () << "->" << frome->getID() << ";" << endl; out << getID () << "->" << toe->getID() << ";" << endl; out << getID () << "->" << stepe->getID() << ";" << endl; out << getID () << "->" << bodye->getID() << ";" << endl; frome->print (out); toe->print (out); stepe->print (out); bodye->print (out); }
1,765
645
#include "MyConditionalPrior.h" #include "DNest4/code/DNest4.h" #include <cmath> using namespace DNest4; namespace Perceptron { MyConditionalPrior::MyConditionalPrior() { } void MyConditionalPrior::from_prior(RNG& rng) { mu.from_prior(rng); const Cauchy cauchy(0.0, 5.0); do { sigma = cauchy.generate(rng); }while(std::abs(sigma) >= 50.0); sigma = exp(sigma); } double MyConditionalPrior::perturb_hyperparameters(RNG& rng) { double logH = 0.0; if(rng.rand() <= 0.5) { logH += mu.perturb(rng); } else { const Cauchy cauchy(0.0, 5.0); sigma = log(sigma); logH += cauchy.perturb(sigma, rng); if(std::abs(sigma) >= 50.0) { sigma = 1.0; return -1E300; } sigma = exp(sigma); } return logH; } double MyConditionalPrior::log_pdf(const std::vector<double>& vec) const { Laplace l(mu.get_value(), sigma); return l.log_pdf(vec[0]); } void MyConditionalPrior::from_uniform(std::vector<double>& vec) const { Laplace l(mu.get_value(), sigma); vec[0] = l.cdf_inverse(vec[0]); } void MyConditionalPrior::to_uniform(std::vector<double>& vec) const { Laplace l(mu.get_value(), sigma); vec[0] = l.cdf(vec[0]); } void MyConditionalPrior::print(std::ostream& out) const { } } // namespace Perceptron
1,363
564
/* * =========================================================================== * Loom SDK * Copyright 2011, 2012, 2013 * The Game Engine Company, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * =========================================================================== */ #include "loom/engine/loom2d/l2dQuad.h" #include "loom/engine/loom2d/l2dImage.h" #include "loom/engine/loom2d/l2dBlendMode.h" #include "loom/graphics/gfxGraphics.h" #include "loom/graphics/gfxColor.h" namespace Loom2D { Type *Quad::typeQuad = NULL; void Quad::updateNativeVertexData(lua_State *L, int index) { int didx = lua_gettop(L); index = lua_absindex(L, index); // todo: optimize VertexData in script needs to be moved native if (nativeVertexDataInvalid) { nativeVertexDataInvalid = false; const char *vmember = imageOrDerived ? "mVertexDataCache" : "mVertexData"; lualoom_getmember(L, index, vmember); lualoom_getmember(L, -1, "mRawData"); lua_rawgeti(L, -1, LSINDEXVECTOR); int rawDataTable = lua_gettop(L); int rcounter = 0; tinted = false; for (int i = 0; i < 4; i++) { GFX::VertexPosColorTex *v = &quadVertices[i]; lua_rawgeti(L, rawDataTable, rcounter++); v->x = (float)lua_tonumber(L, -1); lua_rawgeti(L, rawDataTable, rcounter++); v->y = (float)lua_tonumber(L, -1); //printf("%i %f %f\n", i, v->x, v->y); v->z = 0.0f; GFX::Color c(0); lua_rawgeti(L, rawDataTable, rcounter++); c.a = (float)lua_tonumber(L, -1); lua_rawgeti(L, rawDataTable, rcounter++); c.b = (float)lua_tonumber(L, -1); lua_rawgeti(L, rawDataTable, rcounter++); c.g = (float)lua_tonumber(L, -1); lua_rawgeti(L, rawDataTable, rcounter++); c.r = (float)lua_tonumber(L, -1); // todo: optimize this too: v->abgr = c.getHex(); if(v->abgr != 0x00FFFFFFFF) tinted = true; lua_rawgeti(L, rawDataTable, rcounter++); v->u = (float)lua_tonumber(L, -1); lua_rawgeti(L, rawDataTable, rcounter++); v->v = (float)lua_tonumber(L, -1); } lua_settop(L, didx); } } void Quad::render(lua_State *L) { if (nativeTextureID == -1) { return; } GFX::TextureInfo *tinfo = GFX::Texture::getTextureInfo(nativeTextureID); if (!tinfo) { return; } // if render state has 0.0 alpha, quad batch is invisible so don't render at all and get out of here now! renderState.alpha = parent ? parent->renderState.alpha * alpha : alpha; renderState.clampAlpha(); if(renderState.alpha == 0.0f) { return; } updateLocalTransform(); Matrix mtx; getTargetTransformationMatrix(NULL, &mtx); renderState.clipRect = parent ? parent->renderState.clipRect : Loom2D::Rectangle(0, 0, -1, -1); renderState.blendMode = (blendMode == BlendMode::AUTO && parent) ? parent->renderState.blendMode : blendMode; unsigned int blendSrc, blendDst; BlendMode::BlendFunction(renderState.blendMode, blendSrc, blendDst); if (renderState.isClipping()) GFX::Graphics::setClipRect((int)renderState.clipRect.x, (int)renderState.clipRect.y, (int)renderState.clipRect.width, (int)renderState.clipRect.height); GFX::VertexPosColorTex *v = GFX::QuadRenderer::getQuadVertexMemory(4, nativeTextureID, blendEnabled, blendSrc, blendDst, shader); GFX::VertexPosColorTex *src = quadVertices; if (!v) { return; } for (int i = 0; i < 4; i++) { *v = *src; src++; lmscalar _x = mtx.a * v->x + mtx.c * v->y + mtx.tx; lmscalar _y = mtx.b * v->x + mtx.d * v->y + mtx.ty; v->x = (float) _x; v->y = (float) _y; // modulate vertex alpha by our DisplayObject alpha setting if (renderState.alpha != 1.0f) { lmscalar va = ((float)(v->abgr >> 24)) * renderState.alpha; v->abgr = ((uint32_t)va << 24) | (v->abgr & 0x00FFFFFF); } v++; } } }
4,726
1,695
#include "pe/LdConfigDirWrapper.h" // offset from the beginning of the structure #define getStructFieldOffset(STRUCT, FIELD) ((ULONGLONG) &(STRUCT.FIELD) - (ULONGLONG)&STRUCT) bufsize_t LdConfigDirWrapper::getLdConfigDirSize() { bufsize_t dirSize = 0; if (m_Exe->getBitMode() == Executable::BITS_32) { dirSize = sizeof(pe::IMAGE_LOAD_CONFIG_DIRECTORY32); } else if (m_Exe->getBitMode() == Executable::BITS_64) { dirSize = sizeof(pe::IMAGE_LOAD_CONFIG_DIRECTORY64); } return dirSize; } bufsize_t LdConfigDirWrapper::getHdrDefinedSize() { const offset_t rva = getDirEntryAddress(); offset_t raw = INVALID_ADDR; try { raw = m_Exe->rvaToRaw(rva); } catch (CustomException &e) { raw = INVALID_ADDR; } if (raw == INVALID_ADDR) return 0; offset_t offset = INVALID_ADDR; if (m_Exe->getBitMode() == Executable::BITS_32) { pe::IMAGE_LOAD_CONFIG_DIRECTORY32 ld = { 0 }; offset = getStructFieldOffset(ld, Size); } else if (m_Exe->getBitMode() == Executable::BITS_64) { pe::IMAGE_LOAD_CONFIG_DIRECTORY64 ld = { 0 }; offset = getStructFieldOffset(ld, Size); } DWORD* sizePtr = (DWORD*) m_Exe->getContentAt((raw + offset), sizeof(DWORD)); if (!sizePtr) return 0; return bufsize_t(*sizePtr); } void* LdConfigDirWrapper::getLdConfigDirPtr() { offset_t rva = getDirEntryAddress(); BYTE *ptr = m_Exe->getContentAt(rva, Executable::RVA, this->getSize()); return ptr; } bool LdConfigDirWrapper::wrapSubentriesTable(size_t parentFieldId, size_t counterFieldId) { bool isOk = false; size_t count = this->getNumValue(counterFieldId, &isOk); if (!isOk) { return false; } for (size_t i = 0 ; i < count; i++) { LdConfigEntryWrapper *entry = new LdConfigEntryWrapper(m_Exe, this, i, parentFieldId); if (!entry || !entry->getPtr()) { delete entry; break; } this->entries.push_back(entry); this->subEntriesMap[parentFieldId].push_back(entry); } return isOk; } bool LdConfigDirWrapper::wrap() { clear(); if (!getPtr()) return false; //SEHandlerTable: wrapSubentriesTable(SEH_TABLE, SEH_COUNT); //GuardCFFunctionTable: wrapSubentriesTable(GUARD_TABLE, GUARD_COUNT); wrapSubentriesTable(GUARD_LONG_JUMP_TABLE, GUARD_LONG_JUMP_COUNT); wrapSubentriesTable(GUARD_ADDR_IAT_ENTRY_TABLE, GUARD_ADDR_IAT_ENTRY_COUNT); wrapSubentriesTable(GUARD_EH_CONT_TABLE, GUARD_EH_CONT_COUNT); return true; } void* LdConfigDirWrapper::getPtr() { return getLdConfigDirPtr(); } void LdConfigDirWrapper::clear() { std::map<uint32_t, std::vector<ExeNodeWrapper*> >::iterator mapItr; for (mapItr = this->subEntriesMap.begin(); mapItr != this->subEntriesMap.end(); mapItr++) { std::vector<ExeNodeWrapper*> &vec = mapItr->second; vec.clear(); } ExeNodeWrapper::clear(); } void* LdConfigDirWrapper::firstSubEntryPtr(size_t parentId) { bool isOk = false; offset_t offset = this->getNumValue(parentId, &isOk); if (!isOk) return NULL; Executable::addr_type aT = containsAddrType(parentId); if (aT == Executable::NOT_ADDR) return NULL; bufsize_t handlerSize = static_cast<bufsize_t>(this->firstSubEntrySize(parentId)); char *ptr = (char*) m_Exe->getContentAt(offset, aT, handlerSize); if (!ptr) return NULL; return ptr; } bufsize_t LdConfigDirWrapper::getSize() { //validate the offset const offset_t rva = getDirEntryAddress(); if (!m_Exe->isValidAddr(rva, Executable::RVA)) { return 0; } const bufsize_t hdrSize = this->getHdrDefinedSize(); const bufsize_t structSize = getLdConfigDirSize(); const bufsize_t totalSize = (hdrSize < structSize) ? hdrSize : structSize; // is the size correct const offset_t rvaEnd = rva + totalSize - 1; if (!m_Exe->isValidAddr(rvaEnd, Executable::RVA)) { return 0; } return totalSize; } offset_t LdConfigDirWrapper::_getFieldDelta(bool is32b, size_t fId) { static pe::IMAGE_LOAD_CONFIG_DIRECTORY32 ld32 = { 0 }; static pe::IMAGE_LOAD_CONFIG_DIRECTORY64 ld64 = { 0 }; //offset from the beginning of the IMAGE_LOAD_CONFIG_DIRECTORY_T strucure offset_t fieldOffset = INVALID_ADDR; switch (fId) { case SIZE : fieldOffset = (is32b) ? getStructFieldOffset(ld32, Size) : getStructFieldOffset(ld64, Size); break; case TIMEST : fieldOffset = (is32b) ? getStructFieldOffset(ld32,TimeDateStamp) : getStructFieldOffset(ld64, TimeDateStamp); break; case MAJOR_VER : fieldOffset = (is32b) ? getStructFieldOffset(ld32,MajorVersion) : getStructFieldOffset(ld64, MajorVersion); break; case MINOR_VER : fieldOffset = (is32b) ? getStructFieldOffset(ld32, MinorVersion) : getStructFieldOffset(ld64, MinorVersion); break; case GLOBAL_FLAGS_CLEAR : fieldOffset = (is32b) ? getStructFieldOffset(ld32, GlobalFlagsClear) : getStructFieldOffset(ld64, GlobalFlagsClear); break; case GLOBAL_FLAGS_SET : fieldOffset = (is32b) ? getStructFieldOffset(ld32, GlobalFlagsSet) : getStructFieldOffset(ld64, GlobalFlagsSet); break; case CRITICAT_SEC_TIMEOUT : fieldOffset = (is32b) ? getStructFieldOffset(ld32, CriticalSectionDefaultTimeout) : getStructFieldOffset(ld64, CriticalSectionDefaultTimeout); break; case DECOMMIT_FREE : fieldOffset = (is32b) ? getStructFieldOffset(ld32, DeCommitFreeBlockThreshold) : getStructFieldOffset(ld64, DeCommitFreeBlockThreshold); break; case DECOMMIT_TOTAL : fieldOffset = (is32b) ? getStructFieldOffset(ld32, DeCommitTotalFreeThreshold) : getStructFieldOffset(ld64, DeCommitTotalFreeThreshold); break; case LOCK_PREFIX : fieldOffset = (is32b) ? getStructFieldOffset(ld32, LockPrefixTable) : getStructFieldOffset(ld64, LockPrefixTable); break; case MAX_ALLOC : fieldOffset = (is32b) ? getStructFieldOffset(ld32, MaximumAllocationSize) : getStructFieldOffset(ld64, MaximumAllocationSize); break; case VIRTUAL_MEM : fieldOffset = (is32b) ? getStructFieldOffset(ld32, VirtualMemoryThreshold) : getStructFieldOffset(ld64, VirtualMemoryThreshold); break; case PROC_HEAP_FLAGS32 : //PROC_AFF_MASK64 { fieldOffset = (is32b) ? getStructFieldOffset(ld32, ProcessHeapFlags) : getStructFieldOffset(ld64, ProcessAffinityMask); break; } case PROC_AFF_MASK32 : // PROC_HEAP_FLAGS64 { fieldOffset = (is32b) ? getStructFieldOffset(ld32, ProcessAffinityMask) : getStructFieldOffset(ld64, ProcessHeapFlags); break; } case CSD_VER : fieldOffset = (is32b) ? getStructFieldOffset(ld32, CSDVersion) : getStructFieldOffset(ld64, CSDVersion); break; case DEPENDENT_LOAD_FLAGS : fieldOffset = (is32b) ? getStructFieldOffset(ld32, DependentLoadFlags) : getStructFieldOffset(ld64, DependentLoadFlags); break; case EDIT_LIST : fieldOffset = (is32b) ? getStructFieldOffset(ld32, EditList) : getStructFieldOffset(ld64, EditList); break; case SEC_COOKIE : fieldOffset = (is32b) ? getStructFieldOffset(ld32, SecurityCookie) : getStructFieldOffset(ld64, SecurityCookie); break; case SEH_TABLE : fieldOffset = (is32b) ? getStructFieldOffset(ld32, SEHandlerTable) : getStructFieldOffset(ld64, SEHandlerTable); break; case SEH_COUNT : fieldOffset = (is32b) ? getStructFieldOffset(ld32, SEHandlerCount) : getStructFieldOffset(ld64, SEHandlerCount); break; // W8.1 part: case GUARD_CHECK : fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardCFCheckFunctionPointer) : getStructFieldOffset(ld64, GuardCFCheckFunctionPointer); break; case GUARD_DISPATCH : fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardCFDispatchFunctionPointer) : getStructFieldOffset(ld64, GuardCFDispatchFunctionPointer); break; case GUARD_TABLE: fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardCFFunctionTable) : getStructFieldOffset(ld64, GuardCFFunctionTable); break; case GUARD_COUNT: fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardCFFunctionCount) : getStructFieldOffset(ld64, GuardCFFunctionCount); break; case GUARD_FLAGS: fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardFlags) : getStructFieldOffset(ld64, GuardFlags); break; // W10 part: case CODE_INTEGRITY_FLAGS: fieldOffset = (is32b) ? getStructFieldOffset(ld32, CodeIntegrity.Flags) : getStructFieldOffset(ld64, CodeIntegrity.Flags); break; case CODE_INTEGRITY_CATALOG: fieldOffset = (is32b) ? getStructFieldOffset(ld32, CodeIntegrity.Catalog) : getStructFieldOffset(ld64, CodeIntegrity.Catalog); break; case CODE_INTEGRITY_CATALOG_OFFSET: fieldOffset = (is32b) ? getStructFieldOffset(ld32, CodeIntegrity.CatalogOffset) : getStructFieldOffset(ld64, CodeIntegrity.CatalogOffset); break; case CODE_INTEGRITY_RESERVED: fieldOffset = (is32b) ? getStructFieldOffset(ld32, CodeIntegrity.Reserved) : getStructFieldOffset(ld64, CodeIntegrity.Reserved); break; case GUARD_ADDR_IAT_ENTRY_TABLE: fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardAddressTakenIatEntryTable) : getStructFieldOffset(ld64, GuardAddressTakenIatEntryTable); break; case GUARD_ADDR_IAT_ENTRY_COUNT: fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardAddressTakenIatEntryCount) : getStructFieldOffset(ld64, GuardAddressTakenIatEntryCount); break; case GUARD_LONG_JUMP_TABLE: fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardLongJumpTargetTable) : getStructFieldOffset(ld64, GuardLongJumpTargetTable); break; case GUARD_LONG_JUMP_COUNT: fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardLongJumpTargetCount) : getStructFieldOffset(ld64, GuardLongJumpTargetCount); break; case DYNAMIC_VAL_RELOC: fieldOffset = (is32b) ? getStructFieldOffset(ld32, DynamicValueRelocTable) : getStructFieldOffset(ld64, DynamicValueRelocTable); break; case CHPE_METADATA_PTR: fieldOffset = (is32b) ? getStructFieldOffset(ld32, CHPEMetadataPointer) : getStructFieldOffset(ld64, CHPEMetadataPointer); break; case GUARD_FAILURE_ROUTINE: fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardRFFailureRoutine) : getStructFieldOffset(ld64, GuardRFFailureRoutine); break; case GUARD_FAILURE_ROUTINE_FUNC_PTR: fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardRFFailureRoutineFunctionPointer) : getStructFieldOffset(ld64, GuardRFFailureRoutineFunctionPointer); break; case DYNAMIC_VAL_RELOC_TABLE_OFFSET: fieldOffset = (is32b) ? getStructFieldOffset(ld32, DynamicValueRelocTableOffset) : getStructFieldOffset(ld64, DynamicValueRelocTableOffset); break; case DYNAMIC_VAL_RELOC_TABLE_SECTION: fieldOffset = (is32b) ? getStructFieldOffset(ld32, DynamicValueRelocTableSection) : getStructFieldOffset(ld64, DynamicValueRelocTableSection); break; case RESERVED2: fieldOffset = (is32b) ? getStructFieldOffset(ld32, Reserved2) : getStructFieldOffset(ld64, Reserved2); break; case GUARD_VERIFY_STACK_PTR: fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardRFVerifyStackPointerFunctionPointer) : getStructFieldOffset(ld64, GuardRFVerifyStackPointerFunctionPointer); break; case HOT_PATCH_TABLE_OFFSET: fieldOffset = (is32b) ? getStructFieldOffset(ld32, HotPatchTableOffset) : getStructFieldOffset(ld64, HotPatchTableOffset); break; case RESERVED3: fieldOffset = (is32b) ? getStructFieldOffset(ld32, Reserved3) : getStructFieldOffset(ld64, Reserved3); break; case ENCLAVE_CONFIG_PTR: fieldOffset = (is32b) ? getStructFieldOffset(ld32, EnclaveConfigurationPointer) : getStructFieldOffset(ld64, EnclaveConfigurationPointer); break; case VOLATILE_METADATA_PTR: fieldOffset = (is32b) ? getStructFieldOffset(ld32, VolatileMetadataPointer) : getStructFieldOffset(ld64, VolatileMetadataPointer); break; case GUARD_EH_CONT_TABLE: fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardEHContinuationTable) : getStructFieldOffset(ld64, GuardEHContinuationTable); break; case GUARD_EH_CONT_COUNT: fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardEHContinuationCount) : getStructFieldOffset(ld64, GuardEHContinuationCount); break; } return fieldOffset; } void* LdConfigDirWrapper::getFieldPtr(size_t fId, size_t subField) { const bool is32b = (m_Exe->getBitMode() == Executable::BITS_32) ? true : false; offset_t fieldDelta = _getFieldDelta(is32b, fId); if (fieldDelta != INVALID_ADDR) { const offset_t hdrSize = this->getHdrDefinedSize(); if (fieldDelta >= hdrSize) { return NULL; } return m_Exe->getContentAt(this->getOffset() + fieldDelta, 1); } return NULL; } QString LdConfigDirWrapper::getFieldName(size_t fieldId) { if (!m_Exe) return ""; const bool is32bit = (m_Exe->getBitMode() == Executable::BITS_32); switch (fieldId) { case SIZE : return "Size"; case TIMEST : return "TimeDateStamp"; case MAJOR_VER : return "MajorVersion"; case MINOR_VER : return "MinorVersion"; case GLOBAL_FLAGS_CLEAR : return "GlobalFlagsClear"; case GLOBAL_FLAGS_SET : return "GlobalFlagsSet"; case CRITICAT_SEC_TIMEOUT : return "CriticalSectionDefaultTimeout"; case DECOMMIT_FREE : return "DeCommitFreeBlockThreshold"; case DECOMMIT_TOTAL : return "DeCommitTotalFreeThreshold"; case LOCK_PREFIX : return "LockPrefixTable"; case MAX_ALLOC : return "MaximumAllocationSize"; case VIRTUAL_MEM : return "VirtualMemoryThreshold"; case PROC_HEAP_FLAGS32 : //PROC_AFF_MASK64 { return (is32bit) ? "ProcessHeapFlags" : "ProcessAffinityMask"; } case PROC_AFF_MASK32 : // PROC_HEAP_FLAGS64 { return (is32bit) ? "ProcessAffinityMask" : "ProcessHeapFlags"; } case CSD_VER : return "CSDVersion"; case DEPENDENT_LOAD_FLAGS : return "DependentLoadFlags"; case EDIT_LIST : return "EditList"; case SEC_COOKIE : return "SecurityCookie"; case SEH_TABLE : return "SEHandlerTable"; case SEH_COUNT : return "SEHandlerCount"; // W8.1 part : case GUARD_CHECK : return "GuardCFCheckFunctionPtr"; case GUARD_DISPATCH : return "GuardCFDispatchFunctionPointer"; case GUARD_TABLE: return "GuardCFFunctionTable"; case GUARD_COUNT: return "GuardCFFunctionCount"; case GUARD_FLAGS: return "GuardFlags"; // W10 part: case CODE_INTEGRITY_FLAGS: return "CodeIntegrity.Flags"; //IMAGE_LOAD_CONFIG_CODE_INTEGRITY.Flags case CODE_INTEGRITY_CATALOG: return "CodeIntegrity.Catalog"; //IMAGE_LOAD_CONFIG_CODE_INTEGRITY.Catalog case CODE_INTEGRITY_CATALOG_OFFSET: return "CodeIntegrity.CatalogOffset"; //IMAGE_LOAD_CONFIG_CODE_INTEGRITY.CatalogOffset case CODE_INTEGRITY_RESERVED: return "CodeIntegrity.Reserved"; //IMAGE_LOAD_CONFIG_CODE_INTEGRITY.Reserved case GUARD_ADDR_IAT_ENTRY_TABLE: return "GuardAddressTakenIatEntryTable"; case GUARD_ADDR_IAT_ENTRY_COUNT: return "GuardAddressTakenIatEntryCount"; case GUARD_LONG_JUMP_TABLE: return "GuardLongJumpTargetTable"; case GUARD_LONG_JUMP_COUNT: return "GuardLongJumpTargetCount"; case DYNAMIC_VAL_RELOC: return "DynamicValueRelocTable"; case CHPE_METADATA_PTR: return "CHPEMetadataPointer"; case GUARD_FAILURE_ROUTINE: return "GuardRFFailureRoutine"; case GUARD_FAILURE_ROUTINE_FUNC_PTR: return "GuardRFFailureRoutineFunctionPointer"; case DYNAMIC_VAL_RELOC_TABLE_OFFSET: return "DynamicValueRelocTableOffset"; case DYNAMIC_VAL_RELOC_TABLE_SECTION: return "DynamicValueRelocTableSection"; case RESERVED2: return "Reserved2"; case GUARD_VERIFY_STACK_PTR: return "GuardRFVerifyStackPointerFunctionPointer"; case HOT_PATCH_TABLE_OFFSET: return "HotPatchTableOffset"; case RESERVED3: return "Reserved3"; case ENCLAVE_CONFIG_PTR: return "EnclaveConfigurationPointer"; case VOLATILE_METADATA_PTR: return "VolatileMetadataPointer"; case GUARD_EH_CONT_TABLE: return "GuardEHContinuationTable"; case GUARD_EH_CONT_COUNT: return "GuardEHContinuationCount"; } return getName(); } Executable::addr_type LdConfigDirWrapper::containsAddrType(size_t fieldId, size_t subField) { switch (fieldId) { case LOCK_PREFIX : case EDIT_LIST : case SEC_COOKIE : case SEH_TABLE : case GUARD_CHECK : case GUARD_DISPATCH : case GUARD_TABLE : case GUARD_ADDR_IAT_ENTRY_TABLE: case GUARD_LONG_JUMP_TABLE: case DYNAMIC_VAL_RELOC: case GUARD_FAILURE_ROUTINE: case GUARD_FAILURE_ROUTINE_FUNC_PTR: case GUARD_VERIFY_STACK_PTR: case ENCLAVE_CONFIG_PTR: case VOLATILE_METADATA_PTR: case GUARD_EH_CONT_TABLE: return Executable::VA; } return Executable::NOT_ADDR; } std::set<DWORD> LdConfigDirWrapper::getGuardFlagsSet(DWORD flags) { const size_t guardFlagsCount = 13; const DWORD guardFlags[guardFlagsCount] = { IMAGE_GUARD_CF_INSTRUMENTED, IMAGE_GUARD_CFW_INSTRUMENTED, IMAGE_GUARD_CF_FUNCTION_TABLE_PRESENT, IMAGE_GUARD_SECURITY_COOKIE_UNUSED, IMAGE_GUARD_PROTECT_DELAYLOAD_IAT, IMAGE_GUARD_DELAYLOAD_IAT_IN_ITS_OWN_SECTION, IMAGE_GUARD_CF_EXPORT_SUPPRESSION_INFO_PRESENT, IMAGE_GUARD_CF_ENABLE_EXPORT_SUPPRESSION, IMAGE_GUARD_CF_LONGJUMP_TABLE_PRESENT, IMAGE_GUARD_RF_INSTRUMENTED, IMAGE_GUARD_RF_ENABLE, IMAGE_GUARD_RF_STRICT, IMAGE_GUARD_RETPOLINE_PRESENT }; std::set<DWORD> allFlags; for (size_t i = 0; i < guardFlagsCount; ++i) { const DWORD nextFlag = guardFlags[i]; if (flags & nextFlag) { allFlags.insert(nextFlag); } } return allFlags; } QString LdConfigDirWrapper::translateGuardFlag(DWORD flags) { if (flags & IMAGE_GUARD_CF_INSTRUMENTED) { return ("CF_INSTRUMENTED"); } if (flags & IMAGE_GUARD_CFW_INSTRUMENTED) { return ("CFW_INSTRUMENTED"); } if (flags & IMAGE_GUARD_CF_FUNCTION_TABLE_PRESENT) { return ("CF_FUNCTION_TABLE_PRESENT"); } if (flags & IMAGE_GUARD_SECURITY_COOKIE_UNUSED) { return ("SECURITY_COOKIE_UNUSED"); } if (flags & IMAGE_GUARD_PROTECT_DELAYLOAD_IAT) { return ("PROTECT_DELAYLOAD_IAT"); } if (flags & IMAGE_GUARD_DELAYLOAD_IAT_IN_ITS_OWN_SECTION) { return ("DELAYLOAD_IAT_IN_ITS_OWN_SECTION"); } if (flags & IMAGE_GUARD_CF_EXPORT_SUPPRESSION_INFO_PRESENT) { return ("CF_EXPORT_SUPPRESSION_INFO_PRESENT"); } if (flags & IMAGE_GUARD_CF_ENABLE_EXPORT_SUPPRESSION) { return ("CF_ENABLE_EXPORT_SUPPRESSION"); } if (flags & IMAGE_GUARD_CF_LONGJUMP_TABLE_PRESENT) { return ("CF_LONGJUMP_TABLE_PRESENT"); } if (flags & IMAGE_GUARD_RF_INSTRUMENTED) { return ("RF_INSTRUMENTED"); } if (flags & IMAGE_GUARD_RF_ENABLE) { return ("RF_ENABLE"); } if (flags & IMAGE_GUARD_RF_STRICT) { return ("RF_STRICT"); } if (flags & IMAGE_GUARD_RETPOLINE_PRESENT) { return ("RETPOLINE_PRESENT"); } return ""; } QString LdConfigDirWrapper::translateGuardFlagsContent(const QString& delim) { bool isOk = false; DWORD GuardFlags = this->getNumValue(GUARD_FLAGS, &isOk); if (!isOk) { return "-"; } std::set<DWORD> flagsSet = LdConfigDirWrapper::getGuardFlagsSet(GuardFlags); std::set<DWORD>::iterator itr; QStringList list; for (itr = flagsSet.begin() ; itr != flagsSet.end(); itr++) { const DWORD nextFlag = *itr; const QString flagInfo = LdConfigDirWrapper::translateGuardFlag(nextFlag); if (flagInfo.length() == 0) continue; list.append(flagInfo); } return list.join(delim); } QString LdConfigDirWrapper::translateFieldContent(size_t fieldId) { if (fieldId == GUARD_FLAGS) { return translateGuardFlagsContent(";");; } return ""; } //---------------- void* LdConfigEntryWrapper::getPtr() { if (this->parentDir == NULL) return NULL; void* first = parentDir->firstSubEntryPtr(this->parentFieldId); if (first == NULL) return NULL; bufsize_t fieldSize = static_cast<bufsize_t>(parentDir->firstSubEntrySize(this->parentFieldId)); if (fieldSize == 0) return NULL; offset_t offset = this->getOffset(first); if (offset == INVALID_ADDR) return NULL; //offset from the beginning: offset_t fieldOffset = (this->entryNum * fieldSize); offset += fieldOffset; void *ptr = m_Exe->getContentAt(offset, Executable::RAW, fieldSize); return ptr; } bufsize_t LdConfigEntryWrapper::getSize() { if (this->parentDir == NULL) return 0; if (!getPtr()) return 0; bufsize_t size = static_cast<bufsize_t>(parentDir->firstSubEntrySize(this->parentFieldId)); return size; } void* LdConfigEntryWrapper::getFieldPtr(size_t fieldId, size_t subField) { void* ptr = getPtr(); if (!ptr) return NULL; if (fieldId == NONE) { return ptr; } size_t counter = getFieldsCount(); if (fieldId >= counter) return NULL; if (fieldId == HANDLER_ADDR) { return ptr; } return (void*)((ULONGLONG)ptr + sizeof(DWORD)); } bufsize_t LdConfigEntryWrapper::getFieldSize(size_t fieldId, size_t subField) { size_t count = this->getFieldsCount(); if (fieldId >= count) { return 0; } if (fieldId == HANDLER_ADDR) { return sizeof(DWORD); } return sizeof(BYTE); }
22,889
7,987
// DataTable.cpp: implementation of the CDataTable class. // ////////////////////////////////////////////////////////////////////// #include "DataTable.h" // Includes and external ptr for AssociateDLL scan #include "DBPCompiler.h" #include "direct.h" extern CDBPCompiler* g_pDBPCompiler; extern bool g_bExternaliseDLLS; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CDataTable::CDataTable() { m_dwIndex=0; m_dwType=0; m_pNumeric=0; m_pString=NULL; m_pString2=NULL; m_pNext=NULL; m_bAddedToEXEData=false; } CDataTable::CDataTable(LPSTR pInitString) { m_dwIndex=0; m_dwType=0; m_pNumeric=0; m_pString=new CStr(pInitString); m_pString2=new CStr(""); m_pNext=NULL; m_bAddedToEXEData=false; } CDataTable::~CDataTable() { SAFE_DELETE(m_pString); SAFE_DELETE(m_pString2); } void CDataTable::Free(void) { CDataTable* pCurrent = this; while(pCurrent) { CDataTable* pNext = pCurrent->GetNext(); delete pCurrent; pCurrent = pNext; } } void CDataTable::Add(CDataTable* pNew) { CDataTable* pCurrent = this; while(pCurrent->m_pNext) { pCurrent=pCurrent->GetNext(); } pCurrent->m_pNext=pNew; } bool CDataTable::AddNumeric(double dNum, DWORD dwIndex) { // Create new data item CDataTable* pNewData = new CDataTable; pNewData->SetNumeric(dNum); // Set index pNewData->SetIndex(dwIndex); // Add to Data Table Add(pNewData); // Complete return true; } bool CDataTable::AddString(LPSTR pString, DWORD dwIndex) { // Create new data item CDataTable* pNewData = new CDataTable; CStr* pStr = new CStr(pString); pNewData->SetString(pStr); pNewData->SetString2(NULL); // Set index pNewData->SetIndex(dwIndex); // Add to Data Table Add(pNewData); // Complete return true; } bool CDataTable::AddTwoStrings(LPSTR pString, LPSTR pString2, DWORD* dwIndex) { // If string is NOT unique, fail DWORD dwResult = FindString(pString); if(dwResult>0) { *dwIndex=dwResult; return false; } // Create new data item CDataTable* pNewData = new CDataTable; CStr* pStr1 = new CStr(pString); CStr* pStr2 = new CStr(pString2); pNewData->SetString(pStr1); pNewData->SetString2(pStr2); // Set index pNewData->SetIndex(*dwIndex); // Add to Data Table Add(pNewData); // Complete return true; } bool CDataTable::AddUniqueString(LPSTR pString, DWORD* dwIndex) { // If string is NOT unique, fail DWORD dwResult = FindString(pString); if(dwResult>0) { *dwIndex=dwResult; return false; } // Create new data item CDataTable* pNewData = new CDataTable; CStr* pStr = new CStr(pString); pNewData->SetString(pStr); pNewData->SetString2(NULL); // Set index pNewData->SetIndex(*dwIndex); // Add to Data Table Add(pNewData); // Complete return true; } DWORD CDataTable::FindString(LPSTR pFindString) { // Find String CDataTable* pCurrent = this; while(pCurrent) { // Match list item with search string if(pCurrent->GetString()) if(stricmp(pCurrent->GetString()->GetStr(), pFindString)==NULL) return pCurrent->GetIndex(); pCurrent=pCurrent->GetNext(); } // Failed to find return 0; } bool CDataTable::FindIndexStr(LPSTR pIndexAsString) { // Convert String to Index DWORD dwFindIndex = atoi(pIndexAsString); // Find String CDataTable* pCurrent = this; while(pCurrent) { // Match list item with search string if(pCurrent->GetString()) if(pCurrent->GetIndex()==dwFindIndex) return true; pCurrent=pCurrent->GetNext(); } // Soft Failed to find return false; } bool CDataTable::NotExcluded ( LPSTR pFilename ) { // false if excluded from compile for ( DWORD i=1; i<g_pDBPCompiler->g_dwExcludeFilesCount; i++) if ( g_pDBPCompiler->g_pExcludeFiles [ i ] ) if ( stricmp ( g_pDBPCompiler->g_pExcludeFiles [ i ], pFilename )==NULL ) return false; // lee - 270308 - u67 - do not include DLL at all if flagged if ( g_bExternaliseDLLS==true ) return false; // complete, not excluded return true; } int CDataTable::CompleteAnyLinkAssociates(void) { // Scan user plugins - check if associations require any DBPro DLLs bool bAtLeastOneUserDLLNeeds3D = false; bool bAtLeastOneUserDLLNeedsSOUND = false; // reset index DWORD dwIndex=0; DWORD dwIndexBeforeAdds=0; // First pass basic DLLs, second pass is dependence additions for ( int iAddDependentsLoop=0; iAddDependentsLoop<2; iAddDependentsLoop++ ) { for ( int iPass=0; iPass<2; iPass++ ) { // Switch to PLUGINS-XXXX Folder char pOldDir [ _MAX_PATH ]; getcwd ( pOldDir, _MAX_PATH ); // Depends on pass value if ( iPass==0 ) _chdir(g_pDBPCompiler->GetInternalFile(PATH_PLUGINSUSERFOLDER)); if ( iPass==1 ) _chdir(g_pDBPCompiler->GetInternalFile(PATH_PLUGINSLICENSEDFOLDER)); // Go through DLLs from direct-command-list CDataTable* pCurrent = this->GetNext(); while(pCurrent) { // Check if DLL is user-dll ( leefix - 011208 - u71 - gameFX needed to link to Basic3D! ) LPSTR pDLLName = pCurrent->GetString()->GetStr(); if ( strnicmp ( pDLLName, "dbpro", 5 )!=NULL || strnicmp ( pDLLName, "dbprogamefx", 11 )==NULL ) { // must be user DLL (associated with main DLL) int iAssociationCode = 0; HMODULE hModule = LoadLibrary(pDLLName); if(hModule) { // get associate dll value if any if ( iAddDependentsLoop==0 ) { typedef int ( *RETINTNOPARAM ) ( void ); RETINTNOPARAM GetAssociatedDLLs = ( RETINTNOPARAM ) GetProcAddress ( hModule, "?GetAssociatedDLLs@@YAHXZ" ); if (!GetAssociatedDLLs) GetAssociatedDLLs = (RETINTNOPARAM)GetProcAddress(hModule, "GetAssociatedDLLs"); if ( GetAssociatedDLLs ) iAssociationCode=GetAssociatedDLLs(); } else { // get num of additional dependencies int iNumDLLDependencies = 0; typedef int ( *RETINTNOPARAM ) ( void ); RETINTNOPARAM GetNumDependencies = ( RETINTNOPARAM ) GetProcAddress ( hModule, "?GetNumDependencies@@YAHXZ" ); if (!GetNumDependencies) GetNumDependencies = (RETINTNOPARAM)GetProcAddress(hModule, "GetNumDependencies"); if ( GetNumDependencies ) iNumDLLDependencies=GetNumDependencies(); if ( iNumDLLDependencies > 0 ) { typedef const char * ( *RETLPSTRNOPARAM ) ( int n ); RETLPSTRNOPARAM GetDependencyID = ( RETLPSTRNOPARAM ) GetProcAddress ( hModule, "?GetDependencyID@@YAPBDH@Z" ); if (!GetDependencyID) GetDependencyID = (RETLPSTRNOPARAM)GetProcAddress(hModule, "GetDependencyID"); // store dependencies in list for ( int iD=0; iD<iNumDLLDependencies; iD++ ) { char pDependencyStr[256]; //LPSTR pDependencyStr = new char[256]; strcpy ( pDependencyStr, GetDependencyID(iD) ); DWORD dwTry=dwIndex+1; if(AddUniqueString(pDependencyStr, &dwTry)) dwIndex=dwTry; //SAFE_DELETE(pDependencyStr); } } } } // free it if loaded if(hModule) { FreeLibrary(hModule); hModule=NULL; } // Association Codes (1=3d/2=sound/4-//) if ( iAssociationCode & 1 ) bAtLeastOneUserDLLNeeds3D=true; if ( iAssociationCode & 2 ) bAtLeastOneUserDLLNeedsSOUND=true; } // Next DLL if ( iAddDependentsLoop==0 && iPass==0 ) dwIndex++; pCurrent=pCurrent->GetNext(); } // Restore dir before continue _chdir(pOldDir); } // DLL index before adding any associations if ( iAddDependentsLoop==0 ) dwIndexBeforeAdds=dwIndex; } // link Basic3D if ( bAtLeastOneUserDLLNeeds3D ) { DWORD dwTry=dwIndex+1; if(AddUniqueString("DBProBasic3DDebug.dll", &dwTry)) dwIndex=dwTry; } // link Sound if ( bAtLeastOneUserDLLNeedsSOUND ) { DWORD dwTry=dwIndex+1; if(AddUniqueString("DBProSoundDebug.dll", &dwTry)) dwIndex=dwTry; } // Scan all DLLS, and add any that are link-associated CDataTable* pCurrent = this->GetNext(); while(pCurrent) { // If DLLTable Entry has string.. if(pCurrent->GetString()) { // DLL Name contained in stringname DWORD dwTry = 0; LPSTR pDLL = NULL; LPSTR pDLLName = pCurrent->GetString()->GetStr(); #define TRY_DLL(nm) dwTry=dwIndex+1;pDLL=nm;if(NotExcluded(pDLL))if(AddUniqueString(pDLL,&dwTry))dwIndex=dwTry // Add other DLLs Associated With These.. if(stricmp(pDLLName, "DBProSetupDebug.dll")==NULL) { // Associate DLLs TRY_DLL("DBProBasic2DDebug.dll"); TRY_DLL("DBProTextDebug.dll"); } if(stricmp(pDLLName, "DBProTextDebug.dll")==NULL) { // Associate DLLs TRY_DLL("DBProSetupDebug.dll"); } if(stricmp(pDLLName, "DBProInputDebug.dll")==NULL) { // Checklist Support TRY_DLL("DBProSystemDebug.dll"); } if(stricmp(pDLLName, "DBProSpritesDebug.dll")==NULL) { // Image Support TRY_DLL("DBProImageDebug.dll"); } if(stricmp(pDLLName, "DBProBasic3DDebug.dll")==NULL) { // Image Support TRY_DLL("DBProImageDebug.dll"); // Transforms Support TRY_DLL("DBProTransformsDebug.dll"); } if(stricmp(pDLLName, "DBProBasic2DDebug.dll")==NULL) { // Minimal DirectX TRY_DLL("DBProSetupDebug.dll"); } if(stricmp(pDLLName, "DBProImageDebug.dll")==NULL || stricmp(pDLLName, "DBProAnimationDebug.dll")==NULL || stricmp(pDLLName, "DBProBitmapDebug.dll")==NULL) { // Sprite Support for pasting TRY_DLL("DBProSpritesDebug.dll"); // Minimal DirectX TRY_DLL("DBProSetupDebug.dll"); TRY_DLL("DBProBasic2DDebug.dll"); TRY_DLL("DBProTextDebug.dll"); } if(stricmp(pDLLName, "DBProMultiplayerDebug.dll")==NULL) { // Need access to memblock support TRY_DLL("DBProMemblocksDebug.dll"); } if(stricmp(pDLLName, "DBProMemblocksDebug.dll")==NULL) { // Memblocks Access to Bitmap, Image, Sound and Mesh TRY_DLL("DBProBitmapDebug.dll"); TRY_DLL("DBProImageDebug.dll"); TRY_DLL("DBProSoundDebug.dll"); TRY_DLL("DBProBasic3DDebug.dll"); } if(stricmp(pDLLName, "DBProCameraDebug.dll")==NULL) { TRY_DLL("DBProSetupDebug.dll"); TRY_DLL("DBProImageDebug.dll"); TRY_DLL("DBProVectorsDebug.dll"); TRY_DLL("DBProTransformsDebug.dll"); TRY_DLL("DBProBasic3DDebug.dll"); } if(stricmp(pDLLName, "DBProLightDebug.dll")==NULL) { TRY_DLL("DBProSetupDebug.dll"); TRY_DLL("DBProCameraDebug.dll"); TRY_DLL("DBProVectorsDebug.dll"); TRY_DLL("DBProTransformsDebug.dll"); } if(stricmp(pDLLName, "DBProMatrixDebug.dll")==NULL) { TRY_DLL("DBProSetupDebug.dll"); TRY_DLL("DBProImageDebug.dll"); TRY_DLL("DBProCameraDebug.dll"); TRY_DLL("DBProVectorsDebug.dll"); TRY_DLL("DBProTransformsDebug.dll"); } if(stricmp(pDLLName, "DBProBasic3DDebug.dll")==NULL) { // Primary Support TRY_DLL("DBProSetupDebug.dll"); TRY_DLL("DBProImageDebug.dll"); TRY_DLL("DBProCameraDebug.dll"); TRY_DLL("DBProLightDebug.dll"); TRY_DLL("DBProTransformsDebug.dll"); // Secondary Support TRY_DLL("DBProVectorsDebug.dll"); TRY_DLL("ConvX.dll"); TRY_DLL("Conv3DS.dll"); TRY_DLL("ConvMDL.dll"); TRY_DLL("ConvMD2.dll"); TRY_DLL("ConvMD3.dll"); } if(stricmp(pDLLName, "DBProWorld3DDebug.dll")==NULL ) { // Primary Support TRY_DLL("DBProLODTerrainDebug.dll"); TRY_DLL("DBProQ2BSPDebug.dll"); TRY_DLL("DBProBasic3DDebug.dll"); TRY_DLL("DBProVectorsDebug.dll"); TRY_DLL("DBProTransformsDebug.dll"); TRY_DLL("DBProOwnBSPDebug.dll"); } if(stricmp(pDLLName, "DBProLODTerrainDebug.dll")==NULL ) { // Primary Support TRY_DLL("DBProSetupDebug.dll"); TRY_DLL("DBProImageDebug.dll"); TRY_DLL("DBProCameraDebug.dll"); TRY_DLL("DBProTransformsDebug.dll"); } if(stricmp(pDLLName, "DBProCSGDebug.dll")==NULL ) { // Primary Support TRY_DLL("DBProSetupDebug.dll"); } if(stricmp(pDLLName, "DBProParticlesDebug.dll")==NULL ) { // Primary Support TRY_DLL("DBProParticlesDebug.dll"); TRY_DLL("DBProVectorsDebug.dll"); TRY_DLL("DBProTransformsDebug.dll"); } if(stricmp(pDLLName, "DBProSystemDebug.dll")==NULL ) { // for access to display mem TRY_DLL("DBProSetupDebug.dll"); } if(stricmp(pDLLName, "DBProVectorsDebug.dll")==NULL ) { TRY_DLL("DBProSetupDebug.dll"); } if(stricmp(pDLLName, "DBProTransformsDebug.dll")==NULL) { TRY_DLL("DBProSetupDebug.dll"); } #undef TRY_DLL } // Next entry in DLL Table pCurrent=pCurrent->GetNext(); } // Complete return (dwIndex-dwIndexBeforeAdds); } // WriteDBM bool CDataTable::WriteDBMHeader(DWORD dwKindOfTable) { // Blank Line CStr strDBMBlank(1); if(g_pDBMWriter->OutputDBM(&strDBMBlank)==false) return false; // header Line CStr strDBMLine(256); if(dwKindOfTable==1) strDBMLine.SetText("STRING:"); if(dwKindOfTable==2) strDBMLine.SetText("DATA:"); if(dwKindOfTable==3) strDBMLine.SetText("DLLS:"); if(dwKindOfTable==4) strDBMLine.SetText("COMMANDS:"); if(g_pDBMWriter->OutputDBM(&strDBMLine)==false) return false; return true; } bool CDataTable::WriteDBM(void) { // Write out text CStr strDBMLine(256); strDBMLine.SetText(">>"); if(GetType()==1) { strDBMLine.AddNumericText(GetIndex()); strDBMLine.AddText("="); strDBMLine.AddDoubleText(GetNumeric()); } if(GetType()==2) { strDBMLine.AddNumericText(GetIndex()); strDBMLine.AddText("="); strDBMLine.AddText(GetString()); } // Output details if(g_pDBMWriter->OutputDBM(&strDBMLine)==false) return false; // Write next one if(GetNext()) { if((GetNext()->WriteDBM())==false) return false; } // Complete return true; }
13,633
6,150
#ifndef SNABL_FUNC_HPP #define SNABL_FUNC_HPP #include "snabl/def.hpp" #include "snabl/fimp.hpp" #include "snabl/ptrs.hpp" #include "snabl/stack.hpp" #include "snabl/std.hpp" namespace snabl { struct Lib; struct Func: Def { Lib &lib; const I64 nargs; unordered_map<Sym, unique_ptr<Fimp>> fimps; Func(const Func &)=delete; const Func &operator =(const Func &)=delete; Func(Lib &lib, Sym id, I64 nargs): Def(id), lib(lib), nargs(nargs) { } template <typename... ImpT> Fimp &add_fimp(const Fimp::Args &args, ImpT &&... imp); Fimp &get_fimp() const { return *fimps.begin()->second; } Fimp *get_best_fimp(Stack::const_iterator begin, Stack::const_iterator end) const { I64 best_score(-1); Fimp *best_fimp(nullptr); for (auto &fp: fimps) { auto &f(*fp.second); auto fs(f.score(begin, end)); if (fs != -1) { if (fs == 0) { return &f; } if (best_score == -1 || fs < best_score) { best_score = fs; best_fimp = &f; } } } return best_fimp; } }; template <typename... ImpT> Fimp &Func::add_fimp(const Fimp::Args &args, ImpT &&... imp) { auto id(Fimp::get_id(*this, args)); auto found = fimps.find(id); if (found == fimps.end()) { return *fimps.emplace(id, make_unique<Fimp>(*this, args, forward<ImpT>(imp)...)) .first->second; } auto *fi(found->second.get()); fi->~Fimp(); new (fi) Fimp(*this, args, forward<ImpT>(imp)...); return *fi; } } #endif
1,631
637
/************************************************************************************ Filename : OVR_String_FormatUtil.cpp Content : String format functions. Created : February 27, 2013 Notes : Copyright : Copyright 2013 Oculus VR, Inc. All Rights reserved. Use of this software is subject to the terms of the Oculus license agreement provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. ************************************************************************************/ #include "OVR_String.h" #include "OVR_Log.h" namespace OVR { void StringBuffer::AppendFormat(const char* format, ...) { va_list argList; va_start(argList, format); UPInt size = OVR_vscprintf(format, argList); va_end(argList); char* buffer = (char*) OVR_ALLOC(sizeof(char) * (size+1)); va_start(argList, format); UPInt result = OVR_vsprintf(buffer, size+1, format, argList); OVR_UNUSED1(result); va_end(argList); OVR_ASSERT_LOG(result == size, ("Error in OVR_vsprintf")); AppendString(buffer); OVR_FREE(buffer); } } // OVR
1,174
359
#include "file.h" #ifndef MODE_A #error MODE_A #endif int a() { return s_a; }
80
41
/* StrikeOut: a plugin that allows you to delete Ctree statements and patch the disassembly code. When StrikeOut is active, you will see context menu items in the decompiler window. (c) Elias Bachaalany <elias.bachaalany@gmail.com> */ #include "plugin.h" #include "storage.hpp" #include "utils.hpp" static ssize_t idaapi hr_callback( void* ud, hexrays_event_t event, va_list va); //------------------------------------------------------------------------- struct strikeout_plg_t : public plugmod_t, event_listener_t { action_manager_t am; eanodes_t marked; eavec_t patchstmt_queue; strikeout_plg_t() : am(this), marked(STORE_NODE_NAME) { install_hexrays_callback(hr_callback, this); setup_ui(); } ssize_t idaapi on_event(ssize_t code, va_list va) override { if (code == ui_finish_populating_widget_popup) am.on_ui_finish_populating_widget_popup(va); return 0; } void setup_ui() { auto enable_for_expr = FO_ACTION_UPDATE([], auto vu = get_widget_vdui(widget); return (vu == nullptr) ? AST_DISABLE_FOR_WIDGET : vu->item.citype != VDI_EXPR ? AST_DISABLE : AST_ENABLE; ); auto enable_for_vd = FO_ACTION_UPDATE([], auto vu = get_widget_vdui(widget); return vu == nullptr ? AST_DISABLE_FOR_WIDGET : AST_ENABLE; ); auto enable_for_disasm = FO_ACTION_UPDATE([], return get_widget_type(widget) == BWN_DISASM ? AST_ENABLE_FOR_WIDGET : AST_DISABLE_FOR_WIDGET; ); am.set_popup_path("StrikeOut/"); // Delete statement am.add_action( AMAHF_HXE_POPUP, ACTION_NAME_DELSTMT, "Delete statement", "Del", enable_for_expr, FO_ACTION_ACTIVATE([this]) { vdui_t &vu = *get_widget_vdui(ctx->widget); ea_t stmt_ea = this->do_del_stmt(vu); if (stmt_ea != BADADDR) this->marked.add(stmt_ea); vu.refresh_ctext(); return 1; } ); // Patch code am.add_action( AMAHF_IDA_POPUP, ACTION_NAME_PATCHCODE, "Patch disassembly code", "Ctrl-Shift-Del", enable_for_disasm, FO_ACTION_ACTIVATE([this]) { return this->do_patch_disasm_code(ctx->widget); } ); // Move line: up am.add_action( AMAHF_IDA_POPUP, ACTION_NAME_DISASM_LINEUP, "Move line up", "Alt-Shift-Up", enable_for_disasm, FO_ACTION_ACTIVATE([this]) { return this->do_move_disasm_line(ctx->cur_ea, true); } ); // Move line: down am.add_action( AMAHF_IDA_POPUP, ACTION_NAME_DISASM_LINEDOWN, "Move line down", "Alt-Shift-Down", enable_for_disasm, FO_ACTION_ACTIVATE([this]) { return this->do_move_disasm_line(ctx->cur_ea, false); } ); // Flush the statement patcher am.add_action( AMAHF_HXE_POPUP, ACTION_NAME_PATCHSTMT_FLUSH, "Apply patch statements queue", "Alt-Shift-End", enable_for_vd, FO_ACTION_ACTIVATE([this]) { vdui_t& vu = *get_widget_vdui(ctx->widget); this->do_flush_patch_stmt(vu); return 0; } ); // ================================ Clear ============================= am.set_popup_path("StrikeOut/Clear/"); // Transfer hidden statements as a patch am.add_action( AMAHF_HXE_POPUP | AMAHF_IDA_POPUP, ACTION_NAME_DEL2PATCH, "Reset deleted statements for current function", "Alt-Shift-Ins", FO_ACTION_UPDATE([], auto t = get_widget_type(widget); return (t == BWN_DISASM || t == BWN_PSEUDOCODE) ? AST_ENABLE_FOR_WIDGET : AST_DISABLE_FOR_WIDGET; ), FO_ACTION_ACTIVATE([this]) { this->do_transfer_to_patch_queue(ctx); vdui_t *vu = get_widget_vdui(ctx->widget); if (vu != nullptr) vu->refresh_ctext(); return 1; }); // Clear the queue patch statements am.add_action( AMAHF_HXE_POPUP | AMAHF_IDA_POPUP, ACTION_NAME_PATCHSTMT_CLEAR, "Clear patch statement queue", "Alt-Shift-Del", enable_for_vd, FO_ACTION_ACTIVATE([this]) { this->patchstmt_queue.qclear(); return 0; } ); // Reset all deleted statements am.add_action( AMAHF_HXE_POPUP, ACTION_NAME_DELSTMTS, "Clear all deleted statements", "", enable_for_vd, FO_ACTION_ACTIVATE([this]) { vdui_t &vu = *get_widget_vdui(ctx->widget); this->do_reset_stmts(vu); vu.refresh_ctext(); return 1; } ); am.set_popup_path(); hook_event_listener(HT_UI, this); } virtual ~strikeout_plg_t() { remove_hexrays_callback(hr_callback, this); } bool idaapi run(size_t) override { return false; } void transform_ctree(cfunc_t* cfunc) { marked.load(); cinsnptrvec_t marked_insn; hexrays_collect_cinsn_from_ea helper(cfunc, &marked, &marked_insn); hexrays_keep_lca_cinsns(cfunc, &helper, marked_insn); for (auto stmt_item : marked_insn) { cblock_t* cblock; cblock_t::iterator pos; if (hexrays_get_stmt_block_pos(cfunc, stmt_item, &cblock, &pos, &helper)) cblock->erase(pos); } cfunc->remove_unused_labels(); } // Move disassembly lines int do_move_disasm_line(ea_t ea, bool up) { // Sort addresses codeitem_t items[2]; items[0] = up ? ea : next_head(ea, BADADDR); items[1] = up ? prev_head(ea, 0) : ea; if (!items[0] || !items[1]) { msg("Cannot swap at %a\n", ea); return 0; } if (items[0] == items[1]) return 0; ea_t start_ea, end_ea; start_ea = items[1].ea; end_ea = items[0].ea + ea_t(items[0].size()); auto old_auto = enable_auto(false); msg("Swapping....%a and %a\n", start_ea, end_ea); del_items(start_ea, 0, end_ea - start_ea); // Paste elements end_ea = items[0].paste(start_ea); ea = items[1].paste(end_ea); // Re-create instructions create_insn(start_ea); enable_auto(old_auto); auto_wait(); ea_t navto = up ? start_ea : end_ea; jumpto(navto); return 1; } int do_patch_disasm_code(TWidget* widget) { ea_t ea2; ea_t ea1 = get_selection_range(widget, &ea2, BWN_DISASM); if (ea1 == BADADDR) return 0; msg("patched selection: %a .. %a\n", ea1, ea2); for (; ea1 < ea2; ++ea1) patch_byte(ea1, 0x90); return 1; } ea_t do_del_stmt(vdui_t& vu, bool use_helper=true) { auto cfunc = vu.cfunc; auto item = vu.item.i; hexrays_ctreeparent_visitor_t *helper = nullptr; const citem_t* stmt_item = hexrays_get_stmt_insn(cfunc, item, use_helper ? &helper : nullptr); if (stmt_item == nullptr) return BADADDR; ea_t stmt_ea = stmt_item->ea; cblock_t* cblock; cblock_t::iterator pos; if (hexrays_get_stmt_block_pos(cfunc, stmt_item, &cblock, &pos, use_helper ? helper : nullptr)) { cblock->erase(pos); cfunc->remove_unused_labels(); #if _DEBUG cfunc->verify(ALLOW_UNUSED_LABELS, true); #endif } delete helper; return stmt_ea; } void do_flush_patch_stmt(vdui_t& vu) { // Walk the tree just to get citem_t* from actual saved EAs struct collect_eas_t : public hexrays_ctreeparent_visitor_t { std::map<ea_t, int> eas; bool do_remember = false; void clear() { eas.clear(); } void remember(ea_t ea) { if (ea == BADADDR) return; auto p = eas.find(ea); if (p != eas.end()) return; insn_t ins; decode_insn(&ins, ea); eas[ea] = int(ins.size); } int idaapi visit_insn(cinsn_t* ins) override { if (do_remember) remember(ins->ea); hexrays_ctreeparent_visitor_t::visit_insn(ins); return 0; } int idaapi visit_expr(cexpr_t* expr) { if (do_remember) remember(expr->ea); hexrays_ctreeparent_visitor_t::visit_expr(expr); return 0; } } ti; auto cfunc = vu.cfunc; ti.do_remember = false; ti.apply_to(&cfunc->body, nullptr); static char noops[32] = { 0 }; if (!noops[0]) memset(noops, 0x90, sizeof(noops)); // Collect all children ti.do_remember = true; for (auto ea : patchstmt_queue) { auto citem = ti.by_ea(ea); if (citem == nullptr) continue; ti.apply_to((citem_t*)citem, nullptr); } for (auto& kv : ti.eas) { if (kv.second == 0) continue; patch_bytes(kv.first, noops, kv.second); msg("Patching %a with %d byte(s)...\n", kv.first, kv.second); } msg("Total: %u\n", uint(ti.eas.size())); patchstmt_queue.clear(); } void do_reset_stmts(vdui_t& vu) { marked.reset(); } void do_transfer_to_patch_queue(action_activation_ctx_t *ctx) { if (!marked.load() || ctx->cur_func == nullptr) { msg("No hidden statements or not positioned in a function!\n"); return; } auto f_ea = ctx->cur_func->start_ea; for (auto it = marked.nodes().begin(), end=marked.nodes().end(); it != end; ) { ea_t ea = *it; auto f = get_func(ea); if (f != nullptr && f->start_ea == f_ea) { patchstmt_queue.push_back(ea); marked.nodes().erase(it++); } else { ++it; } } marked.save(); msg("Removed %u hidden statement(s) and moved to patch queue. Refresh to pseudo-code to take effect.\n", (uint)patchstmt_queue.size()); } }; //-------------------------------------------------------------------------- // This decompiler callback handles various hexrays events. static ssize_t idaapi hr_callback(void* ud, hexrays_event_t event, va_list va) { strikeout_plg_t* plugmod = (strikeout_plg_t*)ud; switch (event) { case hxe_populating_popup: plugmod->am.on_hxe_populating_popup(va); break; case hxe_maturity: { auto cfunc = va_arg(va, cfunc_t*); ctree_maturity_t new_maturity = va_argi(va, ctree_maturity_t); if (new_maturity == CMAT_FINAL) plugmod->transform_ctree(cfunc); break; } } return 0; } //-------------------------------------------------------------------------- // Initialize the plugin. static plugmod_t* idaapi init() { return init_hexrays_plugin() ? new strikeout_plg_t() : nullptr; } //-------------------------------------------------------------------------- plugin_t PLUGIN = { IDP_INTERFACE_VERSION, PLUGIN_HIDE | PLUGIN_MULTI, init, nullptr, nullptr, "StrikeOut: Hex-Rays statements editor", "", "hxstrikeout", "" };
12,843
4,287
// GENERATED FILE - DO NOT EDIT. // Generated by generate_tests.py // // Copyright (c) 2022 Google LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "../diff_test_utils.h" #include "gtest/gtest.h" namespace spvtools { namespace diff { namespace { // Test where src and dst have cases of a switch in different order. constexpr char kSrc[] = R"( OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %4 "main" OpExecutionMode %4 LocalSize 1 1 1 OpSource ESSL 310 OpName %4 "main" OpName %7 "BufferIn" OpMemberName %7 0 "i" OpName %9 "" OpName %23 "BufferOut" OpMemberName %23 0 "o" OpName %25 "" OpMemberDecorate %7 0 Offset 0 OpDecorate %7 Block OpDecorate %9 DescriptorSet 0 OpDecorate %9 Binding 0 OpMemberDecorate %23 0 Offset 0 OpDecorate %23 BufferBlock OpDecorate %25 DescriptorSet 0 OpDecorate %25 Binding 1 %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeInt 32 0 %7 = OpTypeStruct %6 %8 = OpTypePointer Uniform %7 %9 = OpVariable %8 Uniform %10 = OpTypeInt 32 1 %11 = OpConstant %10 0 %12 = OpTypePointer Uniform %6 %23 = OpTypeStruct %6 %24 = OpTypePointer Uniform %23 %25 = OpVariable %24 Uniform %28 = OpConstant %10 1 %34 = OpConstant %6 2 %52 = OpConstant %6 1 %4 = OpFunction %2 None %3 %5 = OpLabel %13 = OpAccessChain %12 %9 %11 %14 = OpLoad %6 %13 OpSelectionMerge %22 None OpSwitch %14 %21 0 %15 1 %16 2 %17 3 %18 4 %19 5 %20 %21 = OpLabel %54 = OpAccessChain %12 %25 %11 %55 = OpLoad %6 %54 %56 = OpIAdd %6 %55 %34 %57 = OpAccessChain %12 %25 %11 OpStore %57 %56 OpBranch %22 %15 = OpLabel %26 = OpAccessChain %12 %25 %11 %27 = OpLoad %6 %26 %29 = OpIAdd %6 %27 %28 OpStore %26 %29 OpBranch %22 %16 = OpLabel %31 = OpAccessChain %12 %25 %11 %32 = OpLoad %6 %31 %33 = OpISub %6 %32 %28 OpStore %31 %33 OpBranch %17 %17 = OpLabel %35 = OpAccessChain %12 %25 %11 %36 = OpLoad %6 %35 %37 = OpIMul %6 %36 %34 %38 = OpAccessChain %12 %25 %11 OpStore %38 %37 OpBranch %22 %18 = OpLabel %40 = OpAccessChain %12 %25 %11 %41 = OpLoad %6 %40 %42 = OpUDiv %6 %41 %34 %43 = OpAccessChain %12 %25 %11 OpStore %43 %42 OpBranch %22 %19 = OpLabel %45 = OpAccessChain %12 %25 %11 %46 = OpLoad %6 %45 %47 = OpAccessChain %12 %25 %11 %48 = OpLoad %6 %47 %49 = OpIMul %6 %46 %48 %50 = OpAccessChain %12 %25 %11 OpStore %50 %49 OpBranch %22 %20 = OpLabel %53 = OpAccessChain %12 %25 %11 OpStore %53 %52 OpBranch %21 %22 = OpLabel OpReturn OpFunctionEnd)"; constexpr char kDst[] = R"( OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %4 "main" OpExecutionMode %4 LocalSize 1 1 1 OpSource ESSL 310 OpName %4 "main" OpName %7 "BufferIn" OpMemberName %7 0 "i" OpName %9 "" OpName %23 "BufferOut" OpMemberName %23 0 "o" OpName %25 "" OpMemberDecorate %7 0 Offset 0 OpDecorate %7 Block OpDecorate %9 DescriptorSet 0 OpDecorate %9 Binding 0 OpMemberDecorate %23 0 Offset 0 OpDecorate %23 BufferBlock OpDecorate %25 DescriptorSet 0 OpDecorate %25 Binding 1 %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeInt 32 0 %7 = OpTypeStruct %6 %8 = OpTypePointer Uniform %7 %9 = OpVariable %8 Uniform %10 = OpTypeInt 32 1 %11 = OpConstant %10 0 %12 = OpTypePointer Uniform %6 %23 = OpTypeStruct %6 %24 = OpTypePointer Uniform %23 %25 = OpVariable %24 Uniform %28 = OpConstant %10 1 %34 = OpConstant %6 2 %52 = OpConstant %6 1 %4 = OpFunction %2 None %3 %5 = OpLabel %13 = OpAccessChain %12 %9 %11 %14 = OpLoad %6 %13 OpSelectionMerge %22 None OpSwitch %14 %21 0 %15 1 %16 2 %17 3 %18 4 %19 5 %20 %17 = OpLabel %35 = OpAccessChain %12 %25 %11 %36 = OpLoad %6 %35 %37 = OpIMul %6 %36 %34 %38 = OpAccessChain %12 %25 %11 OpStore %38 %37 OpBranch %22 %18 = OpLabel %40 = OpAccessChain %12 %25 %11 %41 = OpLoad %6 %40 %42 = OpUDiv %6 %41 %34 %43 = OpAccessChain %12 %25 %11 OpStore %43 %42 OpBranch %22 %21 = OpLabel %54 = OpAccessChain %12 %25 %11 %55 = OpLoad %6 %54 %56 = OpIAdd %6 %55 %34 %57 = OpAccessChain %12 %25 %11 OpStore %57 %56 OpBranch %22 %20 = OpLabel %53 = OpAccessChain %12 %25 %11 OpStore %53 %52 OpBranch %21 %15 = OpLabel %26 = OpAccessChain %12 %25 %11 %27 = OpLoad %6 %26 %29 = OpIAdd %6 %27 %28 OpStore %26 %29 OpBranch %22 %19 = OpLabel %45 = OpAccessChain %12 %25 %11 %46 = OpLoad %6 %45 %47 = OpAccessChain %12 %25 %11 %48 = OpLoad %6 %47 %49 = OpIMul %6 %46 %48 %50 = OpAccessChain %12 %25 %11 OpStore %50 %49 OpBranch %22 %16 = OpLabel %31 = OpAccessChain %12 %25 %11 %32 = OpLoad %6 %31 %33 = OpISub %6 %32 %28 OpStore %31 %33 OpBranch %17 %22 = OpLabel OpReturn OpFunctionEnd )"; TEST(DiffTest, ReorderedSwitchBlocks) { constexpr char kDiff[] = R"( ; SPIR-V ; Version: 1.6 ; Generator: Khronos SPIR-V Tools Assembler; 0 -; Bound: 58 +; Bound: 62 ; Schema: 0 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %4 "main" OpExecutionMode %4 LocalSize 1 1 1 OpSource ESSL 310 OpName %4 "main" OpName %7 "BufferIn" OpMemberName %7 0 "i" OpName %9 "" OpName %23 "BufferOut" OpMemberName %23 0 "o" OpName %25 "" OpMemberDecorate %7 0 Offset 0 OpDecorate %7 Block OpDecorate %9 DescriptorSet 0 OpDecorate %9 Binding 0 OpMemberDecorate %23 0 Offset 0 OpDecorate %23 BufferBlock OpDecorate %25 DescriptorSet 0 OpDecorate %25 Binding 1 %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeInt 32 0 %7 = OpTypeStruct %6 %8 = OpTypePointer Uniform %7 %9 = OpVariable %8 Uniform %10 = OpTypeInt 32 1 %11 = OpConstant %10 0 %12 = OpTypePointer Uniform %6 %23 = OpTypeStruct %6 %24 = OpTypePointer Uniform %23 %25 = OpVariable %24 Uniform %28 = OpConstant %10 1 %34 = OpConstant %6 2 %52 = OpConstant %6 1 %4 = OpFunction %2 None %3 %5 = OpLabel %13 = OpAccessChain %12 %9 %11 %14 = OpLoad %6 %13 OpSelectionMerge %22 None OpSwitch %14 %21 0 %15 1 %16 2 %17 3 %18 4 %19 5 %20 %20 = OpLabel %53 = OpAccessChain %12 %25 %11 OpStore %53 %52 OpBranch %21 %19 = OpLabel %45 = OpAccessChain %12 %25 %11 %46 = OpLoad %6 %45 %47 = OpAccessChain %12 %25 %11 %48 = OpLoad %6 %47 %49 = OpIMul %6 %46 %48 %50 = OpAccessChain %12 %25 %11 OpStore %50 %49 OpBranch %22 %18 = OpLabel %40 = OpAccessChain %12 %25 %11 %41 = OpLoad %6 %40 %42 = OpUDiv %6 %41 %34 %43 = OpAccessChain %12 %25 %11 OpStore %43 %42 OpBranch %22 %16 = OpLabel %31 = OpAccessChain %12 %25 %11 %32 = OpLoad %6 %31 %33 = OpISub %6 %32 %28 OpStore %31 %33 OpBranch %17 %17 = OpLabel %35 = OpAccessChain %12 %25 %11 %36 = OpLoad %6 %35 %37 = OpIMul %6 %36 %34 %38 = OpAccessChain %12 %25 %11 OpStore %38 %37 OpBranch %22 %15 = OpLabel %26 = OpAccessChain %12 %25 %11 %27 = OpLoad %6 %26 %29 = OpIAdd %6 %27 %28 OpStore %26 %29 OpBranch %22 %21 = OpLabel %54 = OpAccessChain %12 %25 %11 %55 = OpLoad %6 %54 %56 = OpIAdd %6 %55 %34 %57 = OpAccessChain %12 %25 %11 OpStore %57 %56 OpBranch %22 %22 = OpLabel OpReturn OpFunctionEnd )"; Options options; DoStringDiffTest(kSrc, kDst, kDiff, options); } TEST(DiffTest, ReorderedSwitchBlocksNoDebug) { constexpr char kSrcNoDebug[] = R"( OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %4 "main" OpExecutionMode %4 LocalSize 1 1 1 OpSource ESSL 310 OpMemberDecorate %7 0 Offset 0 OpDecorate %7 Block OpDecorate %9 DescriptorSet 0 OpDecorate %9 Binding 0 OpMemberDecorate %23 0 Offset 0 OpDecorate %23 BufferBlock OpDecorate %25 DescriptorSet 0 OpDecorate %25 Binding 1 %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeInt 32 0 %7 = OpTypeStruct %6 %8 = OpTypePointer Uniform %7 %9 = OpVariable %8 Uniform %10 = OpTypeInt 32 1 %11 = OpConstant %10 0 %12 = OpTypePointer Uniform %6 %23 = OpTypeStruct %6 %24 = OpTypePointer Uniform %23 %25 = OpVariable %24 Uniform %28 = OpConstant %10 1 %34 = OpConstant %6 2 %52 = OpConstant %6 1 %4 = OpFunction %2 None %3 %5 = OpLabel %13 = OpAccessChain %12 %9 %11 %14 = OpLoad %6 %13 OpSelectionMerge %22 None OpSwitch %14 %21 0 %15 1 %16 2 %17 3 %18 4 %19 5 %20 %21 = OpLabel %54 = OpAccessChain %12 %25 %11 %55 = OpLoad %6 %54 %56 = OpIAdd %6 %55 %34 %57 = OpAccessChain %12 %25 %11 OpStore %57 %56 OpBranch %22 %15 = OpLabel %26 = OpAccessChain %12 %25 %11 %27 = OpLoad %6 %26 %29 = OpIAdd %6 %27 %28 OpStore %26 %29 OpBranch %22 %16 = OpLabel %31 = OpAccessChain %12 %25 %11 %32 = OpLoad %6 %31 %33 = OpISub %6 %32 %28 OpStore %31 %33 OpBranch %17 %17 = OpLabel %35 = OpAccessChain %12 %25 %11 %36 = OpLoad %6 %35 %37 = OpIMul %6 %36 %34 %38 = OpAccessChain %12 %25 %11 OpStore %38 %37 OpBranch %22 %18 = OpLabel %40 = OpAccessChain %12 %25 %11 %41 = OpLoad %6 %40 %42 = OpUDiv %6 %41 %34 %43 = OpAccessChain %12 %25 %11 OpStore %43 %42 OpBranch %22 %19 = OpLabel %45 = OpAccessChain %12 %25 %11 %46 = OpLoad %6 %45 %47 = OpAccessChain %12 %25 %11 %48 = OpLoad %6 %47 %49 = OpIMul %6 %46 %48 %50 = OpAccessChain %12 %25 %11 OpStore %50 %49 OpBranch %22 %20 = OpLabel %53 = OpAccessChain %12 %25 %11 OpStore %53 %52 OpBranch %21 %22 = OpLabel OpReturn OpFunctionEnd )"; constexpr char kDstNoDebug[] = R"( OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %4 "main" OpExecutionMode %4 LocalSize 1 1 1 OpSource ESSL 310 OpMemberDecorate %7 0 Offset 0 OpDecorate %7 Block OpDecorate %9 DescriptorSet 0 OpDecorate %9 Binding 0 OpMemberDecorate %23 0 Offset 0 OpDecorate %23 BufferBlock OpDecorate %25 DescriptorSet 0 OpDecorate %25 Binding 1 %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeInt 32 0 %7 = OpTypeStruct %6 %8 = OpTypePointer Uniform %7 %9 = OpVariable %8 Uniform %10 = OpTypeInt 32 1 %11 = OpConstant %10 0 %12 = OpTypePointer Uniform %6 %23 = OpTypeStruct %6 %24 = OpTypePointer Uniform %23 %25 = OpVariable %24 Uniform %28 = OpConstant %10 1 %34 = OpConstant %6 2 %52 = OpConstant %6 1 %4 = OpFunction %2 None %3 %5 = OpLabel %13 = OpAccessChain %12 %9 %11 %14 = OpLoad %6 %13 OpSelectionMerge %22 None OpSwitch %14 %21 0 %15 1 %16 2 %17 3 %18 4 %19 5 %20 %17 = OpLabel %35 = OpAccessChain %12 %25 %11 %36 = OpLoad %6 %35 %37 = OpIMul %6 %36 %34 %38 = OpAccessChain %12 %25 %11 OpStore %38 %37 OpBranch %22 %18 = OpLabel %40 = OpAccessChain %12 %25 %11 %41 = OpLoad %6 %40 %42 = OpUDiv %6 %41 %34 %43 = OpAccessChain %12 %25 %11 OpStore %43 %42 OpBranch %22 %21 = OpLabel %54 = OpAccessChain %12 %25 %11 %55 = OpLoad %6 %54 %56 = OpIAdd %6 %55 %34 %57 = OpAccessChain %12 %25 %11 OpStore %57 %56 OpBranch %22 %20 = OpLabel %53 = OpAccessChain %12 %25 %11 OpStore %53 %52 OpBranch %21 %15 = OpLabel %26 = OpAccessChain %12 %25 %11 %27 = OpLoad %6 %26 %29 = OpIAdd %6 %27 %28 OpStore %26 %29 OpBranch %22 %19 = OpLabel %45 = OpAccessChain %12 %25 %11 %46 = OpLoad %6 %45 %47 = OpAccessChain %12 %25 %11 %48 = OpLoad %6 %47 %49 = OpIMul %6 %46 %48 %50 = OpAccessChain %12 %25 %11 OpStore %50 %49 OpBranch %22 %16 = OpLabel %31 = OpAccessChain %12 %25 %11 %32 = OpLoad %6 %31 %33 = OpISub %6 %32 %28 OpStore %31 %33 OpBranch %17 %22 = OpLabel OpReturn OpFunctionEnd )"; constexpr char kDiff[] = R"( ; SPIR-V ; Version: 1.6 ; Generator: Khronos SPIR-V Tools Assembler; 0 -; Bound: 58 +; Bound: 62 ; Schema: 0 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint GLCompute %4 "main" OpExecutionMode %4 LocalSize 1 1 1 OpSource ESSL 310 OpMemberDecorate %7 0 Offset 0 OpDecorate %7 Block OpDecorate %9 DescriptorSet 0 OpDecorate %9 Binding 0 OpMemberDecorate %23 0 Offset 0 OpDecorate %23 BufferBlock OpDecorate %25 DescriptorSet 0 OpDecorate %25 Binding 1 %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeInt 32 0 %7 = OpTypeStruct %6 %8 = OpTypePointer Uniform %7 %9 = OpVariable %8 Uniform %10 = OpTypeInt 32 1 %11 = OpConstant %10 0 %12 = OpTypePointer Uniform %6 %23 = OpTypeStruct %6 %24 = OpTypePointer Uniform %23 %25 = OpVariable %24 Uniform %28 = OpConstant %10 1 %34 = OpConstant %6 2 %52 = OpConstant %6 1 %4 = OpFunction %2 None %3 %5 = OpLabel %13 = OpAccessChain %12 %9 %11 %14 = OpLoad %6 %13 OpSelectionMerge %22 None OpSwitch %14 %21 0 %15 1 %16 2 %17 3 %18 4 %19 5 %20 %20 = OpLabel %53 = OpAccessChain %12 %25 %11 OpStore %53 %52 OpBranch %21 %19 = OpLabel %45 = OpAccessChain %12 %25 %11 %46 = OpLoad %6 %45 %47 = OpAccessChain %12 %25 %11 %48 = OpLoad %6 %47 %49 = OpIMul %6 %46 %48 %50 = OpAccessChain %12 %25 %11 OpStore %50 %49 OpBranch %22 %18 = OpLabel %40 = OpAccessChain %12 %25 %11 %41 = OpLoad %6 %40 %42 = OpUDiv %6 %41 %34 %43 = OpAccessChain %12 %25 %11 OpStore %43 %42 OpBranch %22 %16 = OpLabel %31 = OpAccessChain %12 %25 %11 %32 = OpLoad %6 %31 %33 = OpISub %6 %32 %28 OpStore %31 %33 OpBranch %17 %17 = OpLabel %35 = OpAccessChain %12 %25 %11 %36 = OpLoad %6 %35 %37 = OpIMul %6 %36 %34 %38 = OpAccessChain %12 %25 %11 OpStore %38 %37 OpBranch %22 %15 = OpLabel %26 = OpAccessChain %12 %25 %11 %27 = OpLoad %6 %26 %29 = OpIAdd %6 %27 %28 OpStore %26 %29 OpBranch %22 %21 = OpLabel %54 = OpAccessChain %12 %25 %11 %55 = OpLoad %6 %54 %56 = OpIAdd %6 %55 %34 %57 = OpAccessChain %12 %25 %11 OpStore %57 %56 OpBranch %22 %22 = OpLabel OpReturn OpFunctionEnd )"; Options options; DoStringDiffTest(kSrcNoDebug, kDstNoDebug, kDiff, options); } } // namespace } // namespace diff } // namespace spvtools
17,749
7,023
// lcd_test.cpp #include "platform.h" #include "lcd_test.h" #include "hwpins.h" #include "traces.h" #include "hwlcdctrl.h" #include "hwsdram.h" #include "framebuffer16.h" #include "clockcnt.h" THwLcdCtrl lcdctrl; TFrameBuffer16 disp; #if defined(BOARD_DISCOVERY_F746) void lcd_init() { uint32_t tmp; uint32_t pinflags = 0; // LCD CONTROLLER PINS hwpinctrl.PinSetup(PORTNUM_E, 4, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_G, 12, pinflags | PINCFG_AF_12); // hwpinctrl.PinSetup(PORTNUM_I, 9, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_I, 10, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_I, 14, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_I, 15, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_J, 0, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_J, 1, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_J, 2, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_J, 3, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_J, 4, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_J, 5, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_J, 6, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_J, 7, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_J, 8, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_J, 9, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_J, 10, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_J, 11, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_J, 13, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_J, 14, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_J, 15, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_K, 0, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_K, 1, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_K, 2, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_K, 4, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_K, 5, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_K, 6, pinflags | PINCFG_AF_14); // hwpinctrl.PinSetup(PORTNUM_K, 7, pinflags | PINCFG_AF_14); // // LCD GPIO PINS hwpinctrl.PinSetup(PORTNUM_I, 12, PINCFG_OUTPUT | PINCFG_GPIO_INIT_1); // LCD_DISP hwpinctrl.PinSetup(PORTNUM_K, 3, PINCFG_OUTPUT | PINCFG_GPIO_INIT_1); // LCD_BL_CTRL // Configure the LCD clock uint32_t lcd_pixel_clock = 8000000; //lcdctrl.Init(480, 272, (void *)0x08000000); // give the rom start as the framebuffer lcdctrl.Init(480, 272, (void *)hwsdram.address); } #endif #if defined(BOARD_DISCOVERY_F429) #include "hwspi.h" TGpioPin pin_disp_cs(PORTNUM_C, 2, false);; TGpioPin pin_disp_rs(PORTNUM_D, 13, false); THwSpi disp_spi; /* Level 1 Commands */ #define LCD_SWRESET 0x01 /* Software Reset */ #define LCD_READ_DISPLAY_ID 0x04 /* Read display identification information */ #define LCD_RDDST 0x09 /* Read Display Status */ #define LCD_RDDPM 0x0A /* Read Display Power Mode */ #define LCD_RDDMADCTL 0x0B /* Read Display MADCTL */ #define LCD_RDDCOLMOD 0x0C /* Read Display Pixel Format */ #define LCD_RDDIM 0x0D /* Read Display Image Format */ #define LCD_RDDSM 0x0E /* Read Display Signal Mode */ #define LCD_RDDSDR 0x0F /* Read Display Self-Diagnostic Result */ #define LCD_SPLIN 0x10 /* Enter Sleep Mode */ #define LCD_SLEEP_OUT 0x11 /* Sleep out register */ #define LCD_PTLON 0x12 /* Partial Mode ON */ #define LCD_NORMAL_MODE_ON 0x13 /* Normal Display Mode ON */ #define LCD_DINVOFF 0x20 /* Display Inversion OFF */ #define LCD_DINVON 0x21 /* Display Inversion ON */ #define LCD_GAMMA 0x26 /* Gamma register */ #define LCD_DISPLAY_OFF 0x28 /* Display off register */ #define LCD_DISPLAY_ON 0x29 /* Display on register */ #define LCD_COLUMN_ADDR 0x2A /* Colomn address register */ #define LCD_PAGE_ADDR 0x2B /* Page address register */ #define LCD_GRAM 0x2C /* GRAM register */ #define LCD_RGBSET 0x2D /* Color SET */ #define LCD_RAMRD 0x2E /* Memory Read */ #define LCD_PLTAR 0x30 /* Partial Area */ #define LCD_VSCRDEF 0x33 /* Vertical Scrolling Definition */ #define LCD_TEOFF 0x34 /* Tearing Effect Line OFF */ #define LCD_TEON 0x35 /* Tearing Effect Line ON */ #define LCD_MAC 0x36 /* Memory Access Control register*/ #define LCD_VSCRSADD 0x37 /* Vertical Scrolling Start Address */ #define LCD_IDMOFF 0x38 /* Idle Mode OFF */ #define LCD_IDMON 0x39 /* Idle Mode ON */ #define LCD_PIXEL_FORMAT 0x3A /* Pixel Format register */ #define LCD_WRITE_MEM_CONTINUE 0x3C /* Write Memory Continue */ #define LCD_READ_MEM_CONTINUE 0x3E /* Read Memory Continue */ #define LCD_SET_TEAR_SCANLINE 0x44 /* Set Tear Scanline */ #define LCD_GET_SCANLINE 0x45 /* Get Scanline */ #define LCD_WDB 0x51 /* Write Brightness Display register */ #define LCD_RDDISBV 0x52 /* Read Display Brightness */ #define LCD_WCD 0x53 /* Write Control Display register*/ #define LCD_RDCTRLD 0x54 /* Read CTRL Display */ #define LCD_WRCABC 0x55 /* Write Content Adaptive Brightness Control */ #define LCD_RDCABC 0x56 /* Read Content Adaptive Brightness Control */ #define LCD_WRITE_CABC 0x5E /* Write CABC Minimum Brightness */ #define LCD_READ_CABC 0x5F /* Read CABC Minimum Brightness */ #define LCD_READ_ID1 0xDA /* Read ID1 */ #define LCD_READ_ID2 0xDB /* Read ID2 */ #define LCD_READ_ID3 0xDC /* Read ID3 */ /* Level 2 Commands */ #define LCD_RGB_INTERFACE 0xB0 /* RGB Interface Signal Control */ #define LCD_FRMCTR1 0xB1 /* Frame Rate Control (In Normal Mode) */ #define LCD_FRMCTR2 0xB2 /* Frame Rate Control (In Idle Mode) */ #define LCD_FRMCTR3 0xB3 /* Frame Rate Control (In Partial Mode) */ #define LCD_INVTR 0xB4 /* Display Inversion Control */ #define LCD_BPC 0xB5 /* Blanking Porch Control register */ #define LCD_DFC 0xB6 /* Display Function Control register */ #define LCD_ETMOD 0xB7 /* Entry Mode Set */ #define LCD_BACKLIGHT1 0xB8 /* Backlight Control 1 */ #define LCD_BACKLIGHT2 0xB9 /* Backlight Control 2 */ #define LCD_BACKLIGHT3 0xBA /* Backlight Control 3 */ #define LCD_BACKLIGHT4 0xBB /* Backlight Control 4 */ #define LCD_BACKLIGHT5 0xBC /* Backlight Control 5 */ #define LCD_BACKLIGHT7 0xBE /* Backlight Control 7 */ #define LCD_BACKLIGHT8 0xBF /* Backlight Control 8 */ #define LCD_POWER1 0xC0 /* Power Control 1 register */ #define LCD_POWER2 0xC1 /* Power Control 2 register */ #define LCD_VCOM1 0xC5 /* VCOM Control 1 register */ #define LCD_VCOM2 0xC7 /* VCOM Control 2 register */ #define LCD_NVMWR 0xD0 /* NV Memory Write */ #define LCD_NVMPKEY 0xD1 /* NV Memory Protection Key */ #define LCD_RDNVM 0xD2 /* NV Memory Status Read */ #define LCD_READ_ID4 0xD3 /* Read ID4 */ #define LCD_PGAMMA 0xE0 /* Positive Gamma Correction register */ #define LCD_NGAMMA 0xE1 /* Negative Gamma Correction register */ #define LCD_DGAMCTRL1 0xE2 /* Digital Gamma Control 1 */ #define LCD_DGAMCTRL2 0xE3 /* Digital Gamma Control 2 */ #define LCD_INTERFACE 0xF6 /* Interface control register */ /* Extend register commands */ #define LCD_POWERA 0xCB /* Power control A register */ #define LCD_POWERB 0xCF /* Power control B register */ #define LCD_DTCA 0xE8 /* Driver timing control A */ #define LCD_DTCB 0xEA /* Driver timing control B */ #define LCD_POWER_SEQ 0xED /* Power on sequence register */ #define LCD_3GAMMA_EN 0xF2 /* 3 Gamma enable register */ #define LCD_PRC 0xF7 /* Pump ratio control register */ /* Size of read registers */ #define LCD_READ_ID4_SIZE 3 /* Size of Read ID4 */ void disp_write_data(uint16_t avalue) { pin_disp_rs.Set1(); // Set WRX to send data pin_disp_cs.Set0(); // Reset LCD control line(/CS) and Send data disp_spi.SendData(avalue); disp_spi.WaitSendFinish(); uint16_t d16; while (disp_spi.TryRecvData(&d16)) { // } pin_disp_cs.Set1(); // Deselect: Chip Select high } void disp_write_reg(uint8_t avalue) { pin_disp_rs.Set0(); // Reset WRX to send command pin_disp_cs.Set0(); // Reset LCD control line(/CS) and Send data disp_spi.SendData(avalue); disp_spi.WaitSendFinish(); uint16_t d16; while (disp_spi.TryRecvData(&d16)) { // } pin_disp_cs.Set1(); // Deselect: Chip Select high } void init_ili9341() { TRACE("Initializing ILI9341...\r\n"); pin_disp_cs.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1); pin_disp_rs.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1); //pin_disp_cs.Set0(); //pin_disp_cs.Set1(); // init SPI5 hwpinctrl.PinSetup(PORTNUM_F, 7, PINCFG_AF_5); // SPI5.SCK hwpinctrl.PinSetup(PORTNUM_F, 8, PINCFG_AF_5 | PINCFG_PULLDOWN); // SPI5.MISO hwpinctrl.PinSetup(PORTNUM_F, 9, PINCFG_AF_5); // SPI5.MOSI disp_spi.idleclk_high = false; disp_spi.speed = 4000000; disp_spi.databits = 8; disp_spi.Init(5); delay_ms(100); /* Configure LCD */ disp_write_reg(0xCA); disp_write_data(0xC3); disp_write_data(0x08); disp_write_data(0x50); disp_write_reg(LCD_POWERB); disp_write_data(0x00); disp_write_data(0xC1); disp_write_data(0x30); disp_write_reg(LCD_POWER_SEQ); disp_write_data(0x64); disp_write_data(0x03); disp_write_data(0x12); disp_write_data(0x81); disp_write_reg(LCD_DTCA); disp_write_data(0x85); disp_write_data(0x00); disp_write_data(0x78); disp_write_reg(LCD_POWERA); disp_write_data(0x39); disp_write_data(0x2C); disp_write_data(0x00); disp_write_data(0x34); disp_write_data(0x02); disp_write_reg(LCD_PRC); disp_write_data(0x20); disp_write_reg(LCD_DTCB); disp_write_data(0x00); disp_write_data(0x00); disp_write_reg(LCD_FRMCTR1); disp_write_data(0x00); disp_write_data(0x1B); disp_write_reg(LCD_DFC); disp_write_data(0x0A); disp_write_data(0xA2); disp_write_reg(LCD_POWER1); disp_write_data(0x10); disp_write_reg(LCD_POWER2); disp_write_data(0x10); disp_write_reg(LCD_VCOM1); disp_write_data(0x45); disp_write_data(0x15); disp_write_reg(LCD_VCOM2); disp_write_data(0x90); disp_write_reg(LCD_MAC); disp_write_data(0xC8); disp_write_reg(LCD_3GAMMA_EN); disp_write_data(0x00); disp_write_reg(LCD_RGB_INTERFACE); disp_write_data(0xC2); disp_write_reg(LCD_DFC); disp_write_data(0x0A); disp_write_data(0xA7); disp_write_data(0x27); disp_write_data(0x04); /* Colomn address set */ disp_write_reg(LCD_COLUMN_ADDR); disp_write_data(0x00); disp_write_data(0x00); disp_write_data(0x00); disp_write_data(0xEF); /* Page address set */ disp_write_reg(LCD_PAGE_ADDR); disp_write_data(0x00); disp_write_data(0x00); disp_write_data(0x01); disp_write_data(0x3F); disp_write_reg(LCD_INTERFACE); disp_write_data(0x01); disp_write_data(0x00); disp_write_data(0x06); disp_write_reg(LCD_GRAM); delay_ms(200); disp_write_reg(LCD_GAMMA); disp_write_data(0x01); disp_write_reg(LCD_PGAMMA); disp_write_data(0x0F); disp_write_data(0x29); disp_write_data(0x24); disp_write_data(0x0C); disp_write_data(0x0E); disp_write_data(0x09); disp_write_data(0x4E); disp_write_data(0x78); disp_write_data(0x3C); disp_write_data(0x09); disp_write_data(0x13); disp_write_data(0x05); disp_write_data(0x17); disp_write_data(0x11); disp_write_data(0x00); disp_write_reg(LCD_NGAMMA); disp_write_data(0x00); disp_write_data(0x16); disp_write_data(0x1B); disp_write_data(0x04); disp_write_data(0x11); disp_write_data(0x07); disp_write_data(0x31); disp_write_data(0x33); disp_write_data(0x42); disp_write_data(0x05); disp_write_data(0x0C); disp_write_data(0x0A); disp_write_data(0x28); disp_write_data(0x2F); disp_write_data(0x0F); disp_write_reg(LCD_SLEEP_OUT); delay_ms(200); disp_write_reg(LCD_DISPLAY_ON); /* GRAM start writing */ disp_write_reg(LCD_GRAM); } void lcd_init() { uint32_t tmp; uint32_t pinflags = PINCFG_SPEED_MEDIUM; /* +------------------------+-----------------------+----------------------------+ + LCD pins assignment + +------------------------+-----------------------+----------------------------+ | LCD_TFT R2 <-> PC.10 | LCD_TFT G2 <-> PA.06 | LCD_TFT B2 <-> PD.06 | | LCD_TFT R3 <-> PB.00 | LCD_TFT G3 <-> PG.10 | LCD_TFT B3 <-> PG.11 | | LCD_TFT R4 <-> PA.11 | LCD_TFT G4 <-> PB.10 | LCD_TFT B4 <-> PG.12 | | LCD_TFT R5 <-> PA.12 | LCD_TFT G5 <-> PB.11 | LCD_TFT B5 <-> PA.03 | | LCD_TFT R6 <-> PB.01 | LCD_TFT G6 <-> PC.07 | LCD_TFT B6 <-> PB.08 | | LCD_TFT R7 <-> PG.06 | LCD_TFT G7 <-> PD.03 | LCD_TFT B7 <-> PB.09 | ------------------------------------------------------------------------------- | LCD_TFT HSYNC <-> PC.06 | LCDTFT VSYNC <-> PA.04 | | LCD_TFT CLK <-> PG.07 | LCD_TFT DE <-> PF.10 | ----------------------------------------------------- */ // LCD CONTROLLER PINS hwpinctrl.PinSetup(PORTNUM_A, 3, pinflags | PINCFG_AF_14); hwpinctrl.PinSetup(PORTNUM_A, 4, pinflags | PINCFG_AF_14); hwpinctrl.PinSetup(PORTNUM_A, 6, pinflags | PINCFG_AF_14); hwpinctrl.PinSetup(PORTNUM_A, 11, pinflags | PINCFG_AF_14); hwpinctrl.PinSetup(PORTNUM_A, 12, pinflags | PINCFG_AF_14); hwpinctrl.PinSetup(PORTNUM_B, 0, pinflags | PINCFG_AF_9); hwpinctrl.PinSetup(PORTNUM_B, 1, pinflags | PINCFG_AF_9); hwpinctrl.PinSetup(PORTNUM_B, 8, pinflags | PINCFG_AF_14); hwpinctrl.PinSetup(PORTNUM_B, 9, pinflags | PINCFG_AF_14); hwpinctrl.PinSetup(PORTNUM_B, 10, pinflags | PINCFG_AF_14); hwpinctrl.PinSetup(PORTNUM_B, 11, pinflags | PINCFG_AF_14); hwpinctrl.PinSetup(PORTNUM_C, 6, pinflags | PINCFG_AF_14); hwpinctrl.PinSetup(PORTNUM_C, 7, pinflags | PINCFG_AF_14); hwpinctrl.PinSetup(PORTNUM_C, 10, pinflags | PINCFG_AF_14); hwpinctrl.PinSetup(PORTNUM_D, 3, pinflags | PINCFG_AF_14); hwpinctrl.PinSetup(PORTNUM_D, 6, pinflags | PINCFG_AF_14); hwpinctrl.PinSetup(PORTNUM_F, 10, pinflags | PINCFG_AF_14); hwpinctrl.PinSetup(PORTNUM_G, 6, pinflags | PINCFG_AF_14); hwpinctrl.PinSetup(PORTNUM_G, 7, pinflags | PINCFG_AF_14); hwpinctrl.PinSetup(PORTNUM_G, 10, pinflags | PINCFG_AF_9); hwpinctrl.PinSetup(PORTNUM_G, 11, pinflags | PINCFG_AF_14); hwpinctrl.PinSetup(PORTNUM_G, 12, pinflags | PINCFG_AF_9); // The ILI9341 must be initialized trough SPI init_ili9341(); //-------------------------------------------------------------- // Configure the internal LCD controller lcdctrl.hsync = 10; lcdctrl.hbp = 20; lcdctrl.hfp = 10; lcdctrl.vsync = 2; lcdctrl.vbp = 2; lcdctrl.vfp = 5; lcdctrl.Init(240, 320, (void *)hwsdram.address); //lcdctrl.Init(240, 320, (void *)0x08000000); } #endif void lcd_test() { TRACE("--- LCD TEST ---\r\n"); lcd_init(); uint16_t w = lcdctrl.hwwidth; uint16_t h = lcdctrl.hwheight; uint16_t * pp; uint16_t color = 0x001F; uint32_t cnt = w * 10; uint32_t n; pp = (uint16_t *)hwsdram.address; for (n = 0; n < cnt; ++n) { *(pp++) = color; } #if 1 disp.Init(w, h, (void *)(hwsdram.address)); disp.FillScreen(0); disp.color = RGB16(0, 255, 0); disp.FillRect(10, 10, 100, 100, disp.color); disp.color = RGB16(255, 0, 0); disp.DrawRect(0, 0, disp.width, disp.height); disp.color = 0xffff; disp.SetCursor(50, 150); disp.DrawString("Hello World!"); #endif TRACE("LCD test finished.\r\n"); }
16,185
7,272
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "elastos/droid/internal/telephony/cdma/sms/CBearerDataHelper.h" #include "elastos/droid/internal/telephony/cdma/sms/BearerData.h" namespace Elastos { namespace Droid { namespace Internal { namespace Telephony { namespace Cdma { namespace Sms { CAR_INTERFACE_IMPL(CBearerDataHelper, Singleton, IBearerDataHelper) CAR_SINGLETON_IMPL(CBearerDataHelper) ECode CBearerDataHelper::CalcTextEncodingDetails( /* [in] */ ICharSequence* msg, /* [in] */ Boolean force7BitEncoding, /* [out] */ IGsmAlphabetTextEncodingDetails** result) { VALIDATE_NOT_NULL(result); AutoPtr<IGsmAlphabetTextEncodingDetails> gsted = BearerData::CalcTextEncodingDetails(msg, force7BitEncoding); *result = gsted; REFCOUNT_ADD(*result); return NOERROR; } ECode CBearerDataHelper::Encode( /* [in] */ IBearerData* bData, /* [out, callee] */ ArrayOf<Byte>** result) { VALIDATE_NOT_NULL(result); AutoPtr<ArrayOf<Byte> > array = BearerData::Encode(bData); *result = array; REFCOUNT_ADD(*result); return NOERROR; } ECode CBearerDataHelper::Decode( /* [in] */ ArrayOf<Byte>* smsData, /* [out] */ IBearerData** result) { VALIDATE_NOT_NULL(result); AutoPtr<IBearerData> bd = BearerData::Decode(smsData); *result = bd; REFCOUNT_ADD(*result); return NOERROR; } ECode CBearerDataHelper::Decode( /* [in] */ ArrayOf<Byte>* smsData, /* [in] */ Int32 serviceCategory, /* [out] */ IBearerData** result) { VALIDATE_NOT_NULL(result); AutoPtr<IBearerData> bd = BearerData::Decode(smsData, serviceCategory); *result = bd; REFCOUNT_ADD(*result); return NOERROR; } } // namespace Sms } // namespace Cdma } // namespace Telephony } // namespace Internal } // namespace Droid } // namespace Elastos
2,541
848
#pragma once #include <cstdint> #include <vector> namespace ssmhasher { class TestGen { private: uint32_t x; uint32_t y; uint32_t z; uint32_t w; void mix(); uint32_t randU32(); public: TestGen(); explicit TestGen(uint32_t seed); void gen(std::byte *blob, std::size_t size); }; } // namespace ssmhasher
330
144
// // Copyright (c) 2012-2021 Snowflake Computing Inc. All right reserved. // #ifndef PC_PYTHON_HELPERS_HPP #define PC_PYTHON_HELPERS_HPP #include "logging.hpp" namespace sf { namespace py { class UniqueRef; using Logger = ::sf::Logger; /** * \brief: import a python module * \param moduleName: the name of the python module * \param ref: the RAII object to manage the PyObject * \return: */ void importPythonModule(const std::string& moduleName, UniqueRef& ref); void importPythonModule(const std::string& moduleName, UniqueRef& ref, const Logger& logger); void importFromModule(const UniqueRef& moduleRef, const std::string& name, UniqueRef& ref); void importFromModule(const UniqueRef& moduleRef, const std::string& name, UniqueRef& ref, const Logger& logger); } // namespace py } // namespace sf #endif // PC_PYTHON_HELPERS_HPP
920
303
#include "pipe.h" #include "types.h" #include "common.h" #include <node_buffer.h> using namespace node; namespace opencl { #ifdef CL_VERSION_2_0 NAN_METHOD(CreatePipe) { Nan::HandleScope scope; REQ_ARGS(5); // Arg 1 NOCL_UNWRAP(context, NoCLContext, info[0]); // Arg 2 cl_mem_flags flags = Nan::To<uint32_t>(info[1]).FromJust(); // Arg 2 cl_uint size = Nan::To<uint32_t>(info[2]).FromJust(); // Arg 3 cl_uint qty = Nan::To<uint32_t>(info[3]).FromJust(); // Arg 4 if (!info[4]->IsNull()) { THROW_ERR(CL_INVALID_VALUE) } cl_int err; cl_mem pipe = ::clCreatePipe( context->getRaw(), flags, size, qty, NULL, &err ); CHECK_ERR(err); info.GetReturnValue().Set(NOCL_WRAP(NoCLMem, pipe)); } NAN_METHOD(GetPipeInfo) { Nan::HandleScope scope; REQ_ARGS(2); // Arg 0 NOCL_UNWRAP(mem, NoCLMem, info[0]); // Arg 1 cl_pipe_info param_name = Nan::To<uint32_t>(info[1]).FromJust(); switch(param_name) { case CL_PIPE_MAX_PACKETS: case CL_PIPE_PACKET_SIZE: { cl_uint val; CHECK_ERR(::clGetPipeInfo(mem->getRaw(),param_name,sizeof(cl_uint), &val, NULL)) info.GetReturnValue().Set(JS_INT(val)); return; } } return Nan::ThrowError(JS_STR(opencl::getExceptionMessage(CL_INVALID_VALUE))); } #endif namespace Pipe { NAN_MODULE_INIT(init) { #ifdef CL_VERSION_2_0 Nan::SetMethod(target, "createPipe", CreatePipe); Nan::SetMethod(target, "getPipeInfo", GetPipeInfo); #endif } } // namespace Pipe } // namespace opencl
1,534
657
#include "src/cpp/learn/backprop/fully_connected.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "src/cpp/learn/backprop/test_utils.h" namespace coral { namespace learn { namespace backprop { namespace { using ::Eigen::MatrixXf; using ::testing::FloatEq; using ::testing::FloatNear; using ::testing::Pointwise; TEST(FullyConnectedTest, SimpleInputs) { Tensor mat_x(2, 5); mat_x << 0, 1, 2, 3, 4, 5, 6, 7, 8, 9; Tensor mat_w = mat_x.transpose(); Tensor vec_b(1, 2); vec_b << 1, 1; std::vector<Tensor> inputs = {mat_x, mat_w, vec_b}; Tensor mat_y_expected(2, 2); mat_y_expected << 31, 81, 81, 256; FullyConnected fc_forward; std::vector<Tensor> outputs = fc_forward.Compute(inputs); Tensor* mat_y = &outputs[0]; EXPECT_THAT(mat_y->reshaped(), Pointwise(FloatEq(), mat_y_expected.reshaped())); } TEST(FullyConnectedGradientTest, GradientOfAveragingElementsOfY) { Tensor mat_x(2, 3); mat_x << 0, 1, 2, 3, 4, 5; Tensor mat_w(3, 1); mat_w << 0, 1, 2; Tensor vec_b(1, 1); vec_b << 7; std::vector<Tensor> inputs = {mat_x, mat_w, vec_b}; // dmat_y is a vector of constants equal to 1/numElements, because the // derivative of the Average value with respect to each element of mat_y is // 1/numElements Tensor dmat_y = Tensor::Ones(mat_x.rows(), mat_w.cols()); dmat_y *= 1.0 / dmat_y.size(); FullyConnected fc; auto x_fc_avg = [&fc, &mat_w, &vec_b](const Tensor& x) { return fc.Compute({x, mat_w, vec_b})[0].mean(); }; auto w_fc_avg = [&fc, &mat_x, &vec_b](const Tensor& w) { return fc.Compute({mat_x, w, vec_b})[0].mean(); }; auto b_fc_avg = [&fc, &mat_x, &mat_w](const Tensor& b) { return fc.Compute({mat_x, mat_w, b})[0].mean(); }; Tensor dx_numerical = numerical_gradient(x_fc_avg, &mat_x); Tensor dw_numerical = numerical_gradient(w_fc_avg, &mat_w); Tensor db_numerical = numerical_gradient(b_fc_avg, &vec_b); inputs.push_back(dmat_y); FullyConnectedGradient fc_gradient; std::vector<Tensor> outputs = fc_gradient.Compute(inputs); const auto& dmat_x = outputs[0]; const auto& dmat_w = outputs[1]; const auto& dvec_b = outputs[2]; EXPECT_THAT(dmat_x.reshaped(), Pointwise(FloatNear(2e-3), dx_numerical.reshaped())); EXPECT_THAT(dmat_w.reshaped(), Pointwise(FloatNear(2e-3), dw_numerical.reshaped())); EXPECT_THAT(dvec_b.reshaped(), Pointwise(FloatNear(2e-3), db_numerical.reshaped())); } TEST(FullyConnectedGradientTest, GradientOfSummingElementsOfY) { Tensor mat_x(3, 3); mat_x << 0, 1, 2, 3, 4, 5, 6, 7, 8; Tensor mat_w(3, 5); mat_w << 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2; Tensor vec_b(1, 5); vec_b << 4, 3, 2, 1, 0; // dmat_y is a vector of ones, because the derivative of the Summed value with // respect to each element of mat_y is 1. Tensor dmat_y = MatrixXf::Ones(mat_x.rows(), mat_w.cols()); FullyConnected fc; auto x_fc_sum = [&fc, &mat_w, &vec_b](const Tensor& x) { return fc.Compute({x, mat_w, vec_b})[0].sum(); }; auto w_fc_sum = [&fc, &mat_x, &vec_b](const Tensor& w) { return fc.Compute({mat_x, w, vec_b})[0].sum(); }; auto b_fc_sum = [&fc, &mat_x, &mat_w](const Tensor& b) { return fc.Compute({mat_x, mat_w, b})[0].sum(); }; Tensor dx_numerical = numerical_gradient(x_fc_sum, &mat_x); Tensor dw_numerical = numerical_gradient(w_fc_sum, &mat_w); Tensor db_numerical = numerical_gradient(b_fc_sum, &vec_b); FullyConnectedGradient fc_gradient; std::vector<Tensor> outputs = fc_gradient.Compute({mat_x, mat_w, vec_b, dmat_y}); const auto& dmat_x = outputs[0]; const auto& dmat_w = outputs[1]; const auto& dvec_b = outputs[2]; EXPECT_THAT(dmat_x.reshaped(), Pointwise(FloatNear(5e-2), dx_numerical.reshaped())); EXPECT_THAT(dmat_w.reshaped(), Pointwise(FloatNear(5e-2), dw_numerical.reshaped())); EXPECT_THAT(dvec_b.reshaped(), Pointwise(FloatNear(5e-2), db_numerical.reshaped())); } } // namespace } // namespace backprop } // namespace learn } // namespace coral
4,079
1,799
/******************************************************************************* * Copyright 2013-2019 Aerospike, Inc. * * 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 <cstdint> #include <node.h> #include <node_buffer.h> #if defined(_MSC_VER) #include "io.h" #include "fcntl.h" #endif extern "C" { #include <aerospike/aerospike.h> #include <aerospike/aerospike_key.h> #include <aerospike/aerospike_batch.h> #include <aerospike/as_key.h> #include <aerospike/as_record.h> #include <aerospike/as_record_iterator.h> #include <aerospike/aerospike_scan.h> #include <aerospike/as_arraylist.h> #include <aerospike/as_arraylist_iterator.h> #include <aerospike/as_boolean.h> #include <aerospike/as_geojson.h> #include <aerospike/as_hashmap.h> #include <aerospike/as_hashmap_iterator.h> #include <aerospike/as_pair.h> #include <aerospike/as_scan.h> #include <aerospike/as_map.h> #include <aerospike/as_nil.h> #include <aerospike/as_stringmap.h> #include <aerospike/as_vector.h> #include <citrusleaf/alloc.h> } #include "client.h" #include "conversions.h" #include "log.h" #include "enums.h" #include "string.h" using namespace node; using namespace v8; const char * DoubleType = "Double"; const char * GeoJSONType = "GeoJSON"; /******************************************************************************* * FUNCTIONS ******************************************************************************/ int get_string_property(char** strp, Local<Object> obj, char const* prop, const LogInfo* log) { Nan::HandleScope scope; Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked(); if (!value->IsString()) { as_v8_error(log, "Type error: %s property should be string", prop); return AS_NODE_PARAM_ERR; } (*strp) = strdup(*Nan::Utf8String(value)); as_v8_detail(log, "%s => \"%s\"", prop, *strp); return AS_NODE_PARAM_OK; } int get_optional_string_property(char** strp, bool* defined, Local<Object> obj, char const* prop, const LogInfo* log) { Nan::HandleScope scope; Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked(); if (value->IsString()) { if (defined != NULL) (*defined) = true; (*strp) = strdup(*Nan::Utf8String(value)); as_v8_detail(log, "%s => \"%s\"", prop, *strp); } else if (value->IsUndefined() || value->IsNull()) { if (defined != NULL) (*defined) = false; } else { as_v8_error(log, "Type error: %s property should be string", prop); return AS_NODE_PARAM_ERR; } return AS_NODE_PARAM_OK; } int get_int_property(int* intp, Local<Object> obj, char const* prop, const LogInfo* log) { Nan::HandleScope scope; Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked(); if (!value->IsNumber()) { as_v8_error(log, "Type error: %s property should be integer", prop); return AS_NODE_PARAM_ERR; } (*intp) = Nan::To<int>(value).FromJust(); as_v8_detail(log, "%s => (int) %d", prop, *intp); return AS_NODE_PARAM_OK; } int get_optional_int_property(int* intp, bool* defined, Local<Object> obj, char const* prop, const LogInfo* log) { Nan::HandleScope scope; Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked(); if (value->IsNumber()) { if (defined != NULL) (*defined) = true; (*intp) = Nan::To<int>(value).FromJust(); as_v8_detail(log, "%s => (int) %d", prop, *intp); } else if (value->IsUndefined() || value->IsNull()) { if (defined != NULL) (*defined) = false; } else { as_v8_error(log, "Type error: %s property should be integer", prop); return AS_NODE_PARAM_ERR; } return AS_NODE_PARAM_OK; } int get_int64_property(int64_t* intp, Local<Object> obj, char const* prop, const LogInfo* log) { Nan::HandleScope scope; Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked(); if (!value->IsNumber()) { as_v8_error(log, "Type error: %s property should be integer", prop); return AS_NODE_PARAM_ERR; } (*intp) = Nan::To<int64_t>(value).FromJust(); as_v8_detail(log, "%s => (int64) %d", prop, *intp); return AS_NODE_PARAM_OK; } int get_uint32_property(uint32_t* uintp, Local<Object> obj, char const* prop, const LogInfo* log) { Nan::HandleScope scope; Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked(); if (value->IsNumber()) { (*uintp) = Nan::To<uint32_t>(value).FromJust(); as_v8_detail(log, "%s => (uint32) %d", prop, *uintp); } else { as_v8_error(log, "Type error: %s property should be integer (uint32)", prop); return AS_NODE_PARAM_ERR; } return AS_NODE_PARAM_OK; } int get_optional_int64_property(int64_t* intp, bool* defined, Local<Object> obj, char const* prop, const LogInfo* log) { Nan::HandleScope scope; Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked(); if (value->IsNumber()) { if (defined != NULL) (*defined) = true; (*intp) = Nan::To<int64_t>(value).FromJust(); as_v8_detail(log, "%s => (int64) %d", prop, *intp); } else if (value->IsUndefined() || value->IsNull()) { if (defined != NULL) (*defined) = false; as_v8_detail(log, "%s => undefined", prop); } else { as_v8_error(log, "Type error: %s property should be integer", prop); return AS_NODE_PARAM_ERR; } return AS_NODE_PARAM_OK; } int get_optional_int32_property(int32_t* intp, bool* defined, Local<Object> obj, char const* prop, const LogInfo* log) { Nan::HandleScope scope; Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked(); if (value->IsNumber()) { if (defined != NULL) (*defined) = true; (*intp) = Nan::To<int32_t>(value).FromJust(); as_v8_detail(log, "%s => (uint32) %d", prop, *intp); } else if (value->IsUndefined() || value->IsNull()) { if (defined != NULL) (*defined) = false; as_v8_detail(log, "%s => undefined", prop); } else { as_v8_error(log, "Type error: %s property should be integer (int32)", prop); return AS_NODE_PARAM_ERR; } return AS_NODE_PARAM_OK; } int get_optional_uint32_property(uint32_t* intp, bool* defined, Local<Object> obj, char const* prop, const LogInfo* log) { Nan::HandleScope scope; Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked(); if (value->IsNumber()) { if (defined != NULL) (*defined) = true; (*intp) = Nan::To<uint32_t>(value).FromJust(); as_v8_detail(log, "%s => (uint32) %d", prop, *intp); } else if (value->IsUndefined() || value->IsNull()) { if (defined != NULL) (*defined) = false; as_v8_detail(log, "%s => undefined", prop); } else { as_v8_error(log, "Type error: %s property should be integer (uint32)", prop); return AS_NODE_PARAM_ERR; } return AS_NODE_PARAM_OK; } int get_optional_bool_property(bool* boolp, bool* defined, Local<Object> obj, char const* prop, const LogInfo* log) { Nan::HandleScope scope; Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked(); if (value->IsBoolean()) { if (defined != NULL) (*defined) = true; (*boolp) = Nan::To<bool>(value).FromJust(); as_v8_detail(log, "%s => (bool) %d", prop, *boolp); } else if (value->IsUndefined() || value->IsNull()) { if (defined != NULL) (*defined) = false; as_v8_detail(log, "%s => undefined", prop); } else { as_v8_error(log, "Type error: %s property should be boolean", prop); return AS_NODE_PARAM_ERR; } return AS_NODE_PARAM_OK; } int get_bool_property(bool* boolp, Local<Object> obj, char const* prop, const LogInfo* log) { Nan::HandleScope scope; Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked(); if (value->IsBoolean()) { (*boolp) = Nan::To<bool>(value).FromJust(); as_v8_detail(log, "%s => (bool) %d", prop, *boolp); } else { as_v8_error(log, "Type error: %s property should be boolean", prop); return AS_NODE_PARAM_ERR; } return AS_NODE_PARAM_OK; } int get_list_property(as_list** list, Local<Object> obj, char const* prop, const LogInfo* log) { Nan::HandleScope scope; Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked(); if (!value->IsArray()) { as_v8_error(log, "Type error: %s property should be array", prop); return AS_NODE_PARAM_ERR; } return list_from_jsarray(list, Local<Array>::Cast(value), log); } int get_bytes_property(uint8_t** bytes, int* size, Local<Object> obj, char const* prop, const LogInfo* log) { Nan::HandleScope scope; Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked(); if (!node::Buffer::HasInstance(value)) { as_v8_error(log, "Type error: %s property should be Buffer", prop); return AS_NODE_PARAM_ERR; } as_v8_debug(log, "Extracting bytes from JS Buffer"); if (extract_blob_from_jsobject(bytes, size, value.As<Object>(), log) != AS_NODE_PARAM_OK) { as_v8_error(log, "Extracting bytes from a JS Buffer failed"); return AS_NODE_PARAM_ERR; } return AS_NODE_PARAM_OK; } int get_asval_property(as_val** value, Local<Object> obj, const char* prop, const LogInfo* log) { Nan::HandleScope scope; Local<Value> v8value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked(); if (v8value->IsUndefined()) { as_v8_error(log, "Type error: %s property should not be undefined", prop); return AS_NODE_PARAM_ERR; } return asval_from_jsvalue(value, v8value, log); } int get_optional_asval_property(as_val** value, bool* defined, Local<Object> obj, const char* prop, const LogInfo* log) { Nan::HandleScope scope; Local<Value> v8value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked(); if (v8value->IsUndefined() || v8value->IsNull()) { if (defined != NULL) (*defined) = false; as_v8_detail(log, "%s => undefined", prop); return AS_NODE_PARAM_OK; } if (defined != NULL) (*defined) = true; return asval_from_jsvalue(value, v8value, log); } int host_from_jsobject(Local<Object> obj, char** addr, uint16_t* port, const LogInfo* log) { Local<Value> v8_addr = Nan::Get(obj, Nan::New("addr").ToLocalChecked()).ToLocalChecked(); Local<Value> v8_port = Nan::Get(obj, Nan::New("port").ToLocalChecked()).ToLocalChecked(); if (v8_addr->IsString()) { *addr = (char*) malloc(HOST_ADDRESS_SIZE); strcpy(*addr, *Nan::Utf8String(v8_addr.As<String>())); as_v8_detail(log, "host addr : %s", (*addr)); } else { return AS_NODE_PARAM_ERR; } if (v8_port->IsNumber()) { *port = (uint16_t) Nan::To<uint32_t>(v8_port).FromJust(); } else { return AS_NODE_PARAM_ERR; } return AS_NODE_PARAM_OK; } int log_from_jsobject(LogInfo* log, Local<Object> obj) { int rc = AS_NODE_PARAM_OK; as_log_level level = log->level; FILE* fd = log->fd; if (obj->IsObject()) { Local<Object> v8_log = obj.As<Object>(); Local<Value> v8_level = Nan::Get(v8_log, Nan::New("level").ToLocalChecked()).ToLocalChecked(); Local<Value> v8_file = Nan::Get(v8_log, Nan::New("file").ToLocalChecked()).ToLocalChecked(); // `level` is optional if (v8_level->IsNumber()){ level = (as_log_level) Nan::To<int>(v8_level).FromJust(); } else if (v8_level->IsNull() || v8_level->IsUndefined()){ // `null` and `undefined` imply the value should not change. } else { // Any other value is a bad parameter rc = AS_NODE_PARAM_ERR; } // `file` is optional if (rc == AS_NODE_PARAM_OK) { if (v8_file->IsNumber()) { int fildes = Nan::To<int>(v8_file).FromJust(); #if !defined(_MSC_VER) fd = fdopen(fildes, "a"); #else intptr_t osfptr = _get_osfhandle(fildes); int osfd = _open_osfhandle(osfptr, O_APPEND); fd = _fdopen(osfd, "a"); #endif if (fd == NULL) { fprintf(stderr, "Could not open file descriptor for logging: %s\n", strerror(errno)); rc = AS_NODE_PARAM_ERR; } } else if (v8_file->IsNull() || v8_file->IsUndefined()){ // `null` and `undefined` imply the value should not change. } else { // Any other value is a bad parameter rc = AS_NODE_PARAM_ERR; } } } else { // The value should be an object. Otherwise it should fail. rc = AS_NODE_PARAM_ERR; } // Only if no error occurred do we set the log values. if (rc == AS_NODE_PARAM_OK) { log->level = level; log->fd = fd; } return rc; } as_val* asval_clone(const as_val* val, const LogInfo* log) { as_val_t t = as_val_type( (as_val*)val); as_val* clone_val = NULL; switch(t) { case AS_NIL: { clone_val = (as_val*) &as_nil; break; } case AS_BOOLEAN: { as_boolean *bool_val = as_boolean_fromval(val); as_boolean *clone_bool = as_boolean_new(bool_val->value); if( clone_bool == NULL) { as_v8_error(log, "cloning a boolean value failed"); } clone_val = as_boolean_toval(clone_bool); break; } case AS_INTEGER: { as_integer* int_val = as_integer_fromval( val ); int64_t ival = as_integer_get( int_val); as_v8_detail(log, "Cloning Integer value %d", ival); as_integer* clone_int = as_integer_new(ival); if(clone_int == NULL) { as_v8_error(log, "Cloning integer failed"); } clone_val = as_integer_toval(clone_int); break; } case AS_STRING: { as_string* str_val = as_string_fromval( val ); char* strval = as_string_get( str_val); as_v8_detail(log, "Cloning String value %s", strval); char* clone_str = (char*) cf_strdup( strval); if(clone_str == NULL) { as_v8_error(log, "cloning string failed"); } as_string* clone_as = as_string_new(clone_str, true); if(clone_as == NULL) { as_v8_error(log, "cloning string failed"); } clone_val = as_string_toval( clone_as); break; } case AS_BYTES: { as_bytes* bytes_val = as_bytes_fromval( val); size_t size = as_bytes_size(bytes_val); uint8_t *bytes = (uint8_t*) cf_malloc(size); memcpy(bytes, as_bytes_get(bytes_val), size); as_v8_detail(log, "Cloning Blob value %u ", bytes); clone_val = as_bytes_toval(as_bytes_new_wrap( bytes, size, true)); break; } case AS_LIST: { as_arraylist* list = (as_arraylist*) as_list_fromval((as_val*)val); clone_val = as_list_toval( (as_list*)as_arraylist_new(as_arraylist_size(list), list->block_size)); as_arraylist_iterator it; as_arraylist_iterator_init( &it, list); int index = 0; as_v8_detail(log, "Cloning a list value of size %d ", as_arraylist_size(list)); while( as_arraylist_iterator_has_next( &it)) { as_val* arr_element = (as_val*) as_arraylist_iterator_next( &it); as_val* clone_element = asval_clone( arr_element, log); as_arraylist_set((as_arraylist*) clone_val, index++, clone_element); } as_v8_detail(log, "Cloning a list SUCCESS"); break; } case AS_MAP: { as_hashmap* map = (as_hashmap*) as_map_fromval(val); clone_val = as_map_toval( (as_map*)as_hashmap_new(as_hashmap_size(map))); as_hashmap_iterator it; as_hashmap_iterator_init( &it, map); while( as_hashmap_iterator_has_next( &it )) { as_pair* pair = (as_pair*) as_hashmap_iterator_next( &it); as_val* orig_key = as_pair_1(pair); as_val* orig_val = as_pair_2(pair); as_val* clone_key = asval_clone( orig_key, log); as_val* clone_mapval = asval_clone( orig_val, log); as_hashmap_set( (as_hashmap*) clone_val, clone_key, clone_mapval); } as_v8_detail( log, "Cloning a map SUCCESS"); break; } case AS_DOUBLE: { as_double * dbl_val = as_double_fromval(val); double dval = as_double_get(dbl_val); as_v8_detail(log, "Cloning double value %g", dval); as_double * clone_dbl = as_double_new(dval); if(clone_dbl == NULL) { as_v8_error(log, "Cloning double failed"); } clone_val = as_double_toval(clone_dbl); break; } case AS_GEOJSON: { as_geojson * geo_val = as_geojson_fromval(val); char* strval = as_geojson_get(geo_val); as_v8_detail(log, "Cloning GeoJSON value %s", strval); char* clone_str = (char*) cf_strdup(strval); if(clone_str == NULL) { as_v8_error(log, "cloning GeoJSON failed"); } as_geojson * clone_as = as_geojson_new(clone_str, true); if(clone_as == NULL) { as_v8_error(log, "cloning GeoJSON failed"); } clone_val = as_geojson_toval(clone_as); break; } default: as_v8_error( log, "as_val received is UNKNOWN type %d", (int)t); break; } return clone_val; } bool key_clone(const as_key* src, as_key** dest, const LogInfo* log, bool alloc_key) { if (src == NULL || dest== NULL) { as_v8_info(log, "Parameter error : NULL in source/destination"); return false; } as_v8_detail(log, "Cloning the key"); as_key_value* val = src->valuep; if (src->digest.init == true) { if (alloc_key) { *dest = as_key_new_digest(src->ns, src->set, src->digest.value); } else { as_key_init_digest(*dest, src->ns, src->set, src->digest.value); } if (val != NULL) { (*dest)->valuep = (as_key_value*) asval_clone((as_val*) val, log); } } else if (val != NULL) { as_key_value* clone_val = (as_key_value*) asval_clone((as_val*) val, log); if (alloc_key) { *dest = as_key_new_value(src->ns, src->set, (as_key_value*) clone_val); } else { as_key_init_value(*dest, src->ns, src->set, (as_key_value*) clone_val); } } else { as_v8_detail(log, "Key has neither value nor digest "); } return true; } bool record_clone(const as_record* src, as_record** dest, const LogInfo* log) { if(src == NULL || dest == NULL) { return false; } as_v8_detail( log, "Cloning the record"); (*dest)->ttl = src->ttl; (*dest)->gen = src->gen; as_record_iterator it; as_record_iterator_init(&it, src); while (as_record_iterator_has_next(&it)) { as_bin * bin = as_record_iterator_next(&it); as_bin_value * val = as_bin_get_value(bin); as_bin_value* clone_val = (as_bin_value*) asval_clone( (as_val*) val, log); as_v8_detail(log, "Bin Name: %s", as_bin_get_name(bin)); as_record_set( *dest, as_bin_get_name(bin), clone_val); } as_key* src_key = (as_key*) &src->key; as_key* dest_key = (as_key*) &(*dest)->key; if(src_key != NULL) { //clone the key but do not malloc the key structure, // use the structure available inside record structure. key_clone( src_key, &dest_key, log, false); } return true; } Local<Object> error_to_jsobject(as_error* error, const LogInfo* log) { Nan::EscapableHandleScope scope; Local<Object> err = Nan::New<Object>(); if (error == NULL) { as_v8_info(log, "error(C structure) object is NULL, node.js error object cannot be constructed"); return scope.Escape(err); } // LDT error codes are populated as a string message. // Parse the string and populate the error object appropriately // so that application can look up the error codes and doesn't have // to look at strings. // Check if it's an UDF ERROR and message has string LDT in it // then it implies it is an LDT error, so parse the error // and populate the error object. if(error->code == AEROSPIKE_ERR_UDF && strstr(error->message, "LDT") != NULL) { char err_message[AS_ERROR_MESSAGE_MAX_LEN] = {"\0"}; as_strlcpy(err_message, error->message, AS_ERROR_MESSAGE_MAX_LEN); char *ptr; ptr = strtok(err_message, ":"); if(ptr != NULL) { error->file = ptr; ptr = strtok(NULL, ":"); } if(ptr != NULL) { error->line = atoi(ptr); ptr = strtok(NULL, ":"); } if(ptr != NULL) { error->code = (as_status) atoi(ptr); ptr = strtok(NULL, ":"); } if(ptr != NULL) { as_strlcpy(error->message, ptr, AS_ERROR_MESSAGE_MAX_LEN); ptr = strtok(NULL, ":"); } // LDT error does not populate function name as of now. error->func = NULL; } Nan::Set(err, Nan::New("code").ToLocalChecked(), Nan::New(error->code)); Nan::Set(err, Nan::New("message").ToLocalChecked(), error->message[0] != '\0' ? Nan::New(error->message).ToLocalChecked() : Nan::New("\0").ToLocalChecked() ); Nan::Set(err, Nan::New("func").ToLocalChecked(), error->func ? Nan::New(error->func).ToLocalChecked() : Nan::New("\0").ToLocalChecked() ); Nan::Set(err, Nan::New("file").ToLocalChecked(), error->file ? Nan::New(error->file).ToLocalChecked() : Nan::New("\0").ToLocalChecked() ); Nan::Set(err, Nan::New("line").ToLocalChecked(), error->line ? Nan::New(error->line) : Nan::New((uint32_t)0) ); Nan::Set(err, Nan::New("inDoubt").ToLocalChecked(), error->in_doubt ? Nan::True() : Nan::False()); return scope.Escape(err); } Local<Value> val_to_jsvalue(as_val* val, const LogInfo* log) { Nan::EscapableHandleScope scope; if ( val == NULL) { as_v8_debug(log, "value = NULL"); return scope.Escape(Nan::Null()); } switch ( as_val_type(val) ) { case AS_NIL: { as_v8_detail(log,"value is of type as_null"); return scope.Escape(Nan::Null()); } case AS_INTEGER : { as_integer * ival = as_integer_fromval(val); if ( ival ) { int64_t data = as_integer_getorelse(ival, -1); as_v8_detail(log, "value = %lld ", data); return scope.Escape(Nan::New((double)data)); } break; } case AS_DOUBLE : { as_double* dval = as_double_fromval(val); if( dval ) { double d = as_double_getorelse(dval, -1); as_v8_detail(log, "value = %lf ",d); return scope.Escape(Nan::New((double)d)); } break; } case AS_STRING : { as_string * sval = as_string_fromval(val); if ( sval ) { char * data = as_string_getorelse(sval, NULL); as_v8_detail(log, "value = \"%s\"", data); return scope.Escape(Nan::New(data).ToLocalChecked()); } break; } case AS_BYTES : { as_bytes * bval = as_bytes_fromval(val); if ( bval ) { uint8_t * data = as_bytes_getorelse(bval, NULL); uint32_t size = as_bytes_size(bval); as_v8_detail(log, "value = <%x %x %x%s>", size > 0 ? data[0] : 0, size > 1 ? data[1] : 0, size > 2 ? data[2] : 0, size > 3 ? " ..." : "" ); // this constructor actually copies data into the new Buffer Local<Object> buff = Nan::CopyBuffer((char*) data, size).ToLocalChecked(); return scope.Escape(buff); } break; } case AS_LIST : { as_arraylist* listval = (as_arraylist*) as_list_fromval((as_val*)val); int size = as_arraylist_size(listval); Local<Array> jsarray = Nan::New<Array>(size); for ( int i = 0; i < size; i++ ) { as_val * arr_val = as_arraylist_get(listval, i); Local<Value> jsval = val_to_jsvalue(arr_val, log); Nan::Set(jsarray, i, jsval); } return scope.Escape(jsarray); } case AS_MAP : { Local<Object> jsobj = Nan::New<Object>(); as_hashmap* map = (as_hashmap*) as_map_fromval(val); as_hashmap_iterator it; as_hashmap_iterator_init(&it, map); while ( as_hashmap_iterator_has_next(&it) ) { as_pair *p = (as_pair*) as_hashmap_iterator_next(&it); as_val* key = as_pair_1(p); as_val* val = as_pair_2(p); Nan::Set(jsobj, val_to_jsvalue(key, log), val_to_jsvalue(val, log)); } return scope.Escape(jsobj); } case AS_GEOJSON : { as_geojson * gval = as_geojson_fromval(val); if ( gval ) { char * data = as_geojson_getorelse(gval, NULL); as_v8_detail(log, "geojson = \"%s\"", data); return scope.Escape(Nan::New<String>(data).ToLocalChecked()); } break; } default: break; } return scope.Escape(Nan::Undefined()); } Local<Object> recordbins_to_jsobject(const as_record* record, const LogInfo* log) { Nan::EscapableHandleScope scope; Local<Object> bins ; if (record == NULL) { as_v8_debug( log, "Record ( C structure) is NULL, cannot form node.js record object"); return scope.Escape(bins); } bins = Nan::New<Object>(); as_record_iterator it; as_record_iterator_init(&it, record); while ( as_record_iterator_has_next(&it) ) { as_bin * bin = as_record_iterator_next(&it); char * name = as_bin_get_name(bin); as_val * val = (as_val *) as_bin_get_value(bin); Local<Value> obj = val_to_jsvalue(val, log ); Nan::Set(bins, Nan::New(name).ToLocalChecked(), obj); as_v8_detail(log, "Setting binname %s ", name); } return scope.Escape(bins); } Local<Object> recordmeta_to_jsobject(const as_record* record, const LogInfo* log) { Nan::EscapableHandleScope scope; Local<Object> meta; if(record == NULL) { as_v8_debug( log, "Record ( C structure) is NULL, cannot form node.js metadata object"); return scope.Escape(meta); } meta = Nan::New<Object>(); Local<Number> ttl; switch(record->ttl) { case AS_RECORD_NO_EXPIRE_TTL: ttl = Nan::New<Number>(TTL_NEVER_EXPIRE); break; default: ttl = Nan::New<Number>(record->ttl); } Nan::Set(meta, Nan::New("ttl").ToLocalChecked(), ttl); as_v8_detail(log, "TTL of the record %d", record->ttl); Nan::Set(meta, Nan::New("gen").ToLocalChecked(), Nan::New(record->gen)); as_v8_detail(log, "Gen of the record %d", record->gen); return scope.Escape(meta); } Local<Object> record_to_jsobject(const as_record* record, const as_key* key, const LogInfo* log) { Nan::EscapableHandleScope scope; Local<Object> okey; if ( record == NULL ) { as_v8_debug( log, "Record ( C structure) is NULL, cannot form node.js record object"); return scope.Escape(okey); } okey = key_to_jsobject(key ? key : &record->key, log); Local<Object> bins = recordbins_to_jsobject(record, log ); Local<Object> meta = recordmeta_to_jsobject(record, log); Local<Object> rec = Nan::New<Object>(); Nan::Set(rec, Nan::New("key").ToLocalChecked(), okey); Nan::Set(rec, Nan::New("meta").ToLocalChecked(), meta); Nan::Set(rec, Nan::New("bins").ToLocalChecked(), bins); return scope.Escape(rec); } Local<Array> batch_records_to_jsarray(const as_batch_read_records* records, const LogInfo* log) { Nan::EscapableHandleScope scope; const as_vector* list = &records->list; Local<Array> results = Nan::New<Array>(list->size); for (uint32_t i = 0; i < list->size; i++) { as_batch_read_record* batch_record = (as_batch_read_record*) as_vector_get((as_vector*) list, i); as_status status = batch_record->result; as_record* record = &batch_record->record; as_key* key = &batch_record->key; Local<Object> result = Nan::New<Object>(); Nan::Set(result, Nan::New("status").ToLocalChecked(), Nan::New(status)); Nan::Set(result, Nan::New("key").ToLocalChecked(), key_to_jsobject(key ? key : &record->key, log)); if (status == AEROSPIKE_OK) { Nan::Set(result, Nan::New("meta").ToLocalChecked(), recordmeta_to_jsobject(record, log)); Nan::Set(result, Nan::New("bins").ToLocalChecked(), recordbins_to_jsobject(record, log)); } Nan::Set(results, i, result); } return scope.Escape(results); } //Forward references; int asval_from_jsvalue(as_val** value, Local<Value> v8value, const LogInfo* log); int extract_blob_from_jsobject(uint8_t** data, int* len, Local<Object> obj, const LogInfo* log); bool instanceof(Local<Value> value, const char * type) { if (value->IsObject()) { Local<String> ctor_name = value.As<Object>()->GetConstructorName(); Nan::Utf8String cn(ctor_name); return 0 == strncmp(*cn, type, strlen(type)); } else { return false; } } /** * Node.js stores all number values > 2^31 in the class Number and * values < 2^31 are stored in the class SMI (Small Integers). To distinguish * between a double and int64_t value in Node.js, retrieve the value as double * and also as int64_t. If the values are same, then store it as int64_t. Else * store it as double. * The problem with this implementation is var 123.00 will be treated as int64_t. * Applications can enforce double type by using the `Aerospike.Double` data type, * e.g. * * const Double = Aerospike.Double * var f = new Double(123) **/ bool is_double_value(Local<Value> value) { if (value->IsNumber()) { int64_t i = Nan::To<int64_t>(value).FromJust(); double d = Nan::To<double>(value).FromJust(); return d != (double)i; } return instanceof(value, DoubleType); } double double_value(Local<Value> value) { if (instanceof(value, DoubleType)) { value = Nan::Get(value.As<Object>(), Nan::New<String>("Double").ToLocalChecked()).ToLocalChecked(); } return Nan::To<double>(value).FromJust(); } bool is_geojson_value(Local<Value> value) { return instanceof(value, GeoJSONType); } char* geojson_as_string(Local<Value> value) { Local<Value> strval = Nan::Get(value.As<Object>(), Nan::New("str").ToLocalChecked()).ToLocalChecked(); return strdup(*Nan::Utf8String(strval)); } int list_from_jsarray(as_list** list, Local<Array> array, const LogInfo* log) { const uint32_t capacity = array->Length(); as_v8_detail(log, "Creating new as_arraylist with capacity %d", capacity); as_arraylist* arraylist = as_arraylist_new(capacity, 0); if (arraylist == NULL) { as_v8_error(log, "List allocation failed"); Nan::ThrowError("List allocation failed"); return AS_NODE_PARAM_ERR; } *list = (as_list*) arraylist; for (uint32_t i = 0; i < capacity; i++) { as_val* val; if (asval_from_jsvalue(&val, Nan::Get(array, i).ToLocalChecked(), log) != AS_NODE_PARAM_OK) { return AS_NODE_PARAM_ERR; } as_list_append(*list, val); } return AS_NODE_PARAM_OK; } int map_from_jsobject(as_map** map, Local<Object> obj, const LogInfo* log) { const Local<Array> props = Nan::GetOwnPropertyNames(obj.As<Object>()).ToLocalChecked(); const uint32_t capacity = props->Length(); as_v8_detail(log, "Creating new as_hashmap with capacity %d", capacity); as_hashmap* hashmap = as_hashmap_new(capacity); if (hashmap == NULL) { as_v8_error(log, "Map allocation failed"); Nan::ThrowError("Map allocation failed"); return AS_NODE_PARAM_ERR; } *map = (as_map*) hashmap; for (uint32_t i = 0; i < capacity; i++) { const Local<Value> name = Nan::Get(props, i).ToLocalChecked(); const Local<Value> value = Nan::Get(obj, name).ToLocalChecked(); as_val* val = NULL; if (asval_from_jsvalue(&val, value, log) != AS_NODE_PARAM_OK) { return AS_NODE_PARAM_ERR; } as_stringmap_set(*map, *Nan::Utf8String(name), val); } return AS_NODE_PARAM_OK; } int asval_from_jsvalue(as_val** value, Local<Value> v8value, const LogInfo* log) { if (v8value->IsNull()) { as_v8_detail(log, "The as_val is NULL"); *value = (as_val*) &as_nil; } else if (v8value->IsUndefined()) { // asval_from_jsvalue is called recursively. // If a bin value is undefined, it should be handled by the caller of // this function gracefully. // If an entry in a map/list is undefined the corresponding entry becomes null. as_v8_detail(log, "Object passed is undefined"); *value = (as_val*) &as_nil; } else if (v8value->IsBoolean()) { *value = (as_val*) as_boolean_new(Nan::To<bool>(v8value).FromJust()); } else if (v8value->IsString()) { *value = (as_val*) as_string_new(strdup(*Nan::Utf8String(v8value)), true); } else if (v8value->IsInt32()) { *value = (as_val*) as_integer_new(Nan::To<int32_t>(v8value).FromJust()); } else if (v8value->IsUint32()) { *value = (as_val*) as_integer_new(Nan::To<uint32_t>(v8value).FromJust()); } else if (is_double_value(v8value)) { *value = (as_val*) as_double_new(double_value(v8value)); } else if (v8value->IsNumber()) { *value = (as_val*) as_integer_new(Nan::To<int64_t>(v8value).FromJust()); } else if (node::Buffer::HasInstance(v8value)) { int size; uint8_t* data; if (extract_blob_from_jsobject(&data, &size, v8value.As<Object>(), log) != AS_NODE_PARAM_OK) { as_v8_error(log, "Extractingb blob from a js object failed"); return AS_NODE_PARAM_ERR; } *value = (as_val*) as_bytes_new_wrap(data, size, true); } else if (v8value->IsArray()) { if (list_from_jsarray((as_list**) value, Local<Array>::Cast(v8value), log) != AS_NODE_PARAM_OK) { return AS_NODE_PARAM_ERR; } } else if (is_geojson_value(v8value)) { char* jsonstr = geojson_as_string(v8value); *value = (as_val*) as_geojson_new(jsonstr, true); } else { // generic object - treat as map if (map_from_jsobject((as_map**) value, v8value.As<Object>(), log) != AS_NODE_PARAM_OK) { return AS_NODE_PARAM_ERR; } } if (as_v8_detail_enabled(log)) { auto val_type = as_val_type(*value); char* val_str = as_val_tostring(*value); as_v8_detail(log, "type: %d, string value: %s", val_type, val_str); cf_free(val_str); } return AEROSPIKE_OK; } int recordbins_from_jsobject(as_record* rec, Local<Object> obj, const LogInfo* log) { const Local<Array> props = Nan::GetOwnPropertyNames(obj).ToLocalChecked(); const uint32_t count = props->Length(); as_record_init(rec, count); for ( uint32_t i = 0; i < count; i++ ) { const Local<Value> name = Nan::Get(props, i).ToLocalChecked(); const Local<Value> value = Nan::Get(obj, name).ToLocalChecked(); // A bin can be undefined, or an entry inside a CDT(list, map) // can be an undefined value. // If a bin is undefined, it must error out at the earliest. if( value->IsUndefined()) { as_v8_error(log, "Bin value 'undefined' not supported: %s", *Nan::Utf8String(name)); return AS_NODE_PARAM_ERR; } Nan::Utf8String n(name); if( strlen(*n) > AS_BIN_NAME_MAX_SIZE ) { as_v8_error(log, "Bin name length exceeded (max. 14): %s", *n); return AS_NODE_PARAM_ERR; } as_val* val = NULL; if (asval_from_jsvalue(&val, value, log) != AS_NODE_PARAM_OK) { return AS_NODE_PARAM_ERR; } switch(as_val_type(val)) { case AS_BOOLEAN: as_val_destroy(val); as_v8_error(log, "Boolean type not supported: %s", *n); return AS_NODE_PARAM_ERR; case AS_INTEGER: as_record_set_integer(rec, *n, (as_integer*)val); break; case AS_DOUBLE: as_record_set_as_double(rec, *n, (as_double*)val); break; case AS_STRING: as_record_set_string(rec, *n, (as_string*)val); break; case AS_BYTES: as_record_set_bytes(rec, *n, (as_bytes*) val); break; case AS_LIST: as_record_set_list(rec, *n, (as_list*) val); break; case AS_MAP: as_record_set_map(rec, *n, (as_map*) val); break; case AS_GEOJSON: as_record_set_geojson(rec, *n, (as_geojson*) val); break; case AS_NIL: as_record_set_nil(rec, *n); break; default: as_v8_error(log,"Skipping unsupported as_val type %i: %s", as_val_type(val), *n); break; } } return AS_NODE_PARAM_OK; } int recordmeta_from_jsobject(as_record* rec, Local<Object> obj, const LogInfo* log) { as_v8_detail(log, "Setting record meta from JS object"); if (setTTL(obj, &rec->ttl, log) != AS_NODE_PARAM_OK) { return AS_NODE_PARAM_ERR; }; if (setGeneration(obj, &rec->gen, log) != AS_NODE_PARAM_OK) {; return AS_NODE_PARAM_ERR; } return AS_NODE_PARAM_OK; } int extract_blob_from_jsobject(uint8_t** data, int* len, Local<Object> obj, const LogInfo* log) { if (!node::Buffer::HasInstance(obj)) { as_v8_error(log, "The binary data is not of the type UnsignedBytes"); return AS_NODE_PARAM_ERR; } (*len) = node::Buffer::Length(obj); (*data) = (uint8_t*) cf_malloc(sizeof(uint8_t) * (*len)); memcpy((*data), node::Buffer::Data(obj), (*len)); return AS_NODE_PARAM_OK; } int setTTL(Local<Object> obj, uint32_t* ttl, const LogInfo* log) { Local<Value> v8_ttl = Nan::Get(obj, Nan::New("ttl").ToLocalChecked()).ToLocalChecked(); if (v8_ttl->IsNumber()) { (*ttl) = Nan::To<uint32_t>(v8_ttl).FromJust(); as_v8_detail(log, "TTL: %d", (*ttl)); } else if (v8_ttl->IsNull() || v8_ttl->IsUndefined()) { // noop - ttl may not be specified } else { return AS_NODE_PARAM_ERR; } return AS_NODE_PARAM_OK; } int setGeneration(Local<Object> obj, uint16_t* generation, const LogInfo* log) { Local<Value> v8_gen = Nan::Get(obj, Nan::New("gen").ToLocalChecked()).ToLocalChecked(); if (v8_gen->IsNumber()) { (*generation) = (uint16_t) Nan::To<uint32_t>(v8_gen).FromJust(); as_v8_detail(log, "Generation: %d", (*generation)); } else if (v8_gen->IsNull() || v8_gen->IsUndefined()) { // noop - gen may not be specified } else { as_v8_error(log, "Generation should be an integer"); return AS_NODE_PARAM_ERR; } return AS_NODE_PARAM_OK; } Local<Object> key_to_jsobject(const as_key* key, const LogInfo* log) { Nan::EscapableHandleScope scope; Local<Object> obj; if (key == NULL) { as_v8_debug(log, "Key (C structure) is NULL, cannot form node.js key object"); return scope.Escape(obj); } obj = Nan::New<Object>(); if (strlen(key->ns) > 0) { as_v8_detail(log, "key.ns = \"%s\"", key->ns); Nan::Set(obj, Nan::New("ns").ToLocalChecked(), Nan::New(key->ns).ToLocalChecked()); } else { as_v8_debug(log, "Key namespace is NULL"); } if (strlen(key->set) > 0) { as_v8_detail(log, "key.set = \"%s\"", key->set); Nan::Set(obj, Nan::New("set").ToLocalChecked(), Nan::New(key->set).ToLocalChecked()); } else { as_v8_debug(log, "Key set is NULL"); } if ( key->valuep ) { as_val * val = (as_val *) key->valuep; as_val_t type = as_val_type(val); switch(type) { case AS_INTEGER: { as_integer * ival = as_integer_fromval(val); as_v8_detail(log, "key.key = %d", as_integer_get(ival)); Nan::Set(obj, Nan::New("key").ToLocalChecked(), Nan::New((double)as_integer_get(ival))); break; } case AS_STRING: { as_string * sval = as_string_fromval(val); as_v8_detail(log, "key.key = \"%s\"", as_string_get(sval)); Nan::Set(obj, Nan::New("key").ToLocalChecked(), Nan::New(as_string_get(sval)).ToLocalChecked()); break; } case AS_BYTES: { as_bytes * bval = as_bytes_fromval(val); if ( bval ) { uint32_t size = as_bytes_size(bval); as_v8_detail(log,"key.key = \"%u\"", bval->value); Local<Object> buff = Nan::CopyBuffer((char*)bval->value, size).ToLocalChecked(); Nan::Set(obj, Nan::New("key").ToLocalChecked(), buff); break; } } default: break; } } else { as_v8_detail(log, "Key value is NULL"); } if (key->digest.init == true) { Local<Object> buff = Nan::CopyBuffer((char*)key->digest.value, AS_DIGEST_VALUE_SIZE).ToLocalChecked(); Nan::Set(obj, Nan::New("digest").ToLocalChecked(), buff); } return scope.Escape(obj); } Local<Object> jobinfo_to_jsobject(const as_job_info* info, const LogInfo* log) { Local<Object> jobinfo; if (info == NULL) { as_v8_debug(log, "Job Info ( C structure) is NULL, cannot form node.js jobInfo object"); return jobinfo; } jobinfo = Nan::New<Object>(); Nan::Set(jobinfo, Nan::New("progressPct").ToLocalChecked(), Nan::New(info->progress_pct)); as_v8_detail(log, "Progress pct of the job %d", info->progress_pct); Local<Value> recordsRead = Nan::New((double)info->records_read); Nan::Set(jobinfo, Nan::New("recordsRead").ToLocalChecked(), recordsRead); as_v8_detail(log, "Number of records read so far %d", info->records_read); Nan::Set(jobinfo, Nan::New("status").ToLocalChecked(), Nan::New(info->status)); return jobinfo; } int key_from_jsobject(as_key* key, Local<Object> obj, const LogInfo* log) { Nan::EscapableHandleScope scope; as_namespace ns = {'\0'}; as_set set = {'\0'}; if (obj->IsNull()) { as_v8_error(log, "The key object passed is Null"); return AS_NODE_PARAM_ERR; } Local<Value> ns_obj = Nan::Get(obj, Nan::New("ns").ToLocalChecked()).ToLocalChecked(); if (ns_obj->IsString()) { if (as_strlcpy(ns, *Nan::Utf8String(ns_obj), AS_NAMESPACE_MAX_SIZE) > AS_NAMESPACE_MAX_SIZE) { as_v8_error(log, "The key namespace is too long (max. %d)", AS_NAMESPACE_MAX_SIZE); return AS_NODE_PARAM_ERR; } if (strlen(ns) == 0) { as_v8_error(log, "The key namespace must not be empty"); return AS_NODE_PARAM_ERR; } as_v8_detail(log, "key.ns = \"%s\"", ns); } else { as_v8_error(log, "The key namespace must be a string"); return AS_NODE_PARAM_ERR; } Local<Value> set_obj = Nan::Get(obj, Nan::New("set").ToLocalChecked()).ToLocalChecked(); if (set_obj->IsString()) { if (as_strlcpy(set, *Nan::Utf8String(set_obj), AS_SET_MAX_SIZE) > AS_SET_MAX_SIZE) { as_v8_error(log, "The key set is too long (max. %d)", AS_SET_MAX_SIZE); return AS_NODE_PARAM_ERR; } if (strlen(set) == 0) { as_v8_debug(log, "Key set passed is empty string"); } as_v8_detail(log,"key.set = \"%s\"", set); } else if (set_obj->IsNull() || set_obj->IsUndefined()) { // noop - set name may not be specified } else { as_v8_error(log, "The key set must be a string"); return AS_NODE_PARAM_ERR; } bool has_value = false; Local<Value> val_obj = Nan::Get(obj, Nan::New("key").ToLocalChecked()).ToLocalChecked(); if (val_obj->IsString()) { char* value = strdup(*Nan::Utf8String(val_obj)); as_key_init(key, ns, set, value); as_v8_detail(log, "key.key = \"%s\"", value); ((as_string*) key->valuep)->free = true; has_value = true; } else if (is_double_value(val_obj)) { as_v8_error(log, "Invalid key value: double - only string, integer and Buffer are supported"); return AS_NODE_PARAM_ERR; } else if (val_obj->IsNumber()) { int64_t value = Nan::To<int64_t>(val_obj).FromJust(); as_key_init_int64(key, ns, set, value); as_v8_detail(log, "key.key = %d", value); has_value = true; } else if (val_obj->IsObject()) { Local<Object> obj = val_obj.As<Object>(); int size ; uint8_t* data ; if (extract_blob_from_jsobject(&data, &size, obj, log) != AS_NODE_PARAM_OK) { return AS_NODE_PARAM_ERR; } as_key_init_rawp(key, ns, set, data, size, true); has_value = true; as_v8_detail(log, "key.key = <%x %x %x%s>", size > 0 ? data[0] : 0, size > 1 ? data[1] : 0, size > 2 ? data[2] : 0, size > 3 ? " ..." : "" ); } else if (val_obj->IsNull() || val_obj->IsUndefined()) { // noop - value can be omitted if digest is given } else { as_v8_error(log, "Invalid key value - only string, integer and Buffer are supported"); return AS_NODE_PARAM_ERR; } if (has_value) { // Copy the digest back to the JS key object as_digest* digest = as_key_digest(key); uint8_t* bytes = digest->value; Local<Object> buff = scope.Escape(Nan::CopyBuffer((char*) bytes, AS_DIGEST_VALUE_SIZE).ToLocalChecked()); Nan::Set(obj, Nan::New("digest").ToLocalChecked(), buff); } else { Local<Value> digest_value = Nan::Get(obj, Nan::New("digest").ToLocalChecked()).ToLocalChecked(); if (digest_value->IsObject()) { Local<Object> digest_obj = digest_value.As<Object>(); int size; uint8_t* data; if (extract_blob_from_jsobject(&data, &size, digest_obj, log) != AS_NODE_PARAM_OK) { return AS_NODE_PARAM_ERR; } as_digest_value digest; memcpy(digest, data, AS_DIGEST_VALUE_SIZE); as_v8_detail(log, "key.digest = <%x %x %x%s>", size > 0 ? digest[0] : 0, size > 1 ? digest[1] : 0, size > 2 ? digest[2] : 0, size > 3 ? " ..." : "" ); as_key_init_digest(key, ns, set, digest); } else if (digest_value->IsNull() || digest_value->IsUndefined()) { as_v8_error(log, "The key must have either a \"value\" or a \"digest\""); return AS_NODE_PARAM_ERR; } else { as_v8_error(log, "Invalid digest value: \"digest\" must be a 20-byte Buffer"); return AS_NODE_PARAM_ERR; } } return AS_NODE_PARAM_OK; } int batch_from_jsarray(as_batch* batch, Local<Array> arr, const LogInfo* log) { uint32_t len = arr->Length(); as_batch_init(batch, len); for (uint32_t i = 0; i < len; i++) { Local<Object> key = Nan::Get(arr, i).ToLocalChecked().As<Object>(); if (key_from_jsobject(as_batch_keyat(batch, i), key, log) != AS_NODE_PARAM_OK) { as_v8_error(log, "Parsing batch key [%d] failed", i); return AS_NODE_PARAM_ERR; } } return AS_NODE_PARAM_OK; } int batch_read_records_from_jsarray(as_batch_read_records** records, Local<Array> arr, const LogInfo* log) { uint32_t no_records = arr->Length(); *records = as_batch_read_create(no_records); for (uint32_t i = 0; i < no_records; i++) { as_batch_read_record* record = as_batch_read_reserve(*records); Local<Object> obj = Nan::Get(arr, i).ToLocalChecked().As<Object>(); Local<Object> key = Nan::Get(obj, Nan::New("key").ToLocalChecked()).ToLocalChecked().As<Object>(); if (key_from_jsobject(&record->key, key, log) != AS_NODE_PARAM_OK) { as_v8_error(log, "Parsing batch keys failed"); return AS_NODE_PARAM_ERR; } Local<Value> v8_bins = Nan::Get(obj, Nan::New("bins").ToLocalChecked()).ToLocalChecked(); if (v8_bins->IsArray()) { char** bin_names; uint32_t n_bin_names; if (bins_from_jsarray(&bin_names, &n_bin_names, Local<Array>::Cast(v8_bins), log) != AS_NODE_PARAM_OK) { as_v8_error(log, "Parsing batch bin names failed"); return AS_NODE_PARAM_ERR; } record->bin_names = bin_names; record->n_bin_names = n_bin_names; } Local<Value> v8_read_all_bins = Nan::Get(obj, Nan::New("read_all_bins").ToLocalChecked()).ToLocalChecked(); if (v8_read_all_bins->IsBoolean()) { record->read_all_bins = Nan::To<bool>(v8_read_all_bins).FromJust(); } } return AS_NODE_PARAM_OK; } int bins_from_jsarray(char*** bins, uint32_t* num_bins, Local<Array> arr, const LogInfo* log) { int arr_length = arr->Length(); char** c_bins = (char**) cf_calloc(sizeof(char*), arr_length+1); as_v8_debug(log, "Number of bins requested %d", arr_length); for( int i = 0; i < arr_length; i++) { Local<Value> bname = Nan::Get(arr, i).ToLocalChecked(); c_bins[i] = (char*)cf_malloc(AS_BIN_NAME_MAX_SIZE); as_strlcpy(c_bins[i], *Nan::Utf8String(bname), AS_BIN_NAME_MAX_SIZE); as_v8_detail(log, "name of the bin %s", c_bins[i]); } // The last entry should be NULL because we are passing to select API calls. c_bins[arr_length] = NULL; *bins = c_bins; *num_bins = (uint32_t) arr_length; return AS_NODE_PARAM_OK; } void free_batch_records(as_batch_read_records* records) { const as_vector* list = &records->list; for (uint32_t i = 0; i < list->size; i++) { as_batch_read_record* batch_record = (as_batch_read_record*) as_vector_get((as_vector*) list, i); if (batch_record->n_bin_names > 0) { for (uint32_t j = 0; j < batch_record->n_bin_names; j++) { cf_free(batch_record->bin_names[j]); } cf_free(batch_record->bin_names); } } as_batch_read_destroy(records); } int udfargs_from_jsobject(char** filename, char** funcname, as_list** args, Local<Object> obj, const LogInfo* log) { if (obj->IsNull()) { as_v8_error(log, "Object passed is NULL"); return AS_NODE_PARAM_ERR; } // Extract UDF module name Local<Value> v8_module = Nan::Get(obj, Nan::New("module").ToLocalChecked()).ToLocalChecked(); if (v8_module->IsString()) { size_t size = v8_module.As<String>()->Length() + 1; if (*filename == NULL) { *filename = (char*) cf_malloc(sizeof(char) * size); } if (as_strlcpy(*filename, *Nan::Utf8String(v8_module), size) > size) { as_v8_error(log, "UDF module name is too long (> %d)", size); return AS_NODE_PARAM_ERR; } as_v8_detail(log, "Filename in the udf args is set to %s", *filename); } else { as_v8_error(log, "UDF module name should be string"); return AS_NODE_PARAM_ERR; } // Extract UDF function name Local<Value> v8_funcname = Nan::Get(obj, Nan::New("funcname").ToLocalChecked()).ToLocalChecked(); if (v8_funcname->IsString()) { size_t size = v8_funcname.As<String>()->Length() + 1; if (*funcname == NULL) { *funcname = (char*) cf_malloc(sizeof(char) * size); } if (as_strlcpy(*funcname, *Nan::Utf8String(v8_funcname), size) > size) { as_v8_error(log, "UDF function name is too long (> %d)", size); return AS_NODE_PARAM_ERR; } as_v8_detail(log, "The function name in the UDF args set to %s", *funcname); } else { as_v8_error(log, "UDF function name should be string"); return AS_NODE_PARAM_ERR; } Local<Value> arglist = Nan::Get(obj, Nan::New("args").ToLocalChecked()).ToLocalChecked(); if (arglist->IsArray()) { list_from_jsarray(args, Local<Array>::Cast(arglist), log); as_v8_detail(log, "Parsing UDF args -- done !!!"); } else if (arglist->IsNull() || arglist->IsUndefined()) { // No argument case: Initialize array with 0 elements. *args = (as_list*) as_arraylist_new(0, 0); } else { as_v8_error(log, "UDF args should be an array"); return AS_NODE_PARAM_ERR; } return AS_NODE_PARAM_OK; } // Like strncpy but does not 0 fill the buffer and always null // terminates. bufsize is the size of the destination buffer. size_t as_strlcpy(char *d, const char *s, size_t bufsize) { size_t len = strlen(s); size_t ret = len; if (len >= bufsize) len = bufsize-1; memcpy(d, s, len); d[len] = 0; return ret; }
55,202
19,169
#include <unistd.h> #include <arpa/inet.h> #include <sys/socket.h> #include <sys/types.h> #include <exception> #include <iostream> #include <thread> #include <atomic> #include <vector> #include <string> #include <functional> #include <condition_variable> #include <mutex> #include <gflags/gflags.h> #include <glog/logging.h> #include <boost/network/protocol/http/server.hpp> #include <boost/network/uri.hpp> #include "dp/graph.h" #include "dp/operators.h" #include "dp/ingress/udp.h" #include "dp/ingress/videocap.h" #include "dp/util/error.h" #include "mqtt/mqtt.h" #include "movidius/ncs.h" #include "movidius/ssd_mobilenet.h" using namespace std; using namespace dp; static constexpr int http_port = 2052; static constexpr int cast_port = 2053; DEFINE_int32(port, in::udp::default_port, "listening port"); DEFINE_string(mqtt_host, "127.0.0.1", "MQTT server address"); DEFINE_int32(mqtt_port, mqtt::client::default_port, "MQTT server port"); DEFINE_string(mqtt_client_id, "", "MQTT client ID"); DEFINE_string(mqtt_topic, "", "MQTT topic"); DEFINE_string(model, "graph", "Model name"); DEFINE_string(http_addr, "", "image server listening address"); DEFINE_int32(http_port, http_port, "image server listening port"); DEFINE_int32(stream_port, cast_port, "TCP streaming port"); struct pub_op { mqtt::client *client; pub_op(mqtt::client* c) : client(c) { } void operator() (graph::ctx ctx) { const auto& str = ctx.in(0)->as<string>(); client->publish(FLAGS_mqtt_topic, str); } }; static string index_html(R"(<!DOCTYPE html> <html> <head> <script language="javascript"> function refreshImage() { document.getElementById('cam0').src = '/jpeg?ts='+Date.now(); setTimeout(refreshImage, 30); } document.addEventListener('DOMContentLoaded', refreshImage); </script> </head> <body> <img id="cam0"> </body> </html> )"); static string sz2str(size_t sz) { char str[64]; sprintf(str, "%u", sz); return str; } struct image_buffer { vector<unsigned char> data; size_t size; image_id id; static constexpr size_t max_buf_size = 0x10000; image_buffer() : data(max_buf_size), size(0) { } const unsigned char* ptr() const { return &data[0]; } void update(const void *buf, size_t _sz, const image_id& _id) { if (_sz > max_buf_size) _sz = max_buf_size; memcpy(&data[0], buf, _sz); size = _sz; id = _id; } }; class image_handler; typedef ::boost::network::http::server<image_handler> http_server_t; class image_handler { public: image_handler() : m_images(2), m_current_buf(0) { } void set_image(const void *buf, size_t size, const image_id& id) { int write_buf = 1 - m_current_buf.load(); m_images[write_buf].update(buf, size, id); atomic_exchange(&m_current_buf, write_buf); m_set_image_cv.notify_all(); } const image_buffer* wait() const { unique_lock<mutex> lock(m_set_image_mux); m_set_image_cv.wait(lock); return &m_images[m_current_buf.load()]; } void operator() (http_server_t::request const& request, http_server_t::connection_ptr conn) { VLOG(4) << request.method << " " << request.destination; boost::network::uri::uri uri("http://localhost:80"+request.destination); static http_server_t::response_header error_headers[] = { {"Content-type", "text/plain"}, {"Connection", "close"}, }; if (request.method == "GET") { if (uri.path() == "/") { handle_index(conn); return; } if (uri.path() == "/jpeg") { handle_jpeg(conn); return; } if (uri.path() == "/stream") { handle_stream(conn); return; } conn->set_status(http_server_t::connection::not_found); conn->set_headers(boost::make_iterator_range(error_headers, error_headers+sizeof(error_headers)/sizeof(error_headers[0]))); conn->write("Path not supported"); return; } conn->set_status(http_server_t::connection::not_supported); conn->set_headers(boost::make_iterator_range(error_headers, error_headers+sizeof(error_headers)/sizeof(error_headers[0]))); conn->write("Method not supported"); } graph::op_func op() { return [this](graph::ctx ctx) { const buf_ref &buf = ctx.in(0)->as<buf_ref>(); const auto& id = ctx.in(1)->as<image_id>(); set_image(buf.ptr, buf.len, id); }; } private: vector<image_buffer> m_images; atomic_int m_current_buf; mutable mutex m_set_image_mux; mutable condition_variable m_set_image_cv; void handle_index(http_server_t::connection_ptr conn) { http_server_t::response_header common_headers[] = { {"Content-type", "text/html"}, {"Content-length", sz2str(index_html.length())}, }; conn->set_status(http_server_t::connection::ok); conn->set_headers(boost::make_iterator_range(common_headers, common_headers+sizeof(common_headers)/sizeof(common_headers[0]))); conn->write(index_html); } void handle_jpeg(http_server_t::connection_ptr conn) { const image_buffer& buf = m_images[m_current_buf.load()]; http_server_t::response_header common_headers[] = { {"Content-type", "image/jpeg"}, {"Content-length", sz2str(buf.size)}, {"Cache-control", "max-age=0, no-cache"}, {"X-ImageId-Seq", sz2str(buf.id.seq)}, {"X-ImageId-Src", buf.id.src}, }; conn->set_status(http_server_t::connection::ok); conn->set_headers(boost::make_iterator_range(common_headers, common_headers+sizeof(common_headers)/sizeof(common_headers[0]))); conn->write(boost::asio::const_buffers_1(buf.ptr(), buf.size), [](boost::system::error_code const&) {}); } void handle_stream(http_server_t::connection_ptr conn) { conn->set_status(http_server_t::connection::not_supported); conn->write("Not implemented"); } }; class socket_listener { public: socket_listener(int type, int port) : m_socket(-1) { try { m_socket = socket(PF_INET, type, 0); if (m_socket < 0) { throw runtime_error(errmsg("socket")); } long en = 1; if (setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &en, sizeof(en)) < 0) { throw runtime_error(errmsg("setsockopt")); } sockaddr_in sa; memset(&sa, 0, sizeof(sa)); sa.sin_family = PF_INET; sa.sin_port = htons((u_short)port); sa.sin_addr.s_addr = INADDR_ANY; if (bind(m_socket, (sockaddr*)&sa, sizeof(sa)) < 0) { throw runtime_error(errmsg("socket bind")); } if (type != SOCK_STREAM) return; if (listen(m_socket, SOMAXCONN) < 0) { throw runtime_error(errmsg("listen")); } } catch (runtime_error&) { if (m_socket >= 0) { close(m_socket); } throw; } } virtual ~socket_listener() { if (m_socket >= 0) { close(m_socket); } } int socket_fd() const { return m_socket; } private: int m_socket; }; class streamer : public socket_listener { public: streamer(int port = cast_port) : socket_listener(SOCK_STREAM, port) { } void run(const image_handler* images) { while (true) { sockaddr_in sa; socklen_t salen = sizeof(sa); int conn = accept(socket_fd(), (sockaddr*)&sa, &salen); if (conn < 0) { LOG(ERROR) << errmsg("accept"); break; } thread client([this, conn, images] { stream_to(conn, images); }); client.detach(); } } private: void stream_to(int conn, const image_handler* images) { const image_buffer* buf; while ((buf = images->wait()) != nullptr) { uint16_t sz = (uint16_t)buf->size; int r = send(conn, &sz, sizeof(sz), MSG_NOSIGNAL); if (r > 0) { r = send(conn, buf->ptr(), buf->size, MSG_NOSIGNAL); } if (r < 0) { LOG(ERROR) << errmsg("send"); break; } } close(conn); } }; class udp_caster : public socket_listener { public: udp_caster(int port = cast_port) : socket_listener(SOCK_DGRAM, port) { } void run(const image_handler* images) { thread listener_thread([this] { run_listener(); }); run_caster(images); listener_thread.join(); } private: struct subscriber { sockaddr_in addr; int failures; subscriber(const sockaddr_in& sa) : failures(0) { memcpy(&addr, &sa, sizeof(addr)); } bool same(const sockaddr_in& sa) const { return addr.sin_port == sa.sin_port && addr.sin_addr.s_addr == sa.sin_addr.s_addr; } string str() const { string s(inet_ntoa(addr.sin_addr)); s += ":" + sz2str(ntohs(addr.sin_port)); return s; } static function<bool(const subscriber&)> if_same(sockaddr_in sa) { return [sa] (const subscriber& sub) -> bool { return sub.same(sa); }; } }; list<subscriber> m_subscribers; mutex m_lock; static constexpr int max_failures = 5; void run_listener() { char buf[4]; while (true) { sockaddr_in sa; socklen_t salen = sizeof(sa); int r = recvfrom(socket_fd(), buf, sizeof(buf), 0, (sockaddr*)&sa, &salen); if (r < 0) { LOG(ERROR) << errmsg("recvfrom"); break; } if (r == 0) continue; switch (buf[0]) { case '+': add_subscriber(sa); break; case '-': del_subscriber(sa); break; } } } void run_caster(const image_handler* images) { const image_buffer* buf; while ((buf = images->wait()) != nullptr) { uint16_t sz = (uint16_t)buf->size; cast(buf); } } void cast(const image_buffer* buf) { unique_lock<mutex> lock(m_lock); list<subscriber>::iterator it = m_subscribers.begin(); while (it != m_subscribers.end()) { auto cur = it; it ++; int r = sendto(socket_fd(), buf->ptr(), buf->size, MSG_NOSIGNAL, (sockaddr*)&cur->addr, sizeof(cur->addr)); if (r < 0) { LOG(ERROR) << cur->str() << ": " << errmsg("sendto"); cur->failures ++; if (cur->failures > max_failures) { LOG(WARNING) << "remove " << cur->str() << " due to too many failures"; m_subscribers.erase(cur); } } } } void add_subscriber(const sockaddr_in& sa) { unique_lock<mutex> lock(m_lock); list<subscriber>::iterator it = find_if(m_subscribers.begin(), m_subscribers.end(), subscriber::if_same(sa)); if (it != m_subscribers.end()) { it->failures = 0; return; } m_subscribers.push_back(subscriber(sa)); } void del_subscriber(const sockaddr_in& sa) { unique_lock<mutex> lock(m_lock); m_subscribers.remove_if(subscriber::if_same(sa)); } }; class app { public: app() { mqtt::initialize(); http_server_t::options options(m_imghandler); options.reuse_address(true) .thread_pool(make_shared<boost::network::utils::thread_pool>()) .port(sz2str(FLAGS_http_port)); if (!FLAGS_http_addr.empty()) { options.address(FLAGS_http_addr); } m_httpsrv.reset(new http_server_t(options)); auto names = movidius::compute_stick::devices(); if (names.empty()) throw runtime_error("no Movidius NCS found"); LOG(INFO) << "MQTT Connect " << FLAGS_mqtt_host << ":" << FLAGS_mqtt_port; m_mqtt_client.reset(new mqtt::client(FLAGS_mqtt_client_id)); m_mqtt_client->connect(FLAGS_mqtt_host, (unsigned short)FLAGS_mqtt_port).wait(); for (auto& name : names) { LOG(INFO) << "Loading " << name << " with model " << FLAGS_model; unique_ptr<movidius::compute_stick> stick(new movidius::compute_stick(name)); unique_ptr<movidius::compute_stick::graph> model(stick->alloc_graph_from_file(FLAGS_model)); unique_ptr<graph> g(new graph(name)); g->def_vars({"input", "id", "size", "pixels", "objects", "result"}); g->add_op("imgid", {"input"}, {"id"}, op::image_id()); g->add_op("decode", {"input"}, {"pixels", "size"}, op::decode_image()); g->add_op("detect", {"pixels"}, {"objects"}, movidius::op::ssd_mobilenet(model.get())); g->add_op("json", {"size", "id", "objects"}, {"result"}, op::detect_boxes_json()); g->add_op("publish", {"result"}, {}, pub_op(m_mqtt_client.get())); g->add_op("imagesrv", {"input", "id"}, {}, m_imghandler.op()); m_dispatcher.add_graph(g.get()); m_ncs.push_back(move(stick)); m_models.push_back(move(model)); m_graphs.push_back(move(g)); } } ~app() { mqtt::cleanup(); } void run() { LOG(INFO) << "Run!"; in::udp udp((uint16_t)FLAGS_port); thread httpsrv_thread([this] { m_httpsrv->run(); }); thread streamer_thread([this] { run_streamer(); }); thread caster_thread([this] { run_caster(); }); udp.run(&m_dispatcher); httpsrv_thread.join(); caster_thread.join(); streamer_thread.join(); } private: unique_ptr<mqtt::client> m_mqtt_client; vector<unique_ptr<movidius::compute_stick>> m_ncs; vector<unique_ptr<movidius::compute_stick::graph>> m_models; vector<unique_ptr<graph>> m_graphs; graph_dispatcher m_dispatcher; image_handler m_imghandler; unique_ptr<http_server_t> m_httpsrv; void run_streamer() { if (FLAGS_stream_port == 0) { return; } streamer strm(FLAGS_stream_port); strm.run(&m_imghandler); } void run_caster() { if (FLAGS_stream_port == 0) { return; } udp_caster caster(FLAGS_stream_port); caster.run(&m_imghandler); } }; int main(int argc, char* argv[]) { google::InitGoogleLogging(argv[0]); google::InstallFailureSignalHandler(); gflags::ParseCommandLineFlags(&argc, &argv, true); app app; app.run(); return 0; }
15,112
5,022
#include "../../include/core/Sprite.h" #include "../../include/graphics/Graphics.h" using namespace PhysicsEngine; Sprite::Sprite(World *world) : Asset(world) { mCreated = false; mChanged = false; mPixelsPerUnit = 100; } Sprite::Sprite(World *world, Guid id) : Asset(world, id) { mCreated = false; mChanged = false; mPixelsPerUnit = 100; } Sprite::~Sprite() { } void Sprite::serialize(YAML::Node &out) const { Asset::serialize(out); out["textureId"] = mTextureId; out["pixelsPerUnit"] = mPixelsPerUnit; } void Sprite::deserialize(const YAML::Node &in) { Asset::deserialize(in); mTextureId = YAML::getValue<Guid>(in, "textureId"); mPixelsPerUnit = YAML::getValue<int>(in, "pixelsPerUnit"); } int Sprite::getType() const { return PhysicsEngine::SPRITE_TYPE; } std::string Sprite::getObjectName() const { return PhysicsEngine::SPRITE_NAME; } bool Sprite::isCreated() const { return mCreated; } bool Sprite::isChanged() const { return mChanged; } GLuint Sprite::getNativeGraphicsVAO() const { return mVao; } Guid Sprite::getTextureId() const { return mTextureId; } void Sprite::setTextureId(Guid textureId) { mTextureId = textureId; mChanged = true; } void Sprite::create() { if (mCreated) { return; } Graphics::createSprite(&mVao); mCreated = true; } void Sprite::destroy() { if (!mCreated) { return; } Graphics::destroySprite(&mVao); mCreated = false; }
1,512
587
#pragma once #include <map> #include <string> #include "../Drawable/Drawable3D.hpp" #include "../Log.hpp" class PhysicsMesh; struct PhysicsElements; class Program; class btGeneric6DofSpringConstraint; class btHingeConstraint; class btTransform; class Spider : public Drawable3D, public Logging::Log { public: struct Part { Part(); Part(unsigned short group, unsigned short mask, float angle, bool active); unsigned short collisionGroup; unsigned short collisionMask; float restAngle; bool active; Drawable3D* part; btHingeConstraint* hinge; btGeneric6DofSpringConstraint* dof; }; Spider(); ~Spider(); // Resets the positions, rotations and such for the whole spider void reset(); void update(float deltaTime); void draw(std::shared_ptr<Program>& program, bool bindTexture = false); void draw(std::shared_ptr<Program>& program, mmm::vec3 offset, bool bindTexture = false); void input(const Input::Event& event); // Returns the child of spider if found by name Drawable3D* child(const std::string& name); std::map<std::string, Part>& parts(); // Upcasts a Drawable3D objet to a Spider object, if possible. static Spider* upcast(Drawable3D* drawable); static std::map<std::string, Part> SPIDER_PARTS; private: static std::map<std::string, btTransform> SPIDER_POSITIONS; PhysicsElements* mElements; std::shared_ptr<PhysicsMesh> mMesh; std::map<std::string, Part> mParts; };
1,650
490
// // Created by Kรฉvin POLOSSAT on 14/01/2018. // #include <memory> #include <iostream> #include "Server.h" #include "Resolver.h" #include "Launcher.h" Server::Server(): reactor_(), acceptor_(reactor_), gameManager_(std::make_unique<rtype::Launcher>()) { lw_network::Reactor reactor; lw_network::Resolver re; re .SetService("4242") .SetFamily(AF_UNSPEC) .SetSockType(SOCK_STREAM) .SetFlags(AI_PASSIVE); int yes = 1; lw_network::error_code e = lw_network::no_error; auto p = re.Resolve(); for (auto const & endPoint : p) { e = lw_network::no_error; acceptor_.open(endPoint.protocol(), e); if (e) { continue; } acceptor_.setOption(SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int), e); acceptor_.bind(endPoint, e); if (e) { acceptor_.close(e); continue; } break; } if (!acceptor_.isOpen()) { std::cerr << "FAIL" << std::endl; return ; } acceptor_.listen(SOMAXCONN, e); if (e) { std::cerr << "FAIL listen" << std::endl; return ; } doAccept_(); } void Server::run() { reactor_.handleEvents(); } void Server::doAccept_() { acceptor_.asyncAccept( [this](lw_network::ReactiveSocket peer, lw_network::error_code ec) { connectionManager_.start(std::make_shared<Connection>(std::move(peer), connectionManager_, gameManager_)); this->doAccept_(); } ); }
1,532
539
// Copyright(c) 2017 POLYGONTEK // // 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 "Precompiled.h" #include "Scripting/LuaVM.h" #include "Math/Math.h" BE_NAMESPACE_BEGIN void LuaVM::RegisterRectF(LuaCpp::Module &module) { LuaCpp::Selector _RectF = module["RectF"]; _RectF.SetClass<RectF>(); _RectF.AddClassCtor<RectF, float, float, float, float>(); _RectF.AddClassMembers<RectF>( "x", &RectF::x, "y", &RectF::y, "w", &RectF::w, "h", &RectF::h, "__tostring", static_cast<const char*(RectF::*)(void)const>(&RectF::ToString), "element", static_cast<float &(RectF::*)(int)>(&RectF::operator[]), // index start from zero "assign", static_cast<RectF&(RectF::*)(const RectF&)>(&RectF::operator=), "set", &RectF::Set, "set_4coords", &RectF::SetFrom4Coords, "is_empty", &RectF::IsEmpty, "is_contain_point", static_cast<bool(RectF::*)(const PointF&)const>(&RectF::IsContainPoint), "is_contain_rect", static_cast<bool(RectF::*)(const RectF&)const>(&RectF::IsContainRect), "is_intersect_rect", static_cast<bool(RectF::*)(const RectF&)const>(&RectF::IsIntersectRect), "add", static_cast<RectF(RectF::*)(const RectF&)const>(&RectF::Add), "add_self", &RectF::AddSelf, "add_point", static_cast<RectF(RectF::*)(const PointF&)const>(&RectF::AddPoint), "add_point_self", &RectF::AddPointSelf, "intersect", static_cast<RectF(RectF::*)(const RectF&)const>(&RectF::Intersect), "intersect_self", &RectF::IntersectSelf, "move", &RectF::Move, "move_self", &RectF::MoveSelf, "shrink", &RectF::Shrink, "shrink_self", &RectF::ShrinkSelf, "expand", &RectF::Expand, "expand_self", &RectF::ExpandSelf, "to_string", static_cast<const char*(RectF::*)()const>(&RectF::ToString)); } BE_NAMESPACE_END
2,410
863
#include "DX11TestLayer.h" #include "H2M/Renderer/TextureH2M.h" #include "H2M/Scene/ComponentsH2M.h" #include "DX11Context.h" #include "DX11SwapChain.h" #include "DX11Renderer.h" #include "DX11Shader.h" #include "DX11InputSystem.h" #include "Core/Application.h" #include "Core/ResourceManager.h" #include "Platform/Windows/WindowsWindow.h" std::shared_ptr<DX11CameraFP> DX11TestLayer::s_Camera; glm::vec2 DX11TestLayer::s_StartMousePosition; H2M::RefH2M<DX11Mesh> DX11TestLayer::s_Mesh; H2M::RefH2M<H2M::MeshH2M> DX11TestLayer::s_MeshLight; H2M::RefH2M<H2M::MeshH2M> DX11TestLayer::s_SkyboxSphere; // Render meshes with materials std::vector<RenderObject> DX11TestLayer::s_RenderObjectsWithMaterials; std::vector<H2M::RefH2M<DX11Material>> DX11TestLayer::s_ListMaterials; ImGuizmo::OPERATION DX11TestLayer::s_ImGuizmoType; bool DX11TestLayer::s_LeftControlKeyPressed = false; bool DX11TestLayer::s_ShowWindowSceneHierarchy = true; bool DX11TestLayer::s_ShowWindowAssetManager = true; bool DX11TestLayer::s_ShowWindowMaterialEditor = true; H2M::RefH2M<H2M::SceneH2M> DX11TestLayer::s_Scene; glm::mat4 DX11TestLayer::s_CurrentlySelectedTransform; float DX11TestLayer::s_ViewportWidth = 0.0f; float DX11TestLayer::s_ViewportHeight = 0.0f; glm::vec2 DX11TestLayer::s_ViewportBounds[2]; bool DX11TestLayer::s_AllowViewportCameraEvents = true; H2M::SceneHierarchyPanelH2M* DX11TestLayer::s_SceneHierarchyPanel; H2M::ContentBrowserPanelH2M* DX11TestLayer::s_ContentBrowserPanel; MaterialEditorPanel* DX11TestLayer::s_MaterialEditorPanel; DX11TestLayer::DX11TestLayer() { s_Camera = std::make_shared<DX11CameraFP>(glm::perspectiveFov(glm::radians(60.0f), 1280.0f, 720.0f, 0.1f, 1000.0f)); } DX11TestLayer::DX11TestLayer(const std::string& name) : MoravaLayer(name) { s_Camera = std::make_shared<DX11CameraFP>(glm::perspectiveFov(glm::radians(60.0f), 1280.0f, 720.0f, 0.1f, 1000.0f)); } DX11TestLayer::~DX11TestLayer() { } void DX11TestLayer::OnAttach() { DX11InputSystem::Get()->AddListener(this); s_Scene = H2M::RefH2M<H2M::SceneH2M>::Create(); s_SceneHierarchyPanel = new H2M::SceneHierarchyPanelH2M(s_Scene); s_ContentBrowserPanel = new H2M::ContentBrowserPanelH2M(); s_MaterialEditorPanel = new MaterialEditorPanel(); // Application::Get()->GetWindow()->SetInFocus(false); DX11InputSystem::Get()->ShowCursor(m_ShowMouseCursor = true); H2M::RefH2M<H2M::MeshH2M> meshSphere = H2M::RefH2M<H2M::MeshH2M>::Create("Models/PardCode/sphere_hq.obj"); /* RenderObject renderObjectGladiator; renderObjectGladiator.Mesh = H2M::RefH2M<H2M::MeshH2M>::Create("Models/Gladiator/Gladiator.fbx"); renderObjectGladiator.Textures.push_back(ResourceManager::LoadHazelTexture2D("Models/Gladiator/Gladiator_weapon_BaseColor.jpg")); renderObjectGladiator.Textures.push_back(ResourceManager::LoadHazelTexture2D("Models/Gladiator/Gladiator_weapon_Normal.jpg")); renderObjectGladiator.Textures.push_back(ResourceManager::LoadHazelTexture2D("Models/Gladiator/Gladiator_BaseColor.jpg")); renderObjectGladiator.Textures.push_back(ResourceManager::LoadHazelTexture2D("Models/Gladiator/Gladiator_Normal.jpg")); renderObjectGladiator.Transform = glm::mat4(1.0f); renderObjectGladiator.Transform = glm::translate(renderObjectGladiator.Transform, glm::vec3(0.0f, 0.0f, -2.0f)); renderObjectGladiator.Transform = glm::scale(renderObjectGladiator.Transform, glm::vec3(0.04f)); renderObjectGladiator.PipelineType = RenderObject::PipelineType::Light; m_RenderObjects.push_back(renderObjectGladiator); RenderObject renderObjectCerberus; renderObjectCerberus.Mesh = H2M::RefH2M<H2M::MeshH2M>::Create("Models/Cerberus/CerberusMaterials.fbx"); renderObjectCerberus.Textures.push_back(renderObjectCerberus.Mesh->GetTextures().at(0)); renderObjectCerberus.Textures.push_back(renderObjectCerberus.Mesh->GetTextures().at(1)); renderObjectCerberus.Transform = glm::mat4(1.0f); renderObjectCerberus.Transform = glm::translate(renderObjectCerberus.Transform, glm::vec3(0.0f, 4.0f, 14.0f)); renderObjectCerberus.Transform = glm::rotate(renderObjectCerberus.Transform, glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f)); renderObjectCerberus.Transform = glm::rotate(renderObjectCerberus.Transform, glm::radians(180.0f), glm::vec3(0.0f, 0.0f, 1.0f)); renderObjectCerberus.Transform = glm::scale(renderObjectCerberus.Transform, glm::vec3(4.0f)); renderObjectCerberus.PipelineType = RenderObject::PipelineType::Light; m_RenderObjects.push_back(renderObjectCerberus); RenderObject renderObjectSphereLeft; renderObjectSphereLeft.Mesh = meshSphere; renderObjectSphereLeft.Textures.push_back(ResourceManager::LoadHazelTexture2D("Textures/PardCode/brick_d.jpg")); renderObjectSphereLeft.Textures.push_back(ResourceManager::LoadHazelTexture2D("Textures/PardCode/brick_n.jpg")); renderObjectSphereLeft.Transform = glm::mat4(1.0f); renderObjectSphereLeft.Transform = glm::translate(renderObjectSphereLeft.Transform, glm::vec3(-4.0f, 2.0f, 0.0f)); renderObjectSphereLeft.PipelineType = RenderObject::PipelineType::Light; m_RenderObjects.push_back(renderObjectSphereLeft); RenderObject renderObjectSphereRight; renderObjectSphereRight.Mesh = meshSphere; renderObjectSphereRight.Textures.push_back(ResourceManager::LoadHazelTexture2D("Textures/PardCode/brick_d.jpg")); renderObjectSphereRight.Textures.push_back(ResourceManager::LoadHazelTexture2D("Textures/PardCode/brick_n.jpg")); renderObjectSphereRight.Transform = glm::mat4(1.0f); renderObjectSphereRight.Transform = glm::translate(renderObjectSphereRight.Transform, glm::vec3(4.0f, 2.0f, 0.0f)); renderObjectSphereRight.PipelineType = RenderObject::PipelineType::Light; m_RenderObjects.push_back(renderObjectSphereRight); */ RenderObject renderObjectTerrain; renderObjectTerrain.Mesh = H2M::RefH2M<H2M::MeshH2M>::Create("Models/PardCode/terrain.obj"); renderObjectTerrain.Textures.push_back(ResourceManager::LoadTexture2D_H2M("Textures/PardCode/sand.jpg", true)); renderObjectTerrain.Textures.push_back(ResourceManager::LoadTexture2D_H2M("Textures/PardCode/normal_blank.png", false)); renderObjectTerrain.Transform = glm::mat4(1.0f); renderObjectTerrain.Transform = glm::scale(renderObjectTerrain.Transform, glm::vec3(4.0f)); renderObjectTerrain.PipelineType = RenderObject::PipelineType::Unlit; m_RenderObjects.push_back(renderObjectTerrain); // ---- other assets ---- ResourceManager::LoadTexture2D_H2M("Textures/PardCode/sky.jpg", true); // ResourceManager::LoadHazelTexture2D("Textures/PardCode/wood.jpg"); // ResourceManager::LoadHazelTexture2D("Textures/PardCode/normal_blank.png"); // ResourceManager::LoadHazelTexture2D("Textures/PardCode/brick.png"); // ResourceManager::LoadHazelTexture2D("Textures/PardCode/brick_d.jpg"); // ResourceManager::LoadHazelTexture2D("Textures/PardCode/brick_n.jpg"); // ResourceManager::LoadHazelTexture2D("Textures/default_material_albedo.png"); // ResourceManager::LoadHazelTexture2D("Textures/PardCode/normal_blank.png"); // ResourceManager::LoadHazelTexture2D("Textures/PardCode/umhlanga_sunrise_4k.jpg"); // ResourceManager::LoadHazelTexture2D("Textures/PardCode/gold.png"); // ResourceManager::LoadHazelTexture2D("Textures/container/container2.png"); // ResourceManager::LoadHazelTexture2D("Textures/container/container2_normal.png"); s_Mesh = H2M::RefH2M<DX11Mesh>::Create(L"Models/PardCode/teapot.obj"); // s_Mesh = H2M::RefH2M<DX11Mesh>::Create(L"Models/PardCode/spaceship.obj"); s_MeshLight = meshSphere; s_SkyboxSphere = meshSphere; /**** BEGIN Pipeline Unlit ****/ H2M::PipelineSpecificationH2M pipelineSpecUnlit; pipelineSpecUnlit.DebugName = "Pipeline Unlit"; pipelineSpecUnlit.Layout = H2M::VertexBufferLayoutH2M{}; MoravaShaderSpecification moravaShaderSpecificationUnlit; moravaShaderSpecificationUnlit.ShaderType = MoravaShaderSpecification::ShaderType::DX11Shader; moravaShaderSpecificationUnlit.VertexShaderPath = "Shaders/HLSL/UnlitVertexShader.hlsl"; moravaShaderSpecificationUnlit.PixelShaderPath = "Shaders/HLSL/UnlitPixelShader.hlsl"; moravaShaderSpecificationUnlit.ForceCompile = false; ResourceManager::CreateOrLoadShader(moravaShaderSpecificationUnlit); pipelineSpecUnlit.Shader = ResourceManager::CreateOrLoadShader(moravaShaderSpecificationUnlit); H2M::RefH2M<DX11Pipeline> pipelineUnlit = DX11Pipeline::Create(pipelineSpecUnlit); /**** END Pipeline Unlit ****/ /**** BEGIN Pipeline Illuminated ****/ H2M::PipelineSpecificationH2M pipelineSpecIlluminated; pipelineSpecIlluminated.DebugName = "Pipeline Illuminated"; pipelineSpecIlluminated.Layout = H2M::VertexBufferLayoutH2M{}; MoravaShaderSpecification moravaShaderSpecificationIlluminated; moravaShaderSpecificationIlluminated.ShaderType = MoravaShaderSpecification::ShaderType::DX11Shader; moravaShaderSpecificationIlluminated.VertexShaderPath = "Shaders/HLSL/DirLightVertexShader.hlsl"; moravaShaderSpecificationIlluminated.PixelShaderPath = "Shaders/HLSL/DirLightPixelShader.hlsl"; moravaShaderSpecificationIlluminated.ForceCompile = false; pipelineSpecIlluminated.Shader = ResourceManager::CreateOrLoadShader(moravaShaderSpecificationIlluminated); H2M::RefH2M<DX11Pipeline> pipelineIlluminated = DX11Pipeline::Create(pipelineSpecIlluminated); /**** END Pipeline Illuminated ****/ /**** BEGIN Create meshes with materials **** H2M::RefH2M<DX11Material> materialIlluminated = H2M::RefH2M<DX11Material>::Create(pipelineIlluminated, "Material Illuminated"); H2M::RefH2M<DX11Material> materialUnlit = H2M::RefH2M<DX11Material>::Create(pipelineIlluminated, "Material Unlit"); H2M::RefH2M<DX11Material> materialIlluminatedDerived = H2M::RefH2M<DX11Material>::Create(materialIlluminated, "Material Illuminated Derived"); H2M::RefH2M<DX11Material> materialUnlitDerived = H2M::RefH2M<DX11Material>::Create(materialUnlit, "Material Unlit Derived"); // BEGIN prepare data for rendering meshes with materials (render objects and the list of materials) // std::vector<RenderObject> DX11TestLayer::s_RenderObjectsWithMaterials; // std::vector<H2M::RefH2M<DX11Material>> DX11TestLayer::s_ListMaterials; s_ListMaterials.reserve(32); // reserve 32 slots H2M::RefH2M<Hazel::HazelTexture2D> textureBarrel = ResourceManager::LoadHazelTexture2D("Textures/PardCode/barrel.jpg"); H2M::RefH2M<Hazel::HazelTexture2D> textureHouseBrick = ResourceManager::LoadHazelTexture2D("Textures/PardCode/house_brick.jpg"); H2M::RefH2M<Hazel::HazelTexture2D> textureHouseWindows = ResourceManager::LoadHazelTexture2D("Textures/PardCode/house_windows.jpg"); H2M::RefH2M<Hazel::HazelTexture2D> textureHouseWood = ResourceManager::LoadHazelTexture2D("Textures/PardCode/house_wood.jpg"); H2M::RefH2M<DX11Material> materialBarrel = DX11Material::Create(pipelineSpecIlluminated.Shader, "Material Barrel"); H2M::RefH2M<DX11Material> materialHouseBrick = DX11Material::Create(pipelineSpecIlluminated.Shader, "Material House Brick"); H2M::RefH2M<DX11Material> materialHouseWindows = DX11Material::Create(pipelineSpecIlluminated.Shader, "Material House Windows"); H2M::RefH2M<DX11Material> materialHouseWood = DX11Material::Create(pipelineSpecIlluminated.Shader, "Material House Wood"); materialBarrel->AddTexture(textureBarrel.As<DX11Texture2D>()); materialHouseBrick->AddTexture(textureHouseBrick.As<DX11Texture2D>()); materialHouseWindows->AddTexture(textureHouseWindows.As<DX11Texture2D>()); materialHouseWood->AddTexture(textureHouseWood.As<DX11Texture2D>()); s_ListMaterials.push_back(materialBarrel); s_ListMaterials.push_back(materialHouseBrick); s_ListMaterials.push_back(materialHouseWindows); s_ListMaterials.push_back(materialHouseWood); RenderObject renderObjectHouse; renderObjectHouse.MeshDX11 = H2M::RefH2M<DX11Mesh>::Create(L"Models/PardCode/house.obj"); renderObjectHouse.Transform = glm::mat4(1.0f); renderObjectHouse.Transform = glm::translate(renderObjectHouse.Transform, glm::vec3(0.0f, 0.0f, -20.0f)); renderObjectHouse.Transform = glm::scale(renderObjectHouse.Transform, glm::vec3(6.0f)); renderObjectHouse.PipelineType = RenderObject::PipelineType::Light; s_RenderObjectsWithMaterials.push_back(renderObjectHouse); /**** END Create meshes with materials ****/ // END prepare data for rendering meshes with materials (render objects and the list of materials) } void DX11TestLayer::OnDetach() { } void DX11TestLayer::OnUpdate(H2M::TimestepH2M ts) { bool windowInFocus = Application::Get()->GetWindow()->IsInFocus(); bool cameraEnabled = windowInFocus; // && !m_ShowMouseCursor; s_Camera->SetEnabled(cameraEnabled); // Log::GetLogger()->info("windowInFocus: {0}, m_ShowMouseCursor: {1}, cameraEnabled: {2}", windowInFocus, m_ShowMouseCursor, cameraEnabled); DX11InputSystem::Get()->Update(); s_Camera->OnUpdate(ts); s_Camera->SetProjectionMatrix( glm::perspectiveFov(glm::radians(60.0f), (float)DX11Renderer::GetViewportWidth(), (float)DX11Renderer::GetViewportHeight(), 0.01f, 1000.0f)); glm::vec4 clearColor = { 0.1f, 0.1f, 0.1f, 1.0f }; Render(clearColor, s_Camera); for (RenderObject renderObject : m_RenderObjects) { DX11Renderer::SubmitMesh(renderObject); } } void DX11TestLayer::OnEvent(H2M::EventH2M& event) { s_Camera->OnEvent(event); if (event.GetEventType() == H2M::EventTypeH2M::WindowResize) { H2M::WindowResizeEventH2M& e = (H2M::WindowResizeEventH2M&)event; if (e.GetWidth() != 0 && e.GetHeight() != 0) { s_Camera->SetViewportSize((float)e.GetWidth(), (float)e.GetHeight()); s_Camera->SetProjectionMatrix(glm::perspectiveFov(glm::radians(60.0f), (float)e.GetWidth(), (float)e.GetHeight(), 0.1f, 1000.0f)); } } } void DX11TestLayer::ShowExampleAppDockSpace(bool* p_open, Window* mainWindow) { } void DX11TestLayer::OnRender(Window* mainWindow, Scene* scene) { DX11Renderer::Draw(scene->GetCamera()); } void DX11TestLayer::OnImGuiRender(Window* mainWindow, Scene* scene) { } void DX11TestLayer::Render(const glm::vec4& clearColor, std::shared_ptr<DX11CameraFP> camera) { } void DX11TestLayer::OnKeyDown(int key) { if (key == VK_LCONTROL) { s_LeftControlKeyPressed = true; } } void DX11TestLayer::OnKeyUp(int key) { if (key == VK_ESCAPE) { // Application::Get()->GetWindow()->SetInFocus(false); DX11InputSystem::Get()->ShowCursor(m_ShowMouseCursor = true); } if (key == 'F') { m_FullscreenEnabled = !m_FullscreenEnabled; WindowsWindow* windowsWindow = (WindowsWindow*)Application::Get()->GetWindow(); RECT windowRECT = windowsWindow->GetSizeScreen(); uint32_t width = windowRECT.right; // - windowRECT.left; uint32_t height = windowRECT.bottom; // - windowRECT.top; DX11Context::Get()->GetSwapChain()->SetFullScreen(m_FullscreenEnabled, width, height); } // ImGizmo switching modes switch (key) { case '1': s_ImGuizmoType = ImGuizmo::OPERATION::TRANSLATE; break; case '2': s_ImGuizmoType = ImGuizmo::OPERATION::ROTATE; break; case '3': s_ImGuizmoType = ImGuizmo::OPERATION::SCALE; break; case '4': s_ImGuizmoType = (ImGuizmo::OPERATION)-1; break; } if (key == VK_LCONTROL) { s_LeftControlKeyPressed = false; } if (s_LeftControlKeyPressed) { if (key == 'H') { s_ShowWindowSceneHierarchy = !s_ShowWindowSceneHierarchy; Log::GetLogger()->info("s_ShowWindowSceneHierarchy: {0}", s_ShowWindowSceneHierarchy); } if (key == VK_SPACE) { s_ShowWindowAssetManager = !s_ShowWindowAssetManager; Log::GetLogger()->info("s_ShowWindowAssetManager: {0}", s_ShowWindowAssetManager); } if (key == 'M') { s_ShowWindowMaterialEditor = !s_ShowWindowMaterialEditor; Log::GetLogger()->info("s_ShowWindowMaterialEditor: {0}", s_ShowWindowMaterialEditor); } } } void DX11TestLayer::OnMouseMove(const glm::vec2& mousePosDelta, const glm::vec2& mousePosAbs) { } void DX11TestLayer::OnLeftMouseDown(const glm::vec2& mousePos) { // MOUSE events POINT currentMousePos = {}; ::GetCursorPos(&currentMousePos); s_StartMousePosition = glm::vec2(currentMousePos.x, currentMousePos.y); if (DX11InputSystem::Get()->IsMouseCursorAboveViewport()) { Application::Get()->GetWindow()->SetInFocus(true); } // DX11InputSystem::Get()->ShowCursor(m_ShowMouseCursor = false); // Log::GetLogger()->info("DX11TestLayer::OnLeftMouseDown {0}x{1}", mousePos.x, mousePos.y); // bool windowInFocus = Application::Get()->GetWindow()->IsInFocus(); // Log::GetLogger()->info("Window::m_InFocus: {0}, m_ShowMouseCursor: {1}, m_Camera->IsEnabled: {2}", // windowInFocus, m_ShowMouseCursor, DX11CameraFP::Get()->IsEnabled()); OnLeftMouseDownEventHandler(mousePos); } void DX11TestLayer::OnRightMouseDown(const glm::vec2& mousePos) { } void DX11TestLayer::OnLeftMouseUp(const glm::vec2& mousePos) { } void DX11TestLayer::OnRightMouseUp(const glm::vec2& mousePos) { } bool DX11TestLayer::OnLeftMouseDownEventHandler(const glm::vec2& mousePos) { float mx = mousePos.x; float my = mousePos.y; Log::GetLogger()->debug("DX11TestLayer::OnLeftMouseDownEventHandler mousePos.x: {0}, mousePos.y: {1}", mousePos.x, mousePos.y); if (!ImGuizmo::IsUsing() && !ImGuizmo::IsOver()) { auto [mouseX, mouseY] = GetMouseViewportSpace(); Log::GetLogger()->debug("DX11TestLayer::OnLeftMouseDownEventHandler GetMouseViewportSpace mouseX: {0}, mouseY: {1}", mouseX, mouseY); if (mouseX > -1.0f && mouseX < 1.0f && mouseY > -1.0f && mouseY < 1.0f) { auto [origin, direction] = CastRay(mouseX, mouseY); EntitySelection::s_SelectionContext.clear(); auto meshEntities = s_Scene->GetAllEntitiesWith<H2M::MeshComponentH2M>(); for (auto e : meshEntities) { H2M::EntityH2M entity = { e, s_Scene.Raw() }; auto mesh = entity.GetComponent<H2M::MeshComponentH2M>().Mesh; if (!mesh) { continue; } std::vector<H2M::RefH2M<H2M::SubmeshH2M>>& submeshes = mesh->GetSubmeshes(); float lastT = std::numeric_limits<float>::max(); // Distance between camera and intersection in CastRay // for (Hazel::Submesh& submesh : submeshes) for (uint32_t i = 0; i < submeshes.size(); i++) { H2M::RefH2M<H2M::SubmeshH2M> submesh = submeshes[i]; auto transform = entity.GetComponent<H2M::TransformComponentH2M>().GetTransform(); H2M::RayH2M ray = { glm::inverse(transform * submesh->Transform) * glm::vec4(origin, 1.0f), glm::inverse(glm::mat3(transform) * glm::mat3(submesh->Transform)) * direction }; float t; bool intersects = ray.IntersectsAABB(submesh->BoundingBox, t); if (intersects) { const auto& triangleCache = ((H2M::MeshH2M*)mesh.Raw())->GetTriangleCache(i); if (triangleCache.size()) { for (const auto& triangle : triangleCache) { if (ray.IntersectsTriangle(triangle.V0.Position, triangle.V1.Position, triangle.V2.Position, t)) { AddSubmeshToSelectionContext({ entity, submesh, t }); Log::GetLogger()->debug("Adding submesh to selection context. Submesh Name: '{0}', selection size: '{1}'", submesh->MeshName, EntitySelection::s_SelectionContext.size()); break; } } } else { AddSubmeshToSelectionContext({ entity, submesh, t }); } } } } std::sort(EntitySelection::s_SelectionContext.begin(), EntitySelection::s_SelectionContext.end(), [](auto& a, auto& b) { return a.Distance < b.Distance; }); // TODO: Handle mesh being deleted, etc if (EntitySelection::s_SelectionContext.size()) { s_CurrentlySelectedTransform = EntitySelection::s_SelectionContext[0].Mesh->Transform; OnSelected(EntitySelection::s_SelectionContext[0]); } else { RefH2M<H2M::EntityH2M> meshEntity = GetMeshEntity(); if (meshEntity) { s_CurrentlySelectedTransform = meshEntity->Transform().GetTransform(); } } } } return false; } std::pair<float, float> DX11TestLayer::GetMouseViewportSpace() { auto [mx, my] = ImGui::GetMousePos(); // Input::GetMousePosition(); mx -= s_ViewportBounds[0].x; my -= s_ViewportBounds[0].y; s_ViewportWidth = s_ViewportBounds[1].x - s_ViewportBounds[0].x; s_ViewportHeight = s_ViewportBounds[1].y - s_ViewportBounds[0].y; return { (mx / s_ViewportWidth) * 2.0f - 1.0f, ((my / s_ViewportHeight) * 2.0f - 1.0f) * -1.0f }; } std::pair<glm::vec3, glm::vec3> DX11TestLayer::CastRay(float mx, float my) { glm::vec4 mouseClipPos = { mx, my, -1.0f, 1.0f }; glm::mat4 projectionMatrix = s_Camera->GetProjectionMatrix(); glm::mat4 viewMatrix = s_Camera->GetViewMatrix(); auto inverseProj = glm::inverse(projectionMatrix); auto inverseView = glm::inverse(glm::mat3(viewMatrix)); glm::vec4 ray = inverseProj * mouseClipPos; glm::vec3 rayPos = s_Camera->GetPosition(); glm::vec3 rayDir = inverseView * glm::vec3(ray); // inverseView * glm::vec3(ray) Log::GetLogger()->debug("DX11TestLayer::CastRay | MousePosition [ {0} {1} ]", mx, my); Log::GetLogger()->debug("DX11TestLayer::CastRay | m_ViewportBounds[0] [ {0} {1} ]", s_ViewportBounds[0].x, s_ViewportBounds[0].y); Log::GetLogger()->debug("DX11TestLayer::CastRay | m_ViewportBounds[1] [ {0} {1} ]", s_ViewportBounds[1].x, s_ViewportBounds[1].y); Log::GetLogger()->debug("DX11TestLayer::CastRay | mouseClipPos [ {0} {1} ]", mouseClipPos.x, mouseClipPos.y); return { rayPos, rayDir }; } void DX11TestLayer::AddSubmeshToSelectionContext(SelectedSubmesh submesh) { EntitySelection::s_SelectionContext.push_back(submesh); if (EntitySelection::s_SelectionContext.size() && EntitySelection::s_SelectionContext[0].Mesh) { Log::GetLogger()->debug("SelectionContext[0].Mesh->MeshName: '{0}'", EntitySelection::s_SelectionContext[0].Mesh->MeshName); } } void DX11TestLayer::OnSelected(const SelectedSubmesh& selectionContext) { // TODO: move to SceneHazelEnvMap s_SceneHierarchyPanel->SetSelected(selectionContext.Entity); s_Scene->SetSelectedEntity(selectionContext.Entity); } RefH2M<H2M::EntityH2M> DX11TestLayer::GetMeshEntity() { RefH2M<H2M::EntityH2M> meshEntity; auto meshEntities = s_Scene->GetAllEntitiesWith<H2M::MeshComponentH2M>(); if (meshEntities.size()) { for (auto entt : meshEntities) { meshEntity = CreateRefH2M<H2M::EntityH2M>(entt, s_Scene.Raw()); } return meshEntity; } return nullptr; }
22,104
8,827
// // icompound.cpp // cnnet // // Created by Mingkai Chen on 2017-07-17. // Copyright ยฉ 2017 Mingkai Chen. All rights reserved. // #include "compounds/mlp.hpp" #ifdef ROCNNET_ICOMPOUND_HPP namespace rocnnet { icompound::icompound (std::string scope) : ilayer(scope) {} icompound::~icompound (void) {} icompound* icompound::clone (std::string scope) const { return static_cast<icompound*>(this->clone_impl(scope)); } icompound* icompound::move (void) { return static_cast<icompound*>(this->move_impl()); } void icompound::initialize (std::string serialname, std::string readscope) { if (readscope.empty()) readscope = scope_; std::vector<nnet::variable<double>*> vars = this->get_variables(); std::vector<nnet::inode<double>*> nv(vars.begin(), vars.end()); if (nnet::read_inorder<double>(nv, readscope, serialname) && nv.empty()) { return; } for (nnet::variable<double>* v : vars) { v->initialize(); } } bool icompound::save (std::string fname, std::string writescope) const { if (writescope.empty()) writescope = scope_; std::vector<nnet::variable<double>*> vars = this->get_variables(); std::vector<nnet::inode<double>*> nv(vars.begin(), vars.end()); return nnet::write_inorder<double>(nv, writescope, fname); } } #endif
1,258
498
#include<vector> #include<unordered_map> #include<algorithm> #include<iostream> using namespace std; class Solution { public: int leastInterval(vector<char>& tasks, int n) { unordered_map<char, int> dict; int maxFreq = -1; int maxFreqCount = 0; for (auto& ch : tasks) dict[ch]++; for (auto& kvp : dict) maxFreq = max(maxFreq, kvp.second); for (auto& kvp : dict) { if (kvp.second == maxFreq) maxFreqCount++; } int res = 0; const int len = tasks.size(); res = max((maxFreq - 1)*(n+1) + maxFreqCount, len); return res; } }; // Test int main() { Solution sol; vector<char> tasks = {'A','A','A','B','B','B'}; int n = 2; auto res = sol.leastInterval(tasks, n); cout << res << endl; return 0; }
862
302
#include "FEMClothMesh.h" #include <autodiff/forward.hpp> #include <autodiff/forward/eigen.hpp> #include "tbb/blocked_range.h" #include "tbb/parallel_for.h" namespace ClothSim { static std::vector<double> buildTriangleAreas(const TriMesh& mesh, const VecVec2d& restUVs) { std::vector<double> triangleAreas(mesh.triangleCount(), 0); tbb::parallel_for(tbb::blocked_range<int>(0, mesh.triangleCount()), [&](tbb::blocked_range<int>& range) { for (int triIndex = range.begin(); triIndex != range.end(); ++triIndex) { const Vec3i& tri = mesh.triangle(triIndex); const Vec2d& v0 = restUVs[tri[0]]; const Vec2d& v1 = restUVs[tri[1]]; const Vec2d& v2 = restUVs[tri[2]]; triangleAreas[triIndex] = .5 * std::fabs(v0[0] * (v1[1] - v2[1]) + v1[0] * (v2[1] - v0[1]) + v2[0] * (v0[1] - v1[1])); } }); return triangleAreas; } static std::vector<double> buildVertexMasses(const TriMesh& mesh, const std::vector<double>& triangleAreas, double density) { std::vector<double> vertexMasses(mesh.vertexCount(), 0); assert(mesh.vertexCount() == mesh.adjacentTriangles().size()); assert(triangleAreas.size() == mesh.triangleCount()); tbb::parallel_for(tbb::blocked_range<int>(0, mesh.vertexCount()), [&](tbb::blocked_range<int>& range) { for (int vertexIndex = range.begin(); vertexIndex != range.end(); ++vertexIndex) { for (int triIndex : mesh.adjacentTriangles()[vertexIndex]) vertexMasses[vertexIndex] += 1. / 3. * density * triangleAreas[triIndex]; } }); return vertexMasses; } static VecMat2x2d buildDmInv(const TriMesh& mesh, const VecVec2d& restUVs) { assert(mesh.vertexCount() == restUVs.size()); VecMat2x2d dmInv(mesh.triangleCount()); tbb::parallel_for(tbb::blocked_range<int>(0, mesh.triangleCount()), [&](tbb::blocked_range<int>& range) { Mat2x2d localD; for (int triIndex = range.begin(); triIndex != range.end(); ++triIndex) { const Vec3i& tri = mesh.triangle(triIndex); localD.col(0) = restUVs[tri[1]] - restUVs[tri[0]]; localD.col(1) = restUVs[tri[2]] - restUVs[tri[0]]; dmInv[triIndex] = localD.inverse(); } }); return dmInv; } template<typename Scalar> Vec6t<Scalar> computeF(const Vec6t<Scalar>& D, const Vec4t<Scalar>& Dinv) { Mat3x2t<Scalar> Dmat; Dmat.block(0, 0, 3, 1) = D.block(0, 0, 3, 1); Dmat.block(0, 1, 3, 1) = D.block(3, 0, 3, 1); Mat2x2t<Scalar> DinvMat; DinvMat.block(0, 0, 2, 1) = Dinv.block(0, 0, 2, 1); DinvMat.block(0, 1, 2, 1) = Dinv.block(2, 0, 2, 1); Mat3x2t<Scalar> Fmat = Dmat * DinvMat; Vec6t<Scalar> Fvec; Fvec.block(0, 0, 3, 1) = Fmat.block(0, 0, 3, 1); Fvec.block(3, 0, 3, 1) = Fmat.block(0, 1, 3, 1); return Fvec; } static Mat3x2d computeF(const Vec3d& v0, const Vec3d& v1, const Vec3d& v2, const Mat2x2d& DmInv) { Mat3x2d Ds; Ds.col(0) = v1 - v0; Ds.col(1) = v2 - v0; return Ds * DmInv; } template<typename Scalar> static Vec6t<Scalar> computeFTemplated(const Vec3t<Scalar>& v0, const Vec3t<Scalar>& v1, const Vec3t<Scalar>& v2, const Mat2x2t<Scalar>& DmInv) { Mat3x2t<Scalar> Ds; Ds.col(0) = v1 - v0; Ds.col(1) = v2 - v0; Mat3x2t<Scalar> Fmat = Ds * DmInv; Vec6t<Scalar> Fvec; Fvec.block(0, 0, 3, 1) = Fmat.col(0); Fvec.block(3, 0, 3, 1) = Fmat.col(1); return Fvec; } static Mat6x9d builddFdxAutodiff(const TriMesh& mesh, const VecMat2x2d& DmInv, int triIndex) { using autodiff::dual; using autodiff::forward::jacobian; using autodiff::forward::at; using autodiff::forward::wrtpack; const Vec3i& tri = mesh.triangle(triIndex); const Vec3d& v0 = mesh.vertex(tri[0]); const Vec3d& v1 = mesh.vertex(tri[1]); const Vec3d& v2 = mesh.vertex(tri[2]); Vec3t<dual> dualV0 = v0.cast<dual>(); Vec3t<dual> dualV1 = v1.cast<dual>(); Vec3t<dual> dualV2 = v2.cast<dual>(); Mat2x2t<dual> dualDmInv = DmInv[triIndex].cast<dual>(); Vec6t<dual> dualF; Mat6x9d dFdx = jacobian(computeFTemplated<dual>, wrtpack(dualV0, dualV1, dualV2), at(dualV0, dualV1, dualV2, dualDmInv), dualF); #if !defined(NDEBUG) Mat3x2d F = computeF(v0, v1, v2, DmInv[triIndex]); Mat3x2d Fautodiff; Fautodiff.col(0) = dualF.block(0, 0, 3, 1).cast<double>(); Fautodiff.col(1) = dualF.block(3, 0, 3, 1).cast<double>(); assert((Fautodiff - F).lpNorm<Eigen::Infinity>() < 1e-10); #endif return dFdx; } static VecMat6x9d builddFdx(const TriMesh& mesh, const VecMat2x2d& DmInv) { VecMat6x9d dFdx(mesh.triangleCount(), Mat6x9d::Zero()); tbb::parallel_for(tbb::blocked_range<int>(0, mesh.triangleCount()), [&](tbb::blocked_range<int>& range) { for (int triIndex = range.begin(); triIndex != range.end(); ++triIndex) { double s0 = DmInv[triIndex].col(0).sum(); double s1 = DmInv[triIndex].col(1).sum(); double d0 = DmInv[triIndex](0, 0); double d1 = DmInv[triIndex](1, 0); double d2 = DmInv[triIndex](0, 1); double d3 = DmInv[triIndex](1, 1); // dF / dx0 dFdx[triIndex](0, 0) = -s0; dFdx[triIndex](3, 0) = -s1; // dF / dy0 dFdx[triIndex](1, 1) = -s0; dFdx[triIndex](4, 1) = -s1; // dF / dz0 dFdx[triIndex](2, 2) = -s0; dFdx[triIndex](5, 2) = -s1; // dF / dx1 dFdx[triIndex](0, 3) = d0; dFdx[triIndex](3, 3) = d2; // dF / dy1 dFdx[triIndex](1, 4) = d0; dFdx[triIndex](4, 4) = d2; // dF / dz1 dFdx[triIndex](2, 5) = d0; dFdx[triIndex](5, 5) = d2; // dF / dx2 dFdx[triIndex](0, 6) = d1; dFdx[triIndex](3, 6) = d3; // dF / dy2 dFdx[triIndex](1, 7) = d1; dFdx[triIndex](4, 7) = d3; // dF / dz2 dFdx[triIndex](2, 8) = d1; dFdx[triIndex](5, 8) = d3; #if !defined(NDEBUG) // Autodiff verification Mat6x9d dFdxAutodiff = builddFdxAutodiff(mesh, DmInv, triIndex); assert((dFdx[triIndex] - dFdxAutodiff).lpNorm<Eigen::Infinity>() < 1e-10); #endif } }); return dFdx; } FEMClothMesh::FEMClothMesh(const std::vector<int>& fixedVertices, const double density, const double stretchStiffness, const double shearStiffness, const VecVec2d& restUVs, const TriMesh& inputMesh) : TriMesh(inputMesh) , myVertexVelocities(this->vertexCount(), Vec3d::Zero()) , myFixedVertices(this->vertexCount(), false) , myDensity(density) , myStretchStiffness(stretchStiffness) , myShearStiffness(shearStiffness) , myRestTriangleAreas(buildTriangleAreas(inputMesh, restUVs)) , myVertexMasses(buildVertexMasses(inputMesh, myRestTriangleAreas, myDensity)) , myDmInv(buildDmInv(inputMesh, restUVs)) , mydFdX(builddFdx(inputMesh, myDmInv)) , myF(this->triangleCount()) , myStateDirty(true) { for (int vertIndex : fixedVertices) myFixedVertices[vertIndex] = true; computeState(); } void FEMClothMesh::buildF() { tbb::parallel_for(tbb::blocked_range<int>(0, this->triangleCount()), [&](const tbb::blocked_range<int>& range) { for (int triIndex = range.begin(); triIndex != range.end(); ++triIndex) { const Vec3i& tri = this->triangle(triIndex); const Vec3d& v0 = this->vertex(tri[0]); const Vec3d& v1 = this->vertex(tri[1]); const Vec3d& v2 = this->vertex(tri[2]); myF[triIndex] = computeF(v0, v1, v2, myDmInv[triIndex]); } }); } void FEMClothMesh::computeState() { if (myStateDirty) { buildF(); myStateDirty = false; } } }
7,096
3,466
/** * Copyright (c) 2020 Intel Corporation * * 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. */ #pragma once #include "activation.hpp" namespace tinymind { #if (defined(TINYMIND_USE_TANH_1_31)) struct TanhValuesTableQ1_31 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_1_31)) #if (defined(TINYMIND_USE_TANH_2_30)) struct TanhValuesTableQ2_30 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_2_30)) #if (defined(TINYMIND_USE_TANH_3_29)) struct TanhValuesTableQ3_29 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_3_29)) #if (defined(TINYMIND_USE_TANH_4_28)) struct TanhValuesTableQ4_28 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_4_28)) #if (defined(TINYMIND_USE_TANH_5_27)) struct TanhValuesTableQ5_27 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_5_27)) #if (defined(TINYMIND_USE_TANH_6_26)) struct TanhValuesTableQ6_26 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_6_26)) #if (defined(TINYMIND_USE_TANH_7_25)) struct TanhValuesTableQ7_25 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_7_25)) #if (defined(TINYMIND_USE_TANH_8_24)) struct TanhValuesTableQ8_24 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_8_24)) #if (defined(TINYMIND_USE_TANH_9_23)) struct TanhValuesTableQ9_23 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_9_23)) #if (defined(TINYMIND_USE_TANH_10_22)) struct TanhValuesTableQ10_22 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_10_22)) #if (defined(TINYMIND_USE_TANH_11_21)) struct TanhValuesTableQ11_21 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_11_21)) #if (defined(TINYMIND_USE_TANH_12_20)) struct TanhValuesTableQ12_20 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_12_20)) #if (defined(TINYMIND_USE_TANH_13_19)) struct TanhValuesTableQ13_19 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_13_19)) #if (defined(TINYMIND_USE_TANH_14_18)) struct TanhValuesTableQ14_18 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_14_18)) #if (defined(TINYMIND_USE_TANH_15_17)) struct TanhValuesTableQ15_17 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_15_17)) #if (defined(TINYMIND_USE_TANH_16_16)) struct TanhValuesTableQ16_16 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_16_16)) #if (defined(TINYMIND_USE_TANH_17_15)) struct TanhValuesTableQ17_15 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_17_15)) #if (defined(TINYMIND_USE_TANH_18_14)) struct TanhValuesTableQ18_14 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_18_14)) #if (defined(TINYMIND_USE_TANH_19_13)) struct TanhValuesTableQ19_13 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_19_13)) #if (defined(TINYMIND_USE_TANH_20_12)) struct TanhValuesTableQ20_12 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_20_12)) #if (defined(TINYMIND_USE_TANH_21_11)) struct TanhValuesTableQ21_11 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_21_11)) #if (defined(TINYMIND_USE_TANH_22_10)) struct TanhValuesTableQ22_10 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_22_10)) #if (defined(TINYMIND_USE_TANH_23_9)) struct TanhValuesTableQ23_9 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_23_9)) #if (defined(TINYMIND_USE_TANH_24_8)) struct TanhValuesTableQ24_8 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_24_8)) #if (defined(TINYMIND_USE_TANH_25_7)) struct TanhValuesTableQ25_7 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_25_7)) #if (defined(TINYMIND_USE_TANH_26_6)) struct TanhValuesTableQ26_6 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_26_6)) #if (defined(TINYMIND_USE_TANH_27_5)) struct TanhValuesTableQ27_5 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_27_5)) #if (defined(TINYMIND_USE_TANH_28_4)) struct TanhValuesTableQ28_4 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_28_4)) #if (defined(TINYMIND_USE_TANH_29_3)) struct TanhValuesTableQ29_3 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_29_3)) #if (defined(TINYMIND_USE_TANH_30_2)) struct TanhValuesTableQ30_2 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_30_2)) #if (defined(TINYMIND_USE_TANH_31_1)) struct TanhValuesTableQ31_1 { static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES]; }; #endif // (defined(TINYMIND_USE_TANH_31_1)) }
7,869
3,419
/* * Copyright (c) 2000, 2020, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * http://oss.oracle.com/licenses/upl. */ #include "coherence/util/filter/InKeySetFilter.hpp" #include "coherence/io/pof/SystemPofContext.hpp" #include "coherence/util/filter/ExtractorFilter.hpp" #include "coherence/util/HashSet.hpp" #include "private/coherence/util/InvocableMapHelper.hpp" COH_OPEN_NAMESPACE3(coherence,util,filter) COH_REGISTER_PORTABLE_CLASS(72, InKeySetFilter); // ----- constructors ------------------------------------------------------- InKeySetFilter::InKeySetFilter() : f_vFilter(self()), m_vSetKeys(self(), NULL, /* mutable */ true), m_fConverted(false) { } InKeySetFilter::InKeySetFilter(Filter::View vFilter, Set::View vSetKeys) : f_vFilter(self(), vFilter), m_vSetKeys(self(), vSetKeys, /* mutable */ true), m_fConverted(false) { } // ----- EntryFilter interface ---------------------------------------------- bool InKeySetFilter::evaluateEntry(Map::Entry::View vEntry) const { if (!m_vSetKeys->contains(vEntry->getKey())) { return false; } return InvocableMapHelper::evaluateEntry(getFilter(), vEntry); } // ----- Filter interface --------------------------------------------------- bool InKeySetFilter::evaluate(Object::View /* v */) const { COH_THROW (UnsupportedOperationException::create( "InKeySetFilter::evaluate")); } // ----- IndexAwareFilter interface ----------------------------------------- size32_t InKeySetFilter::calculateEffectiveness(Map::View vMapIndexes, Set::View vSetKeys) const { Filter::View vFilter = f_vFilter; if (m_vSetKeys->size() < vSetKeys->size()) { vSetKeys = m_vSetKeys; } return instanceof<IndexAwareFilter::View>(vFilter) ? (cast<IndexAwareFilter::View>(vFilter))->calculateEffectiveness(vMapIndexes, vSetKeys) : vSetKeys->size()*ExtractorFilter::eval_cost; } Filter::View InKeySetFilter::applyIndex(Map::View vMapIndexes, Set::Handle hSetKeys) const { hSetKeys->retainAll(m_vSetKeys); Filter::View vFilter = f_vFilter; return instanceof<IndexAwareFilter::View>(vFilter) ? (cast<IndexAwareFilter::View>(vFilter))->applyIndex(vMapIndexes, hSetKeys) : NULL; } // ----- PortableObject interface ------------------------------------------- void InKeySetFilter::readExternal(PofReader::Handle hIn) { initialize(f_vFilter, cast<Filter::View>(hIn->readObject(0))); m_vSetKeys = cast<Set::View>(hIn->readObject(1)); } void InKeySetFilter:: writeExternal(PofWriter::Handle hOut) const { hOut->writeObject(0, getFilter()); hOut->writeObject(1, m_vSetKeys); } // ----- Object interface --------------------------------------------------- TypedHandle<const String> InKeySetFilter::toString() const { return COH_TO_STRING("InKeySetFilter(" << getFilter() << ", keys=" << m_vSetKeys << ')'); } // ----- data member accessors ---------------------------------------------- Filter::View InKeySetFilter::getFilter() const { return f_vFilter; } Set::View InKeySetFilter::getKeys() const { return m_vSetKeys; } // ----- helpers ------------------------------------------------------------ void InKeySetFilter::ensureConverted(Converter::View vConverter) const { COH_SYNCHRONIZED (this) { if (!m_fConverted) { HashSet::Handle hSetConv = HashSet::create(); for (Iterator::Handle iter = m_vSetKeys->iterator(); iter->hasNext();) { hSetConv->add(vConverter->convert(iter->next())); } m_vSetKeys = hSetConv; m_fConverted = true; } } } COH_CLOSE_NAMESPACE3
3,914
1,238
#include <bits/stdc++.h> #define rep(i, n) for (int i = 0; i < (n); ++i) using namespace std; using ll = long long; using P = pair<int, int>; /* next combination */ int next_combination(int sub) { int x = sub & -sub, y = sub + x; return (((sub & ~y) / x) >> 1) | y; } int main() { int n = 5; // {0, 1, 2, 3, 4} ใฎ้ƒจๅˆ†้›†ๅˆใ‚’่€ƒใˆใ‚‹ int k = 3; int bit = (1 << k) - 1; // bit = {0, 1, 2} for (; bit < (1 << n); bit = next_combination(bit)) { /* ใ“ใ“ใซๅ‡ฆ็†ใ‚’ๆ›ธใ */ /* ใใกใ‚“ใจใงใใฆใ„ใ‚‹ใ“ใจใ‚’็ขบ่ชใ—ใฆใฟใ‚‹ */ // bit ใฎ่กจใ™้›†ๅˆใ‚’ๆฑ‚ใ‚ใ‚‹ vector<int> s; rep(i, n) { if (bit & (1 << i)) { // i ใŒ bit ใซๅ…ฅใ‚‹ใ‹ใฉใ†ใ‹ s.push_back(i); } } // bit ใฎ่กจใ™้›†ๅˆใฎๅ‡บๅŠ› cout << bit << ": {"; rep(i, s.size()) { cout << s[i] << " "; } cout << "}" << endl; } }
760
391
#pragma once #include <components/cursor/cursor.hpp> #include <components/session/session.hpp> #include <boost/smart_ptr/intrusive_ptr.hpp> #include <boost/smart_ptr/intrusive_ref_counter.hpp> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <pybind11/stl_bind.h> #include "forward.hpp" namespace py = pybind11; class PYBIND11_EXPORT wrapper_cursor final : public boost::intrusive_ref_counter<wrapper_cursor> { public: using type = components::cursor::cursor_t; using pointer = type*; wrapper_cursor(components::session::session_id_t session, pointer cursor); void close(); bool has_next(); wrapper_cursor &next(); wrapper_cursor &iter(); std::size_t size(); py::object get(py::object key); std::string print(); wrapper_cursor &sort(py::object sorter, py::object order); //paginate(); //_order(); private: std::atomic_bool close_; duck_charmer::session_id_t session_; pointer ptr_; actor_zeta::address_t dispatcher_; py::object get_(const std::string &key) const; py::object get_(std::size_t index) const; }; using wrapper_cursor_ptr = boost::intrusive_ptr<wrapper_cursor>;
1,181
411
#include <stdio.h> #include <memory.h> #include <assert.h> #include <stdlib.h> #include "halide_benchmark.h" #include "pipeline_raw_linear_ro_basic_interleaved.h" #include "pipeline_raw_linear_ro_fold_interleaved.h" #include "pipeline_raw_linear_ro_async_interleaved.h" #include "pipeline_raw_linear_ro_split_interleaved.h" #include "pipeline_raw_linear_ro_split_fold_interleaved.h" #include "HalideRuntimeHexagonDma.h" #include "HalideBuffer.h" int main(int argc, char **argv) { int ret = 0; if (argc < 4) { printf("Usage: %s width height func {basic, fold, async, split, split_fold} \n", argv[0]); return ret; } const int width = atoi(argv[1]); const int height = atoi(argv[2]); const char *str = argv[3]; // Fill the input buffer with random test data. This is just a plain old memory buffer const int buf_size = width * height * 4; uint8_t *data_in = (uint8_t *)malloc(buf_size); // Creating the Input Data so that we can catch if there are any Errors in DMA for (int i = 0; i < buf_size; i++) { data_in[i] = ((uint8_t)rand()) >> 1; } // Setup Halide input buffer with the test buffer Halide::Runtime::Buffer<uint8_t> input(nullptr, width, height, 4); input = input.make_interleaved(width, height, 4); // DMA_step 1: Assign buffer to DMA interface input.device_wrap_native(halide_hexagon_dma_device_interface(), reinterpret_cast<uint64_t>(data_in)); input.set_device_dirty(); // DMA_step 2: Allocate a DMA engine void *dma_engine = nullptr; halide_hexagon_dma_allocate_engine(nullptr, &dma_engine); // DMA_step 3: Associate buffer to DMA engine, and prepare for copying to host (DMA read) halide_hexagon_dma_prepare_for_copy_to_host(nullptr, input, dma_engine, false, halide_hexagon_fmt_RawData); // Setup Halide output buffer Halide::Runtime::Buffer<uint8_t> output(width, height, 4); output = output.make_interleaved(width, height, 4); if (!strcmp(str,"basic")) { printf("Basic pipeline\n"); ret = pipeline_raw_linear_ro_basic_interleaved(input, output); } else if (!strcmp(str,"fold")) { printf("Fold pipeline\n"); ret = pipeline_raw_linear_ro_fold_interleaved(input, output); } else if (!strcmp(str,"async")) { printf("Async pipeline\n"); ret = pipeline_raw_linear_ro_async_interleaved(input, output); } else if (!strcmp(str,"split")) { printf("Split pipeline\n"); ret = pipeline_raw_linear_ro_split_interleaved(input, output); } else if (!strcmp(str,"split_fold")) { printf("Split Fold pipeline\n"); ret = pipeline_raw_linear_ro_split_fold_interleaved(input, output); } else { printf("Incorrect input Correct options: basic, fold, async, split, split_fold\n"); ret = -1; } if (ret != 0) { printf("pipeline failed! %d\n", ret); } else { // verify result by comparing to expected values for (int y=0; y < height; y++) { for (int x=0; x < width; x++) { for (int z=0; z < 4; z++) { uint8_t correct = data_in[x*4 + z + y*width*4] * 2; if (correct != output(x, y, z)) { static int cnt = 0; printf("Mismatch at x=%d y=%d z=%d: %d != %d\n", x, y, z, correct, output(x, y, z)); if (++cnt > 20) abort(); } } } } printf("Success!\n"); } // DMA_step 4: Buffer is processed, disassociate buffer from DMA engine // Optional goto DMA_step 0 for processing more buffers halide_hexagon_dma_unprepare(nullptr, input); // DMA_step 5: Processing is completed and ready to exit, deallocate the DMA engine halide_hexagon_dma_deallocate_engine(nullptr, dma_engine); free(data_in); return ret; }
3,942
1,360
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ //--------------------------------------------------------------------------- // @filename: // CGPOptimizer.cpp // // @doc: // Entry point to GP optimizer // // @test: // // //--------------------------------------------------------------------------- #include "gpopt/CGPOptimizer.h" #include "gpopt/utils/COptTasks.h" // the following headers are needed to reference optimizer library initializers #include "naucrates/init.h" #include "gpopt/init.h" #include "gpos/_api.h" //--------------------------------------------------------------------------- // @function: // CGPOptimizer::TouchLibraryInitializers // // @doc: // Touch library initializers to enforce linker to include them // //--------------------------------------------------------------------------- void CGPOptimizer::TouchLibraryInitializers() { void (*gpos)() = gpos_init; void (*dxl)() = gpdxl_init; void (*opt)() = gpopt_init; } //--------------------------------------------------------------------------- // @function: // CGPOptimizer::PlstmtOptimize // // @doc: // Optimize given query using GP optimizer // //--------------------------------------------------------------------------- PlannedStmt * CGPOptimizer::PplstmtOptimize ( Query *pquery, bool *pfUnexpectedFailure // output : set to true if optimizer unexpectedly failed to produce plan ) { return COptTasks::PplstmtOptimize(pquery, pfUnexpectedFailure); } //--------------------------------------------------------------------------- // @function: // CGPOptimizer::SzDXL // // @doc: // Serialize planned statement into DXL // //--------------------------------------------------------------------------- char * CGPOptimizer::SzDXLPlan ( Query *pquery ) { return COptTasks::SzOptimize(pquery); } //--------------------------------------------------------------------------- // @function: // PplstmtOptimize // // @doc: // Expose GP optimizer API to C files // //--------------------------------------------------------------------------- extern "C" { PlannedStmt *PplstmtOptimize ( Query *pquery, bool *pfUnexpectedFailure ) { return CGPOptimizer::PplstmtOptimize(pquery, pfUnexpectedFailure); } } //--------------------------------------------------------------------------- // @function: // SzDXLPlan // // @doc: // Serialize planned statement to DXL // //--------------------------------------------------------------------------- extern "C" { char *SzDXLPlan ( Query *pquery ) { return CGPOptimizer::SzDXLPlan(pquery); } } // EOF
3,321
991
/*********************************************************\ * File: Application.cpp * \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include "Application.h" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] using namespace PLCore; //[-------------------------------------------------------] //[ Public functions ] //[-------------------------------------------------------] /** * @brief * Constructor */ Application::Application() : GuiApplication() { // Set application title SetTitle("<fill me>"); } /** * @brief * Destructor */ Application::~Application() { }
974
192
#include "stdafx.h" VbHostedCompiler::VbHostedCompiler(gcroot<System::Collections::Generic::IList<System::Reflection::Assembly ^>^> referenceAssemblies) : m_fInit(false), m_referenceAssemblies(gcnew System::Collections::Generic::List<System::Reflection::Assembly ^>(referenceAssemblies)), m_ErrorTable() { } VbHostedCompiler::~VbHostedCompiler() { if(m_spVbCompilerProject) { m_spVbCompilerProject->Disconnect(); } if (m_spVbExternalCompilerProject) { m_spVbExternalCompilerProject->Disconnect(); } } STDMETHODIMP VbHostedCompiler::InitCompiler() { HRESULT hr = S_OK; if (!m_fInit) { ASSERT(!m_spVbCompiler, "[VbHostedCompiler::InitCompiler] 'm_spVbCompiler' member is not NULL"); ASSERT(!m_spVbCompilerHost, "[VbHostedCompiler::InitCompiler] 'm_spVbCompilerHost' member is not NULL"); ASSERT(!m_spVbCompilerProject, "[VbHostedCompiler::InitCompiler] 'm_spVbCompilerProject' member is not NULL"); ASSERT(!m_pCompilerProject, "[VbHostedCompiler::InitCompiler] 'm_pCompilerProject' member is not NULL"); IfFailGo(VbCompilerHost::Create(&m_spVbCompilerHost)); IfFailGo(GetCompiler()); IfFailGo(SetupCompilerProject(&m_ErrorTable)); IfFailGo(CreateExternalCompilerProject()); m_fInit = true; } Error: if (FAILED(hr)) { m_spVbCompilerHost = NULL; m_spVbCompiler = NULL; } return hr; } STDMETHODIMP VbHostedCompiler::CompileExpression ( BSTR Expression, VbContext* pContext, gcroot<System::Type ^> TargetType, VbParsed *pParsed ) { // Asserts are NOT necessary since the Verify* macros all invoke VSFAIL which is a VSASSERT wrapper. VerifyInPtr(Expression, "[VbHostedCompiler::CompileExpression] 'Expression' parameter is null"); VerifyParamCond(SysStringLen(Expression) > 0, E_INVALIDARG, "[VbHostedCompiler::CompileExpression] 'Expression' parameter is zero length string"); VerifyInPtr(pContext, "[VbHostedCompiler::CompileExpression] 'pContext' parameter is null"); VerifyInPtr(pParsed, "[VbHostedCompiler::CompileExpression] 'pParsed' parameter is null"); VB_ENTRY(); IfFailGo(InitCompiler()); pParsed->SetSharedErrorTable(&m_ErrorTable); if (!m_ErrorTable.HasErrors()) { VBHostedSession session(Expression, m_spVbCompiler, m_spVbCompilerHost, m_spVbCompilerProject, m_pExternalCompilerProject, pContext, TargetType); pParsed->GetErrorTable()->Init(m_pCompiler, m_pCompilerProject, NULL); IfFailGo(session.CompileExpression(pParsed)); } g_pvbNorlsManager->GetPageHeap().ShrinkUnusedResources(); VB_EXIT_LABEL(); } STDMETHODIMP VbHostedCompiler::CompileStatements ( BSTR Statements, VbContext* pContext, VbParsed *pParsed ) { // Asserts are NOT necessary since the Verify* macros all invoke VSFAIL which is a VSASSERT wrapper. VerifyInPtr(Statements, "[VbHostedCompiler::CompileStatements] 'Statements' parameter is null"); VerifyParamCond(SysStringLen(Statements) > 0, E_INVALIDARG, "[VbHostedCompiler::CompileStatements] 'Statements' parameter is zero length string"); VerifyInPtr(pContext, "[VbHostedCompiler::CompileStatements] 'pContext' parameter is null"); VerifyInPtr(pParsed, "[VbHostedCompiler::CompileStatements] 'pParsed' parameter is null"); VB_ENTRY(); IfFailGo(InitCompiler()); pParsed->SetSharedErrorTable(&m_ErrorTable); if (!m_ErrorTable.HasErrors()) { VBHostedSession session(Statements, m_spVbCompiler, m_spVbCompilerHost, m_spVbCompilerProject, m_pExternalCompilerProject, pContext, nullptr); pParsed->GetErrorTable()->Init(m_pCompiler, m_pCompilerProject, NULL); IfFailGo(session.CompileStatements(pParsed)); } VB_EXIT_LABEL(); } STDMETHODIMP VbHostedCompiler::GetCompiler() { HRESULT hr = S_OK; CompilerHost *pCompilerHost = NULL; // Don't need to manage lifetime of pCompilerHost as it is controlled by pCompiler. // Create the compiler, this will have references to the default libraries IfFailGo(VBCreateBasicCompiler(false, DelayLoadUICallback, m_spVbCompilerHost, &m_spVbCompiler)); m_pCompiler = (Compiler *)((IVbCompiler*)m_spVbCompiler); //"Compile" the mscorlib project if(m_pCompiler->FindCompilerHost(m_spVbCompilerHost, &pCompilerHost) && pCompilerHost && pCompilerHost->GetComPlusProject()) { IfTrueGo(pCompilerHost->GetComPlusProject()->Compile(), E_FAIL); } else { ASSERT(pCompilerHost, "Could not get Compiler Host"); ASSERT(!pCompilerHost, "Could not get mscorlib's project"); IfFailGo(E_FAIL); } Error: return hr; } STDMETHODIMP VbHostedCompiler::SetupCompilerProject(ErrorTable *pErrorTable) { // Asserts are NOT necessary since the Verify* macros all invoke VSFAIL which is a VSASSERT wrapper. VerifyInPtr(pErrorTable, "[VBHostedSession::SetupCompilerProject] 'pErrorTable' parameter is null"); ASSERT(m_spVbCompilerHost, "[VBHostedSession::SetupCompilerProject] 'm_spVbCompilerHost' is null"); ASSERT(m_spVbCompiler, "[VBHostedSession::SetupCompilerProject] 'm_spVbCompiler' is null"); HRESULT hr = S_OK; IfFailGo(CreateCompilerProject()); IfFailGo(InitializeCompilerProject(pErrorTable)); // Ensure that all the projects (in particular mscorlib and the VB runtime // have been compiled at least to CS_Bound). // IfFailGo(m_pCompiler->CompileToBound( m_pCompilerProject->GetCompilerHost(), NULL, // ULONG *pcWarnings NULL, // ULONG *pcErrors, NULL // VbError **ppErrors )); Error: return hr; } STDMETHODIMP VbHostedCompiler::CreateCompilerProject() { ASSERT(m_spVbCompilerHost, "[VBHostedSession::CreateCompilerProject] 'm_spVbCompilerHost' is null"); ASSERT(m_spVbCompiler, "[VBHostedSession::CreateCompilerProject] 'm_spVbCompiler' is null"); ASSERT(!m_spVbCompilerProject, "[VBHostedSession::CreateCompilerProject] 'm_spVbCompilerProject' is not null"); ASSERT(!m_pCompilerProject, "[VBHostedSession::CreateCompilerProject] 'm_pCompilerProject' is not null"); HRESULT hr = S_OK; // Add System.Core.dll as it is required for DLR tree conversion // { // Register the compiler host to get access to the underlying "CompierHost" // object before the project is created so that System.Core can also be // added to the list of standard libraries and thus found using the // FX search paths and added as a reference to the project when it // is created. // IfFailGo(m_pCompiler->RegisterVbCompilerHost(m_spVbCompilerHost)); CompilerHost *CompilerHost = NULL; IfFalseGo(m_pCompiler->FindCompilerHost(m_spVbCompilerHost, &CompilerHost), E_UNEXPECTED); ThrowIfNull(CompilerHost); DynamicArray<STRING *> *StdLibs = CompilerHost->GetStandardLibraries(); ThrowIfNull(StdLibs); STRING **StdLibsArray = StdLibs->Array(); // Add to the list only if not already present. STRING *SystemCoreDLL = m_pCompiler->AddString(L"System.Core.dll"); for(unsigned i = 0; i < StdLibs->Count(); i++) { if (StringPool::IsEqual(StdLibsArray[i] , SystemCoreDLL)) break; } if (i == StdLibs->Count()) { StdLibs->AddElement(SystemCoreDLL); } } // Create our default project. IfFailGo(m_spVbCompiler->CreateProject ( L"vbhost", m_spVbCompiler, NULL, m_spVbCompilerHost, &m_spVbCompilerProject )); m_pCompilerProject = (CompilerProject*)m_spVbCompilerProject.p; Error: return hr; } STDMETHODIMP VbHostedCompiler::InitializeCompilerProject(ErrorTable *pErrorTable) { // Asserts are NOT necessary since the Verify* macros all invoke VSFAIL which is a VSASSERT wrapper. VerifyInPtr(pErrorTable, "[VBHostedSession::InitializeCompilerProject] 'pErrorTable' parameter is null"); ASSERT(m_pCompiler, "[VBHostedSession::InitializeCompilerProject] 'm_pCompiler' is null"); ASSERT(m_spVbCompilerProject, "[VBHostedSession::InitializeCompilerProject] 'm_spVbCompilerProject' is null"); HRESULT hr = S_OK; // Must initialize errortable before calling SetAssemblyRefs so that failures encountered when processing // the assembly references are captured correctly. pErrorTable->Init(m_pCompiler, m_pCompilerProject, NULL); m_pCompilerProject->AddStandardLibraries(); IfFailGo(VbContext::SetAssemblyRefs(m_referenceAssemblies, m_pCompiler, m_spVbCompilerProject, pErrorTable)); //Need to set the options to something so that the project will be compiled to bound. IfFailGo(VbContext::SetDefaultOptions(m_spVbCompilerProject)); Error: return hr; } STDMETHODIMP VbHostedCompiler::CreateExternalCompilerProject() { ASSERT(m_spVbCompilerHost, "[VBHostedSession::CreateExternalCompilerProject] 'm_spVbCompilerHost' is null"); ASSERT(m_spVbCompiler, "[VBHostedSession::CreateExternalCompilerProject] 'm_spVbCompiler' is null"); ASSERT(!m_spVbExternalCompilerProject, "[VBHostedSession::CreateExternalCompilerProject] 'm_spVbExternalCompilerProject' is not null"); ASSERT(!m_pExternalCompilerProject, "[VBHostedSession::CreateExternalCompilerProject] 'm_pExternalCompilerProject' is not null"); HRESULT hr = S_OK; //Create the Type Scope Project IfFailGo(m_pCompilerProject->AddTypeScopeReference(&m_pExternalCompilerProject)); m_spVbExternalCompilerProject = m_pExternalCompilerProject; Error: return hr; }
9,752
3,151
// Copyright 2019-2021 Lawrence Livermore National Security, LLC and other YGM // Project Developers. See the top-level COPYRIGHT file for details. // // SPDX-License-Identifier: MIT #undef NDEBUG #include <ygm/comm.hpp> #include <ygm/detail/ygm_ptr.hpp> int main(int argc, char** argv) { // Create comm for very small messages ygm::comm world(&argc, &argv, 8); // Test Rank 0 large message to all ranks { size_t large_msg_size = 1024; size_t counter{}; ygm::ygm_ptr<size_t> pcounter(&counter); if (world.rank() == 0) { std::vector<size_t> large_msg(large_msg_size); for (int dest = 0; dest < world.size(); ++dest) { // Count elements in large message's vector world.async( dest, [](auto pcomm, int from, auto pcounter, const std::vector<size_t>& vec) { for (size_t i = 0; i < vec.size(); ++i) { (*pcounter)++; } }, pcounter, large_msg); } } world.barrier(); ASSERT_RELEASE(counter == large_msg_size); } return 0; }
1,072
385
#include "../hpp/benchmark_nod.hpp" NOINLINE(void Nod::initialize()) { // NOOP } NOINLINE(void Nod::validate_assert(std::size_t N)) { return Benchmark<Signal, Nod>::validation_assert(N); } NOINLINE(double Nod::construction(std::size_t N, std::size_t limit)) { return Benchmark<Signal, Nod>::construction(N, limit); } NOINLINE(double Nod::destruction(std::size_t N, std::size_t limit)) { return Benchmark<Signal, Nod>::destruction(N, limit); } NOINLINE(double Nod::connection(std::size_t N, std::size_t limit)) { return Benchmark<Signal, Nod>::connection(N, limit); } NOINLINE(double Nod::disconnect(std::size_t N, std::size_t limit)) { return Benchmark<Signal, Nod>::disconnect(N, limit); } NOINLINE(double Nod::reconnect(std::size_t N, std::size_t limit)) { return Benchmark<Signal, Nod>::reconnect(N, limit); } NOINLINE(double Nod::emission(std::size_t N, std::size_t limit)) { return Benchmark<Signal, Nod>::emission(N, limit); } NOINLINE(double Nod::combined(std::size_t N, std::size_t limit)) { return Benchmark<Signal, Nod>::combined(N, limit); } NOINLINE(double Nod::threaded(std::size_t N, std::size_t limit)) { return Benchmark<Signal, Nod>::threaded(N, limit); }
1,218
470
#pragma once #include<math/Math3d.hpp> #include<render/Filter.hpp> #include<render/Viewport.hpp> namespace tutorial::graphics { class ScreenRayTracer { private: ScreenRayTracer() = delete; public: static void draw(Viewport& viewport, ShaderVersion shader); }; }
277
108
// Copyright 2008 by BBN Technologies Corp. // All Rights Reserved. #include "MIWord.h" using namespace std; const Vocabulary* MIWord::pVoc = 0; MIWord::MIWord(int index) { _index = index; } MIWord& MIWord::operator=(const MIWord& w) { MIBaseElement::operator=(w); _index = w._index; return *this; } bool MIWord::operator==(const MIWord& w) const { return _index == w._index; } bool MIWord::operator!=(const MIWord& w) const { return _index != w._index; } bool MIWord::operator<(const MIWord &w) const { return ((getTotalCount() < w.getTotalCount()) || ((getTotalCount() == w.getTotalCount()) && (_index < w._index))); } bool MIWord::operator>(const MIWord& w) const { return ((getTotalCount() > w.getTotalCount()) || ((getTotalCount() == w.getTotalCount()) && (_index > w._index))); } bool MIWord::operator<=(const MIWord& w) const { return ((getTotalCount()<w.getTotalCount()) || ((getTotalCount() == w.getTotalCount()) && (_index <= w._index))); } bool MIWord::operator>=(const MIWord& w) const { return ((getTotalCount() > w.getTotalCount()) || ((getTotalCount() == w.getTotalCount()) && (_index >= w._index))); } void MIWord::setIndex(int index) { _index = index; } int MIWord::index() const { return _index; } const wstring& MIWord::name() const { return pVoc->get(_index); } void MIWord::useVoc(const Vocabulary &voc) { pVoc = &voc; }
1,523
552
#include <iostream> #include <string> using namespace std; class Track { public: float lengthInSeconds; string trackName; Track () { lengthInSeconds = 0.0f; trackName = "not set"; } }; int main() { Track track; cout << "Track Name = " << track.trackName << endl; cout << "Track Length = " << track.lengthInSeconds << endl; return 0; }
392
135