text
string
size
int64
token_count
int64
#include <iostream> #include <string> #include <map> #include <vector> using namespace std; int main() { int q; cin >> q; map<string, vector<string>> buses_to_stops, stops_to_buses; for (int i = 0; i < q; ++i) { string operation_code; cin >> operation_code; if (operation_code == "NEW_BUS") { string bus; cin >> bus; int stop_count; cin >> stop_count; vector<string>& stops = buses_to_stops[bus]; stops.resize(stop_count); for (string& stop : stops) { cin >> stop; stops_to_buses[stop].push_back(bus); } } else if (operation_code == "BUSES_FOR_STOP") { string stop; cin >> stop; if (stops_to_buses.count(stop) == 0) { cout << "No stop" << endl; } else { for (const string& bus : stops_to_buses[stop]) { cout << bus << " "; } cout << endl; } } else if (operation_code == "STOPS_FOR_BUS") { string bus; cin >> bus; if (buses_to_stops.count(bus) == 0) { cout << "No bus" << endl; } else { for (const string& stop : buses_to_stops[bus]) { cout << "Stop " << stop << ": "; if (stops_to_buses[stop].size() == 1) { cout << "no interchange"; } else { for (const string& other_bus : stops_to_buses[stop]) { if (bus != other_bus) { cout << other_bus << " "; } } } cout << endl; } } } else if (operation_code == "ALL_BUSES") { if (buses_to_stops.empty()) { cout << "No buses" << endl; } else { for (const auto& bus_item : buses_to_stops) { cout << "Bus " << bus_item.first << ": "; for (const string& stop : bus_item.second) { cout << stop << " "; } cout << endl; } } } } return 0; }
2,394
686
/* * Project: FullereneViewer * Version: 1.0 * Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext) */ #include <assert.h> #include "SymmetryAxisNormal.h" #include "CarbonAllotrope.h" #include "OpenGLUtil.h" #include "ShutUp.h" SymmetryAxisNormal::SymmetryAxisNormal(CarbonAllotrope* ca, SymmetryAxis* axis) : InteractiveRegularPolygon(ca, 0, 1.0, 2), p_ca(ca), p_axis(axis) { } SymmetryAxisNormal::~SymmetryAxisNormal() { } void SymmetryAxisNormal::reset_interaction() { InteractiveRegularPolygon::reset_interaction(); } void SymmetryAxisNormal::interaction_original(OriginalForceType UNUSED(force_type), Interactives* UNUSED(interactives), double UNUSED(delta)) { Vector3 north_location; Vector3 south_location; int north = p_axis->get_north_sequence_no(); int south = p_axis->get_south_sequence_no(); switch (p_axis->get_type()) { case AXIS_TYPE_CENTER_OF_TWO_CARBONS: { Carbon* north_carbon = p_ca->get_carbon_by_sequence_no(north); Carbon* south_carbon = p_ca->get_carbon_by_sequence_no(south); north_location = north_carbon->get_center_location(); south_location = south_carbon->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_CARBON_AND_BOND: { Carbon* north_carbon = p_ca->get_carbon_by_sequence_no(north); Bond* south_bond = p_ca->get_bond_by_sequence_no(south); north_location = north_carbon->get_center_location(); south_location = south_bond->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_CARBON_AND_RING: { Carbon* north_carbon = p_ca->get_carbon_by_sequence_no(north); Ring* south_ring = p_ca->get_ring_by_sequence_no(south); north_location = north_carbon->get_center_location(); south_location = south_ring->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_CARBON_AND_BOUNDARY: { Carbon* north_carbon = p_ca->get_carbon_by_sequence_no(north); ConnectedBoundary* south_boundary = p_ca->get_boundary_by_sequence_no(south); north_location = north_carbon->get_center_location(); south_location = south_boundary->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_TWO_BONDS: { Bond* north_bond = p_ca->get_bond_by_sequence_no(north); Bond* south_bond = p_ca->get_bond_by_sequence_no(south); north_location = north_bond->get_center_location(); south_location = south_bond->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_BOND_AND_RING: { Bond* north_bond = p_ca->get_bond_by_sequence_no(north); Ring* south_ring = p_ca->get_ring_by_sequence_no(south); north_location = north_bond->get_center_location(); south_location = south_ring->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_BOND_AND_BOUNDARY: { Bond* north_bond = p_ca->get_bond_by_sequence_no(north); ConnectedBoundary* south_boundary = p_ca->get_boundary_by_sequence_no(south); north_location = north_bond->get_center_location(); south_location = south_boundary->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_TWO_RINGS: { Ring* north_ring = p_ca->get_ring_by_sequence_no(north); Ring* south_ring = p_ca->get_ring_by_sequence_no(south); north_location = north_ring->get_center_location(); south_location = south_ring->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_RING_AND_BOUNDARY: { Ring* north_ring = p_ca->get_ring_by_sequence_no(north); ConnectedBoundary* south_boundary = p_ca->get_boundary_by_sequence_no(south); north_location = north_ring->get_center_location(); south_location = south_boundary->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_TWO_BOUNDARIES: { ConnectedBoundary* north_boundary = p_ca->get_boundary_by_sequence_no(north); ConnectedBoundary* south_boundary = p_ca->get_boundary_by_sequence_no(south); north_location = north_boundary->get_center_location(); south_location = south_boundary->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_ONLY_ONE_CARBON: { Carbon* north_carbon = p_ca->get_carbon_by_sequence_no(north); Vector3 center_location = p_ca->get_center_location(); north_location = north_carbon->get_center_location(); south_location = Vector3() - north_location; } break; case AXIS_TYPE_CENTER_OF_ONLY_ONE_BOND: { Bond* north_bond = p_ca->get_bond_by_sequence_no(north); Vector3 center_location = p_ca->get_center_location(); north_location = north_bond->get_center_location(); south_location = Vector3() - north_location; } break; case AXIS_TYPE_CENTER_OF_ONLY_ONE_RING: { Ring* north_ring = p_ca->get_ring_by_sequence_no(north); Vector3 center_location = p_ca->get_center_location(); north_location = north_ring->get_center_location(); south_location = Vector3() - north_location; } break; case AXIS_TYPE_CENTER_OF_ONLY_ONE_BOUNDARY: { ConnectedBoundary* north_boundary = p_ca->get_boundary_by_sequence_no(north); Vector3 center_location = p_ca->get_center_location(); north_location = north_boundary->get_center_location(); south_location = Vector3() - north_location; } break; default: assert(0); } Vector3 center = (north_location + south_location) * 0.5; Vector3 normal = north_location - south_location; p_normal.clockwise = 1; fix_center_location(center); fix_radius_length(normal.abs() * 0.6); fix_posture(Matrix3(Quaternion(Vector3(0.0, 0.0, 1.0), normal))); } void SymmetryAxisNormal::draw_opaque_by_OpenGL(bool UNUSED(selection)) const { Vector3 norm = get_normal(); norm *= p_radius.length; OpenGLUtil::set_color(0x001810); OpenGLUtil::draw_cylinder(0.1, get_center_location() - norm, get_center_location() + norm); } /* Local Variables: */ /* mode: c++ */ /* End: */
6,271
2,275
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2017 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 INTEL OR ITS 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. END_LEGAL */ #include <iostream> #include <sstream> #include <iomanip> #include <fstream> #include <cstdlib> #include "pin.H" #include "instlib.H" using namespace std; extern "C" void InitXed () { xed_tables_init(); } static char nibble_to_ascii_hex(UINT8 i) { if (i<10) return i+'0'; if (i<16) return i-10+'A'; return '?'; } static void print_hex_line(char* buf, const UINT8* array, const int length) { int n = length; int i=0; if (length == 0) n = XED_MAX_INSTRUCTION_BYTES; for( i=0 ; i< n; i++) { buf[2*i+0] = nibble_to_ascii_hex(array[i]>>4); buf[2*i+1] = nibble_to_ascii_hex(array[i]&0xF); } buf[2*i]=0; } extern "C" UINT32 GetInstructionLenAndDisasm (UINT8 *ip, string *str) { xed_state_t dstate; xed_decoded_inst_t xedd; xed_state_zero(&dstate); if (sizeof(ADDRINT) == 4) xed_state_init(&dstate, XED_MACHINE_MODE_LEGACY_32, XED_ADDRESS_WIDTH_32b, XED_ADDRESS_WIDTH_32b); else xed_state_init(&dstate, XED_MACHINE_MODE_LONG_64, XED_ADDRESS_WIDTH_64b, XED_ADDRESS_WIDTH_64b); xed_decoded_inst_zero_set_mode(&xedd, &dstate); xed_error_enum_t xed_error = xed_decode(&xedd, reinterpret_cast<const UINT8*>(ip), 15); if (XED_ERROR_NONE != xed_error) { fprintf (stderr, "***Error in decoding exception causing instruction at %p\n", ip); return (0); } UINT32 decLen = xed_decoded_inst_get_length(&xedd); ostringstream os; iostream::fmtflags fmt = os.flags(); { char buffer[200]; unsigned int dec_len = 0; unsigned int sp = 0; os << std::setfill('0') << std::hex << std::setw(sizeof(ADDRINT)*2) << reinterpret_cast<UINT64>(ip) << std::dec << ": " << std::setfill(' ') << std::setw(4); os << xed_extension_enum_t2str(xed_decoded_inst_get_extension(&xedd)); print_hex_line(buffer, reinterpret_cast<UINT8*>(ip), decLen); os << " " << buffer; for ( sp=dec_len; sp < 12; sp++) // pad out the instruction bytes os << " "; os << " "; memset(buffer,0,200); int dis_okay = xed_format_context(XED_SYNTAX_INTEL, &xedd, buffer, 200, (ADDRINT)ip, 0, 0); if (dis_okay) os << buffer << endl; else os << "Error disasassembling ip 0x" << std::hex << ip << std::dec << endl; } os.flags(fmt); *str = os.str(); return (decLen); }
4,164
1,569
/* TITLE Improving "ugly" code Chapter20TryThis1.cpp "Bjarne Stroustrup "C++ Programming: Principles and Practice."" COMMENT Objective: If you were able how would you change Jill's code to get rid of the ugliness? Input: - Output: - Author: Chris B. Kirov Date: 17. 02. 2017 */ #include <iostream> #include <vector> double* get_from_jack(int* count); // read from array std::vector<double>* get_from_jill(); // read from vector // First attempt void fct() { int jack_count = 0; double* jack_data = get_from_jack(&jack_count); std::vector<double>* jill_data = get_from_jill(); std::vector<double>& v = *jill_data; // introduce a reference to eliminate ptr dereference in the code // process double h = -1; double* jack_high; double* jill_high; for (int i = 0; i < jack_count; ++i) { if (h < jack_data[i]) { jack_high = &jack_data[i]; } } h = -1; for (int i = 0; i < v.size(); ++i) { if (h < v[i]) { jill_high = &v[i]; } } std::cout <<"Jill's max: " << *jill_high <<" Jack's max: "<< *jack_high; delete[] jack_data; delete jill_data; } //--------------------------------------------------------------------------------------------------------------------------- // Second attempt double* high (double* first, double* last) { double h = -1; double* high; for (double* p = first; p != last; ++p) { if (h < *p) { high = p; } } return high; } //--------------------------------------------------------------------------------------------------------------------------- void fct2() { int jack_count = 0; double* jack_data = get_from_jack(&jack_count); std::vector<double>* jill_data = get_from_jill(); std::vector<double>& v = *jill_data; double* jack_high = high(jack_data, jack_data + jack_count); double* jill_high = high(&v[0], &v[0] + v.size()); std::cout <<"Jill's max: " << *jill_high <<" Jack's max: "<< *jack_high; delete[] jack_data; delete jill_data; } //--------------------------------------------------------------------------------------------------------------------------- int main() { try { } catch (std::exception& e) { std::cerr << e.what(); } getchar (); }
2,222
875
#pragma once #include <SFML/Graphics.hpp> #include <SFML/System.hpp> #include <vector> /** * A class that . */ /** * @brief The Frame class Contains the frames in a vector that are needed for an AnimatedSprite * and the delay between each frame. A frame is an sf::IntRect and the * AnimatedSprite uses that to find the subimage */ class Frame { public: /** * @brief Frame Creates a new Frame */ Frame(); /** * @brief setDelay Sets the delay between the frames * @param d The delay between frames */ void setDelay(double d); /** * @brief addFrame Adds a frame to the back of the vector * @param rect The Frame to add */ void addFrame(const sf::IntRect rect); /** * @brief getFrames Returns a vector that contains all the frames * that have been added. * @return A vector with all the frames */ std::vector<sf::IntRect> getFrames() const; /** * @brief getDelay Gets the delay between frames. * @return Delay between frames */ int getDelay() const; protected: private: std::vector<sf::IntRect> frames; int delay; int height; int width; };
1,125
394
/** * @copybrief * MIT License * Copyright (c) 2020 NeilKleistGao * 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. */ /// @file font_factory.h #include "font_factory.h" #include "log/logger_factory.h" namespace ngind::rendering { FontFactory* FontFactory::_instance = nullptr; FontFactory::FontFactory() : _library(nullptr) { auto error = FT_Init_FreeType(&_library); if (error) { auto logger = log::LoggerFactory::getInstance()->getLogger("crash.log", log::LogLevel::LOG_LEVEL_ERROR); logger->log("Can't load Free Type Library"); logger->flush(); } } FontFactory::~FontFactory() { FT_Done_FreeType(_library); } FontFactory* FontFactory::getInstance() { if (_instance == nullptr) { _instance = new(std::nothrow) FontFactory(); } return _instance; } void FontFactory::destroyInstance() { if (_instance != nullptr) { delete _instance; _instance = nullptr; } } FT_Face FontFactory::loadFontFace(const std::string& filename, const long& index) { FT_Face face = nullptr; auto error = FT_New_Face(_library, filename.c_str(), index, &face); if (error) { face = nullptr; } return face; } } // namespace ngind::rendering
2,261
731
#include "window_manager.hpp" #include <GLFW/glfw3.h> #include <beyond/utils/panic.hpp> WindowManager::WindowManager() { if (!glfwInit()) { beyond::panic("Failed to initialize GLFW\n"); } } WindowManager::~WindowManager() { glfwTerminate(); } void WindowManager::pull_events() { glfwPollEvents(); }
310
119
/* $Id: aliasstr.cpp 539688 2017-06-26 16:58:28Z gouriano $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Aleksey Grichenko * * File Description: * Type info for aliased type generation: includes, used classes, C code etc. */ #include <ncbi_pch.hpp> #include <corelib/ncbiutil.hpp> #include "datatool.hpp" #include "exceptions.hpp" #include "type.hpp" #include "aliasstr.hpp" #include "reftype.hpp" #include "statictype.hpp" #include "stdstr.hpp" #include "code.hpp" #include "srcutil.hpp" #include "classstr.hpp" #include "enumstr.hpp" #include <serial/serialdef.hpp> BEGIN_NCBI_SCOPE CAliasTypeStrings::CAliasTypeStrings(const string& externalName, const string& className, CTypeStrings& ref_type, const CComments& comments) : TParent(comments), m_ExternalName(externalName), m_ClassName(className), m_RefType(&ref_type), m_FullAlias(false), m_Nested(false) { } CAliasTypeStrings::~CAliasTypeStrings(void) { } CAliasTypeStrings::EKind CAliasTypeStrings::GetKind(void) const { if (DataType() && DataType()->IsTypeAlias()) { EKind kind = m_RefType->GetKind(); if (kind == eKindStd || kind == eKindEnum || kind == eKindString) { return eKindClass; } return eKindObject; } return eKindOther; } string CAliasTypeStrings::GetClassName(void) const { return m_ClassName; } string CAliasTypeStrings::GetExternalName(void) const { return m_ExternalName; } string CAliasTypeStrings::GetCType(const CNamespace& /*ns*/) const { return GetClassName(); } string CAliasTypeStrings::GetPrefixedCType(const CNamespace& ns, const string& /*methodPrefix*/) const { return GetCType(ns); } bool CAliasTypeStrings::HaveSpecialRef(void) const { return m_RefType->HaveSpecialRef(); } string CAliasTypeStrings::GetRef(const CNamespace& ns) const { if (DataType() && DataType()->IsTypeAlias()) { return "CLASS, ("+GetCType(ns)+')'; } return m_RefType->GetRef(ns); } bool CAliasTypeStrings::CanBeKey(void) const { return m_RefType->CanBeKey(); } bool CAliasTypeStrings::CanBeCopied(void) const { return m_RefType->CanBeCopied(); } string CAliasTypeStrings::NewInstance(const string& init, const string& place) const { return m_RefType->NewInstance(init, place); } string CAliasTypeStrings::GetInitializer(void) const { string r = m_RefType->GetInitializer(); CTypeStrings::EKind kind = m_RefType->GetKind(); if (!r.empty() && kind != eKindClass && kind != eKindObject) { r = GetClassName() + "(" + r + ")"; } return r; } string CAliasTypeStrings::GetDestructionCode(const string& expr) const { return m_RefType->GetDestructionCode(expr); } string CAliasTypeStrings::GetIsSetCode(const string& var) const { return m_RefType->GetIsSetCode(var); } string CAliasTypeStrings::GetResetCode(const string& var) const { return m_RefType->GetResetCode(var); } string CAliasTypeStrings::GetDefaultCode(const string& var) const { // No value - return empty string if ( var.empty() ) { return NcbiEmptyString; } // Return var for classes, else cast var to the aliased type return GetCType(GetNamespace()) + "(" + var + ")"; } void CAliasTypeStrings::GenerateCode(CClassContext& ctx) const { const CNamespace& ns = ctx.GetNamespace(); string ref_name = m_RefType->GetCType(ns); string className; if (m_Nested) { className = GetClassName(); } else { className = GetClassName() + "_Base"; } CClassCode code(ctx, className); string methodPrefix = code.GetMethodPrefix(); string classFullName(GetClassName()); if (m_Nested) { classFullName = NStr::TrimSuffix_Unsafe(methodPrefix, "::"); } bool is_class = false; bool is_ref_to_alias = false; const CClassTypeStrings::SMemberInfo* mem_alias = nullptr; bool mem_isnull = false; bool type_alias = DataType() && DataType()->IsTypeAlias(); AutoPtr<CTypeStrings> mem_type; CTypeStrings::EKind kind = m_RefType->GetKind(); switch ( kind ) { case eKindClass: case eKindObject: { string name(ref_name); const CClassRefTypeStrings* cls = dynamic_cast<const CClassRefTypeStrings*>(m_RefType.get()); if (cls) { name = cls->GetClassName(); } code.SetParentClass(name, m_RefType->GetNamespace()); } is_class = true; is_ref_to_alias = (dynamic_cast<const CAliasRefTypeStrings*>(m_RefType.get()) != NULL); // only if we have two members, and one of them is attlist // that is, if it was created by DTDParser::CompositeNode if (!is_ref_to_alias && DataType() && !DataType()->IsASNDataSpec() && DataType()->IsReference()) { const CReferenceDataType* reftype = dynamic_cast<const CReferenceDataType*>(DataType()); const CDataType* resolved = reftype->Resolve(); if (resolved && resolved != reftype) { CClassTypeStrings* typeStr = resolved->GetTypeStr(); bool has_attlist = false; if (typeStr && typeStr->m_Members.size() == 2) { for ( const auto& ir: typeStr->m_Members ) { if (ir.attlist) { has_attlist = true; } else { mem_alias = &ir; mem_isnull = ir.haveFlag ? (dynamic_cast<CNullTypeStrings*>(ir.type.get()) != 0) : false; } } if (!has_attlist || mem_alias->externalName != reftype->GetUserTypeName()) { mem_alias = nullptr; } } else { mem_isnull = dynamic_cast<const CNullDataType*>(resolved) != nullptr; } } } break; case eKindStd: case eKindEnum: code.SetParentClass("CStdAliasBase< " + ref_name + " >", CNamespace::KNCBINamespace); break; case eKindString: code.SetParentClass("CStringAliasBase< " + ref_name + " >", CNamespace::KNCBINamespace); break; case eKindOther: // for vector< char > code.SetParentClass("CStringAliasBase< " + ref_name + " >", CNamespace::KNCBINamespace); break; case eKindPointer: case eKindRef: case eKindContainer: NCBI_THROW(CDatatoolException, eNotImplemented, "Invalid aliased type: " + ref_name); } if (m_Nested && type_alias && !mem_alias && !DataType()->HasTag() && !DataType()->IsInUniSeq() && DataType()->GetTagType() == CAsnBinaryDefs::eAutomatic) { bool is_std = kind == eKindStd || kind == eKindEnum || kind == eKindString || kind == eKindOther; if (!is_std) { m_RefType->GenerateTypeCode(ctx); code.SetEmptyClassCode(); return; } } string parentNamespaceRef = code.GetNamespace().GetNamespaceRef(code.GetParentClassNamespace()); BeginClassDeclaration(ctx); // constructor code.ClassPublic() << " " << className << "(void);\n" << "\n"; code.MethodStart(true) << methodPrefix << className << "(void)\n" << "{\n" << "}\n" << "\n"; m_RefType->GenerateTypeCode(ctx); if ( is_class ) { if (is_ref_to_alias) { code.ClassPublic() << " // type info\n" " DECLARE_STD_ALIAS_TYPE_INFO();\n" "\n"; } else { code.ClassPublic() << " // type info\n" " DECLARE_INTERNAL_TYPE_INFO();\n" "\n"; } // m_RefType->GenerateTypeCode(ctx); // I have strong feeling that this was a bad idea // and these methods should be removed if (/*!mem_isnull &&*/ !type_alias) { code.ClassPublic() << " // parent type getter/setter\n" << " const " << ref_name << "& Get(void) const;\n" << " " << ref_name << "& Set(void);\n"; code.MethodStart(true) << "const " << ref_name << "& " << methodPrefix << "Get(void) const\n" << "{\n" << " return *this;\n" << "}\n\n"; code.MethodStart(true) << ref_name << "& " << methodPrefix << "Set(void)\n" << "{\n" << " return *this;\n" << "}\n\n"; } if (type_alias && mem_alias) { string extname(m_ClassName); if (NStr::StartsWith(extname, "C_")) { NStr::TrimPrefixInPlace(extname, "C_"); } else if (NStr::StartsWith(extname, "C")) { NStr::TrimPrefixInPlace(extname, "C"); } string mem_extname(mem_alias->cName); code.ClassPublic() << "\n"; if (!mem_isnull) { code.ClassPublic() << " typedef " << "Tparent::" << mem_alias->tName << " T" << extname << ";\n"; } code.ClassPublic() << " bool IsSet" << extname << "(void) const {\n" << " return Tparent::IsSet" << mem_extname << "();\n" << " }\n"; code.ClassPublic() << " bool CanGet" << extname << "(void) const {\n" << " return Tparent::CanGet" << mem_extname << "();\n" << " }\n"; code.ClassPublic() << " void Reset" << extname << "(void) {\n" << " Tparent::Reset" << mem_extname << "();\n" << " }\n"; if (mem_isnull) { code.ClassPublic() << " " << "void" << " Set" << extname << "(void) {\n" << " Tparent::Set" << mem_extname << "();\n" << " }\n"; } else { code.ClassPublic() << " const " << "T" << extname << "& Get" << extname << "(void) const {\n" << " return Tparent::Get" << mem_extname << "();\n" << " }\n"; code.ClassPublic() << " " << "T" << extname << "& Set" << extname << "(void) {\n" << " return Tparent::Set" << mem_extname << "();\n" << " }\n"; // if (mem_alias->dataType && mem_alias->dataType->IsPrimitive()) { if (mem_alias->type->CanBeCopied()) { code.ClassPublic() << " " << "void" << " Set" << extname << "(const T" << extname << "& value) {\n" << " Tparent::Set" << mem_extname << "(value);\n" << " }\n"; if (mem_alias->simple && m_Nested) { code.ClassPublic() << " " << className << "(const" << " T" << extname << "& value) : Tparent(value) {\n }\n"; code.ClassPublic() << " " << className << "& operator=(const" << " T" << extname << "& value) {\n" << " Tparent::operator=(value);\n" << " return *this;\n" << " }\n"; } } } } } else { code.ClassPublic() << " // type info\n" " DECLARE_STD_ALIAS_TYPE_INFO();\n" "\n"; string constr_decl = className + "(const " + ref_name + "& data)"; code.ClassPublic() << " // explicit constructor from the primitive type\n" << " explicit " << constr_decl << ";\n"; code.MethodStart(true) << methodPrefix << constr_decl << "\n" << " : " << parentNamespaceRef << code.GetParentClassName() << "(data)\n" << "{\n" << "}\n" << "\n"; // I/O operators bool kindIO = kind == eKindStd || kind == eKindEnum || kind == eKindString || kind == eKindPointer; code.MethodStart(true) << "NCBI_NS_NCBI::CNcbiOstream& operator<<\n" << "(NCBI_NS_NCBI::CNcbiOstream& str, const " << (m_Nested ? classFullName : className) << "& obj)\n" << "{\n"; if (kindIO) { code.Methods(true) << " if (NCBI_NS_NCBI::MSerial_Flags::HasSerialFormatting(str)) {\n" << " return WriteObject(str,&obj,obj.GetTypeInfo());\n" << " }\n" << " str << obj.Get();\n" << " return str;\n"; } else { code.Methods(true) << " return WriteObject(str,&obj,obj.GetTypeInfo());\n"; } code.Methods(true) << "}\n\n"; code.MethodStart(true) << "NCBI_NS_NCBI::CNcbiIstream& operator>>\n" << "(NCBI_NS_NCBI::CNcbiIstream& str, " << (m_Nested ? classFullName : className) << "& obj)\n" << "{\n"; if (kindIO) { code.Methods(true) << " if (NCBI_NS_NCBI::MSerial_Flags::HasSerialFormatting(str)) {\n" << " return ReadObject(str,&obj,obj.GetTypeInfo());\n" << " }\n"; if (kind == eKindEnum && m_RefType->GetEnumName() == ref_name) { code.Methods(true) << " std::underlying_type<" << ref_name <<">::type v;\n" << " str >> v;\n" << " obj.Set((" << ref_name << ")v);\n"; } else { code.Methods(true) << " str >> obj.Set();\n"; } code.Methods(true) << " return str;\n"; } else { code.Methods(true) << " return ReadObject(str,&obj,obj.GetTypeInfo());\n"; } code.Methods(true) << "}\n\n"; } // define typeinfo method { // code.CPPIncludes().insert("serial/aliasinfo"); CNcbiOstream& methods = code.Methods(); methods << "BEGIN"; if (m_Nested) { methods << "_NESTED"; } if (dynamic_cast<const CEnumRefTypeStrings*>(m_RefType.get())) { methods << "_ENUM"; } methods << "_ALIAS_INFO(\"" << GetExternalName() << "\", " << classFullName << ", " << m_RefType->GetRef(ns) << ")\n" "{\n"; if ( !GetModuleName().empty() ) { methods << " SET_ALIAS_MODULE(\"" << GetModuleName() << "\");\n"; } const CDataType* dataType = DataType(); if (dataType) { if (dataType->HasTag()) { methods << " SET_ASN_TAGGED_TYPE_INFO(" <<"SetTag, (" << dataType->GetTag() <<',' << dataType->GetTagClassString(dataType->GetTagClass()) << ',' << dataType->GetTagTypeString(dataType->GetTagType()) <<"));\n"; } else if (dataType->GetTagType() != CAsnBinaryDefs::eAutomatic) { methods << " SET_ASN_TAGGED_TYPE_INFO(" <<"SetTagType, (" << dataType->GetTagTypeString(dataType->GetTagType()) <<"));\n"; } } methods << " SET_"; if ( is_class ) { methods << "CLASS"; } else { methods << "STD"; } methods << "_ALIAS_DATA_PTR;\n"; if (mem_alias || type_alias || this->IsFullAlias()) { methods << " SET_FULL_ALIAS;\n"; } methods << " info->CodeVersion(" << DATATOOL_VERSION << ");\n"; methods << " info->DataSpec(" << CDataType::GetSourceDataSpecString() << ");\n"; methods << "}\n" "END_ALIAS_INFO\n" "\n"; } } void CAliasTypeStrings::GenerateUserHPPCode(CNcbiOstream& out) const { // m_RefType->GenerateUserHPPCode(out); const CNamespace& ns = GetNamespace(); string ref_name = m_RefType->GetCType(ns); string className = GetClassName(); if (CClassCode::GetDoxygenComments()) { out << "\n" << "/** @addtogroup "; if (!CClassCode::GetDoxygenGroup().empty()) { out << CClassCode::GetDoxygenGroup(); } else { out << "dataspec_" << GetDoxygenModuleName(); } out << "\n *\n" << " * @{\n" << " */\n\n"; } out << "/////////////////////////////////////////////////////////////////////////////\n"; if (CClassCode::GetDoxygenComments()) { out << "///\n" "/// " << className << " --\n" "///\n\n"; } out << "class "; if ( !CClassCode::GetExportSpecifier().empty() ) out << CClassCode::GetExportSpecifier() << " "; out << GetClassName()<<" : public "<<GetClassName()<<"_Base\n" "{\n" " typedef "<<GetClassName()<<"_Base Tparent;\n" "public:\n"; out << " " << GetClassName() << "(void) {}\n" "\n"; bool is_class = false; const CClassTypeStrings::SMemberInfo* mem_alias = nullptr; bool mem_isnull = false; AutoPtr<CTypeStrings> mem_type; switch ( m_RefType->GetKind() ) { case eKindClass: case eKindObject: is_class = true; if (DataType()->IsReference()) { const CReferenceDataType* reftype = dynamic_cast<const CReferenceDataType*>(DataType()); const CDataType* resolved = reftype->Resolve(); if (resolved && resolved != reftype) { CClassTypeStrings* typeStr = resolved->GetTypeStr(); bool has_attlist = false; if (typeStr) { if (typeStr->m_Members.size() == 2) { for ( const auto& ir: typeStr->m_Members ) { if (ir.attlist) { has_attlist = true; } else { mem_alias = &ir; mem_isnull = ir.haveFlag ? (dynamic_cast<CNullTypeStrings*>(ir.type.get()) != 0) : false; } } if (!has_attlist || mem_alias->externalName != reftype->GetUserTypeName()) { mem_alias = nullptr; } } if (mem_alias && mem_alias->dataType && !mem_alias->dataType->IsStdType()) { mem_alias = nullptr; } } else { mem_isnull = dynamic_cast<const CNullDataType*>(resolved) != nullptr; if (!mem_isnull && !resolved->IsAlias() && resolved->IsStdType()) { mem_type = resolved->GenerateCode(); const CClassTypeStrings* mem_class = dynamic_cast<const CClassTypeStrings*>(mem_type.get()); if (mem_class && mem_class->m_Members.size() == 1) { mem_alias = &(mem_class->m_Members.front()); } } } } } break; default: is_class = false; break; } if ( !is_class ) { // Generate type convertions out << " /// Explicit constructor from the primitive type.\n" << " explicit " << className + "(const " + ref_name + "& value)" << "\n" " : Tparent(value) {}\n\n"; } else if (mem_alias) { #if 0 string tname = mem_alias->type->GetCType(ns); // or mem_alias->tName? #else string tname = "Tparent::" + mem_alias->tName; out << " // typedef " << mem_alias->type->GetCType(ns) << " " << mem_alias->tName << ";\n\n"; #endif string mem_extname(mem_alias->cName); out << " /// Constructor from the primitive type.\n" << " " << className << "(const " << tname << "& value) {\n" << " Set" << mem_extname << "(value);\n" << " }\n"; out << " /// Assignment operator\n" << " " << className << "& operator=(const " << tname << "& value) {\n" << " Set" << mem_extname << "(value);\n" << " return *this;\n" << " }\n"; #if 0 out << " /// Conversion operator\n" << " operator const " << tname << "& (void) {\n" << " return Get" << mem_extname << "();\n" << " }\n" << " operator " << tname << "& (void) {\n" << " return Set" << mem_extname << "();\n" << " }\n"; #endif } out << "};\n"; if (CClassCode::GetDoxygenComments()) { out << "/* @} */\n"; } out << "\n"; } void CAliasTypeStrings::GenerateUserCPPCode(CNcbiOstream& /* out */) const { //m_RefType->GenerateUserCPPCode(out); } void CAliasTypeStrings::GenerateTypeCode(CClassContext& ctx) const { if (DataType()->IsTypeAlias()) { m_Nested = true; GenerateCode(ctx); m_Nested = false; return; } m_RefType->GenerateTypeCode(ctx); } void CAliasTypeStrings::GeneratePointerTypeCode(CClassContext& ctx) const { if (DataType()->IsTypeAlias()) { m_Nested = true; GenerateCode(ctx); m_Nested = false; return; } m_RefType->GeneratePointerTypeCode(ctx); } CAliasRefTypeStrings::CAliasRefTypeStrings(const string& className, const CNamespace& ns, const string& fileName, CTypeStrings& ref_type, const CComments& comments) : CParent(comments), m_ClassName(className), m_Namespace(ns), m_FileName(fileName), m_RefType(&ref_type), m_IsObject(m_RefType->GetKind() == eKindObject) { } CTypeStrings::EKind CAliasRefTypeStrings::GetKind(void) const { return m_IsObject ? eKindObject : eKindClass; } const CNamespace& CAliasRefTypeStrings::GetNamespace(void) const { return m_Namespace; } void CAliasRefTypeStrings::GenerateTypeCode(CClassContext& ctx) const { ctx.HPPIncludes().insert(m_FileName); } void CAliasRefTypeStrings::GeneratePointerTypeCode(CClassContext& ctx) const { ctx.AddForwardDeclaration(m_ClassName, m_Namespace); ctx.CPPIncludes().insert(m_FileName); } string CAliasRefTypeStrings::GetCType(const CNamespace& ns) const { return ns.GetNamespaceRef(m_Namespace) + m_ClassName; } string CAliasRefTypeStrings::GetPrefixedCType(const CNamespace& ns, const string& /*methodPrefix*/) const { return GetCType(ns); } bool CAliasRefTypeStrings::HaveSpecialRef(void) const { return m_RefType->HaveSpecialRef(); } string CAliasRefTypeStrings::GetRef(const CNamespace& ns) const { return "CLASS, ("+GetCType(ns)+')'; } bool CAliasRefTypeStrings::CanBeKey(void) const { return m_RefType->CanBeKey(); } bool CAliasRefTypeStrings::CanBeCopied(void) const { return m_RefType->CanBeCopied(); } string CAliasRefTypeStrings::GetInitializer(void) const { return m_IsObject ? NcbiEmptyString : GetDefaultCode(m_RefType->GetInitializer()); } string CAliasRefTypeStrings::GetDestructionCode(const string& expr) const { return m_IsObject ? NcbiEmptyString : m_RefType->GetDestructionCode(expr); } string CAliasRefTypeStrings::GetIsSetCode(const string& var) const { return m_RefType->GetIsSetCode(var); } string CAliasRefTypeStrings::GetResetCode(const string& var) const { return m_IsObject ? var + ".Reset();\n" : m_RefType->GetResetCode(var + ".Set()"); } string CAliasRefTypeStrings::GetDefaultCode(const string& var) const { // No value - return empty string if ( m_IsObject || var.empty() ) { return NcbiEmptyString; } // Cast var to the aliased type return GetCType(GetNamespace()) + "(" + var + ")"; } void CAliasRefTypeStrings::GenerateCode(CClassContext& ctx) const { m_RefType->GenerateCode(ctx); } void CAliasRefTypeStrings::GenerateUserHPPCode(CNcbiOstream& out) const { m_RefType->GenerateUserHPPCode(out); } void CAliasRefTypeStrings::GenerateUserCPPCode(CNcbiOstream& out) const { m_RefType->GenerateUserCPPCode(out); } END_NCBI_SCOPE
26,327
7,927
// Copyright (c) 2012 Intel Corp // Copyright (c) 2012 The Chromium Authors // // 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 co // pies 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 al // l copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM // PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES // S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS // OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH // ETHER 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 "node.h" #include "v8.h" #include "object_life_monitor.h" namespace nw { using v8::Value; using v8::FunctionCallbackInfo; using v8::Handle; using v8::HandleScope; static void GetHiddenValue(const FunctionCallbackInfo<Value>& args) { HandleScope scope(args.GetIsolate()); args.GetReturnValue().Set(args[0]->ToObject()->GetHiddenValue(args[1]->ToString())); } static void SetHiddenValue(const FunctionCallbackInfo<Value>& args) { args[0]->ToObject()->SetHiddenValue(args[1]->ToString(), args[2]); args.GetReturnValue().Set(v8::Undefined(args.GetIsolate())); } static void GetConstructorName(const FunctionCallbackInfo<Value>& args) { args.GetReturnValue().Set(args[0]->ToObject()->GetConstructorName()); } static void SetDestructor(const FunctionCallbackInfo<Value>& args) { nw::ObjectLifeMonitor::BindTo(args[0]->ToObject(), args[1]); args.GetReturnValue().Set(v8::Undefined(args.GetIsolate())); } static void GetCreationContext(const FunctionCallbackInfo<Value>& args) { v8::EscapableHandleScope handle_scope(args.GetIsolate()); v8::Local<v8::Context> creation_context = args[0]->ToObject()-> CreationContext(); args.GetReturnValue().Set(handle_scope.Escape(creation_context->Global())); } static void GetObjectHash(const FunctionCallbackInfo<Value>& args) { v8::EscapableHandleScope handle_scope(args.GetIsolate()); args.GetReturnValue().Set(handle_scope.Escape(v8::Integer::New(args.GetIsolate(), args[0]->ToObject()->GetIdentityHash()))); } void InitializeV8Util(v8::Handle<v8::Object> target, Handle<v8::Value> unused, Handle<v8::Context> context) { NODE_SET_METHOD(target, "getHiddenValue", GetHiddenValue); NODE_SET_METHOD(target, "setHiddenValue", SetHiddenValue); NODE_SET_METHOD(target, "getConstructorName", GetConstructorName); NODE_SET_METHOD(target, "setDestructor", SetDestructor); NODE_SET_METHOD(target, "getCreationContext", GetCreationContext); NODE_SET_METHOD(target, "getObjectHash", GetObjectHash); } } // namespace nw NODE_MODULE_CONTEXT_AWARE_BUILTIN(v8_util, nw::InitializeV8Util)
3,342
1,105
#include "unistd.h" #include <kern/syscall.h> unsigned int sleep(unsigned int sec) { timespec time = {0, 0}; time.tv_sec = sec; return sys::sys$nano_sleep(&time, nullptr); } suseconds_t usleep(suseconds_t sec) { timespec time = {0, 0}; time.tv_sec = 0; time.tv_nsec = sec * 1000; return sys::sys$nano_sleep(&time, nullptr); }
356
155
/** @file * File splitter: splits soapC.cpp into manageable pieces. It is somewhat * intelligent and avoids splitting inside functions or similar places. */ /* * Copyright (C) 2009-2010 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #include <sys/types.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <limits.h> int main(int argc, char *argv[]) { int rc = 0; FILE *pFileIn = NULL; FILE *pFileOut = NULL; char *pBuffer = NULL; do { if (argc != 4) { fprintf(stderr, "split-soapC: Must be started with exactly three arguments,\n" "1) the input file, 2) the directory where to put the output files and\n" "3) the number chunks to create.\n"); rc = 2; break; } char *pEnd = NULL; unsigned long cChunk = strtoul(argv[3], &pEnd, 0); if (cChunk == ULONG_MAX || cChunk == 0 || !argv[3] || *pEnd) { fprintf(stderr, "split-soapC: Given argument \"%s\" is not a valid chunk count.\n", argv[3]); rc = 2; break; } pFileIn = fopen(argv[1], "rb"); if (!pFileIn) { fprintf(stderr, "split-soapC: Cannot open file \"%s\" for reading.\n", argv[1]); rc = 2; break; } int rc2 = fseek(pFileIn, 0, SEEK_END); long cbFileIn = ftell(pFileIn); int rc3 = fseek(pFileIn, 0, SEEK_SET); if (rc3 == -1 || rc2 == -1 || cbFileIn < 0) { fprintf(stderr, "split-soapC: Seek failure.\n"); rc = 2; break; } if (!(pBuffer = (char*)malloc(cbFileIn + 1))) { fprintf(stderr, "split-soapC: Failed to allocate %ld bytes.\n", cbFileIn); rc = 2; break; } if (fread(pBuffer, 1, cbFileIn, pFileIn) != (size_t)cbFileIn) { fprintf(stderr, "split-soapC: Failed to read %ld bytes from input file.\n", cbFileIn); rc = 2; break; } pBuffer[cbFileIn] = '\0'; const char *pLine = pBuffer; unsigned long cbChunk = cbFileIn / cChunk; unsigned long cFiles = 0; unsigned long uLimit = 0; unsigned long cbWritten = 0; unsigned long cIfNesting = 0; unsigned long cBraceNesting = 0; unsigned long cLinesSinceStaticMap = ~0UL / 2; bool fJustZero = false; do { if (!pFileOut) { /* construct output filename */ char szFilename[1024]; sprintf(szFilename, "%s/soapC-%lu.cpp", argv[2], ++cFiles); szFilename[sizeof(szFilename)-1] = '\0'; printf("info: soapC-%lu.cpp\n", cFiles); /* create output file */ if (!(pFileOut = fopen(szFilename, "wb"))) { fprintf(stderr, "split-soapC: Failed to open file \"%s\" for writing\n", szFilename); rc = 2; break; } if (cFiles > 1) fprintf(pFileOut, "#include \"soapH.h\"%s\n", #ifdef RT_OS_WINDOWS "\r" #else /* !RT_OS_WINDOWS */ "" #endif /* !RT_OS_WINDOWS */ ); uLimit += cbChunk; cLinesSinceStaticMap = ~0UL / 2; } /* find begin of next line and print current line */ const char *pNextLine = strchr(pLine, '\n'); size_t cbLine; if (pNextLine) { pNextLine++; cbLine = pNextLine - pLine; } else cbLine = strlen(pLine); if (fwrite(pLine, 1, cbLine, pFileOut) != cbLine) { fprintf(stderr, "split-soapC: Failed to write to output file\n"); rc = 2; break; } cbWritten += cbLine; /* process nesting depth information */ if (!strncmp(pLine, "#if", 3)) cIfNesting++; else if (!strncmp(pLine, "#endif", 6)) { cIfNesting--; if (!cBraceNesting && !cIfNesting) fJustZero = true; } else { for (const char *p = pLine; p < pLine + cbLine; p++) { if (*p == '{') cBraceNesting++; else if (*p == '}') { cBraceNesting--; if (!cBraceNesting && !cIfNesting) fJustZero = true; } } } /* look for static variables used for enum conversion. */ if (!strncmp(pLine, "static const struct soap_code_map", sizeof("static const struct soap_code_map") - 1)) cLinesSinceStaticMap = 0; else cLinesSinceStaticMap++; /* start a new output file if necessary and possible */ if ( cbWritten >= uLimit && cIfNesting == 0 && fJustZero && cFiles < cChunk && cLinesSinceStaticMap > 150 /*hack!*/) { fclose(pFileOut); pFileOut = NULL; } if (rc) break; fJustZero = false; pLine = pNextLine; } while (pLine); printf("split-soapC: Created %lu files.\n", cFiles); } while (0); if (pBuffer) free(pBuffer); if (pFileIn) fclose(pFileIn); if (pFileOut) fclose(pFileOut); return rc; }
6,351
1,934
#ifndef DRAGON_GRAPH_GRAPH_HPP #define DRAGON_GRAPH_GRAPH_HPP #include <limits> #include <map> #include <vector> namespace dragon { /** * `Graph` is an efficient, easy to use generic implementation of the basic * graph data structure. * * @param ValueT type of value of graph nodes. * @param EdgeValueT type of weight of graph edges. * * @note `Graph` do not support multiple edges between the same nodes. */ template <typename ValueT, typename EdgeValueT = int> class Graph { public: using ValueType = ValueT; using EdgeValueType = EdgeValueT; using SizeType = std::size_t; using AdjacencyStructureType = std::map<SizeType, EdgeValueType>; class Node; using size_type = SizeType; // NOLINT private: template <typename T> using Sequence = std::vector<T>; using NodeSequenceType = Sequence<Node>; public: using iterator = typename NodeSequenceType::iterator; // NOLINT using const_iterator = typename NodeSequenceType::const_iterator; // NOLINT public: static constexpr SizeType npos = std::numeric_limits<SizeType>::max(); static constexpr EdgeValueType nweight = std::numeric_limits<EdgeValueType>::max(); public: Graph(SizeType sz = 0, SizeType root = 0) : m_root(root) { for (auto i = 0U; i < sz; ++i) { m_nodes.emplace_back(i); } } Graph(const Graph&) = default; Graph(Graph&&) noexcept = default; Graph& operator=(const Graph&) = default; Graph& operator=(Graph&&) noexcept = default; ~Graph() = default; /// Returns a reference to ith node of the graph. auto& operator[](SizeType index) { return m_nodes[index]; } auto& operator[](SizeType index) const { return m_nodes[index]; } /// Returns begin iterator for the nodes of the graph. auto begin() { return m_nodes.begin(); } auto begin() const { return m_nodes.begin(); } /// Returns end iterator for the nodes of the graph. auto end() { return m_nodes.end(); } auto end() const { return m_nodes.end(); } auto cbegin() const { return m_nodes.cbegin(); } auto cend() const { return m_nodes.cend(); } /** * Clears all nodes of the graph. */ void clear(); /** * Adds a weighted directed edge from node `u` to `v` (`u` -> `v`), * * If an edge already exists from node `u` to node `v`, then the edge weight * is updated. * * @param u first node of the edge. * @param v second node of the edge. * @param weight weight of the edge. */ void add_directed_edge(SizeType u_i, SizeType v_i, EdgeValueType weight = 1); /** * Adds a weighted undirected edge between node `u` and `v`. * * If an undirected edge already exists between nodes `u` and `v`, then the * edge weight is updated. * * @param u first node of the edge. * @param v second node of the edge. * @param weight weight of the edge. */ void add_undirected_edge(SizeType u_i, SizeType v_i, EdgeValueType weight = 1); /** * Remove a directed edge from node `u` to `v`. * * Does nothing if no directed edge exist from node `u` to `v`. * * @param u_i index of the first node * @param v_i index of the second node */ void remove_directed_edge(SizeType u_i, SizeType v_i); /** * Remove an undirected edge between nodes `u` and `v`. * * Does nothing if no undirected edge exist between nodes `u` and `v`. */ void remove_undirected_edge(SizeType u_i, SizeType v_i); /// Reset all nodes color to `Color::white`. void reset_color(); /// Returns the number of nodes in the graph. auto size() const; /// Returns the index of the root node. auto root() const; enum class Color { white, grey, black }; /** * `Node` is a data structure to represent a node of the graph. */ class Node { public: Node(SizeType index) : m_index(index) {} Node(SizeType index, ValueType p_value) : m_index(index), value(p_value) {} Node(const Node&) = default; Node(Node&&) noexcept = default; Node& operator=(const Node&) = default; Node& operator=(Node&&) noexcept = default; ~Node() = default; public: SizeType index() const { return m_index; } ValueType value; AdjacencyStructureType edges; Color color = Color::white; SizeType parent = npos, depth = npos; private: const SizeType m_index; }; public: const NodeSequenceType& nodes = m_nodes; // NOLINT private: /// Stores nodes of the graph. NodeSequenceType m_nodes; /// Stores index of the root node. const SizeType m_root; }; template <typename ValueT, typename EdgeValueT> constexpr typename Graph<ValueT, EdgeValueT>::SizeType Graph<ValueT, EdgeValueT>::npos; template <typename ValueT, typename EdgeValueT> constexpr typename Graph<ValueT, EdgeValueT>::EdgeValueType Graph<ValueT, EdgeValueT>::nweight; template <typename ValueT, typename EdgeValueT> void Graph<ValueT, EdgeValueT>::add_directed_edge(SizeType u_i, SizeType v_i, EdgeValueType weight) { m_nodes[u_i].edges[v_i] = weight; } template <typename ValueT, typename EdgeValueT> void Graph<ValueT, EdgeValueT>::add_undirected_edge(SizeType u_i, SizeType v_i, EdgeValueType weight) { m_nodes[u_i].edges[v_i] = weight; m_nodes[v_i].edges[u_i] = weight; } template <typename ValueT, typename EdgeValueT> void Graph<ValueT, EdgeValueT>::remove_directed_edge(SizeType u_i, SizeType v_i) { m_nodes[u_i].edges.erase(v_i); } template <typename ValueT, typename EdgeValueT> void Graph<ValueT, EdgeValueT>::remove_undirected_edge(SizeType u_i, SizeType v_i) { m_nodes[u_i].edges.erase(v_i); m_nodes[v_i].edges.erase(u_i); } template <typename ValueT, typename EdgeValueT> void Graph<ValueT, EdgeValueT>::clear() { m_nodes.clear(); } template <typename ValueT, typename EdgeValueT> void Graph<ValueT, EdgeValueT>::reset_color() { for (auto& node : m_nodes) { node.color = Color::white; } } template <typename ValueT, typename EdgeValueT> auto Graph<ValueT, EdgeValueT>::size() const { return m_nodes.size(); } template <typename ValueT, typename EdgeValueT> auto Graph<ValueT, EdgeValueT>::root() const { return m_root; } } // namespace dragon #endif
6,337
2,079
#include <algorithm> #include <cmath> #include "GameLayer.h" #include "Player.h" #include "MapManager.h" #include "PauseScene.h" #include "Config.h" #include "Enemy.h" #include "SelectScene.h" #include "Bullet.h" #include "GameVictoryScene.h" #include "GameProcess.h" #include "PauseUILayer.h" #include "audio/include/AudioEngine.h" #include "Debuger.h" using namespace cocos2d; using namespace experimental; GameLayer::~GameLayer() { NotificationCenter::getInstance()->removeAllObservers(this); } GameLayer* GameLayer::create(int level) { auto layer = new(std::nothrow) GameLayer(); if (layer && layer->init(level)) { layer->autorelease(); } else if (layer) { delete layer; layer = nullptr; } return layer; } bool GameLayer::init(int level) { if (!Layer::init()) { return false; } currentLevel = level; this->isInteractable = false; this->isMovable = true; this->isTransition = false; this->damageTaken = 0; auto visibleSize = Director::getInstance()->getVisibleSize(); auto origion = Director::getInstance()->getVisibleOrigin(); AudioEngine::stopAll(); bgmID = AudioEngine::play2d("music/" + std::to_string(level) + ".mp3", true, 0.5f); //add map auto map = MapManager::create(level); map->setPosition(Vec2::ZERO); map->setName("map"); this->addChild(map, 0); //add player auto player = Player::create("Game/playerDown0.png"); player->setName("player"); player->setScale(3.2, 3.2); player->setPosition(map->getPlayerPosition()); player->setOrigion(player->getPosition()); this->addChild(player, 1); auto shadow = Sprite::create("Game/shadow.png"); shadow->setPosition(Vec2(origion.x + visibleSize.width / 2, origion.y + visibleSize.height / 2)); shadow->setName("shadow"); shadow->setOpacity(0); this->addChild(shadow, 20); //add contact call back function auto plistener = EventListenerPhysicsContact::create(); plistener->onContactBegin = [this](PhysicsContact& cont) -> bool { cont.getShapeA()->getBody()->resetForces(); cont.getShapeB()->getBody()->resetForces(); this->onContactBegin(cont.getShapeA()->getBody()->getNode(), cont.getShapeB()->getBody()->getNode()); return true; }; plistener->onContactSeparate = [this](PhysicsContact& cont) { cont.getShapeA()->getBody()->resetForces(); cont.getShapeB()->getBody()->resetForces(); this->onContactEnd(cont.getShapeA()->getBody()->getNode(), cont.getShapeB()->getBody()->getNode()); }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(plistener, this); //add keyboard call back function auto klistener = EventListenerKeyboard::create(); klistener->onKeyPressed = [player,this](EventKeyboard::KeyCode code, Event* event){ if (this->isMovable && player->getStatus() != Unit::Status::Jump) { switch (code) { case EventKeyboard::KeyCode::KEY_A: player->setDirection(Unit::Direction::Left); player->move(); break; case EventKeyboard::KeyCode::KEY_D: player->setDirection(Unit::Direction::Right); player->move(); break; case EventKeyboard::KeyCode::KEY_S: player->setDirection(Unit::Direction::Down); player->move(); break; case EventKeyboard::KeyCode::KEY_W: player->setDirection(Unit::Direction::Up); player->move(); break; } } if (!player->getIsMoving()) { switch (code) { case EventKeyboard::KeyCode::KEY_J: //interact if (!this->interact()) { this->close(); } break; case EventKeyboard::KeyCode::KEY_L: //fire if (player->checkBulletReady()) { player->fire(); this->fire(); } break; case EventKeyboard::KeyCode::KEY_K: //jump if (player->getStatus() != Unit::Status::Jump && player->hasCollection("plumage")) { player->stop(); player->move(Unit::Status::Jump); AudioEngine::play2d("music/jump.mp3", false, 0.5f); } break; case EventKeyboard::KeyCode::KEY_ESCAPE: //pause game if (!isTransition) { auto scene = PauseScene::createScene(); auto layer = dynamic_cast<PauseUILayer*>(scene->getChildByName("layer")); layer->recievePlayerData(player); Director::getInstance()->pushScene(dynamic_cast<Scene*>(this->getParent())); Director::getInstance()->replaceScene(TransitionFade::create(0.5f, scene)); } break; } } }; klistener->onKeyReleased = [player](cocos2d::EventKeyboard::KeyCode code, cocos2d::Event* event) { if (code == EventKeyboard::KeyCode::KEY_A || code == EventKeyboard::KeyCode::KEY_D || code == EventKeyboard::KeyCode::KEY_S || code == EventKeyboard::KeyCode::KEY_W) { player->stop(); } }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(klistener, this); //add schedule this->schedule(schedule_selector(GameLayer::check)); NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(GameLayer::resume), "resume", nullptr); return true; } void GameLayer::resume(Ref*) { //restart all schedule auto player = this->getChildByName("player"); player->unscheduleAllSelectors(); player->schedule(schedule_selector(Player::update)); player->schedule(schedule_selector(Player::blink)); auto map = this->getChildByName("map"); auto list = map->getChildren(); this->unscheduleAllSelectors(); this->schedule(schedule_selector(GameLayer::check)); for (auto node : list) { if (node->getName().substr(0, 5) == "enemy") { node->unscheduleAllSelectors(); node->schedule(schedule_selector(Enemy::update)); node->schedule(schedule_selector(Enemy::patrol)); } } } void GameLayer::onContactBegin(cocos2d::Node* node1, cocos2d::Node* node2) { if (node1 == nullptr || node2 == nullptr) { return; } if (node2->getName() == "player" || node2->getName() == "bullet") { std::swap(node1, node2); } if (node1->getName() == "player" && node2->getName() == "box") { node2->setTag(this->interactingFlag); this->isInteractable = true; } else if (node1->getName() == "player" && node2->getName() == "mov") { auto player = dynamic_cast<Player*>(node1); if (player->hasCollection("strengthGloove")) { node2->setTag(this->movableFlag); this->push(); } } else if (node1->getName() == "player" && node2->getName().substr(0, 5) == "enemy") { auto enemy = dynamic_cast<Enemy*>(node2); damageTaken += enemy->getDamage(); } else if (node1->getName() == "player" && node2->getName() == "trans") { auto pos = static_cast<std::pair<Vec2, Vec2>*>(node2->getUserData()); auto player = dynamic_cast<Player*>(node1); player->setUserData(pos); this->isTransition = true; this->schedule(schedule_selector(GameLayer::turnOff));//turn off and make transition } else if (node1->getName() == "player" && node2->getName() == "door") { auto player = dynamic_cast<Player*>(node1); auto require = *static_cast<std::string*>(node2->getUserData()); //if have key required, open it; otherwise, let player find it if (player->hasCollection(require)) { auto map = dynamic_cast<MapManager*>(this->getChildByName("map")); map->openDoor(node2->getPosition()); map->removeChild(node2); AudioEngine::pause(bgmID); AudioEngine::play2d("music/open.mp3", false, 0.5f); AudioEngine::resumeAll(); } else{ require = "You need:" + require + "*" + std::to_string(player->getPositionY()); auto msg = String::createWithData((const unsigned char*)(require.c_str()), require.length()); msg->retain(); NotificationCenter::getInstance()->postNotification("show", msg); this->isMovable = false; } } else if (node1->getName() == "player" && node2->getName() == "boss") { if (currentLevel - 1 == Process::getInstance()->FileGet()) { Process::getInstance()->FileModify(); } Director::getInstance()->replaceScene(TransitionFade::create(0.5f, GameVictoryScene::createScene())); } else if (node1->getName() == "bullet" && node2->getName() != "player") { if (node2->getName().substr(0, 5) == "enemy") { auto player = dynamic_cast<Player*>(this->getChildByName("player")); auto enemy = dynamic_cast<Enemy*>(node2); if (enemy->hurt(player->getDamage())) { auto map = this->getChildByName("map"); map->removeChild(node2); } } this->removeChild(node1); } } void GameLayer::turnOff(float) { auto shadow = dynamic_cast<Sprite*>(this->getChildByName("shadow")); shadow->setOpacity(shadow->getOpacity() + 5); if (shadow->getOpacity() == 255) { auto player = dynamic_cast<Player*>(this->getChildByName("player")); auto pos = static_cast<std::pair<Vec2, Vec2>*>(player->getUserData()); auto map = dynamic_cast<MapManager*>(this->getChildByName("map")); //reset map's and player's position map->setPosition(map->getPositionX() + pos->first.x, map->getPositionY() + pos->first.y); map->setOffset(pos->first); player->setPosition(pos->second); player->setOrigion(pos->second); this->schedule(schedule_selector(GameLayer::turnOff)); this->unschedule(schedule_selector(GameLayer::turnOff)); this->schedule(schedule_selector(GameLayer::turnOn)); } } void GameLayer::turnOn(float) { auto shadow = dynamic_cast<Sprite*>(this->getChildByName("shadow")); shadow->setOpacity(shadow->getOpacity() - 5); if (shadow->getOpacity() == 0) { this->unschedule(schedule_selector(GameLayer::turnOn)); this->isTransition = false; } } void GameLayer::onContactEnd(cocos2d::Node* node1, cocos2d::Node* node2){ if (node1 == nullptr || node2 == nullptr) { return; } if (node2->getName() == "player") { std::swap(node1, node2); } if (node1->getName() == "player" && node2->getName() == "box") { node2->setTag(0); this->isInteractable = false; } else if (node1->getName() == "player" && node2->getName() == "mov") { node2->setTag(0); } else if (node1->getName() == "player" && node2->getName().substr(0, 5) == "enemy") { auto enemy = dynamic_cast<Enemy*>(node2); damageTaken -= enemy->getDamage(); } } bool GameLayer::interact() { if (!this->isInteractable) { return false; } auto visibleSize = Director::getInstance()->getVisibleSize(); auto map = dynamic_cast<MapManager*>(this->getChildByName("map")); auto box = dynamic_cast<Sprite*>(map->getChildByTag(this->interactingFlag)); auto player = dynamic_cast<Player*>(this->getChildByName("player")); box->setSpriteFrame(SpriteFrame::create("Game/boxOpen.png", Rect(0, 0, 64, 64))); std::string content = *static_cast<std::string*>(box->getUserData()); auto offset = map->getOffset(); //there is something in the box if (content != "") { this->isMovable = false; AudioEngine::pause(bgmID); interactionID = AudioEngine::play2d("music/get.mp3", false, 0.5f); std::string temp = content; temp += "*"; temp += std::to_string(player->getPositionY()); auto msg = String::createWithData((const unsigned char*)(temp.c_str()), temp.length()); msg->retain(); NotificationCenter::getInstance()->postNotification("show", msg); auto data = Config::getInstance()->getObject(content); auto pic = Sprite::create(data.image_path); pic->setScale(3, 3); pic->setPosition(box->getPositionX() + offset.x, box->getPositionY() + offset.y + pic->getBoundingBox().size.height / 2); pic->setName("temp"); this->addChild(pic, 1); player->addCollection(content); //clear the box content = ""; box->setUserData(new std::string(content)); return true; } return false; } void GameLayer::push() { auto map = dynamic_cast<MapManager*>(this->getChildByName("map")); auto player = dynamic_cast<Player*>(this->getChildByName("player")); auto mov = map->getChildByTag(movableFlag); bool flag = false; Vec2 next = mov->getPosition(), offset = map->getOffset(); switch(player->getDirection()) { case Unit::Direction::Up: flag = (player->getPositionY() - offset.y < mov->getPositionY() && abs(player->getPositionX() - offset.x - mov->getPositionX()) <= map->getTileSize() / 2); next.y += map->getTileSize(); break; case Unit::Direction::Down: flag = (player->getPositionY() - offset.y > mov->getPositionY() && abs(player->getPositionX() - offset.x - mov->getPositionX()) <= map->getTileSize() / 2); next.y -= map->getTileSize(); break; case Unit::Direction::Left: flag = (player->getPositionX() - offset.x > mov->getPositionX() && abs(player->getPositionY() - offset.y - mov->getPositionY()) <= map->getTileSize() / 2); next.x -= map->getTileSize(); break; case Unit::Direction::Right: flag = (player->getPositionX() - offset.x < mov->getPositionX() && abs(player->getPositionY() - offset.y - mov->getPositionY()) <= map->getTileSize() / 2); next.x += map->getTileSize(); break; } if (flag && map->isNull(next)) { map->resetMovableObject(mov->getPosition(), next); mov->setPosition(next); mov->setName(""); mov->setTag(0); } } void GameLayer::check(float dt) { auto map = dynamic_cast<MapManager*>(this->getChildByName("map")); auto player = dynamic_cast<Player*>(this->getChildByName("player")); auto realPos = player->getPosition() - map->getOffset() - Vec2(0, player->getBoundingBox().size.height / 2); bool hasHurted = false; if (map->isHole(realPos)) { if (player->getStatus() != Unit::Status::Jump) { hasHurted = true; } } //in the water if (map->isWater(realPos)) { if (player->hasCollection("fipperWebFoot")) { if (player->getIsMoving()) { player->stop(); player->move(Unit::Status::Swim); } else { player->move(Unit::Status::Swim); player->stop(); } } else { hasHurted = true; } } else if (player->getStatus() == Unit::Status::Swim)/*above a hole*/ { player->stop(); player->move(Unit::Status::Stand); } if (hasHurted) { this->isMovable = false; player->move(); player->stop(); player->hurt(1); player->resetPosition(); this->isMovable = true; } //dead, GG if (player->hurt(damageTaken)) { this->isMovable = false; Director::getInstance()->replaceScene(SelectScene::createScene()); } else if (damageTimer > 0) { damageTimer -= dt; } else if (damageTaken > 0) { if (damageTimer <= 0.0f) { player->setProtection(true); damageTimer = 1.0f; } } if (damageTimer <= 0.0f) { player->setProtection(false); } } void GameLayer::fire() { auto player = dynamic_cast<Player*>(this->getChildByName("player")); Unit::Direction dir = player->getDirection(); auto bullet = Bullet::create(); bullet->setName("bullet"); auto size = player->getBoundingBox().size; switch (dir) { case Unit::Up: bullet->setVelocity(Vec2(0, 1)); bullet->setPosition(Vec2(player->getPositionX(), player->getPositionY() + size.height / 2)); break; case Unit::Down: bullet->setVelocity(Vec2(0, -1)); bullet->setPosition(Vec2(player->getPositionX(), player->getPositionY() - size.height / 2)); break; case Unit::Left: bullet->setVelocity(Vec2(-1, 0)); bullet->setPosition(Vec2(player->getPositionX() - size.width / 2, player->getPositionY())); break; case Unit::Right: bullet->setVelocity(Vec2(1, 0)); bullet->setPosition(Vec2(player->getPositionX() + size.width / 2, player->getPositionY())); break; } this->addChild(bullet, 2); AudioEngine::pause(bgmID); AudioEngine::play2d("music/fire.mp3", false, 0.5f); AudioEngine::resumeAll(); } void GameLayer::close() { auto pic = this->getChildByName("temp"); this->isMovable = true; NotificationCenter::getInstance()->postNotification("hide"); if (pic) { this->removeChild(pic, true); AudioEngine::stop(interactionID); AudioEngine::resumeAll(); } }
15,448
5,835
/* Copyright 2020-2021 The Silkrpc Authors 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 <iostream> #include <string> #include <absl/flags/flag.h> #include <absl/flags/parse.h> #include <absl/flags/usage.h> #include <silkworm/common/util.hpp> #include <silkrpc/common/constants.hpp> #include <silkrpc/common/log.hpp> int ethbackend_async(const std::string& target); int ethbackend_coroutines(const std::string& target); int ethbackend(const std::string& target); int kv_seek_async_callback(const std::string& target, const std::string& table_name, const silkworm::Bytes& key, uint32_t timeout); int kv_seek_async_coroutines(const std::string& target, const std::string& table_name, const silkworm::Bytes& key, uint32_t timeout); int kv_seek_async(const std::string& target, const std::string& table_name, const silkworm::Bytes& key, uint32_t timeout); int kv_seek_both(const std::string& target, const std::string& table_name, const silkworm::Bytes& key, const silkworm::Bytes& subkey); int kv_seek(const std::string& target, const std::string& table_name, const silkworm::Bytes& key); ABSL_FLAG(std::string, key, "", "key as hex string w/o leading 0x"); ABSL_FLAG(silkrpc::LogLevel, logLevel, silkrpc::LogLevel::Critical, "logging level as string"); ABSL_FLAG(std::string, seekkey, "", "seek key as hex string w/o leading 0x"); ABSL_FLAG(std::string, subkey, "", "subkey as hex string w/o leading 0x"); ABSL_FLAG(std::string, tool, "", "gRPC remote interface tool name as string"); ABSL_FLAG(std::string, target, silkrpc::kDefaultTarget, "Erigon location as string <address>:<port>"); ABSL_FLAG(std::string, table, "", "database table name as string"); ABSL_FLAG(uint32_t, timeout, silkrpc::kDefaultTimeout.count(), "gRPC call timeout as integer"); int ethbackend_async(int argc, char* argv[]) { auto target{absl::GetFlag(FLAGS_target)}; if (target.empty() || target.find(":") == std::string::npos) { std::cerr << "Parameter target is invalid: [" << target << "]\n"; std::cerr << "Use --target flag to specify the location of Erigon running instance\n"; return -1; } return ethbackend_async(target); } int ethbackend_coroutines(int argc, char* argv[]) { auto target{absl::GetFlag(FLAGS_target)}; if (target.empty() || target.find(":") == std::string::npos) { std::cerr << "Parameter target is invalid: [" << target << "]\n"; std::cerr << "Use --target flag to specify the location of Erigon running instance\n"; return -1; } return ethbackend_coroutines(target); } int ethbackend(int argc, char* argv[]) { auto target{absl::GetFlag(FLAGS_target)}; if (target.empty() || target.find(":") == std::string::npos) { std::cerr << "Parameter target is invalid: [" << target << "]\n"; std::cerr << "Use --target flag to specify the location of Erigon running instance\n"; return -1; } return ethbackend(target); } int kv_seek_async_callback(int argc, char* argv[]) { auto target{absl::GetFlag(FLAGS_target)}; if (target.empty() || target.find(":") == std::string::npos) { std::cerr << "Parameter target is invalid: [" << target << "]\n"; std::cerr << "Use --target flag to specify the location of Erigon running instance\n"; return -1; } auto table_name{absl::GetFlag(FLAGS_table)}; if (table_name.empty()) { std::cerr << "Parameter table is invalid: [" << table_name << "]\n"; std::cerr << "Use --table flag to specify the name of Erigon database table\n"; return -1; } auto key{absl::GetFlag(FLAGS_key)}; const auto key_bytes = silkworm::from_hex(key); if (key.empty() || !key_bytes.has_value()) { std::cerr << "Parameter key is invalid: [" << key << "]\n"; std::cerr << "Use --key flag to specify the key in key-value dupsort table\n"; return -1; } auto timeout{absl::GetFlag(FLAGS_timeout)}; if (timeout < 0) { std::cerr << "Parameter timeout is invalid: [" << timeout << "]\n"; std::cerr << "Use --timeout flag to specify the timeout in msecs for Erigon KV gRPC calls\n"; return -1; } return kv_seek_async_callback(target, table_name, key_bytes.value(), timeout); } int kv_seek_async_coroutines(int argc, char* argv[]) { auto target{absl::GetFlag(FLAGS_target)}; if (target.empty() || target.find(":") == std::string::npos) { std::cerr << "Parameter target is invalid: [" << target << "]\n"; std::cerr << "Use --target flag to specify the location of Erigon running instance\n"; return -1; } auto table_name{absl::GetFlag(FLAGS_table)}; if (table_name.empty()) { std::cerr << "Parameter table is invalid: [" << table_name << "]\n"; std::cerr << "Use --table flag to specify the name of Erigon database table\n"; return -1; } auto key{absl::GetFlag(FLAGS_key)}; const auto key_bytes = silkworm::from_hex(key); if (key.empty() || !key_bytes.has_value()) { std::cerr << "Parameter key is invalid: [" << key << "]\n"; std::cerr << "Use --key flag to specify the key in key-value dupsort table\n"; return -1; } auto timeout{absl::GetFlag(FLAGS_timeout)}; if (timeout < 0) { std::cerr << "Parameter timeout is invalid: [" << timeout << "]\n"; std::cerr << "Use --timeout flag to specify the timeout in msecs for Erigon KV gRPC calls\n"; return -1; } return kv_seek_async_coroutines(target, table_name, key_bytes.value(), timeout); } int kv_seek_async(int argc, char* argv[]) { auto target{absl::GetFlag(FLAGS_target)}; if (target.empty() || target.find(":") == std::string::npos) { std::cerr << "Parameter target is invalid: [" << target << "]\n"; std::cerr << "Use --target flag to specify the location of Erigon running instance\n"; return -1; } auto table_name{absl::GetFlag(FLAGS_table)}; if (table_name.empty()) { std::cerr << "Parameter table is invalid: [" << table_name << "]\n"; std::cerr << "Use --table flag to specify the name of Erigon database table\n"; return -1; } auto key{absl::GetFlag(FLAGS_key)}; const auto key_bytes = silkworm::from_hex(key); if (key.empty() || !key_bytes.has_value()) { std::cerr << "Parameter key is invalid: [" << key << "]\n"; std::cerr << "Use --key flag to specify the key in key-value dupsort table\n"; return -1; } auto timeout{absl::GetFlag(FLAGS_timeout)}; if (timeout < 0) { std::cerr << "Parameter timeout is invalid: [" << timeout << "]\n"; std::cerr << "Use --timeout flag to specify the timeout in msecs for Erigon KV gRPC calls\n"; return -1; } return kv_seek_async(target, table_name, key_bytes.value(), timeout); } int kv_seek_both(int argc, char* argv[]) { auto target{absl::GetFlag(FLAGS_target)}; if (target.empty() || target.find(":") == std::string::npos) { std::cerr << "Parameter target is invalid: [" << target << "]\n"; std::cerr << "Use --target flag to specify the location of Erigon running instance\n"; return -1; } auto table_name{absl::GetFlag(FLAGS_table)}; if (table_name.empty()) { std::cerr << "Parameter table is invalid: [" << table_name << "]\n"; std::cerr << "Use --table flag to specify the name of Erigon database table\n"; return -1; } auto key{absl::GetFlag(FLAGS_key)}; const auto key_bytes = silkworm::from_hex(key); if (key.empty() || !key_bytes.has_value()) { std::cerr << "Parameter key is invalid: [" << key << "]\n"; std::cerr << "Use --key flag to specify the key in key-value dupsort table\n"; return -1; } auto subkey{absl::GetFlag(FLAGS_subkey)}; const auto subkey_bytes = silkworm::from_hex(subkey); if (subkey.empty() || !subkey_bytes.has_value()) { std::cerr << "Parameter subkey is invalid: [" << subkey << "]\n"; std::cerr << "Use --subkey flag to specify the subkey in key-value dupsort table\n"; return -1; } return kv_seek_both(target, table_name, key_bytes.value(), subkey_bytes.value()); } int kv_seek(int argc, char* argv[]) { auto target{absl::GetFlag(FLAGS_target)}; if (target.empty() || target.find(":") == std::string::npos) { std::cerr << "Parameter target is invalid: [" << target << "]\n"; std::cerr << "Use --target flag to specify the location of Erigon running instance\n"; return -1; } auto table_name{absl::GetFlag(FLAGS_table)}; if (table_name.empty()) { std::cerr << "Parameter table is invalid: [" << table_name << "]\n"; std::cerr << "Use --table flag to specify the name of Erigon database table\n"; return -1; } auto key{absl::GetFlag(FLAGS_key)}; const auto key_bytes = silkworm::from_hex(key); if (key.empty() || !key_bytes.has_value()) { std::cerr << "Parameter key is invalid: [" << key << "]\n"; std::cerr << "Use --key flag to specify the key in key-value dupsort table\n"; return -1; } return kv_seek(target, table_name, key_bytes.value()); } int main(int argc, char* argv[]) { absl::SetProgramUsageMessage("Execute specified Silkrpc tool:\n" "\tethbackend\t\t\tquery the Erigon/Silkworm ETHBACKEND remote interface\n" "\tethbackend_async\t\tquery the Erigon/Silkworm ETHBACKEND remote interface\n" "\tethbackend_coroutines\t\tquery the Erigon/Silkworm ETHBACKEND remote interface\n" "\tkv_seek\t\t\t\tquery using SEEK the Erigon/Silkworm Key-Value (KV) remote interface to database\n" "\tkv_seek_async\t\t\tquery using SEEK the Erigon/Silkworm Key-Value (KV) remote interface to database\n" "\tkv_seek_async_callback\t\tquery using SEEK the Erigon/Silkworm Key-Value (KV) remote interface to database\n" "\tkv_seek_async_coroutines\tquery using SEEK the Erigon/Silkworm Key-Value (KV) remote interface to database\n" "\tkv_seek_both\t\t\tquery using SEEK_BOTH the Erigon/Silkworm Key-Value (KV) remote interface to database\n" ); const auto positional_args = absl::ParseCommandLine(argc, argv); if (positional_args.size() < 2) { std::cerr << "No Silkrpc tool specified as first positional argument\n\n"; std::cerr << absl::ProgramUsageMessage(); return -1; } SILKRPC_LOG_VERBOSITY(absl::GetFlag(FLAGS_logLevel)); const std::string tool{positional_args[1]}; if (tool == "ethbackend_async") { return ethbackend_async(argc, argv); } if (tool == "ethbackend_coroutines") { return ethbackend_coroutines(argc, argv); } if (tool == "ethbackend") { return ethbackend(argc, argv); } if (tool == "kv_seek_async_callback") { return kv_seek_async_callback(argc, argv); } if (tool == "kv_seek_async_coroutines") { return kv_seek_async_coroutines(argc, argv); } if (tool == "kv_seek_async") { return kv_seek_async(argc, argv); } if (tool == "kv_seek_both") { return kv_seek_both(argc, argv); } if (tool == "kv_seek") { return kv_seek(argc, argv); } std::cerr << "Unknown tool " << tool << " specified as first argument\n\n"; std::cerr << absl::ProgramUsageMessage(); return -1; }
11,956
4,048
// Copyright 2021 Pichugin Ilya #include "../../../modules/task_3/pichugin_i_sparse_matrix_ccs/pichugin_i_sparse_matrix_ccs.h" std::vector<double> gen_random_matrix_with_zeros(int r, int c) { std::random_device dev; std::mt19937 gen(dev()); std::uniform_real_distribution<> urd(-100, 100); int size = r * c; std::vector<double> matrix(size); for (int i = 0; i < size; i++) { double value = urd(gen); if (abs(value) > 15) { matrix[i] = 0; } else { matrix[i] = value; } } return matrix; } Matrix gen_random_matrix(int r, int c) { if (r < 1 || c < 1) { throw "Error"; } std::vector<double> _matrix = gen_random_matrix_with_zeros(r, c); Matrix matrix; matrix.r = r; matrix.c = c; matrix.col.resize(c + 1); matrix.col[0] = 0; int size = r * c; int count; for (int x = 0; x < c; x++) { count = 0; for (int y = x; y < size; y += c) { if (_matrix[y] != 0) { matrix.non_zero.push_back(_matrix[y]); matrix.row.push_back(y / c); count++; } } matrix.col[x + 1] = matrix.col[x] + count; } matrix.count = matrix.col[c]; return matrix; } std::vector<double> sequential(const Matrix& A, const Matrix& B) { if (A.c != B.r) { throw "Error"; } std::vector<double> result(A.r * B.c, 0); for (int a = 0; a < A.c; a++) { for (int b = 0; b < B.c; b++) { for (int i = A.col[a]; i < A.col[a + 1]; i++) { for (int j = B.col[b]; j < B.col[b + 1]; j++) { if (a == B.row[j]) { result[A.row[i] * B.c + b] += A.non_zero[i] * B.non_zero[j]; } } } } } return result; } Matrix Bcast(const Matrix& _M) { int proc_rank; MPI_Comm_rank(MPI_COMM_WORLD, &proc_rank); Matrix M = _M; MPI_Bcast(&M.c, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&M.r, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&M.count, 1, MPI_INT, 0, MPI_COMM_WORLD); if (proc_rank > 0) { M.non_zero.resize(M.count); M.row.resize(M.count); M.col.resize(M.c + 1); } MPI_Bcast(M.non_zero.data(), M.count, MPI_DOUBLE, 0, MPI_COMM_WORLD); MPI_Bcast(M.row.data(), M.count, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(M.col.data(), M.c + 1, MPI_INT, 0, MPI_COMM_WORLD); return M; } std::vector<double> parallel(const Matrix& _A, const Matrix& _B) { if (_A.c != _B.r) { throw "Error"; } int proc_rank, proc_count; MPI_Comm_rank(MPI_COMM_WORLD, &proc_rank); MPI_Comm_size(MPI_COMM_WORLD, &proc_count); if (proc_count == 1) { return sequential(_A, _B); } Matrix A = Bcast(_A); Matrix B = Bcast(_B); std::vector<double> proc_result(A.r * B.c, 0); for (int a = proc_rank; a < A.c; a += proc_count) { for (int b = 0; b < B.c; b++) { for (int i = A.col[a]; i < A.col[a + 1]; i++) { for (int j = B.col[b]; j < B.col[b + 1]; j++) { if (a == B.row[j]) { proc_result[A.row[i] * B.c + b] += A.non_zero[i] * B.non_zero[j]; } } } } } std::vector<double> result(A.r * B.c); MPI_Reduce(proc_result.data(), result.data(), A.r * B.c, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); MPI_Barrier(MPI_COMM_WORLD); return result; }
3,210
1,491
#include <stan/math/rev/scal.hpp> #include <gtest/gtest.h> #include <math/rev/scal/fun/nan_util.hpp> #include <math/rev/scal/util.hpp> #include <boost/math/special_functions/digamma.hpp> #include <boost/math/special_functions/zeta.hpp> TEST(AgradRev, digamma) { AVAR a = 0.5; AVAR f = digamma(a); EXPECT_FLOAT_EQ(boost::math::digamma(0.5), f.val()); AVEC x = createAVEC(a); VEC grad_f; f.grad(x, grad_f); EXPECT_FLOAT_EQ(4.9348022005446793094, grad_f[0]); } namespace { struct digamma_fun { template <typename T0> inline T0 operator()(const T0& arg1) const { return digamma(arg1); } }; } // namespace TEST(AgradRev, digamma_NaN) { digamma_fun digamma_; test_nan(digamma_, false, true); } TEST(AgradRev, check_varis_on_stack_10) { AVAR a = 0.5; test::check_varis_on_stack(stan::math::digamma(a)); }
836
380
class Solution { public: bool isPalindrome(int x) { string s = to_string(x); int len = s.size(); for(int i=0;i<len/2;i++){ if(s[i]!=s[len-i-1]) return false; } return true; } };
208
100
#ifndef PHPCXX_FCALL_TCC #define PHPCXX_FCALL_TCC #ifndef PHPCXX_FCALL_H #error "Please do not include this file directly, use fcall.h instead" #endif #include "array.h" #include "value.h" #include "bailoutrestorer.h" namespace { /** * @internal * @brief Helper function for codecov (`_zend_bailout` is for some reason not marked as `noreturn`) * @param filename * @param line */ [[noreturn]] static inline void bailout(const char* filename, long int line) { _zend_bailout(const_cast<char*>(filename), line); ZEND_ASSUME(0); } } namespace phpcxx { template<typename... Params> static Value call(const char* name, Params&&... p) { { BailoutRestorer br; JMP_BUF bailout; FCall call(name); EG(bailout) = &bailout; if (EXPECTED(0 == SETJMP(bailout))) { return call(std::forward<Params>(p)...); } } bailout(__FILE__, __LINE__); } template<typename... Params> static Value call(const Value& v, Params&&... p) { { BailoutRestorer br; JMP_BUF bailout; FCall call(v.pzval()); EG(bailout) = &bailout; if (EXPECTED(0 == SETJMP(bailout))) { return call(std::forward<Params>(p)...); } } bailout(__FILE__, __LINE__); } /** * @brief Constructs `zval` from `phpcxx::Value` * @param[in] v `phpcxx::Value` * @return Pointer to `zval` */ template<> [[gnu::returns_nonnull]] inline zval* FCall::paramHelper(phpcxx::Value&& v, zval&) { return v.pzval(); } /** * @brief Constructs `zval` from `phpcxx::Array` * @param[in] v `phpcxx::Array` * @return Pointer to `zval` */ template<> [[gnu::returns_nonnull]] inline zval* FCall::paramHelper(phpcxx::Array&& v, zval&) { return v.pzval(); } template<typename... Params> inline phpcxx::Value FCall::operator()(Params&&... p) { return this->call(IndicesFor<Params...>{}, std::forward<Params>(p)...); } template<typename ...Args, std::size_t ...Is> inline Value FCall::call(indices<Is...>, Args&&... args) { zval zparams[sizeof...(args) ? sizeof...(args) : sizeof...(args) + 1] = { *FCall::paramHelper(std::move(args), zparams[Is])... }; return this->operator()(sizeof...(args), zparams); } } #endif /* PHPCXX_FCALL_TCC */
2,238
848
#include "../Core/Resources/Game.hpp" #include "../Core/Resources/Logger.hpp" #include "../Core/Loading/Loader.hpp" #include "../Core/Menus/MenuMgr.hpp" #include "../Core/Exceptions.hpp" #include "../Core/Utils/Utils.hpp" #include "Menus/MainMenu.hpp" #include "Menus/InGameMenu.hpp" #include "Menus/InventoryMenu.hpp" #ifdef _WIN32 #include <windows.h> #include <direct.h> #else #include <unistd.h> #endif namespace TouhouFanGame { //! @brief The global logger Logger logger{"./latest.log", Logger::LOG_DEBUG}; void setup(Game &game) { logger.debug("Opening main window"); game.resources.screen.reset(new Rendering::Screen{game.resources, "THFgame"}); game.state.menuMgr.addMenu<MainMenu>("main_menu", game.state.map, game.resources, game.state.hud); game.state.menuMgr.addMenu<InGameMenu>("in_game", game, game.state.map, game.state.hud, *game.resources.screen); game.state.menuMgr.addMenu<InventoryMenu>("inventory", game, game.state.map, game.state.hud, *game.resources.screen, game.resources.textures); } //! @brief The game loop void gameLoop(Game &game) { sf::Event event; game.state.menuMgr.changeMenu("main_menu"); while (game.resources.screen->isOpen()) { game.resources.screen->clear(); while (game.resources.screen->pollEvent(event)) if (event.type == sf::Event::Closed) game.resources.screen->close(); for (auto e = game.state.settings.input->pollEvent(); e; e = game.state.settings.input->pollEvent()) game.state.menuMgr.handleEvent(*e); game.state.menuMgr.renderMenu(); game.resources.screen->display(); } } void run() { Game game; //TODO: Add proper font loading. #ifndef _DEBUG try { #endif logger.info("Setting up..."); setup(game); game.resources.font.loadFromFile("assets/arial.ttf"); game.resources.screen->setFont(game.resources.font); logger.info("Loading assets..."); Loader::loadAssets(game); logger.info("Starting game."); gameLoop(game); #ifndef _DEBUG } catch (std::exception &e) { logger.fatal(getLastExceptionName() + ": " + e.what()); Utils::dispMsg( "Fatal Error", "An unrecoverable error occurred\n\n" + getLastExceptionName() + ":\n" + e.what() + "\n\n" "Click OK to close the application", MB_ICONERROR ); throw; } #endif logger.info("Goodbye !"); } } int main(int, char **argv) { std::string progPath = argv[0]; size_t occurence = #ifdef _WIN32 progPath.find_last_of('\\'); #else progPath.find_last_of('/'); #endif if (occurence != std::string::npos) chdir(progPath.substr(0, occurence).c_str()); else TouhouFanGame::logger.warn("Cannot find program path from argv (" + progPath + ")"); #ifndef _DEBUG try { #endif TouhouFanGame::run(); #ifndef _DEBUG } catch (std::exception &) { return EXIT_FAILURE; } #endif return EXIT_SUCCESS; }
2,839
1,151
#include "repeat_key_xor.h" #include <fstream> #include "absl/strings/escaping.h" #include "gtest/gtest.h" namespace cryptopals { namespace { TEST(RepeatKeyXorTest, RepeatKeyXorEncode) { std::string key = "ICE"; std::string plaintext = "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a " "cymbal"; std::string ciphertext = RepeatKeyXorEncode(plaintext, key); EXPECT_EQ( "0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765" "272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27" "282f", absl::BytesToHexString(ciphertext)); } TEST(RepeatKeyXorTest, GetHammingDistance) { std::string str1 = "this is a test"; std::string str2 = "wokka wokka!!!"; EXPECT_EQ(37, GetHammingDistance(str1, str2)); } TEST(RepeatKeyXorTest, BreakRepeatKeyXor) { std::ifstream file("break_repeat_key_xor.txt", std::ios::in | std::ios::binary); ASSERT_TRUE(file.is_open()); std::stringstream ss; ss << file.rdbuf(); std::string ciphertext_base64 = ss.str(); file.close(); std::string ciphertext; ASSERT_TRUE(absl::Base64Unescape(ciphertext_base64, &ciphertext)); BreakRepeatKeyXorOutput output = BreakRepeatKeyXor(ciphertext); EXPECT_EQ("I'm back and I'm ringin' the bell ", output.plaintext.substr(0, output.plaintext.find('\n'))); EXPECT_EQ("Terminator X: Bring the noise", output.key); } } // namespace } // namespace cryptopals
1,481
665
// // RemotePhotoTool - remote camera control software // Copyright (C) 2008-2018 Michael Fink // /// \file JFIFRewriter.hpp JFIF (JPEG File Interchange Format) rewriter // #pragma once // includes #include <ulib/stream/IStream.hpp> /// \brief JFIF rewriter /// Loads JFIF data stream (used internally by JPEG images) and calls OnBlock() when a new block /// arrives. Derived classes can then choose to re-write that block, e.g. EXIF data. class JFIFRewriter { public: /// ctor JFIFRewriter(Stream::IStream& streamIn, Stream::IStream& streamOut) :m_streamIn(streamIn), m_streamOut(streamOut) { } /// starts rewriting process void Start(); /// JFIF block marker enum T_JFIFBlockMarker { SOI = 0xd8, EOI = 0xd9, APP0 = 0xe0, APP1 = 0xe1, ///< Exif data is store in this block DQT = 0xdb, SOF0 = 0xc0, DHT = 0xc4, SOS = 0xda, }; protected: /// called when the next JFIF block is starting virtual void OnBlock(BYTE marker, WORD length); protected: Stream::IStream& m_streamIn; ///< input stream Stream::IStream& m_streamOut; ///< output stream };
1,151
426
/* * * Copyright (c) 2021 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <ota-provider-common/OTAProviderExample.h> #include <app-common/zap-generated/cluster-id.h> #include <app-common/zap-generated/command-id.h> #include <app/CommandPathParams.h> #include <app/clusters/ota-provider/ota-provider-delegate.h> #include <app/util/af.h> #include <lib/core/CHIPTLV.h> #include <lib/support/CHIPMemString.h> #include <lib/support/RandUtils.h> #include <protocols/secure_channel/PASESession.h> // For chip::kTestDeviceNodeId #include <string.h> using chip::ByteSpan; using chip::Span; using chip::app::CommandPathFlags; using chip::app::CommandPathParams; using chip::app::clusters::OTAProviderDelegate; using chip::TLV::ContextTag; using chip::TLV::TLVWriter; constexpr uint8_t kUpdateTokenLen = 32; // must be between 8 and 32 constexpr uint8_t kUpdateTokenStrLen = kUpdateTokenLen * 2 + 1; // Hex string needs 2 hex chars for every byte constexpr size_t kUriMaxLen = 256; void GetUpdateTokenString(const chip::ByteSpan & token, char * buf, size_t bufSize) { const uint8_t * tokenData = static_cast<const uint8_t *>(token.data()); size_t minLength = chip::min(token.size(), bufSize); for (size_t i = 0; i < (minLength / 2) - 1; ++i) { snprintf(&buf[i * 2], bufSize, "%02X", tokenData[i]); } } void GenerateUpdateToken(uint8_t * buf, size_t bufSize) { for (size_t i = 0; i < bufSize; ++i) { buf[i] = chip::GetRandU8(); } } bool GenerateBdxUri(const Span<char> & fileDesignator, Span<char> outUri, size_t availableSize) { static constexpr char bdxPrefix[] = "bdx://"; chip::NodeId nodeId = chip::kTestDeviceNodeId; // TODO: read this dynamically size_t nodeIdHexStrLen = sizeof(nodeId) * 2; size_t expectedLength = strlen(bdxPrefix) + nodeIdHexStrLen + fileDesignator.size(); if (expectedLength >= availableSize) { return false; } size_t written = static_cast<size_t>(snprintf(outUri.data(), availableSize, "%s" ChipLogFormatX64 "%s", bdxPrefix, ChipLogValueX64(nodeId), fileDesignator.data())); return expectedLength == written; } OTAProviderExample::OTAProviderExample() { memset(mOTAFilePath, 0, kFilepathBufLen); } void OTAProviderExample::SetOTAFilePath(const char * path) { if (path != nullptr) { chip::Platform::CopyString(mOTAFilePath, path); } else { memset(mOTAFilePath, 0, kFilepathBufLen); } } EmberAfStatus OTAProviderExample::HandleQueryImage(chip::app::CommandHandler * commandObj, uint16_t vendorId, uint16_t productId, uint16_t imageType, uint16_t hardwareVersion, uint32_t currentVersion, uint8_t protocolsSupported, const chip::Span<const char> & location, bool clientCanConsent, const chip::ByteSpan & metadataForServer) { // TODO: add confiuration for returning BUSY status EmberAfOTAQueryStatus queryStatus = (strlen(mOTAFilePath) ? EMBER_ZCL_OTA_QUERY_STATUS_UPDATE_AVAILABLE : EMBER_ZCL_OTA_QUERY_STATUS_NOT_AVAILABLE); uint32_t delayedActionTimeSec = 0; uint32_t softwareVersion = currentVersion + 1; // This implementation will always indicate that an update is available // (if the user provides a file). bool userConsentNeeded = false; uint8_t updateToken[kUpdateTokenLen] = { 0 }; char strBuf[kUpdateTokenStrLen] = { 0 }; char uriBuf[kUriMaxLen] = { 0 }; GenerateUpdateToken(updateToken, kUpdateTokenLen); GetUpdateTokenString(ByteSpan(updateToken), strBuf, kUpdateTokenStrLen); ChipLogDetail(SoftwareUpdate, "generated updateToken: %s", strBuf); if (strlen(mOTAFilePath)) { // Only doing BDX transport for now GenerateBdxUri(Span<char>(mOTAFilePath, strlen(mOTAFilePath)), Span<char>(uriBuf, 0), kUriMaxLen); ChipLogDetail(SoftwareUpdate, "generated URI: %s", uriBuf); } CommandPathParams cmdParams = { emberAfCurrentEndpoint(), 0 /* mGroupId */, ZCL_OTA_PROVIDER_CLUSTER_ID, ZCL_QUERY_IMAGE_RESPONSE_COMMAND_ID, (CommandPathFlags::kEndpointIdValid) }; TLVWriter * writer = nullptr; uint8_t tagNum = 0; VerifyOrReturnError((commandObj->PrepareCommand(cmdParams) == CHIP_NO_ERROR), EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError((writer = commandObj->GetCommandDataElementTLVWriter()) != nullptr, EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError(writer->Put(ContextTag(tagNum++), queryStatus) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError(writer->Put(ContextTag(tagNum++), delayedActionTimeSec) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError(writer->PutString(ContextTag(tagNum++), uriBuf) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError(writer->Put(ContextTag(tagNum++), softwareVersion) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError(writer->PutBytes(ContextTag(tagNum++), updateToken, kUpdateTokenLen) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError(writer->Put(ContextTag(tagNum++), userConsentNeeded) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError(writer->PutBytes(ContextTag(tagNum++), updateToken, kUpdateTokenLen) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE); // metadata VerifyOrReturnError((commandObj->FinishCommand() == CHIP_NO_ERROR), EMBER_ZCL_STATUS_FAILURE); return EMBER_ZCL_STATUS_SUCCESS; } EmberAfStatus OTAProviderExample::HandleApplyUpdateRequest(chip::app::CommandHandler * commandObj, const chip::ByteSpan & updateToken, uint32_t newVersion) { // TODO: handle multiple transfers by tracking updateTokens // TODO: add configuration for sending different updateAction and delayedActionTime values EmberAfOTAApplyUpdateAction updateAction = EMBER_ZCL_OTA_APPLY_UPDATE_ACTION_PROCEED; // For now, just allow any update request uint32_t delayedActionTimeSec = 0; char tokenBuf[kUpdateTokenStrLen] = { 0 }; GetUpdateTokenString(updateToken, tokenBuf, kUpdateTokenStrLen); ChipLogDetail(SoftwareUpdate, "%s: token: %s, version: %" PRIu32, __FUNCTION__, tokenBuf, newVersion); VerifyOrReturnError(commandObj != nullptr, EMBER_ZCL_STATUS_INVALID_VALUE); CommandPathParams cmdParams = { emberAfCurrentEndpoint(), 0 /* mGroupId */, ZCL_OTA_PROVIDER_CLUSTER_ID, ZCL_APPLY_UPDATE_REQUEST_RESPONSE_COMMAND_ID, (CommandPathFlags::kEndpointIdValid) }; TLVWriter * writer = nullptr; VerifyOrReturnError((commandObj->PrepareCommand(cmdParams) == CHIP_NO_ERROR), EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError((writer = commandObj->GetCommandDataElementTLVWriter()) != nullptr, EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError(writer->Put(ContextTag(0), updateAction) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError(writer->Put(ContextTag(1), delayedActionTimeSec) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError((commandObj->FinishCommand() == CHIP_NO_ERROR), EMBER_ZCL_STATUS_FAILURE); return EMBER_ZCL_STATUS_SUCCESS; } EmberAfStatus OTAProviderExample::HandleNotifyUpdateApplied(const chip::ByteSpan & updateToken, uint32_t currentVersion) { char tokenBuf[kUpdateTokenStrLen] = { 0 }; GetUpdateTokenString(updateToken, tokenBuf, kUpdateTokenStrLen); ChipLogDetail(SoftwareUpdate, "%s: token: %s, version: %" PRIu32, __FUNCTION__, tokenBuf, currentVersion); emberAfSendImmediateDefaultResponse(EMBER_ZCL_STATUS_SUCCESS); return EMBER_ZCL_STATUS_SUCCESS; }
8,625
2,856
#include "LinkList.h" #include <cstdio> int main() { LinkList L1,L2; List_HeadInsert(L1); printf("-------头插法-------\n"); Print_LinkList(L1); printf("\n"); List_TrailInsert(L2); printf("-------尾插法-------\n"); Print_LinkList(L2); printf("\n"); /*按序号查找结点值*/ LNode* p = GetElem(L1, 4); printf("第%d个结点是%d\n", 4, p->data); /*按值查找结点 */ ElemType e; p = LocateElem(L1, 4); printf("查找结点是%d\n", p->data); printf("\n-------原数据-------\n"); Print_LinkList(L2); printf("\n"); /*向一个结点后插入结点*/ Insert(L2, 4, 99); printf("-------向第4个结点后插入99-------\n"); Print_LinkList(L2); printf("\n"); /*向一个结点前插入结点*/ Insert_Prev(L2, 7, 77); printf("-------向第7个结点前插入77-------\n"); Print_LinkList(L2); printf("\n"); /*按序号删除结点,e接收删除结点的值*/ Delete_Elem(L2, 7, e); printf("-------删除第7个结点%d-------\n",e); Print_LinkList(L2); printf("\n"); /*按值删除结点*/ Delete_ElemByValue(L2, 3); printf("-------删除第3个结点-------\n"); Print_LinkList(L2); printf("\n"); /*求表长*/ int len = Length(L2); printf("表长:%d\n", len); return 0; }
1,155
568
#include <iostream> #include <cmath> using namespace std; int int_sqrt(int x); int Mypow(int di,int mi); int main() { int i; for(i=0;i<=100;i++) cout<<i<<" "<<int_sqrt(i)<<endl; system("pause"); return 0; } int int_sqrt(int x) { int i; for(i=0;;i++) { if(x>=Mypow(i,2)&&x<Mypow(i+1,2)) break; } return i; } int Mypow(int di,int mi) { int i,tmp=1; for(i=0;i<mi;i++) tmp*=di; return tmp; }
461
222
// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: MIT /** * @file * @brief HTTP request and response functionality. */ #pragma once #include "azure/core/case_insensitive_containers.hpp" #include "azure/core/dll_import_export.hpp" #include "azure/core/exception.hpp" #include "azure/core/http/http_status_code.hpp" #include "azure/core/http/raw_response.hpp" #include "azure/core/internal/contract.hpp" #include "azure/core/io/body_stream.hpp" #include "azure/core/nullable.hpp" #include "azure/core/url.hpp" #include <algorithm> #include <cstdint> #include <functional> #include <map> #include <memory> #include <stdexcept> #include <string> #include <unordered_set> #include <vector> #if defined(TESTING_BUILD) // Define the class used from tests to validate retry enabled namespace Azure { namespace Core { namespace Test { class TestHttp_getters_Test; class TestHttp_query_parameter_Test; class TestHttp_RequestStartTry_Test; class TestURL_getters_Test; class TestURL_query_parameter_Test; class TransportAdapter_headWithStream_Test; class TransportAdapter_putWithStream_Test; class TransportAdapter_deleteRequestWithStream_Test; class TransportAdapter_patchWithStream_Test; class TransportAdapter_putWithStreamOnFail_Test; class TransportAdapter_SizePutFromFile_Test; class TransportAdapter_SizePutFromFileDefault_Test; class TransportAdapter_SizePutFromFileBiggerPage_Test; }}} // namespace Azure::Core::Test #endif namespace Azure { namespace Core { namespace Http { /********************* Exceptions **********************/ /** * @brief An error while sending the HTTP request with the transport adapter. */ class TransportException final : public Azure::Core::RequestFailedException { public: /** * @brief Constructs `%TransportException` with a \p message string. * * @remark The transport policy will throw this error whenever the transport adapter fail to * perform a request. * * @param whatArg The explanatory string. */ explicit TransportException(std::string const& whatArg) : Azure::Core::RequestFailedException(whatArg) { } }; /** * @brief The range of bytes within an HTTP resource. * * @note Starts at an `Offset` and ends at `Offset + Length - 1` inclusively. */ struct HttpRange final { /** * @brief The starting point of the HTTP Range. * */ int64_t Offset = 0; /** * @brief The size of the HTTP Range. * */ Azure::Nullable<int64_t> Length; }; /** * @brief The method to be performed on the resource identified by the Request. */ class HttpMethod final { public: /** * @brief Constructs `%HttpMethod` from string. * * @note Won't check if \p value is a known HttpMethod defined as per any RFC. * * @param value A given string to represent the `%HttpMethod`. */ explicit HttpMethod(std::string value) : m_value(std::move(value)) {} /** * @brief Compares two instances of `%HttpMethod` for equality. * * @param other Some `%HttpMethod` instance to compare with. * @return `true` if instances are equal; otherwise, `false`. */ bool operator==(const HttpMethod& other) const { return m_value == other.m_value; } /** * @brief Compares two instances of `%HttpMethod` for equality. * * @param other Some `%HttpMethod` instance to compare with. * @return `false` if instances are equal; otherwise, `true`. */ bool operator!=(const HttpMethod& other) const { return !(*this == other); } /** * @brief Returns the `%HttpMethod` represented as a string. */ const std::string& ToString() const { return m_value; } /** * @brief The representation of a `GET` HTTP method based on [RFC 7231] * (https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.1). */ AZ_CORE_DLLEXPORT const static HttpMethod Get; /** * @brief The representation of a `HEAD` HTTP method based on [RFC 7231] * (https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.2). */ AZ_CORE_DLLEXPORT const static HttpMethod Head; /** * @brief The representation of a `POST` HTTP method based on [RFC 7231] * (https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.3). */ AZ_CORE_DLLEXPORT const static HttpMethod Post; /** * @brief The representation of a `PUT` HTTP method based on [RFC 7231] * (https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.4). */ AZ_CORE_DLLEXPORT const static HttpMethod Put; /** * @brief The representation of a `DELETE` HTTP method based on [RFC 7231] * (https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.5). */ AZ_CORE_DLLEXPORT const static HttpMethod Delete; /** * @brief The representation of a `PATCH` HTTP method based on [RFC 5789] * (https://datatracker.ietf.org/doc/html/rfc5789). */ AZ_CORE_DLLEXPORT const static HttpMethod Patch; private: std::string m_value; }; // extensible enum HttpMethod namespace Policies { namespace _internal { class RetryPolicy; }} // namespace Policies::_internal /** * @brief A request message from a client to a server. * * @details Includes, within the first line of the message, the HttpMethod to be applied to the * resource, the URL of the resource, and the protocol version in use. */ class Request final { friend class Azure::Core::Http::Policies::_internal::RetryPolicy; #if defined(TESTING_BUILD) // make tests classes friends to validate set Retry friend class Azure::Core::Test::TestHttp_getters_Test; friend class Azure::Core::Test::TestHttp_query_parameter_Test; friend class Azure::Core::Test::TestHttp_RequestStartTry_Test; friend class Azure::Core::Test::TestURL_getters_Test; friend class Azure::Core::Test::TestURL_query_parameter_Test; // make tests classes friends to validate private Request ctor that takes both stream and bool friend class Azure::Core::Test::TransportAdapter_headWithStream_Test; friend class Azure::Core::Test::TransportAdapter_putWithStream_Test; friend class Azure::Core::Test::TransportAdapter_deleteRequestWithStream_Test; friend class Azure::Core::Test::TransportAdapter_patchWithStream_Test; friend class Azure::Core::Test::TransportAdapter_putWithStreamOnFail_Test; friend class Azure::Core::Test::TransportAdapter_SizePutFromFile_Test; friend class Azure::Core::Test::TransportAdapter_SizePutFromFileDefault_Test; friend class Azure::Core::Test::TransportAdapter_SizePutFromFileBiggerPage_Test; #endif private: HttpMethod m_method; Url m_url; CaseInsensitiveMap m_headers; CaseInsensitiveMap m_retryHeaders; Azure::Core::IO::BodyStream* m_bodyStream; // flag to know where to insert header bool m_retryModeEnabled{false}; bool m_shouldBufferResponse{true}; // Expected to be called by a Retry policy to reset all headers set after this function was // previously called void StartTry(); /** * @brief Construct an #Azure::Core::Http::Request. * * @param httpMethod HttpMethod. * @param url %Request URL. * @param bodyStream #Azure::Core::IO::BodyStream. * @param shouldBufferResponse A boolean value indicating whether the returned response should * be buffered or returned as a body stream instead. */ explicit Request( HttpMethod httpMethod, Url url, Azure::Core::IO::BodyStream* bodyStream, bool shouldBufferResponse) : m_method(std::move(httpMethod)), m_url(std::move(url)), m_bodyStream(bodyStream), m_retryModeEnabled(false), m_shouldBufferResponse(shouldBufferResponse) { AZURE_ASSERT_MSG(bodyStream, "The bodyStream pointer cannot be null."); } public: /** * @brief Constructs a `%Request`. * * @param httpMethod HTTP method. * @param url %Request URL. * @param bodyStream #Azure::Core::IO::BodyStream. */ explicit Request(HttpMethod httpMethod, Url url, Azure::Core::IO::BodyStream* bodyStream) : Request(httpMethod, std::move(url), bodyStream, true) { } /** * @brief Constructs a `%Request`. * * @param httpMethod HTTP method. * @param url %Request URL. * @param shouldBufferResponse A boolean value indicating whether the returned response should * be buffered or returned as a body stream instead. */ explicit Request(HttpMethod httpMethod, Url url, bool shouldBufferResponse); /** * @brief Constructs a `%Request`. * * @param httpMethod HTTP method. * @param url %Request URL. */ explicit Request(HttpMethod httpMethod, Url url); /** * @brief Set an HTTP header to the #Azure::Core::Http::Request. * * @remark If the header key does not exists, it is added. * * * @param name The name for the header to be set or added. * @param value The value for the header to be set or added. * * @throw if \p name is an invalid header key. */ void SetHeader(std::string const& name, std::string const& value); /** * @brief Remove an HTTP header. * * @param name HTTP header name. */ void RemoveHeader(std::string const& name); // Methods used by transport layer (and logger) to send request /** * @brief Get HttpMethod. * */ HttpMethod GetMethod() const; /** * @brief Get HTTP headers. * */ CaseInsensitiveMap GetHeaders() const; /** * @brief Get HTTP body as #Azure::Core::IO::BodyStream. * */ Azure::Core::IO::BodyStream* GetBodyStream() { return this->m_bodyStream; } /** * @brief A value indicating whether the returned raw response for this request will be buffered * within a memory buffer or if it will be returned as a body stream instead. */ bool ShouldBufferResponse() { return this->m_shouldBufferResponse; } /** * @brief Get URL. * */ Url& GetUrl() { return this->m_url; } /** * @brief Get URL. * */ Url const& GetUrl() const { return this->m_url; } }; namespace _detail { struct RawResponseHelpers final { /** * @brief Insert a header into \p headers checking that \p headerName does not contain invalid * characters. * * @param headers The headers map where to insert header. * @param headerName The header name for the header to be inserted. * @param headerValue The header value for the header to be inserted. * * @throw if \p headerName is invalid. */ static void InsertHeaderWithValidation( CaseInsensitiveMap& headers, std::string const& headerName, std::string const& headerValue); static void inline SetHeader( Azure::Core::Http::RawResponse& response, uint8_t const* const first, uint8_t const* const last) { // get name and value from header auto start = first; auto end = std::find(start, last, ':'); if (end == last) { throw std::invalid_argument("Invalid header. No delimiter ':' found."); } // Always toLower() headers auto headerName = Azure::Core::_internal::StringExtensions::ToLower(std::string(start, end)); start = end + 1; // start value while (start < last && (*start == ' ' || *start == '\t')) { ++start; } end = std::find(start, last, '\r'); auto headerValue = std::string(start, end); // remove \r response.SetHeader(headerName, headerValue); } }; } // namespace _detail namespace _internal { struct HttpShared final { AZ_CORE_DLLEXPORT static char const ContentType[]; AZ_CORE_DLLEXPORT static char const ApplicationJson[]; AZ_CORE_DLLEXPORT static char const Accept[]; AZ_CORE_DLLEXPORT static char const MsRequestId[]; AZ_CORE_DLLEXPORT static char const MsClientRequestId[]; static inline std::string GetHeaderOrEmptyString( Azure::Core::CaseInsensitiveMap const& headers, std::string const& headerName) { auto header = headers.find(headerName); if (header != headers.end()) { return header->second; // second is the header value. } return {}; // empty string } }; } // namespace _internal }}} // namespace Azure::Core::Http
12,682
3,778
#include "task.hpp" #include "../tasks/hold-scope.hpp" #include <anarch/critical> namespace Alux { void ExitSyscall(anarch::SyscallArgs & args) { bool aborted = args.PopBool(); HoldScope scope; scope.ExitTask(aborted ? Task::KillReasonAbort : Task::KillReasonNormal); } anarch::SyscallRet GetPidSyscall() { AssertCritical(); Task & t = Thread::GetCurrent()->GetTask(); return anarch::SyscallRet::Integer32((uint32_t)t.GetIdentifier()); } anarch::SyscallRet GetUidSyscall() { AssertCritical(); Task & t = Thread::GetCurrent()->GetTask(); return anarch::SyscallRet::Integer32((uint32_t)t.GetUserIdentifier()); } }
635
239
#include <benchmark/benchmark.h> #ifdef __clang__ #pragma clang diagnostic ignored "-Wreturn-type" #endif extern "C" { extern int ExternInt; extern int ExternInt2; extern int ExternInt3; inline int Add42(int x) { return x + 42; } struct NotTriviallyCopyable { NotTriviallyCopyable(); explicit NotTriviallyCopyable(int x) : value(x) {} NotTriviallyCopyable(NotTriviallyCopyable const&); int value; }; struct Large { int value; int data[2]; }; } // CHECK-LABEL: test_with_rvalue: extern "C" void test_with_rvalue() { benchmark::DoNotOptimize(Add42(0)); // CHECK: movl $42, %eax // CHECK: ret } // CHECK-LABEL: test_with_large_rvalue: extern "C" void test_with_large_rvalue() { benchmark::DoNotOptimize(Large{ExternInt, {ExternInt, ExternInt}}); // CHECK: ExternInt(%rip) // CHECK: movl %eax, -{{[0-9]+}}(%[[REG:[a-z]+]] // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]]) // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]]) // CHECK: ret } // CHECK-LABEL: test_with_non_trivial_rvalue: extern "C" void test_with_non_trivial_rvalue() { benchmark::DoNotOptimize(NotTriviallyCopyable(ExternInt)); // CHECK: mov{{l|q}} ExternInt(%rip) // CHECK: ret } // CHECK-LABEL: test_with_lvalue: extern "C" void test_with_lvalue() { int x = 101; benchmark::DoNotOptimize(x); // CHECK-GNU: movl $101, %eax // CHECK-CLANG: movl $101, -{{[0-9]+}}(%[[REG:[a-z]+]]) // CHECK: ret } // CHECK-LABEL: test_with_large_lvalue: extern "C" void test_with_large_lvalue() { Large L{ExternInt, {ExternInt, ExternInt}}; benchmark::DoNotOptimize(L); // CHECK: ExternInt(%rip) // CHECK: movl %eax, -{{[0-9]+}}(%[[REG:[a-z]+]]) // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]]) // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]]) // CHECK: ret } // CHECK-LABEL: test_with_non_trivial_lvalue: extern "C" void test_with_non_trivial_lvalue() { NotTriviallyCopyable NTC(ExternInt); benchmark::DoNotOptimize(NTC); // CHECK: ExternInt(%rip) // CHECK: movl %eax, -{{[0-9]+}}(%[[REG:[a-z]+]]) // CHECK: ret } // CHECK-LABEL: test_with_const_lvalue: extern "C" void test_with_const_lvalue() { const int x = 123; benchmark::DoNotOptimize(x); // CHECK: movl $123, %eax // CHECK: ret } // CHECK-LABEL: test_with_large_const_lvalue: extern "C" void test_with_large_const_lvalue() { const Large L{ExternInt, {ExternInt, ExternInt}}; benchmark::DoNotOptimize(L); // CHECK: ExternInt(%rip) // CHECK: movl %eax, -{{[0-9]+}}(%[[REG:[a-z]+]]) // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]]) // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]]) // CHECK: ret } // CHECK-LABEL: test_with_non_trivial_const_lvalue: extern "C" void test_with_non_trivial_const_lvalue() { const NotTriviallyCopyable Obj(ExternInt); benchmark::DoNotOptimize(Obj); // CHECK: mov{{q|l}} ExternInt(%rip) // CHECK: ret } // CHECK-LABEL: test_div_by_two: extern "C" int test_div_by_two(int input) { int divisor = 2; benchmark::DoNotOptimize(divisor); return input / divisor; // CHECK: movl $2, [[DEST:.*]] // CHECK: idivl [[DEST]] // CHECK: ret } // CHECK-LABEL: test_inc_integer: extern "C" int test_inc_integer() { int x = 0; for (int i=0; i < 5; ++i) benchmark::DoNotOptimize(++x); // CHECK: movl $1, [[DEST:.*]] // CHECK: {{(addl \$1,|incl)}} [[DEST]] // CHECK: {{(addl \$1,|incl)}} [[DEST]] // CHECK: {{(addl \$1,|incl)}} [[DEST]] // CHECK: {{(addl \$1,|incl)}} [[DEST]] // CHECK-CLANG: movl [[DEST]], %eax // CHECK: ret return x; } // CHECK-LABEL: test_pointer_rvalue extern "C" void test_pointer_rvalue() { // CHECK: movl $42, [[DEST:.*]] // CHECK: leaq [[DEST]], %rax // CHECK-CLANG: movq %rax, -{{[0-9]+}}(%[[REG:[a-z]+]]) // CHECK: ret int x = 42; benchmark::DoNotOptimize(&x); } // CHECK-LABEL: test_pointer_const_lvalue: extern "C" void test_pointer_const_lvalue() { // CHECK: movl $42, [[DEST:.*]] // CHECK: leaq [[DEST]], %rax // CHECK-CLANG: movq %rax, -{{[0-9]+}}(%[[REG:[a-z]+]]) // CHECK: ret int x = 42; int * const xp = &x; benchmark::DoNotOptimize(xp); } // CHECK-LABEL: test_pointer_lvalue: extern "C" void test_pointer_lvalue() { // CHECK: movl $42, [[DEST:.*]] // CHECK: leaq [[DEST]], %rax // CHECK-CLANG: movq %rax, -{{[0-9]+}}(%[[REG:[a-z+]+]]) // CHECK: ret int x = 42; int *xp = &x; benchmark::DoNotOptimize(xp); }
4,308
1,884
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <folly/portability/GTest.h> #include <thrift/lib/cpp2/BadFieldAccess.h> #include <thrift/test/gen-cpp2/UnionFieldRef_types.h> using namespace std; namespace apache { namespace thrift { namespace test { TEST(UnionFieldTest, basic) { Basic a; EXPECT_EQ(a.getType(), Basic::__EMPTY__); EXPECT_FALSE(a.int64_ref()); EXPECT_THROW(a.int64_ref().value(), bad_field_access); EXPECT_FALSE(a.list_i32_ref()); EXPECT_THROW(a.list_i32_ref().value(), bad_field_access); EXPECT_FALSE(a.str_ref()); EXPECT_THROW(a.str_ref().value(), bad_field_access); const int64_t int64 = 42LL << 42; a.int64_ref() = int64; EXPECT_EQ(a.getType(), Basic::int64); EXPECT_TRUE(a.int64_ref()); EXPECT_EQ(a.int64_ref().value(), int64); EXPECT_FALSE(a.list_i32_ref()); EXPECT_THROW(a.list_i32_ref().value(), bad_field_access); EXPECT_FALSE(a.str_ref()); EXPECT_THROW(a.str_ref().value(), bad_field_access); const vector<int32_t> list_i32 = {3, 1, 2}; a.list_i32_ref() = list_i32; EXPECT_EQ(a.getType(), Basic::list_i32); EXPECT_FALSE(a.int64_ref()); EXPECT_THROW(a.int64_ref().value(), bad_field_access); EXPECT_TRUE(a.list_i32_ref()); EXPECT_EQ(a.list_i32_ref().value(), list_i32); EXPECT_FALSE(a.str_ref()); EXPECT_THROW(a.str_ref().value(), bad_field_access); const string str = "foo"; a.str_ref() = str; EXPECT_EQ(a.getType(), Basic::str); EXPECT_FALSE(a.int64_ref()); EXPECT_THROW(a.int64_ref().value(), bad_field_access); EXPECT_FALSE(a.list_i32_ref()); EXPECT_THROW(a.list_i32_ref().value(), bad_field_access); EXPECT_TRUE(a.str_ref()); EXPECT_EQ(a.str_ref().value(), str); } TEST(UnionFieldTest, operator_deref) { Basic a; EXPECT_THROW(*a.int64_ref(), bad_field_access); EXPECT_THROW(*a.str_ref(), bad_field_access); a.int64_ref() = 42; EXPECT_EQ(*a.int64_ref(), 42); EXPECT_THROW(*a.str_ref(), bad_field_access); a.str_ref() = "foo"; EXPECT_EQ(*a.str_ref(), "foo"); EXPECT_THROW(*a.int64_ref(), bad_field_access); } TEST(UnionFieldTest, operator_assign) { Basic a; a.int64_ref() = 4; a.list_i32_ref() = {1, 2}; // `folly::StringPiece` has explicit support for explicit conversion to // `std::string`-like types, make sure that keeps working here. folly::StringPiece lvalue = "lvalue"; a.str_ref() = lvalue; a.str_ref() = folly::StringPiece("xvalue"); } TEST(UnionFieldTest, duplicate_type) { DuplicateType a; EXPECT_EQ(a.getType(), DuplicateType::__EMPTY__); EXPECT_FALSE(a.str1_ref()); EXPECT_THROW(a.str1_ref().value(), bad_field_access); EXPECT_FALSE(a.list_i32_ref()); EXPECT_THROW(a.list_i32_ref().value(), bad_field_access); EXPECT_FALSE(a.str2_ref()); EXPECT_THROW(a.str2_ref().value(), bad_field_access); a.str1_ref() = string(1000, '1'); EXPECT_EQ(a.getType(), DuplicateType::str1); EXPECT_TRUE(a.str1_ref()); EXPECT_EQ(a.str1_ref().value(), string(1000, '1')); EXPECT_FALSE(a.list_i32_ref()); EXPECT_THROW(a.list_i32_ref().value(), bad_field_access); EXPECT_FALSE(a.str2_ref()); EXPECT_THROW(a.str2_ref().value(), bad_field_access); a.list_i32_ref() = vector<int32_t>(1000, 2); EXPECT_EQ(a.getType(), DuplicateType::list_i32); EXPECT_FALSE(a.str1_ref()); EXPECT_THROW(a.str1_ref().value(), bad_field_access); EXPECT_TRUE(a.list_i32_ref()); EXPECT_EQ(a.list_i32_ref().value(), vector<int32_t>(1000, 2)); EXPECT_FALSE(a.str2_ref()); EXPECT_THROW(a.str2_ref().value(), bad_field_access); a.str2_ref() = string(1000, '3'); EXPECT_EQ(a.getType(), DuplicateType::str2); EXPECT_FALSE(a.str1_ref()); EXPECT_THROW(a.str1_ref().value(), bad_field_access); EXPECT_FALSE(a.list_i32_ref()); EXPECT_THROW(a.list_i32_ref().value(), bad_field_access); EXPECT_TRUE(a.str2_ref()); EXPECT_EQ(a.str2_ref().value(), string(1000, '3')); a.str1_ref() = string(1000, '4'); EXPECT_EQ(a.getType(), DuplicateType::str1); EXPECT_TRUE(a.str1_ref()); EXPECT_EQ(a.str1_ref().value(), string(1000, '4')); EXPECT_FALSE(a.list_i32_ref()); EXPECT_THROW(a.list_i32_ref().value(), bad_field_access); EXPECT_FALSE(a.str2_ref()); EXPECT_THROW(a.str2_ref().value(), bad_field_access); a.str1_ref() = string(1000, '5'); EXPECT_EQ(a.getType(), DuplicateType::str1); EXPECT_TRUE(a.str1_ref()); EXPECT_EQ(a.str1_ref().value(), string(1000, '5')); EXPECT_FALSE(a.list_i32_ref()); EXPECT_THROW(a.list_i32_ref().value(), bad_field_access); EXPECT_FALSE(a.str2_ref()); EXPECT_THROW(a.str2_ref().value(), bad_field_access); } TEST(UnionFieldTest, const_union) { { const Basic a; EXPECT_EQ(a.getType(), Basic::__EMPTY__); EXPECT_FALSE(a.int64_ref()); EXPECT_THROW(a.int64_ref().value(), bad_field_access); EXPECT_FALSE(a.list_i32_ref()); EXPECT_THROW(a.list_i32_ref().value(), bad_field_access); EXPECT_FALSE(a.str_ref()); EXPECT_THROW(a.str_ref().value(), bad_field_access); } { Basic b; const string str = "foo"; b.str_ref() = str; const Basic& a = b; EXPECT_EQ(a.getType(), Basic::str); EXPECT_FALSE(a.int64_ref()); EXPECT_THROW(a.int64_ref().value(), bad_field_access); EXPECT_FALSE(a.list_i32_ref()); EXPECT_THROW(a.list_i32_ref().value(), bad_field_access); EXPECT_TRUE(a.str_ref()); EXPECT_EQ(a.str_ref().value(), str); } } TEST(UnionFieldTest, emplace) { DuplicateType a; EXPECT_EQ(a.str1_ref().emplace(5, '0'), "00000"); EXPECT_EQ(*a.str1_ref(), "00000"); EXPECT_TRUE(a.str1_ref().has_value()); EXPECT_EQ(a.str2_ref().emplace({'1', '2', '3', '4', '5'}), "12345"); EXPECT_EQ(*a.str2_ref(), "12345"); EXPECT_TRUE(a.str2_ref().has_value()); const vector<int32_t> list_i32 = {3, 1, 2}; EXPECT_EQ(a.list_i32_ref().emplace(list_i32), list_i32); EXPECT_EQ(*a.list_i32_ref(), list_i32); EXPECT_TRUE(a.list_i32_ref().has_value()); } TEST(UnionFieldTest, ensure) { Basic a; EXPECT_FALSE(a.str_ref()); EXPECT_EQ(a.str_ref().ensure(), ""); EXPECT_TRUE(a.str_ref()); EXPECT_EQ(a.str_ref().emplace("123"), "123"); EXPECT_EQ(a.str_ref().ensure(), "123"); EXPECT_EQ(*a.str_ref(), "123"); EXPECT_EQ(a.int64_ref().ensure(), 0); EXPECT_FALSE(a.str_ref()); } TEST(UnionFieldTest, member_of_pointer_operator) { Basic a; EXPECT_THROW(a.list_i32_ref()->push_back(3), bad_field_access); a.list_i32_ref().emplace({1, 2}); a.list_i32_ref()->push_back(3); EXPECT_EQ(a.list_i32_ref(), (vector<int32_t>{1, 2, 3})); } TEST(UnionFieldTest, comparison) { auto test = [](auto i) { Basic a; auto ref = a.int64_ref(); ref = i; EXPECT_LE(ref, i + 1); EXPECT_LE(ref, i); EXPECT_LE(i, ref); EXPECT_LE(i - 1, ref); EXPECT_LT(ref, i + 1); EXPECT_LT(i - 1, ref); EXPECT_GT(ref, i - 1); EXPECT_GT(i + 1, ref); EXPECT_GE(ref, i - 1); EXPECT_GE(ref, i); EXPECT_GE(i, ref); EXPECT_GE(i + 1, ref); EXPECT_EQ(ref, i); EXPECT_EQ(i, ref); EXPECT_NE(ref, i - 1); EXPECT_NE(i - 1, ref); }; { SCOPED_TRACE("same type"); test(int64_t(10)); } { SCOPED_TRACE("different type"); test('a'); } } TEST(UnionFieldTest, field_ref_api) { Basic a; a.str_ref() = "foo"; EXPECT_EQ(*a.str_ref(), "foo"); EXPECT_EQ(*as_const(a).str_ref(), "foo"); EXPECT_EQ(*move(a).str_ref(), "foo"); EXPECT_EQ(*move(as_const(a)).str_ref(), "foo"); } TEST(UnionFieldTest, TreeNode) { TreeNode root; root.nodes_ref().emplace(2); (*root.nodes_ref())[0].data_ref() = 10; (*root.nodes_ref())[1].data_ref() = 20; EXPECT_EQ(root.nodes_ref()->size(), 2); EXPECT_EQ((*root.nodes_ref())[0].data_ref(), 10); EXPECT_EQ((*root.nodes_ref())[1].data_ref(), 20); EXPECT_THROW(*root.data_ref(), bad_field_access); EXPECT_THROW(*(*root.nodes_ref())[0].nodes_ref(), bad_field_access); EXPECT_THROW(*(*root.nodes_ref())[1].nodes_ref(), bad_field_access); } } // namespace test } // namespace thrift } // namespace apache
8,497
3,891
/*++ Copyright (c) 2012 Microsoft Corporation Module Name: tactic_manager.cpp Abstract: Collection of tactics & probes Author: Leonardo (leonardo) 2012-03-06 Notes: --*/ #include "cmd_context/tactic_manager.h" tactic_manager::~tactic_manager() { finalize_tactic_cmds(); finalize_probes(); } void tactic_manager::insert(tactic_cmd * c) { symbol const & s = c->get_name(); SASSERT(!m_name2tactic.contains(s)); m_name2tactic.insert(s, c); m_tactics.push_back(c); } void tactic_manager::insert(probe_info * p) { symbol const & s = p->get_name(); SASSERT(!m_name2probe.contains(s)); m_name2probe.insert(s, p); m_probes.push_back(p); } tactic_cmd * tactic_manager::find_tactic_cmd(symbol const & s) const { tactic_cmd * c = nullptr; m_name2tactic.find(s, c); return c; } probe_info * tactic_manager::find_probe(symbol const & s) const { probe_info * p = nullptr; m_name2probe.find(s, p); return p; } void tactic_manager::finalize_tactic_cmds() { std::for_each(m_tactics.begin(), m_tactics.end(), delete_proc<tactic_cmd>()); m_tactics.reset(); m_name2tactic.reset(); } void tactic_manager::finalize_probes() { std::for_each(m_probes.begin(), m_probes.end(), delete_proc<probe_info>()); m_probes.reset(); m_name2probe.reset(); }
1,336
548
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <ctime> #include <cctype> #include <cassert> #include <iostream> #include <sstream> #include <iomanip> #include <string> #include <vector> #include <stack> #include <queue> #include <deque> #include <list> #include <set> #include <map> #include <bitset> #include <algorithm> #include <numeric> #include <complex> #define D(x) cerr << #x << " = " << (x) << endl; #define REP(i,a,n) for(int i=(a); i<(int)(n); i++) #define FOREACH(it,v) for(__typeof((v).begin()) it=(v).begin(); it!=(v).end(); ++it) #define ALL(v) (v).begin(), (v).end() using namespace std; typedef long long int64; const int INF = (int)(1e9); const int64 INFLL = (int64)(1e18); const double EPS = 1e-13; long long sieve_size; bitset<2000010> bs; vector<int> primes; void sieve(long long upperbound) { sieve_size = upperbound+1; bs.set(); bs[0] = bs[1] = 0; for(long long i = 2; i <= sieve_size; i++) if(bs[i]) { for(long long j = i*i; j <= sieve_size; j+=i) bs[j] = 0; primes.push_back((int)i); } } int main() { #ifdef LOCAL freopen("inputs/prime_gap.in", "r", stdin); freopen("outputs/prime_gap.out", "w", stdout); #else ios_base::sync_with_stdio(false); #endif sieve(1500000); int k; while(cin >> k) { if(k == 0) break; int i = int(upper_bound(primes.begin(), primes.end(), k) - primes.begin()) - 1; int j = int(lower_bound(primes.begin(), primes.end(), k) - primes.begin()); cout << (primes[j] - primes[i]) << endl; } return 0; }
1,549
677
#include <bits/stdc++.h> using namespace std; int N, M, P; vector<tuple<int, int, long long>> grafo; long long resp; void BellmanFord(int inicio) { vector<long long> distancia(N + 1, LONG_LONG_MAX); distancia[inicio] = 0; //Verifica o looping negativo (não há máximo) vector<bool> verifica(N + 1, false); verifica[N] = true; int primeiro, segundo; long long moedas; //Verifica o máximo possível, exceto os casos de looping negativo for (int i = 1; i < N; i++) { for (int j = 0; j < M; j++) { tie(primeiro, segundo, moedas) = grafo[j]; if (distancia[primeiro] != LONG_LONG_MAX && distancia[primeiro] + moedas < distancia[segundo]) { distancia[segundo] = distancia[primeiro] + moedas; } //Salvando o vértice percorrido if(verifica[segundo] == true) { verifica[primeiro] = true; } } } //Salvando a resposta máxima atual resp = max((long long)0, -distancia[N]); //Percorrendo o grafo e verificando se há o looping negativo for(int i = 0; i < M; i++) { tie(primeiro, segundo, moedas) = grafo[i]; if (distancia[primeiro] != LONG_LONG_MAX && distancia[primeiro] + moedas < distancia[segundo] && verifica[segundo] == true) { //Looping negativo = impossível resp = -1; break; } } } int main() { cin >> N >> M >> P; for (int i = 0; i < M; i++) { int primeiro, segundo; long long moedas; cin >> primeiro >> segundo >> moedas; grafo.push_back({primeiro, segundo, P - moedas}); } BellmanFord(1); cout << resp << endl; return 0; }
2,005
679
#include "pch.h" #include "RenderTargetImpl.h" #include "ogl.h" #include <Kore/Graphics4/Graphics.h> #include <Kore/Log.h> #include <Kore/System.h> #ifdef KORE_ANDROID #include <GLContext.h> #endif using namespace Kore; #ifndef GL_RGBA16F_EXT #define GL_RGBA16F_EXT 0x881A #endif #ifndef GL_RGBA32F_EXT #define GL_RGBA32F_EXT 0x8814 #endif #ifndef GL_R16F_EXT #define GL_R16F_EXT 0x822D #endif #ifndef GL_R32F_EXT #define GL_R32F_EXT 0x822E #endif #ifndef GL_HALF_FLOAT #define GL_HALF_FLOAT 0x140B #endif #ifndef GL_RED #define GL_RED GL_LUMINANCE #endif namespace { int pow(int pow) { int ret = 1; for (int i = 0; i < pow; ++i) ret *= 2; return ret; } int getPower2(int i) { for (int power = 0;; ++power) if (pow(power) >= i) return pow(power); } bool nonPow2RenderTargetsSupported() { #ifdef KORE_OPENGL_ES #ifdef KORE_ANDROID if (ndk_helper::GLContext::GetInstance()->GetGLVersion() >= 3.0) return true; else return false; #else return true; #endif #else return true; #endif } } void RenderTargetImpl::setupDepthStencil(GLenum texType, int depthBufferBits, int stencilBufferBits, int width, int height) { if (depthBufferBits > 0 && stencilBufferBits > 0) { _hasDepth = true; #if defined(KORE_OPENGL_ES) && !defined(KORE_PI) && !defined(KORE_HTML5) GLenum internalFormat = GL_DEPTH24_STENCIL8_OES; #elif defined(KORE_OPENGL_ES) GLenum internalFormat = NULL; #else GLenum internalFormat; if (depthBufferBits == 24) internalFormat = GL_DEPTH24_STENCIL8; else internalFormat = GL_DEPTH32F_STENCIL8; #endif // Renderbuffer // glGenRenderbuffers(1, &_depthRenderbuffer); // glCheckErrors(); // glBindRenderbuffer(GL_RENDERBUFFER, _depthRenderbuffer); // glCheckErrors(); // glRenderbufferStorage(GL_RENDERBUFFER, internalFormat, width, height); // glCheckErrors(); // #ifdef KORE_OPENGL_ES // glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depthRenderbuffer); // glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _depthRenderbuffer); // #else // glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _depthRenderbuffer); // #endif // glCheckErrors(); // Texture glGenTextures(1, &_depthTexture); glCheckErrors(); glBindTexture(texType, _depthTexture); glCheckErrors(); glTexImage2D(texType, 0, internalFormat, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 0); glCheckErrors(); glTexParameteri(texType, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(texType, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(texType, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(texType, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glCheckErrors(); glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer); glCheckErrors(); #ifdef KORE_OPENGL_ES glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, texType, _depthTexture, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, texType, _depthTexture, 0); #else glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, texType, _depthTexture, 0); #endif glCheckErrors(); } else if (depthBufferBits > 0) { _hasDepth = true; // Renderbuffer // glGenRenderbuffers(1, &_depthRenderbuffer); // glCheckErrors(); // glBindRenderbuffer(GL_RENDERBUFFER, _depthRenderbuffer); // glCheckErrors(); // glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width, height); // glCheckErrors(); // glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depthRenderbuffer); // glCheckErrors(); // Texture glGenTextures(1, &_depthTexture); glCheckErrors(); glBindTexture(texType, _depthTexture); glCheckErrors(); GLint format = depthBufferBits == 16 ? GL_DEPTH_COMPONENT16 : GL_DEPTH_COMPONENT; glTexImage2D(texType, 0, format, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 0); glCheckErrors(); glTexParameteri(texType, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(texType, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(texType, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(texType, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glCheckErrors(); glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer); glCheckErrors(); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, texType, _depthTexture, 0); glCheckErrors(); } } Graphics4::RenderTarget::RenderTarget(int width, int height, int depthBufferBits, bool antialiasing, RenderTargetFormat format, int stencilBufferBits, int contextId) : width(width), height(height), isCubeMap(false), isDepthAttachment(false) { _hasDepth = false; if (nonPow2RenderTargetsSupported()) { texWidth = width; texHeight = height; } else { texWidth = getPower2(width); texHeight = getPower2(height); } this->format = (int)format; this->contextId = contextId; // (DK) required on windows/gl Kore::System::makeCurrent(contextId); glGenTextures(1, &_texture); glCheckErrors(); glBindTexture(GL_TEXTURE_2D, _texture); glCheckErrors(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glCheckErrors(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glCheckErrors(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glCheckErrors(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glCheckErrors(); switch (format) { case Target128BitFloat: #ifdef KORE_OPENGL_ES glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_EXT, texWidth, texHeight, 0, GL_RGBA, GL_FLOAT, 0); #else glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, texWidth, texHeight, 0, GL_RGBA, GL_FLOAT, 0); #endif break; case Target64BitFloat: #ifdef KORE_OPENGL_ES glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_EXT, texWidth, texHeight, 0, GL_RGBA, GL_HALF_FLOAT, 0); #else glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, texWidth, texHeight, 0, GL_RGBA, GL_HALF_FLOAT, 0); #endif break; case Target16BitDepth: #ifdef KORE_OPENGL_ES glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); #endif glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, texWidth, texHeight, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 0); break; case Target8BitRed: glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, texWidth, texHeight, 0, GL_RED, GL_UNSIGNED_BYTE, 0); break; case Target16BitRedFloat: glTexImage2D(GL_TEXTURE_2D, 0, GL_R16F_EXT, texWidth, texHeight, 0, GL_RED, GL_HALF_FLOAT, 0); break; case Target32BitRedFloat: glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F_EXT, texWidth, texHeight, 0, GL_RED, GL_FLOAT, 0); break; case Target32Bit: default: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); } glCheckErrors(); glGenFramebuffers(1, &_framebuffer); glCheckErrors(); glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer); glCheckErrors(); setupDepthStencil(GL_TEXTURE_2D, depthBufferBits, stencilBufferBits, texWidth, texHeight); if (format == Target16BitDepth) { glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, _texture, 0); #ifndef KORE_OPENGL_ES glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); #endif } else { glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _texture, 0); } glCheckErrors(); // GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; // glDrawBuffers(1, drawBuffers); glBindFramebuffer(GL_FRAMEBUFFER, 0); glCheckErrors(); glBindTexture(GL_TEXTURE_2D, 0); glCheckErrors(); } Graphics4::RenderTarget::RenderTarget(int cubeMapSize, int depthBufferBits, bool antialiasing, RenderTargetFormat format, int stencilBufferBits, int contextId) : width(cubeMapSize), height(cubeMapSize), isCubeMap(true), isDepthAttachment(false) { _hasDepth = false; if (nonPow2RenderTargetsSupported()) { texWidth = width; texHeight = height; } else { texWidth = getPower2(width); texHeight = getPower2(height); } this->format = (int)format; this->contextId = contextId; // (DK) required on windows/gl Kore::System::makeCurrent(contextId); glGenTextures(1, &_texture); glCheckErrors(); glBindTexture(GL_TEXTURE_CUBE_MAP, _texture); glCheckErrors(); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glCheckErrors(); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glCheckErrors(); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glCheckErrors(); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glCheckErrors(); switch (format) { case Target128BitFloat: #ifdef KORE_OPENGL_ES for (int i = 0; i < 6; i++) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA32F_EXT, texWidth, texHeight, 0, GL_RGBA, GL_FLOAT, 0); #else for (int i = 0; i < 6; i++) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA32F, texWidth, texHeight, 0, GL_RGBA, GL_FLOAT, 0); #endif break; case Target64BitFloat: #ifdef KORE_OPENGL_ES for (int i = 0; i < 6; i++) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA16F_EXT, texWidth, texHeight, 0, GL_RGBA, GL_HALF_FLOAT, 0); #else for (int i = 0; i < 6; i++) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA16F, texWidth, texHeight, 0, GL_RGBA, GL_HALF_FLOAT, 0); #endif break; case Target16BitDepth: #ifdef KORE_OPENGL_ES glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST); #endif for (int i = 0; i < 6; i++) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_DEPTH_COMPONENT16, texWidth, texHeight, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 0); break; case Target32Bit: default: for (int i = 0; i < 6; i++) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); } glCheckErrors(); glGenFramebuffers(1, &_framebuffer); glCheckErrors(); glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer); glCheckErrors(); setupDepthStencil(GL_TEXTURE_CUBE_MAP, depthBufferBits, stencilBufferBits, texWidth, texHeight); if (format == Target16BitDepth) { isDepthAttachment = true; #ifndef KORE_OPENGL_ES glDrawBuffer(GL_NONE); glCheckErrors(); glReadBuffer(GL_NONE); glCheckErrors(); #endif } glBindFramebuffer(GL_FRAMEBUFFER, 0); glCheckErrors(); glBindTexture(GL_TEXTURE_CUBE_MAP, 0); glCheckErrors(); } Graphics4::RenderTarget::~RenderTarget() { { GLuint textures[] = {_texture}; glDeleteTextures(1, textures); } if (_hasDepth) { GLuint textures[] = {_depthTexture}; glDeleteTextures(1, textures); } GLuint framebuffers[] = {_framebuffer}; glDeleteFramebuffers(1, framebuffers); } void Graphics4::RenderTarget::useColorAsTexture(TextureUnit unit) { glActiveTexture(GL_TEXTURE0 + unit.unit); glCheckErrors(); glBindTexture(isCubeMap ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D, _texture); glCheckErrors(); } void Graphics4::RenderTarget::useDepthAsTexture(TextureUnit unit) { glActiveTexture(GL_TEXTURE0 + unit.unit); glCheckErrors(); glBindTexture(isCubeMap ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D, _depthTexture); glCheckErrors(); } void Graphics4::RenderTarget::setDepthStencilFrom(RenderTarget* source) { glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, isCubeMap ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D, source->_depthTexture, 0); } void Graphics4::RenderTarget::getPixels(u8* data) { glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer); switch ((RenderTargetFormat)format) { case Target128BitFloat: glReadPixels(0, 0, texWidth, texHeight, GL_RGBA, GL_FLOAT, data); break; case Target64BitFloat: glReadPixels(0, 0, texWidth, texHeight, GL_RGBA, GL_HALF_FLOAT, data); break; case Target8BitRed: glReadPixels(0, 0, texWidth, texHeight, GL_RED, GL_UNSIGNED_BYTE, data); break; case Target16BitRedFloat: glReadPixels(0, 0, texWidth, texHeight, GL_RED, GL_HALF_FLOAT, data); break; case Target32BitRedFloat: glReadPixels(0, 0, texWidth, texHeight, GL_RED, GL_FLOAT, data); break; case Target32Bit: default: glReadPixels(0, 0, texWidth, texHeight, GL_RGBA, GL_UNSIGNED_BYTE, data); } } void Graphics4::RenderTarget::generateMipmaps(int levels) { glBindTexture(GL_TEXTURE_2D, _texture); glCheckErrors(); glGenerateMipmap(GL_TEXTURE_2D); glCheckErrors(); }
12,490
5,599
#include <inttypes.h> #include <cstdint> #include "utility/log.hpp" #include "utility/time.hpp" int main(void) { LOG_INFO("Delay Application Starting..."); LOG_INFO( "This example merely prints a statement every second using the delay " "function."); uint32_t counter = 0; while (true) { LOG_INFO("[%lu] Hello, World! (milliseconds = %lu)", counter++, static_cast<uint32_t>(Milliseconds())); Delay(1000); } return 0; }
473
169
#include "deck.h" #include "game.h" #include <iostream> int main() { // create and shuffle deck game::Deck deck{ }; deck.shuffle(); // play a single game of blackjack std::cout << (game::playBlackjack(deck) ? "You win!\n" : "You lose!\n"); return 0; }
268
104
#pragma once #ifndef libtiffconvert_font_h #define libtiffconvert_font_h #include "libtiffconvert.h" #include <string> #include <cstdint> #include <Windows.h> namespace TiffConvert { /// <summary> /// Flags that specify how a font should be loaded. /// </summary> enum FontConfig : uint32_t { FONT_BOLD = (1 << 0), FONT_ITALIC = (1 << 1), FONT_UNDERLINE = (1 << 2), FONT_STRIKEOUT = (1 << 3), FONT_ANTIALIAS = (1 << 4) }; /// <summary> /// Font describes a font that is loaded through libtiffconvert. /// </summary> class Font { private: const font_handle* m_Font = nullptr; public: /// <summary> /// Convert a LOGFONTA descriptor to usable flags. /// </summary> /// <param name="descriptor">The LOGFONTA instance.</param> /// <param name="hq">Whether or not anti-aliasing should be applied to the font.</param> /// <returns>Combined flags.</returns> static uint32_t FlagsFromLogFont(const LOGFONTA& descriptor, bool hq = true); /// <summary> /// Construct a new font by name, height and flags. /// </summary> /// <param name="name">Font family name.</param> /// <param name="height">Font height, in points.</param> /// <param name="flags">Font style flags.</param> Font(const std::string& name, uint32_t height, uint32_t flags = 0); /// <summary> /// Construct a new font by name, height and flags. /// </summary> /// <param name="name">Font family name.</param> /// <param name="height">Font height, in points.</param> /// <param name="flags">Font style flags.</param> Font(const std::wstring& name, uint32_t height, uint32_t flags = 0); /// <summary> /// Construct a new font from LOGFONTA descriptor. /// </summary> /// <param name="descriptor">The LOGFONTA instance.</param> Font(const LOGFONTA& descriptor); /// <summary> /// The destructor frees the internal font. /// </summary> ~Font(); /// <summary> /// Get a const pointer to the internal font object. /// </summary> /// <returns>A const pointer to the internal font object.</returns> const font_handle* get() const noexcept; }; } #endif
2,145
816
// Copyright 2002 The Trustees of Indiana University. // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // Boost.MultiArray Library // Authors: Ronald Garcia // Jeremy Siek // Andrew Lumsdaine // See http://www.boost.org/libs/multi_array for documentation. // // storage_order.cpp - testing storage_order-isms. // #include "boost/multi_array.hpp" #include "boost/test/minimal.hpp" #include "boost/array.hpp" int test_main(int,char*[]) { const int ndims=3; int data_row[] = { 0,1,2,3, 4,5,6,7, 8,9,10,11, 12,13,14,15, 16,17,18,19, 20,21,22,23 }; int data_col[] = { 0,12, 4,16, 8,20, 1,13, 5,17, 9,21, 2,14, 6,18, 10,22, 3,15, 7,19, 11,23 }; const int num_elements = 24; // fortran storage order { typedef boost::multi_array<int,ndims> array; array::extent_gen extents; array A(extents[2][3][4],boost::fortran_storage_order()); A.assign(data_col,data_col+num_elements); int* num = data_row; for (array::index i = 0; i != 2; ++i) for (array::index j = 0; j != 3; ++j) for (array::index k = 0; k != 4; ++k) BOOST_CHECK(A[i][j][k] == *num++); } // Mimic fortran_storage_order using // general_storage_order data placement { typedef boost::general_storage_order<ndims> storage; typedef boost::multi_array<int,ndims> array; array::size_type ordering[] = {0,1,2}; bool ascending[] = {true,true,true}; array::extent_gen extents; array A(extents[2][3][4], storage(ordering,ascending)); A.assign(data_col,data_col+num_elements); int* num = data_row; for (array::index i = 0; i != 2; ++i) for (array::index j = 0; j != 3; ++j) for (array::index k = 0; k != 4; ++k) BOOST_CHECK(A[i][j][k] == *num++); } // general_storage_order with arbitrary storage order { typedef boost::general_storage_order<ndims> storage; typedef boost::multi_array<int,ndims> array; array::size_type ordering[] = {2,0,1}; bool ascending[] = {true,true,true}; array::extent_gen extents; array A(extents[2][3][4], storage(ordering,ascending)); int data_arb[] = { 0,1,2,3, 12,13,14,15, 4,5,6,7, 16,17,18,19, 8,9,10,11, 20,21,22,23 }; A.assign(data_arb,data_arb+num_elements); int* num = data_row; for (array::index i = 0; i != 2; ++i) for (array::index j = 0; j != 3; ++j) for (array::index k = 0; k != 4; ++k) BOOST_CHECK(A[i][j][k] == *num++); } // general_storage_order with descending dimensions. { const int ndims=3; typedef boost::general_storage_order<ndims> storage; typedef boost::multi_array<int,ndims> array; array::size_type ordering[] = {2,0,1}; bool ascending[] = {false,true,true}; array::extent_gen extents; array A(extents[2][3][4], storage(ordering,ascending)); int data_arb[] = { 12,13,14,15, 0,1,2,3, 16,17,18,19, 4,5,6,7, 20,21,22,23, 8,9,10,11 }; A.assign(data_arb,data_arb+num_elements); int* num = data_row; for (array::index i = 0; i != 2; ++i) for (array::index j = 0; j != 3; ++j) for (array::index k = 0; k != 4; ++k) BOOST_CHECK(A[i][j][k] == *num++); } return boost::exit_success; }
3,702
1,582
#include "ResetButton.h" using namespace GUI; ResetButton::ResetButton(QWidget *parent) : QLabel(parent) { setAttribute(Qt::WA_StyledBackground, true); setProperty("class", "ResetButton"); setText("Try again!"); setAlignment(Qt::AlignCenter); setStyleSheet(".ResetButton { background-color: rgb(143,122,102); border-radius: 10px; font: bold; color: white; }"); } void ResetButton::mousePressEvent(QMouseEvent *event) { emit clicked(); //QLabel::mousePressEvent(event); }
519
173
struct Tweet { int id; int time; Tweet* next = nullptr; Tweet(int id, int time) : id(id), time(time) {} }; struct User { int id; unordered_set<int> followeeIds; Tweet* tweetHead = nullptr; User() {} User(int id) : id(id) { follow(id); // follow himself } void follow(int followeeId) { followeeIds.insert(followeeId); } void unfollow(int followeeId) { followeeIds.erase(followeeId); } void post(int tweetId, int time) { Tweet* oldTweetHead = tweetHead; tweetHead = new Tweet(tweetId, time); tweetHead->next = oldTweetHead; } }; class Twitter { public: /** Compose a new tweet. */ void postTweet(int userId, int tweetId) { if (!users.count(userId)) users[userId] = User(userId); users[userId].post(tweetId, time++); } /** * Retrieve the 10 most recent tweet ids in the user's news feed. Each item in * the news feed must be posted by users who the user followed or by the user * herself. Tweets must be ordered from most recent to least recent. */ vector<int> getNewsFeed(int userId) { if (!users.count(userId)) return {}; vector<int> newsFeed; auto compare = [](const Tweet* a, const Tweet* b) { return a->time < b->time; }; priority_queue<Tweet*, vector<Tweet*>, decltype(compare)> maxHeap(compare); for (const int followeeId : users[userId].followeeIds) { Tweet* tweetHead = users[followeeId].tweetHead; if (tweetHead) maxHeap.push(tweetHead); } int count = 0; while (!maxHeap.empty() && count++ < 10) { Tweet* tweet = maxHeap.top(); maxHeap.pop(); newsFeed.push_back(tweet->id); if (tweet->next) maxHeap.push(tweet->next); } return newsFeed; } /** * Follower follows a followee. * If the operation is invalid, it should be a no-op. */ void follow(int followerId, int followeeId) { if (followerId == followeeId) return; if (!users.count(followerId)) users[followerId] = User(followerId); if (!users.count(followeeId)) users[followeeId] = User(followeeId); users[followerId].follow(followeeId); } /** * Follower unfollows a followee. * If the operation is invalid, it should be a no-op. */ void unfollow(int followerId, int followeeId) { if (followerId == followeeId) return; if (users.count(followerId) && users.count(followeeId)) users[followerId].unfollow(followeeId); } private: int time = 0; unordered_map<int, User> users; // {userId: User} };
2,560
920
#include "NMLModelRenderer.h" #include "components/ThreadWorker.h" #include "datasources/VectorDataSource.h" #include "graphics/Shader.h" #include "graphics/ShaderManager.h" #include "graphics/ViewState.h" #include "graphics/utils/GLContext.h" #include "layers/VectorLayer.h" #include "projections/Projection.h" #include "renderers/MapRenderer.h" #include "renderers/components/RayIntersectedElement.h" #include "utils/Log.h" #include <nml/GLModel.h> #include <nml/GLTexture.h> #include <nml/GLResourceManager.h> namespace { struct GLResourceDeleter : carto::ThreadWorker { GLResourceDeleter(std::shared_ptr<carto::nml::GLResourceManager> glResourceManager) : _glResourceManager(std::move(glResourceManager)) { } virtual void operator () () { _glResourceManager->deleteAll(); } private: std::shared_ptr<carto::nml::GLResourceManager> _glResourceManager; }; } namespace carto { NMLModelRenderer::NMLModelRenderer() : _glResourceManager(), _glModelMap(), _elements(), _tempElements(), _mapRenderer(), _options(), _mutex() { } NMLModelRenderer::~NMLModelRenderer() { if (_glResourceManager) { if (auto mapRenderer = _mapRenderer.lock()) { mapRenderer->addRenderThreadCallback(std::make_shared<GLResourceDeleter>(_glResourceManager)); } } } void NMLModelRenderer::addElement(const std::shared_ptr<NMLModel>& element) { _tempElements.push_back(element); } void NMLModelRenderer::refreshElements() { std::lock_guard<std::mutex> lock(_mutex); _elements.clear(); _elements.swap(_tempElements); } void NMLModelRenderer::updateElement(const std::shared_ptr<NMLModel>& element) { std::lock_guard<std::mutex> lock(_mutex); if (std::find(_elements.begin(), _elements.end(), element) == _elements.end()) { _elements.push_back(element); } } void NMLModelRenderer::removeElement(const std::shared_ptr<NMLModel>& element) { std::lock_guard<std::mutex> lock(_mutex); _elements.erase(std::remove(_elements.begin(), _elements.end(), element), _elements.end()); } void NMLModelRenderer::setMapRenderer(const std::weak_ptr<MapRenderer>& mapRenderer) { std::lock_guard<std::mutex> lock(_mutex); _mapRenderer = mapRenderer; } void NMLModelRenderer::setOptions(const std::weak_ptr<Options>& options) { std::lock_guard<std::mutex> lock(_mutex); _options = options; } void NMLModelRenderer::offsetLayerHorizontally(double offset) { std::lock_guard<std::mutex> lock(_mutex); for (const std::shared_ptr<NMLModel>& element : _elements) { element->getDrawData()->offsetHorizontally(offset); } } void NMLModelRenderer::onSurfaceCreated(const std::shared_ptr<ShaderManager>& shaderManager, const std::shared_ptr<TextureManager>& textureManager) { _glResourceManager = std::make_shared<nml::GLResourceManager>(); _glModelMap.clear(); nml::GLTexture::registerGLExtensions(); } bool NMLModelRenderer::onDrawFrame(float deltaSeconds, const ViewState& viewState) { std::lock_guard<std::mutex> lock(_mutex); std::shared_ptr<Options> options = _options.lock(); if (!options) { return false; } // Set expected GL state glDepthMask(GL_TRUE); glEnable(GL_DEPTH_TEST); // Calculate lighting state Color ambientColor = options->getAmbientLightColor(); cglib::vec4<float> ambientLightColor = cglib::vec4<float>(ambientColor.getR(), ambientColor.getG(), ambientColor.getB(), ambientColor.getA()) * (1.0f / 255.0f); Color mainColor = options->getMainLightColor(); cglib::vec4<float> mainLightColor = cglib::vec4<float>(mainColor.getR(), mainColor.getG(), mainColor.getB(), mainColor.getA()) * (1.0f / 255.0f); MapVec mainDir = options->getMainLightDirection(); cglib::vec3<float> mainLightDir = cglib::unit(cglib::vec3<float>::convert(cglib::transform_vector(cglib::vec3<double>(mainDir.getX(), mainDir.getY(), mainDir.getZ()), viewState.getModelviewMat()))); // Draw models cglib::mat4x4<float> projMat = cglib::mat4x4<float>::convert(viewState.getProjectionMat()); for (const std::shared_ptr<NMLModel>& element : _elements) { const NMLModelDrawData& drawData = *element->getDrawData(); std::shared_ptr<nml::Model> sourceModel = drawData.getSourceModel(); std::shared_ptr<nml::GLModel> glModel = _glModelMap[sourceModel]; if (!glModel) { glModel = std::make_shared<nml::GLModel>(*sourceModel); glModel->create(*_glResourceManager); _glModelMap[sourceModel] = glModel; } cglib::mat4x4<float> mvMat = cglib::mat4x4<float>::convert(viewState.getModelviewMat() * drawData.getLocalMat()); nml::RenderState renderState(projMat, mvMat, ambientLightColor, mainLightColor, -mainLightDir); glModel->draw(*_glResourceManager, renderState); } // Remove stale models for (auto it = _glModelMap.begin(); it != _glModelMap.end(); ) { if (it->first.expired()) { it = _glModelMap.erase(it); } else { it++; } } // Dispose unused models _glResourceManager->deleteUnused(); // Restore expected GL state glDepthMask(GL_TRUE); glDisable(GL_DEPTH_TEST); glActiveTexture(GL_TEXTURE0); GLContext::CheckGLError("NMLModelRenderer::onDrawFrame"); return false; } void NMLModelRenderer::onSurfaceDestroyed() { _glResourceManager.reset(); _glModelMap.clear(); } void NMLModelRenderer::calculateRayIntersectedElements(const std::shared_ptr<VectorLayer>& layer, const cglib::ray3<double>& ray, const ViewState& viewState, std::vector<RayIntersectedElement>& results) const { std::lock_guard<std::mutex> lock(_mutex); for (const std::shared_ptr<NMLModel>& element : _elements) { const NMLModelDrawData& drawData = *element->getDrawData(); std::shared_ptr<nml::Model> sourceModel = drawData.getSourceModel(); auto modelIt = _glModelMap.find(sourceModel); if (modelIt == _glModelMap.end()) { continue; } std::shared_ptr<nml::GLModel> glModel = modelIt->second; cglib::mat4x4<double> modelMat = drawData.getLocalMat(); cglib::mat4x4<double> invModelMat = cglib::inverse(modelMat); cglib::ray3<double> rayModel = cglib::transform_ray(ray, invModelMat); cglib::bbox3<double> modelBounds = cglib::bbox3<double>::convert(glModel->getBounds()); if (!cglib::intersect_bbox(modelBounds, rayModel)) { continue; } std::vector<nml::RayIntersection> intersections; glModel->calculateRayIntersections(rayModel, intersections); for (std::size_t i = 0; i < intersections.size(); i++) { cglib::vec3<double> pos = cglib::transform_point(intersections[i].pos, modelMat); MapPos clickPos(pos(0), pos(1), pos(2)); MapPos projectedClickPos = layer->getDataSource()->getProjection()->fromInternal(clickPos); int priority = static_cast<int>(results.size()); results.push_back(RayIntersectedElement(std::static_pointer_cast<VectorElement>(element), layer, projectedClickPos, projectedClickPos, priority, true)); } } } }
7,897
2,400
#pragma once #include "depthai-shared/utility/Serialization.hpp" namespace dai { /** * Specifies a connection between nodes IOs */ struct NodeConnectionSchema { int64_t node1Id = -1; std::string node1OutputGroup; std::string node1Output; int64_t node2Id = -1; std::string node2InputGroup; std::string node2Input; }; DEPTHAI_SERIALIZE_EXT(NodeConnectionSchema, node1Id, node1OutputGroup, node1Output, node2Id, node2InputGroup, node2Input); } // namespace dai
490
168
#include "logger.hpp" #include <iostream> #include "config.hpp" namespace uni_course_cpp { void Logger::log(const std::string& string) { std::cout << string; file_stream_ << string; } Logger::~Logger() { if (file_stream_.is_open()) file_stream_.close(); } Logger::Logger() : file_stream_(std::ofstream(config::log_file_path())) { if (!file_stream_.is_open()) throw std::runtime_error("Can't create file stream"); } } // namespace uni_course_cpp
466
163
#ifndef PK_GRAPHS_DEPTHFIRSTSEARCH_HPP #define PK_GRAPHS_DEPTHFIRSTSEARCH_HPP #include "stack.hpp" #include "vector.hpp" namespace pk { namespace graphs { class depth_first_search { public: template< class graph_type, class visitor_type> static void run( const graph_type& g, const int starting_vertex_id, visitor_type& visitor) { pk::stack<int, graph_type::max_num_of_edges> s; pk::vector<bool, graph_type::max_num_of_vertices> visited(false, g.get_num_of_vertices()); s.push(starting_vertex_id); while(!s.empty()) { const int v = s.top(); s.pop(); if(visited[v]) continue; visitor.visit(v); visited[v] = true; const typename graph_type::adjacency_list& adj_v = g.get_adjacency_list(v); for(int i = adj_v.size() - 1; i >= 0; --i) { const int u = adj_v[i].to; if(visited[u]) continue; s.push(u); } } } }; } // namespace graphs } // namespace pk #endif // PK_GRAPHS_DEPTHFIRSTSEARCH_HPP
1,219
428
/* * Copyright 2014 Matthew Harvey * * 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. */ #ifndef GUARD_help_line_hpp_07384218837779118 #define GUARD_help_line_hpp_07384218837779118 #include <string> namespace swx { /** * Represents a line of help information for presentation to user, * describing a particular string of arguments that might be passed to * a command or command option, together with a description of how the * command or option is used in conjunction with that string of arguments. */ class HelpLine { // special member functions public: HelpLine ( std::string const& p_usage_descriptor, std::string const& p_args_descriptor = std::string() ); HelpLine(char const* p_usage_descriptor); // accessors public: std::string usage_descriptor() const; std::string args_descriptor() const; // data members private: std::string m_usage_descriptor; std::string m_args_descriptor; }; // class HelpLine } // namespace swx #endif // GUARD_help_line_hpp_07384218837779118
1,547
500
#ifndef _BILLGATES_HPP #define _BILLGATES_HPP #include <iostream> #include "../../../extra/include/Definitions.hpp" #include "../Entity.hpp" class BillGates extends Entity { public: }; #endif // _BILLGATES_HPP
214
88
// // Created by Luis Yanes (EI) on 15/09/2017. // #ifndef SEQSORTER_FILEREADER_H #define SEQSORTER_FILEREADER_H #include <cstring> #include <fstream> #include <iostream> #include <fcntl.h> #include <sdglib/readers/Common.hpp> #include <sdglib/utilities/OutputLog.hpp> #include "kseq.hpp" struct FastxReaderParams { uint32_t min_length=0; }; struct FastaRecord { int32_t id; std::string name,seq; }; template<typename FileRecord> class FastaReader { public: /** * @brief * Initialises the FastaReader, opens the file based on the format and instantiates a reader (plain, gzip or bzip2) * @param params * Parameters for filtering the records (i.e. min_size, max_size) * @param filepath * Relative or absolute path to the file that is going to be read. */ explicit FastaReader(FastxReaderParams params, const std::string &filepath) : params(params), numRecords(0) { sdglib::OutputLog(sdglib::LogLevels::INFO) << "Opening: " << filepath << "\n"; gz_file = gzopen(filepath.c_str(), "r"); if (gz_file == Z_NULL || gz_file == NULL) { sdglib::OutputLog(sdglib::LogLevels::WARN) << "Error opening FASTA " << filepath << ": " << std::strerror(errno) << std::endl; throw std::runtime_error("Error opening " + filepath + ": " + std::strerror(errno)); } ks = new kstream<gzFile, FunctorZlib>(gz_file, gzr); } ~FastaReader() { delete ks; gzclose(gz_file); } /** * @brief * Calls the file reader and places the fields from the file onto the FileRecord, the ID is set to the * number of records seen so far. * @param rec * Input/Output parameter where the file fields will be stored. * @return * Whether the function will generate another object or not */ bool next_record(FileRecord& rec) { int l; do { l=(ks -> readFasta(seq)); std::swap(rec.seq, seq.seq); std::swap(rec.name, seq.name); rec.id = numRecords; numRecords++; stats.totalLength+=rec.seq.size(); } while(rec.seq.size() < params.min_length && l >= 0); stats.filteredRecords++; stats.filteredLength+=rec.seq.size(); return (l >= 0); } ReaderStats getSummaryStatistics() { stats.totalRecords = numRecords; return stats; } private: kstream<gzFile, FunctorZlib> *ks; kstream<BZFILE, FunctorBZlib2> *bzKS; kseq seq; uint32_t numRecords = 0; gzFile gz_file; BZFILE * bz_File{}; int fq_File{}; FunctorZlib gzr; FunctorRead rr; FastxReaderParams params; ReaderStats stats; }; struct FastqRecord{ int64_t id; std::string name, comment, seq, qual; }; template<typename FileRecord> class FastqReader { public: /** * @brief * Initialises the FastaReader, opens the file based on the format and instantiates a reader (plain, gzip or bzip2) * @param params * Parameters for filtering the records (i.e. min_size, max_size) * @param filepath * Relative or absolute path to the file that is going to be read. */ explicit FastqReader(FastxReaderParams params, const std::string &filepath) : params(params), numRecords(0),eof_flag(false) { sdglib::OutputLog() << "Opening: " << filepath << "\n"; gz_file = gzopen(filepath.c_str(), "r"); if (gz_file == Z_NULL) { std::cout << "Error opening FASTQ " << filepath << ": " << std::strerror(errno) << std::endl; throw std::runtime_error("Error opening " + filepath + ": " + std::strerror(errno)); } ks = new kstream<gzFile, FunctorZlib>(gz_file, gzr); } /** * @brief * Calls the file reader and places the fields from the file onto the FileRecord, the ID is set to the * number of records seen so far. * @param rec * Input/Output parameter where the file fields will be stored. * @return * Whether the function will generate another object or not */ bool next_record(FileRecord& rec) { int l; if ( eof_flag) return false; { do { l = (ks->readFastq(seq)); std::swap(rec.seq, seq.seq); std::swap(rec.qual, seq.qual); std::swap(rec.name, seq.name); std::swap(rec.comment, seq.comment); rec.id = numRecords; numRecords++; stats.totalLength += rec.seq.size(); } while (rec.seq.size() < params.min_length && l >= 0); } if (l<0) eof_flag=true; else { stats.filteredRecords++; stats.filteredLength += rec.seq.size(); } return (l >= 0); } ReaderStats getSummaryStatistics() { stats.totalRecords=numRecords; return stats; } ~FastqReader() { gzclose(gz_file); delete ks; } private: kstream<gzFile, FunctorZlib> *ks; kseq seq; uint64_t numRecords=0; gzFile gz_file; BZFILE * bz_File{}; int fq_File{}; FunctorZlib gzr; FastxReaderParams params; ReaderStats stats; bool eof_flag; }; #endif //SEQSORTER_FILEREADER_H
5,268
1,759
// Main file, this is where everything gets ran from and more importantly where the exe will start from. also // means everything that follows is a comment. multi lines go like /* */ #include <iostream> // #include means to add code that would not otherwise be useable, in this case "iostream" so that we can print text to a cmd. #include "character.h" #include "Combat.h" #include "map.h" #include "enemies.h" #include "saveFile.h" using namespace std; // This makes it so we dont have to type commands like "std::cout" and instead just use "cout" there are more than one and sometimes you can use this but for our purposes this is helpful. /* multi line comment, Brief instructions on running. up top you will see something that says debug clicking on it you will find start debugging and start without debugging. until later you will always want without debugging. use that to start the program and run it, the shortcut is control + F5. http://www.cplusplus.com/doc/tutorial/ is a link to basic programming tutorials in the syntax of the c++ language. this will not cover everthing we do but the important building blocks we will be going over. //the following is a list of things that need done to continue code, im leaving and updating this so that at anytime we can come back and change thigns that we need to. todo: create a char function, create first map, discuss tutorial or no tutorial, opening menu (start, load, exit). following is int main, this is where the code will always start, its a special function that tells the computer hey this is where your starting. everything we do comes out of there. */ void gameState(map m, character bob) { string choice = " "; cout << "you may now move around and use the look command. Monsters will also try to kill you in certain rooms until you defeat the boss." << endl; cout << "type help if you dont know what to do." << endl; while (bob.hp > 0) { cin >> choice; // error checking if (choice == "help" || choice == "Help" || choice == "h" || choice == "H") //check to see if you the user asked for help (|| is or) { std::system("cls"); cout << "from this menu you have three choices." << endl; cout << "1. look or l will show you what the room looks like as if you had just moved into it." << endl; //gen look is more advanced so that we can see things but in this game its easy to do it small. cout << "2. moving is simply done with n,w,e,s. These will move to the next room you need to go to." << endl; cout << "3. saving is done by simply typing save. This will save the data, let you know if it saved, and then exit. Note you cannot short hand this to s as that is south" << endl << endl; } else if (choice == "look" || choice == "Look" || choice == "l" || choice == "L") { m.loadRoom(5, &bob); } // this bit would be shortened in a refactor but it wasnt important here. My mistake on coding at 4:30 am. else if (choice == "n" || choice == "N" || choice == "s" || choice == "S" || choice == "w" || choice == "W" || choice == "e" || choice == "E") { if (choice == "n" || choice == "N") m.loadRoom(1, &bob); else if (choice == "s" || choice == "S") m.loadRoom(3, &bob); else if (choice == "w" || choice == "W") m.loadRoom(2, &bob); else if (choice == "e" || choice == "E") m.loadRoom(4, &bob); } else if (choice == "save" || choice == "Save") { save(bob); } } } void startGame() { string newName; int choice; map m(8); // we create a instance of the class map and initiliaze it with 9 rooms. cout << "What is your name prisoner?" << endl; cin >> newName; // should prob do some error checking here but we might skip since this is a learning rather than a full on, or do it with justin on rather than solo. cout << "what class would you like to play. Please submit 1, 2, or 3." << endl; cout << "1. fighter" << endl << "2. mage " << endl << "3. thief" << endl; cin >> choice; //same as last cin if (choice == 1) { fighter bob(newName); m.loadRoom(0, &bob); gameState(m, bob); } else if (choice == 2) { mage bob(newName); m.loadRoom(0, &bob); gameState(m, bob); } else if (choice == 3) { thief bob(newName); m.loadRoom(0, &bob); gameState(m, bob); } else { cout << "you are now nothing and the game will crash"; } } void startGame(character bob) { int choice; map m(8); // we create a instance of the class map and initiliaze it with 9 rooms. m.loadRoom(5, &bob); // call the look function on our current room. gameState(m, bob); } int main() { int number = 0; //cout << "hello World" << endl; // cout refers to write text to cmd. << refers to the output flow (<< = out, >> = in) "" anything inside quotation marks refers to a string or text like your reading. endl means to end the line and the next output should be put on the next line. cout << "welcome to midgard"; cout << "please pick an option" << endl; character bob; // switch statement inside a do while loop. do { // menu options cout << "1. Start a new game" << endl; cout << "load saved game." << endl; cout << "3. Quit" << endl; cout << "to quit please press 0" << endl; cin >> number; // Train of thought: needs an input to change out of munu options 1. // user choice^ switch (number) { case 1: startGame(); break; case 2: bob = load(); startGame(bob); break; case 3: cout << "Hope you enjoyed the game!" << endl; number = 0; break; } } while (number != 0); std::system("pause"); // system is a function call to windows, pause refers to the command on cmd meaning to "pause" the current output. a cheap and easy way to see whats going on with code. return 0; // return means to get out of a function, in this case its the main function meaning when this is called the program exits. The code 0 that we return means we exited correctly. }
5,865
1,934
#include "shared.h" bool check_exception (const char* message) { printf ("check_exception(%s)\n", message); return true; } int main () { printf ("Results of scene_context3_test:\n"); try { SceneContext context; context.RegisterErrorHandler ("error:*", &check_exception); printf ("check: %d\n", context.FilterError ("error: my error")); } catch (std::exception& e) { printf ("%s\n", e.what ()); } return 0; }
491
178
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ // my original solution // 96%, 80% class Solution1 { public: TreeNode *mergeTrees(TreeNode *t1, TreeNode *t2) { if (t1 == 0 && t2 == 0) { return 0; } else if (t1 != 0 && t2 != 0) { int newVal; newVal = t1->val + t2->val; t1->val = newVal; t1->left = mergeTrees(t1->left, t2->left); t1->right = mergeTrees(t1->right, t2->right); return t1; } else if (t1 != 0 && t2 == 0) { return t1; } else if (t1 == 0 && t2 != 0) { return t2; } return 0; } }; ////////////////// // my original solution // 96%, 80% class Solution2 { public: TreeNode *mergeTrees(TreeNode *t1, TreeNode *t2) { if (t1 == 0 && t2 == 0) { return 0; } else if (t1 != 0 && t2 != 0) { int newVal; newVal = t1->val + t2->val; t1->val = newVal; t1->left = mergeTrees(t1->left, t2->left); t1->right = mergeTrees(t1->right, t2->right); return t1; } else if (t1 != 0) { return t1; } else { return t2; } return 0; } }; //////////////////// // 99%, 40% class Solution3 { public: TreeNode *mergeTrees(TreeNode *t1, TreeNode *t2) { if (!t1 || !t2) return t1 ? t1 : t2; TreeNode *node = new TreeNode(t1->val + t2->val); node->left = mergeTrees(t1->left, t2->left); node->right = mergeTrees(t1->right, t2->right); return node; } };
1,761
653
#include "ChoiceSetTest.h" using namespace test; using namespace hmi_sdk; using namespace rpc_test; CChoiceSetTest::CChoiceSetTest() { } void CChoiceSetTest::SetUpTestCase() { } void CChoiceSetTest::TearDownTestCase() { } void CChoiceSetTest::SetUp() { } void CChoiceSetTest::TearDown() { } TEST_F(CChoiceSetTest,OnVRPerformInteraction_Success) { AppListMock appListMock; AppDataMock appDataMock; appListMock.DelegateGetActiveApp(); EXPECT_CALL(appListMock,getActiveApp()).WillRepeatedly(Return(&appDataMock)); EXPECT_CALL(appDataMock,OnPerformInteraction(PERFORMINTERACTION_TIMEOUT, 0, true)); EXPECT_CALL(appDataMock,OnPerformInteraction(PERFORMINTERACTION_TIMEOUT, 0, false)); CChoiceSet choiceSet(&appListMock); choiceSet.OnTimeOut(); } TEST_F(CChoiceSetTest,OnPerformInteraction_Success) { AppListMock appListMock; AppDataMock appDataMock; appListMock.DelegateGetActiveApp(); EXPECT_CALL(appListMock,getActiveApp()).WillRepeatedly(Return(&appDataMock)); EXPECT_CALL(appDataMock,OnPerformInteraction(PERFORMINTERACTION_TIMEOUT, 0, true)); EXPECT_CALL(appDataMock,OnPerformInteraction(PERFORMINTERACTION_TIMEOUT, 0, false)); CChoiceSet choiceSet(&appListMock); choiceSet.OnTimeOut(); } TEST_F(CChoiceSetTest,OnPerformInteraction_OnListItemClicked_Success) { AppListMock appListMock; AppDataMock appDataMock; appListMock.DelegateGetActiveApp(); EXPECT_CALL(appListMock,getActiveApp()).WillRepeatedly(Return(&appDataMock)); EXPECT_CALL(appDataMock,OnPerformInteraction(PERFORMINTERACTION_CHOICE, 0, _)).Times(AtLeast(1)); CChoiceSet choiceSet(&appListMock); choiceSet.OnListItemClicked(0); } TEST_F(CChoiceSetTest,OnPerformInteraction_OnChoiceVRClicked_Success) { AppListMock appListMock; AppDataMock appDataMock; appListMock.DelegateGetActiveApp(); EXPECT_CALL(appListMock,getActiveApp()).WillRepeatedly(Return(&appDataMock)); EXPECT_CALL(appDataMock,OnPerformInteraction(PERFORMINTERACTION_TIMEOUT, 0, _)).Times(AtLeast(1)); CChoiceSet choiceSet(&appListMock); choiceSet.OnChoiceVRClicked(); } TEST_F(CChoiceSetTest,OnPerformInteraction_OnReturnBtnClicked_Success) { AppListMock appListMock; AppDataMock appDataMock; appListMock.DelegateGetActiveApp(); EXPECT_CALL(appListMock,getActiveApp()).WillRepeatedly(Return(&appDataMock)); EXPECT_CALL(appDataMock,OnPerformInteraction(RESULT_ABORTED, 0, _)).Times(AtLeast(1)); CChoiceSet choiceSet(&appListMock); choiceSet.OnReturnBtnClicked(); } TEST_F(CChoiceSetTest,getInteractionJson_Success) { AppListMock appListMock; UIInterfaceMock uiManagerMock; Json::Value obj; Json::Value appList_; Json::Value eleArr_; Json::Value element1; Json::Value element2; element1["appName"] = "Music1"; element1["appID"] = 3; element1["icon"] = ""; element2["appName"] = "Music2"; element2["appID"] = 4; element2["icon"] = ""; eleArr_.append(element1); eleArr_.append(element2); appList_["applications"] = eleArr_; obj["id"] = 64; obj["jsonrpc"] = "2.0"; obj["method"] = "BasicCommunication.UpdateAppList"; obj["params"] = appList_; appListMock.DelegateOnRequest(obj); appListMock.DelegateSetUIManager(&uiManagerMock); EXPECT_CALL(appListMock,onRequest(obj)).Times(AtLeast(1)); EXPECT_CALL(appListMock,setUIManager(&uiManagerMock)); EXPECT_CALL(uiManagerMock,onAppShow(ID_APPLINK)).Times(AtLeast(1)); appListMock.setUIManager(&uiManagerMock); appListMock.onRequest(obj); appListMock.DelegateGetActiveApp(); EXPECT_CALL(appListMock,getActiveApp()); EXPECT_FALSE(appListMock.getActiveApp()); Json::Value appObj; Json::Value appId; appObj["method"] = "BasicCommunication.ActivateApp"; appId["appID"] = 3; appObj["id"] = 64; appObj["jsonrpc"] = "2.0"; appObj["params"] = appId; appListMock.DelegateOnRequest(appObj); EXPECT_CALL(appListMock,onRequest(appObj)).Times(AtLeast(1)); appListMock.onRequest(appObj); EXPECT_CALL(appListMock,getActiveApp()).Times(AtLeast(1)); EXPECT_TRUE(appListMock.getActiveApp()); Json::Value InteractionObj; Json::Value choiceSet; Json::Value params; Json::Value initialText; initialText["fieldName"] = "initialInteractionText"; initialText["fieldText"] = "1111111"; for (int i = 0; i< 10;++i) { Json::Value choiceSetEle; choiceSetEle["choiceID"] = i+1; choiceSetEle["menuName"] = QString(("MenuName" + QString::number(i+1))).toStdString(); choiceSet.append(choiceSetEle); } params["appID"] = 3; params["choiceSet"] = choiceSet; params["initialText"] = initialText; InteractionObj["method"] = "UI.PerformInteraction"; InteractionObj["id"] = 127; InteractionObj["jsonrpc"] = "2.0"; InteractionObj["params"] = params; appListMock.DelegateOnRequest(InteractionObj); EXPECT_CALL(appListMock,onRequest(InteractionObj)).Times(AtLeast(1)); appListMock.onRequest(InteractionObj); EXPECT_EQ(3,appListMock.getActiveApp()->getInteractionJson()["Choiceset"]["params"]["appID"].asInt()); // CChoiceSet* cChoiceSet = new CChoiceSet(&appListMock); // cChoiceSet->show(); }
5,299
1,904
// Style: http://geosoft.no/development/cppstyle.html #include <chrono> #include <iostream> #include <stack> #include <vector> #include <cppformat/format.h> #include "int_types.h" using namespace std; using namespace fmt; // The first version of this program would take 2500 hours to run. This was reduced to 250 hours by changing the stack // type from std::stack to std::vector and clearing and reusing the std::vector for each program evaluation. The // std::stack could not be cleared and therefore had to be recreated for each program evaluation. enum Operation { LD_A, LD_B, LD_C, LD_D, AND, OR, XOR, NOT, ENUM_END }; const vector<string> opStrVec = {"v1", "v2", "v3", "v4", "and", "or", "xor", "not", "ENUM_END"}; typedef vector<Operation> OperationVec; typedef vector<u16> U16Stack; typedef std::chrono::high_resolution_clock Time; typedef std::chrono::duration<float> Fsec; void nextProgram(OperationVec& program); bool evalProgram(u16& truthTable, const OperationVec& program); bool evalOperation(U16Stack& s, Operation operation); u16 pop(U16Stack& s); string serializeProgram(const OperationVec& program); int main() { const u32 nSearchLevels = 15; const u64 nTotalPossiblePrograms = pow(static_cast<int>(ENUM_END), nSearchLevels); const u32 nPossibleTruthTables = 1 << 16; // 1 << 16 to cover the full search space. Lower values for testing and benchmarking. const u32 nSearchTruthTables = 1 << 16; print("Total possible programs: {}\n", nTotalPossiblePrograms); u32 nFoundTruthTables = 0; u64 nProgramsEvaluated = 0; u64 nValidPrograms = 0; OperationVec program = {LD_A}; vector<OperationVec> foundOperationVec(nPossibleTruthTables); auto startTime = Time::now(); while (nFoundTruthTables < nSearchTruthTables) { u16 truthTable; bool isValidProgram = evalProgram(truthTable, program); if (isValidProgram) { ++nValidPrograms; if (!foundOperationVec[truthTable].size()) { foundOperationVec[truthTable] = program; ++nFoundTruthTables; } } ++nProgramsEvaluated; if (!(nProgramsEvaluated & 0xffffff) || nFoundTruthTables == nSearchTruthTables) { Fsec elapsedSec = Time::now() - startTime; print("\nTotal time: {:.2f}s\n", elapsedSec.count()); print("Hours until done: {:.2f}\n", static_cast<float>(nTotalPossiblePrograms) / nProgramsEvaluated * elapsedSec.count() / 60.0f / 60.0f); print("Programs evaluated: {} ({:f}%)\n", nProgramsEvaluated, static_cast<float>(nProgramsEvaluated) / nTotalPossiblePrograms * 100.0f); print("Programs evaluated per second: {:d}\n", static_cast<int>(nProgramsEvaluated / elapsedSec.count())); print("Valid programs: {} ({:.2f}%)\n", nValidPrograms, static_cast<float>(nValidPrograms) / nProgramsEvaluated * 100.0f); print("Found truth tables: {} ({:.2f}%)\n", nFoundTruthTables, static_cast<float>(nFoundTruthTables) / nSearchTruthTables * 100.0f); print("Last evaluated: {} ({} ops)\n", serializeProgram(program), program.size()); } nextProgram(program); } return 0; } void nextProgram(OperationVec& program) { auto nOperations = program.size(); for (u32 i = 0; i < nOperations; ++i) { program[i] = static_cast<Operation>(static_cast<int>(program[i]) + 1); if (program[i] != ENUM_END) { break; } program[i] = LD_A; if (i == nOperations - 1) { program.push_back(LD_A); } } } // Find the truth table for a given program. // Return true for valid programs. For a program to be valid, it must not cause a stack underflow during evaluation // and must leave exactly one value on the stack when completed. bool evalProgram(u16& truthTable, const OperationVec& program) { static U16Stack s; s.clear(); for (auto operation : program) { bool stackIsValid = evalOperation(s, operation); if (!stackIsValid) { return false; } } if (s.size() != 1) { return false; } truthTable = s.back(); return true; } bool evalOperation(U16Stack& s, Operation operation) { switch (operation) { case LD_A: s.push_back(0b0000000011111111); break; case LD_B: s.push_back(0b0000111100001111); break; case LD_C: s.push_back(0b0011001100110011); break; case LD_D: s.push_back(0b0101010101010101); break; case AND: if (s.size() < 2) return false; s.push_back(pop(s) & pop(s)); break; case OR: if (s.size() < 2) return false; s.push_back(pop(s) | pop(s)); break; case XOR: if (s.size() < 2) return false; s.push_back(pop(s) ^ pop(s)); break; case NOT: if (!s.size()) return false; s.push_back(~pop(s)); break; case ENUM_END: assert(false); } return true; } u16 pop(U16Stack& s) { u16 v = s.back(); s.pop_back(); return v; } string serializeProgram(const OperationVec& program) { string s; for (auto operation : program) { s += format("{} ", opStrVec[static_cast<int>(operation)]); } return s; } u64 pow(u32 base, u32 exp) { u64 r = base; for (u32 i = 0; i < exp; ++i) { r *= base; } return r; }
5,574
1,903
#include "driver.h" #include "Buffer.h" #include "sockets.h" #include "tcp.h" #include <strings.h> #include <unistd.h> #include <stdio.h> #include <fcntl.h> #include <errno.h> class TcpConnnection : public driver<TcpConnnection> { public: void init(PortPtr port, MessagePtr& message) override { assert(message->type == MSG_TYPE_TCP); time_t now = 0; char timebuf[32]; struct tm tm; now = time(NULL); localtime_r(&now, &tm); // gmtime_r(&now, &tm); strftime(timebuf, sizeof timebuf, "%Y.%m.%d-%H:%M:%S", &tm); start_ = timebuf; state_ = kConnecting; TcpPacket* packet = static_cast<TcpPacket*>(message->data); assert(packet->type == TcpPacket::kShift); assert(packet->shift.fd > 0); fd_ = packet->shift.fd; state_ = kConnected; PortCtl(port, port->id(), 0, port->owner()); // printf("TcpConnnection id=%d init fd = %d\n", port->id(), packet->shift.fd); } void release(PortPtr port, MessagePtr& message) override { port->channel(fd_)->disableAll()->update(); sockets::close(fd_); state_ = kDisconnected; // printf("TcpConnnection id=%d release fd = %d\n", port->id(), fd_); } bool receive(PortPtr port, MessagePtr& message) override { if (message->type == MSG_TYPE_TCP) { TcpPacket* packet = static_cast<TcpPacket*>(message->data); switch (packet->type) { case TcpPacket::kRead: return recv(port, message->source, packet->session, packet->read.nbyte); case TcpPacket::kWrite: return send(port, packet); case TcpPacket::kClose: return close(port, message->source, packet->id); case TcpPacket::kShutdown: return shutdown(port, message->source, packet->id); case TcpPacket::kOpts: return setopts(port, packet); case TcpPacket::kLowWaterMark: return lowWaterMark(port, packet->lowWaterMark.on, packet->lowWaterMark.value); case TcpPacket::kHighWaterMark: return highWaterMark(port, packet->highWaterMark.on, packet->highWaterMark.value); case TcpPacket::kInfo: return getinfo(port, message->source, packet->session); default: return true; } } else if (message->type == MSG_TYPE_EVENT) { Event* event = static_cast<Event*>(message->data); switch (event->type) { case Event::kRead: return handleIoReadEvent(port, event->fd); case Event::kWrite: return handleIoWriteEvent(port, event->fd); case Event::kError: return true; default: return true; } } else { assert(false); return true; } } bool setopts(PortPtr port, TcpPacket* packet) { // printf("port->id() = %d, setopts\n", port->id()); if (packet->opts.optsbits & 0B00000001) { // printf("port->id() = %d, opts.reuseaddr = %d\n", port->id(), packet->opts.reuseaddr); reuseaddr_ = packet->opts.reuseaddr; } if (packet->opts.optsbits & 0B00000010) { // printf("port->id() = %d, opts.reuseport = %d\n", port->id(), packet->opts.reuseport); reuseport_ = packet->opts.reuseport; } if (packet->opts.optsbits & 0B00000100) { // printf("port->id() = %d, opts.keepalive = %d\n", port->id(), packet->opts.keepalive); keepalive_ = packet->opts.keepalive; sockets::setKeepAlive(fd_, keepalive_); } if (packet->opts.optsbits & 0B00001000) { // printf("port->id() = %d, opts.nodelay = %d\n", port->id(), packet->opts.nodelay); nodelay_ = packet->opts.nodelay; sockets::setTcpNoDelay(fd_, nodelay_); } if (packet->opts.optsbits & 0B00010000) { // printf("port->id() = %d, opts.active = %d\n", port->id(), packet->opts.active); active_ = packet->opts.active; } if (packet->opts.optsbits & 0B00100000) { // printf("port->id() = %d, opts.owner = %d\n", port->id(), packet->opts.owner); if (port->owner() != packet->opts.owner) { PortCtl(port, port->id(), port->owner(), packet->opts.owner); port->setOwner(packet->opts.owner); } } if (packet->opts.optsbits & 0B01000000) { // printf("port->id() = %d, opts.read = %d\n", port->id(), packet->opts.read); read_ = packet->opts.read; if (read_) { port->channel(fd_)->enableReading()->update(); } else { port->channel(fd_)->disableReading()->update(); } } return true; } bool handleIoReadEvent(PortPtr port, int fd) { assert(fd_ == fd); int savedErrno = 0; ssize_t n = inputBuffer_.readFd(fd, &savedErrno); if (n > 0) { readCount_ += n; } // printf("port->id() = %d, new message = %zd, active = %d, fd = %d, \n", port->id(), n, active_, fd_); if (active_) { if (n > 0) { TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket) + n); packet->type = TcpPacket::kRead; packet->id = port->id(); packet->session = 0; packet->read.nbyte = n; memcpy(packet->read.data, inputBuffer_.peek(), n); inputBuffer_.retrieve(n); auto msg = port->makeMessage(); msg->type = MSG_TYPE_TCP; msg->data = packet; msg->size = sizeof(TcpPacket) + n; port->send(port->owner(), msg); return true; } else if (n == 0) { if (state_ == kDisconnecting) { port->channel(fd_)->disableReading()->update(); close(port, port->owner(), port->id()); } else { TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket)); packet->type = TcpPacket::kRead; packet->id = port->id(); packet->session = 0; packet->read.nbyte = 0; auto msg = port->makeMessage(); msg->type = MSG_TYPE_TCP; msg->data = packet; msg->size = sizeof(TcpPacket); port->send(port->owner(), msg); port->channel(fd_)->disableReading()->update(); state_ = kDisconnecting; } return true; } else { char t_errnobuf[512] = {'\0'}; strerror_r(savedErrno, t_errnobuf, sizeof t_errnobuf); fprintf(stderr, "port->id() = %d, fd = %d read error=%s\n", port->id(), fd, t_errnobuf); return true; } } else { if (n > 0) { if (inputBuffer_.readableBytes() >= highWaterMark_) { port->channel(fd_)->disableReading()->update(); } } else if (n == 0) { if (state_ == kDisconnecting) { port->channel(fd_)->disableReading()->update(); close(port, port->owner(), port->id()); } else { port->channel(fd_)->disableReading()->update(); state_ = kDisconnecting; } } } return true; } bool handleIoWriteEvent(PortPtr port, int fd) { // static uint32_t i = 0; // i++; assert(fd_ == fd); if (port->channel(fd_)->isWriting()) { ssize_t n = sockets::write(fd_, outputBuffer_.peek(), outputBuffer_.readableBytes()); // if (i < 5) { // printf("port->id() = %d, total = %zd, write = %zd, i = %d\n", port->id(), outputBuffer_.readableBytes(), n, i); // } if (n > 0) { writeCount_ += n; outputBuffer_.retrieve(n); // 低水位回调 if (outputBuffer_.readableBytes() <= lowWaterMark_ && lowWaterMarkResponse_ && state_ == kConnected) { TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket)); packet->type = TcpPacket::kLowWaterMark; packet->id = port->id(); packet->session = 0; packet->lowWaterMark.on = true; packet->lowWaterMark.value = outputBuffer_.readableBytes(); auto msg = port->makeMessage(); msg->type = MSG_TYPE_TCP; msg->data = packet; msg->size = sizeof(TcpPacket); port->send(port->owner(), msg); } if (outputBuffer_.readableBytes() == 0) { port->channel(fd_)->disableWriting()->update(); if (state_ == kDisconnecting) { // close(port, port->owner(), port->id()); sockets::shutdownWrite(fd_); } } } else { char t_errnobuf[512] = {'\0'}; strerror_r(errno, t_errnobuf, sizeof t_errnobuf); // fprintf(stderr, "port->id() = %d, fd = %d, errno = %d, write error = %s\n", port->id(), fd, errno, t_errnobuf); port->channel(fd_)->disableWriting()->update(); // if (state_ == kDisconnecting) // { // sockets::shutdownWrite(connfd_); // } } } else { //LOG_TRACE << "Connection fd = " << channel_->fd() << " is down, no more writing"; } return true; } bool send(PortPtr port, TcpPacket* packet) { // printf("port->id() = %d, send total message = %d\n", port->id(), cmd->towrite.nbyte); const void* data = static_cast<const void*>(packet->write.data); size_t len = packet->write.nbyte; ssize_t nwrote = 0; size_t remaining = len; bool faultError = false; if (state_ != kConnected) { return true; } // if no thing in output queue, try writing directly if (!port->channel(fd_)->isWriting() && outputBuffer_.readableBytes() == 0) { nwrote = sockets::write(fd_, data, len); if (nwrote >= 0) { writeCount_ += nwrote; remaining = len - nwrote; // 低水位回调 if (remaining <= lowWaterMark_ && lowWaterMarkResponse_) { TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket)); packet->type = TcpPacket::kLowWaterMark; packet->id = port->id(); packet->session = 0; packet->lowWaterMark.on = true; packet->lowWaterMark.value = remaining; auto msg = port->makeMessage(); msg->type = MSG_TYPE_TCP; msg->data = packet; msg->size = sizeof(TcpPacket); port->send(port->owner(), msg); } } else { // nwrote < 0 nwrote = 0; if (errno != EWOULDBLOCK) { if (errno == EPIPE || errno == ECONNRESET) { // FIXME: any others? faultError = true; } } } } assert(remaining <= len); if (!faultError && remaining > 0) { size_t oldLen = outputBuffer_.readableBytes(); // 高水位回调 if (oldLen + remaining >= highWaterMark_ && oldLen < highWaterMark_ && highWaterMarkResponse_) { TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket)); packet->type = TcpPacket::kHighWaterMark; packet->id = port->id(); packet->session = 0; packet->highWaterMark.on = true; packet->highWaterMark.value = oldLen + remaining; auto msg = port->makeMessage(); msg->type = MSG_TYPE_TCP; msg->data = packet; msg->size = sizeof(TcpPacket); port->send(port->owner(), msg); } outputBuffer_.append(static_cast<const char*>(data)+nwrote, remaining); if (!port->channel(fd_)->isWriting()) { // printf("port->id() = %d, enableWriting\n", port->id()); port->channel(fd_)->enableWriting()->update(); } } // printf("port->id() = %d, send save message = %zd\n", port->id(), outputBuffer_.readableBytes()); return true; } bool recv(PortPtr port, uint32_t source, uint32_t session, int nbyte) { size_t size = static_cast<size_t>(nbyte); assert(port->owner() == source); assert(state_ == kConnected || state_ == kDisconnecting); // printf("port->id() = %d, total = %zu, read msg start size = %d\n", port->id(), inputBuffer_.readableBytes(), size); if (state_ == kDisconnecting && inputBuffer_.readableBytes() == 0) { // printf("port->id() = %d, read msg 0, close connection\n", port->id()); TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket)); packet->type = TcpPacket::kRead; packet->id = port->id(); packet->session = session; packet->read.nbyte = 0; auto msg = port->makeMessage(); msg->type = MSG_TYPE_TCP; msg->data = packet; msg->size = sizeof(TcpPacket); port->send(source, msg); return true; } if (state_ == kDisconnecting && inputBuffer_.readableBytes() <= size) { // printf("port->id() = %d, read all msg, close connection\n", port->id()); int n = inputBuffer_.readableBytes(); TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket) + n); packet->type = TcpPacket::kRead; packet->id = port->id(); packet->session = session; packet->read.nbyte = n; memcpy(packet->read.data, inputBuffer_.peek(), n); inputBuffer_.retrieve(n); auto msg = port->makeMessage(); msg->type = MSG_TYPE_TCP; msg->data = packet; msg->size = sizeof(TcpPacket) + n; port->send(source, msg); return true; } if (state_ == kConnected && read_ && inputBuffer_.readableBytes() <= size && !port->channel(fd_)->isReading()) { port->channel(fd_)->enableReading()->update(); return false; } if (inputBuffer_.readableBytes() == 0) { return false; } if (inputBuffer_.readableBytes() < size) { return false; } int n = size>0? size : inputBuffer_.readableBytes(); TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket) + n); packet->type = TcpPacket::kRead; packet->id = port->id(); packet->session = session; packet->read.nbyte = n; memcpy(packet->read.data, inputBuffer_.peek(), n); inputBuffer_.retrieve(n); auto msg = port->makeMessage(); msg->type = MSG_TYPE_TCP; msg->data = packet; msg->size = sizeof(TcpPacket) + n; port->send(source, msg); // printf("port->id() = %d, read msg size %d [ok]\n", port->id(), n); return true; } bool shutdown(PortPtr port, uint32_t source, uint32_t id) { // printf("port->id() = %d, shutdown\n", port->id()); assert(port->owner() == source); assert(port->id() == id); if (state_ == kConnected || state_ == kDisconnecting) { // printf("shutdown to close1\n"); if (state_ == kDisconnecting) { close(port, port->owner(), port->id()); return true; } if (!port->channel(fd_)->isWriting()) { // printf("shutdown to close2\n"); // close(port, port->owner(), port->id()); sockets::shutdownWrite(fd_); state_ = kDisconnecting; return true; } } return true; } bool close(PortPtr port, uint32_t source, uint32_t id) { // printf("port->id() = %d, close\n", port->id()); assert(port->owner() == source); assert(port->id() == id); assert(state_ == kConnected || state_ == kDisconnecting); PortCtl(port, port->id(), port->owner(), 0); // we don't close fd, leave it to dtor, so we can find leaks easily. port->exit(); return true; } bool lowWaterMark(PortPtr port, bool on, uint64_t value) { lowWaterMarkResponse_ = on; lowWaterMark_ = value; return true; } bool highWaterMark(PortPtr port, bool on, uint64_t value) { highWaterMarkResponse_ = on; highWaterMark_ = value; return true; } bool getinfo(PortPtr port, uint32_t source, uint32_t session) { struct sockaddr_in6 addr6 = sockets::getPeerAddr(fd_); struct sockaddr* addr = (struct sockaddr*)&addr6; TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket)); memset(packet, 0, sizeof(TcpPacket)); packet->type = TcpPacket::kInfo; packet->id = port->id(); packet->session = session; sockets::toIp(packet->info.ip, 64, addr); packet->info.port = sockets::toPort(addr); packet->info.ipv6 = addr->sa_family == AF_INET6; memcpy(packet->info.start, start_.data(), start_.size()); packet->info.owner = port->owner(); packet->info.readCount = readCount_; packet->info.readBuff = inputBuffer_.readableBytes(); packet->info.writeCount = writeCount_; packet->info.writeBuff = outputBuffer_.readableBytes(); auto msg = port->makeMessage(); msg->type = MSG_TYPE_TCP; msg->data = packet; msg->size = sizeof(TcpPacket); port->send(source, msg); return true; } private: enum State {kConnecting, kConnected, kDisconnecting, kDisconnected}; State state_; int fd_ = 0; Buffer inputBuffer_; Buffer outputBuffer_; // 高低水位回调设置 bool lowWaterMarkResponse_ = false; bool highWaterMarkResponse_ = false; uint64_t lowWaterMark_ = 0; uint64_t highWaterMark_ = 1024*1024*1024; bool reuseaddr_ = false; bool reuseport_ = false; bool keepalive_ = false; bool nodelay_ = false; bool active_ = false; bool read_ = false; std::string start_; uint32_t readCount_ = 0; uint32_t writeCount_ = 0; }; reg(TcpConnnection)
15,597
6,826
#include <iostream> #include "a_star.hpp" using namespace cpp_robotics::path_planning; int main() { std::cout << "Hello, World!" << std::endl; //! load map data cv::Mat map_data = cv::imread("../maps/map2.png", CV_8UC1); if (map_data.empty()) { std::cerr << "load map image fail." << std::endl; return -1; } //! a_star std::cout << map_data.size() << std::endl; a_star::Astar astar(a_star::Heuristic::euclidean, true); astar.init(map_data); auto path = astar.findPath({25,25}, {480, 480}); return 0; }
534
222
class Solution { public: bool isValid(string s) { stack <char> st; int flg = 1; for(int i=0; i<s.size(); i++) { if(s[i]=='(' || s[i]=='{' || s[i]=='[') st.push(s[i]); else { if(st.size()==0) { flg = 0; break; } char ch = st.top(); st.pop(); cout << ch << endl; if(ch=='(' && s[i]==')') ; else if(ch=='{' && s[i]=='}') ; else if(ch=='[' && s[i]==']') ; else flg = 0; } cout << flg << endl; } if(st.size()) flg = 0; return flg; } };
797
260
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Default weak implementation of integration routines appropriate for // userspace. The kernel has its own versions of these symbols that // override this implementation. // #include <zircon/compiler.h> #include <lockdep/lockdep.h> namespace lockdep { // Default implementation of the runtime functions supporting the thread-local // ThreadLockState. These MUST be overridden in environments that do not support // the C++ thread_local TLS mechanism. __WEAK ThreadLockState* SystemGetThreadLockState(LockFlags lock_flags) { thread_local ThreadLockState thread_lock_state{}; return &thread_lock_state; } __WEAK void SystemInitThreadLockState(ThreadLockState* state) {} } // namespace lockdep
872
240
#include "leetcode.hpp" /* 287. 寻找重复数 给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。 假设只有一个重复的整数,找出这个重复的数。 示例 1: 输入: [1,3,4,2,2] 输出: 2 示例 2: 输入: [3,1,3,4,2] 输出: 3 说明: 不能更改原数组(假设数组是只读的)。 只能使用额外的 O(1) 的空间。 时间复杂度小于 O(n^2) 。 数组中只有一个重复的数字,但它可能不止重复出现一次。 */ int findDuplicate(vector<int>& A) { int len = static_cast<int>(A.size()); for (int i = 0; i < len;) { if (A[i] == i + 1) ++i; else { if (A[A[i] - 1] != A[i]) std::swap(A[A[i] - 1], A[i]); else return A[i]; } } return 0; } int main() { vector<int> a = { 1, 3, 4, 2, 2 }, b = { 3, 1, 3, 4, 2 }, c = { 1, 1, 2 }, d = { 3, 3, 3, 3 }; OutExpr(findDuplicate(a), "%d"); OutExpr(findDuplicate(b), "%d"); OutExpr(findDuplicate(c), "%d"); OutExpr(findDuplicate(d), "%d"); }
791
592
#include <esp_log.h> #include <esp_system.h> #include <string.h> #include <GeneralUtils.h> #include <Task.h> #include <freertos/event_groups.h> #include "Mutex.h" #include "Config.h" #include "TimeObj.h" #include "SensorService.h" #include "TimeService.h" #include "Stat.h" #include "WatchDog.h" #include "boardconfig.h" #include "sdkconfig.h" static const char tag[] = "TimeService"; class TimeTask; static TimeTask* task; //---------------------------------------------------------------------- // SNTP time adjustment task //---------------------------------------------------------------------- class TimeTask : public Task { protected: static const int EV_WAKE_SERVER = 1; EventGroupHandle_t events; public: TimeTask(); virtual ~TimeTask(); void enable(); protected: void run(void *data) override; }; TimeTask::TimeTask(){ events = xEventGroupCreate(); } TimeTask::~TimeTask(){ } void TimeTask::enable(){ xEventGroupSetBits(events, EV_WAKE_SERVER); } void TimeTask::run(void *data){ ESP_LOGI(tag, "timezone set to: %s", elfletConfig->getTimezone()); Time::setTZ(elfletConfig->getTimezone()); xEventGroupWaitBits(events, EV_WAKE_SERVER, pdTRUE, pdFALSE, portMAX_DELAY); bool first = true; while (true){ if (Time::shouldAdjust(elfletConfig->getWakeupCause() != WC_NOTSLEEP)){ ESP_LOGI(tag, "start SNTP & wait for finish adjustment"); Time::startSNTP(); if (!Time::waitForFinishAdjustment(3)){ ESP_LOGE(tag, "fail to adjust time by SNTP"); } Time now; ESP_LOGI(tag, "adjusted time: %s", now.format(Time::SIMPLE_DATETIME)); if (baseStat.boottime < 60 * 60 * 24 * 365){ baseStat.boottime = now.getTime(); } updateWatchDog(); } if (first){ first = false; enableSensorCapturing(); } vTaskDelay(60 * 60 * 1000 / portTICK_PERIOD_MS); } } //---------------------------------------------------------------------- // module interface //---------------------------------------------------------------------- bool startTimeService(){ if (!task){ task = new TimeTask; task->setStackSize(2048); task->start(); } return true; } void notifySMTPserverAccesivility(){ task->enable(); }
2,467
774
#include "pch.h" #include "Vulkan.h" #include <kinc/graphics5/shader.h> #include <kinc/graphics5/pipeline.h> #include <assert.h> #include <malloc.h> #include <map> #include <string> #include <string.h> extern VkDevice device; extern VkRenderPass render_pass; extern VkDescriptorSet desc_set; bool memory_type_from_properties(uint32_t typeBits, VkFlags requirements_mask, uint32_t* typeIndex); void createDescriptorLayout(PipelineState5Impl* pipeline); kinc_g5_pipeline_t *currentPipeline = NULL; static bool has_number(kinc_internal_named_number *named_numbers, const char *name) { for (int i = 0; i < KINC_INTERNAL_NAMED_NUMBER_COUNT; ++i) { if (strcmp(named_numbers[i].name, name) == 0) { return true; } } return false; } static uint32_t find_number(kinc_internal_named_number *named_numbers, const char *name) { for (int i = 0; i < KINC_INTERNAL_NAMED_NUMBER_COUNT; ++i) { if (strcmp(named_numbers[i].name, name) == 0) { return named_numbers[i].number; } } return 0; } static void set_number(kinc_internal_named_number *named_numbers, const char *name, uint32_t number) { for (int i = 0; i < KINC_INTERNAL_NAMED_NUMBER_COUNT; ++i) { if (strcmp(named_numbers[i].name, name) == 0) { named_numbers[i].number = number; return; } } for (int i = 0; i < KINC_INTERNAL_NAMED_NUMBER_COUNT; ++i) { if (named_numbers[i].name[0] == 0) { strcpy(named_numbers[i].name, name); named_numbers[i].number = number; return; } } assert(false); } namespace { void parseShader(kinc_g5_shader_t *shader, kinc_internal_named_number *locations, kinc_internal_named_number *textureBindings, kinc_internal_named_number *uniformOffsets) { memset(locations, 0, sizeof(kinc_internal_named_number) * KINC_INTERNAL_NAMED_NUMBER_COUNT); memset(textureBindings, 0, sizeof(kinc_internal_named_number) * KINC_INTERNAL_NAMED_NUMBER_COUNT); memset(uniformOffsets, 0, sizeof(kinc_internal_named_number) * KINC_INTERNAL_NAMED_NUMBER_COUNT); uint32_t *spirv = (uint32_t *)shader->impl.source; int spirvsize = shader->impl.length / 4; int index = 0; unsigned magicNumber = spirv[index++]; unsigned version = spirv[index++]; unsigned generator = spirv[index++]; unsigned bound = spirv[index++]; index++; std::map<uint32_t, std::string> names; std::map<uint32_t, std::string> memberNames; std::map<uint32_t, uint32_t> locs; std::map<uint32_t, uint32_t> bindings; std::map<uint32_t, uint32_t> offsets; while (index < spirvsize) { int wordCount = spirv[index] >> 16; uint32_t opcode = spirv[index] & 0xffff; uint32_t *operands = wordCount > 1 ? &spirv[index + 1] : nullptr; uint32_t length = wordCount - 1; switch (opcode) { case 5: { // OpName uint32_t id = operands[0]; char* string = (char*)&operands[1]; names[id] = string; break; } case 6: { // OpMemberName uint32_t type = operands[0]; if (names[type] == "_k_global_uniform_buffer_type") { uint32_t member = operands[1]; char* string = (char*)&operands[2]; memberNames[member] = string; } break; } case 71: { // OpDecorate uint32_t id = operands[0]; uint32_t decoration = operands[1]; if (decoration == 30) { // location uint32_t location = operands[2]; locs[id] = location; } if (decoration == 33) { // binding uint32_t binding = operands[2]; bindings[id] = binding; } break; } case 72: { // OpMemberDecorate uint32_t type = operands[0]; if (names[type] == "_k_global_uniform_buffer_type") { uint32_t member = operands[1]; uint32_t decoration = operands[2]; if (decoration == 35) { // offset uint32_t offset = operands[3]; offsets[member] = offset; } } } } index += wordCount; } for (std::map<uint32_t, uint32_t>::iterator it = locs.begin(); it != locs.end(); ++it) { set_number(locations, names[it->first].c_str(), it->second); } for (std::map<uint32_t, uint32_t>::iterator it = bindings.begin(); it != bindings.end(); ++it) { set_number(textureBindings, names[it->first].c_str(), it->second); } for (std::map<uint32_t, uint32_t>::iterator it = offsets.begin(); it != offsets.end(); ++it) { set_number(uniformOffsets, memberNames[it->first].c_str(), it->second); } } VkShaderModule demo_prepare_shader_module(const void* code, size_t size) { VkShaderModuleCreateInfo moduleCreateInfo; VkShaderModule module; VkResult err; moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; moduleCreateInfo.pNext = NULL; moduleCreateInfo.codeSize = size; moduleCreateInfo.pCode = (const uint32_t*)code; moduleCreateInfo.flags = 0; err = vkCreateShaderModule(device, &moduleCreateInfo, NULL, &module); assert(!err); return module; } VkShaderModule demo_prepare_vs(VkShaderModule& vert_shader_module, kinc_g5_shader_t *vertexShader) { vert_shader_module = demo_prepare_shader_module(vertexShader->impl.source, vertexShader->impl.length); return vert_shader_module; } VkShaderModule demo_prepare_fs(VkShaderModule& frag_shader_module, kinc_g5_shader_t *fragmentShader) { frag_shader_module = demo_prepare_shader_module(fragmentShader->impl.source, fragmentShader->impl.length); return frag_shader_module; } } void kinc_g5_pipeline_init(kinc_g5_pipeline_t *pipeline) { pipeline->vertexShader = nullptr; pipeline->fragmentShader = nullptr; pipeline->geometryShader = nullptr; pipeline->tessellationEvaluationShader = nullptr; pipeline->tessellationControlShader = nullptr; createDescriptorLayout(&pipeline->impl); Kore::Vulkan::createDescriptorSet(&pipeline->impl, nullptr, nullptr, desc_set); } void kinc_g5_pipeline_destroy(kinc_g5_pipeline_t *pipeline) {} kinc_g5_constant_location_t kinc_g5_pipeline_get_constant_location(kinc_g5_pipeline_t *pipeline, const char *name) { kinc_g5_constant_location_t location; location.impl.vertexOffset = -1; location.impl.fragmentOffset = -1; if (has_number(pipeline->impl.vertexOffsets, name)) { location.impl.vertexOffset = find_number(pipeline->impl.vertexOffsets, name); } if (has_number(pipeline->impl.fragmentOffsets, name)) { location.impl.fragmentOffset = find_number(pipeline->impl.fragmentOffsets, name); } return location; } kinc_g5_texture_unit_t kinc_g5_pipeline_get_texture_unit(kinc_g5_pipeline_t *pipeline, const char *name) { kinc_g5_texture_unit_t unit; unit.impl.binding = find_number(pipeline->impl.textureBindings, name); return unit; } void kinc_g5_pipeline_compile(kinc_g5_pipeline_t *pipeline) { parseShader(pipeline->vertexShader, pipeline->impl.vertexLocations, pipeline->impl.textureBindings, pipeline->impl.vertexOffsets); parseShader(pipeline->fragmentShader, pipeline->impl.fragmentLocations, pipeline->impl.textureBindings, pipeline->impl.fragmentOffsets); // VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = {}; pPipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pPipelineLayoutCreateInfo.pNext = NULL; pPipelineLayoutCreateInfo.setLayoutCount = 1; pPipelineLayoutCreateInfo.pSetLayouts = &pipeline->impl.desc_layout; VkResult err = vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, NULL, &pipeline->impl.pipeline_layout); assert(!err); // VkGraphicsPipelineCreateInfo pipeline_info = {}; VkPipelineCacheCreateInfo pipelineCache_info = {}; VkPipelineInputAssemblyStateCreateInfo ia = {}; VkPipelineRasterizationStateCreateInfo rs = {}; VkPipelineColorBlendStateCreateInfo cb = {}; VkPipelineDepthStencilStateCreateInfo ds = {}; VkPipelineViewportStateCreateInfo vp = {}; VkPipelineMultisampleStateCreateInfo ms = {}; VkDynamicState dynamicStateEnables[VK_DYNAMIC_STATE_RANGE_SIZE]; VkPipelineDynamicStateCreateInfo dynamicState = {}; memset(dynamicStateEnables, 0, sizeof dynamicStateEnables); memset(&dynamicState, 0, sizeof dynamicState); dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; dynamicState.pDynamicStates = dynamicStateEnables; memset(&pipeline_info, 0, sizeof(pipeline_info)); pipeline_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipeline_info.layout = pipeline->impl.pipeline_layout; uint32_t stride = 0; for (int i = 0; i < pipeline->inputLayout[0]->size; ++i) { kinc_g5_vertex_element_t element = pipeline->inputLayout[0]->elements[i]; switch (element.data) { case KINC_G4_VERTEX_DATA_COLOR: stride += 1 * 4; break; case KINC_G4_VERTEX_DATA_FLOAT1: stride += 1 * 4; break; case KINC_G4_VERTEX_DATA_FLOAT2: stride += 2 * 4; break; case KINC_G4_VERTEX_DATA_FLOAT3: stride += 3 * 4; break; case KINC_G4_VERTEX_DATA_FLOAT4: stride += 4 * 4; break; case KINC_G4_VERTEX_DATA_FLOAT4X4: stride += 4 * 4 * 4; break; } } VkVertexInputBindingDescription vi_bindings[1]; #ifdef KORE_WINDOWS VkVertexInputAttributeDescription* vi_attrs = (VkVertexInputAttributeDescription*)alloca(sizeof(VkVertexInputAttributeDescription) * pipeline->inputLayout[0]->size); #else VkVertexInputAttributeDescription vi_attrs[pipeline->inputLayout[0]->size]; #endif VkPipelineVertexInputStateCreateInfo vi = {}; vi.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vi.pNext = NULL; vi.vertexBindingDescriptionCount = 1; vi.pVertexBindingDescriptions = vi_bindings; vi.vertexAttributeDescriptionCount = pipeline->inputLayout[0]->size; vi.pVertexAttributeDescriptions = vi_attrs; vi_bindings[0].binding = 0; vi_bindings[0].stride = stride; vi_bindings[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; uint32_t offset = 0; for (int i = 0; i < pipeline->inputLayout[0]->size; ++i) { kinc_g5_vertex_element_t element = pipeline->inputLayout[0]->elements[i]; switch (element.data) { case KINC_G4_VERTEX_DATA_COLOR: vi_attrs[i].binding = 0; vi_attrs[i].location = find_number(pipeline->impl.vertexLocations, element.name); vi_attrs[i].format = VK_FORMAT_R32_UINT; vi_attrs[i].offset = offset; offset += 1 * 4; break; case KINC_G4_VERTEX_DATA_FLOAT1: vi_attrs[i].binding = 0; vi_attrs[i].location = find_number(pipeline->impl.vertexLocations, element.name); vi_attrs[i].format = VK_FORMAT_R32_SFLOAT; vi_attrs[i].offset = offset; offset += 1 * 4; break; case KINC_G4_VERTEX_DATA_FLOAT2: vi_attrs[i].binding = 0; vi_attrs[i].location = find_number(pipeline->impl.vertexLocations, element.name); vi_attrs[i].format = VK_FORMAT_R32G32_SFLOAT; vi_attrs[i].offset = offset; offset += 2 * 4; break; case KINC_G4_VERTEX_DATA_FLOAT3: vi_attrs[i].binding = 0; vi_attrs[i].location = find_number(pipeline->impl.vertexLocations, element.name); vi_attrs[i].format = VK_FORMAT_R32G32B32_SFLOAT; vi_attrs[i].offset = offset; offset += 3 * 4; break; case KINC_G4_VERTEX_DATA_FLOAT4: vi_attrs[i].binding = 0; vi_attrs[i].location = find_number(pipeline->impl.vertexLocations, element.name); vi_attrs[i].format = VK_FORMAT_R32G32B32A32_SFLOAT; vi_attrs[i].offset = offset; offset += 4 * 4; break; case KINC_G4_VERTEX_DATA_FLOAT4X4: vi_attrs[i].binding = 0; vi_attrs[i].location = find_number(pipeline->impl.vertexLocations, element.name); vi_attrs[i].format = VK_FORMAT_R32G32B32A32_SFLOAT; // TODO vi_attrs[i].offset = offset; offset += 4 * 4 * 4; break; } } memset(&ia, 0, sizeof(ia)); ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; memset(&rs, 0, sizeof(rs)); rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rs.polygonMode = VK_POLYGON_MODE_FILL; rs.cullMode = VK_CULL_MODE_NONE; rs.frontFace = VK_FRONT_FACE_CLOCKWISE; rs.depthClampEnable = VK_FALSE; rs.rasterizerDiscardEnable = VK_FALSE; rs.depthBiasEnable = VK_FALSE; rs.lineWidth = 1.0f; memset(&cb, 0, sizeof(cb)); cb.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; VkPipelineColorBlendAttachmentState att_state[1]; memset(att_state, 0, sizeof(att_state)); att_state[0].colorWriteMask = 0xf; att_state[0].blendEnable = VK_FALSE; cb.attachmentCount = 1; cb.pAttachments = att_state; memset(&vp, 0, sizeof(vp)); vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; vp.viewportCount = 1; dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_VIEWPORT; vp.scissorCount = 1; dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_SCISSOR; memset(&ds, 0, sizeof(ds)); ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; ds.depthTestEnable = VK_FALSE; ds.depthWriteEnable = VK_FALSE; ds.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL; ds.depthBoundsTestEnable = VK_FALSE; ds.back.failOp = VK_STENCIL_OP_KEEP; ds.back.passOp = VK_STENCIL_OP_KEEP; ds.back.compareOp = VK_COMPARE_OP_ALWAYS; ds.stencilTestEnable = VK_FALSE; ds.front = ds.back; memset(&ms, 0, sizeof(ms)); ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; ms.pSampleMask = nullptr; ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; pipeline_info.stageCount = 2; VkPipelineShaderStageCreateInfo shaderStages[2]; memset(&shaderStages, 0, 2 * sizeof(VkPipelineShaderStageCreateInfo)); shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; shaderStages[0].module = demo_prepare_vs(pipeline->impl.vert_shader_module, pipeline->vertexShader); shaderStages[0].pName = "main"; shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; shaderStages[1].module = demo_prepare_fs(pipeline->impl.frag_shader_module, pipeline->fragmentShader); shaderStages[1].pName = "main"; pipeline_info.pVertexInputState = &vi; pipeline_info.pInputAssemblyState = &ia; pipeline_info.pRasterizationState = &rs; pipeline_info.pColorBlendState = &cb; pipeline_info.pMultisampleState = &ms; pipeline_info.pViewportState = &vp; pipeline_info.pDepthStencilState = &ds; pipeline_info.pStages = shaderStages; pipeline_info.renderPass = render_pass; pipeline_info.pDynamicState = &dynamicState; memset(&pipelineCache_info, 0, sizeof(pipelineCache_info)); pipelineCache_info.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; err = vkCreatePipelineCache(device, &pipelineCache_info, nullptr, &pipeline->impl.pipelineCache); assert(!err); err = vkCreateGraphicsPipelines(device, pipeline->impl.pipelineCache, 1, &pipeline_info, nullptr, &pipeline->impl.pipeline); assert(!err); vkDestroyPipelineCache(device, pipeline->impl.pipelineCache, nullptr); vkDestroyShaderModule(device, pipeline->impl.frag_shader_module, nullptr); vkDestroyShaderModule(device, pipeline->impl.vert_shader_module, nullptr); } extern VkDescriptorPool desc_pool; void createDescriptorLayout(PipelineState5Impl* pipeline) { VkDescriptorSetLayoutBinding layoutBindings[8]; memset(layoutBindings, 0, sizeof(layoutBindings)); layoutBindings[0].binding = 0; layoutBindings[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; layoutBindings[0].descriptorCount = 1; layoutBindings[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; layoutBindings[0].pImmutableSamplers = nullptr; layoutBindings[1].binding = 1; layoutBindings[1].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; layoutBindings[1].descriptorCount = 1; layoutBindings[1].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; layoutBindings[1].pImmutableSamplers = nullptr; for (int i = 2; i < 8; ++i) { layoutBindings[i].binding = i; layoutBindings[i].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; layoutBindings[i].descriptorCount = 1; layoutBindings[i].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; layoutBindings[i].pImmutableSamplers = nullptr; } VkDescriptorSetLayoutCreateInfo descriptor_layout = {}; descriptor_layout.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; descriptor_layout.pNext = NULL; descriptor_layout.bindingCount = 8; descriptor_layout.pBindings = layoutBindings; VkResult err = vkCreateDescriptorSetLayout(device, &descriptor_layout, NULL, &pipeline->desc_layout); assert(!err); VkDescriptorPoolSize typeCounts[8]; memset(typeCounts, 0, sizeof(typeCounts)); typeCounts[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; typeCounts[0].descriptorCount = 1; typeCounts[1].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; typeCounts[1].descriptorCount = 1; for (int i = 2; i < 8; ++i) { typeCounts[i].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; typeCounts[i].descriptorCount = 1; } VkDescriptorPoolCreateInfo descriptor_pool = {}; descriptor_pool.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; descriptor_pool.pNext = NULL; descriptor_pool.maxSets = 128; descriptor_pool.poolSizeCount = 8; descriptor_pool.pPoolSizes = typeCounts; err = vkCreateDescriptorPool(device, &descriptor_pool, NULL, &desc_pool); assert(!err); } void Kore::Vulkan::createDescriptorSet(struct PipelineState5Impl_s *pipeline, kinc_g5_texture_t *texture, kinc_g5_render_target_t *renderTarget, VkDescriptorSet &desc_set) { // VkDescriptorImageInfo tex_descs[DEMO_TEXTURE_COUNT]; VkDescriptorBufferInfo buffer_descs[2]; VkDescriptorSetAllocateInfo alloc_info = {}; alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; alloc_info.pNext = NULL; alloc_info.descriptorPool = desc_pool; alloc_info.descriptorSetCount = 1; alloc_info.pSetLayouts = &pipeline->desc_layout; VkResult err = vkAllocateDescriptorSets(device, &alloc_info, &desc_set); assert(!err); memset(&buffer_descs, 0, sizeof(buffer_descs)); if (vertexUniformBuffer != nullptr) { buffer_descs[0].buffer = *vertexUniformBuffer; } buffer_descs[0].offset = 0; buffer_descs[0].range = 256 * sizeof(float); if (fragmentUniformBuffer != nullptr) { buffer_descs[1].buffer = *fragmentUniformBuffer; } buffer_descs[1].offset = 0; buffer_descs[1].range = 256 * sizeof(float); VkDescriptorImageInfo tex_desc; memset(&tex_desc, 0, sizeof(tex_desc)); if (texture != nullptr) { tex_desc.sampler = texture->impl.texture.sampler; tex_desc.imageView = texture->impl.texture.view; } if (renderTarget != nullptr) { tex_desc.sampler = renderTarget->impl.sampler; tex_desc.imageView = renderTarget->impl.destView; } tex_desc.imageLayout = VK_IMAGE_LAYOUT_GENERAL; VkWriteDescriptorSet writes[8]; memset(writes, 0, sizeof(writes)); writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writes[0].dstSet = desc_set; writes[0].dstBinding = 0; writes[0].descriptorCount = 1; writes[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; writes[0].pBufferInfo = &buffer_descs[0]; writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writes[1].dstSet = desc_set; writes[1].dstBinding = 1; writes[1].descriptorCount = 1; writes[1].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; writes[1].pBufferInfo = &buffer_descs[1]; for (int i = 2; i < 8; ++i) { writes[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writes[i].dstSet = desc_set; writes[i].dstBinding = i; writes[i].descriptorCount = 1; writes[i].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; writes[i].pImageInfo = &tex_desc; } if (texture != nullptr || renderTarget != nullptr) { if (vertexUniformBuffer != nullptr && fragmentUniformBuffer != nullptr) { vkUpdateDescriptorSets(device, 3, writes, 0, nullptr); } else { vkUpdateDescriptorSets(device, 1, writes + 2, 0, nullptr); } } else { if (vertexUniformBuffer != nullptr && fragmentUniformBuffer != nullptr) { vkUpdateDescriptorSets(device, 2, writes, 0, nullptr); } } }
19,726
8,366
#include "object.h" #include <iso646.h> #include "rtl_exec.h" #include "intrinsic.h" bool ObjectString::invokeMethod(const utf8string &name, const std::vector<std::shared_ptr<Object>> &args, std::shared_ptr<Object> &result) const { std::string method = name.str(); if (method == "length") { if (args.size() != 0) { throw RtlException(rtl::ne_global::Exception_DynamicConversionException, utf8string("invalid number of arguments to length() (expected 0)")); } result = std::shared_ptr<Object> { new ObjectNumber(number_from_uint64(s.length())) }; return true; } throw RtlException(rtl::ne_global::Exception_DynamicConversionException, utf8string("string object does not support this method")); } utf8string ObjectString::toLiteralString() const { return rtl::ne_string::quoted(s); } bool ObjectArray::invokeMethod(const utf8string &name, const std::vector<std::shared_ptr<Object>> &args, std::shared_ptr<Object> &result) const { std::string method = name.str(); if (method == "size") { if (args.size() != 0) { throw RtlException(rtl::ne_global::Exception_DynamicConversionException, utf8string("invalid number of arguments to size() (expected 0)")); } result = std::shared_ptr<Object> { new ObjectNumber(number_from_uint64(a.size())) }; return true; } throw RtlException(rtl::ne_global::Exception_DynamicConversionException, utf8string("array object does not support this method")); } bool ObjectArray::subscript(std::shared_ptr<Object> index, std::shared_ptr<Object> &r) const { Number i; if (not index->getNumber(i)) { throw RtlException(rtl::ne_global::Exception_DynamicConversionException, utf8string("to Number")); } uint64_t ii = number_to_uint64(i); if (ii >= a.size()) { throw RtlException(rtl::ne_global::Exception_ArrayIndexException, utf8string(number_to_string(i))); } r = a.at(ii); return true; } utf8string ObjectArray::toString() const { utf8string r {"["}; bool first = true; for (auto x: a) { if (not first) { r.append(", "); } else { first = false; } r.append(x != nullptr ? x->toLiteralString() : utf8string("null")); } r.append("]"); return r; } bool ObjectDictionary::invokeMethod(const utf8string &name, const std::vector<std::shared_ptr<Object>> &args, std::shared_ptr<Object> &result) const { std::string method = name.str(); if (method == "keys") { if (args.size() != 0) { throw RtlException(rtl::ne_global::Exception_DynamicConversionException, utf8string("invalid number of arguments to keys() (expected 0)")); } std::vector<std::shared_ptr<Object>> keys; for (auto &x: d) { keys.push_back(std::shared_ptr<Object> { new ObjectString(x.first) }); } result = std::shared_ptr<Object> { new ObjectArray(keys) }; return true; } if (method == "size") { if (args.size() != 0) { throw RtlException(rtl::ne_global::Exception_DynamicConversionException, utf8string("invalid number of arguments to size() (expected 0)")); } result = std::shared_ptr<Object> { new ObjectNumber(number_from_uint64(d.size())) }; return true; } throw RtlException(rtl::ne_global::Exception_DynamicConversionException, utf8string("dictionary object does not support this method")); } bool ObjectDictionary::subscript(std::shared_ptr<Object> index, std::shared_ptr<Object> &r) const { utf8string i; if (not index->getString(i)) { throw RtlException(rtl::ne_global::Exception_DynamicConversionException, utf8string("to String")); } auto e = d.find(i); if (e == d.end()) { return false; } r = e->second; return true; } utf8string ObjectDictionary::toString() const { utf8string r {"{"}; bool first = true; for (auto x: d) { if (not first) { r.append(", "); } else { first = false; } r.append(rtl::ne_string::quoted(x.first)); r.append(": "); r.append(x.second != nullptr ? x.second->toLiteralString() : utf8string("null")); } r.append("}"); return r; }
4,297
1,352
#include "stdafx.h" // Defines STB_IMAGE_IMPLEMENTATION *once* for stb_image.h includes (Should this be placed somewhere else?) #define STB_IMAGE_IMPLEMENTATION // Sneak in truetype as well. #define STB_TRUETYPE_IMPLEMENTATION // This header generates lots of errors, so we ignore those (not rpcs3 code) #ifdef _MSC_VER #pragma warning(push, 0) #include <stb_image.h> #include <stb_truetype.h> #pragma warning(pop) #else #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wall" #pragma GCC diagnostic ignored "-Wextra" #pragma GCC diagnostic ignored "-Wold-style-cast" #pragma GCC diagnostic ignored "-Wstrict-aliasing" #pragma GCC diagnostic ignored "-Wcast-qual" #ifndef __clang__ #pragma GCC diagnostic ignored "-Wunused-but-set-variable" #pragma GCC diagnostic ignored "-Wduplicated-branches" #endif #pragma GCC diagnostic ignored "-Wsign-compare" #include <stb_image.h> #include <stb_truetype.h> #pragma GCC diagnostic pop #endif
947
335
// Copyright 2022 The Google Research Authors. // // 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 "clustering/util/dynamic_weight_threshold.h" #include <cmath> #include "clustering/util/dynamic_weight_threshold.pb.h" #include "absl/status/status.h" namespace research_graph { absl::StatusOr<double> DynamicWeightThreshold( const DynamicWeightThresholdConfig& config, int num_iterations, int iteration) { if (num_iterations < 1) return absl::InvalidArgumentError("num_iterations must be >= 1"); if (iteration < 0 || iteration >= num_iterations) return absl::InvalidArgumentError( "iteration must be between 0 and num_iterations-1 inclusive."); if (num_iterations == 1) { if (config.upper_bound() != config.lower_bound()) { return absl::InvalidArgumentError( "If num_iterations=1, upper and lower bounds must match."); } return config.upper_bound(); } const double upper_bound = config.upper_bound(); const double lower_bound = config.lower_bound(); double dynamic_threshold; switch (config.weight_decay_function()) { case DynamicWeightThresholdConfig::LINEAR_DECAY: dynamic_threshold = upper_bound - ((upper_bound - lower_bound) / (num_iterations - 1)) * iteration; return dynamic_threshold; case DynamicWeightThresholdConfig::EXPONENTIAL_DECAY: if (lower_bound <= 0 || upper_bound <= 0) return absl::InvalidArgumentError( "lower and upper bounds need to positive, if EXPONENTIAL_DECAY is " "used"); dynamic_threshold = upper_bound * std::pow(lower_bound / upper_bound, static_cast<double>(iteration) / static_cast<double>(num_iterations - 1)); return dynamic_threshold; default: return absl::InvalidArgumentError( "Unsupported weight decay function provided"); } } } // namespace research_graph
2,481
725
#include "bmm_lib.h" namespace po = boost::program_options; template<class T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { copy(v.begin(), v.end(), std::ostream_iterator<T>(os, " ")); return os; } void bmm_lib::parse_cli(int nargs, char** args, std::vector<std::string>& paths) { po::options_description desc("Allowed options"); desc.add_options()("help", "produce help message")( "path,p", po::value<std::vector<std::string>>(), "input path to file"); po::variables_map vm; po::store(po::parse_command_line(nargs, args, desc), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << std::endl; return; } paths = vm.count("path") ? vm["path"].as<std::vector<std::string>>() : std::vector<std::string>(); } #ifdef USE_MMIO_MATRICES void bmm_lib::read_matrix(FILE* f, std::vector<uint32_t>& I, std::vector<uint32_t>& J, std::vector<uint32_t>& val) { MM_typecode matcode; int M, N, nnz; uint32_t i; if (mm_read_banner(f, &matcode) != 0) { printf("Could not process Matrix Market banner.\n"); exit(1); } /* This is how one can screen matrix types if their application */ /* only supports a subset of the Matrix Market data types. */ if (mm_is_complex(matcode) && mm_is_matrix(matcode) && mm_is_sparse(matcode)) { printf("Sorry, this application does not support "); printf("Market Market type: [%s]\n", mm_typecode_to_str(matcode)); exit(1); } /* find out size of sparse matrix .... */ if (mm_read_mtx_crd_size(f, &M, &N, &nnz) != 0) exit(1); I = std::vector<uint32_t>(nnz); J = std::vector<uint32_t>(nnz); val = std::vector<uint32_t>(nnz); /* NOTE: when reading in doubles, ANSI C requires the use of the "l" */ /* specifier as in "%lg", "%lf", "%le", otherwise errors will occur */ /* (ANSI C X3.159-1989, Sec. 4.9.6.2, p. 136 lines 13-15) */ /* Replace missing val column with 1s and change the fscanf to match pattern * matrices*/ if (!mm_is_pattern(matcode)) { for (i = 0; i < nnz; i++) { fscanf(f, "%d %d %lg\n", &I[i], &J[i], &val[i]); I[i]--; /* adjust from 1-based to 0-based */ J[i]--; } } else { for (i = 0; i < nnz; i++) { fscanf(f, "%d %d\n", &I[i], &J[i]); val[i] = 1; I[i]--; /* adjust from 1-based to 0-based */ J[i]--; } } if (f != stdin) fclose(f); if (M != N) { printf("COO matrix' columns and rows are not the same"); } } #endif
2,449
1,040
// Boost.Geometry // Copyright (c) 2018 Oracle and/or its affiliates. // Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle // Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_FORMULAS_MERIDIAN_DIRECT_HPP #define BOOST_GEOMETRY_FORMULAS_MERIDIAN_DIRECT_HPP #include <boost/math/constants/constants.hpp> #include <boost/geometry/core/radius.hpp> #include <boost/geometry/formulas/differential_quantities.hpp> #include <boost/geometry/formulas/flattening.hpp> #include <boost/geometry/formulas/meridian_inverse.hpp> #include <boost/geometry/formulas/quarter_meridian.hpp> #include <boost/geometry/formulas/result_direct.hpp> #include <boost/geometry/util/condition.hpp> #include <boost/geometry/util/math.hpp> namespace boost { namespace geometry { namespace formula { /*! \brief Compute the direct geodesic problem on a meridian */ template < typename CT, bool EnableCoordinates = true, bool EnableReverseAzimuth = false, bool EnableReducedLength = false, bool EnableGeodesicScale = false, unsigned int Order = 4 > class meridian_direct { static const bool CalcQuantities = EnableReducedLength || EnableGeodesicScale; static const bool CalcRevAzimuth = EnableReverseAzimuth || CalcQuantities; static const bool CalcCoordinates = EnableCoordinates || CalcRevAzimuth; public: typedef result_direct<CT> result_type; template <typename T, typename Dist, typename Spheroid> static inline result_type apply(T const& lo1, T const& la1, Dist const& distance, bool north, Spheroid const& spheroid) { result_type result; CT const half_pi = math::half_pi<CT>(); CT const pi = math::pi<CT>(); CT const one_and_a_half_pi = pi + half_pi; CT const c0 = 0; CT azimuth = north ? c0 : pi; if (BOOST_GEOMETRY_CONDITION(CalcCoordinates)) { CT s0 = meridian_inverse<CT, Order>::apply(la1, spheroid); int signed_distance = north ? distance : -distance; result.lon2 = lo1; result.lat2 = apply(s0 + signed_distance, spheroid); } if (BOOST_GEOMETRY_CONDITION(CalcRevAzimuth)) { result.reverse_azimuth = azimuth; if (result.lat2 > half_pi && result.lat2 < one_and_a_half_pi) { result.reverse_azimuth = pi; } else if (result.lat2 < -half_pi && result.lat2 > -one_and_a_half_pi) { result.reverse_azimuth = c0; } } if (BOOST_GEOMETRY_CONDITION(CalcQuantities)) { CT const b = CT(get_radius<2>(spheroid)); CT const f = formula::flattening<CT>(spheroid); boost::geometry::math::normalize_spheroidal_coordinates < boost::geometry::radian, double >(result.lon2, result.lat2); typedef differential_quantities < CT, EnableReducedLength, EnableGeodesicScale, Order > quantities; quantities::apply(lo1, la1, result.lon2, result.lat2, azimuth, result.reverse_azimuth, b, f, result.reduced_length, result.geodesic_scale); } return result; } // https://en.wikipedia.org/wiki/Meridian_arc#The_inverse_meridian_problem_for_the_ellipsoid // latitudes are assumed to be in radians and in [-pi/2,pi/2] template <typename T, typename Spheroid> static CT apply(T m, Spheroid const& spheroid) { CT const f = formula::flattening<CT>(spheroid); CT n = f / (CT(2) - f); CT mp = formula::quarter_meridian<CT>(spheroid); CT mu = geometry::math::pi<CT>()/CT(2) * m / mp; if (Order == 0) { return mu; } CT H2 = 1.5 * n; if (Order == 1) { return mu + H2 * sin(2*mu); } CT n2 = n * n; CT H4 = 1.3125 * n2; if (Order == 2) { return mu + H2 * sin(2*mu) + H4 * sin(4*mu); } CT n3 = n2 * n; H2 -= 0.84375 * n3; CT H6 = 1.572916667 * n3; if (Order == 3) { return mu + H2 * sin(2*mu) + H4 * sin(4*mu) + H6 * sin(6*mu); } CT n4 = n2 * n2; H4 -= 1.71875 * n4; CT H8 = 2.142578125 * n4; // Order 4 or higher return mu + H2 * sin(2*mu) + H4 * sin(4*mu) + H6 * sin(6*mu) + H8 * sin(8*mu); } }; }}} // namespace boost::geometry::formula #endif // BOOST_GEOMETRY_FORMULAS_MERIDIAN_DIRECT_HPP
5,309
1,823
#include "Camera.hpp" #include <glm/gtx/rotate_vector.hpp> #include <glm/gtc/matrix_transform.hpp> Camera::Camera () { this->BuildProjectionMatrix(); } Camera::Camera (const glm::vec3 pos, const glm::vec3 direction, const float width, const float height) { m_position = pos; m_direction = direction; m_width = width; m_height = height; this->BuildProjectionMatrix(); } void Camera::BuildProjectionMatrix () { mProjectionMatrix = glm::perspective(glm::radians(m_fov), GetAspectRatio(), m_nearPlane, m_farPlane); } glm::mat4 const Camera::GetViewMatrix () { return glm::lookAt(m_position, m_position + m_direction, m_up); } glm::mat4 const& Camera::GetProjectionMatrix () { return mProjectionMatrix; } glm::vec3 const& Camera::GetPosition () { return m_position; } glm::vec3 const& Camera::GetDirection () { return m_direction; } glm::vec3 const& Camera::GetUp () { return m_up; } glm::vec3 const Camera::GetRight () { return glm::normalize(glm::cross(m_direction, m_up)); } float const Camera::GetAspectRatio () { return m_width / m_height; } void Camera::MoveForward (const float amount) { m_position += m_direction * amount; } void Camera::MoveRight (const float amount) { m_position += GetRight() * amount; } void Camera::RotatePitch (const float amount) { m_pitch += amount; if (m_pitch > 90.f) m_pitch = 90.f - 0.001f; if (m_pitch < -90.f) m_pitch = -90.f + 0.001f; RecomputeDirection(); } void Camera::RotateYaw (const float amount) { m_yaw += amount; if (m_yaw > 360.0f) m_yaw = 0.0f; if (m_yaw < 0.0f) m_yaw = 360.0f; RecomputeDirection(); } void Camera::RecomputeDirection () { float pitch = glm::radians(m_pitch); float yaw = glm::radians(m_yaw); m_direction = (glm::vec3(glm::cos(pitch) * glm::cos(yaw), glm::sin(pitch), glm::cos(pitch) * glm::sin(yaw))); m_direction = glm::normalize(m_direction);\ }
2,031
782
#include <algorithm> #include <cmath> #include <iostream> #include <numeric> #include <vector> #include <sndfile.hh> int main () { const auto pi{3.14159265358979323846264338}; const auto freq{440.0}; const auto duration{1.0}; const auto samplerate{48000}; const auto sample_duration{1.0 / samplerate}; const int sample_count = samplerate * std::round (duration); std::cout << "duration=" << duration << "\n"; std::cout << "samplerate=" << samplerate << "\n"; std::cout << "sample_count=" << sample_count << "\n"; std::cout << "sample_duration=" << sample_duration << "\n"; std::cout << "freq=" << freq; std::cout << std::endl; std::vector<double> buffer (sample_count); std::iota (std::begin (buffer), std::end (buffer), 0); std::transform (std::begin (buffer), std::end (buffer), std::begin (buffer), [&](auto k) { return sin (freq * 2 * k * pi / samplerate); }); std::string filename_prefix = "sine_" + std::to_string (freq) + "_" + std::to_string (samplerate); SndfileHandle sndfilehandle_pcm32 (filename_prefix + "_pcm32.wav", SFM_WRITE, (SF_FORMAT_WAV | SF_FORMAT_PCM_32), 1, samplerate); SndfileHandle sndfilehandle_pcm24 (filename_prefix + "_pcm24.wav", SFM_WRITE, (SF_FORMAT_WAV | SF_FORMAT_PCM_24), 1, samplerate); SndfileHandle sndfilehandle_pcm16 (filename_prefix + "_pcm16.wav", SFM_WRITE, (SF_FORMAT_WAV | SF_FORMAT_PCM_16), 1, samplerate); SndfileHandle sndfilehandle_pcmf (filename_prefix + "_float.wav", SFM_WRITE, (SF_FORMAT_WAV | SF_FORMAT_FLOAT), 1, samplerate); SndfileHandle sndfilehandle_pcmd (filename_prefix + "_double.wav", SFM_WRITE, (SF_FORMAT_WAV | SF_FORMAT_DOUBLE), 1, samplerate); sndfilehandle_pcm32.write (buffer.data (), buffer.size ()); sndfilehandle_pcm24.write (buffer.data (), buffer.size ()); sndfilehandle_pcm16.write (buffer.data (), buffer.size ()); sndfilehandle_pcmf.write (buffer.data (), buffer.size ()); sndfilehandle_pcmd.write (buffer.data (), buffer.size ()); }
2,428
832
/* Copyright (c) 2012-2013 Cheese and Bacon Games, LLC */ /* See the file docs/COPYING.txt for copying permission. */ #include "spawner.h" #include "world.h" #include "collision.h" using namespace std; Spawner::Spawner(short get_spawner_type,short get_type,double get_x,double get_y,bool get_disallow_doubles,bool get_items_stay){ spawner_type=get_spawner_type; type=get_type; x=get_x; y=get_y; disallow_doubles=get_disallow_doubles; items_stay=get_items_stay; } bool Spawner::allow_spawn(){ if(disallow_doubles){ bool allow=true; if(spawner_type==SPAWN_ITEM){ for(int i=0;i<vector_items.size();i++){ if(vector_items[i].exists && type==vector_items[i].type && collision_check(x,y,ITEM_W,ITEM_H,vector_items[i].x,vector_items[i].y,vector_items[i].w,vector_items[i].h)){ allow=false; break; } } } else if(spawner_type==SPAWN_NPC){ for(int i=0;i<vector_npcs.size();i++){ if(vector_npcs[i].exists && type==vector_npcs[i].type && collision_check(x,y,ITEM_W,ITEM_H,vector_npcs[i].x,vector_npcs[i].y,vector_npcs[i].w,vector_npcs[i].h)){ allow=false; break; } } } return allow; } else{ return true; } } void Spawner::spawn_object(short object_type){ if(spawner_type==object_type){ if(object_type==SPAWN_ITEM){ if(fabs(x-player.cam_focused_x())>=SPAWN_RANGE || fabs(y-player.cam_focused_y())>=SPAWN_RANGE){ if(random_range(0,99)<level.survival_spawn_items_chance()){ if(allow_spawn()){ vector_items.push_back(Item(x,y,!items_stay,type,0,false)); } } } } else if(object_type==SPAWN_NPC){ if(fabs(x-player.cam_focused_x())>=SPAWN_RANGE || fabs(y-player.cam_focused_y())>=SPAWN_RANGE){ if(random_range(0,99)<level.survival_spawn_npcs_chance()){ if(allow_spawn()){ vector_npcs.push_back(Npc(x,y,type,false)); vector_npcs[vector_npcs.size()-1].ethereal_to_npcs=true; } } } } } }
2,402
886
#include "signaldata.h" #include <qvector.h> #include <qmutex.h> #include <qreadwritelock.h> class SignalData::PrivateData { public: PrivateData(): boundingRect( 1.0, 1.0, -2.0, -2.0 ) // invalid { values.reserve( 1000 ); } inline void append( const QPointF &sample ) { values.append( sample ); // adjust the bounding rectangle if ( boundingRect.width() < 0 || boundingRect.height() < 0 ) { boundingRect.setRect( sample.x(), sample.y(), 0.0, 0.0 ); } else { boundingRect.setRight( sample.x() ); if ( sample.y() > boundingRect.bottom() ) boundingRect.setBottom( sample.y() ); if ( sample.y() < boundingRect.top() ) boundingRect.setTop( sample.y() ); } } QReadWriteLock lock; QVector<QPointF> values; QRectF boundingRect; QMutex mutex; // protecting pendingValues QVector<QPointF> pendingValues; }; SignalData::SignalData() { elapsedDataSize = 0; d_data = new PrivateData(); } SignalData::~SignalData() { delete d_data; } int SignalData::size() const { return d_data->values.size(); } QPointF SignalData::value( int index ) const { return d_data->values[index]; } QRectF SignalData::boundingRect() const { return d_data->boundingRect; } void SignalData::lock() { d_data->lock.lockForRead(); } void SignalData::unlock() { d_data->lock.unlock(); } void SignalData::append( const QPointF &sample ) { d_data->mutex.lock(); d_data->pendingValues += sample; elapsedDataSize++; const bool isLocked = d_data->lock.tryLockForWrite(); if ( isLocked ) { const int numValues = d_data->pendingValues.size(); const QPointF *pendingValues = d_data->pendingValues.data(); for ( int i = 0; i < numValues; i++ ) d_data->append( pendingValues[i] ); d_data->pendingValues.clear(); d_data->lock.unlock(); } d_data->mutex.unlock(); } void SignalData::clearStaleValues( double limit ) { d_data->lock.lockForWrite(); d_data->boundingRect = QRectF( 1.0, 1.0, -2.0, -2.0 ); // invalid const QVector<QPointF> values = d_data->values; d_data->values.clear(); d_data->values.reserve( values.size() ); int index; for ( index = values.size() - 1; index >= 0; index-- ) { if ( values[index].x() < limit ) break; } if ( index > 0 ) d_data->append( values[index++] ); while ( index < values.size() - 1 ) d_data->append( values[index++] ); d_data->lock.unlock(); }
2,661
958
// - // Copyright 2009 Colin Percival // 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. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. // // The code in this file is taken from a file which was originally written by Colin Percival as part of the Tarsnap // online backup system. // - // // File contains modifications by: The Gulden developers // All modifications: // Copyright (c) 2019 The Gulden developers // Authored by: Malcolm MacLeod (mmacleod@gmx.com) // Distributed under the GULDEN software license, see the accompanying // file COPYING in the root of this repository #if defined(USE_SSE2) #include <emmintrin.h> #include <stdint.h> #include "sysendian.h" #include "crypto_scrypt_smix_sse2.h" static void blkcpy(void*, const void*, size_t); static void blkxor(void*, const void*, size_t); static void salsa20_8(__m128i*); static void blockmix_salsa8(const __m128i*, __m128i*, __m128i*, size_t); static uint64_t integerify(const void*, size_t); static void blkcpy(void* dest, const void* src, size_t len) { __m128i* D = dest; const __m128i* S = src; size_t L = len / 16; size_t i; for (i = 0; i < L; i++) { D[i] = S[i]; } } static void blkxor(void* dest, const void* src, size_t len) { __m128i* D = dest; const __m128i* S = src; size_t L = len / 16; size_t i; for (i = 0; i < L; i++) { D[i] = _mm_xor_si128(D[i], S[i]); } } /* salsa20_8(B): * Apply the salsa20/8 core to the provided block. */ static void salsa20_8(__m128i B[4]) { __m128i X0, X1, X2, X3; __m128i T; size_t i; X0 = B[0]; X1 = B[1]; X2 = B[2]; X3 = B[3]; for (i = 0; i < 8; i += 2) { // Operate on "columns". T = _mm_add_epi32(X0, X3); X1 = _mm_xor_si128(X1, _mm_slli_epi32(T, 7)); X1 = _mm_xor_si128(X1, _mm_srli_epi32(T, 25)); T = _mm_add_epi32(X1, X0); X2 = _mm_xor_si128(X2, _mm_slli_epi32(T, 9)); X2 = _mm_xor_si128(X2, _mm_srli_epi32(T, 23)); T = _mm_add_epi32(X2, X1); X3 = _mm_xor_si128(X3, _mm_slli_epi32(T, 13)); X3 = _mm_xor_si128(X3, _mm_srli_epi32(T, 19)); T = _mm_add_epi32(X3, X2); X0 = _mm_xor_si128(X0, _mm_slli_epi32(T, 18)); X0 = _mm_xor_si128(X0, _mm_srli_epi32(T, 14)); // Rearrange data. X1 = _mm_shuffle_epi32(X1, 0x93); X2 = _mm_shuffle_epi32(X2, 0x4E); X3 = _mm_shuffle_epi32(X3, 0x39); // Operate on "rows". T = _mm_add_epi32(X0, X1); X3 = _mm_xor_si128(X3, _mm_slli_epi32(T, 7)); X3 = _mm_xor_si128(X3, _mm_srli_epi32(T, 25)); T = _mm_add_epi32(X3, X0); X2 = _mm_xor_si128(X2, _mm_slli_epi32(T, 9)); X2 = _mm_xor_si128(X2, _mm_srli_epi32(T, 23)); T = _mm_add_epi32(X2, X3); X1 = _mm_xor_si128(X1, _mm_slli_epi32(T, 13)); X1 = _mm_xor_si128(X1, _mm_srli_epi32(T, 19)); T = _mm_add_epi32(X1, X2); X0 = _mm_xor_si128(X0, _mm_slli_epi32(T, 18)); X0 = _mm_xor_si128(X0, _mm_srli_epi32(T, 14)); // Rearrange data. X1 = _mm_shuffle_epi32(X1, 0x39); X2 = _mm_shuffle_epi32(X2, 0x4E); X3 = _mm_shuffle_epi32(X3, 0x93); } B[0] = _mm_add_epi32(B[0], X0); B[1] = _mm_add_epi32(B[1], X1); B[2] = _mm_add_epi32(B[2], X2); B[3] = _mm_add_epi32(B[3], X3); } /* blockmix_salsa8(Bin, Bout, X, r): * Compute Bout = BlockMix_{salsa20/8, r}(Bin). The input Bin must be 128r * bytes in length; the output Bout must also be the same size. The * temporary space X must be 64 bytes. */ static void blockmix_salsa8(const __m128i* Bin, __m128i* Bout, __m128i* X, size_t r) { size_t i; // 1: X <-- B_{2r - 1} blkcpy(X, &Bin[8 * r - 4], 64); // 2: for i = 0 to 2r - 1 do for (i = 0; i < r; i++) { // 3: X <-- H(X \xor B_i) blkxor(X, &Bin[i * 8], 64); salsa20_8(X); // 4: Y_i <-- X // 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) blkcpy(&Bout[i * 4], X, 64); /* 3: X <-- H(X \xor B_i) */ blkxor(X, &Bin[i * 8 + 4], 64); salsa20_8(X); // 4: Y_i <-- X // 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) blkcpy(&Bout[(r + i) * 4], X, 64); } } /* integerify(B, r): * Return the result of parsing B_{2r-1} as a little-endian integer. * Note that B's layout is permuted compared to the generic implementation. */ static uint64_t integerify(const void* B, size_t r) { const uint32_t* X = (const void*)((uintptr_t)(B) + (2 * r - 1) * 64); return (((uint64_t)(X[13]) << 32) + X[0]); } void crypto_scrypt_smix_sse2(uint8_t * B, size_t r, uint64_t N, void * V, void * XY) { __m128i* X = XY; __m128i* Y = (void*)((uintptr_t)(XY) + 128 * r); __m128i* Z = (void*)((uintptr_t)(XY) + 256 * r); uint32_t* X32 = (void*)X; uint64_t i, j; size_t k; // 1: X <-- B for (k = 0; k < 2 * r; k++) { for (i = 0; i < 16; i++) { X32[k * 16 + i] = le32dec(&B[(k * 16 + (i * 5 % 16)) * 4]); } } // 2: for i = 0 to N - 1 do for (i = 0; i < N; i += 2) { // 3: V_i <-- X blkcpy((void*)((uintptr_t)(V) + i * 128 * r), X, 128 * r); // 4: X <-- H(X) blockmix_salsa8(X, Y, Z, r); // 3: V_i <-- X blkcpy((void*)((uintptr_t)(V) + (i + 1) * 128 * r), Y, 128 * r); // 4: X <-- H(X) blockmix_salsa8(Y, X, Z, r); } // 6: for i = 0 to N - 1 do for (i = 0; i < N; i += 2) { // 7: j <-- Integerify(X) mod N j = integerify(X, r) & (N - 1); // 8: X <-- H(X \xor V_j) blkxor(X, (void*)((uintptr_t)(V) + j * 128 * r), 128 * r); blockmix_salsa8(X, Y, Z, r); // 7: j <-- Integerify(X) mod N j = integerify(Y, r) & (N - 1); // 8: X <-- H(X \xor V_j) blkxor(Y, (void *)((uintptr_t)(V) + j * 128 * r), 128 * r); blockmix_salsa8(Y, X, Z, r); } // 10: B' <-- X for (k = 0; k < 2 * r; k++) { for (i = 0; i < 16; i++) { le32enc(&B[(k * 16 + (i * 5 % 16)) * 4], X32[k * 16 + i]); } } } #endif /* CPUSUPPORT_X86_SSE2 */
7,445
3,644
#pragma once #include <SFML/Graphics.hpp> #include "global_defines.hpp" #include "game_entity.hpp" #include "collision_box.hpp" #include "textured_block.hpp" class Enemy; /** * @brief Class for Enemy Path Markers * * This class represents a invisible Entity that guides the Enemy and controls their pathing around the level */ class PathMarker : public GameEntity { public: /** * @brief Movement Direction for the Enemy */ enum Direction { EnemyPathIdle, EnemyPathLeft, EnemyPathRight, EnemyPathJumpLeft, EnemyPathJumpRight, }; private: /** * @brief The movement direction that this path marker will tell an Enemy to follow */ Direction pathDir = Direction::EnemyPathRight; /** * @brief Speed of the path that the enemy should take */ float speed = 1.0f; /** * @brief Should the enemy shoot while following this path? */ bool shoot = true; /** * @brief CollisionBox of this Path Marker */ CollisionBox collisionBox; /** * @brief Create a new Path Marker with a certain generation code at the default position * * @param _manager The global GameManager pointer * @param[in] generationCode The generation code * @param parent The parent GameEntity node */ PathMarker(GameManager *_manager, int generationCode, GameEntity *parent) : PathMarker(_manager, generationCode, parent, 0, 0) {} /** * @brief Create a new Path Marker with a certain generation code at the given position * * @param _manager The global GameManager pointer * @param[in] generationCode The generation code * @param parent The parent GameEntity node * @param[in] x x coordinate * @param[in] y y coordinate */ PathMarker(GameManager *_manager, int generationCode, GameEntity *parent, float x, float y) : PathMarker(_manager, generationCode, parent, sf::Vector2f(x, y)) {} /** * @brief Create a new Path Marker with a certain generation code at the given position * * @param _manager The global GameManager pointer * @param[in] generationCode The generation code * @param parent The parent GameEntity node * @param[in] pos The position */ PathMarker(GameManager *_manager, int generationCode, GameEntity *parent, sf::Vector2f pos) : GameEntity(_manager, parent) { pathDir = static_cast<Direction>(generationCode % 5); setPosition(pos); setSize(sf::Vector2f(BLOCK_SIZE*0.5f, BLOCK_SIZE)); switch (pathDir) { case EnemyPathIdle: setSize(sf::Vector2f(BLOCK_SIZE, BLOCK_SIZE)); break; case EnemyPathLeft: case EnemyPathJumpLeft: setPosition(pos + sf::Vector2f(BLOCK_SIZE*0.25f, 0)); break; case EnemyPathRight: case EnemyPathJumpRight: setPosition(pos - sf::Vector2f(BLOCK_SIZE*0.25f, 0)); break; } collisionBox = CollisionBox(getTotalPosition(), getSize()); } public: /** * @brief Static function for creating Path Markers from Map file codes * * Used to allow for the possibility of generating subclasses of Path Markers in the future * * @param _manager The global GameManager pointer * @param[in] generationCode The generation code * @param parent The parent GameEntity node * @param[in] x The X coordinate * @param[in] y The Y coordinate * * @return The created Path Marker */ static PathMarker* create(GameManager *_manager, int generationCode, GameEntity *parent, float x, float y) { return new PathMarker(_manager, generationCode, parent, x, y); //may return sub classes in the future } /** * @brief Gets the collision box. * * @return The collision box. */ CollisionBox getCollisionBox() const {return collisionBox;} /** * @brief Is the given Enemy Entity stepping in this Path Marker? * * @param[in] enemy The enemy * * @return True if Enemy's feet is inside this collision box */ bool steppingIn(const Enemy* enemy) const; /** * @brief Gets the path direction */ Direction getPathDir() const {return pathDir;}; /** * @brief Gets the speed. */ float getSpeed() const {return speed;}; /** * @brief Should enemy shoot? * * @return { description_of_the_return_value } */ float shouldShoot() const {return shoot;}; /** * @brief Draw Collision Box and Arrows for Debugging * * @param renderer The Render Target to Draw to */ virtual void draw(sf::RenderTarget &renderer) const override { if (DISPLAY_DEBUGGING_STUFF) { collisionBox.draw(renderer); if (pathDir == EnemyPathIdle) return; sf::ConvexShape arrow; arrow.setPointCount(3); switch (pathDir) { case EnemyPathLeft: arrow.setPoint(0, sf::Vector2f(getSize().x, 0)); arrow.setPoint(1, sf::Vector2f(0, getSize().y/2)); arrow.setPoint(2, sf::Vector2f(getSize().x, getSize().y)); break; case EnemyPathRight: arrow.setPoint(0, sf::Vector2f(0, 0)); arrow.setPoint(1, sf::Vector2f(0, getSize().y)); arrow.setPoint(2, sf::Vector2f(getSize().x, getSize().y/2)); break; case EnemyPathJumpLeft: arrow.setPoint(0, sf::Vector2f(0, 0)); arrow.setPoint(1, sf::Vector2f(0, getSize().y/2)); arrow.setPoint(2, sf::Vector2f(getSize().x, 0)); break; case EnemyPathJumpRight: arrow.setPoint(0, sf::Vector2f(0, 0)); arrow.setPoint(1, sf::Vector2f(getSize().x, getSize().y/2)); arrow.setPoint(2, sf::Vector2f(getSize().x, 0)); break; case EnemyPathIdle: break; } arrow.setFillColor(sf::Color::Green); arrow.setPosition(getTotalPosition()); arrow.setOrigin(getSize()/2.0f); renderer.draw(arrow); } } };
5,762
2,097
version https://git-lfs.github.com/spec/v1 oid sha256:a62772f6d894faf1b10bfe5468fe32accdfecae65e88b1d03150d1f60896ad1d size 1642
129
88
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/codecommit/model/ListAssociatedApprovalRuleTemplatesForRepositoryResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::CodeCommit::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; ListAssociatedApprovalRuleTemplatesForRepositoryResult::ListAssociatedApprovalRuleTemplatesForRepositoryResult() { } ListAssociatedApprovalRuleTemplatesForRepositoryResult::ListAssociatedApprovalRuleTemplatesForRepositoryResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } ListAssociatedApprovalRuleTemplatesForRepositoryResult& ListAssociatedApprovalRuleTemplatesForRepositoryResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("approvalRuleTemplateNames")) { Array<JsonView> approvalRuleTemplateNamesJsonList = jsonValue.GetArray("approvalRuleTemplateNames"); for(unsigned approvalRuleTemplateNamesIndex = 0; approvalRuleTemplateNamesIndex < approvalRuleTemplateNamesJsonList.GetLength(); ++approvalRuleTemplateNamesIndex) { m_approvalRuleTemplateNames.push_back(approvalRuleTemplateNamesJsonList[approvalRuleTemplateNamesIndex].AsString()); } } if(jsonValue.ValueExists("nextToken")) { m_nextToken = jsonValue.GetString("nextToken"); } return *this; }
1,665
510
// Copyright 2021 Phyronnaz #include "VoxelEdModeToolkit.h" #include "VoxelEdMode.h" #include "VoxelEditorToolsPanel.h" #include "EditorModeManager.h" void FVoxelEdModeToolkit::Init(const TSharedPtr<IToolkitHost>& InitToolkitHost) { FModeToolkit::Init(InitToolkitHost); } FName FVoxelEdModeToolkit::GetToolkitFName() const { return FName("VoxelEdMode"); } FText FVoxelEdModeToolkit::GetBaseToolkitName() const { return VOXEL_LOCTEXT("VoxelEdMode Tool"); } class FEdMode* FVoxelEdModeToolkit::GetEditorMode() const { return GLevelEditorModeTools().GetActiveMode(FEdModeVoxel::EM_Voxel); } TSharedPtr<SWidget> FVoxelEdModeToolkit::GetInlineContent() const { return GetPanel().GetWidget(); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// void FVoxelEdModeToolkit::GetToolPaletteNames(TArray<FName>& InPaletteName) const { InPaletteName = { STATIC_FNAME("Main") }; } void FVoxelEdModeToolkit::BuildToolPalette(FName PaletteName, FToolBarBuilder& ToolBarBuilder) { GetPanel().CustomizeToolbar(ToolBarBuilder); } void FVoxelEdModeToolkit::OnToolPaletteChanged(FName PaletteName) { } FText FVoxelEdModeToolkit::GetActiveToolDisplayName() const { return {}; } FText FVoxelEdModeToolkit::GetActiveToolMessage() const { return {}; } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// FVoxelEditorToolsPanel& FVoxelEdModeToolkit::GetPanel() const { FEdModeVoxel* VoxelEdMode = static_cast<FEdModeVoxel*>(GetEditorMode()); check(VoxelEdMode); return VoxelEdMode->GetPanel(); }
1,942
626
#include <iostream> #include <memory> #include <chrono> #include <thread> #include <ctime> #include "networktables/NetworkTable.h" #include "opencv2/opencv.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/cudaarithm.hpp" #include "opencv2/cudaimgproc.hpp" #include "opencv2/cudafilters.hpp" static const cv::Size frameSize(1280, 720); static const double MIN_AREA = 0.0002 * frameSize.height * frameSize.width; static const double BOILER_TAPE_RATIO = 2.5; static const double BOILER_TAPE_RATIO2 = BOILER_TAPE_RATIO/2; static const char* default_intrinsic_file = "jetson-camera-720.yml"; static const double CAMERA_GOAL_HEIGHT = 69; //!<- Tower height is 97" and the camera is 19" above the floor static const double CAMERA_ZERO_DIST = 130; //!<- Tower height is 97" and the camera is 12" above the floor #ifdef XGUI_ENABLED #include "opencv2/highgui.hpp" static const cv::Size displaySize(640, 360); static const double displayRatio = double(displaySize.height) / frameSize.height; static const char* detection_window = "Object Detection"; #endif struct RingRelation { double rating; std::vector<cv::Point> *my_cont; std::vector<cv::Point> *other_cont; cv::RotatedRect my_rect; cv::RotatedRect other_rect; double rate2rings(const RingRelation &other) { double rate = 0; rate += fabs(my_rect.angle)/90.0; // angle is in (-90,+90), 90 is the best rate += 1.0 - fabs(BOILER_TAPE_RATIO - my_rect.size.height/my_rect.size.width); rate += 1.0 - fabs((my_rect.center.x-other_rect.center.x) / (my_rect.center.y-other_rect.center.y)); rate += 1.0 - fabs(BOILER_TAPE_RATIO2 - my_rect.size.height / norm(my_rect.center-other_rect.center)); return rate; }; RingRelation(std::vector<cv::Point> *cont, cv::RotatedRect rect, const std::vector<RingRelation> &chain) : rating(0), my_cont(cont), my_rect(rect), other_cont(cont), other_rect(rect) { for(auto&& other : chain) { double temp = rate2rings(other); if(temp > rating) { rating = temp; other_rect = other.my_rect; other_cont = other.my_cont; } } }; // This comparison operator is for sort. Reversed for descending order. bool operator<(RingRelation &other) { return rating > other.rating; }; }; void CheezyInRange( cv::cuda::GpuMat src, cv::Vec3i BlobLower, cv::Vec3i BlobUpper, cv::cuda::GpuMat dst, cv::cuda::Stream stream = cv::cuda::Stream::Null()) { cv::cuda::GpuMat channels[3]; cv::cuda::split(src, channels, stream); //threshold, reset to zero everything that is above the upper limit cv::cuda::threshold(channels[0], channels[0], BlobUpper[0], 255, cv::THRESH_TOZERO_INV, stream); cv::cuda::threshold(channels[1], channels[1], BlobUpper[1], 255, cv::THRESH_TOZERO_INV, stream); cv::cuda::threshold(channels[2], channels[2], BlobUpper[2], 255, cv::THRESH_TOZERO_INV, stream); //threshold, reset to zero what is below the lower limit, otherwise to 255 cv::cuda::threshold(channels[0], channels[0], BlobLower[0], 255, cv::THRESH_BINARY, stream); cv::cuda::threshold(channels[1], channels[1], BlobLower[1], 255, cv::THRESH_BINARY, stream); cv::cuda::threshold(channels[2], channels[2], BlobLower[2], 255, cv::THRESH_BINARY, stream); //combine all three channels and collapse them into one B/W image (to channels[0]) cv::cuda::bitwise_and(channels[0], channels[1], channels[0], cv::noArray(), stream); cv::cuda::bitwise_and(channels[0], channels[2], dst, cv::noArray(), stream); } void righten(cv::RotatedRect &rectangle) { if (rectangle.size.height < rectangle.size.width) { std::swap(rectangle.size.height, rectangle.size.width); rectangle.angle += 90.0; } rectangle.angle = fmod(rectangle.angle, 180.0); if (rectangle.angle > 90.0) rectangle.angle -= 180; if (rectangle.angle < -90.0) rectangle.angle += 180; } bool readIntrinsics(const char *filename, cv::Mat &intrinsic, cv::Mat &distortion) { cv::FileStorage fs( filename, cv::FileStorage::READ ); if( !fs.isOpened() ) { std::cerr << "Error: Couldn't open intrinsic parameters file " << filename << std::endl; return false; } fs["camera_matrix"] >> intrinsic; fs["distortion_coefficients"] >> distortion; if( intrinsic.empty() || distortion.empty() ) { std::cerr << "Error: Couldn't load intrinsic parameters from " << filename << std::endl; return false; } fs.release(); return true; } cv::Point2d intersect(cv::Point2d pivot, cv::Matx22d rotation, cv::Point one, cv::Point two) { cv::Point2d ret(-1,-1); cv::Point2d one_f(one), two_f(two); cv::Vec2d one_v = rotation * (one_f - pivot); cv::Vec2d two_v = rotation * (two_f - pivot); if(one_v[0] > 0 and two_v[0] > 0) return ret; if(one_v[0] < 0 and two_v[0] < 0) return ret; if(one_v[0] == 0) return one_f; if(two_v[0] == 0) return two_f; double y0 = two_v[1] - two_v[0] * (one_v[1]-two_v[1])/(one_v[0]-two_v[0]); ret = rotation.t() * cv::Point2d(0, y0) + pivot; return ret; } bool compPoints(const cv::Point2d a, const cv::Point2d b) { return (a.y < b.y); } void FindMidPoints(std::vector<cv::Point> *upCont, std::vector<cv::Point> *dnCont, std::vector<cv::Point2d> &imagePoints) { std::vector<cv::Point> new_points = *upCont; new_points.reserve(upCont->size()+dnCont->size()); for(size_t i=0; i<dnCont->size(); ++i) new_points.push_back((*dnCont)[i]); cv::RotatedRect big = cv::minAreaRect(new_points); if(fabs(big.angle) > 45 and fabs(big.angle) < 135) { std::swap(big.size.height, big.size.width); big.angle = fmod(big.angle+90.0, 180.0); if (big.angle > 90.0) big.angle -= 180; if (big.angle < -90.0) big.angle += 180; } double cosT = cos(CV_PI*big.angle/180.0); double sinT = -sin(CV_PI*big.angle/180.0); // RotatedRect::angle is clockwise, so negative cv::Matx22d rmat(cosT, -sinT, sinT, cosT); std::vector<cv::Point2d> pointsUp; for(size_t i = 0; i < upCont->size(); ++i) { cv::Point2d point = intersect(big.center, rmat, (*upCont)[i], (*upCont)[(i+1)%upCont->size()]); if(point != cv::Point2d(-1,-1)) pointsUp.push_back(point); } if(pointsUp.size() > 1) { std::sort(pointsUp.begin(), pointsUp.end(), compPoints); imagePoints.push_back(pointsUp.front()); imagePoints.push_back(pointsUp.back()); } std::vector<cv::Point2d> pointsDn; for(size_t i = 0; i < dnCont->size(); ++i) { cv::Point2d point = intersect(big.center, rmat, (*dnCont)[i], (*dnCont)[(i+1)%dnCont->size()]); if(point != cv::Point2d(-1,-1)) pointsDn.push_back(point); } if(pointsDn.size() > 1) { std::sort(pointsDn.begin(), pointsDn.end(), compPoints); imagePoints.push_back(pointsDn.front()); imagePoints.push_back(pointsDn.back()); } } int main(int argc, const char** argv) { const char* intrinsic_file = default_intrinsic_file; if(argc > 1) intrinsic_file = argv[1]; cv::Mat intrinsic, distortion; if(!readIntrinsics(intrinsic_file, intrinsic, distortion)) return -1; NetworkTable::SetClientMode(); NetworkTable::SetTeam(3130); std::shared_ptr<NetworkTable> table = NetworkTable::GetTable("/Jetson"); std::shared_ptr<NetworkTable> preferences = NetworkTable::GetTable("/Preferences"); cv::Mat frame, filtered, display; cv::cuda::GpuMat gpuC, gpu1, gpu2; static cv::Vec3i BlobLower(66, 200, 30); static cv::Vec3i BlobUpper(94, 255, 255); static int dispMode = 2; // 0: none, 1: bw, 2: color cv::Vec3d camera_offset(-7.0, -4.0, -12); static std::vector<cv::Point3d> realPoints; realPoints.push_back(cv::Point3d(0,-4, 0)); realPoints.push_back(cv::Point3d(0, 0, 0.3)); realPoints.push_back(cv::Point3d(0, 4, 0.3)); realPoints.push_back(cv::Point3d(0, 6, 0)); cv::VideoCapture capture; for(;;) { std::ostringstream capturePipe; capturePipe << "nvcamerasrc ! video/x-raw(memory:NVMM)" << ", width=(int)" << frameSize.width << ", height=(int)" << frameSize.height << ", format=(string)I420, framerate=(fraction)30/1 ! " << "nvvidconv flip-method=2 ! video/x-raw, format=(string)BGRx ! " << "videoconvert ! video/x-raw, format=(string)BGR ! appsink"; // if(!capture.open(capturePipe.str())) { capture.open(0); capture.set(cv::CAP_PROP_FRAME_WIDTH, frameSize.width); capture.set(cv::CAP_PROP_FRAME_HEIGHT, frameSize.height); capture.set(cv::CAP_PROP_FPS, 7.5); capture.set(cv::CAP_PROP_AUTO_EXPOSURE, 0.25); // Magic! 0.25 means manual exposure, 0.75 = auto capture.set(cv::CAP_PROP_EXPOSURE, 0); capture.set(cv::CAP_PROP_BRIGHTNESS, 0.5); capture.set(cv::CAP_PROP_CONTRAST, 0.5); capture.set(cv::CAP_PROP_SATURATION, 0.5); std::cerr << "Resolution: "<< capture.get(cv::CAP_PROP_FRAME_WIDTH) << "x" << capture.get(cv::CAP_PROP_FRAME_HEIGHT) << " FPS: " << capture.get(cv::CAP_PROP_FPS) << std::endl; // } if(capture.isOpened()) break; std::cerr << "Couldn't connect to camera" << std::endl; } #ifdef XGUI_ENABLED cv::namedWindow(detection_window, cv::WINDOW_NORMAL); cv::createTrackbar("Lo H",detection_window, &BlobLower[0], 255); cv::createTrackbar("Hi H",detection_window, &BlobUpper[0], 255); cv::createTrackbar("Lo S",detection_window, &BlobLower[1], 255); cv::createTrackbar("Hi S",detection_window, &BlobUpper[1], 255); cv::createTrackbar("Lo V",detection_window, &BlobLower[2], 255); cv::createTrackbar("Hi V",detection_window, &BlobUpper[2], 255); #endif int elemSize(5); cv::Mat element = getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(elemSize+1,elemSize+1)); cv::Ptr<cv::cuda::Filter> erode = cv::cuda::createMorphologyFilter(cv::MORPH_ERODE, gpu1.type(), element); cv::Ptr<cv::cuda::Filter> dilate = cv::cuda::createMorphologyFilter(cv::MORPH_DILATE, gpu1.type(), element); gpu1.create(frameSize, CV_8UC1); gpu2.create(frameSize, CV_8UC1); cv::cuda::Stream cudastream; for(;;) { capture >> frame; if (frame.empty()) { std::cerr << " Error reading from camera, empty frame." << std::endl; std::this_thread::sleep_for(std::chrono::seconds(2)); continue; } std::vector<long int> timer_values; std::vector<std::string> timer_names; timer_names.push_back("start"); timer_values.push_back(cv::getTickCount()); gpuC.upload(frame); timer_names.push_back("uploaded"); timer_values.push_back(cv::getTickCount()); cv::cuda::cvtColor(gpuC, gpuC, CV_BGR2HSV, 0, cudastream); CheezyInRange(gpuC, BlobLower, BlobUpper, gpu1, cudastream); erode->apply(gpu1, gpu2, cudastream); dilate->apply(gpu2, gpu1, cudastream); timer_names.push_back("cuda sched"); timer_values.push_back(cv::getTickCount()); cudastream.waitForCompletion(); timer_names.push_back("cuda done"); timer_values.push_back(cv::getTickCount()); gpu1.download(filtered); #ifdef XGUI_ENABLED switch(dispMode) { case 1: cv::resize(filtered, display, displaySize); break; case 2: cv::resize(frame, display, displaySize); break; } #endif std::vector<std::vector<cv::Point>> contours; cv::findContours(filtered, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE); std::vector<RingRelation> graph; for (auto&& cont : contours) { cv::RotatedRect rect = cv::minAreaRect(cont); double area = rect.size.height * rect.size.width; if (area < MIN_AREA) continue; righten(rect); if (fabs(rect.angle) < 45) continue; graph.push_back(RingRelation(&cont, rect, graph)); } std::sort(graph.begin(), graph.end()); if (graph.size() > 1) { double distance, yaw; #ifdef XGUI_ENABLED cv::Point dispTarget(displaySize.width/2,displaySize.height*0.9); #endif std::vector<cv::Point2d> imagePoints; if (graph[0].my_rect.center.y < graph[1].my_rect.center.y) { FindMidPoints(graph[0].my_cont, graph[1].my_cont, imagePoints); } else { FindMidPoints(graph[1].my_cont, graph[0].my_cont, imagePoints); } cv::Vec3d rvec, tvec; if(imagePoints.size() == 4) { std::vector<cv::Point2d> undistortedPoints; cv::undistortPoints(imagePoints, undistortedPoints, intrinsic, distortion, cv::noArray(), intrinsic); double cam_tilt = preferences->GetNumber("Front Camera Tilt", 40); cv::Vec3d cam_offset(-18, 0, -18); double cam_cos = cos(CV_PI*cam_tilt/180.0); double dee = cv::norm(undistortedPoints[0] - undistortedPoints[3]); distance = cam_cos * intrinsic.at<double>(1,1) * fabs(realPoints[3].y-realPoints[0].y) / dee; double m_zenith = intrinsic.at<double>(0,0) * preferences->GetNumber("CameraZeroDist", CAMERA_ZERO_DIST) / preferences->GetNumber("CameraHeight", CAMERA_GOAL_HEIGHT); double m_horizon = intrinsic.at<double>(0,0) * preferences->GetNumber("CameraHeight", CAMERA_GOAL_HEIGHT) / preferences->GetNumber("CameraZeroDist", CAMERA_ZERO_DIST); double m_flat = sqrt(intrinsic.at<double>(0,0)*intrinsic.at<double>(0,0) + m_horizon*m_horizon); // dX is the offset of the target from the focal center to the right float dX = undistortedPoints[0].x - intrinsic.at<double>(0,2); // dY is the distance from the zenith to the target on the image float dY = m_zenith + undistortedPoints[0].y - intrinsic.at<double>(1,2); // The real azimuth to the target is on the horizon, so scale it accordingly float azimuth = dX * ((m_zenith + m_horizon) / dY); // Vehicle's yaw is negative arc tangent from the current heading to the target yaw = -atan2(azimuth, m_flat); table->PutNumber("Boiler Distance", distance); table->PutNumber("Boiler Yaw", yaw); } timer_names.push_back("calcs done"); timer_values.push_back(cv::getTickCount()); #ifdef XGUI_ENABLED if (dispMode == 2) { if(imagePoints.size() == 4) { cv::circle(display, imagePoints[0]*displayRatio, 8, cv::Scalar( 0, 0,200), 1); cv::circle(display, imagePoints[1]*displayRatio, 8, cv::Scalar( 0,200,200), 1); cv::circle(display, imagePoints[2]*displayRatio, 8, cv::Scalar( 0,200, 0), 1); cv::circle(display, imagePoints[3]*displayRatio, 8, cv::Scalar(200, 0, 0), 1); } cv::line(display, dispTarget, cv::Point(displaySize.width/2,displaySize.height*0.9), cv::Scalar(0,255,255)); std::ostringstream oss; oss << "Yaw: " << yaw << " Tvec: " << imagePoints; cv::putText(display, oss.str(), cv::Point(20,20), 0, 0.33, cv::Scalar(0,200,200)); std::ostringstream oss1; oss1 << "Distance: " << distance; cv::putText(display, oss1.str(), cv::Point(20,40), 0, 0.33, cv::Scalar(0,200,200)); } #endif } #ifdef XGUI_ENABLED if (dispMode > 0) { for(size_t i=1; i < timer_values.size(); ++i) { long int val = timer_values[i] - timer_values[0]; std::ostringstream osst; osst << timer_names[i] << ": " << val / cv::getTickFrequency(); cv::putText(display, osst.str(), cv::Point(20,40+20*i), 0, 0.33, cv::Scalar(0,200,200)); } cv::imshow(detection_window, display); } int key = cv::waitKey(20); if ((key & 255) == 27) break; if ((key & 255) == 32) { if(++dispMode > 2) dispMode =0; } if ((key & 255) == 's') cv::waitKey(0); #endif } return 0; }
15,173
6,604
#include "IntervalsList.h" #include <iostream> /** * Default constructor */ IntervalsList::IntervalsList() { head = nullptr; tail = nullptr; next = nullptr; } /** * Destructor */ IntervalsList::~IntervalsList() { while (head != nullptr) { Interval* oldHead = head; head = head->next; delete oldHead; } } /** * Add interval to the list * @param begin -- x coordinate of the begin of the new interval * @param end -- x coordinate of the end of the new interval * @param y_coordinate -- y coordinate of the new interval * @param color -- the color of the cluster that the interval belongs to */ void IntervalsList::addInterval(int begin, int end, int y_coordinate, cv::Vec3b color) { if (head == nullptr) { head = new Interval(begin, end, y_coordinate, color); tail = head; return; } tail->next = new Interval(begin, end, y_coordinate, color); tail = tail->next; } /** * Add interval to the list * @param newInterval -- Pointer to the interval */ void IntervalsList::addInterval(Interval *newInterval) { if (head == nullptr) { head = newInterval; tail = head; return; } tail->next = newInterval; tail = tail->next; } /** * Length of the list * @return */ int IntervalsList::getLength() { if (this->head == nullptr) { return 0; } int res = 1; Interval *temp = head; while (temp->next != nullptr) { res++; temp = temp->next; } return res; }
1,553
494
/** * @file murasaki_platform.hpp * * @date 2017/11/12 * @author Seiichi "Suikan" Horie * @brief An interface for the applicaiton from murasaki library to main.c * @details * The resources below are impremented in the murasaki_platform.cpp and serve as glue to the main.c. */ #ifndef MURASAKI_PLATFORM_HPP_ #define MURASAKI_PLATFORM_HPP_ #ifdef __cplusplus extern "C" { #endif #include <stdint.h> // Murasaki platform control /** * @brief Initialize the platform variables. * @ingroup MURASAKI_PLATFORM_GROUP * @details * The murasaki::platform variable is an interface between the application program and HAL / RTOS. * To use it correctly, the initialization is needed before any activity of murasaki client. * * @code * void StartDefaultTask(void const * argument) * { * InitPlatform(); * ExecPlatform(); * } * @endcode * * This function have to be invoked from the StartDefaultTask() of the main.c only once * to initialize the platform variable. * */ void InitPlatform(); /** * @brief The body of the real application. * @ingroup MURASAKI_PLATFORM_GROUP * @details * The body function of the murasaki application. Usually this function is called from * the StartDefaultTask() of the main.c. * * This function is invoked only once, and never return. See @ref InitPlatform() as calling sample. * * By default, it toggles LED as sample program. * This function can be customized freely. */ void ExecPlatform(); /** * @brief Hook for the assert_failure() in main.c * @ingroup MURASAKI_PLATFORM_GROUP * @param file Name of the source file where assertion happen * @param line Number of the line where assertion happen * @details * This routine provides a custom hook for the assertion inside STM32Cube HAL. * All assertion raised in HAL will be redirected here. * * @code * void assert_failed(uint8_t* file, uint32_t line) * { * CustomAssertFailed(file, line); * } * @endcode * By default, this routine output a message with location informaiton * to the debugger console. */ void CustomAssertFailed(uint8_t* file, uint32_t line); /** * @brief Hook for the default exception handler. Never return. * @ingroup MURASAKI_PLATFORM_GROUP * @details * An entry of the exception. Especialy for the Hard Fault exception. * In this function, the Stack pointer just before exception is retrieved * and pass as the first parameter of the PrintFaultResult(). * * Note : To print the correct information, this function have to be * Jumped in from the exception entry without any data push to the stack. * To avoid the pushing extra data to stack or making stack frame, * Compile the program without debug information and with certain * optimization leve, when you investigate the Hard Fault. * * For example, the start up code for the Nucleo-L152RE is startup_stml152xe.s. * This file is generated by CubeIDE. This file has default handler as like this: * * @code * .section .text.Default_Handler,"ax",%progbits * Default_Handler: * Infinite_Loop: * b Infinite_Loop * @endcode * * This code can be modified to call CustomDefaultHanler as like this : * @code * .global CustomDefaultHandler * .section .text.Default_Handler,"ax",%progbits * Default_Handler: * bl CustomDefaultHandler * Infinite_Loop: * b Infinite_Loop * @endcode * * While it is declared as function prototype, the CustomDefaultHandler is just a label. * Do not call from user application. */ void CustomDefaultHandler(); /** * @brief Printing out the context information. * @param stack_pointer retrieved stack pointer before interrupt / exception. * @details * Do not call from application. This is murasaki_internal_only. * */ void PrintFaultResult(unsigned int * stack_pointer); /** * @brief StackOverflow hook for FreeRTOS * @param xTask Task ID which causes stack overflow. * @param pcTaskName Name of the task which cuases stack overflow. * @fn vApplicationStackOverflowHook * @ingroup MURASAKI_PLATFORM_GROUP * * @details * This function will be called from FreeRTOS when some task causes overflow. * See TaskStrategy::getStackMinHeadroom() for details. * * Because this function prototype is declared by system, * we don't have prototype in the murasaki_platform.hpp. */ #ifdef __cplusplus } #endif #endif /* MURASAKI_PLATFORM_HPP_ */
4,342
1,279
#include "tatamize.h" #include "scran/quality_control/FilterCells.hpp" #include "Rcpp.h" //[[Rcpp::export(rng=false)]] SEXP filter_cells(SEXP x, Rcpp::LogicalVector discard) { scran::FilterCells qc; auto y = qc.run(extract_NumericMatrix_shared(x), static_cast<const int*>(discard.begin())); return new_MatrixChan(std::move(y)); }
343
135
#include<iostream> #include<cstdlib> #define a 9 using namespace std; struct prims { int cost; int parent; bool visited; }; void printGraph(int graph[a][a]){ for(int i=0; i<a; i++){ for(int j=0; j<a; j++){ cout<<graph[i][j]<<" "; } cout<<endl; } } int find_min(struct prims arr[a]){ int least, index; for(int i=0; i<a; i++){ if(arr[i].visited==false && arr[i].cost<least){ least= arr[i].cost; index= i; } } return index; } void prims_mst(int graph[a][a], struct prims arr[a]){ for(int m=0; m<a-1; m++){ int k= find_min(arr); arr[k].visited= true; for(int n=0; n<a; n++){ if(arr[n].visited!=true && graph[k][n]<arr[n].cost){ arr[n].parent= k; arr[n].cost= graph[k][n]; } } } for(int i=0; i<a; i++){ cout<<arr[i].parent<<"-> "; } } int main(){ //Graph int graph[a][a]= { { 0,4,0,0,0,0,0,8,0}, { 4,0,8,0,0,0,0,11,0}, { 0,8,0,7,0,4,0,2,0}, { 0,0,7,0,9,14,0,0,0}, { 0,0,0,9,0,10,0,0,0}, { 0,0,4,14,10,0,2,0,0}, { 0,0,0,0,0,2,0,1,6}, { 8,11,0,0,0,0,1,0,7}, { 0,0,2,0,0,0,6,7,0}, }; //Label Array struct prims arr[a]; int INFINITY, m; for(int i=0; i<a; i++){ arr[i].cost= INFINITY; arr[i].parent= -1; arr[i].visited= false; } int start; //cout<<"Enter the node from which you want to start(0-8): "; //cin>>start; arr[0].cost=0; //printGraph(graph); cout<<endl; prims_mst(graph, arr); }
1,777
804
#pragma once /************************************************************************ * This file is part of the AREG SDK core engine. * AREG SDK is dual-licensed under Free open source (Apache version 2.0 * License) and Commercial (with various pricing models) licenses, depending * on the nature of the project (commercial, research, academic or free). * You should have received a copy of the AREG SDK license description in LICENSE.txt. * If not, please contact to info[at]aregtech.com * * \copyright (c) 2017-2021 Aregtech UG. All rights reserved. * \file areg/base/RuntimeClassID.hpp * \ingroup AREG SDK, Asynchronous Event Generator Software Development Kit * \author Artak Avetyan * \brief AREG Platform, Runtime Class ID * This class contains information of Runtime Class ID. * Every Runtime Class contains class ID value to identify and * cast instances of Runtime Object. * As an ID of Runtime class used class name. * ************************************************************************/ /************************************************************************ * Include files. ************************************************************************/ #include "areg/base/GEGlobal.h" #include "areg/base/String.hpp" #include <utility> ////////////////////////////////////////////////////////////////////////// // RuntimeClassID class declaration ////////////////////////////////////////////////////////////////////////// /** * \brief Runtime Class ID is used in all objects derived from * Runtime Objects. It contains the class ID, so that during * runtime can check and cast the instance of Runtime Object. * In particular, Runtime Object and Runtime Class ID are used * in Threads, Events and other objects to check the instance * of object during runtime. * * \see RuntimeObject **/ class AREG_API RuntimeClassID { /************************************************************************ * friend classes to access default constructor. ************************************************************************/ /** * \brief Declare friend classes to access private default constructor * required to initialize runtime class ID in hash map blocks. **/ template < typename KEY, typename VALUE, typename KEY_TYPE, typename VALUE_TYPE, class Implement > friend class TEHashMap; template <typename RESOURCE_KEY, typename RESOURCE_OBJECT, class HashMap, class Implement> friend class TEResourceMap; ////////////////////////////////////////////////////////////////////////// // Static members ////////////////////////////////////////////////////////////////////////// public: /** * \brief Static function to create empty Runtime Class ID object. * By default, the class ID value is BAD_CLASS_ID. * Change the value after creating class ID object. **/ static inline RuntimeClassID createEmptyClassID( void ); ////////////////////////////////////////////////////////////////////////// // Constructors / Destructor ////////////////////////////////////////////////////////////////////////// public: /** * \brief Initialization constructor. * This constructor is initializing the name Runtime Class ID * \param className The name of Runtime Class ID **/ explicit RuntimeClassID( const char * className ); /** * \brief Copy constructor. * \param src The source to copy data. **/ RuntimeClassID( const RuntimeClassID & src ); /** * \brief Move constructor. * \param src The source to move data. **/ RuntimeClassID( RuntimeClassID && src ) noexcept; /** * \brief Destructor **/ ~RuntimeClassID( void ) = default; ////////////////////////////////////////////////////////////////////////// // Operators ////////////////////////////////////////////////////////////////////////// public: /************************************************************************/ // friend global operators /************************************************************************/ /** * \brief Compares null-terminated string with Runtime Class ID name. * \param lhs Left-Hand Operand, string to compare. * \param rhs Right-Hand Operand, Runtime Class ID to compare the name. * \return Returns true if string is equal to Runtime Class ID. **/ friend inline bool operator == ( const char * lhs, const RuntimeClassID & rhs ); /** * \brief Compare null-terminated string with Runtime Class ID name. * \param lhs Left-Hand Operand, string to compare. * \param rhs Right-Hand Operand, Runtime Class to compare the name. * \return Returns true if string is not equal to Runtime Class ID. **/ friend inline bool operator != ( const char * lhs, const RuntimeClassID & rhs ); /** * \brief Compares number with Runtime Class ID calculated number. * \param lhs Left-Hand Operand, number to compare. * \param rhs Right-Hand Operand, Runtime Class ID to compare the calculated number. * \return Returns true if number is equal to Runtime Class ID. **/ friend inline bool operator == ( unsigned int lhs, const RuntimeClassID & rhs ); /** * \brief Compares number with Runtime Class ID calculated number. * \param lhs Left-Hand Operand, number to compare. * \param rhs Right-Hand Operand, Runtime Class ID to compare the calculated number. * \return Returns true if number is not equal to Runtime Class ID. **/ friend inline bool operator != ( unsigned int lhs, const RuntimeClassID & rhs ); /************************************************************************/ // class members operators /************************************************************************/ /** * \brief Assigning operator. Copies Runtime Class ID name from given Runtime Class ID source * \param src The source of Runtime Class ID to copy. * \return Returns Runtime Class ID object. **/ inline RuntimeClassID & operator = ( const RuntimeClassID & src ); /** * \brief Move operator. Moves Runtime Class ID name from given Runtime Class ID source. * \param src The source of Runtime Class ID to move. * \return Returns Runtime Class ID object. **/ inline RuntimeClassID & operator = ( RuntimeClassID && src ) noexcept; /** * \brief Assigning operator. Copies Runtime Class ID name from given string buffer source * \param src The source of string buffer to copy. * \return Returns Runtime Class ID object. **/ inline RuntimeClassID & operator = ( const char * src ); /** * \brief Assigning operator. Copies Runtime Class ID name from given string source * \param src The source of string to copy. * \return Returns Runtime Class ID object. **/ inline RuntimeClassID & operator = ( const String & src ); /** * \brief Comparing operator. Compares 2 Runtime Class ID objects. * \param other The Runtime Class ID object to compare * \return Returns true if 2 instance of Runtime Class ID have same Class ID value. **/ inline bool operator == ( const RuntimeClassID & other ) const; /** * \brief Comparing operator. Compares Runtime Class ID and string. * \param other The null-terminated string to compare * \return Returns true if Runtime Class ID value is equal to null-terminated string. **/ inline bool operator == ( const char * other ) const; /** * \brief Comparing operator. Compares 2 Runtime Class ID objects. * \param other The Runtime Class ID object to compare * \return Returns true if 2 instance of Runtime Class ID have different Class ID values. **/ inline bool operator != ( const RuntimeClassID & other ) const; /** * \brief Comparing operator. Compares Runtime Class ID and string. * \param other The null-terminated string to compare * \return Returns true if Runtime Class ID value is not equal to given null-terminated string. **/ inline bool operator != (const char * other) const; /** * \brief Operator to convert the value or Runtime Class ID to unsigned integer value. * Used to calculate hash value in hash map **/ inline explicit operator unsigned int ( void ) const; ////////////////////////////////////////////////////////////////////////// // Attributes ////////////////////////////////////////////////////////////////////////// /** * \brief Returns true if the value of Runtime Class ID is not equal to RuntimeClassID::BAD_CLASS_ID. **/ inline bool isValid( void ) const; /** * \brief Returns the name of Runtime Class ID. **/ inline const char * getName( void ) const; /** * \brief Sets the name of Runtime Class ID. **/ void setName( const char * className ); /** * \brief Returns calculated number of runtime class. **/ inline unsigned getMagic( void ) const; ////////////////////////////////////////////////////////////////////////// // Hidden methods ////////////////////////////////////////////////////////////////////////// private: /** * \brief Default constructor. Private. Will create BAD_CLASS_ID * object. **/ RuntimeClassID( void ); ////////////////////////////////////////////////////////////////////////// // Member variables ////////////////////////////////////////////////////////////////////////// private: /** * \brief Runtime Class ID value. **/ String mClassName; /** * \brief The calculated number of runtime class. **/ unsigned int mMagicNum; }; ////////////////////////////////////////////////////////////////////////// // RuntimeClassID class inline function implementation ////////////////////////////////////////////////////////////////////////// inline RuntimeClassID RuntimeClassID::createEmptyClassID( void ) { return RuntimeClassID(); } inline RuntimeClassID & RuntimeClassID::operator = ( const RuntimeClassID & src ) { this->mClassName= src.mClassName; this->mMagicNum = src.mMagicNum; return (*this); } inline RuntimeClassID & RuntimeClassID::operator = ( RuntimeClassID && src ) noexcept { this->mClassName= std::move(src.mClassName); this->mMagicNum = src.mMagicNum; return (*this); } inline RuntimeClassID & RuntimeClassID::operator = ( const char * src ) { setName(src); return (*this); } inline RuntimeClassID & RuntimeClassID::operator = ( const String & src ) { setName(src); return (*this); } inline bool RuntimeClassID::operator == ( const RuntimeClassID & other ) const { return (mMagicNum == other.mMagicNum); } inline bool RuntimeClassID::operator == ( const char * other ) const { return mClassName == other; } inline bool RuntimeClassID::operator != ( const RuntimeClassID & other ) const { return (mMagicNum != other.mMagicNum); } inline bool RuntimeClassID::operator != ( const char* other ) const { return mClassName != other; } inline RuntimeClassID::operator unsigned int ( void ) const { return mMagicNum; } inline bool RuntimeClassID::isValid( void ) const { return (mMagicNum != NEMath::CHECKSUM_IGNORE); } inline const char* RuntimeClassID::getName( void ) const { return mClassName.getString(); } inline unsigned RuntimeClassID::getMagic(void) const { return mMagicNum; } inline bool operator == ( const char * lhs, const RuntimeClassID & rhs ) { return rhs.mClassName == lhs; } inline bool operator != ( const char* lhs, const RuntimeClassID & rhs ) { return rhs.mClassName != lhs; } inline bool operator == ( unsigned int lhs, const RuntimeClassID & rhs ) { return rhs.mMagicNum == lhs; } inline bool operator != ( unsigned int lhs, const RuntimeClassID & rhs ) { return rhs.mMagicNum != lhs; }
12,230
3,037
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/base_paths.h" #include "base/bind.h" #include "base/callback.h" #include "base/files/file.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/task/post_task.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "build/build_config.h" #include "chrome/test/base/in_process_browser_test.h" #include "components/services/patch/content/patch_service.h" #include "components/services/patch/public/cpp/patch.h" #include "components/update_client/component_patcher_operation.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "courgette/courgette.h" #include "courgette/third_party/bsdiff/bsdiff.h" namespace { constexpr base::TaskTraits kThreadPoolTaskTraits = { base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}; } // namespace class PatchTest : public InProcessBrowserTest { public: PatchTest() { EXPECT_TRUE(installed_dir_.CreateUniqueTempDir()); EXPECT_TRUE(input_dir_.CreateUniqueTempDir()); EXPECT_TRUE(unpack_dir_.CreateUniqueTempDir()); } static base::FilePath TestFile(const char* name) { base::FilePath path; base::PathService::Get(base::DIR_SOURCE_ROOT, &path); return path.AppendASCII("components") .AppendASCII("test") .AppendASCII("data") .AppendASCII("update_client") .AppendASCII(name); } base::FilePath InputFilePath(const char* name) { base::FilePath path = installed_dir_.GetPath().AppendASCII(name); base::RunLoop run_loop; base::ThreadPool::PostTaskAndReply( FROM_HERE, kThreadPoolTaskTraits, base::BindOnce(&PatchTest::CopyFile, TestFile(name), path), run_loop.QuitClosure()); run_loop.Run(); return path; } base::FilePath PatchFilePath(const char* name) { base::FilePath path = input_dir_.GetPath().AppendASCII(name); base::RunLoop run_loop; base::ThreadPool::PostTaskAndReply( FROM_HERE, kThreadPoolTaskTraits, base::BindOnce(&PatchTest::CopyFile, TestFile(name), path), run_loop.QuitClosure()); run_loop.Run(); return path; } base::FilePath OutputFilePath(const char* name) { return unpack_dir_.GetPath().AppendASCII(name); } base::FilePath InvalidPath(const char* name) { return input_dir_.GetPath().AppendASCII("nonexistent").AppendASCII(name); } void RunPatchTest(const std::string& operation, const base::FilePath& input, const base::FilePath& patch, const base::FilePath& output, int expected_result) { base::RunLoop run_loop; quit_closure_ = run_loop.QuitClosure(); done_called_ = false; base::ThreadPool::CreateSequencedTaskRunner(kThreadPoolTaskTraits) ->PostTask(FROM_HERE, base::BindOnce(&PatchTest::PatchAsyncSequencedTaskRunner, base::Unretained(this), operation, input, patch, output, expected_result)); run_loop.Run(); EXPECT_TRUE(done_called_); } private: void PatchAsyncSequencedTaskRunner( const std::string& operation, const base::FilePath& input, const base::FilePath& patch, const base::FilePath& output, int expected_result) { patch::Patch(patch::LaunchFilePatcher(), operation, input, patch, output, base::BindOnce(&PatchTest::PatchDone, base::Unretained(this), expected_result)); } void PatchDone(int expected, int result) { EXPECT_EQ(expected, result); done_called_ = true; base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}) ->PostTask(FROM_HERE, std::move(quit_closure_)); } static void CopyFile(const base::FilePath& source, const base::FilePath& target) { EXPECT_TRUE(base::CopyFile(source, target)); } base::ScopedTempDir installed_dir_; base::ScopedTempDir input_dir_; base::ScopedTempDir unpack_dir_; base::OnceClosure quit_closure_; bool done_called_; DISALLOW_COPY_AND_ASSIGN(PatchTest); }; IN_PROC_BROWSER_TEST_F(PatchTest, CheckBsdiffOperation) { constexpr int kExpectedResult = bsdiff::OK; base::FilePath input_file = InputFilePath("binary_input.bin"); base::FilePath patch_file = PatchFilePath("binary_bsdiff_patch.bin"); base::FilePath output_file = OutputFilePath("output.bin"); RunPatchTest(update_client::kBsdiff, input_file, patch_file, output_file, kExpectedResult); EXPECT_TRUE(base::ContentsEqual(TestFile("binary_output.bin"), output_file)); } IN_PROC_BROWSER_TEST_F(PatchTest, CheckCourgetteOperation) { constexpr int kExpectedResult = courgette::C_OK; base::FilePath input_file = InputFilePath("binary_input.bin"); base::FilePath patch_file = PatchFilePath("binary_courgette_patch.bin"); base::FilePath output_file = OutputFilePath("output.bin"); RunPatchTest(update_client::kCourgette, input_file, patch_file, output_file, kExpectedResult); EXPECT_TRUE(base::ContentsEqual(TestFile("binary_output.bin"), output_file)); } IN_PROC_BROWSER_TEST_F(PatchTest, InvalidInputFile) { constexpr int kInvalidInputFile = -1; base::FilePath invalid = InvalidPath("binary_input.bin"); base::FilePath patch_file = PatchFilePath("binary_courgette_patch.bin"); base::FilePath output_file = OutputFilePath("output.bin"); RunPatchTest(update_client::kCourgette, invalid, patch_file, output_file, kInvalidInputFile); } IN_PROC_BROWSER_TEST_F(PatchTest, InvalidPatchFile) { constexpr int kInvalidPatchFile = -1; base::FilePath input_file = InputFilePath("binary_input.bin"); base::FilePath invalid = InvalidPath("binary_courgette_patch.bin"); base::FilePath output_file = OutputFilePath("output.bin"); RunPatchTest(update_client::kCourgette, input_file, invalid, output_file, kInvalidPatchFile); } IN_PROC_BROWSER_TEST_F(PatchTest, InvalidOutputFile) { constexpr int kInvalidOutputFile = -1; base::FilePath input_file = InputFilePath("binary_input.bin"); base::FilePath patch_file = PatchFilePath("binary_courgette_patch.bin"); base::FilePath invalid = InvalidPath("output.bin"); RunPatchTest(update_client::kCourgette, input_file, patch_file, invalid, kInvalidOutputFile); }
6,764
2,239
// ------------------------------------------------------------------------- // CV Drone (= OpenCV + AR.Drone) // Copyright(C) 2016 puku0x // https://github.com/puku0x/cvdrone // // This source file is part of CV Drone library. // // This library is free software; you can redistribute it and/or // modify it under the terms of EITHER: // (1) The GNU Lesser General Public License as published by the Free // Software Foundation; either version 2.1 of the License, or (at // your option) any later version. The text of the GNU Lesser // General Public License is included with this library in the // file cvdrone-license-LGPL.txt. // (2) The BSD-style license that is included with this library in // the file cvdrone-license-BSD.txt. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files // cvdrone-license-LGPL.txt and cvdrone-license-BSD.txt for more details. // //! @file ardrone.cpp //! @brief A source file of AR.Drone class // // ------------------------------------------------------------------------- #include "ardrone.h" // -------------------------------------------------------------------------- //! @brief Constructor of AR.Drone class //! @param ardrone_addr IP address of AR.Drone //! @return None // -------------------------------------------------------------------------- ARDrone::ARDrone(const char *ardrone_addr) { // IP Address strncpy(ip, ARDRONE_DEFAULT_ADDR, 16); // Sequence number seq = 0; // Camera image img = NULL; // Version information memset(&version, 0, sizeof(version)); // Navdata memset(&navdata, 0, sizeof(navdata)); // Configurations memset(&config, 0, sizeof(config)); // Video pFormatCtx = NULL; pCodecCtx = NULL; pFrame = NULL; pFrameBGR = NULL; bufferBGR = NULL; pConvertCtx = NULL; // Thread for AT command threadCommand = NULL; mutexCommand = NULL; // Thread for Navdata threadNavdata = NULL; mutexNavdata = NULL; // Thread for Video threadVideo = NULL; mutexVideo = NULL; // Open if the IP address was specified if (ardrone_addr != NULL) { open(ardrone_addr); } } // -------------------------------------------------------------------------- //! @brief Destructor of ARDrone class //! @return None // -------------------------------------------------------------------------- ARDrone::~ARDrone() { // See you close(); } // -------------------------------------------------------------------------- //! @brief Initialize the AR.Drone. //! @param ardrone_addr IP address of AR.Drone //! @return Result of initialization //! @retval 1 Success //! @retval 0 Failure // -------------------------------------------------------------------------- int ARDrone::open(const char *ardrone_addr) { // Initialize FFmpeg av_register_all(); avformat_network_init(); av_log_set_level(AV_LOG_QUIET); // Save IP address strncpy(ip, ardrone_addr, 16); // Get version information if (!getVersionInfo()) return 0; std::cout << "AR.Drone Ver. " << version.major << "." << version.minor << "." << version.revision << "." << std::endl; // Initialize AT command if (!initCommand()) return 0; // Blink LEDs setLED(ARDRONE_LED_ANIM_BLINK_GREEN); // Initialize Navdata if (!initNavdata()) return 0; // Initialize Video if (!initVideo()) return 0; // Wait for updating the status //msleep(500); // Get configurations if (!getConfig()) return 0; // Stop LED animation setLED(ARDRONE_LED_ANIM_STANDARD); // Reset emergency resetWatchDog(); resetEmergency(); return 1; } // -------------------------------------------------------------------------- //! @brief Update the information of the AR.Drone. //! @return Result of update //! @retval 1 Success //! @retval 0 Failure // -------------------------------------------------------------------------- int ARDrone::update(void) { return 1; } // -------------------------------------------------------------------------- //! @brief Finalize the AR.Drone class. //! @return None // -------------------------------------------------------------------------- void ARDrone::close(void) { // Stop AR.Drone if (!onGround()) landing(); // Stop LED animation setLED(ARDRONE_LED_ANIM_STANDARD); // Finalize video finalizeVideo(); // Finalize Navdata finalizeNavdata(); // Finalize AT command finalizeCommand(); }
4,705
1,428
#include "InputData.h" #include "xmltags.h" #include "ParameterValues.h" #include "CNTKWrapperInternals.h" #include "Exceptions.h" InputData::InputData(tinyxml2::XMLElement * pParentNode) { m_id = pParentNode->Attribute(XML_ATTRIBUTE_Id); if (m_id.empty()) throw ProblemParserElementNotFound(XML_ATTRIBUTE_Id); m_name = pParentNode->Attribute(XML_ATTRIBUTE_Name); if (m_name.empty()) m_name = "InputData"; tinyxml2::XMLElement* pNode = pParentNode->FirstChildElement(XML_TAG_Shape); if (pNode == nullptr) throw ProblemParserElementNotFound(XML_TAG_Shape); m_pShape = CIntTuple::getInstance(pNode); } InputData::InputData(string id, CNTK::Variable pInputVariable) { m_id = id; m_inputVariable = pInputVariable; } InputData::~InputData() { } InputData * InputData::getInstance(tinyxml2::XMLElement * pNode) { if (!strcmp(pNode->Name(), XML_TAG_InputData)) return new InputData(pNode); return nullptr; } NDShape InputData::getNDShape() { return m_pShape->getNDShape(); } void InputData::createInputVariable() { m_isInitialized = true; m_inputVariable = CNTK::InputVariable(m_pShape->getNDShape(), CNTK::DataType::Double, CNTKWrapper::Internal::string2wstring(m_id)); }
1,200
462
/* * Copyright (C) 2018 Intel Corporation.All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ /** * File: IasDiagnosticStream.cpp */ #include <assert.h> #include <ctime> #include <cstdio> #include <algorithm> #include <chrono> #include "diagnostic/IasDiagnosticStream.hpp" #include "diagnostic/IasDiagnosticLogWriter.hpp" namespace IasAudio { #define TMP_PATH "/tmp/" static const std::string cClassName = "IasDiagnosticStream::"; #define LOG_PREFIX cClassName + __func__ + "(" + std::to_string(__LINE__) + "):" #define LOG_DEVICE "device=" + mParams.deviceName + ":" #define LOG_STATE "[" + toString(mStreamState) + "]" IasDiagnosticStream::IasDiagnosticStream(const struct IasParams& params, IasDiagnosticLogWriter& logWriter) :mLog(IasAudioLogging::registerDltContext("AHD", "ALSA Handler")) ,mLogThread(IasAudioLogging::registerDltContext("AHDD", "ALSA Handler Diagnostic File Operations Thread")) ,mParams(params) ,mPeriodCounter(0) ,mMaxCounter(0) ,mTmpFile() ,mTmpFileName() ,mTmpFileNameFull() ,mStreamState(eIasStreamStateIdle) ,mStreamStateMutex() ,mFileOpen() ,mFileClose() ,mCondWaitForStart() ,mMutexWaitForStart() ,mStreamStarted(false) ,mErrorCounter(0) ,mLogWriter(logWriter) ,mFileIdx(0) { if (mParams.periodTime == 0) { // Set default to 5333us mParams.periodTime = 5333; } std::uint32_t bytesPerSecond = cBytesPerPeriod * 1000 * 1000 / mParams.periodTime; std::uint32_t bytesPerHour = bytesPerSecond * 60 * 60; mMaxCounter = bytesPerHour / cBytesPerPeriod; DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_DEVICE, "Maximum bytes recorded per hour=", bytesPerHour, "maximum counter=", mMaxCounter); } IasDiagnosticStream::~IasDiagnosticStream() { changeState(IasTriggerStateChange::eIasStop); isStopped(); // this call really waits until the stream is stopped and the file is closed if (mFileOpen.joinable()) { DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, "File open thread will be joined now"); mFileOpen.join(); } if (mFileClose.joinable()) { DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, "File close thread will be joined now"); mFileClose.join(); } DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX); } void IasDiagnosticStream::writeAlsaHandlerData(std::uint64_t timestampDeviceBuffer, std::uint64_t numTransmittedFramesDevice, std::uint64_t timestampAsrcBuffer, std::uint64_t numTransmittedFramesAsrc, std::uint32_t asrcBufferNumFramesAvailable, std::uint32_t numTotalFrames, std::float_t ratioAdaptive) { if (mStreamState != eIasStreamStateStarted) { DLT_LOG_CXX(*mLog, DLT_LOG_VERBOSE, LOG_PREFIX, LOG_STATE, "Stream not started yet"); return; } DLT_LOG_CXX(*mLog, DLT_LOG_VERBOSE, LOG_PREFIX, "Writing data to file, period #", mPeriodCounter); char tmpBuffer[cBytesPerPeriod]; std::uint64_t* ptr_ui64 = reinterpret_cast<std::uint64_t*>(tmpBuffer); *ptr_ui64++ = timestampDeviceBuffer; *ptr_ui64++ = numTransmittedFramesDevice; *ptr_ui64++ = timestampAsrcBuffer; *ptr_ui64++ = numTransmittedFramesAsrc; std::uint32_t* ptr_ui32 = reinterpret_cast<std::uint32_t*>(ptr_ui64); *ptr_ui32++ = asrcBufferNumFramesAvailable; *ptr_ui32++ = numTotalFrames; std::float_t* ptr_float = reinterpret_cast<std::float_t*>(ptr_ui32); *ptr_float = ratioAdaptive; mTmpFile.write(tmpBuffer, cBytesPerPeriod); ++mPeriodCounter; if (mPeriodCounter > mMaxCounter) { mPeriodCounter = 0; changeState(eIasStop); } } IasDiagnosticStream::IasResult IasDiagnosticStream::startStream() { IasStreamState newState = changeState(eIasStart); if ((newState == eIasStreamStateOpening) || (newState == eIasStreamStatePendingOpen)) { return IasResult::eIasOk; } else { return IasResult::eIasFailed; } } IasDiagnosticStream::IasResult IasDiagnosticStream::stopStream() { IasStreamState newState = changeState(eIasStop); if ((newState == eIasStreamStateClosing) || (newState == eIasStreamStatePendingClose)) { return IasResult::eIasOk; } else { return IasResult::eIasFailed; } } IasDiagnosticStream::IasStreamState IasDiagnosticStream::changeState(IasTriggerStateChange trigger) { std::lock_guard<std::mutex> lock(mStreamStateMutex); switch (mStreamState) { case eIasStreamStateIdle: if (trigger == IasTriggerStateChange::eIasStart) { DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStateOpening)); mStreamState = eIasStreamStateOpening; if (mFileOpen.joinable()) { mFileOpen.join(); } mFileOpen = std::thread(&IasDiagnosticStream::openFile, this); } else { DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Ignoring trigger", toString(trigger)); } break; case eIasStreamStateStarted: if (trigger == IasTriggerStateChange::eIasStop) { DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStateClosing)); mStreamState = eIasStreamStateClosing; if (mFileClose.joinable()) { mFileClose.join(); } mFileClose = std::thread(&IasDiagnosticStream::closeFile, this); } else { DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Ignoring trigger", toString(trigger)); } break; case eIasStreamStateOpening: if (trigger == IasTriggerStateChange::eIasOpeningFinished) { DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStateStarted)); mStreamState = eIasStreamStateStarted; { std::lock_guard<std::mutex> lk(mMutexWaitForStart); mStreamStarted = true; } mCondWaitForStart.notify_one(); } else if (trigger == IasTriggerStateChange::eIasStop) { DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStatePendingClose)); mStreamState = eIasStreamStatePendingClose; } else { DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Ignoring trigger", toString(trigger)); } break; case eIasStreamStatePendingClose: if (trigger == IasTriggerStateChange::eIasOpeningFinished) { DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStateClosing)); mStreamState = eIasStreamStateClosing; { std::lock_guard<std::mutex> lk(mMutexWaitForStart); mStreamStarted = true; } mCondWaitForStart.notify_one(); if (mFileClose.joinable()) { mFileClose.join(); } mFileClose = std::thread(&IasDiagnosticStream::closeFile, this); } else { DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Ignoring trigger", toString(trigger)); } break; case eIasStreamStateClosing: if (trigger == IasTriggerStateChange::eIasClosingFinished) { DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStateIdle)); mStreamState = eIasStreamStateIdle; { std::lock_guard<std::mutex> lk(mMutexWaitForStart); mStreamStarted = false; } mCondWaitForStart.notify_one(); } else if (trigger == IasTriggerStateChange::eIasStart) { DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStatePendingOpen)); mStreamState = eIasStreamStatePendingOpen; } else { DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Ignoring trigger", toString(trigger)); } break; case eIasStreamStatePendingOpen: if (trigger == IasTriggerStateChange::eIasClosingFinished) { DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStateOpening)); mStreamState = eIasStreamStateOpening; { std::lock_guard<std::mutex> lk(mMutexWaitForStart); mStreamStarted = false; } mCondWaitForStart.notify_one(); if (mFileOpen.joinable()) { mFileOpen.join(); } mFileOpen = std::thread(&IasDiagnosticStream::openFile, this); } else if (trigger == IasTriggerStateChange::eIasStop) { DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStatePendingClose)); mStreamState = eIasStreamStatePendingClose; } else { DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Ignoring trigger", toString(trigger)); } break; } return mStreamState; } void IasDiagnosticStream::openFile() { if (mTmpFile.is_open() == false) { std::time_t t = std::time(nullptr); std::tm* tm = std::localtime(&t); char currentTime[20] = {'\0'}; if (tm != nullptr) { std::strftime(currentTime, sizeof(currentTime), "%T", tm); } mTmpFileName = std::string(currentTime) + "_" + mParams.deviceName + "_asrc_diag_" + std::to_string(mFileIdx) + ".bin"; mFileIdx++; // Replace all commas with underscore to have a cleaner filename std::replace(mTmpFileName.begin(), mTmpFileName.end(), ',', '_'); mTmpFileNameFull = std::string(TMP_PATH) + mTmpFileName; DLT_LOG_CXX(*mLogThread, DLT_LOG_INFO, LOG_PREFIX, "Opening tmp file", mTmpFileNameFull, "for writing diagnostic log"); mTmpFile.open(mTmpFileNameFull, std::ios::binary|std::ios::out|std::ios::trunc); mErrorCounter = 0; } changeState(eIasOpeningFinished); } void IasDiagnosticStream::closeFile() { if (mTmpFile.is_open()) { std::uint32_t fileSize = static_cast<std::uint32_t>(mTmpFile.tellp()); DLT_LOG_CXX(*mLogThread, DLT_LOG_INFO, LOG_PREFIX, mTmpFileNameFull, "file size=", fileSize); mTmpFile.close(); } DLT_LOG_CXX(*mLogThread, DLT_LOG_INFO, LOG_PREFIX, "Closing file", mTmpFileNameFull, "finished"); bool writeToLog = false; if (mParams.copyTo.compare("log") == 0) { writeToLog = true; } if (mErrorCounter >= mParams.errorThreshold) { if (writeToLog) { mLogWriter.addFile(mTmpFileNameFull); } else { copyFile(); } } else { std::remove(mTmpFileNameFull.c_str()); DLT_LOG_CXX(*mLogThread, DLT_LOG_INFO, LOG_PREFIX, "Removed", mTmpFileNameFull); } mErrorCounter = 0; changeState(eIasClosingFinished); } void IasDiagnosticStream::copyFile() { std::ofstream dstFile; std::ifstream srcFile; std::string dstFileName = mParams.copyTo; if (dstFileName.back() != '/') { dstFileName.append("/"); } dstFileName += mTmpFileName; DLT_LOG_CXX(*mLogThread, DLT_LOG_INFO, LOG_PREFIX, "Copying from", mTmpFileNameFull, "to", dstFileName); dstFile.open(dstFileName, std::ios::binary|std::ios::out|std::ios::trunc); if (dstFile.is_open()) { srcFile.open(mTmpFileNameFull, std::ios::binary); dstFile<<srcFile.rdbuf(); srcFile.close(); dstFile.close(); DLT_LOG_CXX(*mLogThread, DLT_LOG_INFO, LOG_PREFIX, "Copying from", mTmpFileNameFull, "to", dstFileName, "finished successfully."); } else { DLT_LOG_CXX(*mLogThread, DLT_LOG_ERROR, LOG_PREFIX, "Destination file", dstFileName, "couldn't be created"); } std::remove(mTmpFileNameFull.c_str()); DLT_LOG_CXX(*mLogThread, DLT_LOG_INFO, LOG_PREFIX, "Removed", mTmpFileNameFull); } bool IasDiagnosticStream::isStarted() { std::unique_lock<std::mutex> lk(mMutexWaitForStart); bool status = mCondWaitForStart.wait_for(lk, std::chrono::seconds(1), [this] { return mStreamStarted == true; }); if (status == true) { DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, "Stream is started"); } else { DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, "Stream is not started after timeout of 1s"); } return status; } bool IasDiagnosticStream::isStopped() { std::unique_lock<std::mutex> lk(mMutexWaitForStart); bool status = mCondWaitForStart.wait_for(lk, std::chrono::seconds(1), [this] { return mStreamStarted == false; }); if (status == true) { DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, "Stream is stopped"); } else { DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, "Stream is not stopped after timeout of 1s"); } return status; } void IasDiagnosticStream::errorOccurred() { ++mErrorCounter; } #define STRING_RETURN_CASE(name) case name: return std::string(#name); break #define DEFAULT_STRING(name) default: return std::string(name) std::string IasDiagnosticStream::toString(const IasStreamState& streamState) { switch(streamState) { STRING_RETURN_CASE(IasDiagnosticStream::IasStreamState::eIasStreamStateIdle); STRING_RETURN_CASE(IasDiagnosticStream::IasStreamState::eIasStreamStateStarted); STRING_RETURN_CASE(IasDiagnosticStream::IasStreamState::eIasStreamStateOpening); STRING_RETURN_CASE(IasDiagnosticStream::IasStreamState::eIasStreamStateClosing); STRING_RETURN_CASE(IasDiagnosticStream::IasStreamState::eIasStreamStatePendingClose); STRING_RETURN_CASE(IasDiagnosticStream::IasStreamState::eIasStreamStatePendingOpen); DEFAULT_STRING("Invalid IasStreamState => " + std::to_string(streamState)); } } std::string IasDiagnosticStream::toString(const IasTriggerStateChange& trigger) { switch(trigger) { STRING_RETURN_CASE(IasDiagnosticStream::IasTriggerStateChange::eIasStart); STRING_RETURN_CASE(IasDiagnosticStream::IasTriggerStateChange::eIasStop); STRING_RETURN_CASE(IasDiagnosticStream::IasTriggerStateChange::eIasOpeningFinished); STRING_RETURN_CASE(IasDiagnosticStream::IasTriggerStateChange::eIasClosingFinished); DEFAULT_STRING("Invalid IasTriggerStateChange => " + std::to_string(trigger)); } } } /* namespace IasAudio */
14,138
5,186
/* 在第一章中,我们用迭代枚举求解了,寻找最大最小元素 学了分治思想算法,我们能否利用分治的思想 来解决,在数字序列中寻找 最大元素 与 最小元素呢 let's we get start 算法步骤 1 2 3 4 5 分为两部分 1 2 3 4 5 min=1 max=2 3 4 5 min=3 max=3 min=4 max=5 min=3 max=5 min=1 max=2 min=3 max=5 result=> min=1 max=5 */ #include<iostream> #include<cstdio> #include<cstring> using namespace std; const int MAX=100; int list[MAX]; //分治算法之寻找最大和最小元素 void FindMaxMin(int *list,int s,int e,int *maxmin){ if(e-s<=1){//两个元素时 if(list[e]>list[s]){ maxmin[0]=list[e]; maxmin[1]=list[s]; }else{ maxmin[0]=list[e]; maxmin[1]=list[s]; } return; }else{ /*从中间分开,left right 分为两部分 寻找两边的最小元素 与 最大元素 经过比较再选出整体的最大元素与最小元素 */ int mid=(s+e)/2; int leftmaxmin[2]; int rightmaxmin[2]; FindMaxMin(list,s,mid,leftmaxmin); FindMaxMin(list,mid+1,e,rightmaxmin); //比较选出最大值 if(leftmaxmin[0]<rightmaxmin[0]){ maxmin[0]=rightmaxmin[0]; }else{ maxmin[0]=leftmaxmin[0]; } //比较选出最小值 if(leftmaxmin[1]<rightmaxmin[1]){ maxmin[1]=leftmaxmin[1]; }else{ maxmin[1]=rightmaxmin[1]; } } } int main(void){ memset(list,0,sizeof(list)); int maxmin[2]; int n; cout<<"请输入元素个数n\n"; cin>>n; cout<<"n="<<n<<endl; cout<<"请输入元素\n"; for(int i=0;i<n;i++){ scanf("%d",&list[i]); } cout<<"over input list\n"; cout<<"list[]={"; for(int i=0;i<n;i++){ cout<<list[i]<<" "; if(i!=n-1){ cout<<","; } } cout<<"}\n"; FindMaxMin(list,0,n-1,maxmin); cout<<"max="<<maxmin[0]<<" min="<<maxmin[1]<<endl; return 0; }
1,874
886
version https://git-lfs.github.com/spec/v1 oid sha256:c3585e2db12c3926546d8188a694cd568aa96746e1589110d909fb4649296d1f size 18247
130
94
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <glsym/glsym.h> #include <libretro.h> #include <file/file_path.h> #include "libretro_core_options.h" #include "../../game.h" #ifdef OSX #include <pthread.h> #endif #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) struct retro_hw_render_callback hw_render; #if defined(HAVE_PSGL) #define RARCH_GL_FRAMEBUFFER GL_FRAMEBUFFER_OES #define RARCH_GL_FRAMEBUFFER_COMPLETE GL_FRAMEBUFFER_COMPLETE_OES #define RARCH_GL_COLOR_ATTACHMENT0 GL_COLOR_ATTACHMENT0_EXT #elif defined(OSX_PPC) #define RARCH_GL_FRAMEBUFFER GL_FRAMEBUFFER_EXT #define RARCH_GL_FRAMEBUFFER_COMPLETE GL_FRAMEBUFFER_COMPLETE_EXT #define RARCH_GL_COLOR_ATTACHMENT0 GL_COLOR_ATTACHMENT0_EXT #else #define RARCH_GL_FRAMEBUFFER GL_FRAMEBUFFER #define RARCH_GL_FRAMEBUFFER_COMPLETE GL_FRAMEBUFFER_COMPLETE #define RARCH_GL_COLOR_ATTACHMENT0 GL_COLOR_ATTACHMENT0 #endif #define BASE_WIDTH 320 #define BASE_HEIGHT 240 static unsigned MAX_WIDTH = 320; static unsigned MAX_HEIGHT = 240; static unsigned FRAMERATE = 60; static unsigned SND_RATE = 44100; static unsigned width = BASE_WIDTH; static unsigned height = BASE_HEIGHT; static bool libretro_supports_bitmasks = false; Sound::Frame *sndData; char levelpath[255] = {0}; static retro_video_refresh_t video_cb; static retro_audio_sample_batch_t audio_batch_cb; static retro_environment_t environ_cb; static retro_input_poll_t input_poll_cb; static retro_input_state_t input_cb; static retro_set_rumble_state_t set_rumble_cb; #ifdef _WIN32 #include <windows.h> #include <mmsystem.h> // multi-threading void* osMutexInit() { CRITICAL_SECTION *CS = new CRITICAL_SECTION(); InitializeCriticalSection(CS); return CS; } void osMutexFree(void *obj) { DeleteCriticalSection((CRITICAL_SECTION*)obj); delete (CRITICAL_SECTION*)obj; } void osMutexLock(void *obj) { EnterCriticalSection((CRITICAL_SECTION*)obj); } void osMutexUnlock(void *obj) { LeaveCriticalSection((CRITICAL_SECTION*)obj); } int osGetTime() { LARGE_INTEGER Freq, Count; QueryPerformanceFrequency(&Freq); QueryPerformanceCounter(&Count); return int(Count.QuadPart * 1000L / Freq.QuadPart); } void* osRWLockInit() { return osMutexInit(); } void osRWLockFree(void *obj) { osMutexFree(obj); } void osRWLockRead(void *obj) { osMutexLock(obj); } void osRWUnlockRead(void *obj) { osMutexUnlock(obj); } void osRWUnlockWrite(void *obj) { osMutexUnlock(obj); } void osRWLockWrite(void *obj) { osMutexUnlock(obj); } #elif defined(__linux__) #include <pthread.h> #include <sys/time.h> unsigned int startTime; int osGetTime(void) { timeval t; gettimeofday(&t, NULL); return int((t.tv_sec - startTime) * 1000 + t.tv_usec / 1000); } #endif #if defined(__MACH__) #include <mach/mach_time.h> int osGetTime(void) { const int64_t kOneMillion = 1000 * 1000; static mach_timebase_info_data_t info; if (info.denom == 0) mach_timebase_info(&info); return (int)((mach_absolute_time() * info.numer) / (kOneMillion * info.denom)); } #endif void osJoyVibrate(int index, float L, float R) { if(set_rumble_cb) { uint16_t left = int(0xffff * max(0.0f, min(L, 1.0f))); uint16_t right = int(0xffff * max(0.0f, min(R, 1.0f))); set_rumble_cb(index, RETRO_RUMBLE_STRONG, left); set_rumble_cb(index, RETRO_RUMBLE_WEAK, right); } } void retro_init(void) { contentDir[0] = 0; const char slash = path_default_slash_c(); const char *sysdir = NULL; const char *savdir = NULL; const char *subdir = "openlara"; const char *csubdir = "cache"; if (environ_cb(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &sysdir)) { strncpy(cacheDir, sysdir, sizeof(cacheDir)); fill_pathname_slash(cacheDir, sizeof(cacheDir)); strcat(cacheDir, subdir); fill_pathname_slash(cacheDir, sizeof(cacheDir)); if (path_mkdir(cacheDir)) { strcat(cacheDir, csubdir); fill_pathname_slash(cacheDir, sizeof(cacheDir)); if (!path_mkdir(cacheDir)) { cacheDir[0] = 0; fprintf(stderr, "[openlara]: Couldn't create cache subdirectory.\n"); } } else { cacheDir[0] = 0; fprintf(stderr, "[openlara]: Couldn't create cache subdirectory.\n"); } } if (environ_cb(RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY, &savdir)) { strncpy(saveDir, savdir, sizeof(saveDir)); fill_pathname_slash(saveDir, sizeof(saveDir)); strcat(saveDir, subdir); fill_pathname_slash(saveDir, sizeof(saveDir)); fprintf(stderr, "[openlara]: Saves should be in: %s\n", saveDir); if (!path_mkdir(saveDir)) { saveDir[0] = 0; fprintf(stderr, "[openlara]: Couldn't create save subdirectory.\n"); } } if (environ_cb(RETRO_ENVIRONMENT_GET_INPUT_BITMASKS, NULL)) libretro_supports_bitmasks = true; struct retro_rumble_interface rumbleInterface; if (environ_cb(RETRO_ENVIRONMENT_GET_RUMBLE_INTERFACE, &rumbleInterface)) set_rumble_cb = rumbleInterface.set_rumble_state; } void retro_deinit(void) { contentDir[0] = cacheDir[0] = saveDir[0] = 0; libretro_supports_bitmasks = false; } unsigned retro_api_version(void) { return RETRO_API_VERSION; } void retro_set_controller_port_device(unsigned port, unsigned device) { (void)port; (void)device; } void retro_get_system_info(struct retro_system_info *info) { memset(info, 0, sizeof(*info)); info->library_name = "OpenLara"; info->library_version = "v1"; info->need_fullpath = true; info->valid_extensions = "phd|psx|tr2|sat"; } void retro_get_system_av_info(struct retro_system_av_info *info) { info->timing = (struct retro_system_timing) { .fps = (float)FRAMERATE, .sample_rate = (float)SND_RATE, }; info->geometry = (struct retro_game_geometry) { .base_width = BASE_WIDTH, .base_height = BASE_HEIGHT, .max_width = MAX_WIDTH, .max_height = MAX_HEIGHT, .aspect_ratio = (float) MAX_WIDTH / MAX_HEIGHT, }; } void retro_set_environment(retro_environment_t cb) { environ_cb = cb; struct retro_variable variables[] = { { "openlara_framerate", "Framerate (restart); 60fps|70fps|72fps|75fps|90fps|100fps|119fps|120fps|144fps|240fps|244fps|300fps|360fps|30fps", }, { NULL, NULL }, }; libretro_set_core_options(environ_cb); } void retro_set_audio_sample(retro_audio_sample_t cb) { } void retro_set_audio_sample_batch(retro_audio_sample_batch_t cb) { audio_batch_cb = cb; } void retro_set_input_poll(retro_input_poll_t cb) { input_poll_cb = cb; } void retro_set_input_state(retro_input_state_t cb) { input_cb = cb; } void retro_set_video_refresh(retro_video_refresh_t cb) { video_cb = cb; } static void update_variables(bool first_startup) { if (first_startup) { struct retro_variable var; var.key = "openlara_resolution"; if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) { char *pch; char str[100]; snprintf(str, sizeof(str), "%s", var.value); pch = strtok(str, "x"); if (pch) width = strtoul(pch, NULL, 0); pch = strtok(NULL, "x"); if (pch) height = strtoul(pch, NULL, 0); MAX_WIDTH = width; MAX_HEIGHT = height; fprintf(stderr, "[openlara]: Got size: %u x %u.\n", width, height); } var.key = "openlara_framerate"; if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) { if (!strcmp(var.value, "30fps")) FRAMERATE = 30; else if (!strcmp(var.value, "60fps")) FRAMERATE = 60; else if (!strcmp(var.value, "70fps")) FRAMERATE = 70; else if (!strcmp(var.value, "72fps")) FRAMERATE = 72; else if (!strcmp(var.value, "75fps")) FRAMERATE = 75; else if (!strcmp(var.value, "90fps")) FRAMERATE = 90; else if (!strcmp(var.value, "100fps")) FRAMERATE = 100; else if (!strcmp(var.value, "119fps")) FRAMERATE = 119; else if (!strcmp(var.value, "120fps")) FRAMERATE = 120; else if (!strcmp(var.value, "144fps")) FRAMERATE = 144; else if (!strcmp(var.value, "240fps")) FRAMERATE = 240; else if (!strcmp(var.value, "244fps")) FRAMERATE = 244; else if (!strcmp(var.value, "300fps")) FRAMERATE = 300; else if (!strcmp(var.value, "360fps")) FRAMERATE = 360; } else FRAMERATE = 60; } } static vec2 DeadZone(const int x, const int y) { const float max = 0x8000; // abs( max value reported by libretro for analog sticks ) const float deadzone = 0.25f; // TODO: Depends on pad and personal taste. Should probably be a core option. float xa = (x / max); float ya = (y / max); vec2 input(xa,ya); if(input.length() < deadzone) { input.x = 0; input.y = 0; } return input; } void retro_run(void) { bool updated = false; if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) && updated) update_variables(false); input_poll_cb(); /* Player 1+2 */ for (size_t i = 0; i < 2; i++) { int16_t ret = 0; if (libretro_supports_bitmasks) ret = input_cb(i, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_MASK); else { unsigned j; for (j = 0; j < (RETRO_DEVICE_ID_JOYPAD_R2+1); j++) if (input_cb(i, RETRO_DEVICE_JOYPAD, 0, j)) ret |= (1 << j); } /* Analog */ int lsx = input_cb(i, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_X); int lsy = input_cb(i, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_Y); Input::setJoyPos(i, jkL, DeadZone(lsx, lsy)); /* Up */ if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_UP)) Input::setJoyDown(i, JoyKey::jkUp, true); else Input::setJoyDown(i, JoyKey::jkUp, false); /* Down */ if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_DOWN)) Input::setJoyDown(i, JoyKey::jkDown, true); else Input::setJoyDown(i, JoyKey::jkDown, false); /* Left */ if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_LEFT)) Input::setJoyDown(i, JoyKey::jkLeft, true); else Input::setJoyDown(i, JoyKey::jkLeft, false); /* Right */ if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_RIGHT)) Input::setJoyDown(i, JoyKey::jkRight, true); else Input::setJoyDown(i, JoyKey::jkRight, false); /* Inventory screen */ if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_SELECT)) Input::setJoyDown(i, JoyKey::jkSelect, true); else Input::setJoyDown(i, JoyKey::jkSelect, false); /* Start */ if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_START)) Input::setJoyDown(i, JoyKey::jkStart, true); else Input::setJoyDown(i, JoyKey::jkStart, false); /* Draw weapon */ if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_X)) Input::setJoyDown(i, JoyKey::jkY, true); else Input::setJoyDown(i, JoyKey::jkY, false); /* Grab/shoot - Action button */ if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_B)) Input::setJoyDown(i, JoyKey::jkA, true); else Input::setJoyDown(i, JoyKey::jkA, false); /* Roll */ if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_A)) Input::setJoyDown(i, JoyKey::jkB, true); else Input::setJoyDown(i, JoyKey::jkB, false); /* Jump */ if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_Y)) Input::setJoyDown(i, JoyKey::jkX, true); else Input::setJoyDown(i, JoyKey::jkX, false); /* Walk */ if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_R)) Input::setJoyDown(i, JoyKey::jkRB, true); else Input::setJoyDown(i, JoyKey::jkRB, false); /* Look */ if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_L)) Input::setJoyDown(i, JoyKey::jkLB, true); else Input::setJoyDown(i, JoyKey::jkLB, false); /* Duck/Crouch */ if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_L2)) Input::setJoyDown(i, JoyKey::jkLT, true); else Input::setJoyDown(i, JoyKey::jkLT, false); /* Dash */ if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_R2)) Input::setJoyDown(i, JoyKey::jkRT, true); else Input::setJoyDown(i, JoyKey::jkRT, false); } int audio_frames = SND_RATE / FRAMERATE; int16_t *samples = (int16_t*)sndData; Sound::fill(sndData, audio_frames); while (audio_frames > 512) { audio_batch_cb(samples, 512); samples += 1024; audio_frames -= 512; } audio_batch_cb(samples, audio_frames); Core::deltaTime = 1.0 / FRAMERATE; updated = Game::update(); if (updated) Game::render(); video_cb(RETRO_HW_FRAME_BUFFER_VALID, width, height, 0); } static void context_reset(void) { fprintf(stderr, "Context reset!\n"); rglgen_resolve_symbols(hw_render.get_proc_address); sndData = new Sound::Frame[SND_RATE / FRAMERATE]; Game::init(levelpath); } static void context_destroy(void) {} static bool retro_init_hw_context(unsigned preferred) { hw_render.context_type = (retro_hw_context_type)preferred; if (preferred == RETRO_HW_CONTEXT_OPENGL_CORE || preferred == RETRO_HW_CONTEXT_OPENGLES_VERSION) { hw_render.version_major = 3; hw_render.version_minor = 1; } else { hw_render.version_major = 0; hw_render.version_minor = 0; } hw_render.context_reset = context_reset; hw_render.context_destroy = context_destroy; hw_render.depth = true; hw_render.stencil = true; hw_render.bottom_left_origin = true; if (!environ_cb(RETRO_ENVIRONMENT_SET_HW_RENDER, &hw_render)) return false; return true; } bool retro_load_game(const struct retro_game_info *info) { struct retro_input_descriptor desc[] = { // Player 1 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "Left" }, { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "Up" }, { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "Down" }, { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "Right" }, { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Start" }, { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT, "Inventory" }, { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y, "Jump" }, { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X, "Draw weapon" }, { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "Action (Shoot/grab)" }, { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "Roll" }, { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L, "Look (when holding)" }, { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R, "Walk (when holding)" }, { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L2, "Duck/Crouch (TR3 and up)" }, { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R2, "Dash (TR3 and up)" }, // Player 2 { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "Left" }, { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "Up" }, { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "Down" }, { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "Right" }, { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Start" }, { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT, "Inventory" }, { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y, "Jump" }, { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X, "Draw weapon" }, { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "Action (Shoot/grab)" }, { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "Roll" }, { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L, "Look (when holding)" }, { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R, "Walk (when holding)" }, { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L2, "Duck/Crouch (TR3 and up)" }, { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R2, "Dash (TR3 and up)" }, { 0 }, }; environ_cb(RETRO_ENVIRONMENT_SET_HW_SHARED_CONTEXT, NULL); update_variables(true); environ_cb(RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS, desc); enum retro_pixel_format fmt = RETRO_PIXEL_FORMAT_XRGB8888; if (!environ_cb(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt)) { fprintf(stderr, "XRGB8888 is not supported.\n"); return false; } // get current video driver unsigned preferred; if (!environ_cb(RETRO_ENVIRONMENT_GET_PREFERRED_HW_RENDER, &preferred)) preferred = RETRO_HW_CONTEXT_DUMMY; bool found_gl_context = false; if (preferred == RETRO_HW_CONTEXT_OPENGL || preferred == RETRO_HW_CONTEXT_OPENGL_CORE || preferred == RETRO_HW_CONTEXT_OPENGLES_VERSION || preferred == RETRO_HW_CONTEXT_OPENGLES2 || preferred == RETRO_HW_CONTEXT_OPENGLES3) { // try requesting the right context for current driver found_gl_context = retro_init_hw_context(preferred); } else if (preferred == RETRO_HW_CONTEXT_VULKAN) { // if vulkan is the current driver, we probably prefer glcore over gl so that the same slang shaders can be used found_gl_context = retro_init_hw_context(RETRO_HW_CONTEXT_OPENGL_CORE); } else { // try every context as fallback if current driver wasn't found #ifdef HAVE_OPENGLES if (!found_gl_context) found_gl_context = retro_init_hw_context(RETRO_HW_CONTEXT_OPENGLES_VERSION); if (!found_gl_context) found_gl_context = retro_init_hw_context(RETRO_HW_CONTEXT_OPENGLES3); if (!found_gl_context) found_gl_context = retro_init_hw_context(RETRO_HW_CONTEXT_OPENGLES2); #else if (!found_gl_context) found_gl_context = retro_init_hw_context(RETRO_HW_CONTEXT_OPENGL_CORE); if (!found_gl_context) found_gl_context = retro_init_hw_context(RETRO_HW_CONTEXT_OPENGL); #endif } if (!found_gl_context) { fprintf(stderr, "HW Context could not be initialized, exiting...\n"); return false; } if (!path_is_absolute(info->path)) { fprintf(stderr, "Full path to content is required, exiting...\n"); return false; } char basedir[1024] = {0}; fill_pathname_basedir(basedir, info->path, sizeof(basedir)); // contentDir acts as the current working directory in OpenLara strcpy(contentDir, basedir); path_parent_dir(contentDir); fill_pathname_parent_dir_name(basedir, contentDir, sizeof(basedir)); if (strcmp(basedir, "level") == 0) { // level/X/ path_parent_dir(contentDir); } fprintf(stderr, "[openlara]: contentDir: %s\n", contentDir); // make levelpath contain a path relative to contentDir strcpy(levelpath, (info->path+strlen(contentDir))); Core::width = width; Core::height = height; fprintf(stderr, "Loaded game!\n"); return true; } void retro_unload_game(void) { delete[] sndData; Game::deinit(); } unsigned retro_get_region(void) { return RETRO_REGION_NTSC; } bool retro_load_game_special(unsigned type, const struct retro_game_info *info, size_t num) { (void)type; (void)info; (void)num; return false; } size_t retro_serialize_size(void) { return 0; } bool retro_serialize(void *data, size_t size) { (void)data; (void)size; return false; } bool retro_unserialize(const void *data, size_t size) { (void)data; (void)size; return false; } void *retro_get_memory_data(unsigned id) { (void)id; return NULL; } size_t retro_get_memory_size(unsigned id) { (void)id; return 0; } void retro_reset(void) {} void retro_cheat_reset(void) {} void retro_cheat_set(unsigned index, bool enabled, const char *code) { (void)index; (void)enabled; (void)code; } void osToggleVR(bool enable) { }
20,437
8,444
#include <iostream> #include <gpds/container.hpp> #include <gpds/archiver_xml.hpp> #include "cppproperties/properties.hpp" #include "cppproperties/archiver_gpds.hpp" struct shape : tct::properties::properties { MAKE_PROPERTY(locked, bool); MAKE_PROPERTY(x, int); MAKE_PROPERTY(y, int); MAKE_PROPERTY(name, std::string); }; int main() { shape s; s.locked = false; s.x = 24; s.y = 48; s.name = "My Shape"; s.set_attribute("foobar", "zbar"); s.name.set_attribute("name-attr", "test1234"); tct::properties::archiver_gpds ar; const gpds::container& c = ar.save(s); std::stringstream ss; gpds::archiver_xml gpds_ar; gpds_ar.save(ss, c, "properties"); gpds::container gpds_c; gpds_ar.load(ss, gpds_c, "properties"); shape s2; ar.load(s2, gpds_c); std::cout << s2.locked << "\n"; std::cout << s2.x << "\n"; std::cout << s2.y << "\n"; std::cout << s2.name << "\n"; return 0; }
981
418
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: int getLen(ListNode* head){ int len = 0; while(head != NULL){ len++; head = head->next; } return len; } ListNode* removeNthFromEnd(ListNode* head, int n) { if(head == NULL) return head; int len = getLen(head); n = len - n + 1; int cur_node_id = 0; ListNode* head_keep; head_keep = head; if(n == 1){ head = head->next; return head; } while(head_keep != NULL){ cur_node_id++; if(cur_node_id + 1 == n){ head_keep->next = head_keep->next->next; break; } head_keep = head_keep->next; } return head; } };
965
307
/************************************************************************************ Filename : OculusWorldDemo.cpp Content : First-person view test application for Oculus Rift Created : October 4, 2012 Authors : Michael Antonov, Andrew Reisse, Steve LaValle Peter Hoff, Dan Goodman, Bryan Croteau Copyright : Copyright 2012 Oculus VR, Inc. 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 "OVR.h" #include "../CommonSrc/Platform/Platform_Default.h" #include "../CommonSrc/Render/Render_Device.h" #include "../CommonSrc/Render/Render_XmlSceneLoader.h" #include "../CommonSrc/Render/Render_FontEmbed_DejaVu48.h" #include "../CommonSrc/Platform/Gamepad.h" #include <Kernel/OVR_SysFile.h> #include <Kernel/OVR_Log.h> #include <Kernel/OVR_Timer.h> #include "Player.h" // Filename to be loaded by default, searching specified paths. #define WORLDDEMO_ASSET_FILE "Tuscany.xml" #define WORLDDEMO_ASSET_PATH1 "Assets/Tuscany/" #define WORLDDEMO_ASSET_PATH2 "../Assets/Tuscany/" // This path allows the shortcut to work. #define WORLDDEMO_ASSET_PATH3 "Samples/OculusWorldDemo/Assets/Tuscany/" using namespace OVR; using namespace OVR::Platform; using namespace OVR::Render; //------------------------------------------------------------------------------------- // ***** OculusWorldDemo Description // This app renders a simple flat-shaded room allowing the user to move along the // floor and look around with an HMD, mouse and keyboard. The following keys work: // // 'W', 'S', 'A', 'D' and Arrow Keys - Move forward, back; strafe left/right. // F1 - No stereo, no distortion. // F2 - Stereo, no distortion. // F3 - Stereo and distortion. // F4 - Toggle MSAA. // F9 - Cycle through fullscreen and windowed modes. Necessary for previewing content with Rift. // // Important Oculus-specific logic can be found at following locations: // // OculusWorldDemoApp::OnStartup - This function will initialize OVR::DeviceManager and HMD, // creating SensorDevice and attaching it to SensorFusion. // This needs to be done before obtaining sensor data. // // OculusWorldDemoApp::OnIdle - Here we poll SensorFusion for orientation, apply it // to the scene and handle movement. // Stereo rendering is also done here, by delegating to // to Render function for each eye. // //------------------------------------------------------------------------------------- // ***** OculusWorldDemo Application class // An instance of this class is created on application startup (main/WinMain). // It then works as follows: // - Graphics and HMD setup is done OculusWorldDemoApp::OnStartup(). This function // also creates the room model from Slab declarations. // - Per-frame processing is done in OnIdle(). This function processes // sensor and movement input and then renders the frame. // - Additional input processing is done in OnMouse, OnKey. class OculusWorldDemoApp : public Application, public MessageHandler { public: OculusWorldDemoApp(); ~OculusWorldDemoApp(); virtual int OnStartup(int argc, const char** argv); virtual void OnIdle(); virtual void OnMouseMove(int x, int y, int modifiers); virtual void OnKey(OVR::KeyCode key, int chr, bool down, int modifiers); virtual void OnResize(int width, int height); virtual void OnMessage(const Message& msg); void Render(const StereoEyeParams& stereo); // Sets temporarily displayed message for adjustments void SetAdjustMessage(const char* format, ...); // Overrides current timeout, in seconds (not the future default value); // intended to be called right after SetAdjustMessage. void SetAdjustMessageTimeout(float timeout); // Stereo setting adjustment functions. // Called with deltaTime when relevant key is held. void AdjustFov(float dt); void AdjustAspect(float dt); void AdjustIPD(float dt); void AdjustEyeHeight(float dt); void AdjustMotionPrediction(float dt); void AdjustDistortion(float dt, int kIndex, const char* label); void AdjustDistortionK0(float dt) { AdjustDistortion(dt, 0, "K0"); } void AdjustDistortionK1(float dt) { AdjustDistortion(dt, 1, "K1"); } void AdjustDistortionK2(float dt) { AdjustDistortion(dt, 2, "K2"); } void AdjustDistortionK3(float dt) { AdjustDistortion(dt, 3, "K3"); } // Adds room model to scene. void PopulateScene(const char* fileName); void PopulatePreloadScene(); void ClearScene(); // Magnetometer calibration procedure void UpdateManualMagCalibration(); protected: RenderDevice* pRender; RendererParams RenderParams; int Width, Height; int Screen; int FirstScreenInCycle; // Magnetometer calibration and yaw correction Util::MagCalibration MagCal; bool MagAwaitingForwardLook; // *** Oculus HMD Variables Ptr<DeviceManager> pManager; Ptr<SensorDevice> pSensor; Ptr<HMDDevice> pHMD; Ptr<Profile> pUserProfile; SensorFusion SFusion; HMDInfo TheHMDInfo; Ptr<LatencyTestDevice> pLatencyTester; Util::LatencyTest LatencyUtil; double LastUpdate; int FPS; int FrameCounter; double NextFPSUpdate; Array<Ptr<CollisionModel> > CollisionModels; Array<Ptr<CollisionModel> > GroundCollisionModels; // Loading process displays screenshot in first frame // and then proceeds to load until finished. enum LoadingStateType { LoadingState_Frame0, LoadingState_DoLoad, LoadingState_Finished }; // Player Player ThePlayer; Matrix4f View; Scene MainScene; Scene LoadingScene; Scene GridScene; Scene YawMarkGreenScene; Scene YawMarkRedScene; Scene YawLinesScene; LoadingStateType LoadingState; Ptr<ShaderFill> LitSolid, LitTextures[4]; // Stereo view parameters. StereoConfig SConfig; PostProcessType PostProcess; // LOD String MainFilePath; Array<String> LODFilePaths; int ConsecutiveLowFPSFrames; int CurrentLODFileIndex; float DistortionK0; float DistortionK1; float DistortionK2; float DistortionK3; String AdjustMessage; double AdjustMessageTimeout; // Saved distortion state. float SavedK0, SavedK1, SavedK2, SavedK3; float SavedESD, SavedAspect, SavedEyeDistance; // Allows toggling color around distortion. Color DistortionClearColor; // Stereo settings adjustment state. typedef void (OculusWorldDemoApp::*AdjustFuncType)(float); bool ShiftDown; AdjustFuncType pAdjustFunc; float AdjustDirection; enum SceneRenderMode { Scene_World, Scene_Grid, Scene_Both, Scene_YawView }; SceneRenderMode SceneMode; enum TextScreen { Text_None, Text_Orientation, Text_Config, Text_Help, Text_Count }; TextScreen TextScreen; struct DeviceStatusNotificationDesc { DeviceHandle Handle; MessageType Action; DeviceStatusNotificationDesc():Action(Message_None) {} DeviceStatusNotificationDesc(MessageType mt, const DeviceHandle& dev) : Handle(dev), Action(mt) {} }; Array<DeviceStatusNotificationDesc> DeviceStatusNotificationsQueue; Model* CreateModel(Vector3f pos, struct SlabModel* sm); Model* CreateBoundingModel(CollisionModel &cm); void PopulateLODFileNames(); void DropLOD(); void RaiseLOD(); void CycleDisplay(); void GamepadStateChanged(const GamepadState& pad); // Variable used by UpdateManualCalibration Anglef FirstMagYaw; int ManualMagCalStage; int ManualMagFailures; }; //------------------------------------------------------------------------------------- OculusWorldDemoApp::OculusWorldDemoApp() : pRender(0), LastUpdate(0), LoadingState(LoadingState_Frame0), // Initial location SConfig(), PostProcess(PostProcess_Distortion), DistortionClearColor(0, 0, 0), ShiftDown(false), pAdjustFunc(0), AdjustDirection(1.0f), SceneMode(Scene_World), TextScreen(Text_None) { Width = 1280; Height = 800; Screen = 0; FirstScreenInCycle = 0; FPS = 0; FrameCounter = 0; NextFPSUpdate = 0; ConsecutiveLowFPSFrames = 0; CurrentLODFileIndex = 0; AdjustMessageTimeout = 0; } OculusWorldDemoApp::~OculusWorldDemoApp() { RemoveHandlerFromDevices(); if(DejaVu.fill) { DejaVu.fill->Release(); } pLatencyTester.Clear(); pSensor.Clear(); pHMD.Clear(); CollisionModels.ClearAndRelease(); GroundCollisionModels.ClearAndRelease(); } int OculusWorldDemoApp::OnStartup(int argc, const char** argv) { // *** Oculus HMD & Sensor Initialization // Create DeviceManager and first available HMDDevice from it. // Sensor object is created from the HMD, to ensure that it is on the // correct device. pManager = *DeviceManager::Create(); // We'll handle it's messages in this case. pManager->SetMessageHandler(this); pHMD = *pManager->EnumerateDevices<HMDDevice>().CreateDevice(); if (pHMD) { pSensor = *pHMD->GetSensor(); // This will initialize HMDInfo with information about configured IPD, // screen size and other variables needed for correct projection. // We pass HMD DisplayDeviceName into the renderer to select the // correct monitor in full-screen mode. if(pHMD->GetDeviceInfo(&TheHMDInfo)) { //RenderParams.MonitorName = hmd.DisplayDeviceName; SConfig.SetHMDInfo(TheHMDInfo); } // Retrieve relevant profile settings. pUserProfile = pHMD->GetProfile(); if (pUserProfile) { ThePlayer.EyeHeight = pUserProfile->GetEyeHeight(); ThePlayer.EyePos.y = ThePlayer.EyeHeight; } } else { // If we didn't detect an HMD, try to create the sensor directly. // This is useful for debugging sensor interaction; it is not needed in // a shipping app. pSensor = *pManager->EnumerateDevices<SensorDevice>().CreateDevice(); } // Create the Latency Tester device and assign it to the LatencyTesterUtil object. pLatencyTester = *pManager->EnumerateDevices<LatencyTestDevice>().CreateDevice(); if (pLatencyTester) { LatencyUtil.SetDevice(pLatencyTester); } // Make the user aware which devices are present. if(pHMD == NULL && pSensor == NULL) { SetAdjustMessage("---------------------------------\nNO HMD DETECTED\nNO SENSOR DETECTED\n---------------------------------"); } else if(pHMD == NULL) { SetAdjustMessage("----------------------------\nNO HMD DETECTED\n----------------------------"); } else if(pSensor == NULL) { SetAdjustMessage("---------------------------------\nNO SENSOR DETECTED\n---------------------------------"); } else { SetAdjustMessage("--------------------------------------------\n" "Press F9 for Full-Screen on Rift\n" "--------------------------------------------"); } // First message should be extra-long. SetAdjustMessageTimeout(10.0f); if(TheHMDInfo.HResolution > 0) { Width = TheHMDInfo.HResolution; Height = TheHMDInfo.VResolution; } if(!pPlatform->SetupWindow(Width, Height)) { return 1; } String Title = "Oculus World Demo"; if(TheHMDInfo.ProductName[0]) { Title += " : "; Title += TheHMDInfo.ProductName; } pPlatform->SetWindowTitle(Title); // Report relative mouse motion in OnMouseMove pPlatform->SetMouseMode(Mouse_Relative); if(pSensor) { // We need to attach sensor to SensorFusion object for it to receive // body frame messages and update orientation. SFusion.GetOrientation() // is used in OnIdle() to orient the view. SFusion.AttachToSensor(pSensor); SFusion.SetDelegateMessageHandler(this); SFusion.SetPredictionEnabled(true); } // *** Initialize Rendering const char* graphics = "d3d11"; // Select renderer based on command line arguments. for(int i = 1; i < argc; i++) { if(!strcmp(argv[i], "-r") && i < argc - 1) { graphics = argv[i + 1]; } else if(!strcmp(argv[i], "-fs")) { RenderParams.Fullscreen = true; } } // Enable multi-sampling by default. RenderParams.Multisample = 4; pRender = pPlatform->SetupGraphics(OVR_DEFAULT_RENDER_DEVICE_SET, graphics, RenderParams); // *** Configure Stereo settings. SConfig.SetFullViewport(Viewport(0, 0, Width, Height)); SConfig.SetStereoMode(Stereo_LeftRight_Multipass); // Configure proper Distortion Fit. // For 7" screen, fit to touch left side of the view, leaving a bit of // invisible screen on the top (saves on rendering cost). // For smaller screens (5.5"), fit to the top. if (TheHMDInfo.HScreenSize > 0.0f) { if (TheHMDInfo.HScreenSize > 0.140f) // 7" SConfig.SetDistortionFitPointVP(-1.0f, 0.0f); else SConfig.SetDistortionFitPointVP(0.0f, 1.0f); } pRender->SetSceneRenderScale(SConfig.GetDistortionScale()); //pRender->SetSceneRenderScale(1.0f); SConfig.Set2DAreaFov(DegreeToRad(85.0f)); // *** Identify Scene File & Prepare for Loading // This creates lights and models. if (argc == 2) { MainFilePath = argv[1]; PopulateLODFileNames(); } else { fprintf(stderr, "Usage: OculusWorldDemo [input XML]\n"); MainFilePath = WORLDDEMO_ASSET_FILE; } // Try to modify path for correctness in case specified file is not found. if (!SysFile(MainFilePath).IsValid()) { String prefixPath1(pPlatform->GetContentDirectory() + "/" + WORLDDEMO_ASSET_PATH1), prefixPath2(WORLDDEMO_ASSET_PATH2), prefixPath3(WORLDDEMO_ASSET_PATH3); if (SysFile(prefixPath1 + MainFilePath).IsValid()) MainFilePath = prefixPath1 + MainFilePath; else if (SysFile(prefixPath2 + MainFilePath).IsValid()) MainFilePath = prefixPath2 + MainFilePath; else if (SysFile(prefixPath3 + MainFilePath).IsValid()) MainFilePath = prefixPath3 + MainFilePath; } PopulatePreloadScene(); LastUpdate = pPlatform->GetAppTime(); //pPlatform->PlayMusicFile(L"Loop.wav"); return 0; } void OculusWorldDemoApp::OnMessage(const Message& msg) { if (msg.Type == Message_DeviceAdded || msg.Type == Message_DeviceRemoved) { if (msg.pDevice == pManager) { const MessageDeviceStatus& statusMsg = static_cast<const MessageDeviceStatus&>(msg); { // limit the scope of the lock Lock::Locker lock(pManager->GetHandlerLock()); DeviceStatusNotificationsQueue.PushBack( DeviceStatusNotificationDesc(statusMsg.Type, statusMsg.Handle)); } switch (statusMsg.Type) { case OVR::Message_DeviceAdded: LogText("DeviceManager reported device added.\n"); break; case OVR::Message_DeviceRemoved: LogText("DeviceManager reported device removed.\n"); break; default: OVR_ASSERT(0); // unexpected type } } } } void OculusWorldDemoApp::OnResize(int width, int height) { Width = width; Height = height; SConfig.SetFullViewport(Viewport(0, 0, Width, Height)); } void OculusWorldDemoApp::OnMouseMove(int x, int y, int modifiers) { if(modifiers & Mod_MouseRelative) { // Get Delta int dx = x, dy = y; const float maxPitch = ((3.1415f / 2) * 0.98f); // Apply to rotation. Subtract for right body frame rotation, // since yaw rotation is positive CCW when looking down on XZ plane. ThePlayer.EyeYaw -= (Sensitivity * dx) / 360.0f; if(!pSensor) { ThePlayer.EyePitch -= (Sensitivity * dy) / 360.0f; if(ThePlayer.EyePitch > maxPitch) { ThePlayer.EyePitch = maxPitch; } if(ThePlayer.EyePitch < -maxPitch) { ThePlayer.EyePitch = -maxPitch; } } } } void OculusWorldDemoApp::OnKey(OVR::KeyCode key, int chr, bool down, int modifiers) { OVR_UNUSED(chr); switch(key) { case Key_Q: if (down && (modifiers & Mod_Control)) { pPlatform->Exit(0); } break; // Handle player movement keys. // We just update movement state here, while the actual translation is done in OnIdle() // based on time. case Key_W: ThePlayer.MoveForward = down ? (ThePlayer.MoveForward | 1) : (ThePlayer.MoveForward & ~1); break; case Key_S: ThePlayer.MoveBack = down ? (ThePlayer.MoveBack | 1) : (ThePlayer.MoveBack & ~1); break; case Key_A: ThePlayer.MoveLeft = down ? (ThePlayer.MoveLeft | 1) : (ThePlayer.MoveLeft & ~1); break; case Key_D: ThePlayer.MoveRight = down ? (ThePlayer.MoveRight | 1) : (ThePlayer.MoveRight & ~1); break; case Key_Up: ThePlayer.MoveForward = down ? (ThePlayer.MoveForward | 2) : (ThePlayer.MoveForward & ~2); break; case Key_Down: ThePlayer.MoveBack = down ? (ThePlayer.MoveBack | 2) : (ThePlayer.MoveBack & ~2); break; case Key_Left: ThePlayer.MoveLeft = down ? (ThePlayer.MoveLeft | 2) : (ThePlayer.MoveLeft & ~2); break; case Key_Right: ThePlayer.MoveRight = down ? (ThePlayer.MoveRight | 2) : (ThePlayer.MoveRight & ~2); break; case Key_Minus: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustEyeHeight : 0; AdjustDirection = -1; break; case Key_Equal: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustEyeHeight : 0; AdjustDirection = 1; break; case Key_B: if (down) { if(SConfig.GetDistortionScale() == 1.0f) { if(SConfig.GetHMDInfo().HScreenSize > 0.140f) // 7" { SConfig.SetDistortionFitPointVP(-1.0f, 0.0f); } else { SConfig.SetDistortionFitPointVP(0.0f, 1.0f); } } else { // No fitting; scale == 1.0. SConfig.SetDistortionFitPointVP(0, 0); } } break; // Support toggling background color for distortion so that we can see // the effect on the periphery. case Key_V: if (down) { if(DistortionClearColor.B == 0) { DistortionClearColor = Color(0, 128, 255); } else { DistortionClearColor = Color(0, 0, 0); } pRender->SetDistortionClearColor(DistortionClearColor); } break; case Key_F1: SConfig.SetStereoMode(Stereo_None); PostProcess = PostProcess_None; SetAdjustMessage("StereoMode: None"); break; case Key_F2: SConfig.SetStereoMode(Stereo_LeftRight_Multipass); PostProcess = PostProcess_None; SetAdjustMessage("StereoMode: Stereo + No Distortion"); break; case Key_F3: SConfig.SetStereoMode(Stereo_LeftRight_Multipass); PostProcess = PostProcess_Distortion; SetAdjustMessage("StereoMode: Stereo + Distortion"); break; case Key_R: SFusion.Reset(); if (MagCal.IsAutoCalibrating() || MagCal.IsManuallyCalibrating()) MagCal.AbortCalibration(); SetAdjustMessage("Sensor Fusion Reset"); break; case Key_Space: if (!down) { TextScreen = (enum TextScreen)((TextScreen + 1) % Text_Count); } break; case Key_F4: if (!down) { RenderParams = pRender->GetParams(); RenderParams.Multisample = RenderParams.Multisample > 1 ? 1 : 4; pRender->SetParams(RenderParams); if(RenderParams.Multisample > 1) { SetAdjustMessage("Multisampling On"); } else { SetAdjustMessage("Multisampling Off"); } } break; case Key_F9: #ifndef OVR_OS_LINUX // On Linux F9 does the same as F11. if (!down) { CycleDisplay(); } break; #endif #ifdef OVR_OS_MAC case Key_F10: // F11 is reserved on Mac #else case Key_F11: #endif if (!down) { RenderParams = pRender->GetParams(); RenderParams.Display = DisplayId(SConfig.GetHMDInfo().DisplayDeviceName,SConfig.GetHMDInfo().DisplayId); pRender->SetParams(RenderParams); pPlatform->SetMouseMode(Mouse_Normal); pPlatform->SetFullscreen(RenderParams, pRender->IsFullscreen() ? Display_Window : Display_FakeFullscreen); pPlatform->SetMouseMode(Mouse_Relative); // Avoid mode world rotation jump. // If using an HMD, enable post-process (for distortion) and stereo. if(RenderParams.IsDisplaySet() && pRender->IsFullscreen()) { SConfig.SetStereoMode(Stereo_LeftRight_Multipass); PostProcess = PostProcess_Distortion; } } break; case Key_Escape: if(!down) { if (MagCal.IsAutoCalibrating() || MagCal.IsManuallyCalibrating()) { MagCal.AbortCalibration(); SetAdjustMessage("Aborting Magnetometer Calibration"); } else { // switch to primary screen windowed mode pPlatform->SetFullscreen(RenderParams, Display_Window); RenderParams.Display = pPlatform->GetDisplay(0); pRender->SetParams(RenderParams); Screen = 0; } } break; // Stereo adjustments. case Key_BracketLeft: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustFov : 0; AdjustDirection = 1; break; case Key_BracketRight: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustFov : 0; AdjustDirection = -1; break; case Key_Insert: case Key_Num0: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustIPD : 0; AdjustDirection = 1; break; case Key_Delete: case Key_Num9: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustIPD : 0; AdjustDirection = -1; break; case Key_PageUp: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustAspect : 0; AdjustDirection = 1; break; case Key_PageDown: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustAspect : 0; AdjustDirection = -1; break; // Distortion correction adjustments case Key_H: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK0 : NULL; AdjustDirection = -1; break; case Key_Y: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK0 : NULL; AdjustDirection = 1; break; case Key_J: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK1 : NULL; AdjustDirection = -1; break; case Key_U: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK1 : NULL; AdjustDirection = 1; break; case Key_K: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK2 : NULL; AdjustDirection = -1; break; case Key_I: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK2 : NULL; AdjustDirection = 1; break; case Key_L: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK3 : NULL; AdjustDirection = -1; break; case Key_O: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK3 : NULL; AdjustDirection = 1; break; case Key_Tab: if (down) { float t0 = SConfig.GetDistortionK(0), t1 = SConfig.GetDistortionK(1), t2 = SConfig.GetDistortionK(2), t3 = SConfig.GetDistortionK(3); float tESD = SConfig.GetEyeToScreenDistance(), taspect = SConfig.GetAspectMultiplier(), tipd = SConfig.GetIPD(); if(SavedK0 > 0.0f) { SConfig.SetDistortionK(0, SavedK0); SConfig.SetDistortionK(1, SavedK1); SConfig.SetDistortionK(2, SavedK2); SConfig.SetDistortionK(3, SavedK3); SConfig.SetEyeToScreenDistance(SavedESD); SConfig.SetAspectMultiplier(SavedAspect); SConfig.SetIPD(SavedEyeDistance); if ( ShiftDown ) { // Swap saved and current values. Good for doing direct comparisons. SetAdjustMessage("Swapped current and saved. New settings:\n" "ESD:\t120 %.3f\t350 Eye:\t490 %.3f\n" "K0: \t120 %.4f\t350 K2: \t490 %.4f\n" "K1: \t120 %.4f\t350 K3: \t490 %.4f\n", SavedESD, SavedEyeDistance, SavedK0, SavedK2, SavedK1, SavedK3); SavedK0 = t0; SavedK1 = t1; SavedK2 = t2; SavedK3 = t3; SavedESD = tESD; SavedAspect = taspect; SavedEyeDistance = tipd; } else { SetAdjustMessage("Restored:\n" "ESD:\t120 %.3f\t350 Eye:\t490 %.3f\n" "K0: \t120 %.4f\t350 K2: \t490 %.4f\n" "K1: \t120 %.4f\t350 K3: \t490 %.4f\n", SavedESD, SavedEyeDistance, SavedK0, SavedK2, SavedK1, SavedK3); } } else { SetAdjustMessage("Setting Saved"); SavedK0 = t0; SavedK1 = t1; SavedK2 = t2; SavedK3 = t3; SavedESD = tESD; SavedAspect = taspect; SavedEyeDistance = tipd; } } break; case Key_G: if (down) { if(SceneMode == Scene_World) { SceneMode = Scene_Grid; SetAdjustMessage("Grid Only"); } else if(SceneMode == Scene_Grid) { SceneMode = Scene_Both; SetAdjustMessage("Grid Overlay"); } else if(SceneMode == Scene_Both) { SceneMode = Scene_World; SetAdjustMessage("Grid Off"); } } break; // Holding down Shift key accelerates adjustment velocity. case Key_Shift: ShiftDown = down; break; // Reset the camera position in case we get stuck case Key_T: ThePlayer.EyePos = Vector3f(10.0f, 1.6f, 10.0f); break; case Key_F5: if (!down) { UPInt numNodes = MainScene.Models.GetSize(); for(UPInt i = 0; i < numNodes; i++) { Ptr<OVR::Render::Model> nodePtr = MainScene.Models[i]; Render::Model* pNode = nodePtr.GetPtr(); if(pNode->IsCollisionModel) { pNode->Visible = !pNode->Visible; } } } break; case Key_N: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustMotionPrediction : NULL; AdjustDirection = -1; break; case Key_M: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustMotionPrediction : NULL; AdjustDirection = 1; break; /* case Key_N: RaiseLOD(); break; case Key_M: DropLOD(); break; */ // Start calibrating magnetometer case Key_Z: if (down) { ManualMagCalStage = 0; if (MagCal.IsManuallyCalibrating()) MagAwaitingForwardLook = false; else { MagCal.BeginManualCalibration(SFusion); MagAwaitingForwardLook = true; } } break; case Key_X: if (down) { MagCal.BeginAutoCalibration(SFusion); SetAdjustMessage("Starting Auto Mag Calibration"); } break; // Show view of yaw angles (for mag calibration/analysis) case Key_F6: if (down) { if (SceneMode != Scene_YawView) { SceneMode = Scene_YawView; SetAdjustMessage("Magnetometer Yaw Angle Marks"); } else { SceneMode = Scene_World; SetAdjustMessage("Magnetometer Marks Off"); } } break; case Key_C: if (down) { // Toggle chromatic aberration correction on/off. RenderDevice::PostProcessShader shader = pRender->GetPostProcessShader(); if (shader == RenderDevice::PostProcessShader_Distortion) { pRender->SetPostProcessShader(RenderDevice::PostProcessShader_DistortionAndChromAb); SetAdjustMessage("Chromatic Aberration Correction On"); } else if (shader == RenderDevice::PostProcessShader_DistortionAndChromAb) { pRender->SetPostProcessShader(RenderDevice::PostProcessShader_Distortion); SetAdjustMessage("Chromatic Aberration Correction Off"); } else OVR_ASSERT(false); } break; case Key_P: if (down) { // Toggle motion prediction. if (SFusion.IsPredictionEnabled()) { SFusion.SetPredictionEnabled(false); SetAdjustMessage("Motion Prediction Off"); } else { SFusion.SetPredictionEnabled(true); SetAdjustMessage("Motion Prediction On"); } } break; default: break; } } void OculusWorldDemoApp::OnIdle() { double curtime = pPlatform->GetAppTime(); float dt = float(curtime - LastUpdate); LastUpdate = curtime; // Update gamepad. GamepadState gamepadState; if (GetPlatformCore()->GetGamepadManager()->GetGamepadState(0, &gamepadState)) { GamepadStateChanged(gamepadState); } if (LoadingState == LoadingState_DoLoad) { PopulateScene(MainFilePath.ToCStr()); LoadingState = LoadingState_Finished; return; } // Check if any new devices were connected. { bool queueIsEmpty = false; while (!queueIsEmpty) { DeviceStatusNotificationDesc desc; { Lock::Locker lock(pManager->GetHandlerLock()); if (DeviceStatusNotificationsQueue.GetSize() == 0) break; desc = DeviceStatusNotificationsQueue.Front(); // We can't call Clear under the lock since this may introduce a dead lock: // this thread is locked by HandlerLock and the Clear might cause // call of Device->Release, which will use Manager->DeviceLock. The bkg // thread is most likely locked by opposite way: // Manager->DeviceLock ==> HandlerLock, therefore - a dead lock. // So, just grab the first element, save a copy of it and remove // the element (Device->Release won't be called since we made a copy). DeviceStatusNotificationsQueue.RemoveAt(0); queueIsEmpty = (DeviceStatusNotificationsQueue.GetSize() == 0); } bool wasAlreadyCreated = desc.Handle.IsCreated(); if (desc.Action == Message_DeviceAdded) { switch(desc.Handle.GetType()) { case Device_Sensor: if (desc.Handle.IsAvailable() && !desc.Handle.IsCreated()) { if (!pSensor) { pSensor = *desc.Handle.CreateDeviceTyped<SensorDevice>(); SFusion.AttachToSensor(pSensor); SetAdjustMessage("---------------------------\n" "SENSOR connected\n" "---------------------------"); } else if (!wasAlreadyCreated) { LogText("A new SENSOR has been detected, but it is not currently used."); } } break; case Device_LatencyTester: if (desc.Handle.IsAvailable() && !desc.Handle.IsCreated()) { if (!pLatencyTester) { pLatencyTester = *desc.Handle.CreateDeviceTyped<LatencyTestDevice>(); LatencyUtil.SetDevice(pLatencyTester); if (!wasAlreadyCreated) SetAdjustMessage("----------------------------------------\n" "LATENCY TESTER connected\n" "----------------------------------------"); } } break; case Device_HMD: { OVR::HMDInfo info; desc.Handle.GetDeviceInfo(&info); // if strlen(info.DisplayDeviceName) == 0 then // this HMD is 'fake' (created using sensor). if (strlen(info.DisplayDeviceName) > 0 && (!pHMD || !info.IsSameDisplay(TheHMDInfo))) { SetAdjustMessage("------------------------\n" "HMD connected\n" "------------------------"); if (!pHMD || !desc.Handle.IsDevice(pHMD)) pHMD = *desc.Handle.CreateDeviceTyped<HMDDevice>(); // update stereo config with new HMDInfo if (pHMD && pHMD->GetDeviceInfo(&TheHMDInfo)) { //RenderParams.MonitorName = hmd.DisplayDeviceName; SConfig.SetHMDInfo(TheHMDInfo); } LogText("HMD device added.\n"); } break; } default:; } } else if (desc.Action == Message_DeviceRemoved) { if (desc.Handle.IsDevice(pSensor)) { LogText("Sensor reported device removed.\n"); SFusion.AttachToSensor(NULL); pSensor.Clear(); SetAdjustMessage("-------------------------------\n" "SENSOR disconnected.\n" "-------------------------------"); } else if (desc.Handle.IsDevice(pLatencyTester)) { LogText("Latency Tester reported device removed.\n"); LatencyUtil.SetDevice(NULL); pLatencyTester.Clear(); SetAdjustMessage("---------------------------------------------\n" "LATENCY SENSOR disconnected.\n" "---------------------------------------------"); } else if (desc.Handle.IsDevice(pHMD)) { if (pHMD && !pHMD->IsDisconnected()) { SetAdjustMessage("---------------------------\n" "HMD disconnected\n" "---------------------------"); // Disconnect HMD. pSensor is used to restore 'fake' HMD device // (can be NULL). pHMD = pHMD->Disconnect(pSensor); // This will initialize TheHMDInfo with information about configured IPD, // screen size and other variables needed for correct projection. // We pass HMD DisplayDeviceName into the renderer to select the // correct monitor in full-screen mode. if (pHMD && pHMD->GetDeviceInfo(&TheHMDInfo)) { //RenderParams.MonitorName = hmd.DisplayDeviceName; SConfig.SetHMDInfo(TheHMDInfo); } LogText("HMD device removed.\n"); } } } else OVR_ASSERT(0); // unexpected action } } // If one of Stereo setting adjustment keys is pressed, adjust related state. if (pAdjustFunc) { (this->*pAdjustFunc)(dt * AdjustDirection * (ShiftDown ? 5.0f : 1.0f)); } // Process latency tester results. const char* results = LatencyUtil.GetResultsString(); if (results != NULL) { LogText("LATENCY TESTER: %s\n", results); } // Have to place this as close as possible to where the HMD orientation is read. LatencyUtil.ProcessInputs(); // Magnetometer calibration procedure if (MagCal.IsManuallyCalibrating()) UpdateManualMagCalibration(); if (MagCal.IsAutoCalibrating()) { MagCal.UpdateAutoCalibration(SFusion); int n = MagCal.NumberOfSamples(); if (n == 1) SetAdjustMessage(" Magnetometer Calibration Has 1 Sample \n %d Remaining - Please Keep Looking Around ",4-n); else if (n < 4) SetAdjustMessage(" Magnetometer Calibration Has %d Samples \n %d Remaining - Please Keep Looking Around ",n,4-n); if (MagCal.IsCalibrated()) { SFusion.SetYawCorrectionEnabled(true); Vector3f mc = MagCal.GetMagCenter(); SetAdjustMessage(" Magnetometer Calibration Complete \nCenter: %f %f %f",mc.x,mc.y,mc.z); } } // Handle Sensor motion. // We extract Yaw, Pitch, Roll instead of directly using the orientation // to allow "additional" yaw manipulation with mouse/controller. if(pSensor) { Quatf hmdOrient = SFusion.GetPredictedOrientation(); float yaw = 0.0f; hmdOrient.GetEulerAngles<Axis_Y, Axis_X, Axis_Z>(&yaw, &ThePlayer.EyePitch, &ThePlayer.EyeRoll); ThePlayer.EyeYaw += (yaw - ThePlayer.LastSensorYaw); ThePlayer.LastSensorYaw = yaw; // NOTE: We can get a matrix from orientation as follows: // Matrix4f hmdMat(hmdOrient); // Test logic - assign quaternion result directly to view: // Quatf hmdOrient = SFusion.GetOrientation(); // View = Matrix4f(hmdOrient.Inverted()) * Matrix4f::Translation(-EyePos); } if(curtime >= NextFPSUpdate) { NextFPSUpdate = curtime + 1.0; FPS = FrameCounter; FrameCounter = 0; } FrameCounter++; if(FPS < 40) { ConsecutiveLowFPSFrames++; } else { ConsecutiveLowFPSFrames = 0; } if(ConsecutiveLowFPSFrames > 200) { DropLOD(); ConsecutiveLowFPSFrames = 0; } ThePlayer.EyeYaw -= ThePlayer.GamepadRotate.x * dt; ThePlayer.HandleCollision(dt, &CollisionModels, &GroundCollisionModels, ShiftDown); if(!pSensor) { ThePlayer.EyePitch -= ThePlayer.GamepadRotate.y * dt; const float maxPitch = ((3.1415f / 2) * 0.98f); if(ThePlayer.EyePitch > maxPitch) { ThePlayer.EyePitch = maxPitch; } if(ThePlayer.EyePitch < -maxPitch) { ThePlayer.EyePitch = -maxPitch; } } // Rotate and position View Camera, using YawPitchRoll in BodyFrame coordinates. // Matrix4f rollPitchYaw = Matrix4f::RotationY(ThePlayer.EyeYaw) * Matrix4f::RotationX(ThePlayer.EyePitch) * Matrix4f::RotationZ(ThePlayer.EyeRoll); Vector3f up = rollPitchYaw.Transform(UpVector); Vector3f forward = rollPitchYaw.Transform(ForwardVector); // Minimal head modeling; should be moved as an option to SensorFusion. float headBaseToEyeHeight = 0.15f; // Vertical height of eye from base of head float headBaseToEyeProtrusion = 0.09f; // Distance forward of eye from base of head Vector3f eyeCenterInHeadFrame(0.0f, headBaseToEyeHeight, -headBaseToEyeProtrusion); Vector3f shiftedEyePos = ThePlayer.EyePos + rollPitchYaw.Transform(eyeCenterInHeadFrame); shiftedEyePos.y -= eyeCenterInHeadFrame.y; // Bring the head back down to original height View = Matrix4f::LookAtRH(shiftedEyePos, shiftedEyePos + forward, up); // Transformation without head modeling. // View = Matrix4f::LookAtRH(EyePos, EyePos + forward, up); // This is an alternative to LookAtRH: // Here we transpose the rotation matrix to get its inverse. // View = (Matrix4f::RotationY(EyeYaw) * Matrix4f::RotationX(EyePitch) * // Matrix4f::RotationZ(EyeRoll)).Transposed() * // Matrix4f::Translation(-EyePos); switch(SConfig.GetStereoMode()) { case Stereo_None: Render(SConfig.GetEyeRenderParams(StereoEye_Center)); break; case Stereo_LeftRight_Multipass: //case Stereo_LeftDouble_Multipass: Render(SConfig.GetEyeRenderParams(StereoEye_Left)); Render(SConfig.GetEyeRenderParams(StereoEye_Right)); break; } pRender->Present(); // Force GPU to flush the scene, resulting in the lowest possible latency. pRender->ForceFlushGPU(); } void OculusWorldDemoApp::UpdateManualMagCalibration() { float tyaw, pitch, roll; Anglef yaw; Quatf hmdOrient = SFusion.GetOrientation(); hmdOrient.GetEulerAngles<Axis_Y, Axis_X, Axis_Z>(&tyaw, &pitch, &roll); Vector3f mag = SFusion.GetMagnetometer(); float dtr = Math<float>::DegreeToRadFactor; yaw.Set(tyaw); // Using Angle class to handle angle wraparound arithmetic const int timeout = 100; switch(ManualMagCalStage) { case 0: if (MagAwaitingForwardLook) SetAdjustMessage("Magnetometer Calibration\n** Step 1: Please Look Forward **\n** and Press Z When Ready **"); else if (fabs(pitch) < 10.0f*dtr) { MagCal.InsertIfAcceptable(hmdOrient, mag); FirstMagYaw = yaw; MagAwaitingForwardLook = false; if (MagCal.NumberOfSamples() == 1) { ManualMagCalStage = 1; ManualMagFailures = 0; } } else MagAwaitingForwardLook = true; break; case 1: SetAdjustMessage("Magnetometer Calibration\n** Step 2: Please Look Up **"); yaw -= FirstMagYaw; if ((pitch > 50.0f*dtr) && (yaw.Abs() < 20.0f*dtr)) { MagCal.InsertIfAcceptable(hmdOrient, mag); ManualMagFailures++; if ((MagCal.NumberOfSamples() == 2)||(ManualMagFailures > timeout)) { ManualMagCalStage = 2; ManualMagFailures = 0; } } break; case 2: SetAdjustMessage("Magnetometer Calibration\n** Step 3: Please Look Left **"); yaw -= FirstMagYaw; if (yaw.Get() > 60.0f*dtr) { MagCal.InsertIfAcceptable(hmdOrient, mag); ManualMagFailures++; if ((MagCal.NumberOfSamples() == 3)||(ManualMagFailures > timeout)) { ManualMagCalStage = 3; ManualMagFailures = 0; } } break; case 3: SetAdjustMessage("Magnetometer Calibration\n** Step 4: Please Look Right **"); yaw -= FirstMagYaw; if (yaw.Get() < -60.0f*dtr) { MagCal.InsertIfAcceptable(hmdOrient, mag); ManualMagFailures++; if (MagCal.NumberOfSamples() == 4) ManualMagCalStage = 6; else { if (ManualMagFailures > timeout) { ManualMagCalStage = 4; ManualMagFailures = 0; } } } break; case 4: SetAdjustMessage("Magnetometer Calibration\n** Step 5: Please Look Upper Right **"); yaw -= FirstMagYaw; if ((yaw.Get() < -50.0f*dtr) && (pitch > 40.0f*dtr)) { MagCal.InsertIfAcceptable(hmdOrient, mag); if (MagCal.NumberOfSamples() == 4) ManualMagCalStage = 6; else { if (ManualMagFailures > timeout) { ManualMagCalStage = 5; ManualMagFailures = 0; } else ManualMagFailures++; } } break; case 5: SetAdjustMessage("Calibration Failed\n** Try Again From Another Location **"); MagCal.AbortCalibration(); break; case 6: if (!MagCal.IsCalibrated()) { MagCal.SetCalibration(SFusion); SFusion.SetYawCorrectionEnabled(true); Vector3f mc = MagCal.GetMagCenter(); SetAdjustMessage(" Magnetometer Calibration and Activation \nCenter: %f %f %f", mc.x,mc.y,mc.z); } } } static const char* HelpText = "F1 \t100 NoStereo \t420 Z \t520 Manual Mag Calib\n" "F2 \t100 Stereo \t420 X \t520 Auto Mag Calib\n" "F3 \t100 StereoHMD \t420 ; \t520 Mag Set Ref Point\n" "F4 \t100 MSAA \t420 F6 \t520 Mag Info\n" "F9 \t100 FullScreen \t420 R \t520 Reset SensorFusion\n" "F11 \t100 Fast FullScreen \t500 - + \t660 Adj EyeHeight\n" "C \t100 Chromatic Ab \t500 [ ] \t660 Adj FOV\n" "P \t100 Motion Pred \t500 Shift \t660 Adj Faster\n" "N/M \t180 Adj Motion Pred\n" "( / ) \t180 Adj EyeDistance" ; enum DrawTextCenterType { DrawText_NoCenter= 0, DrawText_VCenter = 0x1, DrawText_HCenter = 0x2, DrawText_Center = DrawText_VCenter | DrawText_HCenter }; static void DrawTextBox(RenderDevice* prender, float x, float y, float textSize, const char* text, DrawTextCenterType centerType = DrawText_NoCenter) { float ssize[2] = {0.0f, 0.0f}; prender->MeasureText(&DejaVu, text, textSize, ssize); // Treat 0 a VCenter. if (centerType & DrawText_HCenter) { x = -ssize[0]/2; } if (centerType & DrawText_VCenter) { y = -ssize[1]/2; } prender->FillRect(x-0.02f, y-0.02f, x+ssize[0]+0.02f, y+ssize[1]+0.02f, Color(40,40,100,210)); prender->RenderText(&DejaVu, text, x, y, textSize, Color(255,255,0,210)); } void OculusWorldDemoApp::Render(const StereoEyeParams& stereo) { pRender->BeginScene(PostProcess); // *** 3D - Configures Viewport/Projection and Render pRender->ApplyStereoParams(stereo); pRender->Clear(); pRender->SetDepthMode(true, true); if (SceneMode != Scene_Grid) { MainScene.Render(pRender, stereo.ViewAdjust * View); } if (SceneMode == Scene_YawView) { Matrix4f calView = Matrix4f(); float viewYaw = -ThePlayer.LastSensorYaw + SFusion.GetMagRefYaw(); calView.M[0][0] = calView.M[2][2] = cos(viewYaw); calView.M[0][2] = sin(viewYaw); calView.M[2][0] = -sin(viewYaw); //LogText("yaw: %f\n",SFusion.GetMagRefYaw()); if (SFusion.IsYawCorrectionInProgress()) YawMarkGreenScene.Render(pRender, stereo.ViewAdjust); else YawMarkRedScene.Render(pRender, stereo.ViewAdjust); if (fabs(ThePlayer.EyePitch) < Math<float>::Pi * 0.33) YawLinesScene.Render(pRender, stereo.ViewAdjust * calView); } // *** 2D Text & Grid - Configure Orthographic rendering. // Render UI in 2D orthographic coordinate system that maps [-1,1] range // to a readable FOV area centered at your eye and properly adjusted. pRender->ApplyStereoParams2D(stereo); pRender->SetDepthMode(false, false); float unitPixel = SConfig.Get2DUnitPixel(); float textHeight= unitPixel * 22; if ((SceneMode == Scene_Grid)||(SceneMode == Scene_Both)) { // Draw grid two pixels thick. GridScene.Render(pRender, Matrix4f()); GridScene.Render(pRender, Matrix4f::Translation(unitPixel,unitPixel,0)); } // Display Loading screen-shot in frame 0. if (LoadingState != LoadingState_Finished) { LoadingScene.Render(pRender, Matrix4f()); String loadMessage = String("Loading ") + MainFilePath; DrawTextBox(pRender, 0.0f, 0.25f, textHeight, loadMessage.ToCStr(), DrawText_HCenter); LoadingState = LoadingState_DoLoad; } if(!AdjustMessage.IsEmpty() && AdjustMessageTimeout > pPlatform->GetAppTime()) { DrawTextBox(pRender,0.0f,0.4f, textHeight, AdjustMessage.ToCStr(), DrawText_HCenter); } switch(TextScreen) { case Text_Orientation: { char buf[256], gpustat[256]; OVR_sprintf(buf, sizeof(buf), " Yaw:%4.0f Pitch:%4.0f Roll:%4.0f \n" " FPS: %d Frame: %d \n Pos: %3.2f, %3.2f, %3.2f \n" " EyeHeight: %3.2f", RadToDegree(ThePlayer.EyeYaw), RadToDegree(ThePlayer.EyePitch), RadToDegree(ThePlayer.EyeRoll), FPS, FrameCounter, ThePlayer.EyePos.x, ThePlayer.EyePos.y, ThePlayer.EyePos.z, ThePlayer.EyePos.y); size_t texMemInMB = pRender->GetTotalTextureMemoryUsage() / 1058576; if (texMemInMB) { OVR_sprintf(gpustat, sizeof(gpustat), "\n GPU Tex: %u MB", texMemInMB); OVR_strcat(buf, sizeof(buf), gpustat); } DrawTextBox(pRender, 0.0f, -0.15f, textHeight, buf, DrawText_HCenter); } break; case Text_Config: { char textBuff[2048]; OVR_sprintf(textBuff, sizeof(textBuff), "Fov\t300 %9.4f\n" "EyeDistance\t300 %9.4f\n" "DistortionK0\t300 %9.4f\n" "DistortionK1\t300 %9.4f\n" "DistortionK2\t300 %9.4f\n" "DistortionK3\t300 %9.4f\n" "TexScale\t300 %9.4f", SConfig.GetYFOVDegrees(), SConfig.GetIPD(), SConfig.GetDistortionK(0), SConfig.GetDistortionK(1), SConfig.GetDistortionK(2), SConfig.GetDistortionK(3), SConfig.GetDistortionScale()); DrawTextBox(pRender, 0.0f, 0.0f, textHeight, textBuff, DrawText_Center); } break; case Text_Help: DrawTextBox(pRender, 0.0f, -0.1f, textHeight, HelpText, DrawText_Center); default: break; } // Display colored quad if we're doing a latency test. Color colorToDisplay; if (LatencyUtil.DisplayScreenColor(colorToDisplay)) { pRender->FillRect(-0.4f, -0.4f, 0.4f, 0.4f, colorToDisplay); } pRender->FinishScene(); } // Sets temporarily displayed message for adjustments void OculusWorldDemoApp::SetAdjustMessage(const char* format, ...) { Lock::Locker lock(pManager->GetHandlerLock()); char textBuff[2048]; va_list argList; va_start(argList, format); OVR_vsprintf(textBuff, sizeof(textBuff), format, argList); va_end(argList); // Message will time out in 4 seconds. AdjustMessage = textBuff; AdjustMessageTimeout = pPlatform->GetAppTime() + 4.0f; } void OculusWorldDemoApp::SetAdjustMessageTimeout(float timeout) { AdjustMessageTimeout = pPlatform->GetAppTime() + timeout; } // ***** View Control Adjustments void OculusWorldDemoApp::AdjustFov(float dt) { float esd = SConfig.GetEyeToScreenDistance() + 0.01f * dt; SConfig.SetEyeToScreenDistance(esd); SetAdjustMessage("ESD:%6.3f FOV: %6.3f", esd, SConfig.GetYFOVDegrees()); } void OculusWorldDemoApp::AdjustAspect(float dt) { float rawAspect = SConfig.GetAspect() / SConfig.GetAspectMultiplier(); float newAspect = SConfig.GetAspect() + 0.01f * dt; SConfig.SetAspectMultiplier(newAspect / rawAspect); SetAdjustMessage("Aspect: %6.3f", newAspect); } void OculusWorldDemoApp::AdjustDistortion(float dt, int kIndex, const char* label) { SConfig.SetDistortionK(kIndex, SConfig.GetDistortionK(kIndex) + 0.03f * dt); SetAdjustMessage("%s: %6.4f", label, SConfig.GetDistortionK(kIndex)); } void OculusWorldDemoApp::AdjustIPD(float dt) { SConfig.SetIPD(SConfig.GetIPD() + 0.025f * dt); SetAdjustMessage("EyeDistance: %6.4f", SConfig.GetIPD()); } void OculusWorldDemoApp::AdjustEyeHeight(float dt) { float dist = 0.5f * dt; ThePlayer.EyeHeight += dist; ThePlayer.EyePos.y += dist; SetAdjustMessage("EyeHeight: %4.2f", ThePlayer.EyeHeight); } void OculusWorldDemoApp::AdjustMotionPrediction(float dt) { float motionPred = SFusion.GetPredictionDelta() + 0.01f * dt; if (motionPred < 0.0f) { motionPred = 0.0f; } SFusion.SetPrediction(motionPred); SetAdjustMessage("MotionPrediction: %6.3fs", motionPred); } // Loads the scene data void OculusWorldDemoApp::PopulateScene(const char *fileName) { XmlHandler xmlHandler; if(!xmlHandler.ReadFile(fileName, pRender, &MainScene, &CollisionModels, &GroundCollisionModels)) { SetAdjustMessage("---------------------------------\nFILE LOAD FAILED\n---------------------------------"); SetAdjustMessageTimeout(10.0f); } MainScene.SetAmbient(Vector4f(1.0f, 1.0f, 1.0f, 1.0f)); // Distortion debug grid (brought up by 'G' key). Ptr<Model> gridModel = *Model::CreateGrid(Vector3f(0,0,0), Vector3f(1.0f/10, 0,0), Vector3f(0,1.0f/10,0), 10, 10, 5, Color(0, 255, 0, 255), Color(255, 50, 50, 255) ); GridScene.World.Add(gridModel); // Yaw angle marker and lines (brought up by ';' key). float shifty = -0.5f; Ptr<Model> yawMarkGreenModel = *Model::CreateBox(Color(0, 255, 0, 255), Vector3f(0.0f, shifty, -2.0f), Vector3f(0.05f, 0.05f, 0.05f)); YawMarkGreenScene.World.Add(yawMarkGreenModel); Ptr<Model> yawMarkRedModel = *Model::CreateBox(Color(255, 0, 0, 255), Vector3f(0.0f, shifty, -2.0f), Vector3f(0.05f, 0.05f, 0.05f)); YawMarkRedScene.World.Add(yawMarkRedModel); Ptr<Model> yawLinesModel = *new Model(Prim_Lines); float r = 2.0f; float theta0 = Math<float>::PiOver2; float theta1 = 0.0f; Color c = Color(255, 200, 200, 255); for (int i = 0; i < 35; i++) { theta1 = theta0 + Math<float>::Pi / 18.0f; yawLinesModel->AddLine(yawLinesModel->AddVertex(Vector3f(r*cos(theta0),shifty,-r*sin(theta0)),c), yawLinesModel->AddVertex(Vector3f(r*cos(theta1),shifty,-r*sin(theta1)),c)); theta0 = theta1; yawLinesModel->AddLine(yawLinesModel->AddVertex(Vector3f(r*cos(theta0),shifty,-r*sin(theta0)),c), yawLinesModel->AddVertex(Vector3f(r*cos(theta0),shifty+0.1f,-r*sin(theta0)),c)); theta0 = theta1; } theta1 = theta0 + Math<float>::Pi / 18.0f; yawLinesModel->AddLine(yawLinesModel->AddVertex(Vector3f(r*cos(theta0),shifty,-r*sin(theta0)),c), yawLinesModel->AddVertex(Vector3f(r*cos(theta1),shifty,-r*sin(theta1)),c)); yawLinesModel->AddLine(yawLinesModel->AddVertex(Vector3f(0.0f,shifty+0.1f,-r),c), yawLinesModel->AddVertex(Vector3f(r*sin(0.02f),shifty,-r*cos(0.02f)),c)); yawLinesModel->AddLine(yawLinesModel->AddVertex(Vector3f(0.0f,shifty+0.1f,-r),c), yawLinesModel->AddVertex(Vector3f(r*sin(-0.02f),shifty,-r*cos(-0.02f)),c)); yawLinesModel->SetPosition(Vector3f(0.0f,0.0f,0.0f)); YawLinesScene.World.Add(yawLinesModel); } void OculusWorldDemoApp::PopulatePreloadScene() { // Load-screen screen shot image String fileName = MainFilePath; fileName.StripExtension(); Ptr<File> imageFile = *new SysFile(fileName + "_LoadScreen.tga"); Ptr<Texture> imageTex; if (imageFile->IsValid()) imageTex = *LoadTextureTga(pRender, imageFile); // Image is rendered as a single quad. if (imageTex) { imageTex->SetSampleMode(Sample_Anisotropic|Sample_Repeat); Ptr<Model> m = *new Model(Prim_Triangles); m->AddVertex(-0.5f, 0.5f, 0.0f, Color(255,255,255,255), 0.0f, 0.0f); m->AddVertex( 0.5f, 0.5f, 0.0f, Color(255,255,255,255), 1.0f, 0.0f); m->AddVertex( 0.5f, -0.5f, 0.0f, Color(255,255,255,255), 1.0f, 1.0f); m->AddVertex(-0.5f, -0.5f, 0.0f, Color(255,255,255,255), 0.0f, 1.0f); m->AddTriangle(2,1,0); m->AddTriangle(0,3,2); Ptr<ShaderFill> fill = *new ShaderFill(*pRender->CreateShaderSet()); fill->GetShaders()->SetShader(pRender->LoadBuiltinShader(Shader_Vertex, VShader_MVP)); fill->GetShaders()->SetShader(pRender->LoadBuiltinShader(Shader_Fragment, FShader_Texture)); fill->SetTexture(0, imageTex); m->Fill = fill; LoadingScene.World.Add(m); } } void OculusWorldDemoApp::ClearScene() { MainScene.Clear(); GridScene.Clear(); YawMarkGreenScene.Clear(); YawMarkRedScene.Clear(); YawLinesScene.Clear(); } void OculusWorldDemoApp::PopulateLODFileNames() { //OVR::String mainFilePath = MainFilePath; LODFilePaths.PushBack(MainFilePath); int LODIndex = 1; SPInt pos = strcspn(MainFilePath.ToCStr(), "."); SPInt len = strlen(MainFilePath.ToCStr()); SPInt diff = len - pos; if (diff == 0) return; while(true) { char pathWithoutExt[250]; char buffer[250]; for(SPInt i = 0; i < pos; ++i) { pathWithoutExt[i] = MainFilePath[(int)i]; } pathWithoutExt[pos] = '\0'; OVR_sprintf(buffer, sizeof(buffer), "%s%i.xml", pathWithoutExt, LODIndex); FILE* fp = 0; #if defined(_MSC_VER) && (_MSC_VER >= 1400 ) errno_t err = fopen_s(&fp, buffer, "rb"); if(!fp || err) { #else fp = fopen(buffer, "rb"); if(!fp) { #endif break; } fclose(fp); OVR::String result = buffer; LODFilePaths.PushBack(result); LODIndex++; } } void OculusWorldDemoApp::DropLOD() { if(CurrentLODFileIndex < (int)(LODFilePaths.GetSize() - 1)) { ClearScene(); CurrentLODFileIndex++; PopulateScene(LODFilePaths[CurrentLODFileIndex].ToCStr()); } } void OculusWorldDemoApp::RaiseLOD() { if(CurrentLODFileIndex > 0) { ClearScene(); CurrentLODFileIndex--; PopulateScene(LODFilePaths[CurrentLODFileIndex].ToCStr()); } } //----------------------------------------------------------------------------- void OculusWorldDemoApp::CycleDisplay() { int screenCount = pPlatform->GetDisplayCount(); // If Windowed, switch to the HMD screen first in Full-Screen Mode. // If already Full-Screen, cycle to next screen until we reach FirstScreenInCycle. if (pRender->IsFullscreen()) { // Right now, we always need to restore window before going to next screen. pPlatform->SetFullscreen(RenderParams, Display_Window); Screen++; if (Screen == screenCount) Screen = 0; RenderParams.Display = pPlatform->GetDisplay(Screen); if (Screen != FirstScreenInCycle) { pRender->SetParams(RenderParams); pPlatform->SetFullscreen(RenderParams, Display_Fullscreen); } } else { // Try to find HMD Screen, making it the first screen in full-screen Cycle. FirstScreenInCycle = 0; if (pHMD) { DisplayId HMD (SConfig.GetHMDInfo().DisplayDeviceName, SConfig.GetHMDInfo().DisplayId); for (int i = 0; i< screenCount; i++) { if (pPlatform->GetDisplay(i) == HMD) { FirstScreenInCycle = i; break; } } } // Switch full-screen on the HMD. Screen = FirstScreenInCycle; RenderParams.Display = pPlatform->GetDisplay(Screen); pRender->SetParams(RenderParams); pPlatform->SetFullscreen(RenderParams, Display_Fullscreen); } } void OculusWorldDemoApp::GamepadStateChanged(const GamepadState& pad) { ThePlayer.GamepadMove = Vector3f(pad.LX * pad.LX * (pad.LX > 0 ? 1 : -1), 0, pad.LY * pad.LY * (pad.LY > 0 ? -1 : 1)); ThePlayer.GamepadRotate = Vector3f(2 * pad.RX, -2 * pad.RY, 0); } //------------------------------------------------------------------------------------- OVR_PLATFORM_APP(OculusWorldDemoApp);
63,382
20,881
#include "backbuffer_resolver.hpp" #include "../d3d11_helpers.hpp" #include <DirectXTex.h> namespace sp::core::postprocessing { Backbuffer_resolver::Backbuffer_resolver(Com_ptr<ID3D11Device5> device, shader::Database& shaders) : _resolve_vs{std::get<0>( shaders.vertex("late_backbuffer_resolve"sv).entrypoint("main_vs"sv))}, _resolve_ps{shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_ps"sv)}, _resolve_ps_x2{ shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_x2_ps"sv)}, _resolve_ps_x4{ shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_x4_ps"sv)}, _resolve_ps_x8{ shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_x8_ps"sv)}, _resolve_ps_linear{ shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_linear_ps"sv)}, _resolve_ps_linear_x2{ shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_linear_x2_ps"sv)}, _resolve_ps_linear_x4{ shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_linear_x4_ps"sv)}, _resolve_ps_linear_x8{ shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_linear_x8_ps"sv)}, _resolve_cb{ create_dynamic_constant_buffer(*device, sizeof(std::array<std::uint32_t, 4>))} { } void Backbuffer_resolver::apply(ID3D11DeviceContext1& dc, const Input input, const Flags flags, Swapchain& swapchain, const Interfaces interfaces) noexcept { if (DirectX::MakeTypeless(input.format) == DirectX::MakeTypeless(Swapchain::format)) { apply_matching_format(dc, input, flags, swapchain, interfaces); } else { apply_mismatch_format(dc, input, flags, swapchain, interfaces); } } void Backbuffer_resolver::apply_matching_format(ID3D11DeviceContext1& dc, const Input& input, const Flags flags, Swapchain& swapchain, const Interfaces& interfaces) noexcept { const bool msaa_input = input.sample_count > 1; const bool want_post_aa = flags.use_cmma2; // Fast Path for MSAA only. if (msaa_input && !want_post_aa) { dc.ResolveSubresource(swapchain.texture(), 0, &input.texture, 0, input.format); return; } if (flags.use_cmma2) { interfaces.cmaa2.apply(dc, interfaces.profiler, {.input = input.srv, .output = *input.uav, .width = input.width, .height = input.height}); } dc.CopyResource(swapchain.texture(), &input.texture); } void Backbuffer_resolver::apply_mismatch_format(ID3D11DeviceContext1& dc, const Input& input, const Flags flags, Swapchain& swapchain, const Interfaces& interfaces) noexcept { [[maybe_unused]] const bool msaa_input = input.sample_count > 1; const bool want_post_aa = flags.use_cmma2; // Fast Path for no post AA. if (!want_post_aa) { resolve_input(dc, input, flags, interfaces, *swapchain.rtv()); return; } if (flags.use_cmma2) { auto cmma_target = interfaces.rt_allocator.allocate( {.format = DXGI_FORMAT_R8G8B8A8_TYPELESS, .width = input.width, .height = input.height, .bind_flags = effects::rendertarget_bind_srv_rtv_uav, .srv_format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, .rtv_format = DXGI_FORMAT_R8G8B8A8_UNORM, .uav_format = DXGI_FORMAT_R8G8B8A8_UNORM}); resolve_input(dc, input, flags, interfaces, *cmma_target.rtv()); interfaces.cmaa2.apply(dc, interfaces.profiler, {.input = *cmma_target.srv(), .output = *cmma_target.uav(), .width = input.width, .height = input.height}); dc.CopyResource(swapchain.texture(), &cmma_target.texture()); return; } log_and_terminate("Failed to resolve backbuffer! This should never happen."); } void Backbuffer_resolver::resolve_input(ID3D11DeviceContext1& dc, const Input& input, const Flags flags, const Interfaces& interfaces, ID3D11RenderTargetView& target) noexcept { effects::Profile profile{interfaces.profiler, dc, "Backbuffer Resolve"}; dc.ClearState(); dc.IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); dc.VSSetShader(_resolve_vs.get(), nullptr, 0); const D3D11_VIEWPORT viewport{.TopLeftX = 0.0f, .TopLeftY = 0.0f, .Width = static_cast<float>(input.width), .Height = static_cast<float>(input.height), .MinDepth = 0.0f, .MaxDepth = 1.0f}; dc.RSSetViewports(1, &viewport); auto* const rtv = &target; dc.OMSetRenderTargets(1, &rtv, nullptr); const std::array srvs{&input.srv, get_blue_noise_texture(interfaces)}; dc.PSSetShaderResources(0, srvs.size(), srvs.data()); const std::array<std::uint32_t, 4> randomness{_resolve_rand_dist(_resolve_xorshift), _resolve_rand_dist(_resolve_xorshift)}; update_dynamic_buffer(dc, *_resolve_cb, randomness); auto* const cb = _resolve_cb.get(); dc.PSSetConstantBuffers(0, 1, &cb); dc.PSSetShader(get_resolve_pixel_shader(input, flags), nullptr, 0); dc.Draw(3, 0); } auto Backbuffer_resolver::get_blue_noise_texture(const Interfaces& interfaces) noexcept -> ID3D11ShaderResourceView* { if (_blue_noise_srvs[0] == nullptr) { for (int i = 0; i < 64; ++i) { _blue_noise_srvs[i] = interfaces.resources.at_if( "_SP_BUILTIN_blue_noise_rgb_"s + std::to_string(i)); } } return _blue_noise_srvs[_resolve_rand_dist(_resolve_xorshift)].get(); } auto Backbuffer_resolver::get_resolve_pixel_shader(const Input& input, const Flags flags) noexcept -> ID3D11PixelShader* { if (flags.linear_input) { switch (input.sample_count) { case 1: return _resolve_ps_linear.get(); case 2: return _resolve_ps_linear_x2.get(); case 4: return _resolve_ps_linear_x4.get(); case 8: return _resolve_ps_linear_x8.get(); } } switch (input.sample_count) { case 1: return _resolve_ps.get(); case 2: return _resolve_ps_x2.get(); case 4: return _resolve_ps_x4.get(); case 8: return _resolve_ps_x8.get(); default: log_and_terminate("Unsupported sample count!"); } } }
7,011
2,358
/* ----------------------------------------------------------------------------- * This file is a part of the NVCM project: https://github.com/nvitya/nvcm * Copyright (c) 2018 Viktor Nagy, nvitya * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from * the use of this software. Permission is granted to anyone to use this * software for any purpose, including commercial applications, and to alter * it and redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software in * a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * --------------------------------------------------------------------------- */ /* * file: hwi2cslave_stm32_v1.cpp * brief: STM32 I2C / TWI Slave for F1, F4 * version: 1.00 * date: 2020-03-06 * authors: nvitya */ #include "platform.h" #include "hwpins.h" #include "hwi2cslave.h" #include "stm32_utils.h" #include "traces.h" #if I2C_HW_VER == 1 // v1 (STM32F1xx, STM32F4xx): different register names and defines bool THwI2cSlave_stm32::InitHw(int adevnum) { unsigned tmp; uint8_t busid = STM32_BUSID_APB1; initialized = false; devnum = adevnum; regs = nullptr; if (false) { } #ifdef I2C1 else if (1 == devnum) { regs = I2C1; RCC->APB1ENR |= RCC_APB1ENR_I2C1EN; } #endif #ifdef I2C2 else if (2 == devnum) { regs = I2C2; RCC->APB1ENR |= RCC_APB1ENR_I2C2EN; } #endif #ifdef I2C3 else if (3 == devnum) { regs = I2C3; RCC->APB1ENR |= RCC_APB1ENR_I2C3EN; } #endif if (!regs) { return false; } // disable for setup regs->CR1 &= ~I2C_CR1_PE; regs->CR1 |= I2C_CR1_SWRST; regs->CR1 &= ~I2C_CR1_SWRST; unsigned cr1 = 0; // use the default settings, keep disabled regs->CR1 = cr1; // setup address // this device does not support address mask regs->OAR1 = ((address & 0x7F) << 1); unsigned periphclock = stm32_bus_speed(busid); // CR2 tmp = 0 | (0 << 12) // LAST: 1 = Last transfer on DMA EOT | (0 << 11) // DMAEN: 1 = enable DMA | (1 << 10) // ITBUFEN: 1 = enable data interrupt | (1 << 9) // ITEVTEN: 1 = enable event interrupt | (1 << 8) // ITERREN: 1 = enable error interrupt | ((periphclock / 1000000) << 0) // set clock speed in MHz ; regs->CR2 = tmp; cr1 |= 0 | I2C_CR1_ACK // ACKnowledge must be enabled, otherwise even the own address won't be handled | I2C_CR1_PE // Enable ; regs->CR1 = cr1; initialized = true; return true; } // runstate: // 0: idle // 1: receive data // 5: transmit data void THwI2cSlave_stm32::HandleIrq() { uint32_t sr1 = regs->SR1; uint32_t sr2 = regs->SR2; // warning, the sequence above clears some of the status bits //TRACE("[I2C IRQ %04X %04X]\r\n", sr1, sr2); // check errors if (sr1 & 0xFF00) { if (sr1 & I2C_SR1_AF) // ACK Failure ? { // this is normal regs->SR1 = ~I2C_SR1_AF; // clear AF error } else { //TRACE("I2C errors: %04X\r\n", sr1); regs->SR1 = ~(sr1 & 0xFF00); // clear errors } } // check events if (sr1 & I2C_SR1_ADDR) // address matched, after start / restart { if (sr2 & I2C_SR2_TRA) { istx = true; runstate = 5; // go to transfer data } else { istx = false; runstate = 1; // go to receive data } OnAddressRw(address); // there is no other info on this chip, use own address } if (sr1 & I2C_SR1_RXNE) { uint8_t d = regs->DR; if (1 == runstate) { OnByteReceived(d); } else { // unexpected byte } } if (sr1 & I2C_SR1_TXE) { if (5 == runstate) { uint8_t d = OnTransmitRequest(); regs->DR = d; } else { // force stop, releases the data lines regs->CR1 |= I2C_CR1_STOP; // this must be done here for the proper STOP } } // check stop if (sr1 & I2C_SR1_STOPF) { //TRACE(" STOP DETECTED.\r\n"); // the CR1 must be written in order to clear this flag runstate = 0; uint32_t cr1 = regs->CR1; cr1 &= ~I2C_CR1_STOP; regs->CR1 = cr1; } if (sr2) // to keep sr2 if unused { } } #endif
4,465
1,979
#include "gtest/gtest.h" #include "enumeration_types/enum_defined_by_constant/Colors.h" #include "enumeration_types/enum_defined_by_constant/WHITE_COLOR.h" namespace enumeration_types { namespace enum_defined_by_constant { class EnumDefinedByConstant : public ::testing::Test { }; TEST_F(EnumDefinedByConstant, lightColor) { ASSERT_EQ(1, WHITE_COLOR); ASSERT_EQ(WHITE_COLOR, zserio::enumToValue(Colors::WHITE)); ASSERT_EQ(zserio::enumToValue(Colors::WHITE) + 1, zserio::enumToValue(Colors::BLACK)); } } // namespace enum_defined_by_constant } // namespace enumeration_types
591
227
/*========================================================================= * * Copyright UMC Utrecht and contributors * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkGPUTranslationTransformBase_hxx #define __itkGPUTranslationTransformBase_hxx #include "itkGPUTranslationTransformBase.h" #include <iomanip> // begin of ITKGPUTranslationTransformBase namespace namespace ITKGPUTranslationTransformBase { typedef struct { cl_float offset; } GPUTranslationTransformBase1D; typedef struct { cl_float2 offset; } GPUTranslationTransformBase2D; typedef struct { cl_float3 offset; } GPUTranslationTransformBase3D; //------------------------------------------------------------------------------ template< unsigned int ImageDimension > struct SpaceDimensionToType {}; //---------------------------------------------------------------------------- // Offset template< typename TScalarType, unsigned int SpaceDimension > void SetOffset1( const itk::Vector< TScalarType, SpaceDimension > &, cl_float &, SpaceDimensionToType< SpaceDimension > ) {} template< typename TScalarType, unsigned int SpaceDimension > void SetOffset2( const itk::Vector< TScalarType, SpaceDimension > &, cl_float2 &, SpaceDimensionToType< SpaceDimension > ) {} template< typename TScalarType, unsigned int SpaceDimension > void SetOffset3( const itk::Vector< TScalarType, SpaceDimension > &, cl_float4 &, SpaceDimensionToType< SpaceDimension > ) {} template< typename TScalarType > void SetOffset1( const itk::Vector< TScalarType, 1 > & offset, cl_float & ocloffset, SpaceDimensionToType< 1 > ) { ocloffset = offset[ 0 ]; } template< typename TScalarType > void SetOffset2( const itk::Vector< TScalarType, 2 > & offset, cl_float2 & ocloffset, SpaceDimensionToType< 2 > ) { unsigned int id = 0; for( unsigned int i = 0; i < 2; i++ ) { ocloffset.s[ id++ ] = offset[ i ]; } } template< typename TScalarType > void SetOffset3( const itk::Vector< TScalarType, 3 > & offset, cl_float4 & ocloffset, SpaceDimensionToType< 3 > ) { unsigned int id = 0; for( unsigned int i = 0; i < 3; i++ ) { ocloffset.s[ id++ ] = offset[ i ]; } ocloffset.s[ 3 ] = 0.0; } } // end of ITKGPUTranslationTransformBase namespace //------------------------------------------------------------------------------ namespace itk { template< typename TScalarType, unsigned int NDimensions > GPUTranslationTransformBase< TScalarType, NDimensions > ::GPUTranslationTransformBase() { // Add GPUTranslationTransformBase source const std::string sourcePath( GPUTranslationTransformBaseKernel::GetOpenCLSource() ); m_Sources.push_back( sourcePath ); this->m_ParametersDataManager->Initialize(); this->m_ParametersDataManager->SetBufferFlag( CL_MEM_READ_ONLY ); using namespace ITKGPUTranslationTransformBase; const unsigned int Dimension = SpaceDimension; switch( Dimension ) { case 1: this->m_ParametersDataManager->SetBufferSize( sizeof( GPUTranslationTransformBase1D ) ); break; case 2: this->m_ParametersDataManager->SetBufferSize( sizeof( GPUTranslationTransformBase2D ) ); break; case 3: this->m_ParametersDataManager->SetBufferSize( sizeof( GPUTranslationTransformBase3D ) ); break; default: break; } this->m_ParametersDataManager->Allocate(); } // end Constructor //------------------------------------------------------------------------------ template< typename TScalarType, unsigned int NDimensions > GPUDataManager::Pointer GPUTranslationTransformBase< TScalarType, NDimensions > ::GetParametersDataManager( void ) const { using namespace ITKGPUTranslationTransformBase; const SpaceDimensionToType< SpaceDimension > dim = {}; const unsigned int Dimension = SpaceDimension; switch( Dimension ) { case 1: { GPUTranslationTransformBase1D translationBase; SetOffset1< ScalarType >( GetCPUOffset(), translationBase.offset, dim ); this->m_ParametersDataManager->SetCPUBufferPointer( &translationBase ); } break; case 2: { GPUTranslationTransformBase2D translationBase; SetOffset2< ScalarType >( GetCPUOffset(), translationBase.offset, dim ); this->m_ParametersDataManager->SetCPUBufferPointer( &translationBase ); } break; case 3: { GPUTranslationTransformBase3D translationBase; SetOffset3< ScalarType >( GetCPUOffset(), translationBase.offset, dim ); this->m_ParametersDataManager->SetCPUBufferPointer( &translationBase ); } break; default: break; } this->m_ParametersDataManager->SetGPUDirtyFlag( true ); this->m_ParametersDataManager->UpdateGPUBuffer(); return this->m_ParametersDataManager; } // end GetParametersDataManager() //------------------------------------------------------------------------------ template< typename TScalarType, unsigned int NDimensions > bool GPUTranslationTransformBase< TScalarType, NDimensions > ::GetSourceCode( std::string & source ) const { if( this->m_Sources.size() == 0 ) { return false; } // Create the final source code std::ostringstream sources; // Add other sources for( std::size_t i = 0; i < this->m_Sources.size(); i++ ) { sources << this->m_Sources[ i ] << std::endl; } source = sources.str(); return true; } // end GetSourceCode() } // end namespace itk #endif /* __itkGPUTranslationTransformBase_hxx */
6,052
1,848
// // VisibleSectorListener.hpp // G3MiOSSDK // // Created by Diego Gomez Deck on 1/17/13. // // #ifndef __G3MiOSSDK__VisibleSectorListener__ #define __G3MiOSSDK__VisibleSectorListener__ #include "Sector.hpp" class VisibleSectorListener { public: virtual ~VisibleSectorListener() { } virtual void onVisibleSectorChange(const Sector& visibleSector, const Geodetic3D& cameraPosition) = 0; }; #endif
449
167
/********************************************************************** HttpRequestManager - Submit http 'get' and 'post' requests with a QNetworkAccessManager and receive the results Copyright (C) 2017-2018 by Patrick Avery This source code is released under the New BSD License, (the "License"). 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 "httprequestmanager.h" #include <QDebug> #include <QNetworkRequest> HttpRequestManager::HttpRequestManager( const std::shared_ptr<QNetworkAccessManager>& networkManager, QObject* parent) : QObject(parent), m_networkManager(networkManager), m_requestCounter(0) { // This is done so that handleGet and handlePost are always ran in the // main thread connect(this, &HttpRequestManager::signalGet, this, &HttpRequestManager::handleGet); connect(this, &HttpRequestManager::signalPost, this, &HttpRequestManager::handlePost); } size_t HttpRequestManager::sendGet(QUrl url) { std::unique_lock<std::mutex> lock(m_mutex); QNetworkRequest request(url); emit signalGet(request, m_requestCounter); return m_requestCounter++; } size_t HttpRequestManager::sendPost(QUrl url, const QByteArray& data) { std::unique_lock<std::mutex> lock(m_mutex); QNetworkRequest request(url); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); emit signalPost(request, data, m_requestCounter); return m_requestCounter++; } bool HttpRequestManager::containsData(size_t i) const { std::unique_lock<std::mutex> lock(m_mutex); return m_receivedReplies.find(i) != m_receivedReplies.end(); } const QByteArray& HttpRequestManager::data(size_t i) const { std::unique_lock<std::mutex> lock(m_mutex); static const QByteArray empty = ""; if (m_receivedReplies.find(i) == m_receivedReplies.end()) return empty; return m_receivedReplies.at(i); } void HttpRequestManager::handleGet(QNetworkRequest request, size_t requestId) { std::unique_lock<std::mutex> lock(m_mutex); QNetworkReply* reply = m_networkManager->get(request); connect(reply, (void (QNetworkReply::*)(QNetworkReply::NetworkError))( &QNetworkReply::error), this, &HttpRequestManager::handleError); connect(reply, &QNetworkReply::finished, this, &HttpRequestManager::handleFinished); m_pendingReplies[requestId] = reply; } void HttpRequestManager::handlePost(QNetworkRequest request, QByteArray data, size_t requestId) { std::unique_lock<std::mutex> lock(m_mutex); QNetworkReply* reply = m_networkManager->post(request, data); connect(reply, (void (QNetworkReply::*)(QNetworkReply::NetworkError))( &QNetworkReply::error), this, &HttpRequestManager::handleError); connect(reply, &QNetworkReply::finished, this, &HttpRequestManager::handleFinished); m_pendingReplies[requestId] = reply; } void HttpRequestManager::handleError(QNetworkReply::NetworkError ec) { std::unique_lock<std::mutex> lock(m_mutex); // Make sure the sender is a QNetworkReply QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender()); if (!reply) { qDebug() << "Error in" << __FUNCTION__ << ": sender() is not a" << "QNetworkReply!"; return; } // Make sure this HttpRequestManager owns this reply auto it = std::find_if(m_pendingReplies.begin(), m_pendingReplies.end(), [reply](const std::pair<size_t, QNetworkReply*>& item) { return reply == item.second; }); // If not, print an error and return if (it == m_pendingReplies.end()) { qDebug() << "Error in" << __FUNCTION__ << ": sender() is not owned by" << "this HttpRequestManager instance!"; return; } size_t receivedInd = it->first; // Print a message for some of the more common errors if (ec == QNetworkReply::ConnectionRefusedError) qDebug() << "QNetworkReply received an error: connection refused"; else if (ec == QNetworkReply::RemoteHostClosedError) qDebug() << "QNetworkReply received an error: remote host closed"; else if (ec == QNetworkReply::HostNotFoundError) qDebug() << "QNetworkReply received an error: host not found"; else if (ec == QNetworkReply::TimeoutError) qDebug() << "QNetworkReply received an error: timeout"; else qDebug() << "QNetworkReply received error code:" << ec; m_receivedReplies[receivedInd] = reply->readAll(); m_pendingReplies.erase(receivedInd); reply->deleteLater(); // Emit a signal emit received(receivedInd); } void HttpRequestManager::handleFinished() { std::unique_lock<std::mutex> lock(m_mutex); // Make sure the sender is a QNetworkReply QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender()); if (!reply) { qDebug() << "Error in" << __FUNCTION__ << ": sender() is not a" << "QNetworkReply!"; return; } // Make sure this HttpRequestManager owns this reply auto it = std::find_if(m_pendingReplies.begin(), m_pendingReplies.end(), [reply](const std::pair<size_t, QNetworkReply*>& item) { return reply == item.second; }); // If not, just return if (it == m_pendingReplies.end()) return; size_t receivedInd = it->first; m_receivedReplies[receivedInd] = reply->readAll(); m_pendingReplies.erase(receivedInd); reply->deleteLater(); // Emit a signal emit received(receivedInd); }
5,877
1,835
/* * * * * * * * * * * * * * * * * * * * * ** ** Copyright 2012 Dominik Pretzsch ** ** 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 "stdafx.h" UINT __stdcall SanitizeDwordFromRegistry(MSIHANDLE hInstall) { HRESULT hr = S_OK; UINT er = ERROR_SUCCESS; hr = WcaInitialize(hInstall, "SanitizeDword"); ExitOnFailure(hr, "Failed to initialize"); WcaLog(LOGMSG_STANDARD, "Initialized."); /// wchar_t cPropertyName[MAX_PATH]; wchar_t cPropertyValue[MAX_PATH]; DWORD dwMaxLen = MAX_PATH; // TODO: Support multiple properties (separated by comma) MsiGetProperty(hInstall, L"SANITIZE_DWORD", cPropertyName, &dwMaxLen); MsiGetProperty(hInstall, cPropertyName, cPropertyValue, &dwMaxLen); if (cPropertyValue[0] == '#') { WcaLog(LOGMSG_STANDARD, "Property %s needs sanitation...", cPropertyName); for (unsigned int i = 1; i < dwMaxLen; i++) { cPropertyValue[i - 1] = cPropertyValue[i]; cPropertyValue[i] = NULL; } WcaLog(LOGMSG_STANDARD, "Sanitation done."); } MsiSetProperty(hInstall, cPropertyName, cPropertyValue); /// LExit: er = SUCCEEDED(hr) ? ERROR_SUCCESS : ERROR_INSTALL_FAILURE; return WcaFinalize(er); } // DllMain - Initialize and cleanup WiX custom action utils. extern "C" BOOL WINAPI DllMain( __in HINSTANCE hInst, __in ULONG ulReason, __in LPVOID ) { switch (ulReason) { case DLL_PROCESS_ATTACH: WcaGlobalInitialize(hInst); break; case DLL_PROCESS_DETACH: WcaGlobalFinalize(); break; } return TRUE; }
2,056
787
/** * @author github.com/luncliff (luncliff@gmail.com) */ #undef NDEBUG #include <atomic> #include <cassert> #include <iostream> #include <gsl/gsl> #include <coroutine/return.h> #include <coroutine/windows.h> using namespace std; using namespace coro; auto procedure_call_on_known_thread(HANDLE thread, HANDLE event) -> frame_t { co_await continue_on_apc{thread}; if (SetEvent(event) == FALSE) cerr << system_category().message(GetLastError()) << endl; } DWORD WINAPI wait_in_sleep(LPVOID) { SleepEx(1000, true); return GetLastError(); } int main(int, char*[]) { HANDLE event = CreateEvent(nullptr, false, false, nullptr); assert(event != INVALID_HANDLE_VALUE); auto on_return_1 = gsl::finally([event]() { CloseHandle(event); }); DWORD worker_id{}; HANDLE worker = CreateThread(nullptr, 0, // wait_in_sleep, nullptr, 0, &worker_id); assert(worker != 0); auto on_return_2 = gsl::finally([worker]() { CloseHandle(worker); }); SleepEx(500, true); procedure_call_on_known_thread(worker, event); HANDLE handles[2] = {event, worker}; auto ec = WaitForMultipleObjectsEx(2, handles, TRUE, INFINITE, true); // expect the wait is cancelled by APC (WAIT_IO_COMPLETION) assert(ec == WAIT_OBJECT_0 || ec == WAIT_IO_COMPLETION); DWORD retcode{}; GetExitCodeThread(worker, &retcode); // we used QueueUserAPC so the return can be 'elapsed' milliseconds // allow zero for the timeout assert(retcode >= 0); return EXIT_SUCCESS; }
1,558
561
#ifndef PERIAPSIS_MAIN_WINDOW_H #define PERIAPSIS_MAIN_WINDOW_H // // $Id$ // // Copyright (c) 2008, The Periapsis Project. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the The Periapsis 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 "data/singleton.hpp" #include "data/string.hpp" #include "data/config.hpp" #include "framework/widget.hpp" namespace gsgl { namespace framework { class textbox; class button; class tabbox; } } namespace periapsis { class periapsis_app; class simulation_tab; class settings_tab; class load_scenery_thread; class main_window : public gsgl::framework::widget, public gsgl::data::singleton<main_window> { gsgl::framework::textbox *title_box, *status_bar; gsgl::framework::button *quit_button; gsgl::framework::tabbox *tab_box; simulation_tab *sim_tab; settings_tab *set_tab; bool need_to_load_scenery; load_scenery_thread *loading_thread; public: main_window(gsgl::platform::display & screen, const gsgl::string & title, const int x, const int y); virtual ~main_window(); // void set_status(const gsgl::string & message); // virtual void draw(); // static gsgl::data::config_variable<int> WIDTH; static gsgl::data::config_variable<int> HEIGHT; static gsgl::data::config_variable<gsgl::platform::color> FOREGROUND; static gsgl::data::config_variable<gsgl::platform::color> BACKGROUND; static gsgl::data::config_variable<gsgl::string> FONT_FACE; static gsgl::data::config_variable<int> FONT_SIZE; static gsgl::data::config_variable<int> TITLE_BOX_HEIGHT; static gsgl::data::config_variable<int> STATUS_BAR_HEIGHT; static gsgl::data::config_variable<int> TAB_BOX_SPACE; static gsgl::data::config_variable<int> QUIT_BUTTON_WIDTH; }; // class main_window } // namespace periapsis #endif
3,633
1,253
/* * AnyPatternMatchValidator.cpp * * Created on: Jun 18, 2014 * Author: sroehling */ #include <AnyPatternMatchValidator.h> AnyPatternMatchValidator::AnyPatternMatchValidator() { } bool AnyPatternMatchValidator::validPattern(const PatternMatch &) { return true; } AnyPatternMatchValidator::~AnyPatternMatchValidator() { }
340
111
#include "gamelib/components/CollisionComponent.hpp" #include "gamelib/core/geometry/CollisionSystem.hpp" namespace gamelib { CollisionComponent::CollisionComponent() { _props.registerProperty("flags", flags, 0, num_colflags, str_colflags); } CollisionComponent::~CollisionComponent() { quit(); } bool CollisionComponent::_init() { auto sys = getSubsystem<CollisionSystem>(); if (!sys) return false; sys->add(this); return true; } void CollisionComponent::_quit() { getSubsystem<CollisionSystem>()->remove(this); } Transformable* CollisionComponent::getTransform() { return this; } const Transformable* CollisionComponent::getTransform() const { return this; } }
826
249
#include "tableinfo.h" TableInfo::TableInfo(QObject *parent) : QObject(parent) { } QString TableInfo::name() { return mName; } int TableInfo::id() { return mId; } bool TableInfo::isWaitingOrder() { return waitingOrder; } void TableInfo::setName(const QString &name) { mName = name; emit nameChanged(); } void TableInfo::setWaitingOrder(bool waiting) { waitingOrder = waiting; emit isWaitingOrderChanged(); } void TableInfo::setId(int id) { mId = id; emit idChanged(); }
514
187
#include <iostream> using namespace std; #define TEST(ModuleName) extern void test##ModuleName(void); \ test##ModuleName() int main(void) { TEST(BitVectorRank); TEST(WaveletTree); TEST(WaveletTreeBitVector); TEST(WaveletMatrix); TEST(WaveletMatrixArray); TEST(WaveletMatrixArrayIndirect); }
349
118