hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
ef62b91f0ec7b8260e7193f6b28ce8d08b489b88
6,197
cpp
C++
ionGUI/ionGUI.cpp
iondune/ionEngine
7ce3394dafbabf0e0bb9f5d07dbfae31161800d4
[ "MIT" ]
36
2015-06-28T14:53:06.000Z
2021-10-31T04:26:53.000Z
ionGUI/ionGUI.cpp
iondune/ionEngine
7ce3394dafbabf0e0bb9f5d07dbfae31161800d4
[ "MIT" ]
90
2015-05-01T07:21:43.000Z
2017-08-30T01:16:41.000Z
ionGUI/ionGUI.cpp
iondune/ionEngine
7ce3394dafbabf0e0bb9f5d07dbfae31161800d4
[ "MIT" ]
9
2016-04-08T07:48:02.000Z
2019-07-22T15:13:53.000Z
#include "ionGUI.h" using namespace ion; namespace ImGui { bool SliderDouble(const char * label, double * v, double v_min, double v_max, const char * display_format, double power) { float temp = (float) *v; if (SliderFloat(label, &temp, (float) v_min, (float) v_max, display_format, (float) power)) { *v = (double) temp; return true; } else { return false; } } bool ColorEdit3(const char * label, color3f & Color) { float c[3] = { Color.Red, Color.Green, Color.Blue }; if (ImGui::ColorEdit3(label, c)) { Color = color3f(c[0], c[1], c[2]); return true; } return false; } bool ColorEdit3(const char * label, color3i & Color) { color3f c = Color; if (ColorEdit3(label, c)) { Color = c; return true; } return false; } bool ColorEdit4(const char * label, color4f & Color) { float c[4] = { Color.Red, Color.Green, Color.Blue, Color.Alpha }; if (ImGui::ColorEdit4(label, c)) { Color = color4f(c[0], c[1], c[2], c[3]); return true; } return false; } bool ColorEdit4(const char * label, color4i & Color) { color4f c = Color; if (ColorEdit4(label, c)) { Color = c; return true; } return false; } bool ColorPicker3(const char* label, ion::color3f & Color) { float c[3] = { Color.Red, Color.Green, Color.Blue }; if (ImGui::ColorPicker3(label, c)) { Color = color3f(c[0], c[1], c[2]); return true; } return false; } bool ColorPicker3(const char* label, ion::color3i & Color) { color3f c = Color; if (ColorPicker3(label, c)) { Color = c; return true; } return false; } bool ColorPicker4(const char* label, ion::color4f & Color) { float c[4] = { Color.Red, Color.Green, Color.Blue, Color.Alpha }; if (ImGui::ColorPicker4(label, c)) { Color = color4f(c[0], c[1], c[2], c[3]); return true; } return false; } bool ColorPicker4(const char* label, ion::color4i & Color) { color4f c = Color; if (ColorPicker4(label, c)) { Color = c; return true; } return false; } bool DragVec2(const char * label, ion::vec2i & v, float v_speed, int v_min, int v_max, const char * display_format) { int vals[2] = { v.X, v.Y }; if (ImGui::DragInt2(label, vals, v_speed, v_min, v_max, display_format)) { v = vec2i(vals[0], vals[1]); return true; } return false; } bool DragVec2(const char * label, vec2f & v, float v_speed, float v_min, float v_max, const char * display_format, float power) { float vals[2] = { v.X, v.Y }; if (ImGui::DragFloat2(label, vals, v_speed, v_min, v_max, display_format, power)) { v = vec2f(vals[0], vals[1]); return true; } return false; } bool DragVec3(const char * label, ion::vec3i & v, float v_speed, int v_min, int v_max, const char* display_format) { int vals[3] = { v.X, v.Y, v.Z }; if (ImGui::DragInt3(label, vals, v_speed, v_min, v_max, display_format)) { v = vec3i(vals[0], vals[1], vals[2]); return true; } return false; } bool DragVec3(const char * label, vec3f & v, float v_speed, float v_min, float v_max, const char * display_format, float power) { float vals[3] = { v.X, v.Y, v.Z }; if (ImGui::DragFloat3(label, vals, v_speed, v_min, v_max, display_format, power)) { v = vec3f(vals[0], vals[1], vals[2]); return true; } return false; } bool SliderVec2(const char * label, ion::vec2i & v, int v_min, int v_max, const char * display_format) { int vals[2] = { v.X, v.Y }; if (ImGui::SliderInt2(label, vals, v_min, v_max, display_format)) { v = vec2i(vals[0], vals[1]); return true; } return false; } bool SliderVec2(const char * label, ion::vec2f & v, float v_min, float v_max, const char * display_format, float power) { float vals[2] = { v.X, v.Y }; if (ImGui::SliderFloat2(label, vals, v_min, v_max, display_format, power)) { v = vec2f(vals[0], vals[1]); return true; } return false; } bool SliderVec3(const char * label, ion::vec3i & v, int v_min, int v_max, const char * display_format) { int vals[3] = { v.X, v.Y, v.Z }; if (ImGui::SliderInt3(label, vals, v_min, v_max, display_format)) { v = vec3i(vals[0], vals[1], vals[2]); return true; } return false; } bool SliderVec3(const char * label, ion::vec3f & v, float v_min, float v_max, const char * display_format, float power) { float vals[3] = { v.X, v.Y, v.Z }; if (ImGui::SliderFloat3(label, vals, v_min, v_max, display_format, power)) { v = vec3f(vals[0], vals[1], vals[2]); return true; } return false; } bool Combo(const char * label, int * current_item, std::initializer_list<char const *> const & items, int height_in_items) { vector<char const *> items_vec = items; return ImGui::Combo(label, current_item, items_vec.data(), (int) items.size(), height_in_items); } bool Combo(const char * label, int * current_item, std::vector<string> const & items, int height_in_items) { vector<char const *> items_vec; for (string const & item : items) { items_vec.push_back(item.c_str()); } return ImGui::Combo(label, current_item, items_vec.data(), (int) items.size(), height_in_items); } bool InputText(const char * label, string & buf, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void * user_data) { static vector<char> buffer_copy; static int const ReserveSpace = 32; if (buffer_copy.size() < buf.size() + ReserveSpace) { buffer_copy.resize(buf.size() + ReserveSpace); } strcpy(buffer_copy.data(), buf.c_str()); if (ImGui::InputText(label, buffer_copy.data(), buffer_copy.size(), flags, callback, user_data)) { buf = buffer_copy.data(); return true; } return false; } scoped_id::scoped_id(char const * const str_id) { ImGui::PushID(str_id); } scoped_id::scoped_id(int const int_id) { ImGui::PushID(int_id); } scoped_id::~scoped_id() { ImGui::PopID(); } } char const * ion::BoolToString(bool const B) { return B ? "yes" : "no"; }
23.926641
129
0.611425
iondune
ef64365f574ac3238d50fcfda5a9a1f3d4119b5b
1,664
cc
C++
Source/BladeFramework/source/TimeSource.cc
OscarGame/blade
6987708cb011813eb38e5c262c7a83888635f002
[ "MIT" ]
146
2018-12-03T08:08:17.000Z
2022-03-21T06:04:06.000Z
Source/BladeFramework/source/TimeSource.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
1
2019-01-18T03:35:49.000Z
2019-01-18T03:36:08.000Z
Source/BladeFramework/source/TimeSource.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
31
2018-12-03T10:32:43.000Z
2021-10-04T06:31:44.000Z
/******************************************************************** created: 2010/09/08 filename: TimeSource.cc author: Crazii purpose: *********************************************************************/ #include <BladePCH.h> #include <TimeSource.h> namespace Blade { ////////////////////////////////////////////////////////////////////////// TimeSource::TimeSource() { mTimer = ITimeDevice::create(); mLoopCount = 0; mLoopTime = 0; mAverageLoopTime = 0; mLoopTimeLimit = 0; mLastTime = mTimer->getSeconds(); } ////////////////////////////////////////////////////////////////////////// TimeSource::~TimeSource() { BLADE_DELETE mTimer; } ////////////////////////////////////////////////////////////////////////// void TimeSource::reset() { mTimer->reset(); mLoopCount = 0; mAverageLoopTime = 0; mLoopTime = 0; mLastTime = mTimer->getSeconds(); } ////////////////////////////////////////////////////////////////////////// void TimeSource::update() { mTimer->update(); mLoopTime = mTimer->getSeconds() - mLastTime; mLastTime = mTimer->getSeconds(); if( mLoopTime < 0 ) mLoopTime = 0.0; if( mLoopTimeLimit != 0 && mLoopTime < mLoopTimeLimit ) mLoopTime = mLoopTimeLimit; mLoopCount++; if( mTimer->getMilliseconds() > 1000 * 1000 )//floating point precision { mTimer->reset(); mLastTime = 0; mLoopCount = 0; mAverageLoopTime = mLoopTime; //ILog::DebugOutput << TEXT("timer reset.") << ILog::endLog; } else mAverageLoopTime = mTimer->getSeconds() / mLoopCount; //ILog::DebugOutput << uint( ((scalar)1.0/mLoopTime) ) << ILog::endLog; } }//namespace Blade
24.470588
75
0.478365
OscarGame
ef6632a272ec6d81af7fd2f184d41f8bfdf2ba71
1,309
cpp
C++
map/download_on_map_ads_delegate.cpp
vicpopov/omim
664b458998fb0f2405f68ae830c2798e027b2dcc
[ "Apache-2.0" ]
1
2020-07-21T01:24:24.000Z
2020-07-21T01:24:24.000Z
map/download_on_map_ads_delegate.cpp
vicpopov/omim
664b458998fb0f2405f68ae830c2798e027b2dcc
[ "Apache-2.0" ]
null
null
null
map/download_on_map_ads_delegate.cpp
vicpopov/omim
664b458998fb0f2405f68ae830c2798e027b2dcc
[ "Apache-2.0" ]
null
null
null
#include "map/download_on_map_ads_delegate.hpp" namespace ads { DownloadOnMapDelegate::DownloadOnMapDelegate(storage::CountryInfoGetter const & infoGetter, storage::Storage const & storage, promo::Api const & promoApi, Purchase const & purchase) : m_countryInfoGetter(infoGetter) , m_storage(storage) , m_promoApi(promoApi) , m_purchase(purchase) { } storage::CountryId DownloadOnMapDelegate::GetCountryId(m2::PointD const & pos) { return m_countryInfoGetter.GetRegionCountryId(pos); } storage::CountryId DownloadOnMapDelegate::GetTopmostParentFor(storage::CountryId const & countryId) const { return m_storage.GetTopmostParentFor(countryId); } std::string DownloadOnMapDelegate::GetLinkForCountryId(storage::CountryId const & countryId) const { auto const & cities = m_storage.GetMwmTopCityGeoIds(); auto const it = cities.find(countryId); if (it == cities.cend()) return {}; auto const cityGeoId = strings::to_string(it->second.GetEncodedId()); if (cityGeoId.empty()) return {}; return m_promoApi.GetLinkForDownloader(cityGeoId); } bool DownloadOnMapDelegate::IsAdsRemoved() const { return m_purchase.IsSubscriptionActive(SubscriptionType::RemoveAds); } } // namespace ads
28.456522
105
0.718869
vicpopov
ef66959690a9d751b28f80e30ba86dcd4364e351
3,963
cpp
C++
externals/pantheios-1.0.1-beta214/src/core/api.exitprocess.cpp
betasheet/diffingo
285d21b16c118155e5c149b20fcb20a20276f3d7
[ "MIT" ]
null
null
null
externals/pantheios-1.0.1-beta214/src/core/api.exitprocess.cpp
betasheet/diffingo
285d21b16c118155e5c149b20fcb20a20276f3d7
[ "MIT" ]
null
null
null
externals/pantheios-1.0.1-beta214/src/core/api.exitprocess.cpp
betasheet/diffingo
285d21b16c118155e5c149b20fcb20a20276f3d7
[ "MIT" ]
null
null
null
/* ///////////////////////////////////////////////////////////////////////// * File: src/core/api.exitprocess.cpp * * Purpose: Implementation file for Pantheios core API. * * Created: 21st June 2005 * Updated: 20th March 2012 * * Home: http://www.pantheios.org/ * * Copyright (c) 2005-2012, Matthew Wilson and Synesis Software * Copyright (c) 1999-2005, Synesis Software and Matthew Wilson * 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(s) of Matthew Wilson and Synesis Software nor the * names of any 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. * * ////////////////////////////////////////////////////////////////////// */ /* Pantheios header files * * NOTE: We do _not_ include pantheios/pantheios.hpp here, since we are * not using any of the Application Layer. */ #include <pantheios/pantheios.h> #include <pantheios/internal/lean.h> #include <platformstl/platformstl.h> #if defined(PLATFORMSTL_OS_IS_WINDOWS) # include <windows.h> #else /* ? OS */ # include <stdlib.h> # include <unistd.h> #endif /* OS */ /* ///////////////////////////////////////////////////////////////////////// * Namespace */ #if !defined(PANTHEIOS_NO_NAMESPACE) namespace pantheios { #endif /* !PANTHEIOS_NO_NAMESPACE */ /* ///////////////////////////////////////////////////////////////////////// * Core functions */ #if !defined(PANTHEIOS_NO_NAMESPACE) namespace core { #endif /* !PANTHEIOS_NO_NAMESPACE */ PANTHEIOS_CALL(void) pantheios_exitProcess(int code) { #if defined(PLATFORMSTL_OS_IS_WINDOWS) // By rights, Windows programs should use exit() to close down. However, // pantheios_exit_process() is not a general substitute for exit(). It is // specifically intended to Get-Out-Of-Dodge asap, in the rare case where // Pantheios cannot be initialised. // // NOTE: May need to revisit this in the future, in cases where a // sophisticated back-end, e.g. log4cxx, does not initialise. ::ExitProcess(static_cast<DWORD>(code)); #else /* ? operating system */ ::_exit(code); #endif /* operating system */ } #if !defined(PANTHEIOS_NO_NAMESPACE) } /* namespace core */ #endif /* !PANTHEIOS_NO_NAMESPACE */ /* ///////////////////////////////////////////////////////////////////////// * Namespace */ #if !defined(PANTHEIOS_NO_NAMESPACE) } /* namespace pantheios */ #endif /* !PANTHEIOS_NO_NAMESPACE */ /* ///////////////////////////// end of file //////////////////////////// */
35.383929
78
0.629069
betasheet
ef690afe7ceee35582141c0fee26c8070e2aee88
167
cpp
C++
regression/cbmc-cpp/Overloading_Functions2/main.cpp
tobireinhard/cbmc
fc165c119985adf8db9a13493f272a2def4e79fa
[ "BSD-4-Clause" ]
412
2016-04-02T01:14:27.000Z
2022-03-27T09:24:09.000Z
regression/cbmc-cpp/Overloading_Functions2/main.cpp
tobireinhard/cbmc
fc165c119985adf8db9a13493f272a2def4e79fa
[ "BSD-4-Clause" ]
4,671
2016-02-25T13:52:16.000Z
2022-03-31T22:14:46.000Z
regression/cbmc-cpp/Overloading_Functions2/main.cpp
tobireinhard/cbmc
fc165c119985adf8db9a13493f272a2def4e79fa
[ "BSD-4-Clause" ]
266
2016-02-23T12:48:00.000Z
2022-03-22T18:15:51.000Z
struct A { }; struct B : A { }; struct C : B { }; bool f1(A &) { return true; } bool f1(B &) { return false; } int main() { C c; assert(f1(c) == false); }
6.185185
25
0.48503
tobireinhard
ef6b8863646c06fecceda5facb08b2d3baf61d8a
9,889
cxx
C++
rdpfuzz-winafl/cmake-3.16.0/Source/cmQtAutoGenGlobalInitializer.cxx
fengjixuchui/rdpfuzz
4561b6fbf73ada553ce78ad44918fd0930ee4e85
[ "Apache-2.0" ]
107
2021-08-28T20:08:42.000Z
2022-03-22T08:02:16.000Z
rdpfuzz-winafl/cmake-3.16.0/Source/cmQtAutoGenGlobalInitializer.cxx
fengjixuchui/rdpfuzz
4561b6fbf73ada553ce78ad44918fd0930ee4e85
[ "Apache-2.0" ]
null
null
null
rdpfuzz-winafl/cmake-3.16.0/Source/cmQtAutoGenGlobalInitializer.cxx
fengjixuchui/rdpfuzz
4561b6fbf73ada553ce78ad44918fd0930ee4e85
[ "Apache-2.0" ]
16
2021-08-30T06:57:36.000Z
2022-03-22T08:05:52.000Z
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmQtAutoGenGlobalInitializer.h" #include <utility> #include <cm/memory> #include "cmCustomCommandLines.h" #include "cmCustomCommandTypes.h" #include "cmDuration.h" #include "cmGeneratorTarget.h" #include "cmLocalGenerator.h" #include "cmMakefile.h" #include "cmMessageType.h" #include "cmProcessOutput.h" #include "cmQtAutoGen.h" #include "cmQtAutoGenInitializer.h" #include "cmState.h" #include "cmStateTypes.h" #include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTarget.h" cmQtAutoGenGlobalInitializer::Keywords::Keywords() : AUTOMOC("AUTOMOC") , AUTOUIC("AUTOUIC") , AUTORCC("AUTORCC") , AUTOMOC_EXECUTABLE("AUTOMOC_EXECUTABLE") , AUTOUIC_EXECUTABLE("AUTOUIC_EXECUTABLE") , AUTORCC_EXECUTABLE("AUTORCC_EXECUTABLE") , SKIP_AUTOGEN("SKIP_AUTOGEN") , SKIP_AUTOMOC("SKIP_AUTOMOC") , SKIP_AUTOUIC("SKIP_AUTOUIC") , SKIP_AUTORCC("SKIP_AUTORCC") , AUTOUIC_OPTIONS("AUTOUIC_OPTIONS") , AUTORCC_OPTIONS("AUTORCC_OPTIONS") , qrc("qrc") , ui("ui") { } cmQtAutoGenGlobalInitializer::cmQtAutoGenGlobalInitializer( std::vector<cmLocalGenerator*> const& localGenerators) { for (cmLocalGenerator* localGen : localGenerators) { // Detect global autogen and autorcc target names bool globalAutoGenTarget = false; bool globalAutoRccTarget = false; { cmMakefile* makefile = localGen->GetMakefile(); // Detect global autogen target name if (cmIsOn(makefile->GetSafeDefinition("CMAKE_GLOBAL_AUTOGEN_TARGET"))) { std::string targetName = makefile->GetSafeDefinition("CMAKE_GLOBAL_AUTOGEN_TARGET_NAME"); if (targetName.empty()) { targetName = "autogen"; } GlobalAutoGenTargets_.emplace(localGen, std::move(targetName)); globalAutoGenTarget = true; } // Detect global autorcc target name if (cmIsOn(makefile->GetSafeDefinition("CMAKE_GLOBAL_AUTORCC_TARGET"))) { std::string targetName = makefile->GetSafeDefinition("CMAKE_GLOBAL_AUTORCC_TARGET_NAME"); if (targetName.empty()) { targetName = "autorcc"; } GlobalAutoRccTargets_.emplace(localGen, std::move(targetName)); globalAutoRccTarget = true; } } // Find targets that require AUTOMOC/UIC/RCC processing for (cmGeneratorTarget* target : localGen->GetGeneratorTargets()) { // Process only certain target types switch (target->GetType()) { case cmStateEnums::EXECUTABLE: case cmStateEnums::STATIC_LIBRARY: case cmStateEnums::SHARED_LIBRARY: case cmStateEnums::MODULE_LIBRARY: case cmStateEnums::OBJECT_LIBRARY: // Process target break; default: // Don't process target continue; } if (target->IsImported()) { // Don't process target continue; } bool const moc = target->GetPropertyAsBool(kw().AUTOMOC); bool const uic = target->GetPropertyAsBool(kw().AUTOUIC); bool const rcc = target->GetPropertyAsBool(kw().AUTORCC); if (moc || uic || rcc) { std::string const mocExec = target->GetSafeProperty(kw().AUTOMOC_EXECUTABLE); std::string const uicExec = target->GetSafeProperty(kw().AUTOUIC_EXECUTABLE); std::string const rccExec = target->GetSafeProperty(kw().AUTORCC_EXECUTABLE); // We support Qt4, Qt5 and Qt6 auto qtVersion = cmQtAutoGenInitializer::GetQtVersion(target); bool const validQt = (qtVersion.first.Major == 4) || (qtVersion.first.Major == 5) || (qtVersion.first.Major == 6); bool const mocAvailable = (validQt || !mocExec.empty()); bool const uicAvailable = (validQt || !uicExec.empty()); bool const rccAvailable = (validQt || !rccExec.empty()); bool const mocIsValid = (moc && mocAvailable); bool const uicIsValid = (uic && uicAvailable); bool const rccIsValid = (rcc && rccAvailable); // Disabled AUTOMOC/UIC/RCC warning bool const mocDisabled = (moc && !mocAvailable); bool const uicDisabled = (uic && !uicAvailable); bool const rccDisabled = (rcc && !rccAvailable); if (mocDisabled || uicDisabled || rccDisabled) { cmAlphaNum version = (qtVersion.second == 0) ? cmAlphaNum("<QTVERSION>") : cmAlphaNum(qtVersion.second); cmAlphaNum component = uicDisabled ? "Widgets" : "Core"; std::string const msg = cmStrCat( "AUTOGEN: No valid Qt version found for target ", target->GetName(), ". ", cmQtAutoGen::Tools(mocDisabled, uicDisabled, rccDisabled), " disabled. Consider adding:\n", " find_package(Qt", version, " COMPONENTS ", component, ")\n", "to your CMakeLists.txt file."); target->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, msg); } if (mocIsValid || uicIsValid || rccIsValid) { // Create autogen target initializer Initializers_.emplace_back(cm::make_unique<cmQtAutoGenInitializer>( this, target, qtVersion.first, mocIsValid, uicIsValid, rccIsValid, globalAutoGenTarget, globalAutoRccTarget)); } } } } } cmQtAutoGenGlobalInitializer::~cmQtAutoGenGlobalInitializer() = default; void cmQtAutoGenGlobalInitializer::GetOrCreateGlobalTarget( cmLocalGenerator* localGen, std::string const& name, std::string const& comment) { // Test if the target already exists if (localGen->FindGeneratorTargetToUse(name) == nullptr) { cmMakefile* makefile = localGen->GetMakefile(); // Create utility target cmTarget* target = makefile->AddUtilityCommand( name, cmCommandOrigin::Generator, true, makefile->GetHomeOutputDirectory().c_str() /*work dir*/, std::vector<std::string>() /*output*/, std::vector<std::string>() /*depends*/, cmCustomCommandLines(), false, comment.c_str()); localGen->AddGeneratorTarget(new cmGeneratorTarget(target, localGen)); // Set FOLDER property in the target { char const* folder = makefile->GetState()->GetGlobalProperty("AUTOGEN_TARGETS_FOLDER"); if (folder != nullptr) { target->SetProperty("FOLDER", folder); } } } } void cmQtAutoGenGlobalInitializer::AddToGlobalAutoGen( cmLocalGenerator* localGen, std::string const& targetName) { auto it = GlobalAutoGenTargets_.find(localGen); if (it != GlobalAutoGenTargets_.end()) { cmGeneratorTarget* target = localGen->FindGeneratorTargetToUse(it->second); if (target != nullptr) { target->Target->AddUtility(targetName, localGen->GetMakefile()); } } } void cmQtAutoGenGlobalInitializer::AddToGlobalAutoRcc( cmLocalGenerator* localGen, std::string const& targetName) { auto it = GlobalAutoRccTargets_.find(localGen); if (it != GlobalAutoRccTargets_.end()) { cmGeneratorTarget* target = localGen->FindGeneratorTargetToUse(it->second); if (target != nullptr) { target->Target->AddUtility(targetName, localGen->GetMakefile()); } } } cmQtAutoGen::CompilerFeaturesHandle cmQtAutoGenGlobalInitializer::GetCompilerFeatures( std::string const& generator, std::string const& executable, std::string& error) { // Check if we have cached features { auto it = this->CompilerFeatures_.find(executable); if (it != this->CompilerFeatures_.end()) { return it->second; } } // Check if the executable exists if (!cmSystemTools::FileExists(executable, true)) { error = cmStrCat("The \"", generator, "\" executable ", cmQtAutoGen::Quoted(executable), " does not exist."); return cmQtAutoGen::CompilerFeaturesHandle(); } // Test the executable std::string stdOut; { std::string stdErr; std::vector<std::string> command; command.emplace_back(executable); command.emplace_back("-h"); int retVal = 0; const bool runResult = cmSystemTools::RunSingleCommand( command, &stdOut, &stdErr, &retVal, nullptr, cmSystemTools::OUTPUT_NONE, cmDuration::zero(), cmProcessOutput::Auto); if (!runResult) { error = cmStrCat("Test run of \"", generator, "\" executable ", cmQtAutoGen::Quoted(executable), " failed.\n", cmQtAutoGen::QuotedCommand(command), '\n', stdOut, '\n', stdErr); return cmQtAutoGen::CompilerFeaturesHandle(); } } // Create valid handle cmQtAutoGen::CompilerFeaturesHandle res = std::make_shared<cmQtAutoGen::CompilerFeatures>(); res->HelpOutput = std::move(stdOut); // Register compiler features this->CompilerFeatures_.emplace(executable, res); return res; } bool cmQtAutoGenGlobalInitializer::generate() { return (InitializeCustomTargets() && SetupCustomTargets()); } bool cmQtAutoGenGlobalInitializer::InitializeCustomTargets() { // Initialize global autogen targets { std::string const comment = "Global AUTOGEN target"; for (auto const& pair : GlobalAutoGenTargets_) { GetOrCreateGlobalTarget(pair.first, pair.second, comment); } } // Initialize global autorcc targets { std::string const comment = "Global AUTORCC target"; for (auto const& pair : GlobalAutoRccTargets_) { GetOrCreateGlobalTarget(pair.first, pair.second, comment); } } // Initialize per target autogen targets for (auto& initializer : Initializers_) { if (!initializer->InitCustomTargets()) { return false; } } return true; } bool cmQtAutoGenGlobalInitializer::SetupCustomTargets() { for (auto& initializer : Initializers_) { if (!initializer->SetupCustomTargets()) { return false; } } return true; }
34.1
79
0.668116
fengjixuchui
ef6d55e7afa2d0ba1283ba681a4d5d5e8a423379
1,107
hpp
C++
include/Parser.hpp
Electrux/alacrity-lang
2931533c0f393cf2d2500ac0848da452fbc19295
[ "BSD-3-Clause" ]
15
2019-03-21T14:37:17.000Z
2021-11-14T20:35:46.000Z
include/Parser.hpp
Electrux/alacrity-lang
2931533c0f393cf2d2500ac0848da452fbc19295
[ "BSD-3-Clause" ]
null
null
null
include/Parser.hpp
Electrux/alacrity-lang
2931533c0f393cf2d2500ac0848da452fbc19295
[ "BSD-3-Clause" ]
5
2019-02-02T10:18:04.000Z
2021-05-06T16:34:04.000Z
/* Copyright (c) 2019, Electrux All rights reserved. Using the BSD 3-Clause license for the project, main LICENSE file resides in project's root directory. Please read that file and understand the license terms before using or altering the project. */ #ifndef PARSER_HPP #define PARSER_HPP #include <variant> #include "Lexer/Lexer.hpp" #include "Parser/Stmt.hpp" namespace Parser { class ParseTree { std::vector< Stmt * > m_stmts; public: ParseTree(); explicit ParseTree( const std::vector< Stmt * > & stmts ); ParseTree( ParseTree && original ); ParseTree( ParseTree & original ); ParseTree( ParseTree const & original ) = delete; ParseTree & operator =( ParseTree original ); friend void swap( ParseTree & stmt1, ParseTree & stmt2 ); Stmt * operator []( const size_t loc ); void push_back( Stmt * const stmt ); void pop_back(); size_t size() const; // iteration const std::vector< Stmt * > & GetStmts() const; ~ParseTree(); }; void swap( ParseTree & stmt1, ParseTree & stmt2 ); std::variant< int, ParseTree > ParseTokens( const LexSymVec & tokens ); } #endif // PARSER_HPP
22.14
71
0.710027
Electrux
ef757c4c99b400e488caa342cf57e5c0f9eb2d3c
15,471
hh
C++
db/slt3/var.hh
codesloop/codesloop
d66e51c2d898a72624306f611a90364c76deed06
[ "BSD-2-Clause" ]
3
2016-05-09T15:29:29.000Z
2017-11-22T06:16:18.000Z
db/slt3/var.hh
codesloop/codesloop
d66e51c2d898a72624306f611a90364c76deed06
[ "BSD-2-Clause" ]
null
null
null
db/slt3/var.hh
codesloop/codesloop
d66e51c2d898a72624306f611a90364c76deed06
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2008,2009,2010, CodeSLoop Team 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 ``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 BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _csl_db_var_hh_included_ #define _csl_db_var_hh_included_ /** @file var.hh @brief slt3 var implementation of slt3 variables that helps 'instrumenting' classes to easily use the simple object relational mapping provided by slt3. these variables bind member variables to database fields. */ #include "codesloop/common/pvlist.hh" #include "codesloop/common/pbuf.hh" #include "codesloop/common/int64.hh" #include "codesloop/common/dbl.hh" #include "codesloop/common/binry.hh" #include "codesloop/common/ustr.hh" #include "codesloop/db/slt3/query.hh" #ifdef __cplusplus #include <vector> namespace csl { namespace db { namespace slt3 { class obj; /** @brief slt3::var is the base class of other slt3 variable mappers slt3::var variables represents the mapping between member variables of classes and database fields. this is part of the object relational mapping facilities of slt3. the mapping is done with the help of member variables that are registered by var::helper. the ORM mapping facilities are: sql::helper , reg::helper and var_base::helper they register ORM variables, generate SQL strings and maps database columns to variables. */ class var_base { public: /* abstract functions */ /** @brief abtract function for setting the ORM-property variable from the result of an SQL query @param ch is a pointer to column header data as returned from the database query @param fd is a pointer to field data as returned from the database query @return true if successful */ virtual bool set_value(query::colhead * ch,query::field * fd) = 0; /** @brief abstract function to get the internal variable (common::var) */ virtual const common::var * get_value() const = 0; /** @brief returns the variable's type as specified in common variables or query::colhead enumeration (same) */ virtual int type() = 0; /** @brief destructor */ inline virtual ~var_base() {} /** @brief initializing constructor */ inline var_base(obj & prn) : parent_(&prn) {} protected: /** @brief register a variable with both sql::helper and var_base::helper @param v is a pointer to the variable to be initialized @param name is the database column name associated with the variable @param coltype is the database column type like (INTEGER, REAL, BLOB, ...) @param parent is a pointer to the actual class instance @param flags are the misc properties of the database column like (UNIQUE, DEFAULT, PRIMARY KEY, etc...) */ virtual void register_variable(var_base * v, const char * name, const char * coltype, slt3::obj & parent, const char * flags); /** @brief returns a pointer to the parent object */ inline virtual obj * parent() { return parent_; } obj * parent_; public: /** @brief var_base::helper keeps track of variables and helps the ORM functionality */ class helper { public: /** @brief registers a database variable @param name is the variable's database column name @param v is a reference to the given variable */ bool add_field(const char * name, var_base & v); /** @brief represents a data field */ struct data { const char * name_; var_base * var_; data(const char * nm,var_base & v) : name_(nm), var_(&v) {} }; typedef common::pvlist< 32,data,common::delete_destructor<data> > datalist_t; /** @brief initializes the database table associated with the object @param t is the transaction context to be used @param sql_query as generated by sql::helper @return true if successful the net result of this call is a CREATE TABLE ... SQL call */ bool init(tran & t, const char * sql_query); /** @brief creates an instance of the given object in the database @param t is the transaction context to be used @param sql_query as generated by sql::helper @return true if successful the net result of this call is a INSERT ... SQL call it will also call the objects set_id() call to register the identifier of the given instance. */ bool create(tran & t, const char * sql_query); /** @brief updates an instance of the given object in the database @param t is the transaction context to be used @param sql_query as generated by sql::helper @return true if successful the net result of this call is a UPDATE ... SQL call */ bool save(tran & t, const char * sql_query); /** @brief deletes an instance of the given object from the database @param t is the transaction context to be used @param sql_query as generated by sql::helper @return true if successful the net result of this call is a DELETE ... SQL call */ bool remove(tran & t, const char * sql_query); /** @brief finds an instance of the given object in the database @param t is the transaction context to be used @param sql_query as generated by sql::helper @return true if successful the net result of this call is a SELECT ... SQL call the object's database variables will be filled with the returned data */ bool find_by_id(tran & t, const char * sql_query); /** @brief finds an instance of the given object in the database @param t is the transaction context to be used @param sql_query as generated by sql::helper @param field1 to be put into the where conditions @param field2 to be put into the where conditions (if not -1) @param field3 to be put into the where conditions (if not -1) @param field4 to be put into the where conditions (if not -1) @param field5 to be put into the where conditions (if not -1) @return true if successful the net result of this call is a SELECT ... SQL call the object's database variables will be filled with the returned data. the fieldx variables will be used as condition variables. the fields with non-default values represent a variable by index. indexing start from zero. the variables given are logically AND'ed together. to select on the 3rd and 4th variable of the given object one must first set those variables to the desired values to be searched for, and then call this function with field1=2 and field2=3. */ bool find_by(tran & t, const char * sql_query, int field1, int field2=-1, int field3=-1, int field4=-1, int field5=-1); /** @brief helper that sets the instance id @param id is the id to be set please note that this function assumes that the first variable is the id to be set */ void set_id(long long id); private: datalist_t dtalst_; }; private: /* not allowed to call these */ var_base() {} var_base(const var_base & other) {} var_base & operator=(const var_base & other) { return *this; } }; /** @brief helper to statically determine the SQL column type string based on the template parameter */ template <typename T> struct var_col_type {}; template <> struct var_col_type<common::int64> { static const char * coltype_s; }; template <> struct var_col_type<common::dbl> { static const char * coltype_s; }; template <> struct var_col_type<common::ustr> { static const char * coltype_s; }; template <> struct var_col_type<common::binry> { static const char * coltype_s; }; /** @brief templated variable type that respresents a variable in the ORM user object the varT type is basically a common::var family type plus a name and flags. these together represent a column in the database. the ORM mapper maps classes to tables and member variables to table-columns. the mapping is done through various helper classes like: @li @em sql::helper that generates the SQL query strings @li @em reg::helper that helps in locating the database for the given class @li @em var_base::helper associates the member variables with DB columns and converts between the DB and the variables */ template <typename T> class varT : public var_base { public: /** @brief initializing constructor @param name is the column name to be used @param parent is a refernce to the class whose member is the variable @param flags is the database flags associated with the database column (like UNIQUE, PRIMARY KEY, AUTO_INCREMENT etc...) this constructor registers the variable instance with the sql::helper and the var_base::helper instance */ inline varT(const char * name, slt3::obj & prn,const char * flags="") : var_base(prn) { register_variable(this,name,var_col_type<T>::coltype_s,prn,flags); } /** @brief the variable types are one of common::var family types */ enum { type_v = T::var_type_v }; /** @brief returns the variable's type */ inline int type() { return type_v; } /** @brief sets the variable's content based on info returned from DB query @param ch represents a column header @param fd is the field's data */ inline bool set_value(query::colhead * ch,query::field * fd) { if( !ch || !fd ) return false; bool ret = value_.from_var(*fd); // parent()->on_change(); TODO : check this!!! return ret; } typedef T tval_t; typedef typename T::value_t value_t; /** @brief returns the variable's value in the original representation that is one of: @li long long @li doube @li char * @li tbuf<> */ inline value_t get() const { return value_.value(); } /** @brief forwards the get() operation to the value's get() operation @see common::var for more information */ template <typename V> inline bool get(V & v) const { return value_.get(v); } /** @brief forwards the set() operation to the value's set() operation @see common::var for more information */ template <typename V> inline bool set(V & v) { bool ret = value_.set(v); if( ret ) parent()->on_change(); return ret; } /** @brief forward operator checks for equality */ template <typename V> inline bool operator==(V & other) const { return (value_ == other); } /** @brief copy constructor (initialize from char * string) */ inline varT & operator=(const char * other) { bool success = value_.from_string(other); if( success ) parent()->on_change(); return *this; } /** @brief copy constructor (initialize from wide char string) */ inline varT & operator=(const wchar_t * other) { bool success = value_.from_string(other); if( success ) parent()->on_change(); return *this; } /** @brief copy constructor (initialize from an ther variable) */ inline varT & operator=(const T & other) { bool success = value_.from_var(other); if( success ) parent()->on_change(); return *this; } /** @brief copy constructor (initialize from an other variable - varT) */ inline varT & operator=(const varT & other) { bool success = value_.from_var(other.value_); if( success ) parent()->on_change(); return *this; } /** @brief copy constructor (initialize from binary buffer) */ inline varT & operator=(const common::binry::buf_t & other) { bool success = value_.from_binary(other.data(),other.size()); if( success ) parent()->on_change(); return *this; } /** @brief copy constructor (initialize from binary buffer) */ template <typename X> inline varT & operator=(const X & other) { T tmp(other); bool success = value_.from_var(tmp); if( success ) parent()->on_change(); return *this; } /** @brief copy constructor (initialize from unsigned char vector) */ inline varT & operator=(const std::vector<unsigned char> & vref) { bool success = value_.from_binary( &(vref[0]), vref.size() ); if( success ) parent()->on_change(); return *this; } /** @brief returns a pointer to the internal value */ inline const common::var * get_value() const { return &value_; } private: T value_; }; typedef varT<common::int64> intvar; ///<int64 variable (long long) typedef varT<common::dbl> doublevar; ///<dbl variable (double) typedef varT<common::ustr> strvar; ///<ustr variable (char string) typedef varT<common::binry> blobvar; ///<binry variable (tbuf based binary value) } /* end of slt3 namespace */ } /* end of db namespace */ } /* end of csl namespace */ #endif /* __cplusplus */ #endif /* _csl_db_var_hh_included_ */
38.105911
134
0.6136
codesloop
ef75b739187f4073199194f217cc6cb0915e7c4a
126
cpp
C++
source/ion/ecs/component.cpp
dvdbrink/ion
a5fe2aba7927b7a90e913cbf72325a04172fc494
[ "MIT" ]
null
null
null
source/ion/ecs/component.cpp
dvdbrink/ion
a5fe2aba7927b7a90e913cbf72325a04172fc494
[ "MIT" ]
null
null
null
source/ion/ecs/component.cpp
dvdbrink/ion
a5fe2aba7927b7a90e913cbf72325a04172fc494
[ "MIT" ]
null
null
null
#include <ion/ecs/component.hpp> namespace ion { namespace ecs { BaseComponent::Family BaseComponent::next_family = 0; }}
21
57
0.738095
dvdbrink
ef762f0b45e2b808d9eaf486620c5183c56c4437
1,174
cpp
C++
model/model.cpp
Krzysztof-Ambroziak/Game-of-Life
41f6aa6814a227bb882f4a84a24e092b66564a4e
[ "MIT" ]
null
null
null
model/model.cpp
Krzysztof-Ambroziak/Game-of-Life
41f6aa6814a227bb882f4a84a24e092b66564a4e
[ "MIT" ]
null
null
null
model/model.cpp
Krzysztof-Ambroziak/Game-of-Life
41f6aa6814a227bb882f4a84a24e092b66564a4e
[ "MIT" ]
null
null
null
#include "model.h" Model::Model(int rows, int columns): cellSize(Model::DEFAULT_CELL_SIZE), board(new Board(rows, columns)) {} int Model::getRows() const { return board->getRows(); } int Model::getColumns() const { return board->getColumns(); } int Model::getCellSize() const { return cellSize; } Life Model::getLife(int row, int column) const { return board->getLife(row, column); } void Model::setLive(int row, int column, Life life) { board->setLife(row, column, life); } void Model::changeLife(int row, int column) { Life life = board->getLife(row, column); if(life == Life::DEAD) { board->setLife(row, column, Life::ALIVE); } else { board->setLife(row, column, Life::DEAD); } } int Model::computeAliveNeighbours(int row, int column) const { return board->computeAliveNeighbours(row, column); } int Model::getAliveNeighbours(int row, int column) const { return board->getAliveNeighbours(row, column); } void Model::setAliveNeighbours(int row, int column, int aliveNeighbours) { board->setAliveNeighbours(row, column, aliveNeighbours); } Model::~Model() { delete board; }
22.576923
74
0.668654
Krzysztof-Ambroziak
ef7bf9b91a1d1b22cdc00210840d14dee0d80daa
163
cpp
C++
src/rendering/engine/engine/resources/pipeline.cpp
Bargor/tempest
94837c6dcfef036827076446101e59afb7792f5d
[ "Apache-2.0", "MIT" ]
null
null
null
src/rendering/engine/engine/resources/pipeline.cpp
Bargor/tempest
94837c6dcfef036827076446101e59afb7792f5d
[ "Apache-2.0", "MIT" ]
1
2019-12-02T20:17:52.000Z
2019-12-02T20:17:52.000Z
src/rendering/engine/engine/resources/pipeline.cpp
Bargor/tempest
94837c6dcfef036827076446101e59afb7792f5d
[ "Apache-2.0", "MIT" ]
null
null
null
// This file is part of Tempest project // Author: Karol Kontny #include "pipeline.h" namespace tst { namespace engine {} // namespace engine } // namespace tst
18.111111
39
0.717791
Bargor
ef7ea1008a8c8e331ef658e1214d65c362b8bda2
3,283
cpp
C++
examples/utility/workpool/example_file_open_pool.cpp
vipalade/solidframe
cff130652127ca9607019b4db508bc67f8bbecff
[ "BSL-1.0" ]
26
2015-08-25T16:07:58.000Z
2019-07-05T15:21:22.000Z
examples/utility/workpool/example_file_open_pool.cpp
vipalade/solidframe
cff130652127ca9607019b4db508bc67f8bbecff
[ "BSL-1.0" ]
5
2016-10-15T22:55:15.000Z
2017-09-19T12:41:10.000Z
examples/utility/workpool/example_file_open_pool.cpp
vipalade/solidframe
cff130652127ca9607019b4db508bc67f8bbecff
[ "BSL-1.0" ]
5
2016-09-15T10:34:52.000Z
2018-10-30T11:46:46.000Z
// example_file_open_pool.cpp // // Copyright (c) 2007, 2008, 2018 Valentin Palade (vipalade @ gmail . com) // // This file is part of SolidFrame framework. // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt. // #include "solid/system/filedevice.hpp" #include "solid/system/memory.hpp" #include "solid/utility/workpool.hpp" #include <cerrno> #include <cstring> #include <deque> #include <fstream> #include <iostream> using namespace std; using namespace solid; namespace { template <class T> static T align(T _v, solid::ulong _by); template <class T> static T* align(T* _v, const solid::ulong _by) { if ((size_t)_v % _by) { return _v + (_by - ((size_t)_v % _by)); } else { return _v; } } template <class T> static T align(T _v, const solid::ulong _by) { if (_v % _by) { return _v + (_by - (_v % _by)); } else { return _v; } } const uint32_t pagesize = memory_page_size(); using FileDeuqeT = std::deque<FileDevice>; struct Context { Context() : readsz(4 * pagesize) , bf(new char[readsz + pagesize]) , buf(align(bf, pagesize)) { } ~Context() { delete[] bf; } const solid::ulong readsz; char* bf; char* buf; }; } //namespace int main(int argc, char* argv[]) { if (argc != 4) { cout << "./file_open_pool /path/to/folder file-count folder-count" << endl; return 0; } //char c; char name[1024]; int filecnt = atoi(argv[2]); int foldercnt = atoi(argv[3]); sprintf(name, "%s", argv[1]); char* fldname = name + strlen(argv[1]); char* fname = name + strlen(argv[1]) + 1 + 8; FileDeuqeT fdq; int cnt = 0; uint64_t totsz = 0; for (int i = foldercnt; i; --i) { sprintf(fldname, "/%08u", i); *fname = 0; for (int j = filecnt; j; --j) { sprintf(fname, "/%08u.txt", j); ++cnt; fdq.push_back(FileDevice()); if (fdq.back().open(name, FileDevice::ReadWriteE)) { cout << "error " << strerror(errno) << " " << cnt << endl; cout << "failed to open file " << name << endl; return 0; } else { //cout<<"name = "<<name<<" size = "<<fdq.back().size()<<endl; totsz += fdq.back().size(); } } } cout << "fdq size = " << fdq.size() << " total size " << totsz << endl; //return 0; using WorkPoolT = lockfree::WorkPool<FileDevice*, void>; WorkPoolT wp{ solid::WorkPoolConfiguration(), [](FileDevice* _pfile, Context&& _rctx) { int64_t sz = _pfile->size(); int toread; int cnt = 0; while (sz > 0) { toread = _rctx.readsz; if (toread > sz) toread = sz; int rv = _pfile->read(_rctx.buf, toread); cnt += rv; sz -= rv; } }, Context()}; for (FileDeuqeT::iterator it(fdq.begin()); it != fdq.end(); ++it) { wp.push(&(*it)); } return 0; }
25.449612
89
0.514164
vipalade
ef7f0690cdac31e0b181d7b47cd523a24ff4fa05
1,087
cpp
C++
kernel/tty/kerneloutputdevice.cpp
Bunogi/bunos
52e55d16938c87d45aa148c18d3bf389f2067445
[ "BSD-3-Clause" ]
null
null
null
kernel/tty/kerneloutputdevice.cpp
Bunogi/bunos
52e55d16938c87d45aa148c18d3bf389f2067445
[ "BSD-3-Clause" ]
null
null
null
kernel/tty/kerneloutputdevice.cpp
Bunogi/bunos
52e55d16938c87d45aa148c18d3bf389f2067445
[ "BSD-3-Clause" ]
null
null
null
#include <bustd/stringview.hpp> #include <kernel/interrupts.hpp> #include <kernel/tty/kerneloutputdevice.hpp> namespace kernel::tty { KernelOutputDevice::KernelOutputDevice(x86::tty::Vga &&vga) : m_vga(bu::move(vga)) {} void KernelOutputDevice::write(const char *buf, const usize length) { if (s_m_lock.is_locked() && interrupts::is_in_isr()) { // Backup solution. If this rolls over, we lose data. m_interrupt_buffer.write(reinterpret_cast<const u8 *>(buf), length); return; } const auto guard = s_m_lock.lock(); if (!m_interrupt_buffer.is_empty()) { // flush interrupt buffer bu::StringView s1, s2; ASSERT(m_interrupt_buffer.read_nocopy(s1, s2)); m_vga.write(s1.data(), s1.len()); m_vga.write(s2.data(), s2.len()); m_serial.write(s1.data(), s1.len()); m_serial.write(s2.data(), s2.len()); m_interrupt_buffer.clear(); } m_vga.write(buf, length); m_serial.write(buf, length); } void KernelOutputDevice::flush() { m_vga.flush(); m_serial.flush(); } SpinLock KernelOutputDevice::s_m_lock; } // namespace kernel::tty
27.175
72
0.686293
Bunogi
ef7f7edbc30bb01f0314d4d5a6f7cf3ef88d5c6f
122,193
cc
C++
processors/IA32/bochs/cpu/sse.cc
pavel-krivanek/opensmalltalk-vm
694dfe3ed015e16f5b8e9cf17d37e4bdd32bea16
[ "MIT" ]
445
2016-06-30T08:19:11.000Z
2022-03-28T06:09:49.000Z
processors/IA32/bochs/cpu/sse.cc
pavel-krivanek/opensmalltalk-vm
694dfe3ed015e16f5b8e9cf17d37e4bdd32bea16
[ "MIT" ]
439
2016-06-29T20:14:36.000Z
2022-03-17T19:59:58.000Z
processors/IA32/bochs/cpu/sse.cc
pavel-krivanek/opensmalltalk-vm
694dfe3ed015e16f5b8e9cf17d37e4bdd32bea16
[ "MIT" ]
137
2016-07-02T17:32:07.000Z
2022-03-20T11:17:25.000Z
///////////////////////////////////////////////////////////////////////// // $Id: sse.cc,v 1.62 2008/08/11 18:53:23 sshwarts Exp $ ///////////////////////////////////////////////////////////////////////// // // Copyright (c) 2003 Stanislav Shwartsman // Written by Stanislav Shwartsman [sshwarts at sourceforge net] // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // ///////////////////////////////////////////////////////////////////////// #define NEED_CPU_REG_SHORTCUTS 1 #include "bochs.h" #include "cpu.h" #define LOG_THIS BX_CPU_THIS_PTR /* ********************************************** */ /* SSE Integer Operations (128bit MMX extensions) */ /* ********************************************** */ // for 3-byte opcodes #if (BX_SUPPORT_SSE >= 4) || (BX_SUPPORT_SSE >= 3 && BX_SUPPORT_SSE_EXTENSION > 0) /* 66 0F 38 00 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSHUFB_VdqWdq(bxInstruction_c *i) { #if (BX_SUPPORT_SSE >= 4) || (BX_SUPPORT_SSE >= 3 && BX_SUPPORT_SSE_EXTENSION > 0) BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } for(unsigned j=0; j<16; j++) { unsigned mask = op2.xmmubyte(j); if (mask & 0x80) result.xmmubyte(j) = 0; else result.xmmubyte(j) = op1.xmmubyte(mask & 0xf); } BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PSHUFB_VdqWdq: required SSE3E, use --enable-sse and --enable-sse-extension options")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 01 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PHADDW_VdqWdq(bxInstruction_c *i) { #if (BX_SUPPORT_SSE >= 4) || (BX_SUPPORT_SSE >= 3 && BX_SUPPORT_SSE_EXTENSION > 0) BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmm16u(0) = op1.xmm16u(0) + op1.xmm16u(1); result.xmm16u(1) = op1.xmm16u(2) + op1.xmm16u(3); result.xmm16u(2) = op1.xmm16u(4) + op1.xmm16u(5); result.xmm16u(3) = op1.xmm16u(6) + op1.xmm16u(7); result.xmm16u(4) = op2.xmm16u(0) + op2.xmm16u(1); result.xmm16u(5) = op2.xmm16u(2) + op2.xmm16u(3); result.xmm16u(6) = op2.xmm16u(4) + op2.xmm16u(5); result.xmm16u(7) = op2.xmm16u(6) + op2.xmm16u(7); BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PHADDW_VdqWdq: required SSE3E, use --enable-sse and --enable-sse-extension options")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 02 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PHADDD_VdqWdq(bxInstruction_c *i) { #if (BX_SUPPORT_SSE >= 4) || (BX_SUPPORT_SSE >= 3 && BX_SUPPORT_SSE_EXTENSION > 0) BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmm32u(0) = op1.xmm32u(0) + op1.xmm32u(1); result.xmm32u(1) = op1.xmm32u(2) + op1.xmm32u(3); result.xmm32u(2) = op2.xmm32u(0) + op2.xmm32u(1); result.xmm32u(3) = op2.xmm32u(2) + op2.xmm32u(3); BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PHADDD_VdqWdq: required SSE3E, use --enable-sse and --enable-sse-extension options")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 03 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PHADDSW_VdqWdq(bxInstruction_c *i) { #if (BX_SUPPORT_SSE >= 4) || (BX_SUPPORT_SSE >= 3 && BX_SUPPORT_SSE_EXTENSION > 0) BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmm16s(0) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(0)) + Bit32s(op1.xmm16s(1))); result.xmm16s(1) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(2)) + Bit32s(op1.xmm16s(3))); result.xmm16s(2) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(4)) + Bit32s(op1.xmm16s(5))); result.xmm16s(3) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(6)) + Bit32s(op1.xmm16s(7))); result.xmm16s(4) = SaturateDwordSToWordS(Bit32s(op2.xmm16s(0)) + Bit32s(op2.xmm16s(1))); result.xmm16s(5) = SaturateDwordSToWordS(Bit32s(op2.xmm16s(2)) + Bit32s(op2.xmm16s(3))); result.xmm16s(6) = SaturateDwordSToWordS(Bit32s(op2.xmm16s(4)) + Bit32s(op2.xmm16s(5))); result.xmm16s(7) = SaturateDwordSToWordS(Bit32s(op2.xmm16s(6)) + Bit32s(op2.xmm16s(7))); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PHADDSW_VdqWdq: required SSE3E, use --enable-sse and --enable-sse-extension options")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 04 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PMADDUBSW_VdqWdq(bxInstruction_c *i) { #if (BX_SUPPORT_SSE >= 4) || (BX_SUPPORT_SSE >= 3 && BX_SUPPORT_SSE_EXTENSION > 0) BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } for(unsigned j=0; j<8; j++) { Bit32s temp = Bit32s(op1.xmmubyte(j*2+0))*Bit32s(op2.xmmsbyte(j*2+0)) + Bit32s(op1.xmmubyte(j*2+1))*Bit32s(op2.xmmsbyte(j*2+1)); result.xmm16s(j) = SaturateDwordSToWordS(temp); } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PMADDUBSW_VdqWdq: required SSE3E, use --enable-sse and --enable-sse-extension options")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 05 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PHSUBSW_VdqWdq(bxInstruction_c *i) { #if (BX_SUPPORT_SSE >= 4) || (BX_SUPPORT_SSE >= 3 && BX_SUPPORT_SSE_EXTENSION > 0) BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmm16s(0) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(0)) - Bit32s(op1.xmm16s(1))); result.xmm16s(1) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(2)) - Bit32s(op1.xmm16s(3))); result.xmm16s(2) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(4)) - Bit32s(op1.xmm16s(5))); result.xmm16s(3) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(6)) - Bit32s(op1.xmm16s(7))); result.xmm16s(4) = SaturateDwordSToWordS(Bit32s(op2.xmm16s(0)) - Bit32s(op2.xmm16s(1))); result.xmm16s(5) = SaturateDwordSToWordS(Bit32s(op2.xmm16s(2)) - Bit32s(op2.xmm16s(3))); result.xmm16s(6) = SaturateDwordSToWordS(Bit32s(op2.xmm16s(4)) - Bit32s(op2.xmm16s(5))); result.xmm16s(7) = SaturateDwordSToWordS(Bit32s(op2.xmm16s(6)) - Bit32s(op2.xmm16s(7))); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PHSUBSW_VdqWdq: required SSE3E, use --enable-sse and --enable-sse-extension options")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 05 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PHSUBW_VdqWdq(bxInstruction_c *i) { #if (BX_SUPPORT_SSE >= 4) || (BX_SUPPORT_SSE >= 3 && BX_SUPPORT_SSE_EXTENSION > 0) BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmm16u(0) = op1.xmm16u(0) - op1.xmm16u(1); result.xmm16u(1) = op1.xmm16u(2) - op1.xmm16u(3); result.xmm16u(2) = op1.xmm16u(4) - op1.xmm16u(5); result.xmm16u(3) = op1.xmm16u(6) - op1.xmm16u(7); result.xmm16u(4) = op2.xmm16u(0) - op2.xmm16u(1); result.xmm16u(5) = op2.xmm16u(2) - op2.xmm16u(3); result.xmm16u(6) = op2.xmm16u(4) - op2.xmm16u(5); result.xmm16u(7) = op2.xmm16u(6) - op2.xmm16u(7); BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PHSUBW_VdqWdq: required SSE3E, use --enable-sse and --enable-sse-extension options")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 06 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PHSUBD_VdqWdq(bxInstruction_c *i) { #if (BX_SUPPORT_SSE >= 4) || (BX_SUPPORT_SSE >= 3 && BX_SUPPORT_SSE_EXTENSION > 0) BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmm32u(0) = op1.xmm32u(0) - op1.xmm32u(1); result.xmm32u(1) = op1.xmm32u(2) - op1.xmm32u(3); result.xmm32u(2) = op2.xmm32u(0) - op2.xmm32u(1); result.xmm32u(3) = op2.xmm32u(2) - op2.xmm32u(3); BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PHSUBD_VdqWdq: required SSE3E, use --enable-sse and --enable-sse-extension options")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 08 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSIGNB_VdqWdq(bxInstruction_c *i) { #if (BX_SUPPORT_SSE >= 4) || (BX_SUPPORT_SSE >= 3 && BX_SUPPORT_SSE_EXTENSION > 0) BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } for(unsigned j=0; j<16; j++) { int sign = (op2.xmmsbyte(j) > 0) - (op2.xmmsbyte(j) < 0); op1.xmmsbyte(j) *= sign; } BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PSIGNB_VdqWdq: required SSE3E, use --enable-sse and --enable-sse-extension options")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 09 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSIGNW_VdqWdq(bxInstruction_c *i) { #if (BX_SUPPORT_SSE >= 4) || (BX_SUPPORT_SSE >= 3 && BX_SUPPORT_SSE_EXTENSION > 0) BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } for(unsigned j=0; j<8; j++) { int sign = (op2.xmm16s(j) > 0) - (op2.xmm16s(j) < 0); op1.xmm16s(j) *= sign; } BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PSIGNW_VdqWdq: required SSE3E, use --enable-sse and --enable-sse-extension options")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 0A */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSIGND_VdqWdq(bxInstruction_c *i) { #if (BX_SUPPORT_SSE >= 4) || (BX_SUPPORT_SSE >= 3 && BX_SUPPORT_SSE_EXTENSION > 0) BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } for(unsigned j=0; j<4; j++) { int sign = (op2.xmm32s(j) > 0) - (op2.xmm32s(j) < 0); op1.xmm32s(j) *= sign; } BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PSIGND_VdqWdq: required SSE3E, use --enable-sse and --enable-sse-extension options")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 0B */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PMULHRSW_VdqWdq(bxInstruction_c *i) { #if (BX_SUPPORT_SSE >= 4) || (BX_SUPPORT_SSE >= 3 && BX_SUPPORT_SSE_EXTENSION > 0) BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm16u(0) = (((op1.xmm16s(0) * op2.xmm16s(0)) >> 14) + 1) >> 1; op1.xmm16u(1) = (((op1.xmm16s(1) * op2.xmm16s(1)) >> 14) + 1) >> 1; op1.xmm16u(2) = (((op1.xmm16s(2) * op2.xmm16s(2)) >> 14) + 1) >> 1; op1.xmm16u(3) = (((op1.xmm16s(3) * op2.xmm16s(3)) >> 14) + 1) >> 1; op1.xmm16u(4) = (((op1.xmm16s(4) * op2.xmm16s(4)) >> 14) + 1) >> 1; op1.xmm16u(5) = (((op1.xmm16s(5) * op2.xmm16s(5)) >> 14) + 1) >> 1; op1.xmm16u(6) = (((op1.xmm16s(6) * op2.xmm16s(6)) >> 14) + 1) >> 1; op1.xmm16u(7) = (((op1.xmm16s(7) * op2.xmm16s(7)) >> 14) + 1) >> 1; /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PMULHRSW_VdqWdq: required SSE3E, use --enable-sse and --enable-sse-extension options")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 1C */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PABSB_VdqWdq(bxInstruction_c *i) { #if (BX_SUPPORT_SSE >= 4) || (BX_SUPPORT_SSE >= 3 && BX_SUPPORT_SSE_EXTENSION > 0) BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op; if (i->modC0()) { op = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op); } if(op.xmmsbyte(0x0) < 0) op.xmmubyte(0x0) = -op.xmmsbyte(0x0); if(op.xmmsbyte(0x1) < 0) op.xmmubyte(0x1) = -op.xmmsbyte(0x1); if(op.xmmsbyte(0x2) < 0) op.xmmubyte(0x2) = -op.xmmsbyte(0x2); if(op.xmmsbyte(0x3) < 0) op.xmmubyte(0x3) = -op.xmmsbyte(0x3); if(op.xmmsbyte(0x4) < 0) op.xmmubyte(0x4) = -op.xmmsbyte(0x4); if(op.xmmsbyte(0x5) < 0) op.xmmubyte(0x5) = -op.xmmsbyte(0x5); if(op.xmmsbyte(0x6) < 0) op.xmmubyte(0x6) = -op.xmmsbyte(0x6); if(op.xmmsbyte(0x7) < 0) op.xmmubyte(0x7) = -op.xmmsbyte(0x7); if(op.xmmsbyte(0x8) < 0) op.xmmubyte(0x8) = -op.xmmsbyte(0x8); if(op.xmmsbyte(0x9) < 0) op.xmmubyte(0x9) = -op.xmmsbyte(0x9); if(op.xmmsbyte(0xa) < 0) op.xmmubyte(0xa) = -op.xmmsbyte(0xa); if(op.xmmsbyte(0xb) < 0) op.xmmubyte(0xb) = -op.xmmsbyte(0xb); if(op.xmmsbyte(0xc) < 0) op.xmmubyte(0xc) = -op.xmmsbyte(0xc); if(op.xmmsbyte(0xd) < 0) op.xmmubyte(0xd) = -op.xmmsbyte(0xd); if(op.xmmsbyte(0xe) < 0) op.xmmubyte(0xe) = -op.xmmsbyte(0xe); if(op.xmmsbyte(0xf) < 0) op.xmmubyte(0xf) = -op.xmmsbyte(0xf); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op); #else BX_INFO(("PABSB_VdqWdq: required SSE3E, use --enable-sse and --enable-sse-extension options")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 1D */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PABSW_VdqWdq(bxInstruction_c *i) { #if (BX_SUPPORT_SSE >= 4) || (BX_SUPPORT_SSE >= 3 && BX_SUPPORT_SSE_EXTENSION > 0) BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op; if (i->modC0()) { op = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op); } if(op.xmm16s(0) < 0) op.xmm16u(0) = -op.xmm16s(0); if(op.xmm16s(1) < 0) op.xmm16u(1) = -op.xmm16s(1); if(op.xmm16s(2) < 0) op.xmm16u(2) = -op.xmm16s(2); if(op.xmm16s(3) < 0) op.xmm16u(3) = -op.xmm16s(3); if(op.xmm16s(4) < 0) op.xmm16u(4) = -op.xmm16s(4); if(op.xmm16s(5) < 0) op.xmm16u(5) = -op.xmm16s(5); if(op.xmm16s(6) < 0) op.xmm16u(6) = -op.xmm16s(6); if(op.xmm16s(7) < 0) op.xmm16u(7) = -op.xmm16s(7); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op); #else BX_INFO(("PABSW_VdqWdq: required SSE3E, use --enable-sse and --enable-sse-extension options")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 1E */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PABSD_VdqWdq(bxInstruction_c *i) { #if (BX_SUPPORT_SSE >= 4) || (BX_SUPPORT_SSE >= 3 && BX_SUPPORT_SSE_EXTENSION > 0) BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op; if (i->modC0()) { op = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op); } if(op.xmm32s(0) < 0) op.xmm32u(0) = -op.xmm32s(0); if(op.xmm32s(1) < 0) op.xmm32u(1) = -op.xmm32s(1); if(op.xmm32s(2) < 0) op.xmm32u(2) = -op.xmm32s(2); if(op.xmm32s(3) < 0) op.xmm32u(3) = -op.xmm32s(3); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op); #else BX_INFO(("PABSD_VdqWdq: required SSE3E, use --enable-sse and --enable-sse-extension options")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 10 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PBLENDVB_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, mask = BX_READ_XMM_REG(0); // XMM0 /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } for(unsigned j=0; j<16; j++) if (mask.xmmubyte(j) & 0x80) op1.xmmubyte(j) = op2.xmmubyte(j); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PBLENDVB_VdqWdq: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 14 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::BLENDVPS_VpsWps(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, mask = BX_READ_XMM_REG(0); // XMM0 /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if (mask.xmm32u(0) & 0x80000000) op1.xmm32u(0) = op2.xmm32u(0); if (mask.xmm32u(1) & 0x80000000) op1.xmm32u(1) = op2.xmm32u(1); if (mask.xmm32u(2) & 0x80000000) op1.xmm32u(2) = op2.xmm32u(2); if (mask.xmm32u(3) & 0x80000000) op1.xmm32u(3) = op2.xmm32u(3); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("BLENDVPS_VpsWps: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 15 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::BLENDVPD_VpdWpd(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, mask = BX_READ_XMM_REG(0); // XMM0 /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if (mask.xmm32u(1) & 0x80000000) op1.xmm64u(0) = op2.xmm64u(0); if (mask.xmm32u(3) & 0x80000000) op1.xmm64u(1) = op2.xmm64u(1); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("BLENDVPD_VpdWpd: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 17 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PTEST_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; unsigned result = 0; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if ((op2.xmm64u(0) & op1.xmm64u(0)) == 0 && (op2.xmm64u(1) & op1.xmm64u(1)) == 0) result |= EFlagsZFMask; if ((op2.xmm64u(0) & ~op1.xmm64u(0)) == 0 && (op2.xmm64u(1) & ~op1.xmm64u(1)) == 0) result |= EFlagsCFMask; setEFlagsOSZAPC(result); #else BX_INFO(("PTEST_VdqWdq: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 28 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PMULDQ_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmm64s(0) = Bit64s(op1.xmm32s(0)) * Bit64s(op2.xmm32s(0)); result.xmm64s(1) = Bit64s(op1.xmm32s(2)) * Bit64s(op2.xmm32s(2)); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PMULDQ_VdqWdq: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 29 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PCMPEQQ_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm64u(0) = (op1.xmm64u(0) == op2.xmm64u(0)) ? BX_CONST64(0xffffffffffffffff) : 0; op1.xmm64u(1) = (op1.xmm64u(1) == op2.xmm64u(1)) ? BX_CONST64(0xffffffffffffffff) : 0; /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PCMPEQQ_VdqWdq: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 2B */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PACKUSDW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmm16u(0) = SaturateDwordSToWordU(op1.xmm32s(0)); result.xmm16u(1) = SaturateDwordSToWordU(op1.xmm32s(1)); result.xmm16u(2) = SaturateDwordSToWordU(op1.xmm32s(2)); result.xmm16u(3) = SaturateDwordSToWordU(op1.xmm32s(3)); result.xmm16u(4) = SaturateDwordSToWordU(op2.xmm32s(0)); result.xmm16u(5) = SaturateDwordSToWordU(op2.xmm32s(1)); result.xmm16u(6) = SaturateDwordSToWordU(op2.xmm32s(2)); result.xmm16u(7) = SaturateDwordSToWordU(op2.xmm32s(3)); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PACKUSDW_VdqWdq: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 37 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PCMPGTQ_VdqWdq(bxInstruction_c *i) { #if (BX_SUPPORT_SSE > 4) || (BX_SUPPORT_SSE >= 4 && BX_SUPPORT_SSE_EXTENSION > 0) BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm64u(0) = (op1.xmm64u(0) > op2.xmm64u(0)) ? BX_CONST64(0xffffffffffffffff) : 0; op1.xmm64u(1) = (op1.xmm64u(1) > op2.xmm64u(1)) ? BX_CONST64(0xffffffffffffffff) : 0; /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PCMPGTQ_VdqWdq: required SSE4.2, use --enable-sse and --enable-sse-extension options")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 38 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PMINSB_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } for(unsigned j=0; j<16; j++) { if(op2.xmmsbyte(j) < op1.xmmsbyte(j)) op1.xmmubyte(j) = op2.xmmubyte(j); } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PMINSB_VdqWdq: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 39 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PMINSD_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if(op2.xmm32s(0) < op1.xmm32s(0)) op1.xmm32u(0) = op2.xmm32u(0); if(op2.xmm32s(1) < op1.xmm32s(1)) op1.xmm32u(1) = op2.xmm32u(1); if(op2.xmm32s(2) < op1.xmm32s(2)) op1.xmm32u(2) = op2.xmm32u(2); if(op2.xmm32s(3) < op1.xmm32s(3)) op1.xmm32u(3) = op2.xmm32u(3); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PMINSD_VdqWdq: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 3A */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PMINUW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if(op2.xmm16u(0) < op1.xmm16u(0)) op1.xmm16u(0) = op2.xmm16u(0); if(op2.xmm16u(1) < op1.xmm16u(1)) op1.xmm16u(1) = op2.xmm16u(1); if(op2.xmm16u(2) < op1.xmm16u(2)) op1.xmm16u(2) = op2.xmm16u(2); if(op2.xmm16u(3) < op1.xmm16u(3)) op1.xmm16u(3) = op2.xmm16u(3); if(op2.xmm16u(4) < op1.xmm16u(4)) op1.xmm16u(4) = op2.xmm16u(4); if(op2.xmm16u(5) < op1.xmm16u(5)) op1.xmm16u(5) = op2.xmm16u(5); if(op2.xmm16u(6) < op1.xmm16u(6)) op1.xmm16u(6) = op2.xmm16u(6); if(op2.xmm16u(7) < op1.xmm16u(7)) op1.xmm16u(7) = op2.xmm16u(7); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PMINUW_VdqWdq: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 3B */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PMINUD_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if(op2.xmm32u(0) < op1.xmm32u(0)) op1.xmm32u(0) = op2.xmm32u(0); if(op2.xmm32u(1) < op1.xmm32u(1)) op1.xmm32u(1) = op2.xmm32u(1); if(op2.xmm32u(2) < op1.xmm32u(2)) op1.xmm32u(2) = op2.xmm32u(2); if(op2.xmm32u(3) < op1.xmm32u(3)) op1.xmm32u(3) = op2.xmm32u(3); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PMINUD_VdqWdq: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 3C */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PMAXSB_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } for(unsigned j=0; j<16; j++) { if(op2.xmmsbyte(j) > op1.xmmsbyte(j)) op1.xmmubyte(j) = op2.xmmubyte(j); } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PMAXSB_VdqWdq: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 3D */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PMAXSD_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if(op2.xmm32s(0) > op1.xmm32s(0)) op1.xmm32u(0) = op2.xmm32u(0); if(op2.xmm32s(1) > op1.xmm32s(1)) op1.xmm32u(1) = op2.xmm32u(1); if(op2.xmm32s(2) > op1.xmm32s(2)) op1.xmm32u(2) = op2.xmm32u(2); if(op2.xmm32s(3) > op1.xmm32s(3)) op1.xmm32u(3) = op2.xmm32u(3); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PMAXSD_VdqWdq: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 3E */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PMAXUW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if(op2.xmm16u(0) > op1.xmm16u(0)) op1.xmm16u(0) = op2.xmm16u(0); if(op2.xmm16u(1) > op1.xmm16u(1)) op1.xmm16u(1) = op2.xmm16u(1); if(op2.xmm16u(2) > op1.xmm16u(2)) op1.xmm16u(2) = op2.xmm16u(2); if(op2.xmm16u(3) > op1.xmm16u(3)) op1.xmm16u(3) = op2.xmm16u(3); if(op2.xmm16u(4) > op1.xmm16u(4)) op1.xmm16u(4) = op2.xmm16u(4); if(op2.xmm16u(5) > op1.xmm16u(5)) op1.xmm16u(5) = op2.xmm16u(5); if(op2.xmm16u(6) > op1.xmm16u(6)) op1.xmm16u(6) = op2.xmm16u(6); if(op2.xmm16u(7) > op1.xmm16u(7)) op1.xmm16u(7) = op2.xmm16u(7); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PMAXUW_VdqWdq: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 3F */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PMAXUD_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if(op2.xmm32u(0) > op1.xmm32u(0)) op1.xmm32u(0) = op2.xmm32u(0); if(op2.xmm32u(1) > op1.xmm32u(1)) op1.xmm32u(1) = op2.xmm32u(1); if(op2.xmm32u(2) > op1.xmm32u(2)) op1.xmm32u(2) = op2.xmm32u(2); if(op2.xmm32u(3) > op1.xmm32u(3)) op1.xmm32u(3) = op2.xmm32u(3); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PMAXUD_VdqWdq: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 40 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PMULLD_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } Bit64s product1 = Bit64s(op1.xmm32s(0)) * Bit64s(op2.xmm32s(0)); Bit64s product2 = Bit64s(op1.xmm32s(1)) * Bit64s(op2.xmm32s(1)); Bit64s product3 = Bit64s(op1.xmm32s(2)) * Bit64s(op2.xmm32s(2)); Bit64s product4 = Bit64s(op1.xmm32s(3)) * Bit64s(op2.xmm32s(3)); op1.xmm32u(0) = (Bit32u)(product1 & 0xFFFFFFFF); op1.xmm32u(1) = (Bit32u)(product2 & 0xFFFFFFFF); op1.xmm32u(2) = (Bit32u)(product3 & 0xFFFFFFFF); op1.xmm32u(3) = (Bit32u)(product4 & 0xFFFFFFFF); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PMULLD_VdqWdq: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 38 41 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PHMINPOSUW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op, result; /* op2 is a register or memory reference */ if (i->modC0()) { op = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op); } unsigned min = 0; for (unsigned j=1; j < 8; j++) { if (op.xmm16u(j) < op.xmm16u(min)) min = j; } result.xmm16u(0) = op.xmm16u(min); result.xmm16u(1) = min; result.xmm32u(1) = 0; result.xmm64u(1) = 0; /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PHMINPOSUW_VdqWdq: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 3A 0C */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::BLENDPS_VpsWpsIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; Bit8u mask = i->Ib(); /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if (mask & 0x1) op1.xmm32u(0) = op2.xmm32u(0); if (mask & 0x2) op1.xmm32u(1) = op2.xmm32u(1); if (mask & 0x4) op1.xmm32u(2) = op2.xmm32u(2); if (mask & 0x8) op1.xmm32u(3) = op2.xmm32u(3); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("BLENDPS_VpsWpsIb: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 3A 0D */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::BLENDPD_VpdWpdIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; Bit8u mask = i->Ib(); /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if (mask & 0x1) op1.xmm64u(0) = op2.xmm64u(0); if (mask & 0x2) op1.xmm64u(1) = op2.xmm64u(1); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("BLENDPD_VpdWpdIb: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 3A 0E */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PBLENDW_VdqWdqIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; Bit8u mask = i->Ib(); /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if (mask & 0x01) op1.xmm16u(0) = op2.xmm16u(0); if (mask & 0x02) op1.xmm16u(1) = op2.xmm16u(1); if (mask & 0x04) op1.xmm16u(2) = op2.xmm16u(2); if (mask & 0x08) op1.xmm16u(3) = op2.xmm16u(3); if (mask & 0x10) op1.xmm16u(4) = op2.xmm16u(4); if (mask & 0x20) op1.xmm16u(5) = op2.xmm16u(5); if (mask & 0x40) op1.xmm16u(6) = op2.xmm16u(6); if (mask & 0x80) op1.xmm16u(7) = op2.xmm16u(7); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PBLENDW_VdqWdqIb: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 3A 14 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PEXTRB_HbdUdqIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op = BX_READ_XMM_REG(i->rm()); Bit8u result = op.xmmubyte(i->Ib() & 0xF); /* result is a register or memory reference */ if (i->modC0()) { BX_WRITE_32BIT_REGZ(i->nnn(), result); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ write_virtual_byte(i->seg(), eaddr, result); } #else BX_INFO(("PEXTRB_HbdUdqIb: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 3A 15 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PEXTRW_HwdUdqIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op = BX_READ_XMM_REG(i->rm()); Bit16u result = op.xmm16u(i->Ib() & 7); /* result is a register or memory reference */ if (i->modC0()) { BX_WRITE_32BIT_REGZ(i->nnn(), result); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ write_virtual_word(i->seg(), eaddr, result); } #else BX_INFO(("PEXTRW_HwdUdqIb: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 3A 16 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PEXTRD_HdUdqIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op = BX_READ_XMM_REG(i->rm()); #if BX_SUPPORT_X86_64 if (i->os64L()) /* 64 bit operand size mode */ { Bit64u result = op.xmm64u(i->Ib() & 1); /* result is a register or memory reference */ if (i->modC0()) { BX_WRITE_64BIT_REG(i->nnn(), result); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ write_virtual_qword_64(i->seg(), eaddr, result); } } else #endif { Bit32u result = op.xmm32u(i->Ib() & 3); /* result is a register or memory reference */ if (i->modC0()) { BX_WRITE_32BIT_REGZ(i->nnn(), result); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ write_virtual_dword(i->seg(), eaddr, result); } } #else BX_INFO(("PEXTRD_HdUdqIb: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 3A 17 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::EXTRACTPS_HdUpsIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op = BX_READ_XMM_REG(i->rm()); Bit32u result = op.xmm32u(i->Ib() & 3); /* result is a register or memory reference */ if (i->modC0()) { BX_WRITE_32BIT_REGZ(i->nnn(), result); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ write_virtual_dword(i->seg(), eaddr, result); } #else BX_INFO(("EXTRACTPS_HdUpsIb: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 3A 20 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PINSRB_VdqEbIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()); Bit8u op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_16BIT_REG(i->rm()); // won't allow reading of AH/CH/BH/DH } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ op2 = read_virtual_byte(i->seg(), eaddr); } op1.xmmubyte(i->Ib() & 0xF) = op2; /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PINSRB_VdqEbIb: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 3A 21 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::INSERTPS_VpsWssIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()); Bit8u control = i->Ib(); Bit32u op2; /* op2 is a register or memory reference */ if (i->modC0()) { BxPackedXmmRegister temp = BX_READ_XMM_REG(i->rm()); op2 = temp.xmm32u((control >> 6) & 3); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ op2 = read_virtual_dword(i->seg(), eaddr); } op1.xmm32u((control >> 4) & 3) = op2; if (control & 1) op1.xmm32u(0) = 0; if (control & 2) op1.xmm32u(1) = 0; if (control & 4) op1.xmm32u(2) = 0; if (control & 8) op1.xmm32u(3) = 0; /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("INSERTPS_VpsWssIb: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 3A 22 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PINSRD_VdqEdIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()); #if BX_SUPPORT_X86_64 if (i->os64L()) /* 64 bit operand size mode */ { Bit64u op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_64BIT_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ op2 = read_virtual_qword_64(i->seg(), eaddr); } op1.xmm64u(i->Ib() & 1) = op2; } else #endif { Bit32u op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_32BIT_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ op2 = read_virtual_dword(i->seg(), eaddr); } op1.xmm32u(i->Ib() & 3) = op2; } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PINSRD_VdqEdIb: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 3A 42 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::MPSADBW_VdqWdqIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 4 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } unsigned src_offset = (i->Ib() & 3) * 4; unsigned dst_offset = ((i->Ib() >> 2) & 1) * 4; for (unsigned j=0; j < 8; j++) { result.xmm16u(j) = 0; for (unsigned k=0; k < 4; k++) { Bit8u temp1 = op1.xmmubyte(j + k + dst_offset); Bit8u temp2 = op2.xmmubyte( k + src_offset); if (temp1 > temp2) result.xmm16u(j) += (temp1 - temp2); else result.xmm16u(j) += (temp2 - temp1); } } BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("MPSADBW_VdqWdqIb: required SSE4, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } #endif // (BX_SUPPORT_SSE >= 4 || (BX_SUPPORT_SSE >= 3 && BX_SUPPORT_SSE_EXTENSION > 0) /* 66 0F 60 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PUNPCKLBW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmmubyte(0x0) = op1.xmmubyte(0); result.xmmubyte(0x1) = op2.xmmubyte(0); result.xmmubyte(0x2) = op1.xmmubyte(1); result.xmmubyte(0x3) = op2.xmmubyte(1); result.xmmubyte(0x4) = op1.xmmubyte(2); result.xmmubyte(0x5) = op2.xmmubyte(2); result.xmmubyte(0x6) = op1.xmmubyte(3); result.xmmubyte(0x7) = op2.xmmubyte(3); result.xmmubyte(0x8) = op1.xmmubyte(4); result.xmmubyte(0x9) = op2.xmmubyte(4); result.xmmubyte(0xA) = op1.xmmubyte(5); result.xmmubyte(0xB) = op2.xmmubyte(5); result.xmmubyte(0xC) = op1.xmmubyte(6); result.xmmubyte(0xD) = op2.xmmubyte(6); result.xmmubyte(0xE) = op1.xmmubyte(7); result.xmmubyte(0xF) = op2.xmmubyte(7); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PUNPCKLBW_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 61 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PUNPCKLWD_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmm16u(0) = op1.xmm16u(0); result.xmm16u(1) = op2.xmm16u(0); result.xmm16u(2) = op1.xmm16u(1); result.xmm16u(3) = op2.xmm16u(1); result.xmm16u(4) = op1.xmm16u(2); result.xmm16u(5) = op2.xmm16u(2); result.xmm16u(6) = op1.xmm16u(3); result.xmm16u(7) = op2.xmm16u(3); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PUNPCKLWD_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* UNPCKLPS: 0F 14 */ /* PUNPCKLDQ: 66 0F 62 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::UNPCKLPS_VpsWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 1 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmm32u(0) = op1.xmm32u(0); result.xmm32u(1) = op2.xmm32u(0); result.xmm32u(2) = op1.xmm32u(1); result.xmm32u(3) = op2.xmm32u(1); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("UNPCKLPS_VpsWdq: required SSE, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 63 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PACKSSWB_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmmsbyte(0x0) = SaturateWordSToByteS(op1.xmm16s(0)); result.xmmsbyte(0x1) = SaturateWordSToByteS(op1.xmm16s(1)); result.xmmsbyte(0x2) = SaturateWordSToByteS(op1.xmm16s(2)); result.xmmsbyte(0x3) = SaturateWordSToByteS(op1.xmm16s(3)); result.xmmsbyte(0x4) = SaturateWordSToByteS(op1.xmm16s(4)); result.xmmsbyte(0x5) = SaturateWordSToByteS(op1.xmm16s(5)); result.xmmsbyte(0x6) = SaturateWordSToByteS(op1.xmm16s(6)); result.xmmsbyte(0x7) = SaturateWordSToByteS(op1.xmm16s(7)); result.xmmsbyte(0x8) = SaturateWordSToByteS(op2.xmm16s(0)); result.xmmsbyte(0x9) = SaturateWordSToByteS(op2.xmm16s(1)); result.xmmsbyte(0xA) = SaturateWordSToByteS(op2.xmm16s(2)); result.xmmsbyte(0xB) = SaturateWordSToByteS(op2.xmm16s(3)); result.xmmsbyte(0xC) = SaturateWordSToByteS(op2.xmm16s(4)); result.xmmsbyte(0xD) = SaturateWordSToByteS(op2.xmm16s(5)); result.xmmsbyte(0xE) = SaturateWordSToByteS(op2.xmm16s(6)); result.xmmsbyte(0xF) = SaturateWordSToByteS(op2.xmm16s(7)); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PACKSSWB_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 64 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PCMPGTB_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } for(unsigned j=0; j<16; j++) { op1.xmmubyte(j) = (op1.xmmsbyte(j) > op2.xmmsbyte(j)) ? 0xff : 0; } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PCMPGTB_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 65 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PCMPGTW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm16u(0) = (op1.xmm16s(0) > op2.xmm16s(0)) ? 0xffff : 0; op1.xmm16u(1) = (op1.xmm16s(1) > op2.xmm16s(1)) ? 0xffff : 0; op1.xmm16u(2) = (op1.xmm16s(2) > op2.xmm16s(2)) ? 0xffff : 0; op1.xmm16u(3) = (op1.xmm16s(3) > op2.xmm16s(3)) ? 0xffff : 0; op1.xmm16u(4) = (op1.xmm16s(4) > op2.xmm16s(4)) ? 0xffff : 0; op1.xmm16u(5) = (op1.xmm16s(5) > op2.xmm16s(5)) ? 0xffff : 0; op1.xmm16u(6) = (op1.xmm16s(6) > op2.xmm16s(6)) ? 0xffff : 0; op1.xmm16u(7) = (op1.xmm16s(7) > op2.xmm16s(7)) ? 0xffff : 0; /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PCMPGTW_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 66 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PCMPGTD_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm32u(0) = (op1.xmm32s(0) > op2.xmm32s(0)) ? 0xffffffff : 0; op1.xmm32u(1) = (op1.xmm32s(1) > op2.xmm32s(1)) ? 0xffffffff : 0; op1.xmm32u(2) = (op1.xmm32s(2) > op2.xmm32s(2)) ? 0xffffffff : 0; op1.xmm32u(3) = (op1.xmm32s(3) > op2.xmm32s(3)) ? 0xffffffff : 0; /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PCMPGTD_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 67 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PACKUSWB_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmmubyte(0x0) = SaturateWordSToByteU(op1.xmm16s(0)); result.xmmubyte(0x1) = SaturateWordSToByteU(op1.xmm16s(1)); result.xmmubyte(0x2) = SaturateWordSToByteU(op1.xmm16s(2)); result.xmmubyte(0x3) = SaturateWordSToByteU(op1.xmm16s(3)); result.xmmubyte(0x4) = SaturateWordSToByteU(op1.xmm16s(4)); result.xmmubyte(0x5) = SaturateWordSToByteU(op1.xmm16s(5)); result.xmmubyte(0x6) = SaturateWordSToByteU(op1.xmm16s(6)); result.xmmubyte(0x7) = SaturateWordSToByteU(op1.xmm16s(7)); result.xmmubyte(0x8) = SaturateWordSToByteU(op2.xmm16s(0)); result.xmmubyte(0x9) = SaturateWordSToByteU(op2.xmm16s(1)); result.xmmubyte(0xA) = SaturateWordSToByteU(op2.xmm16s(2)); result.xmmubyte(0xB) = SaturateWordSToByteU(op2.xmm16s(3)); result.xmmubyte(0xC) = SaturateWordSToByteU(op2.xmm16s(4)); result.xmmubyte(0xD) = SaturateWordSToByteU(op2.xmm16s(5)); result.xmmubyte(0xE) = SaturateWordSToByteU(op2.xmm16s(6)); result.xmmubyte(0xF) = SaturateWordSToByteU(op2.xmm16s(7)); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PACKUSWB_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 68 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PUNPCKHBW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmmubyte(0x0) = op1.xmmubyte(0x8); result.xmmubyte(0x1) = op2.xmmubyte(0x8); result.xmmubyte(0x2) = op1.xmmubyte(0x9); result.xmmubyte(0x3) = op2.xmmubyte(0x9); result.xmmubyte(0x4) = op1.xmmubyte(0xA); result.xmmubyte(0x5) = op2.xmmubyte(0xA); result.xmmubyte(0x6) = op1.xmmubyte(0xB); result.xmmubyte(0x7) = op2.xmmubyte(0xB); result.xmmubyte(0x8) = op1.xmmubyte(0xC); result.xmmubyte(0x9) = op2.xmmubyte(0xC); result.xmmubyte(0xA) = op1.xmmubyte(0xD); result.xmmubyte(0xB) = op2.xmmubyte(0xD); result.xmmubyte(0xC) = op1.xmmubyte(0xE); result.xmmubyte(0xD) = op2.xmmubyte(0xE); result.xmmubyte(0xE) = op1.xmmubyte(0xF); result.xmmubyte(0xF) = op2.xmmubyte(0xF); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PUNPCKHBW_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 69 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PUNPCKHWD_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmm16u(0) = op1.xmm16u(4); result.xmm16u(1) = op2.xmm16u(4); result.xmm16u(2) = op1.xmm16u(5); result.xmm16u(3) = op2.xmm16u(5); result.xmm16u(4) = op1.xmm16u(6); result.xmm16u(5) = op2.xmm16u(6); result.xmm16u(6) = op1.xmm16u(7); result.xmm16u(7) = op2.xmm16u(7); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PUNPCKHWD_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* UNPCKHPS: 0F 15 */ /* PUNPCKHDQ: 66 0F 6A */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::UNPCKHPS_VpsWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 1 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmm32u(0) = op1.xmm32u(2); result.xmm32u(1) = op2.xmm32u(2); result.xmm32u(2) = op1.xmm32u(3); result.xmm32u(3) = op2.xmm32u(3); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("UNPCKHPS_VpsWdq: required SSE, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 6B */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PACKSSDW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmm16s(0) = SaturateDwordSToWordS(op1.xmm32s(0)); result.xmm16s(1) = SaturateDwordSToWordS(op1.xmm32s(1)); result.xmm16s(2) = SaturateDwordSToWordS(op1.xmm32s(2)); result.xmm16s(3) = SaturateDwordSToWordS(op1.xmm32s(3)); result.xmm16s(4) = SaturateDwordSToWordS(op2.xmm32s(0)); result.xmm16s(5) = SaturateDwordSToWordS(op2.xmm32s(1)); result.xmm16s(6) = SaturateDwordSToWordS(op2.xmm32s(2)); result.xmm16s(7) = SaturateDwordSToWordS(op2.xmm32s(3)); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PACKSSDW_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* UNPCKLPD: 66 0F 14 */ /* PUNPCKLQDQ: 66 0F 6C */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PUNPCKLQDQ_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm64u(1) = op2.xmm64u(0); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PUNPCKLQDQ_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* UNPCKHPD: 66 0F 15 */ /* PUNPCKHQDQ: 66 0F 6D */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PUNPCKHQDQ_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmm64u(0) = op1.xmm64u(1); result.xmm64u(1) = op2.xmm64u(1); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PUNPCKHQDQ_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 70 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSHUFD_VdqWdqIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op, result; Bit8u order = i->Ib(); /* op is a register or memory reference */ if (i->modC0()) { op = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op); } result.xmm32u(0) = op.xmm32u((order >> 0) & 0x3); result.xmm32u(1) = op.xmm32u((order >> 2) & 0x3); result.xmm32u(2) = op.xmm32u((order >> 4) & 0x3); result.xmm32u(3) = op.xmm32u((order >> 6) & 0x3); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PSHUFD_VdqWdqIb: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* F2 0F 70 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSHUFHW_VdqWdqIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op, result; Bit8u order = i->Ib(); /* op is a register or memory reference */ if (i->modC0()) { op = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op); } result.xmm64u(0) = op.xmm64u(0); result.xmm16u(4) = op.xmm16u(4 + ((order >> 0) & 0x3)); result.xmm16u(5) = op.xmm16u(4 + ((order >> 2) & 0x3)); result.xmm16u(6) = op.xmm16u(4 + ((order >> 4) & 0x3)); result.xmm16u(7) = op.xmm16u(4 + ((order >> 6) & 0x3)); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PSHUFHW_VdqWdqIb: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* F3 0F 70 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSHUFLW_VdqWdqIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op, result; Bit8u order = i->Ib(); /* op is a register or memory reference */ if (i->modC0()) { op = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op); } result.xmm16u(0) = op.xmm16u((order >> 0) & 0x3); result.xmm16u(1) = op.xmm16u((order >> 2) & 0x3); result.xmm16u(2) = op.xmm16u((order >> 4) & 0x3); result.xmm16u(3) = op.xmm16u((order >> 6) & 0x3); result.xmm64u(1) = op.xmm64u(1); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PSHUFLW_VdqWdqIb: required SSE, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 74 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PCMPEQB_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } for(unsigned j=0; j<16; j++) { op1.xmmubyte(j) = (op1.xmmubyte(j) == op2.xmmubyte(j)) ? 0xff : 0; } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PCMPEQB_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 75 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PCMPEQW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm16u(0) = (op1.xmm16u(0) == op2.xmm16u(0)) ? 0xffff : 0; op1.xmm16u(1) = (op1.xmm16u(1) == op2.xmm16u(1)) ? 0xffff : 0; op1.xmm16u(2) = (op1.xmm16u(2) == op2.xmm16u(2)) ? 0xffff : 0; op1.xmm16u(3) = (op1.xmm16u(3) == op2.xmm16u(3)) ? 0xffff : 0; op1.xmm16u(4) = (op1.xmm16u(4) == op2.xmm16u(4)) ? 0xffff : 0; op1.xmm16u(5) = (op1.xmm16u(5) == op2.xmm16u(5)) ? 0xffff : 0; op1.xmm16u(6) = (op1.xmm16u(6) == op2.xmm16u(6)) ? 0xffff : 0; op1.xmm16u(7) = (op1.xmm16u(7) == op2.xmm16u(7)) ? 0xffff : 0; /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PCMPEQW_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 76 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PCMPEQD_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm32u(0) = (op1.xmm32u(0) == op2.xmm32u(0)) ? 0xffffffff : 0; op1.xmm32u(1) = (op1.xmm32u(1) == op2.xmm32u(1)) ? 0xffffffff : 0; op1.xmm32u(2) = (op1.xmm32u(2) == op2.xmm32u(2)) ? 0xffffffff : 0; op1.xmm32u(3) = (op1.xmm32u(3) == op2.xmm32u(3)) ? 0xffffffff : 0; /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PCMPEQD_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F C4 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PINSRW_VdqEwIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()); Bit16u op2; Bit8u count = i->Ib() & 0x7; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_16BIT_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ op2 = read_virtual_word(i->seg(), eaddr); } op1.xmm16u(count) = op2; /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PINSRW_VdqEdIb: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F C5 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PEXTRW_GdUdqIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op = BX_READ_XMM_REG(i->rm()); Bit8u count = i->Ib() & 0x7; Bit32u result = (Bit32u) op.xmm16u(count); BX_WRITE_32BIT_REGZ(i->nnn(), result); #else BX_INFO(("PEXTRW_GdUdqIb: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 0F C6 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::SHUFPS_VpsWpsIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 1 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; Bit8u order = i->Ib(); /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmm32u(0) = op1.xmm32u((order >> 0) & 0x3); result.xmm32u(1) = op1.xmm32u((order >> 2) & 0x3); result.xmm32u(2) = op2.xmm32u((order >> 4) & 0x3); result.xmm32u(3) = op2.xmm32u((order >> 6) & 0x3); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("SHUFPS_VpsWpsIb: required SSE, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F C6 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::SHUFPD_VpdWpdIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; Bit8u order = i->Ib(); /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmm64u(0) = op1.xmm64u((order >> 0) & 0x1); result.xmm64u(1) = op2.xmm64u((order >> 1) & 0x1); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("SHUFPD_VpdWpdIb: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F D1 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSRLW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if(op2.xmm64u(0) > 15) /* looking only to low 64 bits */ { op1.xmm64u(0) = 0; op1.xmm64u(1) = 0; } else { Bit8u shift = op2.xmmubyte(0); op1.xmm16u(0) >>= shift; op1.xmm16u(1) >>= shift; op1.xmm16u(2) >>= shift; op1.xmm16u(3) >>= shift; op1.xmm16u(4) >>= shift; op1.xmm16u(5) >>= shift; op1.xmm16u(6) >>= shift; op1.xmm16u(7) >>= shift; } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PSRLW_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F D2 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSRLD_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if(op2.xmm64u(0) > 31) /* looking only to low 64 bits */ { op1.xmm64u(0) = 0; op1.xmm64u(1) = 0; } else { Bit8u shift = op2.xmmubyte(0); op1.xmm32u(0) >>= shift; op1.xmm32u(1) >>= shift; op1.xmm32u(2) >>= shift; op1.xmm32u(3) >>= shift; } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PSRLD_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F D3 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSRLQ_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if(op2.xmm64u(0) > 63) /* looking only to low 64 bits */ { op1.xmm64u(0) = 0; op1.xmm64u(1) = 0; } else { Bit8u shift = op2.xmmubyte(0); op1.xmm64u(0) >>= shift; op1.xmm64u(1) >>= shift; } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PSRLQ_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F D4 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PADDQ_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm64u(0) += op2.xmm64u(0); op1.xmm64u(1) += op2.xmm64u(1); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PADDQ_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F D5 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PMULLW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } Bit32u product1 = Bit32u(op1.xmm16u(0)) * Bit32u(op2.xmm16u(0)); Bit32u product2 = Bit32u(op1.xmm16u(1)) * Bit32u(op2.xmm16u(1)); Bit32u product3 = Bit32u(op1.xmm16u(2)) * Bit32u(op2.xmm16u(2)); Bit32u product4 = Bit32u(op1.xmm16u(3)) * Bit32u(op2.xmm16u(3)); Bit32u product5 = Bit32u(op1.xmm16u(4)) * Bit32u(op2.xmm16u(4)); Bit32u product6 = Bit32u(op1.xmm16u(5)) * Bit32u(op2.xmm16u(5)); Bit32u product7 = Bit32u(op1.xmm16u(6)) * Bit32u(op2.xmm16u(6)); Bit32u product8 = Bit32u(op1.xmm16u(7)) * Bit32u(op2.xmm16u(7)); op1.xmm16u(0) = product1 & 0xffff; op1.xmm16u(1) = product2 & 0xffff; op1.xmm16u(2) = product3 & 0xffff; op1.xmm16u(3) = product4 & 0xffff; op1.xmm16u(4) = product5 & 0xffff; op1.xmm16u(5) = product6 & 0xffff; op1.xmm16u(6) = product7 & 0xffff; op1.xmm16u(7) = product8 & 0xffff; /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PMULLW_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F D8 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSUBUSB_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmm64u(0) = result.xmm64u(1) = 0; for(unsigned j=0; j<16; j++) { if(op1.xmmubyte(j) > op2.xmmubyte(j)) { result.xmmubyte(j) = op1.xmmubyte(j) - op2.xmmubyte(j); } } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PSUBUSB_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F D9 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSUBUSW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmm64u(0) = result.xmm64u(1) = 0; for(unsigned j=0; j<8; j++) { if(op1.xmm16u(j) > op2.xmm16u(j)) { result.xmm16u(j) = op1.xmm16u(j) - op2.xmm16u(j); } } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PSUBUSW_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F DA */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PMINUB_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } for(unsigned j=0; j<16; j++) { if(op2.xmmubyte(j) < op1.xmmubyte(j)) op1.xmmubyte(j) = op2.xmmubyte(j); } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PMINUB_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* ANDPS: 0F 54 */ /* ANDPD: 66 0F 54 */ /* PAND: 66 0F DB */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::ANDPS_VpsWps(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 1 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm64u(0) &= op2.xmm64u(0); op1.xmm64u(1) &= op2.xmm64u(1); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("ANDPS_VpsWps: required SSE, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F DC */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PADDUSB_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } for(unsigned j=0; j<16; j++) { op1.xmmubyte(j) = SaturateWordSToByteU(Bit16s(op1.xmmubyte(j)) + Bit16s(op2.xmmubyte(j))); } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PADDUSB_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F DD */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PADDUSW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm16u(0) = SaturateDwordSToWordU(Bit32s(op1.xmm16u(0)) + Bit32s(op2.xmm16u(0))); op1.xmm16u(1) = SaturateDwordSToWordU(Bit32s(op1.xmm16u(1)) + Bit32s(op2.xmm16u(1))); op1.xmm16u(2) = SaturateDwordSToWordU(Bit32s(op1.xmm16u(2)) + Bit32s(op2.xmm16u(2))); op1.xmm16u(3) = SaturateDwordSToWordU(Bit32s(op1.xmm16u(3)) + Bit32s(op2.xmm16u(3))); op1.xmm16u(4) = SaturateDwordSToWordU(Bit32s(op1.xmm16u(4)) + Bit32s(op2.xmm16u(4))); op1.xmm16u(5) = SaturateDwordSToWordU(Bit32s(op1.xmm16u(5)) + Bit32s(op2.xmm16u(5))); op1.xmm16u(6) = SaturateDwordSToWordU(Bit32s(op1.xmm16u(6)) + Bit32s(op2.xmm16u(6))); op1.xmm16u(7) = SaturateDwordSToWordU(Bit32s(op1.xmm16u(7)) + Bit32s(op2.xmm16u(7))); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PADDUSW_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F DE */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PMAXUB_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } for(unsigned j=0; j<16; j++) { if(op2.xmmubyte(j) > op1.xmmubyte(j)) op1.xmmubyte(j) = op2.xmmubyte(j); } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PMAXUB_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* ANDNPS: 0F 55 */ /* ANDNPD: 66 0F 55 */ /* PANDN: 66 0F DF */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::ANDNPS_VpsWps(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 1 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm64u(0) = ~(op1.xmm64u(0)) & op2.xmm64u(0); op1.xmm64u(1) = ~(op1.xmm64u(1)) & op2.xmm64u(1); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("ANDNPS_VpsWps: required SSE, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F E0 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PAVGB_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } for(unsigned j=0; j<16; j++) { op1.xmmubyte(j) = (op1.xmmubyte(j) + op2.xmmubyte(j) + 1) >> 1; } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PAVGB_VdqWdq: required SSE, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F E1 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSRAW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if(op2.xmm64u(0) == 0) return; if(op2.xmm64u(0) > 15) /* looking only to low 64 bits */ { result.xmm16u(0) = (op1.xmm16u(0) & 0x8000) ? 0xffff : 0; result.xmm16u(1) = (op1.xmm16u(1) & 0x8000) ? 0xffff : 0; result.xmm16u(2) = (op1.xmm16u(2) & 0x8000) ? 0xffff : 0; result.xmm16u(3) = (op1.xmm16u(3) & 0x8000) ? 0xffff : 0; result.xmm16u(4) = (op1.xmm16u(4) & 0x8000) ? 0xffff : 0; result.xmm16u(5) = (op1.xmm16u(5) & 0x8000) ? 0xffff : 0; result.xmm16u(6) = (op1.xmm16u(6) & 0x8000) ? 0xffff : 0; result.xmm16u(7) = (op1.xmm16u(7) & 0x8000) ? 0xffff : 0; } else { Bit8u shift = op2.xmmubyte(0); result.xmm16u(0) = op1.xmm16u(0) >> shift; result.xmm16u(1) = op1.xmm16u(1) >> shift; result.xmm16u(2) = op1.xmm16u(2) >> shift; result.xmm16u(3) = op1.xmm16u(3) >> shift; result.xmm16u(4) = op1.xmm16u(4) >> shift; result.xmm16u(5) = op1.xmm16u(5) >> shift; result.xmm16u(6) = op1.xmm16u(6) >> shift; result.xmm16u(7) = op1.xmm16u(7) >> shift; if(op1.xmm16u(0) & 0x8000) result.xmm16u(0) |= (0xffff << (16 - shift)); if(op1.xmm16u(1) & 0x8000) result.xmm16u(1) |= (0xffff << (16 - shift)); if(op1.xmm16u(2) & 0x8000) result.xmm16u(2) |= (0xffff << (16 - shift)); if(op1.xmm16u(3) & 0x8000) result.xmm16u(3) |= (0xffff << (16 - shift)); if(op1.xmm16u(4) & 0x8000) result.xmm16u(4) |= (0xffff << (16 - shift)); if(op1.xmm16u(5) & 0x8000) result.xmm16u(5) |= (0xffff << (16 - shift)); if(op1.xmm16u(6) & 0x8000) result.xmm16u(6) |= (0xffff << (16 - shift)); if(op1.xmm16u(7) & 0x8000) result.xmm16u(7) |= (0xffff << (16 - shift)); } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PSRAW_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F E2 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSRAD_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if(op2.xmm64u(0) == 0) return; if(op2.xmm64u(0) > 31) /* looking only to low 64 bits */ { result.xmm32u(0) = (op1.xmm32u(0) & 0x80000000) ? 0xffffffff : 0; result.xmm32u(1) = (op1.xmm32u(1) & 0x80000000) ? 0xffffffff : 0; result.xmm32u(2) = (op1.xmm32u(2) & 0x80000000) ? 0xffffffff : 0; result.xmm32u(3) = (op1.xmm32u(3) & 0x80000000) ? 0xffffffff : 0; } else { Bit8u shift = op2.xmmubyte(0); result.xmm32u(0) = op1.xmm32u(0) >> shift; result.xmm32u(1) = op1.xmm32u(1) >> shift; result.xmm32u(2) = op1.xmm32u(2) >> shift; result.xmm32u(3) = op1.xmm32u(3) >> shift; if(op1.xmm32u(0) & 0x80000000) result.xmm32u(0) |= (0xffffffff << (32-shift)); if(op1.xmm32u(1) & 0x80000000) result.xmm32u(1) |= (0xffffffff << (32-shift)); if(op1.xmm32u(2) & 0x80000000) result.xmm32u(2) |= (0xffffffff << (32-shift)); if(op1.xmm32u(3) & 0x80000000) result.xmm32u(3) |= (0xffffffff << (32-shift)); } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PSRAD_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F E3 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PAVGW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm16u(0) = (op1.xmm16u(0) + op2.xmm16u(0) + 1) >> 1; op1.xmm16u(1) = (op1.xmm16u(1) + op2.xmm16u(1) + 1) >> 1; op1.xmm16u(2) = (op1.xmm16u(2) + op2.xmm16u(2) + 1) >> 1; op1.xmm16u(3) = (op1.xmm16u(3) + op2.xmm16u(3) + 1) >> 1; op1.xmm16u(4) = (op1.xmm16u(4) + op2.xmm16u(4) + 1) >> 1; op1.xmm16u(5) = (op1.xmm16u(5) + op2.xmm16u(5) + 1) >> 1; op1.xmm16u(6) = (op1.xmm16u(6) + op2.xmm16u(6) + 1) >> 1; op1.xmm16u(7) = (op1.xmm16u(7) + op2.xmm16u(7) + 1) >> 1; /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PAVGW_VdqWdq: required SSE, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F E4 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PMULHUW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } Bit32u product1 = Bit32u(op1.xmm16u(0)) * Bit32u(op2.xmm16u(0)); Bit32u product2 = Bit32u(op1.xmm16u(1)) * Bit32u(op2.xmm16u(1)); Bit32u product3 = Bit32u(op1.xmm16u(2)) * Bit32u(op2.xmm16u(2)); Bit32u product4 = Bit32u(op1.xmm16u(3)) * Bit32u(op2.xmm16u(3)); Bit32u product5 = Bit32u(op1.xmm16u(4)) * Bit32u(op2.xmm16u(4)); Bit32u product6 = Bit32u(op1.xmm16u(5)) * Bit32u(op2.xmm16u(5)); Bit32u product7 = Bit32u(op1.xmm16u(6)) * Bit32u(op2.xmm16u(6)); Bit32u product8 = Bit32u(op1.xmm16u(7)) * Bit32u(op2.xmm16u(7)); op1.xmm16u(0) = (Bit16u)(product1 >> 16); op1.xmm16u(1) = (Bit16u)(product2 >> 16); op1.xmm16u(2) = (Bit16u)(product3 >> 16); op1.xmm16u(3) = (Bit16u)(product4 >> 16); op1.xmm16u(4) = (Bit16u)(product5 >> 16); op1.xmm16u(5) = (Bit16u)(product6 >> 16); op1.xmm16u(6) = (Bit16u)(product7 >> 16); op1.xmm16u(7) = (Bit16u)(product8 >> 16); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PMULHUW_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F E5 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PMULHW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } Bit32s product1 = Bit32s(op1.xmm16s(0)) * Bit32s(op2.xmm16s(0)); Bit32s product2 = Bit32s(op1.xmm16s(1)) * Bit32s(op2.xmm16s(1)); Bit32s product3 = Bit32s(op1.xmm16s(2)) * Bit32s(op2.xmm16s(2)); Bit32s product4 = Bit32s(op1.xmm16s(3)) * Bit32s(op2.xmm16s(3)); Bit32s product5 = Bit32s(op1.xmm16s(4)) * Bit32s(op2.xmm16s(4)); Bit32s product6 = Bit32s(op1.xmm16s(5)) * Bit32s(op2.xmm16s(5)); Bit32s product7 = Bit32s(op1.xmm16s(6)) * Bit32s(op2.xmm16s(6)); Bit32s product8 = Bit32s(op1.xmm16s(7)) * Bit32s(op2.xmm16s(7)); op1.xmm16u(0) = (Bit16u)(product1 >> 16); op1.xmm16u(1) = (Bit16u)(product2 >> 16); op1.xmm16u(2) = (Bit16u)(product3 >> 16); op1.xmm16u(3) = (Bit16u)(product4 >> 16); op1.xmm16u(4) = (Bit16u)(product5 >> 16); op1.xmm16u(5) = (Bit16u)(product6 >> 16); op1.xmm16u(6) = (Bit16u)(product7 >> 16); op1.xmm16u(7) = (Bit16u)(product8 >> 16); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PMULHW_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F E8 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSUBSB_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } for(unsigned j=0; j<16; j++) { op1.xmmsbyte(j) = SaturateWordSToByteS(Bit16s(op1.xmmsbyte(j)) - Bit16s(op2.xmmsbyte(j))); } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PSUBSB_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F E9 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSUBSW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm16s(0) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(0)) - Bit32s(op2.xmm16s(0))); op1.xmm16s(1) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(1)) - Bit32s(op2.xmm16s(1))); op1.xmm16s(2) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(2)) - Bit32s(op2.xmm16s(2))); op1.xmm16s(3) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(3)) - Bit32s(op2.xmm16s(3))); op1.xmm16s(4) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(4)) - Bit32s(op2.xmm16s(4))); op1.xmm16s(5) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(5)) - Bit32s(op2.xmm16s(5))); op1.xmm16s(6) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(6)) - Bit32s(op2.xmm16s(6))); op1.xmm16s(7) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(7)) - Bit32s(op2.xmm16s(7))); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PSUBSW_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F EA */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PMINSW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if(op2.xmm16s(0) < op1.xmm16s(0)) op1.xmm16s(0) = op2.xmm16s(0); if(op2.xmm16s(1) < op1.xmm16s(1)) op1.xmm16s(1) = op2.xmm16s(1); if(op2.xmm16s(2) < op1.xmm16s(2)) op1.xmm16s(2) = op2.xmm16s(2); if(op2.xmm16s(3) < op1.xmm16s(3)) op1.xmm16s(3) = op2.xmm16s(3); if(op2.xmm16s(4) < op1.xmm16s(4)) op1.xmm16s(4) = op2.xmm16s(4); if(op2.xmm16s(5) < op1.xmm16s(5)) op1.xmm16s(5) = op2.xmm16s(5); if(op2.xmm16s(6) < op1.xmm16s(6)) op1.xmm16s(6) = op2.xmm16s(6); if(op2.xmm16s(7) < op1.xmm16s(7)) op1.xmm16s(7) = op2.xmm16s(7); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PMINSW_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* ORPS: 0F 56 */ /* ORPD: 66 0F 56 */ /* POR: 66 0F EB */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::ORPS_VpsWps(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 1 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm64u(0) |= op2.xmm64u(0); op1.xmm64u(1) |= op2.xmm64u(1); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("ORPS_VpsWps: required SSE, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F EC */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PADDSB_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } for(unsigned j=0; j<16; j++) { op1.xmmsbyte(j) = SaturateWordSToByteS(Bit16s(op1.xmmsbyte(j)) + Bit16s(op2.xmmsbyte(j))); } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PADDSB_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F ED */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PADDSW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm16s(0) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(0)) + Bit32s(op2.xmm16s(0))); op1.xmm16s(1) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(1)) + Bit32s(op2.xmm16s(1))); op1.xmm16s(2) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(2)) + Bit32s(op2.xmm16s(2))); op1.xmm16s(3) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(3)) + Bit32s(op2.xmm16s(3))); op1.xmm16s(4) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(4)) + Bit32s(op2.xmm16s(4))); op1.xmm16s(5) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(5)) + Bit32s(op2.xmm16s(5))); op1.xmm16s(6) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(6)) + Bit32s(op2.xmm16s(6))); op1.xmm16s(7) = SaturateDwordSToWordS(Bit32s(op1.xmm16s(7)) + Bit32s(op2.xmm16s(7))); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PADDSW_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F EE */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PMAXSW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if(op2.xmm16s(0) > op1.xmm16s(0)) op1.xmm16s(0) = op2.xmm16s(0); if(op2.xmm16s(1) > op1.xmm16s(1)) op1.xmm16s(1) = op2.xmm16s(1); if(op2.xmm16s(2) > op1.xmm16s(2)) op1.xmm16s(2) = op2.xmm16s(2); if(op2.xmm16s(3) > op1.xmm16s(3)) op1.xmm16s(3) = op2.xmm16s(3); if(op2.xmm16s(4) > op1.xmm16s(4)) op1.xmm16s(4) = op2.xmm16s(4); if(op2.xmm16s(5) > op1.xmm16s(5)) op1.xmm16s(5) = op2.xmm16s(5); if(op2.xmm16s(6) > op1.xmm16s(6)) op1.xmm16s(6) = op2.xmm16s(6); if(op2.xmm16s(7) > op1.xmm16s(7)) op1.xmm16s(7) = op2.xmm16s(7); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PMAXSW_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* XORPS: 0F 57 */ /* XORPD: 66 0F 57 */ /* PXOR: 66 0F EF */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::XORPS_VpsWps(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 1 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm64u(0) ^= op2.xmm64u(0); op1.xmm64u(1) ^= op2.xmm64u(1); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("XORPS_VpsWps: required SSE, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F F1 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSLLW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if(op2.xmm64u(0) > 15) /* looking only to low 64 bits */ { op1.xmm64u(0) = 0; op1.xmm64u(1) = 0; } else { Bit8u shift = op2.xmmubyte(0); op1.xmm16u(0) <<= shift; op1.xmm16u(1) <<= shift; op1.xmm16u(2) <<= shift; op1.xmm16u(3) <<= shift; op1.xmm16u(4) <<= shift; op1.xmm16u(5) <<= shift; op1.xmm16u(6) <<= shift; op1.xmm16u(7) <<= shift; } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PSLLW_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F F2 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSLLD_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if(op2.xmm64u(0) > 31) /* looking only to low 64 bits */ { op1.xmm64u(0) = 0; op1.xmm64u(1) = 0; } else { Bit8u shift = op2.xmmubyte(0); op1.xmm32u(0) <<= shift; op1.xmm32u(1) <<= shift; op1.xmm32u(2) <<= shift; op1.xmm32u(3) <<= shift; } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PSLLD_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F F3 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSLLQ_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } if(op2.xmm64u(0) > 63) /* looking only to low 64 bits */ { op1.xmm64u(0) = 0; op1.xmm64u(1) = 0; } else { Bit8u shift = op2.xmmubyte(0); op1.xmm64u(0) <<= shift; op1.xmm64u(1) <<= shift; } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PSLLQ_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F F4 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PMULUDQ_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } result.xmm64u(0) = Bit64u(op1.xmm32u(0)) * Bit64u(op2.xmm32u(0)); result.xmm64u(1) = Bit64u(op1.xmm32u(2)) * Bit64u(op2.xmm32u(2)); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PMULUDQ_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F F5 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PMADDWD_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } for(unsigned j=0; j<4; j++) { if(op1.xmm32u(j) == 0x80008000 && op2.xmm32u(j) == 0x80008000) { result.xmm32u(j) = 0x80000000; } else { result.xmm32u(j) = Bit32s(op1.xmm16s(2*j+0)) * Bit32s(op2.xmm16s(2*j+0)) + Bit32s(op1.xmm16s(2*j+1)) * Bit32s(op2.xmm16s(2*j+1)); } } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), result); #else BX_INFO(("PMADDWD_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F F6 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSADBW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; Bit16u temp1 = 0, temp2 = 0; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } temp1 += abs(op1.xmmubyte(0x0) - op2.xmmubyte(0x0)); temp1 += abs(op1.xmmubyte(0x1) - op2.xmmubyte(0x1)); temp1 += abs(op1.xmmubyte(0x2) - op2.xmmubyte(0x2)); temp1 += abs(op1.xmmubyte(0x3) - op2.xmmubyte(0x3)); temp1 += abs(op1.xmmubyte(0x4) - op2.xmmubyte(0x4)); temp1 += abs(op1.xmmubyte(0x5) - op2.xmmubyte(0x5)); temp1 += abs(op1.xmmubyte(0x6) - op2.xmmubyte(0x6)); temp1 += abs(op1.xmmubyte(0x7) - op2.xmmubyte(0x7)); temp2 += abs(op1.xmmubyte(0x8) - op2.xmmubyte(0x8)); temp2 += abs(op1.xmmubyte(0x9) - op2.xmmubyte(0x9)); temp2 += abs(op1.xmmubyte(0xA) - op2.xmmubyte(0xA)); temp2 += abs(op1.xmmubyte(0xB) - op2.xmmubyte(0xB)); temp2 += abs(op1.xmmubyte(0xC) - op2.xmmubyte(0xC)); temp2 += abs(op1.xmmubyte(0xD) - op2.xmmubyte(0xD)); temp2 += abs(op1.xmmubyte(0xE) - op2.xmmubyte(0xE)); temp2 += abs(op1.xmmubyte(0xF) - op2.xmmubyte(0xF)); op1.xmm64u(0) = Bit64u(temp1); op1.xmm64u(1) = Bit64u(temp2); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PSADBW_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F F8 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSUBB_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } for(unsigned j=0; j<16; j++) { op1.xmmubyte(j) -= op2.xmmubyte(j); } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PSUBB_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F F9 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSUBW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm16u(0) -= op2.xmm16u(0); op1.xmm16u(1) -= op2.xmm16u(1); op1.xmm16u(2) -= op2.xmm16u(2); op1.xmm16u(3) -= op2.xmm16u(3); op1.xmm16u(4) -= op2.xmm16u(4); op1.xmm16u(5) -= op2.xmm16u(5); op1.xmm16u(6) -= op2.xmm16u(6); op1.xmm16u(7) -= op2.xmm16u(7); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PSUBW_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F FA */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSUBD_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm32u(0) -= op2.xmm32u(0); op1.xmm32u(1) -= op2.xmm32u(1); op1.xmm32u(2) -= op2.xmm32u(2); op1.xmm32u(3) -= op2.xmm32u(3); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PSUBD_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F FB */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSUBQ_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm64u(0) -= op2.xmm64u(0); op1.xmm64u(1) -= op2.xmm64u(1); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PSUBQ_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F FC */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PADDB_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } for(unsigned j=0; j<16; j++) { op1.xmmubyte(j) += op2.xmmubyte(j); } /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PADDB_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F FD */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PADDW_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm16u(0) += op2.xmm16u(0); op1.xmm16u(1) += op2.xmm16u(1); op1.xmm16u(2) += op2.xmm16u(2); op1.xmm16u(3) += op2.xmm16u(3); op1.xmm16u(4) += op2.xmm16u(4); op1.xmm16u(5) += op2.xmm16u(5); op1.xmm16u(6) += op2.xmm16u(6); op1.xmm16u(7) += op2.xmm16u(7); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PADDW_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F FE */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PADDD_VdqWdq(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->nnn()), op2; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_XMM_REG(i->rm()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ readVirtualDQwordAligned(i->seg(), eaddr, (Bit8u *) &op2); } op1.xmm32u(0) += op2.xmm32u(0); op1.xmm32u(1) += op2.xmm32u(1); op1.xmm32u(2) += op2.xmm32u(2); op1.xmm32u(3) += op2.xmm32u(3); /* now write result back to destination */ BX_WRITE_XMM_REG(i->nnn(), op1); #else BX_INFO(("PADDD_VdqWdq: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 71 Grp12 010 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSRLW_UdqIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op = BX_READ_XMM_REG(i->rm()); Bit8u shift = i->Ib(); if(shift > 15) { op.xmm64u(0) = 0; op.xmm64u(1) = 0; } else { op.xmm16u(0) >>= shift; op.xmm16u(1) >>= shift; op.xmm16u(2) >>= shift; op.xmm16u(3) >>= shift; op.xmm16u(4) >>= shift; op.xmm16u(5) >>= shift; op.xmm16u(6) >>= shift; op.xmm16u(7) >>= shift; } /* now write result back to destination */ BX_WRITE_XMM_REG(i->rm(), op); #else BX_INFO(("PSRLW_UdqIb: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 0F 71 Grp12 100 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSRAW_UdqIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op = BX_READ_XMM_REG(i->rm()), result; Bit8u shift = i->Ib(); if(shift == 0) return; if(shift > 15) { result.xmm16u(0) = (op.xmm16u(0) & 0x8000) ? 0xffff : 0; result.xmm16u(1) = (op.xmm16u(1) & 0x8000) ? 0xffff : 0; result.xmm16u(2) = (op.xmm16u(2) & 0x8000) ? 0xffff : 0; result.xmm16u(3) = (op.xmm16u(3) & 0x8000) ? 0xffff : 0; result.xmm16u(4) = (op.xmm16u(4) & 0x8000) ? 0xffff : 0; result.xmm16u(5) = (op.xmm16u(5) & 0x8000) ? 0xffff : 0; result.xmm16u(6) = (op.xmm16u(6) & 0x8000) ? 0xffff : 0; result.xmm16u(7) = (op.xmm16u(7) & 0x8000) ? 0xffff : 0; } else { result.xmm16u(0) = op.xmm16u(0) >> shift; result.xmm16u(1) = op.xmm16u(1) >> shift; result.xmm16u(2) = op.xmm16u(2) >> shift; result.xmm16u(3) = op.xmm16u(3) >> shift; result.xmm16u(4) = op.xmm16u(4) >> shift; result.xmm16u(5) = op.xmm16u(5) >> shift; result.xmm16u(6) = op.xmm16u(6) >> shift; result.xmm16u(7) = op.xmm16u(7) >> shift; if(op.xmm16u(0) & 0x8000) result.xmm16u(0) |= (0xffff << (16 - shift)); if(op.xmm16u(1) & 0x8000) result.xmm16u(1) |= (0xffff << (16 - shift)); if(op.xmm16u(2) & 0x8000) result.xmm16u(2) |= (0xffff << (16 - shift)); if(op.xmm16u(3) & 0x8000) result.xmm16u(3) |= (0xffff << (16 - shift)); if(op.xmm16u(4) & 0x8000) result.xmm16u(4) |= (0xffff << (16 - shift)); if(op.xmm16u(5) & 0x8000) result.xmm16u(5) |= (0xffff << (16 - shift)); if(op.xmm16u(6) & 0x8000) result.xmm16u(6) |= (0xffff << (16 - shift)); if(op.xmm16u(7) & 0x8000) result.xmm16u(7) |= (0xffff << (16 - shift)); } /* now write result back to destination */ BX_WRITE_XMM_REG(i->rm(), result); #else BX_INFO(("PSRAW_UdqIb: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 71 Grp12 110 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSLLW_UdqIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op = BX_READ_XMM_REG(i->rm()); Bit8u shift = i->Ib(); if(shift > 15) { op.xmm64u(0) = 0; op.xmm64u(1) = 0; } else { op.xmm16u(0) <<= shift; op.xmm16u(1) <<= shift; op.xmm16u(2) <<= shift; op.xmm16u(3) <<= shift; op.xmm16u(4) <<= shift; op.xmm16u(5) <<= shift; op.xmm16u(6) <<= shift; op.xmm16u(7) <<= shift; } /* now write result back to destination */ BX_WRITE_XMM_REG(i->rm(), op); #else BX_INFO(("PSLLW_UdqIb: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 72 Grp13 010 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSRLD_UdqIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op = BX_READ_XMM_REG(i->rm()); Bit8u shift = i->Ib(); if(shift > 31) { op.xmm64u(0) = 0; op.xmm64u(1) = 0; } else { op.xmm32u(0) >>= shift; op.xmm32u(1) >>= shift; op.xmm32u(2) >>= shift; op.xmm32u(3) >>= shift; } /* now write result back to destination */ BX_WRITE_XMM_REG(i->rm(), op); #else BX_INFO(("PSRLD_UdqIb: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 0F 72 Grp13 100 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSRAD_UdqIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op = BX_READ_XMM_REG(i->rm()), result; Bit8u shift = i->Ib(); if(shift == 0) return; if(shift > 31) { result.xmm32u(0) = (op.xmm32u(0) & 0x80000000) ? 0xffffffff : 0; result.xmm32u(1) = (op.xmm32u(1) & 0x80000000) ? 0xffffffff : 0; result.xmm32u(2) = (op.xmm32u(2) & 0x80000000) ? 0xffffffff : 0; result.xmm32u(3) = (op.xmm32u(3) & 0x80000000) ? 0xffffffff : 0; } else { result.xmm32u(0) = op.xmm32u(0) >> shift; result.xmm32u(1) = op.xmm32u(1) >> shift; result.xmm32u(2) = op.xmm32u(2) >> shift; result.xmm32u(3) = op.xmm32u(3) >> shift; if(op.xmm32u(0) & 0x80000000) result.xmm32u(0) |= (0xffffffff << (32-shift)); if(op.xmm32u(1) & 0x80000000) result.xmm32u(1) |= (0xffffffff << (32-shift)); if(op.xmm32u(2) & 0x80000000) result.xmm32u(2) |= (0xffffffff << (32-shift)); if(op.xmm32u(3) & 0x80000000) result.xmm32u(3) |= (0xffffffff << (32-shift)); } /* now write result back to destination */ BX_WRITE_XMM_REG(i->rm(), result); #else BX_INFO(("PSRAD_UdqIb: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 72 Grp13 110 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSLLD_UdqIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op = BX_READ_XMM_REG(i->rm()); Bit8u shift = i->Ib(); if(shift > 31) { op.xmm64u(0) = 0; op.xmm64u(1) = 0; } else { op.xmm32u(0) <<= shift; op.xmm32u(1) <<= shift; op.xmm32u(2) <<= shift; op.xmm32u(3) <<= shift; } /* now write result back to destination */ BX_WRITE_XMM_REG(i->rm(), op); #else BX_INFO(("PSLLD_UdqIb: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 73 Grp14 010 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSRLQ_UdqIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op = BX_READ_XMM_REG(i->rm()); Bit8u shift = i->Ib(); if(shift > 63) { op.xmm64u(0) = 0; op.xmm64u(1) = 0; } else { op.xmm64u(0) >>= shift; op.xmm64u(1) >>= shift; } /* now write result back to destination */ BX_WRITE_XMM_REG(i->rm(), op); #else BX_INFO(("PSRLQ_UdqIb: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 73 Grp14 011 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSRLDQ_UdqIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op = BX_READ_XMM_REG(i->rm()), result; Bit8u shift = i->Ib(); result.xmm64u(0) = result.xmm64u(1) = 0; for(unsigned j=shift; j<16; j++) { result.xmmubyte(j-shift) = op.xmmubyte(j); } /* now write result back to destination */ BX_WRITE_XMM_REG(i->rm(), result); #else BX_INFO(("PSRLDQ_UdqIb: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 73 Grp14 110 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSLLQ_UdqIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op = BX_READ_XMM_REG(i->rm()); Bit8u shift = i->Ib(); if(shift > 63) { op.xmm64u(0) = 0; op.xmm64u(1) = 0; } else { op.xmm64u(0) <<= shift; op.xmm64u(1) <<= shift; } /* now write result back to destination */ BX_WRITE_XMM_REG(i->rm(), op); #else BX_INFO(("PSLLQ_UdqIb: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } /* 66 0F 73 Grp14 111 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::PSLLDQ_UdqIb(bxInstruction_c *i) { #if BX_SUPPORT_SSE >= 2 BX_CPU_THIS_PTR prepareSSE(); BxPackedXmmRegister op = BX_READ_XMM_REG(i->rm()), result; Bit8u shift = i->Ib(); result.xmm64u(0) = result.xmm64u(1) = 0; for(unsigned j=shift; j<16; j++) { result.xmmubyte(j) = op.xmmubyte(j-shift); } /* now write result back to destination */ BX_WRITE_XMM_REG(i->rm(), result); #else BX_INFO(("PSLLDQ_UdqIb: required SSE2, use --enable-sse option")); exception(BX_UD_EXCEPTION, 0, 0); #endif }
30.245792
101
0.654399
pavel-krivanek
ef821a915e4496f4b87de51ce0211e94400c8404
1,563
cpp
C++
test/utilities/memory/unique.ptr/unique.ptr.runtime/unique.ptr.runtime.ctor/move02.pass.cpp
caiohamamura/libcxx
27c836ff3a9c505deb9fd1616012924de8ff9279
[ "MIT" ]
1,244
2015-01-02T21:08:56.000Z
2022-03-22T21:34:16.000Z
test/utilities/memory/unique.ptr/unique.ptr.runtime/unique.ptr.runtime.ctor/move02.pass.cpp
caiohamamura/libcxx
27c836ff3a9c505deb9fd1616012924de8ff9279
[ "MIT" ]
125
2015-01-22T01:08:00.000Z
2020-05-25T08:28:17.000Z
test/utilities/memory/unique.ptr/unique.ptr.runtime/unique.ptr.runtime.ctor/move02.pass.cpp
caiohamamura/libcxx
27c836ff3a9c505deb9fd1616012924de8ff9279
[ "MIT" ]
124
2015-01-12T15:06:17.000Z
2022-03-26T07:48:53.000Z
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <memory> // unique_ptr // Test unique_ptr move ctor // test move ctor. Should only require a MoveConstructible deleter, or if // deleter is a reference, not even that. #include <memory> #include <cassert> #include "../../deleter.h" struct A { static int count; A() {++count;} A(const A&) {++count;} ~A() {--count;} }; int A::count = 0; class NCDeleter { int state_; NCDeleter(NCDeleter&); NCDeleter& operator=(NCDeleter&); public: NCDeleter() : state_(5) {} int state() const {return state_;} void set_state(int s) {state_ = s;} void operator()(A* p) {delete [] p;} }; std::unique_ptr<A[]> source1() { return std::unique_ptr<A[]>(new A[3]); } void sink1(std::unique_ptr<A[]> p) { } std::unique_ptr<A[], Deleter<A[]> > source2() { return std::unique_ptr<A[], Deleter<A[]> >(new A[3]); } void sink2(std::unique_ptr<A[], Deleter<A[]> > p) { } std::unique_ptr<A[], NCDeleter&> source3() { static NCDeleter d; return std::unique_ptr<A[], NCDeleter&>(new A[3], d); } void sink3(std::unique_ptr<A[], NCDeleter&> p) { } int main() { sink1(source1()); sink2(source2()); sink3(source3()); assert(A::count == 0); }
17.761364
80
0.540627
caiohamamura
ef8384dfd2ab7e23d4c854917133686efed4604b
2,736
cpp
C++
src/GameData.cpp
dem1980/EmulationStation
019e78d0486178520e0ee36322a212b9c9451052
[ "MIT" ]
null
null
null
src/GameData.cpp
dem1980/EmulationStation
019e78d0486178520e0ee36322a212b9c9451052
[ "MIT" ]
null
null
null
src/GameData.cpp
dem1980/EmulationStation
019e78d0486178520e0ee36322a212b9c9451052
[ "MIT" ]
1
2021-02-24T23:00:44.000Z
2021-02-24T23:00:44.000Z
#include "GameData.h" #include <boost/filesystem.hpp> #include <iostream> const std::string GameData::xmlTagGameList = "gameList"; const std::string GameData::xmlTagGame = "game"; const std::string GameData::xmlTagName = "name"; const std::string GameData::xmlTagPath = "path"; const std::string GameData::xmlTagDescription = "desc"; const std::string GameData::xmlTagImagePath = "image"; const std::string GameData::xmlTagRating = "rating"; const std::string GameData::xmlTagUserRating = "userrating"; const std::string GameData::xmlTagTimesPlayed = "timesplayed"; const std::string GameData::xmlTagLastPlayed = "lastplayed"; GameData::GameData(SystemData* system, std::string path, std::string name) : mSystem(system), mPath(path), mName(name), mRating(0.0f), mUserRating(0.0f), mTimesPlayed(0), mLastPlayed(0) { } bool GameData::isFolder() const { return false; } const std::string & GameData::getName() const { return mName; } void GameData::setName(const std::string & name) { mName = name; } const std::string & GameData::getPath() const { return mPath; } void GameData::setPath(const std::string & path) { mPath = path; } const std::string & GameData::getDescription() const { return mDescription; } void GameData::setDescription(const std::string & description) { mDescription = description; } const std::string & GameData::getImagePath() const { return mImagePath; } void GameData::setImagePath(const std::string & imagePath) { mImagePath = imagePath; } float GameData::getRating() const { return mRating; } void GameData::setRating(float rating) { mRating = rating; } float GameData::getUserRating() const { return mUserRating; } void GameData::setUserRating(float rating) { mUserRating = rating; } size_t GameData::getTimesPlayed() const { return mTimesPlayed; } void GameData::setTimesPlayed(size_t timesPlayed) { mTimesPlayed = timesPlayed; } std::time_t GameData::getLastPlayed() const { return mLastPlayed; } void GameData::setLastPlayed(std::time_t lastPlayed) { mLastPlayed = lastPlayed; } std::string GameData::getBashPath() const { //a quick and dirty way to insert a backslash before most characters that would mess up a bash path std::string path = mPath; const char* invalidChars = " '\"\\!$^&*(){}[]?;<>"; for(unsigned int i = 0; i < path.length(); i++) { char c; unsigned int charNum = 0; do { c = invalidChars[charNum]; if(path[i] == c) { path.insert(i, "\\"); i++; break; } charNum++; } while(c != '\0'); } return path; } //returns the boost::filesystem stem of our path - e.g. for "/foo/bar.rom" returns "bar" std::string GameData::getBaseName() const { boost::filesystem::path path(mPath); return path.stem().string(); }
19.683453
111
0.703947
dem1980
ef84a29ef3afd61450620e6687cf4cf220c7f7e4
7,898
hpp
C++
include/geometricks/data_structure/quad_tree.hpp
mitthy/TCC
4c48eb11cafd50334c5faef93edc5f03bc7fc171
[ "MIT" ]
null
null
null
include/geometricks/data_structure/quad_tree.hpp
mitthy/TCC
4c48eb11cafd50334c5faef93edc5f03bc7fc171
[ "MIT" ]
null
null
null
include/geometricks/data_structure/quad_tree.hpp
mitthy/TCC
4c48eb11cafd50334c5faef93edc5f03bc7fc171
[ "MIT" ]
null
null
null
#ifndef GEOMETRICKS_DATA_STRUCTURE_QUAD_TREE_HPP #define GEOMETRICKS_DATA_STRUCTURE_QUAD_TREE_HPP //C stdlib includes #include <stdint.h> #include <assert.h> //C++ stdlib includesca #include <type_traits> //Project includes #include "shapes.hpp" #include "geometricks/memory/allocator.hpp" #include "internal/small_vector.hpp" namespace geometricks { struct quad_tree_traits { static constexpr int max_depth = 10; static constexpr int leaf_size = 4; }; template< typename T, typename Traits = quad_tree_traits > struct quad_tree { quad_tree( geometricks::rectangle rect, geometricks::allocator alloc = geometricks::allocator{} ): m_root_rect( rect ), m_nodes( alloc ), m_element_ref( alloc ), m_elements( alloc ) { m_nodes.push_back( __make_leaf__() ); } bool insert( const T& element ) { geometricks::rectangle bounding_rect = geometricks::make_rectangle( element ); if( !m_root_rect.contains( bounding_rect ) ) { return false; } auto id = m_elements.push_back( std::make_pair( element, bounding_rect ) ); __insert__( { 0 }, m_root_rect, id, 0 ); return true; } private: struct node_index_t { int32_t m_value; operator int32_t() const { return m_value; } }; struct element_index_t { int32_t m_value; operator int32_t() const { return m_value; } }; struct node { //Indexes values in the quad tree. Last bit is used to represent if the value is a leaf or not. struct index_t { operator element_index_t() const { return { static_cast<int32_t>( ( m_value & 0x7FFFFFFF ) - 1 ) }; } operator node_index_t() const { return { static_cast<int32_t>( m_value ) }; } uint32_t m_value; }; bool is_leaf() const { return m_first_child.m_value >> 31; } node& operator=( element_index_t leaf_index ) { m_first_child.m_value = 0x80000000 | ( leaf_index + 1 ); return *this; } node& operator=( node_index_t node_index ) { m_first_child.m_value = node_index; return *this; } index_t m_first_child; }; //Since each element might be on more than one quadrant of the quad tree, we store 1 index to the element for each type it appears. //TODO: think if we have to store the rectangle for each element. (Probably a yes). struct element_t { int32_t id; int32_t next; }; //TODO: SFINAE this to set default value in case leaf_size is not found. static constexpr int LEAF_SIZE = Traits::leaf_size; //TODO: SFINAE this to set default value in case max_depth is not found. static constexpr int MAX_DEPTH = Traits::max_depth; static constexpr typename node::index_t EMPTY_LEAF = { 0x80000000 }; geometricks::rectangle m_root_rect; geometricks::small_vector<node, 1> m_nodes; //Index 0 represents the root. geometricks::small_vector<element_t, LEAF_SIZE> m_element_ref; geometricks::small_vector<std::pair<T, geometricks::rectangle>, LEAF_SIZE> m_elements; static node __make_leaf__() { return node{ EMPTY_LEAF }; } struct __split_ret__ { geometricks::rectangle first; geometricks::rectangle second; geometricks::rectangle third; geometricks::rectangle fourth; }; __split_ret__ __split_rect__( const geometricks::rectangle& rect ) { auto half_width = rect.width / 2; auto half_height = rect.height / 2; return { geometricks::rectangle{ rect.x_left, rect.y_top, half_width, half_height }, geometricks::rectangle{ rect.x_left + half_width + 1, rect.y_top, rect.width - half_width - 1, half_height }, geometricks::rectangle{ rect.x_left, rect.y_top + half_height + 1, half_width, rect.height - half_height - 1 }, geometricks::rectangle{ rect.x_left + half_width + 1, rect.y_top + half_height + 1, rect.width - half_width - 1, rect.height - half_height - 1 } }; } int __count_leaf_objects__( int32_t index ) { int ret = 0; while( index != -1 ) { index = m_element_ref[ index ].next; ++ret; } return ret; } //TODO void __split_node__( node_index_t cur_node, const geometricks::rectangle& rect, int depth ) { //Create 4 new nodes. Edit small vector class to allow insertion of more than 1 object at a time. auto [ first, second, third, fourth ] = __split_rect__( rect ); element_index_t first_child = m_nodes[ cur_node ].m_first_child; int32_t index = first_child; node_index_t first_node = { m_nodes.push_back( __make_leaf__() ) }; m_nodes.push_back( __make_leaf__() ); m_nodes.push_back( __make_leaf__() ); m_nodes.push_back( __make_leaf__() ); assert( m_nodes[ cur_node ].is_leaf() ); m_nodes[ cur_node ] = first_node; assert( !m_nodes[ cur_node ].is_leaf() ); while( index != -1 ) { auto actual_id = m_element_ref[ index ].id; geometricks::rectangle element_rect = m_elements[ actual_id ].second; if( geometricks::intersects_with( first, element_rect ) ) {; __insert__( first_node, first, actual_id, depth + 1 ); } if( geometricks::intersects_with( second, element_rect ) ) { __insert__( { first_node + 1 }, second, actual_id, depth + 1 ); } if( geometricks::intersects_with( third, element_rect ) ) { __insert__( { first_node + 2 }, third, actual_id, depth + 1 ); } if( geometricks::intersects_with( fourth, element_rect ) ) { __insert__( { first_node + 3 }, fourth, actual_id, depth + 1 ); } index = m_element_ref[ index ].next; } } void __insert__( node_index_t cur_node, const geometricks::rectangle& rect, int32_t object_id, int depth ) { if( !m_nodes[ cur_node ].is_leaf() ) { auto [ first, second, third, fourth ] = __split_rect__( rect ); node_index_t first_node_child = m_nodes[ cur_node ].m_first_child; if( geometricks::intersects_with( first, m_elements[ object_id ].second ) ) { __insert__( first_node_child, first, object_id, depth + 1 ); } if( geometricks::intersects_with( second, m_elements[ object_id ].second ) ) { __insert__( { first_node_child + 1 }, second, object_id, depth + 1 ); } if( geometricks::intersects_with( third, m_elements[ object_id ].second ) ) { __insert__( { first_node_child + 2 }, third, object_id, depth + 1 ); } if( geometricks::intersects_with( fourth, m_elements[ object_id ].second ) ) { __insert__( { first_node_child + 3 }, fourth, object_id, depth + 1 ); } } else { element_index_t last_element_index = m_nodes[ cur_node ].m_first_child; element_t new_el{ object_id, last_element_index }; element_index_t element_id = { m_element_ref.push_back( new_el ) }; m_nodes[ cur_node ] = element_id; if( !( depth == MAX_DEPTH || rect.height < 3 || rect.width < 3 ) ) { auto count = __count_leaf_objects__( element_id ); if( count > LEAF_SIZE ) { assert( m_nodes[ cur_node ].is_leaf() ); __split_node__( cur_node, rect, depth ); assert( !m_nodes[ cur_node ].is_leaf() ); } } } } }; } //namespace geometricks #endif //GEOMETRICKS_DATA_STRUCTURE_QUAD_TREE_HPP
34.190476
162
0.609775
mitthy
ef8627edd1d9bc81fe84b0e6c41e724cbe8e3ff1
2,533
hpp
C++
Example/Toturial-3/5 - thread - producer consumer list/thread - producer consumer list/MTLibrary/LockList.hpp
orenccl/Winsock-Multi-Client-Server
143bb3b6c856270249632dc01f5223f65180ca89
[ "MIT" ]
2
2019-11-11T01:03:02.000Z
2019-11-11T01:04:54.000Z
Example/Toturial-3/5 - thread - producer consumer list/thread - producer consumer list/MTLibrary/LockList.hpp
orenccl/MintServer
143bb3b6c856270249632dc01f5223f65180ca89
[ "MIT" ]
null
null
null
Example/Toturial-3/5 - thread - producer consumer list/thread - producer consumer list/MTLibrary/LockList.hpp
orenccl/MintServer
143bb3b6c856270249632dc01f5223f65180ca89
[ "MIT" ]
null
null
null
#pragma once #include "List/TMPSinglyList.hpp" #include "List/TMPDoublyList.hpp" #include "Lock.h" template < class DATA_TYPE > class TMPSinglyLockList : public TMPSinglyList< DATA_TYPE > { public: CLock Locker; inline void Create(UINT object_max) { TMPSinglyList< DATA_TYPE >::Create(object_max); Locker.Create(); } inline TSNode< DATA_TYPE >* LockGetNode() { Locker.Lock(); TSNode< DATA_TYPE >* node = TMPSinglyList< DATA_TYPE >::GetNode(); Locker.Unlock(); return node; } inline void LockLink(TSNode< DATA_TYPE >* link_node) { Locker.Lock(); TMPSinglyList< DATA_TYPE >::Link(link_node); Locker.Unlock(); } inline void LockUnlink(TSNode< DATA_TYPE >* unlink_node) { Locker.Lock(); TMPSinglyList< DATA_TYPE >::Unlink(unlink_node); Locker.Unlock(); } inline void LockFreeNode(TSNode< DATA_TYPE >*& release_node) { Locker.Lock(); TMPSinglyList< DATA_TYPE >::FreeNode(release_node); Locker.Unlock(); } inline TSNode< DATA_TYPE >* LockGetHeadNode() { Locker.Lock(); TSNode< DATA_TYPE >* node = TMPSinglyList< DATA_TYPE >::pHeadNode; Locker.Unlock(); return node; } inline void LockUnlinkFreeNode(TSNode< DATA_TYPE >*& node) { Locker.Lock(); TMPSinglyList< DATA_TYPE >::Unlink(node); TMPSinglyList< DATA_TYPE >::FreeNode(node); Locker.Unlock(); } }; template < class DATA_TYPE > class TMPDoublyLockList : public TMPDoublyList< DATA_TYPE > { public: CLock Locker; inline void Create(UINT object_max) { TMPDoublyList< DATA_TYPE >::Create(object_max); Locker.Create(); } inline TDNode< DATA_TYPE >* LockGetNode() { Locker.Lock(); TDNode< DATA_TYPE >* node = TMPDoublyList< DATA_TYPE >::GetNode(); Locker.Unlock(); return node; } inline void LockLink(TDNode< DATA_TYPE >* link_node) { Locker.Lock(); TMPDoublyList< DATA_TYPE >::Link(link_node); Locker.Unlock(); } inline void LockUnlink(TDNode< DATA_TYPE >* unlink_node) { Locker.Lock(); TMPDoublyList< DATA_TYPE >::Unlink(unlink_node); Locker.Unlock(); } inline void LockFreeNode(TDNode< DATA_TYPE >*& release_node) { Locker.Lock(); TMPDoublyList< DATA_TYPE >::FreeNode(release_node); Locker.Unlock(); } inline TDNode< DATA_TYPE >* LockGetHeadNode() { Locker.Lock(); TDNode< DATA_TYPE >* node = TMPDoublyList< DATA_TYPE >::pHeadNode; Locker.Unlock(); return node; } inline void LockUnlinkFreeNode(TDNode< DATA_TYPE >*& node) { Locker.Lock(); TMPSinglyList< DATA_TYPE >::Unlink(node); TMPSinglyList< DATA_TYPE >::FreeNode(node); Locker.Unlock(); } };
23.238532
68
0.703514
orenccl
ef87588eef357ff09ac11b86790d501435602102
2,813
cpp
C++
tester.cpp
ReinaldoDiasAbreu/TestesAutomatizados
06ce12a3af585d3f3ffadf0e9966346112460c2f
[ "MIT" ]
null
null
null
tester.cpp
ReinaldoDiasAbreu/TestesAutomatizados
06ce12a3af585d3f3ffadf0e9966346112460c2f
[ "MIT" ]
null
null
null
tester.cpp
ReinaldoDiasAbreu/TestesAutomatizados
06ce12a3af585d3f3ffadf0e9966346112460c2f
[ "MIT" ]
null
null
null
#include <iostream> #include <cstring> #include <cstdlib> #include <string> using namespace std; /* Programa de Automatização de Testes */ void help() { cout << endl << " TESTER" << endl << endl; cout << " Executa comparaçoes entre as entradas e saídas especificadas." << endl << endl; cout << " Comando: " << endl << endl; cout << " ./tester exec dir N D" << endl << endl; cout << " exec -> Arquivo executável." << endl; cout << " dir -> Diretório de arquivos de entrada e saída (.in, .sol)." << endl; cout << " N -> Quantidade de testes." << endl; cout << " D -> Remove arquivos de resposta se 1 (.res)." << endl; cout << endl << " Os arquivos de entrada e saída devem ser nomedados da seguinte maneira:" << endl << endl; cout << " 0.in - 0.sol" << endl; cout << " 1.in - 1.sol" << endl; cout << endl << " Todos os arquivos devem ficar no mesmo diretorio (dir) e numerados" << endl; cout << " em sequência de execuçao (De 0 a N-1)." << endl; cout << " O executavel deve ficar no mesmo diretório do tester." << endl << endl; cout << " Exemplo: ./tester myprogram testes 5 1" << endl << endl; } int main(int argc, char *argv[]) { if(argc > 1) { if(argc == 2) { if(strcmp(argv[1], "--help") == 0) { help(); } } else { cout << " TESTER" << endl; cout << "Exec: " << argv[1] << " -> Pasta: /" << argv[2] << " -> Quant: " << argv[3] << endl << endl; string exec = string(argv[1]); string pasta = string(argv[2]); for(int i = 0; i < atoi(argv[3]); i++) { string ind = to_string(i); string cexec = "./" + exec + " < " + pasta + "/" + ind + ".in" + " > " + pasta + "/" + ind + ".res" ; string ccomp = "diff -q " + pasta + "/" + ind + ".res " + pasta + "/" + ind + ".sol"; if(system(cexec.c_str()) == 0) { if(system(ccomp.c_str()) == 0) cout << "TEST " << i << " -> PASSED" << endl; else cout << "TEST " << i << " -> NOT IDENTICAL" << endl; } else cout << "TEST " << i << " -> EXECUTION ERROR" << endl; } string clean = "rm " + pasta + "/*.res"; if(argv[4]) system(clean.c_str()); } } else { cout << "Parametros Invalidos" << endl << endl; help(); } cout << endl << "FINISHED" << endl; return 0; }
35.607595
118
0.424102
ReinaldoDiasAbreu
ef8a57d09afd582ef09165c93fb97678bd9bf94c
13,594
cpp
C++
code/WPILib/Vision/AxisCamera.cpp
trc492/Frc2014AerialAssist
efe9212b47561b317fb6ecfef81965ea5fb8c396
[ "MIT" ]
1
2019-11-19T04:38:22.000Z
2019-11-19T04:38:22.000Z
code/WPILib/Vision/AxisCamera.cpp
trc492/Frc2014AerialAssist
efe9212b47561b317fb6ecfef81965ea5fb8c396
[ "MIT" ]
null
null
null
code/WPILib/Vision/AxisCamera.cpp
trc492/Frc2014AerialAssist
efe9212b47561b317fb6ecfef81965ea5fb8c396
[ "MIT" ]
1
2019-11-19T04:43:30.000Z
2019-11-19T04:43:30.000Z
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */ /*----------------------------------------------------------------------------*/ #include "Vision/AxisCamera.h" #include <string.h> #include "NetworkCommunication/UsageReporting.h" #include "Synchronized.h" #include "Vision/PCVideoServer.h" #include "WPIErrors.h" /** Private NI function to decode JPEG */ IMAQ_FUNC int Priv_ReadJPEGString_C(Image* _image, const unsigned char* _string, uint32_t _stringLength); // Max packet without jumbo frames is 1500... add 36 because?? #define kMaxPacketSize 1536 #define kImageBufferAllocationIncrement 1000 AxisCamera *AxisCamera::_instance = NULL; /** * AxisCamera constructor */ AxisCamera::AxisCamera(const char *ipAddress) : AxisCameraParams(ipAddress) , m_cameraSocket(ERROR) , m_protectedImageBuffer(NULL) , m_protectedImageBufferLength(0) , m_protectedImageSize(0) , m_protectedImageSem(NULL) , m_freshImage(false) , m_imageStreamTask("cameraTask", (FUNCPTR)s_ImageStreamTaskFunction) , m_videoServer(NULL) { m_protectedImageSem = semMCreate(SEM_Q_PRIORITY | SEM_INVERSION_SAFE | SEM_DELETE_SAFE); #if JAVA_CAMERA_LIB != 1 nUsageReporting::report(nUsageReporting::kResourceType_AxisCamera, ipAddress == NULL ? 1 : 2); #endif if (!StatusIsFatal()) m_imageStreamTask.Start((int)this); } /** * Destructor */ AxisCamera::~AxisCamera() { delete m_videoServer; m_videoServer = NULL; m_imageStreamTask.Stop(); close(m_cameraSocket); SemSet_t::iterator it = m_newImageSemSet.begin(); SemSet_t::iterator end = m_newImageSemSet.end(); for (;it != end; it++) { semDelete(*it); } m_newImageSemSet.clear(); semDelete(m_protectedImageSem); } /** * Get a pointer to the AxisCamera object, if the object does not exist, create it * To use the camera on port 2 of a cRIO-FRC, pass "192.168.0.90" to the first GetInstance call. * @return reference to AxisCamera object */ AxisCamera &AxisCamera::GetInstance(const char *cameraIP) { if (NULL == _instance) { _instance = new AxisCamera(cameraIP); _instance->m_videoServer = new PCVideoServer(); } return *_instance; } /** * Called by Java to delete the camera... how thoughtful */ void AxisCamera::DeleteInstance() { delete _instance; _instance = NULL; } /** * Return true if the latest image from the camera has not been retrieved by calling GetImage() yet. * @return true if the image has not been retrieved yet. */ bool AxisCamera::IsFreshImage() { return m_freshImage; } /** * Get the semaphore to be used to synchronize image access with camera acquisition * * Call semTake on the returned semaphore to block until a new image is acquired. * * The semaphore is owned by the AxisCamera class and will be deleted when the class is destroyed. * @return A semaphore to notify when new image is received */ SEM_ID AxisCamera::GetNewImageSem() { SEM_ID sem = semBCreate (SEM_Q_PRIORITY, SEM_EMPTY); m_newImageSemSet.insert(sem); return sem; } /** * Get an image from the camera and store it in the provided image. * @param image The imaq image to store the result in. This must be an HSL or RGB image * This function is called by Java. * @return 1 upon success, zero on a failure */ int AxisCamera::GetImage(Image* imaqImage) { if (m_protectedImageBuffer == NULL) return 0; Synchronized sync(m_protectedImageSem); Priv_ReadJPEGString_C(imaqImage, (unsigned char*)m_protectedImageBuffer, m_protectedImageSize); m_freshImage = false; return 1; } #if JAVA_CAMERA_LIB != 1 /** * Get an image from the camera and store it in the provided image. * @param image The image to store the result in. This must be an HSL or RGB image * @return 1 upon success, zero on a failure */ int AxisCamera::GetImage(ColorImage* image) { return GetImage(image->GetImaqImage()); } /** * Instantiate a new image object and fill it with the latest image from the camera. * * The returned pointer is owned by the caller and is their responsibility to delete. * @return a pointer to an HSLImage object */ HSLImage* AxisCamera::GetImage() { HSLImage *image = new HSLImage(); GetImage(image); return image; } #endif /** * Copy an image into an existing buffer. * This copies an image into an existing buffer rather than creating a new image * in memory. That way a new image is only allocated when the image being copied is * larger than the destination. * This method is called by the PCVideoServer class. * @param imageData The destination image. * @param numBytes The size of the destination image. * @return 0 if failed (no source image or no memory), 1 if success. */ int AxisCamera::CopyJPEG(char **destImage, int &destImageSize, int &destImageBufferSize) { Synchronized sync(m_protectedImageSem); if (destImage == NULL) wpi_setWPIErrorWithContext(NullParameter, "destImage must not be NULL"); if (m_protectedImageBuffer == NULL || m_protectedImageSize <= 0) return 0; // if no source image if (destImageBufferSize < m_protectedImageSize) // if current destination buffer too small { if (*destImage != NULL) delete [] *destImage; destImageBufferSize = m_protectedImageSize + kImageBufferAllocationIncrement; *destImage = new char[destImageBufferSize]; if (*destImage == NULL) return 0; } // copy this image into destination buffer if (*destImage == NULL) { wpi_setWPIErrorWithContext(NullParameter, "*destImage must not be NULL"); } // TODO: Is this copy realy necessary... perhaps we can simply transmit while holding the protected buffer memcpy(*destImage, m_protectedImageBuffer, m_protectedImageSize); destImageSize = m_protectedImageSize; return 1; } /** * Static interface that will cause an instantiation if necessary. * This static stub is directly spawned as a task to read images from the camera. */ int AxisCamera::s_ImageStreamTaskFunction(AxisCamera *thisPtr) { return thisPtr->ImageStreamTaskFunction(); } /** * Task spawned by AxisCamera constructor to receive images from cam * If setNewImageSem has been called, this function does a semGive on each new image * Images can be accessed by calling getImage() */ int AxisCamera::ImageStreamTaskFunction() { // Loop on trying to setup the camera connection. This happens in a background // thread so it shouldn't effect the operation of user programs. while (1) { const char *requestString = "GET /mjpg/video.mjpg HTTP/1.1\n\ User-Agent: HTTPStreamClient\n\ Connection: Keep-Alive\n\ Cache-Control: no-cache\n\ Authorization: Basic RlJDOkZSQw==\n\n"; semTake(m_socketPossessionSem, WAIT_FOREVER); m_cameraSocket = CreateCameraSocket(requestString); if (m_cameraSocket == ERROR) { // Don't hammer the camera if it isn't ready. semGive(m_socketPossessionSem); taskDelay(1000); } else { ReadImagesFromCamera(); } } return 0; } /** * This function actually reads the images from the camera. */ int AxisCamera::ReadImagesFromCamera() { char *imgBuffer = NULL; int imgBufferLength = 0; //Infinite loop, task deletion handled by taskDeleteHook // Socket cleanup handled by destructor // TODO: these recv calls must be non-blocking. Otherwise if the camera // fails during a read, the code hangs and never retries when the camera comes // back up. int counter = 2; while (1) { char initialReadBuffer[kMaxPacketSize] = ""; char intermediateBuffer[1]; char *trailingPtr = initialReadBuffer; int trailingCounter = 0; while (counter) { // TODO: fix me... this cannot be the most efficient way to approach this, reading one byte at a time. if(recv(m_cameraSocket, intermediateBuffer, 1, 0) == ERROR) { wpi_setErrnoErrorWithContext("Failed to read image header"); close (m_cameraSocket); return ERROR; } strncat(initialReadBuffer, intermediateBuffer, 1); // trailingCounter ensures that we start looking for the 4 byte string after // there is at least 4 bytes total. Kind of obscure. // look for 2 blank lines (\r\n) if (NULL != strstr(trailingPtr, "\r\n\r\n")) { --counter; } if (++trailingCounter >= 4) { trailingPtr++; } } counter = 1; char *contentLength = strstr(initialReadBuffer, "Content-Length: "); if (contentLength == NULL) { wpi_setWPIErrorWithContext(IncompatibleMode, "No content-length token found in packet"); close(m_cameraSocket); return ERROR; } contentLength = contentLength + 16; // skip past "content length" int readLength = atol(contentLength); // get the image byte count // Make sure buffer is large enough if (imgBufferLength < readLength) { if (imgBuffer) delete[] imgBuffer; imgBufferLength = readLength + kImageBufferAllocationIncrement; imgBuffer = new char[imgBufferLength]; if (imgBuffer == NULL) { imgBufferLength = 0; continue; } } // Read the image data for "Content-Length" bytes int bytesRead = 0; int remaining = readLength; while(bytesRead < readLength) { int bytesThisRecv = recv(m_cameraSocket, &imgBuffer[bytesRead], remaining, 0); bytesRead += bytesThisRecv; remaining -= bytesThisRecv; } // Update image UpdatePublicImageFromCamera(imgBuffer, readLength); if (semTake(m_paramChangedSem, NO_WAIT) == OK) { // params need to be updated: close the video stream; release the camera. close(m_cameraSocket); semGive(m_socketPossessionSem); return 0; } } } /** * Copy the image from private buffer to shared buffer. * @param imgBuffer The buffer containing the image * @param bufLength The length of the image */ void AxisCamera::UpdatePublicImageFromCamera(char *imgBuffer, int imgSize) { { Synchronized sync(m_protectedImageSem); // Adjust the buffer size if current destination buffer is too small. if (m_protectedImageBufferLength < imgSize) { if (m_protectedImageBuffer != NULL) delete [] m_protectedImageBuffer; m_protectedImageBufferLength = imgSize + kImageBufferAllocationIncrement; m_protectedImageBuffer = new char[m_protectedImageBufferLength]; if (m_protectedImageBuffer == NULL) { m_protectedImageBufferLength = 0; return; } } memcpy(m_protectedImageBuffer, imgBuffer, imgSize); m_protectedImageSize = imgSize; } m_freshImage = true; // Notify everyone who is interested. SemSet_t::iterator it = m_newImageSemSet.begin(); SemSet_t::iterator end = m_newImageSemSet.end(); for (;it != end; it++) { semGive(*it); } } /** * Implement the pure virtual interface so that when parameter changes require a restart, the image task can be bounced. */ void AxisCamera::RestartCameraTask() { m_imageStreamTask.Stop(); m_imageStreamTask.Start((int)this); } #if JAVA_CAMERA_LIB == 1 // C bindings used by Java // These need to stay as is or Java has to change void AxisCameraStart(const char *IPAddress) { #ifdef SVN_REV if (strlen(SVN_REV)) { printf("JavaCameraLib was compiled from SVN revision %s\n", SVN_REV); } else { printf("JavaCameraLib was compiled from a location that is not source controlled.\n"); } #else printf("JavaCameraLib was compiled without -D'SVN_REV=nnnn'\n"); #endif AxisCamera::GetInstance(IPAddress); } int AxisCameraGetImage (Image* image) { return AxisCamera::GetInstance().GetImage(image); } void AxisCameraWriteBrightness(int brightness) { AxisCamera::GetInstance().WriteBrightness(brightness); } int AxisCameraGetBrightness() { return AxisCamera::GetInstance().GetBrightness(); } void AxisCameraWriteWhiteBalance(AxisCameraParams::WhiteBalance_t whiteBalance) { AxisCamera::GetInstance().WriteWhiteBalance(whiteBalance); } AxisCameraParams::WhiteBalance_t AxisCameraGetWhiteBalance() { return AxisCamera::GetInstance().GetWhiteBalance(); } void AxisCameraWriteColorLevel(int colorLevel) { AxisCamera::GetInstance().WriteColorLevel(colorLevel); } int AxisCameraGetColorLevel() { return AxisCamera::GetInstance().GetColorLevel(); } void AxisCameraWriteExposureControl(AxisCameraParams::Exposure_t exposure) { AxisCamera::GetInstance().WriteExposureControl(exposure); } AxisCameraParams::Exposure_t AxisCameraGetExposureControl() { return AxisCamera::GetInstance().GetExposureControl(); } void AxisCameraWriteExposurePriority(int exposure) { AxisCamera::GetInstance().WriteExposurePriority(exposure); } int AxisCameraGetExposurePriority() { return AxisCamera::GetInstance().GetExposurePriority(); } void AxisCameraWriteMaxFPS(int maxFPS) { AxisCamera::GetInstance().WriteMaxFPS(maxFPS); } int AxisCameraGetMaxFPS() { return AxisCamera::GetInstance().GetMaxFPS(); } void AxisCameraWriteResolution(AxisCameraParams::Resolution_t resolution) { AxisCamera::GetInstance().WriteResolution(resolution); } AxisCameraParams::Resolution_t AxisCameraGetResolution() { return AxisCamera::GetInstance().GetResolution(); } void AxisCameraWriteCompression(int compression) { AxisCamera::GetInstance().WriteCompression(compression); } int AxisCameraGetCompression() { return AxisCamera::GetInstance().GetCompression(); } void AxisCameraWriteRotation(AxisCameraParams::Rotation_t rotation) { AxisCamera::GetInstance().WriteRotation(rotation); } AxisCameraParams::Rotation_t AxisCameraGetRotation() { return AxisCamera::GetInstance().GetRotation(); } void AxisCameraDeleteInstance() { AxisCamera::DeleteInstance(); } int AxisCameraFreshImage() { return AxisCamera::GetInstance().IsFreshImage(); } #endif // JAVA_CAMERA_LIB == 1
27.025845
120
0.734736
trc492
ef8b264cd7a612e3c1bfe6c2f13a18893deaf7b6
1,630
cpp
C++
add_strings.cpp
shirishbahirat/algorithm
ec743d4c16ab4f429f22bd6f71540341b3905b3b
[ "Apache-2.0" ]
null
null
null
add_strings.cpp
shirishbahirat/algorithm
ec743d4c16ab4f429f22bd6f71540341b3905b3b
[ "Apache-2.0" ]
null
null
null
add_strings.cpp
shirishbahirat/algorithm
ec743d4c16ab4f429f22bd6f71540341b3905b3b
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <sstream> using namespace std; class Solution { public: string addStrings(string num1, string num2) { int n1 = 0, n2 = 0; int i, j; int carry = 0; int sum; string results = ""; string str1, str2; for (i = (num1.size() - 1), j = (num2.size() - 1); (i >= 0) && (j >= 0); --i, --j) { stringstream s1, s2; s1 << num1[i]; s2 << num2[j]; str1 = s1.str(); str2 = s2.str(); n1 = stoi(str1); n2 = stoi(str2); sum = n1 + n2 + carry; if (sum > 9) { carry = 1; sum %= 10; } else { carry = 0; } results = to_string(sum) + results; } while (j >= 0) { stringstream s2; s2 << num2[j]; str2 = s2.str(); n2 = stoi(str2); sum = n2 + carry; if (sum > 9) { carry = 1; sum %= 10; } else { carry = 0; } results = to_string(sum) + results; --j; } while (i >= 0) { stringstream s1; s1 << num1[i]; str1 = s1.str(); n1 = stoi(str1); sum = n1 + carry; if (sum > 9) { carry = 1; sum %= 10; } else { carry = 0; } results = to_string(sum) + results; --i; } if (carry) { results = to_string(carry) + results; } return results; } }; int main(int argc, char const *argv[]) { Solution *obj = new Solution(); string results = obj->addStrings("408", "5"); cout << results << endl; return 0; }
14.684685
76
0.423313
shirishbahirat
ef8b7a7ddfad18c0bb1876a4ae720e4d6282870b
1,009
cpp
C++
frameworks/C++/cppcms/src/main.cpp
xsoheilalizadeh/FrameworkBenchmarks
855527008f7488e4fd508d1e72dfa9953874a2c6
[ "BSD-3-Clause" ]
5,300
2015-01-02T08:04:20.000Z
2022-03-31T10:08:33.000Z
frameworks/C++/cppcms/src/main.cpp
xsoheilalizadeh/FrameworkBenchmarks
855527008f7488e4fd508d1e72dfa9953874a2c6
[ "BSD-3-Clause" ]
3,075
2015-01-01T05:11:45.000Z
2022-03-31T23:56:33.000Z
frameworks/C++/cppcms/src/main.cpp
xsoheilalizadeh/FrameworkBenchmarks
855527008f7488e4fd508d1e72dfa9953874a2c6
[ "BSD-3-Clause" ]
2,151
2015-01-02T14:16:09.000Z
2022-03-30T00:15:26.000Z
#include <cppcms/service.h> #include <cppcms/applications_pool.h> #include <cppcms/http_response.h> #include <cppcms/url_dispatcher.h> #include <iostream> #include "test_simple.h" #include "test_fortunes.h" #include "test_db.h" class myapp : public cppcms::application { public: myapp(cppcms::service &srv) : cppcms::application(srv) { attach(new test_simple(srv), "/json()", 0); attach(new test_simple(srv), "/plaintext()", 0); attach(new test_fortunes(srv), "/fortunes()", 1); attach(new test_db(srv), "/db()", 0); attach(new test_db(srv), "/queries/.*", 0); attach(new test_db(srv), "/updates/.*", 0); attach(new test_db(srv), "/cached-worlds/.*", 0); } }; int main(int argc, char **argv) { try { cppcms::service app(argc, argv); app.applications_pool().mount(cppcms::applications_factory<myapp>()); app.run(); } catch (std::exception const &e) { std::cerr << e.what() << std::endl; } }
24.609756
77
0.607532
xsoheilalizadeh
ef8bc7dabcb3e35dfd2bb55ab965a44577b48b70
20,488
cpp
C++
src/plugProjectNishimuraU/KurageMgr.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
33
2021-12-08T11:10:59.000Z
2022-03-26T19:59:37.000Z
src/plugProjectNishimuraU/KurageMgr.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
6
2021-12-22T17:54:31.000Z
2022-01-07T21:43:18.000Z
src/plugProjectNishimuraU/KurageMgr.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
2
2022-01-04T06:00:49.000Z
2022-01-26T07:27:28.000Z
#include "types.h" /* Generated from dpostproc .section .rodata # 0x804732E0 - 0x8049E220 .global lbl_80489A38 lbl_80489A38: .asciz "246-KurageMgr" .skip 2 .global lbl_80489A48 lbl_80489A48: .4byte 0x834E8389 .4byte 0x83518368 .4byte 0x8362834E .4byte 0x838A837D .4byte 0x836C815B .4byte 0x83578383 .4byte 0x00000000 .4byte 0x456E656D .4byte 0x79506172 .4byte 0x6D734261 .4byte 0x73650000 .4byte 0x94F28D73 .4byte 0x8D8282B3 .4byte 0x00000000 .4byte 0x8FE38FB8 .4byte 0x8C579094 .4byte 0x00000000 .4byte 0x926E8FE3 .4byte 0x83458346 .4byte 0x83438367 .4byte 0x8E9E8AD4 .4byte 0x00000000 .4byte 0x8B7A82A2 .4byte 0x8D9E82DD .4byte 0x8E9E8AD4 .4byte 0x00000000 .4byte 0x8B7A82A2 .4byte 0x8D9E82DD .4byte 0x8A6D97A6 .4byte 0x00000000 .4byte 0x905595A5 .4byte 0x978E89BA .4byte 0x8E9E8AD4 .4byte 0x00000000 .4byte 0x978E89BA .4byte 0x8DC592E1 .4byte 0x8373834C .4byte 0x90940000 .4byte 0x8B7A82A2 .4byte 0x8D9E82DD .4byte 0x8373834C .4byte 0x90940000 .4byte 0x43726561 .4byte 0x74757265 .4byte 0x3A3A5072 .4byte 0x6F706572 .4byte 0x74790000 .4byte 0x66726963 .4byte 0x74696F6E .4byte 0x286E6F74 .4byte 0x20757365 .4byte 0x64290000 .4byte 0x77616C6C .4byte 0x5265666C .4byte 0x65637469 .4byte 0x6F6E0000 .4byte 0x66616365 .4byte 0x44697241 .4byte 0x646A7573 .4byte 0x74000000 .4byte 0x626F756E .4byte 0x63654661 .4byte 0x63746F72 .4byte 0x00000000 .4byte 0x83898343 .4byte 0x837482CC .4byte 0x8D8282B3 .4byte 0x00000000 .4byte 0x83898343 .4byte 0x837489F1 .4byte 0x959C97A6 .4byte 0x00000000 .4byte 0x8C7889FA .4byte 0x83898343 .4byte 0x83740000 .4byte 0x837D8362 .4byte 0x837682C6 .4byte 0x82CC9396 .4byte 0x82E80000 .4byte 0x837D8362 .4byte 0x837682C6 .4byte 0x82CC82A0 .4byte 0x82BD82E8 .4byte 0x837C838A .4byte 0x83538393 .4byte 0x82CC9149 .4byte 0x92E80000 .4byte 0x8373834E .4byte 0x837E8393 .4byte 0x82C682CC .4byte 0x82A082BD .4byte 0x82E80000 .4byte 0x835F8381 .4byte 0x815B8357 .4byte 0x83588350 .4byte 0x815B838B .4byte 0x585A0000 .4byte 0x835F8381 .4byte 0x815B8357 .4byte 0x83588350 .4byte 0x815B838B .4byte 0x59000000 .4byte 0x835F8381 .4byte 0x815B8357 .4byte 0x8374838C .4byte 0x815B8380 .4byte 0x00000000 .4byte 0x89F1935D .4byte 0x91AC9378 .4byte 0x97A60000 .4byte 0x89F1935D .4byte 0x8DC591E5 .4byte 0x91AC9378 .4byte 0x00000000 .4byte 0x8365838A .4byte 0x8367838A .4byte 0x815B0000 .4byte 0x837A815B .4byte 0x838094CD .4byte 0x88CD0000 .4byte 0x83768389 .4byte 0x83438378 .4byte 0x815B8367 .4byte 0x8B9797A3 .4byte 0x00000000 .4byte 0x8E8B8A45 .4byte 0x8B9797A3 .4byte 0x00000000 .4byte 0x8E8B8A45 .4byte 0x8A709378 .4byte 0x00000000 .4byte 0x92548DF5 .4byte 0x8B9797A3 .4byte 0x00000000 .4byte 0x92548DF5 .4byte 0x8A709378 .4byte 0x00000000 .4byte 0x905582E8 .4byte 0x95A582A2 .4byte 0x97CD0000 .4byte 0x905582E8 .4byte 0x95A582A2 .4byte 0x835F8381 .4byte 0x815B8357 .4byte 0x00000000 .4byte 0x905582E8 .4byte 0x95A582A2 .4byte 0x94CD88CD .4byte 0x00000000 .4byte 0x905582E8 .4byte 0x95A582A2 .4byte 0x97A60000 .4byte 0x8D558C82 .4byte 0x89C2945C .4byte 0x94CD88CD .4byte 0x00000000 .4byte 0x8D558C82 .4byte 0x89C2945C .4byte 0x8A709378 .4byte 0x00000000 .4byte 0x8D558C82 .4byte 0x83718362 .4byte 0x836794CD .4byte 0x88CD0000 .4byte 0x8D558C82 .4byte 0x83718362 .4byte 0x83678A70 .4byte 0x93780000 .4byte 0x8C7889FA .4byte 0x8E9E8AD4 .4byte 0x00000000 .4byte 0x90CE89BB .4byte 0x8E9E8AD4 .4byte 0x00000000 .4byte 0x83718362 .4byte 0x83768368 .4byte 0x838D8362 .4byte 0x8376835F .4byte 0x8381815B .4byte 0x83570000 .4byte 0x926E906B .4byte 0x8B4390E2 .4byte 0x8A6D97A7 .4byte 0x00000000 .4byte 0x926E906B .4byte 0x8B4390E2 .4byte 0x8E9E8AD4 .4byte 0x00000000 .4byte 0x905582E8 .4byte 0x95A582A2 .4byte 0x91C58C82 .4byte 0x82600000 .4byte 0x905582E8 .4byte 0x95A582A2 .4byte 0x92A39574 .4byte 0x82500000 .4byte 0x905582E8 .4byte 0x95A582A2 .4byte 0x91C58C82 .4byte 0x82610000 .4byte 0x905582E8 .4byte 0x95A582A2 .4byte 0x92A39574 .4byte 0x82510000 .4byte 0x905582E8 .4byte 0x95A582A2 .4byte 0x91C58C82 .4byte 0x82620000 .4byte 0x905582E8 .4byte 0x95A582A2 .4byte 0x92A39574 .4byte 0x82520000 .4byte 0x905582E8 .4byte 0x95A582A2 .4byte 0x91C58C82 .4byte 0x82630000 .section .data, "wa" # 0x8049E220 - 0x804EFC20 .global __vt__Q34Game6Kurage3Mgr __vt__Q34Game6Kurage3Mgr: .4byte 0 .4byte 0 .4byte doAnimation__Q24Game12EnemyMgrBaseFv .4byte doEntry__Q24Game12EnemyMgrBaseFv .4byte doSetView__Q24Game12EnemyMgrBaseFi .4byte doViewCalc__Q24Game12EnemyMgrBaseFv .4byte doSimulation__Q24Game12EnemyMgrBaseFf .4byte doDirectDraw__Q24Game12EnemyMgrBaseFR8Graphics .4byte doSimpleDraw__16GenericObjectMgrFP8Viewport .4byte loadResources__16GenericObjectMgrFv .4byte resetMgr__16GenericObjectMgrFv .4byte pausable__16GenericObjectMgrFv .4byte frozenable__16GenericObjectMgrFv .4byte getMatrixLoadType__16GenericObjectMgrFv .4byte 0 .4byte 0 .4byte "@4@__dt__Q34Game6Kurage3MgrFv" .4byte getChildCount__5CNodeFv .4byte "@4@getObject__Q24Game12EnemyMgrBaseFPv" .4byte "@4@getNext__Q24Game12EnemyMgrBaseFPv" .4byte "@4@getStart__Q24Game12EnemyMgrBaseFv" .4byte "@4@getEnd__Q24Game12EnemyMgrBaseFv" .4byte __dt__Q34Game6Kurage3MgrFv .4byte getObject__Q24Game12EnemyMgrBaseFPv .4byte getNext__Q24Game12EnemyMgrBaseFPv .4byte getStart__Q24Game12EnemyMgrBaseFv .4byte getEnd__Q24Game12EnemyMgrBaseFv .4byte alloc__Q24Game12EnemyMgrBaseFv .4byte birth__Q24Game12EnemyMgrBaseFRQ24Game13EnemyBirthArg .4byte getJ3DModelData__Q24Game12EnemyMgrBaseCFv .4byte getGenerator__Q24Game12EnemyMgrBaseCFv .4byte killAll__Q24Game12EnemyMgrBaseFPQ24Game15CreatureKillArg .4byte setupSoundViewerAndBas__Q24Game12EnemyMgrBaseFv .4byte setDebugParm__Q24Game12EnemyMgrBaseFUl .4byte resetDebugParm__Q24Game12EnemyMgrBaseFUl .4byte getMaxObjects__Q24Game12EnemyMgrBaseCFv .4byte startMovie__Q24Game12EnemyMgrBaseFv .4byte endMovie__Q24Game12EnemyMgrBaseFv .4byte get__Q24Game12EnemyMgrBaseFPv .4byte isAlwaysMovieActor__Q24Game12EnemyMgrBaseFv .4byte createObj__Q34Game6Kurage3MgrFi .4byte getEnemy__Q34Game6Kurage3MgrFi .4byte doAlloc__Q34Game6Kurage3MgrFv .4byte getEnemyTypeID__Q34Game6Kurage3MgrFv .4byte createModel__Q24Game12EnemyMgrBaseFv .4byte initParms__Q24Game12EnemyMgrBaseFv .4byte loadResource__Q24Game12EnemyMgrBaseFv .4byte initObjects__Q24Game12EnemyMgrBaseFv .4byte initStoneSetting__Q24Game12EnemyMgrBaseFv .4byte loadModelData__Q24Game12EnemyMgrBaseFP10JKRArchive .4byte loadModelData__Q34Game6Kurage3MgrFv .4byte loadAnimData__Q24Game12EnemyMgrBaseFv .4byte loadTexData__Q24Game12EnemyMgrBaseFv .4byte doLoadBmd__Q34Game6Kurage3MgrFPv .4byte doLoadBdl__Q24Game12EnemyMgrBaseFPv .4byte initGenerator__Q24Game12EnemyMgrBaseFv .global __vt__Q34Game6Kurage5Parms __vt__Q34Game6Kurage5Parms: .4byte 0 .4byte 0 .4byte read__Q34Game6Kurage5ParmsFR6Stream .4byte 0 .section .sdata2, "a" # 0x80516360 - 0x80520E40 .global lbl_8051C0A0 lbl_8051C0A0: .4byte 0x42B40000 .global lbl_8051C0A4 lbl_8051C0A4: .4byte 0x00000000 .global lbl_8051C0A8 lbl_8051C0A8: .4byte 0x43160000 .global lbl_8051C0AC lbl_8051C0AC: .float 1.0 .global lbl_8051C0B0 lbl_8051C0B0: .4byte 0x41200000 .global lbl_8051C0B4 lbl_8051C0B4: .4byte 0x40400000 .global lbl_8051C0B8 lbl_8051C0B8: .4byte 0x40A00000 .global lbl_8051C0BC lbl_8051C0BC: .4byte 0x3CCCCCCD */ namespace Game { /* * --INFO-- * Address: 802AD104 * Size: 000050 */ Kurage::Mgr::Mgr(int, unsigned char) { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r3 bl __ct__Q24Game12EnemyMgrBaseFiUc lis r3, __vt__Q34Game6Kurage3Mgr@ha lis r4, lbl_80489A48@ha addi r5, r3, __vt__Q34Game6Kurage3Mgr@l mr r3, r31 stw r5, 0(r31) addi r5, r5, 0x38 addi r0, r4, lbl_80489A48@l stw r5, 4(r31) stw r0, 0x18(r31) lwz r31, 0xc(r1) lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 802AD154 * Size: 000048 */ void Kurage::Mgr::doAlloc() { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r3 li r3, 0x948 bl __nw__FUl or. r4, r3, r3 beq lbl_802AD180 bl __ct__Q34Game6Kurage5ParmsFv mr r4, r3 lbl_802AD180: mr r3, r31 bl init__Q24Game12EnemyMgrBaseFPQ24Game14EnemyParmsBase lwz r0, 0x14(r1) lwz r31, 0xc(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 802AD19C * Size: 000048 */ Kurage::Parms::Parms() { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r3 bl __ct__Q24Game14EnemyParmsBaseFv lis r4, __vt__Q34Game6Kurage5Parms@ha addi r3, r31, 0x7f8 addi r0, r4, __vt__Q34Game6Kurage5Parms@l li r4, 1 stw r0, 0xd8(r31) bl __ct__Q44Game6Kurage5Parms11ProperParmsFv lwz r0, 0x14(r1) mr r3, r31 lwz r31, 0xc(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 802AD1E4 * Size: 00023C */ Kurage::Parms::ProperParms::ProperParms() { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) extsh. r0, r4 lis r4, lbl_80489A38@ha stw r31, 0xc(r1) addi r31, r4, lbl_80489A38@l stw r30, 8(r1) mr r30, r3 beq lbl_802AD214 addi r0, r30, 0x14c stw r0, 0(r30) lbl_802AD214: li r0, 0 lis r5, 0x66703031@ha stw r0, 4(r30) addi r0, r31, 0x2c mr r4, r30 addi r3, r30, 0xc stw r0, 8(r30) addi r5, r5, 0x66703031@l addi r6, r31, 0x3c bl __ct__8BaseParmFP10ParametersUlPc lis r3, "__vt__7Parm<f>"@ha lis r5, 0x66703032@ha addi r0, r3, "__vt__7Parm<f>"@l lfs f0, lbl_8051C0A0@sda21(r2) stw r0, 0xc(r30) mr r4, r30 lfs f1, lbl_8051C0A4@sda21(r2) addi r3, r30, 0x34 stfs f0, 0x24(r30) addi r5, r5, 0x66703032@l lfs f0, lbl_8051C0A8@sda21(r2) addi r6, r31, 0x48 stfs f1, 0x2c(r30) stfs f0, 0x30(r30) bl __ct__8BaseParmFP10ParametersUlPc lis r3, "__vt__7Parm<f>"@ha lis r5, 0x66703130@ha addi r0, r3, "__vt__7Parm<f>"@l lfs f0, lbl_8051C0AC@sda21(r2) stw r0, 0x34(r30) mr r4, r30 lfs f1, lbl_8051C0A4@sda21(r2) addi r3, r30, 0x5c stfs f0, 0x4c(r30) addi r5, r5, 0x66703130@l lfs f0, lbl_8051C0B0@sda21(r2) addi r6, r31, 0x54 stfs f1, 0x54(r30) stfs f0, 0x58(r30) bl __ct__8BaseParmFP10ParametersUlPc lis r3, "__vt__7Parm<f>"@ha lis r5, 0x66703131@ha addi r0, r3, "__vt__7Parm<f>"@l lfs f0, lbl_8051C0B4@sda21(r2) stw r0, 0x5c(r30) mr r4, r30 lfs f1, lbl_8051C0A4@sda21(r2) addi r3, r30, 0x84 stfs f0, 0x74(r30) addi r5, r5, 0x66703131@l lfs f0, lbl_8051C0B0@sda21(r2) addi r6, r31, 0x68 stfs f1, 0x7c(r30) stfs f0, 0x80(r30) bl __ct__8BaseParmFP10ParametersUlPc lis r3, "__vt__7Parm<f>"@ha lis r5, 0x66703132@ha addi r0, r3, "__vt__7Parm<f>"@l lfs f0, lbl_8051C0B8@sda21(r2) stw r0, 0x84(r30) mr r4, r30 lfs f1, lbl_8051C0A4@sda21(r2) addi r3, r30, 0xac stfs f0, 0x9c(r30) addi r5, r5, 0x66703132@l lfs f0, lbl_8051C0B0@sda21(r2) addi r6, r31, 0x78 stfs f1, 0xa4(r30) stfs f0, 0xa8(r30) bl __ct__8BaseParmFP10ParametersUlPc lis r3, "__vt__7Parm<f>"@ha lis r5, 0x66703034@ha addi r0, r3, "__vt__7Parm<f>"@l lfs f0, lbl_8051C0BC@sda21(r2) stw r0, 0xac(r30) mr r4, r30 lfs f1, lbl_8051C0A4@sda21(r2) addi r3, r30, 0xd4 stfs f0, 0xc4(r30) addi r5, r5, 0x66703034@l lfs f0, lbl_8051C0AC@sda21(r2) addi r6, r31, 0x88 stfs f1, 0xcc(r30) stfs f0, 0xd0(r30) bl __ct__8BaseParmFP10ParametersUlPc lis r3, "__vt__7Parm<f>"@ha lis r5, 0x69703031@ha addi r0, r3, "__vt__7Parm<f>"@l lfs f0, lbl_8051C0B4@sda21(r2) stw r0, 0xd4(r30) mr r4, r30 lfs f1, lbl_8051C0A4@sda21(r2) addi r3, r30, 0xfc stfs f0, 0xec(r30) addi r5, r5, 0x69703031@l lfs f0, lbl_8051C0B0@sda21(r2) addi r6, r31, 0x98 stfs f1, 0xf4(r30) stfs f0, 0xf8(r30) bl __ct__8BaseParmFP10ParametersUlPc lis r3, "__vt__7Parm<i>"@ha lis r5, 0x69703131@ha addi r0, r3, "__vt__7Parm<i>"@l li r3, 0xa stw r0, 0xfc(r30) li r7, 1 li r0, 0x32 mr r4, r30 stw r3, 0x114(r30) addi r3, r30, 0x124 addi r5, r5, 0x69703131@l addi r6, r31, 0xa8 stw r7, 0x11c(r30) stw r0, 0x120(r30) bl __ct__8BaseParmFP10ParametersUlPc lis r3, "__vt__7Parm<i>"@ha li r5, 0xa addi r0, r3, "__vt__7Parm<i>"@l li r4, 1 stw r0, 0x124(r30) li r0, 0x64 mr r3, r30 stw r5, 0x13c(r30) stw r4, 0x144(r30) stw r0, 0x148(r30) lwz r31, 0xc(r1) lwz r30, 8(r1) lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 802AD420 * Size: 000060 */ void Kurage::Mgr::createObj(int) { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r4 stw r30, 8(r1) mr r30, r3 mulli r3, r31, 0x30c addi r3, r3, 0x10 bl __nwa__FUl lis r4, __ct__Q34Game6Kurage3ObjFv@ha lis r5, __dt__Q34Game6Kurage3ObjFv@ha addi r4, r4, __ct__Q34Game6Kurage3ObjFv@l mr r7, r31 addi r5, r5, __dt__Q34Game6Kurage3ObjFv@l li r6, 0x30c bl __construct_new_array stw r3, 0x44(r30) lwz r0, 0x14(r1) lwz r31, 0xc(r1) lwz r30, 8(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 802AD480 * Size: 0000BC */ Kurage::Obj::~Obj() { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) or. r31, r3, r3 stw r30, 8(r1) mr r30, r4 beq lbl_802AD520 lis r3, __vt__Q34Game6Kurage3Obj@ha addi r0, r31, 0x2fc addi r4, r3, __vt__Q34Game6Kurage3Obj@l stw r4, 0(r31) addi r3, r4, 0x1b0 addi r4, r4, 0x2fc stw r3, 0x178(r31) lwz r3, 0x17c(r31) stw r4, 0(r3) lwz r3, 0x17c(r31) subf r0, r3, r0 stw r0, 0xc(r3) beq lbl_802AD510 lis r3, __vt__Q24Game9EnemyBase@ha addi r0, r31, 0x2bc addi r4, r3, __vt__Q24Game9EnemyBase@l addi r3, r31, 0x290 stw r4, 0(r31) addi r5, r4, 0x1b0 addi r6, r4, 0x2f8 li r4, -1 stw r5, 0x178(r31) lwz r5, 0x17c(r31) stw r6, 0(r5) lwz r5, 0x17c(r31) subf r0, r5, r0 stw r0, 0xc(r5) bl __dt__5CNodeFv lbl_802AD510: extsh. r0, r30 ble lbl_802AD520 mr r3, r31 bl __dl__FPv lbl_802AD520: lwz r0, 0x14(r1) mr r3, r31 lwz r31, 0xc(r1) lwz r30, 8(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 802AD53C * Size: 000010 */ void Kurage::Mgr::getEnemy(int) { /* mulli r0, r4, 0x30c lwz r3, 0x44(r3) add r3, r3, r0 blr */ } /* * --INFO-- * Address: 802AD54C * Size: 000068 */ void Kurage::Mgr::loadModelData() { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r3 bl loadModelData__Q24Game12EnemyMgrBaseFv li r5, 0 b lbl_802AD58C lbl_802AD56C: lwz r3, 0x80(r4) rlwinm r0, r5, 2, 0xe, 0x1d addi r5, r5, 1 lwzx r3, r3, r0 lwz r0, 0xc(r3) rlwinm r0, r0, 0, 0x14, 0xf ori r0, r0, 0x2000 stw r0, 0xc(r3) lbl_802AD58C: lwz r4, 0x1c(r31) clrlwi r0, r5, 0x10 lhz r3, 0x7c(r4) cmplw r0, r3 blt lbl_802AD56C lwz r0, 0x14(r1) lwz r31, 0xc(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 802AD5B4 * Size: 0000B0 */ Kurage::Mgr::~Mgr() { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r4 stw r30, 8(r1) or. r30, r3, r3 beq lbl_802AD648 lis r3, __vt__Q34Game6Kurage3Mgr@ha addi r3, r3, __vt__Q34Game6Kurage3Mgr@l stw r3, 0(r30) addi r0, r3, 0x38 stw r0, 4(r30) beq lbl_802AD638 lis r3, __vt__Q24Game12EnemyMgrBase@ha addi r3, r3, __vt__Q24Game12EnemyMgrBase@l stw r3, 0(r30) addi r0, r3, 0x38 stw r0, 4(r30) beq lbl_802AD638 lis r3, __vt__Q24Game13IEnemyMgrBase@ha addic. r0, r30, 4 addi r3, r3, __vt__Q24Game13IEnemyMgrBase@l stw r3, 0(r30) addi r0, r3, 0x38 stw r0, 4(r30) beq lbl_802AD638 lis r4, __vt__16GenericContainer@ha addi r3, r30, 4 addi r0, r4, __vt__16GenericContainer@l li r4, 0 stw r0, 4(r30) bl __dt__5CNodeFv lbl_802AD638: extsh. r0, r31 ble lbl_802AD648 mr r3, r30 bl __dl__FPv lbl_802AD648: lwz r0, 0x14(r1) mr r3, r30 lwz r31, 0xc(r1) lwz r30, 8(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 802AD664 * Size: 000008 */ u32 Kurage::Mgr::getEnemyTypeID() { return 0x39; } /* * --INFO-- * Address: 802AD66C * Size: 00002C */ void Kurage::Mgr::doLoadBmd(void*) { /* stwu r1, -0x10(r1) mflr r0 lis r5, 0x20240030@ha mr r3, r4 stw r0, 0x14(r1) addi r4, r5, 0x20240030@l bl load__22J3DModelLoaderDataBaseFPCvUl lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 802AD698 * Size: 000050 */ void Kurage::Parms::read(Stream&) { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r4 stw r30, 8(r1) mr r30, r3 bl read__10ParametersFR6Stream mr r4, r31 addi r3, r30, 0xe0 bl read__10ParametersFR6Stream mr r4, r31 addi r3, r30, 0x7f8 bl read__10ParametersFR6Stream lwz r0, 0x14(r1) lwz r31, 0xc(r1) lwz r30, 8(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 802AD6E8 * Size: 000008 */ Kurage::Mgr::@4 @~Mgr() { /* addi r3, r3, -4 b __dt__Q34Game6Kurage3MgrFv */ } } // namespace Game
23.906651
71
0.600693
projectPiki
ef8c888becd0e0a6ca8f8b9de99a57389fd0b41f
2,121
cpp
C++
Day 06 Part 2/main.cpp
Miroslav-Cetojevic/aoc-2015
2807fcd3fc684843ae4222b25af6fd086fac77f5
[ "Unlicense" ]
1
2019-11-19T20:19:18.000Z
2019-11-19T20:19:18.000Z
Day 06 Part 2/main.cpp
Miroslav-Cetojevic/aoc-2015
2807fcd3fc684843ae4222b25af6fd086fac77f5
[ "Unlicense" ]
null
null
null
Day 06 Part 2/main.cpp
Miroslav-Cetojevic/aoc-2015
2807fcd3fc684843ae4222b25af6fd086fac77f5
[ "Unlicense" ]
null
null
null
#include <array> #include <fstream> #include <iostream> #include <numeric> #include <string_view> #include <unordered_map> #include <boost/range/irange.hpp> #include <boost/range/istream_range.hpp> enum class Cmd { on, off, toggle }; using uint64 = std::uint64_t; struct Position { uint64 row, col; }; struct EndPoints { std::string state; Position first, last; }; auto& operator>>(std::istream& in, Position& pos) { return in >> pos.row >> pos.col; } auto& operator>>(std::istream& in, EndPoints& pos) { return in >> pos.state >> pos.first >> pos.last; } auto get_total_brightness(std::fstream& file) { constexpr auto gridlen = uint64{1000}; constexpr auto numlights = (gridlen * gridlen); auto grid = std::array<uint64, numlights>{}; const auto commands = std::unordered_map<std::string_view, Cmd>{ {"on", Cmd::on}, {"off", Cmd::off}, {"toggle", Cmd::toggle} }; const auto stream = boost::istream_range<EndPoints>(file); for(const auto& endpoints : stream) { const auto command = commands.find(endpoints.state)->second; const auto& first = endpoints.first; const auto& last = endpoints.last; const auto begin_row = first.row; const auto end_row = (last.row + 1); for(const auto row : boost::irange(begin_row, end_row)) { const auto begin_col = first.col; const auto end_col = (last.col + 1); for(const auto col : boost::irange(begin_col, end_col)) { const auto pos = (row * gridlen + col); switch(command) { case Cmd::on: ++grid[pos]; break; case Cmd::off: grid[pos] -= (grid[pos] > 0); break; case Cmd::toggle: grid[pos] += 2; break; default: std::cerr << "WTF?!? Something went really wrong!" << std::endl; } } } } return std::accumulate(grid.begin(), grid.end(), uint64{}); } int main() { const auto filename = std::string{"instructions.txt"}; auto file = std::fstream{filename}; if(file.is_open()) { std::cout << get_total_brightness(file) << std::endl; } else { std::cerr << "Error! Could not open \"" << filename << "\"!" << std::endl; } return 0; }
21
76
0.634135
Miroslav-Cetojevic
ef8e15eaa0e8267adccdb721ed462f9d1aaacda9
2,069
cpp
C++
lib/lib_http/lib_http.cpp
genesos/brain-launcher-bhdll
6a352bb6a7db9b9c74d940d476ee8a2e7c586683
[ "OML" ]
null
null
null
lib/lib_http/lib_http.cpp
genesos/brain-launcher-bhdll
6a352bb6a7db9b9c74d940d476ee8a2e7c586683
[ "OML" ]
null
null
null
lib/lib_http/lib_http.cpp
genesos/brain-launcher-bhdll
6a352bb6a7db9b9c74d940d476ee8a2e7c586683
[ "OML" ]
null
null
null
#include <afxinet.h> #include "lib_http.h" #include "../GenesisLib/file.h" #include <memory> using std::auto_ptr; using std::wstring; void getWebDownloadToFileCurDir( wstring target, wstring to, boost::function<void(int, bool&)> callback) { getWebDownloadToFile(target, getModuleAbsPath() + to, callback); } void getWebDownloadToFile( wstring target, wstring to, boost::function<void(int, bool&)> callback) { wstringstream wsslog; wsslog<<target<<_T(" => ")<<to; LOG(wsslog); try { wstring fileName = to; wstring dir; { int dirIndex = to.find_last_of(L'\\'); if(dirIndex>=0) { fileName = to.substr(dirIndex+1); dir = to.substr(0,dirIndex); } } if(fileName[0]==L'-') { to = dir+L"\\"+fileName.substr(1); CFile::Remove(to.c_str()); RemoveDirectory(to.c_str()); } else { if(dir.length()>0) { CreateDirectory(dir.c_str(),0); } CFile fDestFile((to).c_str(),CFile::modeCreate|CFile::modeWrite|CFile::typeBinary); CInternetSession netSession; auto_ptr<CStdioFile> fTargetFile(netSession.OpenURL(target.c_str(),1,INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_RELOAD)); bool shutdownDownload = 0; if(fTargetFile.get()) { UINT readLen; char buf[512]; while (readLen = fTargetFile->Read(buf,512)) { fDestFile.Write(buf,readLen); if(callback) { callback(readLen, shutdownDownload); if(shutdownDownload) return; } } } } } catch(CInternetException*) { } catch(CFileException*) { } catch(CException*) { } } wstring getWebDownloadToString( wstring target) { wstringstream wsslog; wsslog<<target<<_T(" => [LOCAL]"); LOG(wsslog); string ret(""); try { CInternetSession netSession; auto_ptr<CStdioFile> fTargetFile(netSession.OpenURL(target.c_str(),1,INTERNET_FLAG_TRANSFER_ASCII|INTERNET_FLAG_RELOAD)); if(fTargetFile.get()) { UINT readLen; char buf[512]; while (readLen=fTargetFile->Read(buf,512)) ret.append(buf,readLen); } } catch(CInternetException*) { } return encodeUNI(ret); }
19.704762
125
0.666022
genesos
ef8e6be06ae45c92cfcdd49c16833dbfe7413078
3,812
cc
C++
src/core/image_io/image_io_png.cc
zhehangd/qjulia2
b6816f5af580534fdb27051ae2bfd7fe47a1a60c
[ "MIT" ]
null
null
null
src/core/image_io/image_io_png.cc
zhehangd/qjulia2
b6816f5af580534fdb27051ae2bfd7fe47a1a60c
[ "MIT" ]
null
null
null
src/core/image_io/image_io_png.cc
zhehangd/qjulia2
b6816f5af580534fdb27051ae2bfd7fe47a1a60c
[ "MIT" ]
null
null
null
#include "image_io_png.h" #include <cstring> #include <vector> #include <png.h> namespace qjulia { void PNGImageReader::ReadImage(const std::string &filename, RGBImage &image) { FILE *fp = fopen(filename.c_str(), "rb"); CHECK(fp); png_byte header[8]; CHECK_EQ(8, fread(header, 1, 8, fp)); CHECK (png_sig_cmp(header, 0, 8) == 0); auto* png_ptr = png_create_read_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); CHECK(png_ptr); auto *info_ptr = png_create_info_struct(png_ptr); CHECK(info_ptr); int setjmp_ret = setjmp(png_jmpbuf(png_ptr)); CHECK(setjmp_ret == 0); png_init_io(png_ptr, fp); png_set_sig_bytes(png_ptr, 8); png_read_info(png_ptr, info_ptr); int width = png_get_image_width(png_ptr, info_ptr); int height = png_get_image_height(png_ptr, info_ptr); png_byte color_type = png_get_color_type(png_ptr, info_ptr); png_byte bit_depth = png_get_bit_depth(png_ptr, info_ptr); CHECK_EQ(bit_depth, 8); CHECK_EQ(color_type, PNG_COLOR_TYPE_RGB); int number_of_passes = png_set_interlace_handling(png_ptr); (void)number_of_passes; png_read_update_info(png_ptr, info_ptr); setjmp_ret = setjmp(png_jmpbuf(png_ptr)); CHECK(setjmp_ret == 0); auto btype_per_row = png_get_rowbytes(png_ptr, info_ptr); CHECK((int)btype_per_row == width * 3); image.Resize(Size(width, height)); auto *data_ptr = image.Data()->vals; std::vector<png_bytep> row_ptrs(height); for (int r = 0; r < height; ++r) {row_ptrs[r] = data_ptr + r * btype_per_row;} png_read_image(png_ptr, row_ptrs.data()); png_read_end(png_ptr, info_ptr); fclose(fp); } void PNGImageReader::ReadImage(const std::string &filename, RGBFloatImage &image) { (void)filename; (void)image; throw NoImageSpecificationSupport(""); } void PNGImageReader::ReadImage(const std::string &filename, GrayscaleImage &image) { (void)filename; (void)image; throw NoImageSpecificationSupport(""); } void PNGImageReader::ReadImage(const std::string &filename, GrayscaleFloatImage &image) { (void)filename; (void)image; throw NoImageSpecificationSupport(""); } void PNGImageWriter::WriteImage(const std::string &filename, const RGBImage &image) { FILE *fp = fopen(filename.c_str(), "wb"); CHECK_NOTNULL(fp); auto* png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); CHECK_NOTNULL(png_ptr); auto* info_ptr = png_create_info_struct(png_ptr); CHECK_NOTNULL(info_ptr); CHECK_EQ(setjmp(png_jmpbuf(png_ptr)), 0); png_init_io(png_ptr, fp); CHECK_EQ(setjmp(png_jmpbuf(png_ptr)), 0); png_byte bit_depth = 8; png_byte color_type = PNG_COLOR_TYPE_RGB; int width = image.Width(); int height = image.Height(); png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth, color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(png_ptr, info_ptr); CHECK_EQ(setjmp(png_jmpbuf(png_ptr)), 0); auto *data_ptr = image.Data()->vals; std::vector<png_bytep> row_ptrs(height); for (int r = 0; r < height; ++r) {row_ptrs[r] = const_cast<png_bytep>(data_ptr) + r * width * 3;} png_write_image(png_ptr, row_ptrs.data()); CHECK_EQ(setjmp(png_jmpbuf(png_ptr)), 0); png_write_end(png_ptr, NULL); fclose(fp); } void PNGImageWriter::WriteImage(const std::string &filename, const RGBFloatImage &image) { (void)filename; (void)image; throw NoImageSpecificationSupport(""); } void PNGImageWriter::WriteImage(const std::string &filename, const GrayscaleImage &image) { (void)filename; (void)image; throw NoImageSpecificationSupport(""); } void PNGImageWriter::WriteImage(const std::string &filename, const GrayscaleFloatImage &image) { (void)filename; (void)image; throw NoImageSpecificationSupport(""); } }
28.237037
99
0.71852
zhehangd
ef92dc4f05392a981f980e0039803d85ac935153
519
hpp
C++
include/controller/guards/is_swap_items_winning.hpp
modern-cpp-examples/match3
bb1f4de11db9e92b6ebdf80f1afe9245e6f86b7e
[ "BSL-1.0" ]
166
2016-04-27T19:01:00.000Z
2022-03-27T02:16:55.000Z
include/controller/guards/is_swap_items_winning.hpp
Fuyutsubaki/match3
bb1f4de11db9e92b6ebdf80f1afe9245e6f86b7e
[ "BSL-1.0" ]
4
2016-05-19T07:47:38.000Z
2018-03-22T04:33:00.000Z
include/controller/guards/is_swap_items_winning.hpp
Fuyutsubaki/match3
bb1f4de11db9e92b6ebdf80f1afe9245e6f86b7e
[ "BSL-1.0" ]
17
2016-05-18T21:17:39.000Z
2022-03-20T22:37:14.000Z
// // Copyright (c) 2016 Krzysztof Jusiak (krzysztof at jusiak dot net) // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #pragma once #include <cassert> #include "controller/data/selected.hpp" #include "model/board.hpp" namespace match3 { const auto is_swap_items_winning = [](const board& b, const selected& s) { assert(s.size() == 2); return b.is_match(s[0]) || b.is_match(s[1]); }; } // match3
23.590909
74
0.697495
modern-cpp-examples
ef94f926c766100b8c004d9d63e70ce4289adc37
417
cpp
C++
leetcode/12.cpp
windniw/just-for-fun
54e5c2be145f3848811bfd127f6a89545e921570
[ "Apache-2.0" ]
1
2019-08-28T23:15:25.000Z
2019-08-28T23:15:25.000Z
leetcode/12.cpp
windniw/just-for-fun
54e5c2be145f3848811bfd127f6a89545e921570
[ "Apache-2.0" ]
null
null
null
leetcode/12.cpp
windniw/just-for-fun
54e5c2be145f3848811bfd127f6a89545e921570
[ "Apache-2.0" ]
null
null
null
class Solution { public: string intToRoman(int num) { string arr[] ={"","I","II","III","IV","V","VI","VII","VIII","IX", "","X","XX","XXX","XL","L","LX","LXX","LXXX","XC", "","C","CC","CCC","CD","D","DC","DCC","DCCC","CM", "","M","MM","MMM"}; return arr[30+num/1000]+arr[20+num%1000/100]+arr[10+num%100/10]+arr[num%10]; } };
37.909091
84
0.407674
windniw
ef95b6a5e266b9a6e93c3a10ddd650d041b76ca8
4,515
cpp
C++
hexx.cpp
kwadrat/project_al
c53c81a50940717511212b80a013a7e5a79b5ff5
[ "MIT" ]
null
null
null
hexx.cpp
kwadrat/project_al
c53c81a50940717511212b80a013a7e5a79b5ff5
[ "MIT" ]
null
null
null
hexx.cpp
kwadrat/project_al
c53c81a50940717511212b80a013a7e5a79b5ff5
[ "MIT" ]
null
null
null
#ifndef _HEXX_CPP #define _HEXX_CPP #include "hexx.h" #include <string.h> #include <stdlib.h> int HexClass::Init(int, char *[]) { IleBuf = 0; /* Na razie w "Buf" nie ma żadnych znaków */ LiczBajtow = 0; /* Nie przekonwertowaliśmy jeszcze żadnych bajtów */ RunOnce = 1; return 1; } void HexClass::Work(void) { int ile; if(RunOnce) { RunOnce = 0; DescribeColumns(); } while((ile = PrevBuf->GetByteArea((Byte *)(Buf_in + IleBuf), HEXX_SZER - IleBuf)) > 0) { IleBuf += ile; if(IleBuf > HEXX_SZER || IleBuf < 0) { SygError("Zła liczba danych w buforze!"); exit(0); } else { if(IleBuf == HEXX_SZER) /* Czy mamy już pełny bufor */ { /* Zaczynamy wydruk treści bufora w trybie szesnastkowym */ LineOut(); } } } if(ile == EOF) { if(IleBuf != 0) /* Czy coś jest w buforze do wydruku */ { LineOut(); /* Wyświetl ostatnią linijkę bufora */ } SignalEndOfData(); } } /* Drukuje w porządnym formacie linijkę tekstu */ void HexClass::LineOut(void) { int i; Byte b; /* - drukuj numer bajtu - drukuj kolejne wartości w trybie HEX - drukuj wartości w trybie ASCII - koniec linii - zwiększ liczbę pokazanych bajtów */ memset(Linia, ' ', HEXX_CPR); sprintf(Pcs, "%08x ", LiczBajtow); strncpy(Linia, Pcs, HEX_OFFSET); for(i = 0; i < IleBuf; i++) { sprintf(Pcs, "%02x", (Byte) Buf_in[i]); strncpy(Linia + HEX_OFFSET + 3 * i, Pcs, 2); } for(i = 0; i < IleBuf; i++) { b = (Byte) Buf_in[i]; Linia[TXT_OFFSET + i] = ((b < 32) || (b > 126)) ? '.' : (char) b; } Linia[NEWLINE_OFFSET] = '\n'; NextBuf->PutByteArea((Byte *)Linia, ZERO_OFFSET); /* Wydruk aż do znaku LF */ LiczBajtow += IleBuf; IleBuf = 0; } int UnHexClass::Init(int, char *[]) { IleWLinii = 0; /* Na początku bufor jest pusty */ return 1; } /* Funkcja przekształcająca linię ASCII w plik binarny, zgodnie z "hex" */ void UnHexClass::Work(void) { int ile; while((ile = PrevBuf->GetByteArea((Byte *)(Linia + IleWLinii), (IleWLinii == 0) ? 76 : 1)) > 0) { IleWLinii += ile; if(IleWLinii >= HEXX_CPR) /* Czy przekraczamy pojemność bufora */ { SygError("Przekroczenie wielkości bufora Linia."); exit(0); } else { if(Linia[IleWLinii - 1] == '\n') /* Czy osiągnęliśmy koniec linii */ { DecodeLine(); /* Wydrukuj linię */ } } } if(ile == EOF) { if(IleWLinii > 0) { DecodeLine(); /* Próbujemy dekodować ostatnie znaki */ } else { if(IleWLinii < 0) { SygError("Ujemna liczba znaków w buforze !"); } } SignalEndOfData(); } } /* Funkcja próbuje dekodować linię */ void UnHexClass::DecodeLine(void) { int value; int i; for(i = 0; i < 16; i++) { Linia[HEX_OFFSET + 3 * i + 2] = '\0'; /* Zakończ napis - nie ma więcej znaków */ if(sscanf(Linia + HEX_OFFSET + 3 * i, "%x", & value) == 1) { /* Tu mamy już zdekodowaną liczbę, teraz ją wysyłamy */ Buf_out[i] = (char) value; } else { break; /* Koniec wczytywania - napotkaliśmy dziwny znak */ } } NextBuf->PutByteArea((Byte *) Buf_out, i); /* Wyślij zebraną linię */ IleWLinii = 0; /* Nie mamy już znaków w linii */ memset(Linia, '\0', HEXX_CPR); /* Czyścimy pamięć */ } void HexClass::DescribeColumns(void) { int i; memset(Linia, ' ', HEXX_CPR); sprintf(Pcs, "offset "); /* Etykieta */ strncpy(Linia, Pcs, HEX_OFFSET); for(i = 0; i < HEXX_SZER; i++) { sprintf(Pcs, "%02x", (Byte) i); strncpy(Linia + HEX_OFFSET + 3 * i, Pcs, 2); } for(i = 0; i < HEXX_SZER; i++) { if(!(i % 4)) { sprintf(Pcs, "%02x", (Byte) i); strncpy(Linia + TXT_OFFSET + i, Pcs, 2); } } Linia[NEWLINE_OFFSET] = '\n'; NextBuf->PutByteArea((Byte *)Linia, ZERO_OFFSET); /* Wydruk aż do znaku LF */ Linia[0] = '\n'; NextBuf->PutByteArea((Byte *)Linia, 1); /* Wydruk pustej linii oddzielającej nagłówek od danych */ } #endif
24.944751
102
0.512957
kwadrat
ef96f571444f20231766f10544923f83f839b25d
4,586
cpp
C++
src/backend/VirtualMemory.cpp
athenaforai/athena
20381d9069fac901666fe5296cdb443c8969bf4a
[ "MIT" ]
null
null
null
src/backend/VirtualMemory.cpp
athenaforai/athena
20381d9069fac901666fe5296cdb443c8969bf4a
[ "MIT" ]
null
null
null
src/backend/VirtualMemory.cpp
athenaforai/athena
20381d9069fac901666fe5296cdb443c8969bf4a
[ "MIT" ]
null
null
null
/* * Copyright (c) 2018 Athena. All rights reserved. * https://athenaframework.ml * * Licensed under MIT 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 "VirtualMemory.h" #include <core/DataType.h> athena::backend::VirtualMemory::VirtualMemory () { head = new VMemoryBlock; head->isUsed = false; head->startAddress = 1; head->endAddress = LONG_MAX; head->nextBlock = nullptr; head->prevBlock = nullptr; maxMemoryUsage = 0; curMemoryUsage = 0; } vm_word athena::backend::VirtualMemory::allocate ( athena::core::Tensor* tensor ) { VMemoryBlock* cur = head; unsigned long memNeeded = tensor->getShape().totalSize() * athena::core::typesize( tensor->getType()); bool allocated = false; while ( cur != nullptr && !allocated ) { if ( !cur->isUsed && (cur->endAddress - cur->startAddress) >= memNeeded ) { auto newUsedBlock = new VMemoryBlock; newUsedBlock->isUsed = true; newUsedBlock->startAddress = cur->startAddress; newUsedBlock->endAddress = newUsedBlock->startAddress + memNeeded; newUsedBlock->prevBlock = cur->prevBlock; if ( cur->prevBlock != nullptr ) { cur->prevBlock->nextBlock = newUsedBlock; } if ( cur->endAddress - cur->startAddress > memNeeded ) { auto freeBlock = new VMemoryBlock; freeBlock->isUsed = false; freeBlock->startAddress = newUsedBlock->endAddress; freeBlock->endAddress = cur->endAddress; freeBlock->nextBlock = cur->nextBlock; freeBlock->prevBlock = newUsedBlock; newUsedBlock->nextBlock = freeBlock; if ( cur->nextBlock != nullptr ) { cur->nextBlock->prevBlock = freeBlock; } } else { newUsedBlock->nextBlock = cur->nextBlock; if ( cur->nextBlock != nullptr ) { cur->nextBlock->prevBlock = newUsedBlock; } } allocated = true; curMemoryUsage += memNeeded; if ( curMemoryUsage > maxMemoryUsage ) { maxMemoryUsage = curMemoryUsage; } cur->nextBlock = nullptr; cur->prevBlock = nullptr; if ( cur == head ) { head = newUsedBlock; } delete cur; cur = newUsedBlock; } else { cur = cur->nextBlock; } } if ( !allocated ) { throw std::runtime_error( "OutOfMemory error" ); } tensor->setStartAddress( cur->startAddress ); tensors.push_back( tensor ); return cur->startAddress; } void athena::backend::VirtualMemory::free ( vm_word virtualAddress ) { VMemoryBlock *cur = head; bool found = false; while ( cur != nullptr && !found ) { if ( cur->startAddress == virtualAddress ) { cur->isUsed = false; curMemoryUsage -= cur->endAddress - cur->startAddress; // merge two free blocks if ( cur->nextBlock != nullptr && !cur->nextBlock->isUsed ) { VMemoryBlock *old = cur->nextBlock; cur->endAddress = old->endAddress; if ( old->nextBlock != nullptr ) { old->nextBlock->prevBlock = cur; } cur->nextBlock = old->nextBlock; old->nextBlock = nullptr; old->prevBlock = nullptr; delete old; } found = true; } else { cur = cur->nextBlock; } } for ( unsigned long i = 0; i < tensors.size(); i++ ) { if ( tensors[ i ]->getStartAddress() == virtualAddress ) { tensors.erase( tensors.begin() + i ); break; } } } void athena::backend::VirtualMemory::free ( athena::core::Tensor* tensor ) { free( tensor->getStartAddress()); } athena::core::Tensor* athena::backend::VirtualMemory::getTensor ( vm_word address ) { for ( auto &tensor : tensors ) { if ( tensor->getStartAddress() == address ) { return tensor; } } return nullptr; }
30.573333
85
0.551243
athenaforai
ef9741d94d95e954c3f79546db000b312ba003c0
1,047
cpp
C++
LightOJ/1017 - Brush (III)/sol.cpp
Tahsin716/OnlineJudge
a5d15f37a8c260740c148370ced7a2a9096050c1
[ "MIT" ]
null
null
null
LightOJ/1017 - Brush (III)/sol.cpp
Tahsin716/OnlineJudge
a5d15f37a8c260740c148370ced7a2a9096050c1
[ "MIT" ]
null
null
null
LightOJ/1017 - Brush (III)/sol.cpp
Tahsin716/OnlineJudge
a5d15f37a8c260740c148370ced7a2a9096050c1
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; int points[101], dp[101][101]; int n, brushWidth, moves; int rec(int position, int remainingMoves) { if (position >= n || remainingMoves == 0) { return 0; } if (dp[position][remainingMoves] != -1) return dp[position][remainingMoves]; int ret = -1; int brushCoverage = points[position] + brushWidth; int taken = 0, index; for (index = position; index < n && points[index] <= brushCoverage; index++) { taken++; } taken += rec(index, remainingMoves - 1); int not_taken = rec(position + 1, remainingMoves); ret = max(taken, not_taken); return dp[position][remainingMoves] = ret; } int main() { int T, testCase = 0; int x, y; scanf("%d", &T); while (T--) { scanf("%d%d%d", &n, &brushWidth, &moves); memset(dp, -1, sizeof dp); for (int i = 0; i < n; i++) { scanf("%d%d", &x, &y); points[i] = y; } sort(points, points + n); printf("Case %d: %d\n", ++testCase, rec(0, moves)); } return 0; }
16.359375
77
0.606495
Tahsin716
ef97f81a67b5d6357f333e7a5bd0d70465cae787
1,685
hpp
C++
src/hanoi.hpp
deepgrace/giant
4070c79892957c8e9244eb7a3d7690a25970f769
[ "BSL-1.0" ]
6
2019-04-02T07:47:37.000Z
2021-05-31T08:01:04.000Z
src/hanoi.hpp
deepgrace/giant
4070c79892957c8e9244eb7a3d7690a25970f769
[ "BSL-1.0" ]
null
null
null
src/hanoi.hpp
deepgrace/giant
4070c79892957c8e9244eb7a3d7690a25970f769
[ "BSL-1.0" ]
4
2019-04-15T08:52:17.000Z
2022-03-25T10:29:57.000Z
// // Copyright (c) 2016-present DeepGrace (complex dot invoke at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/deepgrace/giant // #include <stack> #include <array> #include <iostream> using namespace std; /* _ _ _ | | | | | | _| |_ | | | | |_____| | | | | |_______| | | | | |_________| | | | | |___________| | | | | |_____________| | | | | |_______________| _______| |_______ _______| |_______ | | | | | | ----------------------------------------------------------------------------- #0 #1 #2 */ template <typename T> void hanoi(int n, array<stack<T>, 3>& peg, int from, int to, int use) { if (n > 0) { hanoi(n - 1, peg, from, use, to); peg[to].push(peg[from].top()); peg[from].pop(); cout << from << " -> " << to << endl; hanoi(n - 1, peg, use, to, from); } } template <typename T = int> void move(int n) { array<stack<T>, 3> peg; for (int i = n; i > 0; --i) peg[0].push(i); hanoi(n, peg, 0, 1, 2); }
33.039216
90
0.35727
deepgrace
aab347709abd920f72cf8ed3c232d44e892c4592
12,426
cpp
C++
tools/utilities/finetune/src/DataStatistics.cpp
awf/ELL
25c94a1422efc41d5560db11b136f9d8f957ad41
[ "MIT" ]
2,094
2016-09-28T05:55:24.000Z
2019-05-04T19:06:36.000Z
tools/utilities/finetune/src/DataStatistics.cpp
awesomemachinelearning/ELL
cb897e3aec148a1e9bd648012b5f53ab9d0dd20c
[ "MIT" ]
213
2017-06-30T12:53:40.000Z
2019-05-03T06:35:38.000Z
tools/utilities/finetune/src/DataStatistics.cpp
awesomemachinelearning/ELL
cb897e3aec148a1e9bd648012b5f53ab9d0dd20c
[ "MIT" ]
301
2017-03-24T08:40:00.000Z
2019-05-02T21:22:28.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////// // // Project: Embedded Learning Library (ELL) // File: DataStatistics.cpp (utilities) // Authors: Chuck Jacobs // //////////////////////////////////////////////////////////////////////////////////////////////////// #include "DataStatistics.h" #include "ModelUtils.h" #include "MultidimArray.h" #include <data/include/DataVector.h> #include <math/include/Transformations.h> #include <math/include/Vector.h> #include <math/include/VectorOperations.h> #include <utilities/include/ZipIterator.h> #include <cmath> #include <map> #include <numeric> namespace ell { // Utilities namespace { void ThrowIfEmpty(const UnlabeledDataContainer& dataset) { if (dataset.Size() == 0) { throw utilities::InputException(utilities::InputExceptionErrors::badData, "Empty dataset"); } } template <typename T1, typename T2> void ThrowIfNotSameSize(const std::vector<T1>& a, const std::vector<T2>& b) { if (a.size() != b.size()) { throw utilities::InputException(utilities::InputExceptionErrors::badData, "Sizes don't match"); } } template <typename T1, typename T2> void ThrowIfNotSameSize(const math::RowVector<T1>& a, const math::RowVector<T2>& b) { if (a.Size() != b.Size()) { throw utilities::InputException(utilities::InputExceptionErrors::badData, "Sizes don't match"); } } template <typename T> math::RowVector<T> operator-(const math::RowVector<T>& a, const math::RowVector<T>& b) { ThrowIfNotSameSize(a, b); auto v = a; v -= b; return v; } template <typename T> math::RowVector<T>& operator*=(math::RowVector<T>& a, const math::RowVector<T>& b) { ThrowIfNotSameSize(a, b); auto size = a.Size(); for (size_t i = 0; i < size; ++i) { a[i] *= b[i]; } return a; } template <typename T> math::RowVector<T> operator*(const math::RowVector<T>& a, const math::RowVector<T>& b) { ThrowIfNotSameSize(a, b); auto v = a; v *= b; return v; } template <typename T> math::RowVector<T> operator/(const math::RowVector<T>& a, T denom) { auto v = a; v /= denom; return v; } template <typename T> math::RowVector<T>& operator/=(math::RowVector<T>& a, const math::RowVector<T>& b) { ThrowIfNotSameSize(a, b); auto size = a.Size(); for (size_t i = 0; i < size; ++i) { a[i] /= b[i]; } return a; } template <typename T> math::RowVector<T> Sqrt(const math::RowVector<T>& a) { auto v = a; auto xform = math::SquareRootTransformation<T>; v.Transform(xform); return v; } int GetNumRows(const UnlabeledDataContainer& dataset) { return dataset.Size(); } int GetNumColumns(const UnlabeledDataContainer& dataset) { ThrowIfEmpty(dataset); return dataset[0].Size(); } struct BasicDataStatistics { int numRows; std::vector<int64_t> numZeros; math::RowVector<double> sumElements; math::RowVector<double> sumSquaredElements; }; BasicDataStatistics GetBasicDataStatistics(const UnlabeledDataContainer& dataset, const utilities::MemoryLayout& layout) { ThrowIfEmpty(dataset); BasicDataStatistics result; auto columns = GetNumColumns(dataset); auto numZeros = std::vector<int64_t>(columns); auto sum = math::RowVector<double>(columns); auto sumSquares = math::RowVector<double>(columns); for (const auto& row : dataset) { auto x = CastVector<double>(row); for (int i = 0; i < columns; ++i) { if (x[i] == 0.0) ++numZeros[i]; } sum += x; sumSquares += math::Square(x); } return { GetNumRows(dataset), numZeros, sum, sumSquares, }; } BasicDataStatistics GetBasicDataStatistics(const UnlabeledDataContainer& dataset) { auto columns = GetNumColumns(dataset); utilities::MemoryLayout layout({ columns }); return GetBasicDataStatistics(dataset, layout); } template <typename WeightsType> Sparsity GetWeightsSparsity(const WeightsType& weights) // TODO: add layout { auto weightsVec = weights.ToArray(); auto numZeros = std::count_if(weightsVec.begin(), weightsVec.end(), [](auto a) { return a == 0; }); return { static_cast<int64_t>(weightsVec.size()), numZeros }; } template <typename NodeType> Sparsity GetNodeWeightsSparsity(const NodeType& node) { return GetWeightsSparsity(node.GetLayer().GetWeights()); } Sparsity GetNodeWeightsSparsity(const model::Node& node) { if (IsConvolutionalLayerNode<float>(&node)) { return GetNodeWeightsSparsity(static_cast<const nodes::ConvolutionalLayerNode<float>&>(node)); } if (IsConvolutionalLayerNode<double>(&node)) { return GetNodeWeightsSparsity(static_cast<const nodes::ConvolutionalLayerNode<double>&>(node)); } if (IsFullyConnectedLayerNode<float>(&node)) { return GetNodeWeightsSparsity(static_cast<const nodes::FullyConnectedLayerNode<float>&>(node)); } if (IsFullyConnectedLayerNode<double>(&node)) { return GetNodeWeightsSparsity(static_cast<const nodes::FullyConnectedLayerNode<double>&>(node)); } return { 0, 0 }; } } // namespace DataStatistics GetScalarDataStatistics(const UnlabeledDataContainer& dataset) { auto columns = GetNumColumns(dataset); utilities::MemoryLayout linearLayout({ columns }); auto basicStats = GetBasicDataStatistics(dataset, linearLayout); auto N = basicStats.numRows * columns; auto numZeros = std::accumulate(basicStats.numZeros.begin(), basicStats.numZeros.end(), 0); auto sum = basicStats.sumElements.Aggregate([](auto val) { return val; }); auto sumSquares = basicStats.sumSquaredElements.Aggregate([](auto val) { return val; }); auto mean = sum / N; auto variance = (sumSquares - ((sum * sum) / N)) / N; // == (sumSquares - mean*mean*N) / N auto stdDev = std::sqrt(variance); DataStatistics result; result.sparsity = { { static_cast<int64_t>(N), numZeros } }; result.mean = { mean }; result.variance = { variance }; result.stdDev = { stdDev }; return result; } DataStatistics GetDataStatistics(const UnlabeledDataContainer& dataset, const ell::utilities::MemoryLayout& layout) { auto basicStats = GetBasicDataStatistics(dataset); // per-element basic statistics const auto N = static_cast<double>(basicStats.numRows); const auto& sum = basicStats.sumElements; const auto& sumSquares = basicStats.sumSquaredElements; const auto& mean = sum / N; const auto& variance = (sumSquares - ((sum * sum) / N)) / N; // == (sumSquares - mean*mean*N) / N auto stdDev = Sqrt(variance); DataStatistics result; std::transform(basicStats.numZeros.begin(), basicStats.numZeros.end(), std::back_inserter(result.sparsity), [&](int64_t nz) { return Sparsity{ static_cast<int64_t>(N), nz }; }); result.mean = mean; result.variance = variance; result.stdDev = stdDev; return result; } DataStatistics GetDataStatistics(const UnlabeledDataContainer& dataset) { return GetDataStatistics(dataset, utilities::MemoryLayout({ GetNumColumns(dataset) })); } DataStatistics GetDataStatistics(const UnlabeledDataContainer& dataset, const ell::utilities::MemoryLayout& layout, int dimension) { auto basicStats = GetBasicDataStatistics(dataset, layout); // per-element basic statistics const auto& sum = basicStats.sumElements; const auto& sumSquares = basicStats.sumSquaredElements; const auto& numZeros = basicStats.numZeros; // Squash along the given dimension int outputLength = static_cast<int>(layout.GetLogicalDimensionActiveSize(dimension)); std::vector<int> dimNumZeros(outputLength); std::vector<double> dimSums(outputLength); std::vector<double> dimSumSquares(outputLength); const auto numElements = GetNumColumns(dataset); // the number of elements in each example for (int i = 0; i < numElements; ++i) { auto coords = layout.GetPhysicalCoordinatesFromOffset(i); auto outputIndex = coords[dimension]; dimNumZeros[outputIndex] += numZeros[i]; dimSums[outputIndex] += sum[i]; dimSumSquares[outputIndex] += sumSquares[i]; } int numElementsPerDim = layout.NumElements() / outputLength; const auto N = static_cast<double>(basicStats.numRows * numElementsPerDim); std::vector<Sparsity> dimSparsity(outputLength); ell::math::RowVector<double> dimMeans(outputLength); ell::math::RowVector<double> dimVariances(outputLength); ell::math::RowVector<double> dimStdDevs(outputLength); for (int i = 0; i < outputLength; ++i) { auto sumVal = dimSums[i]; dimMeans[i] = sumVal / N; auto variance = (dimSumSquares[i] - ((sumVal * sumVal) / N)) / N; // == (sumSquares - mean*mean*N) / N dimVariances[i] = variance; dimStdDevs[i] = std::sqrt(variance); dimSparsity[i] = { numElementsPerDim / outputLength, dimNumZeros[i] }; } DataStatistics result; result.sparsity = dimSparsity; result.mean = dimMeans; result.variance = dimVariances; result.stdDev = dimStdDevs; return result; } UnlabeledDataContainer GetNormalizedData(const UnlabeledDataContainer& dataset, const DataStatistics& stats) { ThrowIfEmpty(dataset); UnlabeledDataContainer result; for (const auto& row : dataset) { auto newRow = CastVector<double>(row); newRow -= stats.mean; newRow /= stats.stdDev; result.Add(CastVector<float>(newRow)); } return result; } UnlabeledDataContainer GetNormalizedData(const UnlabeledDataContainer& dataset, const DataStatistics& stats, const ell::utilities::MemoryLayout& layout, int dimension) { ThrowIfEmpty(dataset); if (!layout.IsCanonicalOrder()) { // Throw an exception until we're sure this code is order-independent throw utilities::InputException(utilities::InputExceptionErrors::invalidArgument, "Data not in canonical order"); } UnlabeledDataContainer result; for (const auto& row : dataset) { // Need to broadcast stats and do the subtract / divide on a multidim array auto newRow = CastVector<double>(row).ToArray(); MultidimArray newRowArray(newRow, layout); int size = layout.GetMemorySize(); for(int i = 0; i < size; ++i) { auto coords = layout.GetPhysicalCoordinatesFromOffset(i); newRowArray[coords] -= stats.mean[coords[dimension]]; newRowArray[coords] /= stats.stdDev[coords[dimension]]; } result.Add(CastVector<float>(ell::math::RowVector<double>(newRowArray.GetData()))); } return result; } UnlabeledDataContainer GetReverseNormalizedData(const UnlabeledDataContainer& dataset, const DataStatistics& stats) { ThrowIfEmpty(dataset); UnlabeledDataContainer result; for (const auto& row : dataset) { auto newRow = CastVector<double>(row); newRow *= stats.stdDev; newRow += stats.mean; result.Add(CastVector<float>(newRow)); } return result; } UnlabeledDataContainer GetReverseNormalizedData(const UnlabeledDataContainer& dataset, const DataStatistics& stats, const ell::utilities::MemoryLayout& layout, int dimension) { throw 0; ThrowIfEmpty(dataset); UnlabeledDataContainer result; for (const auto& row : dataset) { // Need to broadcast stats and do the add / multiply on a multidim array auto newRow = CastVector<double>(row).ToArray(); MultidimArray newRowArray(newRow, layout); int size = layout.GetMemorySize(); for (int i = 0; i < size; ++i) { auto coords = layout.GetPhysicalCoordinatesFromOffset(i); newRowArray[coords] *= stats.stdDev[coords[dimension]]; newRowArray[coords] += stats.mean[coords[dimension]]; } result.Add(CastVector<float>(ell::math::RowVector<double>(newRowArray.GetData()))); } return result; } Sparsity GetSubmodelWeightsSparsity(const model::Submodel& submodel) { Sparsity sparsity; submodel.Visit([&](const model::Node& node) { auto nodeSparsity = GetNodeWeightsSparsity(node); sparsity.numValues += nodeSparsity.numValues; sparsity.numZeros += nodeSparsity.numZeros; }); return sparsity; } }
30.910448
174
0.663689
awf
aab3bdd54d06c97c9e82906418a8305c2d016a62
32,698
cpp
C++
src/net.cpp
philipturner/opencl-backend
dd0bdd2c00a4c4d62ff76806048f1c7b2d737284
[ "MIT" ]
null
null
null
src/net.cpp
philipturner/opencl-backend
dd0bdd2c00a4c4d62ff76806048f1c7b2d737284
[ "MIT" ]
null
null
null
src/net.cpp
philipturner/opencl-backend
dd0bdd2c00a4c4d62ff76806048f1c7b2d737284
[ "MIT" ]
null
null
null
#include <dlprim/net.hpp> #include <dlprim/json.hpp> #include <dlprim/shared_resource.hpp> #include <dlprim/ops/initialization.hpp> #include <dlprim/model.hpp> #include <sstream> #include <fstream> #include <set> #include <list> #include <algorithm> #ifndef DISABLE_HDF5 #include "H5Cpp.h" #endif namespace dlprim { Net::Net(Context &ctx) : ctx_(ctx), shared_resource_(new SharedResource()), mode_(CalculationsMode::predict), keep_intermediate_tensors_(false) { } void Net::mode(CalculationsMode m) { mode_ = m; for(auto &c:connections_) c.op->mode(m); } void Net::add_input_tensor(std::string const &name,TensorSpecs const &ts,bool requires_gradient) { TensorSpecs new_ts(ts.shape(),ts.dtype(),requires_gradient); if(!tensor_specs_.insert(std::make_pair(name,new_ts)).second) { throw ValidationError("Tensor " + name + " already exists"); } inputs_.push_back(name); } void Net::set_loss_weight(std::string const &name,float lw) { mark_output_tensor(name); loss_weights_[name] = lw; } void Net::mark_output_tensor(std::string const &name) { if(tensor_specs_.find(name) == tensor_specs_.end()) { throw ValidationError("mark_output_tensor::No such tensor name " + name); } if(std::find(outputs_.begin(),outputs_.end(),name)==outputs_.end()) { outputs_.push_back(name); if(name.find("loss")==0) loss_weights_[name] = 1.0f; } } void Net::save_parameters(std::string const &fname) { json::value header; json::value &tensors = header["tensors"]; tensors = json::object(); size_t start_pos = 0; for(auto &pr : parameters_) { std::string name = pr.first; json::value &tensor_specs = tensors[name]; tensor_specs["dtype"] = data_type_to_string(pr.second.dtype()); Shape shape = pr.second.shape(); for(int i=0;i<shape.size();i++) tensor_specs["shape"][i] = shape[i]; size_t mem = pr.second.memory_size(); tensor_specs["size"] = mem; tensor_specs["start"] = start_pos; start_pos += mem; } std::ostringstream ss; ss << header; std::string header_content = ss.str(); unsigned len = header_content.size(); std::ofstream f(fname,std::fstream::binary); f<< "DLPW"; for(int i=0;i<4;i++) { unsigned char v = 0xFF & (len >> (24 - i*8)); f << (char)(v); } f << header_content; for(auto &pr : parameters_) { void *ptr = pr.second.host_data(); size_t len = pr.second.memory_size(); f.write((char*)ptr,len); } f.flush(); if(!f) { throw ValidationError("I/O error in saving to " + fname); } } void Net::load_model(ModelBase &model) { load_from_json(model.network()); setup(); load_parameters(model); } #ifdef DISABLE_HDF5 void Net::save_parameters_to_hdf5(std::string const &) { throw ValidationError("Library was build without HDF5 support"); } void Net::load_parameters_from_hdf5(std::string const &,bool) { throw ValidationError("Library was build without HDF5 support"); } #else void Net::save_parameters_to_hdf5(std::string const &fname) { try { H5::H5File f(fname,H5F_ACC_TRUNC); for(auto &pr : parameters_) { std::string name = pr.first; Tensor &tensor = pr.second; Shape shape = tensor.shape(); std::vector<hsize_t> dims(1 + shape.size()); for(int i=0;i<shape.size();i++) dims[i] = shape[i]; H5::DataSpace dsp(shape.size(),dims.data()); H5::FloatType datatype( H5::PredType::NATIVE_FLOAT ); datatype.setOrder( H5T_ORDER_LE ); H5::DataSet dataset = f.createDataSet( name , datatype, dsp ); if(tensor.dtype() == float_data) { dataset.write(tensor.data<float>(),H5::PredType::NATIVE_FLOAT); } else { throw ValidationError("FIXME load float16 from hdf5"); } } f.close(); } catch(H5::Exception const &e) { throw ValidationError("Failed to load HDF5 file " + fname + ": " + std::string(e.getCDetailMsg())); } } void Net::load_parameters_from_hdf5(std::string const &fname,bool allow_missing) { try { H5::H5File f(fname,H5F_ACC_RDONLY); for(auto &pr : parameters_) { std::string name = pr.first; Tensor &tensor = pr.second; H5::DataSet dataset; try { dataset = f.openDataSet(name); } catch(H5::Exception const &e) { if(allow_missing) continue; throw; } H5::DataSpace dsp = dataset.getSpace(); int ndims = dsp.getSimpleExtentNdims(); std::vector<hsize_t> dims(ndims); dsp.getSimpleExtentDims(dims.data(),nullptr); Shape ds_shape=Shape::from_range(dims.begin(),dims.end()); if(ds_shape != tensor.shape()) { std::ostringstream ss; ss << "Tensor shape mistmatch for " << name << " expecting " << tensor.shape() << " got " << ds_shape; throw ValidationError(ss.str()); } if(tensor.dtype() == float_data) { dataset.read(tensor.data<float>(),H5::PredType::NATIVE_FLOAT); } else { throw ValidationError("FIXME load float16 from hdf5"); } } } catch(H5::Exception const &e) { throw ValidationError("Failed to load HDF5 file " + fname + ": " + std::string(e.getCDetailMsg())); } copy_parameters_to_device(); } #endif void Net::initialize_parameters(ExecutionContext const &e) { for(auto &conn : connections_) { conn.op->initialize_params(conn.parameters,e); } if(mode() == CalculationsMode::train) { // set loss diff for(auto const &name : output_names()) { if(is_loss(name)) set_to_constant(tensor_diff(name),loss_weights_[name],e); } } } void Net::load_header(std::istream &f,json::value &v) { unsigned char buf[8]={0}; f.read((char*)buf,8); if(memcmp(buf,"DLPW",4) != 0) throw ValidationError("Invalid File Format"); unsigned len = 0; for(int i=0;i<4;i++) { len |= unsigned(buf[4+i]) << ((3-i)*8); } if(len > 1024*1024*64) throw ValidationError("Header seems to be too big"); std::vector<char> buffer(len+1); f.read(buffer.data(),len); if(!f) throw ValidationError("Problem readfing file"); buffer[len] = 0; char const *begin=&buffer[0]; char const *end =&buffer[len]; // (there is +1) if(!v.load(begin,end,true)) { throw ValidationError("Problem parsing content"); } } void Net::load_parameters(std::string const &file_name,bool allow_missing) { std::ifstream f(file_name,std::ifstream::binary); char buf[5]={}; f.read(buf,4); if(buf==std::string("DLPW")) { f.seekg(0); try { load_parameters(f,allow_missing); } catch(std::exception const &e) { throw ValidationError(std::string(e.what()) + " in file " + file_name); } } else if(buf==std::string("\211HDF")) { f.close(); load_parameters_from_hdf5(file_name,allow_missing); } else { throw ValidationError("Unidentified majic number for " + file_name); } } void Net::load_parameters(ModelBase &model,bool allow_missing) { for(auto &pr : parameters_) { std::string name = pr.first; Tensor &tensor = pr.second; Tensor value = model.get_parameter(name); if(value.shape().size() == 0) { if(allow_missing) continue; throw ValidationError("No parameter " + name + " was found"); } if(tensor.shape() != value.shape() || tensor.dtype() != value.dtype()) { std::ostringstream err; err << "Expected " << tensor << " parameter, got " << value << " for " << name; throw ValidationError(err.str()); } memcpy(tensor.host_data(),value.host_data(),tensor.memory_size()); } copy_parameters_to_device(); } void Net::load_parameters(std::istream &f,bool allow_missing) { json::value v; load_header(f,v); size_t offset = f.tellg(); json::object const &tensors=v.find("tensors").object(); for(auto &pr : parameters_) { std::string name = pr.first; Tensor &tensor = pr.second; auto p = tensors.find(name); if(p == tensors.end()) { if(allow_missing) continue; throw ValidationError("No parameter " + name + " was found"); } std::vector<int> dims = p->second.get<std::vector<int> >("shape"); DataType dt = string_to_data_type(p->second.get<std::string>("dtype")); Shape ds_shape=Shape::from_range(dims.begin(),dims.end()); if(ds_shape != tensor.shape() || dt != tensor.dtype()) { std::ostringstream ss; ss << "Tensor shape/type mistmatch for " << name << " expecting " << tensor << " got " << ds_shape << " " << data_type_to_string(dt); throw ValidationError(ss.str()); } size_t start = p->second.get<size_t>("start"); size_t size = p->second.get<size_t>("size"); if(size != tensor.memory_size()) { throw ValidationError("Object size mistmatch"); } f.seekg(start + offset); f.read(static_cast<char *>(tensor.host_data()),size); if(!f) { throw ValidationError("I/O error"); } } copy_parameters_to_device(); } void Net::load_from_json(json::value const &v) { json::array const &inputs = v["inputs"].array(); for(auto const &input:inputs) { auto const &vsp = input.get<std::vector<int> >("shape"); Shape sp=Shape::from_range(vsp.begin(),vsp.end()); DataType dt(string_to_data_type(input.get("dtype","float"))); TensorSpecs spec(sp,dt); std::string name = input.get("name","data"); add_input_tensor(name,spec); } json::array const &operators = v["operators"].array(); json::value empty_options = json::object(); for(size_t i=0;i<operators.size();i++) { json::value const &op = operators[i]; std::string name = op.get<std::string>("name"); std::string type = op.get<std::string>("type"); bool frozen = op.get<bool>("frozen",false); std::vector<std::string> inputs = op.get("inputs", std::vector<std::string>()); std::vector<std::string> outputs = op.get("outputs",std::vector<std::string>()); std::vector<std::string> params = op.get("params", std::vector<std::string>()); json::value const &opts = op.find("options").is_undefined() ? empty_options : op["options"]; std::unique_ptr<Operator> oper = create_by_name(ctx_,type,opts); add_operator(std::move(oper),name,inputs,outputs,params,frozen); } for(json::value const &output : v["outputs"].array()) { if(output.type() == json::is_string) mark_output_tensor(output.str()); else { std::string const &name = output.get<std::string>("name"); if(output.find("loss_weight").is_undefined()) mark_output_tensor(name); else set_loss_weight(name,output.get<float>("loss_weight")); } } } void Net::load_from_json_file(std::string const &name) { std::ifstream f(name); json::value net; int line=-1; if(!net.load(f,true,&line)) { throw ValidationError("Failed to load json from " + name + ", syntax error at line " + std::to_string(line)); } load_from_json(net); } void Net::add_operator( std::unique_ptr<Operator> op, std::string const &name, std::vector<std::string> const &inputs, std::vector<std::string> const &outputs, std::vector<std::string> const &parameters, bool frozen) { Connection conn; conn.op = std::move(op); conn.op->shared_resource(shared_resource()); conn.op->mode(mode_); conn.frozen = frozen; conn.name = name; if(connections_index_.find(name) != connections_index_.end()) { throw ValidationError("Operator with name " + name + " exists"); } for(size_t i=0;i<inputs.size();i++) { auto spec_it = tensor_specs_.find(inputs[i]); if(spec_it == tensor_specs_.end()) { throw ValidationError("No such tensor " + inputs[i]); } conn.input_specs.push_back(spec_it->second); } conn.input_names = inputs; conn.op->setup(conn.input_specs,conn.output_specs,conn.parameter_specs,conn.ws_size); if(conn.output_specs.size() != outputs.size()) { throw ValidationError("Operator " + name + " expects to have " + std::to_string(conn.output_specs.size()) + " outputs, but only " + std::to_string(outputs.size()) + " provided"); } conn.output_names = outputs; for(size_t i=0;i<outputs.size();i++) { auto p = tensor_specs_.find(outputs[i]); if(p == tensor_specs_.end()) { tensor_specs_[outputs[i]] = conn.output_specs[i]; } else { if(p->second != conn.output_specs[i]) { std::ostringstream ss; ss << "Tensor " << outputs[i] << " is already defined with spec " << p->second << " but operator " << name << " requires following output specs " << conn.output_specs[i]; throw ValidationError(ss.str()); } if(std::find(inputs.begin(),inputs.end(),outputs[i]) == inputs.end()) { throw ValidationError("Output " + outputs[i] + " for operator " + name + " aleady exists " " howover it isn't as as input, output tensor can't have different sources other " " then self/in-place operations "); } } if(conn.op->alias_generator()) { if(inputs.size() != outputs.size()) { throw ValidationError("Inputs need to have same size for operator " + name); } for(size_t i=0;i<inputs.size();i++) { if(conn.input_specs[i].dtype() != conn.output_specs[i].dtype() || conn.input_specs[i].shape().total_size() != conn.output_specs[i].shape().total_size()) { throw ValidationError("Alias operator need to have tensors of same type and size, only shape may be altered for "+ name); } std::string src = inputs[i]; std::map<std::string,std::string>::iterator p; while((p=alias_sources_.find(src))!=alias_sources_.end()) src = p->second; alias_sources_[outputs[i]]=src; } } } if(frozen) { for(auto &spec : conn.parameter_specs) { spec.freeze(); } } unsigned params_no = conn.parameter_specs.size(); if(params_no < parameters.size()) { std::ostringstream ss; ss << "Too many parameter names for operaror " << name << " expecting " << params_no << " got " << parameters.size(); throw ValidationError(ss.str()); } conn.parameter_names = parameters; conn.parameter_names.resize(params_no); for(size_t i=0;i<conn.parameter_names.size();i++) { std::string &pname = conn.parameter_names[i]; if(pname.empty() || pname == "auto") { conn.parameter_names[i] = name + "." + std::to_string(i); } auto p = parameter_specs_.find(pname); if(p==parameter_specs_.end()) { parameter_specs_[pname] = conn.parameter_specs[i]; } else { if(p->second != conn.parameter_specs[i]) { std::ostringstream ss; ss << "Conflicting requirements for parameters specifications " << p->second << " vs " << conn.parameter_specs[i] << " for " << pname; throw ValidationError(ss.str()); } } } connections_index_[name] = connections_.size(); connections_.push_back(std::move(conn)); } void Net::setup() { clear_memory(); mark_backpropagating_edges(); setup_ws(); allocate_tensors(); } void Net::setup_ws() { size_t ws = 0; for(auto &c : connections_) ws = std::max(c.ws_size,ws); if(ws > 0) { if(workspace_.memory_size() < ws) { workspace_ = Tensor(); // clear first workspace_ = Tensor(ctx_,Shape(ws),uint8_data); } } else workspace_ = Tensor(); } bool Net::is_loss(std::string const &name) { return loss_weights_.find(name)!=loss_weights_.end(); } void Net::mark_backpropagating_edges() { std::map<std::string,int> requires_gradient; for(std::string const &name : inputs_) { if(tensor_specs_[name].is_trainable()) requires_gradient[name] |= 1; } for(std::string const &name : outputs_) { if(is_loss(name)) requires_gradient[name] |= 2; } for(size_t i=0;i<connections_.size();i++) { connections_[i].gradient_flags = 0; } // needs gradient for(size_t i=0;i<connections_.size();i++) { int &gradient_flags = connections_[i].gradient_flags; for(auto const &spec : connections_[i].parameter_specs) { if(spec.is_trainable()) { gradient_flags |= 1; break; } } for(auto const &name : connections_[i].input_names) { if(requires_gradient[name] & 1) { gradient_flags |= 1; break; } } if((gradient_flags & 1) == 0) continue; for(auto const &name : connections_[i].output_names) { requires_gradient[name] |= 1; } } // needs gradient for(int i=connections_.size()-1;i>=0;i--) { int &gradient_flags = connections_[i].gradient_flags; for(auto const &name : connections_[i].output_names) { if(requires_gradient[name] & 2) { gradient_flags |= 2; break; } } if((connections_[i].gradient_flags & 2) == 0) continue; for(auto const &name : connections_[i].input_names) { requires_gradient[name] |= 2; } } for(auto &ts : tensor_specs_) { if(requires_gradient[ts.first]!=3) { ts.second.freeze(); } } } void Net::tensor_use_list(std::vector<std::list<std::string> > &start, std::vector<std::list<std::string> > &stop) { std::map<std::string,std::pair<int,int> > used_at; int last = connections_.size()-1; for(auto const &n : inputs_) used_at[n] = std::make_pair(0,last); for(auto const &n : outputs_) used_at[n] = std::make_pair(0,last); for(int i=0;i<int(connections_.size());i++) { for(int dir=0;dir<2;dir++) { for(auto const &tensor_name : (dir == 0 ? connections_[i].input_names : connections_[i].output_names)) { std::string name; auto p = alias_sources_.find(tensor_name); if(p != alias_sources_.end()) name = p->second; else name = tensor_name; if(used_at.find(name) == used_at.end()) { used_at[name] = std::make_pair(i,i); } else { auto &fl = used_at[name]; fl.first = std::min(fl.first,i); fl.second = std::max(fl.second,i); } } } } start.clear(); start.resize(connections_.size()); stop.clear(); stop.resize(connections_.size()); for(auto const &v:used_at) { start[v.second.first].push_back(v.first); stop[v.second.second].push_back(v.first); } } void Net::allocate_optimized_chunks(bool forward) { std::vector<std::list<std::string> > alloc_needed; std::vector<std::list<std::string> > free_needed; tensor_use_list(alloc_needed,free_needed); if(!forward) alloc_needed.swap(free_needed); std::multimap<size_t,int> pool; std::vector<size_t> chunks; std::map<std::string,int> chunks_mapping; int step_offset,step_scale; if(forward) { step_offset = 0; step_scale = 1; } else { step_offset = connections_.size() - 1; step_scale = -1; } for(unsigned i=0;i<connections_.size();i++) { int index = i * step_scale + step_offset; for(auto const &n : alloc_needed[index]) { size_t mem = tensor_specs_[n].memory_size(); if(pool.empty()) { chunks_mapping[n] = chunks.size(); chunks.push_back(mem); } else { auto p = pool.lower_bound(mem); if(p!=pool.end()) { chunks_mapping[n] = p->second; pool.erase(p); } else { auto last = pool.rbegin(); chunks_mapping[n] = last->second; chunks[last->second] = mem; // increase memory pool.erase(std::prev(pool.end())); } } } for(auto const &n : free_needed[index]) { int cid = chunks_mapping[n]; pool.insert(std::make_pair(chunks[cid],cid)); } } memory_.clear(); for(size_t i=0;i<chunks.size();i++) { memory_.push_back(Tensor(ctx_,Shape(chunks[i]),uint8_data)); } tensors_.clear(); tensors_diff_.clear(); for(auto const &ts : tensor_specs_) { if(alias_sources_.count(ts.first) > 0) continue; int cid = chunks_mapping[ts.first]; auto base_tensor = memory_[cid]; Tensor actual_tensor = base_tensor.sub_tensor(0,ts.second.shape(),ts.second.dtype()); if(forward) { tensors_[ts.first ] = actual_tensor; } else { tensors_[ts.first ] = Tensor(ctx_,ts.second.shape(),ts.second.dtype()); tensors_diff_[ts.first ] = actual_tensor; } } allocate_aliases(); } void Net::allocate_chunks() { tensors_.clear(); tensors_diff_.clear(); memory_.clear(); bool train = mode_ == CalculationsMode::train; // normal for(auto const &ts : tensor_specs_) { if(alias_sources_.count(ts.first) != 0) continue; tensors_[ts.first ] = Tensor(ctx_,ts.second.shape(),ts.second.dtype()); if(train) tensors_diff_[ts.first ] = Tensor(ctx_,ts.second.shape(),ts.second.dtype()); } allocate_aliases(); } void Net::allocate_aliases() { bool train = mode_ == CalculationsMode::train; // alias for(auto const &ts : tensor_specs_) { auto p = alias_sources_.find(ts.first); if(p==alias_sources_.end()) continue; std::string src_name = p->second; tensors_[ts.first ] = tensors_[src_name].alias(ts.second.shape()); if(train) tensors_diff_[ts.first ] = tensors_diff_[src_name].alias(ts.second.shape()); } } void Net::allocate_tensors() { tensors_.clear(); tensors_diff_.clear(); parameters_.clear(); bool train = mode_ == CalculationsMode::train; if(keep_intermediate_tensors_) allocate_chunks(); else allocate_optimized_chunks(!train); // forward = !train for(auto const &ps : parameter_specs_) { parameters_[ps.first ] = Tensor(ctx_,ps.second.shape(),ps.second.dtype(),ps.second.is_trainable()); if(train && ps.second.is_trainable()) parameters_diff_[ps.first ] = Tensor(ctx_,ps.second.shape(),ps.second.dtype()); } /// FWD connections for(auto &conn : connections_) { conn.input_tensors.clear(); conn.output_tensors.clear(); for(auto const &name : conn.input_names) { conn.input_tensors.push_back(tensors_[name]); } for(auto const &name : conn.output_names) { conn.output_tensors.push_back(tensors_[name]); } if(conn.parameter_names.empty()) continue; conn.parameters.clear(); for(auto const &name : conn.parameter_names) { conn.parameters.push_back(parameters_[name]); } } /// BWD Connections std::set<std::string> zeroed_grad; for(int index=connections_.size()-1;index>=0;index--) { auto &conn = connections_[index]; conn.in_grad.clear(); conn.out_grad.clear(); conn.param_grad.clear(); bool is_trainable = train && conn.gradient_flags == 3; for(auto const &name : conn.input_names) { bool in_place = std::find(conn.output_names.begin(), conn.output_names.end(), name) != conn.output_names.end(); TensorAndGradient tg; tg.data = tensors_[name]; if(tensor_specs_[name].is_trainable() && is_trainable) { tg.diff = tensors_diff_[name]; if(zeroed_grad.find(name) == zeroed_grad.end() || in_place) { tg.accumulate_gradient = 0.0; // first in BP zeroes gradient zeroed_grad.insert(name); } else { tg.accumulate_gradient = 1.0; // next accumulate } tg.requires_gradient = true; } else tg.requires_gradient = false; conn.in_grad.push_back(tg); } for(auto const &name : conn.output_names) { TensorAndGradient tg; tg.data = tensors_[name]; if(is_trainable) tg.diff = tensors_diff_[name]; tg.accumulate_gradient = 0.0; tg.requires_gradient = true; conn.out_grad.push_back(tg); } if(conn.parameter_names.empty()) continue; for(auto const &name : conn.parameter_names) { TensorAndGradient tg; tg.data = parameters_[name]; if(tg.data.is_trainable() && is_trainable) { tg.diff = parameters_diff_[name]; tg.accumulate_gradient = 1.0f; tg.requires_gradient = true; } else { tg.accumulate_gradient = 0; tg.requires_gradient = false; } conn.param_grad.push_back(tg); } } } void Net::copy_parameters_to_device() { cl::CommandQueue q = ctx_.make_queue(); for(auto &pr : parameters_) { pr.second.to_device(q); } } void Net::copy_parameters_to_host() { cl::CommandQueue q = ctx_.make_queue(); for(auto &pr : parameters_) { pr.second.to_host(q); } } void Net::reshape() { std::vector<Shape> in,out; bool train = mode_ == CalculationsMode::train; for(auto &conn : connections_) { in.clear(); out.clear(); for(Tensor &s : conn.input_tensors) in.push_back(s.shape()); conn.op->reshape(in,out,conn.ws_size); for(unsigned i=0;i<out.size();i++) { conn.output_tensors[i].reshape(out[i]); if(train && tensor_specs_[conn.output_names[i]].is_trainable()) { conn.out_grad[i].diff.reshape(out[i]); } } } setup_ws(); } void Net::clear_memory() { for(auto &conn : connections_) { conn.input_tensors.clear(); conn.output_tensors.clear(); conn.in_grad.clear(); conn.out_grad.clear(); conn.param_grad.clear(); } workspace_ = Tensor(); tensors_.clear(); tensors_diff_.clear(); parameters_.clear(); parameters_diff_.clear(); memory_.clear(); } void Net::forward(ExecutionContext const &e,bool sync) { ExecGuard g(e,"forward"); for(size_t i=0;i<connections_.size();i++) { ExecGuard g(e,connections_[i].name.c_str()); ExecutionContext ec = e.generate_series_context(i,connections_.size()); connections_[i].op->forward( connections_[i].input_tensors, connections_[i].output_tensors, connections_[i].parameters, workspace_, ec); if(sync && ctx_.is_opencl_context()) e.queue().finish(); } } void Net::backward(ExecutionContext const &e,bool sync) { ExecGuard g(e,"backward"); for(int i=connections_.size() - 1,it=0;i >= 0;i--,it++) { ExecGuard g(e,connections_[i].name.c_str()); ExecutionContext ec = e.generate_series_context(it,connections_.size()); if(connections_[i].gradient_flags != 3) continue; connections_[i].op->backward( connections_[i].in_grad, connections_[i].out_grad, connections_[i].param_grad, workspace_, ec); if(sync && ctx_.is_opencl_context()) { e.queue().finish(); } } } }
37.670507
149
0.504557
philipturner
aab3d0e4afee5cde64942f5f3c167fba1a517064
1,683
cpp
C++
tools/converter/source/optimizer/tfextra/TFDense.cpp
xhuan28/MNN
81df3a48d79cbc0b75251d12934345948866f7be
[ "Apache-2.0" ]
6,958
2019-05-06T02:38:02.000Z
2022-03-31T18:08:48.000Z
tools/converter/source/optimizer/tfextra/TFDense.cpp
xhuan28/MNN
81df3a48d79cbc0b75251d12934345948866f7be
[ "Apache-2.0" ]
1,775
2019-05-06T04:40:19.000Z
2022-03-30T15:39:24.000Z
tools/converter/source/optimizer/tfextra/TFDense.cpp
xhuan28/MNN
81df3a48d79cbc0b75251d12934345948866f7be
[ "Apache-2.0" ]
1,511
2019-05-06T02:38:05.000Z
2022-03-31T16:59:39.000Z
// // TFDense.cpp // MNNConverter // // Created by MNN on 2019/09/27. // Copyright © 2018, Alibaba Group Holding Limited // #include "MNN_generated.h" #include "TFExtraManager.hpp" namespace MNN { namespace Express { class DenseTransform : public TFExtraManager::Transform { public: virtual EXPRP onExecute(EXPRP expr) const override { auto inputs = expr->inputs(); auto op = expr->get(); MNN_ASSERT(nullptr != op->main_as_Extra()); auto extraAttr = op->main_as_Extra()->attr(); bool transposeA = false; bool transposeB = false; bool bias = false; if (nullptr != extraAttr) { for (int i = 0; i < extraAttr->size(); ++i) { auto attr = extraAttr->GetAs<Attribute>(i); if ("use_bias" == attr->key()->str()) { bias = attr->b(); continue; } if ("transpose_b" == attr->key()->str()) { transposeB = attr->b(); continue; } if ("transpose_a" == attr->key()->str()) { transposeA = attr->b(); continue; } } } auto output = _MatMul(inputs[0], inputs[1], transposeA, transposeB); if (bias) { output = output + inputs[2]; } output->setName(expr->name()); return output->expr().first; } }; static auto gRegister = []() { TFExtraManager::get()->insert("Dense", std::shared_ptr<TFExtraManager::Transform>(new DenseTransform)); return true; }(); } // namespace Express } // namespace MNN
30.6
107
0.510398
xhuan28
aab4f8ac47584ef6f8b443b60c565887faae6394
7,432
cpp
C++
lib/SimpleHttpClient/GeneralClientConnection.cpp
jjzhang166/avocadodb
948d94592c10731857c8617b133bda840b8e833e
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
null
null
null
lib/SimpleHttpClient/GeneralClientConnection.cpp
jjzhang166/avocadodb
948d94592c10731857c8617b133bda840b8e833e
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
null
null
null
lib/SimpleHttpClient/GeneralClientConnection.cpp
jjzhang166/avocadodb
948d94592c10731857c8617b133bda840b8e833e
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann //////////////////////////////////////////////////////////////////////////////// #include "GeneralClientConnection.h" #include "SimpleHttpClient/ClientConnection.h" #include "SimpleHttpClient/SslClientConnection.h" using namespace avocadodb; using namespace avocadodb::basics; using namespace avocadodb::httpclient; //////////////////////////////////////////////////////////////////////////////// /// @brief creates a new client connection //////////////////////////////////////////////////////////////////////////////// GeneralClientConnection::GeneralClientConnection(Endpoint* endpoint, double requestTimeout, double connectTimeout, size_t connectRetries) : _endpoint(endpoint), _freeEndpointOnDestruction(false), _requestTimeout(requestTimeout), _connectTimeout(connectTimeout), _connectRetries(connectRetries), _numConnectRetries(0), _isConnected(false), _isInterrupted(false) { } GeneralClientConnection::GeneralClientConnection( std::unique_ptr<Endpoint>& endpoint, double requestTimeout, double connectTimeout, size_t connectRetries) : _endpoint(endpoint.release()), _freeEndpointOnDestruction(true), _requestTimeout(requestTimeout), _connectTimeout(connectTimeout), _connectRetries(connectRetries), _numConnectRetries(0), _isConnected(false), _isInterrupted(false) {} //////////////////////////////////////////////////////////////////////////////// /// @brief destroys a client connection //////////////////////////////////////////////////////////////////////////////// GeneralClientConnection::~GeneralClientConnection() { if (_freeEndpointOnDestruction) { delete _endpoint; } } //////////////////////////////////////////////////////////////////////////////// /// @brief create a new connection from an endpoint //////////////////////////////////////////////////////////////////////////////// GeneralClientConnection* GeneralClientConnection::factory( Endpoint* endpoint, double requestTimeout, double connectTimeout, size_t numRetries, uint64_t sslProtocol) { if (endpoint->encryption() == Endpoint::EncryptionType::NONE) { return new ClientConnection(endpoint, requestTimeout, connectTimeout, numRetries); } else if (endpoint->encryption() == Endpoint::EncryptionType::SSL) { return new SslClientConnection(endpoint, requestTimeout, connectTimeout, numRetries, sslProtocol); } return nullptr; } GeneralClientConnection* GeneralClientConnection::factory( std::unique_ptr<Endpoint>& endpoint, double requestTimeout, double connectTimeout, size_t numRetries, uint64_t sslProtocol) { if (endpoint->encryption() == Endpoint::EncryptionType::NONE) { return new ClientConnection(endpoint, requestTimeout, connectTimeout, numRetries); } else if (endpoint->encryption() == Endpoint::EncryptionType::SSL) { return new SslClientConnection(endpoint, requestTimeout, connectTimeout, numRetries, sslProtocol); } return nullptr; } //////////////////////////////////////////////////////////////////////////////// /// @brief connect //////////////////////////////////////////////////////////////////////////////// bool GeneralClientConnection::connect() { _isInterrupted = false; disconnect(); if (_numConnectRetries < _connectRetries + 1) { _numConnectRetries++; } else { return false; } connectSocket(); if (!_isConnected) { return false; } _numConnectRetries = 0; return true; } //////////////////////////////////////////////////////////////////////////////// /// @brief disconnect //////////////////////////////////////////////////////////////////////////////// void GeneralClientConnection::disconnect() { if (isConnected()) { disconnectSocket(); } _isConnected = false; _isInterrupted = false; _numConnectRetries = 0; } //////////////////////////////////////////////////////////////////////////////// /// @brief handleWrite /// Write data to endpoint, this uses select to block until some /// data can be written. Then it writes as much as it can without further /// blocking, not calling select again. What has happened is /// indicated by the return value and the bytesWritten variable, /// which is always set by this method. The bytesWritten indicates /// how many bytes have been written from the buffer /// (regardless of whether there was an error or not). The return value /// indicates, whether an error has happened. Note that the other side /// closing the connection is not considered to be an error! The call to /// prepare() does a select and the call to readClientConnection does /// what is described here. //////////////////////////////////////////////////////////////////////////////// bool GeneralClientConnection::handleWrite(double timeout, void const* buffer, size_t length, size_t* bytesWritten) { *bytesWritten = 0; if (prepare(timeout, true)) { return this->writeClientConnection(buffer, length, bytesWritten); } return false; } //////////////////////////////////////////////////////////////////////////////// /// @brief handleRead /// Read data from endpoint, this uses select to block until some /// data has arrived. Then it reads as much as it can without further /// blocking, using select multiple times. What has happened is /// indicated by two flags, the return value and the connectionClosed flag, /// which is always set by this method. The connectionClosed flag indicates /// whether or not the connection has been closed by the other side /// (regardless of whether there was an error or not). The return value /// indicates, whether an error has happened. Note that the other side /// closing the connection is not considered to be an error! The call to /// prepare() does a select and the call to readClientCollection does /// what is described here. //////////////////////////////////////////////////////////////////////////////// bool GeneralClientConnection::handleRead(double timeout, StringBuffer& buffer, bool& connectionClosed) { connectionClosed = false; if (prepare(timeout, false)) { return this->readClientConnection(buffer, connectionClosed); } connectionClosed = true; return false; }
38.112821
86
0.579117
jjzhang166
aab53f4a2b75ce272f45d83272aff6173d134b2c
2,882
cc
C++
src/ir/di-location.cc
lung21/llvm-node
e1b800e8023370134684e33ef700dc0e2a83bac2
[ "MIT" ]
null
null
null
src/ir/di-location.cc
lung21/llvm-node
e1b800e8023370134684e33ef700dc0e2a83bac2
[ "MIT" ]
null
null
null
src/ir/di-location.cc
lung21/llvm-node
e1b800e8023370134684e33ef700dc0e2a83bac2
[ "MIT" ]
null
null
null
#include <nan.h> #include "llvm-context.h" #include "di-location.h" #include "di-local-scope.h" NAN_MODULE_INIT(DILocationWrapper::Init) { auto diLocation = Nan::GetFunction(Nan::New(diLocationTemplate())).ToLocalChecked(); Nan::Set(target, Nan::New("DILocation").ToLocalChecked(), diLocation); } llvm::DILocation *DILocationWrapper::getDILocation() { return diLocation; } v8::Local<v8::Object> DILocationWrapper::of(llvm::DILocation *diLocation) { auto constructorFunction = Nan::GetFunction(Nan::New(diLocationTemplate())).ToLocalChecked(); v8::Local<v8::Value> args[1] = { Nan::New<v8::External>(diLocation) }; auto instance = Nan::NewInstance(constructorFunction, 1, args).ToLocalChecked(); Nan::EscapableHandleScope escapeScpoe; return escapeScpoe.Escape(instance); } bool DILocationWrapper::isInstance(v8::Local<v8::Value> value) { return Nan::New(diLocationTemplate())->HasInstance(value); } DILocationWrapper::DILocationWrapper(llvm::DILocation *location): diLocation(location) {} NAN_METHOD(DILocationWrapper::New) { if (!info.IsConstructCall()) { return Nan::ThrowTypeError("DILocation constructor needs to be called with new"); } if (info.Length() < 1 || !info[0]->IsExternal()) { return Nan::ThrowTypeError("Expected type pointer"); } auto *diLocation = static_cast<llvm::DILocation*>(v8::External::Cast(*info[0])->Value()); auto *wrapper = new DILocationWrapper(diLocation); wrapper->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } NAN_METHOD(DILocationWrapper::get) { if (info.Length() != 4 || !LLVMContextWrapper::isInstance(info[0]) || !info[1]->IsInt32() || !info[2]->IsInt32() || !DILocalScopeWrapper::isInstance(info[3])) { return Nan::ThrowTypeError("get accepts only 4 arguments"); } auto &context = LLVMContextWrapper::FromValue(info[0])->getContext(); uint32_t line = Nan::To<uint32_t>(info[1]).FromJust(); uint32_t column = Nan::To<uint32_t>(info[2]).FromJust(); auto *diLocalScope = DILocalScopeWrapper::FromValue(info[3])->getDILocalScope(); auto *diLocation = llvm::DILocation::get(context, line, column, diLocalScope); info.GetReturnValue().Set(DILocationWrapper::of(diLocation)); } Nan::Persistent<v8::FunctionTemplate> &DILocationWrapper::diLocationTemplate() { static Nan::Persistent<v8::FunctionTemplate> functionTemplate; if (functionTemplate.IsEmpty()) { v8::Local<v8::FunctionTemplate> localTemplate = Nan::New<v8::FunctionTemplate>(DILocationWrapper::New); localTemplate->SetClassName(Nan::New("DILocation").ToLocalChecked()); localTemplate->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetMethod(localTemplate, "get", DILocationWrapper::get); functionTemplate.Reset(localTemplate); } return functionTemplate; }
39.479452
111
0.700902
lung21
aab730637ec91df92aca9d4a62156f886e1bdef6
7,983
cpp
C++
src/workloads/psort/psort.cpp
suyashmahar/libivy
bd3a3f303c44c600ea2f8b68ee892600a4a19ea5
[ "BSD-3-Clause" ]
null
null
null
src/workloads/psort/psort.cpp
suyashmahar/libivy
bd3a3f303c44c600ea2f8b68ee892600a4a19ea5
[ "BSD-3-Clause" ]
null
null
null
src/workloads/psort/psort.cpp
suyashmahar/libivy
bd3a3f303c44c600ea2f8b68ee892600a4a19ea5
[ "BSD-3-Clause" ]
null
null
null
#include <algorithm> #include <chrono> #include <cstdint> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <iterator> #include <optional> #include <span> #include <sys/types.h> #include <thread> #include <unistd.h> #include <vector> #include "libivy.hh" typedef uint8_t *byte_ptr; using libivy::Ivy; using std::optional; using std::span; using std::vector; constexpr static size_t NODES_WORKER = 2; constexpr static char CANARY_VAL[] = "DEADBEEFBAADBEEF"; #define ASSERT_VALID \ (memcmp(shm.value()->header.canary, CANARY_VAL, sizeof(CANARY_VAL)) != 0 && "SHM corrupted") struct shm_hdr { char canary[sizeof(CANARY_VAL)]; uint64_t elems; /* Total num of elements in shm */ uint8_t ready; /* Signal ready to workers */ uint8_t done[NODES_WORKER]; /* Signal completion to manager */ uint64_t nodes; /* Total number of nodes */ /* Pad to make the header take up 1 page of space */ uint8_t padding[libivy::Ivy::PAGE_SZ - (sizeof(CANARY_VAL) + sizeof(uint64_t) * (3) + sizeof(shm_hdr::nodes))]; }; static_assert(sizeof(shm_hdr) == libivy::Ivy::PAGE_SZ); struct shm_layout { shm_hdr header; uint64_t data[]; }; optional<shm_layout *> shm; size_t region_sz = 0; void dump_shm() { return; std::cout << "SHM.data = :" << std::endl; size_t line_cnt = 0; for (size_t iter = 0; iter < shm.value()->header.elems; iter++) { std::cout << "0x" << std::setw(8) << std::setfill('0') << shm.value()->data[iter] << " "; if (++line_cnt > 10) { line_cnt = 0; std::cout << std::endl; } } std::cout << std::endl; } /** * @brief Sort the ith part of the shm * @param id Unique id of the worker */ void sort_worker(size_t id) { /* Busy waiting on ready */ while (!shm.value()->header.ready) { std::cout << "Waiting for the ready signal" << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } ASSERT_VALID; std::cout << "Ready value = " << (int)(shm.value()->header.ready) << std::endl; size_t elems = shm.value()->header.elems; ASSERT_VALID; size_t elems_per_node = (elems/shm.value()->header.nodes); std::cout << "&elems = " << &shm.value()->header.elems << std::endl; std::cout << "elems = " << elems << std::endl; size_t start = elems_per_node * id; uint64_t *data_ptr = shm.value()->data; /* Get a view into the shared memory this worker will sort */ span<uint64_t> workset{&data_ptr[start], elems_per_node}; /* Use qsort on the region */ dump_shm(); DBGH << "Workset.begin() = " << (void*)&data_ptr[start] << " elems per node = " << elems_per_node << std::endl; auto start_time = std::chrono::high_resolution_clock::now(); for (size_t i = 0; i < elems_per_node; i++) { for (size_t j = 1; j < elems_per_node; j++) { if (workset[j - 1] > workset[j]) { auto temp = workset[j - 1]; workset[j - 1] = workset[j]; workset[j] = temp; } } } auto end_time = std::chrono::high_resolution_clock::now(); auto time_diff = end_time - start_time; auto time_elapsed = std::chrono::duration_cast<std::chrono::seconds>(time_diff); std::cout << "Time taken = " << time_elapsed.count() << " s" << std::endl; // data_ptr[0] = 1000; // std::sort(workset.begin(), workset.end(), std::greater<uint64_t>{}); dump_shm(); ASSERT_VALID; /* Signal ready */ shm.value()->header.done[id] = 1; DBGH << "Written done to location " << (void*)&shm.value()->header.done[id] << std::endl; ASSERT_VALID; std::cout << "Sorting completed at " << id << std::endl; } void merge_worker() { ASSERT_VALID; size_t iter[NODES_WORKER]; for (size_t i = 0; i < NODES_WORKER; i++) { iter[i] = 0; } auto next_iter = [&iter](size_t node) { if (iter[node] < shm.value()->header.elems) { iter[node]++; } }; auto done = [&iter]() -> bool { for (size_t i = 0; i < NODES_WORKER; i++) { if (iter[i] != shm.value()->header.elems/NODES_WORKER){ return false; } } return true; }; while (!done()) { vector<uint64_t> cur_elems(NODES_WORKER); uint64_t min_elem = UINT64_MAX; uint64_t min_idx; for (size_t i = 0; i < NODES_WORKER; i++) { if (iter[i] != shm.value()->header.elems/NODES_WORKER) { // std::cout << "offset = " << i*ELEMS + iter[i] << std::endl; auto elems_per_node = shm.value()->header.elems/(NODES_WORKER); auto elem = shm.value()->data[i*elems_per_node + iter[i]]; if (elem <= min_elem) { min_idx = i; min_elem = elem; } } } std::cout << min_elem << " for " << min_idx << std::endl; next_iter(min_idx); } } void setup_shm(Ivy &ivy, std::string in_fname) { std::fstream in_f(in_fname); size_t elems; in_f >> elems; region_sz = sizeof(uint64_t)*elems + sizeof(shm_hdr); auto [shm_, err] = ivy.get_shm(); if (err.has_value()) { throw std::runtime_error("get_shm(): " + err.value()); } DBGH << "Memsetting range " << shm_ << " + " << region_sz << std::endl; // DBGH << "First value = " << ((uint64_t*)shm)[0] << std::endl; // std::memset(shm_, 0, region_sz); // ivy.request_lock(shm_, 4096); shm = reinterpret_cast<shm_layout*>(shm_); } void populate_shm(Ivy &ivy, std::string in_fname) { std::memset(shm.value(), 0, region_sz); std::fstream in_f(in_fname); int in_num; size_t in_iter = 0; size_t elems; in_f >> elems; while (in_f >> in_num) { shm.value()->data[in_iter++] = in_num; } std::cout << "Read " << in_iter << " elems " << std::endl; shm.value()->header.elems = elems; std::cout << "&elems = " << &shm.value()->header.elems << std::endl; std::cout << "elems = " << shm.value() << std::endl; shm.value()->header.ready = 0; for (size_t i = 0; i < NODES_WORKER; i++) shm.value()->header.done[i] = 0; shm.value()->header.nodes = NODES_WORKER; dump_shm(); std::memcpy(&shm.value()->header.canary, CANARY_VAL, sizeof(CANARY_VAL)); shm.value()->header.ready = 1; ivy.dump_shm_page(0); } void wait_for_workers() { /* Wait for every worker to complete */ bool all_done = false; size_t seclap = 0; while (!all_done) { ASSERT_VALID; /* Wait for 100ms before checking */ std::this_thread::sleep_for(std::chrono::seconds(10)); all_done = true; for (size_t i = 0; i < NODES_WORKER; i++) { std::cout << "node " << i << " done val = " << (int)shm.value()->header.done[i] << std::endl; if (shm.value()->header.done[i] != 1) { DBGH << "Checking location " << (void*)(&shm.value()->header.done[i]) << " for id " << i << std::endl; /* At least one node is not ready yet, wait for it */ all_done = false; break; } } seclap += 1; std::cout << seclap << " seconds elapsed waiting for workers" << std::endl; } } int main(int argc, char *argv[]) { std::string in_fname = ""; std::string cfg_fname = ""; uint64_t id = 0; if (argc != 4) { std::cout << "USAGE: " << argv[0] << " <path to input file> <path to config file> <id>" << std::endl; exit(1); } else { in_fname = std::string(argv[1]); cfg_fname = std::string(argv[2]); id = std::strtoull(argv[3], NULL, 0); } Ivy ivy(cfg_fname, id); auto is_manager_res = ivy.is_manager(); auto is_manager = false; if (is_manager_res.second.has_value()) { throw is_manager_res.second.value(); } else { is_manager = is_manager_res.first; } std::cout << "Is manager = " << is_manager << std::endl; setup_shm(ivy, in_fname); if (is_manager) { populate_shm(ivy, in_fname); wait_for_workers(); merge_worker(); } else { sort_worker(id-1); } std::cout << "All done" << std::endl; using namespace std::chrono_literals; dump_shm(); // std::this_thread::sleep_for(24h); while (1); }
23.901198
94
0.59301
suyashmahar
aab93128100df8f51566e82dc2b73c1839d99f59
2,154
cpp
C++
source/logger.cpp
CraftyBoss/SMO-Galaxy-Gravity
c95f5bb7cd9bda797ce2bec17add559f0b611841
[ "MIT" ]
2
2022-03-19T00:54:16.000Z
2022-03-20T01:56:08.000Z
source/logger.cpp
CraftyBoss/SMO-Galaxy-Gravity
c95f5bb7cd9bda797ce2bec17add559f0b611841
[ "MIT" ]
null
null
null
source/logger.cpp
CraftyBoss/SMO-Galaxy-Gravity
c95f5bb7cd9bda797ce2bec17add559f0b611841
[ "MIT" ]
null
null
null
#include "logger.hpp" Logger *gLogger; void Logger::init() { in_addr hostAddress = {0}; sockaddr serverAddress = {0}; if (this->socket_log_state != SOCKET_LOG_UNINITIALIZED) return; nn::nifm::Initialize(); nn::nifm::SubmitNetworkRequest(); while (nn::nifm::IsNetworkRequestOnHold()) { } if (!nn::nifm::IsNetworkAvailable()) { this->socket_log_state = SOCKET_LOG_UNAVAILABLE; return; } if ((this->socket_log_socket = nn::socket::Socket(2, 1, 0)) < 0) { this->socket_log_state = SOCKET_LOG_UNAVAILABLE; return; } nn::socket::InetAton(this->sock_ip, &hostAddress); serverAddress.address = hostAddress; serverAddress.port = nn::socket::InetHtons(this->port); serverAddress.family = 2; if (nn::socket::Connect(this->socket_log_socket, &serverAddress, sizeof(serverAddress)) != 0) { this->socket_log_state = SOCKET_LOG_UNAVAILABLE; return; } this->socket_log_state = SOCKET_LOG_CONNECTED; this->isDisableName = false; } void Logger::LOG(const char *fmt, ...) { va_list args; va_start(args, fmt); char buf[0x500]; if (nn::util::VSNPrintf(buf, sizeof(buf), fmt, args) > 0) { if (!isDisableName) { char prefix[0x510]; nn::util::SNPrintf(prefix, sizeof(prefix), "[%s] %s", this->sockName, buf); socket_log(prefix); } else { socket_log(buf); } } va_end(args); } void Logger::LOG(const char *fmt, va_list args) { // impl for replacing seads system::print char buf[0x500]; if (nn::util::VSNPrintf(buf, sizeof(buf), fmt, args) > 0) { socket_log(buf); } } s32 Logger::READ(char *out) { return this->socket_read_char(out); } bool Logger::pingSocket() { return socket_log("ping") > 0; // if value is greater than zero, than the socket recieved our message, otherwise the connection was lost. } void tryInitSocket() { __asm("STR X20, [X8,#0x18]"); gLogger = new Logger(GLOBALDEBUGIP, 3080, "MainLogger"); // PLACE LOCAL PC IP ADDRESS HERE }
22.4375
141
0.610028
CraftyBoss
aaba0f8d6bae2a8764c1fffcc2e2e22f39b281a8
1,210
cpp
C++
Intuit/2.cpp
aabhas-sao/6Companies30Days
0c07f62b05e18c36fc5262cd51c251b8a6301a2f
[ "MIT" ]
null
null
null
Intuit/2.cpp
aabhas-sao/6Companies30Days
0c07f62b05e18c36fc5262cd51c251b8a6301a2f
[ "MIT" ]
null
null
null
Intuit/2.cpp
aabhas-sao/6Companies30Days
0c07f62b05e18c36fc5262cd51c251b8a6301a2f
[ "MIT" ]
null
null
null
#include <string> #include <vector> using namespace std; class Solution { public: vector<int> DIR = {0, 1, 0, -1, 0}; bool valid(int i, int j, int n, int m) { return i >= 0 && i < n && j >= 0 && j < m; } bool search(int i, int j, int k, vector<vector<char>>& board, string& word, vector<vector<bool>>& vis) { if (k >= word.size()) { return true; } bool found = false; // cout << board[i][j] << endl; vis[i][j] = true; for (int p = 0; p < 4; p++) { int x = i + DIR[p]; int y = j + DIR[p + 1]; if (valid(x, y, board.size(), board[0].size()) && !vis[x][y] && board[x][y] == word[k]) { found = found || search(x, y, k + 1, board, word, vis); } } vis[i][j] = false; return found; } bool isWordExist(vector<vector<char>>& board, string word) { int n = board.size(), m = board[0].size(); bool found = false; vector<vector<bool>> vis(n, vector<bool>(m, false)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (board[i][j] == word[0]) { found = found || search(i, j, 1, board, word, vis); } } } return found; } };
22.830189
77
0.475207
aabhas-sao
aabcd073249ab56d7396df5040ade35c7d4a5dfc
1,715
cpp
C++
Projects/cube_demo/Fireworks.cpp
AlexLamson/ledcube
66ae1e468bcfe0f9930e22773504ca474c987b52
[ "MIT" ]
4
2019-01-26T22:45:40.000Z
2020-10-17T21:14:02.000Z
Projects/cube_demo/Fireworks.cpp
AlexLamson/ledcube
66ae1e468bcfe0f9930e22773504ca474c987b52
[ "MIT" ]
null
null
null
Projects/cube_demo/Fireworks.cpp
AlexLamson/ledcube
66ae1e468bcfe0f9930e22773504ca474c987b52
[ "MIT" ]
2
2019-01-26T22:46:04.000Z
2019-06-21T07:02:40.000Z
/* * Fireworks.cpp * * Created on: Dec 7, 2019 * Author: Alex Lamson */ #include "Fireworks.h" #include <FastLED.h> #include "cube.h" Fireworks::Fireworks() { duration = 30000; } void Fireworks::initialize() { // Stagger the initial spawn - they shouldn't all show up at once for (int i = 0; i < numDots; i++) { startTimes[i] = 2 + 50 * i; } } void Fireworks::tick() { FastLED.clear(); for (byte i = 0; i < numDots; i++) { if (startTimes[i] > 0) { dots[i].init(); startTimes[i] -= 1; } else { dots[i].tick(); } } } Fireworks::Dot::Dot() { init(); } void Fireworks::Dot::init() { position = { 3.5f, 3.5f, 3.5f }; // byte angle = random(255); // speed = { // (cos8(angle)-128)/255.0 * 0.5f, // (sin8(angle)-128)/255.0 * 0.5f, // (randomf()-0.5f) * 0.5f // }; float theta = 2.0f * PI * randomf(); float phi = acos(2.0f * randomf() - 1.0f); speed = { 0.2f * sin(theta) * cos(phi), 0.2f * sin(theta) * sin(phi), 0.2f * cos(theta) }; brightness = 255; hue = random(256); color = CHSV(hue, 255, brightness); } void Fireworks::Dot::tick() { speed.z -= gravity*0.1f; position.x += speed.x; position.y += speed.y; position.z += speed.z; speed.x += -speed.x * 0.07f; speed.y += -speed.y * 0.07f; speed.z += -speed.z * 0.07f; brightness = max(brightness-1, 0); color = CHSV(hue, 255, brightness); if (brightness == 0 || !inCubeBounds(position.x, position.y, position.z)) { init(); } drawSmoothedPixel( position.x, position.y, position.z, color); // leds[ getIndex(position.x, position.y, position.z) ] = color; }
18.244681
77
0.538776
AlexLamson
aabd289d86816cbca2817a950854640cff0b19ce
2,184
cc
C++
ui/views/examples/content_client/examples_main_delegate.cc
iplo/Chain
8bc8943d66285d5258fffc41bed7c840516c4422
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
231
2015-01-08T09:04:44.000Z
2021-12-30T03:03:10.000Z
ui/views/examples/content_client/examples_main_delegate.cc
j4ckfrost/android_external_chromium_org
a1a3dad8b08d1fcf6b6b36c267158ed63217c780
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2017-02-14T21:55:58.000Z
2017-02-14T21:55:58.000Z
ui/views/examples/content_client/examples_main_delegate.cc
j4ckfrost/android_external_chromium_org
a1a3dad8b08d1fcf6b6b36c267158ed63217c780
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
268
2015-01-21T05:53:28.000Z
2022-03-25T22:09:01.000Z
// Copyright (c) 2012 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 "ui/views/examples/content_client/examples_main_delegate.h" #include <string> #include "base/command_line.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/path_service.h" #include "content/public/common/content_switches.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_paths.h" #include "ui/views/examples/content_client/examples_content_browser_client.h" #if defined(OS_WIN) #include "base/logging_win.h" #endif namespace views { namespace examples { namespace { #if defined(OS_WIN) // {83FAC8EE-7A0E-4dbb-A3F6-6F500D7CAB1A} const GUID kViewsExamplesProviderName = { 0x83fac8ee, 0x7a0e, 0x4dbb, { 0xa3, 0xf6, 0x6f, 0x50, 0xd, 0x7c, 0xab, 0x1a } }; #endif } // namespace ExamplesMainDelegate::ExamplesMainDelegate() { } ExamplesMainDelegate::~ExamplesMainDelegate() { } bool ExamplesMainDelegate::BasicStartupComplete(int* exit_code) { const CommandLine& command_line = *CommandLine::ForCurrentProcess(); std::string process_type = command_line.GetSwitchValueASCII(switches::kProcessType); content::SetContentClient(&content_client_); logging::LoggingSettings settings; settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG; bool success = logging::InitLogging(settings); CHECK(success); #if defined(OS_WIN) logging::LogEventProvider::Initialize(kViewsExamplesProviderName); #endif return false; } void ExamplesMainDelegate::PreSandboxStartup() { InitializeResourceBundle(); } content::ContentBrowserClient* ExamplesMainDelegate::CreateContentBrowserClient() { browser_client_.reset(new ExamplesContentBrowserClient); return browser_client_.get(); } void ExamplesMainDelegate::InitializeResourceBundle() { base::FilePath pak_dir; PathService::Get(base::DIR_MODULE, &pak_dir); base::FilePath pak_file; pak_file = pak_dir.Append(FILE_PATH_LITERAL("ui_test.pak")); ui::ResourceBundle::InitSharedInstanceWithPakPath(pak_file); } } // namespace examples } // namespace views
26.962963
77
0.771978
iplo
aabd8af909dedee58c1be66537e5ad14d011a12f
82,600
cc
C++
src/ros/src/security/include/modules/perception/proto/perception_obstacle.pb.cc
Kurinkitos/Twizy-Security
38f3ad3d7315f67e8e691dde69b740b00b33d7b4
[ "MIT" ]
1
2018-05-25T07:20:17.000Z
2018-05-25T07:20:17.000Z
src/ros/src/security/include/modules/perception/proto/perception_obstacle.pb.cc
Kurinkitos/Twizy-Security
38f3ad3d7315f67e8e691dde69b740b00b33d7b4
[ "MIT" ]
null
null
null
src/ros/src/security/include/modules/perception/proto/perception_obstacle.pb.cc
Kurinkitos/Twizy-Security
38f3ad3d7315f67e8e691dde69b740b00b33d7b4
[ "MIT" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: modules/perception/proto/perception_obstacle.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "modules/perception/proto/perception_obstacle.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace apollo { namespace perception { class PointDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Point> { } _Point_default_instance_; class PerceptionObstacleDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<PerceptionObstacle> { } _PerceptionObstacle_default_instance_; class PerceptionObstaclesDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<PerceptionObstacles> { } _PerceptionObstacles_default_instance_; namespace protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto { namespace { ::google::protobuf::Metadata file_level_metadata[3]; const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors[2]; } // namespace PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTableField const TableStruct::entries[] = { {0, 0, 0, ::google::protobuf::internal::kInvalidMask, 0, 0}, }; PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::AuxillaryParseTableField const TableStruct::aux[] = { ::google::protobuf::internal::AuxillaryParseTableField(), }; PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTable const TableStruct::schema[] = { { NULL, NULL, 0, -1, -1, false }, { NULL, NULL, 0, -1, -1, false }, { NULL, NULL, 0, -1, -1, false }, }; const ::google::protobuf::uint32 TableStruct::offsets[] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Point, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Point, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Point, x_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Point, y_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Point, z_), 0, 1, 2, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, position_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, theta_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, velocity_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, length_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, width_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, height_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, polygon_point_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, tracking_time_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, type_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, timestamp_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, point_cloud_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, confidence_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, confidence_type_), 4, 0, 2, 1, 3, 6, 7, ~0u, 8, 5, 9, ~0u, 11, 10, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacles, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacles, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacles, perception_obstacle_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacles, header_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacles, error_code_), ~0u, 0, 1, }; static const ::google::protobuf::internal::MigrationSchema schemas[] = { { 0, 8, sizeof(Point)}, { 11, 30, sizeof(PerceptionObstacle)}, { 44, 52, sizeof(PerceptionObstacles)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&_Point_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&_PerceptionObstacle_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&_PerceptionObstacles_default_instance_), }; namespace { void protobuf_AssignDescriptors() { AddDescriptors(); ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( "modules/perception/proto/perception_obstacle.proto", schemas, file_default_instances, TableStruct::offsets, factory, file_level_metadata, file_level_enum_descriptors, NULL); } void protobuf_AssignDescriptorsOnce() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 3); } } // namespace void TableStruct::Shutdown() { _Point_default_instance_.Shutdown(); delete file_level_metadata[0].reflection; _PerceptionObstacle_default_instance_.Shutdown(); delete file_level_metadata[1].reflection; _PerceptionObstacles_default_instance_.Shutdown(); delete file_level_metadata[2].reflection; } void TableStruct::InitDefaultsImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; ::google::protobuf::internal::InitProtobufDefaults(); ::apollo::common::protobuf_modules_2fcommon_2fproto_2ferror_5fcode_2eproto::InitDefaults(); ::apollo::common::protobuf_modules_2fcommon_2fproto_2fheader_2eproto::InitDefaults(); _Point_default_instance_.DefaultConstruct(); _PerceptionObstacle_default_instance_.DefaultConstruct(); _PerceptionObstacles_default_instance_.DefaultConstruct(); _PerceptionObstacle_default_instance_.get_mutable()->position_ = const_cast< ::apollo::perception::Point*>( ::apollo::perception::Point::internal_default_instance()); _PerceptionObstacle_default_instance_.get_mutable()->velocity_ = const_cast< ::apollo::perception::Point*>( ::apollo::perception::Point::internal_default_instance()); _PerceptionObstacles_default_instance_.get_mutable()->header_ = const_cast< ::apollo::common::Header*>( ::apollo::common::Header::internal_default_instance()); } void InitDefaults() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &TableStruct::InitDefaultsImpl); } void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] = { "\n2modules/perception/proto/perception_ob" "stacle.proto\022\021apollo.perception\032%modules" "/common/proto/error_code.proto\032!modules/" "common/proto/header.proto\"(\n\005Point\022\t\n\001x\030" "\001 \001(\001\022\t\n\001y\030\002 \001(\001\022\t\n\001z\030\003 \001(\001\"\231\005\n\022Percepti" "onObstacle\022\n\n\002id\030\001 \001(\005\022*\n\010position\030\002 \001(\013" "2\030.apollo.perception.Point\022\r\n\005theta\030\003 \001(" "\001\022*\n\010velocity\030\004 \001(\0132\030.apollo.perception." "Point\022\016\n\006length\030\005 \001(\001\022\r\n\005width\030\006 \001(\001\022\016\n\006" "height\030\007 \001(\001\022/\n\rpolygon_point\030\010 \003(\0132\030.ap" "ollo.perception.Point\022\025\n\rtracking_time\030\t" " \001(\001\0228\n\004type\030\n \001(\0162*.apollo.perception.P" "erceptionObstacle.Type\022\021\n\ttimestamp\030\013 \001(" "\001\022\027\n\013point_cloud\030\014 \003(\001B\002\020\001\022\025\n\nconfidence" "\030\r \001(\001:\0011\022]\n\017confidence_type\030\016 \001(\01624.apo" "llo.perception.PerceptionObstacle.Confid" "enceType:\016CONFIDENCE_CNN\"i\n\004Type\022\013\n\007UNKN" "OWN\020\000\022\023\n\017UNKNOWN_MOVABLE\020\001\022\025\n\021UNKNOWN_UN" "MOVABLE\020\002\022\016\n\nPEDESTRIAN\020\003\022\013\n\007BICYCLE\020\004\022\013" "\n\007VEHICLE\020\005\"R\n\016ConfidenceType\022\026\n\022CONFIDE" "NCE_UNKNOWN\020\000\022\022\n\016CONFIDENCE_CNN\020\001\022\024\n\020CON" "FIDENCE_RADAR\020\002\"\262\001\n\023PerceptionObstacles\022" "B\n\023perception_obstacle\030\001 \003(\0132%.apollo.pe" "rception.PerceptionObstacle\022%\n\006header\030\002 " "\001(\0132\025.apollo.common.Header\0220\n\nerror_code" "\030\003 \001(\0162\030.apollo.common.ErrorCode:\002OK" }; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( descriptor, 1036); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "modules/perception/proto/perception_obstacle.proto", &protobuf_RegisterTypes); ::apollo::common::protobuf_modules_2fcommon_2fproto_2ferror_5fcode_2eproto::AddDescriptors(); ::apollo::common::protobuf_modules_2fcommon_2fproto_2fheader_2eproto::AddDescriptors(); ::google::protobuf::internal::OnShutdown(&TableStruct::Shutdown); } void AddDescriptors() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer { StaticDescriptorInitializer() { AddDescriptors(); } } static_descriptor_initializer; } // namespace protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto const ::google::protobuf::EnumDescriptor* PerceptionObstacle_Type_descriptor() { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::file_level_enum_descriptors[0]; } bool PerceptionObstacle_Type_IsValid(int value) { switch (value) { case 0: case 1: case 2: case 3: case 4: case 5: return true; default: return false; } } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const PerceptionObstacle_Type PerceptionObstacle::UNKNOWN; const PerceptionObstacle_Type PerceptionObstacle::UNKNOWN_MOVABLE; const PerceptionObstacle_Type PerceptionObstacle::UNKNOWN_UNMOVABLE; const PerceptionObstacle_Type PerceptionObstacle::PEDESTRIAN; const PerceptionObstacle_Type PerceptionObstacle::BICYCLE; const PerceptionObstacle_Type PerceptionObstacle::VEHICLE; const PerceptionObstacle_Type PerceptionObstacle::Type_MIN; const PerceptionObstacle_Type PerceptionObstacle::Type_MAX; const int PerceptionObstacle::Type_ARRAYSIZE; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 const ::google::protobuf::EnumDescriptor* PerceptionObstacle_ConfidenceType_descriptor() { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::file_level_enum_descriptors[1]; } bool PerceptionObstacle_ConfidenceType_IsValid(int value) { switch (value) { case 0: case 1: case 2: return true; default: return false; } } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const PerceptionObstacle_ConfidenceType PerceptionObstacle::CONFIDENCE_UNKNOWN; const PerceptionObstacle_ConfidenceType PerceptionObstacle::CONFIDENCE_CNN; const PerceptionObstacle_ConfidenceType PerceptionObstacle::CONFIDENCE_RADAR; const PerceptionObstacle_ConfidenceType PerceptionObstacle::ConfidenceType_MIN; const PerceptionObstacle_ConfidenceType PerceptionObstacle::ConfidenceType_MAX; const int PerceptionObstacle::ConfidenceType_ARRAYSIZE; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Point::kXFieldNumber; const int Point::kYFieldNumber; const int Point::kZFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Point::Point() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::InitDefaults(); } SharedCtor(); // @@protoc_insertion_point(constructor:apollo.perception.Point) } Point::Point(const Point& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&x_, &from.x_, reinterpret_cast<char*>(&z_) - reinterpret_cast<char*>(&x_) + sizeof(z_)); // @@protoc_insertion_point(copy_constructor:apollo.perception.Point) } void Point::SharedCtor() { _cached_size_ = 0; ::memset(&x_, 0, reinterpret_cast<char*>(&z_) - reinterpret_cast<char*>(&x_) + sizeof(z_)); } Point::~Point() { // @@protoc_insertion_point(destructor:apollo.perception.Point) SharedDtor(); } void Point::SharedDtor() { } void Point::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Point::descriptor() { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const Point& Point::default_instance() { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::InitDefaults(); return *internal_default_instance(); } Point* Point::New(::google::protobuf::Arena* arena) const { Point* n = new Point; if (arena != NULL) { arena->Own(n); } return n; } void Point::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.perception.Point) if (_has_bits_[0 / 32] & 7u) { ::memset(&x_, 0, reinterpret_cast<char*>(&z_) - reinterpret_cast<char*>(&x_) + sizeof(z_)); } _has_bits_.Clear(); _internal_metadata_.Clear(); } bool Point::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.perception.Point) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional double x = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(9u)) { set_has_x(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &x_))); } else { goto handle_unusual; } break; } // optional double y = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(17u)) { set_has_y(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &y_))); } else { goto handle_unusual; } break; } // optional double z = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(25u)) { set_has_z(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &z_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:apollo.perception.Point) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.perception.Point) return false; #undef DO_ } void Point::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.perception.Point) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional double x = 1; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->x(), output); } // optional double y = 2; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->y(), output); } // optional double z = 3; if (cached_has_bits & 0x00000004u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(3, this->z(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.perception.Point) } ::google::protobuf::uint8* Point::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.perception.Point) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional double x = 1; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->x(), target); } // optional double y = 2; if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->y(), target); } // optional double z = 3; if (cached_has_bits & 0x00000004u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(3, this->z(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.perception.Point) return target; } size_t Point::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:apollo.perception.Point) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } if (_has_bits_[0 / 32] & 7u) { // optional double x = 1; if (has_x()) { total_size += 1 + 8; } // optional double y = 2; if (has_y()) { total_size += 1 + 8; } // optional double z = 3; if (has_z()) { total_size += 1 + 8; } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Point::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.perception.Point) GOOGLE_DCHECK_NE(&from, this); const Point* source = ::google::protobuf::internal::DynamicCastToGenerated<const Point>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.perception.Point) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.perception.Point) MergeFrom(*source); } } void Point::MergeFrom(const Point& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.perception.Point) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 7u) { if (cached_has_bits & 0x00000001u) { x_ = from.x_; } if (cached_has_bits & 0x00000002u) { y_ = from.y_; } if (cached_has_bits & 0x00000004u) { z_ = from.z_; } _has_bits_[0] |= cached_has_bits; } } void Point::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.perception.Point) if (&from == this) return; Clear(); MergeFrom(from); } void Point::CopyFrom(const Point& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.perception.Point) if (&from == this) return; Clear(); MergeFrom(from); } bool Point::IsInitialized() const { return true; } void Point::Swap(Point* other) { if (other == this) return; InternalSwap(other); } void Point::InternalSwap(Point* other) { std::swap(x_, other->x_); std::swap(y_, other->y_); std::swap(z_, other->z_); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Point::GetMetadata() const { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::file_level_metadata[kIndexInFileMessages]; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // Point // optional double x = 1; bool Point::has_x() const { return (_has_bits_[0] & 0x00000001u) != 0; } void Point::set_has_x() { _has_bits_[0] |= 0x00000001u; } void Point::clear_has_x() { _has_bits_[0] &= ~0x00000001u; } void Point::clear_x() { x_ = 0; clear_has_x(); } double Point::x() const { // @@protoc_insertion_point(field_get:apollo.perception.Point.x) return x_; } void Point::set_x(double value) { set_has_x(); x_ = value; // @@protoc_insertion_point(field_set:apollo.perception.Point.x) } // optional double y = 2; bool Point::has_y() const { return (_has_bits_[0] & 0x00000002u) != 0; } void Point::set_has_y() { _has_bits_[0] |= 0x00000002u; } void Point::clear_has_y() { _has_bits_[0] &= ~0x00000002u; } void Point::clear_y() { y_ = 0; clear_has_y(); } double Point::y() const { // @@protoc_insertion_point(field_get:apollo.perception.Point.y) return y_; } void Point::set_y(double value) { set_has_y(); y_ = value; // @@protoc_insertion_point(field_set:apollo.perception.Point.y) } // optional double z = 3; bool Point::has_z() const { return (_has_bits_[0] & 0x00000004u) != 0; } void Point::set_has_z() { _has_bits_[0] |= 0x00000004u; } void Point::clear_has_z() { _has_bits_[0] &= ~0x00000004u; } void Point::clear_z() { z_ = 0; clear_has_z(); } double Point::z() const { // @@protoc_insertion_point(field_get:apollo.perception.Point.z) return z_; } void Point::set_z(double value) { set_has_z(); z_ = value; // @@protoc_insertion_point(field_set:apollo.perception.Point.z) } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int PerceptionObstacle::kIdFieldNumber; const int PerceptionObstacle::kPositionFieldNumber; const int PerceptionObstacle::kThetaFieldNumber; const int PerceptionObstacle::kVelocityFieldNumber; const int PerceptionObstacle::kLengthFieldNumber; const int PerceptionObstacle::kWidthFieldNumber; const int PerceptionObstacle::kHeightFieldNumber; const int PerceptionObstacle::kPolygonPointFieldNumber; const int PerceptionObstacle::kTrackingTimeFieldNumber; const int PerceptionObstacle::kTypeFieldNumber; const int PerceptionObstacle::kTimestampFieldNumber; const int PerceptionObstacle::kPointCloudFieldNumber; const int PerceptionObstacle::kConfidenceFieldNumber; const int PerceptionObstacle::kConfidenceTypeFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 PerceptionObstacle::PerceptionObstacle() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::InitDefaults(); } SharedCtor(); // @@protoc_insertion_point(constructor:apollo.perception.PerceptionObstacle) } PerceptionObstacle::PerceptionObstacle(const PerceptionObstacle& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0), polygon_point_(from.polygon_point_), point_cloud_(from.point_cloud_) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_position()) { position_ = new ::apollo::perception::Point(*from.position_); } else { position_ = NULL; } if (from.has_velocity()) { velocity_ = new ::apollo::perception::Point(*from.velocity_); } else { velocity_ = NULL; } ::memcpy(&theta_, &from.theta_, reinterpret_cast<char*>(&confidence_) - reinterpret_cast<char*>(&theta_) + sizeof(confidence_)); // @@protoc_insertion_point(copy_constructor:apollo.perception.PerceptionObstacle) } void PerceptionObstacle::SharedCtor() { _cached_size_ = 0; ::memset(&position_, 0, reinterpret_cast<char*>(&timestamp_) - reinterpret_cast<char*>(&position_) + sizeof(timestamp_)); confidence_type_ = 1; confidence_ = 1; } PerceptionObstacle::~PerceptionObstacle() { // @@protoc_insertion_point(destructor:apollo.perception.PerceptionObstacle) SharedDtor(); } void PerceptionObstacle::SharedDtor() { if (this != internal_default_instance()) { delete position_; } if (this != internal_default_instance()) { delete velocity_; } } void PerceptionObstacle::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* PerceptionObstacle::descriptor() { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const PerceptionObstacle& PerceptionObstacle::default_instance() { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::InitDefaults(); return *internal_default_instance(); } PerceptionObstacle* PerceptionObstacle::New(::google::protobuf::Arena* arena) const { PerceptionObstacle* n = new PerceptionObstacle; if (arena != NULL) { arena->Own(n); } return n; } void PerceptionObstacle::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.perception.PerceptionObstacle) polygon_point_.Clear(); point_cloud_.Clear(); if (_has_bits_[0 / 32] & 3u) { if (has_position()) { GOOGLE_DCHECK(position_ != NULL); position_->::apollo::perception::Point::Clear(); } if (has_velocity()) { GOOGLE_DCHECK(velocity_ != NULL); velocity_->::apollo::perception::Point::Clear(); } } if (_has_bits_[0 / 32] & 252u) { ::memset(&theta_, 0, reinterpret_cast<char*>(&height_) - reinterpret_cast<char*>(&theta_) + sizeof(height_)); } if (_has_bits_[8 / 32] & 3840u) { ::memset(&tracking_time_, 0, reinterpret_cast<char*>(&timestamp_) - reinterpret_cast<char*>(&tracking_time_) + sizeof(timestamp_)); confidence_type_ = 1; confidence_ = 1; } _has_bits_.Clear(); _internal_metadata_.Clear(); } bool PerceptionObstacle::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.perception.PerceptionObstacle) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional int32 id = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u)) { set_has_id(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &id_))); } else { goto handle_unusual; } break; } // optional .apollo.perception.Point position = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_position())); } else { goto handle_unusual; } break; } // optional double theta = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(25u)) { set_has_theta(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &theta_))); } else { goto handle_unusual; } break; } // optional .apollo.perception.Point velocity = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(34u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_velocity())); } else { goto handle_unusual; } break; } // optional double length = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(41u)) { set_has_length(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &length_))); } else { goto handle_unusual; } break; } // optional double width = 6; case 6: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(49u)) { set_has_width(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &width_))); } else { goto handle_unusual; } break; } // optional double height = 7; case 7: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(57u)) { set_has_height(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &height_))); } else { goto handle_unusual; } break; } // repeated .apollo.perception.Point polygon_point = 8; case 8: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(66u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, add_polygon_point())); } else { goto handle_unusual; } break; } // optional double tracking_time = 9; case 9: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(73u)) { set_has_tracking_time(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &tracking_time_))); } else { goto handle_unusual; } break; } // optional .apollo.perception.PerceptionObstacle.Type type = 10; case 10: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(80u)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::apollo::perception::PerceptionObstacle_Type_IsValid(value)) { set_type(static_cast< ::apollo::perception::PerceptionObstacle_Type >(value)); } else { mutable_unknown_fields()->AddVarint(10, value); } } else { goto handle_unusual; } break; } // optional double timestamp = 11; case 11: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(89u)) { set_has_timestamp(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &timestamp_))); } else { goto handle_unusual; } break; } // repeated double point_cloud = 12 [packed = true]; case 12: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(98u)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, this->mutable_point_cloud()))); } else if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(97u)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( 1, 98u, input, this->mutable_point_cloud()))); } else { goto handle_unusual; } break; } // optional double confidence = 13 [default = 1]; case 13: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(105u)) { set_has_confidence(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &confidence_))); } else { goto handle_unusual; } break; } // optional .apollo.perception.PerceptionObstacle.ConfidenceType confidence_type = 14 [default = CONFIDENCE_CNN]; case 14: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(112u)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::apollo::perception::PerceptionObstacle_ConfidenceType_IsValid(value)) { set_confidence_type(static_cast< ::apollo::perception::PerceptionObstacle_ConfidenceType >(value)); } else { mutable_unknown_fields()->AddVarint(14, value); } } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:apollo.perception.PerceptionObstacle) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.perception.PerceptionObstacle) return false; #undef DO_ } void PerceptionObstacle::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.perception.PerceptionObstacle) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional int32 id = 1; if (cached_has_bits & 0x00000010u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->id(), output); } // optional .apollo.perception.Point position = 2; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, *this->position_, output); } // optional double theta = 3; if (cached_has_bits & 0x00000004u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(3, this->theta(), output); } // optional .apollo.perception.Point velocity = 4; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, *this->velocity_, output); } // optional double length = 5; if (cached_has_bits & 0x00000008u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(5, this->length(), output); } // optional double width = 6; if (cached_has_bits & 0x00000040u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(6, this->width(), output); } // optional double height = 7; if (cached_has_bits & 0x00000080u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(7, this->height(), output); } // repeated .apollo.perception.Point polygon_point = 8; for (unsigned int i = 0, n = this->polygon_point_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 8, this->polygon_point(i), output); } // optional double tracking_time = 9; if (cached_has_bits & 0x00000100u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(9, this->tracking_time(), output); } // optional .apollo.perception.PerceptionObstacle.Type type = 10; if (cached_has_bits & 0x00000020u) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 10, this->type(), output); } // optional double timestamp = 11; if (cached_has_bits & 0x00000200u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(11, this->timestamp(), output); } // repeated double point_cloud = 12 [packed = true]; if (this->point_cloud_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(12, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(_point_cloud_cached_byte_size_); ::google::protobuf::internal::WireFormatLite::WriteDoubleArray( this->point_cloud().data(), this->point_cloud_size(), output); } // optional double confidence = 13 [default = 1]; if (cached_has_bits & 0x00000800u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(13, this->confidence(), output); } // optional .apollo.perception.PerceptionObstacle.ConfidenceType confidence_type = 14 [default = CONFIDENCE_CNN]; if (cached_has_bits & 0x00000400u) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 14, this->confidence_type(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.perception.PerceptionObstacle) } ::google::protobuf::uint8* PerceptionObstacle::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.perception.PerceptionObstacle) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional int32 id = 1; if (cached_has_bits & 0x00000010u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->id(), target); } // optional .apollo.perception.Point position = 2; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 2, *this->position_, deterministic, target); } // optional double theta = 3; if (cached_has_bits & 0x00000004u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(3, this->theta(), target); } // optional .apollo.perception.Point velocity = 4; if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 4, *this->velocity_, deterministic, target); } // optional double length = 5; if (cached_has_bits & 0x00000008u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(5, this->length(), target); } // optional double width = 6; if (cached_has_bits & 0x00000040u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(6, this->width(), target); } // optional double height = 7; if (cached_has_bits & 0x00000080u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(7, this->height(), target); } // repeated .apollo.perception.Point polygon_point = 8; for (unsigned int i = 0, n = this->polygon_point_size(); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 8, this->polygon_point(i), deterministic, target); } // optional double tracking_time = 9; if (cached_has_bits & 0x00000100u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(9, this->tracking_time(), target); } // optional .apollo.perception.PerceptionObstacle.Type type = 10; if (cached_has_bits & 0x00000020u) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 10, this->type(), target); } // optional double timestamp = 11; if (cached_has_bits & 0x00000200u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(11, this->timestamp(), target); } // repeated double point_cloud = 12 [packed = true]; if (this->point_cloud_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 12, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( _point_cloud_cached_byte_size_, target); target = ::google::protobuf::internal::WireFormatLite:: WriteDoubleNoTagToArray(this->point_cloud_, target); } // optional double confidence = 13 [default = 1]; if (cached_has_bits & 0x00000800u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(13, this->confidence(), target); } // optional .apollo.perception.PerceptionObstacle.ConfidenceType confidence_type = 14 [default = CONFIDENCE_CNN]; if (cached_has_bits & 0x00000400u) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 14, this->confidence_type(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.perception.PerceptionObstacle) return target; } size_t PerceptionObstacle::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:apollo.perception.PerceptionObstacle) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } // repeated .apollo.perception.Point polygon_point = 8; { unsigned int count = this->polygon_point_size(); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->polygon_point(i)); } } // repeated double point_cloud = 12 [packed = true]; { unsigned int count = this->point_cloud_size(); size_t data_size = 8UL * count; if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size(data_size); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _point_cloud_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } if (_has_bits_[0 / 32] & 255u) { // optional .apollo.perception.Point position = 2; if (has_position()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->position_); } // optional .apollo.perception.Point velocity = 4; if (has_velocity()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->velocity_); } // optional double theta = 3; if (has_theta()) { total_size += 1 + 8; } // optional double length = 5; if (has_length()) { total_size += 1 + 8; } // optional int32 id = 1; if (has_id()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->id()); } // optional .apollo.perception.PerceptionObstacle.Type type = 10; if (has_type()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->type()); } // optional double width = 6; if (has_width()) { total_size += 1 + 8; } // optional double height = 7; if (has_height()) { total_size += 1 + 8; } } if (_has_bits_[8 / 32] & 3840u) { // optional double tracking_time = 9; if (has_tracking_time()) { total_size += 1 + 8; } // optional double timestamp = 11; if (has_timestamp()) { total_size += 1 + 8; } // optional .apollo.perception.PerceptionObstacle.ConfidenceType confidence_type = 14 [default = CONFIDENCE_CNN]; if (has_confidence_type()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->confidence_type()); } // optional double confidence = 13 [default = 1]; if (has_confidence()) { total_size += 1 + 8; } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void PerceptionObstacle::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.perception.PerceptionObstacle) GOOGLE_DCHECK_NE(&from, this); const PerceptionObstacle* source = ::google::protobuf::internal::DynamicCastToGenerated<const PerceptionObstacle>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.perception.PerceptionObstacle) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.perception.PerceptionObstacle) MergeFrom(*source); } } void PerceptionObstacle::MergeFrom(const PerceptionObstacle& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.perception.PerceptionObstacle) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; polygon_point_.MergeFrom(from.polygon_point_); point_cloud_.MergeFrom(from.point_cloud_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 255u) { if (cached_has_bits & 0x00000001u) { mutable_position()->::apollo::perception::Point::MergeFrom(from.position()); } if (cached_has_bits & 0x00000002u) { mutable_velocity()->::apollo::perception::Point::MergeFrom(from.velocity()); } if (cached_has_bits & 0x00000004u) { theta_ = from.theta_; } if (cached_has_bits & 0x00000008u) { length_ = from.length_; } if (cached_has_bits & 0x00000010u) { id_ = from.id_; } if (cached_has_bits & 0x00000020u) { type_ = from.type_; } if (cached_has_bits & 0x00000040u) { width_ = from.width_; } if (cached_has_bits & 0x00000080u) { height_ = from.height_; } _has_bits_[0] |= cached_has_bits; } if (cached_has_bits & 3840u) { if (cached_has_bits & 0x00000100u) { tracking_time_ = from.tracking_time_; } if (cached_has_bits & 0x00000200u) { timestamp_ = from.timestamp_; } if (cached_has_bits & 0x00000400u) { confidence_type_ = from.confidence_type_; } if (cached_has_bits & 0x00000800u) { confidence_ = from.confidence_; } _has_bits_[0] |= cached_has_bits; } } void PerceptionObstacle::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.perception.PerceptionObstacle) if (&from == this) return; Clear(); MergeFrom(from); } void PerceptionObstacle::CopyFrom(const PerceptionObstacle& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.perception.PerceptionObstacle) if (&from == this) return; Clear(); MergeFrom(from); } bool PerceptionObstacle::IsInitialized() const { return true; } void PerceptionObstacle::Swap(PerceptionObstacle* other) { if (other == this) return; InternalSwap(other); } void PerceptionObstacle::InternalSwap(PerceptionObstacle* other) { polygon_point_.InternalSwap(&other->polygon_point_); point_cloud_.InternalSwap(&other->point_cloud_); std::swap(position_, other->position_); std::swap(velocity_, other->velocity_); std::swap(theta_, other->theta_); std::swap(length_, other->length_); std::swap(id_, other->id_); std::swap(type_, other->type_); std::swap(width_, other->width_); std::swap(height_, other->height_); std::swap(tracking_time_, other->tracking_time_); std::swap(timestamp_, other->timestamp_); std::swap(confidence_type_, other->confidence_type_); std::swap(confidence_, other->confidence_); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata PerceptionObstacle::GetMetadata() const { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::file_level_metadata[kIndexInFileMessages]; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // PerceptionObstacle // optional int32 id = 1; bool PerceptionObstacle::has_id() const { return (_has_bits_[0] & 0x00000010u) != 0; } void PerceptionObstacle::set_has_id() { _has_bits_[0] |= 0x00000010u; } void PerceptionObstacle::clear_has_id() { _has_bits_[0] &= ~0x00000010u; } void PerceptionObstacle::clear_id() { id_ = 0; clear_has_id(); } ::google::protobuf::int32 PerceptionObstacle::id() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.id) return id_; } void PerceptionObstacle::set_id(::google::protobuf::int32 value) { set_has_id(); id_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.id) } // optional .apollo.perception.Point position = 2; bool PerceptionObstacle::has_position() const { return (_has_bits_[0] & 0x00000001u) != 0; } void PerceptionObstacle::set_has_position() { _has_bits_[0] |= 0x00000001u; } void PerceptionObstacle::clear_has_position() { _has_bits_[0] &= ~0x00000001u; } void PerceptionObstacle::clear_position() { if (position_ != NULL) position_->::apollo::perception::Point::Clear(); clear_has_position(); } const ::apollo::perception::Point& PerceptionObstacle::position() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.position) return position_ != NULL ? *position_ : *::apollo::perception::Point::internal_default_instance(); } ::apollo::perception::Point* PerceptionObstacle::mutable_position() { set_has_position(); if (position_ == NULL) { position_ = new ::apollo::perception::Point; } // @@protoc_insertion_point(field_mutable:apollo.perception.PerceptionObstacle.position) return position_; } ::apollo::perception::Point* PerceptionObstacle::release_position() { // @@protoc_insertion_point(field_release:apollo.perception.PerceptionObstacle.position) clear_has_position(); ::apollo::perception::Point* temp = position_; position_ = NULL; return temp; } void PerceptionObstacle::set_allocated_position(::apollo::perception::Point* position) { delete position_; position_ = position; if (position) { set_has_position(); } else { clear_has_position(); } // @@protoc_insertion_point(field_set_allocated:apollo.perception.PerceptionObstacle.position) } // optional double theta = 3; bool PerceptionObstacle::has_theta() const { return (_has_bits_[0] & 0x00000004u) != 0; } void PerceptionObstacle::set_has_theta() { _has_bits_[0] |= 0x00000004u; } void PerceptionObstacle::clear_has_theta() { _has_bits_[0] &= ~0x00000004u; } void PerceptionObstacle::clear_theta() { theta_ = 0; clear_has_theta(); } double PerceptionObstacle::theta() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.theta) return theta_; } void PerceptionObstacle::set_theta(double value) { set_has_theta(); theta_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.theta) } // optional .apollo.perception.Point velocity = 4; bool PerceptionObstacle::has_velocity() const { return (_has_bits_[0] & 0x00000002u) != 0; } void PerceptionObstacle::set_has_velocity() { _has_bits_[0] |= 0x00000002u; } void PerceptionObstacle::clear_has_velocity() { _has_bits_[0] &= ~0x00000002u; } void PerceptionObstacle::clear_velocity() { if (velocity_ != NULL) velocity_->::apollo::perception::Point::Clear(); clear_has_velocity(); } const ::apollo::perception::Point& PerceptionObstacle::velocity() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.velocity) return velocity_ != NULL ? *velocity_ : *::apollo::perception::Point::internal_default_instance(); } ::apollo::perception::Point* PerceptionObstacle::mutable_velocity() { set_has_velocity(); if (velocity_ == NULL) { velocity_ = new ::apollo::perception::Point; } // @@protoc_insertion_point(field_mutable:apollo.perception.PerceptionObstacle.velocity) return velocity_; } ::apollo::perception::Point* PerceptionObstacle::release_velocity() { // @@protoc_insertion_point(field_release:apollo.perception.PerceptionObstacle.velocity) clear_has_velocity(); ::apollo::perception::Point* temp = velocity_; velocity_ = NULL; return temp; } void PerceptionObstacle::set_allocated_velocity(::apollo::perception::Point* velocity) { delete velocity_; velocity_ = velocity; if (velocity) { set_has_velocity(); } else { clear_has_velocity(); } // @@protoc_insertion_point(field_set_allocated:apollo.perception.PerceptionObstacle.velocity) } // optional double length = 5; bool PerceptionObstacle::has_length() const { return (_has_bits_[0] & 0x00000008u) != 0; } void PerceptionObstacle::set_has_length() { _has_bits_[0] |= 0x00000008u; } void PerceptionObstacle::clear_has_length() { _has_bits_[0] &= ~0x00000008u; } void PerceptionObstacle::clear_length() { length_ = 0; clear_has_length(); } double PerceptionObstacle::length() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.length) return length_; } void PerceptionObstacle::set_length(double value) { set_has_length(); length_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.length) } // optional double width = 6; bool PerceptionObstacle::has_width() const { return (_has_bits_[0] & 0x00000040u) != 0; } void PerceptionObstacle::set_has_width() { _has_bits_[0] |= 0x00000040u; } void PerceptionObstacle::clear_has_width() { _has_bits_[0] &= ~0x00000040u; } void PerceptionObstacle::clear_width() { width_ = 0; clear_has_width(); } double PerceptionObstacle::width() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.width) return width_; } void PerceptionObstacle::set_width(double value) { set_has_width(); width_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.width) } // optional double height = 7; bool PerceptionObstacle::has_height() const { return (_has_bits_[0] & 0x00000080u) != 0; } void PerceptionObstacle::set_has_height() { _has_bits_[0] |= 0x00000080u; } void PerceptionObstacle::clear_has_height() { _has_bits_[0] &= ~0x00000080u; } void PerceptionObstacle::clear_height() { height_ = 0; clear_has_height(); } double PerceptionObstacle::height() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.height) return height_; } void PerceptionObstacle::set_height(double value) { set_has_height(); height_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.height) } // repeated .apollo.perception.Point polygon_point = 8; int PerceptionObstacle::polygon_point_size() const { return polygon_point_.size(); } void PerceptionObstacle::clear_polygon_point() { polygon_point_.Clear(); } const ::apollo::perception::Point& PerceptionObstacle::polygon_point(int index) const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.polygon_point) return polygon_point_.Get(index); } ::apollo::perception::Point* PerceptionObstacle::mutable_polygon_point(int index) { // @@protoc_insertion_point(field_mutable:apollo.perception.PerceptionObstacle.polygon_point) return polygon_point_.Mutable(index); } ::apollo::perception::Point* PerceptionObstacle::add_polygon_point() { // @@protoc_insertion_point(field_add:apollo.perception.PerceptionObstacle.polygon_point) return polygon_point_.Add(); } ::google::protobuf::RepeatedPtrField< ::apollo::perception::Point >* PerceptionObstacle::mutable_polygon_point() { // @@protoc_insertion_point(field_mutable_list:apollo.perception.PerceptionObstacle.polygon_point) return &polygon_point_; } const ::google::protobuf::RepeatedPtrField< ::apollo::perception::Point >& PerceptionObstacle::polygon_point() const { // @@protoc_insertion_point(field_list:apollo.perception.PerceptionObstacle.polygon_point) return polygon_point_; } // optional double tracking_time = 9; bool PerceptionObstacle::has_tracking_time() const { return (_has_bits_[0] & 0x00000100u) != 0; } void PerceptionObstacle::set_has_tracking_time() { _has_bits_[0] |= 0x00000100u; } void PerceptionObstacle::clear_has_tracking_time() { _has_bits_[0] &= ~0x00000100u; } void PerceptionObstacle::clear_tracking_time() { tracking_time_ = 0; clear_has_tracking_time(); } double PerceptionObstacle::tracking_time() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.tracking_time) return tracking_time_; } void PerceptionObstacle::set_tracking_time(double value) { set_has_tracking_time(); tracking_time_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.tracking_time) } // optional .apollo.perception.PerceptionObstacle.Type type = 10; bool PerceptionObstacle::has_type() const { return (_has_bits_[0] & 0x00000020u) != 0; } void PerceptionObstacle::set_has_type() { _has_bits_[0] |= 0x00000020u; } void PerceptionObstacle::clear_has_type() { _has_bits_[0] &= ~0x00000020u; } void PerceptionObstacle::clear_type() { type_ = 0; clear_has_type(); } ::apollo::perception::PerceptionObstacle_Type PerceptionObstacle::type() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.type) return static_cast< ::apollo::perception::PerceptionObstacle_Type >(type_); } void PerceptionObstacle::set_type(::apollo::perception::PerceptionObstacle_Type value) { assert(::apollo::perception::PerceptionObstacle_Type_IsValid(value)); set_has_type(); type_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.type) } // optional double timestamp = 11; bool PerceptionObstacle::has_timestamp() const { return (_has_bits_[0] & 0x00000200u) != 0; } void PerceptionObstacle::set_has_timestamp() { _has_bits_[0] |= 0x00000200u; } void PerceptionObstacle::clear_has_timestamp() { _has_bits_[0] &= ~0x00000200u; } void PerceptionObstacle::clear_timestamp() { timestamp_ = 0; clear_has_timestamp(); } double PerceptionObstacle::timestamp() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.timestamp) return timestamp_; } void PerceptionObstacle::set_timestamp(double value) { set_has_timestamp(); timestamp_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.timestamp) } // repeated double point_cloud = 12 [packed = true]; int PerceptionObstacle::point_cloud_size() const { return point_cloud_.size(); } void PerceptionObstacle::clear_point_cloud() { point_cloud_.Clear(); } double PerceptionObstacle::point_cloud(int index) const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.point_cloud) return point_cloud_.Get(index); } void PerceptionObstacle::set_point_cloud(int index, double value) { point_cloud_.Set(index, value); // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.point_cloud) } void PerceptionObstacle::add_point_cloud(double value) { point_cloud_.Add(value); // @@protoc_insertion_point(field_add:apollo.perception.PerceptionObstacle.point_cloud) } const ::google::protobuf::RepeatedField< double >& PerceptionObstacle::point_cloud() const { // @@protoc_insertion_point(field_list:apollo.perception.PerceptionObstacle.point_cloud) return point_cloud_; } ::google::protobuf::RepeatedField< double >* PerceptionObstacle::mutable_point_cloud() { // @@protoc_insertion_point(field_mutable_list:apollo.perception.PerceptionObstacle.point_cloud) return &point_cloud_; } // optional double confidence = 13 [default = 1]; bool PerceptionObstacle::has_confidence() const { return (_has_bits_[0] & 0x00000800u) != 0; } void PerceptionObstacle::set_has_confidence() { _has_bits_[0] |= 0x00000800u; } void PerceptionObstacle::clear_has_confidence() { _has_bits_[0] &= ~0x00000800u; } void PerceptionObstacle::clear_confidence() { confidence_ = 1; clear_has_confidence(); } double PerceptionObstacle::confidence() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.confidence) return confidence_; } void PerceptionObstacle::set_confidence(double value) { set_has_confidence(); confidence_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.confidence) } // optional .apollo.perception.PerceptionObstacle.ConfidenceType confidence_type = 14 [default = CONFIDENCE_CNN]; bool PerceptionObstacle::has_confidence_type() const { return (_has_bits_[0] & 0x00000400u) != 0; } void PerceptionObstacle::set_has_confidence_type() { _has_bits_[0] |= 0x00000400u; } void PerceptionObstacle::clear_has_confidence_type() { _has_bits_[0] &= ~0x00000400u; } void PerceptionObstacle::clear_confidence_type() { confidence_type_ = 1; clear_has_confidence_type(); } ::apollo::perception::PerceptionObstacle_ConfidenceType PerceptionObstacle::confidence_type() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.confidence_type) return static_cast< ::apollo::perception::PerceptionObstacle_ConfidenceType >(confidence_type_); } void PerceptionObstacle::set_confidence_type(::apollo::perception::PerceptionObstacle_ConfidenceType value) { assert(::apollo::perception::PerceptionObstacle_ConfidenceType_IsValid(value)); set_has_confidence_type(); confidence_type_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.confidence_type) } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int PerceptionObstacles::kPerceptionObstacleFieldNumber; const int PerceptionObstacles::kHeaderFieldNumber; const int PerceptionObstacles::kErrorCodeFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 PerceptionObstacles::PerceptionObstacles() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::InitDefaults(); } SharedCtor(); // @@protoc_insertion_point(constructor:apollo.perception.PerceptionObstacles) } PerceptionObstacles::PerceptionObstacles(const PerceptionObstacles& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0), perception_obstacle_(from.perception_obstacle_) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_header()) { header_ = new ::apollo::common::Header(*from.header_); } else { header_ = NULL; } error_code_ = from.error_code_; // @@protoc_insertion_point(copy_constructor:apollo.perception.PerceptionObstacles) } void PerceptionObstacles::SharedCtor() { _cached_size_ = 0; ::memset(&header_, 0, reinterpret_cast<char*>(&error_code_) - reinterpret_cast<char*>(&header_) + sizeof(error_code_)); } PerceptionObstacles::~PerceptionObstacles() { // @@protoc_insertion_point(destructor:apollo.perception.PerceptionObstacles) SharedDtor(); } void PerceptionObstacles::SharedDtor() { if (this != internal_default_instance()) { delete header_; } } void PerceptionObstacles::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* PerceptionObstacles::descriptor() { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const PerceptionObstacles& PerceptionObstacles::default_instance() { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::InitDefaults(); return *internal_default_instance(); } PerceptionObstacles* PerceptionObstacles::New(::google::protobuf::Arena* arena) const { PerceptionObstacles* n = new PerceptionObstacles; if (arena != NULL) { arena->Own(n); } return n; } void PerceptionObstacles::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.perception.PerceptionObstacles) perception_obstacle_.Clear(); if (has_header()) { GOOGLE_DCHECK(header_ != NULL); header_->::apollo::common::Header::Clear(); } error_code_ = 0; _has_bits_.Clear(); _internal_metadata_.Clear(); } bool PerceptionObstacles::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.perception.PerceptionObstacles) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .apollo.perception.PerceptionObstacle perception_obstacle = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, add_perception_obstacle())); } else { goto handle_unusual; } break; } // optional .apollo.common.Header header = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_header())); } else { goto handle_unusual; } break; } // optional .apollo.common.ErrorCode error_code = 3 [default = OK]; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(24u)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::apollo::common::ErrorCode_IsValid(value)) { set_error_code(static_cast< ::apollo::common::ErrorCode >(value)); } else { mutable_unknown_fields()->AddVarint(3, value); } } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:apollo.perception.PerceptionObstacles) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.perception.PerceptionObstacles) return false; #undef DO_ } void PerceptionObstacles::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.perception.PerceptionObstacles) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .apollo.perception.PerceptionObstacle perception_obstacle = 1; for (unsigned int i = 0, n = this->perception_obstacle_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->perception_obstacle(i), output); } cached_has_bits = _has_bits_[0]; // optional .apollo.common.Header header = 2; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, *this->header_, output); } // optional .apollo.common.ErrorCode error_code = 3 [default = OK]; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 3, this->error_code(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.perception.PerceptionObstacles) } ::google::protobuf::uint8* PerceptionObstacles::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.perception.PerceptionObstacles) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .apollo.perception.PerceptionObstacle perception_obstacle = 1; for (unsigned int i = 0, n = this->perception_obstacle_size(); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, this->perception_obstacle(i), deterministic, target); } cached_has_bits = _has_bits_[0]; // optional .apollo.common.Header header = 2; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 2, *this->header_, deterministic, target); } // optional .apollo.common.ErrorCode error_code = 3 [default = OK]; if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 3, this->error_code(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.perception.PerceptionObstacles) return target; } size_t PerceptionObstacles::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:apollo.perception.PerceptionObstacles) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } // repeated .apollo.perception.PerceptionObstacle perception_obstacle = 1; { unsigned int count = this->perception_obstacle_size(); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->perception_obstacle(i)); } } if (_has_bits_[0 / 32] & 3u) { // optional .apollo.common.Header header = 2; if (has_header()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->header_); } // optional .apollo.common.ErrorCode error_code = 3 [default = OK]; if (has_error_code()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->error_code()); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void PerceptionObstacles::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.perception.PerceptionObstacles) GOOGLE_DCHECK_NE(&from, this); const PerceptionObstacles* source = ::google::protobuf::internal::DynamicCastToGenerated<const PerceptionObstacles>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.perception.PerceptionObstacles) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.perception.PerceptionObstacles) MergeFrom(*source); } } void PerceptionObstacles::MergeFrom(const PerceptionObstacles& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.perception.PerceptionObstacles) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; perception_obstacle_.MergeFrom(from.perception_obstacle_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { mutable_header()->::apollo::common::Header::MergeFrom(from.header()); } if (cached_has_bits & 0x00000002u) { error_code_ = from.error_code_; } _has_bits_[0] |= cached_has_bits; } } void PerceptionObstacles::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.perception.PerceptionObstacles) if (&from == this) return; Clear(); MergeFrom(from); } void PerceptionObstacles::CopyFrom(const PerceptionObstacles& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.perception.PerceptionObstacles) if (&from == this) return; Clear(); MergeFrom(from); } bool PerceptionObstacles::IsInitialized() const { return true; } void PerceptionObstacles::Swap(PerceptionObstacles* other) { if (other == this) return; InternalSwap(other); } void PerceptionObstacles::InternalSwap(PerceptionObstacles* other) { perception_obstacle_.InternalSwap(&other->perception_obstacle_); std::swap(header_, other->header_); std::swap(error_code_, other->error_code_); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata PerceptionObstacles::GetMetadata() const { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::file_level_metadata[kIndexInFileMessages]; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // PerceptionObstacles // repeated .apollo.perception.PerceptionObstacle perception_obstacle = 1; int PerceptionObstacles::perception_obstacle_size() const { return perception_obstacle_.size(); } void PerceptionObstacles::clear_perception_obstacle() { perception_obstacle_.Clear(); } const ::apollo::perception::PerceptionObstacle& PerceptionObstacles::perception_obstacle(int index) const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacles.perception_obstacle) return perception_obstacle_.Get(index); } ::apollo::perception::PerceptionObstacle* PerceptionObstacles::mutable_perception_obstacle(int index) { // @@protoc_insertion_point(field_mutable:apollo.perception.PerceptionObstacles.perception_obstacle) return perception_obstacle_.Mutable(index); } ::apollo::perception::PerceptionObstacle* PerceptionObstacles::add_perception_obstacle() { // @@protoc_insertion_point(field_add:apollo.perception.PerceptionObstacles.perception_obstacle) return perception_obstacle_.Add(); } ::google::protobuf::RepeatedPtrField< ::apollo::perception::PerceptionObstacle >* PerceptionObstacles::mutable_perception_obstacle() { // @@protoc_insertion_point(field_mutable_list:apollo.perception.PerceptionObstacles.perception_obstacle) return &perception_obstacle_; } const ::google::protobuf::RepeatedPtrField< ::apollo::perception::PerceptionObstacle >& PerceptionObstacles::perception_obstacle() const { // @@protoc_insertion_point(field_list:apollo.perception.PerceptionObstacles.perception_obstacle) return perception_obstacle_; } // optional .apollo.common.Header header = 2; bool PerceptionObstacles::has_header() const { return (_has_bits_[0] & 0x00000001u) != 0; } void PerceptionObstacles::set_has_header() { _has_bits_[0] |= 0x00000001u; } void PerceptionObstacles::clear_has_header() { _has_bits_[0] &= ~0x00000001u; } void PerceptionObstacles::clear_header() { if (header_ != NULL) header_->::apollo::common::Header::Clear(); clear_has_header(); } const ::apollo::common::Header& PerceptionObstacles::header() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacles.header) return header_ != NULL ? *header_ : *::apollo::common::Header::internal_default_instance(); } ::apollo::common::Header* PerceptionObstacles::mutable_header() { set_has_header(); if (header_ == NULL) { header_ = new ::apollo::common::Header; } // @@protoc_insertion_point(field_mutable:apollo.perception.PerceptionObstacles.header) return header_; } ::apollo::common::Header* PerceptionObstacles::release_header() { // @@protoc_insertion_point(field_release:apollo.perception.PerceptionObstacles.header) clear_has_header(); ::apollo::common::Header* temp = header_; header_ = NULL; return temp; } void PerceptionObstacles::set_allocated_header(::apollo::common::Header* header) { delete header_; header_ = header; if (header) { set_has_header(); } else { clear_has_header(); } // @@protoc_insertion_point(field_set_allocated:apollo.perception.PerceptionObstacles.header) } // optional .apollo.common.ErrorCode error_code = 3 [default = OK]; bool PerceptionObstacles::has_error_code() const { return (_has_bits_[0] & 0x00000002u) != 0; } void PerceptionObstacles::set_has_error_code() { _has_bits_[0] |= 0x00000002u; } void PerceptionObstacles::clear_has_error_code() { _has_bits_[0] &= ~0x00000002u; } void PerceptionObstacles::clear_error_code() { error_code_ = 0; clear_has_error_code(); } ::apollo::common::ErrorCode PerceptionObstacles::error_code() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacles.error_code) return static_cast< ::apollo::common::ErrorCode >(error_code_); } void PerceptionObstacles::set_error_code(::apollo::common::ErrorCode value) { assert(::apollo::common::ErrorCode_IsValid(value)); set_has_error_code(); error_code_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacles.error_code) } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // @@protoc_insertion_point(namespace_scope) } // namespace perception } // namespace apollo // @@protoc_insertion_point(global_scope)
35.866261
144
0.714104
Kurinkitos
aac3c40b4291ce31a7b535e9d7db75c022a1f246
829
cpp
C++
ekf/src_ta/pose.cpp
KerryWu16/src
bed672dc1732cd6af1752bb54ab0abde015bb93a
[ "MIT" ]
2
2017-12-17T11:07:56.000Z
2021-08-19T09:35:11.000Z
ekf/src_working/pose.cpp
KerryWu16/src
bed672dc1732cd6af1752bb54ab0abde015bb93a
[ "MIT" ]
null
null
null
ekf/src_working/pose.cpp
KerryWu16/src
bed672dc1732cd6af1752bb54ab0abde015bb93a
[ "MIT" ]
1
2021-08-19T07:41:48.000Z
2021-08-19T07:41:48.000Z
#include "pose.h" Eigen::Vector3d R_to_rpy(const Eigen::Matrix3d& R) { Eigen::Vector3d rpy; double r = asin(R(2,1)); double p = atan2(-R(2,0)/cos(r), R(2,2)/cos(r)); double y = atan2(-R(0,1)/cos(r), R(1,1)/cos(r)); rpy(0) = r; rpy(1) = p; rpy(2) = y; return rpy; } Eigen::Matrix3d rpy_to_R(const Eigen::Vector3d& rpy) { Eigen::MatrixXd R = Eigen::MatrixXd::Zero(3,3); double r = rpy(0), p = rpy(1), y = rpy(2); R(0,0) = cos(y)*cos(p) - sin(r)*sin(p)*sin(y); R(0,1) = -cos(r)*sin(y); R(0,2) = cos(y)*sin(p) + cos(p)*sin(r)*sin(y); R(1,0) = cos(p)*sin(y) + cos(y)*sin(r)*sin(p); R(1,1) = cos(r)*cos(y); R(1,2) = sin(y)*sin(p) - cos(y)*cos(p)*sin(r); R(2,0) = -cos(r)*sin(p); R(2,1) = sin(r); R(2,2) = cos(r)*cos(p); return R; }
25.121212
53
0.487334
KerryWu16
aac65162c20d2d4fb1a97975af9831c12d95c34c
1,589
cpp
C++
leetcode.com/0241 Different Ways to Add Parentheses/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/0241 Different Ways to Add Parentheses/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/0241 Different Ways to Add Parentheses/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <iostream> #include <vector> using namespace std; class Solution { private: int n; vector<int> nums; vector<char> ops; vector<int> helper(int l, int r) { vector<int> result; if (l == r) return {nums[l]}; for (int i = l; i < r; ++i) { auto left = helper(l, i); auto right = helper(i+1, r); for (int x: left) { for (int y: right) { switch (ops[i]) { case '+': result.push_back(x+y); break; case '-': result.push_back(x-y); break; case '*': result.push_back(x*y); break; } } } } return result; } public: vector<int> diffWaysToCompute(string input) { n = input.length(); const char *input_cstr = input.c_str(); bool get_num = true; for (int i = 0; i < n; get_num = !get_num) { if (get_num) { int tmp; int len; sscanf(input_cstr+i, "%d%n", &tmp, &len); i += len; nums.push_back(tmp); } else { ops.push_back(input_cstr[i++]); } } n = nums.size(); return helper(0, n-1); } }; int main(int argc, char const *argv[]) { Solution s; s.diffWaysToCompute("2-1-1"); return 0; }
25.222222
57
0.390183
sky-bro
aac7c0f1c1a7c9f87d611024111af8f0435cca3c
10,534
cc
C++
audio/audio_receive_stream_unittest.cc
bofeng-song/webrtc
cd06ce5490635ef5ef953b17eabb6e833eed5b76
[ "DOC", "BSD-3-Clause" ]
null
null
null
audio/audio_receive_stream_unittest.cc
bofeng-song/webrtc
cd06ce5490635ef5ef953b17eabb6e833eed5b76
[ "DOC", "BSD-3-Clause" ]
null
null
null
audio/audio_receive_stream_unittest.cc
bofeng-song/webrtc
cd06ce5490635ef5ef953b17eabb6e833eed5b76
[ "DOC", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/audio/audio_receive_stream.h" #include "webrtc/audio/conversion.h" #include "webrtc/modules/remote_bitrate_estimator/include/mock/mock_remote_bitrate_estimator.h" #include "webrtc/modules/rtp_rtcp/source/byte_io.h" #include "webrtc/test/mock_voe_channel_proxy.h" #include "webrtc/test/mock_voice_engine.h" namespace webrtc { namespace test { namespace { using testing::_; using testing::Return; AudioDecodingCallStats MakeAudioDecodeStatsForTest() { AudioDecodingCallStats audio_decode_stats; audio_decode_stats.calls_to_silence_generator = 234; audio_decode_stats.calls_to_neteq = 567; audio_decode_stats.decoded_normal = 890; audio_decode_stats.decoded_plc = 123; audio_decode_stats.decoded_cng = 456; audio_decode_stats.decoded_plc_cng = 789; return audio_decode_stats; } const int kChannelId = 2; const uint32_t kRemoteSsrc = 1234; const uint32_t kLocalSsrc = 5678; const size_t kAbsoluteSendTimeLength = 4; const int kAbsSendTimeId = 2; const int kAudioLevelId = 3; const int kJitterBufferDelay = -7; const int kPlayoutBufferDelay = 302; const unsigned int kSpeechOutputLevel = 99; const CallStatistics kCallStats = { 345, 678, 901, 234, -12, 3456, 7890, 567, 890, 123}; const CodecInst kCodecInst = { 123, "codec_name_recv", 96000, -187, -198, -103}; const NetworkStatistics kNetworkStats = { 123, 456, false, 0, 0, 789, 12, 345, 678, 901, -1, -1, -1, -1, -1, 0}; const AudioDecodingCallStats kAudioDecodeStats = MakeAudioDecodeStatsForTest(); struct ConfigHelper { ConfigHelper() { using testing::Invoke; EXPECT_CALL(voice_engine_, RegisterVoiceEngineObserver(_)).WillOnce(Return(0)); EXPECT_CALL(voice_engine_, DeRegisterVoiceEngineObserver()).WillOnce(Return(0)); AudioState::Config config; config.voice_engine = &voice_engine_; audio_state_ = AudioState::Create(config); EXPECT_CALL(voice_engine_, ChannelProxyFactory(kChannelId)) .WillOnce(Invoke([this](int channel_id) { EXPECT_FALSE(channel_proxy_); channel_proxy_ = new testing::StrictMock<MockVoEChannelProxy>(); EXPECT_CALL(*channel_proxy_, SetLocalSSRC(kLocalSsrc)).Times(1); return channel_proxy_; })); EXPECT_CALL(voice_engine_, SetReceiveAbsoluteSenderTimeStatus(kChannelId, true, kAbsSendTimeId)) .WillOnce(Return(0)); EXPECT_CALL(voice_engine_, SetReceiveAudioLevelIndicationStatus(kChannelId, true, kAudioLevelId)) .WillOnce(Return(0)); stream_config_.voe_channel_id = kChannelId; stream_config_.rtp.local_ssrc = kLocalSsrc; stream_config_.rtp.remote_ssrc = kRemoteSsrc; stream_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kAbsSendTime, kAbsSendTimeId)); stream_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kAudioLevel, kAudioLevelId)); } MockRemoteBitrateEstimator* remote_bitrate_estimator() { return &remote_bitrate_estimator_; } AudioReceiveStream::Config& config() { return stream_config_; } rtc::scoped_refptr<AudioState> audio_state() { return audio_state_; } MockVoiceEngine& voice_engine() { return voice_engine_; } void SetupMockForGetStats() { using testing::DoAll; using testing::SetArgPointee; using testing::SetArgReferee; EXPECT_CALL(voice_engine_, GetRTCPStatistics(kChannelId, _)) .WillOnce(DoAll(SetArgReferee<1>(kCallStats), Return(0))); EXPECT_CALL(voice_engine_, GetRecCodec(kChannelId, _)) .WillOnce(DoAll(SetArgReferee<1>(kCodecInst), Return(0))); EXPECT_CALL(voice_engine_, GetDelayEstimate(kChannelId, _, _)) .WillOnce(DoAll(SetArgPointee<1>(kJitterBufferDelay), SetArgPointee<2>(kPlayoutBufferDelay), Return(0))); EXPECT_CALL(voice_engine_, GetSpeechOutputLevelFullRange(kChannelId, _)).WillOnce( DoAll(SetArgReferee<1>(kSpeechOutputLevel), Return(0))); EXPECT_CALL(voice_engine_, GetNetworkStatistics(kChannelId, _)) .WillOnce(DoAll(SetArgReferee<1>(kNetworkStats), Return(0))); EXPECT_CALL(voice_engine_, GetDecodingCallStatistics(kChannelId, _)) .WillOnce(DoAll(SetArgPointee<1>(kAudioDecodeStats), Return(0))); } private: MockRemoteBitrateEstimator remote_bitrate_estimator_; testing::StrictMock<MockVoiceEngine> voice_engine_; rtc::scoped_refptr<AudioState> audio_state_; AudioReceiveStream::Config stream_config_; testing::StrictMock<MockVoEChannelProxy>* channel_proxy_ = nullptr; }; void BuildAbsoluteSendTimeExtension(uint8_t* buffer, int id, uint32_t abs_send_time) { const size_t kRtpOneByteHeaderLength = 4; const uint16_t kRtpOneByteHeaderExtensionId = 0xBEDE; ByteWriter<uint16_t>::WriteBigEndian(buffer, kRtpOneByteHeaderExtensionId); const uint32_t kPosLength = 2; ByteWriter<uint16_t>::WriteBigEndian(buffer + kPosLength, kAbsoluteSendTimeLength / 4); const uint8_t kLengthOfData = 3; buffer[kRtpOneByteHeaderLength] = (id << 4) + (kLengthOfData - 1); ByteWriter<uint32_t, kLengthOfData>::WriteBigEndian( buffer + kRtpOneByteHeaderLength + 1, abs_send_time); } size_t CreateRtpHeaderWithAbsSendTime(uint8_t* header, int extension_id, uint32_t abs_send_time) { header[0] = 0x80; // Version 2. header[0] |= 0x10; // Set extension bit. header[1] = 100; // Payload type. header[1] |= 0x80; // Marker bit is set. ByteWriter<uint16_t>::WriteBigEndian(header + 2, 0x1234); // Sequence number. ByteWriter<uint32_t>::WriteBigEndian(header + 4, 0x5678); // Timestamp. ByteWriter<uint32_t>::WriteBigEndian(header + 8, 0x4321); // SSRC. int32_t rtp_header_length = webrtc::kRtpHeaderSize; BuildAbsoluteSendTimeExtension(header + rtp_header_length, extension_id, abs_send_time); rtp_header_length += kAbsoluteSendTimeLength; return rtp_header_length; } } // namespace TEST(AudioReceiveStreamTest, ConfigToString) { AudioReceiveStream::Config config; config.rtp.remote_ssrc = kRemoteSsrc; config.rtp.local_ssrc = kLocalSsrc; config.rtp.extensions.push_back( RtpExtension(RtpExtension::kAbsSendTime, kAbsSendTimeId)); config.voe_channel_id = kChannelId; config.combined_audio_video_bwe = true; EXPECT_EQ( "{rtp: {remote_ssrc: 1234, local_ssrc: 5678, extensions: [{name: " "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time, id: 2}]}, " "receive_transport: nullptr, rtcp_send_transport: nullptr, " "voe_channel_id: 2, combined_audio_video_bwe: true}", config.ToString()); } TEST(AudioReceiveStreamTest, ConstructDestruct) { ConfigHelper helper; internal::AudioReceiveStream recv_stream( helper.remote_bitrate_estimator(), helper.config(), helper.audio_state()); } TEST(AudioReceiveStreamTest, AudioPacketUpdatesBweWithTimestamp) { ConfigHelper helper; helper.config().combined_audio_video_bwe = true; internal::AudioReceiveStream recv_stream( helper.remote_bitrate_estimator(), helper.config(), helper.audio_state()); uint8_t rtp_packet[30]; const int kAbsSendTimeValue = 1234; CreateRtpHeaderWithAbsSendTime(rtp_packet, kAbsSendTimeId, kAbsSendTimeValue); PacketTime packet_time(5678000, 0); const size_t kExpectedHeaderLength = 20; EXPECT_CALL(*helper.remote_bitrate_estimator(), IncomingPacket(packet_time.timestamp / 1000, sizeof(rtp_packet) - kExpectedHeaderLength, testing::_, false)) .Times(1); EXPECT_TRUE( recv_stream.DeliverRtp(rtp_packet, sizeof(rtp_packet), packet_time)); } TEST(AudioReceiveStreamTest, GetStats) { ConfigHelper helper; internal::AudioReceiveStream recv_stream( helper.remote_bitrate_estimator(), helper.config(), helper.audio_state()); helper.SetupMockForGetStats(); AudioReceiveStream::Stats stats = recv_stream.GetStats(); EXPECT_EQ(kRemoteSsrc, stats.remote_ssrc); EXPECT_EQ(static_cast<int64_t>(kCallStats.bytesReceived), stats.bytes_rcvd); EXPECT_EQ(static_cast<uint32_t>(kCallStats.packetsReceived), stats.packets_rcvd); EXPECT_EQ(kCallStats.cumulativeLost, stats.packets_lost); EXPECT_EQ(Q8ToFloat(kCallStats.fractionLost), stats.fraction_lost); EXPECT_EQ(std::string(kCodecInst.plname), stats.codec_name); EXPECT_EQ(kCallStats.extendedMax, stats.ext_seqnum); EXPECT_EQ(kCallStats.jitterSamples / (kCodecInst.plfreq / 1000), stats.jitter_ms); EXPECT_EQ(kNetworkStats.currentBufferSize, stats.jitter_buffer_ms); EXPECT_EQ(kNetworkStats.preferredBufferSize, stats.jitter_buffer_preferred_ms); EXPECT_EQ(static_cast<uint32_t>(kJitterBufferDelay + kPlayoutBufferDelay), stats.delay_estimate_ms); EXPECT_EQ(static_cast<int32_t>(kSpeechOutputLevel), stats.audio_level); EXPECT_EQ(Q14ToFloat(kNetworkStats.currentExpandRate), stats.expand_rate); EXPECT_EQ(Q14ToFloat(kNetworkStats.currentSpeechExpandRate), stats.speech_expand_rate); EXPECT_EQ(Q14ToFloat(kNetworkStats.currentSecondaryDecodedRate), stats.secondary_decoded_rate); EXPECT_EQ(Q14ToFloat(kNetworkStats.currentAccelerateRate), stats.accelerate_rate); EXPECT_EQ(Q14ToFloat(kNetworkStats.currentPreemptiveRate), stats.preemptive_expand_rate); EXPECT_EQ(kAudioDecodeStats.calls_to_silence_generator, stats.decoding_calls_to_silence_generator); EXPECT_EQ(kAudioDecodeStats.calls_to_neteq, stats.decoding_calls_to_neteq); EXPECT_EQ(kAudioDecodeStats.decoded_normal, stats.decoding_normal); EXPECT_EQ(kAudioDecodeStats.decoded_plc, stats.decoding_plc); EXPECT_EQ(kAudioDecodeStats.decoded_cng, stats.decoding_cng); EXPECT_EQ(kAudioDecodeStats.decoded_plc_cng, stats.decoding_plc_cng); EXPECT_EQ(kCallStats.capture_start_ntp_time_ms_, stats.capture_start_ntp_time_ms); } } // namespace test } // namespace webrtc
42.995918
95
0.738466
bofeng-song
aaca33354da8f269498e19711f07a70bb93fad0d
1,262
cpp
C++
pass_security.cpp
ferhatgec/passplusplus
5032c87074420d1903276aca9ae92ab387a0317c
[ "MIT" ]
3
2020-11-22T05:00:41.000Z
2021-02-18T15:40:19.000Z
pass_security.cpp
FerhatGec/passplusplus
5032c87074420d1903276aca9ae92ab387a0317c
[ "MIT" ]
null
null
null
pass_security.cpp
FerhatGec/passplusplus
5032c87074420d1903276aca9ae92ab387a0317c
[ "MIT" ]
null
null
null
/*# MIT License # # Copyright (c) 2020 Ferhat Geçdoğan All Rights Reserved. # Distributed under the terms of the MIT License. #*/ #include <iostream> #include "PassQuality.hpp" int main() { std::string str; std::cout << "Enter input string." << "\n"; std::cin >> str; int quality = PassQuality::PassSecurity(str); if(quality == 1) { std::cout << "Found! You should change this password."; } else if(quality == 2) { std::cout << "PassList not found."; } else { std::cout << "Not found, yey!.\nNow, Running PassSecurity2."; quality = PassQuality::PassSecurity2(str); if(quality == 1) { std::cout << "Found! You should change this password."; } else if(quality == 2) { std::cout << "PassList2 not found."; } else { std::cout << "\nNow, Running PassSecurity2.\n"; quality = PassQuality::PassSecurity3(str); if(quality == 1) { std::cout << "Found! You should change this password."; } else if(quality == 2) { std::cout << "PassList3 not found."; } else { std::cout << "Not found, yey!\nYour password not found from all three passlist."; } } } std::cout << "\n"; return 0; }
30.780488
90
0.559429
ferhatgec
aacd318d0a8fa37e9aed416b4db6dbdc9e2c25cc
6,682
cpp
C++
iris-cpp/test/iris/gen/GraphGeneratorTests.cpp
wbknez/iris
ac6f8ca57cec88a24bdf22eca42e2c77a53f4cd0
[ "Apache-2.0" ]
null
null
null
iris-cpp/test/iris/gen/GraphGeneratorTests.cpp
wbknez/iris
ac6f8ca57cec88a24bdf22eca42e2c77a53f4cd0
[ "Apache-2.0" ]
null
null
null
iris-cpp/test/iris/gen/GraphGeneratorTests.cpp
wbknez/iris
ac6f8ca57cec88a24bdf22eca42e2c77a53f4cd0
[ "Apache-2.0" ]
null
null
null
#include <catch.hpp> #include <algorithm> #include <random> #include <vector> #include "iris/Agent.hpp" #include "iris/Types.hpp" #include "iris/gen/GraphGenerator.hpp" #include "iris/io/reader/CensusReader.hpp" void testForDuplicates(const iris::Agent::Network& network) { if(network.size() == 0) { return; } for(iris::Agent::Network::size_type i = 0; i < network.size() - 1; i++) { CHECK(network[i] != network[i + 1]); } } void testForLoops(const iris::AgentID& id, const iris::Agent::Network& network) { for(iris::Agent::Network::size_type i = 0; i < network.size(); i++) { CHECK(network[i] != id); } } TEST_CASE("Verify family size selection works correctly.") { SECTION("Verify singular selection.") { using namespace iris::gen; const auto cdf = CDF{1.0}; const auto result0 = chooseFamilySize(0.2, cdf); const auto result1 = chooseFamilySize(0.8, cdf); CHECK(result0 == 0); CHECK(result1 == 0); } SECTION("Verify multiple selection.") { using namespace iris::gen; const auto cdf = CDF{0.2, 0.5, 0.7, 1.0}; const auto result0 = chooseFamilySize(0.3, cdf); const auto result1 = chooseFamilySize(0.7, cdf); CHECK(result0 == 1); CHECK(result1 == 2); } SECTION("Verify throws when out of bounds.") { using namespace iris::gen; const auto cdf = CDF{0.2, 0.5, 0.7, 1.0}; CHECK_THROWS(chooseFamilySize(1.1, cdf)); } } TEST_CASE("Verify CDF creation works as expected.") { SECTION("Verify construction from census data.") { using namespace iris::gen; using namespace iris::io; const auto census = CensusData{0.2, 0.1, 0.4, 0.2, 0.1}; const auto expected = CDF{0.2, 0.3, 0.7, 0.9, 1.0}; const auto result = createCDF(census); REQUIRE(expected.size() == result.size()); SECTION("Verify the results and expected are equal within epsilon.") { for(CDF::size_type i = 0; i < result.size(); i++) { CHECK(result[i] == Approx(expected[i])); } } } } TEST_CASE("Wire a family unit together.") { SECTION("Verify that a single unit in a family is wired.") { using namespace iris; using namespace iris::gen; Agent agent; const auto familyUnit = FamilyUnit{0, 4}; agent.setUId(0); wireFamilyUnit(agent, familyUnit); const auto expected = Agent::Network{1, 2, 3}; const auto result = agent.getNetwork(); CHECK(expected == result); } SECTION("Verify that all units in a family are wired.") { using namespace iris; using namespace iris::gen; Agent agents[5]; const auto familyUnit = FamilyUnit{0, 5}; // Set up the agent family, first. for(auto i = 0; i < 5; i++) { agents[i].setUId(i); } for(auto j = 0; j < 5; j++) { // Now wire them up. wireFamilyUnit(agents[j], familyUnit); // And check the results. auto expected = Agent::Network(5); std::iota(expected.begin(), expected.end(), 0); expected.erase(std::find(expected.begin(), expected.end(), j)); const auto result = agents[j].getNetwork(); CHECK(expected == result); SECTION("Verify there are no duplicates.") { testForDuplicates(result); } SECTION("Verify there are no loops.") { testForLoops(j, result); } } } } TEST_CASE("Verify out-group connection creation is correct and unique.") { // Create a small "sample set" of agents to use. // For this particular exercise, we are going to make a "small world"; // that is, everyone will be connected to everyone else. // // This will allow us to verify that both the sample space search // (finally) works correctly as well as the algorithm's denial of // repeat selections. // // This is divided into two sections to test varying family sizes. using namespace iris; using namespace iris::gen; using namespace iris::types; using namespace std; random_device seed; mersenne_twister random(seed()); Agent* agents = new Agent[20]; for(auto i = 0; i < 20; i++) { agents[i].setFamilySize(1); agents[i].setUId(i); } SECTION("Verify out-group connections work for singular families only.") { const uint32 outConnections = 19; for(auto j = 0; j < 20; j++) { wireOutGroup(j, agents, 20, outConnections, 1.0, 1.0, random); } SECTION("Verify that there are no duplicates or loops.") { for(auto k = 0; k < 20; k++) { auto network = agents[k].getNetwork(); CHECK(network.size() == 19); testForDuplicates(network); testForLoops(k, network); } } } SECTION("Verify no out-group connects results in zero-size networks.") { const uint32 outConnections = (uint32)0; for(auto j = 0; j < 20; j++) { wireOutGroup(j, agents, 20, outConnections, 1.0, 1.0, random); } SECTION("Verify that there are no duplicates or loops.") { for(auto k = 0; k < 20; k++) { auto network = agents[k].getNetwork(); CHECK(network.size() == 0); testForDuplicates(network); testForLoops(k, network); } } } SECTION("Verify that out connection amounts that result in potential" " networks larger than the total number of agents in the simulation" " are handled correctly.") { const uint32 outConnections = 1000000; for(auto j = 0; j < 20; j++) { wireOutGroup(j, agents, 20, outConnections, 1.0, 1.0, random); } SECTION("Verify that there are no duplicates or loops.") { for(auto k = 0; k < 20; k++) { auto network = agents[k].getNetwork(); CHECK(network.size() == 19); testForDuplicates(network); testForLoops(k, network); } } } delete[] agents; }
26.307087
80
0.533673
wbknez
aacf32b5da67d6dee429224824258952fb498764
1,804
cpp
C++
linked-list/intersection-point.cpp
Strider-7/code
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
[ "MIT" ]
null
null
null
linked-list/intersection-point.cpp
Strider-7/code
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
[ "MIT" ]
null
null
null
linked-list/intersection-point.cpp
Strider-7/code
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <unordered_set> using namespace std; struct Node { int data; Node *next; } *head = nullptr, *last = nullptr; int count(Node *node) { int c = 0; while (node) { c++; node = node->next; } return c; } int intersection(Node *l1, Node *l2) { unordered_set<Node *> s; while (l2) { s.insert(l2); l2 = l2->next; } while (l1) { if (s.find(l1) != s.end()) return l1->data; l1 = l1->next; } return 0; } int intersection2(Node *l1, Node *l2) { int c1 = count(l1); int c2 = count(l2); Node *p = c1 > c2 ? l1 : l2; Node *q = (p == l1) ? l2 : l1; for (int i = 0; i < abs(c1 - c2); i++) p = p->next; while (p && q) { if (p == q) return p->data; p = p->next; q = q->next; } return -1; } Node *getIntersectionNode(Node *headA, Node *headB) { Node *p1 = headA; Node *p2 = headB; if (p1 == NULL || p2 == NULL) return NULL; while (p1 != NULL && p2 != NULL && p1 != p2) { p1 = p1->next; p2 = p2->next; // // Any time they collide or reach end together without colliding // then return any one of the pointers. // if (p1 == p2) return p1; // // If one of them reaches the end earlier then reuse it // by moving it to the beginning of other list. // Once both of them go through reassigning, // they will be equidistant from the collision point. // if (p1 == NULL) p1 = headB; if (p2 == NULL) p2 = headA; } return p1; }
20.5
74
0.459534
Strider-7
aacfacef14c504311ccd082fe29853eeb1a38e90
7,420
cpp
C++
projects/test-suite/SingleSource/Benchmarks/Misc-C++/stepanov_container.cpp
nettrino/IntFlow
0400aef5da2c154268d8b020e393c950435395b3
[ "Unlicense" ]
16
2015-09-08T08:49:11.000Z
2019-07-20T14:46:20.000Z
projects/test-suite/SingleSource/Benchmarks/Misc-C++/stepanov_container.cpp
nettrino/IntFlow
0400aef5da2c154268d8b020e393c950435395b3
[ "Unlicense" ]
1
2019-02-10T08:27:48.000Z
2019-02-10T08:27:48.000Z
projects/test-suite/SingleSource/Benchmarks/Misc-C++/stepanov_container.cpp
nettrino/IntFlow
0400aef5da2c154268d8b020e393c950435395b3
[ "Unlicense" ]
7
2016-05-26T17:31:46.000Z
2020-11-04T06:39:23.000Z
/* Standard Container Benchmark Version 0.9, May 23, 2003 The primary purpose of this benchmark is to show how different standard containers are in terms of performance. We have observed that programmers often use sets, multisets, deques in the situations where sorted vectors are the optimal solutions. Similarly, programmers often choose lists simply because they do a few insertions and deletions without knowing that vectors are more efficient at that for small containers. Frequently, of course, performance does not matter, but it is important that programmers are aware of the consequences of their choices. We are not saying that only vectors should be used, there are cases when one really needs a more complicated data structure, but one needs to understand the price for additional functionality. The secondary purpose of the benchmark is to encourage compiler and library vendors to keep improving performance. For example, it is not acceptable that some compilers give you a sizable penalty for using vector iterators instead of pointer. It is also quite clear that performance of other standard containers could be improved. The benchmark is doing the same task 7 times using different data structures: array, vector (using a pointer as iterator), vector (using the defailt cector iterator), list, deque, set and multiset. The task is to remove duplicates from a sequence of doubles. This is a simple test, but it illustrates the performance of containers. It is clear that the benchmark needs to be eventually extended to slists and even to hash-sets and hash-maps, but we decided that at present it should work only with the standard containers. As the standard grows, so can the benchmark. The additional benefit of not including hash based containers is that now all the test have identical asymptotic complexity and, even more importantly, do almost the same number of comparisons. The difference is only in data structure overhead and cache behavior. The number of times that a given test is run inversly proportional to NlogN where N is the size of the sequence. This allows one to see how containers of different size behave. The instructive values used for the benchmark are: 10, 100, 1000, 10000, 100000, 1000000. The time taken for a run of the benchmark depends on the machine used, the compiler used, the compiler and optimizer settings used, as well as the standard library. Please note that the time taken could be several minutes - and much more if you use a slow debug mode. The output is a table where columns are separated by tabs and rows by newlines. This is barely ok for a human reader, but ideal for feeding into a program, such as a spreadsheet for display or analysis. If you want to add your own test of a container, add the name of your container to the "header string, write a test function like the existing ones, e.g. vector_test, and add a call of "run" for your test in "run_tests". Alex Stepanov stepa...@adobe.com Bjarne Stroustrup b...@cs.tamu.edu */ #include <stddef.h> // some older implementations lack <cstddef> #include <time.h> #include <math.h> #include <stdlib.h> #include <vector> #include <algorithm> #include <list> #include <deque> #include <set> #include <iostream> #include <iomanip> typedef double element_t; using namespace std; vector<double> result_times; // results are puched into this vector typedef void(*Test)(element_t*, element_t*, int); void run(Test f, element_t* first, element_t* last, int number_of_times) { while (number_of_times-- > 0) f(first,last,number_of_times); } void array_test(element_t* first, element_t* last, int number_of_times) { element_t* array = new element_t[last - first]; copy(first, last, array); sort(array, array + (last - first)); unique(array, array + (last - first)); delete [] array; } void vector_pointer_test(element_t* first, element_t* last, int number_of_times) { vector<element_t> container(first, last); // &*container.begin() gets us a pointer to the first element sort(&*container.begin(), &*container.end()); unique(&*container.begin(), &*container.end()); } void vector_iterator_test(element_t* first, element_t* last, int number_of_times) { vector<element_t> container(first, last); sort(container.begin(), container.end()); unique(container.begin(), container.end()); } void deque_test(element_t* first, element_t* last, int number_of_times) { // deque<element_t> container(first, last); CANNOT BE USED BECAUSE OF MVC++ 6 deque<element_t> container(size_t(last - first), 0.0); copy(first, last, container.begin()); sort(container.begin(), container.end()); unique(container.begin(), container.end()); } void list_test(element_t* first, element_t* last, int number_of_times) { list<element_t> container(first, last); container.sort(); container.unique(); } void set_test(element_t* first, element_t* last, int number_of_times) { set<element_t> container(first, last); } void multiset_test(element_t* first, element_t* last, int number_of_times) { multiset<element_t> container(first, last); typedef multiset<element_t>::iterator iterator; { iterator first = container.begin(); iterator last = container.end(); while (first != last) { iterator next = first; if (++next == last) break; if (*first == *next) container.erase(next); else ++first; } } } void initialize(element_t* first, element_t* last) { element_t value = 0.0; while (first != last) { *first++ = value; value += 1.; } } double logtwo(double x) { return log(x)/log((double) 2.0); } const int largest_size = 1000000; int number_of_tests(int size) { double n = size; double largest_n = largest_size; return int(floor((largest_n * logtwo(largest_n)) / (n * logtwo(n)))); } void run_tests(int size) { const int n = number_of_tests(size); const size_t length = 2*size; result_times.clear(); // make a random test set of the chosen size: vector<element_t> buf(length); element_t* buffer = &buf[0]; element_t* buffer_end = &buf[length]; initialize(buffer, buffer + size); // elements initialize(buffer + size, buffer_end); // duplicate elements random_shuffle(buffer, buffer_end); // test the containers: run(array_test, buffer, buffer_end, n); run(vector_pointer_test, buffer, buffer_end, n); run(vector_iterator_test, buffer, buffer_end, n); run(deque_test, buffer, buffer_end, n); run(list_test, buffer, buffer_end, n); run(set_test, buffer, buffer_end, n); run(multiset_test, buffer, buffer_end, n); } int main() { const int sizes [] = { 100000 }; const int n = sizeof(sizes)/sizeof(int); for (int i = 0; i < n; ++i) run_tests(sizes[i]); }
28.648649
92
0.671024
nettrino
aad41d82e808463ab2cf19091b0c0715f0c8bccd
153
cpp
C++
ace/XML_Utils/XML_Typedefs.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
Oem/ACE/ACE_wrappers/ace/XML_Utils/XML_Typedefs.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
ace/XML_Utils/XML_Typedefs.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// $Id: XML_Typedefs.cpp 95760 2012-05-15 13:46:19Z msmit $ #include "XML_Typedefs.h" namespace XML { XML_Typedef::HELPER XML_Typedef::XML_HELPER; }
17
59
0.732026
cflowe
aad49f67357d5126434673624b9d9cd0038489f5
16,642
cxx
C++
main/dbaccess/source/core/api/column.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/dbaccess/source/core/api/column.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/dbaccess/source/core/api/column.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #include "ContainerMediator.hxx" #include "apitools.hxx" #include "column.hxx" #include "core_resource.hrc" #include "core_resource.hxx" #include "dbastrings.hrc" #include "sdbcoretools.hxx" #include <com/sun/star/lang/DisposedException.hpp> #include <com/sun/star/sdbc/ColumnValue.hpp> #include <com/sun/star/sdbc/DataType.hpp> #include <comphelper/basicio.hxx> #include <comphelper/enumhelper.hxx> #include <comphelper/extract.hxx> #include <comphelper/property.hxx> #include <comphelper/seqstream.hxx> #include <comphelper/sequence.hxx> #include <comphelper/types.hxx> #include <connectivity/TTableHelper.hxx> #include <connectivity/dbexception.hxx> #include <connectivity/dbtools.hxx> #include <cppuhelper/typeprovider.hxx> #include <osl/diagnose.h> #include <tools/debug.hxx> #include <algorithm> using namespace dbaccess; using namespace connectivity; using namespace connectivity; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::awt; using namespace ::com::sun::star::io; using namespace ::com::sun::star::container; using namespace ::com::sun::star::util; using namespace ::osl; using namespace ::comphelper; using namespace ::cppu; DBG_NAME(OColumn) //============================================================ //= OColumn //============================================================ //-------------------------------------------------------------------------- OColumn::OColumn( const bool _bNameIsReadOnly ) :OColumnBase( m_aMutex ) ,::comphelper::OPropertyContainer( OColumnBase::rBHelper ) { DBG_CTOR(OColumn, NULL); registerProperty( PROPERTY_NAME, PROPERTY_ID_NAME, _bNameIsReadOnly ? PropertyAttribute::READONLY : 0, &m_sName, ::getCppuType( &m_sName ) ); } //-------------------------------------------------------------------------- OColumn::~OColumn() { DBG_DTOR(OColumn, NULL); } // com::sun::star::lang::XTypeProvider //-------------------------------------------------------------------------- Sequence< Type > OColumn::getTypes() throw (RuntimeException) { return ::comphelper::concatSequences( OColumnBase::getTypes(), ::comphelper::OPropertyContainer::getTypes() ); } // com::sun::star::uno::XInterface IMPLEMENT_FORWARD_XINTERFACE2( OColumn, OColumnBase, ::comphelper::OPropertyContainer ) // ::com::sun::star::lang::XServiceInfo //------------------------------------------------------------------------------ rtl::OUString OColumn::getImplementationName( ) throw(RuntimeException) { return rtl::OUString::createFromAscii("com.sun.star.sdb.OColumn"); } //------------------------------------------------------------------------------ sal_Bool OColumn::supportsService( const ::rtl::OUString& _rServiceName ) throw (RuntimeException) { return ::comphelper::findValue(getSupportedServiceNames(), _rServiceName, sal_True).getLength() != 0; } //------------------------------------------------------------------------------ Sequence< ::rtl::OUString > OColumn::getSupportedServiceNames( ) throw (RuntimeException) { Sequence< ::rtl::OUString > aSNS( 1 ); aSNS[0] = SERVICE_SDBCX_COLUMN; return aSNS; } // OComponentHelper //------------------------------------------------------------------------------ void OColumn::disposing() { OPropertyContainer::disposing(); } // com::sun::star::beans::XPropertySet //------------------------------------------------------------------------------ Reference< XPropertySetInfo > OColumn::getPropertySetInfo() throw (RuntimeException) { return createPropertySetInfo( getInfoHelper() ) ; } // ----------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OColumn::getName( ) throw(::com::sun::star::uno::RuntimeException) { return m_sName; } // ----------------------------------------------------------------------------- void SAL_CALL OColumn::setName( const ::rtl::OUString& _rName ) throw(::com::sun::star::uno::RuntimeException) { m_sName = _rName; } // ----------------------------------------------------------------------------- void OColumn::fireValueChange(const ::connectivity::ORowSetValue& /*_rOldValue*/) { DBG_ERROR( "OColumn::fireValueChange: not implemented!" ); } //------------------------------------------------------------------------------ void OColumn::registerProperty( const ::rtl::OUString& _rName, sal_Int32 _nHandle, sal_Int32 _nAttributes, void* _pPointerToMember, const Type& _rMemberType ) { ::comphelper::OPropertyContainer::registerProperty( _rName, _nHandle, _nAttributes, _pPointerToMember, _rMemberType ); } //------------------------------------------------------------------------------ void OColumn::registerMayBeVoidProperty( const ::rtl::OUString& _rName, sal_Int32 _nHandle, sal_Int32 _nAttributes, Any* _pPointerToMember, const Type& _rExpectedType ) { ::comphelper::OPropertyContainer::registerMayBeVoidProperty( _rName, _nHandle, _nAttributes, _pPointerToMember, _rExpectedType ); } //------------------------------------------------------------------------------ void OColumn::registerPropertyNoMember( const ::rtl::OUString& _rName, sal_Int32 _nHandle, sal_Int32 _nAttributes, const Type& _rType, const void* _pInitialValue ) { ::comphelper::OPropertyContainer::registerPropertyNoMember( _rName, _nHandle, _nAttributes, _rType, _pInitialValue ); } //============================================================ //= OColumns //============================================================ DBG_NAME(OColumns); //-------------------------------------------------------------------------- OColumns::OColumns(::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex, sal_Bool _bCaseSensitive,const ::std::vector< ::rtl::OUString> &_rVector, IColumnFactory* _pColFactory, ::connectivity::sdbcx::IRefreshableColumns* _pRefresh, sal_Bool _bAddColumn, sal_Bool _bDropColumn, sal_Bool _bUseHardRef) : OColumns_BASE(_rParent,_bCaseSensitive,_rMutex,_rVector,_bUseHardRef) ,m_pMediator(NULL) ,m_xDrvColumns(NULL) ,m_pColFactoryImpl(_pColFactory) ,m_pRefreshColumns(_pRefresh) ,m_bInitialized(sal_False) ,m_bAddColumn(_bAddColumn) ,m_bDropColumn(_bDropColumn) { DBG_CTOR(OColumns, NULL); } // ------------------------------------------------------------------------- OColumns::OColumns(::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _rxDrvColumns, sal_Bool _bCaseSensitive,const ::std::vector< ::rtl::OUString> &_rVector, IColumnFactory* _pColFactory, ::connectivity::sdbcx::IRefreshableColumns* _pRefresh, sal_Bool _bAddColumn, sal_Bool _bDropColumn, sal_Bool _bUseHardRef) : OColumns_BASE(_rParent,_bCaseSensitive,_rMutex,_rVector,_bUseHardRef) ,m_pMediator(NULL) ,m_xDrvColumns(_rxDrvColumns) ,m_pColFactoryImpl(_pColFactory) ,m_pRefreshColumns(_pRefresh) ,m_bInitialized(sal_False) ,m_bAddColumn(_bAddColumn) ,m_bDropColumn(_bDropColumn) { DBG_CTOR(OColumns, NULL); } //-------------------------------------------------------------------------- OColumns::~OColumns() { DBG_DTOR(OColumns, NULL); } // XServiceInfo //------------------------------------------------------------------------------ rtl::OUString OColumns::getImplementationName( ) throw(RuntimeException) { return rtl::OUString::createFromAscii("com.sun.star.sdb.OColumns"); } //------------------------------------------------------------------------------ sal_Bool OColumns::supportsService( const ::rtl::OUString& _rServiceName ) throw (RuntimeException) { return ::comphelper::findValue(getSupportedServiceNames(), _rServiceName, sal_True).getLength() != 0; } //------------------------------------------------------------------------------ Sequence< ::rtl::OUString > OColumns::getSupportedServiceNames( ) throw (RuntimeException) { Sequence< ::rtl::OUString > aSNS( 1 ); aSNS[0] = SERVICE_SDBCX_CONTAINER; return aSNS; } //------------------------------------------------------------------ void OColumns::append( const ::rtl::OUString& _rName, OColumn* _pColumn ) { MutexGuard aGuard(m_rMutex); OSL_ENSURE( _pColumn, "OColumns::append: invalid column!" ); OSL_ENSURE( !m_pElements->exists( _rName ),"OColumns::append: Column already exists"); _pColumn->m_sName = _rName; // now really insert the column insertElement( _rName, _pColumn ); } //------------------------------------------------------------------ void OColumns::clearColumns() { MutexGuard aGuard(m_rMutex); disposing(); } // ----------------------------------------------------------------------------- void SAL_CALL OColumns::disposing(void) { MutexGuard aGuard(m_rMutex); m_xDrvColumns = NULL; m_pMediator = NULL; m_pColFactoryImpl = NULL; OColumns_BASE::disposing(); } // ------------------------------------------------------------------------- void OColumns::impl_refresh() throw(::com::sun::star::uno::RuntimeException) { if (m_pRefreshColumns) m_pRefreshColumns->refreshColumns(); } // ------------------------------------------------------------------------- connectivity::sdbcx::ObjectType OColumns::createObject(const ::rtl::OUString& _rName) { OSL_ENSURE(m_pColFactoryImpl, "OColumns::createObject: no column factory!"); connectivity::sdbcx::ObjectType xRet; if ( m_pColFactoryImpl ) { xRet = m_pColFactoryImpl->createColumn(_rName); Reference<XChild> xChild(xRet,UNO_QUERY); if ( xChild.is() ) xChild->setParent(static_cast<XChild*>(static_cast<TXChild*>(this))); } Reference<XPropertySet> xDest(xRet,UNO_QUERY); if ( m_pMediator && xDest.is() ) m_pMediator->notifyElementCreated(_rName,xDest); return xRet; } // ------------------------------------------------------------------------- Reference< XPropertySet > OColumns::createDescriptor() { if ( m_pColFactoryImpl ) { Reference<XPropertySet> xRet = m_pColFactoryImpl->createColumnDescriptor(); Reference<XChild> xChild(xRet,UNO_QUERY); if ( xChild.is() ) xChild->setParent(static_cast<XChild*>(static_cast<TXChild*>(this))); return xRet; } else return Reference< XPropertySet >(); } // ------------------------------------------------------------------------- Any SAL_CALL OColumns::queryInterface( const Type & rType ) throw(RuntimeException) { Any aRet; if(m_xDrvColumns.is()) { aRet = m_xDrvColumns->queryInterface(rType); if ( aRet.hasValue() ) aRet = OColumns_BASE::queryInterface( rType); if ( !aRet.hasValue() ) aRet = TXChild::queryInterface( rType); return aRet; } else if(!m_pTable || (m_pTable && !m_pTable->isNew())) { if(!m_bAddColumn && rType == getCppuType( (Reference<XAppend>*)0)) return Any(); if(!m_bDropColumn && rType == getCppuType( (Reference<XDrop>*)0)) return Any(); } aRet = OColumns_BASE::queryInterface( rType); if ( !aRet.hasValue() ) aRet = TXChild::queryInterface( rType); return aRet; } // ------------------------------------------------------------------------- Sequence< Type > SAL_CALL OColumns::getTypes( ) throw(RuntimeException) { sal_Bool bAppendFound = sal_False,bDropFound = sal_False; sal_Int32 nSize = 0; Type aAppendType = getCppuType( (Reference<XAppend>*)0); Type aDropType = getCppuType( (Reference<XDrop>*)0); if(m_xDrvColumns.is()) { Reference<XTypeProvider> xTypes(m_xDrvColumns,UNO_QUERY); Sequence< Type > aTypes(xTypes->getTypes()); Sequence< Type > aSecTypes(OColumns_BASE::getTypes()); const Type* pBegin = aTypes.getConstArray(); const Type* pEnd = pBegin + aTypes.getLength(); for (;pBegin != pEnd ; ++pBegin) { if(aAppendType == *pBegin) bAppendFound = sal_True; else if(aDropType == *pBegin) bDropFound = sal_True; } nSize = (bDropFound ? (bAppendFound ? 0 : 1) : (bAppendFound ? 1 : 2)); } else { nSize = ((m_pTable && m_pTable->isNew()) ? 0 : ((m_bDropColumn ? (m_bAddColumn ? 0 : 1) : (m_bAddColumn ? 1 : 2)))); bDropFound = (m_pTable && m_pTable->isNew()) || m_bDropColumn; bAppendFound = (m_pTable && m_pTable->isNew()) || m_bAddColumn; } Sequence< Type > aTypes(::comphelper::concatSequences(OColumns_BASE::getTypes(),TXChild::getTypes())); Sequence< Type > aRet(aTypes.getLength() - nSize); const Type* pBegin = aTypes.getConstArray(); const Type* pEnd = pBegin + aTypes.getLength(); for(sal_Int32 i=0;pBegin != pEnd ;++pBegin) { if(*pBegin != aAppendType && *pBegin != aDropType) aRet.getArray()[i++] = *pBegin; else if(bDropFound && *pBegin == aDropType) aRet.getArray()[i++] = *pBegin; else if(bAppendFound && *pBegin == aAppendType) aRet.getArray()[i++] = *pBegin; } return aRet; } // ------------------------------------------------------------------------- // XAppend sdbcx::ObjectType OColumns::appendObject( const ::rtl::OUString& _rForName, const Reference< XPropertySet >& descriptor ) { sdbcx::ObjectType xReturn; Reference< XAppend > xAppend( m_xDrvColumns, UNO_QUERY ); if ( xAppend.is() ) { xAppend->appendByDescriptor(descriptor); xReturn = createObject( _rForName ); } else if ( m_pTable && !m_pTable->isNew() ) { if ( m_bAddColumn ) { Reference< ::com::sun::star::sdb::tools::XTableAlteration> xAlterService = m_pTable->getAlterService(); if ( xAlterService.is() ) { xAlterService->addColumn(m_pTable,descriptor); xReturn = createObject( _rForName ); } else xReturn = OColumns_BASE::appendObject( _rForName, descriptor ); } else ::dbtools::throwGenericSQLException( DBA_RES( RID_STR_NO_COLUMN_ADD ), static_cast<XChild*>(static_cast<TXChild*>(this)) ); } else xReturn = cloneDescriptor( descriptor ); if ( m_pColFactoryImpl ) m_pColFactoryImpl->columnAppended( descriptor ); ::dbaccess::notifyDataSourceModified(m_xParent,sal_True); return xReturn; } // ------------------------------------------------------------------------- // XDrop void OColumns::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName) { Reference< XDrop > xDrop( m_xDrvColumns, UNO_QUERY ); if ( xDrop.is() ) { xDrop->dropByName( _sElementName ); } else if ( m_pTable && !m_pTable->isNew() ) { if ( m_bDropColumn ) { Reference< ::com::sun::star::sdb::tools::XTableAlteration> xAlterService = m_pTable->getAlterService(); if ( xAlterService.is() ) xAlterService->dropColumn(m_pTable,_sElementName); else OColumns_BASE::dropObject(_nPos,_sElementName); } else ::dbtools::throwGenericSQLException( DBA_RES( RID_STR_NO_COLUMN_DROP ), static_cast<XChild*>(static_cast<TXChild*>(this)) ); } if ( m_pColFactoryImpl ) m_pColFactoryImpl->columnDropped(_sElementName); ::dbaccess::notifyDataSourceModified(m_xParent,sal_True); } // ----------------------------------------------------------------------------- Reference< XInterface > SAL_CALL OColumns::getParent( ) throw (RuntimeException) { ::osl::MutexGuard aGuard(m_rMutex); return m_xParent; } // ----------------------------------------------------------------------------- void SAL_CALL OColumns::setParent( const Reference< XInterface >& _xParent ) throw (NoSupportException, RuntimeException) { ::osl::MutexGuard aGuard(m_rMutex); m_xParent = _xParent; } // -----------------------------------------------------------------------------
34.8159
168
0.590554
Grosskopf
aad5ff8d0dc2a3c2e59f6f6e05a56534fc156222
739
hpp
C++
feather/feather.hpp
msmoiz/feather
a28b593aa1cafd7dd1a4ddeb45641b5871feb620
[ "MIT" ]
null
null
null
feather/feather.hpp
msmoiz/feather
a28b593aa1cafd7dd1a4ddeb45641b5871feb620
[ "MIT" ]
null
null
null
feather/feather.hpp
msmoiz/feather
a28b593aa1cafd7dd1a4ddeb45641b5871feb620
[ "MIT" ]
null
null
null
// Copyright 2021 Mustafa Moiz. #pragma once #include <memory> #include <string> #include "input_handler.hpp" #include "cursor.hpp" #include "output_handler.hpp" #include "serializer.hpp" /** * Text editor that handles the following standard * operations: * - Navigation * - Manipulation * - Display * - Serialization */ class Feather { public: Feather(std::unique_ptr<InputHandler> input_handler, std::unique_ptr<OutputHandler> output_handler, std::unique_ptr<Serializer> serializer); void run(); private: std::unique_ptr<InputHandler> input_handler_{nullptr}; std::unique_ptr<OutputHandler> output_handler_{nullptr}; std::unique_ptr<Serializer> serializer_{nullptr}; std::string text_; Cursor cursor_{0}; };
18.948718
57
0.742896
msmoiz
aad6363410d32aa2cdff10d026b96e71aca82829
4,662
cpp
C++
projects/vkworld/wrappers/VkwMemoryHelper.cpp
Bycob/world
c6d943f9029c1bb227891507e5c6fe2b94cecfeb
[ "MIT" ]
16
2021-03-14T16:30:32.000Z
2022-03-18T13:41:53.000Z
projects/vkworld/wrappers/VkwMemoryHelper.cpp
Bycob/world
c6d943f9029c1bb227891507e5c6fe2b94cecfeb
[ "MIT" ]
1
2020-04-21T12:59:37.000Z
2020-04-23T17:49:03.000Z
projects/vkworld/wrappers/VkwMemoryHelper.cpp
BynaryCobweb/world
c6d943f9029c1bb227891507e5c6fe2b94cecfeb
[ "MIT" ]
4
2020-03-08T14:04:50.000Z
2020-12-03T08:51:04.000Z
#include "VkwMemoryHelper.h" #include "Vulkan.h" namespace world { void VkwMemoryHelper::GPUToImage(IVkwMemoryAccess &memory, Image &img) { GPUToImage(memory, img, img.elemSize()); } void VkwMemoryHelper::GPUToImageu(IVkwMemoryAccess &memory, Image &img) { GPUToImageu(memory, img, img.elemSize()); } // TODO change int to size_t to avoid overflow void VkwMemoryHelper::GPUToImage(IVkwMemoryAccess &memory, Image &img, u32 e) { const int w = img.width(), h = img.height(); const int size = w * h * e; float *buffer = new float[size]; memory.getData(buffer, size * sizeof(float), 0); for (u32 y = 0; y < h; ++y) { for (u32 x = 0; x < w; ++x) { u32 pos = (y * w + x) * e; img.setf(x, y, buffer + pos); } } } void VkwMemoryHelper::GPUToImageu(IVkwMemoryAccess &memory, Image &img, u32 e) { const int w = img.width(), h = img.height(); const int size = w * h * e; u8 *buffer = new u8[size]; memory.getData(buffer, size * sizeof(u8), 0); for (u32 y = 0; y < h; ++y) { for (u32 x = 0; x < w; ++x) { u32 pos = (y * w + x) * e; img.set(x, y, buffer + pos); } } } Image VkwMemoryHelper::GPUToImage(VkwImage &vkimg) { ImageType imType; bool isFloat = false; switch (vkimg.format()) { case vk::Format::eR32G32B32A32Sfloat: isFloat = true; case vk::Format::eR8G8B8A8Unorm: imType = ImageType::RGBA; break; case vk::Format::eR32G32B32Sfloat: isFloat = true; case vk::Format::eR8G8B8Unorm: imType = ImageType::RGB; break; case vk::Format::eR32Sfloat: isFloat = true; case vk::Format::eR8Unorm: imType = ImageType::GREYSCALE; break; default: throw std::runtime_error("GPUToImage: Vk image format not supported (" + std::to_string(int(vkimg.format())) + ")"); } Image img(vkimg.width(), vkimg.height(), imType); if (isFloat) { GPUToImage(vkimg, img); } else { GPUToImageu(vkimg, img); } return img; } void VkwMemoryHelper::imageToGPU(const Image &img, IVkwMemoryAccess &memory) { // TODO VkwMemoryHelper::imageToGPU } void VkwMemoryHelper::GPUToTerrain(IVkwMemoryAccess &memory, Terrain &terrain) { } void VkwMemoryHelper::terrainToGPU(const Terrain &terrain, IVkwMemoryAccess &memory) { int res = terrain.getResolution(); float *buf = new float[res * res]; for (int y = 0; y < res; ++y) { for (int x = 0; x < res; ++x) { buf[y * res + x] = float(terrain(x, y)); } } memory.setData(buf, res * res * sizeof(float), 0); delete[] buf; } void VkwMemoryHelper::GPUToMesh(IVkwMemoryAccess &verticesMemory, IVkwMemoryAccess &indicesMemory, Mesh &mesh) { GPUToVertices(verticesMemory, mesh); GPUToIndices(indicesMemory, mesh); } void VkwMemoryHelper::GPUToVertices(IVkwMemoryAccess &memory, Mesh &mesh) {} void VkwMemoryHelper::GPUToIndices(IVkwMemoryAccess &memory, Mesh &mesh) {} void VkwMemoryHelper::copyBuffer(VkwSubBuffer &from, VkwSubBuffer &to) { auto &ctx = Vulkan::context(); vk::CommandBufferAllocateInfo commandBufInfo( ctx._graphicsCommandPool, vk::CommandBufferLevel::ePrimary, 1); auto commandBuf = ctx._device.allocateCommandBuffers(commandBufInfo).at(0); commandBuf.begin(vk::CommandBufferBeginInfo( vk::CommandBufferUsageFlagBits::eOneTimeSubmit)); /*insertBarrier(commandBuf, {}, vk::AccessFlagBits ::eTransferWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eGeneral, vk::PipelineStageFlagBits::eTopOfPipe, vk::PipelineStageFlagBits::eTransfer);*/ vk::BufferCopy bufCopy{from.getOffset(), to.getOffset(), from.getSize()}; commandBuf.copyBuffer(from.handle(), to.handle(), bufCopy); /*insertBarrier(commandBuf, vk::AccessFlagBits ::eTransferWrite, vk::AccessFlagBits ::eShaderRead, vk::ImageLayout::eGeneral, vk::ImageLayout::eGeneral, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader);*/ commandBuf.end(); auto fence = ctx._device.createFence(vk::FenceCreateInfo()); vk::SubmitInfo submitInfo(0, nullptr, nullptr, 1, &commandBuf); ctx.queue(vk::QueueFlagBits::eGraphics).submit(submitInfo, fence); ctx._device.waitForFences(fence, true, 1000000000000); // Destroy resources ctx._device.freeCommandBuffers(ctx._graphicsCommandPool, commandBuf); ctx._device.destroyFence(fence); } } // namespace world
30.671053
80
0.634921
Bycob
aadf19904a3a35e3c4c7a6bc1dfd52136e45a8c2
13,715
cpp
C++
singlib/src_lib/net.cpp
mdegirolami/stay
b47676e5340c2bbd93fe97d52a12a895a3492b22
[ "BSD-3-Clause" ]
2
2021-08-13T01:00:49.000Z
2021-09-07T17:31:14.000Z
singlib/src_lib/net.cpp
mdegirolami/sing
7f674d3a1d5787b3f4016dc28c14e997149fc9f6
[ "BSD-3-Clause" ]
null
null
null
singlib/src_lib/net.cpp
mdegirolami/sing
7f674d3a1d5787b3f4016dc28c14e997149fc9f6
[ "BSD-3-Clause" ]
null
null
null
#define _WIN32_WINNT 0x600 // vista #include "net.h" #ifdef _WIN32 #include <winsock2.h> #include <ws2tcpip.h> #else #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <arpa/inet.h> #endif namespace sing { #ifdef _WIN32 #pragma comment(lib,"ws2_32.lib") void utf8_to_16(const char *src, std::vector<wchar_t> *dst); static int getaddrinfoL(const char *nodename, const char *servname, const struct addrinfo *hints, struct addrinfo **res) { if (nodename != nullptr) { std::vector<wchar_t> wname; std::vector<wchar_t> wservice; utf8_to_16(nodename, &wname); utf8_to_16(servname, &wservice); return(GetAddrInfoW(wname.data(), wservice.data(), (const ADDRINFOW*)hints, (PADDRINFOW*)res)); } return(::getaddrinfo(nodename, servname, hints, res)); } #else typedef int SOCKET; inline void closesocket(int a) { ::close(a); } static const int INVALID_SOCKET = -1; static const int SOCKET_ERROR = -1; static inline int getaddrinfoL(const char *nodename, const char *servname, const struct addrinfo *hints, struct addrinfo **res) { return(::getaddrinfo(nodename, servname, hints, res)); } #endif /////////////////// // // Utilities // ////////////////// const std::string ip4_loopback = "127.0.0.1"; const std::string ip6_loopback = "::1"; static bool createBoundSocketIp4(int32_t port, Sock *out_socket, int socket_type) { struct sockaddr_in addr; memset(addr.sin_zero, 0, sizeof(addr.sin_zero)); addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = INADDR_ANY; SOCKET socket = ::socket(addr.sin_family, socket_type, 0); if (socket == INVALID_SOCKET) { return(false); } if (bind(socket, (sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) { closesocket(socket); *out_socket = (Sock)INVALID_SOCKET; return(false); } *out_socket = (Sock)socket; return(true); } static bool createBoundSocketIp6(int32_t port, Sock *out_socket, int socket_type) { struct sockaddr_in6 addr; memset(&addr, 0, sizeof(addr)); addr.sin6_family = AF_INET6; addr.sin6_addr = in6addr_any; addr.sin6_port = htons(port); SOCKET socket = ::socket(addr.sin6_family, socket_type, 0); if (socket == INVALID_SOCKET) { return(false); } if (bind(socket, (sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) { closesocket(socket); *out_socket = (Sock)INVALID_SOCKET; return(false); } *out_socket = (Sock)socket; return(true); } static bool createBoundSocket(int32_t port, Sock *socket, int socket_type, IpVersion ipv) { if (port < 0) port = 0; if (ipv == IpVersion::v4) { return(createBoundSocketIp4(port, socket, socket_type)); } else if (ipv == IpVersion::v6) { return(createBoundSocketIp6(port, socket, socket_type)); } return(false); } static int32_t getLocalPortFromSocket(SOCKET socket) { Address addr; socklen_t len = sizeof(addr.add_); if (getsockname(socket, (struct sockaddr *)&addr.add_[0], &len) == 0) { addr.len_ = len; return(addr.getPort()); } return(-1); } // // returns false for error/tout // static bool waitForSocket(int32_t tout, SOCKET socket, bool *timedout) { fd_set fds; struct timeval tv; tout = std::min(tout, 2000000); tout = std::max(tout, 0); tv.tv_sec = 0; tv.tv_usec = tout * 1000; int nn; do { FD_ZERO(&fds); FD_SET(socket, &fds); nn = select(socket+1, &fds, nullptr, nullptr, &tv); } while (nn == -1 && errno == EINTR); *timedout = nn == 0; return(nn == 1); } /////////////////// // // Address implementation // ////////////////// Address::Address() { len_ = 0; } bool Address::set(const char *ip_address, const char *port) { struct addrinfo *servinfo; // will point to the results bool result = false; if (ip_address == nullptr || ip_address[0] == 0) return(false); if (port == nullptr || port[0] == 0) return(false); if (getaddrinfoL(ip_address, port, nullptr, &servinfo) != 0) { return(false); } for(struct addrinfo *ptr=servinfo; ptr != nullptr; ptr=ptr->ai_next) { if (ptr->ai_family == AF_INET || ptr->ai_family == AF_INET6) { if (ptr->ai_addrlen < sizeof(add_)) { len_ = ptr->ai_addrlen; memcpy(&add_[0], ptr->ai_addr, len_); result = true; break; } } } freeaddrinfo(servinfo); return(result); } std::string Address::getIpAddress() const { char print_buffer[INET6_ADDRSTRLEN]; if (len_ == 0) return(""); short family = ((sockaddr_in*)&add_[0])->sin_family; if (family == AF_INET) { if (inet_ntop(AF_INET, &((sockaddr_in*)&add_[0])->sin_addr, print_buffer, INET6_ADDRSTRLEN) != nullptr) { return(print_buffer); } } else if (family == AF_INET6) { if (inet_ntop(AF_INET6, &((sockaddr_in6*)&add_[0])->sin6_addr, print_buffer, INET6_ADDRSTRLEN) != nullptr) { return(print_buffer); } } return(""); } int32_t Address::getPort() const { if (len_ == 0) return(-1); short family = ((sockaddr_in*)&add_[0])->sin_family; if (family == AF_INET) { return(ntohs(((sockaddr_in*)&add_[0])->sin_port)); } else if (family == AF_INET6) { return(ntohs(((sockaddr_in6*)&add_[0])->sin6_port)); } return(-1); } /////////////////// // // ListenerSocket implementation // ////////////////// ListenerSocket::ListenerSocket() { sock_ = INVALID_SOCKET; tout_ = false; } ListenerSocket::~ListenerSocket() { close(); } bool ListenerSocket::open(int32_t localport, int32_t queue_length, IpVersion ipv) { if (!createBoundSocket(localport, &sock_, SOCK_STREAM, ipv)) { return(false); } if (listen((SOCKET)sock_, std::max(queue_length, 1)) == SOCKET_ERROR) { close(); return(false); } return(true); } void ListenerSocket::close() { if (sock_ != INVALID_SOCKET) { closesocket((SOCKET)sock_); sock_ = INVALID_SOCKET; } } bool ListenerSocket::accept(ConnectedSocket *socket, int32_t ms_timeout) { Address remote; SOCKET newsock; if (ms_timeout >= 0 && !waitForSocket(ms_timeout, (SOCKET)sock_, &tout_)) { return(false); } socklen_t len; do { len = sizeof(remote.add_); newsock = ::accept((SOCKET)sock_, (sockaddr*)&remote.add_[0], &len); } while (newsock == INVALID_SOCKET && errno == EINTR); if (newsock == INVALID_SOCKET) { return(false); } remote.len_ = len; socket->setSock(newsock); socket->setRemote(remote); return(true); } int32_t ListenerSocket::getLocalPort() const { return(getLocalPortFromSocket((SOCKET)sock_)); } bool ListenerSocket::timedout() const { return(tout_); } /////////////////// // // ConnectedSocket implementation // ////////////////// ConnectedSocket::ConnectedSocket() { sock_ = INVALID_SOCKET; tout_ = false; } ConnectedSocket::~ConnectedSocket() { close(); } bool ConnectedSocket::open(const Address &addr, int32_t localport) { short family = ((sockaddr_in*)&addr.add_[0])->sin_family; IpVersion ipv = family == AF_INET ? IpVersion::v4 : IpVersion::v6; if (!createBoundSocket(localport, &sock_, SOCK_STREAM, ipv)) { return(false); } int retvalue; do { retvalue = connect((SOCKET)sock_, (sockaddr*)&addr.add_[0], addr.len_); } while (retvalue == SOCKET_ERROR && errno == EINTR); if (retvalue == SOCKET_ERROR) { close(); return(false); } remote_ = addr; return(true); } void ConnectedSocket::close() { if (sock_ != INVALID_SOCKET) { closesocket((SOCKET)sock_); sock_ = INVALID_SOCKET; } } int32_t ConnectedSocket::getLocalPort() const { return(getLocalPortFromSocket((SOCKET)sock_)); } void ConnectedSocket::getRemoteAddress(Address *addr) const { *addr = remote_; } bool ConnectedSocket::timedout() const { return(tout_); } bool ConnectedSocket::rcvString(std::string *value, int64_t maxbytes, int32_t ms_timeout) { if (ms_timeout >= 0 && !waitForSocket(ms_timeout, (SOCKET)sock_, &tout_)) { return(false); } value->resize(maxbytes); int received; do { received = recv((SOCKET)sock_, (char*)value->data(), maxbytes, 0); } while (received == -1 && errno == EINTR); value->resize(std::max(received, 0)); // 0 means 'connection closed' return(received > 0); } bool ConnectedSocket::rcv(std::vector<uint8_t> *dst, int64_t count, int32_t ms_timeout, bool append) { if (ms_timeout >= 0 && !waitForSocket(ms_timeout, (SOCKET)sock_, &tout_)) { return(false); } if (!append) dst->clear(); int orig_size = dst->size(); dst->resize(orig_size + count); uint8_t *pdst = dst->data() + orig_size; int received; do { received = recv((SOCKET)sock_, (char*)pdst, count, 0); } while (received == -1 && errno == EINTR); // 0 means 'connection closed' if (received > 0) { dst->resize(orig_size + received); return(true); } dst->resize(orig_size); return(false); } bool ConnectedSocket::sendString(const char *value) { const char *src = value; int len = strlen(value); while (len > 0) { int sent = ::send((SOCKET)sock_, src, len, 0); if (sent <= 0) { if (errno != EINTR) return(false); sent = 0; } src += sent; len -= sent; } return(true); } bool ConnectedSocket::send(const std::vector<uint8_t> &src, int64_t count, int64_t from) { const uint8_t *psrc = src.data(); int64_t len = (int64_t)src.size(); if (from >= len) return(true); psrc += from; len -= from; len = std::min(len, count); while (len > 0) { int sent = ::send((SOCKET)sock_, (const char*)psrc, len, 0); if (sent <= 0) { if (errno != EINTR) return(false); sent = 0; } psrc += sent; len -= sent; } return(true); } // internal use void ConnectedSocket::setSock(int64_t v) { sock_ = v; } void ConnectedSocket::setRemote(const Address &remote) { remote_ = remote; } /////////////////// // // unconnected Sockets // ////////////////// Socket::Socket() { sock_ = INVALID_SOCKET; tout_ = false; } Socket::~Socket() { close(); } bool Socket::open(int32_t localport, IpVersion ipv) { return(createBoundSocket(localport, &sock_, SOCK_DGRAM, ipv)); } void Socket::close() { if (sock_ != INVALID_SOCKET) { closesocket((SOCKET)sock_); sock_ = INVALID_SOCKET; } } int32_t Socket::getLocalPort() const { return(getLocalPortFromSocket((SOCKET)sock_)); } bool Socket::timedout() const { return(tout_); } bool Socket::rcvString(Address *add, std::string *value, int64_t maxbytes, int32_t ms_timeout) { if (ms_timeout >= 0 && !waitForSocket(ms_timeout, (SOCKET)sock_, &tout_)) { return(false); } value->resize(maxbytes); socklen_t len; int received; do { len = sizeof(add->add_); received = recvfrom((SOCKET)sock_, (char*)value->data(), maxbytes, 0, (sockaddr*)&add->add_[0], &len); } while (received == -1 && errno == EINTR); if (received >= 0) add->len_ = len; value->resize(std::max(received, 0)); // 0 is a legal datagram length return(received >= 0); } bool Socket::rcv(Address *add, std::vector<uint8_t> *dst, int64_t count, int32_t ms_timeout, bool append) { if (ms_timeout >= 0 && !waitForSocket(ms_timeout, (SOCKET)sock_, &tout_)) { return(false); } if (!append) dst->clear(); int orig_size = dst->size(); dst->resize(orig_size + count); uint8_t *pdst = dst->data() + orig_size; socklen_t len; int received; do { len = sizeof(add->add_); received = recvfrom((SOCKET)sock_, (char*)pdst, count, 0, (sockaddr*)&add->add_[0], &len); } while (received == -1 && errno == EINTR); // 0 is a legal datagram length if (received >= 0) { add->len_ = len; dst->resize(orig_size + received); return(true); } dst->resize(orig_size); return(false); } bool Socket::sendString(const Address &add, const char *value) { const char *src = value; int len = strlen(value); while (len > 0) { int sent = ::sendto((SOCKET)sock_, src, len, 0, (sockaddr*)&add.add_[0], add.len_); if (sent <= 0) { if (errno != EINTR) return(false); sent = 0; } src += sent; len -= sent; } return(true); } bool Socket::send(const Address &add, const std::vector<uint8_t> &src, int64_t count, int64_t from) { const uint8_t *psrc = src.data(); int64_t len = (int64_t)src.size(); if (from >= len) return(true); psrc += from; len -= from; len = std::min(len, count); while (len > 0) { int sent = ::sendto((SOCKET)sock_, (const char*)psrc, len, 0, (sockaddr*)&add.add_[0], add.len_); if (sent <= 0) { if (errno != EINTR) return(false); sent = 0; } psrc += sent; len -= sent; } return(true); } /////////////////// // // free functions implementation // ////////////////// #ifdef _WIN32 bool netInit() { WSADATA wsaData; return(WSAStartup(MAKEWORD(2,2), &wsaData) == 0); } void netShutdown() { WSACleanup(); } #else bool netInit() { return(true); } void netShutdown() { } #endif } // namespace
23.893728
127
0.594677
mdegirolami
aae0df5dd88cfb272a66f24d3cb361a0d122c89a
643
cpp
C++
source/common/qmsgunregistresult.cpp
c6supper/json_serialize_deserialize_qt
c70e89056900835221309f7c54dcca2e9fefe498
[ "Apache-2.0" ]
null
null
null
source/common/qmsgunregistresult.cpp
c6supper/json_serialize_deserialize_qt
c70e89056900835221309f7c54dcca2e9fefe498
[ "Apache-2.0" ]
null
null
null
source/common/qmsgunregistresult.cpp
c6supper/json_serialize_deserialize_qt
c70e89056900835221309f7c54dcca2e9fefe498
[ "Apache-2.0" ]
null
null
null
/* This file is part of qprofile * * Copyright (C) 2018 Calvin <c6supper@hotmail.com> */ #include "qmessagefactory.h" #include "qmsgunregistresult.h" using namespace QRserver; using namespace rserver; QMessageSelfRegisteration<QMsgUnregistResult> registerQMsgUnregistResult( rserver::eUnRegistResult); QMsgUnregistResult::QMsgUnregistResult(QObject *parent) : QMsgRegisterResult(parent) { setType(rserver::eUnRegistResult); } QMsgUnregistResult::QMsgUnregistResult(const QMsgUnregistResult &message) : QMsgRegisterResult(message) { setType(rserver::eUnRegistResult); } QMsgUnregistResult::~QMsgUnregistResult() {}
22.964286
73
0.782271
c6supper
aae8352578a7ba3ada7a77de0c0a9e63e32f3b2c
588
cpp
C++
ByteCamp/Day2/generator.cpp
JackBai0914/Competitive-Programming-Codebase
a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9
[ "MIT" ]
null
null
null
ByteCamp/Day2/generator.cpp
JackBai0914/Competitive-Programming-Codebase
a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9
[ "MIT" ]
null
null
null
ByteCamp/Day2/generator.cpp
JackBai0914/Competitive-Programming-Codebase
a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <ctime> using namespace std; #define F first #define S second #define MP make_pair typedef long long ll; typedef pair <int, int> pii; int main() { ios::sync_with_stdio(false); //freopen("1.in", "r", stdin); freopen("test.in", "w", stdout); srand(time(0)); cout << 1000 << endl; for (int i = 1; i <= 20; i ++) for (int j = 1; j <= 50; j ++) { cout << i * 20 + rand() % 5 << " " << j * 20 + rand() % 5 << " " << rand() % 5 + 1 << endl; } return 0; }
21
94
0.579932
JackBai0914
aaf048f73026d9a8bc5146eded48c7239d1dfa83
3,207
cpp
C++
src/caffe/util/random_helper.cpp
MSRCCS/Caffe
2eb05997f077fe93832b89d56ea0cd1ea72e3275
[ "BSD-2-Clause" ]
null
null
null
src/caffe/util/random_helper.cpp
MSRCCS/Caffe
2eb05997f077fe93832b89d56ea0cd1ea72e3275
[ "BSD-2-Clause" ]
null
null
null
src/caffe/util/random_helper.cpp
MSRCCS/Caffe
2eb05997f077fe93832b89d56ea0cd1ea72e3275
[ "BSD-2-Clause" ]
null
null
null
#include "caffe/util/random_helper.h" #include <iostream> #include <stdexcept> #include <cstdlib> #include <time.h> #include <math.h> namespace caffe { random_helper::random_init_helper random_helper::m_randInit; #if _HAS_CPP0X std::mt19937_64 random_helper::m_generator; std::uniform_int_distribution<unsigned int> random_helper::m_uniformInt; std::uniform_real_distribution<double> random_helper::m_uniformReal; std::normal_distribution<double> random_helper::m_normalReal; #endif random_helper::random_init_helper::random_init_helper() { srand(time(NULL)); #if _HAS_CPP0X m_generator = std::mt19937_64(std::random_device()()); m_uniformInt = std::uniform_int_distribution<unsigned int>(0, UINT_MAX); m_uniformReal = std::uniform_real_distribution<double>(0.0, 1.0); m_normalReal = std::normal_distribution<double>(0.0, 1.0); #endif } random_helper::random_helper() { } random_helper::~random_helper() { } unsigned int random_helper::uniform_int(unsigned int min/* = 0*/, unsigned int max/* = UINT_MAX*/) { if (min >= max) { std::cout << "random_helper::uniform_int must have min >= max" << std::endl; throw std::runtime_error("random_helper::uniform_int must have min >= max"); } unsigned int range = max - min + 1; #ifndef RAND_DEVICE #if _HAS_CPP0X if (m_uniformInt.min() != min || m_uniformInt.max() != max) m_uniformInt = std::uniform_int_distribution<unsigned int>(min, max); return m_uniformInt(m_generator); #else if (max > RAND_MAX) std::cout << "Warning : random_helper::uniform_int with rand() only with range [0, " << RAND_MAX << "]" << std::endl; return rand() % range + min; #endif #else if (max > std::random_device().max()) std::cout << "Warning : random_helper::uniform_int with random_device() only with range [0, " << std::random_device().max() << "]" << std::endl; return std::random_device()() % range + min; #endif } double random_helper::uniform_real(double min/*= 0.0*/, double max/* = 1.0*/) { if (min >= max) { std::cout << "random_helper::uniform_real must have min >= max" << std::endl; throw std::runtime_error("random_helper::uniform_real must have min >= max"); } #ifndef RAND_DEVICE #if _HAS_CPP0X if (m_uniformReal.min() != min || m_uniformReal.max() != max) m_uniformReal = std::uniform_real_distribution<double>(min, max); return m_uniformReal(m_generator); #else return (double)rand() / (double)RAND_MAX * (max - min) + min; #endif #else return (double)std::random_device()() / (double)std::random_device().max() * (max - min) + min; #endif } double random_helper::normal_real() { #ifndef RAND_DEVICE #if _HAS_CPP0X return m_normalReal(m_generator); #else const double PI = 3.1415926535897932384626433832795; double a = ((double)rand() + 1) / ((double)RAND_MAX + 2); double b = (double)rand() / ((double)RAND_MAX + 1); return sqrt(-2 * log(a))*cos(2 * PI*b); #endif #else const double PI = 3.1415926535897932384626433832795; double a = ((double)std::random_device()() + 1) / ((double)std::random_device().max() + 2); double b = (double)std::random_device()() / ((double)std::random_device().max() + 1); return sqrt(-2 * log(a))*cos(2 * PI*b); #endif } }
31.752475
147
0.692859
MSRCCS
aaf14c9a007c89b56412b97608b1192286b8936e
905
hpp
C++
src/include/duckdb/storage/meta_block_reader.hpp
rainmaple/duckdb
d3df77ba6740b8b089bddbfef77e2b969245b5cf
[ "MIT" ]
9
2021-09-08T13:13:03.000Z
2022-03-11T21:18:05.000Z
src/include/duckdb/storage/meta_block_reader.hpp
rainmaple/duckdb
d3df77ba6740b8b089bddbfef77e2b969245b5cf
[ "MIT" ]
7
2020-08-25T22:24:16.000Z
2020-09-06T00:16:49.000Z
src/include/duckdb/storage/meta_block_reader.hpp
rainmaple/duckdb
d3df77ba6740b8b089bddbfef77e2b969245b5cf
[ "MIT" ]
1
2022-01-18T09:38:19.000Z
2022-01-18T09:38:19.000Z
//===----------------------------------------------------------------------===// // DuckDB // // duckdb/storage/meta_block_reader.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "duckdb/common/common.hpp" #include "duckdb/common/serializer.hpp" #include "duckdb/storage/block.hpp" #include "duckdb/storage/buffer_manager.hpp" namespace duckdb { //! This struct is responsible for reading meta data from disk class MetaBlockReader : public Deserializer { public: MetaBlockReader(BufferManager &manager, block_id_t block); BufferManager &manager; unique_ptr<BufferHandle> handle; idx_t offset; block_id_t next_block; public: //! Read content of size read_size into the buffer void ReadData(data_ptr_t buffer, idx_t read_size) override; private: void ReadNewBlock(block_id_t id); }; } // namespace duckdb
25.857143
80
0.614365
rainmaple
aaf556e844e7b1f62fc8c5079d40bac80bf99997
3,044
cpp
C++
src/main/start.cpp
ondra-novak/lnex
d1412be914098c9ae22ee65568895aff6d58d1ba
[ "MIT" ]
null
null
null
src/main/start.cpp
ondra-novak/lnex
d1412be914098c9ae22ee65568895aff6d58d1ba
[ "MIT" ]
null
null
null
src/main/start.cpp
ondra-novak/lnex
d1412be914098c9ae22ee65568895aff6d58d1ba
[ "MIT" ]
null
null
null
#include <userver/http_server.h> #include <shared/default_app.h> #include <couchit/config.h> #include <couchit/couchDB.h> #include <userver/http_client.h> #include <userver/ssl.h> #include "../couchit/src/couchit/changes.h" #include "../userver/static_webserver.h" #include "server.h" #include "walletsvc.h" int main(int argc, char **argv) { using namespace userver; using namespace ondra_shared; using namespace lnex; ondra_shared::DefaultApp app({}, std::cerr); if (!app.init(argc, argv)) { std::cerr<<"Failed to initialize application" << std::endl; return 1; } auto section_server = app.config["server"]; NetAddrList bind_addr = NetAddr::fromString( section_server.mandatory["listen"].getString(), "9500"); unsigned int threads = section_server.mandatory["threads"].getUInt(); unsigned int dispatchers = section_server["dispatchers"].getUInt(1); unsigned int maxupload = section_server.mandatory["max_upload_mb"].getUInt()*1024*1024; auto section_wallet = app.config["wallet"]; std::optional<WalletConfig> wcfg; if (section_wallet["enabled"].getBool(false)) { wcfg.emplace(); wcfg->login = section_wallet.mandatory["login"].getString(); wcfg->password= section_wallet.mandatory["password"].getString(); wcfg->url= section_wallet.mandatory["url"].getString(); } logProgress("---------- SERVER STAR ---------"); for (const auto &x: bind_addr) logInfo("Listen: $1", x.toString(false)); auto section_db = app.config["database"]; couchit::Config dbcfg; dbcfg.authInfo.username = section_db.mandatory["username"].getString(); dbcfg.authInfo.password = section_db.mandatory["password"].getString(); dbcfg.baseUrl = section_db.mandatory["server_url"].getString(); dbcfg.databaseName = section_db.mandatory["db_name"].getString(); auto section_www = app.config["www"]; std::optional<userver::StaticWebserver::Config> www_cfg; if (section_www["enabled"].getBool()) { www_cfg.emplace(); www_cfg->cachePeriod = section_www["cache"].getUInt(); www_cfg->document_root = section_www.mandatory["document_root"].getPath(); www_cfg->indexFile = section_www.mandatory["index_file"].getString(); } couchit::CouchDB couchdb(dbcfg); couchit::ChangesDistributor chdist(couchdb,true,true); ondra_shared::Scheduler sch = sch.create(); if (wcfg.has_value()) { auto wallet = std::make_shared<WalletService>(couchdb,*wcfg, HttpClientCfg{"lnex.cz"}); wallet->init(wallet, chdist, sch); } MyHttpServer server; server.addRPCPath("/RPC", { true,true,true,maxupload }); server.add_listMethods(); server.add_ping(); if (www_cfg.has_value()) { server.addPath("", StaticWebserver(*www_cfg)); } server.start(bind_addr, threads, dispatchers); sch.immediate() >> [provider = server.getAsyncProvider()]{ userver::setThreadAsyncProvider(provider); }; chdist.runService([&]{ userver::setThreadAsyncProvider(server.getAsyncProvider()); }); server.stopOnSignal(); server.addThread(); server.stop(); chdist.stopService(); logProgress("---------- SERVER STOP ---------"); }
29.269231
89
0.718134
ondra-novak
aaf65e5d2920665f8dfad5ffa2d9f06bce4ceb9f
4,081
cpp
C++
dynamic programming/boolean_patenthesization_memoization.cpp
kashyap99saksham/Code
96658d0920eb79c007701d2a3cc9dbf453d78f96
[ "MIT" ]
16
2020-06-02T19:22:45.000Z
2022-02-05T10:35:28.000Z
dynamic programming/boolean_patenthesization_memoization.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
null
null
null
dynamic programming/boolean_patenthesization_memoization.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
2
2020-08-27T17:40:06.000Z
2022-02-05T10:33:52.000Z
/* Given a boolean expression with following symbols. Symbols 'T' ---> true 'F' ---> false And following operators filled between symbols Operators & ---> boolean AND | ---> boolean OR ^ ---> boolean XOR Count the number of ways we can parenthesize the expression so that the value of expression evaluates to true. For Example: The expression is "T | T & F ^ T", it evaluates true in 4 ways ((T|T)&(F^T)), (T|(T&(F^T))), (((T|T)&F)^T) and (T|((T&F)^T)). Return No_of_ways Mod 1003. Input: First line contains the test cases T. 1<=T<=500 Each test case have two lines First is length of string N. 1<=N<=100 Second line is string S (boolean expression). Output: No of ways Mod 1003. Example: Input: 2 7 T|T&F^T 5 T^F|F Output: 4 2 */ #include<bits/stdc++.h> using namespace std; int dp[201][201][2]; int booleanParenthesis(string s, int i, int j, bool isTrue){ if(i>j) return 0; if(i==j){ if(isTrue==true) return s[i]=='T'; else return s[i]=='F'; } if(dp[i][j][isTrue]!=-1) return dp[i][j][isTrue]; int ans=0, lf, lt, rf, rt; for(int k=i+1;k<j;k+=2){ if(dp[i][k-1][true]!=-1) lt=dp[i][k-1][true]; else { dp[i][k-1][true]=booleanParenthesis(s, i, k-1, true); lt=dp[i][k-1][true]; } if(dp[i][k-1][false]!=-1) lf=dp[i][k-1][false]; else { dp[i][k-1][false]=booleanParenthesis(s, i, k-1,false); lf=dp[i][k-1][false]; } if(dp[k+1][j][true]!=-1) rt=dp[k+1][j][true]; else { dp[k+1][j][true]=booleanParenthesis(s, k+1, j, true); rt=dp[k+1][j][true]; } if(dp[k+1][j][false]!=-1) rf=dp[k+1][j][false]; else { dp[k+1][j][false]=booleanParenthesis(s, k+1, j, false); rf=dp[k+1][j][false]; } if(s[k]=='&'){ if(isTrue==true) ans+=lt*rt; else ans+=lt*rf + lf*rt + lf*rf; } else if(s[k]=='|'){ if(isTrue==true) ans+=lt*rt + lt*rf + lf*rt; else ans+=lf*rf; } else if(s[k]=='^'){ if(isTrue==true) ans+=lt*rf + lf*rt; else ans+=lf*rf + lt*rt; } } return dp[i][j][isTrue]=ans%1003; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t; cin>>t; while(t--){ int n; cin>>n; string s; cin>>s; memset(dp, -1, sizeof(dp)); cout<<booleanParenthesis(s, 0, n-1, true)<<endl; } return 0; } /* Alternative Approach #include<bits/stdc++.h> using namespace std; map<string, int> mp; int booleanParenthesis(string s, int i, int j, bool isTrue){ if(i>j) return 0; if(i==j){ if(isTrue==true) return s[i]=='T'; else return s[i]=='F'; } string tmp=to_string(i); tmp.push_back(' '); tmp.append(to_string(j)); tmp.push_back(' '); tmp.append(to_string(isTrue)); if(mp.find(tmp)!=mp.end()) return mp[tmp]; int ans=0; for(int k=i+1;k<j;k+=2){ int lt=booleanParenthesis(s, i, k-1, true); int lf=booleanParenthesis(s, i, k-1, false); int rt=booleanParenthesis(s, k+1, j, true); int rf=booleanParenthesis(s, k+1, j, false); if(s[k]=='&'){ if(isTrue==true) ans+=lt*rt; else ans+=lt*rf + lf*rt + lf*rf; } else if(s[k]=='|'){ if(isTrue==true) ans+=lt*rt + lt*rf + lf*rt; else ans+=lf*rf; } else if(s[k]=='^'){ if(isTrue==true) ans+=lt*rf + lf*rt; else ans+=lf*rf + lt*rt; } } return mp[tmp]=ans%1003; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t; cin>>t; while(t--){ int n; cin>>n; string s; cin>>s; mp.clear(); cout<<booleanParenthesis(s, 0, n-1, true)<<endl; } return 0; } */
21.707447
110
0.493506
kashyap99saksham
aaf7b8d63b31676a282a2f7410deffb2fdb5e6f7
1,096
cpp
C++
Hacker Rank/Sock Merchant.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
51
2020-02-24T11:14:00.000Z
2022-03-24T09:32:18.000Z
Hacker Rank/Sock Merchant.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
3
2020-10-02T08:16:09.000Z
2021-04-17T16:32:38.000Z
Hacker Rank/Sock Merchant.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
18
2020-04-24T15:33:36.000Z
2022-03-24T09:32:20.000Z
/*Hacker Rank*/ /*Title - Sock Merchant*/ //John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. // //For example, there are n = 7 socks with colors ar = [1,2,1,2,1,3,2] . There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2. // //Function Description // //Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available. // //sockMerchant has the following parameter(s): // //n: the number of socks in the pile //ar: the colors of each sock int sockMerchant(int n, vector<int> ar) { int count=0; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(ar[i]==ar[j] && i!=j) { count++; ar[i]=INT_MAX-i; ar[j]=INT_MAX-j; break; } } } return count; }
32.235294
230
0.629562
Shubhrmcf07
aafc797c3208cb29af83dd8161ba51b4de17c7f5
5,203
cpp
C++
src/fplll/fplll/enum/enumerate_ext.cpp
Hyper5phere/sphere-decoder
f84cbcb47314547150639bbed017e8e540d32ced
[ "Unlicense" ]
null
null
null
src/fplll/fplll/enum/enumerate_ext.cpp
Hyper5phere/sphere-decoder
f84cbcb47314547150639bbed017e8e540d32ced
[ "Unlicense" ]
null
null
null
src/fplll/fplll/enum/enumerate_ext.cpp
Hyper5phere/sphere-decoder
f84cbcb47314547150639bbed017e8e540d32ced
[ "Unlicense" ]
null
null
null
/* (C) 2016 Marc Stevens. This file is part of fplll. fplll is free software: you can redistribute it and/or modify it under the terms of 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. fplll is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with fplll. If not, see <http://www.gnu.org/licenses/>. */ #include "enumerate_ext.h" FPLLL_BEGIN_NAMESPACE // set & get external enumerator (nullptr => disabled) std::function<extenum_fc_enumerate> fplll_extenum = nullptr; void set_external_enumerator(std::function<extenum_fc_enumerate> extenum) { fplll_extenum = extenum; } std::function<extenum_fc_enumerate> get_external_enumerator() { return fplll_extenum; } template <typename ZT, typename FT> bool ExternalEnumeration<ZT, FT>::enumerate(int first, int last, FT &fmaxdist, long fmaxdistexpo, const vector<enumf> &pruning, bool dual) { using namespace std::placeholders; if (fplll_extenum == nullptr) return false; if (last == -1) last = _gso.d; _first = first; _dual = dual; _pruning = pruning; _d = last - _first; _fx.resize(_d); FPLLL_CHECK(_pruning.empty() || int(_pruning.size()) == _d, "ExternalEnumeration: non-empty pruning vector dimension does not match"); FT fr, fmu, fmaxdistnorm; long rexpo; _normexp = -1; for (int i = 0; i < _d; ++i) { fr = _gso.get_r_exp(i + first, i + first, rexpo); _normexp = max(_normexp, rexpo + fr.exponent()); } fmaxdistnorm.mul_2si(fmaxdist, dual ? _normexp - fmaxdistexpo : fmaxdistexpo - _normexp); _maxdist = fmaxdistnorm.get_d(GMP_RNDU); _evaluator.set_normexp(_normexp); // clang-format off _nodes = fplll_extenum(_d, _maxdist, std::bind(&ExternalEnumeration<ZT,FT>::callback_set_config, this, _1, _2, _3, _4, _5), std::bind(&ExternalEnumeration<ZT,FT>::callback_process_sol, this, _1, _2), std::bind(&ExternalEnumeration<ZT,FT>::callback_process_subsol, this, _1, _2, _3), _dual, _evaluator.findsubsols ); // clang-format on return _nodes != ~uint64_t(0); } template <typename ZT, typename FT> void ExternalEnumeration<ZT, FT>::callback_set_config(enumf *mu, size_t mudim, bool mutranspose, enumf *rdiag, enumf *pruning) { FT fr, fmu; long rexpo; for (int i = 0; i < _d; ++i) { fr = _gso.get_r_exp(i + _first, i + _first, rexpo); fr.mul_2si(fr, rexpo - _normexp); rdiag[i] = fr.get_d(); } if (mutranspose) { size_t offs = 0; for (int i = 0; i < _d; ++i, offs += mudim) { for (int j = 0; j < _d; ++j) { _gso.get_mu(fmu, j + _first, i + _first); /* mu[i][j]= */ mu[offs + j] = fmu.get_d(); } } } else { size_t offs = 0; for (int j = 0; j < _d; ++j, offs += mudim) { for (int i = 0; i < _d; ++i) { _gso.get_mu(fmu, j + _first, i + _first); /* mu[j][i] = */ mu[offs + i] = fmu.get_d(); } } } if (_pruning.empty()) { for (int i = 0; i < _d; ++i) pruning[i] = 1.0; } else { for (int i = 0; i < _d; ++i) pruning[i] = _pruning[i]; } } template <typename ZT, typename FT> enumf ExternalEnumeration<ZT, FT>::callback_process_sol(enumf dist, enumf *sol) { for (int i = 0; i < _d; ++i) _fx[i] = sol[i]; _evaluator.eval_sol(_fx, dist, _maxdist); return _maxdist; } template <typename ZT, typename FT> void ExternalEnumeration<ZT, FT>::callback_process_subsol(enumf dist, enumf *subsol, int offset) { for (int i = 0; i < offset; ++i) _fx[i] = 0.0; for (int i = offset; i < _d; ++i) _fx[i] = subsol[i]; _evaluator.eval_sub_sol(offset, _fx, dist); } template class ExternalEnumeration<Z_NR<mpz_t>, FP_NR<double>>; #ifdef FPLLL_WITH_LONG_DOUBLE template class ExternalEnumeration<Z_NR<mpz_t>, FP_NR<long double>>; #endif #ifdef FPLLL_WITH_QD template class ExternalEnumeration<Z_NR<mpz_t>, FP_NR<dd_real>>; template class ExternalEnumeration<Z_NR<mpz_t>, FP_NR<qd_real>>; #endif #ifdef FPLLL_WITH_DPE template class ExternalEnumeration<Z_NR<mpz_t>, FP_NR<dpe_t>>; #endif template class ExternalEnumeration<Z_NR<mpz_t>, FP_NR<mpfr_t>>; template class ExternalEnumeration<Z_NR<long>, FP_NR<double>>; #ifdef FPLLL_WITH_LONG_DOUBLE template class ExternalEnumeration<Z_NR<long>, FP_NR<long double>>; #endif #ifdef FPLLL_WITH_QD template class ExternalEnumeration<Z_NR<long>, FP_NR<dd_real>>; template class ExternalEnumeration<Z_NR<long>, FP_NR<qd_real>>; #endif #ifdef FPLLL_WITH_DPE template class ExternalEnumeration<Z_NR<long>, FP_NR<dpe_t>>; #endif template class ExternalEnumeration<Z_NR<long>, FP_NR<mpfr_t>>; FPLLL_END_NAMESPACE
28.745856
111
0.648664
Hyper5phere
c902e5178700b51e13502179ec3c90727d3221f2
2,215
cpp
C++
src/controls/while_do_else_node.cpp
BehaviorTree/BehaviorTreeCPP
a5411c978ec976f66d83b1df5aa4dd7c632a142c
[ "MIT" ]
null
null
null
src/controls/while_do_else_node.cpp
BehaviorTree/BehaviorTreeCPP
a5411c978ec976f66d83b1df5aa4dd7c632a142c
[ "MIT" ]
null
null
null
src/controls/while_do_else_node.cpp
BehaviorTree/BehaviorTreeCPP
a5411c978ec976f66d83b1df5aa4dd7c632a142c
[ "MIT" ]
null
null
null
/* Copyright (C) 2020 Davide Faconti - All Rights Reserved * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "behaviortree_cpp_v3/controls/while_do_else_node.h" namespace BT { WhileDoElseNode::WhileDoElseNode(const std::string &name) : ControlNode::ControlNode(name, {} ) { setRegistrationID("WhileDoElse"); } void WhileDoElseNode::halt() { ControlNode::halt(); } NodeStatus WhileDoElseNode::tick() { const size_t children_count = children_nodes_.size(); if(children_count != 3) { throw std::logic_error("WhileDoElse must have 3 children"); } setStatus(NodeStatus::RUNNING); NodeStatus condition_status = children_nodes_[0]->executeTick(); if (condition_status == NodeStatus::RUNNING) { return condition_status; } NodeStatus status = NodeStatus::IDLE; if (condition_status == NodeStatus::SUCCESS) { haltChild(2); status = children_nodes_[1]->executeTick(); } else if (condition_status == NodeStatus::FAILURE) { haltChild(1); status = children_nodes_[2]->executeTick(); } if (status == NodeStatus::RUNNING) { return NodeStatus::RUNNING; } else { haltChildren(); return status; } } } // namespace BT
30.342466
161
0.733183
BehaviorTree
c903e520a3785864c52ee95e51d038ba4227aca0
382
cpp
C++
Exercicios/19-08/Exercicio5.cpp
ismaellimadb/Programas-C-
cc626ef3447f699ed8ff9d7619dd78100f299612
[ "Apache-2.0" ]
null
null
null
Exercicios/19-08/Exercicio5.cpp
ismaellimadb/Programas-C-
cc626ef3447f699ed8ff9d7619dd78100f299612
[ "Apache-2.0" ]
null
null
null
Exercicios/19-08/Exercicio5.cpp
ismaellimadb/Programas-C-
cc626ef3447f699ed8ff9d7619dd78100f299612
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <stdlib.h> main() { float t,v,gas,dis; printf("\nDigite o Tempo da viagem em horas\n"); scanf("%f",&t); printf("\nDigite a Velocidade em Km/h\n"); scanf("%f",&v); dis=t*v; gas=dis/2; printf("\nA distancia percorrida pelo automovel foi: %1.f Km\n",dis); printf("\nFoi consumido %.1f litros de combustivel na viagem\n\n",gas); system("pause"); }
23.875
72
0.65445
ismaellimadb
c9085418d4c0c6593bab97d45c43cc0258ba8683
17,176
cpp
C++
src/training/train.cpp
hjchai/NP_extend
da207e9263ebdc3295bff533b2314a122620e2d9
[ "Apache-2.0" ]
null
null
null
src/training/train.cpp
hjchai/NP_extend
da207e9263ebdc3295bff533b2314a122620e2d9
[ "Apache-2.0" ]
null
null
null
src/training/train.cpp
hjchai/NP_extend
da207e9263ebdc3295bff533b2314a122620e2d9
[ "Apache-2.0" ]
null
null
null
/* Copyright 2014 Software Reliability Lab, ETH Zurich 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 <string> #include <fstream> #include <functional> #include <mutex> #include <thread> #include "base.h" #include "gflags/gflags.h" #include "glog/logging.h" #include "jsoncpp/json/json.h" #include "graph_inference.h" #include "stringprintf.h" #include "stringset.h" #include "readerutil.h" DEFINE_string(input, "testdata", "Input file with JSON objects regarding training data"); DEFINE_string(out_model, "model", "File prefix for output models"); DEFINE_bool(hogwild, true, "Whether to use Hogwild parallel training."); DEFINE_int32(num_threads, 8, "Number of threads to use."); DEFINE_int32(num_training_passes, 24, "Number of passes in training."); DEFINE_double(start_learning_rate, 0.1, "Initial learning rate"); DEFINE_double(stop_learning_rate, 0.0001, "Stop learning if learning rate falls below the value"); DEFINE_double(regularization_const, 2.0, "Regularization constant. The higher, the more regularization."); DEFINE_double(svm_margin, 0.1, "SVM Margin = Penalty for keeping equal labels as in the training data during training."); DEFINE_int32(cross_validation_folds, 0, "If more than 1, cross-validation is performed with the specified number of folds"); DEFINE_bool(print_confusion, false, "Print confusion statistics instead of training."); DEFINE_bool(train_multiclass_classifier, false, "Perform training by base multiclass classifier."); typedef std::function<void(const Json::Value&, const Json::Value&)> InputProcessor; void ForeachInput(RecordInput* input, InputProcessor proc) { std::unique_ptr<InputRecordReader> reader(input->CreateReader()); Json::Reader jsonreader; while (!reader->ReachedEnd()) { std::string line; reader->Read(&line); if (line.empty()) continue; Json::Value v; if (!jsonreader.parse(line, v, false)) { LOG(ERROR) << "Could not parse input: " << jsonreader.getFormatedErrorMessages(); } else { proc(v["query"], v["assign"]); } } } void ProcessLinesParallel(InputRecordReader* reader, InputProcessor proc) { std::string line; Json::Reader jsonreader; while (!reader->ReachedEnd()) { std::string line; reader->Read(&line); if (line.empty()) continue; Json::Value v; if (!jsonreader.parse(line, v, false)) { LOG(ERROR) << "Could not parse input: " << jsonreader.getFormatedErrorMessages() << "\n" << line; } else { proc(v["query"], v["assign"]); } } } typedef std::function<void(const std::string&)> RawInputProcessor; void ProcessRawLinesParallel(InputRecordReader* reader, RawInputProcessor proc) { std::string line; while (!reader->ReachedEnd()) { std::string line; reader->Read(&line); if (line.empty()) continue; proc(line); } } void ParallelForeachRawInput(RecordInput* input, RawInputProcessor proc) { // Do parallel ForEach std::unique_ptr<InputRecordReader> reader(input->CreateReader()); std::vector<std::thread> threads; for (int i = 0; i < FLAGS_num_threads; ++i) { threads.push_back(std::thread(std::bind(&ProcessRawLinesParallel, reader.get(), proc))); } for (auto& thread : threads){ thread.join(); } } void ParallelForeachInput(RecordInput* input, InputProcessor proc) { if (!FLAGS_hogwild) { ForeachInput(input, proc); return; } // Do parallel ForEach std::unique_ptr<InputRecordReader> reader(input->CreateReader()); std::vector<std::thread> threads; for (int i = 0; i < FLAGS_num_threads; ++i) { threads.push_back(std::thread(std::bind(&ProcessLinesParallel, reader.get(), proc))); } for (auto& thread : threads){ thread.join(); } } void InitTrain(RecordInput* input, GraphInference* inference) { int count = 0; std::mutex mutex; ParallelForeachInput(input, [&inference,&count,&mutex](const Json::Value& query, const Json::Value& assign) { std::lock_guard<std::mutex> lock(mutex); inference->AddQueryToModel(query, assign); ++count; }); LOG(INFO) << "Loaded " << count << " training data samples."; inference->PrepareForInference(); } void TestInference(RecordInput* input, GraphInference* inference) { int64 start_time = GetCurrentTimeMicros(); double score_gain = 0; // int count = 0; ForeachInput(input, [&](const Json::Value& query, const Json::Value& assign) { // if (count >= 10) return; // count++; Nice2Query* q = inference->CreateQuery(); q->FromJSON(query); Nice2Assignment* a = inference->CreateAssignment(q); a->FromJSON(assign); double start_score = inference->GetAssignmentScore(a); inference->MapInference(q, a); score_gain += inference->GetAssignmentScore(a) - start_score; delete a; delete q; }); int64 end_time = GetCurrentTimeMicros(); LOG(INFO) << "Inference took " << (end_time - start_time) / 1000 << "ms for gain of " << score_gain << "."; } void Train(RecordInput* input, GraphInference* inference, int fold_id) { std::ofstream outfile; if(fold_id == 0){ outfile.open("log/Rate_per_pass_"+std::to_string(FLAGS_cross_validation_folds) +"_"+std::to_string(FLAGS_start_learning_rate) +"_"+std::to_string(FLAGS_regularization_const) +"_"+std::to_string(FLAGS_svm_margin) +"_log.txt"); outfile<< "learning_rate=" << std::fixed << FLAGS_start_learning_rate << ' ' << "regularization_const=" << std::fixed << FLAGS_regularization_const << ' ' << "svm_margin=" << std::fixed << FLAGS_svm_margin << std::endl; } else outfile.open("log/Rate_per_pass_"+std::to_string(FLAGS_cross_validation_folds) +"_"+std::to_string(FLAGS_start_learning_rate) +"_"+std::to_string(FLAGS_regularization_const) +"_"+std::to_string(FLAGS_svm_margin) +"_log.txt", std::ofstream::app); outfile << "Fold: " << fold_id << std::endl; outfile << "Pass" << '\t' << "Learning rate" << '\t' << "Error rate" << std::endl; inference->SSVMInit(FLAGS_regularization_const, FLAGS_svm_margin); double learning_rate = FLAGS_start_learning_rate; LOG(INFO) << "Starting training with --start_learning_rate=" << std::fixed << FLAGS_start_learning_rate << ", --regularization_const=" << std::fixed << FLAGS_regularization_const << " and --svm_margin=" << std::fixed << FLAGS_svm_margin; double last_error_rate = 1.0; for (int pass = 0; pass < FLAGS_num_training_passes; ++pass) { double error_rate = 0.0; GraphInference backup_inference(*inference); int64 start_time = GetCurrentTimeMicros(); PrecisionStats stats; ParallelForeachInput(input, [&inference,&stats,learning_rate](const Json::Value& query, const Json::Value& assign) { std::unique_ptr<Nice2Query> q(inference->CreateQuery()); q->FromJSON(query); std::unique_ptr<Nice2Assignment> a(inference->CreateAssignment(q.get())); a->FromJSON(assign); inference->SSVMLearn(q.get(), a.get(), learning_rate, &stats); }); //inference->PrintDebugInfo(); int64 end_time = GetCurrentTimeMicros(); LOG(INFO) << "Training pass took " << (end_time - start_time) / 1000 << "ms."; LOG(INFO) << "Correct " << stats.correct_labels << " vs " << stats.incorrect_labels << " incorrect labels."; error_rate = stats.incorrect_labels / (static_cast<double>(stats.incorrect_labels + stats.correct_labels)); LOG(INFO) << "Pass " << pass << " with learning rate " << learning_rate << " has error rate of " << std::fixed << error_rate; outfile << pass << '\t' << std::fixed << learning_rate << '\t' << std::fixed << error_rate << std::endl; if (error_rate > last_error_rate) { LOG(INFO) << "Reverting last pass."; learning_rate *= 0.5; // Halve the learning rate. *inference = backup_inference; if (learning_rate < FLAGS_stop_learning_rate) break; // Stop learning in this case. } else { last_error_rate = error_rate; } inference->PrepareForInference(); } outfile.close(); } void Train(RecordInput* input, GraphInference* inference) { inference->SSVMInit(FLAGS_regularization_const, FLAGS_svm_margin); double learning_rate = FLAGS_start_learning_rate; LOG(INFO) << "Starting training with --start_learning_rate=" << std::fixed << FLAGS_start_learning_rate << ", --regularization_const=" << std::fixed << FLAGS_regularization_const << " and --svm_margin=" << std::fixed << FLAGS_svm_margin; double last_error_rate = 1.0; for (int pass = 0; pass < FLAGS_num_training_passes; ++pass) { double error_rate = 0.0; GraphInference backup_inference(*inference); int64 start_time = GetCurrentTimeMicros(); PrecisionStats stats; ParallelForeachInput(input, [&inference,&stats,learning_rate](const Json::Value& query, const Json::Value& assign) { std::unique_ptr<Nice2Query> q(inference->CreateQuery()); q->FromJSON(query); std::unique_ptr<Nice2Assignment> a(inference->CreateAssignment(q.get())); a->FromJSON(assign); inference->SSVMLearn(q.get(), a.get(), learning_rate, &stats); }); int64 end_time = GetCurrentTimeMicros(); LOG(INFO) << "Training pass took " << (end_time - start_time) / 1000 << "ms."; LOG(INFO) << "Correct " << stats.correct_labels << " vs " << stats.incorrect_labels << " incorrect labels."; error_rate = stats.incorrect_labels / (static_cast<double>(stats.incorrect_labels + stats.correct_labels)); LOG(INFO) << "Pass " << pass << " with learning rate " << learning_rate << " has error rate of " << std::fixed << error_rate; if (error_rate > last_error_rate) { LOG(INFO) << "Reverting last pass."; learning_rate *= 0.5; // Halve the learning rate. *inference = backup_inference; if (learning_rate < FLAGS_stop_learning_rate) break; // Stop learning in this case. } else { last_error_rate = error_rate; } inference->PrepareForInference(); } } void PrintConfusion() { std::unique_ptr<RecordInput> input(new FileRecordInput(FLAGS_input)); NodeConfusionStats confusion_stats; ForeachInput(input.get(), [&confusion_stats](const Json::Value& query, const Json::Value& assign) { GraphInference inference; inference.AddQueryToModel(query, assign); std::unique_ptr<Nice2Query> q(inference.CreateQuery()); q->FromJSON(query); std::unique_ptr<Nice2Assignment> a(inference.CreateAssignment(q.get())); a->FromJSON(assign); inference.PrintConfusionStatistics(q.get(), a.get(), &confusion_stats); LOG(INFO) << "Confusion statistics. non-confusable nodes:" << confusion_stats.num_non_confusable_nodes << ", confusable nodes:" << confusion_stats.num_confusable_nodes << ". Num expected confusion errors:" << confusion_stats.num_expected_confusions; }); } void Evaluate(RecordInput* evaluation_data, GraphInference* inference, PrecisionStats* total_stats, int fold_id) { int64 start_time = GetCurrentTimeMicros(); PrecisionStats stats; ParallelForeachInput(evaluation_data, [&inference,&stats](const Json::Value& query, const Json::Value& assign) { std::unique_ptr<Nice2Query> q(inference->CreateQuery()); q->FromJSON(query); std::unique_ptr<Nice2Assignment> a(inference->CreateAssignment(q.get())); a->FromJSON(assign); std::unique_ptr<Nice2Assignment> refa(inference->CreateAssignment(q.get())); refa->FromJSON(assign); a->ClearInferredAssignment(); inference->MapInference(q.get(), a.get()); a->CompareAssignments(refa.get(), &stats); }); int64 end_time = GetCurrentTimeMicros(); LOG(INFO) << "Evaluation pass took " << (end_time - start_time) / 1000 << "ms."; LOG(INFO) << "Correct " << stats.correct_labels << " vs " << stats.incorrect_labels << " incorrect labels"; double error_rate = stats.incorrect_labels / (static_cast<double>(stats.incorrect_labels + stats.correct_labels)); LOG(INFO) << "Error rate of " << std::fixed << error_rate; std::ofstream outfile; outfile.open("log/Rate_per_pass_"+std::to_string(FLAGS_cross_validation_folds) +"_"+std::to_string(FLAGS_start_learning_rate) +"_"+std::to_string(FLAGS_regularization_const) +"_"+std::to_string(FLAGS_svm_margin) +"_log.txt", std::ofstream::app); outfile << "Correct " << stats.correct_labels << " vs " << stats.incorrect_labels << " incorrect labels" << std::endl; outfile << "Error rate of " << std::fixed << error_rate << std::endl; outfile << "========================================" << std::endl; outfile.close(); total_stats->AddStats(stats); } void Evaluate(RecordInput* evaluation_data, GraphInference* inference, PrecisionStats* total_stats) { int64 start_time = GetCurrentTimeMicros(); PrecisionStats stats; ParallelForeachInput(evaluation_data, [&inference,&stats](const Json::Value& query, const Json::Value& assign) { std::unique_ptr<Nice2Query> q(inference->CreateQuery()); q->FromJSON(query); std::unique_ptr<Nice2Assignment> a(inference->CreateAssignment(q.get())); a->FromJSON(assign); std::unique_ptr<Nice2Assignment> refa(inference->CreateAssignment(q.get())); refa->FromJSON(assign); a->ClearInferredAssignment(); inference->MapInference(q.get(), a.get()); a->CompareAssignments(refa.get(), &stats); }); int64 end_time = GetCurrentTimeMicros(); LOG(INFO) << "Evaluation pass took " << (end_time - start_time) / 1000 << "ms."; LOG(INFO) << "Correct " << stats.correct_labels << " vs " << stats.incorrect_labels << " incorrect labels"; double error_rate = stats.incorrect_labels / (static_cast<double>(stats.incorrect_labels + stats.correct_labels)); LOG(INFO) << "Error rate of " << std::fixed << error_rate; total_stats->AddStats(stats); } int main(int argc, char** argv) { google::InstallFailureSignalHandler(); google::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); if (FLAGS_cross_validation_folds > 1) { PrecisionStats total_stats; for (int fold_id = 0; fold_id < FLAGS_cross_validation_folds; ++fold_id) { GraphInference inference; std::unique_ptr<RecordInput> training_data( new ShuffledCacheInput(new CrossValidationInput(new FileRecordInput(FLAGS_input), fold_id, FLAGS_cross_validation_folds, true))); std::unique_ptr<RecordInput> validation_data( new ShuffledCacheInput(new CrossValidationInput(new FileRecordInput(FLAGS_input), fold_id, FLAGS_cross_validation_folds, false))); LOG(INFO) << "Training fold " << fold_id; InitTrain(training_data.get(), &inference); Train(training_data.get(), &inference, fold_id); LOG(INFO) << "Evaluating fold " << fold_id; Evaluate(validation_data.get(), &inference, &total_stats, fold_id); } // Output results of cross-validation (no model is saved in this mode). LOG(INFO) << "========================================"; LOG(INFO) << "Cross-validation done"; LOG(INFO) << "Correct " << total_stats.correct_labels << " vs " << total_stats.incorrect_labels << " incorrect labels for the whole dataset"; double error_rate = total_stats.incorrect_labels / (static_cast<double>(total_stats.incorrect_labels + total_stats.correct_labels)); LOG(INFO) << "Error rate of " << std::fixed << error_rate; std::ofstream outfile; outfile.open("log/Rate_per_pass_"+std::to_string(FLAGS_cross_validation_folds) +"_"+std::to_string(FLAGS_start_learning_rate) +"_"+std::to_string(FLAGS_regularization_const) +"_"+std::to_string(FLAGS_svm_margin) +"_log.txt", std::ofstream::app); outfile << "Cross-validation done" << std::endl; outfile << "In total:" << std::endl; outfile << "Correct " << total_stats.correct_labels << " vs " << total_stats.incorrect_labels << " incorrect labels for the whole dataset" << std::endl; outfile << "Error rate of " << std::fixed << error_rate << std::endl; outfile.close(); std::ofstream outfile1; outfile1.open("log/bp_result.txt",std::ofstream::app); outfile1 << std::fixed << error_rate << std::endl; outfile1.close(); } else if (FLAGS_print_confusion) { PrintConfusion(); } else { LOG(INFO) << "Running structured training..."; // Structured training. GraphInference inference; std::unique_ptr<RecordInput> input(new ShuffledCacheInput(new FileRecordInput(FLAGS_input))); InitTrain(input.get(), &inference); Train(input.get(), &inference); // Save the model in the regular training. inference.SaveModel(FLAGS_out_model); } return 0; }
41.790754
156
0.684269
hjchai
c90b7bdbf24584d772dff1698da8a96bf446e2fd
1,372
cpp
C++
Lab2/SO_SNDBUF.cpp
mohitreddy1996/Distributed-Computing-Lab
a819a3245c14c2faa81cda89db45cdc368813828
[ "MIT" ]
null
null
null
Lab2/SO_SNDBUF.cpp
mohitreddy1996/Distributed-Computing-Lab
a819a3245c14c2faa81cda89db45cdc368813828
[ "MIT" ]
null
null
null
Lab2/SO_SNDBUF.cpp
mohitreddy1996/Distributed-Computing-Lab
a819a3245c14c2faa81cda89db45cdc368813828
[ "MIT" ]
null
null
null
/* * Sets or gets the maximum socket send buffer in bytes. The kernel doubles * this value (to allow space for bookkeeping overhead) when it is set using setsockopt. * Minimum value for this option is 2048. This is the doubled value. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> int main() { int socket_; int send_buff; socklen_t send_buff_len = sizeof(send_buff); if((socket_ = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { perror("socket()"); exit(0); } if(getsockopt(socket_, SOL_SOCKET, SO_SNDBUF, &send_buff, &send_buff_len) < 0) { perror("getsockopt()"); close(socket_); exit(0); } // initially the value is set to 2048 (doubled). Therefore ans = 2048*int_bytes. printf("SO_SNDBUFF value is %d\n", send_buff); printf("Setting SO_SNDBUF to 2500 bytes.\n"); send_buff = 2500; send_buff_len = sizeof(send_buff); if(setsockopt(socket_, SOL_SOCKET, SO_SNDBUF, &send_buff, send_buff_len) < 0) { perror("setsockopt()"); close(socket_); exit(0); } if(getsockopt(socket_, SOL_SOCKET, SO_SNDBUF, &send_buff, &send_buff_len) < 0) { perror("getsockopt()"); close(socket_); exit(0); } printf("SO_SNDBUF is %d\n", send_buff); close(socket_); return 0; }
26.384615
88
0.65379
mohitreddy1996
c90e0903e5169ec8af3bbcadbed687ad3bd0f253
27,869
cpp
C++
src/gpu/GrAHardwareBufferImageGenerator.cpp
CarbonROM/android_external_skqp
72c9856641fddcfe46a1c2287550604061f1eefd
[ "BSD-3-Clause" ]
null
null
null
src/gpu/GrAHardwareBufferImageGenerator.cpp
CarbonROM/android_external_skqp
72c9856641fddcfe46a1c2287550604061f1eefd
[ "BSD-3-Clause" ]
null
null
null
src/gpu/GrAHardwareBufferImageGenerator.cpp
CarbonROM/android_external_skqp
72c9856641fddcfe46a1c2287550604061f1eefd
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" #if defined(SK_BUILD_FOR_ANDROID) && __ANDROID_API__ >= 26 #define GL_GLEXT_PROTOTYPES #define EGL_EGLEXT_PROTOTYPES #include "GrAHardwareBufferImageGenerator.h" #include <android/hardware_buffer.h> #include "GrBackendSurface.h" #include "GrContext.h" #include "GrContextPriv.h" #include "GrProxyProvider.h" #include "GrResourceCache.h" #include "GrResourceProvider.h" #include "GrResourceProviderPriv.h" #include "GrTexture.h" #include "GrTextureProxy.h" #include "SkMessageBus.h" #include "gl/GrGLDefines.h" #include "gl/GrGLTypes.h" #include <EGL/egl.h> #include <EGL/eglext.h> #include <GLES/gl.h> #include <GLES/glext.h> #ifdef SK_VULKAN #include "vk/GrVkExtensions.h" #include "vk/GrVkGpu.h" #endif #define PROT_CONTENT_EXT_STR "EGL_EXT_protected_content" #define EGL_PROTECTED_CONTENT_EXT 0x32C0 static bool can_import_protected_content_eglimpl() { EGLDisplay dpy = eglGetDisplay(EGL_DEFAULT_DISPLAY); const char* exts = eglQueryString(dpy, EGL_EXTENSIONS); size_t cropExtLen = strlen(PROT_CONTENT_EXT_STR); size_t extsLen = strlen(exts); bool equal = !strcmp(PROT_CONTENT_EXT_STR, exts); bool atStart = !strncmp(PROT_CONTENT_EXT_STR " ", exts, cropExtLen+1); bool atEnd = (cropExtLen+1) < extsLen && !strcmp(" " PROT_CONTENT_EXT_STR, exts + extsLen - (cropExtLen+1)); bool inMiddle = strstr(exts, " " PROT_CONTENT_EXT_STR " "); return equal || atStart || atEnd || inMiddle; } static bool can_import_protected_content(GrContext* context) { if (GrBackendApi::kOpenGL == context->backend()) { // Only compute whether the extension is present once the first time this // function is called. static bool hasIt = can_import_protected_content_eglimpl(); return hasIt; } return false; } std::unique_ptr<SkImageGenerator> GrAHardwareBufferImageGenerator::Make( AHardwareBuffer* graphicBuffer, SkAlphaType alphaType, sk_sp<SkColorSpace> colorSpace, GrSurfaceOrigin surfaceOrigin) { AHardwareBuffer_Desc bufferDesc; AHardwareBuffer_describe(graphicBuffer, &bufferDesc); SkColorType colorType; switch (bufferDesc.format) { case AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM: case AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM: colorType = kRGBA_8888_SkColorType; break; case AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT: colorType = kRGBA_F16_SkColorType; break; case AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM: colorType = kRGB_565_SkColorType; break; case AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM: colorType = kRGB_888x_SkColorType; break; case AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM: colorType = kRGBA_1010102_SkColorType; break; default: // Given that we only use this texture as a source, colorType will not impact how Skia uses // the texture. The only potential affect this is anticipated to have is that for some // format types if we are not bound as an OES texture we may get invalid results for SKP // capture if we read back the texture. colorType = kRGBA_8888_SkColorType; break; } SkImageInfo info = SkImageInfo::Make(bufferDesc.width, bufferDesc.height, colorType, alphaType, std::move(colorSpace)); bool createProtectedImage = 0 != (bufferDesc.usage & AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT); return std::unique_ptr<SkImageGenerator>(new GrAHardwareBufferImageGenerator( info, graphicBuffer, alphaType, createProtectedImage, bufferDesc.format, surfaceOrigin)); } GrAHardwareBufferImageGenerator::GrAHardwareBufferImageGenerator(const SkImageInfo& info, AHardwareBuffer* hardwareBuffer, SkAlphaType alphaType, bool isProtectedContent, uint32_t bufferFormat, GrSurfaceOrigin surfaceOrigin) : INHERITED(info) , fHardwareBuffer(hardwareBuffer) , fBufferFormat(bufferFormat) , fIsProtectedContent(isProtectedContent) , fSurfaceOrigin(surfaceOrigin) { AHardwareBuffer_acquire(fHardwareBuffer); } GrAHardwareBufferImageGenerator::~GrAHardwareBufferImageGenerator() { AHardwareBuffer_release(fHardwareBuffer); } /////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef SK_VULKAN class VulkanCleanupHelper { public: VulkanCleanupHelper(GrVkGpu* gpu, VkImage image, VkDeviceMemory memory) : fDevice(gpu->device()) , fImage(image) , fMemory(memory) , fDestroyImage(gpu->vkInterface()->fFunctions.fDestroyImage) , fFreeMemory(gpu->vkInterface()->fFunctions.fFreeMemory) {} ~VulkanCleanupHelper() { fDestroyImage(fDevice, fImage, nullptr); fFreeMemory(fDevice, fMemory, nullptr); } private: VkDevice fDevice; VkImage fImage; VkDeviceMemory fMemory; PFN_vkDestroyImage fDestroyImage; PFN_vkFreeMemory fFreeMemory; }; void GrAHardwareBufferImageGenerator::DeleteVkImage(void* context) { VulkanCleanupHelper* cleanupHelper = static_cast<VulkanCleanupHelper*>(context); delete cleanupHelper; } #define VK_CALL(X) gpu->vkInterface()->fFunctions.f##X; static GrBackendTexture make_vk_backend_texture( GrContext* context, AHardwareBuffer* hardwareBuffer, int width, int height, GrPixelConfig config, GrAHardwareBufferImageGenerator::DeleteImageProc* deleteProc, GrAHardwareBufferImageGenerator::DeleteImageCtx* deleteCtx, bool isProtectedContent, const GrBackendFormat& backendFormat) { SkASSERT(context->backend() == GrBackendApi::kVulkan); GrVkGpu* gpu = static_cast<GrVkGpu*>(context->contextPriv().getGpu()); VkPhysicalDevice physicalDevice = gpu->physicalDevice(); VkDevice device = gpu->device(); SkASSERT(gpu); if (!gpu->vkCaps().supportsAndroidHWBExternalMemory()) { return GrBackendTexture(); } SkASSERT(backendFormat.getVkFormat()); VkFormat format = *backendFormat.getVkFormat(); VkResult err; VkAndroidHardwareBufferFormatPropertiesANDROID hwbFormatProps; hwbFormatProps.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID; hwbFormatProps.pNext = nullptr; VkAndroidHardwareBufferPropertiesANDROID hwbProps; hwbProps.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID; hwbProps.pNext = &hwbFormatProps; err = VK_CALL(GetAndroidHardwareBufferProperties(device, hardwareBuffer, &hwbProps)); if (VK_SUCCESS != err) { return GrBackendTexture(); } VkExternalFormatANDROID externalFormat; externalFormat.sType = VK_STRUCTURE_TYPE_EXTERNAL_FORMAT_ANDROID; externalFormat.pNext = nullptr; externalFormat.externalFormat = 0; // If this is zero it is as if we aren't using this struct. const GrVkYcbcrConversionInfo* ycbcrConversion = backendFormat.getVkYcbcrConversionInfo(); if (!ycbcrConversion) { return GrBackendTexture(); } if (hwbFormatProps.format != VK_FORMAT_UNDEFINED) { // TODO: We should not assume the transfer features here and instead should have a way for // Ganesh's tracking of intenral images to report whether or not they support transfers. SkASSERT(SkToBool(VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT & hwbFormatProps.formatFeatures) && SkToBool(VK_FORMAT_FEATURE_TRANSFER_SRC_BIT & hwbFormatProps.formatFeatures) && SkToBool(VK_FORMAT_FEATURE_TRANSFER_DST_BIT & hwbFormatProps.formatFeatures)); SkASSERT(!ycbcrConversion->isValid()); } else { SkASSERT(ycbcrConversion->isValid()); // We have an external only format SkASSERT(SkToBool(VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT & hwbFormatProps.formatFeatures)); SkASSERT(format == VK_FORMAT_UNDEFINED); SkASSERT(hwbFormatProps.externalFormat == ycbcrConversion->fExternalFormat); externalFormat.externalFormat = hwbFormatProps.externalFormat; } SkASSERT(format == hwbFormatProps.format); const VkExternalMemoryImageCreateInfo externalMemoryImageInfo{ VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO, // sType &externalFormat, // pNext VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID, // handleTypes }; VkImageUsageFlags usageFlags = VK_IMAGE_USAGE_SAMPLED_BIT; if (format != VK_FORMAT_UNDEFINED) { usageFlags = usageFlags | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; } // TODO: Check the supported tilings vkGetPhysicalDeviceImageFormatProperties2 to see if we have // to use linear. Add better linear support throughout Ganesh. VkImageTiling tiling = VK_IMAGE_TILING_OPTIMAL; const VkImageCreateInfo imageCreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, // sType &externalMemoryImageInfo, // pNext 0, // VkImageCreateFlags VK_IMAGE_TYPE_2D, // VkImageType format, // VkFormat { (uint32_t)width, (uint32_t)height, 1 }, // VkExtent3D 1, // mipLevels 1, // arrayLayers VK_SAMPLE_COUNT_1_BIT, // samples tiling, // VkImageTiling usageFlags, // VkImageUsageFlags VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode 0, // queueFamilyCount 0, // pQueueFamilyIndices VK_IMAGE_LAYOUT_UNDEFINED, // initialLayout }; VkImage image; err = VK_CALL(CreateImage(device, &imageCreateInfo, nullptr, &image)); if (VK_SUCCESS != err) { return GrBackendTexture(); } VkPhysicalDeviceMemoryProperties2 phyDevMemProps; phyDevMemProps.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2; phyDevMemProps.pNext = nullptr; uint32_t typeIndex = 0; uint32_t heapIndex = 0; bool foundHeap = false; VK_CALL(GetPhysicalDeviceMemoryProperties2(physicalDevice, &phyDevMemProps)); uint32_t memTypeCnt = phyDevMemProps.memoryProperties.memoryTypeCount; for (uint32_t i = 0; i < memTypeCnt && !foundHeap; ++i) { if (hwbProps.memoryTypeBits & (1 << i)) { const VkPhysicalDeviceMemoryProperties& pdmp = phyDevMemProps.memoryProperties; uint32_t supportedFlags = pdmp.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; if (supportedFlags == VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { typeIndex = i; heapIndex = pdmp.memoryTypes[i].heapIndex; foundHeap = true; } } } if (!foundHeap) { VK_CALL(DestroyImage(device, image, nullptr)); return GrBackendTexture(); } VkImportAndroidHardwareBufferInfoANDROID hwbImportInfo; hwbImportInfo.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID; hwbImportInfo.pNext = nullptr; hwbImportInfo.buffer = hardwareBuffer; VkMemoryDedicatedAllocateInfo dedicatedAllocInfo; dedicatedAllocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO; dedicatedAllocInfo.pNext = &hwbImportInfo; dedicatedAllocInfo.image = image; dedicatedAllocInfo.buffer = VK_NULL_HANDLE; VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, // sType &dedicatedAllocInfo, // pNext hwbProps.allocationSize, // allocationSize typeIndex, // memoryTypeIndex }; VkDeviceMemory memory; err = VK_CALL(AllocateMemory(device, &allocInfo, nullptr, &memory)); if (VK_SUCCESS != err) { VK_CALL(DestroyImage(device, image, nullptr)); return GrBackendTexture(); } VkBindImageMemoryInfo bindImageInfo; bindImageInfo.sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO; bindImageInfo.pNext = nullptr; bindImageInfo.image = image; bindImageInfo.memory = memory; bindImageInfo.memoryOffset = 0; err = VK_CALL(BindImageMemory2(device, 1, &bindImageInfo)); if (VK_SUCCESS != err) { VK_CALL(DestroyImage(device, image, nullptr)); VK_CALL(FreeMemory(device, memory, nullptr)); return GrBackendTexture(); } GrVkImageInfo imageInfo; imageInfo.fImage = image; imageInfo.fAlloc = GrVkAlloc(memory, 0, hwbProps.allocationSize, 0); imageInfo.fImageTiling = tiling; imageInfo.fImageLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageInfo.fFormat = format; imageInfo.fLevelCount = 1; // TODO: This should possibly be VK_QUEUE_FAMILY_FOREIGN_EXT but current Adreno devices do not // support that extension. Or if we know the source of the AHardwareBuffer is not from a // "foreign" device we can leave them as external. imageInfo.fCurrentQueueFamily = VK_QUEUE_FAMILY_EXTERNAL; imageInfo.fYcbcrConversionInfo = *ycbcrConversion; *deleteProc = GrAHardwareBufferImageGenerator::DeleteVkImage; *deleteCtx = new VulkanCleanupHelper(gpu, image, memory); return GrBackendTexture(width, height, imageInfo); } #endif class GLCleanupHelper { public: GLCleanupHelper(GrGLuint texID, EGLImageKHR image, EGLDisplay display) : fTexID(texID) , fImage(image) , fDisplay(display) { } ~GLCleanupHelper() { glDeleteTextures(1, &fTexID); // eglDestroyImageKHR will remove a ref from the AHardwareBuffer eglDestroyImageKHR(fDisplay, fImage); } private: GrGLuint fTexID; EGLImageKHR fImage; EGLDisplay fDisplay; }; void GrAHardwareBufferImageGenerator::DeleteGLTexture(void* context) { GLCleanupHelper* cleanupHelper = static_cast<GLCleanupHelper*>(context); delete cleanupHelper; } static GrBackendTexture make_gl_backend_texture( GrContext* context, AHardwareBuffer* hardwareBuffer, int width, int height, GrPixelConfig config, GrAHardwareBufferImageGenerator::DeleteImageProc* deleteProc, GrAHardwareBufferImageGenerator::DeleteImageCtx* deleteCtx, bool isProtectedContent, const GrBackendFormat& backendFormat) { while (GL_NO_ERROR != glGetError()) {} //clear GL errors EGLClientBuffer clientBuffer = eglGetNativeClientBufferANDROID(hardwareBuffer); EGLint attribs[] = { EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, isProtectedContent ? EGL_PROTECTED_CONTENT_EXT : EGL_NONE, isProtectedContent ? EGL_TRUE : EGL_NONE, EGL_NONE }; EGLDisplay display = eglGetCurrentDisplay(); // eglCreateImageKHR will add a ref to the AHardwareBuffer EGLImageKHR image = eglCreateImageKHR(display, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID, clientBuffer, attribs); if (EGL_NO_IMAGE_KHR == image) { SkDebugf("Could not create EGL image, err = (%#x)", (int) eglGetError() ); return GrBackendTexture(); } GrGLuint texID; glGenTextures(1, &texID); if (!texID) { eglDestroyImageKHR(display, image); return GrBackendTexture(); } glBindTexture(GL_TEXTURE_EXTERNAL_OES, texID); GLenum status = GL_NO_ERROR; if ((status = glGetError()) != GL_NO_ERROR) { SkDebugf("glBindTexture failed (%#x)", (int) status); glDeleteTextures(1, &texID); eglDestroyImageKHR(display, image); return GrBackendTexture(); } glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, image); if ((status = glGetError()) != GL_NO_ERROR) { SkDebugf("glEGLImageTargetTexture2DOES failed (%#x)", (int) status); glDeleteTextures(1, &texID); eglDestroyImageKHR(display, image); return GrBackendTexture(); } context->resetContext(kTextureBinding_GrGLBackendState); GrGLTextureInfo textureInfo; textureInfo.fID = texID; SkASSERT(backendFormat.isValid()); textureInfo.fTarget = *backendFormat.getGLTarget(); textureInfo.fFormat = *backendFormat.getGLFormat(); *deleteProc = GrAHardwareBufferImageGenerator::DeleteGLTexture; *deleteCtx = new GLCleanupHelper(texID, image, display); return GrBackendTexture(width, height, GrMipMapped::kNo, textureInfo); } static GrBackendTexture make_backend_texture( GrContext* context, AHardwareBuffer* hardwareBuffer, int width, int height, GrPixelConfig config, GrAHardwareBufferImageGenerator::DeleteImageProc* deleteProc, GrAHardwareBufferImageGenerator::DeleteImageCtx* deleteCtx, bool isProtectedContent, const GrBackendFormat& backendFormat) { if (context->abandoned()) { return GrBackendTexture(); } bool createProtectedImage = isProtectedContent && can_import_protected_content(context); if (GrBackendApi::kOpenGL == context->backend()) { return make_gl_backend_texture(context, hardwareBuffer, width, height, config, deleteProc, deleteCtx, createProtectedImage, backendFormat); } else { SkASSERT(GrBackendApi::kVulkan == context->backend()); #ifdef SK_VULKAN // Currently we don't support protected images on vulkan SkASSERT(!createProtectedImage); return make_vk_backend_texture(context, hardwareBuffer, width, height, config, deleteProc, deleteCtx, createProtectedImage, backendFormat); #else return GrBackendTexture(); #endif } } GrBackendFormat get_backend_format(GrContext* context, AHardwareBuffer* hardwareBuffer, GrBackendApi backend, uint32_t bufferFormat) { if (backend == GrBackendApi::kOpenGL) { switch (bufferFormat) { //TODO: find out if we can detect, which graphic buffers support GR_GL_TEXTURE_2D case AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM: case AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM: return GrBackendFormat::MakeGL(GR_GL_RGBA8, GR_GL_TEXTURE_EXTERNAL); case AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT: return GrBackendFormat::MakeGL(GR_GL_RGBA16F, GR_GL_TEXTURE_EXTERNAL); case AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM: return GrBackendFormat::MakeGL(GR_GL_RGB565, GR_GL_TEXTURE_EXTERNAL); case AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM: return GrBackendFormat::MakeGL(GR_GL_RGB10_A2, GR_GL_TEXTURE_EXTERNAL); case AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM: return GrBackendFormat::MakeGL(GR_GL_RGB8, GR_GL_TEXTURE_EXTERNAL); default: return GrBackendFormat::MakeGL(GR_GL_RGBA8, GR_GL_TEXTURE_EXTERNAL); } } else if (backend == GrBackendApi::kVulkan) { #ifdef SK_VULKAN switch (bufferFormat) { case AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM: return GrBackendFormat::MakeVk(VK_FORMAT_R8G8B8A8_UNORM); case AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT: return GrBackendFormat::MakeVk(VK_FORMAT_R16G16B16A16_SFLOAT); case AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM: return GrBackendFormat::MakeVk(VK_FORMAT_R5G6B5_UNORM_PACK16); case AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM: return GrBackendFormat::MakeVk(VK_FORMAT_A2B10G10R10_UNORM_PACK32); case AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM: return GrBackendFormat::MakeVk(VK_FORMAT_R8G8B8A8_UNORM); case AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM: return GrBackendFormat::MakeVk(VK_FORMAT_R8G8B8_UNORM); default: { GrVkGpu* gpu = static_cast<GrVkGpu*>(context->contextPriv().getGpu()); SkASSERT(gpu); VkDevice device = gpu->device(); if (!gpu->vkCaps().supportsAndroidHWBExternalMemory()) { return GrBackendFormat(); } VkAndroidHardwareBufferFormatPropertiesANDROID hwbFormatProps; hwbFormatProps.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID; hwbFormatProps.pNext = nullptr; VkAndroidHardwareBufferPropertiesANDROID hwbProps; hwbProps.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID; hwbProps.pNext = &hwbFormatProps; VkResult err = VK_CALL(GetAndroidHardwareBufferProperties(device, hardwareBuffer, &hwbProps)); if (VK_SUCCESS != err) { return GrBackendFormat(); } if (hwbFormatProps.format != VK_FORMAT_UNDEFINED) { return GrBackendFormat(); } GrVkYcbcrConversionInfo ycbcrConversion; ycbcrConversion.fYcbcrModel = hwbFormatProps.suggestedYcbcrModel; ycbcrConversion.fYcbcrRange = hwbFormatProps.suggestedYcbcrRange; ycbcrConversion.fXChromaOffset = hwbFormatProps.suggestedXChromaOffset; ycbcrConversion.fYChromaOffset = hwbFormatProps.suggestedYChromaOffset; ycbcrConversion.fForceExplicitReconstruction = VK_FALSE; ycbcrConversion.fExternalFormat = hwbFormatProps.externalFormat; ycbcrConversion.fExternalFormatFeatures = hwbFormatProps.formatFeatures; if (VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT & hwbFormatProps.formatFeatures) { ycbcrConversion.fChromaFilter = VK_FILTER_LINEAR; } else { ycbcrConversion.fChromaFilter = VK_FILTER_NEAREST; } return GrBackendFormat::MakeVk(ycbcrConversion); } } #else return GrBackendFormat(); #endif } return GrBackendFormat(); } sk_sp<GrTextureProxy> GrAHardwareBufferImageGenerator::makeProxy(GrContext* context) { if (context->abandoned()) { return nullptr; } GrBackendFormat backendFormat = get_backend_format(context, fHardwareBuffer, context->backend(), fBufferFormat); GrPixelConfig pixelConfig = context->contextPriv().caps()->getConfigFromBackendFormat( backendFormat, this->getInfo().colorType()); if (pixelConfig == kUnknown_GrPixelConfig) { return nullptr; } int width = this->getInfo().width(); int height = this->getInfo().height(); GrSurfaceDesc desc; desc.fWidth = width; desc.fHeight = height; desc.fConfig = pixelConfig; GrTextureType textureType = GrTextureType::k2D; if (context->backend() == GrBackendApi::kOpenGL) { textureType = GrTextureType::kExternal; } else if (context->backend() == GrBackendApi::kVulkan) { const VkFormat* format = backendFormat.getVkFormat(); SkASSERT(format); if (*format == VK_FORMAT_UNDEFINED) { textureType = GrTextureType::kExternal; } } auto proxyProvider = context->contextPriv().proxyProvider(); AHardwareBuffer* hardwareBuffer = fHardwareBuffer; AHardwareBuffer_acquire(hardwareBuffer); const bool isProtectedContent = fIsProtectedContent; sk_sp<GrTextureProxy> texProxy = proxyProvider->createLazyProxy( [context, hardwareBuffer, width, height, pixelConfig, isProtectedContent, backendFormat](GrResourceProvider* resourceProvider) { if (!resourceProvider) { AHardwareBuffer_release(hardwareBuffer); return sk_sp<GrTexture>(); } DeleteImageProc deleteImageProc = nullptr; DeleteImageCtx deleteImageCtx = nullptr; GrBackendTexture backendTex = make_backend_texture(context, hardwareBuffer, width, height, pixelConfig, &deleteImageProc, &deleteImageCtx, isProtectedContent, backendFormat); if (!backendTex.isValid()) { return sk_sp<GrTexture>(); } SkASSERT(deleteImageProc && deleteImageCtx); backendTex.fConfig = pixelConfig; // We make this texture cacheable to avoid recreating a GrTexture every time this // is invoked. We know the owning SkIamge will send an invalidation message when the // image is destroyed, so the texture will be removed at that time. sk_sp<GrTexture> tex = resourceProvider->wrapBackendTexture( backendTex, kBorrow_GrWrapOwnership, GrWrapCacheable::kYes, kRead_GrIOType); if (!tex) { deleteImageProc(deleteImageCtx); return sk_sp<GrTexture>(); } if (deleteImageProc) { sk_sp<GrReleaseProcHelper> releaseProcHelper( new GrReleaseProcHelper(deleteImageProc, deleteImageCtx)); tex->setRelease(releaseProcHelper); } return tex; }, backendFormat, desc, fSurfaceOrigin, GrMipMapped::kNo, GrInternalSurfaceFlags::kReadOnly, SkBackingFit::kExact, SkBudgeted::kNo); if (!texProxy) { AHardwareBuffer_release(hardwareBuffer); } return texProxy; } sk_sp<GrTextureProxy> GrAHardwareBufferImageGenerator::onGenerateTexture( GrContext* context, const SkImageInfo& info, const SkIPoint& origin, bool willNeedMipMaps) { sk_sp<GrTextureProxy> texProxy = this->makeProxy(context); if (!texProxy) { return nullptr; } if (0 == origin.fX && 0 == origin.fY && info.width() == this->getInfo().width() && info.height() == this->getInfo().height()) { // If the caller wants the full texture we're done. The caller will handle making a copy for // mip maps if that is required. return texProxy; } // Otherwise, make a copy for the requested subset. SkIRect subset = SkIRect::MakeXYWH(origin.fX, origin.fY, info.width(), info.height()); GrMipMapped mipMapped = willNeedMipMaps ? GrMipMapped::kYes : GrMipMapped::kNo; return GrSurfaceProxy::Copy(context, texProxy.get(), mipMapped, subset, SkBackingFit::kExact, SkBudgeted::kYes); } bool GrAHardwareBufferImageGenerator::onIsValid(GrContext* context) const { if (nullptr == context) { return false; //CPU backend is not supported, because hardware buffer can be swizzled } return GrBackendApi::kOpenGL == context->backend() || GrBackendApi::kVulkan == context->backend(); } #endif //SK_BUILD_FOR_ANDROID_FRAMEWORK
42.161876
100
0.658258
CarbonROM
c91163cc5ff613ab35b1c9002838b13b7ec36ad1
16,452
cpp
C++
Source/MyWindow/WindowData.cpp
favorart/robot-hand
55ea2a74573972a6e5efcf525485e56918d81086
[ "MIT" ]
2
2016-01-16T09:28:40.000Z
2016-04-14T05:21:20.000Z
Source/MyWindow/WindowData.cpp
favorart/robot-hand
55ea2a74573972a6e5efcf525485e56918d81086
[ "MIT" ]
null
null
null
Source/MyWindow/WindowData.cpp
favorart/robot-hand
55ea2a74573972a6e5efcf525485e56918d81086
[ "MIT" ]
null
null
null
#include "StdAfx.h" #include "WindowData.h" #include "Draw.h" #include "HandMotionLawsCustom.h" #include "Position.h" extern bool zoom; using namespace std; using namespace HandMoves; //------------------------------------------------------------------------------- bool RepeatMove (MyWindowData &wd); bool MakeHandMove (MyWindowData &wd); //------------------------------------------------------------------------------- void MyWindowData::TrajectoryFrames::step (Store &store, Hand &hand, const boost::optional<controling_t> controls) { if ( controls.is_initialized () ) { show_ = true; if ( animation ) { controls_ = controling_t{ *controls }; time_ = Hand::frames_t{ 0U }; for ( iter_ = controls_->begin (); (*iter_) != controls_->end () && (**iter_).start == time_; ++(*iter_) ) { hand.step ((**iter_).muscle, (**iter_).last); } ++(*time_); } else { hand.SET_DEFAULT; Point hand_base = hand.position; hand.move (controls->begin (), controls->end (), &trajectory_); // Point hand_base = trajectory_.front (); // wd.trajectory_frames.pop_front (); store.insert (HandMoves::Record (hand.position, hand_base, hand.position, *controls, trajectory_)); // trajectory_.clear (); } } // ============ for ( size_t i = 0U; i < skip_show_steps; ++i ) { // ============ hand.step (); /* !!! WORKING ONLY FOR NEW_HAND !!! */ // ============ /* Auto-drawing trajectory animation */ if ( show_ && animation && time_.is_initialized () ) { if ( ((*iter_) != (*controls_).end ()) && ((**iter_).start == time_) ) { while ( ((*iter_) != (*controls_).end ()) && ((**iter_).start == time_) ) { hand.step ((**iter_).muscle, (**iter_).last); ++(*iter_); } } // ============ if ( hand.moveEnd ) { const Point &hand_pos = hand.position; trajectory_.push_back (hand_pos); // ------------------------------------------- Point base_pos = trajectory_.front (); // wd.trajectory_.pop_front (); store.insert (HandMoves::Record (hand_pos, base_pos, hand_pos, *controls_, trajectory_)); // ------------------------------------------- controls_ = boost::none; // ------------------------------------------- iter_ = boost::none; time_ = boost::none; // ------------------------------------------- break; } else if ( !(*time_ % hand.visitedSaveEach) ) { trajectory_.push_back (hand.position); } // ============ (*time_) += 1U; // ============ } // end if } // end for } void MyWindowData::TrajectoryFrames::draw (HDC hdc, HPEN hPen) const { if ( show_ ) { DrawTrajectory (hdc, trajectory_, hPen); } } void MyWindowData::TrajectoryFrames::clear () { show_ = false; trajectory_.clear (); // ------------------------------------------- controls_ = boost::none; // ------------------------------------------- time_ = boost::none; iter_ = boost::none; } //------------------------------------------------------------------------------- MyWindowData:: MyWindowData () : pWorkerThread (nullptr), // lt (NULL), hand (/* palm */ Point{ -0.75, 1.05 }, /* hand */ Point{ -0.70, 1.00 }, /* arm */ Point{ 0.10, 0.85 }, /* shoulder */ Point{ 0.75, 0.25 }, /* clavicle */ Point{ 0.75, 0.25 }, /* joints_frames */ { { Hand::Elbow,{ // new MotionLaws::ContinuousSlowAcceleration (), // new MotionLaws::ContinuousFastAcceleration (), // new MotionLaws::ContinuousAccelerationThenStabilization (0.25), new MotionLaws::ContinuousAcceleration (), new MotionLaws::ContinuousDeceleration () //, // new MotionLaws::MangoAcceleration (tstring(_T("Resource/ElbowMoveFrames.txt"))), // new MotionLaws::MangoDeceleration (tstring(_T("Resource/ElbowStopFrames.txt"))) } }, { Hand::Shldr,{ // new MotionLaws::ContinuousSlowAcceleration (), // new MotionLaws::ContinuousFastAcceleration (), // new MotionLaws::ContinuousAccelerationThenStabilization (0.25), new MotionLaws::ContinuousAcceleration (), new MotionLaws::ContinuousDeceleration () //, // new MotionLaws::MangoAcceleration (tstring(_T("Resource/ShoulderMoveFrames.txt"))), // new MotionLaws::MangoDeceleration (tstring(_T("Resource/ShoulderStopFrames.txt"))) } } , // { Hand::Wrist, { new MotionLaws::ContinuousAcceleration (), // new MotionLaws::ContinuousDeceleration () } }, { Hand::Clvcl, { // new MotionLaws::ContinuousSlowAcceleration (), // new MotionLaws::ContinuousFastAcceleration (), // new MotionLaws::ContinuousAccelerationThenStabilization (), new MotionLaws::ContinuousAcceleration (), new MotionLaws::ContinuousDeceleration () } } }), target ( /* 200U, 200U, */ 18U, 18U, -0.41, 0.43, -0.03, -0.85 ), scaleLetters (target.min (), target.max ()) { std::srand ((unsigned int) clock ()); testing = false; working_space_show = false; allPointsDB_show = false; /* создаем ручки */ hPen_grn = CreatePen (PS_SOLID, 1, RGB (100, 180, 050)); hPen_red = CreatePen (PS_SOLID, 2, RGB (255, 000, 000)); hPen_blue = CreatePen (PS_SOLID, 2, RGB (000, 000, 255)); hPen_cian = CreatePen (PS_SOLID, 1, RGB (057, 168, 157)); hPen_orng = CreatePen (PS_SOLID, 2, RGB (255, 128, 000)); /* создаем кисти */ hBrush_white = (HBRUSH) GetStockObject (WHITE_BRUSH); hBrush_null = (HBRUSH) GetStockObject (NULL_BRUSH); hBrush_back = CreateSolidBrush (RGB (235, 235, 255) /* background color */ // RGB (255,204,238) ); // p_x = 0; p_y = 0; // fm = 0; fn = 0; } MyWindowData::~MyWindowData () { // if ( lt ) delete lt; //======================= /* очищаем ручку */ DeleteObject (hPen_grn); DeleteObject (hPen_red); DeleteObject (hPen_blue); DeleteObject (hPen_cian); DeleteObject (hPen_orng); DeleteObject (hBrush_white); DeleteObject (hBrush_null); DeleteObject (hBrush_back); DeleteDC (hStaticDC); DeleteObject (hStaticBitmap); //======================= if ( pWorkerThread ) { pWorkerThread->interrupt (); delete pWorkerThread; pWorkerThread = NULL; } //======================= // store.save (CurFileName); //======================= } //------------------------------------------------------------------------------- void OnPaintStaticBckGrnd (HDC hdc, MyWindowData &wd) { DrawDecardsCoordinates (hdc); wd.target.draw (hdc, wd.hPen_grn, /* false, */ true, // false, false); true, false); } void OnPaintStaticFigures (HDC hdc, MyWindowData &wd) { // -------------------------------------------------------------- if ( wd.working_space_show ) /* u */ DrawTrajectory (hdc, wd.working_space, wd.hPen_orng); // ----- Отрисовка точек БД ------------------------------------- if ( !wd.testing && wd.allPointsDB_show && !wd.store.empty () ) { #ifdef _DRAW_STORE_GRADIENT_ size_t colorGradations = 15U; color_interval_t colors = // make_pair (RGB(0,0,130), RGB(255,0,0)); // 128 make_pair (RGB(150,10,245), RGB(245,10,150)); // make_pair (RGB(130,0,0), RGB(255,155,155)); gradient_t gradient; MakeGradient (colors, colorGradations, gradient); #else gradient_t gradient ({ RGB (25, 255, 25), RGB (25, 25, 255), RGB (255, 25, 25) }); #endif // -------------------------------------------------------------- WorkerThreadRunStoreTask ( wd, _T (" *** drawing *** "), [hdc](HandMoves::Store &store, gradient_t gradient, double r, HandMoves::trajectory_t uncoveredPoints, HPEN hPen) { store.draw (hdc, gradient, r); for ( auto &pt : uncoveredPoints ) if ( zoom ) { DrawCircle (hdc, pt, 0.005, hPen); } else { SetPixel (hdc, Tx (pt.x), Ty (pt.y), RGB (255, 0, 0)); } }, gradient, /* (zoom) ? 0.0005 : */ 0., ( wd.uncovered_show ) ? wd.uncoveredPoints : HandMoves::trajectory_t(), wd.hPen_red); } // end if } void OnPainDynamicFigures (HDC hdc, MyWindowData &wd) { const double CircleRadius = 0.01; // -------------------------------------------------------------- /* Target to achive */ // if ( wd.lt ) wd.lt->draw (hdc, wd); // ----- Отрисовка фигуры --------------------------------------- wd.hand.draw (hdc, wd.hPen_red, wd.hBrush_white); // -------------------------------------------------------------- wd.trajectory_frames.draw (hdc, wd.hPen_orng); // -------------------------------------------------------------- if ( !wd.testing && wd.testing_trajectories_show && !wd.testing_trajectories.empty () ) { #ifdef _TESTING_TRAJECTORIES_ANIMATION_ auto it = wd.testing_trajectories.begin (); for ( size_t i = 0U; i < wd.testing_trajectories_animation_num_iteration; ++i, ++it ) { DrawTrajectory (hdc, *it, wd.hPen_blue); DrawCircle (hdc, it->back (), CircleRadius); } #else // !_TESTING_TRAJECTORIES_ANIMATION_ !not! for ( auto &t : wd.testing_trajectories ) { DrawTrajectory (hdc, t, wd.hPen_blue); } #endif // _TESTING_TRAJECTORIES_ANIMATION_ } // end if // ----- Отрисовка точек БД ------------------------------------- if ( !wd.adjPointsDB.empty () ) { HPEN hPen_old = (HPEN) SelectObject (hdc, wd.hPen_cian); for ( auto &p : wd.adjPointsDB ) { DrawCircle (hdc, p->hit, CircleRadius); } SelectObject (hdc, hPen_old); } // -------------------------------------------------------------- if ( wd.mouse_haved ) { DrawAdjacency (hdc, wd.mouse_aim, wd.radius, ellipse, wd.hPen_cian); } // -------------------------------------------------------------- if ( wd.scaleLetters.show ) { wd.scaleLetters.draw (hdc, wd.hand.jointsPositions (), &wd.hand.position); } // -------------------------------------------------------------- } //------------------------------------------------------------------------------- void WorkerThreadTryJoin (MyWindowData &wd) { if ( wd.pWorkerThread && wd.pWorkerThread->try_join_for (boost::chrono::milliseconds (10)) ) { /* joined */ delete wd.pWorkerThread; wd.pWorkerThread = nullptr; wd.testing = false; #ifdef _TESTING_TRAJECTORIES_ANIMATION_ wd.testing_trajectories_animation_num_iteration = 1; wd.testing_trajectories_animation_show = true; #endif // _TESTING_TRAJECTORIES_ANIMATION_ /* Set text of label 'Stat' */ SendMessage (wd.hLabTest, WM_SETTEXT, NULL, reinterpret_cast<LPARAM> (_T (" Done ")) ); } // end if } //------------------------------------------------------------------------------- void OnShowDBPoints (MyWindowData &wd) { if ( !wd.testing ) { wd.adjPointsDB.clear (); wd.testing_trajectories.clear (); wd.store.adjacencyPoints (wd.adjPointsDB, wd.mouse_aim, wd.radius); } } void OnShowDBTrajes (MyWindowData &wd) { wd.trajectory_frames.clear (); for ( auto &rec : wd.adjPointsDB ) { wd.trajectoriesDB.push_back (make_shared<trajectory_t> (rec->trajectory)); } } //------------------------------------------------------------------------------- void OnWindowTimer (MyWindowData &wd) { if ( !wd.testing ) { wd.trajectory_frames.step (wd.store, wd.hand); #ifdef _TESTING_TRAJECTORIES_ANIMATION_ /* Trajectoriaes animation */ if ( wd.testing_trajectories_animation_show && wd.testing_trajectories_animation_num_iteration < wd.testing_trajectories.size () ) { ++wd.testing_trajectories_animation_num_iteration; } #endif // _TESTING_TRAJECTORIES_ANIMATION_ } // end if } void OnWindowMouse (MyWindowData &wd) { wd.mouse_haved = true; wd.mouse_aim = logic_coord (&wd.mouse_coords); /* Setting the Label's text */ tstring message = tstring (wd.mouse_aim) + _T (" "); SendMessage (wd.hLabMAim, WM_SETTEXT, NULL, (WPARAM) message.c_str ()); // ------------------------------------------------- if ( !wd.testing ) { MakeHandMove (wd); } } //------------------------------------------------------------------------------- bool RepeatMove (MyWindowData &wd) { const Point &aim = wd.mouse_aim; // ------------------------------------------------- const Record &rec = wd.store.ClothestPoint (aim, wd.side); // ------------------------------------------------- if ( boost_distance (rec.hit, aim) <= wd.target.precision () ) { /* Repeat Hand Movement */ wd.hand.SET_DEFAULT; wd.trajectory_frames.step (wd.store, wd.hand, boost::optional<controling_t>{rec.controls}); // ------------------------------------------------- if ( !wd.trajectory_frames.animation ) { if ( !boost::equal (wd.trajectory_frames.trajectory, rec.trajectory) ) { throw std::exception ("Incorrect Repeat Hand Move"); } } // ------------------------------------------------- tstring text = GetTextToString (wd.hLabMAim); tstringstream ss; ss << text << _T ("\r"); for ( const Hand::Control &c : rec.controls ) { ss << c << _T (" "); } // \r SendMessage (wd.hLabMAim, WM_SETTEXT, NULL, (LPARAM) ss.str ().c_str ()); // ------------------------------------------------- return true; } // ------------------------------------------------- return false; } bool MakeHandMove (MyWindowData &wd) { // wd.adjPointsDB.clear (); wd.trajectory_frames.clear (); wd.testing_trajectories.clear (); // ------------------------------------------------- if ( !RepeatMove (wd) ) { const Point &aim = wd.mouse_aim; // ------------------------------------------------- Positions::LearnMovements lm (wd.store, wd.hand, wd.target); lm.gradientMethod_admixture (aim, true); // ------------------------------------------------- if ( 0 /* Around Trajectories !!! */) { // adjacency_refs_t range; // std::pair<Record, Record> x_pair, y_pair; // auto count = wd.store.adjacencyByPBorders (aim, 0.06, x_pair, y_pair); // range, aim, min, max); // // tcout << count << std::endl; // // wd.testing_trajectories.push_back (x_pair.first.trajectory); // wd.testing_trajectories.push_back (y_pair.first.trajectory); // wd.testing_trajectories.push_back (x_pair.second.trajectory); // wd.testing_trajectories.push_back (y_pair.second.trajectory); // return false; } // ------------------------------------------------- if ( 0 /* LinearOperator && SimplexMethod */ ) { // HandMoves::controling_t controls; // Positions::LinearOperator lp (wd.store, wd.mouse_aim, // 0.07, controls, true); // // lp.predict (wd.mouse_aim, controls); // // wd.hand.SET_DEFAULT; // wd.hand.move (controls.begin (), controls.end (), &wd.trajectory_frames.trajectory); } // ------------------------------------------------- return !RepeatMove (wd); } // ------------------------------------------------- return true; } //-------------------------------------------------------------------------------
37.306122
112
0.47903
favorart
c912bc26eb9e2529c245dfb6978080aff29d903e
612
cc
C++
content/common/generic_shared_memory_id_generator.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
content/common/generic_shared_memory_id_generator.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
content/common/generic_shared_memory_id_generator.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2015 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 "content/common/generic_shared_memory_id_generator.h" #include "base/atomic_sequence_num.h" namespace content { namespace { // Global atomic to generate gpu memory buffer unique IDs. base::StaticAtomicSequenceNumber g_next_generic_shared_memory_id; } // namespace gfx::GenericSharedMemoryId GetNextGenericSharedMemoryId() { return gfx::GenericSharedMemoryId(g_next_generic_shared_memory_id.GetNext()); } } // namespace content
27.818182
79
0.797386
google-ar
c91a2fd4a83d72981f5256dfc262cb1290af1f82
6,524
cpp
C++
HackerRank/Algorithm/DP/Fibonacci Modified.cpp
Saikat-S/acm-problems-solutions
921c0f3e508e1ee8cd14be867587952d5f67bbb9
[ "MIT" ]
3
2018-05-11T07:33:20.000Z
2020-08-30T11:02:02.000Z
HackerRank/Algorithm/DP/Fibonacci Modified.cpp
Saikat-S/acm-problems-solutions
921c0f3e508e1ee8cd14be867587952d5f67bbb9
[ "MIT" ]
1
2018-05-11T18:10:26.000Z
2018-05-12T18:00:28.000Z
HackerRank/Algorithm/DP/Fibonacci Modified.cpp
Saikat-S/acm-problems-solutions
921c0f3e508e1ee8cd14be867587952d5f67bbb9
[ "MIT" ]
null
null
null
/*************************************************** * Problem Name : Fibonacci Modified.cpp * Problem Link : https://www.hackerrank.com/challenges/fibonacci-modified/problem?h_r=next-challenge&h_v=zen * OJ : HackerRank * Verdict : TLE * Date : 2019-01-21 * Problem Type : dp * Author Name : Saikat Sharma * University : CSE, MBSTU ***************************************************/ #include<iostream> #include<cstdio> #include<algorithm> #include<climits> #include<cstring> #include<string> #include<sstream> #include<cmath> #include<vector> #include<queue> #include<cstdlib> #include<deque> #include<stack> #include<map> #include<set> #define __FastIO ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0) #define FileRead freopen ("/home/saikat/Desktop/logN/input.txt", "r", stdin); #define FileWrite freopen ("/home/saikat/Desktop/logN/output.txt", "w", stdout); #define SET(a,v) memset(a,v,sizeof(a)) #define pii pair<int,int> #define pll pair <ll, ll> #define debug cout <<"#########\n"; #define nl cout << "\n"; #define sp cout << " "; #define sl(n) scanf("%lld", &n) #define sf(n) scanf("%lf", &n) #define si(n) scanf("%d", &n) #define ss(n) scanf("%s", n) #define pf(n) scanf("%d", n) #define pfl(n) scanf("%lld", n) #define all(v) v.begin(), v.end() #define Pow2(x) ((x)*(x)) #define Mod(x, m) ((((x) % (m)) + (m)) % (m)) #define Max3(a, b, c) max(a, max(b, c)) #define Min3(a, b, c) min(a, min(b, c)) #define pb push_back #define mk make_pair #define MAX 25 #define INF 1000000000 using namespace std; typedef long long ll; typedef unsigned long long ull; template <typename T> std::string NumberToString ( T Number ) { std::ostringstream ss; ss << Number; return ss.str(); } ll lcm (ll a, ll b) { return a * b / __gcd (a, b); } /************************************ Code Start Here ******************************************************/ string add (string a, string b) { int al = (int) a.size() - 1; int bl = (int) b.size() - 1; int carry = 0; string result = ""; while (al >= 0 && bl >= 0) { int temp = (int) (a[al] - '0') + (int) (b[bl] - '0') + carry ; carry = 0; if (temp > 9 ) { carry = 1; temp = temp - 10; } result += char (temp + '0'); al--; bl--; } while (al >= 0) { int temp = (int) (a[al] - '0') + carry ; carry = 0; if (temp > 9) { carry = 1; temp = temp % 10; } result += char (temp + '0'); al--; } while (bl >= 0) { int temp = (int) (b[bl] - '0') + carry ; carry = 0; if (temp > 9) { carry = 1; temp = temp % 10; } result += char (temp + '0'); bl--; } if (carry) { result += "1"; } reverse (result.begin(), result.end() ); return result; } string trim (string a) { string res = ""; int i = 0; while (a[i] == '0') { i++; } int sz = a.size(); for (; i < sz; i++) { res += a[i]; } return res; } string strmul (string s1, string s2) { string m, a; int i, l, l2, j, c, s = 0; reverse (s1.begin(), s1.end() ); reverse (s2.begin(), s2.end() ); if (s1.size() > s2.size() ) { swap (s1, s2); } l = s1.size(); l2 = s2.size(); j = 0; m = "", a = ""; for (i = 0; i < l2; i++) { c = 0; m = ""; for (j = 0; j < l; j++) { s = (s1[j] - '0') * (s2[i] - '0') + c; c = s / 10; m += (s % 10) + '0'; } if (c > 0) { m += c % 10 + '0'; } int k; reverse (m.begin(), m.end() ); for (k = j; k < j + i; k++) { m += "0"; } reverse (m.begin(), m.end() ); if (i == 0) { a = m; } if (i != 0) { c = 0; reverse (a.begin(), a.end() ); reverse (m.begin(), m.end() ); a = (add (a, m) ); reverse (a.begin(), a.end() ); } } int flg = 0; for (i = 0; i < (int) a.size(); i++) { if (a[i] != '0') { flg = 1; break; } } if (flg == 0) { a = "0"; } reverse (a.begin(), a.end() ); return a; } string multiply (string num1, string num2) { int n1 = num1.size(); int n2 = num2.size(); if (n1 == 0 || n2 == 0) return "0"; // will keep the result number in vector // in reverse order vector<int> result (n1 + n2, 0); // Below two indexes are used to find positions // in result. int i_n1 = 0; int i_n2 = 0; // Go from right to left in num1 for (int i = n1 - 1; i >= 0; i--) { int carry = 0; int n1 = num1[i] - '0'; // To shift position to left after every // multiplication of a digit in num2 i_n2 = 0; // Go from right to left in num2 for (int j = n2 - 1; j >= 0; j--) { // Take current digit of second number int n2 = num2[j] - '0'; // Multiply with current digit of first number // and add result to previously stored result // at current position. int sum = n1 * n2 + result[i_n1 + i_n2] + carry; // Carry for next iteration carry = sum / 10; // Store result result[i_n1 + i_n2] = sum % 10; i_n2++; } // store carry in next cell if (carry > 0) result[i_n1 + i_n2] += carry; // To shift position to left after every // multiplication of a digit in num1. i_n1++; } // ignore '0's from the right int i = result.size() - 1; while (i >= 0 && result[i] == 0) i--; // If all were '0's - means either both or // one of num1 or num2 were '0' if (i == -1) return "0"; // generate the result string string s = ""; while (i >= 0) s += std::to_string (result[i--]); return s; } string fun (int n, string a, string b) { string c; for (int i = 3; i <= n; i++) { //~ string bb = strmul (b, b); string bb = multiply(b, b); c = (add (a, bb) ); a = b; b = c; } return c; } int main () { //~ __FastIO; int n; string t1, t2; cin >> t1 >> t2 >> n; cout << fun (n, t1, t2 ) << "\n"; return 0; }
22.731707
109
0.448038
Saikat-S
c91a99b7db579f67290a053a03893f254dac1d8a
17,324
cpp
C++
core/src/operator/convolution_op.cpp
cjmcv/dlex-cnn
dbd11ddf8c1515b18be54c74b4d123924cea6fa4
[ "MIT" ]
11
2017-11-19T15:15:28.000Z
2021-12-22T03:17:29.000Z
core/src/operator/convolution_op.cpp
cjmcv/dlex-cnn
dbd11ddf8c1515b18be54c74b4d123924cea6fa4
[ "MIT" ]
null
null
null
core/src/operator/convolution_op.cpp
cjmcv/dlex-cnn
dbd11ddf8c1515b18be54c74b4d123924cea6fa4
[ "MIT" ]
3
2019-02-18T12:47:44.000Z
2021-12-22T03:17:28.000Z
//////////////////////////////////////////////////////////////// // > Copyright (c) 2017 by Contributors. // > https://github.com/cjmcv // > brief // > author Jianming Chen //////////////////////////////////////////////////////////////// #include "operator/convolution_op.h" #include <sstream> namespace dlex_cnn { template <typename Dtype> ConvolutionOp<Dtype>::ConvolutionOp() { op_type_ = "Convolution"; } template <typename Dtype> ConvolutionOp<Dtype>::ConvolutionOp(ConvolutionOpParam param) { op_type_ = "Convolution"; param_ = param; } template <typename Dtype> ConvolutionOp<Dtype>::~ConvolutionOp() {} template <typename Dtype> int ConvolutionOp<Dtype>::SetOpParam(const std::string &op_param_str) { std::string opt_str = op_param_str; param_.blas_enable = atoi(FetchSubStr(opt_str, "blas_enable:", ",").c_str()); param_.kernel_num = atoi(FetchSubStr(opt_str, "kernel_num:", ",").c_str()); param_.kernel_h = atoi(FetchSubStr(opt_str, "kernel_h:", ",").c_str()); param_.kernel_w = atoi(FetchSubStr(opt_str, "kernel_w:", ",").c_str()); param_.stride_h = atoi(FetchSubStr(opt_str, "stride_h:", ",").c_str()); param_.stride_w = atoi(FetchSubStr(opt_str, "stride_w:", ",").c_str()); param_.pad_w = atoi(FetchSubStr(opt_str, "pad_w:", ",").c_str()); param_.dilation_h = atoi(FetchSubStr(opt_str, "dilation_h:", ",").c_str()); param_.dilation_w = atoi(FetchSubStr(opt_str, "dilation_w:", ",").c_str()); return 0; } template <typename Dtype> std::string ConvolutionOp<Dtype>::GenOpParamStr() const { std::stringstream param_str; param_str << "blas_enable:" << param_.blas_enable << ",kernel_num:" << param_.kernel_num << ",kernel_h:" << param_.kernel_h << ",kernel_w:" << param_.kernel_w << ",stride_h:" << param_.stride_h << ",stride_w:" << param_.stride_w << ",pad_h:" << param_.pad_h << ",pad_w:" << param_.pad_w << ",dilation_h:" << param_.dilation_h << ",dilation_w:" << param_.dilation_w << ","; return param_str.str(); } template <typename Dtype> int ConvolutionOp<Dtype>::InferOutShape(std::vector<int> &in_shape, std::vector<int> &out_shape) { out_shape.clear(); out_shape.push_back(in_shape[tind::eNum]); out_shape.push_back(param_.kernel_num); out_shape.push_back((in_shape[tind::eHeight] + 2 * param_.pad_h - (param_.dilation_h * (param_.kernel_h - 1) + 1)) / param_.stride_h + 1); out_shape.push_back((in_shape[tind::eWidth] + 2 * param_.pad_w - (param_.dilation_w * (param_.kernel_w - 1) + 1)) / param_.stride_w + 1); return 0; } template <typename Dtype> int ConvolutionOp<Dtype>::AllocBuf4Node(const std::vector<int> &in_shape, const std::vector<int> &out_shape, std::vector<std::shared_ptr<Tensor<Dtype>>> &data) const { data.clear(); //printf("data and gradient: size() : %d, %d\n", data.size(), gradient_.size()); data.push_back(std::make_shared<Tensor<Dtype>>(in_shape)); //weight (kernels for convolution) data.push_back(std::make_shared<Tensor<Dtype>>( param_.kernel_num, in_shape[tind::eChannels], param_.kernel_w, param_.kernel_h)); //blas if (param_.blas_enable) data.push_back(std::make_shared<Tensor<Dtype>>(out_shape[tind::eChannels], 1, 1, 1)); return 0; } template <typename Dtype> int ConvolutionOp<Dtype>::AllocOpBuf4Train(const std::vector<int> &in_shape, const std::vector<int> &out_shape) { if (in_shape[tind::eNum] <= 0 || in_shape[tind::eChannels] <= 0 || in_shape[tind::eHeight] <= 0 || in_shape[tind::eWidth] <= 0 || in_shape[tind::eNum] > 5000 || in_shape[tind::eChannels] > 5000 || in_shape[tind::eHeight] > 5000 || in_shape[tind::eWidth] > 5000) { DLOG_ERR("[ InnerProductOp::AllocOpBuf4Train ]: in_shape is invalid -> (%d, %d, %d, %d) \n", in_shape[tind::eNum], in_shape[tind::eChannels], in_shape[tind::eHeight], in_shape[tind::eWidth]); return -1; } diff_.clear(); diff_.push_back(std::make_shared<Tensor<Dtype>>(in_shape)); gradient_.clear(); gradient_.push_back(std::make_shared<Tensor<Dtype>>( param_.kernel_num, in_shape[tind::eChannels], param_.kernel_w, param_.kernel_h)); if (param_.blas_enable) gradient_.push_back(std::make_shared<Tensor<Dtype>>(out_shape[tind::eChannels], 1, 1, 1)); return 0; } template <typename Dtype> void ConvolutionOp<Dtype>::Forward( const std::vector<std::shared_ptr<Tensor<Dtype>>> &prev, const std::vector<std::shared_ptr<Tensor<Dtype>>> &next) { const std::vector<int> prev_shape = prev[0]->get_shape(); const std::vector<int> next_shape = next[0]->get_shape(); const std::vector<int> prev_size = prev[0]->get_size(); const std::vector<int> next_size = next[0]->get_size(); const std::vector<int> kernel_shape = prev[1]->get_shape(); ///////////////////////////////////////////////////// //auto worker = [&](const size_t start, const size_t stop){ // convolution2d(prev_data + start*prev_size[tind::e3D], kernel_data, bias_data, next_data + start*next_size[tind::e3D], // stop - start, prev_shape[tind::eChannels], prev_shape[tind::eWidth], prev_shape[tind::eHeight], // param_.kernel_num, param_.kernel_w, param_.kernel_h, param_.stride_w, param_.stride_h, // next_shape[tind::eWidth], next_shape[tind::eHeight], (int)param_.pad_type); //}; //worker(0, prev_shape[tind::eNum]); ///////////////////////////////////////////////////// const Dtype* prev_data = (Dtype *)prev[0]->GetPushCpuData(); const Dtype* kernel_data = (Dtype *)prev[1]->GetPushCpuData(); const Dtype* bias_data = (Dtype *)prev[2]->GetPushCpuData(); Dtype* next_data = (Dtype *)next[0]->GetCpuData(); // (1, channels*kernel_h*kernel_w, output_h*output_w) const int output_h = (prev_shape[tind::eHeight] + 2 * param_.pad_h - (param_.dilation_h * (param_.kernel_h - 1) + 1)) / param_.stride_h + 1; const int output_w = (prev_shape[tind::eWidth] + 2 * param_.pad_w - (param_.dilation_w * (param_.kernel_w - 1) + 1)) / param_.stride_w + 1; // The dimension of col_buffer is relevent to "prev". -> From prev to col_buffer. // prev channel num is equal to kernel's channel num. int col_height = prev_shape[tind::eChannels] * param_.kernel_h * param_.kernel_w; int col_width = output_h * output_w; if (col_buffer_ == NULL) col_buffer_ = std::make_shared<Tensor<Dtype>>(1, 1, col_height, col_width); else if (col_buffer_->get_size()[tind::e4D] != 1 * 1 * col_height * col_width) col_buffer_.reset(new Tensor<Dtype>(1, 1, col_height, col_width)); Dtype* col_data = (Dtype *)col_buffer_->GetPushCpuData(); next[0]->SetCpuZero(); for (int ni = 0; ni < prev_shape[tind::eNum]; ni++) { //printf("address: %d\n", col_data); im2col_cpu<Dtype>(prev_data + ni*prev_size[tind::e3D], prev_shape[tind::eChannels], prev_shape[tind::eHeight], prev_shape[tind::eWidth], param_.kernel_h, param_.kernel_w, param_.pad_h, param_.pad_w, param_.stride_h, param_.stride_w, param_.dilation_h, param_.dilation_w, col_data); //printf("address: %d\n", col_data); //bool bTransA, bool bTransB, const int M, const int N, const int K, const float alpha, const Dtype* A, const Dtype* B, const float beta, Dtype* C gemm_cpu(false, false, param_.kernel_num, col_width, col_height, (Dtype)1, kernel_data, col_data, (Dtype)0, next_data + ni * next_size[tind::e3D]); } // kernel_num is equal to output channel number, one kernel corresponds to one bias. // So take channels to be the index to select bias, and use the same bias in a channel. if (param_.blas_enable) add_bias( next_shape[tind::eNum], next_shape[tind::eChannels], next_size[tind::e2D], bias_data, next_data); } template <typename Dtype> void ConvolutionOp<Dtype>::Backward( const std::vector<std::shared_ptr<Tensor<Dtype>>> &prev, const std::vector<std::shared_ptr<Tensor<Dtype>>> &next, const std::vector<std::shared_ptr<Tensor<Dtype>>> &prev_diff, const std::vector<std::shared_ptr<Tensor<Dtype>>> &next_diff) { // data const std::vector<int> prev_shape = prev[0]->get_shape(); const std::vector<int> next_shape = next[0]->get_shape(); const std::vector<int> prev_size = prev[0]->get_size(); const std::vector<int> next_size = next[0]->get_size(); // diff const std::vector<int> prev_diff_shape = prev_diff[0]->get_shape(); const std::vector<int> next_diff_shape = next_diff[0]->get_shape(); const std::vector<int> prev_diff_size = prev_diff[0]->get_size(); const std::vector<int> next_diff_size = next_diff[0]->get_size(); // weight const std::vector<int> kernel_shape = prev[1]->get_shape(); const std::vector<int> kernel_size = prev[1]->get_size(); // bias //const std::vector<int> biasShape = prev[2]->get_shape(); const std::vector<int> bias_size = prev[2]->get_size(); const Dtype* prev_data = (Dtype*)prev[0]->GetPushCpuData(); const Dtype* next_data = (Dtype*)next[0]->GetPushCpuData(); Dtype* prev_diff_data = (Dtype*)prev_diff[0]->GetCpuData(); Dtype* next_diff_data = (Dtype*)next_diff[0]->GetPushCpuData(); Dtype *kernel_data = (Dtype*)prev[1]->GetPushCpuData(); //Dtype *bias_data = (Dtype*)prev[2]->GetPushCpuData(); Dtype* col_data = (Dtype *)col_buffer_->GetPushCpuData(); //update prev_diff prev_diff[0]->SetCpuZero(); for (int i = 0; i < prev_diff_shape[tind::eNum]; i++) { gemm_cpu(true, false, kernel_size[tind::e3D], next_diff_size[tind::e2D], kernel_shape[tind::eNum], (Dtype)1.0, kernel_data, next_diff_data + i * next_diff_size[tind::e3D], (Dtype)0.0, col_data); col2im_cpu(col_data, prev_diff_shape[tind::eChannels], prev_diff_shape[tind::eHeight], prev_diff_shape[tind::eWidth], param_.kernel_h, param_.kernel_w, param_.pad_h, param_.pad_w, param_.stride_h, param_.stride_w, param_.dilation_h, param_.dilation_w, prev_diff_data + i * prev_diff_size[tind::e3D]); } //update weight Diff gradient_[0]->SetCpuZero(); Dtype* kernel_gradient_data = (Dtype *)gradient_[0]->GetCpuData(); for (int ni = 0; ni < prev_diff_shape[tind::eNum]; ni++) { im2col_cpu<Dtype>(prev_data + ni*prev_size[tind::e3D], prev_shape[tind::eChannels], prev_shape[tind::eHeight], prev_shape[tind::eWidth], param_.kernel_h, param_.kernel_w, param_.pad_h, param_.pad_w, param_.stride_h, param_.stride_w, param_.dilation_h, param_.dilation_w, col_data); // kernel_shape[tind::eNum] == next_shape[tind::eChannels] gemm_cpu(false, true, kernel_shape[tind::eNum], kernel_size[tind::e3D], next_size[tind::e2D], (Dtype)1.0, next_diff_data + ni * next_diff_size[tind::e3D], col_data, (Dtype)1.0, kernel_gradient_data); } div_inplace_cpu(kernel_size[tind::e4D], (Dtype)next_shape[tind::eNum], kernel_gradient_data); //update bias gradient gradient_[1]->SetCpuZero(); Dtype* bias_gradient_data = (Dtype *)gradient_[1]->GetCpuData(); backward_bias( next_diff_shape[tind::eNum], next_diff_shape[tind::eChannels], next_diff_size[tind::e2D], next_diff_data, bias_gradient_data); div_inplace_cpu(bias_size[tind::e4D], (Dtype)next_shape[tind::eNum], bias_gradient_data); } #ifdef USE_CUDA template <typename Dtype> void ConvolutionOp<Dtype>::Forward_gpu( const std::vector<std::shared_ptr<Tensor<Dtype>>> &prev, const std::vector<std::shared_ptr<Tensor<Dtype>>> &next) { const std::vector<int> prev_shape = prev[0]->get_shape(); const std::vector<int> next_shape = next[0]->get_shape(); const std::vector<int> prev_size = prev[0]->get_size(); const std::vector<int> next_size = next[0]->get_size(); const std::vector<int> kernel_shape = prev[1]->get_shape(); const Dtype* prev_data = (Dtype *)prev[0]->GetPushGpuData(); const Dtype* kernel_data = (Dtype *)prev[1]->GetPushGpuData(); const Dtype* bias_data = (Dtype *)prev[2]->GetPushGpuData(); Dtype* next_data = (Dtype *)next[0]->GetGpuData(); // (1, channels*kernel_h*kernel_w, output_h*output_w) const int output_h = (prev_shape[tind::eHeight] + 2 * param_.pad_h - (param_.dilation_h * (param_.kernel_h - 1) + 1)) / param_.stride_h + 1; const int output_w = (prev_shape[tind::eWidth] + 2 * param_.pad_w - (param_.dilation_w * (param_.kernel_w - 1) + 1)) / param_.stride_w + 1; // The dimension of col_buffer is relevent to "prev". -> From prev to col_buffer. // prev channel num is equal to kernel's channel num. int col_height = prev_shape[tind::eChannels] * param_.kernel_h * param_.kernel_w; int col_width = output_h * output_w; if (col_buffer_ == NULL) col_buffer_ = std::make_shared<Tensor<Dtype>>(1, 1, col_height, col_width); else if (col_buffer_->get_size()[tind::e4D] != 1 * 1 * col_height * col_width) col_buffer_.reset(new Tensor<Dtype>(1, 1, col_height, col_width)); Dtype* col_data = (Dtype *)col_buffer_->GetPushGpuData(); next[0]->SetGpuZero(); for (int ni = 0; ni < prev_shape[tind::eNum]; ni++) { //printf("address: %d\n", col_data); im2col_gpu<Dtype>(prev_data + ni*prev_size[tind::e3D], prev_shape[tind::eChannels], prev_shape[tind::eHeight], prev_shape[tind::eWidth], param_.kernel_h, param_.kernel_w, param_.pad_h, param_.pad_w, param_.stride_h, param_.stride_w, param_.dilation_h, param_.dilation_w, col_data); gemm_gpu(CuHandleManager::cublas_handle(), false, false, param_.kernel_num, col_width, col_height, (Dtype)1, kernel_data, col_data, (Dtype)0, next_data + ni * next_size[tind::e3D]); } if (param_.blas_enable) add_bias_gpu(next_shape[tind::eNum], next_shape[tind::eChannels], next_size[tind::e2D], bias_data, next_data); } template <typename Dtype> void ConvolutionOp<Dtype>::Backward_gpu( const std::vector<std::shared_ptr<Tensor<Dtype>>> &prev, const std::vector<std::shared_ptr<Tensor<Dtype>>> &next, const std::vector<std::shared_ptr<Tensor<Dtype>>> &prev_diff, const std::vector<std::shared_ptr<Tensor<Dtype>>> &next_diff) { // data const std::vector<int> prev_shape = prev[0]->get_shape(); const std::vector<int> next_shape = next[0]->get_shape(); const std::vector<int> prev_size = prev[0]->get_size(); const std::vector<int> next_size = next[0]->get_size(); // diff const std::vector<int> prev_diff_shape = prev_diff[0]->get_shape(); const std::vector<int> next_diff_shape = next_diff[0]->get_shape(); const std::vector<int> prev_diff_size = prev_diff[0]->get_size(); const std::vector<int> next_diff_size = next_diff[0]->get_size(); // weight const std::vector<int> kernel_shape = prev[1]->get_shape(); const std::vector<int> kernel_size = prev[1]->get_size(); // bias //const std::vector<int> biasShape = prev[2]->get_shape(); const std::vector<int> bias_size = prev[2]->get_size(); const Dtype* prev_data = (Dtype*)prev[0]->GetPushGpuData(); const Dtype* next_data = (Dtype*)next[0]->GetPushGpuData(); Dtype* prev_diff_data = (Dtype*)prev_diff[0]->GetGpuData(); Dtype* next_diff_data = (Dtype*)next_diff[0]->GetPushGpuData(); Dtype *kernel_data = (Dtype*)prev[1]->GetPushGpuData(); //Dtype *bias_data = (Dtype*)prev[2]->GetPushGpuData(); Dtype* col_data = (Dtype *)col_buffer_->GetPushGpuData(); //update prev_diff prev_diff[0]->SetGpuZero(); for (int i = 0; i < prev_diff_shape[tind::eNum]; i++) { gemm_gpu(CuHandleManager::cublas_handle(), true, false, kernel_size[tind::e3D], next_diff_size[tind::e2D], kernel_shape[tind::eNum], (Dtype)1.0, kernel_data, next_diff_data + i * next_diff_size[tind::e3D], (Dtype)0.0, col_data); col2im_gpu(col_data, prev_diff_shape[tind::eChannels], prev_diff_shape[tind::eHeight], prev_diff_shape[tind::eWidth], param_.kernel_h, param_.kernel_w, param_.pad_h, param_.pad_w, param_.stride_h, param_.stride_w, param_.dilation_h, param_.dilation_w, prev_diff_data + i * prev_diff_size[tind::e3D]); } //update weight Diff gradient_[0]->SetGpuZero(); //const std::vector<int> kernelGradientSize = gradient_[0]->get_size(); Dtype* kernel_gradient_data = (Dtype *)gradient_[0]->GetGpuData(); for (int ni = 0; ni < prev_diff_shape[tind::eNum]; ni++) { im2col_gpu<Dtype>(prev_data + ni*prev_size[tind::e3D], prev_shape[tind::eChannels], prev_shape[tind::eHeight], prev_shape[tind::eWidth], param_.kernel_h, param_.kernel_w, param_.pad_h, param_.pad_w, param_.stride_h, param_.stride_w, param_.dilation_h, param_.dilation_w, col_data); // kernel_shape[tind::eNum] == next_shape[tind::eChannels] gemm_gpu(CuHandleManager::cublas_handle(), false, true, kernel_shape[tind::eNum], kernel_size[tind::e3D], next_size[tind::e2D], (Dtype)1.0, next_diff_data + ni * next_diff_size[tind::e3D], col_data, (Dtype)1.0, kernel_gradient_data); } div_inplace_gpu(kernel_size[tind::e4D], (Dtype)next_shape[tind::eNum], kernel_gradient_data); //update bias gradient gradient_[1]->SetGpuZero(); Dtype* bias_gradient_data = (Dtype *)gradient_[1]->GetGpuData(); backward_bias_gpu(next_diff_shape[tind::eNum], next_diff_shape[tind::eChannels], next_diff_size[tind::e2D], next_diff_data, bias_gradient_data); div_inplace_gpu(bias_size[tind::e4D], (Dtype)next_shape[tind::eNum], bias_gradient_data); } #endif INSTANTIATE_CLASS(ConvolutionOp); }//namespace
40.571429
150
0.680039
cjmcv
c91b9726d365b44398a1b0be35867be214e2fecc
53
cxx
C++
test/input/Typedef-to-Class-template.cxx
radoslawcybulski/CastXML
7d8d719fdea8cad7702e62b6174b2665a4bf2ca5
[ "Apache-2.0" ]
428
2015-01-06T17:01:38.000Z
2022-03-22T12:34:03.000Z
test/input/Typedef-to-Class-template.cxx
radoslawcybulski/CastXML
7d8d719fdea8cad7702e62b6174b2665a4bf2ca5
[ "Apache-2.0" ]
175
2015-01-06T17:07:37.000Z
2022-03-07T23:06:02.000Z
test/input/Typedef-to-Class-template.cxx
radoslawcybulski/CastXML
7d8d719fdea8cad7702e62b6174b2665a4bf2ca5
[ "Apache-2.0" ]
101
2015-01-25T14:18:42.000Z
2022-02-05T08:56:06.000Z
template <typename T> class A; typedef A<int> start;
13.25
21
0.735849
radoslawcybulski
c91eb8c8702492b102c3978e5331c89fc4ffd623
21,342
cpp
C++
external/glu-0.1.0.0/source/texture2d.cpp
spetz911/almaty3d
0dda0f05862be2585eae9b6e2e8cf476c043e3dc
[ "MIT" ]
571
2015-01-08T16:29:38.000Z
2022-03-16T06:45:42.000Z
external/glu-0.1.0.0/source/texture2d.cpp
spetz911/almaty3d
0dda0f05862be2585eae9b6e2e8cf476c043e3dc
[ "MIT" ]
45
2015-01-15T12:47:28.000Z
2022-03-04T09:22:32.000Z
external/glu-0.1.0.0/source/texture2d.cpp
spetz911/almaty3d
0dda0f05862be2585eae9b6e2e8cf476c043e3dc
[ "MIT" ]
136
2015-01-31T15:24:57.000Z
2022-02-17T19:26:24.000Z
/////////////////////////////////////////////////////////////////////////////////// /// OpenGL Image (gli.g-truc.net) /// /// Copyright (c) 2008 - 2013 G-Truc Creation (www.g-truc.net) /// 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. /// /// @ref core /// @file gli/gtx/gl_texture2d.inl /// @date 2010-09-27 / 2013-01-13 /// @author Christophe Riccio /////////////////////////////////////////////////////////////////////////////////// #include <glm/glm.hpp> #include <gli/gli.hpp> namespace glu{ namespace detail { //GL_COMPRESSED_RED, GL_COMPRESSED_RG, GL_COMPRESSED_RGB, GL_COMPRESSED_RGBA, GL_COMPRESSED_SRGB, GL_COMPRESSED_SRGB_ALPHA, //GL_SRGB, GL_SRGB8, GL_SRGB_ALPHA, or GL_SRGB8_ALPHA8 struct texture_desc { GLint InternalFormat; GLint InternalFormatCompressed; GLint InternalFormatSRGB; GLint InternalFormatCompressedSRGB; GLenum ExternalFormat; GLenum ExternalFormatRev; GLenum Type; }; //GL_RED, GL_RG, GL_RGB, GL_BGR, GL_RGBA, and GL_BGRA. //GL_UNSIGNED_BYTE, GL_BYTE, GL_UNSIGNED_SHORT, GL_SHORT, GL_UNSIGNED_INT, //GL_INT, GL_FLOAT, GL_UNSIGNED_BYTE_3_3_2, GL_UNSIGNED_BYTE_2_3_3_REV, //GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV, GL_UNSIGNED_SHORT_4_4_4_4, //GL_UNSIGNED_SHORT_4_4_4_4_REV, GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_SHORT_1_5_5_5_REV, //GL_UNSIGNED_INT_8_8_8_8, GL_UNSIGNED_INT_8_8_8_8_REV, GL_UNSIGNED_INT_10_10_10_2, //GL_UNSIGNED_INT_2_10_10_10_REV # ifndef GL_COMPRESSED_RGBA_BPTC_UNORM_ARB # define GL_COMPRESSED_RGBA_BPTC_UNORM_ARB 0x8E8C # endif # ifndef GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB # define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB 0x8E8D # endif # ifndef GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB # define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB 0x8E8E # endif # ifndef GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB # define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB 0x8E8F # endif inline texture_desc gli2ogl_cast(gli::format const & Format) { texture_desc Cast[] = { {GL_NONE, GL_NONE, GL_NONE, GL_NONE, GL_NONE, GL_NONE, GL_NONE}, //// Normalized //{GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_UNSIGNED_BYTE}, //{GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_UNSIGNED_BYTE}, //{GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_UNSIGNED_BYTE}, //{GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_UNSIGNED_BYTE}, //{GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_UNSIGNED_SHORT}, //{GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_UNSIGNED_SHORT}, //{GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_UNSIGNED_SHORT}, //{GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_UNSIGNED_SHORT}, //{GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_UNSIGNED_INT}, //{GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_UNSIGNED_INT}, //{GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_UNSIGNED_INT}, //{GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_UNSIGNED_INT}, // Unsigned {GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_UNSIGNED_BYTE}, {GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_UNSIGNED_BYTE}, {GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_UNSIGNED_BYTE}, {GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_UNSIGNED_BYTE}, {GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_UNSIGNED_SHORT}, {GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_UNSIGNED_SHORT}, {GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_UNSIGNED_SHORT}, {GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_UNSIGNED_SHORT}, {GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_UNSIGNED_INT}, {GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_UNSIGNED_INT}, {GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_UNSIGNED_INT}, {GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_UNSIGNED_INT}, // Signed {GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_BYTE}, {GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_BYTE}, {GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_BYTE}, {GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_BYTE}, {GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_SHORT}, {GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_SHORT}, {GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_SHORT}, {GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_SHORT}, {GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_INT}, {GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_INT}, {GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_INT}, {GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_INT}, // Float {GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_HALF_FLOAT}, {GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_HALF_FLOAT}, {GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_HALF_FLOAT}, {GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_HALF_FLOAT}, {GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_FLOAT}, {GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_FLOAT}, {GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_FLOAT}, {GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_FLOAT}, // Packed {GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_HALF_FLOAT}, {GL_RGB9_E5, GL_RGB9_E5, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_HALF_FLOAT}, {GL_R11F_G11F_B10F, GL_R11F_G11F_B10F, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_HALF_FLOAT}, {GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_HALF_FLOAT}, {GL_RGBA4, GL_RGBA4, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_HALF_FLOAT}, {GL_RGB10_A2, GL_RGB10_A2, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_HALF_FLOAT}, // Depth {GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT}, {GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT}, {GL_DEPTH24_STENCIL8, GL_DEPTH24_STENCIL8, GL_DEPTH24_STENCIL8, GL_DEPTH24_STENCIL8, GL_DEPTH_COMPONENT, GL_DEPTH_STENCIL, GL_UNSIGNED_INT}, {GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_FLOAT}, {GL_DEPTH32F_STENCIL8, GL_DEPTH32F_STENCIL8, GL_DEPTH32F_STENCIL8, GL_DEPTH32F_STENCIL8, GL_DEPTH_COMPONENT, GL_DEPTH_STENCIL, GL_UNSIGNED_INT}, // Compressed formats {GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_NONE, GL_NONE, GL_NONE}, {GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_NONE, GL_NONE, GL_NONE}, {GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_NONE, GL_NONE, GL_NONE}, {GL_COMPRESSED_RED_RGTC1, GL_COMPRESSED_RED_RGTC1, GL_COMPRESSED_RED_RGTC1, GL_COMPRESSED_RED_RGTC1, GL_NONE, GL_NONE, GL_NONE}, {GL_COMPRESSED_SIGNED_RED_RGTC1, GL_COMPRESSED_SIGNED_RED_RGTC1, GL_COMPRESSED_SIGNED_RED_RGTC1, GL_COMPRESSED_SIGNED_RED_RGTC1, GL_NONE, GL_NONE, GL_NONE}, {GL_COMPRESSED_RG_RGTC2, GL_COMPRESSED_RG_RGTC2, GL_COMPRESSED_RG_RGTC2, GL_COMPRESSED_RG_RGTC2, GL_NONE, GL_NONE, GL_NONE}, {GL_COMPRESSED_SIGNED_RG_RGTC2, GL_COMPRESSED_SIGNED_RG_RGTC2, GL_COMPRESSED_SIGNED_RG_RGTC2, GL_COMPRESSED_SIGNED_RG_RGTC2, GL_NONE, GL_NONE, GL_NONE}, {GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB, GL_NONE, GL_NONE, GL_NONE}, {GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_NONE, GL_NONE, GL_NONE}, {GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB, GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB, GL_NONE, GL_NONE, GL_NONE}, }; return Cast[Format]; } }//namespace detail inline GLuint create_texture_2d(char const * Filename) { gli::texture2D Texture(gli::load_dds(Filename)); if(Texture.empty()) return 0; GLint Alignment(0); glGetIntegerv(GL_UNPACK_ALIGNMENT, &Alignment); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); GLuint Name(0); glGenTextures(1, &Name); glTextureStorage2DEXT(Name, GL_TEXTURE_2D, static_cast<GLint>(Texture.levels()), static_cast<GLenum>(gli::internal_format(Texture.format())), static_cast<GLsizei>(Texture.dimensions().x), static_cast<GLsizei>(Texture.dimensions().y)); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, Texture.levels() > 1 ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, static_cast<GLint>(Texture.levels() - 1)); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_RED); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_BLUE); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ALPHA); if(!gli::is_compressed(Texture.format())) { for(gli::texture2D::size_type Level(0); Level < Texture.levels(); ++Level) { glTextureSubImage2DEXT(Name, GL_TEXTURE_2D, static_cast<GLint>(Level), 0, 0, static_cast<GLsizei>(Texture[Level].dimensions().x), static_cast<GLsizei>(Texture[Level].dimensions().y), static_cast<GLenum>(gli::external_format(Texture.format())), static_cast<GLenum>(gli::type_format(Texture.format())), Texture[Level].data()); } } else { for(gli::texture2D::size_type Level(0); Level < Texture.levels(); ++Level) { glCompressedTextureSubImage2DEXT(Name, GL_TEXTURE_2D, static_cast<GLint>(Level), 0, 0, static_cast<GLsizei>(Texture[Level].dimensions().x), static_cast<GLsizei>(Texture[Level].dimensions().y), static_cast<GLenum>(gli::external_format(Texture.format())), static_cast<GLsizei>(Texture[Level].size()), Texture[Level].data()); } } // Restaure previous states glPixelStorei(GL_UNPACK_ALIGNMENT, Alignment); return Name; } inline GLuint create_texture_2d_array(char const * Filename) { gli::texture2DArray Texture(gli::load_dds(Filename)); if(Texture.empty()) return 0; GLint Alignment(0); glGetIntegerv(GL_UNPACK_ALIGNMENT, &Alignment); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); GLuint Name(0); glGenTextures(1, &Name); glTextureStorage3DEXT(Name, GL_TEXTURE_2D_ARRAY, static_cast<GLint>(Texture.levels()), static_cast<GLenum>(gli::internal_format(Texture.format())), static_cast<GLsizei>(Texture.dimensions().x), static_cast<GLsizei>(Texture.dimensions().y), static_cast<GLsizei>(Texture.layers())); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, Texture.levels() > 1 ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_BASE_LEVEL, 0); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_LEVEL, static_cast<GLint>(Texture.levels() - 1)); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_R, GL_RED); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_G, GL_GREEN); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_B, GL_BLUE); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_A, GL_ALPHA); if(!gli::is_compressed(Texture.format())) { for(gli::texture2D::size_type Layer(0); Layer < Texture.layers(); ++Layer) for(gli::texture2D::size_type Level(0); Level < Texture.levels(); ++Level) { glTextureSubImage3DEXT(Name, GL_TEXTURE_2D_ARRAY, static_cast<GLint>(Level), 0, 0, static_cast<GLint>(Layer), static_cast<GLsizei>(Texture[Layer][Level].dimensions().x), static_cast<GLsizei>(Texture[Layer][Level].dimensions().y), 1, static_cast<GLenum>(gli::external_format(Texture.format())), static_cast<GLenum>(gli::type_format(Texture.format())), Texture[Layer][Level].data()); } } else { for(gli::texture2D::size_type Layer(0); Layer < Texture.layers(); ++Layer) for(gli::texture2D::size_type Level(0); Level < Texture.levels(); ++Level) { glCompressedTextureSubImage3DEXT(Name, GL_TEXTURE_2D_ARRAY, static_cast<GLint>(Level), 0, 0, static_cast<GLint>(Layer), static_cast<GLsizei>(Texture[Layer][Level].dimensions().x), static_cast<GLsizei>(Texture[Layer][Level].dimensions().y), 1, static_cast<GLenum>(gli::external_format(Texture.format())), static_cast<GLsizei>(Texture[Layer][Level].size()), Texture[Layer][Level].data()); } } // Restaure previous states glPixelStorei(GL_UNPACK_ALIGNMENT, Alignment); return Name; } inline GLuint create_texture_2d(gli::storage const & Storage) { gli::texture2D Texture(Storage); if(Texture.empty()) return 0; GLuint Name(0); glGenTextures(1, &Name); glTextureStorage2DEXT(Name, GL_TEXTURE_2D, static_cast<GLint>(Texture.levels()), static_cast<GLenum>(gli::internal_format(Texture.format())), static_cast<GLsizei>(Texture.dimensions().x), static_cast<GLsizei>(Texture.dimensions().y)); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, Texture.levels() > 1 ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, static_cast<GLint>(Texture.levels() - 1)); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_RED); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_BLUE); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ALPHA); if(!gli::is_compressed(Texture.format())) { for(gli::texture2D::size_type Level(0); Level < Texture.levels(); ++Level) { glTextureSubImage2DEXT(Name, GL_TEXTURE_2D, static_cast<GLint>(Level), 0, 0, static_cast<GLsizei>(Texture[Level].dimensions().x), static_cast<GLsizei>(Texture[Level].dimensions().y), static_cast<GLenum>(gli::external_format(Texture.format())), static_cast<GLenum>(gli::type_format(Texture.format())), Texture[Level].data()); } } else { for(gli::texture2D::size_type Level(0); Level < Texture.levels(); ++Level) { glCompressedTextureSubImage2DEXT(Name, GL_TEXTURE_2D, static_cast<GLint>(Level), 0, 0, static_cast<GLsizei>(Texture[Level].dimensions().x), static_cast<GLsizei>(Texture[Level].dimensions().y), static_cast<GLenum>(gli::external_format(Texture.format())), static_cast<GLsizei>(Texture[Level].size()), Texture[Level].data()); } } return Name; } inline GLuint create_texture_2d_array(gli::storage const & Storage) { gli::texture2DArray Texture(Storage); if(Texture.empty()) return 0; GLuint Name(0); glGenTextures(1, &Name); glTextureStorage3DEXT(Name, GL_TEXTURE_2D_ARRAY, static_cast<GLint>(Texture.levels()), static_cast<GLenum>(gli::internal_format(Texture.format())), static_cast<GLsizei>(Texture.dimensions().x), static_cast<GLsizei>(Texture.dimensions().y), static_cast<GLsizei>(Texture.layers())); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, Texture.levels() > 1 ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_BASE_LEVEL, 0); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_LEVEL, static_cast<GLint>(Texture.levels() - 1)); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_R, GL_RED); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_G, GL_GREEN); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_B, GL_BLUE); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_A, GL_ALPHA); if(!gli::is_compressed(Texture.format())) { for(gli::texture2D::size_type Layer(0); Layer < Texture.layers(); ++Layer) for(gli::texture2D::size_type Level(0); Level < Texture.levels(); ++Level) { glTextureSubImage3DEXT(Name, GL_TEXTURE_2D_ARRAY, static_cast<GLint>(Level), 0, 0, static_cast<GLint>(Layer), static_cast<GLsizei>(Texture[Layer][Level].dimensions().x), static_cast<GLsizei>(Texture[Layer][Level].dimensions().y), 1, static_cast<GLenum>(gli::external_format(Texture.format())), static_cast<GLenum>(gli::type_format(Texture.format())), Texture[Layer][Level].data()); } } else { for(gli::texture2D::size_type Layer(0); Layer < Texture.layers(); ++Layer) for(gli::texture2D::size_type Level(0); Level < Texture.levels(); ++Level) { glCompressedTextureSubImage3DEXT(Name, GL_TEXTURE_2D_ARRAY, static_cast<GLint>(Level), 0, 0, static_cast<GLint>(Layer), static_cast<GLsizei>(Texture[Layer][Level].dimensions().x), static_cast<GLsizei>(Texture[Layer][Level].dimensions().y), 1, static_cast<GLenum>(gli::external_format(Texture.format())), static_cast<GLsizei>(Texture[Layer][Level].size()), Texture[Layer][Level].data()); } } return Name; } class scopedPixelStore { public: scopedPixelStore(GLint Alignment) : SavedAlignment(0) { glGetIntegerv(GL_UNPACK_ALIGNMENT, &this->SavedAlignment); glPixelStorei(GL_UNPACK_ALIGNMENT, Alignment); } ~scopedPixelStore() { glPixelStorei(GL_UNPACK_ALIGNMENT, this->SavedAlignment); } private: GLint SavedAlignment; }; inline GLuint create_texture(char const * Filename) { gli::storage Storage(gli::load_dds(Filename)); scopedPixelStore PixelStore(1); if(Storage.layers() > 1) return create_texture_2d_array(Storage); else return create_texture_2d(Storage); } }//namespace gli
46.598253
203
0.74187
spetz911
c91f6bac4ddac5fccd0f0747a46d7a333465be0d
11,706
cc
C++
ggadget/file_manager_wrapper.cc
suzhe/google-gadgets-for-linux
b58baabd8458c8515c9902b8176151a08d240983
[ "Apache-2.0" ]
175
2015-01-01T12:40:33.000Z
2019-05-24T22:33:59.000Z
ggadget/file_manager_wrapper.cc
suzhe/google-gadgets-for-linux
b58baabd8458c8515c9902b8176151a08d240983
[ "Apache-2.0" ]
11
2015-01-19T16:30:56.000Z
2018-04-25T01:06:52.000Z
ggadget/file_manager_wrapper.cc
suzhe/google-gadgets-for-linux
b58baabd8458c8515c9902b8176151a08d240983
[ "Apache-2.0" ]
97
2015-01-19T15:35:29.000Z
2019-05-15T05:48:02.000Z
/* Copyright 2008 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "file_manager_wrapper.h" #include <vector> #include "gadget_consts.h" #include "light_map.h" #include "logger.h" #include "slot.h" #include "string_utils.h" #include "system_utils.h" #include "small_object.h" namespace ggadget { class FileManagerWrapper::Impl : public SmallObject<> { public: Impl() : default_(NULL) { } ~Impl() { delete default_; default_ = NULL; for (size_t i = 0; i < file_managers_.size(); ++i) delete file_managers_[i].second; file_managers_.clear(); } bool RegisterFileManager(const char *prefix, FileManagerInterface *fm) { // The default FileManager if (!prefix || !*prefix) { if (default_) { LOG("Default file manager must be unregistered before replaced."); return false; } default_ = fm; return true; } if (!fm || !fm->IsValid()) { LOG("An invalid FileManager instance is specified for prefix %s", prefix); return false; } file_managers_.push_back(std::make_pair(std::string(prefix), fm)); return true; } bool UnregisterFileManager(const char *prefix, FileManagerInterface *fm) { // The default FileManager if (!prefix || !*prefix) { if (fm == default_) { default_ = NULL; return true; } LOG("UnregisterFileManager: Default file manager mismatch."); return false; } for (FileManagerPrefixMap::iterator it = file_managers_.begin(); it != file_managers_.end(); ++it) { if (it->first == prefix && it->second == fm) { file_managers_.erase(it); return true; } } LOG("UnregisterFileManager: File manager not found."); return false; } bool IsValid() { if (default_ && default_->IsValid()) return true; for (FileManagerPrefixMap::iterator it = file_managers_.begin(); it != file_managers_.end(); ++it) { if (it->second->IsValid()) return true; } return false; } bool Init(const char *base_path, bool create) { if (default_) return default_->Init(base_path, create); return false; } bool ReadFile(const char *file, std::string *data) { size_t index = 0; FileManagerInterface *fm = NULL; std::string path; bool matched = false; while ((fm = GetNextMatching(file, &index, &path)) != NULL) { matched = true; if (fm->ReadFile(path.c_str(), data)) return true; } if (default_ && !matched) return default_->ReadFile(file, data); return false; } bool WriteFile(const char *file, const std::string &data, bool overwrite) { size_t index = 0; FileManagerInterface *fm = NULL; std::string path; bool matched = false; while ((fm = GetNextMatching(file, &index, &path)) != NULL) { matched = true; // Only writes the file to the first matched FileManager, // unless it fails. if (fm->WriteFile(path.c_str(), data, overwrite)) return true; } if (default_ && !matched) return default_->WriteFile(file, data, overwrite); return false; } bool RemoveFile(const char *file) { size_t index = 0; FileManagerInterface *fm = NULL; std::string path; bool result = false; bool matched = false; while ((fm = GetNextMatching(file, &index, &path)) != NULL) { matched = true; // Removes the file in all matched FileManager instance. if (fm->RemoveFile(path.c_str())) result = true; } if (default_ && !matched) result = default_->RemoveFile(file); return result; } bool ExtractFile(const char *file, std::string *into_file) { size_t index = 0; FileManagerInterface *fm = NULL; std::string path; bool matched = false; while ((fm = GetNextMatching(file, &index, &path)) != NULL) { matched = true; if (fm->ExtractFile(path.c_str(), into_file)) return true; } if (default_ && !matched) return default_->ExtractFile(file, into_file); return false; } bool FileExists(const char *file, std::string *path) { size_t index = 0; FileManagerInterface *fm = NULL; std::string lookup_path; bool matched = false; while ((fm = GetNextMatching(file, &index, &lookup_path)) != NULL) { matched = true; if (fm->FileExists(lookup_path.c_str(), path)) return true; } if (default_ && !matched) return default_->FileExists(file, path); return false; } bool IsDirectlyAccessible(const char *file, std::string *path) { size_t index = 0; FileManagerInterface *fm = NULL; std::string lookup_path; bool matched = false; while ((fm = GetNextMatching(file, &index, &lookup_path)) != NULL) { matched = true; if (fm->IsDirectlyAccessible(lookup_path.c_str(), path)) return true; } if (default_ && !matched) return default_->IsDirectlyAccessible(file, path); return false; } std::string GetFullPath(const char *file) { size_t index = 0; FileManagerInterface *fm = NULL; std::string lookup_path; bool matched = false; while ((fm = GetNextMatching(file, &index, &lookup_path)) != NULL) { matched = true; std::string full_path = fm->GetFullPath(lookup_path.c_str()); if (full_path.length()) return full_path; } if (default_ && !matched) return default_->GetFullPath(file); return std::string(""); } class EnumProxy { public: EnumProxy(LightSet<std::string> *history, const std::string &prefix, Slot1<bool, const char *> *callback) : history_(history), prefix_(prefix), callback_(callback) { } bool Callback(const char *name) { std::string path = BuildFilePath(prefix_.c_str(), name, NULL); if (history_->find(path) == history_->end()) { history_->insert(path); return (*callback_)(BuildFilePath(prefix_.c_str(), name, NULL).c_str()); } return true; } private: LightSet<std::string> *history_; std::string prefix_; Slot1<bool, const char *> *callback_; }; bool EnumerateFiles(const char *dir, Slot1<bool, const char *> *callback) { ASSERT(dir); std::string dir_name(dir); std::string dir_name_with_sep(dir_name); if (!dir_name.empty() && dir_name[dir_name.size() - 1] == kDirSeparator) dir_name.erase(dir_name.size() - 1); if (!dir_name_with_sep.empty() && dir_name_with_sep[dir_name_with_sep.size() - 1] != kDirSeparator) dir_name += kDirSeparator; // Record enumrated files to prevent duplication in multiple managers. bool result = true; LightSet<std::string> history; for (size_t i = 0; result && i < file_managers_.size(); i++) { const std::string &prefix = file_managers_[i].first; FileManagerInterface *fm = file_managers_[i].second; if (GadgetStrNCmp(prefix.c_str(), dir_name.c_str(), prefix.size()) == 0) { // Dir is under this file manager. EnumProxy proxy(&history, "", callback); result = fm->EnumerateFiles(dir_name.c_str() + prefix.size(), NewSlot(&proxy, &EnumProxy::Callback)); } else if (GadgetStrNCmp(prefix.c_str(), dir_name_with_sep.c_str(), dir_name_with_sep.size()) == 0) { // This file manager is under dir. EnumProxy proxy(&history, prefix.substr(dir_name_with_sep.size()), callback); result = fm->EnumerateFiles("", NewSlot(&proxy, &EnumProxy::Callback)); } } if (result && default_) { EnumProxy proxy(&history, "", callback); result = default_->EnumerateFiles(dir_name.c_str(), NewSlot(&proxy, &EnumProxy::Callback)); } delete callback; return result; } uint64_t GetLastModifiedTime(const char *file) { size_t index = 0; FileManagerInterface *fm = NULL; std::string lookup_path; bool matched = false; while ((fm = GetNextMatching(file, &index, &lookup_path)) != NULL) { matched = true; uint64_t result = fm->GetLastModifiedTime(lookup_path.c_str()); if (result > 0) return result; } if (default_ && !matched) return default_->GetLastModifiedTime(file); return 0; } FileManagerInterface *GetNextMatching(const char *path, size_t *index, std::string *lookup_path) { if (*index >= file_managers_.size() || !path || !*path) return NULL; while (*index < file_managers_.size()) { const std::string &prefix = file_managers_[*index].first; FileManagerInterface *fm = file_managers_[*index].second; ++*index; if (GadgetStrNCmp(prefix.c_str(), path, prefix.size()) == 0) { *lookup_path = std::string(path + prefix.size()); return fm; } } return NULL; } typedef std::vector<std::pair<std::string, FileManagerInterface *> > FileManagerPrefixMap; FileManagerPrefixMap file_managers_; FileManagerInterface *default_; }; FileManagerWrapper::FileManagerWrapper() : impl_(new Impl()) { } FileManagerWrapper::~FileManagerWrapper() { delete impl_; impl_ = NULL; } bool FileManagerWrapper::RegisterFileManager(const char *prefix, FileManagerInterface *fm) { return impl_->RegisterFileManager(prefix, fm); } bool FileManagerWrapper::UnregisterFileManager(const char *prefix, FileManagerInterface *fm) { return impl_->UnregisterFileManager(prefix, fm); } bool FileManagerWrapper::IsValid() { return impl_->IsValid(); } bool FileManagerWrapper::Init(const char *base_path, bool create) { return impl_->Init(base_path, create); } bool FileManagerWrapper::ReadFile(const char *file, std::string *data) { return impl_->ReadFile(file, data); } bool FileManagerWrapper::WriteFile(const char *file, const std::string &data, bool overwrite) { return impl_->WriteFile(file, data, overwrite); } bool FileManagerWrapper::RemoveFile(const char *file) { return impl_->RemoveFile(file); } bool FileManagerWrapper::ExtractFile(const char *file, std::string *into_file) { return impl_->ExtractFile(file, into_file); } bool FileManagerWrapper::FileExists(const char *file, std::string *path) { return impl_->FileExists(file, path); } bool FileManagerWrapper::IsDirectlyAccessible(const char *file, std::string *path) { return impl_->IsDirectlyAccessible(file, path); } std::string FileManagerWrapper::GetFullPath(const char *file) { return impl_->GetFullPath(file); } uint64_t FileManagerWrapper::GetLastModifiedTime(const char *file) { return impl_->GetLastModifiedTime(file); } bool FileManagerWrapper::EnumerateFiles(const char *dir, Slot1<bool, const char *> *callback) { return impl_->EnumerateFiles(dir, callback); } } // namespace ggadget
28.975248
80
0.626089
suzhe
c92049a8a890eb5cfc8904ab24729e5274bf7faf
673
cpp
C++
Iomanip.cpp
monicastle/C_PDC_06
e5447d853ae2702341a33cec1448ac500a356540
[ "MIT" ]
null
null
null
Iomanip.cpp
monicastle/C_PDC_06
e5447d853ae2702341a33cec1448ac500a356540
[ "MIT" ]
null
null
null
Iomanip.cpp
monicastle/C_PDC_06
e5447d853ae2702341a33cec1448ac500a356540
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <iomanip> using namespace std; class NT { string a, i, l; public: friend ostream &operator<<( ostream &o, const NT &n ); friend istream &operator>>( istream &i, NT &n ); }; ostream &operator<<( ostream &o, const NT &n ) { o << "(" << n.a << ") " << n.i << "-" << n.l; return o; } istream &operator>>( istream &i, NT &n ) { i.ignore(); i >> setw(3) >> n.a; i.ignore(2); i >> setw(4) >> n.i; i.ignore(); i >> setw(4) >> n.l; return i; } int main() { NT t; cout << "Telefono en la forma (504) 3193-9169:" << endl; cin >> t; cout << "Telefono: " << t << endl; }
23.206897
60
0.506686
monicastle
c9231b3faca86f68810e83440b8ee3c9b4b0ff1f
986
cc
C++
complejos/src/complejos.funciones.cc
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Pablourquia
21990a872be9dbb32722a5f33fe743ba8faecd94
[ "MIT" ]
null
null
null
complejos/src/complejos.funciones.cc
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Pablourquia
21990a872be9dbb32722a5f33fe743ba8faecd94
[ "MIT" ]
null
null
null
complejos/src/complejos.funciones.cc
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Pablourquia
21990a872be9dbb32722a5f33fe743ba8faecd94
[ "MIT" ]
null
null
null
/** * Universidad de La Laguna * Escuela Superior de Ingeniería y Tecnología * Grado en Ingeniería Informática * Informática Básica * * @file complejos.funciones.cc * @author Pablo Urquía Adrián alu0101398327@ull.edu.es * @date 26 de diciembre de 2020 * @brief El programa calcula la suma o resta de numeros complejos mediantes clases y funciones * @bug No hay bugs conocidos * */ #include <iostream> #include <string> #include <fstream> #include <cstring> #include "complejos.funciones.h" Complejo add(Complejo complejo1, Complejo complejo2){ Complejo result {0, 0}; result.setReal(complejo1.getReal() + complejo2.getReal()); result.setImaginaria(complejo1.getImaginaria() + complejo2.getImaginaria()); return result; } Complejo sub (Complejo complejo1, Complejo complejo2){ Complejo result {0, 0}; result.setReal(complejo1.getReal() - complejo2.getReal()); result.setImaginaria(complejo1.getImaginaria() - complejo2.getImaginaria()); return result; }
29.878788
95
0.747465
ULL-ESIT-IB-2020-2021
c923ed4109d412bf111f807d60eb5d46ed02645c
2,086
cpp
C++
cpp/src/rz/rz-kauvir/rz-graph-core/kernel/graph/rz-re-node.cpp
Mosaic-DigammaDB/SSQM
c150cec88b4ac2d26a972faf38d56e9dfb137ae6
[ "BSL-1.0" ]
null
null
null
cpp/src/rz/rz-kauvir/rz-graph-core/kernel/graph/rz-re-node.cpp
Mosaic-DigammaDB/SSQM
c150cec88b4ac2d26a972faf38d56e9dfb137ae6
[ "BSL-1.0" ]
1
2018-11-13T17:41:46.000Z
2018-11-13T20:54:38.000Z
cpp/src/rz/rz-kauvir/rz-graph-core/kernel/graph/rz-re-node.cpp
Mosaic-DigammaDB/SSQM
c150cec88b4ac2d26a972faf38d56e9dfb137ae6
[ "BSL-1.0" ]
1
2018-11-13T16:43:10.000Z
2018-11-13T16:43:10.000Z
// Copyright Nathaniel Christen 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "rz-re-node.h" #include "token/rz-re-token.h" #include "rzns.h" USING_RZNS(RECore) void RE_Node::each_connection(std::function<void(const RE_Connectors& connector, const RE_Node&, const RE_Connection* connection)> fn) const { targets_iterator_type it(targets_); while(it.hasNext()) { it.next(); const RE_Connectors& connector = *it.key(); const RE_Node& target = *it.value(); fn(connector, target, nullptr); } annotated_targets_iterator_type ait(annotated_targets_); while(ait.hasNext()) { ait.next(); const RE_Connectors& connector = *ait.key(); const RE_Connection* connection = ait.value().first.raw_pointer(); const RE_Node& target = *ait.value().second; fn(connector, target, connection); } } caon_ptr<RZ_Lisp_Token> RE_Node::lisp_token() { if(re_token()) { return re_token()->lisp_token(); } return nullptr; } void RE_Node::debug_connections() { targets_iterator_type it(targets_); while(it.hasNext()) { it.next(); CAON_EVALUATE_DEBUG(RE_Connectors ,key ,it.key()) CAON_EVALUATE_DEBUG(RE_Node ,value ,it.value()) } } void RE_Node::add_hyponode(caon_ptr<RE_Node> n) { hyponodes_.push_back(n); } void RE_Node::swap_relation(const RE_Connectors& connector, caon_ptr<RE_Node> n1, caon_ptr<RE_Node> n2) { CAON_PTR_DEBUG(RE_Node ,n1) CAON_PTR_DEBUG(RE_Node ,n2) #ifdef NO_CAON RE_Connectors* pc = const_cast<RE_Connectors*>( &connector ); targets_.remove(pc, n1); targets_.insert(pc, n2); #else targets_.remove(&connector, n1); targets_.insert(&connector, n2); #endif //NO_CAON } void RE_Node::delete_relation(const RE_Connectors& connector, caon_ptr<RE_Node> n1) { CAON_PTR_DEBUG(RE_Node ,n1) #ifdef NO_CAON RE_Connectors* pc = const_cast<RE_Connectors*>( &connector ); targets_.remove(pc, n1); #else targets_.remove(&connector, n1); #endif //NO_CAON }
21.070707
80
0.71093
Mosaic-DigammaDB
c924f1ab471224b85bade7398be02f883367abd0
1,176
cpp
C++
PoseLab/OverlayText.cpp
vishwaphansal7/tf-cpp-pose-detect
aad54ee0234d94c1cf7e54252ec875e22cd2ad23
[ "MIT" ]
1
2021-05-03T15:06:54.000Z
2021-05-03T15:06:54.000Z
PoseLab/OverlayText.cpp
vishwaphansal7/tf-cpp-pose-detect
aad54ee0234d94c1cf7e54252ec875e22cd2ad23
[ "MIT" ]
null
null
null
PoseLab/OverlayText.cpp
vishwaphansal7/tf-cpp-pose-detect
aad54ee0234d94c1cf7e54252ec875e22cd2ad23
[ "MIT" ]
null
null
null
#include "pch.h" #include "OverlayText.h" using namespace std; OverlayText::OverlayText(Alignment alignment, QObject *parent) : OverlayElement(alignment, parent) , placeHolder() {} OverlayText::OverlayText(const QString& placeHolder, Alignment alignment, QObject* parent) : OverlayElement(alignment, parent) , placeHolder(placeHolder) {} OverlayText::~OverlayText() { } void OverlayText::setText(const QString& text) { lock_guard<mutex> lock(data); this->text = text; } // TODO layout decisions distributed between overlay text and painter QSize OverlayText::size(QPainter& painter, const QRect& bounds) { lock_guard<mutex> lock(data); chooseFont(painter, bounds); return QSize(painter.fontMetrics().horizontalAdvance(text), bounds.height()); } void OverlayText::paint(QPainter& painter, const QRect& bounds) { lock_guard<mutex> lock(data); chooseFont(painter, bounds); painter.drawText(QPoint(bounds.left(), bounds.top() + bounds.height() / 4 * 3), text); } void OverlayText::chooseFont(QPainter& painter, const QRect& bounds) { QFont f = painter.font(); int fontHeight = (bounds.height() - 8) / 1; f.setPixelSize(fontHeight); painter.setFont(f); }
26.133333
90
0.741497
vishwaphansal7
c925d5664112111d13f69559aafad90b42c5da45
178
cpp
C++
Src/Kranos/Entry.cpp
KDahir247/KranosLoader
5e55a0f1a697170020c2601c9b0d04b0da27da93
[ "MIT" ]
null
null
null
Src/Kranos/Entry.cpp
KDahir247/KranosLoader
5e55a0f1a697170020c2601c9b0d04b0da27da93
[ "MIT" ]
null
null
null
Src/Kranos/Entry.cpp
KDahir247/KranosLoader
5e55a0f1a697170020c2601c9b0d04b0da27da93
[ "MIT" ]
null
null
null
// // Created by kdahi on 2020-09-26. // #include "Kranos.h" int main(){ Kranos::Log::Init(); auto app = Kranos::CreateApplication(); app->Run(); delete app; }
13.692308
43
0.578652
KDahir247
c9273e66205639978031ba50898266381236b1bb
628
cpp
C++
dependencies/skse64/src/skse64/CommonLibSSE/src/RE/ExtraCount.cpp
clayne/papyrus-debug-server
f5c3878cd485ba68aaadf39bb830ca88bf53bfff
[ "MIT" ]
10
2019-06-01T20:24:04.000Z
2021-08-16T19:32:24.000Z
dependencies/skse64/src/skse64/CommonLibSSE/src/RE/ExtraCount.cpp
clayne/papyrus-debug-server
f5c3878cd485ba68aaadf39bb830ca88bf53bfff
[ "MIT" ]
null
null
null
dependencies/skse64/src/skse64/CommonLibSSE/src/RE/ExtraCount.cpp
clayne/papyrus-debug-server
f5c3878cd485ba68aaadf39bb830ca88bf53bfff
[ "MIT" ]
4
2019-06-09T05:00:55.000Z
2022-01-27T16:30:31.000Z
#include "RE/ExtraCount.h" #include "skse64/GameExtraData.h" // s_ExtraCountVtbl namespace RE { ExtraCount::ExtraCount() : BSExtraData(), count(0), pad14(0) { ((std::uintptr_t*)this)[0] = s_ExtraCountVtbl.GetUIntPtr(); } ExtraCount::ExtraCount(SInt32 a_count) : BSExtraData(), count(a_count), pad14(0) { ((std::uintptr_t*)this)[0] = s_ExtraCountVtbl.GetUIntPtr(); } ExtraDataType ExtraCount::GetType() const { return ExtraDataType::kCount; } bool ExtraCount::IsNotEqual(const BSExtraData* a_rhs) const { auto rhs = static_cast<const ExtraCount*>(a_rhs); return count != rhs->count; } }
17.444444
61
0.687898
clayne
c9275bb8e895e3023dfdf5062fff3ab276e7cef3
17,036
cc
C++
core-src/InferMove.cc
Quuxplusone/Homeworlds
8e193a60a0cc59901df1980f3866731d5c1ee15a
[ "BSD-2-Clause" ]
11
2016-07-01T10:51:58.000Z
2021-03-18T07:59:32.000Z
core-src/InferMove.cc
Quuxplusone/Homeworlds
8e193a60a0cc59901df1980f3866731d5c1ee15a
[ "BSD-2-Clause" ]
1
2017-06-11T04:30:09.000Z
2017-06-11T04:30:09.000Z
core-src/InferMove.cc
Quuxplusone/Homeworlds
8e193a60a0cc59901df1980f3866731d5c1ee15a
[ "BSD-2-Clause" ]
3
2016-02-27T16:53:28.000Z
2017-06-10T19:21:24.000Z
#include <algorithm> #include <assert.h> #include "state.h" #include "ApplyMove.h" #include "InferMove.h" #include "SingleAction.h" #include "WholeMove.h" static int count_unconstrained_catastrophes(const WholeMove &move, int ax) { /* If "move" contains catastrophe actions of the form "cat" --- as * opposed to "cat red" or "cat at Alpha" or "cat red at Alpha" --- * then we can make those catastrophes in arbitrary order and the * resulting state will be the same, as long as the number of * overpopulations in the current state is equal to the number of * catastrophes specified by the user. */ int count = 0; assert(ax < (int)move.actions.size()); assert(move.actions[ax].kind == CATASTROPHE); for (int i = ax; i < (int)move.actions.size(); ++i) { const SingleAction &action = move.actions[i]; if (action.kind != CATASTROPHE) { break; } if (action.where != "" || action.piece.color != UNKNOWN_COLOR) { return 0; } count += 1; } return count; } static bool infer_catastrophe(const GameState &st, const WholeMove &move, SingleAction &action) { assert(action.kind == CATASTROPHE); /* Figure out how many catastrophes are being made after this one. * This is so that we can handle "sac y2; ...; cat; cat". * However, we're not going to handle arbitrary constraints; * just look for "cat" with color and star unknown. */ const int numcats = count_unconstrained_catastrophes(move, &action - &move.actions[0]); const bool order_matters = (numcats == 0); SingleAction newaction = action; int found = 0; for (const StarSystem& here : st.stars) { if (action.where != "" && here.name != action.where) { continue; } for (Color c = RED; c <= BLUE; ++c) { if (action.piece.color != UNKNOWN_COLOR && c != action.piece.color) { continue; } if (here.numberOf(c) >= 4) { if (found != 0) { if (order_matters || found == numcats) { /* We can't deal with this ambiguity. */ return false; } } else { newaction.where = here.name; newaction.piece.color = c; } found += 1; } } } action = newaction; if (order_matters) { assert(found == 0 || found == 1); return (found != 0); } else { assert(found <= numcats); return (found == numcats); } } static bool infer_sacrifice(const GameState &st, int attacker, const WholeMove &move, SingleAction &action) { assert(action.kind == SACRIFICE); int ax; for (ax=0; move.actions[ax].kind != SACRIFICE; ++ax) { continue; } int num_actions = 0; Color needed_color = UNKNOWN_COLOR; for (++ax; ax < (int)move.actions.size(); ++ax) { if (move.actions[ax].kind == CATASTROPHE) { break; } switch (move.actions[ax].kind) { case SACRIFICE: assert(false); break; case CAPTURE: if (needed_color != UNKNOWN_COLOR && needed_color != RED) return false; needed_color = RED; break; case MOVE: case MOVE_CREATE: if (needed_color != UNKNOWN_COLOR && needed_color != YELLOW) return false; needed_color = YELLOW; break; case BUILD: if (needed_color != UNKNOWN_COLOR && needed_color != GREEN) return false; needed_color = GREEN; break; case CONVERT: if (needed_color != UNKNOWN_COLOR && needed_color != BLUE) return false; needed_color = BLUE; break; default: assert(false); } num_actions += 1; } assert(0 <= num_actions && num_actions <= 3); Size min_needed_size = (num_actions == 3 ? LARGE : (num_actions == 2 ? MEDIUM : SMALL)); if (action.piece.size != UNKNOWN_SIZE && action.piece.size < min_needed_size) { return false; } if (needed_color != UNKNOWN_COLOR) { if (action.piece.color == UNKNOWN_COLOR) { action.piece.color = needed_color; } else if (action.piece.color != needed_color) { return false; } } SingleAction newaction = action; bool foundone = false; for (const StarSystem& here : st.stars) { if (action.where != "" && here.name != action.where) { continue; } if (here.ships[attacker].empty()) continue; for (Color c = RED; c <= BLUE; ++c) { if (action.piece.color != UNKNOWN_COLOR && c != action.piece.color) { continue; } /* Can't sacrifice the last ship at your own homeworld. */ if (c != YELLOW && here.homeworldOf == attacker && here.ships[attacker].number() == 1) { continue; } for (Size s = min_needed_size; s <= LARGE; ++s) { if (action.piece.size != UNKNOWN_SIZE && s != action.piece.size) { continue; } if (here.ships[attacker].numberOf(c,s) != 0) { if (foundone) return false; newaction.where = here.name; newaction.piece.color = c; newaction.piece.size = s; foundone = true; } } } } action = newaction; return foundone; } static bool infer_multicapture(const GameState &st, int attacker, WholeMove *move, SingleAction &action) { assert(action.kind == CAPTURE); const int defender = 1-attacker; /* Count the ships we're capturing with the equivalent of "capture r1y1g1". */ PieceCollection to_capture; for (int j = (&action - &move->actions[0]); j < (int)move->actions.size(); ++j) { SingleAction &actjon = move->actions[j]; if (actjon.kind != CAPTURE || actjon.where != "") { break; } if (actjon.piece.color == UNKNOWN_COLOR || actjon.piece.size == UNKNOWN_SIZE) { break; } to_capture.insert(actjon.piece); } /* Now try to capture any ships matching that set. */ PieceCollection captured; int j = (&action - &move->actions[0]); for (const StarSystem& here : st.stars) { /* Since we only try infer_multicapture() when we've already seen a sacrifice, * that means that we don't need to check for hasAccessTo(RED) here. */ if (here.ships[attacker].empty()) continue; if (here.ships[defender].empty()) continue; const Size biggest = here.ships[attacker].biggestSize(); for (Color c = RED; c <= BLUE; ++c) { for (Size s = SMALL; s <= biggest; ++s) { const int target = to_capture.numberOf(c,s); int num_here = here.ships[defender].numberOf(c,s); if (target != 0 && num_here != 0) { /* One of our targets is here! */ if (captured.numberOf(c,s) != 0 && (captured.numberOf(c,s) + num_here > target)) { return false; /* Ambiguity! */ } num_here = std::min(num_here, target - captured.numberOf(c,s)); captured.insert(c,s,num_here); for ( ; num_here != 0; --num_here) { assert(move->actions[j].kind == CAPTURE); assert(move->actions[j].where.empty()); move->actions[j].where = here.name; move->actions[j].piece = Piece(c, s); ++j; } } } } } assert(captured.contains(to_capture)); if (captured != to_capture) { return false; } assert(j == (&action - &move->actions[0]) + to_capture.number()); return true; } static bool infer_capture(const GameState &st, int attacker, WholeMove *move, SingleAction &action, bool saw_sacrifice) { assert(action.kind == CAPTURE); if (saw_sacrifice && action.where == "" && action.piece.color != UNKNOWN_COLOR && action.piece.size != UNKNOWN_SIZE) { /* This can handle "capture y2; capture y2" where the two y2 ships * are in two different systems. */ return infer_multicapture(st, attacker, move, action); } const int defender = 1-attacker; SingleAction newaction = action; bool foundone = false; for (const StarSystem& here : st.stars) { if (action.where != "" && here.name != action.where) { continue; } if (!saw_sacrifice && !here.playerHasAccessTo(attacker, RED)) { continue; } if (here.ships[attacker].empty()) continue; if (here.ships[defender].empty()) continue; const Size biggest = here.ships[attacker].biggestSize(); for (Color c = RED; c <= BLUE; ++c) { if (action.piece.color != UNKNOWN_COLOR && c != action.piece.color) { continue; } for (Size s = SMALL; s <= biggest; ++s) { if (action.piece.size != UNKNOWN_SIZE && s != action.piece.size) { continue; } if (here.ships[defender].numberOf(c,s) == 0) { continue; } if (foundone) return false; newaction.where = here.name; newaction.piece.color = c; newaction.piece.size = s; foundone = true; } } } action = newaction; return foundone; } static bool infer_movement(const GameState &st, int attacker, SingleAction &action, bool saw_sacrifice) { /* We currently can't infer that e.g. in the situation * Home (0,g3b2) y1-r1 * Alpha (b1) g2- * Beta (b2) r2- * "sacrifice; move" must mean "sacrifice y1 at Home; move g2 from Alpha to Home" * because g2 is the only ship able to reach Home by the end of the turn to prevent * a loss. */ if (action.whither.empty() || action.piece.color == UNKNOWN_COLOR || action.piece.size == UNKNOWN_SIZE) { return false; } if (action.kind == MOVE_CREATE) { if (action.newpiece.color == UNKNOWN_COLOR || action.newpiece.size == UNKNOWN_SIZE) { return false; } } bool foundone = false; const StarSystem *whither = st.systemNamed(action.whither.c_str()); if ((whither == nullptr) != (action.kind == MOVE_CREATE)) { return false; } for (const StarSystem& here : st.stars) { if (here.homeworldOf == attacker && here.ships[attacker].number() == 1) { continue; } if (!saw_sacrifice && !here.playerHasAccessTo(attacker, YELLOW)) { continue; } /* The inferred "where" must be adjacent to the given "whither". */ if (action.kind == MOVE_CREATE && here.star.numberOf(action.newpiece.size) != 0) { continue; } if (action.kind == MOVE && !here.isAdjacentTo(*whither)) { continue; } /* A ship of the appropriate type must exist here. */ if (here.ships[attacker].numberOf(action.piece.color, action.piece.size) != 0) { if (foundone) return false; action.where = here.name; foundone = true; } } return foundone; } static bool infer_build(const GameState &st, int attacker, SingleAction &action, bool saw_sacrifice) { assert(action.kind == BUILD); SingleAction newaction = action; bool foundone = false; for (Color c = RED; c <= BLUE; ++c) { if (action.piece.color != UNKNOWN_COLOR && c != action.piece.color) { continue; } if (st.stash.numberOf(c) == 0) { continue; } const Size s = st.stash.smallestSizeOf(c); if (action.piece.size != UNKNOWN_SIZE && s != action.piece.size) { continue; } // Can we build this color anywhere? for (const StarSystem& here : st.stars) { if (action.where != "" && here.name != action.where) continue; if (!saw_sacrifice && !here.playerHasAccessTo(attacker, GREEN)) { continue; } if (here.ships[attacker].numberOf(c) != 0) { if (foundone) return false; newaction.where = here.name; newaction.piece.color = c; newaction.piece.size = s; foundone = true; } } } action = newaction; return foundone; } static bool infer_convert(const GameState &st, int attacker, SingleAction &action, bool saw_sacrifice) { assert(action.kind == CONVERT); SingleAction newaction = action; bool foundone = false; for (const StarSystem& here : st.stars) { if (action.where != "" && here.name != action.where) { continue; } if (!saw_sacrifice && !here.playerHasAccessTo(attacker, BLUE)) { continue; } if (here.ships[attacker].empty()) { continue; } for (Color c = RED; c <= BLUE; ++c) { if (action.piece.color != UNKNOWN_COLOR && c != action.piece.color) { continue; } if (action.newpiece.color != UNKNOWN_COLOR && c == action.newpiece.color) { continue; } for (Size s = SMALL; s <= LARGE; ++s) { if (action.piece.size != UNKNOWN_SIZE && s != action.piece.size) { continue; } if (here.ships[attacker].numberOf(c,s) == 0) { continue; } /* What color might we turn this ship? */ for (Color nc = RED; nc <= BLUE; ++nc) { if (action.newpiece.color != UNKNOWN_COLOR && nc != action.newpiece.color) { continue; } if (nc == c) continue; if (st.stash.numberOf(nc,s) != 0) { if (foundone) return false; newaction.where = here.name; newaction.piece.color = c; newaction.piece.size = s; newaction.newpiece.color = nc; newaction.newpiece.size = s; foundone = true; } } } } } action = newaction; return foundone; } /* Given a move with missing pieces (e.g., "build g1" instead of * "build g1 at Earth"), infer the missing pieces from the state of * the game (for example, if the only place g1 could be built is at * Earth, then "build g1" must mean "build g1 at Earth"). * If the intended move is unambiguous, fill it in and return true. * If the move matches multiple non-equivalent possibilities, return * false (trashing the input move in the process). */ bool inferMoveFromState(GameState newst, int attacker, WholeMove *move) { if (!move->isMissingPieces()) { return true; } bool saw_sacrifice = false; for (SingleAction& action : move->actions) { if (action.kind == SACRIFICE) { saw_sacrifice = true; } assert(action.sanitycheck()); if (action.isMissingPieces()) { switch (action.kind) { case CATASTROPHE: if (!infer_catastrophe(newst, *move, action)) return false; break; case SACRIFICE: if (!infer_sacrifice(newst, attacker, *move, action)) return false; break; case CAPTURE: if (!infer_capture(newst, attacker, move, action, saw_sacrifice)) return false; break; case MOVE: case MOVE_CREATE: if (!infer_movement(newst, attacker, action, saw_sacrifice)) return false; break; case BUILD: if (!infer_build(newst, attacker, action, saw_sacrifice)) return false; break; case CONVERT: if (!infer_convert(newst, attacker, action, saw_sacrifice)) return false; break; } } /* Now we have either filled in the missing pieces of "action", * or bailed out by returning false. */ assert(!action.isMissingPieces()); assert(action.sanitycheck()); if (ApplyMove::Single(newst, attacker, action) != ApplyMove::Result::SUCCESS) { return false; } } return true; }
37.441758
119
0.529467
Quuxplusone
c928d5b6850cb5fd0810fd3139e9c93e3dbc93ff
2,147
cpp
C++
src/py/wrapper/wrapper_748e3ec2e85552f2ab39e490d409b414.cpp
StatisKit/Core
79d8ec07c203eb7973a6cf482852ddb2e8e1e93e
[ "Apache-2.0" ]
null
null
null
src/py/wrapper/wrapper_748e3ec2e85552f2ab39e490d409b414.cpp
StatisKit/Core
79d8ec07c203eb7973a6cf482852ddb2e8e1e93e
[ "Apache-2.0" ]
7
2018-03-20T14:23:16.000Z
2019-04-09T11:57:57.000Z
src/py/wrapper/wrapper_748e3ec2e85552f2ab39e490d409b414.cpp
StatisKit/Core
79d8ec07c203eb7973a6cf482852ddb2e8e1e93e
[ "Apache-2.0" ]
7
2017-04-28T07:41:01.000Z
2021-03-15T18:17:20.000Z
#include "_core.h" ::statiskit::Index (::statiskit::OptimizationEstimationImpl< ::statiskit::CategoricalUnivariateMixtureDistribution *, ::statiskit::CategoricalUnivariateMixtureDistribution, ::statiskit::CategoricalUnivariateDistributionEstimation >::*method_pointer_bda0d58ff17959ed95ba92c4ef5ae7cb)()const= &::statiskit::OptimizationEstimationImpl< struct ::statiskit::CategoricalUnivariateMixtureDistribution *, struct ::statiskit::CategoricalUnivariateMixtureDistribution, struct ::statiskit::CategoricalUnivariateDistributionEstimation >::size; namespace autowig { } void wrapper_748e3ec2e85552f2ab39e490d409b414(pybind11::module& module) { pybind11::class_<class ::statiskit::OptimizationEstimationImpl< struct ::statiskit::CategoricalUnivariateMixtureDistribution *, struct ::statiskit::CategoricalUnivariateMixtureDistribution, struct ::statiskit::CategoricalUnivariateDistributionEstimation >, autowig::HolderType< class ::statiskit::OptimizationEstimationImpl< struct ::statiskit::CategoricalUnivariateMixtureDistribution *, struct ::statiskit::CategoricalUnivariateMixtureDistribution, struct ::statiskit::CategoricalUnivariateDistributionEstimation > >::Type, class ::statiskit::ActiveEstimation< struct ::statiskit::CategoricalUnivariateMixtureDistribution, struct ::statiskit::CategoricalUnivariateDistributionEstimation > > class_748e3ec2e85552f2ab39e490d409b414(module, "_OptimizationEstimationImpl_748e3ec2e85552f2ab39e490d409b414", ""); class_748e3ec2e85552f2ab39e490d409b414.def(pybind11::init< >()); class_748e3ec2e85552f2ab39e490d409b414.def(pybind11::init< struct ::statiskit::CategoricalUnivariateMixtureDistribution const *, struct ::statiskit::UnivariateData const * >()); class_748e3ec2e85552f2ab39e490d409b414.def(pybind11::init< class ::statiskit::OptimizationEstimationImpl< struct ::statiskit::CategoricalUnivariateMixtureDistribution *, struct ::statiskit::CategoricalUnivariateMixtureDistribution, struct ::statiskit::CategoricalUnivariateDistributionEstimation > const & >()); class_748e3ec2e85552f2ab39e490d409b414.def("__len__", method_pointer_bda0d58ff17959ed95ba92c4ef5ae7cb, ""); }
126.294118
812
0.843037
StatisKit
c93096f74bb06058f3d4e810a4cd199fe14c789b
5,038
cxx
C++
Interaction/Widgets/vtkAbstractSplineRepresentation.cxx
cclauss/VTK
f62a52cce9044159efb4adb7cc0cfd7ec0bc8b6d
[ "BSD-3-Clause" ]
1,755
2015-01-03T06:55:00.000Z
2022-03-29T05:23:26.000Z
Interaction/Widgets/vtkAbstractSplineRepresentation.cxx
cclauss/VTK
f62a52cce9044159efb4adb7cc0cfd7ec0bc8b6d
[ "BSD-3-Clause" ]
29
2015-04-23T20:58:30.000Z
2022-03-02T16:16:42.000Z
Interaction/Widgets/vtkAbstractSplineRepresentation.cxx
cclauss/VTK
f62a52cce9044159efb4adb7cc0cfd7ec0bc8b6d
[ "BSD-3-Clause" ]
1,044
2015-01-05T22:48:27.000Z
2022-03-31T02:38:26.000Z
/*========================================================================= Program: Visualization Toolkit Module: vtkAbstractSplineRepresentation.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkAbstractSplineRepresentation.h" #include "vtkDoubleArray.h" #include "vtkParametricFunctionSource.h" #include "vtkParametricSpline.h" #include "vtkPolyDataMapper.h" #include "vtkRenderer.h" //------------------------------------------------------------------------------ vtkAbstractSplineRepresentation::vtkAbstractSplineRepresentation() { // Initialize pipeline configuration this->ParametricFunctionSource->SetScalarModeToNone(); this->ParametricFunctionSource->GenerateTextureCoordinatesOff(); this->ParametricFunctionSource->SetUResolution(this->Resolution); this->LineMapper->SetResolveCoincidentTopologyToPolygonOffset(); this->LineActor->SetMapper(this->LineMapper); } //------------------------------------------------------------------------------ vtkAbstractSplineRepresentation::~vtkAbstractSplineRepresentation() { this->SetParametricSplineInternal(nullptr); } //------------------------------------------------------------------------------ void vtkAbstractSplineRepresentation::CleanRepresentation() { this->LineMapper->SetInputConnection(nullptr); this->SetParametricSplineInternal(nullptr); } //------------------------------------------------------------------------------ void vtkAbstractSplineRepresentation::SetParametricSplineInternal(vtkParametricSpline* spline) { if (this->ParametricSpline != spline) { // to avoid destructor recursion vtkParametricSpline* temp = this->ParametricSpline; this->ParametricSpline = spline; if (temp != nullptr) { temp->UnRegister(this); } if (this->ParametricSpline != nullptr) { this->ParametricSpline->Register(this); this->ParametricFunctionSource->SetParametricFunction(this->ParametricSpline); } this->Modified(); } } //------------------------------------------------------------------------------ void vtkAbstractSplineRepresentation::SetParametricSpline(vtkParametricSpline* spline) { this->SetParametricSplineInternal(spline); } //------------------------------------------------------------------------------ vtkDoubleArray* vtkAbstractSplineRepresentation::GetHandlePositions() { return vtkArrayDownCast<vtkDoubleArray>(this->ParametricSpline->GetPoints()->GetData()); } //------------------------------------------------------------------------------ void vtkAbstractSplineRepresentation::SetResolution(int resolution) { if (this->Resolution == resolution || resolution < (this->NumberOfHandles - 1)) { return; } this->Resolution = resolution; this->ParametricFunctionSource->SetUResolution(this->Resolution); this->Modified(); } //------------------------------------------------------------------------------ void vtkAbstractSplineRepresentation::GetPolyData(vtkPolyData* pd) { if (!pd) { vtkErrorMacro(<< "ERROR: Invalid or nullptr polydata\n"); return; } this->ParametricFunctionSource->Update(); pd->ShallowCopy(this->ParametricFunctionSource->GetOutput()); } //------------------------------------------------------------------------------ double vtkAbstractSplineRepresentation::GetSummedLength() { vtkPoints* points = this->ParametricFunctionSource->GetOutput()->GetPoints(); int npts = points->GetNumberOfPoints(); if (npts < 2) { return 0.0; } double a[3]; double b[3]; double sum = 0.0; int i = 0; points->GetPoint(i, a); // check in which case we are: even or odd number of points // (else the last while loop iteration would go too far for an even number) int imax = (npts % 2 == 0) ? npts - 2 : npts - 1; while (i < imax) { points->GetPoint(i + 1, b); sum += sqrt(vtkMath::Distance2BetweenPoints(a, b)); i = i + 2; points->GetPoint(i, a); sum = sum + sqrt(vtkMath::Distance2BetweenPoints(a, b)); } if (npts % 2 == 0) { points->GetPoint(i + 1, b); sum += sqrt(vtkMath::Distance2BetweenPoints(a, b)); } return sum; } //------------------------------------------------------------------------------ void vtkAbstractSplineRepresentation::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "ParametricSpline: (" << this->ParametricSpline << "\n"; if (this->ParametricSpline) { this->ParametricSpline->PrintSelf(os, indent.GetNextIndent()); os << indent << ")\n"; } else { os << "none)\n"; } os << indent << "Resolution: " << this->Resolution << "\n"; }
30.907975
94
0.581977
cclauss
c935b56933ae6973b030fa7e611bf911b43362bf
1,156
cpp
C++
competitive programming/leetcode/2020-July-Challenge/Day-26-Add Digits.cpp
kashyap99saksham/Code
96658d0920eb79c007701d2a3cc9dbf453d78f96
[ "MIT" ]
16
2020-06-02T19:22:45.000Z
2022-02-05T10:35:28.000Z
competitive programming/leetcode/2020-July-Challenge/Day-26-Add Digits.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
null
null
null
competitive programming/leetcode/2020-July-Challenge/Day-26-Add Digits.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
2
2020-08-27T17:40:06.000Z
2022-02-05T10:33:52.000Z
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. Example: Input: 38 Output: 2 Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. Follow up: Could you do it without any loop/recursion in O(1) runtime? Hide Hint #1 A naive implementation of the above process is trivial. Could you come up with other methods? Hide Hint #2 What are all the possible results? Hide Hint #3 How do they occur, periodically or randomly? Hide Hint #4 You may find this Wikipedia article useful. class Solution { public: int addDigits(int num) { int digitalRoot = 0; while (num > 0) { digitalRoot += num % 10; num = num / 10; if (num == 0 && digitalRoot > 9) { num = digitalRoot; digitalRoot = 0; } } return digitalRoot; } }; class Solution { public: int addDigits(int num) { if (num == 0) return 0; if (num % 9 == 0) return 9; return num % 9; } };
19.266667
100
0.563149
kashyap99saksham
c936fe0dd64bf31918c0c92382614e1a40b655c2
1,101
hpp
C++
include/System/Threading/Mutex.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Threading/Mutex.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Threading/Mutex.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Threading.WaitHandle #include "System/Threading/WaitHandle.hpp" // Completed includes // Type namespace: System.Threading namespace System::Threading { // Forward declaring type: Mutex class Mutex; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::Threading::Mutex); DEFINE_IL2CPP_ARG_TYPE(::System::Threading::Mutex*, "System.Threading", "Mutex"); // Type namespace: System.Threading namespace System::Threading { // Size: 0x29 #pragma pack(push, 1) // Autogenerated type: System.Threading.Mutex // [TokenAttribute] Offset: FFFFFFFF // [ComVisibleAttribute] Offset: 683E3C class Mutex : public ::System::Threading::WaitHandle { public: }; // System.Threading.Mutex #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
34.40625
81
0.700272
v0idp
c9395ba269c386a05d320993fd999853206b271d
7,460
cpp
C++
tests/3d_examples/test_3d_myocaridum/src/muscle_activation.cpp
BenceVirtonomy/SPHinXsys
a86beb4f55fbf501677dac70a293025714f7e9e6
[ "Apache-2.0" ]
92
2019-05-29T10:20:47.000Z
2022-03-28T20:51:32.000Z
tests/3d_examples/test_3d_myocaridum/src/muscle_activation.cpp
ChiZhangatTUM/SPHinXsys
faa88cab07866f9ba5e370654ab3b515c46c6432
[ "Apache-2.0" ]
47
2019-07-18T09:37:11.000Z
2022-03-30T12:10:53.000Z
tests/3d_examples/test_3d_myocaridum/src/muscle_activation.cpp
Xiangyu-Hu/SPHinXsys
faa88cab07866f9ba5e370654ab3b515c46c6432
[ "Apache-2.0" ]
50
2019-05-29T10:20:57.000Z
2022-03-28T03:46:13.000Z
/** * @file muscle_activation.cpp * @brief This is the first example of electro activation of myocardium * @author Chi Zhang and Xiangyu Hu */ #include "sphinxsys.h" /** Name space. */ using namespace SPH; /** Geometry parameters. */ Real PL = 1.0; /**< Length. */ Real PH = 1.0; /**< Thickness for thick plate. */ Real PW = 1.0; /**< Width. */ /**< Initial particle spacing. */ Real resolution_ref = PH / 25.0; Real SL = 4.0 * resolution_ref; /**< Extension for holder. */ /** Domain bounds of the system. */ BoundingBox system_domain_bounds(Vecd(-SL, -SL, -SL), Vecd(PL + SL, PH + SL, PW + SL)); /**< SimTK geometric modeling resolution. */ int resolution(20); /** For material properties of the solid. */ Real rho_0 = 1.0; Real a_0[4] = {0.059, 0.0, 0.0, 0.0}; Real b_0[4] = {8.023, 0.0, 0.0, 0.0}; Vec3d fiber_direction(1.0, 0.0, 0.0); Vec3d sheet_direction(0.0, 1.0, 0.0); Real reference_voltage = 30.0; Real linear_active_stress_factor = - 0.5; /** reference stress to achieve weakly compressible condition */ Real bulk_modulus = 30.0 * reference_voltage * fabs(linear_active_stress_factor); /** Define the geometry. */ TriangleMeshShape* createMyocardium() { Vecd halfsize_myocardium(0.5 * (PL + SL), 0.5 * PH, 0.5 * PW); Vecd translation_myocardium(0.5 * (PL - SL), 0.5 * PH, 0.5*PW); TriangleMeshShape* geometry_myocardium = new TriangleMeshShape(halfsize_myocardium, resolution, translation_myocardium); return geometry_myocardium; } /** Define the holder geometry. */ TriangleMeshShape* CreateHolder() { Vecd halfsize_shape(0.5 * SL, 0.5 * PH, 0.5 * PW); Vecd translation_shape(-0.5 * SL, 0.5 * PH, 0.5 * PW); TriangleMeshShape* geometry = new TriangleMeshShape(halfsize_shape, resolution, translation_shape); return geometry; } /** Define the myocardium body. */ class Myocardium : public SolidBody { public: Myocardium(SPHSystem &system, std::string body_name) : SolidBody(system, body_name) { ComplexShapeTriangleMesh *mesh = new ComplexShapeTriangleMesh(); body_shape_ = new ComplexShape(mesh); mesh->addTriangleMeshShape(createMyocardium(), ShapeBooleanOps::add); } }; /** * @brief define the Holder base which will be constrained. * NOTE: this class can only be instanced after body particles * have been generated */ class Holder : public BodyPartByParticle { public: Holder(SolidBody *solid_body, std::string constrained_region_name) : BodyPartByParticle(solid_body, constrained_region_name) { ComplexShapeTriangleMesh *mesh = new ComplexShapeTriangleMesh(); body_part_shape_ = new ComplexShape(mesh); mesh->addTriangleMeshShape(CreateHolder(), ShapeBooleanOps::add); tagBodyPart(); } }; /** * Assign case dependent muscle activation histroy */ class MyocardiumActivation : public active_muscle_dynamics::MuscleActivation { public: MyocardiumActivation(SolidBody *myocardium) : active_muscle_dynamics::MuscleActivation(myocardium) {}; protected: void Update(size_t index_i, Real dt) override { Real voltage = pos_0_[index_i][0] <= 0 ? 0.0 : reference_voltage * pos_0_[index_i][0] / PL; active_contraction_stress_[index_i] += GlobalStaticVariables::physical_time_ <= 1.0 ? linear_active_stress_factor * voltage * dt : 0.0; }; }; class ConstrainHolder : public solid_dynamics::ConstrainSolidBodyRegion { public: ConstrainHolder(SolidBody* body, BodyPartByParticle* body_part, int axis_id) : solid_dynamics::ConstrainSolidBodyRegion(body, body_part), axis_id_(axis_id) {}; protected: int axis_id_; virtual Vecd getDisplacement(Vecd& pos_0, Vecd& pos_n) { Vecd pos_temp = pos_n; pos_temp[axis_id_] = pos_0[axis_id_]; return pos_temp; }; virtual Vecd getVelocity(Vecd& pos_0, Vecd& pos_n, Vecd& vel_n) { Vecd vel_temp = vel_n; vel_temp[axis_id_] = 0.0; return vel_temp; }; virtual Vecd getAcceleration(Vecd& pos_0, Vecd& pos_n, Vecd& dvel_dt) { Vecd dvel_dt_temp = dvel_dt; dvel_dt_temp[axis_id_] = 0.0; return dvel_dt_temp; }; }; /** * Setup material properties of myocardium */ class ActiveMyocardiumMuscle : public ActiveMuscle<Muscle> { public: ActiveMyocardiumMuscle() : ActiveMuscle<Muscle>() { rho0_ = rho_0; bulk_modulus_ = bulk_modulus; f0_ = fiber_direction; s0_ = sheet_direction; std::copy(a_0, a_0 + 4, a0_); std::copy(b_0, b_0 + 4, b0_); assignDerivedMaterialParameters(); } }; /** * The main program */ int main() { /** Setup the system. */ SPHSystem system(system_domain_bounds, resolution_ref); /** Creat a Myocardium body, corresponding material, particles and reaction model. */ Myocardium *myocardium_muscle_body = new Myocardium(system, "MyocardiumMuscleBody"); ActiveMyocardiumMuscle *active_myocardium_muscle = new ActiveMyocardiumMuscle(); ActiveMuscleParticles myocardium_muscle_particles(myocardium_muscle_body, active_myocardium_muscle); /** topology */ BodyRelationInner* myocardium_muscle_body_inner = new BodyRelationInner(myocardium_muscle_body); /** * This section define all numerical methods will be used in this case. */ /** Corrected strong configuration. */ solid_dynamics::CorrectConfiguration corrected_configuration_in_strong_form(myocardium_muscle_body_inner); /** Time step size calculation. */ solid_dynamics::AcousticTimeStepSize computing_time_step_size(myocardium_muscle_body); /** Compute the active contraction stress */ MyocardiumActivation myocardium_activation(myocardium_muscle_body); /** active and passive stress relaxation. */ solid_dynamics::StressRelaxationFirstHalf stress_relaxation_first_half(myocardium_muscle_body_inner); solid_dynamics::StressRelaxationSecondHalf stress_relaxation_second_half(myocardium_muscle_body_inner); /** Constrain region of the inserted body. */ ConstrainHolder constrain_holder(myocardium_muscle_body, new Holder(myocardium_muscle_body, "Holder"), 0); /** Output */ In_Output in_output(system); BodyStatesRecordingToVtu write_states(in_output, system.real_bodies_); /** * From here the time stepping begines. * Set the starting time. */ GlobalStaticVariables::physical_time_ = 0.0; system.initializeSystemCellLinkedLists(); system.initializeSystemConfigurations(); corrected_configuration_in_strong_form.parallel_exec(); write_states.writeToFile(0); /** Setup physical parameters. */ int ite = 0; Real end_time = 1.2; Real output_period = end_time / 60.0; Real dt = 0.0; /** Statistics for computing time. */ tick_count t1 = tick_count::now(); tick_count::interval_t interval; /** * Main loop */ while (GlobalStaticVariables::physical_time_ < end_time) { Real integration_time = 0.0; while (integration_time < output_period) { if (ite % 100 == 0) { std::cout << "N=" << ite << " Time: " << GlobalStaticVariables::physical_time_ << " dt: " << dt << "\n"; } myocardium_activation.parallel_exec(dt); stress_relaxation_first_half.parallel_exec(dt); constrain_holder.parallel_exec(dt); stress_relaxation_second_half.parallel_exec(dt); ite++; dt = computing_time_step_size.parallel_exec(); integration_time += dt; GlobalStaticVariables::physical_time_ += dt; } tick_count t2 = tick_count::now(); write_states.writeToFile(); tick_count t3 = tick_count::now(); interval += t3 - t2; } tick_count t4 = tick_count::now(); tick_count::interval_t tt; tt = t4 - t1 - interval; std::cout << "Total wall time for computation: " << tt.seconds() << " seconds." << std::endl; return 0; }
31.476793
102
0.732172
BenceVirtonomy
c93af6079e1309e3b8ad50a41e9976cd23f41d2a
3,231
cpp
C++
rh_engine_lib/Engine/VulkanImpl/VulkanTopLevelAccelerationStructure.cpp
petrgeorgievsky/gtaRenderHook
124358410c3edca56de26381e239ca29aa6dc1cc
[ "MIT" ]
232
2016-08-29T00:33:32.000Z
2022-03-29T22:39:51.000Z
rh_engine_lib/Engine/VulkanImpl/VulkanTopLevelAccelerationStructure.cpp
petrgeorgievsky/gtaRenderHook
124358410c3edca56de26381e239ca29aa6dc1cc
[ "MIT" ]
10
2021-01-02T12:40:49.000Z
2021-08-31T06:31:04.000Z
rh_engine_lib/Engine/VulkanImpl/VulkanTopLevelAccelerationStructure.cpp
petrgeorgievsky/gtaRenderHook
124358410c3edca56de26381e239ca29aa6dc1cc
[ "MIT" ]
40
2017-12-18T06:14:39.000Z
2022-01-29T16:35:23.000Z
// // Created by peter on 01.05.2020. // #include "VulkanTopLevelAccelerationStructure.h" #include "VulkanCommon.h" #include <DebugUtils/DebugLogger.h> #include <vk_mem_alloc.h> namespace rh::engine { VulkanTopLevelAccelerationStructure::VulkanTopLevelAccelerationStructure( const TLASCreateInfoVulkan &create_info ) : mDevice( create_info.mDevice ) { vk::AccelerationStructureCreateInfoNV vk_ac_create_info{}; mAccelInfo.instanceCount = create_info.mMaxInstanceCount; mAccelInfo.type = vk::AccelerationStructureTypeNV::eTopLevel; vk_ac_create_info.info = mAccelInfo; auto result = mDevice.createAccelerationStructureNV( vk_ac_create_info ); if ( !CALL_VK_API( result.result, TEXT( "Failed to create acceleration structure!" ) ) ) return; mAccel = result.value; vk::AccelerationStructureMemoryRequirementsInfoNV accelerationStructureMemoryRequirementsInfoNv{}; accelerationStructureMemoryRequirementsInfoNv.accelerationStructure = mAccel; vk::MemoryRequirements2 req = mDevice.getAccelerationStructureMemoryRequirementsNV( accelerationStructureMemoryRequirementsInfoNv ); // allocate /*VulkanMemoryAllocationInfo alloc_info{}; alloc_info.mRequirements = req.memoryRequirements; alloc_info.mDeviceLocal = true; mAccelMemory = create_info.mAllocator->AllocateDeviceMemory( alloc_info );*/ mAllocator = create_info.mAllocator->GetImpl(); VkMemoryRequirements requirements = req.memoryRequirements; VmaAllocationInfo allocationDetail{}; VmaAllocationCreateInfo allocationCreateInfo{}; allocationCreateInfo.usage = VmaMemoryUsage::VMA_MEMORY_USAGE_GPU_ONLY; // TODO: HANLE ERRORS vmaAllocateMemory( mAllocator, &requirements, &allocationCreateInfo, &mAllocation, &allocationDetail ); // bind vk::BindAccelerationStructureMemoryInfoNV bind_info{}; bind_info.accelerationStructure = mAccel; bind_info.memory = allocationDetail.deviceMemory; bind_info.memoryOffset = allocationDetail.offset; // bind_info.memory = mAccelMemory; if ( mDevice.bindAccelerationStructureMemoryNV( 1, &bind_info ) != vk::Result::eSuccess ) { debug::DebugLogger::Error( "Failed to bind TLAS memory!" ); std::terminate(); } // compute scratch size vk::AccelerationStructureMemoryRequirementsInfoNV memoryRequirementsInfo{ vk::AccelerationStructureMemoryRequirementsTypeNV::eBuildScratch, mAccel }; mScratchSize = mDevice .getAccelerationStructureMemoryRequirementsNV( memoryRequirementsInfo ) .memoryRequirements.size; } VulkanTopLevelAccelerationStructure::~VulkanTopLevelAccelerationStructure() { mDevice.destroyAccelerationStructureNV( mAccel ); vmaFreeMemory( mAllocator, mAllocation ); /*mDevice.destroyAccelerationStructureNV( mAccel ); mDevice.freeMemory( mAccelMemory );*/ } std::uint64_t VulkanTopLevelAccelerationStructure::GetScratchSize() { return mScratchSize; } } // namespace rh::engine
36.303371
80
0.715258
petrgeorgievsky
c93dcccfc5fae96bb019a3aeb4cb4a33037b75fb
333
hpp
C++
runtime/common.hpp
evanbowman/lisp
3471c44e615d1c4d40ae6657fa681edde7306fc8
[ "BSD-3-Clause" ]
1
2018-09-10T16:58:14.000Z
2018-09-10T16:58:14.000Z
runtime/common.hpp
evanbowman/lisp
3471c44e615d1c4d40ae6657fa681edde7306fc8
[ "BSD-3-Clause" ]
null
null
null
runtime/common.hpp
evanbowman/lisp
3471c44e615d1c4d40ae6657fa681edde7306fc8
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <stddef.h> #include <stdint.h> #include <vector> namespace ebl { using ImmediateId = uint16_t; using SymbolId = uint16_t; using StackLoc = uint16_t; using FrameDist = uint16_t; struct VarLoc { FrameDist frameDist_; StackLoc offset_; }; using Bytecode = std::vector<uint8_t>; } // namespace ebl
15.857143
38
0.714715
evanbowman
c93ed7ebc49915daae30d4c4bbb315e6ca0bb7cc
340
cpp
C++
cpp/libs/hello-cmake/hello/main.cpp
joaolsouzajr/labs
49b1287798b15ff1676b2eb0d89de6520c4218f0
[ "MIT" ]
null
null
null
cpp/libs/hello-cmake/hello/main.cpp
joaolsouzajr/labs
49b1287798b15ff1676b2eb0d89de6520c4218f0
[ "MIT" ]
null
null
null
cpp/libs/hello-cmake/hello/main.cpp
joaolsouzajr/labs
49b1287798b15ff1676b2eb0d89de6520c4218f0
[ "MIT" ]
null
null
null
#include <stdio.h> #include "hello.h" uint8_t buffer [] = {0x00, 0x00, 0x00,0x11, 0x01}; int main() { hello(); double value = (buffer[5] << 24) | (buffer[4] << 16) | (buffer[3] << 8) | (buffer[2]) | (buffer[1]); printf ("floats: %4.2f \n", value); cout << value << endl; return 0; }
18.888889
51
0.479412
joaolsouzajr
c93fe6acfb887be6ef19e8515de16d04d376e2c9
14,092
cpp
C++
die-json-test/testParserOK.cpp
thinlizzy/die-json
11e274fc219a2d6d0c3b4d77333248bc64cf0c81
[ "MIT" ]
1
2015-10-18T16:19:48.000Z
2015-10-18T16:19:48.000Z
die-json-test/testParserOK.cpp
thinlizzy/die-json
11e274fc219a2d6d0c3b4d77333248bc64cf0c81
[ "MIT" ]
null
null
null
die-json-test/testParserOK.cpp
thinlizzy/die-json
11e274fc219a2d6d0c3b4d77333248bc64cf0c81
[ "MIT" ]
null
null
null
#include <tut.h> #include "../die-json.h" #include <sstream> #include <iostream> #include <vector> #include <memory> namespace { struct Value { die::json::Parser::ObjectName name; die::json::ValueType valueType; die::json::Parser::ValueStr value; bool operator==(Value const & v) const { return name == v.name && valueType == v.valueType && value == v.value; }; bool operator!=(Value const & v) const { return ! operator==(v); } }; } namespace { struct setup { die::json::Parser parser; void parseSingleValue(std::string const & strToParse, die::json::ValueType valueType, die::json::Parser::ValueStr const & valueStr) { bool calledV = false; parser.value([&](auto name, auto type, auto value) { tut::ensure_equals(name, "name"); tut::ensure_equals(type, valueType); tut::ensure_equals(value, valueStr); calledV = true; }); std::istringstream iss(strToParse); auto parsed = parser.parse(iss); tut::ensure("parser did not reach final state", parsed); tut::ensure("value has not been called", calledV); } void setParserEvents(std::string & path, std::vector<Value> & values, std::vector<std::string> & arrays) { parser .startObject([&path](auto name) { path += name + "/"; }) .endObject([&path](auto name) { auto rem = name + "/"; auto p = path.rfind(rem); auto ok = p != std::string::npos && path.size() - p == rem.size(); tut::ensure(path + "does not end with " + rem, ok); path.resize(path.size() - rem.size()); }) .value([&values,&path](auto name, auto type, auto value) { values.push_back({path+name,type,value}); }) .startArray([&arrays](auto name) { arrays.push_back(name + '['); }) .endArray([&arrays](auto name) { arrays.push_back(name + ']'); }) ; } }; struct SingleCall { // shared_ptr is a needed kludge here because I am copying into std::function std::shared_ptr<bool> calledPtr = std::make_shared<bool>(false); std::string expectedName; bool called() const { return *calledPtr; } void operator()(std::string const & name) { tut::ensure_equals("regarding object name", expectedName, name); *calledPtr = true; } }; } std::ostream & operator<<(std::ostream & os, Value value) { return os << value.name << ',' << value.valueType << ',' << value.value; } namespace tut { using std::istringstream; typedef test_group<setup> tg; tg parser_test_group("JsonParserOK"); typedef tg::object testobject; template<> template<> void testobject::test<1>() { set_test_name("parse empty"); bool called = false; parser.startObject([&called](auto name) { ensure("root object name should be empty", name.empty()); called = true; }); istringstream iss("{}"); auto parsed = parser.parse(iss); ensure("parser did not reach final state", parsed); ensure("startObject has not been called", called); } template<> template<> void testobject::test<2>() { set_test_name("parse single string"); SingleCall startObj,endObj; parser .startObject(startObj) .endObject(endObj); bool calledV = false; parser.value([&calledV](auto name, auto type, auto value) { ensure_equals(name, "name"); ensure_equals(type, die::json::ValueType::string); ensure_equals(value, "value"); calledV = true; }); istringstream iss("{ \"name\" : \"value\" }"); auto parsed = parser.parse(iss); ensure("parser did not reach final state", parsed); ensure("startObject has not been called", startObj.called()); ensure("endObject has not been called", endObj.called()); ensure("value has not been called", calledV); } template<> template<> void testobject::test<3>() { set_test_name("string with escape and unicode"); parseSingleValue(R"json({ "name" : "\"value\" \ua1B0 \\ \/ \b\f\n\r\t" })json", die::json::ValueType::string, std::string(R"json("value" \ua1B0 \ / )json") + '\b' + '\f' + '\n' + '\r' + '\t'); } template<> template<> void testobject::test<4>() { set_test_name("parse keywords"); parseSingleValue("{ \"name\" : null }",die::json::ValueType::null,"null"); parseSingleValue("{ \"name\" : true }",die::json::ValueType::boolean,"true"); parseSingleValue("{ \n" "\"name\" : false \n" "}",die::json::ValueType::boolean,"false"); } template<> template<> void testobject::test<5>() { set_test_name("numbers"); parseSingleValue("{ \"name\" : 0 }",die::json::ValueType::number,"0"); parseSingleValue("{ \"name\" : 1029 }",die::json::ValueType::number,"1029"); parseSingleValue("{ \"name\" : -129 }",die::json::ValueType::number,"-129"); parseSingleValue("{ \"name\" : 0.3 }",die::json::ValueType::number,"0.3"); parseSingleValue("{ \"name\" : -1.324 }",die::json::ValueType::number,"-1.324"); parseSingleValue("{ \"name\" : -0.55 }",die::json::ValueType::number,"-0.55"); parseSingleValue("{ \"name\" : 0.55e10 }",die::json::ValueType::number,"0.55e10"); parseSingleValue("{ \"name\" : 55E+88 }",die::json::ValueType::number,"55E+88"); parseSingleValue("{ \"name\" : -4.5E-2878 }",die::json::ValueType::number,"-4.5E-2878"); parseSingleValue("{ \"name\" : 77.66e+20 }",die::json::ValueType::number,"77.66e+20"); } template<> template<> void testobject::test<6>() { set_test_name("more values"); std::vector<Value> values; parser.value([&values](auto name, auto type, auto value) { values.push_back({name,type,value}); }); istringstream iss("{ \n" "\"nameStr\" : \"value\" ,\n" "\"nameNum\" : 10,\n" "\"zero\" : 0,\n" " \"superTrue\":true,\n" "\"myNull\" : null,\n" "\"nameBool\" : false\n" " }"); auto parsed = parser.parse(iss); ensure("parser did not reach final state", parsed); ensure_equals(values.size(), 6); ensure_equals(values[0], Value{"nameStr", die::json::ValueType::string, "value"}); ensure_equals(values[1], Value{"nameNum", die::json::ValueType::number, "10"}); ensure_equals(values[2], Value{"zero", die::json::ValueType::number, "0"}); ensure_equals(values[3], Value{"superTrue", die::json::ValueType::boolean, "true"}); ensure_equals(values[4], Value{"myNull", die::json::ValueType::null, "null"}); ensure_equals(values[5], Value{"nameBool", die::json::ValueType::boolean, "false"}); } template<> template<> void testobject::test<7>() { set_test_name("nested objects"); std::string path; std::vector<Value> values; std::vector<std::string> arrays; setParserEvents(path,values,arrays); istringstream iss(R"json( { "nameStr" : "value", "object1" : { "zero":0, "nameStr" : "value", "placeholder" : null }, "object2" : {}, "anotherStr":"valueStr2", "object3" : { "numbah" : 0.5E-23, "nested" : { "meh" : null } }, "lastValue":-1 } )json"); auto parsed = parser.parse(iss); ensure("parser did not reach final state", parsed); ensure_equals(values.size(), 8); ensure_equals(values[0], Value{"/nameStr", die::json::ValueType::string, "value"}); ensure_equals(values[1], Value{"/object1/zero", die::json::ValueType::number, "0"}); ensure_equals(values[2], Value{"/object1/nameStr", die::json::ValueType::string, "value"}); ensure_equals(values[3], Value{"/object1/placeholder", die::json::ValueType::null, "null"}); ensure_equals(values[4], Value{"/anotherStr", die::json::ValueType::string, "valueStr2"}); ensure_equals(values[5], Value{"/object3/numbah", die::json::ValueType::number, "0.5E-23"}); ensure_equals(values[6], Value{"/object3/nested/meh", die::json::ValueType::null, "null"}); ensure_equals(values[7], Value{"/lastValue", die::json::ValueType::number, "-1"}); } template<> template<> void testobject::test<8>() { set_test_name("empty array"); SingleCall startObj,endObj,startArr,endArr; startArr.expectedName = "array"; endArr.expectedName = "array"; parser .startObject(startObj) .endObject(endObj) .startArray(startArr) .endArray(endArr); bool calledV = false; parser.value([&calledV](auto name, auto type, auto value) { calledV = true; }); istringstream iss("{ \"array\" : [] }"); auto parsed = parser.parse(iss); ensure("parser did not reach final state", parsed); ensure("startObject has not been called", startObj.called()); ensure("startArray has not been called", startArr.called()); ensure("endArray has not been called", endArr.called()); ensure("endObject has not been called", endObj.called()); ensure_not("value should never be called", calledV); } template<> template<> void testobject::test<9>() { set_test_name("arrays of values"); std::vector<Value> values; SingleCall startObj,endObj,startArr,endArr; startArr.expectedName = "array"; endArr.expectedName = "array"; parser .startObject(startObj) .endObject(endObj) .startArray(startArr) .endArray(endArr) .value([&values](auto name, auto type, auto value) { values.push_back({name,type,value}); }) ; istringstream iss("{ \"array\" : [ 1,2, null, \"oi\",false,0 ] }"); auto parsed = parser.parse(iss); ensure("parser did not reach final state", parsed); ensure("startObject has not been called", startObj.called()); ensure("startArray has not been called", startArr.called()); ensure("endArray has not been called", endArr.called()); ensure("endObject has not been called", endObj.called()); ensure_equals(values.size(), 6); ensure_equals(values[0], Value{"array", die::json::ValueType::number, "1"}); ensure_equals(values[1], Value{"array", die::json::ValueType::number, "2"}); ensure_equals(values[2], Value{"array", die::json::ValueType::null, "null"}); ensure_equals(values[3], Value{"array", die::json::ValueType::string, "oi"}); ensure_equals(values[4], Value{"array", die::json::ValueType::boolean, "false"}); ensure_equals(values[5], Value{"array", die::json::ValueType::number, "0"}); } template<> template<> void testobject::test<10>() { set_test_name("arrays of objects and values"); std::string path; std::vector<Value> values; std::vector<std::string> arrays; setParserEvents(path,values,arrays); istringstream iss(R"json( { "nameStr" : "value", "myObjects" : [ { "zero":0, "nameStr" : "value", "placeholder" : null }, {}, "valueStr2", { "numbah" : 0.5E-23, "nested" : { "meh" : null } }, -1 ], "otherArray" : [2,1] } )json"); auto parsed = parser.parse(iss); ensure("parser did not reach final state", parsed); ensure_equals(values.size(), 10); ensure_equals(values[0], Value{"/nameStr", die::json::ValueType::string, "value"}); ensure_equals(values[1], Value{"/myObjects/zero", die::json::ValueType::number, "0"}); ensure_equals(values[2], Value{"/myObjects/nameStr", die::json::ValueType::string, "value"}); ensure_equals(values[3], Value{"/myObjects/placeholder", die::json::ValueType::null, "null"}); ensure_equals(values[4], Value{"/myObjects", die::json::ValueType::string, "valueStr2"}); ensure_equals(values[5], Value{"/myObjects/numbah", die::json::ValueType::number, "0.5E-23"}); ensure_equals(values[6], Value{"/myObjects/nested/meh", die::json::ValueType::null, "null"}); ensure_equals(values[7], Value{"/myObjects", die::json::ValueType::number, "-1"}); ensure_equals(values[8], Value{"/otherArray", die::json::ValueType::number, "2"}); ensure_equals(values[9], Value{"/otherArray", die::json::ValueType::number, "1"}); ensure_equals(arrays.size(), 4); ensure_equals(arrays[0], "myObjects["); ensure_equals(arrays[1], "myObjects]"); ensure_equals(arrays[2], "otherArray["); ensure_equals(arrays[3], "otherArray]"); } template<> template<> void testobject::test<11>() { set_test_name("arrays of arrays"); std::string path; std::vector<Value> values; std::vector<std::string> arrays; setParserEvents(path,values,arrays); istringstream iss(R"json( { "myObjects" : [ 1, { "zero":0, "nameStr" : "value", "placeholder" : null }, "valueStr3", [1,2,3], { "numbah" : 0.5E-23, "nested" : { "meh" : null } }, [4,5,{ "six": [7,8,9], "ten" : null }, 11 ] ] } )json"); auto parsed = parser.parse(iss); ensure("parser did not reach final state", parsed); ensure_equals(values.size(), 17); ensure_equals(values[0], Value{"/myObjects", die::json::ValueType::number, "1"}); ensure_equals(values[1], Value{"/myObjects/zero", die::json::ValueType::number, "0"}); ensure_equals(values[2], Value{"/myObjects/nameStr", die::json::ValueType::string, "value"}); ensure_equals(values[3], Value{"/myObjects/placeholder", die::json::ValueType::null, "null"}); ensure_equals(values[4], Value{"/myObjects", die::json::ValueType::string, "valueStr3"}); ensure_equals(values[5], Value{"/myObjects", die::json::ValueType::number, "1"}); ensure_equals(values[6], Value{"/myObjects", die::json::ValueType::number, "2"}); ensure_equals(values[7], Value{"/myObjects", die::json::ValueType::number, "3"}); ensure_equals(values[8], Value{"/myObjects/numbah", die::json::ValueType::number, "0.5E-23"}); ensure_equals(values[9], Value{"/myObjects/nested/meh", die::json::ValueType::null, "null"}); ensure_equals(values[10], Value{"/myObjects", die::json::ValueType::number, "4"}); ensure_equals(values[11], Value{"/myObjects", die::json::ValueType::number, "5"}); ensure_equals(values[12], Value{"/myObjects/six", die::json::ValueType::number, "7"}); ensure_equals(values[13], Value{"/myObjects/six", die::json::ValueType::number, "8"}); ensure_equals(values[14], Value{"/myObjects/six", die::json::ValueType::number, "9"}); ensure_equals(values[15], Value{"/myObjects/ten", die::json::ValueType::null, "null"}); ensure_equals(values[16], Value{"/myObjects", die::json::ValueType::number, "11"}); ensure_equals(arrays.size(), 8); ensure_equals(arrays[0], "myObjects["); ensure_equals(arrays[1], "myObjects["); ensure_equals(arrays[2], "myObjects]"); ensure_equals(arrays[3], "myObjects["); ensure_equals(arrays[4], "six["); ensure_equals(arrays[5], "six]"); ensure_equals(arrays[6], "myObjects]"); ensure_equals(arrays[7], "myObjects]"); } }
33.002342
133
0.650156
thinlizzy
c9456221164d502c9c31eb9be474df6aaef0e7b8
2,909
cc
C++
outboundbot/src/model/ListResourceTagsResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
outboundbot/src/model/ListResourceTagsResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
outboundbot/src/model/ListResourceTagsResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/outboundbot/model/ListResourceTagsResult.h> #include <json/json.h> using namespace AlibabaCloud::OutboundBot; using namespace AlibabaCloud::OutboundBot::Model; ListResourceTagsResult::ListResourceTagsResult() : ServiceResult() {} ListResourceTagsResult::ListResourceTagsResult(const std::string &payload) : ServiceResult() { parse(payload); } ListResourceTagsResult::~ListResourceTagsResult() {} void ListResourceTagsResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto resourceTagsNode = value["ResourceTags"]; if(!resourceTagsNode["TotalCount"].isNull()) resourceTags_.totalCount = std::stoi(resourceTagsNode["TotalCount"].asString()); if(!resourceTagsNode["PageNumber"].isNull()) resourceTags_.pageNumber = std::stoi(resourceTagsNode["PageNumber"].asString()); if(!resourceTagsNode["PageSize"].isNull()) resourceTags_.pageSize = std::stoi(resourceTagsNode["PageSize"].asString()); auto allListNode = resourceTagsNode["List"]["ResourceTag"]; for (auto resourceTagsNodeListResourceTag : allListNode) { ResourceTags::ResourceTag resourceTagObject; if(!resourceTagsNodeListResourceTag["Key"].isNull()) resourceTagObject.key = resourceTagsNodeListResourceTag["Key"].asString(); if(!resourceTagsNodeListResourceTag["Value"].isNull()) resourceTagObject.value = resourceTagsNodeListResourceTag["Value"].asString(); resourceTags_.list.push_back(resourceTagObject); } if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; if(!value["Code"].isNull()) code_ = value["Code"].asString(); if(!value["Message"].isNull()) message_ = value["Message"].asString(); if(!value["HttpStatusCode"].isNull()) httpStatusCode_ = std::stoi(value["HttpStatusCode"].asString()); } std::string ListResourceTagsResult::getMessage()const { return message_; } ListResourceTagsResult::ResourceTags ListResourceTagsResult::getResourceTags()const { return resourceTags_; } int ListResourceTagsResult::getHttpStatusCode()const { return httpStatusCode_; } std::string ListResourceTagsResult::getCode()const { return code_; } bool ListResourceTagsResult::getSuccess()const { return success_; }
30.621053
83
0.759367
aliyun
c945a5d43a215a57d44512dc6586a9dc74236a81
3,115
cpp
C++
ModuleSceneIntro.cpp
Denisdrk6/Ignition-Engine
bd23fa119452356fce5047236b09b2243346be3e
[ "MIT" ]
1
2021-09-29T14:50:17.000Z
2021-09-29T14:50:17.000Z
ModuleSceneIntro.cpp
Denisdrk6/Ignition-Engine
bd23fa119452356fce5047236b09b2243346be3e
[ "MIT" ]
null
null
null
ModuleSceneIntro.cpp
Denisdrk6/Ignition-Engine
bd23fa119452356fce5047236b09b2243346be3e
[ "MIT" ]
null
null
null
#include "Globals.h" #include "Application.h" #include "ModuleSceneIntro.h" #include "Primitive.h" #include "imgui/imgui.h" #include "FbxLoader.h" #include "ModuleCamera3D.h" #include "ModuleRenderer3D.h" ModuleSceneIntro::ModuleSceneIntro(Application* app, bool start_enabled) : Module(app, start_enabled) { } ModuleSceneIntro::~ModuleSceneIntro() {} // Load assets bool ModuleSceneIntro::Start() { App->log->AddLog("Loading Intro Scene\n"); bool ret = true; App->fbx->LoadFbx("Assets/BakerHouse.fbx"); //game_objects.push_back(CreateGameObject()); return ret; } // Update: draw scene update_status ModuleSceneIntro::Update(float dt) { bool ret = true; PrimPlane p(0, 1, 0, 0); p.axis = true; p.Render(); //LOAD FBX 3 for (int i = 0; !App->fbx->meshes.empty() && (i < App->fbx->meshes.size()); i++) App->renderer3D->DrawMesh(App->fbx->meshes.at(i)); for (int i = 0; i < game_objects.size(); i++) game_objects.at(i)->Update(); return UPDATE_CONTINUE; } // Load assets bool ModuleSceneIntro::CleanUp() { App->log->AddLog("Unloading Intro scene\n"); for (int i = 0; i < game_objects.size(); i++) { game_objects.at(i)->CleanUp(); RELEASE(game_objects.at(i)); } game_objects.clear(); /* //__________Unbind buffers____________ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_TEXTURE_COORD_ARRAY, 0); glBindBuffer(GL_TEXTURE_2D, 0); //___________DISABLE STATES__________ glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); */ return true; } GameObject* ModuleSceneIntro::CreateGameObject() { GameObject* gameObject = new GameObject(); return gameObject; } void ModuleSceneIntro::DrawHierarchy() { ImGui::SetNextWindowSize({ 300.0f, (float)App->window->height - 220.0f }); ImGui::SetNextWindowPos({ 0.0f, 20.0f }); // Main menu bar is 20px high ImGui::Begin("Hierarchy", (bool*)true, ImGuiWindowFlags_NoCollapse); // Cannot be manually closed by user for (int i = 0; i < game_objects.size(); i++) { if (game_objects[i]->children.size() > 0) { if (ImGui::TreeNodeEx(game_objects[i]->name.c_str())) { for (int j = 0; j < game_objects[i]->children.size(); j++) { DrawRecursive(game_objects[i]->children[j]); } ImGui::TreePop(); } } else { ImGui::Text(game_objects[i]->name.c_str()); } } //if (ImGui::IsItemClicked()) ImGui::End(); } void ModuleSceneIntro::DrawRecursive(GameObject* parent) { if (parent->children.size() > 0) { if (ImGui::TreeNodeEx(parent->name.c_str())) { for (int j = 0; j < parent->children.size(); j++) { DrawRecursive(parent->children[j]); } ImGui::TreePop(); } } else { ImGui::Text(parent->name.c_str()); } }
21.93662
109
0.597111
Denisdrk6
c94a6a3b468b75bccc3302a626c5541cb1c265ef
843
cpp
C++
PacManState/src/level/LevelManager.cpp
BeardedPlatypus/PacMan
319e9776582cf9118b38c72d31855fb4c598e986
[ "MIT" ]
5
2019-12-23T22:45:46.000Z
2021-11-11T06:27:12.000Z
PacManState/src/level/LevelManager.cpp
BeardedPlatypus/PacMan
319e9776582cf9118b38c72d31855fb4c598e986
[ "MIT" ]
null
null
null
PacManState/src/level/LevelManager.cpp
BeardedPlatypus/PacMan
319e9776582cf9118b38c72d31855fb4c598e986
[ "MIT" ]
1
2021-11-11T06:27:14.000Z
2021-11-11T06:27:14.000Z
#include "stdafx.h" #include "level/LevelManager.h" namespace pacman { namespace state { namespace level { LevelManager::LevelManager(unsigned int n_dots) : _total_n_dots(n_dots) { } inline unsigned int LevelManager::GetCurrentLevel() const { return this->_current_level; } void LevelManager::IncrementCurrentLevel() { this->_current_level += 1; this->_consumed_dots = 0; } inline unsigned int LevelManager::GetTotalNDots() const { return this->_total_n_dots; } inline unsigned int LevelManager::GetDotsLeftInCurrentLevel() const { return this->GetTotalNDots() - this->GetDotsConsumedInCurrentLevel(); } inline unsigned int LevelManager::GetDotsConsumedInCurrentLevel() const { return this->_consumed_dots; } inline void LevelManager::IncrementDotsConsumedInCurrentLevel() { this->_consumed_dots += 1; } } } }
19.159091
75
0.756821
BeardedPlatypus
c94d50615309a9c267780d41da3124b59fd2a703
2,443
cpp
C++
Ch9_2/Ch9_2/Source.cpp
Es10liv/mcc.cplusplus
23150f2fd5a56dbacc7c1809455e4e85d1fdd29e
[ "MIT" ]
null
null
null
Ch9_2/Ch9_2/Source.cpp
Es10liv/mcc.cplusplus
23150f2fd5a56dbacc7c1809455e4e85d1fdd29e
[ "MIT" ]
null
null
null
Ch9_2/Ch9_2/Source.cpp
Es10liv/mcc.cplusplus
23150f2fd5a56dbacc7c1809455e4e85d1fdd29e
[ "MIT" ]
null
null
null
// Chapter 7 programming challenge 2 test scores #include<iostream> #include<iomanip> using namespace std; // prototype functions void sort(double*, int); double average(double*, int); int main() { // create variables // number of test scores int intTestScores; // pointer to array double *testScorePtr; // average test score double dblTestAverage; // get the number of test scores cout << "How many test scores will you enter?" << endl; cin >> intTestScores; // validate the input prevent user from entering a negative number while (intTestScores < 0) { cout << "The number cannot be negative." << endl; cout << "Enter another number: "; cin >> intTestScores; } // create the array to hold test scores testScorePtr = new double[intTestScores]; // fill the array with a loop for (int count = 0; count < intTestScores; count++) { cout << "\nEnter The test score for test # " << (count + 1) << ": "; cin >> testScorePtr[count]; while (testScorePtr[count] < 0) { cout << "The number cannot be negative." << endl; cout << "Enter another number: "; cin >> intTestScores; } } // sort the test scores sort(testScorePtr, intTestScores); // get the average of the test scores dblTestAverage = average(testScorePtr, intTestScores); // display the sort result and the averages cout << "The average of all tests: " << dblTestAverage << endl; delete[] testScorePtr; testScorePtr = 0; return 0; } // write a function to sort the array in ascending order void sort(double* score, int size) { int startScan, minIndex; double minValue; for (startScan = 0; startScan < (size - 1); startScan++) { minIndex = startScan; minValue = *(score + startScan); for (int index = startScan + 1; index < size; index++) { if (*(score + index) < minValue) { minValue = *(score + index); minIndex = index; } } *(score + minIndex) = *(score + startScan); *(score + startScan) = minValue; } } // Write a function to calculate the average using a pointer to the array of scores double average(double *score, int size) { double total = 0.00; double dblTotalAverage; cout << fixed << showpoint << setprecision(2); for (int count = 0; count < size; count++) { total += *score; score++; dblTotalAverage = total / size; } return dblTotalAverage; }
22.209091
84
0.635694
Es10liv
c94dcf7aa68ccef0767ae0e7a64e6447efd8ca84
3,394
cpp
C++
bin/libs/systemc-2.3.1/src/sysc/datatypes/fx/scfx_pow10.cpp
buaawj/Research
23bf0d0df67f80b7a860f9d2dc3f30b60554c26d
[ "OML" ]
9
2019-07-15T10:05:29.000Z
2022-03-14T12:55:19.000Z
bin/libs/systemc-2.3.1/src/sysc/datatypes/fx/scfx_pow10.cpp
buaawj/Research
23bf0d0df67f80b7a860f9d2dc3f30b60554c26d
[ "OML" ]
2
2019-11-30T23:27:47.000Z
2021-11-02T12:01:05.000Z
systemc-2.3.1/src/sysc/datatypes/fx/scfx_pow10.cpp
tianzhuqiao/bsmedit
3e443ed6db7b44b3b0da0e4bc024b65dcfe8e7a4
[ "MIT" ]
null
null
null
/***************************************************************************** The following code is derived, directly or indirectly, from the SystemC source code Copyright (c) 1996-2014 by all Contributors. All Rights reserved. The contents of this file are subject to the restrictions and limitations set forth in the SystemC Open Source License (the "License"); You may not use this file except in compliance with such restrictions and limitations. You may obtain instructions on how to receive a copy of the License at http://www.accellera.org/. Software distributed by Contributors under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. *****************************************************************************/ /***************************************************************************** scfx_pow10.cpp - Original Author: Robert Graulich, Synopsys, Inc. Martin Janssen, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ // $Log: scfx_pow10.cpp,v $ // Revision 1.1.1.1 2006/12/15 20:20:04 acg // SystemC 2.3 // // Revision 1.3 2006/01/13 18:53:58 acg // Andy Goodrich: added $Log command so that CVS comments are reproduced in // the source. // #include "sysc/datatypes/fx/scfx_pow10.h" namespace sc_dt { // ---------------------------------------------------------------------------- // CLASS : scfx_pow10 // // Class to compute (and cache) powers of 10 in arbitrary precision. // ---------------------------------------------------------------------------- scfx_pow10::scfx_pow10() { m_pos[0] = scfx_rep( 10.0 ); m_neg[0] = scfx_rep( 0.1 ); for( int i = 1; i < SCFX_POW10_TABLE_SIZE; i ++ ) { m_pos[i].set_nan(); m_neg[i].set_nan(); } } scfx_pow10::~scfx_pow10() {} const scfx_rep scfx_pow10::operator() ( int i ) { if( i == 0 ) { return scfx_rep( 1.0 ); } if( i > 0 ) { int bit = scfx_find_msb( i ); scfx_rep result = *pos( bit ); if( bit ) { while( -- bit >= 0 ) { if( ( 1 << bit ) & i ) { scfx_rep* tmp = mult_scfx_rep( result, *pos( bit ) ); result = *tmp; delete tmp; } } } return result; } else { i = -i; int bit = scfx_find_msb( i ); scfx_rep result = *neg( bit ); if( bit ) { while( -- bit >= 0 ) { if( ( 1 << bit ) & i ) { scfx_rep* tmp = mult_scfx_rep( result, *neg( bit ) ); result = *tmp; delete tmp; } } } return result; } } scfx_rep* scfx_pow10::pos( int i ) { if( ! m_pos[i].is_normal() ) { multiply( m_pos[i], *pos( i - 1 ), *pos( i - 1 ) ); } return &m_pos[i]; } scfx_rep* scfx_pow10::neg( int i ) { if( ! m_neg[i].is_normal() ) { multiply( m_neg[i], *neg( i - 1 ), *neg( i - 1 ) ); } return &m_neg[i]; } } // namespace sc_dt // Taf!
23.246575
79
0.489393
buaawj
c94fee71ae262ecc5cd5d2c79b3b955f2f5ed8b2
4,328
cpp
C++
tests/test_ocp_to_nlp.cpp
tgurriet/smooth_feedback
1f926cb4269741ddc09ba048af5bea5e0390a053
[ "MIT" ]
null
null
null
tests/test_ocp_to_nlp.cpp
tgurriet/smooth_feedback
1f926cb4269741ddc09ba048af5bea5e0390a053
[ "MIT" ]
null
null
null
tests/test_ocp_to_nlp.cpp
tgurriet/smooth_feedback
1f926cb4269741ddc09ba048af5bea5e0390a053
[ "MIT" ]
null
null
null
// smooth_feedback: Control theory on Lie groups // https://github.com/pettni/smooth_feedback // // Licensed under the MIT License <http://opensource.org/licenses/MIT>. // // Copyright (c) 2021 Petter Nilsson // // 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, EVecPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <gtest/gtest.h> #include <Eigen/Core> #include <smooth/so3.hpp> #include "smooth/feedback/ocp_to_nlp.hpp" template<typename T, std::size_t N> using Vec = Eigen::Vector<T, N>; TEST(OcpToNlp, Derivatives2) { // objective auto theta = []<typename T>(T tf, Vec<T, 2> x0, Vec<T, 2> xf, Vec<T, 1> q) -> T { return (tf - 2) * (tf - 2) + x0.cwiseProduct(xf).squaredNorm() + xf.squaredNorm() + q.sum(); }; // dynamics auto f = []<typename T>(T t, Vec<T, 2> x, Vec<T, 1> u) -> Vec<T, 2> { return Vec<T, 2>{{x.y() + t, x.x() * u.x() * u.x()}}; }; // integrals auto g = []<typename T>(T t, Vec<T, 2> x, Vec<T, 1> u) -> Vec<T, 1> { return Vec<T, 1>{{t + t * x.squaredNorm() + u.squaredNorm()}}; }; // running constraint auto cr = []<typename T>(T t, Vec<T, 2> x, Vec<T, 1> u) -> Vec<T, 4> { Vec<T, 4> ret(4); ret << t, t * x * u.x(), u.cwiseAbs2(); return ret; }; // end constraint auto ce = []<typename T>(T tf, Vec<T, 2> x0, Vec<T, 2> xf, Vec<T, 1> q) -> Vec<T, 6> { Vec<T, 6> ret(6); ret << tf, x0.cwiseProduct(xf), xf, q.cwiseAbs2(); return ret; }; const smooth::feedback::OCP< Vec<double, 2>, Vec<double, 1>, decltype(theta), decltype(f), decltype(g), decltype(cr), decltype(ce)> ocp{ .theta = theta, .f = f, .g = g, .cr = cr, .crl = Vec<double, 4>::Constant(4, -1), .cru = Vec<double, 4>::Constant(4, 1), .ce = ce, .cel = Vec<double, 6>::Constant(6, -1), .ceu = Vec<double, 6>::Constant(6, 1), }; smooth::feedback::Mesh<3, 3> mesh; mesh.refine_ph(0, 4); mesh.refine_ph(0, 4); auto nlp = ocp_to_nlp(ocp, mesh); using nlp_t = std::decay_t<decltype(nlp)>; static_assert(smooth::feedback::HessianNLP<nlp_t>); srand(5); const Eigen::VectorXd x = Eigen::VectorXd::Random(nlp.n()); const Eigen::VectorXd lambda = Eigen::VectorXd::Random(nlp.m()); // Analytic derivatives const auto & df_dx = nlp.df_dx(x); const auto & d2f_dx2 = nlp.d2f_dx2(x); const auto & dg_dx = nlp.dg_dx(x); const auto & d2g_dx2 = nlp.d2g_dx2(x, lambda); // Numerical derivatives (of base function) const auto [fval, df_dx_num, d2f_dx2_num] = smooth::diff::dr<2>([&](const auto & xvar) { return nlp.f(xvar); }, smooth::wrt(x)); const auto [gval, dg_dx_num] = smooth::diff::dr<1>([&](const auto & xvar) { return nlp.g(xvar); }, smooth::wrt(x)); const auto g_l_fun = [&](Eigen::VectorXd xvar) -> double { return lambda.dot(nlp.g(xvar)); }; const auto [u1_, u2_, d2g_dx2_num] = smooth::diff::dr<2>(g_l_fun, smooth::wrt(x)); ASSERT_TRUE(Eigen::MatrixXd(df_dx).isApprox(df_dx_num, 1e-4)); ASSERT_TRUE(Eigen::MatrixXd(dg_dx).isApprox(dg_dx_num, 1e-4)); ASSERT_TRUE(Eigen::MatrixXd(Eigen::MatrixXd(d2f_dx2).selfadjointView<Eigen::Upper>()) .isApprox(d2f_dx2_num, 1e-3)); ASSERT_TRUE(Eigen::MatrixXd(Eigen::MatrixXd(d2g_dx2).selfadjointView<Eigen::Upper>()) .isApprox(d2g_dx2_num, 1e-3)); }
35.768595
96
0.635628
tgurriet
c95042c83710813b2cd789db3d28d034608323c1
1,262
cc
C++
core/MediaLoader.cc
jjzhang166/mous
54a219712970bd6fabbac85102e1615babb69c41
[ "BSD-2-Clause" ]
1
2018-04-04T05:48:37.000Z
2018-04-04T05:48:37.000Z
core/MediaLoader.cc
aliakbarRashidi/mous
54a219712970bd6fabbac85102e1615babb69c41
[ "BSD-2-Clause" ]
null
null
null
core/MediaLoader.cc
aliakbarRashidi/mous
54a219712970bd6fabbac85102e1615babb69c41
[ "BSD-2-Clause" ]
null
null
null
#include <core/MediaLoader.h> #include <core/Plugin.h> #include "MediaLoaderImpl.h" namespace mous { MediaLoader::MediaLoader() : impl(std::make_unique<Impl>()) { } MediaLoader::~MediaLoader() { } void MediaLoader::RegisterSheetParserPlugin(const Plugin* pAgent) { return impl->RegisterSheetParserPlugin(pAgent); } void MediaLoader::RegisterSheetParserPlugin(std::vector<const Plugin*>& agents) { return impl->RegisterSheetParserPlugin(agents); } void MediaLoader::RegisterTagParserPlugin(const Plugin* pAgent) { return impl->RegisterTagParserPlugin(pAgent); } void MediaLoader::RegisterTagParserPlugin(std::vector<const Plugin*>& agents) { return impl->RegisterTagParserPlugin(agents); } void MediaLoader::UnregisterPlugin(const Plugin* pAgent) { return impl->UnregisterPlugin(pAgent); } void MediaLoader::UnregisterPlugin(std::vector<const Plugin*>& agents) { return impl->UnregisterPlugin(agents); } void MediaLoader::UnregisterAll() { return impl->UnregisterAll(); } std::vector<std::string> MediaLoader::SupportedSuffixes() const { return impl->SupportedSuffixes(); } ErrorCode MediaLoader::LoadMedia(const std::string& path, std::deque<MediaItem>& list) const { return impl->LoadMedia(path, list); } }
20.031746
92
0.747227
jjzhang166
c951da414e3efd7073d6e7a9fab62c0d2b7d76e6
3,889
cpp
C++
challenge_4/cpp/dewie102/src/BinaryTree.cpp
rchicoli/2017-challenges
44f0b672e5dea34de1dde131b6df837d462f8e29
[ "Apache-2.0" ]
271
2017-01-01T22:58:36.000Z
2021-11-28T23:05:29.000Z
challenge_4/cpp/dewie102/src/BinaryTree.cpp
AakashOfficial/2017Challenges
a8f556f1d5b43c099a0394384c8bc2d826f9d287
[ "Apache-2.0" ]
283
2017-01-01T23:26:05.000Z
2018-03-23T00:48:55.000Z
challenge_4/cpp/dewie102/src/BinaryTree.cpp
AakashOfficial/2017Challenges
a8f556f1d5b43c099a0394384c8bc2d826f9d287
[ "Apache-2.0" ]
311
2017-01-01T22:59:23.000Z
2021-09-23T00:29:12.000Z
#include "include/BinaryTree.h" // Set root node to null to avoid errors BST::BST () { m_root = nullptr; } // Call the delete tree function to free up memory BST::~BST () { DeleteTree (); } void BST::CreateNode (int l_value) { if (m_root != nullptr) { // If the root node exsits call the create node function using the root as the starting point CreateNode (l_value, m_root); } else { // If the root node does not exsit, create it m_root = new Node; m_root->m_value = l_value; m_root->m_left = nullptr; m_root->m_right = nullptr; } } void BST::DeleteTree () { if (m_root != nullptr) { // If the root node is not null then start the recursive call to delete node starting at the root. DeleteTree (m_root); } } Node* BST::Search (int l_value) { return Search (l_value, m_root); // Search for a given value starting at the root. } void BST::PrintTree () { if (m_root != nullptr) { PrintTree (m_root); // Start a recursive call to print out the tree, starting at the root } else { std::cout << "Binary Tree is Empty" << std::endl; } } void BST::InvertTree () { if (m_root != nullptr) { InvertTree (m_root); // Start a recursive call to invert the tree, starting at the root } } void BST::CreateNode (int l_value, Node* l_leaf) { if (l_leaf != nullptr) { // Make sure hte leaf is not null to avoid access violations if (l_value > l_leaf->m_value) { // If the value is greater than, add it to the right of the tree if (l_leaf->m_right == nullptr) { // If the node to the right is null, create it there. Node* leaf = new Node; leaf->m_value = l_value; leaf->m_left = nullptr; leaf->m_right = nullptr; l_leaf->m_right = leaf; } else { CreateNode (l_value, l_leaf->m_right); // Else recursively check right. } } else if (l_value < l_leaf->m_value) { // If the value is less than, add it to the left of the tree if (l_leaf->m_left == nullptr) { // If the node to the left is null, create it there. Node* leaf = new Node; leaf->m_value = l_value; leaf->m_left = nullptr; leaf->m_right = nullptr; l_leaf->m_left = leaf; } else { CreateNode (l_value, l_leaf->m_left); // Else recursively check left. } } else { return; } } } void BST::DeleteTree (Node* l_leaf) { if (l_leaf != nullptr) { DeleteTree(l_leaf->m_left); // Recursively delete the left child node DeleteTree(l_leaf->m_right); // Recursively delete the right child node delete l_leaf; // Delete the current node } } Node* BST::Search (int l_value, Node* l_leaf) { if (m_root != nullptr) { // Make sure the root is not null if (l_leaf != nullptr) { // Make sure the node is not null if (l_leaf->m_value == l_value) { // if the node value is equal to the searched, return the node return l_leaf; } else { if (l_value > l_leaf->m_value) { Search (l_value, l_leaf->m_right); // If the value is greater than, check right child node } else if (l_value < l_leaf->m_value) { Search (l_value, l_leaf->m_left); // If the value is less than check left child node } } } } return nullptr; } void BST::PrintTree (Node* l_leaf) { if (l_leaf != nullptr) { if (l_leaf->m_left != nullptr) { PrintTree (l_leaf->m_left); // Recursively print left node } std::cout << l_leaf->m_value << " "; // Print current node value if (l_leaf->m_right != nullptr) { PrintTree (l_leaf->m_right); // Recursively print right node } } } void BST::InvertTree (Node* l_leaf) { if (l_leaf != nullptr) { InvertTree (l_leaf->m_left); // Recursively invert the left child nodes InvertTree (l_leaf->m_right); // Recursively inver the right child nodes Node* temp = l_leaf->m_left; // Temp node for storage of the left node. l_leaf->m_left = l_leaf->m_right; // Switch the left node for the right node l_leaf->m_right = temp; // Set the right node equal to the temp } return; }
30.147287
124
0.662124
rchicoli
c95225d585036ca147288de29f0ad287be22dc49
4,463
cc
C++
src/tools/main_extract_state_from_snaps.cc
Zhang690683220/SHAW
867f0f02114cc339e657714cfaf17887d7e5caae
[ "BSD-3-Clause" ]
null
null
null
src/tools/main_extract_state_from_snaps.cc
Zhang690683220/SHAW
867f0f02114cc339e657714cfaf17887d7e5caae
[ "BSD-3-Clause" ]
null
null
null
src/tools/main_extract_state_from_snaps.cc
Zhang690683220/SHAW
867f0f02114cc339e657714cfaf17887d7e5caae
[ "BSD-3-Clause" ]
null
null
null
#include "CLI11.hpp" #include "Kokkos_Core.hpp" #include "../shared/constants.hpp" #include "../shared/meta/meta_kokkos.hpp" #include "../shared/io/matrix_write.hpp" #include "../shared/io/matrix_read.hpp" #include "../shared/io/vector_write.hpp" #include "utility" int main(int argc, char *argv[]) { CLI::App app{"Extract state(s) at target time steps from a snapshot matrix"}; using pair_t = std::pair<std::string, std::string>; pair_t snaps = {}; std::size_t fSize = 1; std::vector<std::size_t> timeSteps = {}; std::size_t samplingFreq = {}; std::string outputFormat = {}; std::string outFileAppend = {}; app.add_option("--snaps", snaps, "Pair: fullpath_to_snaps binary/ascii")->required(); app.add_option("--samplingfreq", samplingFreq, "Sampling freq used to save snapshot")->required(); app.add_option("--fsize", fSize, "Forcing size used to generate snapshots")->required(); app.add_option("--timesteps", timeSteps, "Target time steps to extract")->required(); app.add_option("--outformat", outputFormat, "Outputformat: binary/ascii")->required(); app.add_option("--outfileappend", outFileAppend, "String to append to output file"); CLI11_PARSE(app, argc, argv); std::cout << "snaps file = " << std::get<0>(snaps) << std::endl; std::cout << "snaps format = " << std::get<1>(snaps) << std::endl; std::cout << "Size of f = " << fSize << std::endl; if (timeSteps[0]==-1){ std::cout << "Target time steps = only last step"; } else{ std::cout << "Target time steps = "; for (auto & it : timeSteps) std::cout << it << " "; std::cout << std::endl; } std::cout << "Sampling freq = " << samplingFreq << std::endl; std::cout << "Output format = " << outputFormat << std::endl; //------------------------------------------------------------ const auto snapFile = std::get<0>(snaps); const bool snapBinary = std::get<1>(snaps)=="binary"; // on input, we have the time steps so we need to convert // from time steps to indices of the snapsshopt matrix std::vector<int> targetIndices = {}; for (auto it : timeSteps){ targetIndices.push_back( it / samplingFreq ); } //------------------------------------------------------------ Kokkos::initialize(); //argc, argv); { using sc_t = double; using kll = Kokkos::LayoutLeft; if (fSize == 1) { //////////////////////////// // this is rank-1 case //////////////////////////// // *** load states *** using snap_t = Kokkos::View<sc_t**, kll, Kokkos::HostSpace>; snap_t snaps("snaps", 1, 1); if (snapBinary){ readBinaryMatrixWithSize(snapFile, snaps); } else{ readAsciiMatrixWithSize(snapFile, snaps); } std::cout << "snap size: " << snaps.extent(0) << " " << snaps.extent(1) << std::endl; for (std::size_t i=0; i<timeSteps.size(); ++i){ const auto thisTimeStep = timeSteps[i]; auto stateFile = "state_timestep_" + std::to_string(thisTimeStep); if (outFileAppend.empty() == false) stateFile += "_" + outFileAppend; auto state = Kokkos::subview(snaps, Kokkos::ALL(), targetIndices[i]-1); writeToFile(stateFile, state, (outputFormat=="binary"), true); } } else if (fSize >= 2) { //////////////////////////// // this is rank-2 case //////////////////////////// // *** load states *** using snap_t = Kokkos::View<sc_t***, kll, Kokkos::HostSpace>; snap_t snaps("snaps", 1, 1, 1); if (snapBinary){ readBinaryMatrixWithSize(snapFile, snaps); } else{ throw std::runtime_error("Rank-2 snaps ascii not supported yet"); } std::cout << "snap size: " << snaps.extent(0) << " " << snaps.extent(1) << " " << snaps.extent(2) << std::endl; for (std::size_t fId=0; fId<snaps.extent(2); ++fId) { const std::string fString = "f_"+std::to_string(fId); for (std::size_t i=0; i<timeSteps.size(); ++i) { const auto thisTimeStep = timeSteps[i]; const auto tsString = "timestep_"+std::to_string(thisTimeStep); auto stateFile = "state_"+tsString+"_"+fString; if (outFileAppend.empty() == false) stateFile += "_" + outFileAppend; auto state = Kokkos::subview(snaps, Kokkos::ALL(), targetIndices[i]-1, fId); writeToFile(stateFile, state, (outputFormat=="binary"), true); } } } } Kokkos::finalize(); std::cout << "success" << std::endl; return 0; }
29.95302
85
0.578759
Zhang690683220