text
string
size
int64
token_count
int64
/* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Product name: redemption, a FLOSS RDP proxy Copyright (C) Wallix 2014 Author(s): Christophe Grosjean bunch of functions used to serialized binary data */ #pragma once #include <array> #include <vector> inline std::array<uint8_t, 2> out_uint16_le(unsigned int v) { return {uint8_t(v), uint8_t(v >> 8)}; } inline std::array<uint8_t, 1> out_uint8(unsigned int v) { return {uint8_t(v)}; } inline std::array<uint8_t, 4> out_uint32_le(unsigned int v) { return {uint8_t(v), uint8_t(v >> 8), uint8_t(v >> 16), uint8_t(v >> 24)}; } inline void push_back_array(std::vector<uint8_t> & v, u8_array_view a) { v.insert(std::end(v), a.data(), a.data() + a.size()); }
1,383
499
#include <bits/stdc++.h> using namespace std; string ltrim(const string &); string rtrim(const string &); vector<string> split(const string &); /* * Complete the 'dynamicArray' function below. * * The function is expected to return an INTEGER_ARRAY. * The function accepts following parameters: * 1. INTEGER n * 2. 2D_INTEGER_ARRAY queries */ vector<int> dynamicArray(int n, vector<vector<int>> queries) { vector<vector<int>> seqlist(n); vector<int> sol; int lastAnswer=0, seq, size; for(vector<int> i:queries) { seq = (i[1]^lastAnswer)%n; if(i[0]==1) { seqlist[seq].push_back(i[2]); } else { size=seqlist[seq].size(); lastAnswer=seqlist[seq][i[2]%size]; sol.push_back(lastAnswer); } } return sol; } int main() { ofstream fout(getenv("OUTPUT_PATH")); string first_multiple_input_temp; getline(cin, first_multiple_input_temp); vector<string> first_multiple_input = split(rtrim(first_multiple_input_temp)); int n = stoi(first_multiple_input[0]); int q = stoi(first_multiple_input[1]); vector<vector<int>> queries(q); for (int i = 0; i < q; i++) { queries[i].resize(3); string queries_row_temp_temp; getline(cin, queries_row_temp_temp); vector<string> queries_row_temp = split(rtrim(queries_row_temp_temp)); for (int j = 0; j < 3; j++) { int queries_row_item = stoi(queries_row_temp[j]); queries[i][j] = queries_row_item; } } vector<int> result = dynamicArray(n, queries); for (int i = 0; i < result.size(); i++) { fout << result[i]; if (i != result.size() - 1) { fout << "\n"; } } fout << "\n"; fout.close(); return 0; } string ltrim(const string &str) { string s(str); s.erase( s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace))) ); return s; } string rtrim(const string &str) { string s(str); s.erase( find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end() ); return s; } vector<string> split(const string &str) { vector<string> tokens; string::size_type start = 0; string::size_type end = 0; while ((end = str.find(" ", start)) != string::npos) { tokens.push_back(str.substr(start, end - start)); start = end + 1; } tokens.push_back(str.substr(start)); return tokens; }
2,551
929
// // _COREREGCLASSINFOWIN_CPP_ // // Copyright (C) 2017-2020 Tactical Computing Laboratories, LLC // All Rights Reserved // contact@tactcomplabs.com // // See LICENSE in the top level directory for licensing details // #include "CoreGenPortal/PortalCore/CoreRegClassInfoWin.h" // Event Table wxBEGIN_EVENT_TABLE(CoreRegClassInfoWin, wxDialog) EVT_BUTTON(wxID_OK, CoreRegClassInfoWin::OnPressOk) EVT_BUTTON(wxID_SAVE, CoreRegClassInfoWin::OnSave) wxEND_EVENT_TABLE() CoreRegClassInfoWin::CoreRegClassInfoWin( wxWindow* parent, wxWindowID id, const wxString& title, CoreGenRegClass *RegClass ) : wxDialog( parent, id, title, wxDefaultPosition, wxSize(500,320), wxDEFAULT_DIALOG_STYLE|wxVSCROLL ){ RegClassNode = RegClass; // init the internals this->SetLayoutAdaptationMode(wxDIALOG_ADAPTATION_MODE_ENABLED); this->SetSizeHints( wxDefaultSize, wxDefaultSize ); // create the outer box sizer OuterSizer = new wxBoxSizer( wxVERTICAL ); // create the scrolled window Wnd = new wxScrolledWindow(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, wxT("Scroll")); // create the inner sizer InnerSizer = new wxBoxSizer( wxVERTICAL ); // add all the interior data // -- reg class RegClassNameSizer = new wxBoxSizer( wxHORIZONTAL ); RegClassNameText = new wxStaticText( Wnd, 2, wxT("Register Class Name"), wxDefaultPosition, wxSize(160, -1), 0 ); RegClassNameText->Wrap(-1); RegClassNameSizer->Add( RegClassNameText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 0 ); RegClassNameCtrl = new wxTextCtrl( Wnd, 0, RegClass ? wxString(RegClass->GetName()) : "", wxDefaultPosition, wxSize(320,25), 0, wxDefaultValidator, wxT("Reg Class Name") ); RegClassNameSizer->Add( RegClassNameCtrl, 0, wxALL, 0 ); InnerSizer->Add( RegClassNameSizer, 0, wxALIGN_CENTER|wxALL, 5 ); // -- Write ports ReadPortsSizer = new wxBoxSizer( wxHORIZONTAL ); ReadPortsText = new wxStaticText( Wnd, 4, wxT("Read Ports"), wxDefaultPosition, wxSize(160, -1), 0 ); ReadPortsText->Wrap(-1); ReadPortsSizer->Add( ReadPortsText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 0 ); ReadPortsCtrl = new wxTextCtrl( Wnd, 5, RegClass ? wxString(std::to_string(RegClass->GetReadPorts())) : "", wxDefaultPosition, wxSize(320,25), 0, wxDefaultValidator, wxT("Read Ports") ); ReadPortsSizer->Add( ReadPortsCtrl, 0, wxALL, 0 ); InnerSizer->Add( ReadPortsSizer, 0, wxALIGN_CENTER|wxALL, 5 ); // -- write ports WritePortsSizer = new wxBoxSizer( wxHORIZONTAL ); WritePortsText = new wxStaticText( Wnd, 6, wxT("Write Ports"), wxDefaultPosition, wxSize(160, -1), 0 ); WritePortsText->Wrap(-1); WritePortsSizer->Add( WritePortsText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 0 ); WritePortsCtrl = new wxTextCtrl( Wnd, 7, RegClass ? wxString(std::to_string(RegClass->GetWritePorts())) : "", wxDefaultPosition, wxSize(320,25), 0, wxDefaultValidator, wxT("Write Ports") ); WritePortsSizer->Add( WritePortsCtrl, 0, wxALL, 0 ); InnerSizer->Add( WritePortsSizer, 0, wxALIGN_CENTER|wxALL, 5 ); //-- registers RegNameSizer = new wxBoxSizer( wxHORIZONTAL ); RegNameText = new wxStaticText( Wnd, 3, wxT("Registers"), wxDefaultPosition, wxSize(160,-1), 0 ); RegNameText->Wrap(-1); RegNameSizer->Add( RegNameText, 0, wxALIGN_CENTER|wxALL, 0 ); RegNameCtrl = new wxTextCtrl( Wnd, 1, wxEmptyString, wxDefaultPosition, wxSize(320,100), wxTE_MULTILINE|wxHSCROLL, wxDefaultValidator, wxT("registers") ); if(RegClass){ for( unsigned i=0; i<RegClass->GetNumReg(); i++ ){ RegNameCtrl->AppendText(wxString(RegClass->GetReg(i)->GetName())+wxT("\n") ); } } RegNameSizer->Add( RegNameCtrl, 0, wxALL, 0 ); InnerSizer->Add( RegNameSizer, 0, wxALIGN_CENTER|wxALL, 5 ); // add the static line FinalStaticLine = new wxStaticLine( Wnd, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); InnerSizer->Add( FinalStaticLine, 1, wxEXPAND | wxALL, 5 ); // setup all the buttons m_socbuttonsizer = new wxStdDialogButtonSizer(); m_userOK = new wxButton( Wnd, wxID_CANCEL ); m_userSAVE = new wxButton( Wnd, wxID_SAVE); m_socbuttonsizer->SetAffirmativeButton( m_userOK ); m_socbuttonsizer->SetCancelButton( m_userSAVE ); m_socbuttonsizer->Realize(); InnerSizer->Add( m_socbuttonsizer, 0, wxALL, 5 ); Wnd->SetScrollbars(20,20,50,50); Wnd->SetSizer( InnerSizer ); Wnd->SetAutoLayout(true); Wnd->Layout(); // draw the dialog box until we get more info OuterSizer->Add(Wnd, 1, wxEXPAND | wxALL, 5 ); this->SetSizer( OuterSizer ); this->SetAutoLayout( true ); this->Layout(); } void CoreRegClassInfoWin::OnPressOk(wxCommandEvent& ok){ this->EndModal(wxID_OK); } void CoreRegClassInfoWin::OnSave(wxCommandEvent& save){ PortalMainFrame *PMF = (PortalMainFrame*)this->GetParent(); if(PMF->OnSave(this, this->RegClassNode, CGRegC)) this->EndModal(wxID_SAVE); } CoreRegClassInfoWin::~CoreRegClassInfoWin(){ } // EOF
6,836
2,120
// Copyright (c) 2020, devgo.club // All rights reserved. #include <stdint.h> #include <stdlib.h> #include <iostream> int32_t get_max(int32_t x = 101, int32_t y = 102, int32_t z = 103); int32_t get_max(int32_t x, int32_t y); int main(int argc, char **argv) { int32_t a = 1; int32_t b = 2; int32_t c = 3; std::cout << "get_max: " << get_max(a, b, c) << std::endl; // std::cout << "get_max: " << get_max(a, b) << std::endl; // error: call to // 'get_max' is ambiguous return EXIT_SUCCESS; } int32_t get_max(int32_t x, int32_t y, int32_t z) { int32_t result = x; if (y > result) { result = y; } if (z > result) { result = z; } return result; } int32_t get_max(int32_t x, int32_t y) { int32_t result = x; if (y > result) { result = y; } return result; }
809
412
#include <bits/stdc++.h> #define watch(x) std::cout << (#x) << " is " << (x) << std::endl using LL = long long; int main() { //freopen("in", "r", stdin); std::cin.tie(nullptr)->sync_with_stdio(false); int cas = 1; std::cin >> cas; while (cas--) { LL n; std::cin >> n; if (n & 1) { std::cout << -1 << std::endl; continue; } n /= 2; std::vector<int> a; while (n) { --n; int x = 1; while (n >> x) ++x; --x; n -= (1LL << x); a.emplace_back(1); for (int i = 1; i < x; ++i) a.emplace_back(0); } std::cout << a.size() << std::endl; for (auto x : a) std::cout << x << " "; std::cout << std::endl; } return 0; }
660
340
// PUBG FULL SDK - Generated By Respecter (5.3.4.11 [06/03/2019]) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "PUBG_Niagara_parameters.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function Niagara.NiagaraComponent.SetRenderingEnabled // (Final, Native) // Parameters: // bool bInRenderingEnabled (Parm, ZeroConstructor, IsPlainOldData) void UNiagaraComponent::SetRenderingEnabled(bool bInRenderingEnabled) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetRenderingEnabled"); UNiagaraComponent_SetRenderingEnabled_Params params; params.bInRenderingEnabled = bInRenderingEnabled; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.SetNiagaraVariableVec4 // (Final, Native) // Parameters: // class FString* InVariableName (Parm, ZeroConstructor) // struct FVector4* InValue (ConstParm, Parm, OutParm, ReferenceParm, IsPlainOldData) void UNiagaraComponent::SetNiagaraVariableVec4(class FString* InVariableName, struct FVector4* InValue) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetNiagaraVariableVec4"); UNiagaraComponent_SetNiagaraVariableVec4_Params params; params.InVariableName = InVariableName; params.InValue = InValue; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.SetNiagaraVariableVec3 // (Final, Native) // Parameters: // class FString* InVariableName (Parm, ZeroConstructor) // struct FVector* InValue (Parm, IsPlainOldData) void UNiagaraComponent::SetNiagaraVariableVec3(class FString* InVariableName, struct FVector* InValue) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetNiagaraVariableVec3"); UNiagaraComponent_SetNiagaraVariableVec3_Params params; params.InVariableName = InVariableName; params.InValue = InValue; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.SetNiagaraVariableVec2 // (Final, Native) // Parameters: // class FString* InVariableName (Parm, ZeroConstructor) // struct FVector2D* InValue (Parm, IsPlainOldData) void UNiagaraComponent::SetNiagaraVariableVec2(class FString* InVariableName, struct FVector2D* InValue) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetNiagaraVariableVec2"); UNiagaraComponent_SetNiagaraVariableVec2_Params params; params.InVariableName = InVariableName; params.InValue = InValue; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.SetNiagaraVariableFloat // (Final, Native) // Parameters: // class FString* InVariableName (Parm, ZeroConstructor) // float* InValue (Parm, ZeroConstructor, IsPlainOldData) void UNiagaraComponent::SetNiagaraVariableFloat(class FString* InVariableName, float* InValue) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetNiagaraVariableFloat"); UNiagaraComponent_SetNiagaraVariableFloat_Params params; params.InVariableName = InVariableName; params.InValue = InValue; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.SetNiagaraVariableBool // (Final, Native) // Parameters: // class FString* InVariableName (Parm, ZeroConstructor) // bool* InValue (Parm, ZeroConstructor, IsPlainOldData) void UNiagaraComponent::SetNiagaraVariableBool(class FString* InVariableName, bool* InValue) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetNiagaraVariableBool"); UNiagaraComponent_SetNiagaraVariableBool_Params params; params.InVariableName = InVariableName; params.InValue = InValue; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.SetNiagaraStaticMeshDataInterfaceActor // (Final, Native) // Parameters: // class FString* InVariableName (Parm, ZeroConstructor) // class AActor** InSource (Parm, ZeroConstructor, IsPlainOldData) void UNiagaraComponent::SetNiagaraStaticMeshDataInterfaceActor(class FString* InVariableName, class AActor** InSource) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetNiagaraStaticMeshDataInterfaceActor"); UNiagaraComponent_SetNiagaraStaticMeshDataInterfaceActor_Params params; params.InVariableName = InVariableName; params.InSource = InSource; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.SetNiagaraEmitterSpawnRate // (Final, Native) // Parameters: // class FString* InEmitterName (Parm, ZeroConstructor) // float* InValue (Parm, ZeroConstructor, IsPlainOldData) void UNiagaraComponent::SetNiagaraEmitterSpawnRate(class FString* InEmitterName, float* InValue) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetNiagaraEmitterSpawnRate"); UNiagaraComponent_SetNiagaraEmitterSpawnRate_Params params; params.InEmitterName = InEmitterName; params.InValue = InValue; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.ResetEffect // (Final, Native) void UNiagaraComponent::ResetEffect() { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.ResetEffect"); UNiagaraComponent_ResetEffect_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.ReinitializeEffect // (Final, Native) void UNiagaraComponent::ReinitializeEffect() { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.ReinitializeEffect"); UNiagaraComponent_ReinitializeEffect_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
7,202
2,335
/* Copyright 2018-2019 Google 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 "vkex/QueryPool.h" #include "vkex/Device.h" #include "vkex/ToString.h" namespace vkex { // ================================================================================================= // QueryPool // ================================================================================================= CQueryPool::CQueryPool() { } CQueryPool::~CQueryPool() { } vkex::Result CQueryPool::InternalCreate( const vkex::QueryPoolCreateInfo& create_info, const VkAllocationCallbacks* p_allocator ) { // Copy create info m_create_info = create_info; // Create Vulkan sampler { // Create info m_vk_create_info = { VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO }; m_vk_create_info.queryType = m_create_info.query_type; m_vk_create_info.queryCount = m_create_info.query_count; m_vk_create_info.pipelineStatistics = m_create_info.pipeline_statistics.flags; // Create Vulkan sampler VkResult vk_result = InvalidValue<VkResult>::Value; VKEX_VULKAN_RESULT_CALL( vk_result, vkex::CreateQueryPool( *m_device, &m_vk_create_info, p_allocator, &m_vk_object) ); if (vk_result != VK_SUCCESS) { return vkex::Result(vk_result); } } return vkex::Result::Success; } vkex::Result CQueryPool::InternalDestroy(const VkAllocationCallbacks* p_allocator) { if (m_vk_object != VK_NULL_HANDLE) { vkex::DestroyQueryPool( *m_device, m_vk_object, p_allocator); m_vk_object = VK_NULL_HANDLE; } return vkex::Result::Success; } } // namespace vkex
2,161
743
/* * Copyright 2018 LedoCool. * * 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: CheckCollisions.cpp * Author: LedoCool * * Created on December 24, 2018, 8:35 PM */ #include "CheckCollisionsSystem.h" #include "engine/Etc/Rect.h" #include "engine/Etc/Vector2.h" #include "engine/Game/Camera.h" #include "engine/Ecs/Components/IncludeComponents.h" CheckCollisionsSystem::CheckCollisionsSystem() { } CheckCollisionsSystem::~ CheckCollisionsSystem() { } void CheckCollisionsSystem::Execute(Uint32 dt, std::shared_ptr<GameState>& gameState) { gameState->collidingEntitites.clear(); BuildBinaryTree(gameState); for(auto entity : gameState->map->GetEntities()) { auto position = std::dynamic_pointer_cast<Position>(entity->GetComponent(ComponentTypes::POSITION).lock()); auto velocity = std::dynamic_pointer_cast<Velocity>(entity->GetComponent(ComponentTypes::VELOCITY).lock()); auto acceleration = std::dynamic_pointer_cast<Acceleration>(entity->GetComponent(ComponentTypes::ACCELERATION).lock()); auto size = std::dynamic_pointer_cast<Size>(entity->GetComponent(ComponentTypes::SIZE).lock()); if(!acceleration) { acceleration = std::make_shared<Acceleration>(Vector2<float>(0.f, 0.f), 0.f); } if(!velocity) { velocity = std::make_shared<Velocity>(Vector2<float>(0.f, 0.f), 0.f); } if(!(position && size)) { continue; } float halfSize = size->size() / 2.f; Rect<float> boundingRect( - halfSize, halfSize, - halfSize, halfSize ); for(auto weakPossiblyCollidingEntity : gameState->collisionTree->GetObjects(boundingRect)) { auto collider = weakPossiblyCollidingEntity.lock(); if(!collider || collider == entity) { continue; } auto colliderPosition = std::dynamic_pointer_cast<Position>(collider->GetComponent(ComponentTypes::POSITION).lock()); auto colliderVelocity = std::dynamic_pointer_cast<Velocity>(collider->GetComponent(ComponentTypes::VELOCITY).lock()); auto coliderAcceleration = std::dynamic_pointer_cast<Acceleration>(collider->GetComponent(ComponentTypes::ACCELERATION).lock()); auto colliderSize = std::dynamic_pointer_cast<Size>(collider->GetComponent(ComponentTypes::SIZE).lock()); if(!coliderAcceleration) { coliderAcceleration = std::make_shared<Acceleration>(Vector2<float>(0.f, 0.f), 0.f); } if(!colliderVelocity) { colliderVelocity = std::make_shared<Velocity>(Vector2<float>(0.f, 0.f), 0.f); } if(!(colliderPosition && colliderSize)) { continue; } float colliderHalfSize = colliderSize->size() / 2.f; Rect<float> colliderBoundingRect( - colliderHalfSize, colliderHalfSize, - colliderHalfSize, colliderHalfSize ); for(Uint32 iTime = 0; iTime < dt; iTime++) { Vector2<float> entity1_position = position->coords(); entity1_position += velocity->velocity() * iTime; entity1_position += acceleration->vector() * iTime * iTime / 2.f; Vector2<float> entity2_position = colliderPosition->coords(); entity2_position += colliderVelocity->velocity() * iTime; entity2_position += coliderAcceleration->vector() * iTime * iTime / 2.f; if(boundingRect.addPosition(entity1_position.x(), entity1_position.y()).CollidesWith( colliderBoundingRect.addPosition(entity2_position.x(), entity2_position.y()))) { Vector2<float> diff = entity1_position - entity2_position; if(diff.Magnitude() <= colliderSize->size() + size->size()) { std::weak_ptr<Entity> leftEntity(entity); std::pair<std::weak_ptr<Entity>, std::weak_ptr<Entity> > collidingPair(leftEntity, weakPossiblyCollidingEntity); gameState->collidingEntitites.push_back(collidingPair); } } } } } } void CheckCollisionsSystem::BuildBinaryTree(std::shared_ptr<GameState>& gameState) { auto cameraCoordinates = gameState->camera->GetCoordinates(); auto screenSize = gameState->camera->GetScreenProportions(); Rect<float> chunk( cameraCoordinates.x() - screenSize.x(), cameraCoordinates.x() + screenSize.x(), cameraCoordinates.y() - screenSize.y(), cameraCoordinates.y() + screenSize.y() ); gameState->collisionTree = std::make_shared<TreeRoot>(); gameState->collisionTree->BuildTree(chunk, gameState->map->GetEntities()); }
5,709
1,620
/* TP 2016/2017 (Tutorijal 4, Zadatak 1) Autotestovi by Eldar Kurtic, sva pitanja, sugestije i prijave gresaka javite na mail ekurtic3@etf.unsa.ba NAPOMENA: testovi ce biti konacni TEK pred pocetak tutorijala. Zbog toga pokrenite testove za SVE zadatke na tutorijalu, da se ne bi desila situacija da neko uradi zadatak ranije i prolazi mu npr. 5/5 testova a naknadno dodano jos 2 testa koja mu padaju! */ #include <iostream> #include <limits> #include <cmath> int Cifre(long long int n, int &c_min, int &c_max){ auto pomocna(n); int brojac=0; int min(9), max(0); if(pomocna==0) { c_min=0; c_max=0; return brojac+1; } while(pomocna!=0){ int zadnja = std::fabs(pomocna % 10); if(zadnja < min) min = zadnja; if(zadnja > max) max = zadnja; brojac++; pomocna/=10; } c_min = min; c_max = max; return brojac; } int main () { int a, b; long long broj; std::cout << "Unesite broj: "; std::cin >> broj; int cifre = Cifre(broj, a, b); std::cout << "Broj " << broj << " ima " << cifre << " cifara, najveca je " << b << " a najmanja " << a << "."; return 0; }
1,186
536
// Generated by Haxe 3.4.7 #include <hxcpp.h> #ifndef INCLUDED_95f339a1d026d52c #define INCLUDED_95f339a1d026d52c #include "hxMath.h" #endif #ifndef INCLUDED_openfl_display_GraphicsDataType #include <openfl/display/GraphicsDataType.h> #endif #ifndef INCLUDED_openfl_display_GraphicsStroke #include <openfl/display/GraphicsStroke.h> #endif #ifndef INCLUDED_openfl_display_IGraphicsData #include <openfl/display/IGraphicsData.h> #endif #ifndef INCLUDED_openfl_display_IGraphicsFill #include <openfl/display/IGraphicsFill.h> #endif #ifndef INCLUDED_openfl_display_IGraphicsStroke #include <openfl/display/IGraphicsStroke.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_55614d7317440053_221_new,"openfl.display.GraphicsStroke","new",0x5684f03f,"openfl.display.GraphicsStroke.new","openfl/display/GraphicsStroke.hx",221,0x5e4870cf) namespace openfl{ namespace display{ void GraphicsStroke_obj::__construct( ::Dynamic thickness,hx::Null< bool > __o_pixelHinting, ::Dynamic __o_scaleMode, ::Dynamic __o_caps, ::Dynamic __o_joints,hx::Null< Float > __o_miterLimit,::Dynamic fill){ bool pixelHinting = __o_pixelHinting.Default(false); ::Dynamic scaleMode = __o_scaleMode.Default(2); ::Dynamic caps = __o_caps.Default(0); ::Dynamic joints = __o_joints.Default(2); Float miterLimit = __o_miterLimit.Default(3); HX_STACKFRAME(&_hx_pos_55614d7317440053_221_new) HXLINE( 223) if (hx::IsNull( thickness )) { HXLINE( 223) thickness = ::Math_obj::NaN; } HXLINE( 225) this->caps = caps; HXLINE( 226) this->fill = fill; HXLINE( 227) this->joints = joints; HXLINE( 228) this->miterLimit = miterLimit; HXLINE( 229) this->pixelHinting = pixelHinting; HXLINE( 230) this->scaleMode = scaleMode; HXLINE( 231) this->thickness = thickness; HXLINE( 232) this->_hx___graphicsDataType = ::openfl::display::GraphicsDataType_obj::STROKE_dyn(); } Dynamic GraphicsStroke_obj::__CreateEmpty() { return new GraphicsStroke_obj; } void *GraphicsStroke_obj::_hx_vtable = 0; Dynamic GraphicsStroke_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< GraphicsStroke_obj > _hx_result = new GraphicsStroke_obj(); _hx_result->__construct(inArgs[0],inArgs[1],inArgs[2],inArgs[3],inArgs[4],inArgs[5],inArgs[6]); return _hx_result; } bool GraphicsStroke_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x7fc28725; } static ::openfl::display::IGraphicsStroke_obj _hx_openfl_display_GraphicsStroke__hx_openfl_display_IGraphicsStroke= { }; static ::openfl::display::IGraphicsData_obj _hx_openfl_display_GraphicsStroke__hx_openfl_display_IGraphicsData= { }; void *GraphicsStroke_obj::_hx_getInterface(int inHash) { switch(inHash) { case (int)0xf088881a: return &_hx_openfl_display_GraphicsStroke__hx_openfl_display_IGraphicsStroke; case (int)0xc177ee0c: return &_hx_openfl_display_GraphicsStroke__hx_openfl_display_IGraphicsData; } #ifdef HXCPP_SCRIPTABLE return super::_hx_getInterface(inHash); #else return 0; #endif } hx::ObjectPtr< GraphicsStroke_obj > GraphicsStroke_obj::__new( ::Dynamic thickness,hx::Null< bool > __o_pixelHinting, ::Dynamic __o_scaleMode, ::Dynamic __o_caps, ::Dynamic __o_joints,hx::Null< Float > __o_miterLimit,::Dynamic fill) { hx::ObjectPtr< GraphicsStroke_obj > __this = new GraphicsStroke_obj(); __this->__construct(thickness,__o_pixelHinting,__o_scaleMode,__o_caps,__o_joints,__o_miterLimit,fill); return __this; } hx::ObjectPtr< GraphicsStroke_obj > GraphicsStroke_obj::__alloc(hx::Ctx *_hx_ctx, ::Dynamic thickness,hx::Null< bool > __o_pixelHinting, ::Dynamic __o_scaleMode, ::Dynamic __o_caps, ::Dynamic __o_joints,hx::Null< Float > __o_miterLimit,::Dynamic fill) { GraphicsStroke_obj *__this = (GraphicsStroke_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(GraphicsStroke_obj), true, "openfl.display.GraphicsStroke")); *(void **)__this = GraphicsStroke_obj::_hx_vtable; __this->__construct(thickness,__o_pixelHinting,__o_scaleMode,__o_caps,__o_joints,__o_miterLimit,fill); return __this; } GraphicsStroke_obj::GraphicsStroke_obj() { } void GraphicsStroke_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(GraphicsStroke); HX_MARK_MEMBER_NAME(caps,"caps"); HX_MARK_MEMBER_NAME(fill,"fill"); HX_MARK_MEMBER_NAME(joints,"joints"); HX_MARK_MEMBER_NAME(miterLimit,"miterLimit"); HX_MARK_MEMBER_NAME(pixelHinting,"pixelHinting"); HX_MARK_MEMBER_NAME(scaleMode,"scaleMode"); HX_MARK_MEMBER_NAME(thickness,"thickness"); HX_MARK_MEMBER_NAME(_hx___graphicsDataType,"__graphicsDataType"); HX_MARK_END_CLASS(); } void GraphicsStroke_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(caps,"caps"); HX_VISIT_MEMBER_NAME(fill,"fill"); HX_VISIT_MEMBER_NAME(joints,"joints"); HX_VISIT_MEMBER_NAME(miterLimit,"miterLimit"); HX_VISIT_MEMBER_NAME(pixelHinting,"pixelHinting"); HX_VISIT_MEMBER_NAME(scaleMode,"scaleMode"); HX_VISIT_MEMBER_NAME(thickness,"thickness"); HX_VISIT_MEMBER_NAME(_hx___graphicsDataType,"__graphicsDataType"); } hx::Val GraphicsStroke_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"caps") ) { return hx::Val( caps ); } if (HX_FIELD_EQ(inName,"fill") ) { return hx::Val( fill ); } break; case 6: if (HX_FIELD_EQ(inName,"joints") ) { return hx::Val( joints ); } break; case 9: if (HX_FIELD_EQ(inName,"scaleMode") ) { return hx::Val( scaleMode ); } if (HX_FIELD_EQ(inName,"thickness") ) { return hx::Val( thickness ); } break; case 10: if (HX_FIELD_EQ(inName,"miterLimit") ) { return hx::Val( miterLimit ); } break; case 12: if (HX_FIELD_EQ(inName,"pixelHinting") ) { return hx::Val( pixelHinting ); } break; case 18: if (HX_FIELD_EQ(inName,"__graphicsDataType") ) { return hx::Val( _hx___graphicsDataType ); } } return super::__Field(inName,inCallProp); } hx::Val GraphicsStroke_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"caps") ) { caps=inValue.Cast< ::Dynamic >(); return inValue; } if (HX_FIELD_EQ(inName,"fill") ) { fill=inValue.Cast< ::Dynamic >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"joints") ) { joints=inValue.Cast< ::Dynamic >(); return inValue; } break; case 9: if (HX_FIELD_EQ(inName,"scaleMode") ) { scaleMode=inValue.Cast< ::Dynamic >(); return inValue; } if (HX_FIELD_EQ(inName,"thickness") ) { thickness=inValue.Cast< Float >(); return inValue; } break; case 10: if (HX_FIELD_EQ(inName,"miterLimit") ) { miterLimit=inValue.Cast< Float >(); return inValue; } break; case 12: if (HX_FIELD_EQ(inName,"pixelHinting") ) { pixelHinting=inValue.Cast< bool >(); return inValue; } break; case 18: if (HX_FIELD_EQ(inName,"__graphicsDataType") ) { _hx___graphicsDataType=inValue.Cast< ::openfl::display::GraphicsDataType >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void GraphicsStroke_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_HCSTRING("caps","\x21","\x1c","\xba","\x41")); outFields->push(HX_HCSTRING("fill","\x83","\xce","\xbb","\x43")); outFields->push(HX_HCSTRING("joints","\xe9","\xe7","\x09","\x91")); outFields->push(HX_HCSTRING("miterLimit","\xf6","\x5c","\x6a","\x54")); outFields->push(HX_HCSTRING("pixelHinting","\xd5","\x9b","\xfb","\x6c")); outFields->push(HX_HCSTRING("scaleMode","\x0d","\xdb","\xd3","\x2b")); outFields->push(HX_HCSTRING("thickness","\x74","\xf1","\x66","\x5a")); outFields->push(HX_HCSTRING("__graphicsDataType","\x0f","\x5d","\x4d","\x46")); super::__GetFields(outFields); }; #if HXCPP_SCRIPTABLE static hx::StorageInfo GraphicsStroke_obj_sMemberStorageInfo[] = { {hx::fsObject /*Dynamic*/ ,(int)offsetof(GraphicsStroke_obj,caps),HX_HCSTRING("caps","\x21","\x1c","\xba","\x41")}, {hx::fsObject /*::openfl::display::IGraphicsFill*/ ,(int)offsetof(GraphicsStroke_obj,fill),HX_HCSTRING("fill","\x83","\xce","\xbb","\x43")}, {hx::fsObject /*Dynamic*/ ,(int)offsetof(GraphicsStroke_obj,joints),HX_HCSTRING("joints","\xe9","\xe7","\x09","\x91")}, {hx::fsFloat,(int)offsetof(GraphicsStroke_obj,miterLimit),HX_HCSTRING("miterLimit","\xf6","\x5c","\x6a","\x54")}, {hx::fsBool,(int)offsetof(GraphicsStroke_obj,pixelHinting),HX_HCSTRING("pixelHinting","\xd5","\x9b","\xfb","\x6c")}, {hx::fsObject /*Dynamic*/ ,(int)offsetof(GraphicsStroke_obj,scaleMode),HX_HCSTRING("scaleMode","\x0d","\xdb","\xd3","\x2b")}, {hx::fsFloat,(int)offsetof(GraphicsStroke_obj,thickness),HX_HCSTRING("thickness","\x74","\xf1","\x66","\x5a")}, {hx::fsObject /*::openfl::display::GraphicsDataType*/ ,(int)offsetof(GraphicsStroke_obj,_hx___graphicsDataType),HX_HCSTRING("__graphicsDataType","\x0f","\x5d","\x4d","\x46")}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo *GraphicsStroke_obj_sStaticStorageInfo = 0; #endif static ::String GraphicsStroke_obj_sMemberFields[] = { HX_HCSTRING("caps","\x21","\x1c","\xba","\x41"), HX_HCSTRING("fill","\x83","\xce","\xbb","\x43"), HX_HCSTRING("joints","\xe9","\xe7","\x09","\x91"), HX_HCSTRING("miterLimit","\xf6","\x5c","\x6a","\x54"), HX_HCSTRING("pixelHinting","\xd5","\x9b","\xfb","\x6c"), HX_HCSTRING("scaleMode","\x0d","\xdb","\xd3","\x2b"), HX_HCSTRING("thickness","\x74","\xf1","\x66","\x5a"), HX_HCSTRING("__graphicsDataType","\x0f","\x5d","\x4d","\x46"), ::String(null()) }; static void GraphicsStroke_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(GraphicsStroke_obj::__mClass,"__mClass"); }; #ifdef HXCPP_VISIT_ALLOCS static void GraphicsStroke_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(GraphicsStroke_obj::__mClass,"__mClass"); }; #endif hx::Class GraphicsStroke_obj::__mClass; void GraphicsStroke_obj::__register() { hx::Object *dummy = new GraphicsStroke_obj; GraphicsStroke_obj::_hx_vtable = *(void **)dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_HCSTRING("openfl.display.GraphicsStroke","\xcd","\x64","\xa2","\xa3"); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mMarkFunc = GraphicsStroke_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = hx::Class_obj::dupFunctions(GraphicsStroke_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< GraphicsStroke_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = GraphicsStroke_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = GraphicsStroke_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = GraphicsStroke_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace openfl } // end namespace display
10,884
4,737
// Fill out your copyright notice in the Description page of Project Settings. #include "SDesiredSizeBox.h" #include "Layout/LayoutUtils.h" SLATE_IMPLEMENT_WIDGET(SDesiredSizeBox) void SDesiredSizeBox::PrivateRegisterAttributes(FSlateAttributeInitializer& AttributeInitializer) { SLATE_ADD_MEMBER_ATTRIBUTE_DEFINITION_WITH_NAME(AttributeInitializer, "SlotPadding", ChildSlot.SlotPaddingAttribute, EInvalidateWidgetReason::Layout); SLATE_ADD_MEMBER_ATTRIBUTE_DEFINITION(AttributeInitializer, WidthFactor, EInvalidateWidgetReason::Layout); SLATE_ADD_MEMBER_ATTRIBUTE_DEFINITION(AttributeInitializer, HeightFactor, EInvalidateWidgetReason::Layout); } SDesiredSizeBox::SDesiredSizeBox() : ChildSlot(this) , WidthFactor(*this) , HeightFactor(*this) { SetCanTick(false); bCanSupportFocus = false; } void SDesiredSizeBox::Construct(const FArguments& InArgs) { SetWidthFactor(InArgs._WidthFactor); SetHeightFactor(InArgs._HeightFactor); ChildSlot .HAlign(InArgs._HAlign) .VAlign(InArgs._VAlign) .Padding(InArgs._Padding) [ InArgs._Content.Widget ]; } void SDesiredSizeBox::SetContent(const TSharedRef<SWidget>& InContent) { ChildSlot [ InContent ]; } void SDesiredSizeBox::SetHAlign(const EHorizontalAlignment HAlign) { ChildSlot.SetHorizontalAlignment(HAlign); } void SDesiredSizeBox::SetVAlign(const EVerticalAlignment VAlign) { ChildSlot.SetVerticalAlignment(VAlign); } void SDesiredSizeBox::SetPadding(TAttribute<FMargin> InPadding) { ChildSlot.SetPadding(InPadding); } void SDesiredSizeBox::SetWidthFactor(TAttribute<FOptionalSize> InWidthFactor) { WidthFactor.Assign(*this, InWidthFactor); } void SDesiredSizeBox::SetHeightFactor(TAttribute<FOptionalSize> InHeightFactor) { HeightFactor.Assign(*this, InHeightFactor); } FVector2D SDesiredSizeBox::ComputeDesiredSize(float) const { const EVisibility ChildVisibility = ChildSlot.GetWidget()->GetVisibility(); if (ChildVisibility != EVisibility::Collapsed) { return FVector2D(ComputeDesiredWidth(), ComputeDesiredHeight()); } return FVector2D::ZeroVector; } float SDesiredSizeBox::ComputeDesiredWidth() const { const FVector2D& UnmodifiedChildDesiredSize = ChildSlot.GetWidget()->GetDesiredSize() + ChildSlot.GetPadding().GetDesiredSize(); const FOptionalSize CurrentWidthFactor = WidthFactor.Get(); float CurrentWidth = UnmodifiedChildDesiredSize.X; if (CurrentWidthFactor.IsSet()) { CurrentWidth *= CurrentWidthFactor.Get(); } return CurrentWidth; } float SDesiredSizeBox::ComputeDesiredHeight() const { const FVector2D& UnmodifiedChildDesiredSize = ChildSlot.GetWidget()->GetDesiredSize() + ChildSlot.GetPadding().GetDesiredSize(); const FOptionalSize CurrentHeightFactor = HeightFactor.Get(); float CurrentHeight = UnmodifiedChildDesiredSize.Y; if (CurrentHeightFactor.IsSet()) { CurrentHeight *= CurrentHeightFactor.Get(); } return CurrentHeight; } void SDesiredSizeBox::OnArrangeChildren(const FGeometry& AllottedGeometry, FArrangedChildren& ArrangedChildren) const { const EVisibility ChildVisibility = ChildSlot.GetWidget()->GetVisibility(); if (ArrangedChildren.Accepts(ChildVisibility)) { const FMargin SlotPadding(ChildSlot.GetPadding()); const AlignmentArrangeResult XAlignmentResult = AlignChild<Orient_Horizontal>(AllottedGeometry.GetLocalSize().X, ChildSlot, SlotPadding); const AlignmentArrangeResult YAlignmentResult = AlignChild<Orient_Vertical>(AllottedGeometry.GetLocalSize().Y, ChildSlot, SlotPadding); ArrangedChildren.AddWidget( AllottedGeometry.MakeChild( ChildSlot.GetWidget(), FVector2D(XAlignmentResult.Offset, YAlignmentResult.Offset), FVector2D(XAlignmentResult.Size, YAlignmentResult.Size) ) ); } } FChildren* SDesiredSizeBox::GetChildren() { return &ChildSlot; } int32 SDesiredSizeBox::OnPaint(const FPaintArgs& Args, const FGeometry& AllottedGeometry, const FSlateRect& MyCullingRect, FSlateWindowElementList& OutDrawElements, const int32 LayerId, const FWidgetStyle& InWidgetStyle, const bool bParentEnabled) const { // SDesiredBox just draws its only child FArrangedChildren ArrangedChildren(EVisibility::Visible); ArrangeChildren(AllottedGeometry, ArrangedChildren); // Maybe none of our children are visible if(ArrangedChildren.Num() > 0) { check(ArrangedChildren.Num() == 1); const FArrangedWidget& TheChild = ArrangedChildren[0]; return TheChild.Widget->Paint(Args.WithNewParent(this), TheChild.Geometry, MyCullingRect, OutDrawElements, LayerId, InWidgetStyle, ShouldBeEnabled(bParentEnabled)); } return LayerId; }
4,530
1,566
/* * 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/iot/model/ListProductByTagsResult.h> #include <json/json.h> using namespace AlibabaCloud::Iot; using namespace AlibabaCloud::Iot::Model; ListProductByTagsResult::ListProductByTagsResult() : ServiceResult() {} ListProductByTagsResult::ListProductByTagsResult(const std::string &payload) : ServiceResult() { parse(payload); } ListProductByTagsResult::~ListProductByTagsResult() {} void ListProductByTagsResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allProductInfosNode = value["ProductInfos"]["ProductInfo"]; for (auto valueProductInfosProductInfo : allProductInfosNode) { ProductInfo productInfosObject; if(!valueProductInfosProductInfo["ProductName"].isNull()) productInfosObject.productName = valueProductInfosProductInfo["ProductName"].asString(); if(!valueProductInfosProductInfo["ProductKey"].isNull()) productInfosObject.productKey = valueProductInfosProductInfo["ProductKey"].asString(); if(!valueProductInfosProductInfo["CreateTime"].isNull()) productInfosObject.createTime = std::stol(valueProductInfosProductInfo["CreateTime"].asString()); if(!valueProductInfosProductInfo["Description"].isNull()) productInfosObject.description = valueProductInfosProductInfo["Description"].asString(); if(!valueProductInfosProductInfo["NodeType"].isNull()) productInfosObject.nodeType = std::stoi(valueProductInfosProductInfo["NodeType"].asString()); productInfos_.push_back(productInfosObject); } if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; if(!value["ErrorMessage"].isNull()) errorMessage_ = value["ErrorMessage"].asString(); if(!value["Code"].isNull()) code_ = value["Code"].asString(); } std::string ListProductByTagsResult::getErrorMessage()const { return errorMessage_; } std::vector<ListProductByTagsResult::ProductInfo> ListProductByTagsResult::getProductInfos()const { return productInfos_; } std::string ListProductByTagsResult::getCode()const { return code_; } bool ListProductByTagsResult::getSuccess()const { return success_; }
2,805
862
// Copyright © 2016 Venture Media Labs. // // This file is part of mxml. The full mxml copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include "AppearanceHandler.h" #include <lxml/DoubleHandler.h> #include <mxml/dom/InvalidDataError.h> #include <cstring> namespace mxml { static const char* kLineWidthTag = "line-width"; static const char* kNoteSizeTag = "note-size"; static const char* kDistanceTag = "distance"; void AppearanceHandler::startElement(const lxml::QName& qname, const AttributeMap& attributes) { _result = dom::Appearance{}; } lxml::RecursiveHandler* AppearanceHandler::startSubElement(const lxml::QName& qname) { if (strcmp(qname.localName(), kLineWidthTag) == 0) return &_handler; else if (strcmp(qname.localName(), kNoteSizeTag) == 0) return &_handler; else if (strcmp(qname.localName(), kDistanceTag) == 0) return &_handler; return 0; } void AppearanceHandler::endSubElement(const lxml::QName& qname, RecursiveHandler* parser) { if (strcmp(qname.localName(), kLineWidthTag) == 0) { auto lineWidthNode = _handler.result(); auto type = lineTypeFromString(lineWidthNode->attribute("type")); auto value = lxml::DoubleHandler::parseDouble(lineWidthNode->text()); _result.lineWidths[type] = static_cast<dom::tenths_t>(value); } else if (strcmp(qname.localName(), kNoteSizeTag) == 0) { auto sizeNode = _handler.result(); auto type = noteTypeFromString(sizeNode->attribute("type")); auto value = lxml::DoubleHandler::parseDouble(sizeNode->text()); _result.noteSizes[type] = static_cast<dom::tenths_t>(value); } else if (strcmp(qname.localName(), kDistanceTag) == 0) { auto distanceNode = _handler.result(); auto type = distanceTypeFromString(distanceNode->attribute("type")); auto value = lxml::DoubleHandler::parseDouble(distanceNode->text()); _result.distances[type] = static_cast<dom::tenths_t>(value); } } dom::LineType AppearanceHandler::lineTypeFromString(const std::string& string) { if (string == "beam") return dom::LineType::Beam; if (string == "bracket") return dom::LineType::Bracket; if (string == "dashes") return dom::LineType::Dashes; if (string == "enclosure") return dom::LineType::Enclosure; if (string == "ending") return dom::LineType::Ending; if (string == "extend") return dom::LineType::Extend; if (string == "heavy barline") return dom::LineType::HeavyBarline; if (string == "leger") return dom::LineType::Leger; if (string == "light barline") return dom::LineType::LightBarline; if (string == "octave shift") return dom::LineType::OctaveShift; if (string == "pedal") return dom::LineType::Pedal; if (string == "slur middle") return dom::LineType::SlurMiddle; if (string == "slur tip") return dom::LineType::SlurTip; if (string == "staff") return dom::LineType::Staff; if (string == "stem") return dom::LineType::Stem; if (string == "tie middle") return dom::LineType::TieMiddle; if (string == "tie tip") return dom::LineType::TieTip; if (string == "tuplet bracket") return dom::LineType::TupletBracket; if (string == "wedge") return dom::LineType::Wedge; throw dom::InvalidDataError("Invalid halign type " + string); } dom::NoteType AppearanceHandler::noteTypeFromString(const std::string& string) { if (string == "cue") return dom::NoteType::Cue; if (string == "grace") return dom::NoteType::Grace; if (string == "large") return dom::NoteType::Large; throw dom::InvalidDataError("Invalid halign type " + string); } dom::DistanceType AppearanceHandler::distanceTypeFromString(const std::string& string) { if (string == "beam") return dom::DistanceType::Beam; if (string == "hyphen") return dom::DistanceType::Hyphen; throw dom::InvalidDataError("Invalid halign type " + string); } } // namespace mxml
4,166
1,293
// Copyright (c) 2018 Graphcore Ltd. All rights reserved. #include <vector> // for `find', we need the algorithm header #include <algorithm> #include <memory> #include <popart/op/add.hpp> #include <popart/opmanager.hpp> #include <popart/tensor.hpp> namespace popart { // TODO : T6250 : Add support for V6 axis & broadcast attributes AddOp::AddOp(const OperatorIdentifier &_opid, const Op::Settings &_settings) : ElementWiseNpBroadcastableBinaryWithGradOp(_opid, _settings) { // TODO : Use the attributes in Add-6 } std::unique_ptr<Op> AddOp::clone() const { return std::make_unique<AddOp>(*this); } bool AddOp::hasLhsInplaceVariant() const { return true; } bool AddOp::hasRhsInplaceVariant() const { return true; } std::unique_ptr<Op> AddOp::getLhsInplaceVariant() const { return std::make_unique<AddLhsInplaceOp>(getSettings()); } std::unique_ptr<Op> AddOp::getRhsInplaceVariant() const { return std::make_unique<AddRhsInplaceOp>(getSettings()); } OperatorIdentifier AddOp::getLhsOperatorIdentifier() const { return Onnx::CustomOperators::AddLhsInplace; } OperatorIdentifier AddOp::getRhsOperatorIdentifier() const { return Onnx::CustomOperators::AddRhsInplace; } AddArg0GradOp::AddArg0GradOp(const Op &op, const std::vector<int64_t> &_axes) : ReduceSumOp(Onnx::GradOperators::AddArg0Grad, _axes, false, op.getSettings()), forward_op_arg_info(op.inInfo(AddOp::getArg0InIndex())) {} const std::map<int, int> &AddArg0GradOp::gradOutToNonGradIn() const { static const std::map<int, int> outInfo = { {getOutIndex(), AddOp::getArg0InIndex()}}; return outInfo; } const std::vector<GradInOutMapper> &AddArg0GradOp::gradInputInfo() const { static const std::vector<GradInOutMapper> inInfo = { {getInIndex(), AddOp::getOutIndex(), GradOpInType::GradOut}}; return inInfo; } void AddArg0GradOp::setup() { outInfo(getOutIndex()) = forward_op_arg_info; } std::unique_ptr<Op> AddArg0GradOp::clone() const { return std::make_unique<AddArg0GradOp>(*this); } AddArg1GradOp::AddArg1GradOp(const Op &op, const std::vector<int64_t> &_axes) : ReduceSumOp(Onnx::GradOperators::AddArg1Grad, _axes, false, op.getSettings()), forward_op_arg_info(op.inInfo(AddOp::getArg1InIndex())) {} const std::map<int, int> &AddArg1GradOp::gradOutToNonGradIn() const { static const std::map<int, int> outInfo = { {getOutIndex(), AddOp::getArg1InIndex()}}; return outInfo; } const std::vector<GradInOutMapper> &AddArg1GradOp::gradInputInfo() const { // input at index 0 : gradient of output of add // might need to reduce across certain axes of this // if numpy broadcasting happened static const std::vector<GradInOutMapper> inInfo = { {getInIndex(), AddOp::getOutIndex(), GradOpInType::GradOut}}; return inInfo; } void AddArg1GradOp::setup() { outInfo(getOutIndex()) = forward_op_arg_info; } std::unique_ptr<Op> AddArg1GradOp::clone() const { return std::make_unique<AddArg1GradOp>(*this); } namespace { static OpDefinition::DataTypes T = {DataType::UINT32, DataType::UINT64, DataType::INT32, DataType::INT64, DataType::FLOAT16, DataType::FLOAT}; static OpDefinition addOpDef({OpDefinition::Inputs({{"A", T}, {"B", T}}), OpDefinition::Outputs({{"C", T}}), OpDefinition::Attributes({})}); static OpCreator<AddOp> addOpCreator(OpDefinitions( {{Onnx::Operators::Add_6, addOpDef}, {Onnx::Operators::Add_7, addOpDef}})); static OpCreator<AddLhsInplaceOp> addAddLhsInplaceCreator( OpDefinitions({{Onnx::CustomOperators::AddLhsInplace, addOpDef}})); } // namespace } // namespace popart
3,912
1,305
// Copyright (c) 2012-2017 VideoStitch SAS // Copyright (c) 2018 stitchEm #include "export.hpp" #include "rawOutput.hpp" #include "libgpudiscovery/delayLoad.hpp" #include "libvideostitch/output.hpp" #include "libvideostitch/plugin.hpp" #ifdef DELAY_LOAD_ENABLED SET_DELAY_LOAD_HOOK #endif // DELAY_LOAD_ENABLED /** \name Services for writer plugin. */ //\{ extern "C" VS_PLUGINS_EXPORT VideoStitch::Potential<VideoStitch::Output::Output>* createWriterFn( VideoStitch::Ptv::Value const* config, VideoStitch::Plugin::VSWriterPlugin::Config run_time) { VideoStitch::Output::RawWriter* writer = VideoStitch::Output::RawWriter::create(config, run_time); if (writer) { return new VideoStitch::Potential<VideoStitch::Output::Output>(writer); } return new VideoStitch::Potential<VideoStitch::Output::Output>( VideoStitch::Origin::Output, VideoStitch::ErrType::InvalidConfiguration, "Could not create RAW Writer"); } extern "C" VS_PLUGINS_EXPORT bool handleWriterFn(VideoStitch::Ptv::Value const* config) { return VideoStitch::Output::RawWriter::handles(config); } //\}
1,092
387
#include "pch.h" void Proxy::Init() { wchar_t realDllPath[MAX_PATH]; GetSystemDirectory(realDllPath, MAX_PATH); wcscat_s(realDllPath, L"\\xinput1_3.dll"); HMODULE hDll = LoadLibrary(realDllPath); if (hDll == nullptr) { MessageBox(nullptr, L"Cannot load original xinput1_3.dll library", L"Proxy", MB_ICONERROR); ExitProcess(0); } #define RESOLVE(fn) Original##fn = GetProcAddress(hDll, #fn) RESOLVE(DllMain); RESOLVE(XInputEnable); RESOLVE(XInputGetBatteryInformation); RESOLVE(XInputGetCapabilities); RESOLVE(XInputGetDSoundAudioDeviceGuids); RESOLVE(XInputGetKeystroke); RESOLVE(XInputGetState); RESOLVE(XInputSetState); #undef RESOLVE } __declspec(naked) void FakeDllMain() { __asm { jmp [Proxy::OriginalDllMain] } } __declspec(naked) void FakeXInputEnable() { __asm { jmp [Proxy::OriginalXInputEnable] } } __declspec(naked) void FakeXInputGetBatteryInformation() { __asm { jmp [Proxy::OriginalXInputGetBatteryInformation] } } __declspec(naked) void FakeXInputGetCapabilities() { __asm { jmp [Proxy::OriginalXInputGetCapabilities] } } __declspec(naked) void FakeXInputGetDSoundAudioDeviceGuids() { __asm { jmp [Proxy::OriginalXInputGetDSoundAudioDeviceGuids] } } __declspec(naked) void FakeXInputGetKeystroke() { __asm { jmp [Proxy::OriginalXInputGetKeystroke] } } __declspec(naked) void FakeXInputGetState() { __asm { jmp [Proxy::OriginalXInputGetState] } } __declspec(naked) void FakeXInputSetState() { __asm { jmp [Proxy::OriginalXInputSetState] } }
1,765
590
/* CDF 9/10/98 A bold new initiaitive! */ #include "3dc.h" #include "inline.h" #include "module.h" #include "io.h" #include "strategy_def.h" #include "gamedef.h" #include "bh_types.h" #include "dynblock.h" #include "dynamics.h" #include "weapons.h" #include "compiled_shapes.h" #include "inventory.h" #include "triggers.h" #include "mslhand.h" #define UseLocalAssert TRUE #include "ourasert.h" #include "pmove.h" #include "pvisible.h" #include "bh_switch_door.h" #include "bh_platform_lift.h" #include "load_shape.h" #include "bh_weapon.h" #include "bh_debris.h" #include "lighting.h" #include "bh_link_switch.h" #include "bh_binary_switch.h" #include "pheromone.h" #include "bh_predator.h" #include "bh_agun.h" #include "plat_shp.h" #include "psnd.h" #include "ai_sight.h" #include "sequences.h" #include "huddefs.h" #include "showcmds.h" #include "sfx.h" #include "bh_marine.h" #include "bh_dummy.h" #include "bh_far.h" #include "targeting.h" #include "dxlog.h" #include "los.h" #include "psndplat.h" #include "extents.h" #include "pldghost.h" #include "pldnet.h" extern unsigned char Null_Name[8]; extern ACTIVESOUNDSAMPLE ActiveSounds[]; extern SECTION * GetNamedHierarchyFromLibrary(const char * rif_name, const char * hier_name); void CreateDummy(VECTORCH *Position); /* Begin code! */ void CastDummy(void) { #define BOTRANGE 2000 VECTORCH position; if (AvP.Network!=I_No_Network) { NewOnScreenMessage("NO DUMMYS IN MULTIPLAYER MODE"); return; } position=Player->ObStrategyBlock->DynPtr->Position; position.vx+=MUL_FIXED(Player->ObStrategyBlock->DynPtr->OrientMat.mat31,BOTRANGE); position.vy+=MUL_FIXED(Player->ObStrategyBlock->DynPtr->OrientMat.mat32,BOTRANGE); position.vz+=MUL_FIXED(Player->ObStrategyBlock->DynPtr->OrientMat.mat33,BOTRANGE); CreateDummy(&position); } void CreateDummy(VECTORCH *Position) { STRATEGYBLOCK* sbPtr; /* create and initialise a strategy block */ sbPtr = CreateActiveStrategyBlock(); if(!sbPtr) { NewOnScreenMessage("FAILED TO CREATE DUMMY: SB CREATION FAILURE"); return; /* failure */ } InitialiseSBValues(sbPtr); sbPtr->I_SBtype = I_BehaviourDummy; AssignNewSBName(sbPtr); /* create, initialise and attach a dynamics block */ sbPtr->DynPtr = AllocateDynamicsBlock(DYNAMICS_TEMPLATE_MARINE_PLAYER); if(sbPtr->DynPtr) { EULER zeroEuler = {0,0,0}; DYNAMICSBLOCK *dynPtr = sbPtr->DynPtr; GLOBALASSERT(dynPtr); dynPtr->PrevPosition = dynPtr->Position = *Position; dynPtr->OrientEuler = zeroEuler; CreateEulerMatrix(&dynPtr->OrientEuler, &dynPtr->OrientMat); TransposeMatrixCH(&dynPtr->OrientMat); } else { /* dynamics block allocation failed... */ RemoveBehaviourStrategy(sbPtr); NewOnScreenMessage("FAILED TO CREATE DUMMY: DYNBLOCK CREATION FAILURE"); return; } sbPtr->shapeIndex = 0; sbPtr->maintainVisibility = 1; sbPtr->containingModule = ModuleFromPosition(&(sbPtr->DynPtr->Position), (MODULE*)0); /* Initialise dummy's stats */ { sbPtr->SBDamageBlock.Health=30000<<ONE_FIXED_SHIFT; sbPtr->SBDamageBlock.Armour=30000<<ONE_FIXED_SHIFT; sbPtr->SBDamageBlock.SB_H_flags.AcidResistant=1; sbPtr->SBDamageBlock.SB_H_flags.FireResistant=1; sbPtr->SBDamageBlock.SB_H_flags.ElectricResistant=1; sbPtr->SBDamageBlock.SB_H_flags.PerfectArmour=1; sbPtr->SBDamageBlock.SB_H_flags.ElectricSensitive=0; sbPtr->SBDamageBlock.SB_H_flags.Combustability=0; sbPtr->SBDamageBlock.SB_H_flags.Indestructable=1; } /* create, initialise and attach a dummy data block */ sbPtr->SBdataptr = (void *)AllocateMem(sizeof(DUMMY_STATUS_BLOCK)); if(sbPtr->SBdataptr) { SECTION *root_section; DUMMY_STATUS_BLOCK *dummyStatus = (DUMMY_STATUS_BLOCK *)sbPtr->SBdataptr; GLOBALASSERT(dummyStatus); dummyStatus->incidentFlag=0; dummyStatus->incidentTimer=0; dummyStatus->HModelController.section_data=NULL; dummyStatus->HModelController.Deltas=NULL; switch (AvP.PlayerType) { case I_Marine: dummyStatus->PlayerType=I_Marine; root_section=GetNamedHierarchyFromLibrary("hnpcmarine","marine with pulse rifle"); if (!root_section) { RemoveBehaviourStrategy(sbPtr); NewOnScreenMessage("FAILED TO CREATE DUMMY: NO HMODEL"); return; } Create_HModel(&dummyStatus->HModelController,root_section); InitHModelSequence(&dummyStatus->HModelController,(int)HMSQT_MarineStand,(int)MSSS_Fidget_A,-1); break; case I_Alien: dummyStatus->PlayerType=I_Alien; root_section=GetNamedHierarchyFromLibrary("hnpcalien","alien"); if (!root_section) { RemoveBehaviourStrategy(sbPtr); NewOnScreenMessage("FAILED TO CREATE DUMMY: NO HMODEL"); return; } Create_HModel(&dummyStatus->HModelController,root_section); InitHModelSequence(&dummyStatus->HModelController,(int)HMSQT_AlienStand,(int)ASSS_Standard,-1); break; case I_Predator: dummyStatus->PlayerType=I_Predator; root_section=GetNamedHierarchyFromLibrary("hnpcpredator","pred with wristblade"); if (!root_section) { RemoveBehaviourStrategy(sbPtr); NewOnScreenMessage("FAILED TO CREATE DUMMY: NO HMODEL"); return; } Create_HModel(&dummyStatus->HModelController,root_section); InitHModelSequence(&dummyStatus->HModelController,(int)HMSQT_PredatorStand,(int)PSSS_Standard,-1); break; } ProveHModel_Far(&dummyStatus->HModelController,sbPtr); if(!(sbPtr->containingModule)) { /* no containing module can be found... abort*/ RemoveBehaviourStrategy(sbPtr); NewOnScreenMessage("FAILED TO CREATE DUMMY: MODULE CONTAINMENT FAILURE"); return; } LOCALASSERT(sbPtr->containingModule); MakeDummyNear(sbPtr); NewOnScreenMessage("DUMMY CREATED"); } else { /* no data block can be allocated */ RemoveBehaviourStrategy(sbPtr); NewOnScreenMessage("FAILED TO CREATE DUMMY: MALLOC FAILURE"); return; } } void MakeDummyNear(STRATEGYBLOCK *sbPtr) { extern MODULEMAPBLOCK AlienDefaultMap; MODULE tempModule; DISPLAYBLOCK *dPtr; DYNAMICSBLOCK *dynPtr; DUMMY_STATUS_BLOCK *dummyStatusPointer; LOCALASSERT(sbPtr); LOCALASSERT(sbPtr->SBdptr == NULL); dynPtr = sbPtr->DynPtr; dummyStatusPointer = (DUMMY_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(dummyStatusPointer); LOCALASSERT(dynPtr); AlienDefaultMap.MapShape = sbPtr->shapeIndex; tempModule.m_mapptr = &AlienDefaultMap; tempModule.m_sbptr = (STRATEGYBLOCK*)NULL; tempModule.m_numlights = 0; tempModule.m_lightarray = (struct lightblock *)0; tempModule.m_extraitemdata = (struct extraitemdata *)0; tempModule.m_dptr = NULL; AllocateModuleObject(&tempModule); dPtr = tempModule.m_dptr; if(dPtr==NULL) return; /* cannot allocate displayblock, so leave far */ sbPtr->SBdptr = dPtr; dPtr->ObStrategyBlock = sbPtr; dPtr->ObMyModule = NULL; /* need to initialise positional information in the new display block */ dPtr->ObWorld = dynPtr->Position; dPtr->ObEuler = dynPtr->OrientEuler; dPtr->ObMat = dynPtr->OrientMat; /* zero linear velocity in dynamics block */ sbPtr->DynPtr->LinVelocity.vx = 0; sbPtr->DynPtr->LinVelocity.vy = 0; sbPtr->DynPtr->LinVelocity.vz = 0; /* state and sequence initialisation */ dPtr->HModelControlBlock=&dummyStatusPointer->HModelController; ProveHModel(dPtr->HModelControlBlock,dPtr); /*Copy extents from the collision extents in extents.c*/ dPtr->ObMinX=-CollisionExtents[CE_MARINE].CollisionRadius; dPtr->ObMaxX=CollisionExtents[CE_MARINE].CollisionRadius; dPtr->ObMinZ=-CollisionExtents[CE_MARINE].CollisionRadius; dPtr->ObMaxZ=CollisionExtents[CE_MARINE].CollisionRadius; dPtr->ObMinY=CollisionExtents[CE_MARINE].CrouchingTop; dPtr->ObMaxY=CollisionExtents[CE_MARINE].Bottom; dPtr->ObRadius = 1000; } void MakeDummyFar(STRATEGYBLOCK *sbPtr) { DUMMY_STATUS_BLOCK *dummyStatusPointer; int i; LOCALASSERT(sbPtr); LOCALASSERT(sbPtr->SBdptr != NULL); dummyStatusPointer = (DUMMY_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(dummyStatusPointer); /* get rid of the displayblock */ i = DestroyActiveObject(sbPtr->SBdptr); LOCALASSERT(i==0); sbPtr->SBdptr = NULL; /* zero linear velocity in dynamics block */ sbPtr->DynPtr->LinVelocity.vx = 0; sbPtr->DynPtr->LinVelocity.vy = 0; sbPtr->DynPtr->LinVelocity.vz = 0; } void DummyBehaviour(STRATEGYBLOCK *sbPtr) { DUMMY_STATUS_BLOCK *dummyStatusPointer; LOCALASSERT(sbPtr); LOCALASSERT(sbPtr->containingModule); dummyStatusPointer = (DUMMY_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(dummyStatusPointer); /* Should be the same near as far. */ /* test if we've got a containing module: if we haven't, do nothing. This is important as the object could have been marked for deletion by the visibility management system...*/ if(!sbPtr->containingModule) { DestroyAnyStrategyBlock(sbPtr); /* just to make sure */ return; } else if (dummyStatusPointer->PlayerType!=I_Alien) { AddMarinePheromones(sbPtr->containingModule->m_aimodule); } /* Incident handling. */ dummyStatusPointer->incidentFlag=0; dummyStatusPointer->incidentTimer-=NormalFrameTime; if (dummyStatusPointer->incidentTimer<0) { dummyStatusPointer->incidentFlag=1; dummyStatusPointer->incidentTimer=32767+(FastRandom()&65535); } }
9,245
3,840
/*++ Copyright (c) 1992 Microsoft Corporation Module Name: crash.cxx Abstract: Contains code concerned with recovery actions that are taken when a service crashes. This file contains the following functions: ScQueueRecoveryAction CCrashRecord::IncrementCount CRestartContext::Perform CRebootMessageContext::Perform CRebootContext::Perform CRunCommandContext::Perform Author: Anirudh Sahni (anirudhs) 02-Dec-1996 Environment: User Mode -Win32 Revision History: 22-Oct-1998 jschwart Convert SCM to use NT thread pool APIs 02-Dec-1996 AnirudhS Created --*/ // // INCLUDES // #include "precomp.hxx" #include <lmcons.h> // needed for other lm headers #include <lmerr.h> // NERR_Success #include <lmshare.h> // NetSessionEnum #include <lmmsg.h> // NetMessageBufferSend #include <lmapibuf.h> // NetApiBufferFree #include <valid.h> // ACTION_TYPE_INVALID #include <svcslib.h> // CWorkItemContext #include "smartp.h" // CHeapPtr #include "scconfig.h" // ScReadFailureActions, etc. #include "depend.h" // ScStartServiceAndDependencies #include "account.h" // ScLogonService #include "scseclib.h" // ScCreateAndSetSD #include "start.h" // ScAllowInteractiveServices, ScInitStartupInfo #include "resource.h" // IDS_SC_ACTION_BASE // // Defines and Typedefs // #define FILETIMES_PER_SEC ((__int64) 10000000) // (1 second)/(100 ns) #define LENGTH(array) (sizeof(array)/sizeof((array)[0])) // // Globals // // // Local Function Prototypes // VOID ScLogRecoveryFailure( IN SC_ACTION_TYPE ActionType, IN LPCWSTR ServiceDisplayName, IN DWORD Error ); inline LPWSTR LocalDup( LPCWSTR String ) { LPWSTR Dup = (LPWSTR) LocalAlloc(0, WCSSIZE(String)); if (Dup != NULL) { wcscpy(Dup, String); } return Dup; } // // Callback context for restarting a service // class CRestartContext : public CWorkItemContext { DECLARE_CWorkItemContext public: CRestartContext( IN LPSERVICE_RECORD ServiceRecord ) : _ServiceRecord(ServiceRecord) { ServiceRecord->UseCount++; SC_LOG2(USECOUNT, "CRestartContext: %ws increment " "USECOUNT=%lu\n", ServiceRecord->ServiceName, ServiceRecord->UseCount); } ~CRestartContext() { CServiceRecordExclusiveLock RLock; ScDecrementUseCountAndDelete(_ServiceRecord); } private: LPSERVICE_RECORD _ServiceRecord; }; // // Callback context for broadcasting a reboot message // class CRebootMessageContext : public CWorkItemContext { DECLARE_CWorkItemContext public: CRebootMessageContext( IN LPWSTR RebootMessage, IN DWORD Delay, IN LPWSTR DisplayName ) : _RebootMessage(RebootMessage), _Delay(Delay), _DisplayName(LocalDup(DisplayName)) { } ~CRebootMessageContext() { LocalFree(_RebootMessage); } private: LPWSTR _RebootMessage; DWORD _Delay; LPWSTR _DisplayName; }; // // Callback context for a reboot // (The service name is used only for logging) // class CRebootContext : public CWorkItemContext { DECLARE_CWorkItemContext public: CRebootContext( IN DWORD ActionDelay, IN LPWSTR DisplayName ) : _Delay(ActionDelay), _DisplayName(DisplayName) { } ~CRebootContext() { LocalFree(_DisplayName); } private: DWORD _Delay; LPWSTR _DisplayName; }; // // Callback context for running a recovery command // class CRunCommandContext : public CWorkItemContext { DECLARE_CWorkItemContext public: CRunCommandContext( IN LPSERVICE_RECORD ServiceRecord, IN LPWSTR FailureCommand ) : _ServiceRecord(ServiceRecord), _FailureCommand(FailureCommand) { // // The service record is used to get the // account name to run the command in. // ServiceRecord->UseCount++; SC_LOG2(USECOUNT, "CRunCommandContext: %ws increment " "USECOUNT=%lu\n", ServiceRecord->ServiceName, ServiceRecord->UseCount); } ~CRunCommandContext() { LocalFree(_FailureCommand); CServiceRecordExclusiveLock RLock; ScDecrementUseCountAndDelete(_ServiceRecord); } private: LPSERVICE_RECORD _ServiceRecord; LPWSTR _FailureCommand; }; /****************************************************************************/ VOID ScQueueRecoveryAction( IN LPSERVICE_RECORD ServiceRecord ) /*++ Routine Description: Arguments: Return Value: none. --*/ { SC_ACTION_TYPE ActionType = SC_ACTION_NONE; DWORD ActionDelay = 0; DWORD FailNum = 1; NTSTATUS ntStatus; // // See if there is any recovery action configured for this service. // HKEY Key = NULL; { DWORD ResetPeriod = INFINITE; LPSERVICE_FAILURE_ACTIONS_WOW64 psfa = NULL; DWORD Error = ScOpenServiceConfigKey( ServiceRecord->ServiceName, KEY_READ, FALSE, // don't create if missing &Key ); if (Error == ERROR_SUCCESS) { Error = ScReadFailureActions(Key, &psfa); } if (Error != ERROR_SUCCESS) { SC_LOG(ERROR, "Couldn't read service's failure actions, %lu\n", Error); } else if (psfa != NULL && psfa->cActions > 0) { ResetPeriod = psfa->dwResetPeriod; } // // Allocate a crash record for the service. // Increment the service's crash count, subject to the reset period // we just read from the registry (INFINITE if we read none). // if (ServiceRecord->CrashRecord == NULL) { ServiceRecord->CrashRecord = new CCrashRecord; } if (ServiceRecord->CrashRecord == NULL) { SC_LOG0(ERROR, "Couldn't allocate service's crash record\n"); // // NOTE: We still continue, taking the failure count to be 1. // (The crash record is used only in the "else" clause.) // } else { FailNum = ServiceRecord->CrashRecord->IncrementCount(ResetPeriod); } // // Figure out which recovery action we're going to take. // if (psfa != NULL && psfa->cActions > 0) { SC_ACTION * lpsaActions = (SC_ACTION *) ((LPBYTE) psfa + psfa->dwsaActionsOffset); DWORD i = min(FailNum, psfa->cActions); ActionType = lpsaActions[i - 1].Type; ActionDelay = lpsaActions[i - 1].Delay; if (ACTION_TYPE_INVALID(ActionType)) { SC_LOG(ERROR, "Service has invalid action type %lu\n", ActionType); ActionType = SC_ACTION_NONE; } } LocalFree(psfa); } // // Log an event about this service failing, and about the proposed // recovery action. // if (ActionType != SC_ACTION_NONE) { WCHAR wszActionString[50]; if (!LoadString(GetModuleHandle(NULL), IDS_SC_ACTION_BASE + ActionType, wszActionString, LENGTH(wszActionString))) { SC_LOG(ERROR, "LoadString failed %lu\n", GetLastError()); wszActionString[0] = L'\0'; } SC_LOG2(ERROR, "The following recovery action will be taken in %d ms: %ws.\n", ActionDelay, wszActionString); ScLogEvent(NEVENT_SERVICE_CRASH, ServiceRecord->DisplayName, FailNum, ActionDelay, ActionType, wszActionString); } else { ScLogEvent(NEVENT_SERVICE_CRASH_NO_ACTION, ServiceRecord->DisplayName, FailNum); } // // Queue a work item that will actually carry out the action after the // delay has elapsed. // switch (ActionType) { case SC_ACTION_NONE: break; case SC_ACTION_RESTART: { CRestartContext * pCtx = new CRestartContext(ServiceRecord); if (pCtx == NULL) { SC_LOG0(ERROR, "Couldn't allocate restart context\n"); break; } ntStatus = pCtx->AddDelayedWorkItem(ActionDelay, WT_EXECUTEONLYONCE); if (!NT_SUCCESS(ntStatus)) { SC_LOG(ERROR, "Couldn't add restart work item 0x%x\n", ntStatus); delete pCtx; } break; } case SC_ACTION_REBOOT: { // // Get the reboot message for the service, if any // LPWSTR RebootMessage = NULL; ScReadRebootMessage(Key, &RebootMessage); if (RebootMessage != NULL) { // // Broadcast the message to all users. Do this in a separate // thread so that we can release our exclusive lock on the // service database quickly. // CRebootMessageContext * pCtx = new CRebootMessageContext( RebootMessage, ActionDelay, ServiceRecord->DisplayName ); if (pCtx == NULL) { SC_LOG0(ERROR, "Couldn't allocate restart context\n"); LocalFree(RebootMessage); break; } ntStatus = pCtx->AddWorkItem(WT_EXECUTEONLYONCE); if (!NT_SUCCESS(ntStatus)) { SC_LOG(ERROR, "Couldn't add restart work item 0x%x\n", ntStatus); delete pCtx; } } else { // // Queue a work item to perform the reboot after the delay has // elapsed. // (CODEWORK Share this code with CRebootMessageContext::Perform) // LPWSTR DisplayNameCopy = LocalDup(ServiceRecord->DisplayName); CRebootContext * pCtx = new CRebootContext( ActionDelay, DisplayNameCopy ); if (pCtx == NULL) { SC_LOG0(ERROR, "Couldn't allocate reboot context\n"); LocalFree(DisplayNameCopy); } else { ntStatus = pCtx->AddWorkItem(WT_EXECUTEONLYONCE); if (!NT_SUCCESS(ntStatus)) { SC_LOG(ERROR, "Couldn't add reboot work item 0x%x\n", ntStatus); delete pCtx; } } } } break; case SC_ACTION_RUN_COMMAND: { // // Get the failure command for the service, if any // CHeapPtr<LPWSTR> FailureCommand; ScReadFailureCommand(Key, &FailureCommand); if (FailureCommand == NULL) { SC_LOG0(ERROR, "Asked to run a failure command, but found " "none for this service\n"); ScLogRecoveryFailure( SC_ACTION_RUN_COMMAND, ServiceRecord->DisplayName, ERROR_NO_RECOVERY_PROGRAM ); break; } // // Replace %1% in the failure command with the failure count. // (FormatMessage is *useless* for this purpose because it AV's // if the failure command contains a %2, %3 etc.!) // UNICODE_STRING Formatted; { UNICODE_STRING Unformatted; RtlInitUnicodeString(&Unformatted, FailureCommand); Formatted.Length = 0; Formatted.MaximumLength = Unformatted.MaximumLength + 200; Formatted.Buffer = (LPWSTR) LocalAlloc(0, Formatted.MaximumLength); if (Formatted.Buffer == NULL) { SC_LOG(ERROR, "Couldn't allocate formatted string, %lu\n", GetLastError()); break; } WCHAR Environment[30]; wsprintf(Environment, L"1=%lu%c", FailNum, L'\0'); NTSTATUS ntstatus = RtlExpandEnvironmentStrings_U( Environment, &Unformatted, &Formatted, NULL); if (!NT_SUCCESS(ntstatus)) { SC_LOG(ERROR, "RtlExpandEnvironmentStrings_U failed %#lx\n", ntstatus); wcscpy(Formatted.Buffer, FailureCommand); } } CRunCommandContext * pCtx = new CRunCommandContext(ServiceRecord, Formatted.Buffer); if (pCtx == NULL) { SC_LOG0(ERROR, "Couldn't allocate RunCommand context\n"); LocalFree(Formatted.Buffer); break; } ntStatus = pCtx->AddDelayedWorkItem(ActionDelay, WT_EXECUTEONLYONCE); if (!NT_SUCCESS(ntStatus)) { SC_LOG(ERROR, "Couldn't add RunCommand work item 0x%x\n", ntStatus); delete pCtx; } } break; default: SC_ASSERT(0); } if (Key != NULL) { ScRegCloseKey(Key); } } DWORD CCrashRecord::IncrementCount( DWORD ResetSeconds ) /*++ Routine Description: Increments a service's crash count. Arguments: ResetSeconds - Length, in seconds, of a period of no crashes after which the crash count should be reset to zero. Return Value: The service's new crash count. --*/ { __int64 SecondLastCrashTime = _LastCrashTime; GetSystemTimeAsFileTime((FILETIME *) &_LastCrashTime); if (ResetSeconds == INFINITE || SecondLastCrashTime + ResetSeconds * FILETIMES_PER_SEC > _LastCrashTime) { _Count++; } else { SC_LOG(CONFIG_API, "More than %lu seconds have elapsed since last " "crash, resetting crash count.\n", ResetSeconds); _Count = 1; } SC_LOG(CONFIG_API, "Service's crash count is now %lu\n", _Count); return _Count; } VOID CRestartContext::Perform( IN BOOLEAN fWaitStatus ) /*++ Routine Description: --*/ { // // Make sure we were called because of a timeout // SC_ASSERT(fWaitStatus == TRUE); SC_LOG(CONFIG_API, "Restarting %ws service...\n", _ServiceRecord->ServiceName); RemoveDelayedWorkItem(); // // CODEWORK Allow arguments to the service. // DWORD status = ScStartServiceAndDependencies(_ServiceRecord, 0, NULL, FALSE); if (status == NO_ERROR) { status = _ServiceRecord->StartError; SC_LOG(CONFIG_API, "ScStartServiceAndDependencies succeeded, StartError = %lu\n", status); } else { SC_LOG(CONFIG_API, "ScStartServiceAndDependencies failed, %lu\n", status); // // Should we treat ERROR_SERVICE_ALREADY_RUNNING as a success? // No, because it could alert the administrator to a less-than- // optimal system configuration wherein something else is // restarting the service. // ScLogRecoveryFailure( SC_ACTION_RESTART, _ServiceRecord->DisplayName, status ); } delete this; } VOID CRebootMessageContext::Perform( IN BOOLEAN fWaitStatus ) /*++ Routine Description: --*/ { // // Broadcast the reboot message to all users // SESSION_INFO_0 * Buffer = NULL; DWORD EntriesRead = 0, TotalEntries = 0; NTSTATUS ntStatus; NET_API_STATUS Status = NetSessionEnum( NULL, // servername NULL, // UncClientName NULL, // username 0, // level (LPBYTE *) &Buffer, 0xFFFFFFFF, // prefmaxlen &EntriesRead, &TotalEntries, NULL // resume_handle ); if (EntriesRead > 0) { SC_ASSERT(EntriesRead == TotalEntries); SC_ASSERT(Status == NERR_Success); WCHAR ComputerName[MAX_COMPUTERNAME_LENGTH + 1]; DWORD nSize = LENGTH(ComputerName); if (!GetComputerName(ComputerName, &nSize)) { SC_LOG(ERROR, "GetComputerName failed! %lu\n", GetLastError()); } else { DWORD MsgLen = (DWORD) WCSSIZE(_RebootMessage); for (DWORD i = 0; i < EntriesRead; i++) { Status = NetMessageBufferSend( NULL, // servername Buffer[i].sesi0_cname, // msgname ComputerName, // fromname (LPBYTE) _RebootMessage,// buf MsgLen // buflen ); if (Status != NERR_Success) { SC_LOG2(ERROR, "NetMessageBufferSend to %ws failed %lu\n", Buffer[i].sesi0_cname, Status); } } } } else if (Status != NERR_Success) { SC_LOG(ERROR, "NetSessionEnum failed %lu\n", Status); } if (Buffer != NULL) { NetApiBufferFree(Buffer); } // // Queue a work item to perform the reboot after the delay has elapsed. // Note: We're counting the delay from the time that the broadcast finished. // CRebootContext * pCtx = new CRebootContext(_Delay, _DisplayName); if (pCtx == NULL) { SC_LOG0(ERROR, "Couldn't allocate reboot context\n"); } else { _DisplayName = NULL; // pCtx will free it ntStatus = pCtx->AddWorkItem(WT_EXECUTEONLYONCE); if (!NT_SUCCESS(ntStatus)) { SC_LOG(ERROR, "Couldn't add reboot work item 0x%x\n", ntStatus); delete pCtx; } } delete this; } VOID CRebootContext::Perform( IN BOOLEAN fWaitStatus ) /*++ Routine Description: --*/ { SC_LOG0(CONFIG_API, "Rebooting machine...\n"); // Write an event log entry? // // Enable our shutdown privilege. Since we are shutting down, don't // bother doing it for only the current thread and don't bother // disabling it afterwards. // BOOLEAN WasEnabled; NTSTATUS Status = RtlAdjustPrivilege( SE_SHUTDOWN_PRIVILEGE, TRUE, // enable FALSE, // this thread only? - No &WasEnabled); if (!NT_SUCCESS(Status)) { SC_LOG(ERROR, "RtlAdjustPrivilege failed! %#lx\n", Status); SC_ASSERT(0); } else { WCHAR wszShutdownText[128]; WCHAR wszPrintableText[128 + MAX_SERVICE_NAME_LENGTH]; if (LoadString(GetModuleHandle(NULL), IDS_SC_REBOOT_MESSAGE, wszShutdownText, LENGTH(wszShutdownText))) { wsprintf(wszPrintableText, wszShutdownText, _DisplayName); } else { // // If LoadString failed, it probably means the buffer // is too small to hold the localized string // SC_LOG(ERROR, "LoadString failed! %lu\n", GetLastError()); SC_ASSERT(FALSE); wszShutdownText[0] = L'\0'; } if (!InitiateSystemShutdownEx(NULL, // machine name wszPrintableText, // reboot message _Delay / 1000, // timeout in seconds TRUE, // force apps closed TRUE, // reboot SHTDN_REASON_MAJOR_SOFTWARE | SHTDN_REASON_MINOR_UNSTABLE)) { DWORD dwError = GetLastError(); // // If two services fail simultaneously and both are configured // to reboot the machine, InitiateSystemShutdown will fail all // calls past the first with ERROR_SHUTDOWN_IN_PROGRESS. We // don't want to log an event in this case. // if (dwError != ERROR_SHUTDOWN_IN_PROGRESS) { SC_LOG(ERROR, "InitiateSystemShutdown failed! %lu\n", dwError); ScLogRecoveryFailure( SC_ACTION_REBOOT, _DisplayName, dwError ); } } } delete this; } VOID CRunCommandContext::Perform( IN BOOLEAN fWaitStatus ) /*++ Routine Description: CODEWORK Share this code with ScLogonAndStartImage --*/ { // // Make sure we were called because of a timeout // SC_ASSERT(fWaitStatus == TRUE); DWORD status = NO_ERROR; HANDLE Token = NULL; PSID ServiceSid = NULL; // SID is returned only if not LocalSystem LPWSTR AccountName = NULL; SECURITY_ATTRIBUTES SaProcess; // Process security info (used only if not LocalSystem) STARTUPINFOW StartupInfo; PROCESS_INFORMATION ProcessInfo; RemoveDelayedWorkItem(); // // Get the Account Name for the service. A NULL Account Name means the // service is configured to run in the LocalSystem account. // status = ScLookupServiceAccount( _ServiceRecord->ServiceName, &AccountName ); // We only need to log on if it's not the LocalSystem account if (AccountName != NULL) { // // CODEWORK: Keep track of recovery EXEs spawned so we can // load/unload the user profile for the process. // status = ScLogonService( _ServiceRecord->ServiceName, AccountName, &Token, NULL, &ServiceSid ); if (status != NO_ERROR) { SC_LOG(ERROR, "CRunCommandContext: ScLogonService failed, %lu\n", status); goto Clean0; } SaProcess.nLength = sizeof(SECURITY_ATTRIBUTES); SaProcess.bInheritHandle = FALSE; SC_ACE_DATA AceData[] = { {ACCESS_ALLOWED_ACE_TYPE, 0, 0, PROCESS_ALL_ACCESS, &ServiceSid}, {ACCESS_ALLOWED_ACE_TYPE, 0, 0, PROCESS_SET_INFORMATION | PROCESS_TERMINATE | SYNCHRONIZE, &LocalSystemSid} }; NTSTATUS ntstatus = ScCreateAndSetSD( AceData, // AceData LENGTH(AceData), // AceCount NULL, // OwnerSid (optional) NULL, // GroupSid (optional) &SaProcess.lpSecurityDescriptor // pNewDescriptor ); LocalFree(ServiceSid); if (! NT_SUCCESS(ntstatus)) { SC_LOG(ERROR, "CRunCommandContext: ScCreateAndSetSD failed %#lx\n", ntstatus); status = RtlNtStatusToDosError(ntstatus); goto Clean1; } SC_LOG2(CONFIG_API,"CRunCommandContext: about to spawn recovery program in account %ws: %ws\n", AccountName, _FailureCommand); // // Impersonate the user so we don't give access to // EXEs that have been locked down for the account. // if (!ImpersonateLoggedOnUser(Token)) { status = GetLastError(); SC_LOG1(ERROR, "ScLogonAndStartImage: ImpersonateLoggedOnUser failed %d\n", status); goto Clean2; } // // Spawn the Image Process // ScInitStartupInfo(&StartupInfo, FALSE); if (!CreateProcessAsUserW( Token, // logon token NULL, // lpApplicationName _FailureCommand, // lpCommandLine &SaProcess, // process' security attributes NULL, // first thread's security attributes FALSE, // whether new process inherits handles CREATE_NEW_CONSOLE, // creation flags NULL, // environment block NULL, // current directory &StartupInfo, // startup info &ProcessInfo // process info )) { status = GetLastError(); SC_LOG(ERROR, "CRunCommandContext: CreateProcessAsUser failed %lu\n", status); RevertToSelf(); goto Clean2; } RevertToSelf(); } else { // // It's the LocalSystem account // // // If the process is to be interactive, set the appropriate flags. // BOOL bInteractive = FALSE; if (AccountName == NULL && _ServiceRecord->ServiceStatus.dwServiceType & SERVICE_INTERACTIVE_PROCESS) { bInteractive = ScAllowInteractiveServices(); if (!bInteractive) { // // Write an event to indicate that an interactive service // was started, but the system is configured to not allow // services to be interactive. // ScLogEvent(NEVENT_SERVICE_NOT_INTERACTIVE, _ServiceRecord->DisplayName); } } ScInitStartupInfo(&StartupInfo, bInteractive); SC_LOG1(CONFIG_API,"CRunCommandContext: about to spawn recovery program in " "the LocalSystem account: %ws\n", _FailureCommand); // // Spawn the Image Process // if (!CreateProcessW( NULL, // lpApplicationName _FailureCommand, // lpCommandLine NULL, // process' security attributes NULL, // first thread's security attributes FALSE, // whether new process inherits handles CREATE_NEW_CONSOLE, // creation flags NULL, // environment block NULL, // current directory &StartupInfo, // startup info &ProcessInfo // process info )) { status = GetLastError(); SC_LOG(ERROR, "CRunCommandContext: CreateProcess failed %lu\n", status); goto Clean2; } } SC_LOG0(CONFIG_API, "Recovery program spawned successfully.\n"); CloseHandle(ProcessInfo.hThread); CloseHandle(ProcessInfo.hProcess); Clean2: if (AccountName != NULL) { RtlDeleteSecurityObject(&SaProcess.lpSecurityDescriptor); } Clean1: if (AccountName != NULL) { CloseHandle(Token); } Clean0: if (status != NO_ERROR) { ScLogRecoveryFailure( SC_ACTION_RUN_COMMAND, _ServiceRecord->DisplayName, status ); } delete this; } VOID ScLogRecoveryFailure( IN SC_ACTION_TYPE ActionType, IN LPCWSTR ServiceDisplayName, IN DWORD Error ) /*++ Routine Description: --*/ { WCHAR wszActionString[50]; if (!LoadString(GetModuleHandle(NULL), IDS_SC_ACTION_BASE + ActionType, wszActionString, LENGTH(wszActionString))) { SC_LOG(ERROR, "LoadString failed %lu\n", GetLastError()); wszActionString[0] = L'\0'; } ScLogEvent( NEVENT_SERVICE_RECOVERY_FAILED, ActionType, wszActionString, (LPWSTR) ServiceDisplayName, Error ); }
31,699
8,939
// // main.cpp // TwoColor // // Created by mingyue on 2022/3/6. // Copyright © 2022 Gmingyue. All rights reserved. // #include <iostream> #include <vector> using namespace std; class Graph { public: vector<vector<int> *> * adj; Graph() { } Graph(int V) { this->V = V; this->E = 0; adj = new vector<vector<int> *>(this->V); for (int i = 0; i < V; i++) { adj->at(i) = new vector<int>(); } } ~Graph() { cout << "~Graph()" << endl; for (int i = 0; i < V; i++) { delete adj->at(i); } delete adj; } int getV() { return V; } int getE() { return E; } void addEdge(int v, int w) { adj->at(v)->push_back(w); adj->at(w)->push_back(v); E++; } void show() { for (int i = 0; i < adj->size(); i++) { cout << i << ":"; for (int j = 0; j < adj->at(i)->size(); j++) { cout << adj->at(i)->at(j) << " "; } cout << endl; } } private: int V; int E; }; class TwoColor { public: TwoColor() { } TwoColor(Graph * g) { marked = new vector<bool>(g->getV(), false); color = new vector<bool>(g->getV(), false); for (int s = 0; s < g->getV(); s++) { if (marked->at(s) == false) { dfs(g, s); } } } ~TwoColor() { cout << "~TwoColor()" << endl; delete marked; delete color; } bool getIsTwoColorable() { return isTwoColorable; } private: vector<bool> * marked; vector<bool> * color; bool isTwoColorable = true; void dfs(Graph * g, int v) { marked->at(v) = true; for (int w = 0; w < g->adj->at(v)->size(); w++) { if (marked->at(g->adj->at(v)->at(w)) == false) { color->at(g->adj->at(v)->at(w)) = !color->at(v); dfs(g, g->adj->at(v)->at(w)); } else if (color->at(g->adj->at(v)->at(w)) == color->at(v)) { isTwoColorable = false; } } } }; int main(int argc, const char * argv[]) { Graph * g = new Graph(4); g->addEdge(0, 1); g->addEdge(1, 2); g->addEdge(2, 3); g->addEdge(3, 0); // g->addEdge(1, 3); g->show(); TwoColor twoColor = TwoColor(g); cout << twoColor.getIsTwoColorable() << endl; delete g; return 0; }
2,517
938
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "androidadjusthelper.h" #include <QAndroidJniObject> #include <QString> void AndroidAdjustHelper::trackEvent(const QString& event) { QAndroidJniObject javaMessage = QAndroidJniObject::fromString(event); QAndroidJniObject::callStaticMethod<void>( "org/mozilla/firefox/vpn/qt/VPNAdjustHelper", "trackEvent", "(Ljava/lang/String;)V", javaMessage.object<jstring>()); }
597
194
/***************************************************************************************************************************** * Copyright 2020 Gabriel Gheorghe. All rights reserved. * This code is licensed under the BSD 3-Clause "New" or "Revised" License * License url: https://github.com/GabyForceQ/PolluxEngine/blob/master/LICENSE *****************************************************************************************************************************/ #include "Engine/enginepch.hpp" #include "BuildConfiguration.hpp" namespace Pollux::BuildSystem { BuildConfiguration::BuildConfiguration(BuildOptimization optimization) noexcept : optimization{ optimization } { } BuildConfiguration& BuildConfiguration::operator=(const BuildConfiguration& rhs) { projectName = rhs.projectName; projectPath = rhs.projectPath; buildOutputType = rhs.buildOutputType; preprocessorDefinitions = rhs.preprocessorDefinitions; includeDirectories = rhs.includeDirectories; bUsePrecompiledHeaders = rhs.bUsePrecompiledHeaders; precompiledHeaderName = rhs.precompiledHeaderName; bUseDebugLibraries = rhs.bUseDebugLibraries; wholeProgramOptimization = rhs.wholeProgramOptimization; bLinkIncremental = rhs.bLinkIncremental; functionLevelLinking = rhs.functionLevelLinking; bIntrinsicFunctions = rhs.bIntrinsicFunctions; bBufferSecurityCheck = rhs.bBufferSecurityCheck; bStringPooling = rhs.bStringPooling; bGenerateDebugInformation = rhs.bGenerateDebugInformation; bOptimizeReferences = rhs.bOptimizeReferences; bEnableCOMDATFolding = rhs.bEnableCOMDATFolding; return *this; } void BuildConfiguration::Reset() { projectName = ""; projectPath = ""; buildOutputType = BuildOutputType::None; preprocessorDefinitions.clear(); includeDirectories.clear(); bUsePrecompiledHeaders = false; precompiledHeaderName = ""; bUseDebugLibraries = false; wholeProgramOptimization = BuildBooleanType::None; bLinkIncremental = false; functionLevelLinking = BuildBooleanType::None; bIntrinsicFunctions = false; bBufferSecurityCheck = false; bStringPooling = false; bGenerateDebugInformation = false; bOptimizeReferences = false; bEnableCOMDATFolding = false; } }
2,469
646
#include "stdafx.h" #include "PhysicsComponent.h" #include "ComponentManager.h" #include "BoxCollider.h" /** * @brief Construct a new Physics Component:: Physics Component object * controls physics movements in the world * */ PhysicsComponent::PhysicsComponent() : minY(0), isRising(false), yPosFallDiff(0) { } PhysicsComponent::~PhysicsComponent() { } int PhysicsComponent::InitRootSignatureParameters(int indexOffset) { return 0; } void PhysicsComponent::Init() { } /** * @brief updates the node position with physics movements * */ void PhysicsComponent::Update() { ComponentManager* fullOwner = ComponentManager::GetOwner(owner); auto colliderComp = fullOwner->GetComponent(typeid(BoxCollider).name()); if (colliderComp != nullptr) { auto collider = ((BoxCollider*)colliderComp.get())->GetCollider(); if (XMVectorGetY(m_transform->position) - collider.Extents.y >= minY && !isRising) { if (previouslyRising) { previouslyRising = false; yPos = XMVectorGetY(m_transform->position); } // fall down yPosFallDiff *= yPosFallMultiplyer; yPos -= yPosFallDiff; m_transform->position = XMVectorSetY(m_transform->position, yPos); } // is going up if (isRising) { yPos = XMVectorGetY(m_transform->position); yPosFallDiff = yPosFallStart; previouslyRising = true; } // is under minY if (XMVectorGetY(m_transform->position) - collider.Extents.y <= minY) { yPos = minY; //put on top of minY yPosFallDiff = yPosFallStart; m_transform->position = XMVectorSetY(m_transform->position, minY + collider.Extents.y); } } else { if (XMVectorGetY(m_transform->position) >= minY && !isRising) { if (previouslyRising) { previouslyRising = false; yPos = XMVectorGetY(m_transform->position); } // fall down yPosFallDiff = yPosFallDiff * yPosFallMultiplyer + (yPosFallDiff); yPos -= yPosFallDiff; m_transform->position = XMVectorSetY(m_transform->position, yPos); } // is going up if (isRising) { yPos = XMVectorGetY(m_transform->position); yPosFallDiff = yPosFallStart; previouslyRising = true; } // is under minY if (XMVectorGetY(m_transform->position) <= minY) { yPos = minY; //put on top of minY yPosFallDiff = yPosFallStart; m_transform->position = XMVectorSetY(m_transform->position, minY); } } } void PhysicsComponent::Render() { } void PhysicsComponent::OnKeyDown(UINT key) { } void PhysicsComponent::OnKeyUp(UINT key) { } void PhysicsComponent::OnMouseMoved(float x, float y) { } void PhysicsComponent::OnDeviceRemoved() { } void PhysicsComponent::CreateWindowSizeDependentResources() { } void PhysicsComponent::CreateDeviceDependentResources() { }
2,695
1,050
/******************************************************************************* * tlx/string/appendline.cpp * * Part of tlx - http://panthema.net/tlx * * Copyright (C) 2019 Timo Bingmann <tb@panthema.net> * * All rights reserved. Published under the Boost Software License, Version 1.0 ******************************************************************************/ #include <tlx/string/appendline.hpp> #include <algorithm> namespace tlx { std::istream& appendline(std::istream& is, std::string& str, char delim) { size_t size = str.size(); size_t capacity = str.capacity(); std::streamsize rest = capacity - size; if (rest == 0) { // if rest is zero, already expand string capacity = std::max(static_cast<size_t>(8), capacity * 2); rest = capacity - size; } // give getline access to all of capacity str.resize(capacity); // get until delim or rest is filled is.getline(const_cast<char*>(str.data()) + size, rest, delim); // gcount includes the delimiter size_t new_size = size + is.gcount(); // is failbit set? if (!is) { // if string ran out of space, expand, and retry if (is.gcount() + 1 == rest) { is.clear(); str.resize(new_size); str.reserve(capacity * 2); return appendline(is, str, delim); } // else fall through and deliver error } else if (!is.eof()) { // subtract delimiter --new_size; } // resize string to fit its contents str.resize(new_size); return is; } } // namespace tlx /******************************************************************************/
1,690
509
#include <ros/ros.h> #include <omp.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/Image.h> #include <opencv2/core.hpp> #include <opencv2/highgui/highgui.hpp> ros::Publisher pub; ros::Subscriber sub; double radar_upgrade_time = 1632182400; void load_radar(cv::Mat raw_data, std::vector<int64_t> &timestamps, std::vector<float> &azimuths, std::vector<bool> &valid, cv::Mat &fft_data) { int encoder_size = 5600; int N = raw_data.rows; timestamps = std::vector<int64_t>(N, 0); azimuths = std::vector<float>(N, 0); valid = std::vector<bool>(N, true); int range_bins = raw_data.cols - 11; fft_data = cv::Mat::zeros(N, range_bins, CV_32F); #pragma omp parallel for (int i = 0; i < N; ++i) { uchar* byteArray = raw_data.ptr<uchar>(i); timestamps[i] = *((int64_t *)(byteArray)); azimuths[i] = *((uint16_t *)(byteArray + 8)) * 2 * M_PI / float(encoder_size); // std::cout << azimuths[i] << std::endl; valid[i] = byteArray[10] == 255; for (int j = 0; j < range_bins; j++) { fft_data.at<float>(i, j) = (float)*(byteArray + 11 + j) / 255.0; } } // std::cout << timestamps[0] << " " << timestamps[1] << std::endl; } float get_azimuth_index(std::vector<float> &azimuths, float azimuth) { float mind = 1000; float closest = 0; for (uint i = 0; i < azimuths.size(); ++i) { float d = fabs(azimuths[i] - azimuth); if (d < mind) { mind = d; closest = i; } } if (azimuths[closest] < azimuth) { float delta = (azimuth - azimuths[closest]) / (azimuths[closest + 1] - azimuths[closest]); closest += delta; } else if (azimuths[closest] > azimuth){ float delta = (azimuths[closest] - azimuth) / (azimuths[closest] - azimuths[closest - 1]); closest -= delta; } return closest; } void radar_polar_to_cartesian(std::vector<float> &azimuths, cv::Mat &fft_data, float radar_resolution, float cart_resolution, int cart_pixel_width, bool interpolate_crossover, cv::Mat &cart_img) { float cart_min_range = (cart_pixel_width / 2) * cart_resolution; if (cart_pixel_width % 2 == 0) cart_min_range = (cart_pixel_width / 2 - 0.5) * cart_resolution; cv::Mat map_x = cv::Mat::zeros(cart_pixel_width, cart_pixel_width, CV_32F); cv::Mat map_y = cv::Mat::zeros(cart_pixel_width, cart_pixel_width, CV_32F); #pragma omp parallel for collapse(2) for (int j = 0; j < map_y.cols; ++j) { for (int i = 0; i < map_y.rows; ++i) { map_y.at<float>(i, j) = -1 * cart_min_range + j * cart_resolution; } } #pragma omp parallel for collapse(2) for (int i = 0; i < map_x.rows; ++i) { for (int j = 0; j < map_x.cols; ++j) { map_x.at<float>(i, j) = cart_min_range - i * cart_resolution; } } cv::Mat range = cv::Mat::zeros(cart_pixel_width, cart_pixel_width, CV_32F); cv::Mat angle = cv::Mat::zeros(cart_pixel_width, cart_pixel_width, CV_32F); float azimuth_step = azimuths[1] - azimuths[0]; // float azimuth_step = (M_PI / 200); // azimuths[0] = 0; #pragma omp parallel for collapse(2) for (int i = 0; i < range.rows; ++i) { for (int j = 0; j < range.cols; ++j) { float x = map_x.at<float>(i, j); float y = map_y.at<float>(i, j); float r = (sqrt(pow(x, 2) + pow(y, 2)) - radar_resolution / 2) / radar_resolution; if (r < 0) r = 0; range.at<float>(i, j) = r; float theta = atan2f(y, x); if (theta < 0) theta += 2 * M_PI; // angle.at<float>(i, j) = get_azimuth_index(azimuths, theta); angle.at<float>(i, j) = (theta - azimuths[0]) / azimuth_step; } } if (interpolate_crossover) { cv::Mat a0 = cv::Mat::zeros(1, fft_data.cols, CV_32F); cv::Mat aN_1 = cv::Mat::zeros(1, fft_data.cols, CV_32F); for (int j = 0; j < fft_data.cols; ++j) { a0.at<float>(0, j) = fft_data.at<float>(0, j); aN_1.at<float>(0, j) = fft_data.at<float>(fft_data.rows-1, j); } cv::vconcat(aN_1, fft_data, fft_data); cv::vconcat(fft_data, a0, fft_data); angle = angle + 1; } cv::remap(fft_data, cart_img, range, angle, cv::INTER_LINEAR, cv::BORDER_CONSTANT, cv::Scalar(0, 0, 0)); } void callback(const sensor_msgs::ImageConstPtr & msg) { cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::MONO8); cv::Mat raw_data = cv_ptr->image; // Extract fft_data and relevant meta data std::vector<int64_t> timestamps; std::vector<float> azimuths; std::vector<bool> valid; cv::Mat polar_img; load_radar(raw_data, timestamps, azimuths, valid, polar_img); cv::Mat cart_img; float cart_resolution = 0.25; int cart_pixel_width = 1000; bool interpolate_crossover = true; float radar_resolution = 0.0596; double t = msg->header.stamp.toSec();; if (t > radar_upgrade_time) { radar_resolution = 0.04381; } radar_polar_to_cartesian(azimuths, polar_img, radar_resolution, cart_resolution, cart_pixel_width, interpolate_crossover, cart_img); // Convert to cartesian cv::Mat vis; cart_img.convertTo(vis, CV_8U, 255.0); cv_bridge::CvImage out_msg; out_msg.encoding = "mono8"; out_msg.image = vis; pub.publish(out_msg.toImageMsg()); } int main(int32_t argc, char** argv) { ros::init(argc, argv, "convert"); ros::NodeHandle nh; std::cout << omp_get_num_threads() << std::endl; pub = nh.advertise<sensor_msgs::Image>("/Navtech/Cartesian", 4); sub = nh.subscribe("/talker1/Navtech/Polar", 10, &callback); ros::spin(); return 0; }
5,743
2,411
// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license. #pragma once #include "Pomdog/Basic/Export.hpp" namespace Pomdog { class POMDOG_EXPORT Shader { public: virtual ~Shader() = default; }; } // namespace Pomdog
239
91
--- content/common/user_agent.cc.orig 2021-01-18 21:28:57 UTC +++ content/common/user_agent.cc @@ -213,6 +213,14 @@ std::string BuildOSCpuInfoFromOSVersionAndCpuType(cons ); #endif +#if defined(OS_BSD) +#if defined(__x86_64__) + base::StringAppendF(&os_cpu, "; Linux x86_64"); +#else + base::StringAppendF(&os_cpu, "; Linux i686"); +#endif +#endif + return os_cpu; }
381
181
#define RPC_HPP_CLIENT_IMPL #include "client.hpp" #include <iostream> #include <stdexcept> #include <string> int main(int argc, char* argv[]) { if (argc < 3) { std::cerr << "USAGE: rpc_client <server_ipv4> <port_num>\n"; return EXIT_FAILURE; } RpcClient client{ argv[1], argv[2] }; std::string currentFuncName; try { // Trivial function example { currentFuncName = "Sum"; const auto result = client.template call_func<int>("Sum", 1, 2); std::cout << "Sum(1, 2) == " << result << '\n'; } // Example of calling w/ references { currentFuncName = "AddOneToEach"; std::vector<int> vec{ 1, 2, 3, 4, 5 }; client.template call_func<void>("AddOneToEach", vec); std::cout << "AddOneToEach({ 1, 2, 3, 4, 5 }) == {"; for (size_t i = 0; i < vec.size() - 1; ++i) { std::cout << ' ' << vec[i] << ", "; } std::cout << ' ' << vec.back() << " }\n"; } // Template function example { currentFuncName = "GetTypeName<int>"; auto result = client.template call_func<std::string>("GetTypeName<int>"); std::cout << "GetTypeName<int>() == \"" << result << "\"\n"; currentFuncName = "GetTypeName<double>"; result = client.template call_func<std::string>("GetTypeName<double>"); std::cout << "GetTypeName<double>() == \"" << result << "\"\n"; currentFuncName = "GetTypeName<std::string>"; result = client.template call_func<std::string>("GetTypeName<std::string>"); std::cout << "GetTypeName<std::string>() == \"" << result << "\"\n"; } // Now shutdown the server { currentFuncName = "KillServer"; client.call_func("KillServer"); std::cout << "Server shutdown remotely...\n"; } return EXIT_SUCCESS; } catch (const std::exception& ex) { std::cerr << "Call to '" << currentFuncName << "' failed, reason: " << ex.what() << '\n'; return EXIT_FAILURE; } }
2,212
724
/* * * (C) Copyright IBM Corp. and others 1998-2013 - All Rights Reserved * */ #include "LETypes.h" #include "MorphTables.h" #include "SubtableProcessor2.h" #include "NonContextualGlyphSubst.h" #include "NonContextualGlyphSubstProc2.h" #include "TrimmedArrayProcessor2.h" #include "LEGlyphStorage.h" #include "LESwaps.h" U_NAMESPACE_BEGIN UOBJECT_DEFINE_RTTI_IMPLEMENTATION(TrimmedArrayProcessor2) TrimmedArrayProcessor2::TrimmedArrayProcessor2() { } TrimmedArrayProcessor2::TrimmedArrayProcessor2(const LEReferenceTo<MorphSubtableHeader2> &morphSubtableHeader, LEErrorCode &success) : NonContextualGlyphSubstitutionProcessor2(morphSubtableHeader, success) { const LEReferenceTo<NonContextualGlyphSubstitutionHeader2> header(morphSubtableHeader, success); trimmedArrayLookupTable = LEReferenceTo<TrimmedArrayLookupTable>(morphSubtableHeader, success, &header->table); firstGlyph = SWAPW(trimmedArrayLookupTable->firstGlyph); lastGlyph = firstGlyph + SWAPW(trimmedArrayLookupTable->glyphCount); valueArray = LEReferenceToArrayOf<LookupValue>(morphSubtableHeader, success, &trimmedArrayLookupTable->valueArray[0], LE_UNBOUNDED_ARRAY); } TrimmedArrayProcessor2::~TrimmedArrayProcessor2() { } void TrimmedArrayProcessor2::process(LEGlyphStorage &glyphStorage, LEErrorCode &success) { if(LE_FAILURE(success)) return; le_int32 glyphCount = glyphStorage.getGlyphCount(); le_int32 glyph; for (glyph = 0; glyph < glyphCount; glyph += 1) { LEGlyphID thisGlyph = glyphStorage[glyph]; TTGlyphID ttGlyph = (TTGlyphID) LE_GET_GLYPH(thisGlyph); if ((ttGlyph > firstGlyph) && (ttGlyph < lastGlyph)) { TTGlyphID newGlyph = SWAPW(valueArray(ttGlyph - firstGlyph, success)); glyphStorage[glyph] = LE_SET_GLYPH(thisGlyph, newGlyph); } } } U_NAMESPACE_END
1,851
682
#include<bits/stdc++.h> using namespace std; typedef long long ll; int main() { // freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout); int t; cin>>t; int n; int ara[111]; while(t--) { int i; scanf("%d", &n); for(int i=1; i<=n; i++) scanf("%d", &ara[i]); int ans=1; if( !(n&1)) ans=0; else { for(i=1; i<=(n>>1)+1; i++ ) { if(ara[i]!= i) { ans=0; break; } } for(i; i<=n; i++) { if(ara[i]!= n-i+1) { ans=0; break; } // cnt--; } } if(ans) printf("yes\n"); else printf("no\n"); } return 0; }
893
334
#include <iostream> #include <iomanip> #include <string> #include <sstream> using namespace std; int main() { stringstream ss; ss << "there are " << 9 << "apple in my cart"; cout << ss.str() << endl; ss.str(""); ss << showbase << hex << 16; cout << "ss = " << ss.str() << endl; ss.str(""); ss << 3.14; cout << "ss = " << ss.str() << endl; }
353
148
#include <iostream> #include <queue> using namespace std; int main(){ // declaring max pqueue priority_queue<int> maxpq; // declaring min pqueue // any container which supports the following opreations can be used to implement priority_queue // empty(), push_back(), size(), pop_back(), front() // replace the container you want in place of vector priority_queue<int, vector<int>, greater<int>> minpq; // operations on max pq // inserting a new element into priority queue maxpq.push(10); maxpq.push(20); maxpq.push(30); // getting top element cout << "maxpq top element: " << maxpq.top() << "\n"; // removing top element which is the highest value element maxpq.pop(); // operations on minpq minpq.push(30); minpq.push(100); minpq.push(25); minpq.push(40); // getting the top element cout << "minpq top element: " << minpq.top() << "\n"; return 0; } /* maxpqueue is a container adaptor heap property is always maintained first element is always the greatest element (max maxpqueue) internally uses functions of heap like make_heap, push_heap and pop_heap to maintain heap structure */ /* */
1,196
380
#include "Precompiled.h" #include "WorldIO.h" #include "World.h" namespace { std::string ToString(const Vishv::Math::Shapes::Capsule& cap) { std::string txt; txt += "Position: " + cap.mTransform.Position().ToString() + "\n"; txt += "Rotation: " + cap.mTransform.Rotation().ToString() + "\n"; txt += "Radius: " + std::to_string(cap.mRadius) + "\n"; txt += "Height: " + std::to_string(cap.GetHeight()) + "\n"; return std::move(txt); } std::string ToString(const Vishv::Math::Shapes::Cuboid& c) { std::string txt; txt += "Position: " + c.mTransform.Position().ToString() + "\n"; txt += "Rotation: " + c.mTransform.Rotation().ToString() + "\n"; txt += "LengthX: " + std::to_string(c.GetLengthX()) + "\n"; txt += "LengthY: " + std::to_string(c.GetLengthY()) + "\n"; txt += "LengthZ: " + std::to_string(c.GetLengthZ()) + "\n"; return std::move(txt); } } void Vishv::AI::WorldIO::Save(std::filesystem::path path, const World & world) { std::fstream file; file.open(path, std::ios::out); file.close(); file.open(path); if (!file.is_open()) return; file << "NumberObstacles: " << world.GetObstacles().size() << std::endl; file << "NumberWalls: " << world.GetWalls().size() << std::endl; for (size_t i = 0; i < world.GetObstacles().size(); ++i) file << ToString(world.GetObstacles()[i]); for (size_t i = 0; i < world.GetWalls().size(); ++i) file << ToString(world.GetWalls()[i]); } void Vishv::AI::WorldIO::Load(std::filesystem::path path, World & world) { std::fstream file; file.close(); file.open(path); if (!file.is_open()) return; size_t maxObs, maxWall; std::string holder; file >> holder >> maxObs >> holder >> maxWall; world.GetObstacles().reserve(maxObs); world.GetWalls().reserve(maxWall); for (size_t i = 0; i < maxObs; ++i) { World::Obstacle obs; Math::Vector3 pr; Math::Quaternion q; file >> holder >> pr.x >> pr.y >> pr.z; obs.mTransform.mPosition = pr; file >> holder >> q.w >> q.x >> q.y >> q.z; obs.mTransform.SetRotation(std::move(q)); float h; file >> holder >> obs.mRadius >> holder >> h; obs.SetHeight(h); world.Register(obs); } for (size_t i = 0; i < maxWall; ++i) { World::Wall wall; Math::Vector3 pr; Math::Quaternion q; file >> holder >> pr.x >> pr.y >> pr.z; wall.mTransform.mPosition = pr; file >> holder >> q.w >> q.x >> q.y >> q.z; wall.mTransform.SetRotation(std::move(q)); file >> holder >> pr.x >> holder >> pr.y >> holder >> pr.z; wall.SetLengthX(pr.x); wall.SetLengthY(pr.y); wall.SetLengthZ(pr.z); world.Register(wall); } }
2,575
1,092
/**************************************************************************** ** $Id: glbox.cpp,v 1.1.2.3 1999/02/01 12:17:42 aavit Exp $ ** ** Implementation of GLBox ** This is a simple QGLWidget displaying a box ** ** The OpenGL code is mostly borrowed from Brian Pauls "spin" example ** in the Mesa distribution ** ****************************************************************************/ #include "glbox.h" #include <math.h> /*! Create a GLBox widget */ GLBox::GLBox( QWidget* parent, const char* name, const QGLWidget* shareWidget ) : QGLWidget( parent, name, shareWidget ) { xRot = yRot = zRot = 0.0; // default object rotation scale = 1.5; // default object scale } /*! Create a GLBox widget */ GLBox::GLBox( const QGLFormat& format, QWidget* parent, const char* name, const QGLWidget* shareWidget ) : QGLWidget( format, parent, name, shareWidget ) { xRot = yRot = zRot = 0.0; // default object rotation scale = 1.5; // default object scale } /*! Release allocated resources */ GLBox::~GLBox() { glDeleteLists( object, 1 ); } /*! Set up the OpenGL rendering state, and define display list */ void GLBox::initializeGL() { glClearColor( 0.0, 0.5, 0.0, 0.0 ); // Let OpenGL clear to green object = makeObject(); // Make display list glEnable( GL_DEPTH_TEST ); } /*! Set up the OpenGL view port, matrix mode, etc. */ void GLBox::resizeGL( int w, int h ) { glViewport( 0, 0, (GLint)w, (GLint)h ); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glFrustum(-1.0, 1.0, -1.0, 1.0, 1.0, 200.0); } /*! Paint the box. The actual openGL commands for drawing the box are performed here. */ void GLBox::paintGL() { glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glTranslatef( 0.0, 0.0, -3.0 ); glScalef( scale, scale, scale ); glRotatef( xRot, 1.0, 0.0, 0.0 ); glRotatef( yRot, 0.0, 1.0, 0.0 ); glRotatef( zRot, 0.0, 0.0, 1.0 ); glCallList( object ); } /*! Generate an OpenGL display list for the object to be shown, i.e. the box */ GLuint GLBox::makeObject() { GLuint list; list = glGenLists( 1 ); glNewList( list, GL_COMPILE ); GLint i, j, rings, sides; float theta1, phi1, theta2, phi2; float v0[03], v1[3], v2[3], v3[3]; float t0[03], t1[3], t2[3], t3[3]; float n0[3], n1[3], n2[3], n3[3]; float innerRadius=0.4; float outerRadius=0.8; float scalFac; double pi = 3.14159265358979323846; rings = 8; sides = 10; scalFac=1/(outerRadius*2); for (i = 0; i < rings; i++) { theta1 = (float)i * 2.0 * pi / rings; theta2 = (float)(i + 1) * 2.0 * pi / rings; for (j = 0; j < sides; j++) { phi1 = (float)j * 2.0 * pi / sides; phi2 = (float)(j + 1) * 2.0 * pi / sides; v0[0] = cos(theta1) * (outerRadius + innerRadius * cos(phi1)); v0[1] = -sin(theta1) * (outerRadius + innerRadius * cos(phi1)); v0[2] = innerRadius * sin(phi1); v1[0] = cos(theta2) * (outerRadius + innerRadius * cos(phi1)); v1[1] = -sin(theta2) * (outerRadius + innerRadius * cos(phi1)); v1[2] = innerRadius * sin(phi1); v2[0] = cos(theta2) * (outerRadius + innerRadius * cos(phi2)); v2[1] = -sin(theta2) * (outerRadius + innerRadius * cos(phi2)); v2[2] = innerRadius * sin(phi2); v3[0] = cos(theta1) * (outerRadius + innerRadius * cos(phi2)); v3[1] = -sin(theta1) * (outerRadius + innerRadius * cos(phi2)); v3[2] = innerRadius * sin(phi2); n0[0] = cos(theta1) * (cos(phi1)); n0[1] = -sin(theta1) * (cos(phi1)); n0[2] = sin(phi1); n1[0] = cos(theta2) * (cos(phi1)); n1[1] = -sin(theta2) * (cos(phi1)); n1[2] = sin(phi1); n2[0] = cos(theta2) * (cos(phi2)); n2[1] = -sin(theta2) * (cos(phi2)); n2[2] = sin(phi2); n3[0] = cos(theta1) * (cos(phi2)); n3[1] = -sin(theta1) * (cos(phi2)); n3[2] = sin(phi2); t0[0] = v0[0]*scalFac + 0.5; t0[1] = v0[1]*scalFac + 0.5; t0[2] = v0[2]*scalFac + 0.5; t1[0] = v1[0]*scalFac + 0.5; t1[1] = v1[1]*scalFac + 0.5; t1[2] = v1[2]*scalFac + 0.5; t2[0] = v2[0]*scalFac + 0.5; t2[1] = v2[1]*scalFac + 0.5; t2[2] = v2[2]*scalFac + 0.5; t3[0] = v3[0]*scalFac + 0.5; t3[1] = v3[1]*scalFac + 0.5; t3[2] = v3[2]*scalFac + 0.5; glColor3f( (GLfloat) ((i+j) % 2), (GLfloat) 0.0, (GLfloat) 0.0 ); glBegin(GL_POLYGON); glNormal3fv(n3); glTexCoord3fv(t3); glVertex3fv(v3); glNormal3fv(n2); glTexCoord3fv(t2); glVertex3fv(v2); glNormal3fv(n1); glTexCoord3fv(t1); glVertex3fv(v1); glNormal3fv(n0); glTexCoord3fv(t0); glVertex3fv(v0); glEnd(); } } glEndList(); return list; } /*! Set the rotation angle of the object to \e degrees around the X axis. */ void GLBox::setXRotation( int degrees ) { xRot = (GLfloat)(degrees % 360); updateGL(); } /*! Set the rotation angle of the object to \e degrees around the Y axis. */ void GLBox::setYRotation( int degrees ) { yRot = (GLfloat)(degrees % 360); updateGL(); } /*! Set the rotation angle of the object to \e degrees around the Z axis. */ void GLBox::setZRotation( int degrees ) { zRot = (GLfloat)(degrees % 360); updateGL(); } /*! Sets the rotation angles of this object to that of \a fromBox */ void GLBox::copyRotation( const GLBox& fromBox ) { xRot = fromBox.xRot; yRot = fromBox.yRot; zRot = fromBox.zRot; }
5,891
2,437
#include "muduo/base/common/logfile.h" #include "muduo/base/common/logging.h" #include "muduo/base/common/file_util.h" #include "muduo/base/common/process_info.h" #include "define/define_new.h" #include <assert.h> #include <cstdio> #include <cstring> #include <ctime> #include <libgen.h> using namespace muduo; std::string LogFile::s_fileDir = "log/"; std::unique_ptr<muduo::LogFile> g_logFile; void outputFunc(const CHAR* msg, SDWORD len) { g_logFile->append(msg, len); } void flushFunc() { g_logFile->flush(); } LogFile::LogFile(const std::string& basename, off_t rollSize, bool threadSafe, SDWORD flushInterval, SDWORD checkEveryN) : m_basename(basename) , m_rollSize(rollSize) , m_flushInterval(flushInterval) , m_checkEveryN(checkEveryN) , m_count(0) , m_mutex(threadSafe ? NEW MutexLock : nullptr) , m_startOfPeriod(0) , m_lastRoll(0) , m_lastFlush(0) { assert(basename.find('/') == std::string::npos); RollFile(); } LogFile::~LogFile() = default; void LogFile::append(const CHAR* logline, SDWORD len) { if (m_mutex) { MutexLockGuard lock(*m_mutex); append_unlocked(logline, len); } else { append_unlocked(logline, len); } } void LogFile::flush() { if (m_mutex) { MutexLockGuard lock(*m_mutex); m_file->flush(); } else { m_file->flush(); } } void LogFile::append_unlocked(const CHAR* logline, SDWORD len) { m_file->append(logline, len); if (m_file->getWrittenBytes() > m_rollSize) { RollFile(); } else { ++ m_count; if (m_count >= m_checkEveryN) { m_count = 0; time_t now = ::time(nullptr); time_t thisPeriod = now / kRollPerSeconds * kRollPerSeconds; if (thisPeriod != m_startOfPeriod) { RollFile(); } else if (now - m_lastFlush > m_flushInterval) { m_lastFlush = now; m_file->flush(); } } } } bool LogFile::RollFile() { time_t now = 0; std::string filename = getLogFileName(m_basename, &now); time_t start = now / kRollPerSeconds * kRollPerSeconds; if (now > m_lastRoll) { m_lastRoll = now; m_lastFlush = now; m_startOfPeriod = start; m_file.reset(NEW FileUtil::AppendFile(LogFile::s_fileDir + filename)); return true; } return false; } void LogFile::SetLogFile(const char* exePath, const char* baseName, off_t rollSize) { g_logFile.reset(NEW muduo::LogFile(baseName, rollSize)); muduo::Logger::setOutputFunc(outputFunc); muduo::Logger::setFlushFunc(flushFunc); } void LogFile::setLogFileDir(const char* fileDir) { s_fileDir = ::dirname(const_cast<char*>(fileDir)); s_fileDir += "/log/"; } std::string LogFile::getLogFileName(const std::string& basename, time_t* now) { std::string filename; filename.reserve(basename.size() + 64); filename = basename; CHAR timebuf[32]; struct tm tm; *now = time(nullptr); //gmtime_r(now, &tm); // FIXME: localtime_r ? localtime_r(now, &tm); strftime(timebuf, sizeof timebuf, "_%Y%m%d_%H%M%S_", &tm); filename += timebuf; // filename += ProcessInfo::hostname(); CHAR pidbuf[32]; snprintf(pidbuf, sizeof pidbuf, "%d", ProcessInfo::pid()); filename += pidbuf; filename += ".log"; return filename; }
3,279
1,277
#include <iostream> #include <string> #include "sockettf.h" #include <anet/anet.h> #include <unistd.h> #include <anet/serversocket.h> #include <anet/log.h> #include <signal.h> using namespace std; namespace anet { CPPUNIT_TEST_SUITE_REGISTRATION(SocketTF); class PlainConnectRunnable : public Runnable { public: void run(Thread* thread, void *args) { Socket *socket = (Socket *) args; CPPUNIT_ASSERT(socket); CPPUNIT_ASSERT(socket->connect()); } }; struct SocketPair { ServerSocket * serverSocket; Socket *acceptedSocket; }; class PlainServerRunnable : public Runnable { public: void run(Thread* thread, void *args) { SocketPair *sockpair = (SocketPair*)args; CPPUNIT_ASSERT(sockpair->serverSocket); sockpair->acceptedSocket = sockpair->serverSocket->accept(); CPPUNIT_ASSERT(sockpair->acceptedSocket); } }; struct PlainReadArgs { Socket *socket; char * buffer; int bytes; int bytesRead; }; class PlainReadRunnable : public Runnable { public: void run(Thread* thread, void *args) { PlainReadArgs *myArgs = static_cast<PlainReadArgs*> (args); myArgs->bytesRead = myArgs->socket->read(myArgs->buffer, myArgs->bytes); } }; void SocketTF::setUp() { } void SocketTF::tearDown() { } void SocketTF::testSetGetAddress() { Socket socket; char result[32]; string expect; //testing invalid address CPPUNIT_ASSERT(!socket.setAddress("NoSushAddress.james.zhang",12345)); CPPUNIT_ASSERT(socket.setAddress(NULL, 12345)); CPPUNIT_ASSERT(socket.getAddr(result, 10)); CPPUNIT_ASSERT_EQUAL(string("0.0.0.0:1"), string(result)); CPPUNIT_ASSERT(socket.setAddress("", 0)); CPPUNIT_ASSERT(socket.setAddress("localhost", 12345)); CPPUNIT_ASSERT(socket.getAddr(result, 32)); CPPUNIT_ASSERT_EQUAL(string("127.0.0.1:12345"), string(result)); CPPUNIT_ASSERT(socket.setAddress("127.0.0.1", -1)); CPPUNIT_ASSERT(socket.getAddr(result, 32)); CPPUNIT_ASSERT_EQUAL(string("127.0.0.1:65535"), string(result)); CPPUNIT_ASSERT(socket.setAddress("202.165.102.205", 12345)); CPPUNIT_ASSERT(socket.setAddress("www.yahoo.com", 12345)); CPPUNIT_ASSERT(socket.setAddress("g.cn", 12345)); } void SocketTF::testReadWrite() { Socket socket; ServerSocket serverSocket; char data[]="Some Data"; char output[1024]; CPPUNIT_ASSERT_EQUAL(-1,socket.write(data, strlen(data))); CPPUNIT_ASSERT(socket.setAddress("localhost", 11234)); CPPUNIT_ASSERT(serverSocket.setAddress("localhost", 11234)); CPPUNIT_ASSERT(serverSocket.listen()); SocketPair socketPair; socketPair.serverSocket=&serverSocket; Thread tc, ts; PlainConnectRunnable pcr; PlainServerRunnable psr; tc.start(&pcr,&socket);//connect ts.start(&psr,&socketPair);//accept ts.join(); tc.join(); Socket *acceptedSocket = socketPair.acceptedSocket; acceptedSocket->setSoBlocking(false); socket.setSoBlocking(false); CPPUNIT_ASSERT(acceptedSocket); CPPUNIT_ASSERT_EQUAL(9, socket.write(data, strlen(data))); CPPUNIT_ASSERT_EQUAL(9, acceptedSocket->read(output, 10)); CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->read(NULL, 3)); CPPUNIT_ASSERT_EQUAL(string(data, 9), string(output, 9)); CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->read(output,10)); CPPUNIT_ASSERT_EQUAL(EAGAIN, Socket::getLastError()); CPPUNIT_ASSERT_EQUAL(3, socket.write(data, 3)); CPPUNIT_ASSERT_EQUAL(3, acceptedSocket->read(output, 10)); CPPUNIT_ASSERT_EQUAL(4, acceptedSocket->write(data, 4)); CPPUNIT_ASSERT_EQUAL(4, socket.read(output, 10)); CPPUNIT_ASSERT_EQUAL(string(data, 4), string(output, 4)); CPPUNIT_ASSERT_EQUAL(-1, socket.write(NULL, 3)); CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->read(NULL, 3)); acceptedSocket->close(); CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->read(output, 10)); CPPUNIT_ASSERT_EQUAL(0, socket.read(output,3)); /**@note: we can write to socket whose peer was closed*/ CPPUNIT_ASSERT_EQUAL(3, socket.write(data,3)); delete acceptedSocket; socket.close(); CPPUNIT_ASSERT_EQUAL(-1, socket.write(data, 3)); tc.start(&pcr,&socket);//connect ts.start(&psr,&socketPair);//accept ts.join(); tc.join(); acceptedSocket = socketPair.acceptedSocket; acceptedSocket->setSoBlocking(false); CPPUNIT_ASSERT(acceptedSocket); acceptedSocket->shutdown(); CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->read(output, 10)); signal(SIGPIPE, SIG_IGN); CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->write(data, 10)); /** * @todo need to handle socket shutdown? * CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->read(output, 10)); * CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->write(data, 10)); */ socket.close(); delete acceptedSocket; CPPUNIT_ASSERT(socket.createUDP()); CPPUNIT_ASSERT_EQUAL(-1, socket.write(data, 3)); CPPUNIT_ASSERT(socket.setAddress("localhost",22)); CPPUNIT_ASSERT(socket.connect()); CPPUNIT_ASSERT_EQUAL(5, socket.write(data, 5)); /** * @todo need more UDP interface * CPPUNIT_ASSERT_EQUAL(string("Need More"), string("UDP Interface")); */ socket.close(); serverSocket.close(); acceptedSocket->close(); } void SocketTF::testConnect() { char data[] = "Short Data"; char output[256]; Socket socket; CPPUNIT_ASSERT(!socket.connect()); CPPUNIT_ASSERT(socket.setAddress("localhost",12346)); CPPUNIT_ASSERT(!socket.connect()); ServerSocket serverSocket; ServerSocket serverSocket2; CPPUNIT_ASSERT(!serverSocket.listen()); CPPUNIT_ASSERT(serverSocket.setAddress("localhost",12346)); CPPUNIT_ASSERT(serverSocket2.setAddress("localhost",12346)); CPPUNIT_ASSERT(serverSocket.listen()); CPPUNIT_ASSERT(serverSocket.setSoBlocking(false)); CPPUNIT_ASSERT(!serverSocket2.listen()); CPPUNIT_ASSERT(socket.connect()); CPPUNIT_ASSERT(socket.setSoBlocking(false)); /** * @todo should we detect if no body accept()? * CPPUNIT_ASSERT_EQUAL(-1, socket.write(data,3)); */ CPPUNIT_ASSERT_EQUAL(3, socket.write(data,3)); Socket *acceptedSocket = serverSocket.accept(); CPPUNIT_ASSERT(acceptedSocket); CPPUNIT_ASSERT(acceptedSocket->setSoBlocking(false)); ANET_LOG(DEBUG,"Before acceptedSocket->read(output,256)"); CPPUNIT_ASSERT_EQUAL(3, acceptedSocket->read(output,256)); ANET_LOG(DEBUG,"After acceptedSocket->read(output,256)"); CPPUNIT_ASSERT_EQUAL(string(data,3), string(output,3)); ANET_LOG(DEBUG,"Before serverSocket.accept()"); Socket *acceptedSocket2 = serverSocket.accept(); ANET_LOG(DEBUG,"After serverSocket.accept()"); CPPUNIT_ASSERT(!acceptedSocket2); delete acceptedSocket; acceptedSocket = NULL; CPPUNIT_ASSERT(socket.reconnect()); acceptedSocket2 = serverSocket.accept(); CPPUNIT_ASSERT(acceptedSocket2); CPPUNIT_ASSERT(acceptedSocket2->setSoBlocking(true)); Thread thread; PlainReadRunnable readRunnable; PlainReadArgs args; args.socket = acceptedSocket2; args.buffer = output; args.bytes = 8; thread.start(&readRunnable, &args); socket.setTcpNoDelay(true); sleep(1); CPPUNIT_ASSERT_EQUAL(3, socket.write(data,3)); CPPUNIT_ASSERT_EQUAL(5, socket.write(data+3, 5)); thread.join(); /**Blocking read will be blocked when there is no data to read! * So we should expect args.bytes > 0*/ CPPUNIT_ASSERT(args.bytesRead > 0); CPPUNIT_ASSERT_EQUAL(string(data,args.bytesRead), string(output,args.bytesRead)); delete acceptedSocket2; } void SocketTF::testListenZeroIPZeroPort() { ANET_LOG(DEBUG, "testListenZeroIPZeroPort"); ServerSocket server; CPPUNIT_ASSERT(server.setAddress("0.0.0.0", 0)); char result[32]; CPPUNIT_ASSERT(server.getAddr(result, 32)); CPPUNIT_ASSERT_EQUAL(string("0.0.0.0:0"), string(result)); CPPUNIT_ASSERT(!server.getAddr(result, 32, true)); CPPUNIT_ASSERT(server.listen()); CPPUNIT_ASSERT(server.getAddr(result, 32, true)); ANET_LOG(DEBUG, "active address: %s", result); CPPUNIT_ASSERT(string("0.0.0.0:0") != string(result)); } }
8,237
3,112
#include <sstream> #include <cassert> #include "structures/congruence_atom.h" #define CA theorysolver::CongruenceAtom #define SPCA std::shared_ptr<CA> using namespace theorysolver; Term::Term(unsigned int symbol_id) : type(Term::SYMBOL), symbol_id(symbol_id), function_name(), arguments() { } Term::Term(std::string function_name, std::vector<std::shared_ptr<Term>> arguments) : type(Term::FUNCTION), symbol_id(0), function_name(function_name), arguments(arguments) { } Term::Term(const Term &t) : type(t.type), symbol_id(t.symbol_id), function_name(t.function_name), arguments(t.arguments) { } std::string Term::to_string() const { if (this->type == Term::SYMBOL) return "x" + std::to_string(this->symbol_id); else { std::ostringstream oss; oss << this->function_name + "("; for (unsigned i=0; i<this->arguments.size(); i++) { if (i) oss << ", "; oss << "x" + this->arguments[i]->to_string(); } oss << ")"; return oss.str(); } } bool CongruenceAtom::is_atom_variable(std::string variable) { return variable.c_str()[0] == '#'; } bool CongruenceAtom::is_atom_literal(const std::map<int, std::string> &literal_to_name, unsigned int literal) { return CongruenceAtom::is_atom_variable(literal_to_name.at(literal)); } unsigned int CongruenceAtom::atom_id_from_literal(const std::map<int, std::string> &variable_to_name, unsigned int literal) { unsigned int atom_id; atom_id = atoi(variable_to_name.at(literal).c_str()+1); return atom_id; } std::string CongruenceAtom::variable_name_from_atom_id(unsigned long int atom_id) { return "#" + std::to_string(atom_id); } int CongruenceAtom::literal_from_atom_id(const std::map<std::string, int> &name_to_variable, unsigned int atom_id) { return name_to_variable.at("#" + std::to_string(atom_id)); } SPCA CongruenceAtom::SPCA_from_literal(const CA_list &literal_to_CA, std::map<int, std::string> &variable_to_name, unsigned int literal) { unsigned int atom_id = CongruenceAtom::atom_id_from_literal(variable_to_name, literal); assert(atom_id > 0); assert(atom_id <= literal_to_CA.size()); return literal_to_CA[atom_id-1]; } long unsigned int CongruenceAtom::add_CA(CA_list &literal_to_CA, Term &left, Operator op, Term &right) { literal_to_CA.push_back(SPCA(new CA(std::shared_ptr<Term>(new Term(left)), op, std::shared_ptr<Term>(new Term(right))))); return literal_to_CA.size(); } std::shared_ptr<CongruenceAtom> CongruenceAtom::SPCA_from_variable(const CA_list &literal_to_CA, std::string variable) { return literal_to_CA[atoi(variable.c_str()+1)-1]; } bool Term::operator==(const Term &that) const { if (this->type != that.type) return false; else if (this->type == Term::SYMBOL) return this->symbol_id == that.symbol_id; else if (this->type == Term::FUNCTION) { if (this->arguments.size() != that.arguments.size()) return false; if (this->function_name != that.function_name) return false; for (unsigned i=0; i<this->arguments.size(); i++) if (!(this->arguments[i] == that.arguments[i])) return false; return true; } else assert(false); } CongruenceAtom::CongruenceAtom(std::shared_ptr<Term> left, enum Operator op, std::shared_ptr<Term> right) : left(left), right(right), op(op), canonical(NULL) { } std::string CongruenceAtom::to_string() const { return this->left->to_string() + (this->op == CongruenceAtom::EQUAL ? "=" : "!=") + this->right->to_string(); }
3,617
1,267
// Copyright 2020 Your Name <your_email> #include <gmock/gmock.h> #include <page_container.hpp> #include "stat_sender_test.hpp" #include <used_memory.hpp> TEST(MemoryUsage, MemUsingTest) { std::vector<std::string> old_raw_data{ "first" }, new_raw_data { "first", "second", "third", "fourth" }; used_memory memory; memory.on_raw_data_load(old_raw_data, new_raw_data); EXPECT_EQ(memory.used(), 45); memory.clear(); std::vector<item> old_data{}, new_data{ {1, "rand", 10}, {2, "rand", 20}, {3, "rand", 30} }; memory.on_data_load(old_data, new_data); EXPECT_EQ(memory.used(), 69); } void prepare_stringstream(std::stringstream& ss, size_t lines = 20){ for (size_t i = 0; i < lines; ++i) { ss << (i + 1) << " cor " << (i < 6 ? 25 : 50) << '\n'; } ss << 21 << " inc " << "ls" << '\n'; ss << 22 << " inc " << "la" << '\n'; } TEST(PageContainer_Test, Data_Test) { srand(time(nullptr)); std::stringstream ss{}; prepare_stringstream(ss); page_container page; page.load_raw_data(ss); page.load_data(0); EXPECT_EQ(page.data_size(), 20); } TEST(PageContainer_Test, AsyncSend_Test) { using ::testing::_; using ::testing::AtLeast; srand(time(nullptr)); std::stringstream ss{}; prepare_stringstream(ss); used_memory* used = new used_memory(); mock_stat_sender* sender = new mock_stat_sender(); page_container<mock_stat_sender> page(used, sender); page.load_raw_data(ss); EXPECT_CALL(*sender, async_send(_, std::string_view{"/items/loaded"})) .Times(2); EXPECT_CALL(*sender, async_send(_, std::string_view{"/items/skipped"})) .Times(12); page.load_data(0); page.load_data(30); } TEST(PageContainer_Test, AlreadySeen){ std::stringstream ss{}; prepare_stringstream(ss); ss << 20 << " cop " << 20 << '\n'; page_container page{}; page.load_raw_data(ss); EXPECT_THROW(page.load_data(0), std::runtime_error); } TEST(PageContainer_Test, EmptyFile){ std::ifstream file_{"empty.txt"}; std::ofstream empty{"empty.txt"}; page_container page{}; EXPECT_THROW(page.load_raw_data(file_), std::runtime_error); empty.close(); } TEST(PageContainer_Test, CorruptedFile){ std::ifstream file_; file_.close(); page_container page{}; EXPECT_THROW(page.load_raw_data(file_), std::runtime_error); } TEST(PageContainer_Test, TooSmallInputStream){ std::stringstream ss{}; prepare_stringstream(ss, 5); page_container page{}; EXPECT_THROW(page.load_raw_data(ss), std::runtime_error); } TEST(PageContainer_Test, TooSmallInputStream_LoadData){ std::stringstream ss{}; prepare_stringstream(ss); page_container page{}; page.load_raw_data(ss); EXPECT_THROW(page.load_data(1000),std::runtime_error); }
2,670
1,049
/* * guess number */ #include <iostream> using namespace std; int main() { int input; cin >> input; input *= 1001; input /= 7 * 11 * 13; cout << input; return 0; }
179
78
#pragma once #include <Geometry2d/Point.hpp> #include "planning/MotionConstraints.hpp" namespace Planning { /** * @brief A spatial path with no time or angle information. */ class BezierPath { public: /** * @brief Construct a bezier path for a curve with a given velocity, going * through the specified points and with specified velocity at endpoints. * * @param points The points through which the final curve must pass. These * will be used as the endpoints for consecutive Bezier segments. In * total there will be points.size() - 1 curves. This must not be * empty. * @param vi The initial velocity, used as a tangent for the first curve. * @param vf The final velocity, used as a tangent for the last curve. * @param motion_constraints Linear constraints for motion. These are used * to approximate the time between control points, which is later used * to match up tangent vectors (approximately) with velocities. */ BezierPath(const std::vector<Geometry2d::Point>& points, Geometry2d::Point vi, Geometry2d::Point vf, MotionConstraints motion_constraints); /** * @brief Evaluate the path at a particular instant drawn from [0, 1]. * Calculates only those values requested (by passing in a non-null * pointer). * * @param s The index to sample along, in the range of [0, 1]. * @param position Output parameter for the position at s, if non-null. * @param tangent Output parameter for the tangent vector at s, if non-null. * @param curvature Output parameter for the curvature at s, if non-null. */ void Evaluate(double s, Geometry2d::Point* position = nullptr, Geometry2d::Point* tangent = nullptr, double* curvature = nullptr) const; /** * @brief Whether or not this curve is empty. */ [[nodiscard]] bool empty() const { return control.empty(); } /** * @brief The number of cubic segments in this Bezier curve. */ [[nodiscard]] int size() const { return control.size(); } /** * @brief Control points for a Bezier curve. */ struct CubicBezierControlPoints { Geometry2d::Point p0, p1, p2, p3; CubicBezierControlPoints() = default; CubicBezierControlPoints(Geometry2d::Point p0, Geometry2d::Point p1, Geometry2d::Point p2, Geometry2d::Point p3) : p0(p0), p1(p1), p2(p2), p3(p3) {} }; private: std::vector<CubicBezierControlPoints> control; }; } // namespace Planning
2,633
769
/******************************************************************************\ * * * ____ _ _ _ * * | __ ) ___ ___ ___| |_ / \ ___| |_ ___ _ __ * * | _ \ / _ \ / _ \/ __| __| / _ \ / __| __/ _ \| '__| * * | |_) | (_) | (_) \__ \ |_ _ / ___ \ (__| || (_) | | * * |____/ \___/ \___/|___/\__(_)_/ \_\___|\__\___/|_| * * * * * * * * Copyright (C) 2011 - 2014 * * Dominik Charousset <dominik.charousset@haw-hamburg.de> * * * * Distributed under the Boost Software License, Version 1.0. See * * accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt * \******************************************************************************/ #include <cstdio> #include <cstring> #include <sstream> #include <unistd.h> #include <sys/types.h> #include "boost/actor/config.hpp" #include "boost/actor/node_id.hpp" #include "boost/actor/serializer.hpp" #include "boost/actor/singletons.hpp" #include "boost/actor/primitive_variant.hpp" #include "boost/actor/io/middleman.hpp" #include "boost/actor/detail/ripemd_160.hpp" #include "boost/actor/detail/get_root_uuid.hpp" #include "boost/actor/detail/get_mac_addresses.hpp" #include "boost/actor/detail/safe_equal.hpp" namespace { std::uint8_t hex_char_value(char c) { if (isdigit(c)) { return static_cast<std::uint8_t>(c - '0'); } else if (isalpha(c)) { if (c >= 'a' && c <= 'f') { return static_cast<std::uint8_t>((c - 'a') + 10); } else if (c >= 'A' && c <= 'F') { return static_cast<std::uint8_t>((c - 'A') + 10); } } throw std::invalid_argument(std::string("illegal character: ") + c); } } // namespace <anonymous> namespace boost { namespace actor { void host_id_from_string(const std::string& hash, node_id::host_id_type& node_id) { if (hash.size() != (node_id.size() * 2)) { throw std::invalid_argument("string argument is not a node id hash"); } auto j = hash.c_str(); for (size_t i = 0; i < node_id.size(); ++i) { // read two characters, each representing 4 bytes auto& val = node_id[i]; val = static_cast<uint8_t>(hex_char_value(*j++) << 4); val |= hex_char_value(*j++); } } bool equal(const std::string& hash, const node_id::host_id_type& node_id) { if (hash.size() != (node_id.size() * 2)) { return false; } auto j = hash.c_str(); try { for (size_t i = 0; i < node_id.size(); ++i) { // read two characters, each representing 4 bytes std::uint8_t val; val = static_cast<uint8_t>(hex_char_value(*j++) << 4); val |= hex_char_value(*j++); if (val != node_id[i]) { return false; } } } catch (std::invalid_argument&) { return false; } return true; } node_id::~node_id() { } node_id::node_id(const node_id& other) : super(), m_process_id(other.process_id()), m_host_id(other.host_id()) { } node_id::node_id(std::uint32_t a, const std::string& b) : m_process_id(a) { host_id_from_string(b, m_host_id); } node_id::node_id(std::uint32_t a, const host_id_type& b) : m_process_id(a), m_host_id(b) { } std::string to_string(const node_id::host_id_type& node_id) { std::ostringstream oss; oss << std::hex; oss.fill('0'); for (size_t i = 0; i < node_id::host_id_size; ++i) { oss.width(2); oss << static_cast<std::uint32_t>(node_id[i]); } return oss.str(); } int node_id::compare(const node_id& other) const { int tmp = strncmp(reinterpret_cast<const char*>(host_id().data()), reinterpret_cast<const char*>(other.host_id().data()), host_id_size); if (tmp == 0) { if (m_process_id < other.process_id()) return -1; else if (m_process_id == other.process_id()) return 0; return 1; } return tmp; } void node_id::serialize_invalid(serializer* sink) { sink->write_value(static_cast<uint32_t>(0)); node_id::host_id_type zero; std::fill(zero.begin(), zero.end(), 0); sink->write_raw(node_id::host_id_size, zero.data()); } std::string to_string(const node_id& what) { std::ostringstream oss; oss << what.process_id() << "@" << to_string(what.host_id()); return oss.str(); } std::string to_string(const node_id_ptr& what) { std::ostringstream oss; oss << "@process_info("; if (!what) oss << "null"; else oss << to_string(*what); oss << ")"; return oss.str(); } } // namespace actor } // namespace boost
5,209
1,785
#include "DebugCube.h" #include "W_RNG.h" #include "W_ResourceLoader.h" namespace wolf { static const Vertex cubeVertices[] = { // Front { -0.5f, -0.5f, 0.5f, 255, 0, 0, 255, 0.0f, 0.0f }, { -0.5f, 0.5f, 0.5f, 255, 0, 0, 255, 0.0f, 0.0f }, { 0.5f, 0.5f, 0.5f, 255, 0, 0, 255, 0.0f, 0.0f }, { 0.5f, 0.5f, 0.5f, 255, 0, 0, 255, 0.0f, 0.0f }, { 0.5f, -0.5f, 0.5f, 255, 0, 0, 255, 0.0f, 0.0f }, { -0.5f, -0.5f, 0.5f, 255, 0, 0, 255, 0.0f, 0.0f }, // Back { 0.5f, 0.5f,-0.5f, 128, 0, 0, 255, 0.0f, 0.0f }, { -0.5f, 0.5f,-0.5f, 128, 0, 0, 255, 0.0f, 0.0f }, { -0.5f, -0.5f,-0.5f, 128, 0, 0, 255, 0.0f, 0.0f }, { -0.5f, -0.5f,-0.5f, 128, 0, 0, 255, 0.0f, 0.0f }, { 0.5f, -0.5f,-0.5f, 128, 0, 0, 255, 0.0f, 0.0f }, { 0.5f, 0.5f,-0.5f, 128, 0, 0, 255, 0.0f, 0.0f }, // Left { -0.5f, 0.5f,-0.5f, 0, 255, 0, 255, 0.0f, 0.0f }, { -0.5f, 0.5f, 0.5f, 0, 255, 0, 255, 0.0f, 0.0f }, { -0.5f, -0.5f, 0.5f, 0, 255, 0, 255, 0.0f, 0.0f }, { -0.5f, -0.5f, 0.5f, 0, 255, 0, 255, 0.0f, 0.0f }, { -0.5f, -0.5f,-0.5f, 0, 255, 0, 255, 0.0f, 0.0f }, { -0.5f, 0.5f,-0.5f, 0, 255, 0, 255, 0.0f, 0.0f }, // Right { 0.5f, 0.5f, 0.5f, 0, 128, 0, 255, 0.0f, 0.0f }, { 0.5f, 0.5f,-0.5f, 0, 128, 0, 255, 0.0f, 0.0f }, { 0.5f, -0.5f,-0.5f, 0, 128, 0, 255, 0.0f, 0.0f }, { 0.5f, -0.5f,-0.5f, 0, 128, 0, 255, 0.0f, 0.0f }, { 0.5f, -0.5f, 0.5f, 0, 128, 0, 255, 0.0f, 0.0f }, { 0.5f, 0.5f, 0.5f, 0, 128, 0, 255, 0.0f, 0.0f }, // Top { -0.5f, 0.5f, 0.5f, 0, 0, 255, 255, 0.0f, 0.0f }, { -0.5f, 0.5f,-0.5f, 0, 0, 255, 255, 0.0f, 0.0f }, { 0.5f, 0.5f,-0.5f, 0, 0, 255, 255, 0.0f, 0.0f }, { 0.5f, 0.5f,-0.5f, 0, 0, 255, 255, 0.0f, 0.0f }, { 0.5f, 0.5f, 0.5f, 0, 0, 255, 255, 0.0f, 0.0f }, { -0.5f, 0.5f, 0.5f, 0, 0, 255, 255, 0.0f, 0.0f }, // Bottom { -0.5f, -0.5f, 0.5f, 0, 0, 128, 255, 0.0f, 0.0f }, { 0.5f, -0.5f, 0.5f, 0, 0, 128, 255, 0.0f, 0.0f }, { 0.5f, -0.5f,-0.5f, 0, 0, 128, 255, 0.0f, 0.0f }, { 0.5f, -0.5f,-0.5f, 0, 0, 128, 255, 0.0f, 0.0f }, { -0.5f, -0.5f,-0.5f, 0, 0, 128, 255, 0.0f, 0.0f }, { -0.5f, -0.5f, 0.5f, 0, 0, 128, 255, 0.0f, 0.0f }, }; DebugCube::DebugCube() { setPos(glm::vec3(RNG::GetRandom(-10.0f, 10.0f), RNG::GetRandom(-0.5f, 0.5f), RNG::GetRandom(-10.0f, 10.0f))); setScale(glm::vec3(RNG::GetRandom(0.75f, 1.5f), RNG::GetRandom(0.75f, 1.5f), RNG::GetRandom(0.75f, 1.5f))); // set up rendering g_pProgram = ProgramManager::CreateProgram(wolf::ResourceLoader::Instance().getShaders("cube")); g_pVB = BufferManager::CreateVertexBuffer(cubeVertices, sizeof(Vertex) * 6 * 6); g_pDecl = new VertexDeclaration(); g_pDecl->Begin(); Vertex::applyAttributes(g_pDecl); g_pDecl->SetVertexBuffer(g_pVB); g_pDecl->End(); } DebugCube::~DebugCube() { } void DebugCube::Update(float delta) { Node::Update(delta); } void DebugCube::Render(glm::mat4 projview) { Node::Render(projview); g_pProgram->Bind(); // Bind Uniforms g_pProgram->SetUniform("projection", projview); g_pProgram->SetUniform("world", glm::translate(getPos()) * glm::scale(getScale())); g_pProgram->SetUniform("view", glm::mat4()); // Set up source data g_pDecl->Bind(); // Draw! glDrawArrays(GL_TRIANGLES, 0, 6 * 6); } }
3,355
2,489
/* * Copyright 2003,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <log4cxx/logmanager.h> #include <log4cxx/logger.h> #include <log4cxx/helpers/cyclicbuffer.h> #include <log4cxx/spi/loggingevent.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; #define MAX 1000 class CyclicBufferTestCase : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(CyclicBufferTestCase); CPPUNIT_TEST(test0); CPPUNIT_TEST(test1); CPPUNIT_TEST(testResize); CPPUNIT_TEST_SUITE_END(); LoggerPtr logger; std::vector<LoggingEventPtr> e; public: void setUp() { logger = Logger::getLogger(_T("x")); e.reserve(1000); for (int i = 0; i < MAX; i++) { e.push_back( new LoggingEvent(_T(""), logger, Level::DEBUG, _T("e"))); } } void tearDown() { LogManager::shutdown(); } void test0() { int size = 2; CyclicBuffer cb(size); CPPUNIT_ASSERT_EQUAL(size, cb.getMaxSize()); cb.add(e[0]); CPPUNIT_ASSERT_EQUAL(1, cb.length()); CPPUNIT_ASSERT_EQUAL(e[0], cb.get()); CPPUNIT_ASSERT_EQUAL(0, cb.length()); CPPUNIT_ASSERT(cb.get() == 0); CPPUNIT_ASSERT_EQUAL(0, cb.length()); CyclicBuffer cb2(size); cb2.add(e[0]); cb2.add(e[1]); CPPUNIT_ASSERT_EQUAL(2, cb2.length()); CPPUNIT_ASSERT_EQUAL(e[0], cb2.get()); CPPUNIT_ASSERT_EQUAL(1, cb2.length()); CPPUNIT_ASSERT_EQUAL(e[1], cb2.get()); CPPUNIT_ASSERT_EQUAL(0, cb2.length()); CPPUNIT_ASSERT(cb2.get() == 0); CPPUNIT_ASSERT_EQUAL(0, cb2.length()); } void test1() { for (int bufSize = 1; bufSize <= 128; bufSize *= 2) doTest1(bufSize); } void doTest1(int size) { //System.out.println("Doing test with size = "+size); CyclicBuffer cb(size); CPPUNIT_ASSERT_EQUAL(size, cb.getMaxSize()); int i; for (i = -(size + 10); i < (size + 10); i++) { CPPUNIT_ASSERT(cb.get(i) == 0); } for (i = 0; i < MAX; i++) { cb.add(e[i]); int limit = (i < (size - 1)) ? i : (size - 1); //System.out.println("\nLimit is " + limit + ", i="+i); for (int j = limit; j >= 0; j--) { //System.out.println("i= "+i+", j="+j); CPPUNIT_ASSERT_EQUAL(e[i - (limit - j)], cb.get(j)); } CPPUNIT_ASSERT(cb.get(-1) == 0); CPPUNIT_ASSERT(cb.get(limit + 1) == 0); } } void testResize() { for (int isize = 1; isize <= 128; isize *= 2) { doTestResize(isize, (isize / 2) + 1, (isize / 2) + 1); doTestResize(isize, (isize / 2) + 1, isize + 10); doTestResize(isize, isize + 10, (isize / 2) + 1); doTestResize(isize, isize + 10, isize + 10); } } void doTestResize(int initialSize, int numberOfAdds, int newSize) { //System.out.println("initialSize = "+initialSize+", numberOfAdds=" // +numberOfAdds+", newSize="+newSize); CyclicBuffer cb(initialSize); for (int i = 0; i < numberOfAdds; i++) { cb.add(e[i]); } cb.resize(newSize); int offset = numberOfAdds - initialSize; if (offset < 0) { offset = 0; } int len = (newSize < numberOfAdds) ? newSize : numberOfAdds; len = (len < initialSize) ? len : initialSize; //System.out.println("Len = "+len+", offset="+offset); for (int j = 0; j < len; j++) { CPPUNIT_ASSERT_EQUAL(e[offset + j], cb.get(j)); } } }; CPPUNIT_TEST_SUITE_REGISTRATION(CyclicBufferTestCase);
3,905
1,832
#include "Camera.h" Camera::Camera(float width, float height) : up(0.f, -1.f, 0.f) , target(0.f, 0.f, 0.f) , width(width) , height(height) { } void Camera::Update() { D3DXMatrixLookAtLH(&view, &GetTransform()->GetPosition(), &target, &up); D3DXMatrixOrthoLH(&proj, width, height, 0.01f, 1000.0f); //D3DXMatrixPerspectiveFovLH(&proj, D3DX_PI/4, width/height, 0.01f, 1000.0f); HR(gD3DDevice->SetTransform(D3DTS_VIEW, &view)); HR(gD3DDevice->SetTransform(D3DTS_PROJECTION, &proj)); } Camera::~Camera() { }
516
259
// Functions for the <see cref="PiaTable"/> class to manage Pia Table pia // calculations. // $Id: PiaTable.cpp 1.45 2011/08/09 14:59:55EDT 044579 Development $ #include <fstream> #include <utility> // for rel_ops #include "PiaTable.h" #include "oactcnst.h" #include "PiaException.h" #include "piaparms.h" #include "DebugCase.h" #if defined(DEBUGCASE) #include <sstream> #include "Trace.h" #endif using namespace std; #if !defined(__SGI_STL_INTERNAL_RELOPS) using namespace std::rel_ops; #endif /// <summary>Initializes this instance.</summary> /// /// <remarks>Calls <see cref="initialize"/>.</remarks> /// /// <param name="newWorkerData">Worker basic data.</param> /// <param name="newPiaData">Pia calculation data.</param> /// <param name="newPiaParams">Pia calculation parameters.</param> /// <param name="newMaxyear">Maximum year of projection.</param> PiaTable::PiaTable( const WorkerDataGeneral& newWorkerData, const PiaData& newPiaData, const PiaParams& newPiaParams, int newMaxyear ) : OldPia(newWorkerData, newPiaData, newPiaParams, newMaxyear, "New-Start Calculation (pre-1977 Act)", PIA_TABLE) { initialize(); } /// <summary>Destructor.</summary> PiaTable::~PiaTable() { } /// <summary>Determines applicability of method, using stored values.</summary> /// /// <remarks>This version calls the static version with 3 arguments.</remarks> /// /// <returns>True if method is applicable.</returns> bool PiaTable::isApplicable() { if (isApplicable(workerData, piaData, getIoasdi())) { setApplicable(APPLICABLE); return(true); } return(false); } /// <summary>Determines applicability of method, using passed values.</summary> /// /// <returns>True if method is applicable.</returns> /// /// <param name="workerData">Worker basic data.</param> /// <param name="piaData">Pia calculation data.</param> /// <param name="ioasdi">Type of benefit.</param> bool PiaTable::isApplicable( const WorkerDataGeneral& workerData, const PiaData& piaData, WorkerDataGeneral::ben_type ioasdi ) { return (piaData.getEligYear() < YEAR79 && workerData.getBenefitDate() >= PiaParams::amend52 && (ioasdi != WorkerDataGeneral::SURVIVOR || DateMoyr(workerData.getDeathDate()) >= PiaParams::amend52) ); } /// <summary>Computes Pia Table PIA.</summary> /// /// <exception cref="PiaException"><see cref="PiaException"/> of type /// <see cref="PIA_IDS_PIATABLE1"/> if year of entitlement is out of range /// (only in debug mode); of type <see cref="PIA_IDS_PIATABLE2"/> if year of /// benefit is out of range (only in debug mode).</exception> void PiaTable::calculate() { #if defined(DEBUGCASE) if (isDebugPid(workerData.getIdNumber())) { Trace::writeLine(workerData.getIdString() + ": Starting PiaTable::calculate"); } #endif DateMoyr dateMoyr = (getIoasdi() == WorkerDataGeneral::SURVIVOR) ? DateMoyr(workerData.getDeathDate()) : workerData.getEntDate(); #if !defined(NDEBUG) if (dateMoyr.getYear() < YEAR37) throw PiaException(PIA_IDS_PIATABLE1); #endif int i1 = dateMoyr.getYear(); yearCpi[YEAR_ENT] = (i1 < YEAR51) ? i1 : (static_cast<int>(dateMoyr.getMonth()) >= piaParams.getMonthBeninc(i1)) ? i1 : i1 - 1; #if !defined(NDEBUG) if (workerData.getBenefitDate().getYear() < YEAR37) throw PiaException(PIA_IDS_PIATABLE2); #endif i1 = workerData.getBenefitDate().getYear(); yearCpi[YEAR_BEN] = (static_cast<int>(workerData.getBenefitDate().getMonth()) >= piaParams.getMonthBeninc(i1)) ? i1 : i1 - 1; yearCpi[FIRST_YEAR] = 1975; const AverageWage& earnings = workerData.getTotalize() ? piaData.earnTotalizedLimited : piaData.earnOasdiLimited; i1 = piaData.getEarn50(PiaData::EARN_WITH_TOTALIZATION); const int i4 = piaData.getEarnYear(); for (int i2 = i1; i2 <= i4; i2++) { if (!piaData.freezeYears.isFreezeYear(i2)) earnIndexed[i2] = earnings[i2]; } const int i3 = piaData.compPeriodNew.getN(); orderEarnings(i1, i4, i3); totalEarnCal(i1, i4, i3); #if defined(DEBUGCASE) if (isDebugPid(workerData.getIdNumber())) { ostringstream strm; strm << workerData.getIdString() << ", ame " << getAme() << ": After totalEarnCal"; Trace::writeLine(strm.str()); } #endif if (workerData.getBenefitDate() < PiaParams::amend742) { setTableNum(oldPiaCal()); } else { setTableNum(cpiBase(workerData.getBenefitDate(), false, getAme(), !workerData.getTotalize())); } piaEnt.set(piasub); mfbEnt.set(mfbsub); if (workerData.getTotalize()) { piaElig[yearCpi[FIRST_YEAR]] = piaEnt.get(); prorate(); piaEnt.set(piaElig[yearCpi[FIRST_YEAR]]); static_cast<void>(mfbOldCal(true)); } setDirty(); #if defined(DEBUGCASE) if (isDebugPid(workerData.getIdNumber())) { Trace::writeLine(workerData.getIdString() + ": Returning from PiaTable::calculate"); } #endif }
4,968
1,847
//////////////////////////////////////////////////////////////// // precompiled header for render elements // #include "renElemPch.h"
136
36
#include <blik.hpp> #include "blik_vector.hpp" namespace BLIK { Vector::Vector() { x = 0; y = 0; vx = 0; vy = 0; } Vector::Vector(const Vector& rhs) { operator=(rhs); } Vector::Vector(float x, float y, float vx, float vy) { this->x = x; this->y = y; this->vx = vx; this->vy = vy; } Vector::Vector(const Point& pos, const Point& vec) { x = pos.x; y = pos.y; vx = vec.x; vy = vec.y; } Vector::~Vector() { } Vector& Vector::operator=(const Vector& rhs) { x = rhs.x; y = rhs.y; vx = rhs.vx; vy = rhs.vy; return *this; } Vector& Vector::operator+=(const Point& rhs) { x += rhs.x; y += rhs.y; return *this; } Vector Vector::operator+(const Point& rhs) const { return Vector(*this).operator+=(rhs); } Vector& Vector::operator-=(const Point& rhs) { x -= rhs.x; y -= rhs.y; return *this; } Vector Vector::operator-(const Point& rhs) const { return Vector(*this).operator-=(rhs); } bool Vector::operator==(const Vector& rhs) const { return (x == rhs.x && y == rhs.y && vx == rhs.vx && vy == rhs.vy); } bool Vector::operator!=(const Vector& rhs) const { return !operator==(rhs); } }
1,453
523
#include "Solar.h" Solar::Solar(void) { geo = false; DEG2RAD = 3.14159/180; velocity = 1; Mer = 0.0, Ven = 0.0, Ear = 0.0, Moo = 0.0, Moo2 = 0.0, Mar = 0.0, Jup = 0.0, Sat = 0.0, Ura = 0.0, Nep = 0.0, Plu = 0.0; shine[0] = 10; mooCol[0]=2.3, mooCol[1]=2.3, mooCol[2]=2.3; moo2Col[0]=0.93,moo2Col[1]=0.93,moo2Col[2]=0.93; merCol[0]=2.05, merCol[1]=1.90, merCol[0]=1.12; venCol[0]=1.39, venCol[1]=0.54, venCol[2]=0.26; earCol[0]=0.0, earCol[1]=0.3, earCol[2]=0.6; marCol[0]=1.39, marCol[1]=0.26, marCol[2]=0.0; jupCol[0]=0.80, jupCol[1]=0.53, jupCol[2]=0.25; satCol[0]=0.6, satCol[1]=0.5, satCol[2]=0.09; uraCol[0]=0.40, uraCol[1]=0.900,uraCol[2]=1.0; nepCol[0]=0.135,nepCol[1]=0.115,nepCol[2]=0.85; pluCol[0]=0.7, pluCol[1]=0.8, pluCol[2]=1.00; eyex=80.0, eyey=10.0, eyez= 10.0; centerx=0.0, centery=0.0, centerz=0.0; upx=0.0, upy=1.0, upz=0.0; } Solar::~Solar(void) { } void Solar::incVelocity() { velocity++; } void Solar::decVelocity() { velocity--; } float Solar::getVelocity() { return velocity; } void Solar::spin() { Mer += 16.0 * velocity; if(Mer > 360.0) Mer = Mer - 360.0; Ven += 12.0 * velocity; if(Ven > 360.0) Ven = Ven - 360.0; Ear += 10.0 * velocity; if(Ear > 360.0) Ear = Ear - 360.0; Moo += 2.0 * velocity; if(Moo > 360.0) Moo = Moo - 360.0; Moo2 += 1.0 * velocity; if(Moo2 > 360.0) Moo2 = Moo2 - 360.0; Mar += 8.0 * velocity; if(Mar > 360.0) Mar = Mar - 360.0; Jup += 5.0 * velocity; if(Jup > 360.0) Jup = Jup - 360.0; Sat += 4.0 * velocity; if(Sat > 360.0) Sat = Sat - 360.0; Ura += 3.0 * velocity; if(Ura > 360.0) Ura = Ura - 360.0; Nep += 2.0 * velocity; if(Nep > 360.0) Nep = Nep - 360.0; Plu += 1.0 * velocity; if(Plu > 360.0) Plu = Plu - 360.0; } void Solar::drawCircle(float radius) { glBegin(GL_LINE_LOOP); for (int i=0; i<=360; i++) { float degInRad = i*DEG2RAD; glVertex2f(cos(degInRad)*radius,sin(degInRad)*radius); } glEnd(); } void Solar::draw() { GLfloat position[] = { 0.0, 0.0, 1.5, 1.0 }; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, shine); glPushMatrix(); gluLookAt(eyex, eyey, eyez, centerx, centery, centerz, upx, upy, upz); glPushMatrix(); glPushMatrix(); glRotatef(90,1,0,0); drawCircle(4.9); glPopMatrix(); glRotated((GLdouble) Mer, 0.0, 1.0, 0.0); glTranslated(0.0, 0.0, 4.9); glRotated((GLdouble) Mer, 0.0, 1.0, 0.0); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, merCol); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, merCol); glutSolidSphere(0.049, 20, 20); glDisable(GL_DIFFUSE); if (geo) { glPushMatrix(); glTranslated(0.1,0.0,0.1); glRotated((GLdouble) Mer, 0.0, 1.0, 0.0); glutSolidCone(0.1,0.4,10,10); glPopMatrix(); } glPopMatrix(); glPushMatrix(); glPushMatrix(); glRotatef(90,1,0,0); drawCircle(5.2); glPopMatrix(); glRotated((GLdouble) Ven, 0.0, 1.0, 0.0); glTranslated(0.1, 0.0, 5.2); glRotated((GLdouble) Ven - 1, 0.0, 1.0, 0.0); //Retrograde (Counter) Rotation glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, venCol); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, venCol); glutSolidSphere(0.12, 20, 20); glDisable(GL_DIFFUSE); if (geo) { glPushMatrix(); glTranslated(0.1,0.0,0.1); glRotated((GLdouble) Ven, 0.0, 1.0, 0.0); glutSolidCone(0.1,0.4,10,10); glPopMatrix(); } glPopMatrix(); glPushMatrix(); glPushMatrix(); glRotatef(90,1,0,0); drawCircle(5.6); glPopMatrix(); glRotated((GLdouble) Ear, 0.0, 1.0, 0.0); glTranslated(0.1, 0.0, 5.6); glRotated((GLdouble) Ear, 0.0, 1.0, 0.0); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, earCol); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, earCol); glutSolidSphere(0.13, 20, 20); glDisable(GL_DIFFUSE); glPushMatrix(); if (geo) { glPushMatrix(); glPushMatrix(); gluLookAt(0.1,0.0,0.1,0,0,0,0,1,0); glPopMatrix(); glTranslated(0.1,0.0,0.1); glRotated((GLdouble) Ear, 0.0, 1.0, 0.0); glutSolidCone(0.1,0.4,10,10); glPopMatrix(); } glRotated((GLdouble) Moo, 0.0, 1.0, 0.0); glTranslated(0.1, 0.0, 0.1); glRotated((GLdouble) Moo, 0.0, 1.0, 0.0); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mooCol); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, mooCol); glutSolidSphere(0.02, 20, 20); glDisable(GL_DIFFUSE); glPopMatrix(); glPopMatrix(); glPushMatrix(); glPushMatrix(); glRotatef(90,1,0,0); drawCircle(6.0); glPopMatrix(); glRotated((GLdouble) Mar, 0.0, 1.0, 0.0); glTranslated(0.1, 0.0, 6.0); glRotated((GLdouble) Mar, 0.0, 1.0, 0.0); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, marCol); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, marCol); glutSolidSphere(0.067, 20, 20); glDisable(GL_DIFFUSE); if (geo) { glPushMatrix(); glTranslated(0.1,0.0,0.1); glRotated((GLdouble) Mar, 0.0, 1.0, 0.0); glutSolidCone(0.1,0.4,10,10); glPopMatrix(); } glPushMatrix(); glRotated((GLdouble) Moo, 0.0, 1.0, 0.0); glTranslated(0.0, 0.0, 0.1); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mooCol); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, mooCol); glRotated((GLdouble) Moo, 0.0, 1.0, 0.0); glutSolidSphere(0.015, 20, 10); glPopMatrix(); glPushMatrix(); glRotated((GLdouble) Moo2, 0.0, 1.0, 0.0); glTranslated(0.0, 0.0, 0.15); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, moo2Col); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, moo2Col); glRotated((GLdouble) Moo2, 0.0, 1.0, 0.0); glutSolidSphere(0.01, 20, 10); glPopMatrix(); glPopMatrix(); glPushMatrix(); glPushMatrix(); glRotatef(90,1,0,0); drawCircle(9.7); glPopMatrix(); glRotated((GLdouble) Jup, 0.0, 1.0, 0.0); glTranslated(0.1, 0.0, 9.7); glRotated((GLdouble) Jup, 0.0, 1.0, 0.0); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, jupCol); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, jupCol); glutSolidSphere(1.42, 20, 20); glDisable(GL_DIFFUSE); if (geo) { glPushMatrix(); glTranslated(2,0.0,0.1); glRotated((GLdouble) Jup, 0.0, 1.0, 0.0); glutSolidCone(0.1,0.4,10,10); glPopMatrix(); } glPopMatrix(); glPushMatrix(); glPushMatrix(); glRotatef(90,1,0,0); drawCircle(14.0); glPopMatrix(); glRotated((GLdouble) Sat, 0.0, 1.0, 0.0); glTranslated(0.1, 0.0, 14.0); glRotated((GLdouble) Sat, 0.0, 1.0, 0.0); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, satCol); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, satCol); glPushMatrix(); glRotatef(45,1,0,0); for (float i=1.7;i<=2.5;i+=0.05) { drawCircle(i); //std::cout<<i<<std::endl; } glPopMatrix(); glutSolidSphere(1.20, 20, 20); glDisable(GL_DIFFUSE); if (geo) { glPushMatrix(); glTranslated(2,0.0,0.1); glRotated((GLdouble) Sat, 0.0, 1.0, 0.0); glutSolidCone(0.1,0.4,10,10); glPopMatrix(); } glPopMatrix(); glPushMatrix(); glPushMatrix(); glRotatef(90,1,0,0); drawCircle(23.5); glPopMatrix(); glRotated((GLdouble) Ura, 0.0, 1.0, 0.0); glTranslated(0.1, 0.0, 23.5); glRotated((GLdouble) Ura - 1, 1.0, 0.0, 0.0); //Retrograde Rotation glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, uraCol); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, uraCol); glutSolidSphere(0.51, 20, 20); glDisable(GL_DIFFUSE); if (geo) { glPushMatrix(); glTranslated(1,0.0,0.1); glRotated((GLdouble) Ura, 0.0, 1.0, 0.0); glutSolidCone(0.1,0.4,10,10); glPopMatrix(); } glPopMatrix(); glPushMatrix(); glPushMatrix(); glRotatef(90,1,0,0); drawCircle(34.5); glPopMatrix(); glRotated((GLdouble) Nep, 0.0, 1.0, 0.0); glTranslated(0.1, 0.0, 34.5); glRotated((GLdouble) Nep, 1.0, 0.0, 0.0); //Rotates top to bottom glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, nepCol); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, nepCol); glutSolidSphere(0.49, 20, 20); glDisable(GL_DIFFUSE); if (geo) { glPushMatrix(); glTranslated(1,0.0,0.1); glRotated((GLdouble) Ura, 0.0, 1.0, 0.0); glutSolidCone(0.1,0.4,10,10); glPopMatrix(); } glPopMatrix(); glPushMatrix(); glPushMatrix(); glRotatef(90,1,0,0); drawCircle(44.0); glPopMatrix(); glRotated((GLdouble) Plu, 0.0, 1.0, 0.0); glTranslated(0.1, 0.0, 44.0); glRotated((GLdouble) Plu, 0.0, 1.0, 0.0); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, pluCol); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, pluCol); glutSolidSphere(0.1, 20, 20); glDisable(GL_DIFFUSE); if (geo) { glPushMatrix(); glTranslated(1,0.0,0.1); glRotated((GLdouble) Plu, 0.0, 1.0, 0.0); glutSolidCone(0.1,0.4,10,10); glPopMatrix(); } glPopMatrix(); glLightfv(GL_LIGHT0, GL_POSITION, position); GLfloat global_ambient[] = {0.5f, 0.5f, 0.5f, 1.0f}; //Emission glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient); //Emission glDisable(GL_LIGHTING); glColor3f(1.0, 1.0, 0.0); glRotated((GLdouble) Ear, 0.0, 1.0, 0.0); glutSolidSphere(4.00, 20, 20); glEnable(GL_LIGHTING); glPopMatrix(); }
9,248
5,642
#include <EdwinAlkinsGameEngine.h> class SandBox : public EdwinAlkinsGameEngine::Application{ public: SandBox() { } ~SandBox() { } }; EdwinAlkinsGameEngine::Application* EdwinAlkinsGameEngine::CreateApplication() { return new SandBox(); }
250
91
//----------------------------------------------------------------------------- // Copyright (c) 2013-2018 Benjamin Buch // // https://github.com/bebuch/BitmapViewer // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) //----------------------------------------------------------------------------- #include <BitmapViewer/slider.hpp> #include <QMouseEvent> #include <QPaintEvent> #include <QWheelEvent> #include <QPainter> #include <cmath> namespace bitmap_viewer{ constexpr double shift_range = std::numeric_limits< unsigned >::max() + 1.; slider::slider(QWidget* parent): QWidget(parent), active_(false), shift_(0), startpos_(0), startshift_(0) { setCursor(Qt::OpenHandCursor); colors_.update.connect([this]{repaint();change();}); } void slider::set_shift(unsigned s){ shift_ = colors_.pass_pos(s); repaint(); shift_changed(s); change(); } void slider::set_strips(unsigned count){ colors_.set_strips(count); set_shift(shift()); } void slider::contrast_line(bool enable){ colors_.contrast_line(enable); } void slider::next_palette(){ colors_.next_palette(); } unsigned slider::inc_step(unsigned step, int inc)const{ if(inc < 0){ inc = -inc % colors_.strips(); step += colors_.strips() - inc; }else{ step += inc; step %= colors_.strips(); } return step; } void slider::right_shift(){ auto step_pos = colors_.step_pos(shift_); step_pos = inc_step(step_pos, -1); set_shift(colors_.pass_step_pos(step_pos)); } void slider::left_shift(){ auto step_pos = colors_.step_pos(shift_); step_pos = inc_step(step_pos, 1); set_shift(colors_.pass_step_pos(step_pos)); } void slider::fold_linear(){ colors_.set_fold(colors_.fold() + 1); } void slider::unfold_linear(){ colors_.set_fold(colors_.fold() - 1); } void slider::fold_exponential(){ colors_.set_fold(colors_.fold() << 1); } void slider::unfold_exponential(){ colors_.set_fold(colors_.fold() >> 1); } void slider::mouseMoveEvent(QMouseEvent* event){ if(!active_) return; unsigned w = width(); set_shift(startshift_ + startpos_ - event->x() * (shift_range / w)); } void slider::mousePressEvent(QMouseEvent* event){ if(event->button() != Qt::LeftButton) return; active_ = true; setCursor(Qt::ClosedHandCursor); unsigned w = width(); startpos_ = event->x() * (shift_range / w); startshift_ = shift_; } void slider::mouseReleaseEvent(QMouseEvent* event){ if(event->button() != Qt::LeftButton) return; setCursor(Qt::OpenHandCursor); active_ = false; } void slider::paintEvent(QPaintEvent*){ QPainter painter(this); unsigned w = width(); for(unsigned i = 0; i < w; ++i){ painter.setPen(colors_(shift_ + i * (shift_range / w))); painter.drawLine(i, 0, i, height()); } auto text = QString("Pos: %1").arg(colors_.step_pos(shift_)); auto flags = Qt::AlignLeft | Qt::AlignVCenter; auto fontfactor = 0.7; auto fontsize = height() * fontfactor; auto x_offset = height() * (1 - fontfactor) / 2; auto p1 = QPointF(x_offset, 0); auto p2 = QPointF(w - 2*x_offset, height()); QFont font; font.setPixelSize(fontsize); font.setStyleStrategy(QFont::PreferAntialias); font.setStyleStrategy(QFont::PreferQuality); painter.setRenderHint(QPainter::TextAntialiasing); painter.setFont(font); painter.setPen(Qt::white); int range = 2; for(int y = -range; y <= range; ++y){ for(int x = -range; x <= range; ++x){ painter.drawText(QRectF(p1 + QPointF(x, y), p2), text, flags); } } painter.setPen(Qt::black); painter.drawText(QRectF(p1, p2), text, flags); } void slider::wheelEvent(QWheelEvent* event){ auto step_pos = colors_.step_pos(shift_); double factor = 1; if(event->buttons() & Qt::LeftButton) factor = 0.25; if(event->buttons() & Qt::RightButton) factor = 4; step_pos = inc_step( step_pos, std::max(factor * colors_.strips() / 32, 1.) * (event->angleDelta().y() > 0 ? 1 : -1) ); set_shift(colors_.pass_step_pos(step_pos)); } }
4,099
1,657
#pragma once #define GLFW_INCLUDE_NONE #include <GLFW/glfw3.h> #include <GL/glew.h> #include "Math.hpp" #include <iostream> class Window { public: static void create(unsigned int _width, unsigned int _height, const char* _title, bool _resizable = false, bool _decorated = true); static void clear(); static void update(); static void close(); static GLFWwindow* getWindowPtr(); private: static GLFWwindow* m_window; };
431
154
#include "histogram.h" void histogram_opt(int in[INPUT_SIZE], int hist[VALUE_SIZE]) { int acc = 0; int i, val; int in_buf[INPUT_SIZE], hist_buf[VALUE_SIZE]; for(i = 0; i < INPUT_SIZE; i++) { #pragma HLS PIPELINE II=1 in_buf[i] = in[i]; } int old = in_buf[0]; loop0: for(i = 0; i < INPUT_SIZE; i++) { #pragma HLS PIPELINE II=1 val = in_buf[i]; if(old == val) { acc = acc + 1; } else { hist_buf[old] = acc; acc = hist_buf[val] + 1; } old = val; } hist_buf[old] = acc; for(i = 0; i < VALUE_SIZE; i++) { #pragma HLS PIPELINE II=1 hist[i] = hist_buf[i]; } }
627
300
#include <iostream> #include <cmath> #include <thread> #include <tuple> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <librealsense2/rs.hpp> // rs.h is for C; rs.hpp is for C++... #include <DarknetNet.h> #include <darknet/images/image_opencv.h> #include <darknet/images/http_stream.h> #include <darknet/images/realsense-opencv-helpers.hpp> #include <utility> using namespace cv; using namespace std; #define POSE_MAX_PEOPLE 96 #define MODEL 0 template<typename T> inline int intRound(const T a) { return lround(a); } template<typename T> inline T fastMin(const T a, const T b) { return (a < b ? a : b); } class OpenposePostProcessor { public: OpenposePostProcessor() { OpenposePostProcessor::initialize(); } /** * // Result for BODY_25 (25 body parts consisting of COCO + foot) // const std::map<unsigned int, std::string> POSE_BODY_25_BODY_PARTS { // {0, "Nose"}, // {1, "Neck"}, // {2, "RShoulder"}, // {3, "RElbow"}, // {4, "RWrist"}, // {5, "LShoulder"}, // {6, "LElbow"}, // {7, "LWrist"}, // {8, "MidHip"}, // {9, "RHip"}, // {10, "RKnee"}, // {11, "RAnkle"}, // {12, "LHip"}, // {13, "LKnee"}, // {14, "LAnkle"}, // {15, "REye"}, // {16, "LEye"}, // {17, "REar"}, // {18, "LEar"}, // {19, "LBigToe"}, // {20, "LSmallToe"}, // {21, "LHeel"}, // {22, "RBigToe"}, // {23, "RSmallToe"}, // {24, "RHeel"}, // {25, "Background"} // }; * * @param frame * @param keyPoints * @param keyShape * @param threshold * @param scale */ static void renderPoseKeyPoints(Mat &frame, const vector<float> &keyPoints, vector<int> keyShape, const float threshold, float scale) { initialize(); const int nrKeyPoints = keyShape[1]; const int pairs_size = OpenposePostProcessor::BODY_PART_PAIRS.size(); const int number_colors = OpenposePostProcessor::COLORS.size(); for (int person = 0; person < keyShape[0]; ++person) { // Draw lines for (int pair = 0u; pair < pairs_size; pair += 2) { const int index1 = (int) (person * nrKeyPoints + OpenposePostProcessor::BODY_PART_PAIRS[pair]) * keyShape[2]; const int index2 = (int) (person * nrKeyPoints + OpenposePostProcessor::BODY_PART_PAIRS[pair + 1]) * keyShape[2]; if (keyPoints[index1 + 2] > threshold && keyPoints[index2 + 2] > threshold) { const int color_index = OpenposePostProcessor::BODY_PART_PAIRS[pair + 1] * 3; Scalar color{OpenposePostProcessor::COLORS[(color_index + 2) % number_colors], OpenposePostProcessor::COLORS[(color_index + 1) % number_colors], OpenposePostProcessor::COLORS[(color_index + 0) % number_colors]}; Point keyPoint1{intRound(keyPoints[index1] * scale), intRound(keyPoints[index1 + 1] * scale)}; Point keyPoint2{intRound(keyPoints[index2] * scale), intRound(keyPoints[index2 + 1] * scale)}; line(frame, keyPoint1, keyPoint2, color, 2); } } // Draw circles for (int part = 0; part < nrKeyPoints; ++part) { const int index = (person * nrKeyPoints + part) * keyShape[2]; if (keyPoints[index + 2] > threshold) { const int color_index = part * 3; Scalar color{OpenposePostProcessor::COLORS[(color_index + 2) % number_colors], OpenposePostProcessor::COLORS[(color_index + 1) % number_colors], OpenposePostProcessor::COLORS[(color_index + 0) % number_colors]}; Point center{intRound(keyPoints[index] * scale), intRound(keyPoints[index + 1] * scale)}; circle(frame, center, 3, color, -1); } } } } static void connectBodyparts( vector<float> &poseKeypoints, const float *const map, const float *const peaks, int mapW, int mapH, const int inter_min_above_th, const float inter_th, const int min_subset_cnt, const float min_subset_score, vector<int> &keypoint_shape) { initialize(); keypoint_shape.resize(3); const int num_body_parts = MODEL_SIZE - 1; // model part number const int num_body_part_pairs = (int) (OpenposePostProcessor::BODY_PART_PAIRS.size() / 2); std::vector<std::pair<std::vector<int>, double>> subset; const int subset_counter_index = num_body_parts; const int subset_size = num_body_parts + 1; const int peaks_offset = 3 * (POSE_MAX_PEOPLE + 1); const int map_offset = mapW * mapH; for (unsigned int pair_index = 0u; pair_index < num_body_part_pairs; ++pair_index) { const int body_partA = OpenposePostProcessor::BODY_PART_PAIRS[2 * pair_index]; const int body_partB = OpenposePostProcessor::BODY_PART_PAIRS[2 * pair_index + 1]; const float *candidateA = peaks + body_partA * peaks_offset; const float *candidateB = peaks + body_partB * peaks_offset; const int nA = (int) (candidateA[0]); // number of part A candidates const int nB = (int) (candidateB[0]); // number of part B candidates // add parts into the subset in special case if (nA == 0 || nB == 0) { // Change w.r.t. other // nB == 0 or not if (nA == 0) { for (int i = 1; i <= nB; ++i) { bool num = false; for (auto &j : subset) { const int off = body_partB * peaks_offset + i * 3 + 2; if (j.first[body_partB] == off) { num = true; break; } } if (!num) { std::vector<int> row_vector(subset_size, 0); // store the index row_vector[body_partB] = body_partB * peaks_offset + i * 3 + 2; // the parts number of that person row_vector[subset_counter_index] = 1; // total score const float subsetScore = candidateB[i * 3 + 2]; subset.emplace_back(std::make_pair(row_vector, subsetScore)); } } } else { // if (nA != 0 && nB == 0) for (int i = 1; i <= nA; i++) { bool num = false; for (auto &j : subset) { const int off = body_partA * peaks_offset + i * 3 + 2; if (j.first[body_partA] == off) { num = true; break; } } if (!num) { std::vector<int> row_vector(subset_size, 0); // store the index row_vector[body_partA] = body_partA * peaks_offset + i * 3 + 2; // parts number of that person row_vector[subset_counter_index] = 1; // total score const float subsetScore = candidateA[i * 3 + 2]; subset.emplace_back(std::make_pair(row_vector, subsetScore)); } } } } else { std::vector<std::tuple<double, int, int>> temp; const int num_inter = 10; // limb PAF x-direction heatmap const float *const mapX = map + OpenposePostProcessor::POSE_MAP_INDEX[2 * pair_index] * map_offset; // limb PAF y-direction heatmap const float *const mapY = map + OpenposePostProcessor::POSE_MAP_INDEX[2 * pair_index + 1] * map_offset; // start greedy algorithm for (int i = 1; i <= nA; i++) { for (int j = 1; j <= nB; j++) { const int dX = (int) (candidateB[j * 3] - candidateA[i * 3]); const int dY = (int) (candidateB[j * 3 + 1] - candidateA[i * 3 + 1]); const auto norm_vec = float(std::sqrt(dX * dX + dY * dY)); // If the peaksPtr are coincident. Don't connect them. if (norm_vec > 1e-6) { const float sX = candidateA[i * 3]; const float sY = candidateA[i * 3 + 1]; const float vecX = ((float) dX) / norm_vec; const float vecY = ((float) dY) / norm_vec; float sum = 0.; int count = 0; for (int lm = 0; lm < num_inter; lm++) { const int mX = fastMin(mapW - 1, intRound(sX + ((float) (lm * dX)) / num_inter)); const int mY = fastMin(mapH - 1, intRound(sY + ((float) (lm * dY)) / num_inter)); const int idx = mY * mapW + mX; const float score = (vecX * mapX[idx] + vecY * mapY[idx]); if (score > inter_th) { sum += score; ++count; } } // parts score + connection score if (count > inter_min_above_th) { temp.emplace_back(std::make_tuple(sum / ((float) count), i, j)); } } } } // select the top minAB connection, assuming that each part occur only once // sort rows in descending order based on parts + connection score if (!temp.empty()) { std::sort(temp.begin(), temp.end(), std::greater<std::tuple<float, int, int>>()); } std::vector<std::tuple<int, int, double>> connectionK; const int minAB = fastMin(nA, nB); // assuming that each part occur only once, filter out same part1 to different part2 std::vector<int> occurA(nA, 0); std::vector<int> occurB(nB, 0); int counter = 0; for (auto &row : temp) { const float score = std::get<0>(row); const int aidx = std::get<1>(row); const int bidx = std::get<2>(row); if (!occurA[aidx - 1] && !occurB[bidx - 1]) { // save two part score "position" and limb mean PAF score connectionK.emplace_back(std::make_tuple(body_partA * peaks_offset + aidx * 3 + 2, body_partB * peaks_offset + bidx * 3 + 2, score)); ++counter; if (counter == minAB) { break; } occurA[aidx - 1] = 1; occurB[bidx - 1] = 1; } } // Cluster all the body part candidates into subset based on the part connection // initialize first body part connection if (pair_index == 0) { for (const auto connectionKI : connectionK) { std::vector<int> row_vector(num_body_parts + 3, 0); const int indexA = std::get<0>(connectionKI); const int indexB = std::get<1>(connectionKI); const double score = std::get<2>(connectionKI); row_vector[OpenposePostProcessor::BODY_PART_PAIRS[0]] = indexA; row_vector[OpenposePostProcessor::BODY_PART_PAIRS[1]] = indexB; row_vector[subset_counter_index] = 2; // add the score of parts and the connection const double subset_score = peaks[indexA] + peaks[indexB] + score; subset.emplace_back(std::make_pair(row_vector, subset_score)); } } // Add ears connections (in case person is looking to opposite direction to camera) else if (pair_index == 17 || pair_index == 18) { for (const auto &connectionKI : connectionK) { const int indexA = std::get<0>(connectionKI); const int indexB = std::get<1>(connectionKI); for (auto &subsetJ : subset) { auto &subsetJ_first = subsetJ.first[body_partA]; auto &subsetJ_first_plus1 = subsetJ.first[body_partB]; if (subsetJ_first == indexA && subsetJ_first_plus1 == 0) { subsetJ_first_plus1 = indexB; } else if (subsetJ_first_plus1 == indexB && subsetJ_first == 0) { subsetJ_first = indexA; } } } } else { if (!connectionK.empty()) { for (auto &i : connectionK) { const int indexA = std::get<0>(i); const int indexB = std::get<1>(i); const double score = std::get<2>(i); int num = 0; // if A is already in the subset, add B for (auto &j : subset) { if (j.first[body_partA] == indexA) { j.first[body_partB] = indexB; ++num; j.first[subset_counter_index] = j.first[subset_counter_index] + 1; j.second = j.second + peaks[indexB] + score; } } // if A is not found in the subset, create new one and add both if (num == 0) { std::vector<int> row_vector(subset_size, 0); row_vector[body_partA] = indexA; row_vector[body_partB] = indexB; row_vector[subset_counter_index] = 2; const auto subsetScore = (float) (peaks[indexA] + peaks[indexB] + score); subset.emplace_back(std::make_pair(row_vector, subsetScore)); } } } } } } // Delete people below thresholds, and save to output int number_people = 0; std::vector<int> valid_subset_indexes; valid_subset_indexes.reserve(fastMin((size_t) POSE_MAX_PEOPLE, subset.size())); for (unsigned int index = 0; index < subset.size(); ++index) { const int subset_counter = subset[index].first[subset_counter_index]; const double subset_score = subset[index].second; if (subset_counter >= min_subset_cnt && (subset_score / subset_counter) > min_subset_score) { ++number_people; valid_subset_indexes.emplace_back(index); if (number_people == POSE_MAX_PEOPLE) { break; } } } // Fill and return pose_keypoints keypoint_shape = {number_people, (int) num_body_parts, 3}; if (number_people > 0) { poseKeypoints.resize(number_people * (int) num_body_parts * 3); } else { poseKeypoints.clear(); } for (unsigned int person = 0u; person < valid_subset_indexes.size(); ++person) { const auto &subsetI = subset[valid_subset_indexes[person]].first; for (int bodyPart = 0u; bodyPart < num_body_parts; bodyPart++) { const int base_offset = (int) (person * num_body_parts + bodyPart) * 3; const int body_part_index = subsetI[bodyPart]; if (body_part_index > 0) { poseKeypoints[base_offset] = peaks[body_part_index - 2]; poseKeypoints[base_offset + 1] = peaks[body_part_index - 1]; poseKeypoints[base_offset + 2] = peaks[body_part_index]; } else { poseKeypoints[base_offset] = 0.f; poseKeypoints[base_offset + 1] = 0.f; poseKeypoints[base_offset + 2] = 0.f; } } } } static void findHeatmapPeaks(const float *src, float *dst, const int SRCW, const int SRCH, const int SRC_CH, const float TH) { initialize(); // find peaks (8-connected neighbor), weights with 7 by 7 area to get sub-pixel location and response const int SRC_PLANE_OFFSET = SRCW * SRCH; // add 1 for saving total people count, 3 for x, y, score const int DST_PLANE_OFFSET = (POSE_MAX_PEOPLE + 1) * 3; float *dstPtr = dst; int c = 0; int x = 0; int y = 0; int i = 0; int j = 0; // TODO: reduce multiplication by using pointer for (c = 0; c < SRC_CH - 1; ++c) { int num_people = 0; for (y = 1; y < SRCH - 1 && num_people != POSE_MAX_PEOPLE; ++y) { for (x = 1; x < SRCW - 1 && num_people != POSE_MAX_PEOPLE; ++x) { int idx = y * SRCW + x; float value = src[idx]; if (value > TH) { const float TOPLEFT = src[idx - SRCW - 1]; const float TOP = src[idx - SRCW]; const float TOPRIGHT = src[idx - SRCW + 1]; const float LEFT = src[idx - 1]; const float RIGHT = src[idx + 1]; const float BUTTOMLEFT = src[idx + SRCW - 1]; const float BUTTOM = src[idx + SRCW]; const float BUTTOMRIGHT = src[idx + SRCW + 1]; if (value > TOPLEFT && value > TOP && value > TOPRIGHT && value > LEFT && value > RIGHT && value > BUTTOMLEFT && value > BUTTOM && value > BUTTOMRIGHT) { float x_acc = 0; float y_acc = 0; float score_acc = 0; for (i = -3; i <= 3; ++i) { int ux = x + i; if (ux >= 0 && ux < SRCW) { for (j = -3; j <= 3; ++j) { int uy = y + j; if (uy >= 0 && uy < SRCH) { float score = src[uy * SRCW + ux]; x_acc += (float) ux * score; y_acc += (float) uy * score; score_acc += score; } } } } x_acc /= score_acc; y_acc /= score_acc; score_acc = value; dstPtr[(num_people + 1) * 3 + 0] = x_acc; dstPtr[(num_people + 1) * 3 + 1] = y_acc; dstPtr[(num_people + 1) * 3 + 2] = score_acc; ++num_people; } } } } dstPtr[0] = (float) num_people; src += SRC_PLANE_OFFSET; dstPtr += DST_PLANE_OFFSET; } } static void postProcess(const DarknetNet &net, Mat &image, float *output, float scale) { initialize(); // cout << "Resize net output back to input size..." << endl; // 7. resize net output back to input size to get heatMap auto *heatMap = new float[net.inW * net.inH * OpenposePostProcessor::NET_OUT_CHANNELS]; for (int i = 0; i < OpenposePostProcessor::NET_OUT_CHANNELS; ++i) { Mat netOut(net.outH, net.outW, CV_32F, (output + net.outH * net.outW * i)); Mat nmsin(net.inH, net.inW, CV_32F, heatMap + net.inH * net.inW * i); resize(netOut, nmsin, Size(net.inW, net.inH), 0, 0, INTER_CUBIC); } // cout << "Finding heatMap peaks..." << endl; // 8. get heatMap peaks auto heatMapSize = 3 * (POSE_MAX_PEOPLE + 1) * (OpenposePostProcessor::NET_OUT_CHANNELS - 1); // cout << "heatMapSize = " << heatMapSize << endl; auto *heatMapPeaks = new float[heatMapSize]; OpenposePostProcessor::findHeatmapPeaks(heatMap, heatMapPeaks, net.inW, net.inH, OpenposePostProcessor::NET_OUT_CHANNELS, 0.05); // cout << "Linking parts..." << endl; // 9. link parts vector<float> keyPoints; vector<int> shape; OpenposePostProcessor::connectBodyparts(keyPoints, heatMap, heatMapPeaks, net.inW, net.inH, 9, 0.05, 6, 0.4, shape); // cout << "Key Points:" << endl; /* for (float keyPoint : keyPoints) { cout << keyPoint << ", "; } cout << endl; for (int shapePoint : shape) { cout << shapePoint << ", "; } cout << endl; //*/ // cout << "Drawing result..." << endl; // 10. draw result OpenposePostProcessor::renderPoseKeyPoints(image, keyPoints, shape, 0.05, scale); // cout << "Showing result..." << endl; // 11. show result // cout << "people: " << shape[0] << endl; delete[] heatMapPeaks; delete[] heatMap; } private: static int INITIALIZED; static int MODEL_SIZE; static int NET_OUT_CHANNELS; static vector<int> POSE_MAP_INDEX; static vector<int> BODY_PART_PAIRS; static vector<float> COLORS; static void initialize() { if (OpenposePostProcessor::INITIALIZED) { return; } #if MODEL == 0 OpenposePostProcessor::MODEL_SIZE = 26; // size = 2 * model_size OpenposePostProcessor::POSE_MAP_INDEX = { 26, 27, 40, 41, 48, 49, 42, 43, 44, 45, 50, 51, 52, 53, 32, 33, 28, 29, 30, 31, 34, 35, 36, 37, 38, 39, 56, 57, 58, 59, 62, 63, 60, 61, 64, 65, 46, 47, 54, 55, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, }; // size = variable OpenposePostProcessor::BODY_PART_PAIRS = { 1, 8, 1, 2, 1, 5, 2, 3, 3, 4, 5, 6, 6, 7, 8, 9, 9, 10, 10, 11, 8, 12, 12, 13, 13, 14, 1, 0, 0, 15, 15, 17, 0, 16, 16, 18, 2, 17, 5, 18, 14, 19, 19, 20, 14, 21, 11, 22, 22, 23, 11, 24, }; // size = 3 * (model_size - 1) OpenposePostProcessor::COLORS = { 255, 0, 85, 255, 0, 0, 255, 85, 0, 255, 170, 0, 255, 255, 0, 170, 255, 0, 85, 255, 0, 0, 255, 0, 255, 0, 0, 0, 255, 85, 0, 255, 170, 0, 255, 255, 0, 170, 255, 0, 85, 255, 0, 0, 255, 255, 0, 170, 170, 0, 255, 255, 0, 255, 85, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, }; #elif MODEL == 1 OpenposePostProcessor::MODEL_SIZE = 19; // size = 2 * model_size OpenposePostProcessor::POSE_MAP_INDEX = { 31, 32, 39, 40, 33, 34, 35, 36, 41, 42, 43, 44, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 47, 48, 49, 50, 53, 54, 51, 52, 55, 56, 37, 38, 45, 46, }; // size = variable OpenposePostProcessor::BODY_PART_PAIRS = { 1, 2, 1, 5, 2, 3, 3, 4, 5, 6, 6, 7, 1, 8, 8, 9, 9, 10, 1, 11, 11, 12, 12, 13, 1, 0, 0, 14, 14, 16, 0, 15, 15, 17, 2, 16, 5, 17, }; // size = 3 * (model_size - 1) OpenposePostProcessor::COLORS = { 255, 0, 85, 255, 0, 0, 255, 85, 0, 255, 170, 0, 255, 255, 0, 170, 255, 0, 85, 255, 0, 0, 255, 0, 0, 255, 85, 0, 255, 170, 0, 255, 255, 0, 170, 255, 0, 85, 255, 0, 0, 255, 255, 0, 170, 170, 0, 255, 255, 0, 255, 85, 0, 255, }; #endif OpenposePostProcessor::NET_OUT_CHANNELS = 3 * OpenposePostProcessor::MODEL_SIZE; OpenposePostProcessor::INITIALIZED = 1; } }; int OpenposePostProcessor::INITIALIZED = 0; int OpenposePostProcessor::MODEL_SIZE = 0; int OpenposePostProcessor::NET_OUT_CHANNELS = 0; vector<int> OpenposePostProcessor::POSE_MAP_INDEX; vector<int> OpenposePostProcessor::BODY_PART_PAIRS; vector<float> OpenposePostProcessor::COLORS; class YoloPostProcessor { public: YoloPostProcessor() { YoloPostProcessor::initialize(); } static void postProcess(const DarknetNet &net, Mat &imageInput, float *output, float scale, float thresh = 0.25, float hierarchyThresh = 0.5, int letterBox = 0, int printDetections = 0) { initialize(); int nrBoxes = 0; detection *detections = get_network_boxes(net.net, imageInput.cols, imageInput.rows, thresh, hierarchyThresh, nullptr, 1, &nrBoxes, letterBox); if (YoloPostProcessor::NMS != 0) { if (net.lastDetectionLayer.nms_kind == DEFAULT_NMS) { do_nms_sort(detections, nrBoxes, net.lastDetectionLayer.classes, YoloPostProcessor::NMS); } else { diounms_sort(detections, nrBoxes, net.lastDetectionLayer.classes, YoloPostProcessor::NMS, net.lastDetectionLayer.nms_kind, net.lastDetectionLayer.beta_nms); } } // scale detections for (int i = 0; i < nrBoxes; i++) { float xScale = (scale * (float) net.inW) / ((float) imageInput.cols); detections[i].bbox.x *= xScale; detections[i].bbox.w *= xScale; float yScale = (scale * (float) net.inH) / ((float) imageInput.rows); detections[i].bbox.y *= yScale; detections[i].bbox.h *= yScale; } Mat *imagePtr = &imageInput; draw_detections_cv_v3((void ***) &imagePtr, detections, nrBoxes, thresh, net.names, net.alphabet, net.lastDetectionLayer.classes, printDetections); free_detections(detections, nrBoxes); } private: static int INITIALIZED; static float NMS; static void initialize() { if (YoloPostProcessor::INITIALIZED) { return; } YoloPostProcessor::INITIALIZED = 1; } }; int YoloPostProcessor::INITIALIZED = 0; float YoloPostProcessor::NMS = .45; // 0.4F; #pragma clang diagnostic push #pragma ide diagnostic ignored "hicpp-signed-bitwise" Mat createNetSizeImage(const Mat &im, const int netW, const int netH, float &scale) { // for tall image int newH = netH; float s = (float) newH / (float) im.rows; int newW = (int) ((float) im.cols * s); if (newW > netW) { // for fat image newW = netW; s = (float) newW / (float) im.cols; newH = (int) ((float) im.rows * s); } scale = 1 / s; Rect dst_area(0, 0, newW, newH); Mat dst = Mat::zeros(netH, netW, CV_8UC3); resize(im, dst(dst_area), Size(newW, newH)); return dst; } void preProcessImage(float *netInput, Mat &image, int netInW, int netInH, float &scale, bool yolo = false) { // cout << "Enter preProcessImage..." << endl; double timeBegin = getTickCount(); // cout << "Resize image to net input..." << endl; // 3. resize to net input size, put scaled image on the top left Mat netIm = createNetSizeImage(image, netInW, netInH, scale); // cout << "Normalize input image..." << endl; // 4. normalized to float type cv::cvtColor(netIm, netIm, cv::COLOR_RGB2BGR); //* netIm.convertTo(netIm, CV_32F); /*/ if (yolo) { netIm.convertTo(netIm, CV_32F, 1 / 255.f, 0.0); } else { netIm.convertTo(netIm, CV_32F, 1 / 256.f, -0.5); } //*/ // cout << "Splitting image channels..." << endl; // 5. split channels float *netInDataPtr = netInput; vector<Mat> inputChannels; for (int i = 0; i < 3; ++i) { Mat channel(netInH, netInW, CV_32FC1, netInDataPtr); inputChannels.emplace_back(channel); netInDataPtr += (netInW * netInH); } split(netIm, inputChannels); double feeTime = (getTickCount() - timeBegin) / getTickFrequency() * 1000; cout << "pre-process time: " << feeTime << "ms" << endl; } #pragma clang diagnostic pop class Workflow { public: explicit Workflow(DarknetNet *net, float *netInput, const char *windowName, volatile int *stop) : net(net), netInput(netInput), windowName(windowName), stop(stop), scale(0.0) { this->processStart = new volatile int(0); this->postProcessStart = new volatile int(0); this->processThread = thread(&Workflow::processThreadFunction, this); this->postProcessThread = thread(&Workflow::postProcessThreadFunction, this); namedWindow(this->windowName); } ~Workflow() { this->finish(); } void process() { preProcessImage(this->netInput, *(this->inputImage), this->net->inW, this->net->inH, this->scale); // cout << "Feeding forward through network..." << endl; // 6. feed forward double timeBegin = getTickCount(); this->netOutData = this->net->runNet(this->netInput); double feeTime = (getTickCount() - timeBegin) / getTickFrequency() * 1000; cout << "process time: " << feeTime << "ms" << endl; } void postProcess() { if (this->outputImage == nullptr) { return; } double timeBegin = getTickCount(), feeTime; OpenposePostProcessor::postProcess(*(this->net), *(this->outputImage), this->netOutData, this->scale); feeTime = (getTickCount() - timeBegin) / getTickFrequency() * 1000; cout << "Openpose post-process time: " << feeTime << "ms" << endl; timeBegin = getTickCount(); YoloPostProcessor::postProcess(*(this->net), *(this->outputImage), this->netOutData, this->scale); feeTime = (getTickCount() - timeBegin) / getTickFrequency() * 1000; cout << "YOLO post-process time: " << feeTime << "ms" << endl; } void processThreadFunction() { while (!custom_atomic_load_int(this->stop)) { while (!custom_atomic_load_int(this->processStart)) { if (custom_atomic_load_int(this->stop)) return; this_thread::yield(); } this->process(); custom_atomic_store_int(this->processStart, 0); } } void postProcessThreadFunction() { while (!custom_atomic_load_int(this->stop)) { while (!custom_atomic_load_int(this->postProcessStart)) { if (custom_atomic_load_int(this->stop)) return; this_thread::yield(); } this->postProcess(); custom_atomic_store_int(this->postProcessStart, 0); } } static void threadBarrier(volatile int *threadVariable) { while (custom_atomic_load_int(threadVariable)) { std::chrono::milliseconds duration(Workflow::threadSleepTime); std::this_thread::sleep_for(duration); } } bool workflow(Mat inImage, int wait = 1) { this->inputImage = new Mat(std::move(inImage)); custom_atomic_store_int(this->processStart, 1); custom_atomic_store_int(this->postProcessStart, 1); Workflow::threadBarrier(this->processStart); Workflow::threadBarrier(this->postProcessStart); bool result = true; if (this->outputImage != nullptr) { imshow(this->windowName, *(this->outputImage)); int key = cv::waitKey(wait); if (key == 27 || key == 'q') { result = false; } delete this->outputImage; this->outputImage = nullptr; } this->outputImage = this->inputImage; return result; } void finish() { this->inputImage = nullptr; delete this->outputImage; this->outputImage = nullptr; custom_atomic_store_int(this->stop, 1); this->processThread.join(); this->postProcessThread.join(); destroyAllWindows(); } private: thread processThread, postProcessThread; static const int threadSleepTime = 1; volatile int *stop, *processStart, *postProcessStart; const char *windowName; float *netOutData{}, *netInput, scale; DarknetNet *net{}; Mat *inputImage{}, *outputImage{}; }; void cameraInput(DarknetNet &net) { VideoCapture camera(0); if (!camera.isOpened()) { cout << "Error!" << endl; return; } Mat im; auto *netInData = new float[net.inW * net.inH * 3](); volatile int stop = 0; Workflow w(&net, netInData, (const char *) "demo", &stop); while (!custom_atomic_load_int(&stop)) { camera.read(im); if (im.empty()) { cout << "Image empty Error!" << endl; return; } if (!w.workflow(im)) { custom_atomic_store_int(&stop, 1); } } delete[] netInData; } void realsenseInput(DarknetNet &net) { try { rs2::pipeline pipe; auto config = pipe.start(); auto profile = config.get_stream(RS2_STREAM_COLOR).as<rs2::video_stream_profile>(); rs2::align alignTo(RS2_STREAM_COLOR); cout << "Started RealSense pipeline!" << endl; unsigned long long lastFrameNumber = 0; auto *netInData = new float[net.inW * net.inH * 3](); volatile int *stop = new volatile int(0); // custom_atomic_store_int(&stop, 0); Workflow w(&net, netInData, (const char *) "demo", stop); while (!custom_atomic_load_int(stop)) { rs2::frameset currentFrame = pipe.wait_for_frames(); currentFrame = alignTo.process(currentFrame); // Make sure the frames are spatially aligned // rs2::depth_frame depth = currentFrame.get_depth_frame(); rs2::video_frame image = currentFrame.get_color_frame(); if (image.get_frame_number() == lastFrameNumber) continue; lastFrameNumber = image.get_frame_number(); // auto depthMat = depth_frame_to_meters(depth); auto im = frame_to_mat(image); if (!w.workflow(im)) { custom_atomic_store_int(stop, 1); } } delete[] netInData; } catch (const rs2::error &e) { cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n" << " " << e.what() << endl; } catch (const exception &e) { cerr << e.what() << endl; } } void singleImageInput(DarknetNet &net, Mat &im) { auto *netInData = new float[net.inW * net.inH * 3](); volatile int stop = 0; Workflow w(&net, netInData, "demo", &stop); w.workflow(im, 0); w.finish(); delete[] netInData; } void selectMode(DarknetNet &net, char *mode, int argc, char **argv) { if (strcmp("image", mode) == 0) { if (argc < 6) { cout << "Image mode requires the image path as argument!" << endl; return; } Mat im = imread(argv[5]); if (im.empty()) { cout << "Failed to read image!" << endl; return; } singleImageInput(net, im); } else if (strcmp("camera", mode) == 0) { cameraInput(net); } else if (strcmp("realsense", mode) == 0) { realsenseInput(net); } } void workflow(char *dataPath, char *cfgPath, char *weightPath, char *mode, int argc, char **argv, int benchmarkLayers = 0) { // 1. initialize net DarknetNet net(cfgPath, weightPath, dataPath); net.initNet(benchmarkLayers); selectMode(net, mode, argc, argv); net.releaseNet(); } int main(int ac, char **av) { if (ac < 5) { cout << "usage: ./program [data cfg] [cfg file] [weight file] [mode] [mode arguments]" << endl; return 1; } char *dataCfg = av[1]; char *netCfg = av[2]; char *weightFile = av[3]; char *mode = av[4]; workflow(dataCfg, netCfg, weightFile, mode, ac, av); return 0; }
37,669
12,191
#include <string> #include <vector> #include <iostream> #include <cstring> // std::memcpy #include "core/sample.hpp" // trigno::sample::ID namespace trigno { Sample::Sample(sensor::ID id, size_t n_channels, const char* raw_data) : _id(id), _data(n_channels) { /* ... */ if (raw_data != nullptr) { for (int ch = 0; ch < n_channels; ch++) { std::memcpy(&_data[ch], raw_data, sizeof(_data[ch])); } } } Sample::Sample(sensor::ID id, const std::vector< float >& values) : _id(id), _data(values) { /* ... */ } sensor::ID Sample::id() const noexcept { return _id; } size_t Sample::size() const noexcept { return _data.size(); } bool Sample::empty() const noexcept { return _data.empty(); } float& Sample::operator[](size_t channel) { if (channel >= _data.size()) { throw std::out_of_range("[" + std::string(__func__) + "] Invalid channel index!!"); } return _data[channel]; } const float& Sample::operator[](size_t channel) const { if (channel >= _data.size()) { throw std::out_of_range("[" + std::string(__func__) + "] Invalid channel index!!"); } return _data[channel]; } const Sample::Container& Sample::data() const { return _data; } Sample::operator const Container&() const { return _data; } Sample::operator const Sample::Value&() const noexcept { return _data.front(); } Sample::Value Sample::average() const { auto avg = 0.0; for (const auto& value : _data) { avg += value; } return (avg/=size()); } std::vector< float >::iterator Sample::begin() { return _data.begin(); } std::vector< float >::const_iterator Sample::begin() const { return _data.begin(); } std::vector< float >::iterator Sample::end() { return _data.end(); } std::vector< float >::const_iterator Sample::end() const { return _data.end(); } } // namespace trigno
1,980
687
/* BSD 3-Clause License * * Copyright (c) 2020, Simon de Hartog <simon@dehartog.name> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * vim:set ts=4 sw=4 noexpandtab: */ #include <cerrno> #include <ctime> #include <iomanip> #include <iostream> #include <sstream> #include <stdexcept> #include "HoursMinutes.h" namespace SdH { uint8_t HoursMinutes::parseChar(const char char_i) { if (char_i < '0' || char_i > '9') { throw std::invalid_argument( std::string("Invalid character '") + char_i + "' in time string" ); } return char_i - '0'; } uint8_t HoursMinutes::parse(const std::string & str_i, const uint8_t max_i) { if (str_i.empty() || str_i == "0" || str_i == "00") return 0; uint8_t rv = 0; // Return Value switch (str_i.size()) { case 2: rv = parseChar(str_i[0]) * 10 + parseChar(str_i[1]); break; case 1: rv = parseChar(str_i[0]); break; default: throw std::invalid_argument("Integer string longer than two characters"); } if (rv > max_i) { std::ostringstream oss; oss << "String value \"" << str_i << "\" is a valid integer but is larger than "; oss << static_cast<uint16_t>(max_i); throw std::overflow_error(oss.str()); } return rv; } void HoursMinutes::set(const std::string & hm_i) { size_t pos = 0; uint8_t tmphrs = 0; uint8_t tmpmin = 0; if (hm_i.empty() || hm_i == ":") { reset(); return; } pos = hm_i.find(':'); if (pos == std::string::npos) { // No hours specified, just minutes tmpmin = parse(hm_i, 59); hours_a = 0; minutes_a = tmpmin; return; } tmphrs = parse(hm_i.substr(0, pos), 23); tmpmin = parse(hm_i.substr(pos+1), 59); hours_a = tmphrs; minutes_a = tmpmin; } void HoursMinutes::set(const time_t & time_i) { struct tm *tmptr = nullptr; tmptr = localtime(&time_i); if (tmptr == nullptr) { throw std::runtime_error("Unable to break down time to parts"); } hours_a = tmptr->tm_hour; minutes_a = tmptr->tm_min; } HoursMinutes & HoursMinutes::operator+=(const HoursMinutes & rhs_i) { hours_a += rhs_i.hours_a; minutes_a += rhs_i.minutes_a; if (minutes_a > 59) { hours_a++; minutes_a %= 60; } if (hours_a > 23) hours_a %= 24; return (*this); } } // SdH namespace std::ostream & operator<<(std::ostream & os, const SdH::HoursMinutes & hm) { os << std::dec << std::setw(2) << std::setfill('0') << static_cast<uint16_t>(hm.hours()); os << ':'; os << std::dec << std::setw(2) << std::setfill('0') << static_cast<uint16_t>(hm.minutes()); return os; }
4,050
1,702
#ifndef VERBATIM_VERTEX_BUFFER #define VERBATIM_VERTEX_BUFFER #include "verbatim_array.hpp" #include "verbatim_vertex.hpp" // Forward declaration. class Program; /** Vertex buffer. */ class VertexBuffer { private: /** Current vertex buffer. */ static const VertexBuffer* g_bound_vertex_buffer; /** Currently programmed vertex buffer. */ static const VertexBuffer* g_programmed_vertex_buffer; private: /** OpenGL id. */ GLuint m_id_data[2]; /** Vertex array. */ Array<Vertex> m_vertices; /** Index array. */ Array<uint16_t> m_indices; private: /** \brief Accessor. * * \return Vertex buffer OpenGL id. */ GLuint getVertexId() const { return m_id_data[0]; } /** \brief Accessor. * * \return Index buffer OpenGL id. */ GLuint getIndexId() const { return m_id_data[1]; } public: /** \brief Accessor. * * \param idx Index of vertex to access. * \return Vertex at given index. */ const Vertex& getVertex(size_t idx) const { return m_vertices[idx]; } public: /** \brief Constructor. */ VertexBuffer(); public: /** \brief Add face to this vertex buffer. * * \param op Index to add. */ void addIndex(uint16_t op) { #if defined(USE_LD) if(g_debug) { std::cout << op << std::endl; } #endif m_indices.add(op); } /** \brief Add vertex to this vertex buffer. * * \param op Vertex to add. */ void addVertex(const Vertex &op) { #if defined(USE_LD) if(g_debug) { std::cout << op << std::endl; } #endif m_vertices.add(op); } /** \brief Tell if amount of vertices fits in this vertex buffer. * * \param op Number of offered vertices. * \return True if fits, false if not. */ bool fitsVertices(size_t op) { return (65536 >= (m_vertices.getSize() + op)); } /** \brief Accessor. * * \return Index count. */ size_t getIndexCount() const { return m_indices.getSize(); } /** \brief Accessor. * * \return Vertex count. */ size_t getVertexCount() const { return m_vertices.getSize(); } private: /** \brief Bind this vertex buffer for rendering and/or modification. */ void bind() const; public: /** \brief Update this vertex buffer into the GPU. * * \param indicesEnabled Set to true (default) if index buffer is relevant and should be uploaded. */ void update(bool indicesEnabled = true); /** \brief Use this vertex buffer for rendering. * * \param op Program to use. */ void use(const Program *op) const; public: /** \brief Reset programmed vertex buffer. * * Must be done when changing a program. */ static void reset_programmed_vertex_buffer() { g_programmed_vertex_buffer = NULL; } /** \brief Unbind vertex buffer. */ static void unbind() { dnload_glBindBuffer(GL_ARRAY_BUFFER, 0); dnload_glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); g_bound_vertex_buffer = NULL; reset_programmed_vertex_buffer(); } #if defined(USE_LD) public: /** \brief Print operator. * * \param lhs Left-hand-side operand. * \param rhs Right-hand-side operand. */ friend std::ostream& operator<<(std::ostream &lhs, const VertexBuffer &rhs) { return lhs << "VertexBuffer(" << &rhs << ')'; } #endif }; #endif
3,592
1,225
//write include statements #include"variables.h" //write namespace using statement for cout using std::cin; using std::cout; /* Call multiply_numbers with 10 and 10 parameter values and display function result */ int main() { double meal_amount; double tip_rate; double tip_amount; double tax_amount; double total; cout<<"Enter your meal amount here: "; cin>>meal_amount; tax_amount = get_sales_tax(meal_amount); cout<<"Enter the percent tip here without the percent sign decimals: "; cin>>tip_rate; tip_amount = get_tip_amount(meal_amount, tip_rate); total = tax_amount + meal_amount + tip_amount; cout<<"\n"<<"Your meal amount is: "<<meal_amount<<"\n"; cout<<"The sales tax is: "<<tax_amount<<"\n"; cout<<"Your tip amount is: "<<tip_amount<<"\n"; cout<<"Your total is: "<<total; return 0; }
821
298
/* * Copyright (c) 2016 K. Isom <coder@kyleisom.net> * * Permission is hereby granted, free of charge, to any person obtaining a copy * 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 <cstdint> #include <cstring> #include <ctime> #include <map> #include <ostream> #include <sstream> #include <string> #include <klogger/tlv.hh> namespace klog { namespace tlv { static const char hexlut[] = "0123456789ABCDEF"; std::string hex_encode(const std::string& s) { size_t length = s.size(); std::string out; out.reserve(2 * length); for (size_t i = 0; i < length; i++) { unsigned char c = s[i]; out.push_back(hexlut[c >> 4]); out.push_back(hexlut[c & 0xF]); } return out; } std::string hex_encode(const char *s, size_t length) { std::string out; out.reserve(2 * length); for (size_t i = 0; i < length; i++) { unsigned char c = s[i]; out.push_back(hexlut[c >> 4]); out.push_back(hexlut[c & 0xF]); } return out; } static inline void write_tag(std::ostream& outs, std::uint8_t t) { outs.write(reinterpret_cast<const char *>(&t), 1); } static inline size_t length_octets(size_t length) { std::uint8_t loct = 1; if (length <= 0x7F) { return loct; } for (size_t i = (sizeof(length) * 8) - 1; i >= 1; i--) { size_t bits = 1; bits <<= i; if (0 == (length & bits)) { continue; } loct = (i + 8) >> 3; break; } return loct; } bool write_length(std::ostream &outs, size_t length) { std::uint8_t loct = 1; if (length <= 0x7F) { outs.write(reinterpret_cast<const char *>(&length), 1); } else { for (size_t i = (sizeof(length) * 8) - 1; i >= 1; i--) { size_t bits = 1; bits <<= i; if (0 == (length & bits)) { continue; } loct = (i + 8) >> 3; break; } loct = 0x80 + loct; outs.write(reinterpret_cast<const char *>(&loct), 1); if (!outs.good()) { return false; } char buf[8]; ::memcpy(buf, &length, 8); size_t sz = sizeof(length); for (size_t i = 0; i < sz / 2; i++) { char tmp = buf[i]; buf[i] = buf[sz-i-1]; buf[sz-i-1] = tmp; } size_t off = 0; for (size_t i = 0; i < sz; i++) { if (0 != (buf[i] & 0xFF)) { off = i; break; } } outs.write(reinterpret_cast<const char *>(buf+off), sz-off); if (!outs.good()) { return false; } } return outs.good(); } bool write_timestamp(std::ostream &outs, uint64_t t) { write_tag(outs, TTimestamp); if (!outs.good()) { return false; } if (!write_length(outs, sizeof(t))) { return false; } char buf[8]; ::memcpy(buf, &t, sizeof(t)); size_t sz = sizeof(t); for (size_t i = 0; i < sz / 2; i++) { char tmp = buf[i]; buf[i] = buf[sz-i-1]; buf[sz-i-1] = tmp; } outs.write(reinterpret_cast<const char *>(buf), sz); return outs.good(); } bool write_loglevel(std::ostream &outs, std::uint8_t lvl) { write_tag(outs, TLevel); if (!outs.good()) { return false; } if (!write_length(outs, sizeof(lvl))) { return false; } outs.write(reinterpret_cast<const char *>(&lvl), sizeof(lvl)); return outs.good(); } bool write_string(std::ostream &outs, std::string s) { size_t length = s.size(); write_tag(outs, TString); if (!outs.good()) { return false; } if (!write_length(outs, length)) { return false; } outs.write(reinterpret_cast<const char *>(s.c_str()), length); return outs.good(); } bool write_header(std::ostream& outs, std::uint8_t tag, std::uint64_t length) { write_tag(outs, tag); if (!outs.good()) { return false; } return write_length(outs, length); } static inline size_t string_record_length(std::string s) { size_t slen = s.size(); size_t length; length = sizeof(TString); length += length_octets(slen); length += slen; return length; } static inline size_t log_length(std::string actor, std::string event, std::map<std::string, std::string> attrs) { // Timestamp record is 1 byte tag + 1 byte length + 8 byte // value (10 bytes total); level record is 1 byte tag + // 1 byte length + 1 byte value (3 bytes). size_t length = 13; length += string_record_length(actor); length += string_record_length(event); for (auto it = attrs.begin(); it != attrs.end(); it++) { length += string_record_length(it->first); length += string_record_length(it->second); } return length; } bool write_tlv_log(std::ostream& outs, std::uint8_t lvl, std::string actor, std::string event, std::map<std::string, std::string> attrs) { std::time_t t = std::time(nullptr); size_t l = log_length(actor, event, attrs); if (!write_header(outs, TLogEntry, static_cast<std::uint64_t>(l))) { return false; } if (!write_timestamp(outs, std::uint64_t(t))) { return false; } else if (!write_loglevel(outs, lvl)) { return false; } else if (!write_string(outs, actor)) { return false; } else if (!write_string(outs, event)) { return false; } for (auto it = attrs.begin(); it != attrs.end(); it++) { if (!write_string(outs, it->first)) { return false; } else if (!write_string(outs, it->second)) { return false; } } return outs.good(); } } // namespace tlv } // namespace klog
6,080
2,637
/****************************************************************************** ** ** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com> ** All rights reserved. ** ** This file is a part of the chemkit project. For more information ** see <http://www.chemkit.org>. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** * Neither the name of the chemkit project nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ******************************************************************************/ #include "graphicstool.h" #include "graphicsview.h" namespace chemkit { // === GraphicsToolPrivate ================================================= // class GraphicsToolPrivate { public: GraphicsView *view; }; // === GraphicsTool ======================================================== // /// \class GraphicsTool graphicstool.h chemkit/graphicstool.h /// \ingroup chemkit-graphics /// \brief The GraphicsTool class handles graphics events for a /// GraphicsView. // --- Construction and Destruction ---------------------------------------- // /// Creates a new graphics tool. GraphicsTool::GraphicsTool() : d(new GraphicsToolPrivate) { d->view = 0; } /// Destroys the graphics tool. GraphicsTool::~GraphicsTool() { delete d; } // --- Properties ---------------------------------------------------------- // /// Sets the view to \p view. void GraphicsTool::setView(GraphicsView *view) { d->view = view; } /// Returns the view the tool is a part of. Returns \c 0 if the tool /// is not in any view. GraphicsView* GraphicsTool::view() const { return d->view; } // --- Event Handling------------------------------------------------------- // /// Handle a mouse press event. void GraphicsTool::mousePressEvent(QMouseEvent *event) { Q_UNUSED(event); } /// Handle a mouse release event. void GraphicsTool::mouseReleaseEvent(QMouseEvent *event) { Q_UNUSED(event); } /// Handle a mouse double click event. void GraphicsTool::mouseDoubleClickEvent(QMouseEvent *event) { Q_UNUSED(event); } /// Handle a mouse move event. void GraphicsTool::mouseMoveEvent(QMouseEvent *event) { Q_UNUSED(event); } /// Handle a mouse wheel event. void GraphicsTool::wheelEvent(QWheelEvent *event) { Q_UNUSED(event); } /// This method is called when the current tool in the view changes. /// /// \see GraphicsView::setTool() void GraphicsTool::toolChanged(const boost::shared_ptr<GraphicsTool> &tool) { Q_UNUSED(tool); } } // end chemkit namespace
3,865
1,181
#pragma once #include "Windows.hpp" #include <GLFW/glfw3.h> #include <functional> void framebuffer_size_callback(GLFWwindow* window, int width, int height); void ProcessInput(GLFWwindow *window); namespace TinySandbox { class GLFW_Windows : public Windows { public: GLFW_Windows(); GLFW_Windows(int width, int height, const char* title, ::GLFWmonitor *monitor, ::GLFWwindow *share); ~GLFW_Windows(); bool ShouldClose(); void Loop(); void SetInputCallback(std::function<void(GLFWwindow*)> _inputCallback); GLFWwindow* GetGLFWInstance(); private: GLFWwindow *m_glfwInstance; std::function<void(GLFWwindow*)> inputCallback; }; }
679
272
// This file if part of the llir-opt project. // Licensing information can be found in the LICENSE file. // (C) 2018 Nandor Licker. All rights reserved. #include <sstream> #include <llvm/Target/RISCV/RISCVInstrInfo.h> #include <llvm/Target/RISCV/MCTargetDesc/RISCVMCTargetDesc.h> #include "emitter/riscv/riscvannot_printer.h" namespace RISCV = llvm::RISCV; namespace TargetOpcode = llvm::TargetOpcode; using TargetInstrInfo = llvm::TargetInstrInfo; using StackVal = llvm::FixedStackPseudoSourceValue; // ----------------------------------------------------------------------------- char RISCVAnnotPrinter::ID; // ----------------------------------------------------------------------------- static const char *kRegNames[] = { "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16", "x17", "x18", "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28", "x29", "x30", "x31", }; // ----------------------------------------------------------------------------- RISCVAnnotPrinter::RISCVAnnotPrinter( llvm::MCContext *ctx, llvm::MCStreamer *os, const llvm::MCObjectFileInfo *objInfo, const llvm::DataLayout &layout, const ISelMapping &mapping, bool shared) : AnnotPrinter(ID, ctx, os, objInfo, layout, mapping, shared) { } // ----------------------------------------------------------------------------- RISCVAnnotPrinter::~RISCVAnnotPrinter() { } // ----------------------------------------------------------------------------- std::optional<unsigned> RISCVAnnotPrinter::GetRegisterIndex(llvm::Register reg) { switch (reg) { case RISCV::X5: return 0; case RISCV::X6: return 1; case RISCV::X7: return 2; case RISCV::X8: return 3; case RISCV::X9: return 4; case RISCV::X10: return 5; case RISCV::X11: return 6; case RISCV::X12: return 7; case RISCV::X13: return 8; case RISCV::X14: return 9; case RISCV::X15: return 10; case RISCV::X16: return 11; case RISCV::X17: return 12; case RISCV::X18: return 13; case RISCV::X19: return 14; case RISCV::X20: return 15; case RISCV::X21: return 16; case RISCV::X22: return 17; case RISCV::X23: return 18; case RISCV::X24: return 19; case RISCV::X25: return 20; case RISCV::X26: return 21; case RISCV::X27: return 22; case RISCV::X28: return 23; case RISCV::X29: return 24; case RISCV::X30: return 25; case RISCV::X31: return 26; default: return std::nullopt; } } // ----------------------------------------------------------------------------- llvm::StringRef RISCVAnnotPrinter::GetRegisterName(unsigned reg) { assert((reg < (sizeof(kRegNames) / sizeof(kRegNames[0]))) && "invalid reg"); return kRegNames[reg]; } // ----------------------------------------------------------------------------- llvm::Register RISCVAnnotPrinter::GetStackPointer() { return RISCV::X2; } // ----------------------------------------------------------------------------- llvm::StringRef RISCVAnnotPrinter::getPassName() const { return "LLIR RISCV Annotation Inserter"; }
3,098
1,159
// 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. #include "exec/parquet-common.h" namespace impala { /// Mapping of impala's internal types to parquet storage types. This is indexed by /// PrimitiveType enum const parquet::Type::type INTERNAL_TO_PARQUET_TYPES[] = { parquet::Type::BOOLEAN, // Invalid parquet::Type::BOOLEAN, // NULL type parquet::Type::BOOLEAN, parquet::Type::INT32, parquet::Type::INT32, parquet::Type::INT32, parquet::Type::INT64, parquet::Type::FLOAT, parquet::Type::DOUBLE, parquet::Type::INT96, // Timestamp parquet::Type::BYTE_ARRAY, // String parquet::Type::BYTE_ARRAY, // Date, NYI parquet::Type::BYTE_ARRAY, // DateTime, NYI parquet::Type::BYTE_ARRAY, // Binary NYI parquet::Type::FIXED_LEN_BYTE_ARRAY, // Decimal parquet::Type::BYTE_ARRAY, // VARCHAR(N) parquet::Type::BYTE_ARRAY, // CHAR(N) }; const int INTERNAL_TO_PARQUET_TYPES_SIZE = sizeof(INTERNAL_TO_PARQUET_TYPES) / sizeof(INTERNAL_TO_PARQUET_TYPES[0]); /// Mapping of Parquet codec enums to Impala enums const THdfsCompression::type PARQUET_TO_IMPALA_CODEC[] = { THdfsCompression::NONE, THdfsCompression::SNAPPY, THdfsCompression::GZIP, THdfsCompression::LZO }; const int PARQUET_TO_IMPALA_CODEC_SIZE = sizeof(PARQUET_TO_IMPALA_CODEC) / sizeof(PARQUET_TO_IMPALA_CODEC[0]); /// Mapping of Impala codec enums to Parquet enums const parquet::CompressionCodec::type IMPALA_TO_PARQUET_CODEC[] = { parquet::CompressionCodec::UNCOMPRESSED, parquet::CompressionCodec::SNAPPY, // DEFAULT parquet::CompressionCodec::GZIP, // GZIP parquet::CompressionCodec::GZIP, // DEFLATE parquet::CompressionCodec::SNAPPY, parquet::CompressionCodec::SNAPPY, // SNAPPY_BLOCKED parquet::CompressionCodec::LZO, }; const int IMPALA_TO_PARQUET_CODEC_SIZE = sizeof(IMPALA_TO_PARQUET_CODEC) / sizeof(IMPALA_TO_PARQUET_CODEC[0]); parquet::Type::type ConvertInternalToParquetType(PrimitiveType type) { DCHECK_GE(type, 0); DCHECK_LT(type, INTERNAL_TO_PARQUET_TYPES_SIZE); return INTERNAL_TO_PARQUET_TYPES[type]; } THdfsCompression::type ConvertParquetToImpalaCodec( parquet::CompressionCodec::type codec) { DCHECK_GE(codec, 0); DCHECK_LT(codec, PARQUET_TO_IMPALA_CODEC_SIZE); return PARQUET_TO_IMPALA_CODEC[codec]; } parquet::CompressionCodec::type ConvertImpalaToParquetCodec( THdfsCompression::type codec) { DCHECK_GE(codec, 0); DCHECK_LT(codec, IMPALA_TO_PARQUET_CODEC_SIZE); return IMPALA_TO_PARQUET_CODEC[codec]; } }
3,257
1,248
#include "../../../../include/odfaeg/Graphics/GUI/filedialog.hpp" #include "../../../../include/odfaeg/Math/maths.h" #include <filesystem> namespace odfaeg { namespace graphic { namespace gui { FileDialog::FileDialog(math::Vec3f position, math::Vec3f size, const Font* font) : rw(sf::VideoMode(size.x, size.y), "File Dialog", sf::Style::Default, window::ContextSettings(0, 0, 0, 3, 0)), LightComponent (rw, position, size, size * 0.5), font(font) { std::cout<<"position : "<<getPosition()<<std::endl; rw.setPosition(sf::Vector2i(position.x, position.y)); pTop = new Panel (rw, position, size); pBottom = new Panel (rw, position, size); pDirectories = new Panel (rw, position, size); pFiles = new Panel (rw, position, size); lTop = new Label (rw, position, size, font, "", 15); bChoose = new Button (position, size, font, "Choose", 15, rw); bCancel = new Button (position, size, font, "Cancel", 15, rw); pTop->setRelPosition(0.f, 0.f); pTop->setRelSize(1.f, 0.1f); pDirectories->setRelPosition(0.f, 0.1f); pDirectories->setRelSize(0.5f, 0.8f); pFiles->setRelPosition(0.5f, 0.1f); pFiles->setRelSize(0.5f, 0.8f); pBottom->setRelPosition(0.f, 0.9f); pBottom->setRelSize(1.f, 0.1f); pTop->setParent(this); pBottom->setParent(this); pDirectories->setParent(this); pFiles->setParent(this); addChild(pTop); addChild(pBottom); addChild(pDirectories); addChild(pFiles); lTop->setParent(pTop); bChoose->setParent(pBottom); bCancel->setParent(pBottom); bChoose->addActionListener(this); bCancel->addActionListener(this); std::string currentPath = std::filesystem::current_path(); lTop->setRelPosition(0.f, 0.f); lTop->setRelSize(1.f, 1.f); lTop->setForegroundColor(sf::Color::Black); pTop->addChild(lTop); lTop->setText(currentPath); lTop->setBackgroundColor(sf::Color::Red); appliDir = lTop->getText(); std::string textDir; #if defined (ODFAEG_SYSTEM_LINUX) if (DIR* root = opendir("/")) { dirent* ent; unsigned int i = 0; while((ent = readdir(root)) != NULL) { if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) { textDir = std::string(ent->d_name); Label* lDirectory = new Label(rw, position, size, font, "",15); //lDirectory->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255)); lDirectory->setParent(pDirectories); lDirectory->setRelPosition(0.f, 0.04f * i); lDirectory->setRelSize(1, 0.04f); pDirectories->addChild(lDirectory); lDirectory->setText(sf::String(textDir)); core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left); core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lDirectory), core::FastDelegate<void>(&FileDialog::onDirSelected, this, lDirectory)); if(ent->d_type == DT_DIR) { lDirectory->setForegroundColor(sf::Color::Red); getListener().connect("1d"+textDir, cmd); } else { getListener().connect("1f"+textDir, cmd); } i++; } } } currentPath = lTop->getText(); if (DIR* current = opendir(currentPath.c_str())) { dirent *ent; std::string fileNames; unsigned int i = 0; while ((ent = readdir(current)) != NULL) { if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) { fileNames = std::string(ent->d_name); Label* lFile = new Label(rw, position, size, font, "",15); //lFile->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255)); lFile->setParent(pFiles); lFile->setRelPosition(0.f, 0.04f * i); lFile->setRelSize(1.f, 0.04f); pFiles->addChild(lFile); lFile->setText(sf::String(fileNames)); core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left); core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lFile), core::FastDelegate<void>(&FileDialog::onFileSelected, this, lFile)); if(ent->d_type == DT_DIR) { lFile->setForegroundColor(sf::Color::Red); getListener().connect("2d"+fileNames, cmd); } else { getListener().connect("2f"+fileNames, cmd); } i++; } } } #else if defined(ODFAEG_SYSTEM_WINDOWS) if (DIR* root = opendir("C:\\")) { dirent* ent; struct stat st; unsigned int i = 0; while((ent = readdir(root)) != NULL) { if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) { textDir = std::string(ent->d_name); std::string fullPath = "C:\\" + textDir; stat(fullPath.c_str(), &st); Label* lDirectory = new Label(rw, position, size, font, "",15); //lDirectory->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255)); lDirectory->setParent(pDirectories); lDirectory->setRelPosition(0.f, 0.04f * i); lDirectory->setRelSize(1, 0.04f); pDirectories->addChild(lDirectory); lDirectory->setText(textDir); core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left); core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lDirectory), core::FastDelegate<void>(&FileDialog::onDirSelected, this, lDirectory)); if(S_ISDIR(st.st_mode)) { lDirectory->setForegroundColor(sf::Color::Red); getListener().connect("1d"+textDir, cmd); } else { lDirectory->setForegroundColor(sf::Color::Black); getListener().connect("1f"+textDir, cmd); } i++; } } } currentPath = lTop->getText(); if (DIR* current = opendir(currentPath.c_str())) { dirent *ent; struct stat st; std::string fileNames; unsigned int i = 0; while ((ent = readdir(current)) != NULL) { if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) { fileNames = std::string(ent->d_name); stat(fileNames.c_str(), &st); Label* lFile = new Label(rw, position, size, font, "",15); //lFile->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255)); lFile->setParent(pFiles); lFile->setRelPosition(0.f, 0.04f * i); lFile->setRelSize(1.f, 0.04f); pFiles->addChild(lFile); lFile->setText(fileNames); core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left); core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lFile), core::FastDelegate<void>(&FileDialog::onFileSelected, this, lFile)); if(S_ISDIR(st.st_mode)) { lFile->setForegroundColor(sf::Color::Red); getListener().connect("2d"+fileNames, cmd); } else { lFile->setForegroundColor(sf::Color::Black); getListener().connect("2f"+fileNames, cmd); } i++; } } } #endif bChoose->setRelPosition(0.7f, 0.1f); bChoose->setRelSize(0.1f, 0.8f); bChoose->setParent(pBottom); pBottom->addChild(bChoose); bCancel->setRelPosition(0.85f, 0.1f); bCancel->setRelSize(0.1f, 0.8f); bCancel->setParent(pBottom); pBottom->addChild(bCancel); setRelPosition(0, 0); setRelSize(1, 1); setAutoResized(true); } void FileDialog::clear() { rw.clear(); pTop->clear(); pBottom->clear(); pDirectories->clear(); pFiles->clear(); } void FileDialog::onDraw(RenderTarget& target, RenderStates states) { //if (rw.isOpen()) { target.draw(*pTop, states); target.draw(*pDirectories, states); target.draw(*pFiles, states); target.draw(*pBottom, states); //} } void FileDialog::onDirSelected(Label* label) { for (unsigned int i = 0; i < pFiles->getChildren().size(); i++) { if (static_cast<Label*>(pFiles->getChildren()[i])->getForegroundColor() == sf::Color::Red) { getListener().removeCommand("2d"+static_cast<Label*>(pFiles->getChildren()[i])->getText()); } else { getListener().removeCommand("2f"+static_cast<Label*>(pFiles->getChildren()[i])->getText()); } } pFiles->removeAll(); for (unsigned int i = 0; i < pDirectories->getChildren().size(); i++) { static_cast<Label*>(pDirectories->getChildren()[i])->setBackgroundColor(sf::Color::Black); } std::string dirName; #if defined (ODFAEG_SYSTEM_LINUX) dirName = "/" + label->getText(); #else if defined (ODFAEG_SYSTEM_WINDOWS) dirName = "C:\\" + label->getText(); #endif // if std::string currentDir = dirName; lTop->setText(currentDir); label->setBackgroundColor(sf::Color::Blue); if (label->getForegroundColor() == sf::Color::Red) { #if defined (ODFAEG_SYSTEM_LINUX) if (DIR* current = opendir(dirName.c_str())) { dirent *ent; std::string fileNames; unsigned int i = 0; while ((ent = readdir(current)) != NULL) { if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) { fileNames = std::string(ent->d_name); Label* lFile = new Label(rw, getPosition(), getSize(), font, "",15); //lFile->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255)); lFile->setParent(pFiles); lFile->setRelPosition(0.f, 0.04f * i); lFile->setRelSize(1.f, 0.04f); pFiles->addChild(lFile); lFile->setText(fileNames); core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left); core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lFile), core::FastDelegate<void>(&FileDialog::onFileSelected, this, lFile)); if(ent->d_type == DT_DIR) { lFile->setForegroundColor(sf::Color::Red); getListener().connect("2d"+fileNames, cmd); } else { getListener().connect("2f"+fileNames, cmd); } i++; } } closedir(current); } #else if defined (ODFAEG_SYSTEM_WINDOWS) if (DIR* current = opendir(dirName.c_str())) { dirent *ent; struct stat st; std::string fileNames; unsigned int i = 0; while ((ent = readdir(current)) != NULL) { if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) { fileNames = std::string(ent->d_name); std::string fullPath = currentDir + "\\" + fileNames; stat(fullPath.c_str(), &st); Label* lFile = new Label(rw, getPosition(), getSize(), font, "",15); //lFile->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255)); lFile->setParent(pFiles); lFile->setRelPosition(0.f, 0.04f * i); lFile->setRelSize(1.f, 0.04f); lFile->setName("LFILE"); pFiles->addChild(lFile); lFile->setText(fileNames); core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left); core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lFile), core::FastDelegate<void>(&FileDialog::onFileSelected, this, lFile)); if(S_ISDIR(st.st_mode)) { lFile->setForegroundColor(sf::Color::Red); getListener().connect("2d"+fileNames, cmd); } else { lFile->setForegroundColor(sf::Color::Black); getListener().connect("2f"+fileNames, cmd); } i++; } } closedir(current); } #endif } setAutoResized(true); } void FileDialog::onFileSelected(Label* label) { std::string fileName = label->getText(); sf::Color color = label->getForegroundColor(); if (color == sf::Color::Red) { for (unsigned int i = 0; i < pFiles->getChildren().size(); i++) { if (static_cast<Label*>(pFiles->getChildren()[i])->getForegroundColor() == sf::Color::Red) { if (static_cast<Label*>(pFiles->getChildren()[i])->getText() == label->getText()) getListener().removeLater("2d"+static_cast<Label*>(pFiles->getChildren()[i])->getText()); else getListener().removeCommand("2d"+static_cast<Label*>(pFiles->getChildren()[i])->getText()); } else { if (static_cast<Label*>(pFiles->getChildren()[i])->getText() == label->getText()) getListener().removeLater("2f"+static_cast<Label*>(pFiles->getChildren()[i])->getText()); else getListener().removeCommand("2f"+static_cast<Label*>(pFiles->getChildren()[i])->getText()); } } pFiles->removeAll(); std::string currentDir = lTop->getText(); #if defined (ODFAEG_SYSTEM_LINUX) currentDir += "/"+fileName; #else if defined (ODFAEG_SYSTEM_WINDOWS) currentDir += "\\"+fileName; #endif // if lTop->setText(currentDir); #if defined (ODFAEG_SYSTEM_LINUX) if (DIR* current = opendir(currentDir.c_str())) { dirent *ent; std::string fileNames; unsigned int i = 0; while ((ent = readdir(current)) != NULL) { if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) { fileNames = std::string(ent->d_name); Label* lFile = new Label(rw, getPosition(), getSize(), font, "",15); //lFile->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255)); lFile->setParent(pFiles); lFile->setRelPosition(0.f, 0.04f * i); lFile->setRelSize(1.f, 0.04f); pFiles->addChild(lFile); lFile->setText(fileNames); core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left); core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lFile), core::FastDelegate<void>(&FileDialog::onFileSelected, this, lFile)); if(ent->d_type == DT_DIR) { lFile->setForegroundColor(sf::Color::Red); getListener().connect("2d"+fileNames, cmd); } else { getListener().connect("2f"+fileNames, cmd); } i++; } } closedir(current); } #else if defined (ODFAEG_SYSTEM_WINDOWS) if (DIR* current = opendir(currentDir.c_str())) { dirent *ent; struct stat st; std::string fileNames; unsigned int i = 0; while ((ent = readdir(current)) != NULL) { if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) { fileNames = std::string(ent->d_name); std::string fullPath = currentDir + "\\" + fileNames; stat(fullPath.c_str(), &st); Label* lFile = new Label(rw, getPosition(), getSize(), font, "",15); //lFile->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255)); lFile->setParent(pFiles); lFile->setRelPosition(0.f, 0.04f * i); lFile->setRelSize(1.f, 0.04f); pFiles->addChild(lFile); lFile->setText(fileNames); lFile->setName("LFILE"); core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left); core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lFile), core::FastDelegate<void>(&FileDialog::onFileSelected, this, lFile)); if(S_ISDIR(st.st_mode)) { lFile->setForegroundColor(sf::Color::Red); getListener().connect("2d"+fileNames, cmd); } else { lFile->setForegroundColor(sf::Color::Black); getListener().connect("2f"+fileNames, cmd); } i++; } } closedir(current); } #endif } else { for (unsigned int i = 0; i < pFiles->getChildren().size(); i++) { static_cast<Label*>(pFiles->getChildren()[i])->setBackgroundColor(sf::Color::Black); } label->setBackgroundColor(sf::Color::Blue); } setAutoResized(true); } std::string FileDialog::getPathChosen() { std::string path = pathChosen; pathChosen = ""; return path; } std::string FileDialog::getAppiDir() { return appliDir; } void FileDialog::onEventPushed(window::IEvent event, RenderWindow& window) { if (event.type == window::IEvent::WINDOW_EVENT && event.mouseButton.type == window::IEvent::WINDOW_EVENT_CLOSED) { rw.setVisible(false); } /*for (unsigned int i = 0; i < pDirectories.getChildren().size(); i++) { pDirectories.getChildren()[i]->onUpdate(&getWindow(), event); } for (unsigned int i = 0; i < pFiles.getChildren().size(); i++) { pFiles.getChildren()[i]->onUpdate(&getWindow(), event); } bChoose.onUpdate(&getWindow(), event); bCancel.onUpdate(&getWindow(), event); getListener().pushEvent(event); bChoose.getListener().pushEvent(event); bCancel.getListener().pushEvent(event);*/ } void FileDialog::onVisibilityChanged(bool visible) { rw.setVisible(visible); } void FileDialog::actionPerformed(Button* button) { if (button->getText() == "Choose") { for (unsigned int i = 0; i < pDirectories->getChildren().size(); i++) { Label* label = static_cast<Label*>(pDirectories->getChildren()[i]); if (label->getForegroundColor() == sf::Color::Black && label->getBackgroundColor() == sf::Color::Blue) { pathChosen = lTop->getText(); return; } } for (unsigned int i = 0; i < pFiles->getChildren().size(); i++) { Label* label = static_cast<Label*>(pFiles->getChildren()[i]); if (label->getForegroundColor() == sf::Color::Black && label->getBackgroundColor() == sf::Color::Blue) { #if defined (ODFAEG_SYSTEM_LINUX) pathChosen = lTop->getText()+"/"+label->getText(); #else if defined (ODFAEG_SYSTEM_WINDOWS) pathChosen = lTop->getText()+"\\"+label->getText(); #endif // if } } } else if (button->getText() == "Cancel") { rw.setVisible(false); } } } } }
25,386
6,686
#include "StdH.h" #include "Paths.h" MRAGPP_NAMESPACE_BEGIN; CPaths::CPaths() { ps_iIterator = 0; } CPaths::~CPaths() { ps_aPaths.Clear(); } CPath& CPaths::Create(const Vector2f &vPos1, const Vector2f &vPos2, int iTotalFrameCount, mragPathsOnUpdateFunction onUpdate, mragPathsOnFinishFunction onFinish) { CPath &newPath = ps_aPaths.Push(); newPath.p_pPaths = this; newPath.p_vPos1 = vPos1; newPath.p_vPos2 = vPos2; newPath.p_iTotalFrameCount = iTotalFrameCount; newPath.p_pOnUpdate = onUpdate; newPath.p_pOnFinish = onFinish; return newPath; } CPath& CPaths::Create(const Vector2f &vPos1, const Vector2f &vPos2, float fSeconds, mragPathsOnUpdateFunction onUpdate, mragPathsOnFinishFunction onFinish) { return Create(vPos1, vPos2, (int)ceil(fSeconds / 0.0166667f), onUpdate, onFinish); } void CPaths::Update() { for(int i=0; i<ps_aPaths.Count(); i++) { ps_aPaths[i].p_bReady = true; } for(ps_iIterator=0; ps_iIterator<ps_aPaths.Count(); ps_iIterator++) { if(!ps_aPaths[ps_iIterator].p_bReady) { continue; } ps_aPaths[ps_iIterator].Update(); } } void CPaths::Render() { for(ps_iIterator=0; ps_iIterator<ps_aPaths.Count(); ps_iIterator++) { ps_aPaths[ps_iIterator].Render(); } } MRAGPP_NAMESPACE_END;
1,271
565
#include "nao_auto_bridge.h" #include <boost/algorithm/string/join.hpp> #include <iostream> #include <vector> #include <ros/ros.h> #include <actionlib/server/simple_action_server.h> #include <naoqi_bridge_msgs/SpeechWithFeedbackAction.h> #include <naoqi_bridge_msgs/SetSpeechVocabularyAction.h> #include <naoqi_bridge_msgs/WordRecognized.h> #include <std_msgs/String.h> #include <std_srvs/Empty.h> using std::string; void SimulatedNao::OnSpeechActionGoal(const string& text) { //Note: We could replicate behaviour ROS_INFO("Nao said: %s", text.c_str()); } void SimulatedNao::OnSpeechVocabularyAction(const std::vector<string>& words) { //Note: We could replicate behaviour const string joined = boost::algorithm::join(words, ","); ROS_INFO("Words recognized set: %s", joined.c_str()); } void SimulatedNao::OnSpeech(const string& text) { //Note: We could replicate behaviour ROS_INFO("Nao said: %s", text.c_str()); } void SimulatedNao::OnReconfigure() { //Note: We could replicate behaviour ROS_INFO("Speech reconfigured"); } void SimulatedNao::OnStartRecognition() { //Note: We could replicate behaviour if (!this->speech_data.recognition_started) { ROS_INFO("Recognition started"); this->speech_data.recognition_started = true; } else { ROS_INFO("Tried to start recognition, but it was already started by another node"); } } void SimulatedNao::OnStopRecognition() { //Note: We could replicate behaviour if (this->speech_data.recognition_started) { ROS_INFO("Recognition stopped"); this->speech_data.recognition_started = false; } else { ROS_INFO("Tried top stop recognition, but it is already stopped"); } } namespace BridgeNaoSpeech { std::unique_ptr<actionlib::SimpleActionServer<naoqi_bridge_msgs::SpeechWithFeedbackAction>> act_srv_speech_action_goal; std::unique_ptr<actionlib::SimpleActionServer<naoqi_bridge_msgs::SetSpeechVocabularyAction>> act_srv_speech_vocabulary_action; ros::Subscriber sub_speech; ros::ServiceServer srv_reconfigure, srv_start_recognition, srv_stop_recognition; void on_speech_action_goal( const naoqi_bridge_msgs::SpeechWithFeedbackGoalConstPtr &goal ) { nao_connection.OnSpeechActionGoal(goal->say); naoqi_bridge_msgs::SpeechWithFeedbackResult result; act_srv_speech_action_goal->setSucceeded(result); } void on_speech_vocabulary_action( const naoqi_bridge_msgs::SetSpeechVocabularyGoalConstPtr &goal ) { nao_connection.OnSpeechVocabularyAction(goal->words); naoqi_bridge_msgs::SetSpeechVocabularyResult result; act_srv_speech_vocabulary_action->setSucceeded(result); } void on_speech( const std_msgs::StringConstPtr &msg ) { nao_connection.OnSpeech(msg->data); } bool on_reconfigure( std_srvs::Empty::Request &req, std_srvs::Empty::Response &resp ){ nao_connection.OnReconfigure(); return true; } bool on_start_recognition( std_srvs::Empty::Request &req, std_srvs::Empty::Response &resp ){ nao_connection.OnStartRecognition(); return true; } bool on_stop_recognition( std_srvs::Empty::Request &req, std_srvs::Empty::Response &resp ){ nao_connection.OnStopRecognition(); return true; } void init(ros::NodeHandle &n) { std::string voice, language; float volume; std::vector<std::string> vocabulary; bool enable_audio_expression, enable_visual_expression, word_spoting; n.param("voice", voice, std::string("")); n.param("language", language, std::string("")); n.param("volume", volume, 0.0f); n.param("vocabulary", vocabulary, std::vector<std::string>()); n.param("enable_audio_expression", enable_audio_expression, false); n.param("enable_visual_expression", enable_visual_expression, false); n.param("word_spoting", word_spoting, false); act_srv_speech_action_goal = std::unique_ptr<actionlib::SimpleActionServer<naoqi_bridge_msgs::SpeechWithFeedbackAction>>( new actionlib::SimpleActionServer<naoqi_bridge_msgs::SpeechWithFeedbackAction>(n, "speech_action/goal", on_speech_action_goal, true)); act_srv_speech_vocabulary_action = std::unique_ptr<actionlib::SimpleActionServer<naoqi_bridge_msgs::SetSpeechVocabularyAction>>( new actionlib::SimpleActionServer<naoqi_bridge_msgs::SetSpeechVocabularyAction>(n, "/speech_vocabulary_action/goal", on_speech_vocabulary_action, true)); sub_speech = n.subscribe("speech", 1000, on_speech); srv_reconfigure = n.advertiseService("reconfigure", on_reconfigure); srv_start_recognition = n.advertiseService("start_recognition", on_start_recognition); srv_stop_recognition = n.advertiseService("stop_recognition", on_stop_recognition); } }
5,051
1,696
#include <Entity.hpp> #include <Graphics.hpp> #include <KeyPoll.hpp> #include <Map.hpp> #include <Music.hpp> #include <Script.hpp> #include <editor.hpp> //#include "UtilityClass.h" #include <Enums.hpp> #include <FileSystemUtils.hpp> #include <ctime> #include <string> #include <tinyxml/tinyxml.hpp> edlevelclass::edlevelclass() { tileset = 0; tilecol = 0; roomname = ""; warpdir = 0; platx1 = 0; platy1 = 0; platx2 = 320; platy2 = 240; platv = 4; enemyx1 = 0; enemyy1 = 0; enemyx2 = 320; enemyy2 = 240; enemytype = 0; directmode = 0; } editorclass::editorclass() { maxwidth = 20; maxheight = 20; //We create a blank map for(int j = 0; j < 30 * maxwidth; j++) { for(int i = 0; i < 40 * maxheight; i++) { contents.push_back(0); } } for(int j = 0; j < 30; j++) { for(int i = 0; i < 40; i++) { swapmap.push_back(0); } } for(int i = 0; i < 30 * maxheight; i++) { vmult.push_back(int(i * 40 * maxwidth)); } reset(); } // comparison, not case sensitive. bool compare_nocase(std::string first, std::string second) { unsigned int i = 0; while((i < first.length()) && (i < second.length())) { if(tolower(first[i]) < tolower(second[i])) return true; else if(tolower(first[i]) > tolower(second[i])) return false; ++i; } if(first.length() < second.length()) return true; else return false; } void editorclass::getDirectoryData() { ListOfMetaData.clear(); directoryList.clear(); directoryList = FILESYSTEM_getLevelDirFileNames(); for(size_t i = 0; i < directoryList.size(); i++) { LevelMetaData temp; if(getLevelMetaData(directoryList[i], temp)) { ListOfMetaData.push_back(temp); } } for(size_t i = 0; i < ListOfMetaData.size(); i++) { for(size_t k = 0; k < ListOfMetaData.size(); k++) { if(compare_nocase(ListOfMetaData[i].title, ListOfMetaData[k].title)) { std::swap(ListOfMetaData[i], ListOfMetaData[k]); std::swap(directoryList[i], directoryList[k]); } } } } bool editorclass::getLevelMetaData(std::string & _path, LevelMetaData & _data) { unsigned char * mem = NULL; FILESYSTEM_loadFileToMemory(_path.c_str(), &mem, NULL); if(mem == NULL) { printf("Level %s not found :(\n", _path.c_str()); return false; } TiXmlDocument doc; doc.Parse((const char *)mem); FILESYSTEM_freeMemory(&mem); TiXmlHandle hDoc(&doc); TiXmlElement * pElem; TiXmlHandle hRoot(0); { pElem = hDoc.FirstChildElement().Element(); // should always have a valid root but handle gracefully if it does if(!pElem) { printf("No valid root! Corrupt level file?\n"); } // save this for later hRoot = TiXmlHandle(pElem); } for(pElem = hRoot.FirstChild("Data").FirstChild().Element(); pElem; pElem = pElem->NextSiblingElement()) { std::string pKey(pElem->Value()); const char * pText = pElem->GetText(); if(pText == NULL) { pText = ""; } if(pKey == "MetaData") { for(TiXmlElement * subElem = pElem->FirstChildElement(); subElem; subElem = subElem->NextSiblingElement()) { std::string pKey(subElem->Value()); const char * pText = subElem->GetText(); if(pText == NULL) { pText = ""; } _data.filename = _path; if(pKey == "Created") { _data.timeCreated = pText; } if(pKey == "Creator") { _data.creator = pText; } if(pKey == "Title") { _data.title = pText; } if(pKey == "Modified") { _data.timeModified = pText; } if(pKey == "Modifiers") { _data.modifier = pText; } if(pKey == "Desc1") { _data.Desc1 = pText; } if(pKey == "Desc2") { _data.Desc2 = pText; } if(pKey == "Desc3") { _data.Desc3 = pText; } if(pKey == "website") { _data.website = pText; } } } } return (_data.filename != ""); } void editorclass::reset() { version = 2; //New smaller format change is 2 mapwidth = 5; mapheight = 5; EditorData::GetInstance().title = "Untitled Level"; EditorData::GetInstance().creator = "Unknown"; Desc1 = ""; Desc2 = ""; Desc3 = ""; website = ""; roomnamehide = 0; zmod = false; xmod = false; spacemod = false; spacemenu = 0; shiftmenu = false; shiftkey = false; saveandquit = false; note = ""; notedelay = 0; roomnamemod = false; textentry = false; savemod = false; loadmod = false; deletekeyheld = false; titlemod = false; creatormod = false; desc1mod = false; desc2mod = false; desc3mod = false; websitemod = false; settingsmod = false; warpmod = false; //Two step process warpent = -1; boundarymod = 0; boundarytype = 0; boundx1 = 0; boundx2 = 0; boundy1 = 0; boundy2 = 0; scripttextmod = false; scripttextent = 0; scripttexttype = 0; drawmode = 0; dmtile = 0; dmtileeditor = 0; entcol = 0; tilex = 0; tiley = 0; levx = 0; levy = 0; keydelay = 0; lclickdelay = 0; savekey = false; loadkey = false; updatetiles = true; changeroom = true; levmusic = 0; entframe = 0; entframedelay = 0; numtrinkets = 0; numcrewmates = 0; EditorData::GetInstance().numedentities = 0; levmusic = 0; roomtextmod = false; roomtextent = 0; for(int j = 0; j < maxheight; j++) { for(int i = 0; i < maxwidth; i++) { level[i + (j * maxwidth)].tileset = 0; level[i + (j * maxwidth)].tilecol = (i + j) % 32; level[i + (j * maxwidth)].roomname = ""; level[i + (j * maxwidth)].warpdir = 0; level[i + (j * maxwidth)].platx1 = 0; level[i + (j * maxwidth)].platy1 = 0; level[i + (j * maxwidth)].platx2 = 320; level[i + (j * maxwidth)].platy2 = 240; level[i + (j * maxwidth)].platv = 4; level[i + (j * maxwidth)].enemyx1 = 0; level[i + (j * maxwidth)].enemyy1 = 0; level[i + (j * maxwidth)].enemyx2 = 320; level[i + (j * maxwidth)].enemyy2 = 240; } } for(int j = 0; j < 30 * maxwidth; j++) { for(int i = 0; i < 40 * maxheight; i++) { contents[i + (j * 30 * maxwidth)] = 0; } } if(numhooks > 0) { for(int i = 0; i < numhooks; i++) { removehook(hooklist[i]); } } for(int i = 0; i < 500; i++) { sb[i] = ""; } for(int i = 0; i < 500; i++) { hooklist[i] = ""; } clearscriptbuffer(); sblength = 1; sbx = 0; sby = 0; pagey = 0; scripteditmod = false; sbscript = "null"; scripthelppage = 0; scripthelppagedelay = 0; hookmenupage = 0; hookmenu = 0; numhooks = 0; script.customscript.clear(); } void editorclass::weirdloadthing(std::string t) { //Stupid pointless function because I hate C++ and everything to do with it //It's even stupider now that I don't need to append .vvvvvv anymore! bah, whatever //t=t+".vvvvvv"; load(t); } void editorclass::gethooks() { //Scan through the script and create a hooks list based on it numhooks = 0; std::string tstring; std::string tstring2; for(size_t i = 0; i < script.customscript.size(); i++) { tstring = script.customscript[i]; if((int)tstring.length() - 1 >= 0) // FIXME: This is sketchy. -flibit { tstring = tstring[tstring.length() - 1]; } else { tstring = ""; } if(tstring == ":") { tstring2 = ""; tstring = script.customscript[i]; for(size_t j = 0; j < tstring.length() - 1; j++) { tstring2 += tstring[j]; } hooklist[numhooks] = tstring2; numhooks++; } } } void editorclass::loadhookineditor(std::string t) { //Find hook t in the scriptclass, then load it into the editor clearscriptbuffer(); std::string tstring; bool removemode = false; for(size_t i = 0; i < script.customscript.size(); i++) { if(script.customscript[i] == t + ":") { removemode = true; } else if(removemode) { tstring = script.customscript[i]; if(tstring != "") { tstring = tstring[tstring.length() - 1]; } if(tstring == ":") { //this is a hook removemode = false; } else { //load in this line sb[sblength - 1] = script.customscript[i]; sblength++; } } } if(sblength > 1) sblength--; } void editorclass::addhooktoscript(std::string t) { //Adds hook+the scriptbuffer to the end of the scriptclass removehookfromscript(t); script.customscript.push_back(t + ":"); if(sblength >= 1) { for(int i = 0; i < sblength; i++) { script.customscript.push_back(sb[i]); } } } void editorclass::removehookfromscript(std::string t) { //Find hook t in the scriptclass, then removes it (and any other code with it) std::string tstring; bool removemode = false; for(size_t i = 0; i < script.customscript.size(); i++) { if(script.customscript[i] == t + ":") { removemode = true; //Remove this line for(size_t j = i; j < script.customscript.size() - 1; j++) { script.customscript[j] = script.customscript[j + 1]; } script.customscript.pop_back(); i--; } else if(removemode) { //If this line is not the start of a new hook, remove it! tstring = script.customscript[i]; tstring = tstring[tstring.length() - 1]; if(tstring == ":") { //this is a hook removemode = false; } else { //Remove this line for(size_t j = i; j < script.customscript.size() - 1; j++) { script.customscript[j] = script.customscript[j + 1]; } script.customscript.pop_back(); i--; } } } } void editorclass::removehook(std::string t) { //Check the hooklist for the hook t. If it's there, remove it from here and the script for(int i = 0; i < numhooks; i++) { if(hooklist[i] == t) { removehookfromscript(t); for(int j = i; j < numhooks; j++) { hooklist[j] = hooklist[j + 1]; } hooklist[numhooks] = ""; numhooks--; i--; } } } void editorclass::addhook(std::string t) { //Add an empty function to the list in both editor and script removehook(t); hooklist[numhooks] = t; numhooks++; addhooktoscript(t); } bool editorclass::checkhook(std::string t) { //returns true if hook t already is in the list for(int i = 0; i < numhooks; i++) { if(hooklist[i] == t) return true; } return false; } void editorclass::clearscriptbuffer() { for(int i = 0; i < sblength + 1; i++) { sb[i] = ""; } sblength = 1; } void editorclass::removeline(int t) { //Remove line t from the script if(sblength > 0) { if(sblength == t) { sblength--; } else { for(int i = t; i < sblength; i++) { sb[i] = sb[i + 1]; } sb[sblength] = ""; sblength--; } } } void editorclass::insertline(int t) { //insert a blank line into script at line t for(int i = sblength; i >= t; i--) { sb[i + 1] = sb[i]; } sb[t] = ""; sblength++; } void editorclass::loadlevel(int rxi, int ryi) { //Set up our buffer array to be picked up by mapclass rxi -= 100; ryi -= 100; if(rxi < 0) rxi += mapwidth; if(ryi < 0) ryi += mapheight; if(rxi >= mapwidth) rxi -= mapwidth; if(ryi >= mapheight) ryi -= mapheight; for(int j = 0; j < 30; j++) { for(int i = 0; i < 40; i++) { swapmap[i + (j * 40)] = contents[i + (rxi * 40) + vmult[j + (ryi * 30)]]; } } } int editorclass::getlevelcol(int t) { if(level[t].tileset == 0) //Space Station { return level[t].tilecol; } else if(level[t].tileset == 1) //Outside { return 32 + level[t].tilecol; } else if(level[t].tileset == 2) //Lab { return 40 + level[t].tilecol; } else if(level[t].tileset == 3) //Warp Zone { return 46 + level[t].tilecol; } else if(level[t].tileset == 4) //Ship { return 52 + level[t].tilecol; } return 0; } int editorclass::getenemycol(int t) { switch(t) { //RED case 3: case 7: case 12: case 23: case 28: case 34: case 42: case 48: case 58: return 6; break; //GREEN case 5: case 9: case 22: case 25: case 29: case 31: case 38: case 46: case 52: case 53: return 7; break; //BLUE case 1: case 6: case 14: case 27: case 33: case 44: case 50: case 57: return 12; break; //YELLOW case 4: case 17: case 24: case 30: case 37: case 45: case 51: case 55: return 9; break; //PURPLE case 2: case 11: case 15: case 19: case 32: case 36: case 49: return 20; break; //CYAN case 8: case 10: case 13: case 18: case 26: case 35: case 41: case 47: case 54: return 11; break; //PINK case 16: case 20: case 39: case 43: case 56: return 8; break; //ORANGE case 21: case 40: return 17; break; default: return 6; break; } return 0; } int editorclass::getwarpbackground(int rx, int ry) { int tmp = rx + (maxwidth * ry); switch(level[tmp].tileset) { case 0: //Space Station switch(level[tmp].tilecol) { case 0: return 3; break; case 1: return 2; break; case 2: return 1; break; case 3: return 4; break; case 4: return 5; break; case 5: return 3; break; case 6: return 1; break; case 7: return 0; break; case 8: return 5; break; case 9: return 0; break; case 10: return 2; break; case 11: return 1; break; case 12: return 5; break; case 13: return 0; break; case 14: return 3; break; case 15: return 2; break; case 16: return 4; break; case 17: return 0; break; case 18: return 3; break; case 19: return 1; break; case 20: return 4; break; case 21: return 5; break; case 22: return 1; break; case 23: return 4; break; case 24: return 5; break; case 25: return 0; break; case 26: return 3; break; case 27: return 1; break; case 28: return 5; break; case 29: return 4; break; case 30: return 5; break; case 31: return 2; break; default: return 6; break; } break; case 1: //Outside switch(level[tmp].tilecol) { case 0: return 3; break; case 1: return 1; break; case 2: return 0; break; case 3: return 2; break; case 4: return 4; break; case 5: return 5; break; case 6: return 2; break; case 7: return 4; break; default: return 6; break; } break; case 2: //Lab switch(level[tmp].tilecol) { case 0: return 0; break; case 1: return 1; break; case 2: return 2; break; case 3: return 3; break; case 4: return 4; break; case 5: return 5; break; case 6: return 6; break; default: return 6; break; } break; case 3: //Warp Zone switch(level[tmp].tilecol) { case 0: return 0; break; case 1: return 1; break; case 2: return 2; break; case 3: return 3; break; case 4: return 4; break; case 5: return 5; break; case 6: return 6; break; default: return 6; break; } break; case 4: //Ship switch(level[tmp].tilecol) { case 0: return 5; break; case 1: return 0; break; case 2: return 4; break; case 3: return 2; break; case 4: return 3; break; case 5: return 1; break; case 6: return 6; break; default: return 6; break; } break; case 5: //Tower return 6; break; default: return 6; break; } } int editorclass::getenemyframe(int t) { switch(t) { case 0: return 78; break; case 1: return 88; break; case 2: return 36; break; case 3: return 164; break; case 4: return 68; break; case 5: return 48; break; case 6: return 176; break; case 7: return 168; break; case 8: return 112; break; case 9: return 114; break; default: return 78; break; } return 78; } void editorclass::placetile(int x, int y, int t) { if(x >= 0 && y >= 0 && x < mapwidth * 40 && y < mapheight * 30) { contents[x + (levx * 40) + vmult[y + (levy * 30)]] = t; } } void editorclass::placetilelocal(int x, int y, int t) { if(x >= 0 && y >= 0 && x < 40 && y < 30) { contents[x + (levx * 40) + vmult[y + (levy * 30)]] = t; } updatetiles = true; } int editorclass::base(int x, int y) { //Return the base tile for the given tileset and colour temp = x + (y * maxwidth); if(level[temp].tileset == 0) //Space Station { if(level[temp].tilecol >= 22) { return 483 + ((level[temp].tilecol - 22) * 3); } else if(level[temp].tilecol >= 11) { return 283 + ((level[temp].tilecol - 11) * 3); } else { return 83 + (level[temp].tilecol * 3); } } else if(level[temp].tileset == 1) //Outside { return 480 + (level[temp].tilecol * 3); } else if(level[temp].tileset == 2) //Lab { return 280 + (level[temp].tilecol * 3); } else if(level[temp].tileset == 3) //Warp Zone/Intermission { return 80 + (level[temp].tilecol * 3); } else if(level[temp].tileset == 4) //SHIP { return 101 + (level[temp].tilecol * 3); } return 0; } int editorclass::backbase(int x, int y) { //Return the base tile for the background of the given tileset and colour temp = x + (y * maxwidth); if(level[temp].tileset == 0) //Space Station { //Pick depending on tilecol switch(level[temp].tilecol) { case 0: case 5: case 26: return 680; //Blue break; case 3: case 16: case 23: return 683; //Yellow break; case 9: case 12: case 21: return 686; //Greeny Cyan break; case 4: case 8: case 24: case 28: case 30: return 689; //Green break; case 20: case 29: return 692; //Orange break; case 2: case 6: case 11: case 22: case 27: return 695; //Red break; case 1: case 10: case 15: case 19: case 31: return 698; //Pink break; case 14: case 18: return 701; //Dark Blue break; case 7: case 13: case 17: case 25: return 704; //Cyan break; default: return 680; break; } } else if(level[temp].tileset == 1) //outside { return 680 + (level[temp].tilecol * 3); } else if(level[temp].tileset == 2) //Lab { return 0; } else if(level[temp].tileset == 3) //Warp Zone/Intermission { return 120 + (level[temp].tilecol * 3); } else if(level[temp].tileset == 4) //SHIP { return 741 + (level[temp].tilecol * 3); } return 0; } int editorclass::at(int x, int y) { if(x < 0) return at(0, y); if(y < 0) return at(x, 0); if(x >= 40) return at(39, y); if(y >= 30) return at(x, 29); if(x >= 0 && y >= 0 && x < 40 && y < 30) { return contents[x + (levx * 40) + vmult[y + (levy * 30)]]; } return 0; } int editorclass::freewrap(int x, int y) { if(x < 0) return freewrap(x + (mapwidth * 40), y); if(y < 0) return freewrap(x, y + (mapheight * 30)); if(x >= (mapwidth * 40)) return freewrap(x - (mapwidth * 40), y); if(y >= (mapheight * 30)) return freewrap(x, y - (mapheight * 30)); if(x >= 0 && y >= 0 && x < (mapwidth * 40) && y < (mapheight * 30)) { if(contents[x + vmult[y]] == 0) { return 0; } else { if(contents[x + vmult[y]] >= 2 && contents[x + vmult[y]] < 80) { return 0; } if(contents[x + vmult[y]] >= 680) { return 0; } } } return 1; } int editorclass::backonlyfree(int x, int y) { //Returns 1 if tile is a background tile, 0 otherwise if(x < 0) return backonlyfree(0, y); if(y < 0) return backonlyfree(x, 0); if(x >= 40) return backonlyfree(39, y); if(y >= 30) return backonlyfree(x, 29); if(x >= 0 && y >= 0 && x < 40 && y < 30) { if(contents[x + (levx * 40) + vmult[y + (levy * 30)]] >= 680) { return 1; } } return 0; } int editorclass::backfree(int x, int y) { //Returns 0 if tile is not a block or background tile, 1 otherwise if(x < 0) return backfree(0, y); if(y < 0) return backfree(x, 0); if(x >= 40) return backfree(39, y); if(y >= 30) return backfree(x, 29); if(x >= 0 && y >= 0 && x < 40 && y < 30) { if(contents[x + (levx * 40) + vmult[y + (levy * 30)]] == 0) { return 0; } else { //if(contents[x+(levx*40)+vmult[y+(levy*30)]]>=2 && contents[x+(levx*40)+vmult[y+(levy*30)]]<80){ // return 0; //} } } return 1; } int editorclass::spikefree(int x, int y) { //Returns 0 if tile is not a block or spike, 1 otherwise if(x == -1) return free(0, y); if(y == -1) return free(x, 0); if(x == 40) return free(39, y); if(y == 30) return free(x, 29); if(x >= 0 && y >= 0 && x < 40 && y < 30) { if(contents[x + (levx * 40) + vmult[y + (levy * 30)]] == 0) { return 0; } else { if(contents[x + (levx * 40) + vmult[y + (levy * 30)]] >= 680) { return 0; } } } return 1; } int editorclass::free(int x, int y) { //Returns 0 if tile is not a block, 1 otherwise if(x == -1) return free(0, y); if(y == -1) return free(x, 0); if(x == 40) return free(39, y); if(y == 30) return free(x, 29); if(x >= 0 && y >= 0 && x < 40 && y < 30) { if(contents[x + (levx * 40) + vmult[y + (levy * 30)]] == 0) { return 0; } else { if(contents[x + (levx * 40) + vmult[y + (levy * 30)]] >= 2 && contents[x + (levx * 40) + vmult[y + (levy * 30)]] < 80) { return 0; } if(contents[x + (levx * 40) + vmult[y + (levy * 30)]] >= 680) { return 0; } } } return 1; } int editorclass::absfree(int x, int y) { //Returns 0 if tile is not a block, 1 otherwise, abs on grid if(x >= 0 && y >= 0 && x < mapwidth * 40 && y < mapheight * 30) { if(contents[x + vmult[y]] == 0) { return 0; } else { if(contents[x + vmult[y]] >= 2 && contents[x + vmult[y]] < 80) { return 0; } if(contents[x + vmult[y]] >= 680) { return 0; } } } return 1; } int editorclass::match(int x, int y) { if(free(x - 1, y) == 0 && free(x, y - 1) == 0 && free(x + 1, y) == 0 && free(x, y + 1) == 0) return 0; if(free(x - 1, y) == 0 && free(x, y - 1) == 0) return 10; if(free(x + 1, y) == 0 && free(x, y - 1) == 0) return 11; if(free(x - 1, y) == 0 && free(x, y + 1) == 0) return 12; if(free(x + 1, y) == 0 && free(x, y + 1) == 0) return 13; if(free(x, y - 1) == 0) return 1; if(free(x - 1, y) == 0) return 2; if(free(x, y + 1) == 0) return 3; if(free(x + 1, y) == 0) return 4; if(free(x - 1, y - 1) == 0) return 5; if(free(x + 1, y - 1) == 0) return 6; if(free(x - 1, y + 1) == 0) return 7; if(free(x + 1, y + 1) == 0) return 8; return 0; } int editorclass::warpzonematch(int x, int y) { if(free(x - 1, y) == 0 && free(x, y - 1) == 0 && free(x + 1, y) == 0 && free(x, y + 1) == 0) return 0; if(free(x - 1, y) == 0 && free(x, y - 1) == 0) return 10; if(free(x + 1, y) == 0 && free(x, y - 1) == 0) return 11; if(free(x - 1, y) == 0 && free(x, y + 1) == 0) return 12; if(free(x + 1, y) == 0 && free(x, y + 1) == 0) return 13; if(free(x, y - 1) == 0) return 1; if(free(x - 1, y) == 0) return 2; if(free(x, y + 1) == 0) return 3; if(free(x + 1, y) == 0) return 4; if(free(x - 1, y - 1) == 0) return 5; if(free(x + 1, y - 1) == 0) return 6; if(free(x - 1, y + 1) == 0) return 7; if(free(x + 1, y + 1) == 0) return 8; return 0; } int editorclass::outsidematch(int x, int y) { if(backonlyfree(x - 1, y) == 0 && backonlyfree(x + 1, y) == 0) return 2; if(backonlyfree(x, y - 1) == 0 && backonlyfree(x, y + 1) == 0) return 1; return 0; } int editorclass::backmatch(int x, int y) { //Returns the first position match for a border // 5 1 6 // 2 X 4 // 7 3 8 /* if(at(x-1,y)>=80 && at(x,y-1)>=80) return 10; if(at(x+1,y)>=80 && at(x,y-1)>=80) return 11; if(at(x-1,y)>=80 && at(x,y+1)>=80) return 12; if(at(x+1,y)>=80 && at(x,y+1)>=80) return 13; if(at(x,y-1)>=80) return 1; if(at(x-1,y)>=80) return 2; if(at(x,y+1)>=80) return 3; if(at(x+1,y)>=80) return 4; if(at(x-1,y-1)>=80) return 5; if(at(x+1,y-1)>=80) return 6; if(at(x-1,y+1)>=80) return 7; if(at(x+1,y+1)>=80) return 8; */ if(backfree(x - 1, y) == 0 && backfree(x, y - 1) == 0 && backfree(x + 1, y) == 0 && backfree(x, y + 1) == 0) return 0; if(backfree(x - 1, y) == 0 && backfree(x, y - 1) == 0) return 10; if(backfree(x + 1, y) == 0 && backfree(x, y - 1) == 0) return 11; if(backfree(x - 1, y) == 0 && backfree(x, y + 1) == 0) return 12; if(backfree(x + 1, y) == 0 && backfree(x, y + 1) == 0) return 13; if(backfree(x, y - 1) == 0) return 1; if(backfree(x - 1, y) == 0) return 2; if(backfree(x, y + 1) == 0) return 3; if(backfree(x + 1, y) == 0) return 4; if(backfree(x - 1, y - 1) == 0) return 5; if(backfree(x + 1, y - 1) == 0) return 6; if(backfree(x - 1, y + 1) == 0) return 7; if(backfree(x + 1, y + 1) == 0) return 8; return 0; } int editorclass::edgetile(int x, int y) { switch(match(x, y)) { case 14: return 0; break; case 10: return 80; break; case 11: return 82; break; case 12: return 160; break; case 13: return 162; break; case 1: return 81; break; case 2: return 120; break; case 3: return 161; break; case 4: return 122; break; case 5: return 42; break; case 6: return 41; break; case 7: return 2; break; case 8: return 1; break; case 0: default: return 0; break; } return 0; } int editorclass::warpzoneedgetile(int x, int y) { switch(backmatch(x, y)) { case 14: return 0; break; case 10: return 80; break; case 11: return 82; break; case 12: return 160; break; case 13: return 162; break; case 1: return 81; break; case 2: return 120; break; case 3: return 161; break; case 4: return 122; break; case 5: return 42; break; case 6: return 41; break; case 7: return 2; break; case 8: return 1; break; case 0: default: return 0; break; } return 0; } int editorclass::outsideedgetile(int x, int y) { switch(outsidematch(x, y)) { case 2: return 0; break; case 1: return 1; break; case 0: default: return 2; break; } return 2; } int editorclass::backedgetile(int x, int y) { switch(backmatch(x, y)) { case 14: return 0; break; case 10: return 80; break; case 11: return 82; break; case 12: return 160; break; case 13: return 162; break; case 1: return 81; break; case 2: return 120; break; case 3: return 161; break; case 4: return 122; break; case 5: return 42; break; case 6: return 41; break; case 7: return 2; break; case 8: return 1; break; case 0: default: return 0; break; } return 0; } int editorclass::labspikedir(int x, int y, int t) { // a slightly more tricky case if(free(x, y + 1) == 1) return 63 + (t * 2); if(free(x, y - 1) == 1) return 64 + (t * 2); if(free(x - 1, y) == 1) return 51 + (t * 2); if(free(x + 1, y) == 1) return 52 + (t * 2); return 63 + (t * 2); } int editorclass::spikedir(int x, int y) { if(free(x, y + 1) == 1) return 8; if(free(x, y - 1) == 1) return 9; if(free(x - 1, y) == 1) return 49; if(free(x + 1, y) == 1) return 50; return 8; } void editorclass::findstartpoint(Game & game) { //Ok! Scan the room for the closest checkpoint int testeditor = -1; //First up; is there a start point on this screen? for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { //if() on screen if(edentity[i].t == 16 && testeditor == -1) { testeditor = i; } } if(testeditor == -1) { game.edsavex = 160; game.edsavey = 120; game.edsaverx = 100; game.edsavery = 100; game.edsavegc = 0; game.edsavey--; game.edsavedir = 1 - edentity[testeditor].p1; } else { //Start point spawn int tx = (edentity[testeditor].x - (edentity[testeditor].x % 40)) / 40; int ty = (edentity[testeditor].y - (edentity[testeditor].y % 30)) / 30; game.edsavex = ((edentity[testeditor].x % 40) * 8) - 4; game.edsavey = (edentity[testeditor].y % 30) * 8; game.edsaverx = 100 + tx; game.edsavery = 100 + ty; game.edsavegc = 0; game.edsavey--; game.edsavedir = 1 - edentity[testeditor].p1; } } void editorclass::saveconvertor() { //In the case of resizing breaking a level, this function can fix it maxwidth = 20; maxheight = 20; int oldwidth = 10, oldheight = 10; std::vector<int> tempcontents; for(int j = 0; j < 30 * oldwidth; j++) { for(int i = 0; i < 40 * oldheight; i++) { tempcontents.push_back(contents[i + (j * 40 * oldwidth)]); } } contents.clear(); for(int j = 0; j < 30 * maxheight; j++) { for(int i = 0; i < 40 * maxwidth; i++) { contents.push_back(0); } } for(int j = 0; j < 30 * oldheight; j++) { for(int i = 0; i < 40 * oldwidth; i++) { contents[i + (j * 40 * oldwidth)] = tempcontents[i + (j * 40 * oldwidth)]; } } tempcontents.clear(); for(int i = 0; i < 30 * maxheight; i++) { vmult.push_back(int(i * 40 * maxwidth)); } for(int j = 0; j < maxheight; j++) { for(int i = 0; i < maxwidth; i++) { level[i + (j * maxwidth)].tilecol = (i + j) % 6; } } contents.clear(); } int editorclass::findtrinket(int t) { int ttrinket = 0; for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { if(i == t) return ttrinket; if(edentity[i].t == 9) ttrinket++; } return 0; } int editorclass::findcrewmate(int t) { int ttrinket = 0; for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { if(i == t) return ttrinket; if(edentity[i].t == 15) ttrinket++; } return 0; } int editorclass::findwarptoken(int t) { int ttrinket = 0; for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { if(i == t) return ttrinket; if(edentity[i].t == 13) ttrinket++; } return 0; } void editorclass::countstuff() { numtrinkets = 0; numcrewmates = 0; for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { if(edentity[i].t == 9) numtrinkets++; if(edentity[i].t == 15) numcrewmates++; } } void editorclass::load(std::string & _path) { reset(); unsigned char * mem = NULL; static const char * levelDir = "levels/"; if(_path.compare(0, strlen(levelDir), levelDir) != 0) { _path = levelDir + _path; } FILESYSTEM_loadFileToMemory(_path.c_str(), &mem, NULL); if(mem == NULL) { printf("No level %s to load :(\n", _path.c_str()); return; } TiXmlDocument doc; doc.Parse((const char *)mem); FILESYSTEM_freeMemory(&mem); TiXmlHandle hDoc(&doc); TiXmlElement * pElem; TiXmlHandle hRoot(0); version = 0; { pElem = hDoc.FirstChildElement().Element(); // should always have a valid root but handle gracefully if it does if(!pElem) { printf("No valid root! Corrupt level file?\n"); } pElem->QueryIntAttribute("version", &version); // save this for later hRoot = TiXmlHandle(pElem); } for(pElem = hRoot.FirstChild("Data").FirstChild().Element(); pElem; pElem = pElem->NextSiblingElement()) { std::string pKey(pElem->Value()); const char * pText = pElem->GetText(); if(pText == NULL) { pText = ""; } if(pKey == "MetaData") { for(TiXmlElement * subElem = pElem->FirstChildElement(); subElem; subElem = subElem->NextSiblingElement()) { std::string pKey(subElem->Value()); const char * pText = subElem->GetText(); if(pText == NULL) { pText = ""; } if(pKey == "Creator") { EditorData::GetInstance().creator = pText; } if(pKey == "Title") { EditorData::GetInstance().title = pText; } if(pKey == "Desc1") { Desc1 = pText; } if(pKey == "Desc2") { Desc2 = pText; } if(pKey == "Desc3") { Desc3 = pText; } if(pKey == "website") { website = pText; } } } if(pKey == "mapwidth") { mapwidth = atoi(pText); } if(pKey == "mapheight") { mapheight = atoi(pText); } if(pKey == "levmusic") { levmusic = atoi(pText); } if(pKey == "contents") { std::string TextString = (pText); if(TextString.length()) { std::vector<std::string> values = split(TextString, ','); //contents.clear(); for(size_t i = 0; i < contents.size(); i++) { contents[i] = 0; } int x = 0; int y = 0; for(size_t i = 0; i < values.size(); i++) { contents[x + (maxwidth * 40 * y)] = atoi(values[i].c_str()); x++; if(x == mapwidth * 40) { x = 0; y++; } } } } /*else if(version==1){ if (pKey == "contents") { std::string TextString = (pText); if(TextString.length()) { std::vector<std::string> values = split(TextString,','); contents.clear(); for(int i = 0; i < values.size(); i++) { contents.push_back(atoi(values[i].c_str())); } } } //} */ if(pKey == "edEntities") { int i = 0; for(TiXmlElement * edEntityEl = pElem->FirstChildElement(); edEntityEl; edEntityEl = edEntityEl->NextSiblingElement()) { std::string pKey(edEntityEl->Value()); //const char* pText = edEntityEl->GetText() ; if(edEntityEl->GetText() != NULL) { edentity[i].scriptname = std::string(edEntityEl->GetText()); } edEntityEl->QueryIntAttribute("x", &edentity[i].x); edEntityEl->QueryIntAttribute("y", &edentity[i].y); edEntityEl->QueryIntAttribute("t", &edentity[i].t); edEntityEl->QueryIntAttribute("p1", &edentity[i].p1); edEntityEl->QueryIntAttribute("p2", &edentity[i].p2); edEntityEl->QueryIntAttribute("p3", &edentity[i].p3); edEntityEl->QueryIntAttribute("p4", &edentity[i].p4); edEntityEl->QueryIntAttribute("p5", &edentity[i].p5); edEntityEl->QueryIntAttribute("p6", &edentity[i].p6); i++; } EditorData::GetInstance().numedentities = i; } if(pKey == "levelMetaData") { int i = 0; for(TiXmlElement * edLevelClassElement = pElem->FirstChildElement(); edLevelClassElement; edLevelClassElement = edLevelClassElement->NextSiblingElement()) { std::string pKey(edLevelClassElement->Value()); if(edLevelClassElement->GetText() != NULL) { level[i].roomname = std::string(edLevelClassElement->GetText()); } edLevelClassElement->QueryIntAttribute("tileset", &level[i].tileset); edLevelClassElement->QueryIntAttribute("tilecol", &level[i].tilecol); edLevelClassElement->QueryIntAttribute("platx1", &level[i].platx1); edLevelClassElement->QueryIntAttribute("platy1", &level[i].platy1); edLevelClassElement->QueryIntAttribute("platx2", &level[i].platx2); edLevelClassElement->QueryIntAttribute("platy2", &level[i].platy2); edLevelClassElement->QueryIntAttribute("platv", &level[i].platv); edLevelClassElement->QueryIntAttribute("enemyx1", &level[i].enemyx1); edLevelClassElement->QueryIntAttribute("enemyy1", &level[i].enemyy1); edLevelClassElement->QueryIntAttribute("enemyx2", &level[i].enemyx2); edLevelClassElement->QueryIntAttribute("enemyy2", &level[i].enemyy2); edLevelClassElement->QueryIntAttribute("enemytype", &level[i].enemytype); edLevelClassElement->QueryIntAttribute("directmode", &level[i].directmode); edLevelClassElement->QueryIntAttribute("warpdir", &level[i].warpdir); i++; } } if(pKey == "script") { std::string TextString = (pText); if(TextString.length()) { std::vector<std::string> values = split(TextString, '|'); script.clearcustom(); for(size_t i = 0; i < values.size(); i++) { script.customscript.push_back(values[i]); } } } } gethooks(); countstuff(); version = 2; //saveconvertor(); } void editorclass::save(std::string & _path) { TiXmlDocument doc; TiXmlElement * msg; TiXmlDeclaration * decl = new TiXmlDeclaration("1.0", "", ""); doc.LinkEndChild(decl); TiXmlElement * root = new TiXmlElement("MapData"); root->SetAttribute("version", version); doc.LinkEndChild(root); TiXmlComment * comment = new TiXmlComment(); comment->SetValue(" Save file "); root->LinkEndChild(comment); TiXmlElement * data = new TiXmlElement("Data"); root->LinkEndChild(data); msg = new TiXmlElement("MetaData"); time_t rawtime; struct tm * timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); std::string timeAndDate = asctime(timeinfo); //timeAndDate += dateStr; EditorData::GetInstance().timeModified = timeAndDate; if(EditorData::GetInstance().timeModified == "") { EditorData::GetInstance().timeCreated = timeAndDate; } //getUser TiXmlElement * meta = new TiXmlElement("Creator"); meta->LinkEndChild(new TiXmlText(EditorData::GetInstance().creator.c_str())); msg->LinkEndChild(meta); meta = new TiXmlElement("Title"); meta->LinkEndChild(new TiXmlText(EditorData::GetInstance().title.c_str())); msg->LinkEndChild(meta); meta = new TiXmlElement("Created"); meta->LinkEndChild(new TiXmlText(UtilityClass::String(version).c_str())); msg->LinkEndChild(meta); meta = new TiXmlElement("Modified"); meta->LinkEndChild(new TiXmlText(EditorData::GetInstance().modifier.c_str())); msg->LinkEndChild(meta); meta = new TiXmlElement("Modifiers"); meta->LinkEndChild(new TiXmlText(UtilityClass::String(version).c_str())); msg->LinkEndChild(meta); meta = new TiXmlElement("Desc1"); meta->LinkEndChild(new TiXmlText(Desc1.c_str())); msg->LinkEndChild(meta); meta = new TiXmlElement("Desc2"); meta->LinkEndChild(new TiXmlText(Desc2.c_str())); msg->LinkEndChild(meta); meta = new TiXmlElement("Desc3"); meta->LinkEndChild(new TiXmlText(Desc3.c_str())); msg->LinkEndChild(meta); meta = new TiXmlElement("website"); meta->LinkEndChild(new TiXmlText(website.c_str())); msg->LinkEndChild(meta); data->LinkEndChild(msg); msg = new TiXmlElement("mapwidth"); msg->LinkEndChild(new TiXmlText(UtilityClass::String(mapwidth).c_str())); data->LinkEndChild(msg); msg = new TiXmlElement("mapheight"); msg->LinkEndChild(new TiXmlText(UtilityClass::String(mapheight).c_str())); data->LinkEndChild(msg); msg = new TiXmlElement("levmusic"); msg->LinkEndChild(new TiXmlText(UtilityClass::String(levmusic).c_str())); data->LinkEndChild(msg); //New save format std::string contentsString = ""; for(int y = 0; y < mapheight * 30; y++) { for(int x = 0; x < mapwidth * 40; x++) { contentsString += UtilityClass::String(contents[x + (maxwidth * 40 * y)]) + ","; } } msg = new TiXmlElement("contents"); msg->LinkEndChild(new TiXmlText(contentsString.c_str())); data->LinkEndChild(msg); //Old save format /* std::string contentsString; for(int i = 0; i < contents.size(); i++ ) { contentsString += UtilityClass::String(contents[i]) + ","; } msg = new TiXmlElement( "contents" ); msg->LinkEndChild( new TiXmlText( contentsString.c_str() )); data->LinkEndChild( msg ); */ msg = new TiXmlElement("edEntities"); for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { TiXmlElement * edentityElement = new TiXmlElement("edentity"); edentityElement->SetAttribute("x", edentity[i].x); edentityElement->SetAttribute("y", edentity[i].y); edentityElement->SetAttribute("t", edentity[i].t); edentityElement->SetAttribute("p1", edentity[i].p1); edentityElement->SetAttribute("p2", edentity[i].p2); edentityElement->SetAttribute("p3", edentity[i].p3); edentityElement->SetAttribute("p4", edentity[i].p4); edentityElement->SetAttribute("p5", edentity[i].p5); edentityElement->SetAttribute("p6", edentity[i].p6); edentityElement->LinkEndChild(new TiXmlText(edentity[i].scriptname.c_str())); edentityElement->LinkEndChild(new TiXmlText("")); msg->LinkEndChild(edentityElement); } data->LinkEndChild(msg); msg = new TiXmlElement("levelMetaData"); for(int i = 0; i < 400; i++) { TiXmlElement * edlevelclassElement = new TiXmlElement("edLevelClass"); edlevelclassElement->SetAttribute("tileset", level[i].tileset); edlevelclassElement->SetAttribute("tilecol", level[i].tilecol); edlevelclassElement->SetAttribute("platx1", level[i].platx1); edlevelclassElement->SetAttribute("platy1", level[i].platy1); edlevelclassElement->SetAttribute("platx2", level[i].platx2); edlevelclassElement->SetAttribute("platy2", level[i].platy2); edlevelclassElement->SetAttribute("platv", level[i].platv); edlevelclassElement->SetAttribute("enemyx1", level[i].enemyx1); edlevelclassElement->SetAttribute("enemyy1", level[i].enemyy1); edlevelclassElement->SetAttribute("enemyx2", level[i].enemyx2); edlevelclassElement->SetAttribute("enemyy2", level[i].enemyy2); edlevelclassElement->SetAttribute("enemytype", level[i].enemytype); edlevelclassElement->SetAttribute("directmode", level[i].directmode); edlevelclassElement->SetAttribute("warpdir", level[i].warpdir); edlevelclassElement->LinkEndChild(new TiXmlText(level[i].roomname.c_str())); msg->LinkEndChild(edlevelclassElement); } data->LinkEndChild(msg); std::string scriptString; for(size_t i = 0; i < script.customscript.size(); i++) { scriptString += script.customscript[i] + "|"; } msg = new TiXmlElement("script"); msg->LinkEndChild(new TiXmlText(scriptString.c_str())); data->LinkEndChild(msg); doc.SaveFile((std::string(FILESYSTEM_getUserLevelDirectory()) + _path).c_str()); } void addedentity(int xp, int yp, int tp, int p1 /*=0*/, int p2 /*=0*/, int p3 /*=0*/, int p4 /*=0*/, int p5 /*=320*/, int p6 /*=240*/) { edentity[EditorData::GetInstance().numedentities].x = xp; edentity[EditorData::GetInstance().numedentities].y = yp; edentity[EditorData::GetInstance().numedentities].t = tp; edentity[EditorData::GetInstance().numedentities].p1 = p1; edentity[EditorData::GetInstance().numedentities].p2 = p2; edentity[EditorData::GetInstance().numedentities].p3 = p3; edentity[EditorData::GetInstance().numedentities].p4 = p4; edentity[EditorData::GetInstance().numedentities].p5 = p5; edentity[EditorData::GetInstance().numedentities].p6 = p6; edentity[EditorData::GetInstance().numedentities].scriptname = ""; EditorData::GetInstance().numedentities++; } void naddedentity(int xp, int yp, int tp, int p1 /*=0*/, int p2 /*=0*/, int p3 /*=0*/, int p4 /*=0*/, int p5 /*=320*/, int p6 /*=240*/) { edentity[EditorData::GetInstance().numedentities].x = xp; edentity[EditorData::GetInstance().numedentities].y = yp; edentity[EditorData::GetInstance().numedentities].t = tp; edentity[EditorData::GetInstance().numedentities].p1 = p1; edentity[EditorData::GetInstance().numedentities].p2 = p2; edentity[EditorData::GetInstance().numedentities].p3 = p3; edentity[EditorData::GetInstance().numedentities].p4 = p4; edentity[EditorData::GetInstance().numedentities].p5 = p5; edentity[EditorData::GetInstance().numedentities].p6 = p6; edentity[EditorData::GetInstance().numedentities].scriptname = ""; } void copyedentity(int a, int b) { edentity[a].x = edentity[b].x; edentity[a].y = edentity[b].y; edentity[a].t = edentity[b].t; edentity[a].p1 = edentity[b].p1; edentity[a].p2 = edentity[b].p2; edentity[a].p3 = edentity[b].p3; edentity[a].p4 = edentity[b].p4; edentity[a].p5 = edentity[b].p5; edentity[a].p6 = edentity[b].p6; edentity[a].scriptname = edentity[b].scriptname; } void removeedentity(int t) { if(t == EditorData::GetInstance().numedentities - 1) { EditorData::GetInstance().numedentities--; } else { for(int m = t; m < EditorData::GetInstance().numedentities; m++) copyedentity(m, m + 1); EditorData::GetInstance().numedentities--; } } int edentat(int xp, int yp) { for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { if(edentity[i].x == xp && edentity[i].y == yp) return i; } return -1; } bool edentclear(int xp, int yp) { for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { if(edentity[i].x == xp && edentity[i].y == yp) return false; } return true; } void fillbox(Graphics & dwgfx, int x, int y, int x2, int y2, int c) { FillRect(dwgfx.backBuffer, x, y, x2 - x, 1, c); FillRect(dwgfx.backBuffer, x, y2 - 1, x2 - x, 1, c); FillRect(dwgfx.backBuffer, x, y, 1, y2 - y, c); FillRect(dwgfx.backBuffer, x2 - 1, y, 1, y2 - y, c); } void fillboxabs(Graphics & dwgfx, int x, int y, int x2, int y2, int c) { FillRect(dwgfx.backBuffer, x, y, x2, 1, c); FillRect(dwgfx.backBuffer, x, y + y2 - 1, x2, 1, c); FillRect(dwgfx.backBuffer, x, y, 1, y2, c); FillRect(dwgfx.backBuffer, x + x2 - 1, y, 1, y2, c); } extern editorclass ed; extern edentities edentity[3000]; extern int temp; extern scriptclass script; void editorclass::generatecustomminimap(Graphics & dwgfx, mapclass & map) { map.customwidth = mapwidth; map.customheight = mapheight; map.customzoom = 1; if(map.customwidth <= 10 && map.customheight <= 10) map.customzoom = 2; if(map.customwidth <= 5 && map.customheight <= 5) map.customzoom = 4; //Set minimap offsets if(map.customzoom == 4) { map.custommmxoff = 24 * (5 - map.customwidth); map.custommmxsize = 240 - (map.custommmxoff * 2); map.custommmyoff = 18 * (5 - map.customheight); map.custommmysize = 180 - (map.custommmyoff * 2); } else if(map.customzoom == 2) { map.custommmxoff = 12 * (10 - map.customwidth); map.custommmxsize = 240 - (map.custommmxoff * 2); map.custommmyoff = 9 * (10 - map.customheight); map.custommmysize = 180 - (map.custommmyoff * 2); } else { map.custommmxoff = 6 * (20 - map.customwidth); map.custommmxsize = 240 - (map.custommmxoff * 2); map.custommmyoff = int(4.5 * (20 - map.customheight)); map.custommmysize = 180 - (map.custommmyoff * 2); } FillRect(dwgfx.images[12], dwgfx.getRGB(0, 0, 0)); int tm = 0; int temp = 0; //Scan over the map size if(ed.mapheight <= 5 && ed.mapwidth <= 5) { //4x map for(int j2 = 0; j2 < ed.mapheight; j2++) { for(int i2 = 0; i2 < ed.mapwidth; i2++) { //Ok, now scan over each square tm = 196; if(ed.level[i2 + (j2 * ed.maxwidth)].tileset == 1) tm = 96; for(int j = 0; j < 36; j++) { for(int i = 0; i < 48; i++) { temp = ed.absfree(int(i * 0.83) + (i2 * 40), int(j * 0.83) + (j2 * 30)); if(temp >= 1) { //Fill in this pixel FillRect(dwgfx.images[12], (i2 * 48) + i, (j2 * 36) + j, 1, 1, dwgfx.getRGB(tm, tm, tm)); } } } } } } else if(ed.mapheight <= 10 && ed.mapwidth <= 10) { //2x map for(int j2 = 0; j2 < ed.mapheight; j2++) { for(int i2 = 0; i2 < ed.mapwidth; i2++) { //Ok, now scan over each square tm = 196; if(ed.level[i2 + (j2 * ed.maxwidth)].tileset == 1) tm = 96; for(int j = 0; j < 18; j++) { for(int i = 0; i < 24; i++) { temp = ed.absfree(int(i * 1.6) + (i2 * 40), int(j * 1.6) + (j2 * 30)); if(temp >= 1) { //Fill in this pixel FillRect(dwgfx.images[12], (i2 * 24) + i, (j2 * 18) + j, 1, 1, dwgfx.getRGB(tm, tm, tm)); } } } } } } else { for(int j2 = 0; j2 < ed.mapheight; j2++) { for(int i2 = 0; i2 < ed.mapwidth; i2++) { //Ok, now scan over each square tm = 196; if(ed.level[i2 + (j2 * ed.maxwidth)].tileset == 1) tm = 96; for(int j = 0; j < 9; j++) { for(int i = 0; i < 12; i++) { temp = ed.absfree(3 + (i * 3) + (i2 * 40), (j * 3) + (j2 * 30)); if(temp >= 1) { //Fill in this pixel FillRect(dwgfx.images[12], (i2 * 12) + i, (j2 * 9) + j, 1, 1, dwgfx.getRGB(tm, tm, tm)); } } } } } } } void editorrender(KeyPoll & key, Graphics & dwgfx, Game & game, mapclass & map, entityclass & obj, UtilityClass & help) { //TODO //dwgfx.backbuffer.lock(); //Draw grid FillRect(dwgfx.backBuffer, 0, 0, 320, 240, dwgfx.getRGB(0, 0, 0)); for(int j = 0; j < 30; j++) { for(int i = 0; i < 40; i++) { fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(8, 8, 8)); //a simple grid if(i % 4 == 0) fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(16, 16, 16)); if(j % 4 == 0) fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(16, 16, 16)); //Minor guides if(i == 9) fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(24, 24, 24)); if(i == 30) fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(24, 24, 24)); if(j == 6 || j == 7) fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(24, 24, 24)); if(j == 21 || j == 22) fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(24, 24, 24)); //Major guides if(i == 20 || i == 19) fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(32, 32, 32)); if(j == 14) fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(32, 32, 32)); } } //Or draw background //dwgfx.drawbackground(1, map); if(!ed.settingsmod) { switch(ed.level[ed.levx + (ed.levy * ed.maxwidth)].warpdir) { case 1: dwgfx.rcol = ed.getwarpbackground(ed.levx, ed.levy); dwgfx.drawbackground(3, map); break; case 2: dwgfx.rcol = ed.getwarpbackground(ed.levx, ed.levy); dwgfx.drawbackground(4, map); break; case 3: dwgfx.rcol = ed.getwarpbackground(ed.levx, ed.levy); dwgfx.drawbackground(5, map); break; default: break; } } //Draw map, in function int temp; if(ed.level[ed.levx + (ed.maxwidth * ed.levy)].tileset == 0 || ed.level[ed.levx + (ed.maxwidth * ed.levy)].tileset == 10) { for(int j = 0; j < 30; j++) { for(int i = 0; i < 40; i++) { temp = ed.contents[i + (ed.levx * 40) + ed.vmult[j + (ed.levy * 30)]]; if(temp > 0) dwgfx.drawtile(i * 8, j * 8, temp); } } } else { for(int j = 0; j < 30; j++) { for(int i = 0; i < 40; i++) { temp = ed.contents[i + (ed.levx * 40) + ed.vmult[j + (ed.levy * 30)]]; if(temp > 0) dwgfx.drawtile2(i * 8, j * 8, temp); } } } //Edge tile fix //Buffer the sides of the new room with tiles from other rooms, to ensure no gap problems. for(int j = 0; j < 30; j++) { //left edge if(ed.freewrap((ed.levx * 40) - 1, j + (ed.levy * 30)) == 1) { FillRect(dwgfx.backBuffer, 0, j * 8, 2, 8, dwgfx.getRGB(255, 255, 255 - help.glow)); } //right edge if(ed.freewrap((ed.levx * 40) + 40, j + (ed.levy * 30)) == 1) { FillRect(dwgfx.backBuffer, 318, j * 8, 2, 8, dwgfx.getRGB(255, 255, 255 - help.glow)); } } for(int i = 0; i < 40; i++) { if(ed.freewrap((ed.levx * 40) + i, (ed.levy * 30) - 1) == 1) { FillRect(dwgfx.backBuffer, i * 8, 0, 8, 2, dwgfx.getRGB(255, 255, 255 - help.glow)); } if(ed.freewrap((ed.levx * 40) + i, 30 + (ed.levy * 30)) == 1) { FillRect(dwgfx.backBuffer, i * 8, 238, 8, 2, dwgfx.getRGB(255, 255, 255 - help.glow)); } } //Draw entities game.customcol = ed.getlevelcol(ed.levx + (ed.levy * ed.maxwidth)) + 1; ed.entcol = ed.getenemycol(game.customcol); obj.customplatformtile = game.customcol * 12; ed.temp = edentat(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30)); for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { //if() on screen int tx = (edentity[i].x - (edentity[i].x % 40)) / 40; int ty = (edentity[i].y - (edentity[i].y % 30)) / 30; point tpoint; SDL_Rect drawRect; if(tx == ed.levx && ty == ed.levy) { switch(edentity[i].t) { case 1: //Entities //FillRect(dwgfx.backBuffer, (edentity[i].x*8)- (ed.levx*40*8),(edentity[i].y*8)- (ed.levy*30*8), 16,16, dwgfx.getRGB(64,32,64)); //dwgfx.drawsprite((edentity[i].x*8)- (ed.levx*40*8),(edentity[i].y*8)- (ed.levy*30*8),ed.getenemyframe(ed.level[ed.levx+(ed.levy*ed.maxwidth)].enemytype),164,48,48); dwgfx.drawspritesetcol((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), ed.getenemyframe(ed.level[ed.levx + (ed.levy * ed.maxwidth)].enemytype), ed.entcol, help); if(edentity[i].p1 == 0) dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 4, (edentity[i].y * 8) - (ed.levy * 30 * 8) + 4, "V", 255, 255, 255 - help.glow, false); if(edentity[i].p1 == 1) dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 4, (edentity[i].y * 8) - (ed.levy * 30 * 8) + 4, "^", 255, 255, 255 - help.glow, false); if(edentity[i].p1 == 2) dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 4, (edentity[i].y * 8) - (ed.levy * 30 * 8) + 4, "<", 255, 255, 255 - help.glow, false); if(edentity[i].p1 == 3) dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 4, (edentity[i].y * 8) - (ed.levy * 30 * 8) + 4, ">", 255, 255, 255 - help.glow, false); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 16, 16, dwgfx.getBGR(255, 164, 255)); break; case 2: //Threadmills & platforms tpoint.x = (edentity[i].x * 8) - (ed.levx * 40 * 8); tpoint.y = (edentity[i].y * 8) - (ed.levy * 30 * 8); drawRect = dwgfx.tiles_rect; drawRect.x += tpoint.x; drawRect.y += tpoint.y; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); drawRect.x += 8; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); drawRect.x += 8; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); drawRect.x += 8; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); if(edentity[i].p1 <= 4) { if(edentity[i].p1 == 0) dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 12, (edentity[i].y * 8) - (ed.levy * 30 * 8), "V", 255 - help.glow, 255 - help.glow, 255 - help.glow, false); if(edentity[i].p1 == 1) dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 12, (edentity[i].y * 8) - (ed.levy * 30 * 8), "^", 255 - help.glow, 255 - help.glow, 255 - help.glow, false); if(edentity[i].p1 == 2) dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 12, (edentity[i].y * 8) - (ed.levy * 30 * 8), "<", 255 - help.glow, 255 - help.glow, 255 - help.glow, false); if(edentity[i].p1 == 3) dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 12, (edentity[i].y * 8) - (ed.levy * 30 * 8), ">", 255 - help.glow, 255 - help.glow, 255 - help.glow, false); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 32, 8, dwgfx.getBGR(255, 255, 255)); } if(edentity[i].p1 == 5) { dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), ">>>>", 255 - help.glow, 255 - help.glow, 255 - help.glow, false); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 32, 8, dwgfx.getBGR(255, 255, 255)); } else if(edentity[i].p1 == 6) { dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), "<<<<", 255 - help.glow, 255 - help.glow, 255 - help.glow, false); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 32, 8, dwgfx.getBGR(255, 255, 255)); } if(edentity[i].p1 >= 7) { //FillRect(dwgfx.backBuffer, (edentity[i].x*8)- (ed.levx*40*8),(edentity[i].y*8)- (ed.levy*30*8), 32,8, dwgfx.getBGR(64,128,64)); tpoint.x = (edentity[i].x * 8) - (ed.levx * 40 * 8) + 32; tpoint.y = (edentity[i].y * 8) - (ed.levy * 30 * 8); drawRect = dwgfx.tiles_rect; drawRect.x += tpoint.x; drawRect.y += tpoint.y; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); drawRect.x += 8; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); drawRect.x += 8; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); drawRect.x += 8; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); } if(edentity[i].p1 == 7) { dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 4, (edentity[i].y * 8) - (ed.levy * 30 * 8), "> > > > ", 255 - help.glow, 255 - help.glow, 255 - help.glow, false); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 64, 8, dwgfx.getBGR(255, 255, 255)); } else if(edentity[i].p1 == 8) { dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 4, (edentity[i].y * 8) - (ed.levy * 30 * 8), "< < < < ", 255 - help.glow, 255 - help.glow, 255 - help.glow, false); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 64, 8, dwgfx.getBGR(255, 255, 255)); } break; case 3: //Disappearing Platform //FillRect(dwgfx.backBuffer, (edentity[i].x*8)- (ed.levx*40*8),(edentity[i].y*8)- (ed.levy*30*8), 32,8, dwgfx.getBGR(64,64,128)); tpoint.x = (edentity[i].x * 8) - (ed.levx * 40 * 8); tpoint.y = (edentity[i].y * 8) - (ed.levy * 30 * 8); drawRect = dwgfx.tiles_rect; drawRect.x += tpoint.x; drawRect.y += tpoint.y; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); drawRect.x += 8; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); drawRect.x += 8; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); drawRect.x += 8; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), "////", 255 - help.glow, 255 - help.glow, 255 - help.glow, false); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 32, 8, dwgfx.getBGR(255, 255, 255)); break; case 9: //Shiny Trinket dwgfx.drawsprite((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 22, 196, 196, 196); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 16, 16, dwgfx.getRGB(164, 164, 255)); break; case 10: //Checkpoints if(edentity[i].p1 == 0) //From roof { dwgfx.drawsprite((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 20, 196, 196, 196); } else if(edentity[i].p1 == 1) //From floor { dwgfx.drawsprite((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 21, 196, 196, 196); } fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 16, 16, dwgfx.getRGB(164, 164, 255)); break; case 11: //Gravity lines if(edentity[i].p1 == 0) //Horizontal { int tx = edentity[i].x - (ed.levx * 40); int tx2 = edentity[i].x - (ed.levx * 40); int ty = edentity[i].y - (ed.levy * 30); while(ed.spikefree(tx, ty) == 0) tx--; while(ed.spikefree(tx2, ty) == 0) tx2++; tx++; FillRect(dwgfx.backBuffer, (tx * 8), (ty * 8) + 4, (tx2 - tx) * 8, 1, dwgfx.getRGB(194, 194, 194)); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 8, 8, dwgfx.getRGB(164, 255, 164)); edentity[i].p2 = tx; edentity[i].p3 = (tx2 - tx) * 8; } else //Vertical { int tx = edentity[i].x - (ed.levx * 40); int ty = edentity[i].y - (ed.levy * 30); int ty2 = edentity[i].y - (ed.levy * 30); while(ed.spikefree(tx, ty) == 0) ty--; while(ed.spikefree(tx, ty2) == 0) ty2++; ty++; FillRect(dwgfx.backBuffer, (tx * 8) + 3, (ty * 8), 1, (ty2 - ty) * 8, dwgfx.getRGB(194, 194, 194)); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 8, 8, dwgfx.getRGB(164, 255, 164)); edentity[i].p2 = ty; edentity[i].p3 = (ty2 - ty) * 8; } break; case 13: //Warp tokens dwgfx.drawsprite((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 18 + (ed.entframe % 2), 196, 196, 196); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 16, 16, dwgfx.getRGB(164, 164, 255)); if(ed.temp == i) { dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8) - 8, "(" + help.String(((edentity[i].p1 - int(edentity[i].p1 % 40)) / 40) + 1) + "," + help.String(((edentity[i].p2 - int(edentity[i].p2 % 30)) / 30) + 1) + ")", 210, 210, 255); } else { dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8) - 8, help.String(ed.findwarptoken(i)), 210, 210, 255); } break; case 15: //Crewmates dwgfx.drawspritesetcol((edentity[i].x * 8) - (ed.levx * 40 * 8) - 4, (edentity[i].y * 8) - (ed.levy * 30 * 8), 144, obj.crewcolour(edentity[i].p1), help); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 16, 24, dwgfx.getRGB(164, 164, 164)); break; case 16: //Start if(edentity[i].p1 == 0) //Left { dwgfx.drawspritesetcol((edentity[i].x * 8) - (ed.levx * 40 * 8) - 4, (edentity[i].y * 8) - (ed.levy * 30 * 8), 0, obj.crewcolour(0), help); } else if(edentity[i].p1 == 1) { dwgfx.drawspritesetcol((edentity[i].x * 8) - (ed.levx * 40 * 8) - 4, (edentity[i].y * 8) - (ed.levy * 30 * 8), 3, obj.crewcolour(0), help); } fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 16, 24, dwgfx.getRGB(164, 255, 255)); if(ed.entframe < 2) { dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) - 12, (edentity[i].y * 8) - (ed.levy * 30 * 8) - 8, "START", 255, 255, 255); } else { dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) - 12, (edentity[i].y * 8) - (ed.levy * 30 * 8) - 8, "START", 196, 196, 196); } break; case 17: //Roomtext if(edentity[i].scriptname.length() < 1) { fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 8, 8, dwgfx.getRGB(96, 96, 96)); } else { fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), edentity[i].scriptname.length() * 8, 8, dwgfx.getRGB(96, 96, 96)); } dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), edentity[i].scriptname, 196, 196, 255 - help.glow); break; case 18: //Terminals dwgfx.drawsprite((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8) + 8, 17, 96, 96, 96); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 16, 24, dwgfx.getRGB(164, 164, 164)); if(ed.temp == i) { dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8) - 8, edentity[i].scriptname, 210, 210, 255); } break; case 19: //Script Triggers fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), edentity[i].p1 * 8, edentity[i].p2 * 8, dwgfx.getRGB(255, 164, 255)); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 8, 8, dwgfx.getRGB(255, 255, 255)); if(ed.temp == i) { dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8) - 8, edentity[i].scriptname, 210, 210, 255); } break; case 50: //Warp lines if(edentity[i].p1 >= 2) //Horizontal { int tx = edentity[i].x - (ed.levx * 40); int tx2 = edentity[i].x - (ed.levx * 40); int ty = edentity[i].y - (ed.levy * 30); while(ed.free(tx, ty) == 0) tx--; while(ed.free(tx2, ty) == 0) tx2++; tx++; fillboxabs(dwgfx, (tx * 8), (ty * 8) + 1, (tx2 - tx) * 8, 6, dwgfx.getRGB(255, 255, 194)); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 8, 8, dwgfx.getRGB(255, 255, 164)); edentity[i].p2 = tx; edentity[i].p3 = (tx2 - tx) * 8; } else //Vertical { int tx = edentity[i].x - (ed.levx * 40); int ty = edentity[i].y - (ed.levy * 30); int ty2 = edentity[i].y - (ed.levy * 30); while(ed.free(tx, ty) == 0) ty--; while(ed.free(tx, ty2) == 0) ty2++; ty++; fillboxabs(dwgfx, (tx * 8) + 1, (ty * 8), 6, (ty2 - ty) * 8, dwgfx.getRGB(255, 255, 194)); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 8, 8, dwgfx.getRGB(255, 255, 164)); edentity[i].p2 = ty; edentity[i].p3 = (ty2 - ty) * 8; } break; } } //Need to also check warp point destinations if(edentity[i].t == 13 && ed.warpent != i) { tx = (edentity[i].p1 - (edentity[i].p1 % 40)) / 40; ty = (edentity[i].p2 - (edentity[i].p2 % 30)) / 30; if(tx == ed.levx && ty == ed.levy) { dwgfx.drawsprite((edentity[i].p1 * 8) - (ed.levx * 40 * 8), (edentity[i].p2 * 8) - (ed.levy * 30 * 8), 18 + (ed.entframe % 2), 64, 64, 64); fillboxabs(dwgfx, (edentity[i].p1 * 8) - (ed.levx * 40 * 8), (edentity[i].p2 * 8) - (ed.levy * 30 * 8), 16, 16, dwgfx.getRGB(64, 64, 96)); if(ed.tilex + (ed.levx * 40) == edentity[i].p1 && ed.tiley + (ed.levy * 30) == edentity[i].p2) { dwgfx.Print((edentity[i].p1 * 8) - (ed.levx * 40 * 8), (edentity[i].p2 * 8) - (ed.levy * 30 * 8) - 8, "(" + help.String(((edentity[i].x - int(edentity[i].x % 40)) / 40) + 1) + "," + help.String(((edentity[i].y - int(edentity[i].y % 30)) / 30) + 1) + ")", 190, 190, 225); } else { dwgfx.Print((edentity[i].p1 * 8) - (ed.levx * 40 * 8), (edentity[i].p2 * 8) - (ed.levy * 30 * 8) - 8, help.String(ed.findwarptoken(i)), 190, 190, 225); } } } } if(ed.boundarymod > 0) { if(ed.boundarymod == 1) { fillboxabs(dwgfx, ed.tilex * 8, ed.tiley * 8, 8, 8, dwgfx.getRGB(255 - (help.glow / 2), 191 + (help.glow), 210 + (help.glow / 2))); fillboxabs(dwgfx, (ed.tilex * 8) + 2, (ed.tiley * 8) + 2, 4, 4, dwgfx.getRGB(128 - (help.glow / 4), 100 + (help.glow / 2), 105 + (help.glow / 4))); } else if(ed.boundarymod == 2) { if((ed.tilex * 8) + 8 <= ed.boundx1 || (ed.tiley * 8) + 8 <= ed.boundy1) { fillboxabs(dwgfx, ed.boundx1, ed.boundy1, 8, 8, dwgfx.getRGB(255 - (help.glow / 2), 191 + (help.glow), 210 + (help.glow / 2))); fillboxabs(dwgfx, ed.boundx1 + 2, ed.boundy1 + 2, 4, 4, dwgfx.getRGB(128 - (help.glow / 4), 100 + (help.glow / 2), 105 + (help.glow / 4))); } else { fillboxabs(dwgfx, ed.boundx1, ed.boundy1, (ed.tilex * 8) + 8 - ed.boundx1, (ed.tiley * 8) + 8 - ed.boundy1, dwgfx.getRGB(255 - (help.glow / 2), 191 + (help.glow), 210 + (help.glow / 2))); fillboxabs(dwgfx, ed.boundx1 + 2, ed.boundy1 + 2, (ed.tilex * 8) + 8 - ed.boundx1 - 4, (ed.tiley * 8) + 8 - ed.boundy1 - 4, dwgfx.getRGB(128 - (help.glow / 4), 100 + (help.glow / 2), 105 + (help.glow / 4))); } } } else { //Draw boundaries int tmp = ed.levx + (ed.levy * ed.maxwidth); if(ed.level[tmp].enemyx1 != 0 && ed.level[tmp].enemyy1 != 0 && ed.level[tmp].enemyx2 != 320 && ed.level[tmp].enemyy2 != 240) { fillboxabs(dwgfx, ed.level[tmp].enemyx1, ed.level[tmp].enemyy1, ed.level[tmp].enemyx2 - ed.level[tmp].enemyx1, ed.level[tmp].enemyy2 - ed.level[tmp].enemyy1, dwgfx.getBGR(255 - (help.glow / 2), 64, 64)); } if(ed.level[tmp].platx1 != 0 && ed.level[tmp].platy1 != 0 && ed.level[tmp].platx2 != 320 && ed.level[tmp].platy2 != 240) { fillboxabs(dwgfx, ed.level[tmp].platx1, ed.level[tmp].platy1, ed.level[tmp].platx2 - ed.level[tmp].platx1, ed.level[tmp].platy2 - ed.level[tmp].platy1, dwgfx.getBGR(64, 64, 255 - (help.glow / 2))); } } //Draw connecting map guidelines //TODO //Draw Cursor switch(ed.drawmode) { case 0: case 1: case 2: case 9: case 10: case 12: //Single point fillboxabs(dwgfx, (ed.tilex * 8), (ed.tiley * 8), 8, 8, dwgfx.getRGB(200, 32, 32)); break; case 3: case 4: case 8: case 13: //2x2 fillboxabs(dwgfx, (ed.tilex * 8), (ed.tiley * 8), 16, 16, dwgfx.getRGB(200, 32, 32)); break; case 5: case 6: case 7: //Platform fillboxabs(dwgfx, (ed.tilex * 8), (ed.tiley * 8), 32, 8, dwgfx.getRGB(200, 32, 32)); break; case 14: //X if not on edge if(ed.tilex == 0 || ed.tilex == 39 || ed.tiley == 0 || ed.tiley == 29) { fillboxabs(dwgfx, (ed.tilex * 8), (ed.tiley * 8), 8, 8, dwgfx.getRGB(200, 32, 32)); } else { dwgfx.Print((ed.tilex * 8), (ed.tiley * 8), "X", 255, 0, 0); } break; case 11: case 15: case 16: //2x3 fillboxabs(dwgfx, (ed.tilex * 8), (ed.tiley * 8), 16, 24, dwgfx.getRGB(200, 32, 32)); break; } if(ed.drawmode < 3) { if(ed.zmod && ed.drawmode < 2) { fillboxabs(dwgfx, (ed.tilex * 8) - 8, (ed.tiley * 8) - 8, 24, 24, dwgfx.getRGB(200, 32, 32)); } else if(ed.xmod && ed.drawmode < 2) { fillboxabs(dwgfx, (ed.tilex * 8) - 16, (ed.tiley * 8) - 16, 24 + 16, 24 + 16, dwgfx.getRGB(200, 32, 32)); } } //If in directmode, show current directmode tile if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].directmode == 1) { //Tile box for direct mode int t2 = 0; if(ed.dmtileeditor > 0) { ed.dmtileeditor--; if(ed.dmtileeditor <= 4) { t2 = (4 - ed.dmtileeditor) * 12; } //Draw five lines of the editor temp = ed.dmtile - (ed.dmtile % 40); temp -= 80; FillRect(dwgfx.backBuffer, 0, -t2, 320, 40, dwgfx.getRGB(0, 0, 0)); FillRect(dwgfx.backBuffer, 0, -t2 + 40, 320, 2, dwgfx.getRGB(255, 255, 255)); if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset == 0) { for(int i = 0; i < 40; i++) { dwgfx.drawtile(i * 8, 0 - t2, (temp + 1200 + i) % 1200); dwgfx.drawtile(i * 8, 8 - t2, (temp + 1200 + 40 + i) % 1200); dwgfx.drawtile(i * 8, 16 - t2, (temp + 1200 + 80 + i) % 1200); dwgfx.drawtile(i * 8, 24 - t2, (temp + 1200 + 120 + i) % 1200); dwgfx.drawtile(i * 8, 32 - t2, (temp + 1200 + 160 + i) % 1200); } } else { for(int i = 0; i < 40; i++) { dwgfx.drawtile2(i * 8, 0 - t2, (temp + 1200 + i) % 1200); dwgfx.drawtile2(i * 8, 8 - t2, (temp + 1200 + 40 + i) % 1200); dwgfx.drawtile2(i * 8, 16 - t2, (temp + 1200 + 80 + i) % 1200); dwgfx.drawtile2(i * 8, 24 - t2, (temp + 1200 + 120 + i) % 1200); dwgfx.drawtile2(i * 8, 32 - t2, (temp + 1200 + 160 + i) % 1200); } } //Highlight our little block fillboxabs(dwgfx, ((ed.dmtile % 40) * 8) - 2, 16 - 2, 12, 12, dwgfx.getRGB(196, 196, 255 - help.glow)); fillboxabs(dwgfx, ((ed.dmtile % 40) * 8) - 1, 16 - 1, 10, 10, dwgfx.getRGB(0, 0, 0)); } if(ed.dmtileeditor > 0 && t2 <= 30) { dwgfx.Print(2, 45 - t2, "Tile:", 196, 196, 255 - help.glow, false); dwgfx.Print(58, 45 - t2, help.String(ed.dmtile), 196, 196, 255 - help.glow, false); FillRect(dwgfx.backBuffer, 44, 44 - t2, 10, 10, dwgfx.getRGB(196, 196, 255 - help.glow)); FillRect(dwgfx.backBuffer, 45, 45 - t2, 8, 8, dwgfx.getRGB(0, 0, 0)); if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset == 0) { dwgfx.drawtile(45, 45 - t2, ed.dmtile); } else { dwgfx.drawtile2(45, 45 - t2, ed.dmtile); } } else { dwgfx.Print(2, 12, "Tile:", 196, 196, 255 - help.glow, false); dwgfx.Print(58, 12, help.String(ed.dmtile), 196, 196, 255 - help.glow, false); FillRect(dwgfx.backBuffer, 44, 11, 10, 10, dwgfx.getRGB(196, 196, 255 - help.glow)); FillRect(dwgfx.backBuffer, 45, 12, 8, 8, dwgfx.getRGB(0, 0, 0)); if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset == 0) { dwgfx.drawtile(45, 12, ed.dmtile); } else { dwgfx.drawtile2(45, 12, ed.dmtile); } } } //Draw GUI if(ed.boundarymod > 0) { if(ed.boundarymod == 1) { FillRect(dwgfx.backBuffer, 0, 230, 320, 240, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 0, 231, 320, 240, dwgfx.getRGB(0, 0, 0)); switch(ed.boundarytype) { case 0: dwgfx.Print(4, 232, "SCRIPT BOX: Click on top left", 255, 255, 255, false); break; case 1: dwgfx.Print(4, 232, "ENEMY BOUNDS: Click on top left", 255, 255, 255, false); break; case 2: dwgfx.Print(4, 232, "PLATFORM BOUNDS: Click on top left", 255, 255, 255, false); break; case 3: dwgfx.Print(4, 232, "COPY TILES: Click on top left", 255, 255, 255, false); break; default: dwgfx.Print(4, 232, "Click on top left", 255, 255, 255, false); break; } } else if(ed.boundarymod == 2) { FillRect(dwgfx.backBuffer, 0, 230, 320, 240, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 0, 231, 320, 240, dwgfx.getRGB(0, 0, 0)); switch(ed.boundarytype) { case 0: dwgfx.Print(4, 232, "SCRIPT BOX: Click on bottom right", 255, 255, 255, false); break; case 1: dwgfx.Print(4, 232, "ENEMY BOUNDS: Click on bottom right", 255, 255, 255, false); break; case 2: dwgfx.Print(4, 232, "PLATFORM BOUNDS: Click on bottom right", 255, 255, 255, false); break; case 3: dwgfx.Print(4, 232, "COPY TILES: Click on bottom right", 255, 255, 255, false); break; default: dwgfx.Print(4, 232, "Click on bottom right", 255, 255, 255, false); break; } } } else if(ed.scripteditmod) { //Elaborate C64 BASIC menu goes here! FillRect(dwgfx.backBuffer, 0, 0, 320, 240, dwgfx.getBGR(123, 111, 218)); FillRect(dwgfx.backBuffer, 14, 16, 292, 208, dwgfx.getRGB(162, 48, 61)); switch(ed.scripthelppage) { case 0: dwgfx.Print(16, 28, "**** VVVVVV SCRIPT EDITOR ****", 123, 111, 218, true); dwgfx.Print(16, 44, "PRESS ESC TO RETURN TO MENU", 123, 111, 218, true); //dwgfx.Print(16,60,"READY.", 123, 111, 218, false); if(ed.numhooks > 0) { for(int i = 0; i < 9; i++) { if(ed.hookmenupage + i < ed.numhooks) { if(ed.hookmenupage + i == ed.hookmenu) { std::string tstring = "> " + ed.hooklist[(ed.numhooks - 1) - (ed.hookmenupage + i)] + " <"; std::transform(tstring.begin(), tstring.end(), tstring.begin(), ::toupper); dwgfx.Print(16, 68 + (i * 16), tstring, 123, 111, 218, true); } else { dwgfx.Print(16, 68 + (i * 16), ed.hooklist[(ed.numhooks - 1) - (ed.hookmenupage + i)], 123, 111, 218, true); } } } } else { dwgfx.Print(16, 110, "NO SCRIPT IDS FOUND", 123, 111, 218, true); dwgfx.Print(16, 130, "CREATE A SCRIPT WITH EITHER", 123, 111, 218, true); dwgfx.Print(16, 140, "THE TERMINAL OR SCRIPT BOX TOOLS", 123, 111, 218, true); } break; case 1: //Current scriptname FillRect(dwgfx.backBuffer, 14, 226, 292, 12, dwgfx.getRGB(162, 48, 61)); dwgfx.Print(16, 228, "CURRENT SCRIPT: " + ed.sbscript, 123, 111, 218, true); //Draw text for(int i = 0; i < 25; i++) { if(i + ed.pagey < 500) { dwgfx.Print(16, 20 + (i * 8), ed.sb[i + ed.pagey], 123, 111, 218, false); } } //Draw cursor if(ed.entframe < 2) { dwgfx.Print(16 + (ed.sbx * 8), 20 + (ed.sby * 8), "_", 123, 111, 218, false); } break; } } else if(ed.settingsmod) { if(!game.colourblindmode) dwgfx.drawtowerbackgroundsolo(map); int tr = map.r - (help.glow / 4) - int(fRandom() * 4); int tg = map.g - (help.glow / 4) - int(fRandom() * 4); int tb = map.b - (help.glow / 4) - int(fRandom() * 4); if(tr < 0) tr = 0; if(tr > 255) tr = 255; if(tg < 0) tg = 0; if(tg > 255) tg = 255; if(tb < 0) tb = 0; if(tb > 255) tb = 255; if(game.currentmenuname == "ed_settings") { dwgfx.bigprint(-1, 75, "Map Settings", tr, tg, tb, true); } else if(game.currentmenuname == "ed_desc") { if(ed.titlemod) { if(ed.entframe < 2) { dwgfx.bigprint(-1, 35, key.keybuffer + "_", tr, tg, tb, true); } else { dwgfx.bigprint(-1, 35, key.keybuffer + " ", tr, tg, tb, true); } } else { dwgfx.bigprint(-1, 35, EditorData::GetInstance().title, tr, tg, tb, true); } if(ed.creatormod) { if(ed.entframe < 2) { dwgfx.Print(-1, 60, "by " + key.keybuffer + "_", tr, tg, tb, true); } else { dwgfx.Print(-1, 60, "by " + key.keybuffer + " ", tr, tg, tb, true); } } else { dwgfx.Print(-1, 60, "by " + EditorData::GetInstance().creator, tr, tg, tb, true); } if(ed.websitemod) { if(ed.entframe < 2) { dwgfx.Print(-1, 70, key.keybuffer + "_", tr, tg, tb, true); } else { dwgfx.Print(-1, 70, key.keybuffer + " ", tr, tg, tb, true); } } else { dwgfx.Print(-1, 70, ed.website, tr, tg, tb, true); } if(ed.desc1mod) { if(ed.entframe < 2) { dwgfx.Print(-1, 90, key.keybuffer + "_", tr, tg, tb, true); } else { dwgfx.Print(-1, 90, key.keybuffer + " ", tr, tg, tb, true); } } else { dwgfx.Print(-1, 90, ed.Desc1, tr, tg, tb, true); } if(ed.desc2mod) { if(ed.entframe < 2) { dwgfx.Print(-1, 100, key.keybuffer + "_", tr, tg, tb, true); } else { dwgfx.Print(-1, 100, key.keybuffer + " ", tr, tg, tb, true); } } else { dwgfx.Print(-1, 100, ed.Desc2, tr, tg, tb, true); } if(ed.desc3mod) { if(ed.entframe < 2) { dwgfx.Print(-1, 110, key.keybuffer + "_", tr, tg, tb, true); } else { dwgfx.Print(-1, 110, key.keybuffer + " ", tr, tg, tb, true); } } else { dwgfx.Print(-1, 110, ed.Desc3, tr, tg, tb, true); } } else if(game.currentmenuname == "ed_music") { dwgfx.bigprint(-1, 65, "Map Music", tr, tg, tb, true); dwgfx.Print(-1, 85, "Current map music:", tr, tg, tb, true); switch(ed.levmusic) { case 0: dwgfx.Print(-1, 120, "No background music", tr, tg, tb, true); break; case 1: dwgfx.Print(-1, 120, "1: Pushing Onwards", tr, tg, tb, true); break; case 2: dwgfx.Print(-1, 120, "2: Positive Force", tr, tg, tb, true); break; case 3: dwgfx.Print(-1, 120, "3: Potential For Anything", tr, tg, tb, true); break; case 4: dwgfx.Print(-1, 120, "4: Passion For Exploring", tr, tg, tb, true); break; case 6: dwgfx.Print(-1, 120, "5: Presenting VVVVVV", tr, tg, tb, true); break; case 8: dwgfx.Print(-1, 120, "6: Predestined Fate", tr, tg, tb, true); break; case 10: dwgfx.Print(-1, 120, "7: Popular Potpourri", tr, tg, tb, true); break; case 11: dwgfx.Print(-1, 120, "8: Pipe Dream", tr, tg, tb, true); break; case 12: dwgfx.Print(-1, 120, "9: Pressure Cooker", tr, tg, tb, true); break; case 13: dwgfx.Print(-1, 120, "10: Paced Energy", tr, tg, tb, true); break; case 14: dwgfx.Print(-1, 120, "11: Piercing The Sky", tr, tg, tb, true); break; default: dwgfx.Print(-1, 120, "?: something else", tr, tg, tb, true); break; } } else if(game.currentmenuname == "ed_quit") { dwgfx.bigprint(-1, 90, "Save before", tr, tg, tb, true); dwgfx.bigprint(-1, 110, "quiting?", tr, tg, tb, true); } dwgfx.drawmenu(game, tr, tg, tb, 15); /* dwgfx.Print(4, 224, "Enter name to save map as:", 255,255,255, false); if(ed.entframe<2){ dwgfx.Print(4, 232, ed.filename+"_", 196, 196, 255 - help.glow, true); }else{ dwgfx.Print(4, 232, ed.filename+" ", 196, 196, 255 - help.glow, true); } */ } else if(ed.scripttextmod) { FillRect(dwgfx.backBuffer, 0, 221, 320, 240, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 0, 222, 320, 240, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(4, 224, "Enter script id name:", 255, 255, 255, false); if(ed.entframe < 2) { dwgfx.Print(4, 232, edentity[ed.scripttextent].scriptname + "_", 196, 196, 255 - help.glow, true); } else { dwgfx.Print(4, 232, edentity[ed.scripttextent].scriptname + " ", 196, 196, 255 - help.glow, true); } } else if(ed.savemod) { FillRect(dwgfx.backBuffer, 0, 221, 320, 240, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 0, 222, 320, 240, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(4, 224, "Enter filename to save map as:", 255, 255, 255, false); if(ed.entframe < 2) { dwgfx.Print(4, 232, ed.filename + "_", 196, 196, 255 - help.glow, true); } else { dwgfx.Print(4, 232, ed.filename + " ", 196, 196, 255 - help.glow, true); } } else if(ed.loadmod) { FillRect(dwgfx.backBuffer, 0, 221, 320, 240, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 0, 222, 320, 240, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(4, 224, "Enter map filename to load:", 255, 255, 255, false); if(ed.entframe < 2) { dwgfx.Print(4, 232, ed.filename + "_", 196, 196, 255 - help.glow, true); } else { dwgfx.Print(4, 232, ed.filename + " ", 196, 196, 255 - help.glow, true); } } else if(ed.roomnamemod) { FillRect(dwgfx.backBuffer, 0, 221, 320, 240, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 0, 222, 320, 240, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(4, 224, "Enter new room name:", 255, 255, 255, false); if(ed.entframe < 2) { dwgfx.Print(4, 232, ed.level[ed.levx + (ed.levy * ed.maxwidth)].roomname + "_", 196, 196, 255 - help.glow, true); } else { dwgfx.Print(4, 232, ed.level[ed.levx + (ed.levy * ed.maxwidth)].roomname + " ", 196, 196, 255 - help.glow, true); } } else if(ed.roomtextmod) { FillRect(dwgfx.backBuffer, 0, 221, 320, 240, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 0, 222, 320, 240, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(4, 224, "Enter text string:", 255, 255, 255, false); if(ed.entframe < 2) { dwgfx.Print(4, 232, edentity[ed.roomtextent].scriptname + "_", 196, 196, 255 - help.glow, true); } else { dwgfx.Print(4, 232, edentity[ed.roomtextent].scriptname + " ", 196, 196, 255 - help.glow, true); } } else if(ed.warpmod) { //placing warp token FillRect(dwgfx.backBuffer, 0, 221, 320, 240, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 0, 222, 320, 240, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(4, 224, "Left click to place warp destination", 196, 196, 255 - help.glow, false); dwgfx.Print(4, 232, "Right click to cancel", 196, 196, 255 - help.glow, false); } else { if(ed.spacemod) { FillRect(dwgfx.backBuffer, 0, 208, 320, 240, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 0, 209, 320, 240, dwgfx.getRGB(0, 0, 0)); //Draw little icons for each thingy int tx = 6, ty = 211, tg = 32; if(ed.spacemenu == 0) { for(int i = 0; i < 10; i++) { FillRect(dwgfx.backBuffer, 4 + (i * tg), 209, 20, 20, dwgfx.getRGB(32, 32, 32)); } FillRect(dwgfx.backBuffer, 4 + (ed.drawmode * tg), 209, 20, 20, dwgfx.getRGB(64, 64, 64)); //0: dwgfx.drawtile(tx, ty, 83); dwgfx.drawtile(tx + 8, ty, 83); dwgfx.drawtile(tx, ty + 8, 83); dwgfx.drawtile(tx + 8, ty + 8, 83); //1: tx += tg; dwgfx.drawtile(tx, ty, 680); dwgfx.drawtile(tx + 8, ty, 680); dwgfx.drawtile(tx, ty + 8, 680); dwgfx.drawtile(tx + 8, ty + 8, 680); //2: tx += tg; dwgfx.drawtile(tx + 4, ty + 4, 8); //3: tx += tg; dwgfx.drawsprite(tx, ty, 22, 196, 196, 196); //4: tx += tg; dwgfx.drawsprite(tx, ty, 21, 196, 196, 196); //5: tx += tg; dwgfx.drawtile(tx, ty + 4, 3); dwgfx.drawtile(tx + 8, ty + 4, 4); //6: tx += tg; dwgfx.drawtile(tx, ty + 4, 24); dwgfx.drawtile(tx + 8, ty + 4, 24); //7: tx += tg; dwgfx.drawtile(tx, ty + 4, 1); dwgfx.drawtile(tx + 8, ty + 4, 1); //8: tx += tg; dwgfx.drawsprite(tx, ty, 78 + ed.entframe, 196, 196, 196); //9: tx += tg; FillRect(dwgfx.backBuffer, tx + 2, ty + 8, 12, 1, dwgfx.getRGB(255, 255, 255)); for(int i = 0; i < 9; i++) { fillboxabs(dwgfx, 4 + (i * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96)); dwgfx.Print(22 + (i * tg) - 4, 225 - 4, help.String(i + 1), 164, 164, 164, false); } if(ed.drawmode == 9) dwgfx.Print(22 + (ed.drawmode * tg) - 4, 225 - 4, "0", 255, 255, 255, false); fillboxabs(dwgfx, 4 + (9 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96)); dwgfx.Print(22 + (9 * tg) - 4, 225 - 4, "0", 164, 164, 164, false); fillboxabs(dwgfx, 4 + (ed.drawmode * tg), 209, 20, 20, dwgfx.getRGB(200, 200, 200)); if(ed.drawmode < 9) { dwgfx .Print(22 + (ed.drawmode * tg) - 4, 225 - 4, help.String(ed.drawmode + 1), 255, 255, 255, false); } dwgfx.Print(4, 232, "1/2", 196, 196, 255 - help.glow, false); } else { for(int i = 0; i < 7; i++) { FillRect(dwgfx.backBuffer, 4 + (i * tg), 209, 20, 20, dwgfx.getRGB(32, 32, 32)); } FillRect(dwgfx.backBuffer, 4 + ((ed.drawmode - 10) * tg), 209, 20, 20, dwgfx.getRGB(64, 64, 64)); //10: dwgfx.Print(tx, ty, "A", 196, 196, 255 - help.glow, false); dwgfx.Print(tx + 8, ty, "B", 196, 196, 255 - help.glow, false); dwgfx.Print(tx, ty + 8, "C", 196, 196, 255 - help.glow, false); dwgfx.Print(tx + 8, ty + 8, "D", 196, 196, 255 - help.glow, false); //11: tx += tg; dwgfx.drawsprite(tx, ty, 17, 196, 196, 196); //12: tx += tg; fillboxabs(dwgfx, tx + 4, ty + 4, 8, 8, dwgfx.getRGB(96, 96, 96)); //13: tx += tg; dwgfx.drawsprite(tx, ty, 18 + (ed.entframe % 2), 196, 196, 196); //14: tx += tg; FillRect(dwgfx.backBuffer, tx + 6, ty + 2, 4, 12, dwgfx.getRGB(255, 255, 255)); //15: tx += tg; dwgfx.drawsprite(tx, ty, 186, 75, 75, 255 - help.glow / 4 - (fRandom() * 20)); //16: tx += tg; dwgfx .drawsprite(tx, ty, 184, 160 - help.glow / 2 - (fRandom() * 20), 200 - help.glow / 2, 220 - help.glow); if(ed.drawmode == 10) dwgfx.Print(22 + ((ed.drawmode - 10) * tg) - 4, 225 - 4, "R", 255, 255, 255, false); if(ed.drawmode == 11) dwgfx.Print(22 + ((ed.drawmode - 10) * tg) - 4, 225 - 4, "T", 255, 255, 255, false); if(ed.drawmode == 12) dwgfx.Print(22 + ((ed.drawmode - 10) * tg) - 4, 225 - 4, "Y", 255, 255, 255, false); if(ed.drawmode == 13) dwgfx.Print(22 + ((ed.drawmode - 10) * tg) - 4, 225 - 4, "U", 255, 255, 255, false); if(ed.drawmode == 14) dwgfx.Print(22 + ((ed.drawmode - 10) * tg) - 4, 225 - 4, "I", 255, 255, 255, false); if(ed.drawmode == 15) dwgfx.Print(22 + ((ed.drawmode - 10) * tg) - 4, 225 - 4, "O", 255, 255, 255, false); if(ed.drawmode == 16) dwgfx.Print(22 + ((ed.drawmode - 10) * tg) - 4, 225 - 4, "P", 255, 255, 255, false); fillboxabs(dwgfx, 4 + (0 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96)); dwgfx.Print(22 + (0 * tg) - 4, 225 - 4, "R", 164, 164, 164, false); fillboxabs(dwgfx, 4 + (1 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96)); dwgfx.Print(22 + (1 * tg) - 4, 225 - 4, "T", 164, 164, 164, false); fillboxabs(dwgfx, 4 + (2 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96)); dwgfx.Print(22 + (2 * tg) - 4, 225 - 4, "Y", 164, 164, 164, false); fillboxabs(dwgfx, 4 + (3 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96)); dwgfx.Print(22 + (3 * tg) - 4, 225 - 4, "U", 164, 164, 164, false); fillboxabs(dwgfx, 4 + (4 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96)); dwgfx.Print(22 + (4 * tg) - 4, 225 - 4, "I", 164, 164, 164, false); fillboxabs(dwgfx, 4 + (5 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96)); dwgfx.Print(22 + (5 * tg) - 4, 225 - 4, "O", 164, 164, 164, false); fillboxabs(dwgfx, 4 + (6 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96)); dwgfx.Print(22 + (6 * tg) - 4, 225 - 4, "P", 164, 164, 164, false); dwgfx.Print(4, 232, "2/2", 196, 196, 255 - help.glow, false); } dwgfx.Print(128, 232, "< and > keys change tool", 196, 196, 255 - help.glow, false); FillRect(dwgfx.backBuffer, 0, 198, 120, 10, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 0, 199, 119, 9, dwgfx.getRGB(0, 0, 0)); switch(ed.drawmode) { case 0: dwgfx.Print(2, 199, "1: Walls", 196, 196, 255 - help.glow); break; case 1: dwgfx.Print(2, 199, "2: Backing", 196, 196, 255 - help.glow); break; case 2: dwgfx.Print(2, 199, "3: Spikes", 196, 196, 255 - help.glow); break; case 3: dwgfx.Print(2, 199, "4: Trinkets", 196, 196, 255 - help.glow); break; case 4: dwgfx.Print(2, 199, "5: Checkpoint", 196, 196, 255 - help.glow); break; case 5: dwgfx.Print(2, 199, "6: Disappear", 196, 196, 255 - help.glow); break; case 6: dwgfx.Print(2, 199, "7: Conveyors", 196, 196, 255 - help.glow); break; case 7: dwgfx.Print(2, 199, "8: Moving", 196, 196, 255 - help.glow); break; case 8: dwgfx.Print(2, 199, "9: Enemies", 196, 196, 255 - help.glow); break; case 9: dwgfx.Print(2, 199, "0: Grav Line", 196, 196, 255 - help.glow); break; case 10: dwgfx.Print(2, 199, "R: Roomtext", 196, 196, 255 - help.glow); break; case 11: dwgfx.Print(2, 199, "T: Terminal", 196, 196, 255 - help.glow); break; case 12: dwgfx.Print(2, 199, "Y: Script Box", 196, 196, 255 - help.glow); break; case 13: dwgfx.Print(2, 199, "U: Warp Token", 196, 196, 255 - help.glow); break; case 14: dwgfx.Print(2, 199, "I: Warp Lines", 196, 196, 255 - help.glow); break; case 15: dwgfx.Print(2, 199, "O: Crewmate", 196, 196, 255 - help.glow); break; case 16: dwgfx.Print(2, 199, "P: Start Point", 196, 196, 255 - help.glow); break; } FillRect(dwgfx.backBuffer, 260, 198, 80, 10, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 261, 199, 80, 9, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(268, 199, "(" + help.String(ed.levx + 1) + "," + help.String(ed.levy + 1) + ")", 196, 196, 255 - help.glow, false); } else { //FillRect(dwgfx.backBuffer, 0,230,72,240, dwgfx.RGB(32,32,32)); //FillRect(dwgfx.backBuffer, 0,231,71,240, dwgfx.RGB(0,0,0)); if(ed.level[ed.levx + (ed.maxwidth * ed.levy)].roomname != "") { if(ed.tiley < 28) { if(ed.roomnamehide > 0) ed.roomnamehide--; FillRect(dwgfx.backBuffer, 0, 230 + ed.roomnamehide, 320, 10, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(5, 231 + ed.roomnamehide, ed.level[ed.levx + (ed.maxwidth * ed.levy)].roomname, 196, 196, 255 - help.glow, true); } else { if(ed.roomnamehide < 12) ed.roomnamehide++; FillRect(dwgfx.backBuffer, 0, 230 + ed.roomnamehide, 320, 10, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(5, 231 + ed.roomnamehide, ed.level[ed.levx + (ed.maxwidth * ed.levy)].roomname, 196, 196, 255 - help.glow, true); } dwgfx.Print(4, 222, "SPACE ^ SHIFT ^", 196, 196, 255 - help.glow, false); dwgfx.Print(268, 222, "(" + help.String(ed.levx + 1) + "," + help.String(ed.levy + 1) + ")", 196, 196, 255 - help.glow, false); } else { dwgfx.Print(4, 232, "SPACE ^ SHIFT ^", 196, 196, 255 - help.glow, false); dwgfx.Print(268, 232, "(" + help.String(ed.levx + 1) + "," + help.String(ed.levy + 1) + ")", 196, 196, 255 - help.glow, false); } } if(ed.shiftmenu) { fillboxabs(dwgfx, 0, 127, 161 + 8, 140, dwgfx.getRGB(64, 64, 64)); FillRect(dwgfx.backBuffer, 0, 128, 160 + 8, 140, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(4, 130, "F1: Change Tileset", 164, 164, 164, false); dwgfx.Print(4, 140, "F2: Change Colour", 164, 164, 164, false); dwgfx.Print(4, 150, "F3: Change Enemies", 164, 164, 164, false); dwgfx.Print(4, 160, "F4: Enemy Bounds", 164, 164, 164, false); dwgfx.Print(4, 170, "F5: Platform Bounds", 164, 164, 164, false); dwgfx.Print(4, 190, "F10: Direct Mode", 164, 164, 164, false); dwgfx.Print(4, 210, "W: Change Warp Dir", 164, 164, 164, false); dwgfx.Print(4, 220, "E: Change Roomname", 164, 164, 164, false); fillboxabs(dwgfx, 220, 207, 100, 60, dwgfx.getRGB(64, 64, 64)); FillRect(dwgfx.backBuffer, 221, 208, 160, 60, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(224, 210, "S: Save Map", 164, 164, 164, false); dwgfx.Print(224, 220, "L: Load Map", 164, 164, 164, false); } } if(!ed.settingsmod && !ed.scripteditmod) { //Same as above, without borders switch(ed.drawmode) { case 0: dwgfx.Print(2, 2, "1: Walls", 196, 196, 255 - help.glow); break; case 1: dwgfx.Print(2, 2, "2: Backing", 196, 196, 255 - help.glow); break; case 2: dwgfx.Print(2, 2, "3: Spikes", 196, 196, 255 - help.glow); break; case 3: dwgfx.Print(2, 2, "4: Trinkets", 196, 196, 255 - help.glow); break; case 4: dwgfx.Print(2, 2, "5: Checkpoint", 196, 196, 255 - help.glow); break; case 5: dwgfx.Print(2, 2, "6: Disappear", 196, 196, 255 - help.glow); break; case 6: dwgfx.Print(2, 2, "7: Conveyors", 196, 196, 255 - help.glow); break; case 7: dwgfx.Print(2, 2, "8: Moving", 196, 196, 255 - help.glow); break; case 8: dwgfx.Print(2, 2, "9: Enemies", 196, 196, 255 - help.glow); break; case 9: dwgfx.Print(2, 2, "0: Grav Line", 196, 196, 255 - help.glow); break; case 10: dwgfx.Print(2, 2, "R: Roomtext", 196, 196, 255 - help.glow); break; case 11: dwgfx.Print(2, 2, "T: Terminal", 196, 196, 255 - help.glow); break; case 12: dwgfx.Print(2, 2, "Y: Script Box", 196, 196, 255 - help.glow); break; case 13: dwgfx.Print(2, 2, "U: Warp Token", 196, 196, 255 - help.glow); break; case 14: dwgfx.Print(2, 2, "I: Warp Lines", 196, 196, 255 - help.glow); break; case 15: dwgfx.Print(2, 2, "O: Crewmate", 196, 196, 255 - help.glow); break; case 16: dwgfx.Print(2, 2, "P: Start Point", 196, 196, 255 - help.glow); break; } //dwgfx.Print(254, 2, "F1: HELP", 196, 196, 255 - help.glow, false); } /* for(int i=0; i<script.customscript.size(); i++){ dwgfx.Print(0,i*8,script.customscript[i],255,255,255); } dwgfx.Print(0,8*script.customscript.size(),help.String(script.customscript.size()),255,255,255); for(int i=0; i<ed.numhooks; i++){ dwgfx.Print(260,i*8,ed.hooklist[i],255,255,255); } dwgfx.Print(260,8*ed.numhooks,help.String(ed.numhooks),255,255,255); */ if(ed.notedelay > 0) { FillRect(dwgfx.backBuffer, 0, 115, 320, 18, dwgfx.getRGB(92, 92, 92)); FillRect(dwgfx.backBuffer, 0, 116, 320, 16, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(0, 121, ed.note, 196 - ((45 - ed.notedelay) * 4), 196 - ((45 - ed.notedelay) * 4), 196 - ((45 - ed.notedelay) * 4), true); } if(game.test) { dwgfx.Print(5, 5, game.teststring, 196, 196, 255 - help.glow, false); } dwgfx.drawfade(); if(game.flashlight > 0 && !game.noflashingmode) { game.flashlight--; dwgfx.flashlight(); } if(game.screenshake > 0 && !game.noflashingmode) { game.screenshake--; dwgfx.screenshake(); } else { dwgfx.render(); } //dwgfx.backbuffer.unlock(); } void editorlogic(Graphics & dwgfx, Game & game, musicclass & music, mapclass & map, UtilityClass & help) { //Misc help.updateglow(); map.bypos -= 2; map.bscroll = -2; ed.entframedelay--; if(ed.entframedelay <= 0) { ed.entframe = (ed.entframe + 1) % 4; ed.entframedelay = 8; } if(ed.notedelay > 0) { ed.notedelay--; } if(dwgfx.fademode == 1) { //Return to game map.nexttowercolour(); map.colstate = 10; game.gamestate = 1; dwgfx.fademode = 4; music.stopmusic(); music.play(6); map.nexttowercolour(); ed.settingsmod = false; dwgfx.backgrounddrawn = false; game.createmenu("mainmenu"); } } void editorinput(KeyPoll & key, Graphics & dwgfx, Game & game, mapclass & map, entityclass & obj, UtilityClass & help, musicclass & music) { //TODO Mouse Input! game.mx = (float)key.mx; game.my = (float)key.my; ed.tilex = (game.mx - (game.mx % 8)) / 8; ed.tiley = (game.my - (game.my % 8)) / 8; game.press_left = false; game.press_right = false; game.press_action = false; game.press_map = false; if(key.isDown(KEYBOARD_LEFT) || key.isDown(KEYBOARD_a)) { game.press_left = true; } if(key.isDown(KEYBOARD_RIGHT) || key.isDown(KEYBOARD_d)) { game.press_right = true; } if(key.isDown(KEYBOARD_z) || key.isDown(KEYBOARD_SPACE) || key.isDown(KEYBOARD_v)) { // || key.isDown(KEYBOARD_UP) || key.isDown(KEYBOARD_DOWN) game.press_action = true; }; if(key.isDown(KEYBOARD_ENTER)) game.press_map = true; if(key.isDown(27) && !ed.settingskey) { ed.settingskey = true; if(ed.textentry) { key.disabletextentry(); ed.roomnamemod = false; ed.loadmod = false; ed.savemod = false; ed.textentry = false; ed.titlemod = false; ed.desc1mod = false; ed.desc2mod = false; ed.desc3mod = false; ed.websitemod = false; ed.creatormod = false; if(ed.scripttextmod) { ed.scripttextmod = false; removeedentity(ed.scripttextmod); } ed.shiftmenu = false; ed.shiftkey = false; } else if(ed.boundarymod > 0) { ed.boundarymod = 0; } else { ed.settingsmod = !ed.settingsmod; dwgfx.backgrounddrawn = false; game.createmenu("ed_settings"); map.nexttowercolour(); } } if(!key.isDown(27)) { ed.settingskey = false; } if(key.keymap[SDLK_LCTRL] || key.keymap[SDLK_RCTRL]) { if(key.leftbutton) key.rightbutton = true; } if(ed.scripteditmod) { if(ed.scripthelppage == 0) { //hook select menu if(ed.keydelay > 0) ed.keydelay--; if(key.keymap[SDLK_UP] && ed.keydelay <= 0) { ed.keydelay = 6; ed.hookmenu--; } if(key.keymap[SDLK_DOWN] && ed.keydelay <= 0) { ed.keydelay = 6; ed.hookmenu++; } if(ed.hookmenu >= ed.numhooks) { ed.hookmenu = ed.numhooks - 1; } if(ed.hookmenu < 0) ed.hookmenu = 0; if(ed.hookmenu < ed.hookmenupage) { ed.hookmenupage = ed.hookmenu; } if(ed.hookmenu >= ed.hookmenupage + 9) { ed.hookmenupage = ed.hookmenu + 8; } if(!key.keymap[SDLK_BACKSPACE]) ed.deletekeyheld = 0; if(key.keymap[SDLK_BACKSPACE] && ed.deletekeyheld == 0) { ed.deletekeyheld = 1; music.playef(2); ed.removehook(ed.hooklist[(ed.numhooks - 1) - ed.hookmenu]); } if(!game.press_action && !game.press_left && !game.press_right && !key.keymap[SDLK_UP] && !key.keymap[SDLK_DOWN] && !key.isDown(27)) game.jumpheld = false; if(!game.jumpheld) { if(game.press_action || game.press_left || game.press_right || game.press_map || key.keymap[SDLK_UP] || key.keymap[SDLK_DOWN] || key.isDown(27)) { game.jumpheld = true; } if((game.press_action || game.press_map) && ed.numhooks > 0) { game.mapheld = true; ed.scripthelppage = 1; key.keybuffer = ""; ed.sbscript = ed.hooklist[(ed.numhooks - 1) - ed.hookmenu]; ed.loadhookineditor(ed.sbscript); ed.sby = ed.sblength - 1; ed.pagey = 0; while(ed.sby >= 20) { ed.pagey++; ed.sby--; } key.keybuffer = ed.sb[ed.pagey + ed.sby]; ed.sbx = ed.sb[ed.pagey + ed.sby].length(); } if(key.isDown(27)) { ed.scripteditmod = false; ed.settingsmod = false; } } } else if(ed.scripthelppage == 1) { //Script editor! if(key.isDown(27)) { ed.scripthelppage = 0; game.jumpheld = true; //save the script for use again! ed.addhook(ed.sbscript); } if(ed.keydelay > 0) ed.keydelay--; if(key.keymap[SDLK_UP] && ed.keydelay <= 0) { ed.keydelay = 6; ed.sby--; if(ed.sby <= 5) { if(ed.pagey > 0) { ed.pagey--; ed.sby++; } else { if(ed.sby < 0) ed.sby = 0; } } key.keybuffer = ed.sb[ed.pagey + ed.sby]; } if(key.keymap[SDLK_DOWN] && ed.keydelay <= 0) { ed.keydelay = 6; if(ed.sby + ed.pagey < ed.sblength) { ed.sby++; if(ed.sby >= 20) { ed.pagey++; ed.sby--; } } key.keybuffer = ed.sb[ed.pagey + ed.sby]; } if(key.pressedbackspace && ed.sb[ed.pagey + ed.sby] == "") { //Remove this line completely ed.removeline(ed.pagey + ed.sby); ed.sby--; if(ed.sby <= 5) { if(ed.pagey > 0) { ed.pagey--; ed.sby++; } else { if(ed.sby < 0) ed.sby = 0; } } key.keybuffer = ed.sb[ed.pagey + ed.sby]; } ed.sb[ed.pagey + ed.sby] = key.keybuffer; ed.sbx = ed.sb[ed.pagey + ed.sby].length(); if(!game.press_map && !key.isDown(27)) game.mapheld = false; if(!game.mapheld) { if(game.press_map) { game.mapheld = true; //Continue to next line if(ed.sby + ed.pagey >= ed.sblength) //we're on the last line { ed.sby++; if(ed.sby >= 20) { ed.pagey++; ed.sby--; } if(ed.sby + ed.pagey >= ed.sblength) ed.sblength = ed.sby + ed.pagey; key.keybuffer = ed.sb[ed.pagey + ed.sby]; ed.sbx = ed.sb[ed.pagey + ed.sby].length(); } else { //We're not, insert a line instead ed.sby++; if(ed.sby >= 20) { ed.pagey++; ed.sby--; } ed.insertline(ed.sby + ed.pagey); key.keybuffer = ""; ed.sbx = 0; } } } } } else if(ed.textentry) { if(ed.roomnamemod) { ed.level[ed.levx + (ed.levy * ed.maxwidth)].roomname = key.keybuffer; } else if(ed.savemod) { ed.filename = key.keybuffer; } else if(ed.loadmod) { ed.filename = key.keybuffer; } else if(ed.roomtextmod) { edentity[ed.roomtextent].scriptname = key.keybuffer; } else if(ed.scripttextmod) { edentity[ed.scripttextent].scriptname = key.keybuffer; } else if(ed.titlemod) { EditorData::GetInstance().title = key.keybuffer; } else if(ed.creatormod) { EditorData::GetInstance().creator = key.keybuffer; } else if(ed.websitemod) { ed.website = key.keybuffer; } else if(ed.desc1mod) { ed.Desc1 = key.keybuffer; } else if(ed.desc2mod) { ed.Desc2 = key.keybuffer; } else if(ed.desc3mod) { ed.Desc3 = key.keybuffer; } if(!game.press_map && !key.isDown(27)) game.mapheld = false; if(!game.mapheld) { if(game.press_map) { game.mapheld = true; if(ed.roomnamemod) { ed.level[ed.levx + (ed.levy * ed.maxwidth)].roomname = key.keybuffer; ed.roomnamemod = false; } else if(ed.savemod) { std::string savestring = ed.filename + ".vvvvvv"; ed.save(savestring); ed.note = "[ Saved map: " + ed.filename + ".vvvvvv]"; ed.notedelay = 45; ed.savemod = false; ed.shiftmenu = false; ed.shiftkey = false; if(ed.saveandquit) { //quit editor dwgfx.fademode = 2; } } else if(ed.loadmod) { std::string loadstring = ed.filename + ".vvvvvv"; ed.load(loadstring); ed.note = "[ Loaded map: " + ed.filename + ".vvvvvv]"; ed.notedelay = 45; ed.loadmod = false; ed.shiftmenu = false; ed.shiftkey = false; } else if(ed.roomtextmod) { edentity[ed.roomtextent].scriptname = key.keybuffer; ed.roomtextmod = false; ed.shiftmenu = false; ed.shiftkey = false; } else if(ed.scripttextmod) { edentity[ed.scripttextent].scriptname = key.keybuffer; ed.scripttextmod = false; ed.clearscriptbuffer(); if(!ed.checkhook(edentity[ed.scripttextent].scriptname)) { ed.addhook(edentity[ed.scripttextent].scriptname); } } else if(ed.titlemod) { EditorData::GetInstance().title = key.keybuffer; ed.titlemod = false; } else if(ed.creatormod) { EditorData::GetInstance().creator = key.keybuffer; ed.creatormod = false; } else if(ed.websitemod) { ed.website = key.keybuffer; ed.websitemod = false; } else if(ed.desc1mod) { ed.Desc1 = key.keybuffer; } else if(ed.desc2mod) { ed.Desc2 = key.keybuffer; } else if(ed.desc3mod) { ed.Desc3 = key.keybuffer; ed.desc3mod = false; } key.disabletextentry(); ed.textentry = false; if(ed.desc1mod) { ed.desc1mod = false; ed.textentry = true; ed.desc2mod = true; key.enabletextentry(); key.keybuffer = ed.Desc2; } else if(ed.desc2mod) { ed.desc2mod = false; ed.textentry = true; ed.desc3mod = true; key.enabletextentry(); key.keybuffer = ed.Desc3; } } } } else { if(ed.settingsmod) { if(!game.press_action && !game.press_left && !game.press_right && !key.keymap[SDLK_UP] && !key.keymap[SDLK_DOWN]) game.jumpheld = false; if(!game.jumpheld) { if(game.press_action || game.press_left || game.press_right || game.press_map || key.keymap[SDLK_UP] || key.keymap[SDLK_DOWN]) { game.jumpheld = true; } if(game.menustart) { if(game.press_left || key.keymap[SDLK_UP]) { game.currentmenuoption--; } else if(game.press_right || key.keymap[SDLK_DOWN]) { game.currentmenuoption++; } } if(game.currentmenuoption < 0) game.currentmenuoption = game.nummenuoptions - 1; if(game.currentmenuoption >= game.nummenuoptions) game.currentmenuoption = 0; if(game.press_action) { if(game.currentmenuname == "ed_desc") { if(game.currentmenuoption == 0) { ed.textentry = true; ed.titlemod = true; key.enabletextentry(); key.keybuffer = EditorData::GetInstance().title; } else if(game.currentmenuoption == 1) { ed.textentry = true; ed.creatormod = true; key.enabletextentry(); key.keybuffer = EditorData::GetInstance().creator; } else if(game.currentmenuoption == 2) { ed.textentry = true; ed.desc1mod = true; key.enabletextentry(); key.keybuffer = ed.Desc1; } else if(game.currentmenuoption == 3) { ed.textentry = true; ed.websitemod = true; key.enabletextentry(); key.keybuffer = ed.website; } else if(game.currentmenuoption == 4) { music.playef(11); game.createmenu("ed_settings"); map.nexttowercolour(); } } else if(game.currentmenuname == "ed_settings") { if(game.currentmenuoption == 0) { //Change level description stuff music.playef(11); game.createmenu("ed_desc"); map.nexttowercolour(); } else if(game.currentmenuoption == 1) { //Enter script editormode music.playef(11); ed.scripteditmod = true; ed.clearscriptbuffer(); key.enabletextentry(); key.keybuffer = ""; ed.hookmenupage = 0; ed.hookmenu = 0; ed.scripthelppage = 0; ed.scripthelppagedelay = 0; ed.sby = 0; ed.sbx = 0, ed.pagey = 0; } else if(game.currentmenuoption == 2) { music.playef(11); game.createmenu("ed_music"); map.nexttowercolour(); if(ed.levmusic > 0) music.play(ed.levmusic); } else if(game.currentmenuoption == 3) { //Load level ed.settingsmod = false; dwgfx.backgrounddrawn = false; map.nexttowercolour(); ed.loadmod = true; ed.textentry = true; key.enabletextentry(); key.keybuffer = ed.filename; ed.keydelay = 6; game.mapheld = true; dwgfx.backgrounddrawn = false; } else if(game.currentmenuoption == 4) { //Save level ed.settingsmod = false; dwgfx.backgrounddrawn = false; map.nexttowercolour(); ed.savemod = true; ed.textentry = true; key.enabletextentry(); key.keybuffer = ed.filename; ed.keydelay = 6; game.mapheld = true; dwgfx.backgrounddrawn = false; } else if(game.currentmenuoption == 5) { music.playef(11); game.createmenu("ed_quit"); map.nexttowercolour(); } } else if(game.currentmenuname == "ed_music") { if(game.currentmenuoption == 0) { ed.levmusic++; if(ed.levmusic == 5) ed.levmusic = 6; if(ed.levmusic == 7) ed.levmusic = 8; if(ed.levmusic == 9) ed.levmusic = 10; if(ed.levmusic == 15) ed.levmusic = 0; if(ed.levmusic > 0) { music.play(ed.levmusic); } else { music.haltdasmusik(); } music.playef(11); } else if(game.currentmenuoption == 1) { music.playef(11); music.fadeout(); game.createmenu("ed_settings"); map.nexttowercolour(); } } else if(game.currentmenuname == "ed_quit") { if(game.currentmenuoption == 0) { //Saving and quit ed.saveandquit = true; ed.settingsmod = false; dwgfx.backgrounddrawn = false; map.nexttowercolour(); ed.savemod = true; ed.textentry = true; key.enabletextentry(); key.keybuffer = ed.filename; ed.keydelay = 6; game.mapheld = true; dwgfx.backgrounddrawn = false; } else if(game.currentmenuoption == 1) { //Quit without saving music.playef(11); music.fadeout(); dwgfx.fademode = 2; } else if(game.currentmenuoption == 2) { //Go back to editor music.playef(11); game.createmenu("ed_settings"); map.nexttowercolour(); } } } } } else { //Shortcut keys //TO DO: make more user friendly if(key.keymap[SDLK_F1] && ed.keydelay == 0) { ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset++; dwgfx.backgrounddrawn = false; if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset >= 5) ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset = 0; if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset == 0) { if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol >= 32) ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol = 0; } else if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset == 1) { if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol >= 8) ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol = 0; } else { if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol >= 6) ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol = 0; } ed.notedelay = 45; switch(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset) { case 0: ed.note = "Now using Space Station Tileset"; break; case 1: ed.note = "Now using Outside Tileset"; break; case 2: ed.note = "Now using Lab Tileset"; break; case 3: ed.note = "Now using Warp Zone Tileset"; break; case 4: ed.note = "Now using Ship Tileset"; break; case 5: ed.note = "Now using Tower Tileset"; break; default: ed.note = "Tileset Changed"; break; } ed.updatetiles = true; ed.keydelay = 6; } if(key.keymap[SDLK_F2] && ed.keydelay == 0) { ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol++; dwgfx.backgrounddrawn = false; if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset == 0) { if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol >= 32) ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol = 0; } else if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset == 1) { if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol >= 8) ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol = 0; } else { if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol >= 6) ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol = 0; } ed.updatetiles = true; ed.keydelay = 6; ed.notedelay = 45; ed.note = "Tileset Colour Changed"; } if(key.keymap[SDLK_F3] && ed.keydelay == 0) { ed.level[ed.levx + (ed.levy * ed.maxwidth)].enemytype = (ed.level[ed.levx + (ed.levy * ed.maxwidth)].enemytype + 1) % 10; ed.keydelay = 6; ed.notedelay = 45; ed.note = "Enemy Type Changed"; } if(key.keymap[SDLK_F4] && ed.keydelay == 0) { ed.keydelay = 6; ed.boundarytype = 1; ed.boundarymod = 1; } if(key.keymap[SDLK_F5] && ed.keydelay == 0) { ed.keydelay = 6; ed.boundarytype = 2; ed.boundarymod = 1; } if(key.keymap[SDLK_F10] && ed.keydelay == 0) { if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].directmode == 1) { ed.level[ed.levx + (ed.levy * ed.maxwidth)].directmode = 0; ed.note = "Direct Mode Disabled"; } else { ed.level[ed.levx + (ed.levy * ed.maxwidth)].directmode = 1; ed.note = "Direct Mode Enabled"; } dwgfx.backgrounddrawn = false; ed.notedelay = 45; ed.updatetiles = true; ed.keydelay = 6; } if(key.keymap[SDLK_1]) ed.drawmode = 0; if(key.keymap[SDLK_2]) ed.drawmode = 1; if(key.keymap[SDLK_3]) ed.drawmode = 2; if(key.keymap[SDLK_4]) ed.drawmode = 3; if(key.keymap[SDLK_5]) ed.drawmode = 4; if(key.keymap[SDLK_6]) ed.drawmode = 5; if(key.keymap[SDLK_7]) ed.drawmode = 6; if(key.keymap[SDLK_8]) ed.drawmode = 7; if(key.keymap[SDLK_9]) ed.drawmode = 8; if(key.keymap[SDLK_0]) ed.drawmode = 9; if(key.keymap[SDLK_r]) ed.drawmode = 10; if(key.keymap[SDLK_t]) ed.drawmode = 11; if(key.keymap[SDLK_y]) ed.drawmode = 12; if(key.keymap[SDLK_u]) ed.drawmode = 13; if(key.keymap[SDLK_i]) ed.drawmode = 14; if(key.keymap[SDLK_o]) ed.drawmode = 15; if(key.keymap[SDLK_p]) ed.drawmode = 16; if(key.keymap[SDLK_w] && ed.keydelay == 0) { int j = 0, tx = 0, ty = 0; for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { if(edentity[i].t == 50) { tx = (edentity[i].p1 - (edentity[i].p1 % 40)) / 40; ty = (edentity[i].p2 - (edentity[i].p2 % 30)) / 30; if(tx == ed.levx && ty == ed.levy) { j++; } } } if(j > 0) { ed.note = "ERROR: Cannot have both warp types"; ed.notedelay = 45; } else { ed.level[ed.levx + (ed.levy * ed.maxwidth)].warpdir = (ed.level[ed.levx + (ed.levy * ed.maxwidth)].warpdir + 1) % 4; if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].warpdir == 0) { ed.note = "Room warping disabled"; ed.notedelay = 45; dwgfx.backgrounddrawn = false; } else if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].warpdir == 1) { ed.note = "Room warps horizontally"; ed.notedelay = 45; dwgfx.backgrounddrawn = false; } else if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].warpdir == 2) { ed.note = "Room warps vertically"; ed.notedelay = 45; dwgfx.backgrounddrawn = false; } else if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].warpdir == 3) { ed.note = "Room warps in all directions"; ed.notedelay = 45; dwgfx.backgrounddrawn = false; } } ed.keydelay = 6; } if(key.keymap[SDLK_e] && ed.keydelay == 0) { ed.roomnamemod = true; ed.textentry = true; key.enabletextentry(); key.keybuffer = ed.level[ed.levx + (ed.levy * ed.maxwidth)].roomname; ed.keydelay = 6; game.mapheld = true; } //Save and load if(key.keymap[SDLK_s] && ed.keydelay == 0) { ed.savemod = true; ed.textentry = true; key.enabletextentry(); key.keybuffer = ed.filename; ed.keydelay = 6; game.mapheld = true; dwgfx.backgrounddrawn = false; } if(key.keymap[SDLK_l] && ed.keydelay == 0) { ed.loadmod = true; ed.textentry = true; key.enabletextentry(); key.keybuffer = ed.filename; ed.keydelay = 6; game.mapheld = true; dwgfx.backgrounddrawn = false; } if(!game.press_map) game.mapheld = false; if(!game.mapheld) { if(game.press_map) { game.mapheld = true; //Ok! Scan the room for the closest checkpoint int testeditor = -1; int startpoint = 0; //First up; is there a start point on this screen? for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { //if() on screen if(edentity[i].t == 16 && testeditor == -1) { int tx = (edentity[i].x - (edentity[i].x % 40)) / 40; int ty = (edentity[i].y - (edentity[i].y % 30)) / 30; if(tx == ed.levx && ty == ed.levy) { testeditor = i; startpoint = 1; } } } if(testeditor == -1) { //Ok, settle for a check point for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { //if() on screen if(edentity[i].t == 10 && testeditor == -1) { int tx = (edentity[i].x - (edentity[i].x % 40)) / 40; int ty = (edentity[i].y - (edentity[i].y % 30)) / 30; if(tx == ed.levx && ty == ed.levy) { testeditor = i; } } } } if(testeditor == -1) { ed.note = "ERROR: No checkpoint to spawn at"; ed.notedelay = 45; } else { if(startpoint == 0) { //Checkpoint spawn int tx = (edentity[testeditor].x - (edentity[testeditor].x % 40)) / 40; int ty = (edentity[testeditor].y - (edentity[testeditor].y % 30)) / 30; game.edsavex = (edentity[testeditor].x % 40) * 8; game.edsavey = (edentity[testeditor].y % 30) * 8; game.edsaverx = 100 + tx; game.edsavery = 100 + ty; game.edsavegc = edentity[testeditor].p1; if(game.edsavegc == 0) { game.edsavey--; } else { game.edsavey -= 8; } game.edsavedir = 0; } else { //Start point spawn int tx = (edentity[testeditor].x - (edentity[testeditor].x % 40)) / 40; int ty = (edentity[testeditor].y - (edentity[testeditor].y % 30)) / 30; game.edsavex = ((edentity[testeditor].x % 40) * 8) - 4; game.edsavey = (edentity[testeditor].y % 30) * 8; game.edsaverx = 100 + tx; game.edsavery = 100 + ty; game.edsavegc = 0; game.edsavey--; game.edsavedir = 1 - edentity[testeditor].p1; } music.stopmusic(); dwgfx.backgrounddrawn = false; script.startgamemode(21, dwgfx, game, map, obj, music); } //Return to game //game.gamestate=GAMEMODE; /*if(dwgfx.fademode==0) { dwgfx.fademode = 2; music.fadeout(); }*/ } } if(key.keymap[SDLK_x]) { ed.xmod = true; } else { ed.xmod = false; } if(key.keymap[SDLK_z]) { ed.zmod = true; } else { ed.zmod = false; } //Keyboard shortcuts if(ed.keydelay > 0) { ed.keydelay--; } else { if(key.keymap[SDLK_LSHIFT] || key.keymap[SDLK_RSHIFT]) { if(key.keymap[SDLK_UP]) { ed.keydelay = 6; ed.mapheight--; } else if(key.keymap[SDLK_DOWN]) { ed.keydelay = 6; ed.mapheight++; } if(key.keymap[SDLK_LEFT]) { ed.keydelay = 6; ed.mapwidth--; } else if(key.keymap[SDLK_RIGHT]) { ed.keydelay = 6; ed.mapwidth++; } if(ed.keydelay == 6) { if(ed.mapwidth < 1) ed.mapwidth = 1; if(ed.mapheight < 1) ed.mapheight = 1; if(ed.mapwidth >= ed.maxwidth) ed.mapwidth = ed.maxwidth; if(ed.mapheight >= ed.maxheight) ed.mapheight = ed.maxheight; ed.note = "Mapsize is now [" + help.String(ed.mapwidth) + "," + help.String(ed.mapheight) + "]"; ed.notedelay = 45; } } else { if(key.keymap[SDLK_COMMA]) { ed.drawmode--; ed.keydelay = 6; } else if(key.keymap[SDLK_PERIOD]) { ed.drawmode++; ed.keydelay = 6; } if(ed.drawmode < 0) { ed.drawmode = 16; if(ed.spacemod) ed.spacemenu = 0; } if(ed.drawmode > 16) ed.drawmode = 0; if(ed.drawmode > 9) { if(ed.spacemod) ed.spacemenu = 1; } else { if(ed.spacemod) ed.spacemenu = 0; } if(key.keymap[SDLK_LCTRL] || key.keymap[SDLK_RCTRL]) { ed.dmtileeditor = 10; if(key.keymap[SDLK_LEFT]) { ed.dmtile--; ed.keydelay = 3; if(ed.dmtile < 0) ed.dmtile += 1200; } else if(key.keymap[SDLK_RIGHT]) { ed.dmtile++; ed.keydelay = 3; if(ed.dmtile >= 1200) ed.dmtile -= 1200; } if(key.keymap[SDLK_UP]) { ed.dmtile -= 40; ed.keydelay = 3; if(ed.dmtile < 0) ed.dmtile += 1200; } else if(key.keymap[SDLK_DOWN]) { ed.dmtile += 40; ed.keydelay = 3; if(ed.dmtile >= 1200) ed.dmtile -= 1200; } } else { if(key.keymap[SDLK_UP]) { ed.keydelay = 6; dwgfx.backgrounddrawn = false; ed.levy--; ed.updatetiles = true; ed.changeroom = true; } else if(key.keymap[SDLK_DOWN]) { ed.keydelay = 6; dwgfx.backgrounddrawn = false; ed.levy++; ed.updatetiles = true; ed.changeroom = true; } else if(key.keymap[SDLK_LEFT]) { ed.keydelay = 6; dwgfx.backgrounddrawn = false; ed.levx--; ed.updatetiles = true; ed.changeroom = true; } else if(key.keymap[SDLK_RIGHT]) { ed.keydelay = 6; dwgfx.backgrounddrawn = false; ed.levx++; ed.updatetiles = true; ed.changeroom = true; } } if(ed.levx < 0) ed.levx += ed.mapwidth; if(ed.levx >= ed.mapwidth) ed.levx -= ed.mapwidth; if(ed.levy < 0) ed.levy += ed.mapheight; if(ed.levy >= ed.mapheight) ed.levy -= ed.mapheight; } if(key.keymap[SDLK_SPACE]) { ed.spacemod = !ed.spacemod; ed.keydelay = 6; } if(key.keymap[SDLK_LSHIFT] || key.keymap[SDLK_RSHIFT]) { if(!ed.shiftkey) { if(ed.shiftmenu) { ed.shiftmenu = false; } else { ed.shiftmenu = true; } } ed.shiftkey = true; } else { ed.shiftkey = false; } } } if(!ed.settingsmod) { if(ed.boundarymod > 0) { if(key.leftbutton) { if(ed.lclickdelay == 0) { if(ed.boundarymod == 1) { ed.lclickdelay = 1; ed.boundx1 = (ed.tilex * 8); ed.boundy1 = (ed.tiley * 8); ed.boundarymod = 2; } else if(ed.boundarymod == 2) { if((ed.tilex * 8) + 8 >= ed.boundx1 || (ed.tiley * 8) + 8 >= ed.boundy1) { ed.boundx2 = (ed.tilex * 8) + 8; ed.boundy2 = (ed.tiley * 8) + 8; } else { ed.boundx2 = ed.boundx1 + 8; ed.boundy2 = ed.boundy1 + 8; } if(ed.boundarytype == 0) { //Script trigger ed.scripttextmod = true; ed.scripttextent = EditorData::GetInstance().numedentities; addedentity((ed.boundx1 / 8) + (ed.levx * 40), (ed.boundy1 / 8) + (ed.levy * 30), 19, (ed.boundx2 - ed.boundx1) / 8, (ed.boundy2 - ed.boundy1) / 8); ed.lclickdelay = 1; ed.textentry = true; key.enabletextentry(); key.keybuffer = ""; ed.lclickdelay = 1; } else if(ed.boundarytype == 1) { //Enemy bounds int tmp = ed.levx + (ed.levy * ed.maxwidth); ed.level[tmp].enemyx1 = ed.boundx1; ed.level[tmp].enemyy1 = ed.boundy1; ed.level[tmp].enemyx2 = ed.boundx2; ed.level[tmp].enemyy2 = ed.boundy2; } else if(ed.boundarytype == 2) { //Platform bounds int tmp = ed.levx + (ed.levy * ed.maxwidth); ed.level[tmp].platx1 = ed.boundx1; ed.level[tmp].platy1 = ed.boundy1; ed.level[tmp].platx2 = ed.boundx2; ed.level[tmp].platy2 = ed.boundy2; } else if(ed.boundarytype == 3) { //Copy } ed.boundarymod = 0; ed.lclickdelay = 1; } } } else { ed.lclickdelay = 0; } if(key.rightbutton) { ed.boundarymod = 0; } } else if(ed.warpmod) { //Placing warp token if(key.leftbutton) { if(ed.lclickdelay == 0) { if(ed.free(ed.tilex, ed.tiley) == 0) { edentity[ed.warpent].p1 = ed.tilex + (ed.levx * 40); edentity[ed.warpent].p2 = ed.tiley + (ed.levy * 30); ed.warpmod = false; ed.warpent = -1; ed.lclickdelay = 1; } } } else { ed.lclickdelay = 0; } if(key.rightbutton) { removeedentity(ed.warpent); ed.warpmod = false; ed.warpent = -1; } } else { //Mouse input if(key.leftbutton) { if(ed.lclickdelay == 0) { //Depending on current mode, place something if(ed.drawmode == 0) { //place tiles //Are we in direct mode? if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].directmode >= 1) { if(ed.xmod) { for(int j = -2; j < 3; j++) { for(int i = -2; i < 3; i++) { ed.placetilelocal(ed.tilex + i, ed.tiley + j, ed.dmtile); } } } else if(ed.zmod) { for(int j = -1; j < 2; j++) { for(int i = -1; i < 2; i++) { ed.placetilelocal(ed.tilex + i, ed.tiley + j, ed.dmtile); } } } else { ed.placetilelocal(ed.tilex, ed.tiley, ed.dmtile); } } else { if(ed.xmod) { for(int j = -2; j < 3; j++) { for(int i = -2; i < 3; i++) { ed.placetilelocal(ed.tilex + i, ed.tiley + j, 80); } } } else if(ed.zmod) { for(int j = -1; j < 2; j++) { for(int i = -1; i < 2; i++) { ed.placetilelocal(ed.tilex + i, ed.tiley + j, 80); } } } else { ed.placetilelocal(ed.tilex, ed.tiley, 80); } } } else if(ed.drawmode == 1) { //place background tiles if(ed.xmod) { for(int j = -2; j < 3; j++) { for(int i = -2; i < 3; i++) { ed.placetilelocal(ed.tilex + i, ed.tiley + j, 2); } } } else if(ed.zmod) { for(int j = -1; j < 2; j++) { for(int i = -1; i < 2; i++) { ed.placetilelocal(ed.tilex + i, ed.tiley + j, 2); } } } else { ed.placetilelocal(ed.tilex, ed.tiley, 2); } } else if(ed.drawmode == 2) { //place spikes ed.placetilelocal(ed.tilex, ed.tiley, 8); } int tmp = edentat(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30)); if(tmp == -1) { //Room text and script triggers can be placed in walls if(ed.drawmode == 10) { ed.roomtextmod = true; ed.roomtextent = EditorData::GetInstance().numedentities; ed.textentry = true; key.enabletextentry(); key.keybuffer = ""; dwgfx.backgrounddrawn = false; addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 17); ed.lclickdelay = 1; } else if(ed.drawmode == 12) //Script Trigger { ed.boundarytype = 0; ed.boundx1 = ed.tilex * 8; ed.boundy1 = ed.tiley * 8; ed.boundarymod = 2; ed.lclickdelay = 1; } } if(tmp == -1 && ed.free(ed.tilex, ed.tiley) == 0) { if(ed.drawmode == 3) { if(ed.numtrinkets < 20) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 9); ed.lclickdelay = 1; ed.numtrinkets++; } else { ed.note = "ERROR: Max number of trinkets is 20"; ed.notedelay = 45; } } else if(ed.drawmode == 4) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 10, 1); ed.lclickdelay = 1; } else if(ed.drawmode == 5) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 3); ed.lclickdelay = 1; } else if(ed.drawmode == 6) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 2, 5); ed.lclickdelay = 1; } else if(ed.drawmode == 7) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 2, 0); ed.lclickdelay = 1; } else if(ed.drawmode == 8) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 1, 0); ed.lclickdelay = 1; } else if(ed.drawmode == 9) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 11, 0); ed.lclickdelay = 1; } else if(ed.drawmode == 11) { ed.scripttextmod = true; ed.scripttextent = EditorData::GetInstance().numedentities; ed.textentry = true; key.enabletextentry(); addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 18, 0); ed.lclickdelay = 1; } else if(ed.drawmode == 13) { ed.warpmod = true; ed.warpent = EditorData::GetInstance().numedentities; addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 13); ed.lclickdelay = 1; } else if(ed.drawmode == 14) { //Warp lines if(ed.level[ed.levx + (ed.maxwidth * ed.levy)].warpdir == 0) { if(ed.tilex == 0) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 50, 0); } else if(ed.tilex == 39) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 50, 1); } else if(ed.tiley == 0) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 50, 2); } else if(ed.tiley == 29) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 50, 3); } else { ed.note = "ERROR: Warp lines must be on edges"; ed.notedelay = 45; } } else { ed.note = "ERROR: Cannot have both warp types"; ed.notedelay = 45; } ed.lclickdelay = 1; } else if(ed.drawmode == 15) //Crewmate { if(ed.numcrewmates < 20) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 15, 1 + int(fRandom() * 5)); ed.lclickdelay = 1; ed.numcrewmates++; } else { ed.note = "ERROR: Max number of crewmates is 20"; ed.notedelay = 45; } } else if(ed.drawmode == 16) //Start Point { //If there is another start point, destroy it for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { if(edentity[i].t == 16) { removeedentity(i); i--; } } addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 16, 0); ed.lclickdelay = 1; } } else if(edentity[tmp].t == 1) { edentity[tmp].p1 = (edentity[tmp].p1 + 1) % 4; ed.lclickdelay = 1; } else if(edentity[tmp].t == 2) { if(edentity[tmp].p1 >= 5) { edentity[tmp].p1 = (edentity[tmp].p1 + 1) % 9; if(edentity[tmp].p1 < 5) edentity[tmp].p1 = 5; } else { edentity[tmp].p1 = (edentity[tmp].p1 + 1) % 4; } ed.lclickdelay = 1; } else if(edentity[tmp].t == 10) { edentity[tmp].p1 = (edentity[tmp].p1 + 1) % 2; ed.lclickdelay = 1; } else if(edentity[tmp].t == 11) { edentity[tmp].p1 = (edentity[tmp].p1 + 1) % 2; ed.lclickdelay = 1; } else if(edentity[tmp].t == 15) { edentity[tmp].p1 = (edentity[tmp].p1 + 1) % 6; ed.lclickdelay = 1; } else if(edentity[tmp].t == 16) { edentity[tmp].p1 = (edentity[tmp].p1 + 1) % 2; ed.lclickdelay = 1; } else if(edentity[tmp].t == 17) { ed.roomtextmod = true; ed.roomtextent = tmp; ed.textentry = true; key.enabletextentry(); key.keybuffer = edentity[tmp].scriptname; ed.lclickdelay = 1; } else if(edentity[tmp].t == 18) { ed.scripttextmod = true; ed.scripttextent = tmp; ed.textentry = true; key.enabletextentry(); key.keybuffer = edentity[tmp].scriptname; ed.lclickdelay = 1; } } } else { ed.lclickdelay = 0; } if(key.rightbutton) { //place tiles if(ed.xmod) { for(int j = -2; j < 3; j++) { for(int i = -2; i < 3; i++) { ed.placetilelocal(ed.tilex + i, ed.tiley + j, 0); } } } else if(ed.zmod) { for(int j = -1; j < 2; j++) { for(int i = -1; i < 2; i++) { ed.placetilelocal(ed.tilex + i, ed.tiley + j, 0); } } } else { ed.placetilelocal(ed.tilex, ed.tiley, 0); } for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { if(edentity[i].x == ed.tilex + (ed.levx * 40) && edentity[i].y == ed.tiley + (ed.levy * 30)) { if(edentity[i].t == 9) ed.numtrinkets--; if(edentity[i].t == 15) ed.numcrewmates--; removeedentity(i); } } } if(key.middlebutton) { ed.dmtile = ed.contents[ed.tilex + (ed.levx * 40) + ed.vmult[ed.tiley + (ed.levy * 30)]]; } } } } if(ed.updatetiles && ed.level[ed.levx + (ed.levy * ed.maxwidth)].directmode == 0) { ed.updatetiles = false; //Correctly set the tiles in the current room switch(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset) { case 0: //The Space Station for(int j = 0; j < 30; j++) { for(int i = 0; i < 40; i++) { temp = i + (ed.levx * 40) + ed.vmult[j + (ed.levy * 30)]; if(ed.contents[temp] >= 3 && ed.contents[temp] < 80) { //Fix spikes ed.contents[temp] = ed.spikedir(i, j); } else if(ed.contents[temp] == 2 || ed.contents[temp] >= 680) { //Fix background ed.contents[temp] = ed.backedgetile(i, j) + ed.backbase(ed.levx, ed.levy); } else if(ed.contents[temp] > 0) { //Fix tiles ed.contents[temp] = ed.edgetile(i, j) + ed.base(ed.levx, ed.levy); } } } break; case 1: //Outside for(int j = 0; j < 30; j++) { for(int i = 0; i < 40; i++) { temp = i + (ed.levx * 40) + ed.vmult[j + (ed.levy * 30)]; if(ed.contents[temp] >= 3 && ed.contents[temp] < 80) { //Fix spikes ed.contents[temp] = ed.spikedir(i, j); } else if(ed.contents[temp] == 2 || ed.contents[temp] >= 680) { //Fix background ed.contents[temp] = ed.outsideedgetile(i, j) + ed.backbase(ed.levx, ed.levy); } else if(ed.contents[temp] > 0) { //Fix tiles ed.contents[temp] = ed.edgetile(i, j) + ed.base(ed.levx, ed.levy); } } } break; case 2: //Lab for(int j = 0; j < 30; j++) { for(int i = 0; i < 40; i++) { temp = i + (ed.levx * 40) + ed.vmult[j + (ed.levy * 30)]; if(ed.contents[temp] >= 3 && ed.contents[temp] < 80) { //Fix spikes ed.contents[temp] = ed.labspikedir(i, j, ed.level[ed.levx + (ed.maxwidth * ed.levy)].tilecol); } else if(ed.contents[temp] == 2 || ed.contents[temp] >= 680) { //Fix background ed.contents[temp] = 713; } else if(ed.contents[temp] > 0) { //Fix tiles ed.contents[temp] = ed.edgetile(i, j) + ed.base(ed.levx, ed.levy); } } } break; case 3: //Warp Zone/Intermission for(int j = 0; j < 30; j++) { for(int i = 0; i < 40; i++) { temp = i + (ed.levx * 40) + ed.vmult[j + (ed.levy * 30)]; if(ed.contents[temp] >= 3 && ed.contents[temp] < 80) { //Fix spikes ed.contents[temp] = ed.spikedir(i, j); } else if(ed.contents[temp] == 2 || ed.contents[temp] >= 680) { //Fix background ed.contents[temp] = 713; //ed.backbase(ed.levx,ed.levy); } else if(ed.contents[temp] > 0) { //Fix tiles //ed.contents[temp]=ed.warpzoneedgetile(i,j)+ed.base(ed.levx,ed.levy); ed.contents[temp] = ed.edgetile(i, j) + ed.base(ed.levx, ed.levy); } } } break; case 4: //The ship for(int j = 0; j < 30; j++) { for(int i = 0; i < 40; i++) { temp = i + (ed.levx * 40) + ed.vmult[j + (ed.levy * 30)]; if(ed.contents[temp] >= 3 && ed.contents[temp] < 80) { //Fix spikes ed.contents[temp] = ed.spikedir(i, j); } else if(ed.contents[temp] == 2 || ed.contents[temp] >= 680) { //Fix background ed.contents[temp] = ed.backedgetile(i, j) + ed.backbase(ed.levx, ed.levy); } else if(ed.contents[temp] > 0) { //Fix tiles ed.contents[temp] = ed.edgetile(i, j) + ed.base(ed.levx, ed.levy); } } } break; case 5: //The Tower break; case 6: //Custom Set 1 break; case 7: //Custom Set 2 break; case 8: //Custom Set 3 break; case 9: //Custom Set 4 break; } } }
141,050
81,673
#include "FactoryTypeInputs.h" #include "ParserHelpers.h" mappers::FactoryTypeInputs::FactoryTypeInputs(std::istream& theStream) { registerRegex("[a-z_]+", [this](const std::string& inputGood, std::istream& theStream) { const commonItems::singleDouble inputValue(theStream); productionInputValues.insert(std::make_pair(inputGood, inputValue.getDouble())); }); registerRegex("[a-zA-Z0-9\\_.:]+", commonItems::ignoreItem); parseStream(theStream); clearRegisteredKeywords(); }
490
173
// Statistics.cpp // (C) Copyright 2017 by Martin Brunn see License.txt for details // #include "Statistics.h" Statistics::Statistics() { } Statistics::~Statistics() { }
192
77
// free(): is C method (Is it necessary to use C in your C++ app?) // delete: is C++ operator int main() { int* a = new int[5]; a[4] = 4; int* b = a; //free( a ); // It works but is necessary to include stdlib.h //free( b ); //delete a[]; // It works. delete[] b; // It works. __debugbreak(); return 0; }
321
137
#pragma once #ifdef ARCHITECT_CLANG_SUPPORT #include <functional> #include <string> typedef struct CXTranslationUnitImpl *CXTranslationUnit; namespace architect { class Registry; namespace clang { typedef std::function<bool(const std::string &)> Filter; struct Parameters { Filter filter; // returns whether to visit symbols in the file Parameters(); }; class DirectoryFilter { public: DirectoryFilter(); // working directory DirectoryFilter(const std::string &path); bool operator()(const std::string &filename) const; private: std::string _path; }; void parse(Registry &registry, const CXTranslationUnit translationUnit, Parameters &parameters = Parameters()); bool parse(Registry &registry, int argc, const char *const *argv, Parameters &parameters = Parameters()); } } #endif
836
279
#include "Popup.hpp" #include "Colors.hpp" namespace sfs { Popup::Popup(Scene &scene, const sf::Font &font, const sf::Vector2f &position) noexcept : UI(scene, "Popup", position) , _box(addComponent<Rectangle>()) , _text(addComponent<Text>(font, "", sf::Color::Black)) , _queue() , _elapsed(0.f) { } void Popup::updateString() noexcept { _text.setString(_queue.front().first); auto rect = _text.getLocalBounds(); float gapx = rect.width * 1.5; float gapy = rect.height * 2; _box.setSize(sf::Vector2f(gapx, gapy)); _box.setOffset(sf::Vector2f(-rect.width, 0)); auto boxrect = _box.getLocalBounds(); _text.setOffset(sf::Vector2f((boxrect.width - rect.width) / 2 - rect.left, (boxrect.height - rect.height) / 2 - rect.top) + _box.getOffset()); } sf::Uint8 Popup::getAlpha() const noexcept { if (_elapsed <= _queue.front().second / 3) { return _elapsed * 255 / (_queue.front().second / 3); } else if (_elapsed <= _queue.front().second * 2 / 3) { return 255; } return 255 - (_elapsed * 255 / (_queue.front().second / 3)); } sf::FloatRect Popup::getGlobalBounds() noexcept { return _text.getGlobalBounds(); } void Popup::clean() noexcept { auto color = _box.getFillColor(); color.a = 0; _box.setFillColor(color); _text.setString(""); _elapsed = 0; } void Popup::start() noexcept { } void Popup::update() noexcept { if (_queue.size() > 0) { _elapsed += scene().deltaTime(); if (_elapsed >= _queue.front().second) { _queue.pop(); _elapsed = 0.f; if (_queue.size() > 0) { updateString(); } else { Popup::clean(); return; } } auto color = _box.getFillColor(); auto alpha = getAlpha(); color.a = alpha; _box.setFillColor(color); color = _text.getFillColor(); color.a = alpha; _text.setFillColor(color); } } void Popup::onEvent(const sf::Event &) noexcept { } void Popup::onDestroy() noexcept { } void Popup::setTexture(const sf::Texture &texture) noexcept { _box.setTexture(&texture); } void Popup::setCharacterSize(uint32_t size) noexcept { _text.setCharacterSize(size); } void Popup::setBoxColor(const sf::Color &color) noexcept { _box.setFillColor(color); } void Popup::setTextColor(const sf::Color &color) noexcept { _text.setFillColor(color); } void Popup::push(const sf::String &string, float duration) noexcept { _queue.emplace(string, duration); if (_queue.size() == 1) updateString(); } void Popup::clear() noexcept { pop(_queue.size()); } void Popup::pop(size_t n) noexcept { while (_queue.size() > 0 && n > 0) _queue.pop(); if (_queue.size() == 0) Popup::clean(); } } // namespace sfs
2,609
1,079
#include "Preprocessor.h" Preprocessor::Preprocessor(std::string file) : _cap(new cv::VideoCapture(file)) { MEMORY("Preprocessor created"); if(!_cap->isOpened()) throw GenericException(GenericException::CAP_NOT_OPENED); } Preprocessor::~Preprocessor() { MEMORY("Preprocessor deleted"); } bool Preprocessor::getFrame(cv::Mat &out,cv::Mat &out_real,float w , float h, bool gray) { cv::Mat tmp; *_cap >> tmp; if(tmp.rows ==0) return false; tmp.copyTo(out_real); if(h>0) { resize(tmp,out,cv::Size(w,h)); } else { resize(tmp,out,cv::Size(w,w/(float)tmp.cols*tmp.rows)); } if(gray) { cvtColor(out,out,CV_RGB2GRAY); } display(ConfigManager::VIEW_FRAME_REAL, out_real); display(ConfigManager::VIEW_FRAME_RESIZED, out); VERBOSE_O("Preprocesso:: resized frame reuqest"); return true; } bool Preprocessor::getFrame(cv::Mat &out,float w , float h, bool gray) { cv::Mat tmp; *_cap >> tmp; if(tmp.rows ==0) return false; if(h>0) { resize(tmp,out,cv::Size(w,h)); } else { resize(tmp,out,cv::Size(w,w/(float)tmp.cols*tmp.rows)); } if(gray) { cvtColor(out,out,CV_RGB2GRAY); } return true; }
1,240
483
// // Created by USER on 6/1/2020. // #include <iostream> #include "Print.h" #include "../../PyVariable.h" #include "../../primitive/PyString.h" #include "../../../MemoryManager.h" PyClass *Print::process(std::map<std::string, PyClass *> &map) { const PyString* asStr = map["data"]->asString(); if (asStr == nullptr) { std::cout << map["data"] << std::endl; } else { std::cout << asStr->getValue() << std::endl; } return MemoryManager::getManager().getNone(); } Print::Print() : PyInternalFunction(new PyVariable("data", false)) {}
571
198
#include "CellRenderer.hpp" #include "String.hpp" #include "TextLayout.hpp" #include "VTConverter.hpp" #include <string> using namespace std; namespace MinConsoleNative { CellRenderer::CellRenderer(int consoleWidth, int consoleHeight, CellRendererMode mode) { this->consoleWidth = consoleWidth; this->consoleHeight = consoleHeight; this->mode = mode; this->cellArray = new Cell[consoleWidth * consoleHeight]; this->cellArrayBuffer = new Cell[consoleWidth * consoleHeight]; if (mode == CellRendererMode::Fast) { this->charInfos = new CHAR_INFO[consoleWidth * consoleHeight]; } else { this->charInfos = nullptr; } } CellRenderer::~CellRenderer() { delete[] this->cellArray; delete[] this->cellArrayBuffer; if (mode == CellRendererMode::Fast) { delete[] this->charInfos; } } void CellRenderer::Clear(const Cell& cell) { for (int i = 0; i < consoleWidth * consoleHeight; i++) { this->cellArrayBuffer[i] = this->cellArray[i]; //copy this->cellArray[i] = cell; //set default } } void CellRenderer::Render() { if (mode == CellRendererMode::Fast) RenderFast(); else if (mode == CellRendererMode::TrueColor) RenderTrueColor(); else if (mode == CellRendererMode::Mixed) RenderMixed(); else if (mode == CellRendererMode::FastTrueColor) RenderFastTrueColor(); } void CellRenderer::Draw(const Vector2& pos, const Cell& cell) { if (pos.x < 0 || pos.x > consoleWidth - 1 || pos.y < 0 || pos.y > consoleHeight - 1) return; int index = consoleWidth * pos.y + pos.x; this->cellArray[index] = cell; } void CellRenderer::DrawString(const Vector2& pos, const std::wstring& wstr, Color24 foreColor, Color24 backColor, bool underScore) { for (int i = 0; i < wstr.size(); i++) { CellRenderer::Draw(Vector2(pos.x + i, pos.y), Cell(wstr[i], foreColor, backColor, underScore)); } } int CellRenderer::DrawString2(const Vector2& pos, const std::wstring& wstr, Color24 foreColor, Color24 backColor, bool underScore) { vector<wstring> grids = textLayout.WstringToGrids(wstr); for (int i = 0; i < grids.size(); i++) { const wstring& gridStr = grids[i]; if (gridStr.size() == 1) { CellRenderer::Draw(Vector2(pos.x + i * 2, pos.y), Cell(gridStr[0], foreColor, backColor, underScore, true)); CellRenderer::Draw(Vector2(pos.x + i * 2 + 1, pos.y), Cell(L' ', foreColor, backColor, underScore, false)); } else if (gridStr.size() == 2) { CellRenderer::Draw(Vector2(pos.x + i * 2, pos.y), Cell(gridStr[0], foreColor, backColor, underScore)); CellRenderer::Draw(Vector2(pos.x + i * 2 + 1, pos.y), Cell(gridStr[1], foreColor, backColor, underScore)); } } return grids.size(); } void CellRenderer::DrawStringWrap(const Vector2& pos, const std::wstring& wstr, Color24 foreColor, Color24 backColor, bool underScore) { for (int i = 0; i < wstr.size(); i++) { int positionX = pos.x + i; int positionY = pos.y; while (positionX > consoleWidth - 1) { positionX -= consoleWidth; positionY++; } CellRenderer::Draw(Vector2(positionX, positionY), Cell(wstr[i], foreColor, backColor, underScore)); } } int CellRenderer::DrawString2Wrap(const Vector2& pos, const std::wstring& wstr, Color24 foreColor, Color24 backColor, bool underScore) { vector<wstring> grids = textLayout.WstringToGrids(wstr); for (int i = 0; i < grids.size(); i++) { int positionX = pos.x + i * 2; int positionY = pos.y; while (positionX > consoleWidth - 1) { positionX -= consoleWidth; positionY++; } const wstring& gridStr = grids[i]; if (gridStr.size() == 1) { CellRenderer::Draw(Vector2(positionX, positionY), Cell(gridStr[0], foreColor, backColor, underScore, true)); CellRenderer::Draw(Vector2(positionX + 1, positionY), Cell(L' ', foreColor, backColor, underScore, false)); } else if (gridStr.size() == 2) { CellRenderer::Draw(Vector2(positionX, positionY), Cell(gridStr[0], foreColor, backColor, underScore)); CellRenderer::Draw(Vector2(positionX + 1, positionY), Cell(gridStr[1], foreColor, backColor, underScore)); } } return grids.size(); } void CellRenderer::DrawBorderBox(const Vector2& pos, const Vector2& size, const Vector2& borderSize, const Cell& cell, const Cell& borderCell) { for (int i = 0; i < size.y; i++) { for (int j = 0; j < size.x; j++) { if (i >= 0 && i < borderSize.y || j >= 0 && j < borderSize.x || i <= size.y - 1 && i > size.y - 1 - borderSize.y || j <= size.x - 1 && j > size.x - 1 - borderSize.x) { CellRenderer::Draw(Vector2(pos.x + j, pos.y + i), borderCell); } else { CellRenderer::Draw(Vector2(pos.x + j, pos.y + i), cell); } } } } void CellRenderer::DrawBorderBox2(const Vector2& pos, const Vector2& size, const Vector2& borderSize, const std::wstring& cellWstr, Color24 cellForeColor, Color24 cellBackColor, bool cellUnderScore, const std::wstring& borderWstr, Color24 borderForeColor, Color24 borderBackColor, bool borderUnderScore) { for (int i = 0; i < size.y; i++) { for (int j = 0; j < size.x; j++) { if (i >= 0 && i < borderSize.y || j >= 0 && j < borderSize.x || i <= size.y - 1 && i > size.y - 1 - borderSize.y || j <= size.x - 1 && j > size.x - 1 - borderSize.x) { CellRenderer::DrawString2(Vector2(pos.x + j * 2, pos.y + i), borderWstr, borderForeColor, borderBackColor, borderUnderScore); } else { CellRenderer::DrawString2(Vector2(pos.x + j * 2, pos.y + i), cellWstr, cellForeColor, cellBackColor, cellUnderScore); } } } } void CellRenderer::RenderFast() { bool findLeadingByte = false; for (int i = 0; i < consoleWidth * consoleHeight; i++) { const Cell& cell = this->cellArray[i]; ushort att = 0; att |= MinConsoleColorToUshort(cell.foreColor.ToConsoleColor(), cell.backColor.ToConsoleColor()); if (cell.underScore) att |= COMMON_LVB_UNDERSCORE; if (cell.isLeadingByte) { att |= COMMON_LVB_LEADING_BYTE; findLeadingByte = true; } else if (findLeadingByte) { att |= COMMON_LVB_TRAILING_BYTE; findLeadingByte = false; } charInfos[i].Attributes = att; charInfos[i].Char.UnicodeChar = cell.c; } console.WriteConsoleOutputW(charInfos, 0, 0, consoleWidth, consoleHeight); } void CellRenderer::RenderMixed() { //draw true color: for (int i = 0; i < consoleWidth * consoleHeight; i++) { const Cell& cell = this->cellArray[i]; const Cell& cellBuffer = this->cellArrayBuffer[i]; if (cell != cellBuffer) { COORD position = { i % consoleWidth, i / consoleWidth }; COORD beforePosition = console.GetConsoleCursorPos(); console.SetConsoleCursorPos(position); console.Write(String::WcharToWstring(L' '), cell.foreColor, cell.backColor, cell.underScore); console.SetConsoleCursorPos(beforePosition); } } //draw string: wstring* lines = new wstring[consoleHeight]; for (int i = 0; i < consoleWidth * consoleHeight; i++) { lines[i / consoleWidth] += this->cellArray[i].c; const Cell& cell = this->cellArray[i]; if (cell.isLeadingByte) { i++; } } for (int i = 0; i < consoleHeight; i++) { console.WriteConsoleOutputCharacterW(lines[i], { 0, (short)i }); } delete[] lines; } void CellRenderer::RenderTrueColor() { for (int i = 0; i < consoleWidth * consoleHeight; i++) { const Cell& cell = this->cellArray[i]; const Cell& cellBuffer = this->cellArrayBuffer[i]; if (cell != cellBuffer) { COORD position = { i % consoleWidth, i / consoleWidth }; COORD beforePosition = console.GetConsoleCursorPos(); console.SetConsoleCursorPos(position); console.Write(String::WcharToWstring(cell.c), cell.foreColor, cell.backColor, cell.underScore); console.SetConsoleCursorPos(beforePosition); } } } void CellRenderer::RenderFastTrueColor() { wstring wstr; for (int i = 0; i < consoleWidth * consoleHeight; i++) { const Cell& cell = this->cellArray[i]; wstr += cell.c; //wstring foreColor = L"\033[38;2;255;0;255m"; //wstr += foreColor + cell.c; //wstring fore_str = VTConverter::VTForeColor(cell.foreColor); //wstring back_str = VTConverter::VTBackColor(cell.backColor); //wstring us_str = VTConverter::VTUnderline(cell.underScore); //wstring reset_str = VTConverter::VTResetStyle(); //wstr += (fore_str + back_str + us_str + cell.c + reset_str); } //console.Write(wstr, { 233,21,22 }); console.Write(wstr); } }
10,355
3,108
#include <windows.h> BOOL APIENTRY wWinMain(HINSTANCE, HINSTANCE, LPTSTR, int) { int argc; wchar_t **argv = CommandLineToArgvW(GetCommandLineW(), &argc); if (argc < 4) return ERROR_INVALID_PARAMETER; DWORD nErr=ERROR_SUCCESS, nParentID = (DWORD)_wtol(argv[1]); HANDLE hList[2] = { OpenProcess(SYNCHRONIZE, FALSE, nParentID), (HANDLE)_wtol(argv[3]) }; if (!hList[0]) return GetLastError(); if (!AttachConsole(nParentID)) { //Attach to the parent console nErr = GetLastError(); goto Done; } if (!SetEvent((HANDLE)_wtol(argv[2]))) { //Allow the parent to continue execution nErr = GetLastError(); goto Done; } if (WaitForMultipleObjects(2, hList, FALSE, INFINITE) == WAIT_FAILED) nErr = GetLastError(); Done: CloseHandle(hList[0]); return nErr; }
817
352
/** * Copyright (C) 2022 Advanced Micro Devices, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located 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 "SectionAIEPartition.h" #include "XclBinUtilities.h" #include <boost/algorithm/string/predicate.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/functional/factory.hpp> #include <boost/property_tree/json_parser.hpp> #include <iostream> namespace XUtil = XclBinUtilities; // ------------------------------------------------------------------------- // Static Variables / Classes SectionAIEPartition::init SectionAIEPartition::initializer; SectionAIEPartition::init::init() { auto sectionInfo = std::make_unique<SectionInfo>(AIE_PARTITION, "AIE_PARTITION", boost::factory<SectionAIEPartition*>()); sectionInfo->nodeName = "aie_partition"; sectionInfo->supportsSubSections = true; sectionInfo->supportsIndexing = true; // There is only one-subsection that is supported. By default it is not named. sectionInfo->subSections.push_back(""); sectionInfo->supportedAddFormats.push_back(FormatType::json); sectionInfo->supportedDumpFormats.push_back(FormatType::json); addSectionType(std::move(sectionInfo)); } // ------------------------------------------------------------------------- class SectionHeap { public: SectionHeap() = delete; SectionHeap(uint64_t heapSectionOffset) { if (XUtil::bytesToAlign(heapSectionOffset) != 0) throw std::runtime_error("Error: HeapSectionOffset is not aligned to 8 bytes"); m_heapSectionOffset = heapSectionOffset; } void write(const char* pBuffer, size_t size, bool align = true) { if ((pBuffer != nullptr) && size) m_heapBuffer.write(pBuffer, size); if (align) XUtil::alignBytes(m_heapBuffer, 8); } uint64_t getNextBufferOffset() { // Get the current size m_heapBuffer.seekp(0, std::ios_base::end); uint64_t bufSize = (uint64_t)m_heapBuffer.tellp(); // And add it to the buffer offset. return bufSize + m_heapSectionOffset; } void writeHeapToStream(std::ostringstream& osStream) { const auto& sHeap = m_heapBuffer.str(); osStream.write(sHeap.c_str(), sHeap.size()); } protected: uint64_t m_heapSectionOffset; std::ostringstream m_heapBuffer; }; // ---------------------------------------------------------------------------- bool SectionAIEPartition::subSectionExists(const std::string& /*sSubSectionName*/) const { // No buffer no subsections return (m_pBuffer != nullptr); } // ------------------------------------------------------------------------- static const std::vector<std::pair<std::string, CDO_Type>> CTTypes = { { "UNKNOWN", CT_UNKNOWN }, { "PRIMARY", CT_PRIMARY }, { "LITE", CT_LITE } }; static const std::string& getCDOTypeStr(CDO_Type eCDOType) { auto iter = std::find_if(CTTypes.begin(), CTTypes.end(), [&](const auto& entry) {return entry.second == eCDOType;}); if (iter == CTTypes.end()) return getCDOTypeStr(CT_UNKNOWN); return iter->first; } static CDO_Type getCDOTypesEnum(const std::string& sTypeName) { auto iter = std::find_if(CTTypes.begin(), CTTypes.end(), [&](const auto& entry) {return boost::iequals(entry.first, sTypeName);}); if (iter == CTTypes.end()) return CT_UNKNOWN; return iter->second; } // ------------------------------------------------------------------------- static void process_PDI_uuid(const boost::property_tree::ptree& ptPDI, aie_pdi& aieParitionPDI) { XUtil::TRACE("Processing PDI UUID"); auto uuid = ptPDI.get<std::string>("uuid", ""); if (uuid.empty()) throw std::runtime_error("Error: The PDI element is missing the 'uuid' node."); // Clean up the UUID boost::replace_all(uuid, "0x", ""); // Remove all "0x" boost::replace_all(uuid, "-", ""); // Remove all minus signs if (uuid.size() < (2 * sizeof(aie_pdi::uuid))) // Add leading zeros uuid.insert(0, (2 * sizeof(aie_pdi::uuid) - uuid.size()), '0'); if (uuid.size() > (2 * sizeof(aie_pdi::uuid))) throw std::runtime_error("Error: The UUID node value is larger then the storage size for this value."); // Write out the value XUtil::hexStringToBinaryBuffer(uuid, reinterpret_cast<unsigned char*>(aieParitionPDI.uuid), sizeof(aie_pdi::uuid)); } // ------------------------------------------------------------------------- static void read_file_into_buffer(const std::string& fileName, const boost::filesystem::path& fromRelativeDir, std::vector<char>& buffer) { // Build the path to our file of interest boost::filesystem::path filePath = fileName; if (filePath.is_relative()) { filePath = fromRelativeDir; filePath /= fileName; } XUtil::TRACE(boost::format("Reading in the file: '%s'") % filePath.string()); // Open the file std::ifstream file(filePath.string(), std::ifstream::in | std::ifstream::binary); if (!file.is_open()) throw std::runtime_error("ERROR: Unable to open the file for reading: " + fileName); // Get the file size file.seekg(0, file.end); std::streamsize fileSize = file.tellg(); file.seekg(0, file.beg); // Resize the buffer and read in the array buffer.resize(fileSize); file.read(buffer.data(), fileSize); // Make sure that the entire buffer was read if (file.gcount() != fileSize) throw std::runtime_error("ERROR: Input stream for the binary buffer is smaller then the expected size."); } // ------------------------------------------------------------------------- static void process_PDI_file(const boost::property_tree::ptree& ptAIEPartitionPDI, const boost::filesystem::path& relativeFromDir, aie_pdi& aiePartitionPDI, SectionHeap& heap) { XUtil::TRACE("Processing PDI Files"); const auto& fileName = ptAIEPartitionPDI.get<std::string>("file_name", ""); if (fileName.empty()) throw std::runtime_error("Error: Missing PDI file name node."); // Read file image from disk std::vector<char> buffer; read_file_into_buffer(fileName, relativeFromDir, buffer); // Store file image in the heap aiePartitionPDI.pdi_image.size = static_cast<decltype(aiePartitionPDI.pdi_image.size)>(buffer.size()); aiePartitionPDI.pdi_image.offset = static_cast<decltype(aiePartitionPDI.pdi_image.offset)>(heap.getNextBufferOffset()); heap.write(reinterpret_cast<const char*>(buffer.data()), buffer.size()); } // ------------------------------------------------------------------------- static void process_pre_cdo_groups(const boost::property_tree::ptree& ptAIECDOGroup, cdo_group& aieCDOGroup, SectionHeap& heap) { XUtil::TRACE("Processing Pre CDO Groups"); std::vector<std::string> preCDOGroups = XUtil::as_vector_simple<std::string>(ptAIECDOGroup, "pre_cdo_groups"); aieCDOGroup.pre_cdo_groups.size = static_cast<decltype(aieCDOGroup.pre_cdo_groups.size)>(preCDOGroups.size()); // It is O.K. not to have any CDO groups if (aieCDOGroup.pre_cdo_groups.size == 0) return; // Record where the CDO group array starts. aieCDOGroup.pre_cdo_groups.offset = static_cast<decltype(aieCDOGroup.pre_cdo_groups.offset)>(heap.getNextBufferOffset()); // Write out the CDO value to the heap. for (const auto& element : preCDOGroups) { uint64_t preGroupID = std::strtoul(element.c_str(), NULL, 0); heap.write(reinterpret_cast<const char*>(&preGroupID), sizeof(decltype(preGroupID)), false /*align*/); } // Align the heap to the next 64-bit word. heap.write(nullptr, 0); } // ------------------------------------------------------------------------- static void process_PDI_cdo_groups(const boost::property_tree::ptree& ptAIEPartitionPDI, aie_pdi& aiePDI, SectionHeap& heap) { XUtil::TRACE("Processing CDO Groups"); std::vector<boost::property_tree::ptree> ptCDOs = XUtil::as_vector<boost::property_tree::ptree>(ptAIEPartitionPDI, "cdo_groups"); aiePDI.cdo_groups.size = static_cast<decltype(aiePDI.cdo_groups.size)>(ptCDOs.size()); if (aiePDI.cdo_groups.size == 0) throw std::runtime_error("Error: There are no cdo groups in the PDI node AIE Partition section."); // Examine each of the CDO groups std::vector<cdo_group> vCDOs; for (const auto& element : ptCDOs) { cdo_group aieCDOGroup = { }; // Name auto name = element.get<std::string>("name", ""); aieCDOGroup.mpo_name = static_cast<decltype(aieCDOGroup.mpo_name)>(heap.getNextBufferOffset()); heap.write(reinterpret_cast<const char*>(name.c_str()), name.size() + 1 /*Null CharL*/); // Type aieCDOGroup.cdo_type = static_cast<decltype(aieCDOGroup.cdo_type)>(getCDOTypesEnum(element.get<std::string>("type", ""))); // PDI ID auto sPDIValue = element.get<std::string>("pdi_id", ""); if (sPDIValue.empty()) throw std::runtime_error("Error: PDI ID node value not found"); aieCDOGroup.pdi_id = std::strtoul(sPDIValue.c_str(), NULL, 0); // DPU Function ID (optional) auto sDPUValue = element.get<std::string>("dpu_kernel_id", ""); if (!sDPUValue.empty()) aieCDOGroup.dpu_kernel_id = std::strtoul(sDPUValue.c_str(), NULL, 0); // PRE CDO Groups (optional) process_pre_cdo_groups(element, aieCDOGroup, heap); // Finished processing the element. Save it away. vCDOs.push_back(aieCDOGroup); } // Write out the CDO group array. Note: The CDO group element is 64-bit aligned. aiePDI.cdo_groups.offset = static_cast<decltype(aiePDI.cdo_groups.offset)>(heap.getNextBufferOffset()); for (const auto& element : vCDOs) heap.write(reinterpret_cast<const char*>(&element), sizeof(cdo_group)); } // ------------------------------------------------------------------------- static void process_PDIs(const boost::property_tree::ptree& ptAIEPartition, const boost::filesystem::path& relativeFromDir, aie_partition& aiePartitionHdr, SectionHeap& heap) { XUtil::TRACE("Processing PDIs"); std::vector<boost::property_tree::ptree> ptPDIs = XUtil::as_vector<boost::property_tree::ptree>(ptAIEPartition, "PDIs"); aiePartitionHdr.aie_pdi.size = static_cast<decltype(aiePartitionHdr.aie_pdi.size)>(ptPDIs.size()); if (aiePartitionHdr.aie_pdi.size == 0) throw std::runtime_error("Error: There are no PDI nodes in the AIE Partition section."); // Examine each of the PDI entries std::vector<aie_pdi> vPDIs; for (const auto& element : ptPDIs) { aie_pdi aiePartitionPDI = { }; process_PDI_uuid(element, aiePartitionPDI); process_PDI_file(element, relativeFromDir, aiePartitionPDI, heap); process_PDI_cdo_groups(element, aiePartitionPDI, heap); // Finished processing the element. Save it away. vPDIs.push_back(aiePartitionPDI); } // Write out the PDI array. Note: The PDI elements are 64-bit aligned. aiePartitionHdr.aie_pdi.offset = static_cast<decltype(aiePartitionHdr.aie_pdi.offset)>(heap.getNextBufferOffset()); for (const auto& element : vPDIs) heap.write(reinterpret_cast<const char*>(&element), sizeof(aie_pdi)); } // ------------------------------------------------------------------------- static void process_partition_info(const boost::property_tree::ptree& ptAIEPartition, aie_partition_info& partitionInfo, SectionHeap& heap) { XUtil::TRACE("Processing partition info"); static const boost::property_tree::ptree ptEmpty; // Get the information regarding the relocatable partitions const auto& ptPartition = ptAIEPartition.get_child("partition", ptEmpty); if (ptPartition.empty()) throw std::runtime_error("Error: The AIE partition is missing the 'partition' node."); partitionInfo = { }; // Parse the column's width partitionInfo.column_width = ptPartition.get<uint16_t>("column_width", 0); if (partitionInfo.column_width == 0) throw std::runtime_error("Error: Missing AIE partition column width"); // Parse the start columns std::vector<uint16_t> startColumns = XUtil::as_vector_simple<uint16_t>(ptPartition, "start_columns"); partitionInfo.start_columns.size = static_cast<decltype(partitionInfo.start_columns.size)>(startColumns.size()); if (partitionInfo.start_columns.size == 0) throw std::runtime_error("Error: Missing start columns for the AIE partition."); // Write out the 16-bit array. partitionInfo.start_columns.offset = static_cast<decltype(partitionInfo.start_columns.offset)>(heap.getNextBufferOffset()); for (const auto element : startColumns) heap.write(reinterpret_cast<const char*>(&element), sizeof(uint16_t), false /*align*/); // Align the heap to the next 64 bit word heap.write(nullptr, 0, true /*align*/); } // ------------------------------------------------------------------------- static void createAIEPartitionImage(const std::string& sectionIndexName, const boost::filesystem::path& relativeFromDir, std::istream& iStream, std::ostringstream& osBuffer) { errno = 0; // Reset any strtoul errors that might have occurred elsewhere // Get the boost property tree iStream.clear(); iStream.seekg(0); boost::property_tree::ptree pt; boost::property_tree::read_json(iStream, pt); XUtil::TRACE_PrintTree("AIE_PARTITION", pt); const boost::property_tree::ptree& ptAIEPartition = pt.get_child("aie_partition"); aie_partition aie_partitionHdr = { }; // Initialized the start of the section heap SectionHeap heap(sizeof(aie_partition)); aie_partitionHdr.mpo_name = static_cast<decltype(aie_partitionHdr.mpo_name)>(heap.getNextBufferOffset()); heap.write(sectionIndexName.c_str(), sectionIndexName.size() + 1 /*Null char*/); // Process the nodes process_partition_info(ptAIEPartition, aie_partitionHdr.info, heap); process_PDIs(ptAIEPartition, relativeFromDir, aie_partitionHdr, heap); // Write out the contents of the section osBuffer.write(reinterpret_cast<const char*>(&aie_partitionHdr), sizeof(aie_partitionHdr)); heap.writeHeapToStream(osBuffer); } // ------------------------------------------------------------------------- void SectionAIEPartition::readSubPayload(const char* pOrigDataSection, unsigned int /*origSectionSize*/, std::istream& iStream, const std::string& sSubSectionName, Section::FormatType eFormatType, std::ostringstream& buffer) const { // Only default (e.g. empty) sub sections are supported if (!sSubSectionName.empty()) { auto errMsg = boost::format("ERROR: Subsection '%s' not support by section '%s") % sSubSectionName % getSectionKindAsString(); throw std::runtime_error(boost::str(errMsg)); } // Some basic DRC checks if (pOrigDataSection != nullptr) { std::string errMsg = "ERROR: AIE Partition section already exists."; throw std::runtime_error(errMsg); } if (eFormatType != Section::FormatType::json) { std::string errMsg = "ERROR: AIE Parition only supports the JSON format."; throw std::runtime_error(errMsg); } // Get the JSON's file parent directory. This is used later to any // relative PDI images that might need need to be read in. boost::filesystem::path p(getPathAndName()); const auto relativeFromDir = p.parent_path(); createAIEPartitionImage(getSectionIndexName(), relativeFromDir, iStream, buffer); } // ------------------------------------------------------------------------- static void populate_partition_info(const char* pBase, const aie_partition_info& aiePartitionInfo, boost::property_tree::ptree& ptAiePartition) { XUtil::TRACE("Populating Partition Info"); boost::property_tree::ptree ptPartitionInfo; // Column Width ptPartitionInfo.put("column_width", (boost::format("%d") % aiePartitionInfo.column_width).str()); // Start Columns boost::property_tree::ptree ptStartColumnArray; const uint16_t* columnArray = reinterpret_cast<const uint16_t*>(pBase + aiePartitionInfo.start_columns.offset); for (uint32_t index = 0; index < aiePartitionInfo.start_columns.size; index++) { boost::property_tree::ptree ptElement; ptElement.put("", (boost::format("%d") % columnArray[index]).str()); ptStartColumnArray.push_back({ "", ptElement }); } ptPartitionInfo.add_child("start_columns", ptStartColumnArray); ptAiePartition.add_child("partition", ptPartitionInfo); } // ------------------------------------------------------------------------- static void populate_pre_cdo_groups(const char* pBase, const cdo_group& aieCDOGroup, boost::property_tree::ptree& ptCDOGroup) { XUtil::TRACE("Populating PRE CDO groups"); // If there is nothing to process, don't create the entry if (aieCDOGroup.pre_cdo_groups.size == 0) return; boost::property_tree::ptree ptPreCDOGroupArray; const uint64_t* aiePreCDOGroupArray = reinterpret_cast<const uint64_t*>(pBase + aieCDOGroup.pre_cdo_groups.offset); for (uint32_t index = 0; index < aieCDOGroup.pre_cdo_groups.size; index++) { const uint64_t& element = aiePreCDOGroupArray[index]; boost::property_tree::ptree ptElement; ptElement.put("", (boost::format("0x%x") % element)); ptPreCDOGroupArray.push_back({ "", ptElement }); } ptCDOGroup.add_child("pre_cdo_groups", ptPreCDOGroupArray); } // ------------------------------------------------------------------------- static void populate_cdo_groups(const char* pBase, const aie_pdi& aiePDI, boost::property_tree::ptree& ptAiePDI) { XUtil::TRACE("Populating CDO groups"); boost::property_tree::ptree ptCDOGroupArray; const cdo_group* aieCDOGroupArray = reinterpret_cast<const cdo_group*>(pBase + aiePDI.cdo_groups.offset); for (uint32_t index = 0; index < aiePDI.cdo_groups.size; index++) { const cdo_group& element = aieCDOGroupArray[index]; boost::property_tree::ptree ptElement; // Name ptElement.put("name", reinterpret_cast<const char*>(pBase + element.mpo_name)); // Type if ((CDO_Type)element.cdo_type != CT_UNKNOWN) ptElement.put("type", getCDOTypeStr((CDO_Type)element.cdo_type)); // PDI ID ptElement.put("pdi_id", (boost::format("0x%x") % element.pdi_id).str()); // Function ID if (element.dpu_kernel_id) ptElement.put("dpu_kernel_id", (boost::format("0x%x") % element.dpu_kernel_id).str()); // Pre cdo groups populate_pre_cdo_groups(pBase, element, ptElement); // Add the cdo group element to the array ptCDOGroupArray.push_back({ "", ptElement }); } ptAiePDI.add_child("cdo_groups", ptCDOGroupArray); } // ------------------------------------------------------------------------- static void write_pdi_image(const char* pBase, const aie_pdi& aiePDI, const std::string& fileName, const boost::filesystem::path& relativeToDir) { boost::filesystem::path filePath = relativeToDir; filePath /= fileName; XUtil::TRACE(boost::format("Creating PDI Image: %s") % filePath.string()); std::fstream oPDIFile; oPDIFile.open(filePath.string(), std::ifstream::out | std::ifstream::binary); if (!oPDIFile.is_open()) { const auto errMsg = boost::format("ERROR: Unable to open the file for writing: %s") % filePath.string(); throw std::runtime_error(errMsg.str()); } oPDIFile.write(reinterpret_cast<const char*>(pBase + aiePDI.pdi_image.offset), aiePDI.pdi_image.size); } // ------------------------------------------------------------------------- static void populate_PDIs(const char* pBase, const boost::filesystem::path& relativeToDir, const aie_partition& aiePartition, boost::property_tree::ptree& ptAiePartition) { XUtil::TRACE("Populating DPI Array"); boost::property_tree::ptree ptPDIArray; const aie_pdi* aiePdiArray = reinterpret_cast<const aie_pdi*>(pBase + aiePartition.aie_pdi.offset); for (uint32_t index = 0; index < aiePartition.aie_pdi.size; index++) { const aie_pdi& element = aiePdiArray[index]; boost::property_tree::ptree ptElement; // UUID ptElement.put("uuid", XUtil::getUUIDAsString(element.uuid)); // Partition Image std::string fileName = XUtil::getUUIDAsString(element.uuid) + ".pdi"; write_pdi_image(pBase, element, fileName, relativeToDir); ptElement.put("file_name", fileName); // CDO Groups populate_cdo_groups(pBase, element, ptElement); // Add the PDI element to the array ptPDIArray.push_back({ "", ptElement }); } ptAiePartition.add_child("PDIs", ptPDIArray); } // ------------------------------------------------------------------------- static void writeAIEPartitionImage(const char* pBuffer, unsigned int bufferSize, const boost::filesystem::path& relativeToDir, std::ostream& oStream) { XUtil::TRACE("AIE_PARTITION : Creating JSON IMAGE"); // Do we have enough room to overlay the header structure if (bufferSize < sizeof(aie_partition)) { auto errMsg = boost::format("ERROR: Segment size (%d) is smaller than the size of the aie_partition structure (%d)") % bufferSize % sizeof(aie_partition); throw std::runtime_error(boost::str(errMsg)); } auto pHdr = reinterpret_cast<const aie_partition*>(pBuffer); // Name boost::property_tree::ptree ptAiePartition; ptAiePartition.put("name", pBuffer + pHdr->mpo_name); // Partition info populate_partition_info(pBuffer, pHdr->info, ptAiePartition); // PDIs populate_PDIs(pBuffer, relativeToDir, *pHdr, ptAiePartition); // Write out the built property tree boost::property_tree::ptree ptRoot; ptRoot.put_child("aie_partition", ptAiePartition); XUtil::TRACE_PrintTree("root", ptRoot); boost::property_tree::write_json(oStream, ptRoot); } // ------------------------------------------------------------------------- void SectionAIEPartition::writeSubPayload(const std::string& sSubSectionName, FormatType eFormatType, std::fstream& oStream) const { // Some basic DRC checks if (m_pBuffer == nullptr) { std::string errMsg = "ERROR: Vendor Metadata section does not exist."; throw std::runtime_error(errMsg); } if (!sSubSectionName.empty()) { auto errMsg = boost::format("ERROR: Subsection '%s' not support by section '%s") % sSubSectionName % getSectionKindAsString(); throw std::runtime_error(boost::str(errMsg)); } // Some basic DRC checks if (eFormatType != Section::FormatType::json) { std::string errMsg = "ERROR: AIE Partition section only supports the JSON format."; throw std::runtime_error(errMsg); } boost::filesystem::path p(getPathAndName()); const auto relativeToDir = p.parent_path(); writeAIEPartitionImage(m_pBuffer, m_bufferSize, relativeToDir, oStream); } // ------------------------------------------------------------------------- void SectionAIEPartition::readXclBinBinary(std::istream& iStream, const axlf_section_header& sectionHeader) { Section::readXclBinBinary(iStream, sectionHeader); XUtil::TRACE("Determining AIE_PARTITION Section Name"); // Do we have enough room to overlay the header structure if (m_bufferSize < sizeof(aie_partition)) { auto errMsg = boost::format("ERROR: Segment size (%d) is smaller than the size of the aie_partition structure (%d)") % m_bufferSize % sizeof(aie_partition); throw std::runtime_error(boost::str(errMsg)); } auto pHdr = reinterpret_cast<const aie_partition*>(m_pBuffer); // Name std::string name = m_pBuffer + pHdr->mpo_name; XUtil::TRACE(std::string("Successfully read in the AIE_PARTITION section: '") + name + "' "); Section::m_sIndexName = name; } // -------------------------------------------------------------------------
24,644
7,978
/****************************************************************************** * Copyright (c) 2020, Intel Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception. * *****************************************************************************/ #include "systemc.h" #include <sct_assert.h> using namespace sc_core; // Read not initialized variables/arrays in reset -- error/warning reported class A : public sc_module { public: sc_in<bool> clk{"clk"}; sc_signal<bool> nrst{"nrst"}; int* p; int m; int* q = &m; int n; int& r = n; int mm; SC_CTOR(A) { p = sc_new<int>(); SC_CTHREAD(readProc1, clk.pos()); async_reset_signal_is(nrst, false); SC_CTHREAD(readProc2, clk.pos()); async_reset_signal_is(nrst, false); } sc_signal<int> s{"s"}; void f1(int par_a[3]) { auto ii = par_a[1]; } void f2(int (&par_a)[3], int i) { auto ii = par_a[i]; } void f3(int par_a[3][3], int i) { auto ii = par_a[i+1][i+2]; } sc_signal<int> s0; void readProc1() { int aa[3]; int bb[3] = {0,1,2}; int cc[3][3]; int dd[3]; f1(aa); // Warning f2(bb, 1); f3(cc, 0); // Warning int i = dd[1]; // Warning int j; int& r = j; i = r; // Warning int l; i = l + 1; // Warning s0 = i; wait(); while(1) { wait(); } } sc_signal<int> s1; void readProc2() { int i; i = *p; // Error i = mm; // Error int j = *q; // Error j = r; // Error s1 = i + j; wait(); while(1) { wait(); } } }; int sc_main(int argc, char* argv[]) { sc_clock clk("clk", 1, SC_NS); A a_mod{"a_mod"}; a_mod.clk(clk); sc_start(); return 0; }
2,144
768
#include <iostream> #include <algorithm> #include <vector> using namespace std; class Segment { public: int len; vector<long long> tree; Segment(int n) : len(n) { tree.resize(2*n); } void make() { for (int i=len-1; i>0; i--) tree[i] = (tree[i*2] + tree[i*2+1]); } void update(int i, int val) { i += len; tree[i] = val; for (i/=2; i>0; i/=2) tree[i] = (tree[2*i] + tree[2*i+1]); } long long query(int l, int r) { l += len; r += len; long long ret = 0; while (l <= r) { if (l % 2 == 1) ret += tree[l++]; if (r % 2 == 0) ret += tree[r--]; l /= 2; r /= 2; } return ret; } }; int main() { ios_base::sync_with_stdio(0); cout.tie(0); cin.tie(0); vector<pair<int, int>> vec; int n, t; cin >> n; for (int i=0; i<n; ++i) { cin >> t; vec.push_back({t, i}); } sort(vec.rbegin(), vec.rend()); int ans = 0; Segment seg = Segment(n); for (int i=0; i<n; ++i) { int x = vec[i].second; int l = seg.query(0, x); int r = seg.query(x, n); if (l*2 < r || r*2 < l) ans++; seg.update(x, 1); } cout << ans << '\n'; return 0; }
1,104
597
#include <string> #include <memory> #include <utility> #include <vector> #include "include/micro_hal_control_plugin.h" using namespace std::chrono_literals; namespace micro_hal_control { MicroHalControlPlugin::MicroHalControlPlugin() { printf("Hello World!\n"); }; MicroHalControlPlugin::~MicroHalControlPlugin() = default; // Overloaded Gazebo entry point void MicroHalControlPlugin::Load(gazebo::physics::ModelPtr parent, sdf::ElementPtr sdf) { } // Register this plugin with the simulator GZ_REGISTER_MODEL_PLUGIN(MicroHalControlPlugin) } // namespace micro_hal_control
621
203
#include "beastquest/auth.hh" #include <boost/beast.hpp> #include <string> namespace detail = boost::beast::detail; namespace quest { BasicAuth::BasicAuth(std::string username, std::string password) : username_{std::move(username)}, password_{std::move(password)}, auth_string_("Basic " + detail::base64_encode(username_ + ":" + password_)) {} std::string BasicAuth::GetAuthString() const noexcept { return auth_string_; } bool BasicAuth::IsEmpty() const noexcept { return auth_string_.empty(); } } // namespace quest
559
166
#ifndef _OPENCV_DMP_HPP_ #define _OPENCV_DMP_HPP_ #include <vector> #include <opencv2/core/core.hpp> #include <boost/filesystem.hpp> #include <limits> #include <map> #include <set> #include <list> #include <vector> #include <stdexcept> #include <opencv2/imgproc/imgproc.hpp> //for DEBUG //#include <opencv2/highgui/highgui.hpp> /// /// Generate a opening DMP profile /// \param inputImage The image that will be filtered for light objects /// \param ses The set of strictly increasing geodesic structuring elements /// template <typename OperatingPixelType> std::vector<cv::Mat> opencvOpenDmp(const cv::Mat& inputImage, const std::vector<int>& ses); /// /// Dilation by Reconstruction using the Downhill Filter algorithm (Robinson,Whelan) /// /// \param mask The image/surface that bounds the reconstruction of the marker /// \param mark The image/surface that initializes the reconstruction /// \returns The dilation reconstruction template <typename OperatingPixelType> cv::Mat dilationByReconstructionDownhill(const cv::Mat& mask, const cv::Mat& mark); /// /// Generate a closing DMP profile /// \param inputImage The image that will be filtered for dark objects /// \param ses The set of strictly increasing geodesic structuring elements /// template <typename OperatingPixelType> std::vector<cv::Mat> opencvCloseDmp(const cv::Mat& inputImage, const std::vector<int>& ses); /// /// Erosion by Reconstruction using an Uphill Filter algorithm (insp. by Robinson,Whelan) /// /// \param mask The image/surface that bounds the reconstruction of the marker /// \param mark The image/surface that initializes the reconstruction /// \returns The erosion reconstruction template <typename OperatingPixelType> cv::Mat erosionByReconstructionUphill(const cv::Mat& mask, const cv::Mat& mark); /// Dump the pyramid levels /// \param dmp the pyramid cells to dump /// \param sideTag the Open or Close identifier for the levels /// \param outputPath the output directory /// \param filePath the filename being processed void dumpDmpLevels(const std::vector<cv::Mat>& dmp, const std::vector<int>& ses, const std::string& sideTag, const boost::filesystem::path& outputPath, const boost::filesystem::path& filePath); // ============================ // ============================ // == BEGIN Template Functions // ============================ // ============================ template <typename OperatingPixelType> std::vector<cv::Mat> opencvOpenDmp(const cv::Mat& inputImage, const std::vector<int>& ses) { //cgi::log::MetaLogStream& log(cgi::log::MetaLogStream::instance()); // ++ Open, then dilate by reconstruction //if (false == std::numeric_limits<T>::is_integer) // CGI_THROW(std::logic_error,"Invalid template type"); // Build Structuring Elements std::vector<cv::Mat> structuringElements; for (std::vector<int>::const_iterator level = ses.begin();level!=ses.end();++level) { const int lev = *level; // Circular structuring element const int edgeSize = lev+1+lev; // turn radius into edge size structuringElements.push_back( cv::getStructuringElement(cv::MORPH_ELLIPSE,cv::Size(edgeSize,edgeSize)) ); } // Build Morphological Operation Stack (open) std::vector<cv::Mat> mos; for (unsigned int level = 0;level<structuringElements.size();++level) { cv::Mat filteredImage(inputImage.size().height, inputImage.size().width, cv::DataType<OperatingPixelType>::type); cv::morphologyEx(inputImage, filteredImage, cv::MORPH_OPEN, structuringElements.at(level)); mos.push_back(filteredImage); } const int n_lvls = mos.size(); // log << cgi::log::Priority::INFO << "opencvOpenDmp" << "MOS Produced, size:" << n_lvls << cgi::log::flush; // Set the Tile band count to the SEs array size std::vector<cv::Mat> profile; profile.reserve(n_lvls); // //////////////////////////////////////////////////////////////////////// // USE: dilationByReconstructionDownhill(const cv::Mat& mask,const cv::Mat& mark) cv::Mat tempRec; // Temporary Open Record cv::Mat lastRec; // previous level Open Record // Open = (erode,dilate) //typename MorphologyOperator<DataType>::type morphology(_ses[0]); //typename ReconstructionOperator<DataType>::type reconstructor; //dilationByReconstructionDownhill( inputImage, mos.at(0) ).copyTo(tempRec); tempRec = dilationByReconstructionDownhill<OperatingPixelType>( inputImage, mos.at(0) ).clone(); // get the absolute difference of the two images cv::Mat diffImage(inputImage.size().height, inputImage.size().width, cv::DataType<OperatingPixelType>::type); absdiff(inputImage, tempRec, diffImage); profile.push_back(diffImage.clone()); tempRec.copyTo(lastRec); // Subsequent Levels for (int i = 1;i < n_lvls;++i) { // reconstruction(mask , mark) //dilationByReconstructionDownhill( inputImage, mos.at(i) ).copyTo(tempRec); tempRec = dilationByReconstructionDownhill<OperatingPixelType>( inputImage, mos.at(i) ).clone(); // BEGIN DEBUG /* std::stringstream ss; ss << "reconstruction_from_opening_" << i << ".png"; if(!cv::imwrite(ss.str(), tempRec)) { throw std::runtime_error("Failed to write"); } */ // END DEBUG // get the absolute difference of the two images absdiff(lastRec, tempRec, diffImage); profile.push_back(diffImage.clone()); tempRec.copyTo(lastRec); } return profile; } template <typename OperatingPixelType> cv::Mat dilationByReconstructionDownhill(const cv::Mat& mask, const cv::Mat& mark) { //typedef unsigned short OperatingPixelType; //cgi::log::MetaLogStream& log(cgi::log::MetaLogStream::instance()); if (false == std::numeric_limits<OperatingPixelType>::is_integer) //CGI_THROW(std::logic_error,"Invalid template / operating-pixel type"); throw new std::logic_error("Invalid template / operating-pixel type"); const cv::Size size = mask.size(); //if (size.width != mark.size().width || size.height != mark.size().height) if (size != mark.size()) { //log << cgi::log::Priority::ERROR << "dilationByReconstructionUphill" //<< "Size mismatch: (" //<< size.width << "," << size.height << ") != (" //<< mark.size().width << "," << mark.size().height << ")" << cgi::log::flush; } // -------------------------------- // Place each p : I(p) > 0 into List[I(p)] // -------------------------------- // Copy the marker into the reconstruction // we can then grow it in place // value i has a list of pixels at position (y,x) cv::Mat reconstruction(mark.size().height, mark.size().width, cv::DataType<OperatingPixelType>::type); mark.copyTo(reconstruction); // for template, use typename // typedef typename std::list<std::pair<int,int> > LocationListType; // typedef typename std::map< OperatingPixelType, LocationListType > MapOfLocationListType; typedef typename std::list<std::pair<int,int> > LocationListType; typedef typename std::map< OperatingPixelType, LocationListType > MapOfLocationListType; // This is essentially an indexed image version of the input `mark' raster MapOfLocationListType valueLocationListMap; // Build an in-memory indexed image // but while we are at it, verify that it is properly bounded by `mask' raster for (int i = 0; i < size.height; ++i) for (int j = 0; j < size.width; ++j) { const OperatingPixelType pixelValue = reconstruction.at<OperatingPixelType>(i, j); if (pixelValue > mask.at<OperatingPixelType>(i, j)) { //std::cout << "Storing ("<< i << "," << j <<") into valueLocationListMap["<< static_cast<int>(pixelValue) << "]" << std::endl; std::stringstream msg; msg << "(pixelValue > mask[0](i, j)), for raster location = ("<<i<<","<<j<<")"; //CGI_THROW (std::logic_error, msg.str()); // the marker must always be LTE the mask, by definition throw new std::logic_error( msg.str()); } valueLocationListMap[pixelValue].push_back( std::make_pair<int,int>(i,j) ); } // No valid pixels or values above floor? Return the input as output if (valueLocationListMap.size() == 0) return reconstruction; // -------------------------------- // The farthest downhill we will go // is to the current min(mark[0]) // therefore, we do not need to // process the current min, we // already copied them to output const OperatingPixelType minValue = valueLocationListMap.begin()->first; valueLocationListMap[minValue].clear(); std::set<std::pair<int,int> > finalizedPixels; // -------------------------------- // Do a backward iteration (downhill) // through the // valueLocationListMap[values] // -------------------------------- // use typename for template version //for (typename MapOfLocationListType::reverse_iterator valueList = valueLocationListMap.rbegin(); // valueList != valueLocationListMap.rend(); ++valueList) for (typename MapOfLocationListType::reverse_iterator valueList = valueLocationListMap.rbegin(); valueList != valueLocationListMap.rend(); ++valueList) { // The gray value const OperatingPixelType currentValue = valueList->first; // The list of (y,x) tuples LocationListType locations = valueList->second; // for each location indexed in the value list while (!locations.empty()) { // Debug thing // if (locations.size() > (size.width * size.height)) // { // CGI_THROW(std::logic_error, "GrayscaleDilationByReconstructionDownhill has gone out of control, this should never happen!"); // } // pull/pop the first position from the list, mark it as finalized std::pair<int,int> frontPosition = locations.front(); finalizedPixels.insert(frontPosition); locations.pop_front(); const int y = frontPosition.first; const int x = frontPosition.second; const int pre_x = x - 1; const int post_x = x + 1; const int pre_y = y - 1; const int post_y = y + 1; // For each neighbor // - a - // b p d // - c - // a = (pre_y,x), b = (y,pre_x), c = (post_y,x), d = (y,post_x) // Neighbor Pixel 'a' const std::pair<int,int> a = std::make_pair<int,int>(pre_y,x); const OperatingPixelType mask_a = mask.at<OperatingPixelType>(pre_y,x); // if neighbor index is within bounds and not finalized if ((finalizedPixels.find(a) == finalizedPixels.end()) && (pre_y >= 0) && (mask_a > 0)) { OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(pre_y,x); OperatingPixelType constraintValue = std::min<OperatingPixelType>(currentValue,mask_a); // std::cout << "Neighbor(a) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl; if (neighborValue < constraintValue) { reconstruction.at<OperatingPixelType>(pre_y,x) = constraintValue; if ( constraintValue == currentValue ) { // std::cout << "Adding ("<< pre_y << "," << x <<") to current list" << std::endl; locations.push_back( a ); } else { // std::cout << "Moving ("<< pre_y << "," << x <<") from " // << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl; valueLocationListMap[neighborValue].remove( a ); valueLocationListMap[constraintValue].push_back( a ); } } } // Neighbor Pixel 'b' const std::pair<int,int> b = std::make_pair<int,int>(y,pre_x); const OperatingPixelType mask_b = mask.at<OperatingPixelType>(y,pre_x); if ((finalizedPixels.find(b) == finalizedPixels.end()) && (pre_x >= 0) && (mask_b > 0)) { OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(y,pre_x); OperatingPixelType constraintValue = std::min<OperatingPixelType>(currentValue,mask_b); // std::cout << "Neighbor(b) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl; if (neighborValue < constraintValue) { reconstruction.at<OperatingPixelType>(y,pre_x) = constraintValue; if ( constraintValue == currentValue ) { // std::cout << "Adding ("<< y << "," << pre_x <<") to current list" << std::endl; locations.push_back( b ); } else { // std::cout << "Moving ("<< y << "," << pre_x <<") from " // << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl; valueLocationListMap[neighborValue].remove( b ); valueLocationListMap[constraintValue].push_back( b ); } } } // Neighbor Pixel 'c' const std::pair<int,int> c = std::make_pair<int,int>(post_y,x); const OperatingPixelType mask_c = mask.at<OperatingPixelType>(post_y,x); if ((finalizedPixels.find(c) == finalizedPixels.end()) && (post_y < size.height) && (mask_c > 0)) { OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(post_y,x); OperatingPixelType constraintValue = std::min<OperatingPixelType>(currentValue,mask_c); // std::cout << "Neighbor(c) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl; if (neighborValue < constraintValue) { reconstruction.at<OperatingPixelType>(post_y,x) = constraintValue; if ( constraintValue == currentValue ) { // std::cout << "Adding ("<< post_y << "," << x <<") to current list" << std::endl; locations.push_back( c ); } else { // std::cout << "Moving ("<< post_y << "," << x <<") from " // << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl; valueLocationListMap[neighborValue].remove( c ); valueLocationListMap[constraintValue].push_back( c ); } } } // Neighbor Pixel 'd' const std::pair<int,int> d = std::make_pair<int,int>(y,post_x); const OperatingPixelType mask_d = mask.at<OperatingPixelType>(y,post_x); if ((finalizedPixels.find(d) == finalizedPixels.end()) && (post_x < size.width) && (mask_d > 0)) { OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(y,post_x); OperatingPixelType constraintValue = std::min<OperatingPixelType>(currentValue,mask_d); // std::cout << "Neighbor(d) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl; if (neighborValue < constraintValue) { reconstruction.at<OperatingPixelType>(y,post_x) = constraintValue; if ( constraintValue == currentValue ) { // std::cout << "Adding ("<< y << "," << post_x <<") to current list" << std::endl; locations.push_back( d ); } else { // std::cout << "Moving ("<< y << "," << post_x <<") from " // << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl; valueLocationListMap[neighborValue].remove( d ); valueLocationListMap[constraintValue].push_back( d ); } } } } // end, a value's position list is emptied. } // end for each value in the marker return reconstruction; }; template <typename OperatingPixelType> std::vector<cv::Mat> opencvCloseDmp(const cv::Mat& inputImage, const std::vector<int>& ses) { //cgi::log::MetaLogStream& log(cgi::log::MetaLogStream::instance()); // ++ Close, then erode by reconstruction //if (false == std::numeric_limits<T>::is_integer) // CGI_THROW(std::logic_error,"Invalid template type"); // Build Structuring Elements std::vector<cv::Mat> structuringElements; for (std::vector<int>::const_iterator level = ses.begin();level!=ses.end();++level) { const int lev = *level; // Circular structuring element const int edgeSize = lev+1+lev; // turn radius into edge size structuringElements.push_back( cv::getStructuringElement(cv::MORPH_ELLIPSE,cv::Size(edgeSize,edgeSize)) ); } // Build Morphological Operation Stack (close) std::vector<cv::Mat> mos; for (unsigned int level = 0;level<structuringElements.size();++level) { cv::Mat filteredImage(inputImage.size().height, inputImage.size().width, cv::DataType<OperatingPixelType>::type); cv::morphologyEx(inputImage, filteredImage, cv::MORPH_CLOSE, structuringElements.at(level)); mos.push_back(filteredImage); } const int n_lvls = mos.size(); // log << cgi::log::Priority::INFO << "opencvCloseDmp" << "MOS Produced, size:" << n_lvls << cgi::log::flush; // Set the Tile band count to the SEs array size std::vector<cv::Mat> profile; profile.reserve(n_lvls); // //////////////////////////////////////////////////////////////////////// // USE: erosionByReconstructionUphill(const cv::Mat& mask,const cv::Mat& mark) cv::Mat tempRec; // Temporary Close Record cv::Mat lastRec; // previous level Close Record // Close = (dilate,erode) //typename MorphologyOperator<DataType>::type morphology(_ses[0]); //typename ReconstructionOperator<DataType>::type reconstructor; //erosionByReconstructionUphill<OperatingPixelType>( inputImage, mos.at(0) ).copyTo(tempRec); tempRec = erosionByReconstructionUphill<OperatingPixelType>( inputImage, mos.at(0) ).clone(); // get the absolute difference of the two images cv::Mat diffImage(inputImage.size().height, inputImage.size().width, cv::DataType<OperatingPixelType>::type); absdiff(inputImage, tempRec, diffImage); profile.push_back(diffImage.clone()); tempRec.copyTo(lastRec); // Subsequent Levels for (int i = 1;i < n_lvls;++i) { // reconstruction(mask , mark) // NOTE: Potentially bad line //erosionByReconstructionUphill<OperatingPixelType>( inputImage, mos.at(i) ).copyTo(tempRec); tempRec = erosionByReconstructionUphill<OperatingPixelType>( inputImage, mos.at(i) ).clone(); // BEGIN DEBUG /* std::stringstream ss; ss << "reconstruction_from_closing_" << i << ".png"; if(!cv::imwrite(ss.str(), tempRec)) { throw std::runtime_error("Failed to write"); } */ // END DEBUG // get the absolute difference of the two images absdiff(lastRec, tempRec, diffImage); profile.push_back(diffImage.clone()); tempRec.copyTo(lastRec); } return profile; }; template <typename OperatingPixelType> cv::Mat erosionByReconstructionUphill(const cv::Mat& mask, const cv::Mat& mark) { // cgi::log::MetaLogStream& log(cgi::log::MetaLogStream::instance()); if (false == std::numeric_limits<OperatingPixelType>::is_integer) //CGI_THROW(std::logic_error,"Invalid template / operating-pixel type"); throw new std::logic_error("Invalid template / operating-pixel type"); const cv::Size size = mask.size(); //if (size.width != mark.size().width || size.height != mark.size().height) if (size != mark.size()) { //log << cgi::log::Priority::ERROR << "erosionByReconstructionDownhill" //<< "Size mismatch: (" //<< size.width << "," << size.height << ") != (" //<< mark.size().width << "," << mark.size().height << ")" << cgi::log::flush; } // -------------------------------- // Place each p : I(p) > 0 into List[I(p)] // -------------------------------- // Copy the marker into the reconstruction // we can then grow it in place // value i has a list of pixels at position (y,x) cv::Mat reconstruction(mark.size().height, mark.size().width, cv::DataType<OperatingPixelType>::type); mark.copyTo(reconstruction); // for template, use typename // typedef typename std::list<std::pair<int,int> > LocationListType; // typedef typename std::map< OperatingPixelType, LocationListType > MapOfLocationListType; typedef std::list<std::pair<int,int> > LocationListType; typedef std::map< OperatingPixelType, LocationListType > MapOfLocationListType; // This is essentially an indexed image version of the input `mark' raster MapOfLocationListType valueLocationListMap; // Build an in-memory indexed image // but while we are at it, verify that it is properly bounded by `mask' raster for (int i = 0; i < size.height; ++i) for (int j = 0; j < size.width; ++j) { const OperatingPixelType pixelValue = reconstruction.at<OperatingPixelType>(i, j); if (pixelValue < mask.at<OperatingPixelType>(i, j)) { //std::cout << "Storing ("<< i << "," << j <<") into valueLocationListMap["<< static_cast<int>(pixelValue) << "]" << std::endl; std::stringstream msg; msg << "(pixelValue < mask[0](i, j)), for raster location = ("<<i<<","<<j<<")"; //CGI_THROW (std::logic_error, msg.str()); // the marker must always be GTE the mask, by definition throw new std::logic_error(msg.str()); } valueLocationListMap[pixelValue].push_back( std::make_pair<int,int>(i,j) ); } // No valid pixels or values below floor? Return the input as output if (valueLocationListMap.size() == 0) return reconstruction; // -------------------------------- // The farthest uphill we will go // is to the current max(mark[0]) // therefore, we do not need to // process the current max, we // already copied them to output const OperatingPixelType maxValue = valueLocationListMap.rbegin()->first; valueLocationListMap[maxValue].clear(); std::set<std::pair<int,int> > finalizedPixels; // -------------------------------- // Do a forward iteration (uphill) // through the // valueLocationListMap[values] // -------------------------------- // use typename for template version //for (typename MapOfLocationListType::iterator valueList = valueLocationListMap.begin(); // valueList != valueLocationListMap.end(); ++valueList) for (typename MapOfLocationListType::iterator valueList = valueLocationListMap.begin(); valueList != valueLocationListMap.end(); ++valueList) { // The gray value const OperatingPixelType currentValue = valueList->first; // The list of (y,x) tuples LocationListType locations = valueList->second; // for each location indexed in the value list while (!locations.empty()) { // Debug thing // if (locations.size() > (size.width * size.height)) // { // CGI_THROW(std::logic_error, "GrayscaleDilationByReconstructionDownhill has gone out of control, this should never happen!"); // } // pull/pop the first position from the list, mark it as finalized std::pair<int,int> frontPosition = locations.front(); finalizedPixels.insert(frontPosition); locations.pop_front(); const int y = frontPosition.first; const int x = frontPosition.second; const int pre_x = x - 1; const int post_x = x + 1; const int pre_y = y - 1; const int post_y = y + 1; // For each neighbor // - a - // b p d // - c - // a = (pre_y,x), b = (y,pre_x), c = (post_y,x), d = (y,post_x) // Neighbor Pixel 'a' const std::pair<int,int> a = std::make_pair<int,int>(pre_y,x); const OperatingPixelType mask_a = mask.at<OperatingPixelType>(pre_y,x); // if neighbor index is within bounds and not finalized if ((finalizedPixels.find(a) == finalizedPixels.end()) && (pre_y >= 0) && (mask_a > 0)) { OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(pre_y,x); OperatingPixelType constraintValue = std::max<OperatingPixelType>(currentValue,mask_a); // std::cout << "Neighbor(a) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl; if (neighborValue > constraintValue) { reconstruction.at<OperatingPixelType>(pre_y,x) = constraintValue; if ( constraintValue == currentValue ) { // std::cout << "Adding ("<< pre_y << "," << x <<") to current list" << std::endl; locations.push_back( a ); } else { // std::cout << "Moving ("<< pre_y << "," << x <<") from " // << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl; valueLocationListMap[neighborValue].remove( a ); valueLocationListMap[constraintValue].push_back( a ); } } } // Neighbor Pixel 'b' const std::pair<int,int> b = std::make_pair<int,int>(y,pre_x); const OperatingPixelType mask_b = mask.at<OperatingPixelType>(y,pre_x); if ((finalizedPixels.find(b) == finalizedPixels.end()) && (pre_x >= 0) && (mask_b > 0)) { OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(y,pre_x); OperatingPixelType constraintValue = std::max<OperatingPixelType>(currentValue,mask_b); // std::cout << "Neighbor(b) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl; if (neighborValue > constraintValue) { reconstruction.at<OperatingPixelType>(y,pre_x) = constraintValue; if ( constraintValue == currentValue ) { // std::cout << "Adding ("<< y << "," << pre_x <<") to current list" << std::endl; locations.push_back( b ); } else { // std::cout << "Moving ("<< y << "," << pre_x <<") from " // << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl; valueLocationListMap[neighborValue].remove( b ); valueLocationListMap[constraintValue].push_back( b ); } } } // Neighbor Pixel 'c' const std::pair<int,int> c = std::make_pair<int,int>(post_y,x); const OperatingPixelType mask_c = mask.at<OperatingPixelType>(post_y,x); if ((finalizedPixels.find(c) == finalizedPixels.end()) && (post_y < size.height) && (mask_c > 0)) { OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(post_y,x); OperatingPixelType constraintValue = std::max<OperatingPixelType>(currentValue,mask_c); // std::cout << "Neighbor(c) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl; if (neighborValue > constraintValue) { reconstruction.at<OperatingPixelType>(post_y,x) = constraintValue; if ( constraintValue == currentValue ) { // std::cout << "Adding ("<< post_y << "," << x <<") to current list" << std::endl; locations.push_back( c ); } else { // std::cout << "Moving ("<< post_y << "," << x <<") from " // << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl; valueLocationListMap[neighborValue].remove( c ); valueLocationListMap[constraintValue].push_back( c ); } } } // Neighbor Pixel 'd' const std::pair<int,int> d = std::make_pair<int,int>(y,post_x); const OperatingPixelType mask_d = mask.at<OperatingPixelType>(y,post_x); if ((finalizedPixels.find(d) == finalizedPixels.end()) && (post_x < size.width) && (mask_d > 0)) { OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(y,post_x); OperatingPixelType constraintValue = std::max<OperatingPixelType>(currentValue,mask_d); // std::cout << "Neighbor(d) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl; if (neighborValue > constraintValue) { reconstruction.at<OperatingPixelType>(y,post_x) = constraintValue; if ( constraintValue == currentValue ) { // std::cout << "Adding ("<< y << "," << post_x <<") to current list" << std::endl; locations.push_back( d ); } else { // std::cout << "Moving ("<< y << "," << post_x <<") from " // << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl; valueLocationListMap[neighborValue].remove( d ); valueLocationListMap[constraintValue].push_back( d ); } } } } // end, a value's position list is emptied. } // end for each value in the marker return reconstruction; }; #endif //_OPENCV_DMP_HPP_
27,492
10,087
/* * \file CPointerToImplementation.cpp * \author https://github.com/infojg9 * \brief An example of the PIMPL Design / Pointer to Implementation. * \copyright MIT/BSD Redistributable License */ #include "CPointerToImplementation.h" #include <iostream> #ifdef _WIN32 #include <windows.h> #else #include <sys/time.h> #endif namespace Pimple { namespace V1 { /// \class Private Impl class decoupled implementation, kind of Bridge pattern class CPointerToImplementation::Impl { public: Impl() = default; virtual ~Impl(); Impl(Impl const&) = default; Impl& operator=(Impl const&) = default; Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; double GetElapsed() const; std::string mName; #ifdef _WIN32 DWORD mStartTime; #else struct timeval mStartTime; #endif }; CPointerToImplementation::CPointerToImplementation(std::string const& name) : m_pImpl(std::make_unique<CPointerToImplementation::Impl>()) { m_pImpl->mName = name; #ifdef _WIN32 m_pImpl->mStartTime = GetTickCount(); #else gettimeofday(&m_pImpl->mStartTime, nullptr); #endif } CPointerToImplementation::~CPointerToImplementation() { std::cout << m_pImpl->mName << ": consumed : " << m_pImpl->GetElapsed() << " secs" << std::endl; m_pImpl.reset(); m_pImpl = nullptr; } CPointerToImplementation::ImplPtr&& CPointerToImplementation::getImplPtr() { return std::move(m_pImpl); } /// Allow explicit deep copy in copy constructor from rImpl object reference CPointerToImplementation::CPointerToImplementation( CPointerToImplementation const& rImpl) : m_pImpl(std::make_unique<Impl>(*rImpl.m_pImpl)) {} /// Allow explicit deep copy in copy assignment operator from rImpl object reference CPointerToImplementation& CPointerToImplementation::operator=(CPointerToImplementation const& rImpl) { *m_pImpl = *rImpl.m_pImpl; return *this; } double CPointerToImplementation::Impl::GetElapsed() const { #ifdef _WIN32 return (GetTickCount() - mStartTime) / 1e3; #else struct timeval end_time; gettimeofday(&end_time, nullptr); double t1 = mStartTime.tv_usec / 1e6 + mStartTime.tv_sec; double t2 = end_time.tv_usec / 1e6 + end_time.tv_sec; return t2 - t1; #endif } CPointerToImplementation::Impl::~Impl() { } } /// namespace V1 } /// namespace Pimple
2,291
826
#ifndef __HTTP_SESSION_H__ #define __HTTP_SESSION_H__ #include <memory> #include <iostream> #include <boost/beast/core.hpp> #include <boost/beast/http.hpp> #include <boost/beast/version.hpp> #include <boost/asio/bind_executor.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/strand.hpp> #include <boost/property_tree/json_parser.hpp> #include "utils.hpp" using tcp = boost::asio::ip::tcp; namespace http = boost::beast::http; namespace ptree = boost::property_tree; template<class Body, class Allocator, class Send> using RequestHandlerType = void (*) (http::request<Body, http::basic_fields<Allocator>>&& req, Send&& send); // Handles an HTTP server connection template <template<typename, typename> class RequestHandler> class Session : public std::enable_shared_from_this<Session<RequestHandler>> { struct SendLambda { Session& session_; explicit SendLambda(Session& self) : session_(self) { /* */ } template<bool isRequest, class MsgBody, class Fields> void operator()(http::message<isRequest, MsgBody, Fields>&& msg) const { // The lifetime of the message has to extend // for the duration of the async operation so // we use a shared_ptr to manage it. auto msgSp = std::make_shared<http::message<isRequest, MsgBody, Fields>>(std::move(msg)); // Store a type-erased version of the shared // pointer in the class to keep it alive. session_.res_ = msgSp; // Write the response http::async_write( session_.socket_, *msgSp, boost::asio::bind_executor( session_.strand_, std::bind( &Session::on_write, this->session_.shared_from_this(), std::placeholders::_1, std::placeholders::_2, msgSp->need_eof()))); } }; tcp::socket socket_; boost::asio::strand<boost::asio::io_context::executor_type> strand_; boost::beast::flat_buffer buffer_; http::request<http::string_body> req_; std::shared_ptr<void> res_; SendLambda sendLambda_; public: // Take ownership of the socket explicit Session(tcp::socket socket) : socket_(std::move(socket)), strand_(socket_.get_executor()), sendLambda_(*this) { } void run() { do_read(); } void do_read() { req_ = {}; // Clean the request // And then read it http::async_read(socket_, buffer_, req_, boost::asio::bind_executor( strand_, std::bind( &Session::on_read, this->shared_from_this(), std::placeholders::_1, std::placeholders::_2 ) ) ); } void do_close() { boost::system::error_code ec; socket_.shutdown(tcp::socket::shutdown_send, ec); } void on_read(boost::system::error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); // This means they closed the connection if(ec == http::error::end_of_stream) return do_close(); if(ec) return fail(ec, "couldn't read"); // Send the response RequestHandler<http::string_body, SendLambda>()(std::move(req_), sendLambda_); } void on_write(boost::system::error_code ec, std::size_t bytes_transferred, bool close) { boost::ignore_unused(bytes_transferred); if(ec) return fail(ec, "write"); if(close) { // This means we should close the connection, usually because // the response indicated the "Connection: close" semantic. return do_close(); } // We're done with the response so delete it res_ = nullptr; // Read another request do_read(); } }; #endif
3,694
1,184
#include "TCPManager.h" TCPManager* TCPManager::instance = nullptr; TCPManager::TCPManager() { } TCPManager::~TCPManager() { for (std::string id : online_subscribers) close(subscribers_by_id[id]); close(listen_fd); } TCPManager* TCPManager::get_instance() { if (!instance) instance = new TCPManager(); return instance; } bool TCPManager::init(int port) { listen_fd = socket(AF_INET, SOCK_STREAM, 0); if (listen_fd < 0) return false; int flag = 1; // Disable Neagle. if (setsockopt(listen_fd, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof(int)) < 0) return -1; struct sockaddr_in serv_addr; serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(port); serv_addr.sin_addr.s_addr = INADDR_ANY; if (bind(listen_fd, (sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) return false; if (listen(listen_fd, MAX_CLIENTS) < 0) return false; return true; } int TCPManager::get_listen_fd() { return listen_fd; } void TCPManager::close_subscriber(std::string id) { printf("Client %s disconnected.\n", id.c_str()); close(subscribers_by_id[id]); online_subscribers.erase(id); subscribers_by_fd.erase(subscribers_by_id[id]); subscribers_by_id.erase(id); } void TCPManager::close_fd(int fd) { close(fd); if (subscribers_by_fd.find(fd) != subscribers_by_fd.end()) { printf("Client %s disconnected.\n", subscribers_by_fd[fd].c_str()); online_subscribers.erase(subscribers_by_fd[fd]); subscribers_by_id.erase(subscribers_by_fd[fd]); subscribers_by_fd.erase(fd); } } int TCPManager::manage_new_connection() { int new_sock_fd; socklen_t sock_len = sizeof(sockaddr_in); sockaddr_in client_addr; new_sock_fd = accept(listen_fd, (sockaddr*)&client_addr, &sock_len); subscriber_fd_info[new_sock_fd] = client_addr; return new_sock_fd; } bool TCPManager::receive_client_commands(int fd) { auto node = last_unfinished.find(fd); client_command last_command; int last_command_len; // Check for a previous unfinished command. if (node == last_unfinished.end()) { memset((char*)&last_command, 0, sizeof(last_command)); last_command_len = 0; } else { last_command = last_unfinished[fd].first; last_command_len = last_unfinished[fd].second; last_unfinished.erase(fd); } int n; unsigned char buf[1500]; memset(buf, 0, 1500); // Receive some data. if ((n = recv(fd, buf, 1500, 0)) < 0) { perror("An error occurred while receiving a command from client"); close_fd(fd); return false; } // Client closed connection. if (n == 0) { close_fd(fd); return false; } int offset = 0; // Add to the unfinished command as much as possible. if (n < (int)sizeof(client_command) - last_command_len) { memcpy(((char*)&last_command) + last_command_len, buf, n); last_unfinished[fd] = std::pair<client_command, int>(last_command, last_command_len+n); return true; } // Finish last command and process it. memcpy(((char*)&last_command) + last_command_len, buf, sizeof(client_command)-last_command_len); if (!manage_command(last_command, fd)) return false; offset = sizeof(client_command)-last_command_len; // Read full commands and process them. while (offset + (int)sizeof(client_command) <= n) { memcpy((char*)&last_command, buf+offset, sizeof(client_command)); if (!manage_command(last_command, fd)) return false; offset += sizeof(client_command); } // Add the beginning of a new unfinished command. if (offset < n) { memcpy((char*)&last_command, buf+offset, n-offset); last_command_len = n-offset; last_unfinished[fd] = std::pair<client_command, int>(last_command, last_command_len); } return true; } bool TCPManager::manage_command(client_command &command, int fd) { sockaddr_in client_addr = subscriber_fd_info[fd]; if (command.cmd_type == APPROVAL_REQUEST) { std::string id; char buf[100]; memset(buf, 0, 100); memcpy(buf, &command.id, sizeof(command.id)); id.assign(buf, buf+strlen(buf)); // There is already a client with the same id, connection refused. if (online_subscribers.find(id) != online_subscribers.end()) { send_approval_reply(fd, false); close_fd(fd); return false; } else { // Add new id-fd links. online_subscribers.insert(id); subscribers_by_fd.insert(std::pair<int, std::string>(fd, id)); subscribers_by_id.insert(std::pair<std::string, int>(id, fd)); char* ip = (char*)&(client_addr.sin_addr.s_addr); printf("New client %s connected from %d.%d.%d.%d:%d.\n", id.c_str(), ip[0], ip[1], ip[2], ip[3], ntohs(client_addr.sin_port)); if (!send_approval_reply(fd, true)) { close_fd(fd); return false; } if (!send_pending_notifications(fd)) { close_subscriber(id); return false; } } } else { if (command.cmd_type == UPDATE) { std::string topic, cmd; char buf[100]; memset(buf, 0, 100); memcpy(buf, command.topic, sizeof(command.topic)); topic.assign(buf, buf+strlen(buf)); memset(buf, 0, 100); memcpy(buf, command.command, sizeof(command.command)); cmd.assign(buf, buf+strlen(buf)); if (cmd.compare("subscribe") == 0) { subscribe(subscribers_by_fd[fd], topic, command.SF); } else { if (cmd.compare("unsubscribe") == 0) unsubscribe(subscribers_by_fd[fd], topic, command.SF); } } } return true; } void TCPManager::subscribe(std::string id, std::string topic, unsigned char SF) { if (subscriptions.find(topic) == subscriptions.end()) subscriptions[topic] = std::map<std::string, int>(); if (subscriptions[topic].find(id) != subscriptions[topic].end()) subscriptions[topic].erase(id); subscriptions[topic].insert(std::pair<std::string, int>(id, (int)SF)); } void TCPManager::unsubscribe(std::string id, std::string topic, unsigned char SF) { if (subscriptions.find(topic) != subscriptions.end()) subscriptions[topic].erase(id); } void TCPManager::manage_notification(notification notif, fd_set *read_fds) { char buf[1600]; memset(buf, 0, sizeof(buf)); std::string topic; memcpy(buf, notif.topic, sizeof(notif.topic)); topic.assign(buf, buf+strlen(buf)); std::map<std::string, int>::iterator it; for (it = subscriptions[topic].begin(); it != subscriptions[topic].end(); it++) { std::string id = it->first; int sf = it->second; if (online_subscribers.find(id) != online_subscribers.end()) { if (!send_notification(id, notif)) { FD_CLR(subscribers_by_id[id], read_fds); close_subscriber(id); } } else { if (sf == 1) { if (pending_notificatons.find(id) == pending_notificatons.end()) pending_notificatons[id] = std::queue<notification>(); pending_notificatons[id].push(notif); } } } } bool TCPManager::send_notification(std::string id, notification notif) { int len = sizeof(notification) - sizeof(notif.payload) + notif.len; if (send(subscribers_by_id[id], &notif, len, 0) < 0) { perror("An error occurred while sending notification to client"); return false; } return true; } bool TCPManager::send_pending_notifications(int fd) { std::string id = subscribers_by_fd[fd]; if (pending_notificatons.find(id) != pending_notificatons.end()) { while (pending_notificatons[id].size() > 0) { notification notif = pending_notificatons[id].front(); if (!send_notification(id, notif)) return false; pending_notificatons[id].pop(); } } return true; } bool TCPManager::send_approval_reply(int fd, bool accepted) { notification notif; memset((char*)&notif, 0, sizeof(notification)); notif.len = sizeof(notif.payload); if (accepted) notif.data_type = 1; else notif.data_type = 0; if (send(fd, (char*)&notif, sizeof(notification), 0) < 0) { perror("An error occurred while sending approval of connection"); return false; } return true; }
9,104
3,062
#ifndef _PERSEUS_META #define _PERSEUS_META #define ANIM_BUTTON_PREAMBLE disableSerialization;_ctrl=_this select 0;if(ctrlEnabled _ctrl)then{ #define ANIM_BUTTON_HELPER_0(ARG) ANIM_BUTTON_PREAMBLE _ctrl ctrlSetText 'Perseus\Interface\Textures\##ARG##.paa';}; #define ANIM_BUTTON_HELPER_1(ARG) ANIM_BUTTON_PREAMBLE if([ctrlPosition _ctrl,[_this select 2,_this select 3]]call perseus_fnc_ui_checkAreaIntersect)then{_ctrl ctrlSetText 'Perseus\Interface\Textures\##ARG##_mOVER.paa';}else{_ctrl ctrlSetText 'Perseus\Interface\Textures\##ARG##_NORM.paa';};}; #define ANIM_BUTTON(ARG) onMouseEnter=QUOTE(ANIM_BUTTON_HELPER_0(JOIN(ARG,_mOVER)));\ onMouseExit=QUOTE(ANIM_BUTTON_HELPER_0(JOIN(ARG,_NORM)));\ onMouseButtonDown=QUOTE(ANIM_BUTTON_HELPER_0(JOIN(ARG,_CLICK)));\ onMouseButtonUp=QUOTE(ANIM_BUTTON_HELPER_1(ARG)) #endif
823
396
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "Misc/Exec.h" FExec::~FExec() { }
106
51
#include "PihaDeviceProvider.h" #include <assert.h> #include <algorithm> #include "PihaDevice.h" namespace Piha { DeviceProvider::DeviceProvider() { } DeviceProvider::~DeviceProvider() { deleteDevices(); } void DeviceProvider::addDevice( Device* device ) { mDevices.push_back( device ); for ( Listeners::iterator itrListener=mListeners.begin(); itrListener!=mListeners.end(); ++itrListener ) (*itrListener)->onDeviceAdded( this, device ); } void DeviceProvider::deleteDevice( Device* device ) { Devices::iterator itr = std::find( mDevices.begin(), mDevices.end(), device ); if ( itr==mDevices.end() ) return; for ( Listeners::iterator itrListener=mListeners.begin(); itrListener!=mListeners.end(); ++itrListener ) (*itrListener)->onDeviceRemoving( this, device ); mDevices.erase( itr ); delete device; } void DeviceProvider::deleteDevices() { Devices devices = mDevices; // The copy is on purpose here for ( Devices::iterator itr=devices.begin(); itr!=devices.end(); itr++ ) { Device* device = *itr; deleteDevice( device ); } assert( mDevices.empty() ); } const Devices& DeviceProvider::getDevices() const { return mDevices; } void DeviceProvider::addListener( Listener* listener ) { assert(listener); mListeners.push_back(listener); } bool DeviceProvider::removeListener( Listener* listener ) { Listeners::iterator itr = std::find( mListeners.begin(), mListeners.end(), listener ); if ( itr==mListeners.end() ) return false; mListeners.erase( itr ); return true; } }
1,512
541
// Houzi Game Engine // Copyright (c) 2018 Davide Corradi // Licensed under the MIT license. #include "hou/gfx/mesh_draw_mode.hpp" #include "hou/cor/core_functions.hpp" #define MESH_DRAW_MODE_CASE(mdm, os) \ case mesh_draw_mode::mdm: \ return (os) << #mdm namespace hou { std::ostream& operator<<(std::ostream& os, mesh_draw_mode mdm) { switch(mdm) { MESH_DRAW_MODE_CASE(points, os); MESH_DRAW_MODE_CASE(line_strip, os); MESH_DRAW_MODE_CASE(line_loop, os); MESH_DRAW_MODE_CASE(lines, os); MESH_DRAW_MODE_CASE(line_strip_adjacency, os); MESH_DRAW_MODE_CASE(line_adjacency, os); MESH_DRAW_MODE_CASE(triangle_strip, os); MESH_DRAW_MODE_CASE(triangle_fan, os); MESH_DRAW_MODE_CASE(triangles, os); MESH_DRAW_MODE_CASE(triangle_strip_adjacency, os); MESH_DRAW_MODE_CASE(patches, os); } return STREAM_VALUE(os, mesh_draw_mode, mdm); } } // namespace hou
914
414
/** MIT License Copyright (c) 2018 Sarthak Mahajan 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. */ /** *@copyright Copyright (c) 2018 Sarthak Mahajan *@file test.cpp *@author Sarthak Mahajan *@brief All tests are defined here. * Primarily to check image channels and predicted turns. */ #include <gtest/gtest.h> #include <gmock/gmock.h> #include <iostream> #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/opencv.hpp" #include "../include/lanedetector.hpp" #include "../include/preProcess.hpp" #include "include/mockpreProcess.hpp" TEST(channels, testNumOfChannelsReturned) { preProcess helperObj; cv::Mat testImg, retImg; std::string imgPath("test.png"); testImg = cv::imread(imgPath, cv::IMREAD_COLOR); retImg = helperObj.grayImage(testImg); EXPECT_EQ(1, retImg.channels()); } TEST(turns, checkTurnDirectionLeft) { lanedetector testObj(true, true, 1.5, -1.5, cv::Point(200, 0), cv::Point(800, 0), 640, 12); EXPECT_EQ("LEFT", testObj.predictTurn()); } TEST(turns, checkTurnDirectionRight) { lanedetector testObj(true, true, 1.5, 1.5, cv::Point(200, 0), cv::Point(400, 0), 640, 12); EXPECT_EQ("RIGHT", testObj.predictTurn()); } TEST(preProcess, testPreProcessFuncs) { std::string imgPath("test.png"); mockpreProcess mockObj; EXPECT_CALL(mockObj, performAllOps(imgPath)).Times(1).WillOnce( ::testing::Return(1)); mockObj.performAllOps(imgPath); }
2,487
889
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; #define ll long long #define mem(Arr,x) memset(Arr,x,sizeof(Arr)) #define lowbit(x) ((x)&(-x)) const int maxN=101000; const int inf=2147483647; int n,Seq[maxN]; int numcnt,Num[maxN]; int BIT[maxN],F[maxN]; int GetMax(int pos); void Modify(int pos,int key); int main(){ scanf("%d",&n); for (int i=1;i<=n;i++) scanf("%d",&Seq[i]),Num[i]=Seq[i]=-Seq[i]; numcnt=n; sort(&Num[1],&Num[n+1]);numcnt=unique(&Num[1],&Num[n+1])-Num-1; int Mx=0; for (int i=n;i>=1;i--){ int p=lower_bound(&Num[1],&Num[numcnt+1],Seq[i])-Num;//cout<<"p:"<<p<<endl; F[i]=GetMax(p-1)+1; Modify(p,F[i]); Mx=max(Mx,F[i]); } //for (int i=1;i<=n;i++) cout<<F[i]<<" ";cout<<endl; for (int i=1;i<=n;i++) Seq[i]=-Seq[i]; int Q;scanf("%d",&Q); while (Q--){ int k;scanf("%d",&k); if (k>Mx) printf("Impossible\n"); else{ for (int i=1,j=1,mn=-inf;(j<=k)&&(i<=n);i++) if ((F[i]+j-1>=k)&&(Seq[i]>mn)){ printf("%d ",Seq[i]);mn=max(mn,Seq[i]);j++; } printf("\n"); } } return 0; } int GetMax(int pos){ int ret=0; while (pos){ ret=max(ret,BIT[pos]);pos-=lowbit(pos); } return ret; } void Modify(int pos,int key){ while (pos<=numcnt){ BIT[pos]=max(BIT[pos],key);pos+=lowbit(pos); } return; }
1,327
703
#pragma once #include "CellState.hpp" #include "Coord.hpp" #include "Direction.hpp" #include <concepts> #include <cstdint> namespace model { enum class VisitStatus : std::uint8_t { STOP_VISITING, KEEP_VISITING }; using enum VisitStatus; // Non-directional visitors don't have a direction. They are used with // visit-algorithms that are not "linear", but involve mult-direction scans, // such as the whole board, or "what's adjacent to this cell" // // returning void indicates there is no early-stop while visiting // If you don't care about short-circuiting the visit, don't return true. // template <typename T> concept CellVisitorAll = requires(T visitor, CellState cell) { { visitor(Coord{0, 0}, cell) } -> std::same_as<void>; }; // // returning a VisitStatus indicates the visit may be stopped prematurely // template <typename T> concept CellVisitorSome = requires(T visitor, CellState cell) { { visitor(Coord{0, 0}, cell) } -> std::same_as<VisitStatus>; }; // // Unify both Some/All cell visitors // Many visit algos can work with either - when undirected // template <typename T> concept CellVisitor = CellVisitorAll<T> || CellVisitorSome<T>; // ============== // Directed visitors are CellVisitors but are also notified of the direction // they are going. This is generally associated with the visitors that travel // along lines. template <typename T> concept DirectedCellVisitorAll = requires(T visitor, CellState cell) { { visitor(Direction{}, Coord{0, 0}, cell) } -> std::same_as<void>; }; template <typename T> concept DirectedCellVisitorSome = requires(T visitor, CellState cell) { { visitor(Direction{}, Coord{0, 0}, cell) } -> std::same_as<VisitStatus>; }; // // Short circuitable or not, up to the caller // template <typename T> concept DirectedCellVisitor = DirectedCellVisitorAll<T> || DirectedCellVisitorSome<T>; // The most flexible of all for the caller, short-circuitable or not, directed // or not. template <typename T> concept OptDirCellVisitor = DirectedCellVisitor<T> || CellVisitor<T>; // for determining if we should visit a cell or not, for when the visit function // queries a predicate before dispatching. template <typename T> concept CellVisitPredicate = requires(T visitor, CellState cell) { { visitor(Coord{0, 0}, cell) } -> std::same_as<bool>; }; } // namespace model
2,338
728
/* * 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. */ /** * @author Vyacheslav P. Shakin */ #include "Ia32IRManager.h" #include "Ia32Encoder.h" #include "Ia32Printer.h" #include "Log.h" #include "EMInterface.h" #include "Ia32Printer.h" #include "Ia32CodeGenerator.h" #include "Dominator.h" #include <math.h> namespace Jitrino { namespace Ia32 { using namespace std; //========================================================================================================= static void appendToInstList(Inst *& head, Inst * listToAppend) { if (head==NULL) { head=listToAppend; } else if (listToAppend!=NULL){ listToAppend->insertBefore(head); } } //_________________________________________________________________________________________________ const char * newString(MemoryManager& mm, const char * str, U_32 length) { assert(str!=NULL); if (length==EmptyUint32) length=(U_32)strlen(str); char * psz=new(mm) char[length+1]; strncpy(psz, str, length); psz[length]=0; return psz; } //_____________________________________________________________________________________________ IRManager::IRManager(MemoryManager& memManager, TypeManager& tm, MethodDesc& md, CompilationInterface& compIface) :memoryManager(memManager), typeManager(tm), methodDesc(md), compilationInterface(compIface), opndId(0), instId(0), opnds(memManager), gpTotalRegUsage(0), entryPointInst(NULL), _hasLivenessInfo(false), internalHelperInfos(memManager), infoMap(memManager), verificationLevel(0), hasCalls(false), hasNonExceptionCalls(false), laidOut(false), codeStartAddr(NULL), refsCompressed(VMInterface::areReferencesCompressed()) { for (U_32 i=0; i<lengthof(regOpnds); i++) regOpnds[i]=NULL; fg = new (memManager) ControlFlowGraph(memManager, this); fg->setEntryNode(fg->createBlockNode()); fg->setLoopTree(new (memManager) LoopTree(memManager, fg)); initInitialConstraints(); registerInternalHelperInfo("printRuntimeOpndInternalHelper", IRManager::InternalHelperInfo((void*)&printRuntimeOpndInternalHelper, &CallingConvention_STDCALL)); } //_____________________________________________________________________________________________ void IRManager::addOpnd(Opnd * opnd) { assert(opnd->id>=opnds.size()); opnds.push_back(opnd); opnd->id=(U_32)opnds.size()-1; } //_____________________________________________________________________________________________ Opnd * IRManager::newOpnd(Type * type) { Opnd * opnd=new(memoryManager) Opnd(opndId++, type, getInitialConstraint(type)); addOpnd(opnd); return opnd; } //_____________________________________________________________________________________________ Opnd * IRManager::newOpnd(Type * type, Constraint c) { c.intersectWith(Constraint(OpndKind_Any, getTypeSize(type))); assert(!c.isNull()); Opnd * opnd=new(memoryManager) Opnd(opndId++, type, c); addOpnd(opnd); return opnd; } //_____________________________________________________________________________________________ Opnd * IRManager::newImmOpnd(Type * type, int64 immediate) { Opnd * opnd = newOpnd(type); opnd->assignImmValue(immediate); return opnd; } //____________________________________________________________________________________________ Opnd * IRManager::newImmOpnd(Type * type, Opnd::RuntimeInfo::Kind kind, void * arg0, void * arg1, void * arg2, void * arg3) { Opnd * opnd=newImmOpnd(type, 0); opnd->setRuntimeInfo(new(memoryManager) Opnd::RuntimeInfo(kind, arg0, arg1, arg2, arg3)); return opnd; } //_____________________________________________________________________________________________ ConstantAreaItem * IRManager::newConstantAreaItem(float f) { return new(memoryManager) ConstantAreaItem( ConstantAreaItem::Kind_FPSingleConstantAreaItem, sizeof(float), new(memoryManager) float(f) ); } //_____________________________________________________________________________________________ ConstantAreaItem * IRManager::newConstantAreaItem(double d) { return new(memoryManager) ConstantAreaItem( ConstantAreaItem::Kind_FPDoubleConstantAreaItem, sizeof(double), new(memoryManager) double(d) ); } //_____________________________________________________________________________________________ ConstantAreaItem * IRManager::newSwitchTableConstantAreaItem(U_32 numTargets) { return new(memoryManager) ConstantAreaItem( ConstantAreaItem::Kind_SwitchTableConstantAreaItem, sizeof(BasicBlock*)*numTargets, new(memoryManager) BasicBlock*[numTargets] ); } //_____________________________________________________________________________________________ ConstantAreaItem * IRManager::newInternalStringConstantAreaItem(const char * str) { if (str==NULL) str=""; return new(memoryManager) ConstantAreaItem( ConstantAreaItem::Kind_InternalStringConstantAreaItem, (U_32)strlen(str)+1, (void*)newInternalString(str) ); } //_____________________________________________________________________________________________ ConstantAreaItem * IRManager::newBinaryConstantAreaItem(U_32 size, const void * pv) { return new(memoryManager) ConstantAreaItem(ConstantAreaItem::Kind_BinaryConstantAreaItem, size, pv); } //_____________________________________________________________________________________________ Opnd * IRManager::newFPConstantMemOpnd(float f, Opnd * baseOpnd, BasicBlock* bb) { ConstantAreaItem * item=newConstantAreaItem(f); Opnd * addr=newImmOpnd(typeManager.getUnmanagedPtrType(typeManager.getSingleType()), Opnd::RuntimeInfo::Kind_ConstantAreaItem, item); #ifdef _EM64T_ bb->appendInst(newCopyPseudoInst(Mnemonic_MOV, baseOpnd, addr)); return newMemOpndAutoKind(typeManager.getSingleType(), MemOpndKind_ConstantArea, baseOpnd); #else return newMemOpndAutoKind(typeManager.getSingleType(), MemOpndKind_ConstantArea, addr); #endif } //_____________________________________________________________________________________________ Opnd * IRManager::newFPConstantMemOpnd(double d, Opnd * baseOpnd, BasicBlock* bb) { ConstantAreaItem * item=newConstantAreaItem(d); Opnd * addr=newImmOpnd(typeManager.getUnmanagedPtrType(typeManager.getDoubleType()), Opnd::RuntimeInfo::Kind_ConstantAreaItem, item); #ifdef _EM64T_ bb->appendInst(newCopyPseudoInst(Mnemonic_MOV, baseOpnd, addr)); return newMemOpndAutoKind(typeManager.getDoubleType(), MemOpndKind_ConstantArea, baseOpnd); #else return newMemOpndAutoKind(typeManager.getDoubleType(), MemOpndKind_ConstantArea, addr); #endif } //_____________________________________________________________________________________________ Opnd * IRManager::newInternalStringConstantImmOpnd(const char * str) { ConstantAreaItem * item=newInternalStringConstantAreaItem(str); return newImmOpnd(typeManager.getUnmanagedPtrType(typeManager.getIntPtrType()), Opnd::RuntimeInfo::Kind_ConstantAreaItem, item); } //_____________________________________________________________________________________________ Opnd * IRManager::newBinaryConstantImmOpnd(U_32 size, const void * pv) { ConstantAreaItem * item=newBinaryConstantAreaItem(size, pv); return newImmOpnd(typeManager.getUnmanagedPtrType(typeManager.getIntPtrType()), Opnd::RuntimeInfo::Kind_ConstantAreaItem, item); } //_____________________________________________________________________________________________ SwitchInst * IRManager::newSwitchInst(U_32 numTargets, Opnd * index) { assert(numTargets>0); assert(index!=NULL); Inst * instList = NULL; ConstantAreaItem * item=newSwitchTableConstantAreaItem(numTargets); // This tableAddress in SwitchInst is kept separately [from getOpnd(0)] // so it allows to replace an Opnd (used in SpillGen) and keep the table // itself intact. Opnd * tableAddr=newImmOpnd(typeManager.getIntPtrType(), Opnd::RuntimeInfo::Kind_ConstantAreaItem, item); #ifndef _EM64T_ Opnd * targetOpnd = newMemOpnd(typeManager.getIntPtrType(), MemOpndKind_ConstantArea, 0, index, newImmOpnd(typeManager.getInt32Type(), sizeof(POINTER_SIZE_INT)), tableAddr); #else // on EM64T immediate displacement cannot be of 64 bit size, so move it to a register first Opnd * baseOpnd = newOpnd(typeManager.getInt64Type()); appendToInstList(instList, newCopyPseudoInst(Mnemonic_MOV, baseOpnd, tableAddr)); Opnd * targetOpnd = newMemOpnd(typeManager.getUnmanagedPtrType(typeManager.getIntPtrType()), MemOpndKind_ConstantArea, baseOpnd, index, newImmOpnd(typeManager.getInt32Type(), sizeof(POINTER_SIZE_INT)), 0); #endif SwitchInst * inst=new(memoryManager, 1) SwitchInst(Mnemonic_JMP, instId++, tableAddr); inst->insertOpnd(0, targetOpnd, Inst::OpndRole_Explicit); inst->assignOpcodeGroup(this); appendToInstList(instList, inst); return (SwitchInst *)instList; } //_____________________________________________________________________________________________ Opnd * IRManager::newRegOpnd(Type * type, RegName reg) { Opnd * opnd = newOpnd(type, Constraint(getRegKind(reg))); opnd->assignRegName(reg); return opnd; } //_____________________________________________________________________________________________ Opnd * IRManager::newMemOpnd(Type * type, MemOpndKind k, Opnd * base, Opnd * index, Opnd * scale, Opnd * displacement, RegName segReg) { Opnd * opnd = newOpnd(type); opnd->assignMemLocation(k,base,index,scale,displacement); if (segReg != RegName_Null) opnd->setSegReg(segReg); return opnd; } //_________________________________________________________________________________________________ Opnd * IRManager::newMemOpnd(Type * type, Opnd * base, Opnd * index, Opnd * scale, Opnd * displacement, RegName segReg) { return newMemOpnd(type, MemOpndKind_Heap, base, index, scale, displacement, segReg); } //_____________________________________________________________________________________________ Opnd * IRManager::newMemOpnd(Type * type, MemOpndKind k, Opnd * base, I_32 displacement, RegName segReg) { return newMemOpnd(type, k, base, 0, 0, newImmOpnd(typeManager.getInt32Type(), displacement), segReg); } //_____________________________________________________________________________________________ Opnd * IRManager::newMemOpndAutoKind(Type * type, MemOpndKind k, Opnd * opnd0, Opnd * opnd1, Opnd * opnd2) { Opnd * base=NULL, * displacement=NULL; Constraint c=opnd0->getConstraint(Opnd::ConstraintKind_Current); if (!(c&OpndKind_GPReg).isNull()){ base=opnd0; }else if (!(c&OpndKind_Imm).isNull()){ displacement=opnd0; }else assert(0); if (opnd1!=NULL){ c=opnd1->getConstraint(Opnd::ConstraintKind_Current); if (!(c&OpndKind_GPReg).isNull()){ base=opnd1; }else if (!(c&OpndKind_Imm).isNull()){ displacement=opnd1; }else assert(0); } return newMemOpnd(type, k, base, 0, 0, displacement); } //_____________________________________________________________________________________________ void IRManager::initInitialConstraints() { for (U_32 i=0; i<lengthof(initialConstraints); i++) initialConstraints[i] = createInitialConstraint((Type::Tag)i); } //_____________________________________________________________________________________________ Constraint IRManager::createInitialConstraint(Type::Tag t)const { OpndSize sz=getTypeSize(t); if (t==Type::Single||t==Type::Double||t==Type::Float) return Constraint(OpndKind_XMMReg, sz)|Constraint(OpndKind_Mem, sz); if (sz<=Constraint::getDefaultSize(OpndKind_GPReg)) return Constraint(OpndKind_GPReg, sz)|Constraint(OpndKind_Mem, sz)|Constraint(OpndKind_Imm, sz); if (sz==OpndSize_64) return Constraint(OpndKind_Mem, sz)|Constraint(OpndKind_Imm, sz); // imm before lowering return Constraint(OpndKind_Memory, sz); } //_____________________________________________________________________________________________ Inst * IRManager::newInst(Mnemonic mnemonic, Opnd * opnd0, Opnd * opnd1, Opnd * opnd2) { Inst * inst = new(memoryManager, 4) Inst(mnemonic, instId++, Inst::Form_Native); U_32 i=0; Opnd ** opnds = inst->getOpnds(); U_32 * roles = inst->getOpndRoles(); if (opnd0!=NULL){ opnds[i] = opnd0; roles[i] = Inst::OpndRole_Explicit; i++; if (opnd1!=NULL){ opnds[i] = opnd1; roles[i] = Inst::OpndRole_Explicit; i++; if (opnd2!=NULL){ opnds[i] = opnd2; roles[i] = Inst::OpndRole_Explicit; i++; }}} inst->opndCount = i; inst->assignOpcodeGroup(this); return inst; } //_____________________________________________________________________________________________ Inst * IRManager::newInst(Mnemonic mnemonic, Opnd * opnd0, Opnd * opnd1, Opnd * opnd2, Opnd * opnd3, Opnd * opnd4, Opnd * opnd5, Opnd * opnd6, Opnd * opnd7 ) { Inst * inst = new(memoryManager, 8) Inst(mnemonic, instId++, Inst::Form_Native); U_32 i=0; Opnd ** opnds = inst->getOpnds(); U_32 * roles = inst->getOpndRoles(); if (opnd0!=NULL){ opnds[i] = opnd0; roles[i] = Inst::OpndRole_Explicit; i++; if (opnd1!=NULL){ opnds[i] = opnd1; roles[i] = Inst::OpndRole_Explicit; i++; if (opnd2!=NULL){ opnds[i] = opnd2; roles[i] = Inst::OpndRole_Explicit; i++; if (opnd3!=NULL){ opnds[i] = opnd3; roles[i] = Inst::OpndRole_Explicit; i++; if (opnd4!=NULL){ opnds[i] = opnd4; roles[i] = Inst::OpndRole_Explicit; i++; if (opnd5!=NULL){ opnds[i] = opnd5; roles[i] = Inst::OpndRole_Explicit; i++; if (opnd6!=NULL){ opnds[i] = opnd6; roles[i] = Inst::OpndRole_Explicit; i++; if (opnd7!=NULL){ opnds[i] = opnd7; roles[i] = Inst::OpndRole_Explicit; i++; }}}}}}}}; inst->opndCount = i; inst->assignOpcodeGroup(this); return inst; } //_____________________________________________________________________________________________ Inst * IRManager::newInstEx(Mnemonic mnemonic, U_32 defCount, Opnd * opnd0, Opnd * opnd1, Opnd * opnd2) { Inst * inst = new(memoryManager, 4) Inst(mnemonic, instId++, Inst::Form_Extended); U_32 i=0; Opnd ** opnds = inst->getOpnds(); U_32 * roles = inst->getOpndRoles(); if (opnd0!=NULL){ opnds[i] = opnd0; roles[i] = Inst::OpndRole_Explicit; i++; if (opnd1!=NULL){ opnds[i] = opnd1; roles[i] = Inst::OpndRole_Explicit; i++; if (opnd2!=NULL){ opnds[i] = opnd2; roles[i] = Inst::OpndRole_Explicit; i++; }}} inst->opndCount = i; inst->defOpndCount=defCount; inst->assignOpcodeGroup(this); return inst; } //_____________________________________________________________________________________________ Inst * IRManager::newInstEx(Mnemonic mnemonic, U_32 defCount, Opnd * opnd0, Opnd * opnd1, Opnd * opnd2, Opnd * opnd3, Opnd * opnd4, Opnd * opnd5, Opnd * opnd6, Opnd * opnd7 ) { Inst * inst = new(memoryManager, 8) Inst(mnemonic, instId++, Inst::Form_Extended); U_32 i=0; Opnd ** opnds = inst->getOpnds(); U_32 * roles = inst->getOpndRoles(); if (opnd0!=NULL){ opnds[i] = opnd0; roles[i] = Inst::OpndRole_Explicit; i++; if (opnd1!=NULL){ opnds[i] = opnd1; roles[i] = Inst::OpndRole_Explicit; i++; if (opnd2!=NULL){ opnds[i] = opnd2; roles[i] = Inst::OpndRole_Explicit; i++; if (opnd3!=NULL){ opnds[i] = opnd3; roles[i] = Inst::OpndRole_Explicit; i++; if (opnd4!=NULL){ opnds[i] = opnd4; roles[i] = Inst::OpndRole_Explicit; i++; if (opnd5!=NULL){ opnds[i] = opnd5; roles[i] = Inst::OpndRole_Explicit; i++; if (opnd6!=NULL){ opnds[i] = opnd6; roles[i] = Inst::OpndRole_Explicit; i++; if (opnd7!=NULL){ opnds[i] = opnd7; roles[i] = Inst::OpndRole_Explicit; i++; }}}}}}}}; inst->opndCount = i; inst->defOpndCount=defCount; inst->assignOpcodeGroup(this); return inst; } //_________________________________________________________________________________________________ Inst * IRManager::newI8PseudoInst(Mnemonic mnemonic, U_32 defCount, Opnd * opnd0, Opnd * opnd1, Opnd * opnd2, Opnd * opnd3 ) { Inst * inst=new (memoryManager, 4) Inst(mnemonic, instId++, Inst::Form_Extended); inst->kind = Inst::Kind_I8PseudoInst; U_32 i=0; Opnd ** opnds = inst->getOpnds(); assert(opnd0->getType()->isInteger() ||opnd0->getType()->isPtr()); if (opnd0!=NULL){ opnds[i] = opnd0; i++; if (opnd1!=NULL){ opnds[i] = opnd1; i++; if (opnd2!=NULL){ opnds[i] = opnd2; i++; if (opnd3!=NULL){ opnds[i] = opnd3; i++; }}}}; inst->defOpndCount=defCount; inst->opndCount = i; inst->assignOpcodeGroup(this); return inst; } //_____________________________________________________________________________________________ SystemExceptionCheckPseudoInst * IRManager::newSystemExceptionCheckPseudoInst(CompilationInterface::SystemExceptionId exceptionId, Opnd * opnd0, Opnd * opnd1, bool checksThisForInlinedMethod) { SystemExceptionCheckPseudoInst * inst=new (memoryManager, 8) SystemExceptionCheckPseudoInst(exceptionId, instId++, checksThisForInlinedMethod); U_32 i=0; Opnd ** opnds = inst->getOpnds(); if (opnd0!=NULL){ opnds[i++] = opnd0; if (opnd1!=NULL){ opnds[i++] = opnd1; }} inst->opndCount = i; inst->assignOpcodeGroup(this); return inst; } //_________________________________________________________________________________________________ BranchInst * IRManager::newBranchInst(Mnemonic mnemonic, Node* trueTarget, Node* falseTarget, Opnd * targetOpnd) { BranchInst * inst=new(memoryManager, 2) BranchInst(mnemonic, instId++); if (targetOpnd==0) targetOpnd=newImmOpnd(typeManager.getInt32Type(), 0); inst->insertOpnd(0, targetOpnd, Inst::OpndRole_Explicit); inst->assignOpcodeGroup(this); inst->setFalseTarget(falseTarget); inst->setTrueTarget(trueTarget); return inst; } //_________________________________________________________________________________________________ JumpInst * IRManager::newJumpInst(Opnd * targetOpnd) { JumpInst * inst=new(memoryManager, 2) JumpInst(instId++); if (targetOpnd==0) { targetOpnd=newImmOpnd(typeManager.getInt32Type(), 0); } inst->insertOpnd(0, targetOpnd, Inst::OpndRole_Explicit); inst->assignOpcodeGroup(this); return inst; } //_________________________________________________________________________________________________ EntryPointPseudoInst * IRManager::newEntryPointPseudoInst(const CallingConvention * cc) { // there is nothing wrong with calling this method several times. // it's just a self-check, as the currently assumed behaviour is that this method is invoked only once. assert(NULL == entryPointInst); EntryPointPseudoInst * inst=new(memoryManager, methodDesc.getNumParams() * 2) EntryPointPseudoInst(this, instId++, cc); fg->getEntryNode()->appendInst(inst); inst->assignOpcodeGroup(this); entryPointInst = inst; if (getCompilationInterface().getCompilationParams().exe_notify_method_entry) { Opnd **hlpArgs = new (memoryManager) Opnd* [1]; hlpArgs[0] = newImmOpnd(typeManager.getIntPtrType(), Opnd::RuntimeInfo::Kind_MethodRuntimeId, &methodDesc); Node* prolog = getFlowGraph()->getEntryNode(); prolog->appendInst(newRuntimeHelperCallInst(VM_RT_JVMTI_METHOD_ENTER_CALLBACK, 1, (Opnd**)hlpArgs, NULL)); } return inst; } //_________________________________________________________________________________________________ CallInst * IRManager::newCallInst(Opnd * targetOpnd, const CallingConvention * cc, U_32 argCount, Opnd ** args, Opnd * retOpnd) { CallInst * callInst=new(memoryManager, (argCount + (retOpnd ? 1 : 0)) * 2 + 1) CallInst(this, instId++, cc, targetOpnd->getRuntimeInfo()); CallingConventionClient & ccc = callInst->callingConventionClient; U_32 i=0; if (retOpnd!=NULL){ ccc.pushInfo(Inst::OpndRole_Def, retOpnd->getType()->tag); callInst->insertOpnd(i++, retOpnd, Inst::OpndRole_Auxilary|Inst::OpndRole_Def); } callInst->defOpndCount = i; callInst->insertOpnd(i++, targetOpnd, Inst::OpndRole_Explicit|Inst::OpndRole_Use); if (argCount>0){ for (U_32 j=0; j<argCount; j++){ ccc.pushInfo(Inst::OpndRole_Use, args[j]->getType()->tag); callInst->insertOpnd(i++, args[j], Inst::OpndRole_Auxilary|Inst::OpndRole_Use); } } callInst->opndCount = i; callInst->assignOpcodeGroup(this); return callInst; } //_________________________________________________________________________________________________ CallInst * IRManager::newRuntimeHelperCallInst(VM_RT_SUPPORT helperId, U_32 numArgs, Opnd ** args, Opnd * retOpnd) { Inst * instList = NULL; Opnd * target=newImmOpnd(typeManager.getInt32Type(), Opnd::RuntimeInfo::Kind_HelperAddress, (void*)helperId); const CallingConvention * cc=getCallingConvention(helperId); appendToInstList(instList,newCallInst(target, cc, numArgs, args, retOpnd)); return (CallInst *)instList; } //_________________________________________________________________________________________________ CallInst * IRManager::newInternalRuntimeHelperCallInst(const char * internalHelperID, U_32 numArgs, Opnd ** args, Opnd * retOpnd) { const InternalHelperInfo * info=getInternalHelperInfo(internalHelperID); assert(info!=NULL); Inst * instList = NULL; Opnd * target=newImmOpnd(typeManager.getInt32Type(), Opnd::RuntimeInfo::Kind_InternalHelperAddress, (void*)newInternalString(internalHelperID)); const CallingConvention * cc=info->callingConvention; appendToInstList(instList,newCallInst(target, cc, numArgs, args, retOpnd)); return (CallInst *)instList; } //_________________________________________________________________________________________________ Inst* IRManager::newEmptyPseudoInst() { return new(memoryManager, 0) EmptyPseudoInst(instId++); } //_________________________________________________________________________________________________ MethodMarkerPseudoInst* IRManager::newMethodEntryPseudoInst(MethodDesc* mDesc) { return new(memoryManager, 0) MethodMarkerPseudoInst(mDesc, instId++, Inst::Kind_MethodEntryPseudoInst); } //_________________________________________________________________________________________________ MethodMarkerPseudoInst* IRManager::newMethodEndPseudoInst(MethodDesc* mDesc) { return new(memoryManager, 0) MethodMarkerPseudoInst(mDesc, instId++, Inst::Kind_MethodEndPseudoInst); } //_________________________________________________________________________________________________ void IRManager::registerInternalHelperInfo(const char * internalHelperID, const InternalHelperInfo& info) { assert(internalHelperID!=NULL && internalHelperID[0]!=0); internalHelperInfos[newInternalString(internalHelperID)]=info; } //_________________________________________________________________________________________________ RetInst * IRManager::newRetInst(Opnd * retOpnd) { RetInst * retInst=new (memoryManager, 4) RetInst(this, instId++); assert( NULL != entryPointInst && NULL != entryPointInst->getCallingConventionClient().getCallingConvention() ); retInst->insertOpnd(0, newImmOpnd(typeManager.getInt16Type(), 0), Inst::OpndRole_Explicit|Inst::OpndRole_Use); if (retOpnd!=NULL){ retInst->insertOpnd(1, retOpnd, Inst::OpndRole_Auxilary|Inst::OpndRole_Use); retInst->getCallingConventionClient().pushInfo(Inst::OpndRole_Use, retOpnd->getType()->tag); retInst->opndCount = 2; } else retInst->opndCount = 1; retInst->assignOpcodeGroup(this); return retInst; } //_________________________________________________________________________________________________ void IRManager::applyCallingConventions() { const Nodes& nodes = fg->getNodes(); for (Nodes::const_iterator it = nodes.begin(), end = nodes.end(); it!=end; ++it) { Node* node = *it; if (node->isBlockNode()){ for (Inst * inst= (Inst*)node->getFirstInst(); inst!=NULL; inst=inst->getNextInst()){ if (inst->hasKind(Inst::Kind_EntryPointPseudoInst)){ EntryPointPseudoInst * eppi=(EntryPointPseudoInst*)inst; eppi->callingConventionClient.finalizeInfos(Inst::OpndRole_Def, CallingConvention::ArgKind_InArg); eppi->callingConventionClient.layoutAuxilaryOpnds(Inst::OpndRole_Def, OpndKind_Memory); }else if (inst->hasKind(Inst::Kind_CallInst)){ CallInst * callInst=(CallInst*)inst; callInst->callingConventionClient.finalizeInfos(Inst::OpndRole_Use, CallingConvention::ArgKind_InArg); callInst->callingConventionClient.layoutAuxilaryOpnds(Inst::OpndRole_Use, OpndKind_Any); callInst->callingConventionClient.finalizeInfos(Inst::OpndRole_Def, CallingConvention::ArgKind_RetArg); callInst->callingConventionClient.layoutAuxilaryOpnds(Inst::OpndRole_Def, OpndKind_Null); }else if (inst->hasKind(Inst::Kind_RetInst)){ RetInst * retInst=(RetInst*)inst; retInst->callingConventionClient.finalizeInfos(Inst::OpndRole_Use, CallingConvention::ArgKind_RetArg); retInst->callingConventionClient.layoutAuxilaryOpnds(Inst::OpndRole_Use, OpndKind_Null); if (retInst->getCallingConventionClient().getCallingConvention()->calleeRestoresStack()){ U_32 stackDepth=getEntryPointInst()->getArgStackDepth(); retInst->getOpnd(0)->assignImmValue(stackDepth); } } } } } } //_________________________________________________________________________________________________ CatchPseudoInst * IRManager::newCatchPseudoInst(Opnd * exception) { CatchPseudoInst * inst=new (memoryManager, 1) CatchPseudoInst(instId++); inst->insertOpnd(0, exception, Inst::OpndRole_Def); inst->setConstraint(0, RegName_EAX); inst->defOpndCount = 1; inst->opndCount = 1; inst->assignOpcodeGroup(this); return inst; } //_________________________________________________________________________________________________ GCInfoPseudoInst* IRManager::newGCInfoPseudoInst(const StlVector<Opnd*>& basesAndMptrs) { #ifdef _DEBUG for (StlVector<Opnd*>::const_iterator it = basesAndMptrs.begin(), end = basesAndMptrs.end(); it!=end; ++it) { Opnd* opnd = *it; assert(opnd->getType()->isObject() || opnd->getType()->isManagedPtr()); } #endif GCInfoPseudoInst* inst = new(memoryManager, (U_32)basesAndMptrs.size()) GCInfoPseudoInst(this, instId++); Opnd ** opnds = inst->getOpnds(); Constraint * constraints = inst->getConstraints(); for (U_32 i = 0, n = (U_32)basesAndMptrs.size(); i < n; i++){ Opnd * opnd = basesAndMptrs[i]; opnds[i] = opnd; constraints[i] = Constraint(OpndKind_Any, opnd->getSize()); } inst->opndCount = (U_32)basesAndMptrs.size(); inst->assignOpcodeGroup(this); return inst; } //_________________________________________________________________________________________________ CMPXCHG8BPseudoInst * IRManager::newCMPXCHG8BPseudoInst(Opnd* mem, Opnd* edx, Opnd* eax, Opnd* ecx, Opnd* ebx) { CMPXCHG8BPseudoInst* inst = new (memoryManager, 8) CMPXCHG8BPseudoInst(instId++); Opnd** opnds = inst->getOpnds(); Constraint* opndConstraints = inst->getConstraints(); // we do not set mem as a use in the inst // just to cheat cg::verifier (see IRManager::verifyOpnds() function) opnds[0] = mem; opnds[1] = edx; opnds[2] = eax; opnds[3] = getRegOpnd(RegName_EFLAGS); opnds[4] = edx; opnds[5] = eax; opnds[6] = ecx; opnds[7] = ebx; opndConstraints[0] = Constraint(OpndKind_Memory, OpndSize_64); opndConstraints[1] = Constraint(RegName_EDX); opndConstraints[2] = Constraint(RegName_EAX); opndConstraints[3] = Constraint(RegName_EFLAGS); opndConstraints[4] = Constraint(RegName_EDX); opndConstraints[5] = Constraint(RegName_EAX); opndConstraints[6] = Constraint(RegName_ECX); opndConstraints[7] = Constraint(RegName_EBX); inst->opndCount = 8; inst->defOpndCount = 4; inst->assignOpcodeGroup(this); return inst; } //_________________________________________________________________________________________________ Inst * IRManager::newCopyPseudoInst(Mnemonic mn, Opnd * opnd0, Opnd * opnd1) { assert(mn==Mnemonic_MOV||mn==Mnemonic_PUSH||mn==Mnemonic_POP); U_32 allOpndCnt = opnd0->getType()->isInt8() ? 4 : 2; Inst * inst=new (memoryManager, allOpndCnt) Inst(mn, instId++, Inst::Form_Extended); inst->kind = Inst::Kind_CopyPseudoInst; assert(opnd0!=NULL); assert(opnd1==NULL||opnd0->getSize()<=opnd1->getSize()); Opnd ** opnds = inst->getOpnds(); Constraint * opndConstraints = inst->getConstraints(); opnds[0] = opnd0; opndConstraints[0] = Constraint(OpndKind_Any, opnd0->getSize()); if (opnd1!=NULL){ opnds[1] = opnd1; opndConstraints[1] = Constraint(OpndKind_Any, opnd0->getSize()); inst->opndCount = 2; }else inst->opndCount = 1; if (mn != Mnemonic_PUSH) inst->defOpndCount = 1; inst->assignOpcodeGroup(this); return inst; } //_________________________________________________________________________________________________ AliasPseudoInst * IRManager::newAliasPseudoInst(Opnd * targetOpnd, Opnd * sourceOpnd, U_32 offset) { assert(sourceOpnd->isPlacedIn(OpndKind_Memory)); assert(!targetOpnd->hasAssignedPhysicalLocation()); assert(targetOpnd->canBePlacedIn(OpndKind_Memory)); Type * sourceType=sourceOpnd->getType(); OpndSize sourceSize=getTypeSize(sourceType); Type * targetType=targetOpnd->getType(); OpndSize targetSize=getTypeSize(targetType); #ifdef _DEBUG U_32 sourceByteSize=getByteSize(sourceSize); U_32 targetByteSize=getByteSize(targetSize); assert(getByteSize(sourceSize)>0 && getByteSize(targetSize)>0); assert(offset+targetByteSize<=sourceByteSize); #endif U_32 allocOpndNum = sourceOpnd->getType()->isInt8() ? 3 : 2; AliasPseudoInst * inst=new (memoryManager, allocOpndNum) AliasPseudoInst(instId++); inst->getOpnds()[0] = targetOpnd; inst->getConstraints()[0] = Constraint(OpndKind_Mem, targetSize); inst->getOpnds()[1] = sourceOpnd; inst->getConstraints()[1] = Constraint(OpndKind_Mem, sourceSize); if (sourceOpnd->getType()->isInt8()) { inst->getConstraints()[2] = Constraint(OpndKind_Mem, targetSize); } inst->defOpndCount = 1; inst->opndCount = 2; inst->offset=offset; layoutAliasPseudoInstOpnds(inst); inst->assignOpcodeGroup(this); return inst; } //_________________________________________________________________________________________________ AliasPseudoInst * IRManager::newAliasPseudoInst(Opnd * targetOpnd, U_32 sourceOpndCount, Opnd ** sourceOpnds) { assert(targetOpnd->isPlacedIn(OpndKind_Memory)); Type * targetType=targetOpnd->getType(); OpndSize targetSize=getTypeSize(targetType); assert(getByteSize(targetSize)>0); U_32 allocOpnNum = 0; for (U_32 i=0; i<sourceOpndCount; i++) allocOpnNum += getByteSize(getTypeSize(sourceOpnds[i]->getType())); allocOpnNum += getByteSize(getTypeSize(targetOpnd->getType())); AliasPseudoInst * inst=new (memoryManager, allocOpnNum) AliasPseudoInst(instId++); Opnd ** opnds = inst->getOpnds(); Constraint * opndConstraints = inst->getConstraints(); opnds[0] = targetOpnd; opndConstraints[0] = Constraint(OpndKind_Mem, targetSize); U_32 offset=0; for (U_32 i=0; i<sourceOpndCount; i++){ assert(!sourceOpnds[i]->hasAssignedPhysicalLocation() || (sourceOpnds[i]->isPlacedIn(OpndKind_Memory) && sourceOpnds[i]->getMemOpndKind() == targetOpnd->getMemOpndKind()) ); assert(sourceOpnds[i]->canBePlacedIn(OpndKind_Memory)); Type * sourceType=sourceOpnds[i]->getType(); OpndSize sourceSize=getTypeSize(sourceType); U_32 sourceByteSize=getByteSize(sourceSize); assert(sourceByteSize>0); assert(offset+sourceByteSize<=getByteSize(targetSize)); opnds[1 + i] = sourceOpnds[i]; opndConstraints[1 + i] = Constraint(OpndKind_Mem, sourceSize); offset+=sourceByteSize; } inst->defOpndCount = 1; inst->opndCount = sourceOpndCount + 1; layoutAliasPseudoInstOpnds(inst); inst->assignOpcodeGroup(this); return inst; } //_________________________________________________________________________________________________ void IRManager::layoutAliasPseudoInstOpnds(AliasPseudoInst * inst) { assert(inst->getOpndCount(Inst::OpndRole_InstLevel|Inst::OpndRole_Def) == 1); Opnd * const * opnds = inst->getOpnds(); Opnd * defOpnd=opnds[0]; Opnd * const * useOpnds = opnds + 1; U_32 useCount = inst->getOpndCount(Inst::OpndRole_InstLevel|Inst::OpndRole_Use); assert(useCount > 0); if (inst->offset==EmptyUint32){ U_32 offset=0; for (U_32 i=0; i<useCount; i++){ Opnd * innerOpnd=useOpnds[i]; assignInnerMemOpnd(defOpnd, innerOpnd, offset); offset+=getByteSize(innerOpnd->getSize()); } }else assignInnerMemOpnd(useOpnds[0], defOpnd, inst->offset); } //_________________________________________________________________________________________________ void IRManager::addAliasRelation(AliasRelation * relations, Opnd * outerOpnd, Opnd * innerOpnd, U_32 offset) { if (outerOpnd==innerOpnd){ assert(offset==0); return; } const AliasRelation& outerRel=relations[outerOpnd->getId()]; if (outerRel.outerOpnd!=NULL){ addAliasRelation(relations, outerRel.outerOpnd, innerOpnd, outerRel.offset+offset); return; } AliasRelation& innerRel=relations[innerOpnd->getId()]; if (innerRel.outerOpnd!=NULL){ addAliasRelation(relations, outerOpnd, innerRel.outerOpnd, offset-(int)innerRel.offset); } #ifdef _DEBUG Type * outerType=outerOpnd->getType(); OpndSize outerSize=getTypeSize(outerType); U_32 outerByteSize=getByteSize(outerSize); assert(offset<outerByteSize); Type * innerType=innerOpnd->getType(); OpndSize innerSize=getTypeSize(innerType); U_32 innerByteSize=getByteSize(innerSize); assert(outerByteSize>0 && innerByteSize>0); assert(offset+innerByteSize<=outerByteSize); #endif innerRel.outerOpnd=outerOpnd; innerRel.offset=offset; } //_________________________________________________________________________________________________ void IRManager::getAliasRelations(AliasRelation * relations) { const Nodes& nodes = fg->getNodes(); for (Nodes::const_iterator it = nodes.begin(), end = nodes.end(); it!=end; ++it) { Node* node = *it; if (node->isBlockNode()) { for (Inst * inst=(Inst*)node->getFirstInst(); inst!=NULL; inst=inst->getNextInst()) { if (inst->hasKind(Inst::Kind_AliasPseudoInst)){ AliasPseudoInst * aliasInst=(AliasPseudoInst *)inst; Opnd * const * opnds = inst->getOpnds(); U_32 useCount = inst->getOpndCount(Inst::OpndRole_InstLevel|Inst::OpndRole_Use); assert(inst->getOpndCount(Inst::OpndRole_InstLevel|Inst::OpndRole_Def) == 1 && useCount > 0); Opnd * defOpnd=opnds[0]; Opnd * const * useOpnds = opnds + 1; if (aliasInst->offset==EmptyUint32){ U_32 offset=0; for (U_32 i=0; i<useCount; i++){ Opnd * innerOpnd=useOpnds[i]; addAliasRelation(relations, defOpnd, innerOpnd, offset); offset+=getByteSize(innerOpnd->getSize()); } }else{ addAliasRelation(relations, useOpnds[0], defOpnd, aliasInst->offset); } } } } } } //_________________________________________________________________________________________________ void IRManager::layoutAliasOpnds() { MemoryManager mm("layoutAliasOpnds"); U_32 opndCount=getOpndCount(); AliasRelation * relations=new (memoryManager) AliasRelation[opndCount]; getAliasRelations(relations); for (U_32 i=0; i<opndCount; i++){ if (relations[i].outerOpnd!=NULL){ Opnd * innerOpnd=getOpnd(i); assert(innerOpnd->isPlacedIn(OpndKind_Mem)); assert(relations[i].outerOpnd->isPlacedIn(OpndKind_Mem)); Opnd * innerDispOpnd=innerOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Displacement); if (innerDispOpnd==NULL){ innerDispOpnd=newImmOpnd(typeManager.getInt32Type(), 0); innerOpnd->setMemOpndSubOpnd(MemOpndSubOpndKind_Displacement, innerDispOpnd); } Opnd * outerDispOpnd=relations[i].outerOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Displacement); U_32 outerDispValue=(U_32)(outerDispOpnd!=NULL?outerDispOpnd->getImmValue():0); innerDispOpnd->assignImmValue(outerDispValue+relations[i].offset); } } } //_________________________________________________________________________________________________ U_32 IRManager::assignInnerMemOpnd(Opnd * outerOpnd, Opnd* innerOpnd, U_32 offset) { assert(outerOpnd->isPlacedIn(OpndKind_Memory)); Opnd * outerDisp=outerOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Displacement); MemOpndKind outerMemOpndKind=outerOpnd->getMemOpndKind(); Opnd::RuntimeInfo * outerDispRI=outerDisp!=NULL?outerDisp->getRuntimeInfo():NULL; uint64 outerDispValue=outerDisp!=NULL?outerDisp->getImmValue():0; Opnd * outerBase=outerOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Base); Opnd * outerIndex=outerOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Index); Opnd * outerScale=outerOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Scale); OpndSize innerSize = innerOpnd->getSize(); U_32 innerByteSize = getByteSize(innerSize); Opnd * innerDisp=newImmOpnd(outerDisp!=NULL?outerDisp->getType():typeManager.getInt32Type(), outerDispValue+offset); if (outerDispRI){ Opnd::RuntimeInfo * innerDispRI=new(memoryManager) Opnd::RuntimeInfo( outerDispRI->getKind(), outerDispRI->getValue(0), outerDispRI->getValue(1), outerDispRI->getValue(2), outerDispRI->getValue(3), offset ); innerDisp->setRuntimeInfo(innerDispRI); } innerOpnd->assignMemLocation(outerMemOpndKind, outerBase, outerIndex, outerScale, innerDisp); return innerByteSize; } //_________________________________________________________________________________________________ void IRManager::assignInnerMemOpnds(Opnd * outerOpnd, Opnd** innerOpnds, U_32 innerOpndCount) { #ifdef _DEBUG U_32 outerByteSize = getByteSize(outerOpnd->getSize()); #endif for (U_32 i=0, offset=0; i<innerOpndCount; i++){ offset+=assignInnerMemOpnd(outerOpnd, innerOpnds[i], offset); assert(offset<=outerByteSize); } } //_________________________________________________________________________________________________ U_32 getLayoutOpndAlignment(Opnd * opnd) { OpndSize size=opnd->getSize(); if (size==OpndSize_80 || size==OpndSize_128) return 16; if (size==OpndSize_64) return 8; else return 4; } //_________________________________________________________________________________________________ Inst * IRManager::newCopySequence(Mnemonic mn, Opnd * opnd0, Opnd * opnd1, U_32 gpRegUsageMask, U_32 flagsRegUsageMask) { if (mn==Mnemonic_MOV) return newCopySequence(opnd0, opnd1, gpRegUsageMask, flagsRegUsageMask); else if (mn==Mnemonic_PUSH||mn==Mnemonic_POP) return newPushPopSequence(mn, opnd0, gpRegUsageMask); assert(0); return NULL; } //_________________________________________________________________________________________________ Inst * IRManager::newMemMovSequence(Opnd * targetOpnd, Opnd * sourceOpnd, U_32 regUsageMask, bool checkSource) { Inst * instList=NULL; RegName tmpRegName=RegName_Null, unusedTmpRegName=RegName_Null; bool registerSetNotLocked = !isRegisterSetLocked(OpndKind_GPReg); #ifdef _EM64T_ for (U_32 reg = RegName_RAX; reg<=RegName_R15/*(U_32)(targetOpnd->getSize()<OpndSize_64?RegName_RBX:RegName_RDI)*/; reg++) { #else for (U_32 reg = RegName_EAX; reg<=(U_32)(targetOpnd->getSize()<OpndSize_32?RegName_EBX:RegName_EDI); reg++) { #endif RegName regName = (RegName) reg; if (regName == STACK_REG) continue; Opnd * subOpnd = targetOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Base); if(subOpnd && subOpnd->isPlacedIn(regName)) continue; subOpnd = targetOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Index); if(subOpnd && subOpnd->isPlacedIn(regName)) continue; if (checkSource){ subOpnd = sourceOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Base); if(subOpnd && subOpnd->isPlacedIn(regName)) continue; subOpnd = sourceOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Index); if(subOpnd && subOpnd->isPlacedIn(regName)) continue; } tmpRegName=regName; if (registerSetNotLocked || (getRegMask(tmpRegName)&regUsageMask)==0){ unusedTmpRegName=tmpRegName; break; } } assert(tmpRegName!=RegName_Null); Opnd * tmp=getRegOpnd(tmpRegName); Opnd * tmpAdjusted=newRegOpnd(targetOpnd->getType(), tmpRegName); Opnd * tmpRegStackOpnd = newMemOpnd(tmp->getType(), MemOpndKind_StackAutoLayout, getRegOpnd(STACK_REG), 0); if (unusedTmpRegName==RegName_Null) appendToInstList(instList, newInst(Mnemonic_MOV, tmpRegStackOpnd, tmp)); appendToInstList(instList, newInst(Mnemonic_MOV, tmpAdjusted, sourceOpnd)); // must satisfy constraints appendToInstList(instList, newInst(Mnemonic_MOV, targetOpnd, tmpAdjusted)); // must satisfy constraints if (unusedTmpRegName==RegName_Null) appendToInstList(instList, newInst(Mnemonic_MOV, tmp, tmpRegStackOpnd)); return instList; } //_________________________________________________________________________________________________ Inst * IRManager::newCopySequence(Opnd * targetBOpnd, Opnd * sourceBOpnd, U_32 regUsageMask, U_32 flagsRegUsageMask) { Opnd * targetOpnd=(Opnd*)targetBOpnd, * sourceOpnd=(Opnd*)sourceBOpnd; Constraint targetConstraint = targetOpnd->getConstraint(Opnd::ConstraintKind_Location); Constraint sourceConstraint = sourceOpnd->getConstraint(Opnd::ConstraintKind_Location); if (targetConstraint.isNull() || sourceConstraint.isNull()){ return newCopyPseudoInst(Mnemonic_MOV, targetOpnd, sourceOpnd); } OpndSize sourceSize=sourceConstraint.getSize(); U_32 sourceByteSize=getByteSize(sourceSize); OpndKind targetKind=(OpndKind)targetConstraint.getKind(); OpndKind sourceKind=(OpndKind)sourceConstraint.getKind(); #if defined(_DEBUG) || !defined(_EM64T_) OpndSize targetSize=targetConstraint.getSize(); assert(targetSize<=sourceSize); // only same size or truncating conversions are allowed #endif if (targetKind&OpndKind_Reg) { if(sourceOpnd->isPlacedIn(OpndKind_Imm) && sourceOpnd->getImmValue()==0 && targetKind==OpndKind_GPReg && !sourceOpnd->getRuntimeInfo() && !(getRegMask(RegName_EFLAGS)&flagsRegUsageMask)) { return newInst(Mnemonic_XOR,targetOpnd, targetOpnd); } else if (targetKind==OpndKind_XMMReg && sourceOpnd->getMemOpndKind()==MemOpndKind_ConstantArea) { #ifdef _EM64T_ Opnd * addr = NULL; Opnd * base = sourceOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Base); if(base) { Inst * defInst = base->getDefiningInst(); if(defInst && defInst->getMnemonic() == Mnemonic_MOV) { addr = defInst->getOpnd(1); if(!addr->getRuntimeInfo()) { // addr opnd may be spilled. Let's try deeper defInst = addr->getDefiningInst(); if(defInst && defInst->getMnemonic() == Mnemonic_MOV) { addr = defInst->getOpnd(1); } else { addr = NULL; } } } } #else Opnd * addr = sourceOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Displacement); #endif Opnd::RuntimeInfo* addrRI = addr == NULL ? NULL : addr->getRuntimeInfo(); if( addrRI && addrRI->getKind()==Opnd::RuntimeInfo::Kind_ConstantAreaItem) { void * fpPtr = (void *)((ConstantAreaItem *)addrRI->getValue(0))->getValue(); if (sourceByteSize==4) { float val = *(float *)fpPtr; if(val == 0 && !signbit(val)) { return newInst(Mnemonic_XORPS,targetOpnd, targetOpnd); } }else if (sourceByteSize==8) { double val = *(double *)fpPtr; if(val == 0 && !signbit(val)) { return newInst(Mnemonic_XORPD,targetOpnd, targetOpnd); } } } } } if ( (targetKind==OpndKind_GPReg||targetKind==OpndKind_Mem) && (sourceKind==OpndKind_GPReg||sourceKind==OpndKind_Mem||sourceKind==OpndKind_Imm) ){ if (sourceKind==OpndKind_Mem && targetKind==OpndKind_Mem){ Inst * instList=NULL; #ifndef _EM64T_ U_32 targetByteSize=getByteSize(targetSize); if (sourceByteSize<=4){ instList=newMemMovSequence(targetOpnd, sourceOpnd, regUsageMask); }else{ Opnd * targetOpnds[IRMaxOperandByteSize/4]; // limitation because we are currently don't support large memory operands U_32 targetOpndCount = 0; for (U_32 cb=0; cb<sourceByteSize && cb<targetByteSize; cb+=4) targetOpnds[targetOpndCount++] = newOpnd(typeManager.getInt32Type()); AliasPseudoInst * targetAliasInst=newAliasPseudoInst(targetOpnd, targetOpndCount, targetOpnds); layoutAliasPseudoInstOpnds(targetAliasInst); for (U_32 cb=0, targetOpndSlotIndex=0; cb<sourceByteSize && cb<targetByteSize; cb+=4, targetOpndSlotIndex++){ Opnd * sourceOpndSlot=newOpnd(typeManager.getInt32Type()); appendToInstList(instList, newAliasPseudoInst(sourceOpndSlot, sourceOpnd, cb)); Opnd * targetOpndSlot=targetOpnds[targetOpndSlotIndex]; appendToInstList(instList, newMemMovSequence(targetOpndSlot, sourceOpndSlot, regUsageMask, true)); } appendToInstList(instList, targetAliasInst); } #else instList=newMemMovSequence(targetOpnd, sourceOpnd, regUsageMask); #endif assert(instList!=NULL); return instList; }else{ #ifdef _EM64T_ if((targetOpnd->getMemOpndKind() == MemOpndKind_StackAutoLayout) && (sourceKind==OpndKind_Imm) && (sourceOpnd->getSize() == OpndSize_64)) return newMemMovSequence(targetOpnd, sourceOpnd, regUsageMask, false); else #else assert(sourceByteSize<=4); #endif return newInst(Mnemonic_MOV, targetOpnd, sourceOpnd); // must satisfy constraints } }else if ( (targetKind==OpndKind_XMMReg||targetKind==OpndKind_Mem) && (sourceKind==OpndKind_XMMReg||sourceKind==OpndKind_Mem) ){ targetOpnd->setMemOpndAlignment(Opnd::MemOpndAlignment_16); sourceOpnd->setMemOpndAlignment(Opnd::MemOpndAlignment_16); if (sourceByteSize==4){ return newInst(Mnemonic_MOVSS,targetOpnd, sourceOpnd); }else if (sourceByteSize==8){ bool regsOnly = targetKind==OpndKind_XMMReg && sourceKind==OpndKind_XMMReg; if (regsOnly && CPUID::isSSE2Supported()) { return newInst(Mnemonic_MOVAPD, targetOpnd, sourceOpnd); } else { return newInst(Mnemonic_MOVSD, targetOpnd, sourceOpnd); } } }else if (targetKind==OpndKind_FPReg && sourceKind==OpndKind_Mem){ sourceOpnd->setMemOpndAlignment(Opnd::MemOpndAlignment_16); return newInst(Mnemonic_FLD, targetOpnd, sourceOpnd); }else if (targetKind==OpndKind_Mem && sourceKind==OpndKind_FPReg){ targetOpnd->setMemOpndAlignment(Opnd::MemOpndAlignment_16); return newInst(Mnemonic_FSTP, targetOpnd, sourceOpnd); }else if (targetKind==OpndKind_XMMReg && (sourceKind==OpndKind_Mem || sourceKind==OpndKind_GPReg)){ if (sourceKind==OpndKind_Mem) sourceOpnd->setMemOpndAlignment(Opnd::MemOpndAlignment_16); return newInst(Mnemonic_MOVD, targetOpnd, sourceOpnd); }else if ((targetKind==OpndKind_Mem || targetKind==OpndKind_GPReg) && sourceKind==OpndKind_XMMReg){ if (targetKind==OpndKind_Mem) targetOpnd->setMemOpndAlignment(Opnd::MemOpndAlignment_16); return newInst(Mnemonic_MOVD, targetOpnd, sourceOpnd); }else if ( (targetKind==OpndKind_FPReg && sourceKind==OpndKind_XMMReg)|| (targetKind==OpndKind_XMMReg && sourceKind==OpndKind_FPReg) ){ Inst * instList=NULL; Opnd * tmp = newMemOpnd(targetOpnd->getType(), MemOpndKind_StackAutoLayout, getRegOpnd(STACK_REG), 0); tmp->setMemOpndAlignment(Opnd::MemOpndAlignment_16); appendToInstList(instList, newCopySequence(tmp, sourceOpnd, regUsageMask)); appendToInstList(instList, newCopySequence(targetOpnd, tmp, regUsageMask)); return instList; } assert(0); return NULL; } //_________________________________________________________________________________________________ Inst * IRManager::newPushPopSequence(Mnemonic mn, Opnd * opnd, U_32 regUsageMask) { assert(opnd!=NULL); Constraint constraint = opnd->getConstraint(Opnd::ConstraintKind_Location); if (constraint.isNull()) return newCopyPseudoInst(mn, opnd); OpndKind kind=(OpndKind)constraint.getKind(); OpndSize size=constraint.getSize(); Inst * instList=NULL; #ifdef _EM64T_ if ( ((kind==OpndKind_GPReg ||kind==OpndKind_Mem)&& size!=OpndSize_32)||(kind==OpndKind_Imm && size<OpndSize_32)){ return newInst(mn, opnd); #else if ( kind==OpndKind_GPReg||kind==OpndKind_Mem||kind==OpndKind_Imm ){ if (size==OpndSize_32){ return newInst(mn, opnd); }else if (size<OpndSize_32){ }else if (size==OpndSize_64){ if (mn==Mnemonic_PUSH){ Opnd * opndLo=newOpnd(typeManager.getUInt32Type()); appendToInstList(instList, newAliasPseudoInst(opndLo, opnd, 0)); Opnd * opndHi=newOpnd(typeManager.getIntPtrType()); appendToInstList(instList, newAliasPseudoInst(opndHi, opnd, 4)); appendToInstList(instList, newInst(Mnemonic_PUSH, opndHi)); appendToInstList(instList, newInst(Mnemonic_PUSH, opndLo)); }else{ Opnd * opnds[2]={ newOpnd(typeManager.getUInt32Type()), newOpnd(typeManager.getInt32Type()) }; appendToInstList(instList, newInst(Mnemonic_POP, opnds[0])); appendToInstList(instList, newInst(Mnemonic_POP, opnds[1])); appendToInstList(instList, newAliasPseudoInst(opnd, 2, opnds)); } return instList; } #endif } Opnd * espOpnd=getRegOpnd(STACK_REG); Opnd * tmp=newMemOpnd(opnd->getType(), MemOpndKind_StackManualLayout, espOpnd, 0); #ifdef _EM64T_ Opnd * sizeOpnd=newImmOpnd(typeManager.getInt32Type(), sizeof(POINTER_SIZE_INT)); if(kind==OpndKind_Imm) { assert(mn==Mnemonic_PUSH); appendToInstList(instList, newInst(Mnemonic_SUB, espOpnd, sizeOpnd)); appendToInstList(instList, newMemMovSequence(tmp, opnd, regUsageMask)); } else if (kind == OpndKind_GPReg){ assert(mn==Mnemonic_PUSH); appendToInstList(instList, newInst(Mnemonic_SUB, espOpnd, sizeOpnd)); appendToInstList(instList, newInst(Mnemonic_MOV, tmp, opnd)); } else { if (mn==Mnemonic_PUSH){ appendToInstList(instList, newInst(Mnemonic_SUB, espOpnd, sizeOpnd)); appendToInstList(instList, newCopySequence(tmp, opnd, regUsageMask)); }else{ appendToInstList(instList, newCopySequence(opnd, tmp, regUsageMask)); appendToInstList(instList, newInst(Mnemonic_ADD, espOpnd, sizeOpnd)); } } #else U_32 cb=getByteSize(size); U_32 slotSize=4; cb=(cb+slotSize-1)&~(slotSize-1); Opnd * sizeOpnd=newImmOpnd(typeManager.getInt32Type(), cb); if (mn==Mnemonic_PUSH){ appendToInstList(instList, newInst(Mnemonic_SUB, espOpnd, sizeOpnd)); appendToInstList(instList, newCopySequence(tmp, opnd, regUsageMask)); }else{ appendToInstList(instList, newCopySequence(opnd, tmp, regUsageMask)); appendToInstList(instList, newInst(Mnemonic_ADD, espOpnd, sizeOpnd)); } #endif return instList; } //_________________________________________________________________________________________________ const CallingConvention * IRManager::getCallingConvention(VM_RT_SUPPORT helperId)const { HELPER_CALLING_CONVENTION callConv = compilationInterface.getRuntimeHelperCallingConvention(helperId); switch (callConv){ case CALLING_CONVENTION_DRL: return &CallingConvention_Managed; case CALLING_CONVENTION_STDCALL: return &CallingConvention_STDCALL; case CALLING_CONVENTION_CDECL: return &CallingConvention_CDECL; case CALLING_CONVENTION_MULTIARRAY: return &CallingConvention_MultiArray; default: assert(0); return NULL; } } //_________________________________________________________________________________________________ const CallingConvention * IRManager::getCallingConvention(MethodDesc * methodDesc)const { return &CallingConvention_Managed; } //_________________________________________________________________________________________________ Opnd * IRManager::defArg(Type * type, U_32 position) { assert(NULL != entryPointInst); Opnd * opnd=newOpnd(type); entryPointInst->insertOpnd(position, opnd, Inst::OpndRole_Auxilary|Inst::OpndRole_Def); entryPointInst->callingConventionClient.pushInfo(Inst::OpndRole_Def, type->tag); return opnd; } //_________________________________________________________________________________________________ Opnd * IRManager::getRegOpnd(RegName regName) { assert(getRegSize(regName)==Constraint::getDefaultSize(getRegKind(regName))); // are we going to change this? U_32 idx=( (getRegKind(regName) & 0x1f) << 4 ) | ( getRegIndex(regName)&0xf ); if (!regOpnds[idx]){ #ifdef _EM64T_ Type * t = (getRegSize(regName) == OpndSize_64 ? typeManager.getUInt64Type() : typeManager.getUInt32Type()); regOpnds[idx]=newRegOpnd(t, regName); #else regOpnds[idx]=newRegOpnd(typeManager.getUInt32Type(), regName); #endif } return regOpnds[idx]; } void IRManager::calculateTotalRegUsage(OpndKind regKind) { assert(regKind == OpndKind_GPReg); U_32 opndCount=getOpndCount(); for (U_32 i=0; i<opndCount; i++){ Opnd * opnd=getOpnd(i); if (opnd->isPlacedIn(regKind)) { RegName reg = opnd->getRegName(); unsigned mask = getRegMask(reg); #if !defined(_EM64T_) if ((reg == RegName_AH) || (reg == RegName_CH) || (reg == RegName_DH) || (reg == RegName_BH)) mask >>= 4; #endif gpTotalRegUsage |= mask; } } } //_________________________________________________________________________________________________ U_32 IRManager::getTotalRegUsage(OpndKind regKind)const { return gpTotalRegUsage; } //_________________________________________________________________________________________________ bool IRManager::isPreallocatedRegOpnd(Opnd * opnd) { RegName regName=opnd->getRegName(); if (regName==RegName_Null || getRegSize(regName)!=Constraint::getDefaultSize(getRegKind(regName))) return false; U_32 idx=( (getRegKind(regName) & 0x1f) << 4 ) | ( getRegIndex(regName)&0xf ); return regOpnds[idx]==opnd; } //_______________________________________________________________________________________________________________ Type * IRManager::getManagedPtrType(Type * sourceType) { return typeManager.getManagedPtrType(sourceType); } //_________________________________________________________________________________________________ Type * IRManager::getTypeFromTag(Type::Tag tag)const { switch (tag) { case Type::Void: case Type::Tau: case Type::Int8: case Type::Int16: case Type::Int32: case Type::IntPtr: case Type::Int64: case Type::UInt8: case Type::UInt16: case Type::UInt32: case Type::UInt64: case Type::Single: case Type::Double: case Type::Boolean: case Type::Float: return typeManager.getPrimitiveType(tag); default: return new(memoryManager) Type(tag); } } //_____________________________________________________________________________________________ OpndSize IRManager::getTypeSize(Type::Tag tag) { OpndSize size; switch (tag) { case Type::Int8: case Type::UInt8: case Type::Boolean: size = OpndSize_8; break; case Type::Int16: case Type::UInt16: case Type::Char: size = OpndSize_16; break; #ifndef _EM64T_ case Type::IntPtr: case Type::UIntPtr: #endif case Type::Int32: case Type::UInt32: size = OpndSize_32; break; #ifdef _EM64T_ case Type::IntPtr: case Type::UIntPtr: #endif case Type::Int64: case Type::UInt64: size = OpndSize_64; break; case Type::Single: size = OpndSize_32; break; case Type::Double: size = OpndSize_64; break; case Type::Float: size = OpndSize_80; break; default: #ifdef _EM64T_ size = (tag>=Type::CompressedSystemObject && tag<=Type::CompressedVTablePtr)?OpndSize_32:OpndSize_64; #else size = OpndSize_32; #endif break; } return size; } //_____________________________________________________________________________________________ void IRManager::indexInsts() { const Nodes& postOrder = fg->getNodesPostOrder(); U_32 idx=0; for (Nodes::const_reverse_iterator it = postOrder.rbegin(), end = postOrder.rend(); it!=end; ++it) { Node* node = *it; if (node->isBlockNode()){ for (Inst* inst = (Inst*)node->getFirstInst(); inst!=NULL; inst = inst->getNextInst()) { inst->index=idx++; } } } } //_____________________________________________________________________________________________ U_32 IRManager::calculateOpndStatistics(bool reindex) { POpnd * arr=&opnds.front(); for (U_32 i=0, n=(U_32)opnds.size(); i<n; i++){ Opnd * opnd=arr[i]; if (opnd==NULL) { continue; } opnd->defScope=Opnd::DefScope_Temporary; opnd->definingInst=NULL; opnd->refCount=0; if (reindex) { opnd->id=EmptyUint32; } } U_32 index=0; U_32 instIdx=0; const Nodes& nodes = fg->getNodesPostOrder(); for (Nodes::const_reverse_iterator it = nodes.rbegin(), end = nodes.rend(); it!=end; ++it) { Node* node = *it; if (!node->isBlockNode()) { continue; } I_32 execCount=1;//(I_32)node->getExecCount()*100; for (Inst * inst=(Inst*)node->getFirstInst(); inst!=NULL; inst=inst->getNextInst()){ inst->index=instIdx++; for (U_32 i=0, n=inst->getOpndCount(Inst::OpndRole_InstLevel|Inst::OpndRole_UseDef); i<n; i++){ Opnd * opnd=inst->getOpnd(i); opnd->addRefCount(index, execCount); if ((inst->getOpndRoles(i)&Inst::OpndRole_Def)!=0){ opnd->setDefiningInst(inst); } } } } for (U_32 i=0; i<IRMaxRegNames; i++){ // update predefined regOpnds to prevent losing them from the ID space if (regOpnds[i]!=NULL) { regOpnds[i]->addRefCount(index, 1); } } return index; } //_____________________________________________________________________________________________ void IRManager::packOpnds() { static CountTime packOpndsTimer("ia32::packOpnds"); AutoTimer tm(packOpndsTimer); _hasLivenessInfo=false; U_32 maxIndex=calculateOpndStatistics(true); U_32 opndsBefore=(U_32)opnds.size(); opnds.resize(opnds.size()+maxIndex); POpnd * arr=&opnds.front(); for (U_32 i=0; i<opndsBefore; i++){ Opnd * opnd=arr[i]; if (opnd->id!=EmptyUint32) arr[opndsBefore+opnd->id]=opnd; } opnds.erase(opnds.begin(), opnds.begin()+opndsBefore); _hasLivenessInfo=false; } //_____________________________________________________________________________________________ void IRManager::fixLivenessInfo( U_32 * map ) { U_32 opndCount = getOpndCount(); const Nodes& nodes = fg->getNodes(); for (Nodes::const_iterator it = nodes.begin(), end = nodes.end(); it!=end; ++it) { CGNode* node = (CGNode*)*it; BitSet * ls = node->getLiveAtEntry(); ls->resize(opndCount); } } //_____________________________________________________________________________________________ void IRManager::calculateLivenessInfo() { static CountTime livenessTimer("ia32::liveness"); AutoTimer tm(livenessTimer); _hasLivenessInfo=false; LoopTree* lt = fg->getLoopTree(); lt->rebuild(false); const U_32 opndCount = getOpndCount(); const Nodes& nodes = fg->getNodesPostOrder(); //clean all prev. liveness info for (Nodes::const_iterator it = nodes.begin(),end = nodes.end();it!=end; ++it) { CGNode* node = (CGNode*)*it; node->getLiveAtEntry()->resizeClear(opndCount); } U_32 loopDepth = lt->getMaxLoopDepth(); U_32 nIterations = loopDepth + 1; #ifdef _DEBUG nIterations++; //one more extra iteration to prove that nothing changed #endif BitSet tmpLs(memoryManager, opndCount); bool changed = true; Node* exitNode = fg->getExitNode(); for (U_32 iteration=0; iteration < nIterations; iteration++) { changed = false; for (Nodes::const_iterator it = nodes.begin(),end = nodes.end();it!=end; ++it) { CGNode* node = (CGNode*)*it; if (node == exitNode) { if (!methodDesc.isStatic() && (methodDesc.isSynchronized() || methodDesc.isParentClassIsLikelyExceptionType())) { BitSet * exitLs = node->getLiveAtEntry(); EntryPointPseudoInst * entryPointInst = getEntryPointInst(); #ifdef _EM64T_ Opnd * thisOpnd = entryPointInst->thisOpnd; //on EM64T 'this' opnd is spilled to stack only after finalizeCallSites call (copy expansion pass) //TODO: do it after code selector and tune early propagation and regalloc to skip this opnd from optimizations. if (thisOpnd == NULL) continue; #else Opnd * thisOpnd = entryPointInst->getOpnd(0); #endif exitLs->setBit(thisOpnd->getId(), true); } continue; } bool processNode = true; if (iteration > 0) { U_32 depth = lt->getLoopDepth(node); processNode = iteration <= depth; #ifdef _DEBUG processNode = processNode || iteration == nIterations-1; //last iteration will check all blocks #endif } if (processNode) { getLiveAtExit(node, tmpLs); if (node->isBlockNode()){ for (Inst * inst=(Inst*)node->getLastInst(); inst!=NULL; inst=inst->getPrevInst()){ updateLiveness(inst, tmpLs); } } BitSet * ls = node->getLiveAtEntry(); if (iteration == 0 || !ls->isEqual(tmpLs)) { changed = true; ls->copyFrom(tmpLs); } } } if (!changed) { break; } } #ifdef _DEBUG assert(!changed); #endif _hasLivenessInfo=true; } //_____________________________________________________________________________________________ bool IRManager::ensureLivenessInfoIsValid() { return true; } //_____________________________________________________________________________________________ void IRManager::getLiveAtExit(const Node * node, BitSet & ls) const { assert(ls.getSetSize()<=getOpndCount()); const Edges& edges=node->getOutEdges(); U_32 i=0; for (Edges::const_iterator ite = edges.begin(), ende = edges.end(); ite!=ende; ++ite, ++i) { Edge* edge = *ite; CGNode * succ=(CGNode*)edge->getTargetNode(); const BitSet * succLs=succ->getLiveAtEntry(); if (i==0) { ls.copyFrom(*succLs); } else { ls.unionWith(*succLs); } } } //_____________________________________________________________________________________________ void IRManager::updateLiveness(const Inst * inst, BitSet & ls) const { const Opnd * const * opnds = inst->getOpnds(); U_32 opndCount = inst->getOpndCount(); for (U_32 i = 0; i < opndCount; i++){ const Opnd * opnd = opnds[i]; U_32 id = opnd->getId(); if (inst->isLiveRangeEnd(i)) ls.setBit(id, false); else if (inst->isLiveRangeStart(i)) ls.setBit(id, true); } for (U_32 i = 0; i < opndCount; i++){ const Opnd * opnd = opnds[i]; if (opnd->getMemOpndKind() != MemOpndKind_Null){ const Opnd * const * subOpnds = opnd->getMemOpndSubOpnds(); for (U_32 j = 0; j < MemOpndSubOpndKind_Count; j++){ const Opnd * subOpnd = subOpnds[j]; if (subOpnd != NULL && subOpnd->isSubjectForLivenessAnalysis()) ls.setBit(subOpnd->getId(), true); } } } } //_____________________________________________________________________________________________ U_32 IRManager::getRegUsageFromLiveSet(BitSet * ls, OpndKind regKind)const { assert(ls->getSetSize()<=getOpndCount()); U_32 mask=0; BitSet::IterB ib(*ls); for (int i = ib.getNext(); i != -1; i = ib.getNext()){ Opnd * opnd=getOpnd(i); if (opnd->isPlacedIn(regKind)) mask |= getRegMask(opnd->getRegName()); } return mask; } //_____________________________________________________________________________________________ void IRManager::getRegUsageAtExit(const Node * node, OpndKind regKind, U_32 & mask)const { assert(node->isBlockNode()); const Edges& edges=node->getOutEdges(); mask=0; for (Edges::const_iterator ite = edges.begin(), ende = edges.end(); ite!=ende; ++ite) { Edge* edge = *ite; mask |= getRegUsageAtEntry(edge->getTargetNode(), regKind); } } //_____________________________________________________________________________________________ void IRManager::updateRegUsage(const Inst * inst, OpndKind regKind, U_32 & mask)const { Inst::Opnds opnds(inst, Inst::OpndRole_All); for (Inst::Opnds::iterator it = opnds.begin(); it != opnds.end(); it = opnds.next(it)){ Opnd * opnd=inst->getOpnd(it); if (opnd->isPlacedIn(regKind)){ U_32 m=getRegMask(opnd->getRegName()); if (inst->isLiveRangeEnd(it)) mask &= ~m; else if (inst->isLiveRangeStart(it)) mask |= m; } } } //_____________________________________________________________________________________________ void IRManager::resetOpndConstraints() { for (U_32 i=0, n=getOpndCount(); i<n; i++){ Opnd * opnd=getOpnd(i); opnd->setCalculatedConstraint(opnd->getConstraint(Opnd::ConstraintKind_Initial)); } } void IRManager::finalizeCallSites() { #ifdef _EM64T_ MethodDesc& md = getMethodDesc(); if (!md.isStatic() && (md.isSynchronized() || md.isParentClassIsLikelyExceptionType())) { Type* thisType = entryPointInst->getOpnd(0)->getType(); entryPointInst->thisOpnd = newMemOpnd(thisType, MemOpndKind_StackAutoLayout, getRegOpnd(STACK_REG), 0); entryPointInst->getBasicBlock()->appendInst(newCopyPseudoInst(Mnemonic_MOV, entryPointInst->thisOpnd, entryPointInst->getOpnd(0))); } #endif const Nodes& nodes = fg->getNodes(); for (Nodes::const_iterator it = nodes.begin(), end = nodes.end(); it != end; ++it) { Node* node = *it; if (node->isBlockNode()) { for (Inst * inst = (Inst*)node->getLastInst(), * prevInst = NULL; inst != NULL; inst = prevInst) { prevInst = inst->getPrevInst(); if (inst->getMnemonic() == Mnemonic_CALL) { const CallInst * callInst = (const CallInst*)inst; const CallingConvention * cc = callInst->getCallingConventionClient().getCallingConvention(); const StlVector<CallingConventionClient::StackOpndInfo>& stackOpndInfos = callInst->getCallingConventionClient().getStackOpndInfos(Inst::OpndRole_Use); Inst * instToPrepend = inst; Opnd * const * opnds = callInst->getOpnds(); unsigned shadowSize = 0; // Align stack. if (callInst->getArgStackDepthAlignment() > 0) { node->prependInst(newInst(Mnemonic_SUB, getRegOpnd(STACK_REG), newImmOpnd(typeManager.getInt32Type(), callInst->getArgStackDepthAlignment())), inst); } // Put inputs on the stack. for (U_32 i = 0, n = (U_32)stackOpndInfos.size(); i < n; i++) { Opnd* opnd = opnds[stackOpndInfos[i].opndIndex]; Inst * pushInst = newCopyPseudoInst(Mnemonic_PUSH, opnd); pushInst->insertBefore(instToPrepend); instToPrepend = pushInst; } #ifdef _WIN64 // Assert that shadow doesn't break stack alignment computed earlier. assert((shadowSize & (STACK_ALIGNMENT - 1)) == 0); Opnd::RuntimeInfo * rt = callInst->getRuntimeInfo(); //TODO (Low priority): Strictly speaking we should allocate shadow area for CDECL // calling convention. Currently it is used in one case only (see VM_RT_MULTIANEWARRAY_RESOLVED). // But this helper is not aware about shadow area. if (rt && cc == &CallingConvention_STDCALL) { // Stack size for parameters: "number of entries is equal to 4 or the maximum number of parameters" // See http://msdn2.microsoft.com/en-gb/library/ms794596.aspx for details. // Shadow - is an area on stack reserved to map parameters passed with registers. shadowSize = 4 * sizeof(POINTER_SIZE_INT); node->prependInst(newInst(Mnemonic_SUB, getRegOpnd(STACK_REG), newImmOpnd(typeManager.getInt32Type(), shadowSize)), inst); } #endif unsigned stackPopSize = cc->calleeRestoresStack() ? 0 : callInst->getArgStackDepth(); stackPopSize += shadowSize; // Restore stack pointer. if(stackPopSize != 0) { Inst* newIns = newInst(Mnemonic_ADD, getRegOpnd(STACK_REG), newImmOpnd(typeManager.getInt32Type(), stackPopSize)); newIns->insertAfter(inst); } } } } } } //_____________________________________________________________________________________________ U_32 IRManager::calculateStackDepth() { MemoryManager mm("calculateStackDepth"); StlVector<I_32> stackDepths(mm, fg->getNodeCount(), -1); I_32 maxMethodStackDepth = -1; const Nodes& nodes = fg->getNodesPostOrder(); //iterating in topological (reverse postorder) order for (Nodes::const_reverse_iterator itn = nodes.rbegin(), endn = nodes.rend(); itn!=endn; ++itn) { Node* node = *itn; if (node->isBlockNode() || (node->isDispatchNode() && node!=fg->getUnwindNode())) { I_32 stackDepth=-1; const Edges& edges=node->getInEdges(); for (Edges::const_iterator ite = edges.begin(), ende = edges.end(); ite!=ende; ++ite) { Edge* edge = *ite; Node * pred=edge->getSourceNode(); I_32 predStackDepth=stackDepths[pred->getDfNum()]; if (predStackDepth>=0){ assert(stackDepth==-1 || stackDepth==predStackDepth); stackDepth=predStackDepth; } } if (stackDepth<0) { stackDepth=0; } if (node->isBlockNode()){ for (Inst * inst=(Inst*)node->getFirstInst(); inst!=NULL; inst=inst->getNextInst()){ inst->setStackDepth(stackDepth); Inst::Opnds opnds(inst, Inst::OpndRole_Explicit | Inst::OpndRole_Auxilary | Inst::OpndRole_UseDef); Inst::Opnds::iterator it = opnds.begin(); if (it != opnds.end() && inst->getOpnd(it)->isPlacedIn(STACK_REG)) { if (inst->getMnemonic()==Mnemonic_ADD) stackDepth -= (I_32)inst->getOpnd(opnds.next(it))->getImmValue(); else if (inst->getMnemonic()==Mnemonic_SUB) stackDepth += (I_32)inst->getOpnd(opnds.next(it))->getImmValue(); else assert(0); }else{ if(inst->getMnemonic()==Mnemonic_PUSH) { stackDepth+=getByteSize(inst->getOpnd(it)->getSize()); } else if (inst->getMnemonic() == Mnemonic_POP) { stackDepth-=getByteSize(inst->getOpnd(it)->getSize()); } else if (inst->getMnemonic() == Mnemonic_PUSHFD) { stackDepth+=sizeof(POINTER_SIZE_INT); } else if (inst->getMnemonic() == Mnemonic_POPFD) { stackDepth-=sizeof(POINTER_SIZE_INT); } else if (inst->getMnemonic() == Mnemonic_CALL && ((CallInst *)inst)->getCallingConventionClient().getCallingConvention()->calleeRestoresStack()) { stackDepth -= ((CallInst *)inst)->getArgStackDepth(); } } maxMethodStackDepth = std::max(maxMethodStackDepth, stackDepth); } assert(stackDepth>=0); } stackDepths[node->getDfNum()]=stackDepth; } } assert(maxMethodStackDepth>=0); return (U_32)maxMethodStackDepth; } //_____________________________________________________________________________________________ bool IRManager::isOnlyPrologSuccessor(Node * bb) { Node * predBB = bb; for(; ; ) { if(predBB == fg->getEntryNode()) { return true; } if (predBB != bb && predBB->getOutDegree() > 1) { return false; } if (predBB->getInDegree() > 1) { return false; } predBB = predBB->getInEdges().front()->getSourceNode(); } } //_____________________________________________________________________________________________ void IRManager::expandSystemExceptions(U_32 reservedForFlags) { calculateOpndStatistics(); StlMap<Opnd *, POINTER_SIZE_INT> checkOpnds(getMemoryManager()); StlVector<Inst *> excInsts(memoryManager); const Nodes& nodes = fg->getNodes(); for (Nodes::const_iterator it = nodes.begin(), end = nodes.end(); it!=end; ++it) { Node* node = *it; if (node->isBlockNode()){ Inst * inst=(Inst*)node->getLastInst(); if (inst && inst->hasKind(Inst::Kind_SystemExceptionCheckPseudoInst)) { excInsts.push_back(inst); Node* dispatchNode = node->getExceptionEdgeTarget(); if (dispatchNode==NULL || dispatchNode==fg->getUnwindNode()) { checkOpnds[inst->getOpnd(0)] = ((SystemExceptionCheckPseudoInst*)inst)->checksThisOfInlinedMethod() ? (POINTER_SIZE_INT)-1: (POINTER_SIZE_INT)inst; } } if(checkOpnds.size() == 0) continue; for (inst=(Inst*)node->getFirstInst(); inst!=NULL; inst = inst->getNextInst()){ if (inst->getMnemonic() == Mnemonic_CALL && !inst->hasKind(Inst::Kind_SystemExceptionCheckPseudoInst) && ((CallInst *)inst)->isDirect()) { Opnd::RuntimeInfo * rt = inst->getOpnd(((ControlTransferInst*)inst)->getTargetOpndIndex())->getRuntimeInfo(); if(rt->getKind() == Opnd::RuntimeInfo::Kind_MethodDirectAddr && !((MethodDesc *)rt->getValue(0))->isStatic()) { Inst::Opnds opnds(inst, Inst::OpndRole_Auxilary | Inst::OpndRole_Use); for (Inst::Opnds::iterator it = opnds.begin(); it != opnds.end(); it = opnds.next(it)){ Opnd * opnd = inst->getOpnd(it); if(checkOpnds.find(opnd) != checkOpnds.end()) checkOpnds[opnd] = (POINTER_SIZE_INT)-1; } } } } } } for(StlVector<Inst *>::iterator it = excInsts.begin(); it != excInsts.end(); it++) { Inst * lastInst = *it; Node* bb = lastInst->getNode(); switch (((SystemExceptionCheckPseudoInst*)lastInst)->getExceptionId()){ case CompilationInterface::Exception_NullPointer: { Node* oldTarget = bb->getUnconditionalEdge()->getTargetNode(); //must exist Opnd * opnd = lastInst->getOpnd(0); Edge* dispatchEdge = bb->getExceptionEdge(); assert(dispatchEdge!=NULL); Node* dispatchNode= dispatchEdge->getTargetNode(); if ((dispatchNode!=fg->getUnwindNode()) ||(checkOpnds[opnd] == (POINTER_SIZE_INT)-1 #ifdef _EM64T_ ||!Type::isCompressedReference(opnd->getType()->tag) #endif )){ Node* throwBasicBlock = fg->createBlockNode(); ObjectType* excType = compilationInterface.findClassUsingBootstrapClassloader(NULL_POINTER_EXCEPTION); assert(lastInst->getBCOffset()!=ILLEGAL_BC_MAPPING_VALUE); throwException(excType, lastInst->getBCOffset(), throwBasicBlock); //Inst* throwInst = newRuntimeHelperCallInst(VM_RT_NULL_PTR_EXCEPTION, 0, NULL, NULL); //throwInst->setBCOffset(lastInst->getBCOffset()); //throwBasicBlock->appendInst(throwInst); int64 zero = 0; if( refsCompressed && opnd->getType()->isReference() ) { assert(!Type::isCompressedReference(opnd->getType()->tag)); zero = (int64)(POINTER_SIZE_INT)VMInterface::getHeapBase(); } Opnd* zeroOpnd = NULL; if((POINTER_SIZE_INT)zero == (U_32)zero) { // heap base fits into 32 bits zeroOpnd = newImmOpnd(opnd->getType(), zero); } else { // zero can not be an immediate at comparison Opnd* zeroImm = newImmOpnd(typeManager.getIntPtrType(), zero); zeroOpnd = newOpnd(opnd->getType()); Inst* copy = newCopyPseudoInst(Mnemonic_MOV, zeroOpnd, zeroImm); bb->appendInst(copy); copy->setBCOffset(lastInst->getBCOffset()); } Inst* cmpInst = newInst(Mnemonic_CMP, opnd, zeroOpnd); bb->appendInst(cmpInst); cmpInst->setBCOffset(lastInst->getBCOffset()); bb->appendInst(newBranchInst(Mnemonic_JZ, throwBasicBlock, oldTarget)); fg->addEdge(bb, throwBasicBlock, 0); assert(dispatchNode!=NULL); fg->addEdge(throwBasicBlock, dispatchNode, 1); if((checkOpnds[opnd] == (POINTER_SIZE_INT)-1) && (opnd->getDefScope() == Opnd::DefScope_Temporary) && isOnlyPrologSuccessor(bb)) { checkOpnds[opnd] = (POINTER_SIZE_INT)lastInst; } } else { //hardware exception handling if (bb->getFirstInst() == lastInst) { fg->removeEdge(dispatchEdge); } } break; } default: assert(0); } lastInst->unlink(); } } void IRManager::throwException(ObjectType* excType, uint16 bcOffset, Node* basicBlock){ assert(excType); #ifdef _EM64T_ bool lazy = false; #else bool lazy = true; #endif Inst* throwInst = NULL; assert(bcOffset!=ILLEGAL_BC_MAPPING_VALUE); if (lazy){ Opnd * helperOpnds[] = { // first parameter exception class newImmOpnd(typeManager.getUnmanagedPtrType(typeManager.getIntPtrType()), Opnd::RuntimeInfo::Kind_TypeRuntimeId, excType), // second is constructor method handle, 0 - means default constructor newImmOpnd(typeManager.getUnmanagedPtrType(typeManager.getIntPtrType()), 0) }; throwInst=newRuntimeHelperCallInst( VM_RT_THROW_LAZY, lengthof(helperOpnds), helperOpnds, NULL); } else { Opnd * helperOpnds1[] = { newImmOpnd(typeManager.getInt32Type(), Opnd::RuntimeInfo::Kind_Size, excType), newImmOpnd(typeManager.getUnmanagedPtrType(typeManager.getIntPtrType()), Opnd::RuntimeInfo::Kind_AllocationHandle, excType) }; Opnd * retOpnd=newOpnd(excType); CallInst * callInst=newRuntimeHelperCallInst( VM_RT_NEW_RESOLVED_USING_VTABLE_AND_SIZE, lengthof(helperOpnds1), helperOpnds1, retOpnd); callInst->setBCOffset(bcOffset); basicBlock->appendInst(callInst); MethodDesc* md = compilationInterface.resolveMethod( excType, DEFAUlT_COSTRUCTOR_NAME, DEFAUlT_COSTRUCTOR_DESCRIPTOR); Opnd * target = newImmOpnd(typeManager.getIntPtrType(), Opnd::RuntimeInfo::Kind_MethodDirectAddr, md); Opnd * helperOpnds2[] = { (Opnd*)retOpnd }; callInst=newCallInst(target, getDefaultManagedCallingConvention(), lengthof(helperOpnds2), helperOpnds2, NULL); callInst->setBCOffset(bcOffset); basicBlock->appendInst(callInst); Opnd * helperOpnds3[] = { (Opnd*)retOpnd }; throwInst=newRuntimeHelperCallInst( VM_RT_THROW, lengthof(helperOpnds3), helperOpnds3, NULL); } throwInst->setBCOffset(bcOffset); basicBlock->appendInst(throwInst); } //_____________________________________________________________________________________________ void IRManager::translateToNativeForm() { const Nodes& nodes = fg->getNodes(); for (Nodes::const_iterator it = nodes.begin(),end = nodes.end();it!=end; ++it) { Node* node = *it; if (node->isBlockNode()){ for (Inst * inst=(Inst*)node->getFirstInst(); inst!=NULL; inst=inst->getNextInst()){ if (inst->getForm()==Inst::Form_Extended) { inst->makeNative(this); } } } } } //_____________________________________________________________________________________________ void IRManager::eliminateSameOpndMoves() { const Nodes& nodes = fg->getNodes(); for (Nodes::const_iterator it = nodes.begin(),end = nodes.end();it!=end; ++it) { Node* node = *it; if (node->isBlockNode()){ for (Inst * inst=(Inst*)node->getFirstInst(), *nextInst=NULL; inst!=NULL; inst=nextInst){ nextInst=inst->getNextInst(); if (inst->getMnemonic()==Mnemonic_MOV && inst->getOpnd(0)==inst->getOpnd(1)) { inst->unlink(); } } } } } //_____________________________________________________________________________________________ void IRManager::resolveRuntimeInfo() { for (U_32 i=0, n=getOpndCount(); i<n; i++){ Opnd * opnd=getOpnd(i); resolveRuntimeInfo(opnd); } } void IRManager::resolveRuntimeInfo(Opnd* opnd) const { if (!opnd->isPlacedIn(OpndKind_Imm)) return; Opnd::RuntimeInfo * info=opnd->getRuntimeInfo(); if (info==NULL) return; int64 value=0; switch(info->getKind()){ case Opnd::RuntimeInfo::Kind_HelperAddress: /** The value of the operand is compilationInterface->getRuntimeHelperAddress */ value=(POINTER_SIZE_INT)compilationInterface.getRuntimeHelperAddress( (VM_RT_SUPPORT)(POINTER_SIZE_INT)info->getValue(0) ); assert(value!=0); break; case Opnd::RuntimeInfo::Kind_InternalHelperAddress: /** The value of the operand is irManager.getInternalHelperInfo((const char*)[0]).pfn */ value=(POINTER_SIZE_INT)getInternalHelperInfo((const char*)info->getValue(0))->pfn; assert(value!=0); break; case Opnd::RuntimeInfo::Kind_TypeRuntimeId: /* The value of the operand is [0]->ObjectType::getRuntimeIdentifier() */ value=(POINTER_SIZE_INT)((NamedType*)info->getValue(0))->getRuntimeIdentifier(); break; case Opnd::RuntimeInfo::Kind_MethodRuntimeId: value=(POINTER_SIZE_INT)((MethodDesc*)info->getValue(0))->getMethodHandle(); break; case Opnd::RuntimeInfo::Kind_AllocationHandle: /* The value of the operand is [0]->ObjectType::getAllocationHandle() */ value=(POINTER_SIZE_INT)((ObjectType*)info->getValue(0))->getAllocationHandle(); break; case Opnd::RuntimeInfo::Kind_StringDescription: /* [0] - Type * - the containing class, [1] - string token */ assert(0); break; case Opnd::RuntimeInfo::Kind_Size: /* The value of the operand is [0]->ObjectType::getObjectSize() */ value=(POINTER_SIZE_INT)((ObjectType*)info->getValue(0))->getObjectSize(); break; case Opnd::RuntimeInfo::Kind_StringAddress: /** The value of the operand is the address where the interned version of the string is stored*/ { MethodDesc* mDesc = (MethodDesc*)info->getValue(0); U_32 token = (U_32)(POINTER_SIZE_INT)info->getValue(1); value = (POINTER_SIZE_INT) compilationInterface.getStringInternAddr(mDesc,token); }break; case Opnd::RuntimeInfo::Kind_StaticFieldAddress: /** The value of the operand is [0]->FieldDesc::getAddress() */ value=(POINTER_SIZE_INT)((FieldDesc*)info->getValue(0))->getAddress(); break; case Opnd::RuntimeInfo::Kind_FieldOffset: /** The value of the operand is [0]->FieldDesc::getOffset() */ value=(POINTER_SIZE_INT)((FieldDesc*)info->getValue(0))->getOffset(); break; case Opnd::RuntimeInfo::Kind_VTableAddrOffset: /** The value of the operand is compilationInterface.getVTableOffset(), zero args */ value = (int64)VMInterface::getVTableOffset(); break; case Opnd::RuntimeInfo::Kind_VTableConstantAddr: /** The value of the operand is [0]->ObjectType::getVTable() */ value=(POINTER_SIZE_INT)((ObjectType*)info->getValue(0))->getVTable(); break; case Opnd::RuntimeInfo::Kind_MethodVtableSlotOffset: /** The value of the operand is [0]->MethodDesc::getOffset() */ value=(POINTER_SIZE_INT)((MethodDesc*)info->getValue(0))->getOffset(); break; case Opnd::RuntimeInfo::Kind_MethodIndirectAddr: /** The value of the operand is [0]->MethodDesc::getIndirectAddress() */ value=(POINTER_SIZE_INT)((MethodDesc*)info->getValue(0))->getIndirectAddress(); break; case Opnd::RuntimeInfo::Kind_MethodDirectAddr: /** The value of the operand is *[0]->MethodDesc::getIndirectAddress() */ value=*(POINTER_SIZE_INT*)((MethodDesc*)info->getValue(0))->getIndirectAddress(); break; case Opnd::RuntimeInfo::Kind_ConstantAreaItem: /** The value of the operand is address of constant pool item ((ConstantPoolItem*)[0])->getAddress() */ value=(POINTER_SIZE_INT)((ConstantAreaItem*)info->getValue(0))->getAddress(); break; case Opnd::RuntimeInfo::Kind_EM_ProfileAccessInterface: /** The value of the operand is a pointer to the EM_ProfileAccessInterface */ value=(POINTER_SIZE_INT)(getProfilingInterface()->getEMProfileAccessInterface()); break; case Opnd::RuntimeInfo::Kind_Method_Value_Profile_Handle: /** The value of the operand is Method_Profile_Handle for the value profile of the compiled method */ value=(POINTER_SIZE_INT)(getProfilingInterface()->getMethodProfileHandle(ProfileType_Value, getMethodDesc())); break; default: assert(0); } opnd->assignImmValue(value+info->getAdditionalOffset()); } //_____________________________________________________________________________________________ bool IRManager::verify() { if (!verifyOpnds()) return false; updateLivenessInfo(); if (!verifyLiveness()) return false; if (!verifyHeapAddressTypes()) return false; #ifdef _DEBUG //check unwind node; Node* unwind = fg->getUnwindNode(); Node* exit = fg->getExitNode(); assert(exit!=NULL); assert(unwind == NULL || (unwind->getOutDegree() == 1 && unwind->isConnectedTo(true, exit))); const Edges& exitInEdges = exit->getInEdges(); for (Edges::const_iterator ite = exitInEdges.begin(), ende = exitInEdges.end(); ite!=ende; ++ite) { Edge* edge = *ite; Node* source = edge->getSourceNode(); assert(source == unwind || source->isBlockNode()); } const Nodes& nodes = fg->getNodesPostOrder();//check only reachable nodes. for (Nodes::const_iterator it = nodes.begin(), end = nodes.end(); it!=end; ++it) { CGNode* node = (CGNode*)*it; node->verify(); } #endif return true; } //_____________________________________________________________________________________________ // // This routine checks that every memory heap operand is referenced by single instruction only. // // There are two kinds of operands - instruction-level, which are saved in Ia32::Inst structure, // and sub-operands (of instruction-level operands), which are saved in Ia32::Opnd structure. // Of course, not all instruction-level operands have sub-operands. // // With this design, it would be impossible to replace sub-operand in one instruction without // affecting all other instructions that reference the same instruction-level operand of which // the sub-operand is part of. // // For some codegen modules (SpillGen, ConstraintResolver) it is critically important to be able // to replace operand (Inst::replaceOpnd) in one instruction, without side-effect on all other // instruction. More specifically, only heap operands are manipulated in such way. // // NOTE // For some obscure reason, AliasPseudoInst violates this principle, but experiments show // that AliasPseudoInst can be ignored. Otherwise, massive errors from this instruction // make the check meanigless. // bool IRManager::verifyOpnds() const { bool ok = true; typedef StlVector<Inst*> InstList; // to register all instruction referenced an operand typedef StlVector<InstList*> OpndList; // one entry for each operand, instruction register or 0 const U_32 opnd_count = getOpndCount(); OpndList opnd_list(getMemoryManager(), opnd_count); // fixed size // Watch only MemOpndKind_Heap operands - all others are simply ignored. for (U_32 i = 0; i != opnd_count; ++i) { InstList* ilp = 0; if (getOpnd(i)->getMemOpndKind() == MemOpndKind_Heap) ilp = new (getMemoryManager()) InstList(getMemoryManager()); opnd_list[i] = ilp; } const Nodes& nodes = fg->getNodes(); for (Nodes::const_iterator nd = nodes.begin(), nd_end = nodes.end(); nd != nd_end; ++nd) { Node* node = *nd; if (node->isBlockNode()) { for (Inst* inst = (Inst*)node->getFirstInst(); inst != NULL; inst = inst->getNextInst()) if (!inst->hasKind(Inst::Kind_AliasPseudoInst)) { // Inspect instruction-level operand only (but all of them), ignore sub-operands. Inst::Opnds opnds(inst, Inst::OpndRole_InstLevel | Inst::OpndRole_UseDef); for (Inst::Opnds::iterator op = opnds.begin(), op_end = opnds.end(); op != op_end; op = opnds.next(op)) { Opnd* opnd = opnds.getOpnd(op); // If this is a watched operand, then register the instruction that referenced it. InstList* ilp = opnd_list.at(opnd->getId()); if (ilp != 0) ilp->push_back(inst); } } } } for (U_32 i = 0; i != opnd_count; ++i) { InstList* ilp = opnd_list.at(i); if (ilp != 0 && ilp->size() > 1) { // Error found ok = false; VERIFY_OUT("MemOpnd " << getOpnd(i) << " was referenced in the instructions:"); for (InstList::iterator it = ilp->begin(), end = ilp->end(); it != end; ++it) { Inst* inst = *it; VERIFY_OUT(" I" << inst->getId()); } VERIFY_OUT(std::endl); } } return ok; } //_____________________________________________________________________________________________ bool IRManager::verifyLiveness() { Node* prolog=fg->getEntryNode(); bool failed=false; BitSet * ls=getLiveAtEntry(prolog); assert(ls!=NULL); Constraint calleeSaveRegs=getCallingConvention()->getCalleeSavedRegs(OpndKind_GPReg); BitSet::IterB lives(*ls); for (int i = lives.getNext(); i != -1; i = lives.getNext()){ Opnd * opnd=getOpnd(i); assert(opnd!=NULL); if ( opnd->isSubjectForLivenessAnalysis() && (opnd->isPlacedIn(RegName_EFLAGS)||!isPreallocatedRegOpnd(opnd)) ){ VERIFY_OUT("Operand live at entry: " << opnd << ::std::endl); VERIFY_OUT("This means there is a use of the operand when it is not yet defined" << ::std::endl); failed=true; }; } if (failed) VERIFY_OUT(::std::endl << "Liveness verification failure" << ::std::endl); return !failed; } //_____________________________________________________________________________________________ bool IRManager::verifyHeapAddressTypes() { bool failed=false; for (U_32 i=0, n=getOpndCount(); i<n; i++){ Opnd * opnd = getOpnd(i); if (opnd->isPlacedIn(OpndKind_Mem) && opnd->getMemOpndKind()==MemOpndKind_Heap){ Opnd * properTypeSubOpnd=NULL; for (U_32 j=0; j<MemOpndSubOpndKind_Count; j++){ Opnd * subOpnd=opnd->getMemOpndSubOpnd((MemOpndSubOpndKind)j); if (subOpnd!=NULL){ Type * type=subOpnd->getType(); if (type->isManagedPtr() || type->isObject() || type->isMethodPtr() || type->isVTablePtr() || type->isUnmanagedPtr() #ifdef _EM64T_ || subOpnd->getRegName() == RegName_RSP/*SOE handler*/ #else || subOpnd->getRegName() == RegName_ESP/*SOE handler*/ #endif ){ if (properTypeSubOpnd!=NULL){ VERIFY_OUT("Heap operand " << opnd << " contains more than 1 sub-operands of type Object or ManagedPointer "<<::std::endl); VERIFY_OUT("Opnd 1: " << properTypeSubOpnd << ::std::endl); VERIFY_OUT("Opnd 2: " << subOpnd << ::std::endl); failed=true; break; } properTypeSubOpnd=subOpnd; } } } if (failed) break; if (properTypeSubOpnd==NULL){ VERIFY_OUT("Heap operand " << opnd << " contains no sub-operands of type Object or ManagedPointer "<<::std::endl); failed=true; break; } } } if (failed) VERIFY_OUT(::std::endl << "Heap address type verification failure" << ::std::endl); return !failed; } ControlFlowGraph* IRManager::createSubCFG(bool withReturn, bool withUnwind) { ControlFlowGraph* cfg = new (memoryManager) ControlFlowGraph(memoryManager, this); cfg->setEntryNode(cfg->createBlockNode()); cfg->setExitNode(cfg->createExitNode()); if (withReturn) { cfg->setReturnNode(cfg->createBlockNode()); cfg->addEdge(cfg->getReturnNode(), cfg->getExitNode(), 1); } if (withUnwind) { cfg->setUnwindNode(cfg->createDispatchNode()); cfg->addEdge(cfg->getUnwindNode(), cfg->getExitNode(), 1); } return cfg; } // factory method for ControlFlowGraph Node* IRManager::createNode(MemoryManager& mm, Node::Kind kind) { if (kind == Node::Kind_Block) { return new (mm) BasicBlock(mm, *this); } return new (mm) CGNode(mm, *this, kind); } // factory method for ControlFlowGraph Edge* IRManager::createEdge(MemoryManager& mm, Node::Kind srcKind, Node::Kind dstKind) { if (srcKind == Node::Kind_Dispatch && dstKind == Node::Kind_Block) { return new (mm) CatchEdge(); } return ControlFlowGraphFactory::createEdge(mm, srcKind, dstKind); } bool IRManager::isGCSafePoint(const Inst* inst) { if (inst->getMnemonic() == Mnemonic_CALL) { const CallInst* callInst = (const CallInst*)inst; Opnd::RuntimeInfo * rt = callInst->getRuntimeInfo(); bool isInternalHelper = rt && rt->getKind() == Opnd::RuntimeInfo::Kind_InternalHelperAddress; bool isNonGCVMHelper = false; if (!isInternalHelper) { CompilationInterface* ci = CompilationContext::getCurrentContext()->getVMCompilationInterface(); isNonGCVMHelper = rt && rt->getKind() == Opnd::RuntimeInfo::Kind_HelperAddress && !ci->mayBeInterruptible((VM_RT_SUPPORT)(POINTER_SIZE_INT)rt->getValue(0)); } bool isGCPoint = !isInternalHelper && !isNonGCVMHelper; return isGCPoint; } return false; } //============================================================================================= // class Ia32::SessionAction implementation //============================================================================================= void SessionAction::run() { irManager = &getIRManager(); stageId=Log::getStageId(); if (isLogEnabled(LogStream::IRDUMP)) Log::printStageBegin(log(LogStream::IRDUMP).out(), stageId, "IA32", getName(), getTagName()); U_32 needInfo=getNeedInfo(); if (needInfo & NeedInfo_LivenessInfo) irManager->updateLivenessInfo(); if (needInfo & NeedInfo_LoopInfo) irManager->updateLoopInfo(); runImpl(); U_32 sideEffects=getSideEffects(); if (sideEffects & SideEffect_InvalidatesLivenessInfo) irManager->invalidateLivenessInfo(); if (sideEffects & SideEffect_InvalidatesLoopInfo) irManager->invalidateLoopInfo(); debugOutput("after"); if (!verify()) crash("\nVerification failure after %s\n", getName()); if (isLogEnabled(LogStream::IRDUMP)) Log::printStageEnd(log(LogStream::IRDUMP).out(), stageId, "IA32", getName(), getTagName()); } U_32 SessionAction::getSideEffects()const { return ~(U_32)0; } U_32 SessionAction::getNeedInfo()const { return ~(U_32)0; } bool SessionAction::verify(bool force) { if (force || getVerificationLevel()>=2) return getIRManager().verify(); return true; } void SessionAction::dumpIR(const char * subKind1, const char * subKind2) { Ia32::dumpIR(irManager, stageId, "IA32 LIR CFG after ", getName(), getTagName(), subKind1, subKind2); } void SessionAction::printDot(const char * subKind1, const char * subKind2) { Ia32::printDot(irManager, stageId, "IA32 LIR CFG after ", getName(), getTagName(), subKind1, subKind2); } void SessionAction::debugOutput(const char * subKind) { if (!isIRDumpEnabled()) return; if (isLogEnabled(LogStream::IRDUMP)) { irManager->updateLoopInfo(); irManager->updateLivenessInfo(); if (isLogEnabled("irdump_verbose")) { dumpIR(subKind, "opnds"); dumpIR(subKind, "liveness"); } dumpIR(subKind); } if (isLogEnabled(LogStream::DOTDUMP)) { irManager->updateLoopInfo(); irManager->updateLivenessInfo(); printDot(subKind); printDot(subKind, "liveness"); } } void SessionAction::computeDominators(void) { ControlFlowGraph* cfg = irManager->getFlowGraph(); DominatorTree* dominatorTree = cfg->getDominatorTree(); if(dominatorTree != NULL && dominatorTree->isValid()) { // Already valid. return; } static CountTime computeDominatorsTimer("ia32::helper::computeDominators"); AutoTimer tm(computeDominatorsTimer); DominatorBuilder db; dominatorTree = db.computeDominators(irManager->getMemoryManager(), cfg,false,true); cfg->setDominatorTree(dominatorTree); } } //namespace Ia32 } //namespace Jitrino
105,085
32,887
/* This file is part of Nokia HEIF library * * Copyright (c) 2015-2021 Nokia Corporation and/or its subsidiary(-ies). All rights reserved. * * Contact: heif@nokia.com * * This software, including documentation, is protected by copyright controlled by Nokia Corporation and/ or its * subsidiaries. All rights are reserved. * * Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior * written consent of Nokia. */ #ifndef FREESPACEBOX_HPP #define FREESPACEBOX_HPP #include "bbox.hpp" #include "bitstream.hpp" class FreeSpaceBox : public Box { public: FreeSpaceBox(); ~FreeSpaceBox() override = default; /** * @brief setSize Set FreeSpaceBox size. * @param size FreeSpaceBox size in bytes. Must be 8 or more because of the box header size. * @return True if size was set successfully (size >= 8), false otherwise. */ bool setSize(std::uint32_t size); void writeBox(ISOBMFF::BitStream& bitstr) const override; void parseBox(ISOBMFF::BitStream& bitstr) override; }; #endif
1,087
347
#include <lug/Graphics/GltfLoader.hpp> #if defined(LUG_SYSTEM_ANDROID) #include <android/asset_manager.h> #include <lug/Window/Android/WindowImplAndroid.hpp> #include <lug/Window/Window.hpp> #endif #include <gltf2/Exceptions.hpp> #include <lug/System/Logger/Logger.hpp> #include <lug/Graphics/Builder/Scene.hpp> #include <lug/Graphics/Builder/Material.hpp> #include <lug/Graphics/Builder/Mesh.hpp> #include <lug/Graphics/Builder/Texture.hpp> #include <lug/Graphics/Scene/Scene.hpp> namespace lug { namespace Graphics { GltfLoader::GltfLoader(Renderer& renderer): Loader(renderer) {} static void* getBufferViewData(const gltf2::Asset& asset, const gltf2::Accessor& accessor) { const gltf2::BufferView& bufferView = asset.bufferViews[accessor.bufferView]; const gltf2::Buffer& buffer = asset.buffers[bufferView.buffer]; if (!buffer.data) { LUG_LOG.error("GltfLoader::createMesh Buffer data can't be null"); return nullptr; } // TODO(nokitoo): handle uri return buffer.data + bufferView.byteOffset + accessor.byteOffset; } static uint32_t getAttributeSize(const gltf2::Accessor& accessor) { uint32_t componentSize = 0; switch (accessor.componentType) { case gltf2::Accessor::ComponentType::Byte: componentSize = sizeof(char); break; case gltf2::Accessor::ComponentType::UnsignedByte: componentSize = sizeof(unsigned char); break; case gltf2::Accessor::ComponentType::Short: componentSize = sizeof(short); break; case gltf2::Accessor::ComponentType::UnsignedShort: componentSize = sizeof(unsigned short); break; case gltf2::Accessor::ComponentType::UnsignedInt: componentSize = sizeof(unsigned int); break; case gltf2::Accessor::ComponentType::Float: componentSize = sizeof(float); break; } // Mutliply the componentSize according to the type switch (accessor.type) { case gltf2::Accessor::Type::Scalar: return componentSize; case gltf2::Accessor::Type::Vec2: return componentSize * 2; case gltf2::Accessor::Type::Vec3: return componentSize * 3; case gltf2::Accessor::Type::Vec4: return componentSize * 4; case gltf2::Accessor::Type::Mat2: return componentSize * 4; case gltf2::Accessor::Type::Mat3: return componentSize * 9; case gltf2::Accessor::Type::Mat4: return componentSize * 16; } return componentSize; } Resource::SharedPtr<Render::Texture> GltfLoader::createTexture(Renderer& renderer, const gltf2::Asset& asset, GltfLoader::LoadedAssets& loadedAssets, int32_t index) { const gltf2::Texture& gltfTexture = asset.textures[index]; if (loadedAssets.textures[index]) { return loadedAssets.textures[index]; } Builder::Texture textureBuilder(renderer); if (gltfTexture.source != -1) { // TODO: Handle correctly the load with bufferView / uri data if (!textureBuilder.addLayer(asset.images[gltfTexture.source].uri)) { LUG_LOG.error("GltfLoader::createTexture: Can't load the texture \"{}\"", asset.images[gltfTexture.source].uri); return nullptr; } } if (gltfTexture.sampler != -1) { const gltf2::Sampler& sampler = asset.samplers[gltfTexture.sampler]; switch(sampler.magFilter) { case gltf2::Sampler::MagFilter::None: break; case gltf2::Sampler::MagFilter::Nearest: textureBuilder.setMagFilter(Render::Texture::Filter::Nearest); break; case gltf2::Sampler::MagFilter::Linear: textureBuilder.setMagFilter(Render::Texture::Filter::Linear); break; } switch(sampler.minFilter) { case gltf2::Sampler::MinFilter::None: break; case gltf2::Sampler::MinFilter::Nearest: textureBuilder.setMinFilter(Render::Texture::Filter::Nearest); break; case gltf2::Sampler::MinFilter::Linear: textureBuilder.setMinFilter(Render::Texture::Filter::Linear); break; case gltf2::Sampler::MinFilter::NearestMipMapNearest: textureBuilder.setMinFilter(Render::Texture::Filter::Nearest); textureBuilder.setMipMapFilter(Render::Texture::Filter::Nearest); break; case gltf2::Sampler::MinFilter::LinearMipMapNearest: textureBuilder.setMinFilter(Render::Texture::Filter::Linear); textureBuilder.setMipMapFilter(Render::Texture::Filter::Nearest); break; case gltf2::Sampler::MinFilter::NearestMipMapLinear: textureBuilder.setMinFilter(Render::Texture::Filter::Nearest); textureBuilder.setMipMapFilter(Render::Texture::Filter::Linear); break; case gltf2::Sampler::MinFilter::LinearMipMapLinear: textureBuilder.setMinFilter(Render::Texture::Filter::Linear); textureBuilder.setMipMapFilter(Render::Texture::Filter::Linear); break; } switch(sampler.wrapS) { case gltf2::Sampler::WrappingMode::ClampToEdge: textureBuilder.setWrapS(Render::Texture::WrappingMode::ClampToEdge); break; case gltf2::Sampler::WrappingMode::MirroredRepeat: textureBuilder.setWrapS(Render::Texture::WrappingMode::MirroredRepeat); break; case gltf2::Sampler::WrappingMode::Repeat: textureBuilder.setWrapS(Render::Texture::WrappingMode::Repeat); break; } switch(sampler.wrapT) { case gltf2::Sampler::WrappingMode::ClampToEdge: textureBuilder.setWrapT(Render::Texture::WrappingMode::ClampToEdge); break; case gltf2::Sampler::WrappingMode::MirroredRepeat: textureBuilder.setWrapT(Render::Texture::WrappingMode::MirroredRepeat); break; case gltf2::Sampler::WrappingMode::Repeat: textureBuilder.setWrapT(Render::Texture::WrappingMode::Repeat); break; } } loadedAssets.textures[index] = textureBuilder.build(); return loadedAssets.textures[index]; } Resource::SharedPtr<Render::Material> GltfLoader::createMaterial(Renderer& renderer, const gltf2::Asset& asset, GltfLoader::LoadedAssets& loadedAssets, int32_t index) { if (index == -1) { return createDefaultMaterial(renderer, loadedAssets); } if (loadedAssets.materials[index]) { return loadedAssets.materials[index]; } const gltf2::Material& gltfMaterial = asset.materials[index]; Builder::Material materialBuilder(renderer); materialBuilder.setName(gltfMaterial.name); materialBuilder.setBaseColorFactor({ gltfMaterial.pbr.baseColorFactor[0], gltfMaterial.pbr.baseColorFactor[1], gltfMaterial.pbr.baseColorFactor[2], gltfMaterial.pbr.baseColorFactor[3] }); if (gltfMaterial.pbr.baseColorTexture.index != -1) { Resource::SharedPtr<Render::Texture> texture = createTexture(renderer, asset, loadedAssets, gltfMaterial.pbr.baseColorTexture.index); if (!texture) { LUG_LOG.error("GltfLoader::createMaterial Can't create the texture resource"); return nullptr; } materialBuilder.setBaseColorTexture(texture, gltfMaterial.pbr.baseColorTexture.texCoord); } materialBuilder.setMetallicFactor(gltfMaterial.pbr.metallicFactor); materialBuilder.setRoughnessFactor(gltfMaterial.pbr.roughnessFactor); if (gltfMaterial.pbr.metallicRoughnessTexture.index != -1) { Resource::SharedPtr<Render::Texture> texture = createTexture(renderer, asset, loadedAssets, gltfMaterial.pbr.metallicRoughnessTexture.index); if (!texture) { LUG_LOG.error("GltfLoader::createMaterial Can't create the texture resource"); return nullptr; } materialBuilder.setMetallicRoughnessTexture(texture, gltfMaterial.pbr.metallicRoughnessTexture.texCoord); } if (gltfMaterial.normalTexture.index != -1) { Resource::SharedPtr<Render::Texture> texture = createTexture(renderer, asset, loadedAssets, gltfMaterial.normalTexture.index); if (!texture) { LUG_LOG.error("GltfLoader::createMaterial Can't create the texture resource"); return nullptr; } materialBuilder.setNormalTexture(texture, gltfMaterial.normalTexture.texCoord); } if (gltfMaterial.occlusionTexture.index != -1) { Resource::SharedPtr<Render::Texture> texture = createTexture(renderer, asset, loadedAssets, gltfMaterial.occlusionTexture.index); if (!texture) { LUG_LOG.error("GltfLoader::createMaterial Can't create the texture resource"); return nullptr; } materialBuilder.setOcclusionTexture(texture, gltfMaterial.occlusionTexture.texCoord); } if (gltfMaterial.emissiveTexture.index != -1) { Resource::SharedPtr<Render::Texture> texture = createTexture(renderer, asset, loadedAssets, gltfMaterial.emissiveTexture.index); if (!texture) { LUG_LOG.error("GltfLoader::createMaterial Can't create the texture resource"); return nullptr; } materialBuilder.setEmissiveTexture(texture, gltfMaterial.emissiveTexture.texCoord); } materialBuilder.setEmissiveFactor({ gltfMaterial.emissiveFactor[0], gltfMaterial.emissiveFactor[1], gltfMaterial.emissiveFactor[2] }); loadedAssets.materials[index] = materialBuilder.build(); return loadedAssets.materials[index]; } Resource::SharedPtr<Render::Material> GltfLoader::createDefaultMaterial(Renderer& renderer, GltfLoader::LoadedAssets& loadedAssets) { if (loadedAssets.defaultMaterial) { return loadedAssets.defaultMaterial; } Builder::Material materialBuilder(renderer); loadedAssets.defaultMaterial = materialBuilder.build(); return loadedAssets.defaultMaterial; } static void* generateNormals(float* positions, uint32_t accessorCount) { Math::Vec3f* data = new Math::Vec3f[accessorCount]; uint32_t trianglesCount = accessorCount / 3; uint32_t positionsIdx = 0; for (uint32_t i = 0; i < trianglesCount; ++i) { Math::Vec3f a{positions[positionsIdx], positions[positionsIdx + 1], positions[positionsIdx + 2]}; Math::Vec3f b{positions[positionsIdx + 3], positions[positionsIdx + 4], positions[positionsIdx + 5]}; Math::Vec3f c{positions[positionsIdx + 6], positions[positionsIdx + 7], positions[positionsIdx + 8]}; Math::Vec3f edge1 = b - a; Math::Vec3f edge2 = c - a; data[i++] = cross(edge1, edge2); } return data; } Resource::SharedPtr<Render::Mesh> GltfLoader::createMesh(Renderer& renderer, const gltf2::Asset& asset, GltfLoader::LoadedAssets& loadedAssets, int32_t index) { const gltf2::Mesh& gltfMesh = asset.meshes[index]; if (loadedAssets.meshes[index]) { return loadedAssets.meshes[index]; } Builder::Mesh meshBuilder(renderer); meshBuilder.setName(gltfMesh.name); for (const gltf2::Primitive& gltfPrimitive : gltfMesh.primitives) { Builder::Mesh::PrimitiveSet* primitiveSet = meshBuilder.addPrimitiveSet(); // Mode switch (gltfPrimitive.mode) { case gltf2::Primitive::Mode::Points: primitiveSet->setMode(Render::Mesh::PrimitiveSet::Mode::Points); break; case gltf2::Primitive::Mode::Lines: primitiveSet->setMode(Render::Mesh::PrimitiveSet::Mode::Lines); break; case gltf2::Primitive::Mode::LineLoop: LUG_LOG.error("GltfLoader::createMesh Unsupported mode LineLoop"); return nullptr; case gltf2::Primitive::Mode::LineStrip: primitiveSet->setMode(Render::Mesh::PrimitiveSet::Mode::LineStrip); break; case gltf2::Primitive::Mode::Triangles: primitiveSet->setMode(Render::Mesh::PrimitiveSet::Mode::Triangles); break; case gltf2::Primitive::Mode::TriangleStrip: primitiveSet->setMode(Render::Mesh::PrimitiveSet::Mode::TriangleStrip); break; case gltf2::Primitive::Mode::TriangleFan: primitiveSet->setMode(Render::Mesh::PrimitiveSet::Mode::TriangleFan); break; } // Indices if (gltfPrimitive.indices != -1) { const gltf2::Accessor& accessor = asset.accessors[gltfPrimitive.indices]; // Get the accessor from its index (directly from indices) uint32_t componentSize = getAttributeSize(accessor); void* data = getBufferViewData(asset, accessor); if (!data) { return nullptr; } primitiveSet->addAttributeBuffer( data, componentSize, accessor.count, Render::Mesh::PrimitiveSet::Attribute::Type::Indice ); } // Attributes struct { void* data{nullptr}; uint32_t accessorCount{0}; } positions; // Store positions for normals generation bool hasNormals = false; for (auto& attribute : gltfPrimitive.attributes) { Render::Mesh::PrimitiveSet::Attribute::Type type; if (attribute.first == "POSITION") { type = Render::Mesh::PrimitiveSet::Attribute::Type::Position; } else if (attribute.first == "NORMAL") { type = Render::Mesh::PrimitiveSet::Attribute::Type::Normal; hasNormals = true; } else if (attribute.first == "TANGENT") { type = Render::Mesh::PrimitiveSet::Attribute::Type::Tangent; } else if (attribute.first.find("TEXCOORD_") != std::string::npos) { type = Render::Mesh::PrimitiveSet::Attribute::Type::TexCoord; } else if (attribute.first.find("COLOR_") != std::string::npos) { type = Render::Mesh::PrimitiveSet::Attribute::Type::Color; } else { LUG_LOG.warn("GltfLoader::createMesh Unsupported attribute {}", attribute.first); continue; } // TODO(nokitoo): See if we can use COLOR_0 or if we just discard it const gltf2::Accessor& accessor = asset.accessors[attribute.second]; // Get the accessor from its index (second in the pair) uint32_t componentSize = getAttributeSize(accessor); void* data = getBufferViewData(asset, accessor); if (!data) { return nullptr; } if (type == Render::Mesh::PrimitiveSet::Attribute::Type::Position) { // Store positions in case we need to generate the normals later positions.data = data; positions.accessorCount = accessor.count; } primitiveSet->addAttributeBuffer(data, componentSize, accessor.count, type); } // Generate flat normals if there is not any if (!hasNormals) { void* data = generateNormals((float*)positions.data, positions.accessorCount); if (!data) { return nullptr; } primitiveSet->addAttributeBuffer( data, sizeof(Math::Vec3f), positions.accessorCount, Render::Mesh::PrimitiveSet::Attribute::Type::Normal ); } // Material Resource::SharedPtr<Render::Material> material = createMaterial(renderer, asset, loadedAssets, gltfPrimitive.material); if (!material) { LUG_LOG.error("GltfLoader::createMesh Can't create the material resource"); return nullptr; } primitiveSet->setMaterial(material); // TODO(nokitoo): set node transformations } loadedAssets.meshes[index] = meshBuilder.build(); return loadedAssets.meshes[index]; } bool GltfLoader::createNode(Renderer& renderer, const gltf2::Asset& asset, GltfLoader::LoadedAssets& loadedAssets, int32_t index, Scene::Node& parent) { const gltf2::Node& gltfNode = asset.nodes[index]; Scene::Node* node = parent.createSceneNode(gltfNode.name); parent.attachChild(*node); if (gltfNode.mesh != -1) { Resource::SharedPtr<Render::Mesh> mesh = createMesh(renderer, asset, loadedAssets, gltfNode.mesh); if (!mesh) { LUG_LOG.error("GltfLoader::createNode Can't create the mesh resource"); return false; } node->attachMeshInstance(mesh); } node->setPosition({ gltfNode.translation[0], gltfNode.translation[1], gltfNode.translation[2] }, Node::TransformSpace::Parent); node->setRotation(Math::Quatf{ gltfNode.rotation[3], gltfNode.rotation[0], gltfNode.rotation[1], gltfNode.rotation[2] }, Node::TransformSpace::Parent); node->scale({ gltfNode.scale[0], gltfNode.scale[1], gltfNode.scale[2] }); for (uint32_t nodeIdx : gltfNode.children) { if (!createNode(renderer, asset, loadedAssets, nodeIdx, *node)) { return false; } } return true; } Resource::SharedPtr<Resource> GltfLoader::loadFile(const std::string& filename) { gltf2::Asset asset; try { #if defined(LUG_SYSTEM_ANDROID) asset = gltf2::load(filename, (lug::Window::priv::WindowImpl::activity)->assetManager); #else asset = gltf2::load(filename); #endif // TODO(nokitoo): Format the asset if not already done // Should we store the version of format in asset.extensions or asset.copyright/asset.version ? } catch (gltf2::MisformattedException& e) { LUG_LOG.error("GltfLoader::loadFile Can't load the file \"{}\": {}", filename, e.what()); return nullptr; } // Create the container for the already loaded assets GltfLoader::LoadedAssets loadedAssets; loadedAssets.textures.resize(asset.textures.size()); loadedAssets.materials.resize(asset.materials.size()); loadedAssets.meshes.resize(asset.meshes.size()); // Load the scene if (asset.scene == -1) { // No scene to load return nullptr; } const gltf2::Scene& gltfScene = asset.scenes[asset.scene]; Builder::Scene sceneBuilder(_renderer); sceneBuilder.setName(gltfScene.name); Resource::SharedPtr<lug::Graphics::Scene::Scene> scene = sceneBuilder.build(); if (!scene) { LUG_LOG.error("GltfLoader::loadFile Can't create the scene resource"); return nullptr; } for (uint32_t nodeIdx : gltfScene.nodes) { if (!createNode(_renderer, asset, loadedAssets, nodeIdx, scene->getRoot())) { return nullptr; } } return Resource::SharedPtr<Resource>::cast(scene); } } // Graphics } // lug
19,279
5,801
#include "flat_file.hpp" #include "hibp.hpp" #include <cstdlib> int main(int /* argc */, char* argv[]) { std::ios_base::sync_with_stdio(false); std::cerr << argv[0] << ": reading `have i been pawned` text database from stdin,\n" "converting to binary format and writing to stdout." << std::endl; auto writer = flat_file::stream_writer<hibp::pawned_pw>(std::cout); for (std::string line; std::getline(std::cin, line);) writer.write(hibp::convert_to_binary(line)); return EXIT_SUCCESS; }
550
193
#include "heap.h" #include <algorithm> #include <cassert> #include "stack.h" using namespace vaiven; using std::min; using std::max; // set by interpreter Heap* vaiven::globalHeap = NULL; GcableType vaiven::Gcable::getType() { return (GcableType) (((GcableType) this->type) & ~GcableMarkBit); } bool vaiven::Gcable::isMarked() { return (this->type & GcableMarkBit) == GcableMarkBit; } bool vaiven::Gcable::mark() { if (isMarked()) { return false; } this->type = (GcableType) (((GcableType) this->type) | GcableMarkBit); return true; } void vaiven::Gcable::unmark() { this->type = (GcableType) (((GcableType) this->type) & ~GcableMarkBit); } GcableList* vaiven::Heap::newList() { if (isFull()) { gc(); } GcableList* ptr = new GcableList(); owned_ptrs.insert(ptr); heap_min = min(heap_min, (uint64_t) ptr); heap_max = max(heap_max, (uint64_t) ptr); return ptr; } GcableString* vaiven::Heap::newString() { if (isFull()) { gc(); } GcableString* ptr = new GcableString(); owned_ptrs.insert(ptr); heap_min = min(heap_min, (uint64_t) ptr); heap_max = max(heap_max, (uint64_t) ptr); return ptr; } GcableObject* vaiven::Heap::newObject() { if (isFull()) { gc(); } GcableObject* ptr = new GcableObject(); owned_ptrs.insert(ptr); heap_min = min(heap_min, (uint64_t) ptr); heap_max = max(heap_max, (uint64_t) ptr); return ptr; } bool vaiven::Heap::owns(void* ptr) { uint64_t addr = (uint64_t) ptr; // inside heap and is aligned to 64 bits if (addr < heap_min || addr > heap_max || addr & 7 != 1) { return false; } return owned_ptrs.find((Gcable*) ptr) != owned_ptrs.end(); } bool vaiven::Heap::isFull() { return owned_ptrs.size() >= size; } void vaiven::Heap::mark(Gcable* ptr) { if (!owns(ptr)) { return; } if (ptr->mark()) { return; } switch (ptr->getType()) { case GCABLE_TYPE_LIST: { GcableList* list = (GcableList*) ptr; for (vector<Value>::iterator it = list->list.begin(); it != list->list.end(); ++it) { mark(it->getPtr()); } break; } case GCABLE_TYPE_STRING: // already marked, nothing to do break; case GCABLE_TYPE_OBJECT: { GcableObject* object = (GcableObject*) ptr; for (unordered_map<string, Value>::iterator it = object->properties.begin(); it != object->properties.end(); ++it) { mark(it->second.getPtr()); } } } } void vaiven::Heap::sweep() { unordered_set<Gcable*>::iterator it = owned_ptrs.begin(); while (it != owned_ptrs.end()) { Gcable* gcable = (Gcable*) *it; if (!gcable->isMarked()) { switch (gcable->getType()) { case GCABLE_TYPE_LIST: delete static_cast<GcableList*>(gcable); break; case GCABLE_TYPE_STRING: delete static_cast<GcableString*>(gcable); break; case GCABLE_TYPE_OBJECT: delete static_cast<GcableObject*>(gcable); break; } it = owned_ptrs.erase(it); } else { gcable->unmark(); ++it; } } } void vaiven::Heap::free(Gcable* ptr) { if (ptr->getType() == GCABLE_TYPE_LIST) { delete (GcableList*) ptr; } else if (ptr->getType() == GCABLE_TYPE_STRING) { delete (GcableString*) ptr; } else if (ptr->getType() == GCABLE_TYPE_OBJECT) { delete (GcableObject*) ptr; } owned_ptrs.erase(ptr); } void vaiven::Heap::gc() { Stack callStack; StackFrame frame = callStack.top(); while (true) { for (int i = 0; i < frame.size; ++i) { mark((Gcable*) frame.locals[i]); } if (!frame.hasNext()) { break; } frame = frame.next(); } for (std::deque<Value>::iterator it = interpreterStack.c.begin(); it != interpreterStack.c.end(); ++it) { mark((Gcable*) it->getPtr()); } std::map<string, Value> scopeMap; globalScope.fill(scopeMap); for (std::map<string, Value>::iterator it = scopeMap.begin(); it != scopeMap.end(); ++it) { mark((Gcable*) it->second.getPtr()); } sweep(); size = max((int) owned_ptrs.size() * HEAP_FACTOR, MIN_HEAP_SIZE); }
4,126
1,618
#include <gtest/gtest.h> #include "utility/partitioner.h" TEST(Partitioner, Basic) { Partitioner part1(0, 0b111, 3); part1.compute(); std::vector<uint64_t> vres1 = part1.getResult(); std::set<uint64_t> ref1 = {0x0000, 0x0100, 0x0010, 0x0110, 0x0210}, res1(vres1.begin(), vres1.end()); EXPECT_EQ(ref1, res1); }
355
175
#include "graph_map/ndt_dl/ndtdl_map_param.h" #include <boost/serialization/export.hpp> BOOST_CLASS_EXPORT(perception_oru::libgraphMap::NDTDLMapParam) using namespace std; namespace perception_oru{ namespace libgraphMap{ void NDTDLMapParam::GetParametersFromRos(){ MapParam::GetParametersFromRos(); ros::NodeHandle nh("~"); cout<<"reading parameters from ros inside NDTDLMapParam::GetRosParametersFromRos()"<<endl; nh.param<std::string>("Super_important_map_parameter",SuperImportantMapParameter,"parhaps not so important..."); nh.param("resolution",resolution_,1.0); } } }
590
205
#include <iostream> #include <vector> using namespace std; class Solution { public: double findMedianSortedArrays(vector<int>& top, vector<int>& bottom) { if (top.size() > bottom.size()) { return findMedianSortedArrays(bottom, top); } int left = 0; int right = top.size(); double answer; while (left<=right) { // Calculate top and bottom middles int topMiddle = (left+right)/2; int bottomMiddle = (top.size()+bottom.size()+1)/2 - topMiddle; // Set top left and right int topLeft = INT_MIN; int topRight = INT_MAX; if (topMiddle > 0 ) { topLeft = top[topMiddle-1]; } if (topMiddle < top.size()) { topRight = top[topMiddle]; } // Set bottom left and right int bottomLeft = INT_MIN; int bottomRight = INT_MAX; if (bottomMiddle > 0) { bottomLeft = bottom[bottomMiddle-1]; } if (bottomMiddle < bottom.size()) { bottomRight = bottom[bottomMiddle]; } // Binary search if (bottomLeft > topRight) { left = topMiddle+1; continue; } if (topLeft > bottomRight) { right = topMiddle-1; continue; } // Found if ((top.size()+bottom.size())%2==0) { answer = ((double) max(topLeft, bottomLeft) + min(topRight, bottomRight))/2; } else { answer = max(topLeft, bottomLeft); } break; } return answer; } }; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); #ifndef ONLINE_JUDGE // freopen("input.txt", "r", stdin); // freopen("error.txt", "w", stderr); // freopen("output.txt", "w", stdout); #endif vector<int> nums1{1,1,1,1,1,1,1,1,1,1,4,4}; vector<int> nums2{1,3,4,4,4,4,4,4,4,4,4}; Solution s; cout << s.findMedianSortedArrays(nums1, nums2) << endl; return 0; }
2,174
668
/** @file "/owlcpp/include/owlcpp/detail/vector_set.hpp" part of owlcpp project. @n @n Distributed under the Boost Software License, Version 1.0; see doc/license.txt. @n Copyright Mikhail K Levin 2013 *******************************************************************************/ #ifndef VECTOR_SET_HPP_ #define VECTOR_SET_HPP_ #include <vector> namespace owlcpp{ /**@brief Collection of unique objects stored in a vector *******************************************************************************/ template<class T, class Comp = std::less<T>, class Alloc = std::allocator<T> > class Vector_set { typedef std::vector<T, Alloc> stor_t; public: typedef T value_type; typedef typename stor_t::iterator iterator; typedef typename stor_t::const_iterator const_iterator; Vector_set() : v_(), comp_() {} Vector_set(Comp const& comp) : v_(), comp_(comp) {} iterator begin() {return v_.begin();} iterator end() {return v_.end();} const_iterator begin() const {return v_.begin();} const_iterator end() const {return v_.end();} std::size_t size() const {return v_.size();} std::pair<iterator, bool> insert(value_type const& t) { iterator i = std::lower_bound(v_.begin(), v_.end(), t, comp_); if( i == v_.end() || comp_(t, *i) ) { return std::make_pair(v_.insert(i, t), true); } return std::make_pair(i, false); } const_iterator find(value_type const& t) const { const_iterator i = std::lower_bound(v_.begin(), v_.end(), t, comp_); if( i == v_.end() || comp_(t, *i) ) return v_.end(); return i; } value_type const& operator[](const std::size_t n) const {return v_[n];} value_type const& at(const std::size_t n) const {return v_.at(n);} private: stor_t v_; Comp comp_; }; }//namespace owlcpp #endif /* VECTOR_SET_HPP_ */
1,830
614
#ifndef FALCON_FUNCTIONAL_INVOKE_PARTIAL_RECURSIVE_PARAM_HPP #define FALCON_FUNCTIONAL_INVOKE_PARTIAL_RECURSIVE_PARAM_HPP #include <falcon/math/min.hpp> #include <falcon/c++1x/syntax.hpp> #include <falcon/functional/invoke.hpp> #include <falcon/parameter/manip.hpp> #include <falcon/preprocessor/not_ide_parser.hpp> #include <utility> namespace falcon { template<std::size_t NumberArg> class invoke_partial_recursive_param_loop_fn { static_assert(NumberArg > 1, "NumberArg < 2"); template<std::size_t N, class = void> struct Impl { template< class F, class... Args , std::size_t Start = (N - 1) * (NumberArg - 1) + NumberArg + 1> static constexpr CPP1X_DELEGATE_FUNCTION( impl_(F && func, Args&&... args) , invoke( typename parameter_index_cat< parameter_index<0>, build_range_parameter_index_t< Start , min(Start + (NumberArg - 1), sizeof...(Args) + 1) > >::type() , std::forward<F>(func) , Impl<N-1>::impl_(std::forward<F>(func), std::forward<Args>(args)...) , std::forward<Args>(args)... ) ) }; template<class T> struct Impl<0, T> { template<class F, class... Args> static constexpr CPP1X_DELEGATE_FUNCTION( impl_(F && func, Args&&... args) , invoke( build_parameter_index_t<min(NumberArg, sizeof...(Args))>() , std::forward<F>(func) , std::forward<Args>(args)... ) ) }; public: constexpr invoke_partial_recursive_param_loop_fn() noexcept {} template< class F, class... Args , std::size_t N = (sizeof...(Args) - 2) / (NumberArg - 1)> constexpr CPP1X_DELEGATE_FUNCTION( operator()(F && func, Args&&... args) const , Impl<N>::impl_(std::forward<F>(func), std::forward<Args>(args)...) ) }; /** * \brief Call \c func with \c NumberArg arguments. The return of \c func is the first argument of next call. * \return Last operations. * * \code * int n = invoke_partial_param_loop<2>(accu_t(), 1,2,3,4,5,6); * \endcode * equivalent to * \code * accu_t accu; * int n = accu(accu(accu(accu(accu(1,2),3),4),5),6); * \endcode * * \ingroup call-arguments */ template<std::size_t NumberArg, class F, class... Args> constexpr CPP1X_DELEGATE_FUNCTION( invoke_partial_recursive_param_loop(F func, Args&&... args) , invoke_partial_recursive_param_loop_fn<NumberArg>()( std::forward<F>(func), std::forward<Args>(args)...) ) } #endif
2,455
936