text
string
size
int64
token_count
int64
// pch_std.cpp ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // pch_std.cpp -- pre-compiled headers -- non-clr compiles // =========== ---------------------------------------- // // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "h__include.h" #pragma hdrstop("../pch/pch_std.pch")
501
119
// Copyright(c) 2019, NVIDIA CORPORATION. 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. // // VulkanHpp Samples : Events // Use basic events #include "../utils/utils.hpp" #include "vulkan/vulkan.hpp" #include <iostream> static char const * AppName = "Events"; static char const * EngineName = "Vulkan.hpp"; int main( int /*argc*/, char ** /*argv*/ ) { try { vk::Instance instance = vk::su::createInstance( AppName, EngineName, {}, vk::su::getInstanceExtensions() ); #if !defined( NDEBUG ) vk::DebugUtilsMessengerEXT debugUtilsMessenger = instance.createDebugUtilsMessengerEXT( vk::su::makeDebugUtilsMessengerCreateInfoEXT() ); #endif vk::PhysicalDevice physicalDevice = instance.enumeratePhysicalDevices().front(); uint32_t graphicsQueueFamilyIndex = vk::su::findGraphicsQueueFamilyIndex( physicalDevice.getQueueFamilyProperties() ); vk::Device device = vk::su::createDevice( physicalDevice, graphicsQueueFamilyIndex ); vk::CommandPool commandPool = vk::su::createCommandPool( device, graphicsQueueFamilyIndex ); vk::CommandBuffer commandBuffer = device.allocateCommandBuffers( vk::CommandBufferAllocateInfo( commandPool, vk::CommandBufferLevel::ePrimary, 1 ) ) .front(); vk::Queue graphicsQueue = device.getQueue( graphicsQueueFamilyIndex, 0 ); /* VULKAN_KEY_START */ // Start with a trivial command buffer and make sure fence wait doesn't time out commandBuffer.begin( vk::CommandBufferBeginInfo( vk::CommandBufferUsageFlags() ) ); commandBuffer.setViewport( 0, vk::Viewport( 0.0f, 0.0f, 10.0f, 10.0f, 0.0f, 1.0f ) ); commandBuffer.end(); vk::Fence fence = device.createFence( vk::FenceCreateInfo() ); vk::SubmitInfo submitInfo( {}, {}, commandBuffer ); graphicsQueue.submit( submitInfo, fence ); // Make sure timeout is long enough for a simple command buffer without waiting for an event vk::Result result; int timeouts = -1; do { result = device.waitForFences( fence, true, vk::su::FenceTimeout ); timeouts++; } while ( result == vk::Result::eTimeout ); assert( result == vk::Result::eSuccess ); if ( timeouts != 0 ) { std::cout << "Unsuitable timeout value, exiting\n"; exit( -1 ); } // Now create an event and wait for it on the GPU vk::Event event = device.createEvent( vk::EventCreateInfo( vk::EventCreateFlags() ) ); commandBuffer.reset( vk::CommandBufferResetFlags() ); commandBuffer.begin( vk::CommandBufferBeginInfo() ); commandBuffer.waitEvents( event, vk::PipelineStageFlagBits::eHost, vk::PipelineStageFlagBits::eBottomOfPipe, nullptr, nullptr, nullptr ); commandBuffer.end(); device.resetFences( fence ); // Note that stepping through this code in the debugger is a bad idea because the GPU can TDR waiting for the event. // Execute the code from vk::Queue::submit() through vk::Device::setEvent() without breakpoints graphicsQueue.submit( submitInfo, fence ); // We should timeout waiting for the fence because the GPU should be waiting on the event result = device.waitForFences( fence, true, vk::su::FenceTimeout ); if ( result != vk::Result::eTimeout ) { std::cout << "Didn't get expected timeout in vk::Device::waitForFences, exiting\n"; exit( -1 ); } // Set the event from the CPU and wait for the fence. // This should succeed since we set the event device.setEvent( event ); do { result = device.waitForFences( fence, true, vk::su::FenceTimeout ); } while ( result == vk::Result::eTimeout ); assert( result == vk::Result::eSuccess ); commandBuffer.reset( {} ); device.resetFences( fence ); device.resetEvent( event ); // Now set the event from the GPU and wait on the CPU commandBuffer.begin( vk::CommandBufferBeginInfo() ); commandBuffer.setEvent( event, vk::PipelineStageFlagBits::eBottomOfPipe ); commandBuffer.end(); // Look for the event on the CPU. It should be vk::Result::eEventReset since we haven't sent the command buffer yet. result = device.getEventStatus( event ); assert( result == vk::Result::eEventReset ); // Send the command buffer and loop waiting for the event graphicsQueue.submit( submitInfo, fence ); int polls = 0; do { result = device.getEventStatus( event ); polls++; } while ( result != vk::Result::eEventSet ); printf( "%d polls to find the event set\n", polls ); do { result = device.waitForFences( fence, true, vk::su::FenceTimeout ); } while ( result == vk::Result::eTimeout ); assert( result == vk::Result::eSuccess ); device.destroyEvent( event ); device.destroyFence( fence ); /* VULKAN_KEY_END */ device.freeCommandBuffers( commandPool, commandBuffer ); device.destroyCommandPool( commandPool ); device.destroy(); #if !defined( NDEBUG ) instance.destroyDebugUtilsMessengerEXT( debugUtilsMessenger ); #endif instance.destroy(); } catch ( vk::SystemError & err ) { std::cout << "vk::SystemError: " << err.what() << std::endl; exit( -1 ); } catch ( std::exception & err ) { std::cout << "std::exception: " << err.what() << std::endl; exit( -1 ); } catch ( ... ) { std::cout << "unknown error\n"; exit( -1 ); } return 0; }
5,922
1,850
/* * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. */ #include "schema/vnc_cfg_types.h" #include <pugixml/pugixml.hpp> #include "base/logging.h" #include "ifmap/ifmap_server_parser.h" #include "ifmap/ifmap_server_table.h" #include "testing/gunit.h" using namespace std; class DisplayNameTest : public ::testing::Test { protected: virtual void SetUp() { xparser_ = IFMapServerParser::GetInstance("vnc_cfg"); vnc_cfg_ParserInit(xparser_); } pugi::xml_document xdoc_; IFMapServerParser *xparser_; }; TEST_F(DisplayNameTest, Load) { pugi::xml_parse_result result = xdoc_.load_file("controller/src/schema/testdata/display_name.xml"); EXPECT_TRUE(result); IFMapServerParser::RequestList requests; xparser_->ParseResults(xdoc_, &requests); EXPECT_EQ(1, requests.size()); DBRequest *request = requests.front(); IFMapServerTable::RequestData *data = static_cast<IFMapServerTable::RequestData *>(request->data.get()); ASSERT_TRUE(data); autogen::VirtualNetwork::StringProperty *display_name = static_cast<autogen::VirtualNetwork::StringProperty *>(data->content.get()); EXPECT_EQ("foo", display_name->data); } int main(int argc, char **argv) { LoggingInit(); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
1,367
469
#include "pch.h" // enable for visual studio version >= 2019 // #include "stdafx.h" // enable for visual studio version < 2019 #include "GetLastErrorToString.h" GetLastErrorToString::operator CString() { CreateMsg(); return m_msg; } GetLastErrorToString::operator LPCTSTR() { CreateMsg(); return (LPCTSTR)m_msg; } void GetLastErrorToString::CreateMsg() { LPTSTR *buff; m_ID = GetLastError(); FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, m_ID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&buff, 10, NULL); m_msg.Format(_T("%s"), (TCHAR*)buff); LocalFree(buff); #ifdef UNICODE _RPTW2(_CRT_WARN, _T("Error ID: %d Msg: %s"), m_ID, m_msg); #else _RPT2(_CRT_WARN, _T("Error ID: %d Msg: %s"), m_ID, m_msg); #endif }
800
350
#include <QCoreApplication> #include <QString> #include <QDateTime> #include <QDebug> #include "core.h" #include "commonutil.h" int main(int argc, char** argv) { // Q_UNUSED(argc); // Q_UNUSED(argv); // qInstallMessageHandler(myMessageOutput); QCoreApplication app(argc, argv); Core::getInstance()->start(); return app.exec(); }
361
133
#define CATCH_CONFIG_PREFIX_ALL #include <algorithm> #include <iostream> #include <numeric> #include <vector> #include "perceive/contrib/catch.hpp" #include "perceive/optimization/kz-filter.hpp" namespace perceive { // ------------------------------------------------------------------- TEST_CASE // CATCH_TEST_CASE("KzFilter0", "[kz-filter-0]") { CATCH_SECTION("kz-filter-0") { // INFO("HEllo"); // KzFilter filter; // filter.init(5, 4); // cout << str(filter) << endl; } } } // namespace perceive
545
193
#include "qak_plugin.h" #include "maskedmousearea.h" #include "propertytoggle.h" #include "resource.h" #include "store.h" #include <qqml.h> void QakPlugin::registerTypes(const char *uri) { // @uri Qak qmlRegisterType<MaskedMouseArea>(uri, 1, 0, "MaskedMouseArea"); qmlRegisterType<Resource>(uri, 1, 0, "Resource"); qmlRegisterType<Store>(uri, 1, 0, "Store"); qmlRegisterType<PropertyToggle>(uri, 1, 0, "PropertyToggle"); }
446
173
#include <utility> #include <vector> #include <gtest/gtest.h> #include <entt/signal/sigh.hpp> struct sigh_listener { static void f(int &v) { v = 42; } bool g(int) { k = !k; return true; } bool h(const int &) { return k; } void i() {} // useless definition just because msvc does weird things if both are empty void l() { k = k && k; } bool k{false}; }; struct before_after { void add(int v) { value += v; } void mul(int v) { value *= v; } static void static_add(int v) { before_after::value += v; } static void static_mul(before_after &instance, int v) { instance.value *= v; } static inline int value{}; }; struct SigH: ::testing::Test { void SetUp() override { before_after::value = 0; } }; struct const_nonconst_noexcept { void f() { ++cnt; } void g() noexcept { ++cnt; } void h() const { ++cnt; } void i() const noexcept { ++cnt; } mutable int cnt{0}; }; TEST_F(SigH, Lifetime) { using signal = entt::sigh<void(void)>; ASSERT_NO_FATAL_FAILURE(signal{}); signal src{}, other{}; ASSERT_NO_FATAL_FAILURE(signal{src}); ASSERT_NO_FATAL_FAILURE(signal{std::move(other)}); ASSERT_NO_FATAL_FAILURE(src = other); ASSERT_NO_FATAL_FAILURE(src = std::move(other)); ASSERT_NO_FATAL_FAILURE(delete new signal{}); } TEST_F(SigH, Clear) { entt::sigh<void(int &)> sigh; entt::sink sink{sigh}; sink.connect<&sigh_listener::f>(); ASSERT_FALSE(sink.empty()); ASSERT_FALSE(sigh.empty()); sink.disconnect(static_cast<const void *>(nullptr)); ASSERT_FALSE(sink.empty()); ASSERT_FALSE(sigh.empty()); sink.disconnect(); ASSERT_TRUE(sink.empty()); ASSERT_TRUE(sigh.empty()); } TEST_F(SigH, Swap) { entt::sigh<void(int &)> sigh1; entt::sigh<void(int &)> sigh2; entt::sink sink1{sigh1}; entt::sink sink2{sigh2}; sink1.connect<&sigh_listener::f>(); ASSERT_FALSE(sink1.empty()); ASSERT_TRUE(sink2.empty()); ASSERT_FALSE(sigh1.empty()); ASSERT_TRUE(sigh2.empty()); std::swap(sigh1, sigh2); ASSERT_TRUE(sink1.empty()); ASSERT_FALSE(sink2.empty()); ASSERT_TRUE(sigh1.empty()); ASSERT_FALSE(sigh2.empty()); } TEST_F(SigH, Functions) { entt::sigh<void(int &)> sigh; entt::sink sink{sigh}; int v = 0; sink.connect<&sigh_listener::f>(); sigh.publish(v); ASSERT_FALSE(sigh.empty()); ASSERT_EQ(1u, sigh.size()); ASSERT_EQ(42, v); v = 0; sink.disconnect<&sigh_listener::f>(); sigh.publish(v); ASSERT_TRUE(sigh.empty()); ASSERT_EQ(0u, sigh.size()); ASSERT_EQ(v, 0); } TEST_F(SigH, FunctionsWithPayload) { entt::sigh<void()> sigh; entt::sink sink{sigh}; int v = 0; sink.connect<&sigh_listener::f>(v); sigh.publish(); ASSERT_FALSE(sigh.empty()); ASSERT_EQ(1u, sigh.size()); ASSERT_EQ(42, v); v = 0; sink.disconnect<&sigh_listener::f>(v); sigh.publish(); ASSERT_TRUE(sigh.empty()); ASSERT_EQ(0u, sigh.size()); ASSERT_EQ(v, 0); sink.connect<&sigh_listener::f>(v); sink.disconnect(v); sigh.publish(); ASSERT_EQ(v, 0); } TEST_F(SigH, Members) { sigh_listener l1, l2; entt::sigh<bool(int)> sigh; entt::sink sink{sigh}; sink.connect<&sigh_listener::g>(l1); sigh.publish(42); ASSERT_TRUE(l1.k); ASSERT_FALSE(sigh.empty()); ASSERT_EQ(1u, sigh.size()); sink.disconnect<&sigh_listener::g>(l1); sigh.publish(42); ASSERT_TRUE(l1.k); ASSERT_TRUE(sigh.empty()); ASSERT_EQ(0u, sigh.size()); sink.connect<&sigh_listener::g>(&l1); sink.connect<&sigh_listener::h>(l2); ASSERT_FALSE(sigh.empty()); ASSERT_EQ(2u, sigh.size()); sink.disconnect(static_cast<const void *>(nullptr)); ASSERT_FALSE(sigh.empty()); ASSERT_EQ(2u, sigh.size()); sink.disconnect(&l1); ASSERT_FALSE(sigh.empty()); ASSERT_EQ(1u, sigh.size()); } TEST_F(SigH, Collector) { sigh_listener listener; entt::sigh<bool(int)> sigh; entt::sink sink{sigh}; int cnt = 0; sink.connect<&sigh_listener::g>(&listener); sink.connect<&sigh_listener::h>(listener); listener.k = true; sigh.collect([&listener, &cnt](bool value) { ASSERT_TRUE(value); listener.k = true; ++cnt; }, 42); ASSERT_FALSE(sigh.empty()); ASSERT_EQ(cnt, 2); cnt = 0; sigh.collect([&cnt](bool value) { // gtest and its macro hell are sometimes really annoying... [](auto v) { ASSERT_TRUE(v); }(value); ++cnt; return true; }, 42); ASSERT_EQ(cnt, 1); } TEST_F(SigH, CollectorVoid) { sigh_listener listener; entt::sigh<void(int)> sigh; entt::sink sink{sigh}; int cnt = 0; sink.connect<&sigh_listener::g>(&listener); sink.connect<&sigh_listener::h>(listener); sigh.collect([&cnt]() { ++cnt; }, 42); ASSERT_FALSE(sigh.empty()); ASSERT_EQ(cnt, 2); cnt = 0; sigh.collect([&cnt]() { ++cnt; return true; }, 42); ASSERT_EQ(cnt, 1); } TEST_F(SigH, Connection) { entt::sigh<void(int &)> sigh; entt::sink sink{sigh}; int v = 0; auto conn = sink.connect<&sigh_listener::f>(); sigh.publish(v); ASSERT_FALSE(sigh.empty()); ASSERT_TRUE(conn); ASSERT_EQ(42, v); v = 0; conn.release(); sigh.publish(v); ASSERT_TRUE(sigh.empty()); ASSERT_FALSE(conn); ASSERT_EQ(0, v); } TEST_F(SigH, ScopedConnection) { sigh_listener listener; entt::sigh<void(int)> sigh; entt::sink sink{sigh}; { ASSERT_FALSE(listener.k); entt::scoped_connection conn = sink.connect<&sigh_listener::g>(listener); sigh.publish(42); ASSERT_FALSE(sigh.empty()); ASSERT_TRUE(listener.k); ASSERT_TRUE(conn); } sigh.publish(42); ASSERT_TRUE(sigh.empty()); ASSERT_TRUE(listener.k); } TEST_F(SigH, ScopedConnectionConstructorsAndOperators) { sigh_listener listener; entt::sigh<void(int)> sigh; entt::sink sink{sigh}; { entt::scoped_connection inner{}; ASSERT_TRUE(sigh.empty()); ASSERT_FALSE(listener.k); ASSERT_FALSE(inner); inner = sink.connect<&sigh_listener::g>(listener); sigh.publish(42); ASSERT_FALSE(sigh.empty()); ASSERT_TRUE(listener.k); ASSERT_TRUE(inner); inner.release(); ASSERT_TRUE(sigh.empty()); ASSERT_FALSE(inner); auto basic = sink.connect<&sigh_listener::g>(listener); inner = std::as_const(basic); sigh.publish(42); ASSERT_FALSE(sigh.empty()); ASSERT_FALSE(listener.k); ASSERT_TRUE(inner); } sigh.publish(42); ASSERT_TRUE(sigh.empty()); ASSERT_FALSE(listener.k); } TEST_F(SigH, ConstNonConstNoExcept) { entt::sigh<void()> sigh; entt::sink sink{sigh}; const_nonconst_noexcept functor; const const_nonconst_noexcept cfunctor; sink.connect<&const_nonconst_noexcept::f>(functor); sink.connect<&const_nonconst_noexcept::g>(&functor); sink.connect<&const_nonconst_noexcept::h>(cfunctor); sink.connect<&const_nonconst_noexcept::i>(&cfunctor); sigh.publish(); ASSERT_EQ(functor.cnt, 2); ASSERT_EQ(cfunctor.cnt, 2); sink.disconnect<&const_nonconst_noexcept::f>(functor); sink.disconnect<&const_nonconst_noexcept::g>(&functor); sink.disconnect<&const_nonconst_noexcept::h>(cfunctor); sink.disconnect<&const_nonconst_noexcept::i>(&cfunctor); sigh.publish(); ASSERT_EQ(functor.cnt, 2); ASSERT_EQ(cfunctor.cnt, 2); } TEST_F(SigH, BeforeFunction) { entt::sigh<void(int)> sigh; entt::sink sink{sigh}; before_after functor; sink.connect<&before_after::add>(functor); sink.connect<&before_after::static_add>(); sink.before<&before_after::static_add>().connect<&before_after::mul>(functor); sigh.publish(2); ASSERT_EQ(functor.value, 6); } TEST_F(SigH, BeforeMemberFunction) { entt::sigh<void(int)> sigh; entt::sink sink{sigh}; before_after functor; sink.connect<&before_after::static_add>(); sink.connect<&before_after::add>(functor); sink.before<&before_after::add>(functor).connect<&before_after::mul>(functor); sigh.publish(2); ASSERT_EQ(functor.value, 6); } TEST_F(SigH, BeforeFunctionWithPayload) { entt::sigh<void(int)> sigh; entt::sink sink{sigh}; before_after functor; sink.connect<&before_after::static_add>(); sink.connect<&before_after::static_mul>(functor); sink.before<&before_after::static_mul>(functor).connect<&before_after::add>(functor); sigh.publish(2); ASSERT_EQ(functor.value, 8); } TEST_F(SigH, BeforeInstanceOrPayload) { entt::sigh<void(int)> sigh; entt::sink sink{sigh}; before_after functor; sink.connect<&before_after::static_mul>(functor); sink.connect<&before_after::add>(functor); sink.before(functor).connect<&before_after::static_add>(); sigh.publish(2); ASSERT_EQ(functor.value, 6); } TEST_F(SigH, BeforeAnythingElse) { entt::sigh<void(int)> sigh; entt::sink sink{sigh}; before_after functor; sink.connect<&before_after::add>(functor); sink.before().connect<&before_after::mul>(functor); sigh.publish(2); ASSERT_EQ(functor.value, 2); } TEST_F(SigH, BeforeListenerNotPresent) { entt::sigh<void(int)> sigh; entt::sink sink{sigh}; before_after functor; sink.connect<&before_after::mul>(functor); sink.before<&before_after::add>(&functor).connect<&before_after::add>(functor); sigh.publish(2); ASSERT_EQ(functor.value, 2); } TEST_F(SigH, UnboundDataMember) { sigh_listener listener; entt::sigh<bool &(sigh_listener &)> sigh; entt::sink sink{sigh}; ASSERT_FALSE(listener.k); sink.connect<&sigh_listener::k>(); sigh.collect([](bool &value) { value = !value; }, listener); ASSERT_TRUE(listener.k); } TEST_F(SigH, UnboundMemberFunction) { sigh_listener listener; entt::sigh<void(sigh_listener *, int)> sigh; entt::sink sink{sigh}; ASSERT_FALSE(listener.k); sink.connect<&sigh_listener::g>(); sigh.publish(&listener, 42); ASSERT_TRUE(listener.k); }
10,237
4,193
/* * 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. */ #if defined(XALAN_BUILD_DEPRECATED_DOM_BRIDGE) // Class header file. #include "FormatterToDeprecatedXercesDOM.hpp" #include <cassert> #include <xercesc/sax/AttributeList.hpp> #if XERCES_VERSION_MAJOR >= 2 #include <xercesc/dom/deprecated/DOM_CDATASection.hpp> #include <xercesc/dom/deprecated/DOM_Comment.hpp> #include <xercesc/dom/deprecated/DOM_EntityReference.hpp> #include <xercesc/dom/deprecated/DOM_ProcessingInstruction.hpp> #include <xercesc/dom/deprecated/DOM_Text.hpp> #else #include <xercesc/dom/DOM_CDATASection.hpp> #include <xercesc/dom/DOM_Comment.hpp> #include <xercesc/dom/DOM_EntityReference.hpp> #include <xercesc/dom/DOM_ProcessingInstruction.hpp> #include <xercesc/dom/DOM_Text.hpp> #endif #include <xalanc/XalanDOM/XalanDOMString.hpp> #include <xalanc/PlatformSupport/DOMStringHelper.hpp> #include <xalanc/PlatformSupport/PrefixResolver.hpp> #include <xalanc/DOMSupport/DOMServices.hpp> #include <xalanc/XercesParserLiaison/XercesDOMException.hpp> namespace XALAN_CPP_NAMESPACE { const XalanDOMString FormatterToDeprecatedXercesDOM::s_emptyString; FormatterToDeprecatedXercesDOM::FormatterToDeprecatedXercesDOM( DOM_Document_Type& doc, DOM_DocumentFragmentType& docFrag, DOM_ElementType& currentElement) : FormatterListener(OUTPUT_METHOD_DOM), m_doc(doc), m_docFrag(docFrag), m_currentElem(currentElement), m_elemStack(), m_buffer(), m_textBuffer() { assert(m_doc != 0 && m_docFrag != 0); } FormatterToDeprecatedXercesDOM::FormatterToDeprecatedXercesDOM( DOM_Document_Type& doc, DOM_ElementType& elem) : FormatterListener(OUTPUT_METHOD_DOM), m_doc(doc), m_docFrag(), m_currentElem(elem), m_elemStack(), m_buffer(), m_textBuffer() { assert(m_doc != 0); } FormatterToDeprecatedXercesDOM::FormatterToDeprecatedXercesDOM( DOM_Document_Type& doc) : FormatterListener(OUTPUT_METHOD_DOM), m_doc(doc), m_docFrag(), m_currentElem(), m_elemStack(), m_buffer(), m_textBuffer() { assert(m_doc != 0); } FormatterToDeprecatedXercesDOM::~FormatterToDeprecatedXercesDOM() { } void FormatterToDeprecatedXercesDOM::setDocumentLocator(const Locator* const /* locator */) { // No action for the moment. } void FormatterToDeprecatedXercesDOM::startDocument() { // No action for the moment. } void FormatterToDeprecatedXercesDOM::endDocument() { // No action for the moment. } void FormatterToDeprecatedXercesDOM::startElement( const XMLCh* const name, AttributeListType& attrs) { try { processAccumulatedText(); DOM_ElementType elem = createElement(name, attrs); append(elem); m_elemStack.push_back(m_currentElem); m_currentElem = elem; } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::endElement(const XMLCh* const /* name */) { try { processAccumulatedText(); if(m_elemStack.empty() == false) { m_currentElem = m_elemStack.back(); m_elemStack.pop_back(); } else { m_currentElem = 0; } } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::characters( const XMLCh* const chars, const unsigned int length) { m_textBuffer.append(chars, length); } void FormatterToDeprecatedXercesDOM::charactersRaw( const XMLCh* const chars, const unsigned int length) { try { processAccumulatedText(); cdata(chars, length); } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::entityReference(const XMLCh* const name) { try { processAccumulatedText(); DOM_EntityReferenceType theXercesNode = m_doc.createEntityReference(name); assert(theXercesNode.isNull() == false); append(theXercesNode); } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::ignorableWhitespace( const XMLCh* const chars, const unsigned int length) { try { processAccumulatedText(); assign(m_buffer, chars, length); DOM_TextType theXercesNode = m_doc.createTextNode(m_buffer.c_str()); assert(theXercesNode.isNull() == false); append(theXercesNode); } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::processingInstruction( const XMLCh* const target, const XMLCh* const data) { try { processAccumulatedText(); DOM_ProcessingInstructionType theXercesNode = m_doc.createProcessingInstruction(target, data); assert(theXercesNode.isNull() == false); append(theXercesNode); } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::resetDocument() { } void FormatterToDeprecatedXercesDOM::comment(const XMLCh* const data) { try { processAccumulatedText(); DOM_CommentType theXercesNode = m_doc.createComment(data); assert(theXercesNode.isNull() == false); append(theXercesNode); } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::cdata( const XMLCh* const ch, const unsigned int length) { try { processAccumulatedText(); assign(m_buffer, ch, length); DOM_CDATASectionType theXercesNode = m_doc.createCDATASection(m_buffer.c_str()); assert(theXercesNode.isNull() == false); append(theXercesNode); } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::append(DOM_NodeType &newNode) { assert(newNode != 0); if(m_currentElem.isNull() == false) { m_currentElem.appendChild(newNode); } else if(m_docFrag.isNull() == false) { m_docFrag.appendChild(newNode); } else { m_doc.appendChild(newNode); } } DOM_ElementType FormatterToDeprecatedXercesDOM::createElement( const XalanDOMChar* theElementName, AttributeListType& attrs) { DOM_ElementType theElement; if (m_prefixResolver == 0) { theElement = m_doc.createElement(theElementName); addAttributes(theElement, attrs); } else { // Check for the namespace... const XalanDOMString* const theNamespace = DOMServices::getNamespaceForPrefix(theElementName, *m_prefixResolver, false , m_buffer); if (theNamespace == 0 || length(*theNamespace) == 0) { theElement = m_doc.createElement(theElementName); } else { theElement = m_doc.createElementNS(theNamespace->c_str(), theElementName); } addAttributes(theElement, attrs); } return theElement; } void FormatterToDeprecatedXercesDOM::addAttributes( DOM_ElementType& theElement, AttributeListType& attrs) { const unsigned int nAtts = attrs.getLength(); if (m_prefixResolver == 0) { for(unsigned int i = 0; i < nAtts; i++) { theElement.setAttribute(attrs.getName(i), attrs.getValue(i)); } } else { for(unsigned int i = 0; i < nAtts; i++) { const XalanDOMChar* const theName = attrs.getName(i); assert(theName != 0); // Check for the namespace... const XalanDOMString* const theNamespace = DOMServices::getNamespaceForPrefix(theName, *m_prefixResolver, true, m_buffer); if (theNamespace == 0 || length(*theNamespace) == 0) { theElement.setAttribute(theName, attrs.getValue(i)); } else { theElement.setAttributeNS(theNamespace->c_str(), theName, attrs.getValue(i)); } } } } void FormatterToDeprecatedXercesDOM::processAccumulatedText() { if (m_textBuffer.empty() == false) { DOM_TextType theXercesNode = m_doc.createTextNode(m_textBuffer.c_str()); assert(theXercesNode.isNull() == false); append(theXercesNode); clear(m_textBuffer); } } } #endif //XALAN_BUILD_DEPRECATED_DOM_BRIDGE
9,980
3,289
/** @file ImmutableListTests.cpp * * Unit tests for pistis::util::ImmutableList */ #include <pistis/util/ImmutableList.hpp> #include <pistis/exceptions/OutOfRangeError.hpp> #include <pistis/testing/Allocator.hpp> #include <gtest/gtest.h> #include <sstream> #include <stdint.h> using namespace pistis::exceptions; using namespace pistis::util; namespace pt = pistis::testing; namespace { typedef ::pt::Allocator<uint32_t> TestAllocator; typedef ImmutableList<uint32_t, TestAllocator> UInt32List; typedef std::vector<uint32_t> TrueList; inline std::string toStr(bool v) { return v ? "true" : "false"; } template <typename T> inline std::unique_ptr<T> make_result(const T& result) { return std::unique_ptr<T>(new T(result)); } template <typename Item, typename Allocator> std::unique_ptr<::testing::AssertionResult> verifyListAccessors( std::unique_ptr<::testing::AssertionResult> prior, const std::vector<Item>& truth, const ImmutableList<Item, Allocator>& list ) { if (!*prior) { return std::move(prior); } if (truth.empty() != list.empty()) { return make_result( ::testing::AssertionFailure() << "truth.empty() != list.empty() [ " << toStr(truth.empty()) << " != " << toStr(list.empty()) << " ]" ); } if (truth.size() != list.size()) { return make_result( ::testing::AssertionFailure() << "truth.size() != list.size() [ " << truth.size() << " != " << list.size() << " ]" ); } // list.size() == truth.size() by prior assertion if (!list.size()) { // Don't check front() and back() } else if (truth.front() != list.front()) { return make_result( ::testing::AssertionFailure() << "truth.front() != list.front() [ " << truth.front() << " != " << list.front() << " ]" ); } else if (truth.back() != list.back()) { return make_result( ::testing::AssertionFailure() << "truth.back() != list.back() [ " << truth.back() << " != " << list.back() << " ]" ); } return make_result(::testing::AssertionSuccess()); } template <typename ListIterator, typename TruthIterator> std::unique_ptr<::testing::AssertionResult> verifyRange( std::unique_ptr<::testing::AssertionResult> prior, TruthIterator truthBegin, ListIterator listBegin, ListIterator listEnd) { if (!*prior) { return std::move(prior); } auto i = truthBegin; uint32_t ndx = 0; for (auto j = listBegin; j != listEnd; ++i, ++j, ++ndx) { if (*i != *j) { return make_result( ::testing::AssertionFailure() << "truth[" << ndx << "] (which is " << *i << " ) != list[" << ndx << "] (which is " << *j << ")" ); } } return make_result(::testing::AssertionSuccess()); } template <typename Item, typename Allocator> ::testing::AssertionResult verifyList( const std::vector<Item>& truth, const ImmutableList<Item, Allocator>& list ) { std::unique_ptr<::testing::AssertionResult> result = make_result(::testing::AssertionSuccess()); result = verifyListAccessors(std::move(result), truth, list); result = verifyRange(std::move(result), truth.begin(), list.begin(), list.end()); result = verifyRange(std::move(result), truth.cbegin(), list.cbegin(), list.cend()); return *result; } } TEST(ImmutableListTests, CreateEmpty) { const TestAllocator allocator("TEST_1"); UInt32List list(allocator); EXPECT_EQ(allocator.name(), list.allocator().name()); EXPECT_TRUE(verifyList(TrueList(), list)); } TEST(ImmutableListTests, CreateFromSingleItem) { const TestAllocator allocator("TEST_1"); UInt32List list(3, 16, allocator); TrueList truth{ 16, 16, 16 }; EXPECT_EQ(allocator.name(), list.allocator().name()); EXPECT_TRUE(verifyList(truth, list)); } TEST(ImmutableListTests, CreateFromLengthAndIterator) { const std::vector<uint32_t> DATA{ 5, 16, 2, 23 }; const TestAllocator allocator("TEST_1"); TrueList truth(DATA); UInt32List list(DATA.size(), DATA.begin(), allocator); EXPECT_EQ(allocator.name(), list.allocator().name()); EXPECT_TRUE(verifyList(truth, list)); } TEST(ImmutableListTests, CreateFromRange) { const std::vector<uint32_t> DATA{ 5, 16, 2, 23 }; const TestAllocator allocator("TEST_1"); TrueList truth(DATA); UInt32List list(DATA.begin(), DATA.end(), allocator); EXPECT_EQ(allocator.name(), list.allocator().name()); EXPECT_TRUE(verifyList(truth, list)); } TEST(ImmutableListTests, CreateFromInitializerList) { const TestAllocator allocator("TEST_1"); TrueList truth{ 7, 4, 9, 22, 27 }; UInt32List list{ { 7, 4, 9, 22, 27 }, allocator }; EXPECT_EQ(allocator.name(), list.allocator().name()); EXPECT_TRUE(verifyList(truth, list)); } TEST(ImmutableListTests, CreateFromCopy) { const TestAllocator allocator("TEST_1"); const TestAllocator otherAllocator("TEST_2"); const std::vector<uint32_t> DATA{ 4, 12, 9 }; const TrueList truth(DATA); UInt32List list( DATA.begin(), DATA.end(), allocator); ASSERT_EQ(allocator.name(), list.allocator().name()); ASSERT_TRUE(verifyList(truth, list)); UInt32List copy(list); EXPECT_EQ(allocator.name(), copy.allocator().name()); EXPECT_TRUE(verifyList(truth, copy)); EXPECT_EQ(allocator.name(), list.allocator().name()); EXPECT_TRUE(verifyList(truth, list)); UInt32List copyWithNewAllocator(list, otherAllocator); EXPECT_EQ(otherAllocator.name(), copyWithNewAllocator.allocator().name()); EXPECT_TRUE(verifyList(truth, copyWithNewAllocator)); EXPECT_EQ(allocator.name(), list.allocator().name()); EXPECT_TRUE(verifyList(truth, list)); } TEST(ImmutableListTests, Back) { const std::vector<uint32_t> DATA{ 3, 2, 1, 4 }; UInt32List list(DATA.begin(), DATA.end()); EXPECT_EQ(4, list.back()); EXPECT_EQ(4, list.back(0)); EXPECT_EQ(1, list.back(1)); EXPECT_EQ(2, list.back(2)); EXPECT_EQ(3, list.back(3)); } TEST(ImmutableListTests, At) { const std::vector<uint32_t> DATA{ 3, 2, 1, 4 }; UInt32List list(DATA.begin(), DATA.end()); for (uint32_t i = 0; i != DATA.size(); ++i) { EXPECT_EQ(DATA[i], list.at(i)); } EXPECT_THROW(list.at(list.size()), std::range_error); } TEST(ImmutableListTests, Sublist) { const TestAllocator allocator("TEST_1"); const TrueList truth{3, 4, 5, 6}; UInt32List list{ { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, allocator }; UInt32List sublist(list.sublist(3, 7)); EXPECT_EQ(allocator.name(), sublist.allocator().name()); EXPECT_TRUE(verifyList(truth, sublist)); EXPECT_TRUE(verifyList(TrueList(), list.sublist(3, 3))); EXPECT_TRUE(verifyList(TrueList(), list.sublist(10, 10))); EXPECT_THROW(list.sublist(11, 15), OutOfRangeError); EXPECT_THROW(list.sublist(10, 11), OutOfRangeError); EXPECT_THROW(list.sublist( 7, 3), IllegalValueError); } TEST(ImmutableListTests, Concat) { const TestAllocator allocator("TEST_1"); const TrueList trueConcatenated{ 5, 4, 2, 7, 1, 9, 4 }; UInt32List list1{ { 5, 4, 2, 7 }, allocator }; UInt32List list2{ { 1, 9, 4 }, allocator }; UInt32List empty{ allocator }; UInt32List concatenated = list1.concat(list2); EXPECT_EQ(allocator.name(), concatenated.allocator().name()); EXPECT_TRUE(verifyList(trueConcatenated, concatenated)); EXPECT_TRUE(verifyList(TrueList{ 5, 4, 2, 7 }, list1.concat(empty))); EXPECT_TRUE(verifyList(TrueList{ 5, 4, 2, 7 }, empty.concat(list1))); EXPECT_TRUE(verifyList(TrueList{ 1, 9, 4 }, list2.concat(empty))); EXPECT_TRUE(verifyList(TrueList{ 1, 9, 4 }, empty.concat(list2))); } TEST(ImmutableListTests, Add) { const TestAllocator allocator("TEST_1"); const TrueList trueOriginal{ 5, 4, 2, 7 }; const TrueList trueAddedToEnd{ 5, 4, 2, 7, 3 }; UInt32List list{ { 5, 4, 2, 7 }, allocator }; UInt32List empty{ allocator }; EXPECT_TRUE(verifyList(trueAddedToEnd, list.add(3))); EXPECT_TRUE(verifyList(trueOriginal, list)); EXPECT_TRUE(verifyList(TrueList{ 10 }, empty.add(10))); } TEST(ImmutableListTests, Insert) { const TestAllocator allocator("TEST_1"); const TrueList trueAddedAtStart{ 6, 5, 4, 2, 7 }; const TrueList trueAddedInMiddle{ 5, 4, 1, 2, 7 }; const TrueList trueAddedAtEnd{ 5, 4, 2, 7, 9 }; UInt32List list{ { 5, 4, 2, 7 }, allocator }; UInt32List empty{ allocator }; EXPECT_TRUE(verifyList(trueAddedAtStart, list.insert(0, 6))); EXPECT_TRUE(verifyList(trueAddedInMiddle, list.insert(2, 1))); EXPECT_TRUE(verifyList(trueAddedAtEnd, list.insert(4, 9))); EXPECT_TRUE(verifyList(TrueList{ 10 }, empty.insert(0, 10))); } TEST(ImmutableListTests, Remove) { const TestAllocator allocator("TEST_1"); const TrueList trueRemovedAtStart{ 4, 2, 7 }; const TrueList trueRemovedInMiddle{ 5, 4, 7 }; const TrueList trueRemovedAtEnd{ 5, 4, 2 }; UInt32List list{ { 5, 4, 2, 7 }, allocator }; UInt32List oneItem{ { 10 }, allocator }; EXPECT_TRUE(verifyList(trueRemovedAtStart, list.remove(0))); EXPECT_TRUE(verifyList(trueRemovedInMiddle, list.remove(2))); EXPECT_TRUE(verifyList(trueRemovedAtEnd, list.remove(4))); EXPECT_TRUE(verifyList(TrueList{ }, oneItem.remove(0))); } TEST(ImmutableListTests, Replace) { const TestAllocator allocator("TEST_1"); const TrueList trueReplacedAtStart{ 6, 4, 2, 7 }; const TrueList trueReplacedInMiddle{ 5, 4, 9, 7 }; const TrueList trueReplacedAtEnd{ 5, 4, 2, 1 }; UInt32List list{ { 5, 4, 2, 7 }, allocator }; EXPECT_TRUE(verifyList(trueReplacedAtStart, list.replace((size_t)0, 6))); EXPECT_TRUE(verifyList(trueReplacedInMiddle, list.replace(2, 9))); EXPECT_TRUE(verifyList(trueReplacedAtEnd, list.replace(3, 1))); } TEST(ImmutableListTests, Map) { const TestAllocator allocator("TEST_1"); const std::vector<std::string> truth{ "5", "2", "7", "13" }; UInt32List list{ { 5, 2, 7, 13 }, allocator }; ImmutableList< std::string, pt::Allocator<std::string> > mapped( list.map([](uint32_t x) { std::ostringstream tmp; tmp << x; return tmp.str(); }) ); EXPECT_EQ(allocator.name(), mapped.allocator().name()); EXPECT_TRUE(verifyList(truth, mapped)); } TEST(ImmutableListTest, Reduce) { UInt32List list{ 5, 2, 7, 13 }; UInt32List emptyList; auto concat = [](const std::string& s, uint32_t x) { std::ostringstream tmp; tmp << s << ", " << x; return tmp.str(); }; auto mix = [](uint32_t x, uint32_t y) { return x * 100 + y; }; EXPECT_EQ("**, 5, 2, 7, 13", list.reduce(concat, "**")); EXPECT_EQ("**", emptyList.reduce(concat, "**")); EXPECT_EQ(5020713, list.reduce(mix)); EXPECT_THROW(emptyList.reduce(mix), IllegalStateError); } TEST(ImmutableListTests, ListEquality) { UInt32List list{ 3, 2, 5, 10, 7 }; UInt32List same{ 3, 2, 5, 10, 7 }; UInt32List different{ 3, 2, 9, 10, 7 }; EXPECT_TRUE(list == same); EXPECT_FALSE(list == different); EXPECT_TRUE(list != different); EXPECT_FALSE(list != same); } TEST(ImmutableListTests, RandomAccess) { const std::vector<uint32_t> DATA{ 3, 2, 5, 10, 7 }; UInt32List list(DATA.begin(), DATA.end()); for (uint32_t i = 0; i < DATA.size(); ++i) { EXPECT_EQ(DATA[i], list[i]); } }
11,142
4,441
#include <iostream> #include "funciones.h" using namespace std; int main() { //initialize values // State variable X is [position, velocity] double y = 8.5 ; double t = 0; double dt = 0.1; while(y>0){ cout<<y<<" "<<t<<endl; y = rungeKutta(t,0.1,20,y)[0]; t = rungeKutta(t,0.1,20,y)[1]; } return 0; }
345
156
#include "main.h" #include <natus/application/global.h> #include <natus/application/app.h> #include <natus/tool/imgui/sprite_editor.h> #include <natus/device/global.h> #include <natus/gfx/camera/pinhole_camera.h> #include <natus/graphics/shader/nsl_bridge.hpp> #include <natus/graphics/variable/variable_set.hpp> #include <natus/profile/macros.h> #include <natus/format/global.h> #include <natus/format/nsl/nsl_module.h> #include <natus/geometry/mesh/polygon_mesh.h> #include <natus/geometry/mesh/tri_mesh.h> #include <natus/geometry/mesh/flat_tri_mesh.h> #include <natus/geometry/3d/cube.h> #include <natus/geometry/3d/tetra.h> #include <natus/math/vector/vector3.hpp> #include <natus/math/vector/vector4.hpp> #include <natus/math/matrix/matrix4.hpp> #include <natus/math/utility/angle.hpp> #include <natus/math/utility/3d/transformation.hpp> #include <thread> namespace this_file { using namespace natus::core::types ; class test_app : public natus::application::app { natus_this_typedefs( test_app ) ; private: natus::graphics::async_views_t _graphics ; app::window_async_t _wid_async ; app::window_async_t _wid_async2 ; natus::graphics::state_object_res_t _root_render_states ; natus::gfx::pinhole_camera_t _camera_0 ; natus::io::database_res_t _db ; natus::device::three_device_res_t _dev_mouse ; natus::device::ascii_device_res_t _dev_ascii ; bool_t _do_tool = true ; natus::tool::sprite_editor_res_t _se ; public: test_app( void_t ) { natus::application::app::window_info_t wi ; #if 0 _wid_async = this_t::create_window( "A Render Window", wi, { natus::graphics::backend_type::gl3, natus::graphics::backend_type::d3d11} ) ; _wid_async2 = this_t::create_window( "A Render Window", wi) ; _wid_async.window().position( 50, 50 ) ; _wid_async.window().resize( 800, 800 ) ; _wid_async2.window().position( 50 + 800, 50 ) ; _wid_async2.window().resize( 800, 800 ) ; _graphics = natus::graphics::async_views_t( { _wid_async.async(), _wid_async2.async() } ) ; #else _wid_async = this_t::create_window( "A Render Window", wi ) ; _wid_async.window().resize( 1000, 1000 ) ; #endif _db = natus::io::database_t( natus::io::path_t( DATAPATH ), "./working", "data" ) ; _se = natus::tool::sprite_editor_res_t( natus::tool::sprite_editor_t( _db ) ) ; } test_app( this_cref_t ) = delete ; test_app( this_rref_t rhv ) : app( ::std::move( rhv ) ) { _wid_async = std::move( rhv._wid_async ) ; _wid_async2 = std::move( rhv._wid_async2 ) ; _camera_0 = std::move( rhv._camera_0 ) ; _db = std::move( rhv._db ) ; _graphics = std::move( rhv._graphics ) ; _se = std::move( rhv._se ) ; } virtual ~test_app( void_t ) {} virtual natus::application::result on_event( window_id_t const, this_t::window_event_info_in_t wei ) noexcept { _camera_0.perspective_fov( natus::math::angle<float_t>::degree_to_radian( 90.0f ), float_t(wei.w) / float_t(wei.h), 1.0f, 1000.0f ) ; return natus::application::result::ok ; } private: virtual natus::application::result on_init( void_t ) noexcept { natus::device::global_t::system()->search( [&] ( natus::device::idevice_res_t dev_in ) { if( natus::device::three_device_res_t::castable( dev_in ) ) { _dev_mouse = dev_in ; } else if( natus::device::ascii_device_res_t::castable( dev_in ) ) { _dev_ascii = dev_in ; } } ) ; if( !_dev_mouse.is_valid() ) natus::log::global_t::status( "no three mouse found" ) ; if( !_dev_ascii.is_valid() ) natus::log::global_t::status( "no ascii keyboard found" ) ; { _camera_0.look_at( natus::math::vec3f_t( 0.0f, 60.0f, -50.0f ), natus::math::vec3f_t( 0.0f, 1.0f, 0.0f ), natus::math::vec3f_t( 0.0f, 0.0f, 0.0f )) ; } // root render states { natus::graphics::state_object_t so = natus::graphics::state_object_t( "root_render_states" ) ; { natus::graphics::render_state_sets_t rss ; rss.depth_s.do_change = true ; rss.depth_s.ss.do_activate = false ; rss.depth_s.ss.do_depth_write = false ; rss.polygon_s.do_change = true ; rss.polygon_s.ss.do_activate = true ; rss.polygon_s.ss.ff = natus::graphics::front_face::clock_wise ; rss.polygon_s.ss.cm = natus::graphics::cull_mode::back ; rss.polygon_s.ss.fm = natus::graphics::fill_mode::fill ; so.add_render_state_set( rss ) ; } _root_render_states = std::move( so ) ; _graphics.for_each( [&]( natus::graphics::async_view_t a ) { a.configure( _root_render_states ) ; } ) ; } { //_se->add_sprite_sheet( "industrial", natus::io::location_t( "images.industrial.industrial.v2.png" ) ) ; //_se->add_sprite_sheet( "enemies", natus::io::location_t( "images.Paper-Pixels-8x8.Enemies.png" ) ) ; //_se->add_sprite_sheet( "player", natus::io::location_t( "images.Player.png" ) ) ; //_se->add_sprite_sheet( "tiles", natus::io::location_t( "images.Tiles.png" ) ) ; _se->add_sprite_sheet( "sprite_sheets", natus::io::location_t( "sprite_sheets.natus" ) ) ; } return natus::application::result::ok ; } float value = 0.0f ; virtual natus::application::result on_update( natus::application::app_t::update_data_in_t ) noexcept { NATUS_PROFILING_COUNTER_HERE( "Update Clock" ) ; return natus::application::result::ok ; } virtual natus::application::result on_device( natus::application::app_t::device_data_in_t ) noexcept { { natus::device::layouts::ascii_keyboard_t ascii( _dev_ascii ) ; if( ascii.get_state( natus::device::layouts::ascii_keyboard_t::ascii_key::f8 ) == natus::device::components::key_state::released ) { } else if( ascii.get_state( natus::device::layouts::ascii_keyboard_t::ascii_key::f9 ) == natus::device::components::key_state::released ) { } else if( ascii.get_state( natus::device::layouts::ascii_keyboard_t::ascii_key::f2 ) == natus::device::components::key_state::released ) { _do_tool = !_do_tool ; } } NATUS_PROFILING_COUNTER_HERE( "Device Clock" ) ; return natus::application::result::ok ; } virtual natus::application::result on_graphics( natus::application::app_t::render_data_in_t ) noexcept { // render the root render state sets render object // this will set the root render states { _graphics.for_each( [&]( natus::graphics::async_view_t a ) { a.push( _root_render_states ) ; } ) ; } // render the root render state sets render object // this will set the root render states { _graphics.for_each( [&]( natus::graphics::async_view_t a ) { a.pop( natus::graphics::backend::pop_type::render_state ); } ) ; } NATUS_PROFILING_COUNTER_HERE( "Render Clock" ) ; return natus::application::result::ok ; } virtual natus::application::result on_tool( natus::tool::imgui_view_t imgui ) noexcept { if( !_do_tool ) return natus::application::result::no_imgui ; { bool_t show_demo = true ; ImGui::ShowDemoWindow( &show_demo ) ; } _se->do_tool( imgui ) ; return natus::application::result::ok ; } virtual natus::application::result on_shutdown( void_t ) noexcept { return natus::application::result::ok ; } }; natus_res_typedef( test_app ) ; } int main( int argc, char ** argv ) { return natus::application::global_t::create_application( this_file::test_app_res_t( this_file::test_app_t() ) )->exec() ; }
9,138
3,062
// // Copyright (C) 2004 Andras Varga // // This program 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 program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program; if not, see <http://www.gnu.org/licenses/>. // #include "inet/transportlayer/tcp_common/TCPSegment.h" namespace inet { namespace tcp { Register_Class(Sack); bool Sack::empty() const { return start_var == 0 && end_var == 0; } bool Sack::contains(const Sack& other) const { return seqLE(start_var, other.start_var) && seqLE(other.end_var, end_var); } void Sack::clear() { start_var = end_var = 0; } void Sack::setSegment(unsigned int start_par, unsigned int end_par) { setStart(start_par); setEnd(end_par); } std::string Sack::str() const { std::stringstream out; out << "[" << start_var << ".." << end_var << ")"; return out.str(); } Register_Class(TCPSegment); uint32_t TCPSegment::getSegLen() { return payloadLength_var + (finBit_var ? 1 : 0) + (synBit_var ? 1 : 0); } void TCPSegment::truncateSegment(uint32 firstSeqNo, uint32 endSeqNo) { ASSERT(payloadLength_var > 0); // must have common part: #ifndef NDEBUG if (!(seqLess(sequenceNo_var, endSeqNo) && seqLess(firstSeqNo, sequenceNo_var + payloadLength_var))) { throw cRuntimeError(this, "truncateSegment(%u,%u) called on [%u, %u) segment\n", firstSeqNo, endSeqNo, sequenceNo_var, sequenceNo_var + payloadLength_var); } #endif // ifndef NDEBUG unsigned int truncleft = 0; unsigned int truncright = 0; if (seqLess(sequenceNo_var, firstSeqNo)) { truncleft = firstSeqNo - sequenceNo_var; } if (seqGreater(sequenceNo_var + payloadLength_var, endSeqNo)) { truncright = sequenceNo_var + payloadLength_var - endSeqNo; } truncateData(truncleft, truncright); } unsigned short TCPSegment::getHeaderOptionArrayLength() { unsigned short usedLength = 0; for (uint i = 0; i < getHeaderOptionArraySize(); i++) usedLength += getHeaderOption(i)->getLength(); return usedLength; } TCPSegment& TCPSegment::operator=(const TCPSegment& other) { if (this == &other) return *this; clean(); TCPSegment_Base::operator=(other); copy(other); return *this; } void TCPSegment::copy(const TCPSegment& other) { for (const auto & elem : other.payloadList) addPayloadMessage(elem.msg->dup(), elem.endSequenceNo); for (const auto opt: other.headerOptionList) addHeaderOption(opt->dup()); } TCPSegment::~TCPSegment() { clean(); } void TCPSegment::clean() { dropHeaderOptions(); while (!payloadList.empty()) { cPacket *msg = payloadList.front().msg; payloadList.pop_front(); dropAndDelete(msg); } } void TCPSegment::truncateData(unsigned int truncleft, unsigned int truncright) { ASSERT(payloadLength_var >= truncleft + truncright); if (0 != byteArray_var.getDataArraySize()) byteArray_var.truncateData(truncleft, truncright); while (!payloadList.empty() && (payloadList.front().endSequenceNo - sequenceNo_var) <= truncleft) { cPacket *msg = payloadList.front().msg; payloadList.pop_front(); dropAndDelete(msg); } sequenceNo_var += truncleft; payloadLength_var -= truncleft + truncright; // truncate payload data correctly while (!payloadList.empty() && (payloadList.back().endSequenceNo - sequenceNo_var) > payloadLength_var) { cPacket *msg = payloadList.back().msg; payloadList.pop_back(); dropAndDelete(msg); } } void TCPSegment::parsimPack(cCommBuffer *b) PARSIMPACK_CONST { TCPSegment_Base::parsimPack(b); b->pack((int)headerOptionList.size()); for (const auto opt: headerOptionList) { b->packObject(opt); } b->pack((int)payloadList.size()); for (PayloadList::const_iterator it = payloadList.begin(); it != payloadList.end(); it++) { b->pack(it->endSequenceNo); b->packObject(it->msg); } } void TCPSegment::parsimUnpack(cCommBuffer *b) { TCPSegment_Base::parsimUnpack(b); int i, n; b->unpack(n); for (i = 0; i < n; i++) { TCPOption *opt = check_and_cast<TCPOption*>(b->unpackObject()); headerOptionList.push_back(opt); } b->unpack(n); for (i = 0; i < n; i++) { TCPPayloadMessage payload; b->unpack(payload.endSequenceNo); payload.msg = check_and_cast<cPacket*>(b->unpackObject()); payloadList.push_back(payload); } } void TCPSegment::setPayloadArraySize(unsigned int size) { throw cRuntimeError(this, "setPayloadArraySize() not supported, use addPayloadMessage()"); } unsigned int TCPSegment::getPayloadArraySize() const { return payloadList.size(); } TCPPayloadMessage& TCPSegment::getPayload(unsigned int k) { auto i = payloadList.begin(); while (k > 0 && i != payloadList.end()) (++i, --k); if (i == payloadList.end()) throw cRuntimeError("Model error at getPayload(): index out of range"); return *i; } void TCPSegment::setPayload(unsigned int k, const TCPPayloadMessage& payload_var) { throw cRuntimeError(this, "setPayload() not supported, use addPayloadMessage()"); } void TCPSegment::addPayloadMessage(cPacket *msg, uint32 endSequenceNo) { take(msg); TCPPayloadMessage payload; payload.endSequenceNo = endSequenceNo; payload.msg = msg; payloadList.push_back(payload); } cPacket *TCPSegment::removeFirstPayloadMessage(uint32& endSequenceNo) { if (payloadList.empty()) return nullptr; cPacket *msg = payloadList.front().msg; endSequenceNo = payloadList.front().endSequenceNo; payloadList.pop_front(); drop(msg); return msg; } void TCPSegment::addHeaderOption(TCPOption *option) { headerOptionList.push_back(option); } void TCPSegment::setHeaderOptionArraySize(unsigned int size) { throw cRuntimeError(this, "setHeaderOptionArraySize() not supported, use addHeaderOption()"); } unsigned int TCPSegment::getHeaderOptionArraySize() const { return headerOptionList.size(); } TCPOptionPtr& TCPSegment::getHeaderOption(unsigned int k) { return headerOptionList.at(k); } void TCPSegment::setHeaderOption(unsigned int k, const TCPOptionPtr& headerOption) { throw cRuntimeError(this, "setHeaderOption() not supported, use addHeaderOption()"); } void TCPSegment::dropHeaderOptions() { for (auto opt : headerOptionList) delete opt; headerOptionList.clear(); } } // namespace tcp } // namespace inet
7,019
2,321
#include "gtest/gtest.h" #include <string> #include "csimsbw.h" #include "csim/error_codes.h" // generated with test resource locations #include "test_resources.h" TEST(SBW, model_string) { char* modelString; int length; int code = csim_serialiseCellmlFromUrl( TestResources::getLocation( TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE), &modelString, &length); EXPECT_EQ(code, 0); EXPECT_NE(std::string(modelString), ""); }
505
177
// Copyright © 2017-2020 Khaos Wallet. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include "Signer.h" #include "Address.h" #include "../PublicKey.h" using namespace TW; using namespace TW::Algorand; const Data TRANSACTION_TAG = {84, 88}; const std::string TRANSACTION_PAY = "pay"; Proto::SigningOutput Signer::sign(const Proto::SigningInput &input) noexcept { auto protoOutput = Proto::SigningOutput(); auto key = PrivateKey(Data(input.private_key().begin(), input.private_key().end())); auto pubkey = key.getPublicKey(TWPublicKeyTypeED25519); auto from = Address(pubkey); auto note = Data(input.note().begin(), input.note().end()); auto genesisId = input.genesis_id(); auto genesisHash = Data(input.genesis_hash().begin(), input.genesis_hash().end()); if (input.has_transaction_pay()) { auto message = input.transaction_pay(); auto to = Address(message.to_address()); auto transaction = Transaction(from, to, message.fee(), message.amount(), message.first_round(), message.last_round(), note, TRANSACTION_PAY, genesisId, genesisHash); auto signature = sign(key, transaction); auto serialized = transaction.serialize(signature); protoOutput.set_encoded(serialized.data(), serialized.size()); } return protoOutput; } Data Signer::sign(const PrivateKey &privateKey, Transaction &transaction) noexcept { Data data; append(data, TRANSACTION_TAG); append(data, transaction.serialize()); auto signature = privateKey.sign(data, TWCurveED25519); return Data(signature.begin(), signature.end()); }
1,822
557
/* Given an integer array of size n, find all elements that appear more than ? n/3 ? times. Note: The algorithm should run in linear time and in O(1) space. Runtime: 16 ms, faster than 87.33% of C++ online submissions for Majority Element II. Memory Usage: 10.7 MB, less than 50.89% of C++ online submissions for Majority Element II. */ class Solution { public: vector<int> majorityElement(vector<int>& nums) { vector<int> result; if (nums.size() == 0) return result; int min_bound = nums.size() / 3; //use hash unordered_map<int, int> mymap; for (const int& x : nums) { ++mymap[x]; } for (auto p : mymap) { if (p.second > min_bound) result.push_back(p.first); } sort(result.begin(), result.end()); return result; } };
748
287
#include "PCU.h" #include "parma_dcpart.h" #include "parma_commons.h" #include "parma_convert.h" #include <maximalIndependentSet/mis.h> #include <pcu_util.h> typedef std::map<unsigned, unsigned> muu; namespace { bool isInMis(muu& mt) { unsigned seed = TO_UINT(PCU_Comm_Self()+1); mis_init(seed); misLuby::partInfo part; part.id = PCU_Comm_Self(); std::set<int> targets; APF_ITERATE(muu, mt, mtItr) { int peer = TO_INT(mtItr->second); if( !targets.count(peer) ) { part.adjPartIds.push_back(peer); part.net.push_back(peer); targets.insert(peer); } } part.net.push_back(part.id); return mis(part,false,true); } } class dcPartFixer::PartFixer : public dcPart { public: PartFixer(apf::Mesh* mesh, unsigned verbose=0) : dcPart(mesh,verbose), m(mesh), vb(verbose) { fix(); } private: apf::Mesh* m; unsigned vb; int totNumDc() { int ndc = TO_INT(numDisconnectedComps()); return PCU_Add_Int(ndc); } void setupPlan(muu& dcCompTgts, apf::Migration* plan) { apf::MeshEntity* e; apf::MeshIterator* itr = m->begin(m->getDimension()); while( (e = m->iterate(itr)) ) { if( isIsolated(e) ) continue; unsigned id = compId(e); if ( dcCompTgts.count(id) ) plan->send(e, TO_INT(dcCompTgts[id])); } m->end(itr); } /** * @brief remove the disconnected set(s) of elements from the part * @remark migrate the disconnected set(s) of elements into the adjacent part * that shares the most faces with the disconnected set of elements * requires that the sets of elements forming disconnected components * are tagged */ void fix() { double t1 = PCU_Time(); int loop = 0; int ndc = 0; while( (ndc = totNumDc()) && loop++ < 50 ) { double t2 = PCU_Time(); muu dcCompTgts; unsigned maxSz = 0; for(unsigned i=0; i<getNumComps(); i++) if( getCompSize(i) > maxSz ) maxSz = getCompSize(i); for(unsigned i=0; i<getNumComps(); i++) if( getCompSize(i) != maxSz ) dcCompTgts[i] = getCompPeer(i); PCU_ALWAYS_ASSERT( dcCompTgts.size() == getNumComps()-1 ); apf::Migration* plan = new apf::Migration(m); if ( isInMis(dcCompTgts) ) setupPlan(dcCompTgts, plan); reset(); double t3 = PCU_Time(); m->migrate(plan); if( ! PCU_Comm_Self() && vb) parmaCommons::status( "loop %d components %d seconds <fix migrate> %.3f %.3f\n", loop, ndc, t3-t2, PCU_Time()-t3); } parmaCommons::printElapsedTime(__func__, PCU_Time() - t1); } }; dcPartFixer::dcPartFixer(apf::Mesh* mesh, unsigned verbose) : pf( new PartFixer(mesh,verbose) ) {} dcPartFixer::~dcPartFixer() { delete pf; }
2,934
1,129
/* * * Copyright (C) 1997-2010, OFFIS e.V. * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation were developed by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: ofstd * * Author: Andreas Barth * * Purpose: test programm for class OFStack * * Last Update: $Author: joergr $ * Update Date: $Date: 2010-10-14 13:15:16 $ * CVS/RCS Revision: $Revision: 1.11 $ * Status: $State: Exp $ * * CVS/RCS Log at end of file * */ #include "dcmtk/config/osconfig.h" #include "dcmtk/ofstd/ofstream.h" #include "dcmtk/ofstd/ofstack.h" #include "dcmtk/ofstd/ofconsol.h" int main() { OFStack<int> st; st.push(1); st.push(2); st.push(3); OFStack<int> nst(st); COUT << "Output of number of Elements in st: " << st.size() << OFendl; COUT << "Output and deletion of st: "; while(!st.empty()) { COUT << st.top() << " "; st.pop(); } COUT << OFendl; COUT << "Output of number of Elements in copy from st: " << nst.size() << OFendl; COUT << "Output and deletion of copy from st: "; while(!nst.empty()) { COUT << nst.top() << " "; nst.pop(); } COUT << OFendl; } /* ** ** CVS/RCS Log: ** $Log: tststack.cc,v $ ** Revision 1.11 2010-10-14 13:15:16 joergr ** Updated copyright header. Added reference to COPYRIGHT file. ** ** Revision 1.10 2006/08/14 16:42:48 meichel ** Updated all code in module ofstd to correctly compile if the standard ** namespace has not included into the global one with a "using" directive. ** ** Revision 1.9 2005/12/08 15:49:11 meichel ** Changed include path schema for all DCMTK header files ** ** Revision 1.8 2004/01/16 10:37:23 joergr ** Removed acknowledgements with e-mail addresses from CVS log. ** ** Revision 1.7 2002/04/16 13:37:01 joergr ** Added configurable support for C++ ANSI standard includes (e.g. streams). ** ** Revision 1.6 2001/06/01 15:51:41 meichel ** Updated copyright header ** ** Revision 1.5 2000/03/08 16:36:08 meichel ** Updated copyright header. ** ** Revision 1.4 2000/03/03 14:02:53 meichel ** Implemented library support for redirecting error messages into memory ** instead of printing them to stdout/stderr for GUI applications. ** ** Revision 1.3 1998/11/27 12:42:11 joergr ** Added copyright message to source files and changed CVS header. ** ** ** */
2,457
1,031
//============================================================================================================= /** * @file gpuinterpolationitem.cpp * @author Lars Debor <lars.debor@tu-ilmenau.de>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date October, 2017 * * @section LICENSE * * Copyright (C) 2017, Lars Debor and Matti Hamalainen. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of MNE-CPP authors nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * @brief GpuInterpolationItem class definition. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "gpuinterpolationitem.h" #include "../../materials/gpuinterpolationmaterial.h" #include "../../3dhelpers/custommesh.h" #include <mne/mne_bem_surface.h> //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <Qt3DCore/QEntity> #include <Qt3DCore/QTransform> #include <Qt3DRender/QComputeCommand> #include <Qt3DRender/QAttribute> #include <Qt3DRender/QGeometryRenderer> //************************************************************************************************************* //============================================================================================================= // Eigen INCLUDES //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace DISP3DLIB; using namespace Qt3DRender; using namespace Qt3DCore; //************************************************************************************************************* //============================================================================================================= // DEFINE GLOBAL METHODS //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= GpuInterpolationItem::GpuInterpolationItem(Qt3DCore::QEntity *p3DEntityParent, int iType, const QString &text) : Abstract3DTreeItem(p3DEntityParent, iType, text) , m_bIsDataInit(false) , m_pMaterial(new GpuInterpolationMaterial) { initItem(); } //************************************************************************************************************* void GpuInterpolationItem::initData(const MNELIB::MNEBemSurface &tMneBemSurface, QSharedPointer<SparseMatrix<double> > tInterpolationMatrix) { if(m_bIsDataInit == true) { qDebug("GpuInterpolationItem::initData data already initialized"); return; } m_pMaterial->setWeightMatrix(tInterpolationMatrix); //Create draw entity if needed if(!m_pMeshDrawEntity) { m_pMeshDrawEntity = new QEntity(this); m_pCustomMesh = new CustomMesh; //Interpolated signal attribute QAttribute *pInterpolatedSignalAttrib = new QAttribute; pInterpolatedSignalAttrib->setAttributeType(Qt3DRender::QAttribute::VertexAttribute); pInterpolatedSignalAttrib->setDataType(Qt3DRender::QAttribute::Float); pInterpolatedSignalAttrib->setVertexSize(4); pInterpolatedSignalAttrib->setByteOffset(0); pInterpolatedSignalAttrib->setByteStride(4 * sizeof(float)); pInterpolatedSignalAttrib->setName(QStringLiteral("OutputColor")); pInterpolatedSignalAttrib->setBuffer(m_pMaterial->getOutputColorBuffer()); //add interpolated signal Attribute m_pCustomMesh->addAttribute(pInterpolatedSignalAttrib); m_pMeshDrawEntity->addComponent(m_pCustomMesh); m_pMeshDrawEntity->addComponent(m_pMaterial); } //Create compute entity if needed if(!m_pComputeEntity) { m_pComputeEntity = new QEntity(this); m_pComputeCommand = new QComputeCommand; m_pComputeEntity->addComponent(m_pComputeCommand); m_pComputeEntity->addComponent(m_pMaterial); } const uint iWeightMatRows = tMneBemSurface.rr.rows(); //Set work group size const uint iWorkGroupsSize = static_cast<uint>(std::ceil(std::sqrt(iWeightMatRows))); m_pComputeCommand->setWorkGroupX(iWorkGroupsSize); m_pComputeCommand->setWorkGroupY(iWorkGroupsSize); m_pComputeCommand->setWorkGroupZ(1); //Set custom mesh data //generate mesh base color QColor baseColor = QColor(80, 80, 80, 255); MatrixX3f matVertColor(tMneBemSurface.rr.rows(),3); for(int i = 0; i < matVertColor.rows(); ++i) { matVertColor(i,0) = baseColor.redF(); matVertColor(i,1) = baseColor.greenF(); matVertColor(i,2) = baseColor.blueF(); } //Set renderable 3D entity mesh and color data m_pCustomMesh->setMeshData(tMneBemSurface.rr, tMneBemSurface.nn, tMneBemSurface.tris, matVertColor, Qt3DRender::QGeometryRenderer::Triangles); m_bIsDataInit = true; } //************************************************************************************************************* void GpuInterpolationItem::setWeightMatrix(QSharedPointer<SparseMatrix<double> > tInterpolationMatrix) { if(m_bIsDataInit == false) { qDebug("GpuInterpolationItem::setWeightMatrix item data is not initialized!"); return; } m_pMaterial->setWeightMatrix(tInterpolationMatrix); } //************************************************************************************************************* void GpuInterpolationItem::addNewRtData(const VectorXf &tSignalVec) { if(m_pMaterial && m_bIsDataInit) { m_pMaterial->addSignalData(tSignalVec); } } //************************************************************************************************************* void GpuInterpolationItem::setNormalization(const QVector3D &tVecThresholds) { m_pMaterial->setNormalization(tVecThresholds); } //************************************************************************************************************* void GpuInterpolationItem::setColormapType(const QString &tColormapType) { m_pMaterial->setColormapType(tColormapType); } //************************************************************************************************************* void GpuInterpolationItem::initItem() { this->setEditable(false); this->setCheckable(true); this->setCheckState(Qt::Checked); this->setToolTip(this->text()); } //*************************************************************************************************************
9,172
2,468
/// @file /// /// Copyright Matus Chochlik. /// Distributed under the Boost Software License, Version 1.0. /// See accompanying file LICENSE_1_0.txt or copy at /// http://www.boost.org/LICENSE_1_0.txt /// #include <eagine/app/context.hpp> #include <eagine/extract.hpp> #include <eagine/integer_range.hpp> #include <eagine/logging/type/yes_no_maybe.hpp> #include <eagine/maybe_unused.hpp> #include <eagine/oglplus/config/basic.hpp> #include <eagine/valid_if/decl.hpp> #include <eagine/eglplus/egl.hpp> #include <eagine/eglplus/egl_api.hpp> namespace eagine::app { //------------------------------------------------------------------------------ // surface //------------------------------------------------------------------------------ class eglplus_opengl_surface : public main_ctx_object , public video_provider { public: eglplus_opengl_surface(main_ctx_parent parent, eglplus::egl_api& egl) : main_ctx_object{EAGINE_ID(EGLPbuffer), parent} , _egl_api{egl} {} auto get_context_attribs( execution_context&, const bool gl_otherwise_gles, const launch_options&, const video_options&) const -> std::vector<eglplus::egl_types::int_type>; auto initialize( execution_context&, const eglplus::display_handle, const eglplus::egl_types::config_type, const launch_options&, const video_options&) -> bool; auto initialize( execution_context&, const eglplus::display_handle, const valid_if_nonnegative<span_size_t>& device_idx, const launch_options&, const video_options&) -> bool; auto initialize( execution_context&, const identifier instance, const launch_options&, const video_options&) -> bool; void clean_up(); auto video_kind() const noexcept -> video_context_kind final; auto instance_id() const noexcept -> identifier final; auto is_offscreen() noexcept -> tribool final; auto has_framebuffer() noexcept -> tribool final; auto surface_size() noexcept -> std::tuple<int, int> final; auto surface_aspect() noexcept -> float final; void parent_context_changed(const video_context&) final; void video_begin(execution_context&) final; void video_end(execution_context&) final; void video_commit(execution_context&) final; private: eglplus::egl_api& _egl_api; identifier _instance_id; eglplus::display_handle _display{}; eglplus::surface_handle _surface{}; eglplus::context_handle _context{}; int _width{1}; int _height{1}; }; //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::get_context_attribs( execution_context&, const bool gl_otherwise_gles, const launch_options&, const video_options& video_opts) const -> std::vector<eglplus::egl_types::int_type> { const auto& EGL = _egl_api.constants(); const auto add_major_version = [&](auto attribs) { return attribs + (EGL.context_major_version | (video_opts.gl_version_major() / 3)); }; const auto add_minor_version = [&](auto attribs) { eglplus::context_attrib_traits::value_type fallback = 0; if(gl_otherwise_gles) { if(!video_opts.gl_compatibility_context()) { fallback = 3; } } return attribs + (EGL.context_minor_version | (video_opts.gl_version_minor() / fallback)); }; const auto add_profile_mask = [&](auto attribs) { const auto compat = video_opts.gl_compatibility_context(); if(compat) { return attribs + (EGL.context_opengl_profile_mask | EGL.context_opengl_compatibility_profile_bit); } else { return attribs + (EGL.context_opengl_profile_mask | EGL.context_opengl_core_profile_bit); } }; const auto add_debugging = [&](auto attribs) { return attribs + (EGL.context_opengl_debug | video_opts.gl_debug_context()); }; const auto add_robustness = [&](auto attribs) { return attribs + (EGL.context_opengl_robust_access | video_opts.gl_robust_access()); }; return add_robustness( add_debugging(add_profile_mask(add_minor_version( add_major_version(eglplus::context_attribute_base()))))) .copy(); } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::initialize( execution_context& exec_ctx, const eglplus::display_handle display, const eglplus::egl_types::config_type config, const launch_options& opts, const video_options& video_opts) -> bool { const auto& [egl, EGL] = _egl_api; const auto apis{egl.get_client_api_bits(display)}; const bool has_gl = apis.has(EGL.opengl_bit); const bool has_gles = apis.has(EGL.opengl_es_bit); if(!has_gl && !has_gles) { log_info("display does not support any OpenAPI APIs;skipping"); return false; } log_info("display device supports GL APIs") .arg(EAGINE_ID(OpenGL), yes_no_maybe(has_gl)) .arg(EAGINE_ID(OpenGL_ES), yes_no_maybe(has_gles)) .arg(EAGINE_ID(PreferES), yes_no_maybe(video_opts.prefer_gles())); const bool gl_otherwise_gles = has_gl && !video_opts.prefer_gles(); _width = video_opts.surface_width() / 1; _height = video_opts.surface_height() / 1; const auto surface_attribs = (EGL.width | _width) + (EGL.height | _height); if(ok surface{ egl.create_pbuffer_surface(display, config, surface_attribs)}) { _surface = surface; const auto gl_api = gl_otherwise_gles ? eglplus::client_api(EGL.opengl_api) : eglplus::client_api(EGL.opengl_es_api); if(ok bound{egl.bind_api(gl_api)}) { const auto context_attribs = get_context_attribs( exec_ctx, gl_otherwise_gles, opts, video_opts); if(ok ctxt{egl.create_context( display, config, eglplus::context_handle{}, view(context_attribs))}) { _context = ctxt; return true; } else { log_error("failed to create context") .arg(EAGINE_ID(message), (!ctxt).message()); } } else { log_error("failed to bind OpenGL API") .arg(EAGINE_ID(message), (!bound).message()); } } else { log_error("failed to create pbuffer ${width}x${height}") .arg(EAGINE_ID(width), _width) .arg(EAGINE_ID(height), _height) .arg(EAGINE_ID(message), (!surface).message()); } return false; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::initialize( execution_context& exec_ctx, const eglplus::display_handle display, const valid_if_nonnegative<span_size_t>& device_idx, const launch_options& opts, const video_options& video_opts) -> bool { const auto& [egl, EGL] = _egl_api; if(device_idx) { log_info("trying EGL device ${index}") .arg(EAGINE_ID(index), extract(device_idx)); } else { exec_ctx.log_info("trying default EGL display device"); } if(ok initialized{egl.initialize(display)}) { if(auto conf_driver_name{video_opts.driver_name()}) { if(egl.MESA_query_driver(display)) { if(ok driver_name{egl.get_display_driver_name(display)}) { if(are_equal( extract(video_opts.driver_name()), extract(driver_name))) { log_info("using the ${driver} MESA display driver") .arg( EAGINE_ID(driver), EAGINE_ID(Identifier), extract(driver_name)); } else { log_info( "${current} does not match the configured " "${config} display driver; skipping") .arg( EAGINE_ID(current), EAGINE_ID(Identifier), extract(driver_name)) .arg( EAGINE_ID(config), EAGINE_ID(Identifier), extract(conf_driver_name)); return false; } } else { log_error("failed to get EGL display driver name"); return false; } } else { log_info( "cannot determine current display driver to match " "with configured ${config} driver; skipping") .arg( EAGINE_ID(config), EAGINE_ID(Identifier), extract(conf_driver_name)); return false; } } else { if(egl.MESA_query_driver(display)) { if(ok driver_name{egl.get_display_driver_name(display)}) { log_info("using the ${driver} MESA display driver") .arg( EAGINE_ID(driver), EAGINE_ID(Identifier), extract(driver_name)); } } } _display = display; const auto config_attribs = (EGL.red_size | (video_opts.color_bits() / EGL.dont_care)) + (EGL.green_size | (video_opts.color_bits() / EGL.dont_care)) + (EGL.blue_size | (video_opts.color_bits() / EGL.dont_care)) + (EGL.alpha_size | (video_opts.alpha_bits() / EGL.dont_care)) + (EGL.depth_size | (video_opts.depth_bits() / EGL.dont_care)) + (EGL.stencil_size | (video_opts.stencil_bits() / EGL.dont_care)) + (EGL.color_buffer_type | EGL.rgb_buffer) + (EGL.surface_type | EGL.pbuffer_bit) + (EGL.renderable_type | (EGL.opengl_bit | EGL.opengl_es3_bit)); if(ok count{egl.choose_config.count(_display, config_attribs)}) { log_info("found ${count} suitable framebuffer configurations") .arg(EAGINE_ID(count), extract(count)); if(ok config{egl.choose_config(_display, config_attribs)}) { return initialize(exec_ctx, _display, config, opts, video_opts); } else { const string_view dont_care{"-"}; log_error("no matching framebuffer configuration found") .arg( EAGINE_ID(color), EAGINE_ID(integer), video_opts.color_bits(), dont_care) .arg( EAGINE_ID(alpha), EAGINE_ID(integer), video_opts.alpha_bits(), dont_care) .arg( EAGINE_ID(depth), EAGINE_ID(integer), video_opts.depth_bits(), dont_care) .arg( EAGINE_ID(stencil), EAGINE_ID(integer), video_opts.stencil_bits(), dont_care) .arg(EAGINE_ID(message), (!config).message()); } } else { log_error("failed to query framebuffer configurations") .arg(EAGINE_ID(message), (!count).message()); } } else { exec_ctx.log_error("failed to initialize EGL display") .arg(EAGINE_ID(message), (!initialized).message()); } return false; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::initialize( execution_context& exec_ctx, const identifier id, const launch_options& opts, const video_options& video_opts) -> bool { _instance_id = id; const auto& [egl, EGL] = _egl_api; const auto device_kind = video_opts.device_kind(); const auto device_path = video_opts.device_path(); const auto device_idx = video_opts.device_index(); const bool select_device = device_kind.is_valid() || device_path.is_valid() || device_idx.is_valid() || video_opts.driver_name().is_valid(); if(select_device && egl.EXT_device_enumeration) { if(ok dev_count{egl.query_devices.count()}) { const auto n = std_size(extract(dev_count)); std::vector<eglplus::egl_types::device_type> devices; devices.resize(n); if(egl.query_devices(cover(devices))) { for(const auto cur_dev_idx : integer_range(n)) { bool matching_device = true; auto device = eglplus::device_handle(devices[cur_dev_idx]); if(device_idx) { if(std_size(extract(device_idx)) == cur_dev_idx) { log_info("explicitly selected device ${index}") .arg(EAGINE_ID(index), extract(device_idx)); } else { matching_device = false; log_info( "current device index is ${current} but, " "device ${config} requested; skipping") .arg(EAGINE_ID(current), cur_dev_idx) .arg(EAGINE_ID(config), extract(device_idx)); } } if(device_kind) { if(extract(device_kind) == video_device_kind::hardware) { if(!egl.MESA_device_software(device)) { log_info( "device ${index} seems to be hardware as " "explicitly specified by configuration") .arg(EAGINE_ID(index), cur_dev_idx); } else { matching_device = false; log_info( "device ${index} is software but, " "hardware device requested; skipping") .arg(EAGINE_ID(index), cur_dev_idx); } } else if( extract(device_kind) == video_device_kind::software) { if(!egl.EXT_device_drm(device)) { log_info( "device ${index} seems to be software as " "explicitly specified by configuration") .arg(EAGINE_ID(index), cur_dev_idx); } else { matching_device = false; log_info( "device ${index} is hardware but, " "software device requested; skipping") .arg(EAGINE_ID(index), cur_dev_idx); } } } if(device_path) { if(egl.EXT_device_drm(device)) { if(ok path{egl.query_device_string( device, EGL.drm_device_file)}) { if(are_equal( extract(device_path), extract(path))) { log_info( "using DRM device ${path} as " "explicitly specified by configuration") .arg( EAGINE_ID(path), EAGINE_ID(FsPath), extract(path)); } else { matching_device = false; log_info( "device file is ${current}, but " "${config} was requested; skipping") .arg( EAGINE_ID(current), EAGINE_ID(FsPath), extract(path)) .arg( EAGINE_ID(config), EAGINE_ID(FsPath), extract(device_path)); } } } else { log_warning( "${config} requested by config, but cannot " "determine current device file path") .arg( EAGINE_ID(config), EAGINE_ID(FsPath), extract(device_path)); } } if(matching_device) { if(ok display{egl.get_platform_display(device)}) { if(initialize( exec_ctx, display, signedness_cast(cur_dev_idx), opts, video_opts)) { return true; } else { _egl_api.terminate(display); } } } } } } } else { if(ok display{egl.get_display()}) { return initialize(exec_ctx, display, -1, opts, video_opts); } else { exec_ctx.log_error("failed to get EGL display") .arg(EAGINE_ID(message), (!display).message()); } } return false; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_surface::clean_up() { if(_display) { if(_context) { _egl_api.destroy_context(_display, _context); } if(_surface) { _egl_api.destroy_surface(_display, _surface); } _egl_api.terminate(_display); } } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::video_kind() const noexcept -> video_context_kind { return video_context_kind::opengl; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::instance_id() const noexcept -> identifier { return _instance_id; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::is_offscreen() noexcept -> tribool { return true; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::has_framebuffer() noexcept -> tribool { return true; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::surface_size() noexcept -> std::tuple<int, int> { return {_width, _height}; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::surface_aspect() noexcept -> float { return float(_width) / float(_height); } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_surface::parent_context_changed(const video_context&) {} //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_surface::video_begin(execution_context&) { _egl_api.make_current(_display, _surface, _context); } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_surface::video_end(execution_context&) { _egl_api.make_current.none(_display); } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_surface::video_commit(execution_context&) { _egl_api.swap_buffers(_display, _surface); } //------------------------------------------------------------------------------ // provider //------------------------------------------------------------------------------ class eglplus_opengl_provider : public main_ctx_object , public hmi_provider { public: eglplus_opengl_provider(main_ctx_parent parent) : main_ctx_object{EAGINE_ID(EGLPPrvdr), parent} {} auto is_implemented() const noexcept -> bool final; auto implementation_name() const noexcept -> string_view final; auto is_initialized() -> bool final; auto should_initialize(execution_context&) -> bool final; auto initialize(execution_context&) -> bool final; void update(execution_context&) final; void clean_up(execution_context&) final; void input_enumerate( callable_ref<void(std::shared_ptr<input_provider>)>) final; void video_enumerate( callable_ref<void(std::shared_ptr<video_provider>)>) final; void audio_enumerate( callable_ref<void(std::shared_ptr<audio_provider>)>) final; private: eglplus::egl_api _egl_api; std::map<identifier, std::shared_ptr<eglplus_opengl_surface>> _surfaces; }; //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_provider::is_implemented() const noexcept -> bool { return _egl_api.get_display && _egl_api.initialize && _egl_api.terminate && _egl_api.get_configs && _egl_api.choose_config && _egl_api.get_config_attrib && _egl_api.query_string && _egl_api.swap_buffers; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_provider::implementation_name() const noexcept -> string_view { return {"eglplus"}; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_provider::is_initialized() -> bool { return !_surfaces.empty(); } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_provider::should_initialize(execution_context& exec_ctx) -> bool { for(auto& [inst, video_opts] : exec_ctx.options().video_requirements()) { EAGINE_MAYBE_UNUSED(inst); if(video_opts.has_provider(implementation_name())) { return true; } } return false; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_provider::initialize(execution_context& exec_ctx) -> bool { if(_egl_api.get_display) { auto& options = exec_ctx.options(); for(auto& [inst, video_opts] : options.video_requirements()) { const bool should_create_surface = video_opts.has_provider(implementation_name()) && (video_opts.video_kind() == video_context_kind::opengl); if(should_create_surface) { if(auto surface{std::make_shared<eglplus_opengl_surface>( *this, _egl_api)}) { if(extract(surface).initialize( exec_ctx, inst, options, video_opts)) { _surfaces[inst] = std::move(surface); } else { extract(surface).clean_up(); } } } } return true; } exec_ctx.log_error("EGL is context is not supported"); return false; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_provider::update(execution_context&) {} //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_provider::clean_up(execution_context&) { for(auto& entry : _surfaces) { entry.second->clean_up(); } } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_provider::input_enumerate( callable_ref<void(std::shared_ptr<input_provider>)>) {} //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_provider::video_enumerate( callable_ref<void(std::shared_ptr<video_provider>)> handler) { for(auto& p : _surfaces) { handler(p.second); } } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_provider::audio_enumerate( callable_ref<void(std::shared_ptr<audio_provider>)>) {} //------------------------------------------------------------------------------ auto make_eglplus_opengl_provider(main_ctx_parent parent) -> std::shared_ptr<hmi_provider> { return {std::make_shared<eglplus_opengl_provider>(parent)}; } //------------------------------------------------------------------------------ } // namespace eagine::app
25,800
7,141
#include "FontCache.h" using Gdiplus::FontStyleRegular; using Gdiplus::UnitPixel; using Gdiplus::UnitPoint; using Gdiplus::FontCollection; namespace PRImA { /* * Class CFontCache * * Static cache for fonts used in Aletheia * * CC 05.10.2011 - created */ const wchar_t * CFontCache::FONT_ALETHEIA_SANS = _T("Aletheia Sans"); const wchar_t * CFontCache::FONT_ARIAL = _T("Arial"); const wchar_t * CFontCache::FONT_MS_SHELL_DLG = L"MS Shell Dlg"; map<CUniString, map<int, CFont *> * > CFontCache::s_NormalFonts; map<CUniString, map<int, CFont *> * > CFontCache::s_BoldFonts; map<CUniString, map<double, Gdiplus::Font *> * > CFontCache::s_GdiPlusFonts; CCriticalSection CFontCache::s_CriticalSect; PrivateFontCollection * CFontCache::s_GdiPlusFontCollection = NULL; set<CUniString> CFontCache::s_PrivateGdiPlusFonts; /* * Constructor */ CFontCache::CFontCache(void) { } /* * Destructor */ CFontCache::~CFontCache(void) { } /* * Initialises a font collection for GDI+ fonts (thread-safe) */ void CFontCache::InitPrivateFontCollection() { CSingleLock lock(&s_CriticalSect, TRUE); if (s_GdiPlusFontCollection == NULL) s_GdiPlusFontCollection = new PrivateFontCollection(); lock.Unlock(); } /* * Adds non-installed font from a file for usage with GDI+ */ void CFontCache::AddPrivateGdiPlusFont(CUniString fontName, CUniString filepath) { InitPrivateFontCollection(); s_GdiPlusFontCollection->AddFontFile(filepath.GetBuffer()); s_PrivateGdiPlusFonts.insert(fontName); } /* * Deletes all cached fonts */ void CFontCache::DeleteFonts() { CSingleLock lock(&s_CriticalSect, TRUE); for (map<CUniString, map<int, CFont *> * >::iterator it = s_NormalFonts.begin(); it != s_NormalFonts.end(); it++) { map<int, CFont *> * map2 = (*it).second; for (map<int, CFont *>::iterator it2 = map2->begin(); it2 != map2->end(); it2++) { (*it2).second->DeleteObject(); delete (*it2).second; } delete map2; } for (map<CUniString, map<int, CFont *> * >::iterator it = s_BoldFonts.begin(); it != s_BoldFonts.end(); it++) { map<int, CFont *> * map2 = (*it).second; for (map<int, CFont *>::iterator it2 = map2->begin(); it2 != map2->end(); it2++) { (*it2).second->DeleteObject(); delete (*it2).second; } delete map2; } for (map<CUniString, map<double, Gdiplus::Font *> * >::iterator it3 = s_GdiPlusFonts.begin(); it3 != s_GdiPlusFonts.end(); it3++) { map<double, Gdiplus::Font *> * map2 = (*it3).second; for (map<double, Gdiplus::Font *>::iterator it4 = map2->begin(); it4 != map2->end(); it4++) { delete (*it4).second; } delete map2; } lock.Unlock(); } /* * Returns a font of the given name (see CFontCache::FONT_...) and height (in pixel). */ CFont * CFontCache::GetFont(CUniString id, int height, bool bold /*= false*/) { CSingleLock lock(&s_CriticalSect, TRUE); map<CUniString, map<int, CFont *> * > & fonts = bold ? s_BoldFonts : s_NormalFonts; //Id map<CUniString, map<int, CFont *> * >::iterator itId = fonts.find(id); map<int, CFont *> * heightMap = NULL; if (itId == fonts.end()) { heightMap = new map<int, CFont *>(); fonts.insert(pair<CUniString, map<int, CFont *> *>(id, heightMap)); } else heightMap = (*itId).second; //Size map<int, CFont *>::iterator itHeight = heightMap->find(height); CFont * font = NULL; if (itHeight == heightMap->end()) { //Create font font = new CFont(); font->CreateFont( height, // nHeight 0, // nWidth 0, // nEscapement 0, // nOrientation bold ? FW_BOLD : FW_NORMAL,// nWeight FALSE, // bItalic FALSE, // bUnderline 0, // cStrikeOut ANSI_CHARSET, // nwchar_tSet OUT_DEFAULT_PRECIS, // nOutPrecision CLIP_DEFAULT_PRECIS, // nClipPrecision DEFAULT_QUALITY, // nQuality DEFAULT_PITCH | FF_SWISS, // nPitchAndFamily id); // lpszFacename heightMap->insert(pair<int, CFont*>(height, font)); } else font = (*itHeight).second; lock.Unlock(); return font; } /* * Returns a font of the given name (see CFontCache::FONT_...) and size (in pixel or point). * * 'unitIsPoint' - If true, the size is interpreted as point, otherwise as pixel */ Gdiplus::Font * CFontCache::GetGdiPlusFont(CUniString id, double size, bool unitIsPoint /*= true*/) { InitPrivateFontCollection(); CSingleLock lock(&s_CriticalSect, TRUE); //Id map<CUniString, map<double, Gdiplus::Font *> * >::iterator itId = s_GdiPlusFonts.find(id); map<double, Gdiplus::Font *> * heightMap = NULL; if (itId == s_GdiPlusFonts.end()) { heightMap = new map<double, Gdiplus::Font *>(); s_GdiPlusFonts.insert(pair<const wchar_t *, map<double, Gdiplus::Font *> *>(id, heightMap)); } else heightMap = (*itId).second; //Size map<double, Gdiplus::Font *>::iterator itHeight = heightMap->find(size); Gdiplus::Font * font = NULL; if (itHeight == heightMap->end()) { //Is the font a private one? set<CUniString>::iterator itPrivate = s_PrivateGdiPlusFonts.find(id); if (itPrivate != s_PrivateGdiPlusFonts.end()) //Private { //Create font if (unitIsPoint) font = new Gdiplus::Font(id, (Gdiplus::REAL)size, FontStyleRegular, UnitPoint, s_GdiPlusFontCollection); else font = new Gdiplus::Font(id, (Gdiplus::REAL)size, FontStyleRegular, UnitPixel, s_GdiPlusFontCollection); } else //Normal system font { //Create font if (unitIsPoint) font = new Gdiplus::Font(id, (Gdiplus::REAL)size, FontStyleRegular); else font = new Gdiplus::Font(id, (Gdiplus::REAL)size, FontStyleRegular, UnitPixel); } heightMap->insert(pair<double, Gdiplus::Font*>(size, font)); } else font = (*itHeight).second; lock.Unlock(); return font; } } //end namespace
5,891
2,347
/** * \date 2014-08-04 * \brief Implementation of OpenGeoSys simulation application * * \copyright * Copyright (c) 2012-2020, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include <tclap/CmdLine.h> #include <chrono> #ifndef _WIN32 #ifdef __APPLE__ #include <xmmintrin.h> #else #include <cfenv> #endif // __APPLE__ #endif // _WIN32 #ifdef USE_PETSC #include <vtkMPIController.h> #include <vtkSmartPointer.h> #endif // BaseLib #include "BaseLib/ConfigTreeUtil.h" #include "BaseLib/DateTools.h" #include "BaseLib/FileTools.h" #include "BaseLib/RunTime.h" #include "BaseLib/TemplateLogogFormatterSuppressedGCC.h" #include "Applications/ApplicationsLib/LinearSolverLibrarySetup.h" #include "Applications/ApplicationsLib/LogogSetup.h" #include "Applications/ApplicationsLib/ProjectData.h" #include "Applications/ApplicationsLib/TestDefinition.h" #include "Applications/InSituLib/Adaptor.h" #include "InfoLib/CMakeInfo.h" #include "InfoLib/GitInfo.h" #include "ProcessLib/TimeLoop.h" #include "NumLib/NumericsConfig.h" #ifdef OGS_USE_PYTHON #include "ogs_embedded_python.h" #endif int main(int argc, char* argv[]) { // Parse CLI arguments. TCLAP::CmdLine cmd( "OpenGeoSys-6 software.\n" "Copyright (c) 2012-2020, OpenGeoSys Community " "(http://www.opengeosys.org) " "Distributed under a Modified BSD License. " "See accompanying file LICENSE.txt or " "http://www.opengeosys.org/project/license\n" "version: " + GitInfoLib::GitInfo::ogs_version + "\n" + "CMake arguments: " + CMakeInfoLib::CMakeInfo::cmake_args, ' ', GitInfoLib::GitInfo::ogs_version); TCLAP::ValueArg<std::string> reference_path_arg( "r", "reference", "Run output result comparison after successful simulation comparing to " "all files in the given path.", false, "", "PATH"); cmd.add(reference_path_arg); TCLAP::UnlabeledValueArg<std::string> project_arg( "project-file", "Path to the ogs6 project file.", true, "", "PROJECT_FILE"); cmd.add(project_arg); TCLAP::ValueArg<std::string> outdir_arg("o", "output-directory", "the output directory to write to", false, "", "PATH"); cmd.add(outdir_arg); TCLAP::ValueArg<std::string> log_level_arg("l", "log-level", "the verbosity of logging " "messages: none, error, warn, " "info, debug, all", false, #ifdef NDEBUG "info", #else "all", #endif "LOG_LEVEL"); cmd.add(log_level_arg); TCLAP::SwitchArg nonfatal_arg("", "config-warnings-nonfatal", "warnings from parsing the configuration " "file will not trigger program abortion"); cmd.add(nonfatal_arg); TCLAP::SwitchArg unbuffered_cout_arg("", "unbuffered-std-out", "use unbuffered standard output"); cmd.add(unbuffered_cout_arg); #ifndef _WIN32 // TODO: On windows floating point exceptions are not handled // currently TCLAP::SwitchArg enable_fpe_arg("", "enable-fpe", "enables floating point exceptions"); cmd.add(enable_fpe_arg); #endif // _WIN32 cmd.parse(argc, argv); // deactivate buffer for standard output if specified if (unbuffered_cout_arg.isSet()) { std::cout.setf(std::ios::unitbuf); } ApplicationsLib::LogogSetup logog_setup; logog_setup.setLevel(log_level_arg.getValue()); INFO("This is OpenGeoSys-6 version %s.", GitInfoLib::GitInfo::ogs_version.c_str()); #ifndef _WIN32 // On windows this command line option is not present. // Enable floating point exceptions if (enable_fpe_arg.isSet()) { #ifdef __APPLE__ _MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() & ~_MM_MASK_INVALID); #else feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW); #endif // __APPLE__ } #endif // _WIN32 #ifdef OGS_USE_PYTHON pybind11::scoped_interpreter guard = ApplicationsLib::setupEmbeddedPython(); (void)guard; #endif BaseLib::RunTime run_time; { auto const start_time = std::chrono::system_clock::now(); auto const time_str = BaseLib::formatDate(start_time); INFO("OGS started on %s.", time_str.c_str()); } std::unique_ptr<ApplicationsLib::TestDefinition> test_definition; auto ogs_status = EXIT_SUCCESS; try { bool solver_succeeded = false; { ApplicationsLib::LinearSolverLibrarySetup linear_solver_library_setup(argc, argv); #if defined(USE_PETSC) vtkSmartPointer<vtkMPIController> controller = vtkSmartPointer<vtkMPIController>::New(); controller->Initialize(&argc, &argv, 1); vtkMPIController::SetGlobalController(controller); logog_setup.setFormatter( std::make_unique<BaseLib::TemplateLogogFormatterSuppressedGCC< TOPIC_LEVEL_FLAG | TOPIC_FILE_NAME_FLAG | TOPIC_LINE_NUMBER_FLAG>>()); #endif run_time.start(); auto project_config = BaseLib::makeConfigTree( project_arg.getValue(), !nonfatal_arg.getValue(), "OpenGeoSysProject"); BaseLib::setProjectDirectory( BaseLib::extractPath(project_arg.getValue())); ProjectData project(*project_config, BaseLib::getProjectDirectory(), outdir_arg.getValue()); if (!reference_path_arg.isSet()) { // Ignore the test_definition section. project_config->ignoreConfigParameter("test_definition"); } else { test_definition = std::make_unique<ApplicationsLib::TestDefinition>( //! \ogs_file_param{prj__test_definition} project_config->getConfigSubtree("test_definition"), reference_path_arg.getValue(), outdir_arg.getValue()); INFO("Cleanup possible output files before running ogs."); BaseLib::removeFiles(test_definition->getOutputFiles()); } #ifdef USE_INSITU auto isInsituConfigured = false; //! \ogs_file_param{prj__insitu} if (auto t = project_config->getConfigSubtreeOptional("insitu")) { InSituLib::Initialize( //! \ogs_file_param{prj__insitu__scripts} t->getConfigSubtree("scripts"), BaseLib::extractPath(project_arg.getValue())); isInsituConfigured = true; } #else project_config->ignoreConfigParameter("insitu"); #endif INFO("Initialize processes."); for (auto& p : project.getProcesses()) { p->initialize(); } // Check intermediately that config parsing went fine. project_config.checkAndInvalidate(); BaseLib::ConfigTree::assertNoSwallowedErrors(); BaseLib::ConfigTree::assertNoSwallowedErrors(); BaseLib::ConfigTree::assertNoSwallowedErrors(); INFO("Solve processes."); auto& time_loop = project.getTimeLoop(); time_loop.initialize(); solver_succeeded = time_loop.loop(); #ifdef USE_INSITU if (isInsituConfigured) InSituLib::Finalize(); #endif INFO("[time] Execution took %g s.", run_time.elapsed()); #if defined(USE_PETSC) controller->Finalize(1); #endif } // This nested scope ensures that everything that could possibly // possess a ConfigTree is destructed before the final check below is // done. BaseLib::ConfigTree::assertNoSwallowedErrors(); ogs_status = solver_succeeded ? EXIT_SUCCESS : EXIT_FAILURE; } catch (std::exception& e) { ERR(e.what()); ogs_status = EXIT_FAILURE; } { auto const end_time = std::chrono::system_clock::now(); auto const time_str = BaseLib::formatDate(end_time); INFO("OGS terminated on %s.", time_str.c_str()); } if (ogs_status == EXIT_FAILURE) { ERR("OGS terminated with error."); return EXIT_FAILURE; } if (test_definition == nullptr) { // There are no tests, so just exit; return ogs_status; } INFO(""); INFO("##########################################"); INFO("# Running tests #"); INFO("##########################################"); INFO(""); if (!test_definition->runTests()) { ERR("One of the tests failed."); return EXIT_FAILURE; } return EXIT_SUCCESS; }
9,544
2,840
/* Dwarf Therapist Copyright (c) 2018 Clement Vuchener 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 "defaultroleweight.h" #include "standardpaths.h" DefaultRoleWeight DefaultRoleWeight::attributes("attributes", 0.25); DefaultRoleWeight DefaultRoleWeight::skills("skills", 1.0); DefaultRoleWeight DefaultRoleWeight::facets("traits", 0.20); DefaultRoleWeight DefaultRoleWeight::beliefs("beliefs", 0.20); DefaultRoleWeight DefaultRoleWeight::goals("goals", 0.10); DefaultRoleWeight DefaultRoleWeight::needs("needs", 0.10); DefaultRoleWeight DefaultRoleWeight::preferences("prefs", 0.15); DefaultRoleWeight::DefaultRoleWeight(const char *key, float default_value) : m_value_key(QString("options/default_%1_weight").arg(key)) , m_overwrite_key(QString("options/overwrite_default_%1_weight").arg(key)) , m_default_value(default_value) , m_value(default_value) { } void DefaultRoleWeight::update() { auto s = StandardPaths::settings(); m_overwrite = s->value(m_overwrite_key, s->contains(m_value_key)).toBool(); m_value = s->value(m_value_key, m_default_value).toFloat(); } void DefaultRoleWeight::update_all() { attributes.update(); skills.update(); facets.update(); beliefs.update(); goals.update(); needs.update(); preferences.update(); }
2,289
754
#include "duckdb/execution/operator/set/physical_recursive_cte.hpp" #include "duckdb/common/vector_operations/vector_operations.hpp" #include "duckdb/common/types/chunk_collection.hpp" #include "duckdb/execution/aggregate_hashtable.hpp" #include "duckdb/parallel/pipeline.hpp" #include "duckdb/storage/buffer_manager.hpp" #include "duckdb/parallel/task_scheduler.hpp" #include "duckdb/execution/executor.hpp" #include "duckdb/parallel/event.hpp" namespace duckdb { PhysicalRecursiveCTE::PhysicalRecursiveCTE(vector<LogicalType> types, bool union_all, unique_ptr<PhysicalOperator> top, unique_ptr<PhysicalOperator> bottom, idx_t estimated_cardinality) : PhysicalOperator(PhysicalOperatorType::RECURSIVE_CTE, move(types), estimated_cardinality), union_all(union_all) { children.push_back(move(top)); children.push_back(move(bottom)); } PhysicalRecursiveCTE::~PhysicalRecursiveCTE() { } //===--------------------------------------------------------------------===// // Sink //===--------------------------------------------------------------------===// class RecursiveCTEState : public GlobalSinkState { public: explicit RecursiveCTEState(ClientContext &context, const PhysicalRecursiveCTE &op) : new_groups(STANDARD_VECTOR_SIZE) { ht = make_unique<GroupedAggregateHashTable>(BufferManager::GetBufferManager(context), op.types, vector<LogicalType>(), vector<BoundAggregateExpression *>()); } unique_ptr<GroupedAggregateHashTable> ht; bool intermediate_empty = true; ChunkCollection intermediate_table; idx_t chunk_idx = 0; SelectionVector new_groups; }; unique_ptr<GlobalSinkState> PhysicalRecursiveCTE::GetGlobalSinkState(ClientContext &context) const { return make_unique<RecursiveCTEState>(context, *this); } idx_t PhysicalRecursiveCTE::ProbeHT(DataChunk &chunk, RecursiveCTEState &state) const { Vector dummy_addresses(LogicalType::POINTER); // Use the HT to eliminate duplicate rows idx_t new_group_count = state.ht->FindOrCreateGroups(chunk, dummy_addresses, state.new_groups); // we only return entries we have not seen before (i.e. new groups) chunk.Slice(state.new_groups, new_group_count); return new_group_count; } SinkResultType PhysicalRecursiveCTE::Sink(ExecutionContext &context, GlobalSinkState &state, LocalSinkState &lstate, DataChunk &input) const { auto &gstate = (RecursiveCTEState &)state; if (!union_all) { idx_t match_count = ProbeHT(input, gstate); if (match_count > 0) { gstate.intermediate_table.Append(input); } } else { gstate.intermediate_table.Append(input); } return SinkResultType::NEED_MORE_INPUT; } //===--------------------------------------------------------------------===// // Source //===--------------------------------------------------------------------===// void PhysicalRecursiveCTE::GetData(ExecutionContext &context, DataChunk &chunk, GlobalSourceState &gstate_p, LocalSourceState &lstate) const { auto &gstate = (RecursiveCTEState &)*sink_state; while (chunk.size() == 0) { if (gstate.chunk_idx < gstate.intermediate_table.ChunkCount()) { // scan any chunks we have collected so far chunk.Reference(gstate.intermediate_table.GetChunk(gstate.chunk_idx)); gstate.chunk_idx++; break; } else { // we have run out of chunks // now we need to recurse // we set up the working table as the data we gathered in this iteration of the recursion working_table->Reset(); working_table->Merge(gstate.intermediate_table); // and we clear the intermediate table gstate.intermediate_table.Reset(); gstate.chunk_idx = 0; // now we need to re-execute all of the pipelines that depend on the recursion ExecuteRecursivePipelines(context); // check if we obtained any results // if not, we are done if (gstate.intermediate_table.Count() == 0) { break; } } } } void PhysicalRecursiveCTE::ExecuteRecursivePipelines(ExecutionContext &context) const { if (pipelines.empty()) { throw InternalException("Missing pipelines for recursive CTE"); } for (auto &pipeline : pipelines) { auto sink = pipeline->GetSink(); if (sink != this) { // reset the sink state for any intermediate sinks sink->sink_state = sink->GetGlobalSinkState(context.client); } for (auto &op : pipeline->GetOperators()) { if (op) { op->op_state = op->GetGlobalOperatorState(context.client); } } pipeline->Reset(); } auto &executor = pipelines[0]->executor; vector<shared_ptr<Event>> events; executor.ReschedulePipelines(pipelines, events); while (true) { executor.WorkOnTasks(); if (executor.HasError()) { executor.ThrowException(); } bool finished = true; for (auto &event : events) { if (!event->IsFinished()) { finished = false; break; } } if (finished) { // all pipelines finished: done! break; } } } } // namespace duckdb
4,989
1,679
class MedicalLarge { name = $STR_ZECCUP_MedicalLarge; // EAST class Hospital_CUP_O_TK { name = $STR_ZECCUP_MilitaryDesert_MedicalLarge_Hospital_CUP_O_TK; // Credit: 2600K icon = "\ca\data\flag_rus_co.paa"; side = 8; class Object0 {side = 8; vehicle = "TK_WarfareBFieldhHospital_Base_EP1"; rank = ""; position[] = {0.195923,-5.93896,0}; dir = 210;}; class Object1 {side = 8; vehicle = "Land_CamoNetVar_EAST_EP1"; rank = ""; position[] = {-11.6127,-2.72363,0}; dir = 90;}; class Object2 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {-15.3256,-8.50635,0}; dir = 270;}; class Object3 {side = 8; vehicle = "Land_fort_bagfence_corner"; rank = ""; position[] = {-6.59546,-8.46338,0}; dir = 270;}; class Object4 {side = 8; vehicle = "Land_HBarrier3"; rank = ""; position[] = {-15.5317,-9.78564,0}; dir = 0;}; class Object5 {side = 8; vehicle = "Land_HBarrier3"; rank = ""; position[] = {-9.46423,-11.7817,0}; dir = 270;}; class Object7 {side = 8; vehicle = "FoldTable"; rank = ""; position[] = {-9.75,-3.375,0}; dir = 30;}; class Object8 {side = 8; vehicle = "Land_WaterBarrel_F"; rank = ""; position[] = {-4.96875,-8.81641,0}; dir = 112.818;}; class Object9 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-10.4955,-3.6665,0}; dir = 240;}; class Object10 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-9.75452,-4.38281,0}; dir = 315;}; class Object11 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-9.93164,-2.69141,0}; dir = 15;}; class Object12 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-9.00452,-3.0835,0}; dir = 45;}; class Object13 {side = 8; vehicle = "Body"; rank = ""; position[] = {-0.707642,-3.521,0}; dir = 315;}; // Z: 0.0999999 class Object14 {side = 8; vehicle = "Barrel4"; rank = ""; position[] = {-13.25,-8.625,0}; dir = 0;}; class Object15 {side = 8; vehicle = "Barrel4"; rank = ""; position[] = {-13.9216,-7.93555,0}; dir = 0;}; class Object16 {side = 8; vehicle = "Barrel4"; rank = ""; position[] = {-14.0197,-8.65381,0}; dir = 105;}; class Object17 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {-15.3256,0.368652,0}; dir = 270;}; class Object18 {side = 8; vehicle = "Land_fort_bagfence_corner"; rank = ""; position[] = {-2.52954,8.83838,0}; dir = 90;}; class Object19 {side = 8; vehicle = "Land_fort_bagfence_long"; rank = ""; position[] = {-13.3904,6.23584,0}; dir = 0;}; class Object20 {side = 8; vehicle = "Land_fort_bagfence_long"; rank = ""; position[] = {-5.14038,6.36084,0}; dir = 0;}; class Object21 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {-7.11633,6.49658,0}; dir = 0;}; class Object22 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {-3.11633,6.37158,0}; dir = 0;}; class Object23 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {-11.3663,6.37158,0}; dir = 0;}; class Object24 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {-15.2413,6.12158,0}; dir = 0;}; class Object25 {side = 8; vehicle = "Land_FieldToilet_F"; rank = ""; position[] = {-3.375,4.25,0}; dir = 345.002;}; class Object26 {side = 8; vehicle = "AmmoCrates_NoInteractive_Small"; rank = ""; position[] = {-13.8955,1.35156,0}; dir = 90;}; class Object27 {side = 8; vehicle = "FoldTable"; rank = ""; position[] = {-9.29749,2.15967,0}; dir = 120;}; class Object28 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-10.3053,2.16406,0}; dir = 45;}; class Object29 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-9.00635,1.41406,0}; dir = 135;}; class Object30 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-9.58862,2.90527,0}; dir = 330;}; class Object31 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-8.61414,2.34131,0}; dir = 105;}; class Object32 {side = 8; vehicle = "MetalBarrel_burning_F"; rank = ""; position[] = {-3.75,2.375,0}; dir = 105;}; class Object33 {side = 8; vehicle = "Land_Pallets_F"; rank = ""; position[] = {-4.00256,14.0288,0}; dir = 90;}; class Object34 {side = 8; vehicle = "Land_Pallet_F"; rank = ""; position[] = {-2.61108,15.373,0}; dir = 192.542;}; class Object35 {side = 8; vehicle = "Land_fort_rampart_EP1"; rank = ""; position[] = {8.69763,-11.3872,0}; dir = 300;}; class Object36 {side = 8; vehicle = "Barrel4"; rank = ""; position[] = {8.96472,-9.39063,0}; dir = 330;}; class Object37 {side = 8; vehicle = "Barrel4"; rank = ""; position[] = {8.22583,-9.4541,0}; dir = 330;}; class Object38 {side = 8; vehicle = "Barrel4"; rank = ""; position[] = {8.5,-10.125,0}; dir = 75;}; class Object39 {side = 8; vehicle = "Land_fort_artillery_nest_EP1"; rank = ""; position[] = {18.4866,6.375,0}; dir = 90;}; class Object40 {side = 8; vehicle = "TK_WarfareBFieldhHospital_Base_EP1"; rank = ""; position[] = {4.73523,6.29248,0}; dir = 180;}; class Object41 {side = 8; vehicle = "Land_CamoNetVar_EAST_EP1"; rank = ""; position[] = {14.1373,6.52637,0}; dir = 90;}; class Object42 {side = 8; vehicle = "Land_fort_rampart_EP1"; rank = ""; position[] = {6.125,12.6494,0}; dir = 180;}; class Object43 {side = 8; vehicle = "AmmoCrates_NoInteractive_Large"; rank = ""; position[] = {13.9001,11.2822,0}; dir = 300;}; class Object44 {side = 8; vehicle = "FoldTable"; rank = ""; position[] = {13.8027,7.09961,0}; dir = 330;}; class Object45 {side = 8; vehicle = "Land_WaterBarrel_F"; rank = ""; position[] = {16.8672,3.83154,0}; dir = 123.359;}; class Object46 {side = 8; vehicle = "Body"; rank = ""; position[] = {15.1174,2.87842,0}; dir = 150;}; class Object47 {side = 8; vehicle = "Body"; rank = ""; position[] = {12.2452,1.75684,0}; dir = 180;}; class Object48 {side = 8; vehicle = "Body"; rank = ""; position[] = {13.6187,2.13037,0}; dir = 165;}; class Object49 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {13.6823,6.30811,0}; dir = 180;}; class Object50 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {14.6732,6.5918,0}; dir = 255;}; class Object51 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {13.9232,7.89111,0}; dir = 345;}; class Object52 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {13.1201,7.28418,0}; dir = 315;}; class Object53 {side = 8; vehicle = "AmmoCrate_NoInteractive_"; rank = ""; position[] = {14.7791,11.0151,0}; dir = 300;}; class Object54 {side = 8; vehicle = "Land_Pallets_stack_F"; rank = ""; position[] = {17.2242,5.30664,0}; dir = 196.374;}; }; // WEST class Hospital_CUP_B_USMC { name = $STR_ZECCUP_MilitaryDesert_MedicalLarge_Hospital_CUP_B_USMC; // Credit: 2600K icon = "\ca\data\flag_usa_co.paa"; side = 8; class Object0 {side = 8; vehicle = "Land_CamoNetVar_NATO_EP1"; rank = ""; position[] = {-7.36267,-7.84863,0}; dir = 90;}; class Object1 {side = 8; vehicle = "Land_HBarrier_large"; rank = ""; position[] = {-1.0127,-13.3354,0}; dir = 0;}; class Object2 {side = 8; vehicle = "Land_HBarrier_large"; rank = ""; position[] = {-9.2627,-13.5854,0}; dir = 0;}; class Object3 {side = 8; vehicle = "Land_HBarrier3"; rank = ""; position[] = {-12.6608,-10.0933,0}; dir = 90;}; class Object4 {side = 8; vehicle = "AmmoCrates_NoInteractive_Large"; rank = ""; position[] = {-8.70935,-11.6304,0}; dir = 0;}; class Object5 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {-11.2512,-2.49072,0}; dir = 240;}; class Object6 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {-2.61743,-2.36914,0}; dir = 300;}; class Object7 {side = 8; vehicle = "Land_BagFence_Round_F"; rank = ""; position[] = {-12.2045,-3.12598,0}; dir = 135;}; class Object8 {side = 8; vehicle = "Land_BagFence_Long_F"; rank = ""; position[] = {-12.7654,-8.62891,0}; dir = 270;}; class Object9 {side = 8; vehicle = "Land_BagFence_Long_F"; rank = ""; position[] = {-12.7655,-5.75391,0}; dir = 270;}; class Object10 {side = 8; vehicle = "Land_CampingTable_F"; rank = ""; position[] = {-6.875,-4.125,0}; dir = 315.002;}; class Object11 {side = 8; vehicle = "Land_CampingTable_F"; rank = ""; position[] = {-6.12183,-8.74609,0}; dir = 59.392;}; class Object12 {side = 8; vehicle = "Land_CampingTable_F"; rank = ""; position[] = {-6.30188,-4.69873,0}; dir = 134.559;}; class Object13 {side = 8; vehicle = "Land_CampingTable_F"; rank = ""; position[] = {-6.82617,-9.15381,0}; dir = 240.001;}; class Object14 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-7.58191,-4.03955,0}; dir = 329.971;}; class Object15 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-6.34473,-5.36133,0}; dir = 119.98;}; class Object16 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-7.0918,-9.81445,0}; dir = 254.978;}; class Object17 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-5.49463,-8.96143,0}; dir = 44.9741;}; class Object18 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-7.50916,-8.9707,0}; dir = 239.966;}; class Object19 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-5.77698,-7.9707,0}; dir = 89.9435;}; class Object20 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-5.46082,-4.83203,0}; dir = 164.938;}; class Object21 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-6.875,-3.41797,0}; dir = 314.957;}; class Object22 {side = 8; vehicle = "AmmoCrates_NoInteractive_Small"; rank = ""; position[] = {-4.35156,-11.6455,0}; dir = 0;}; class Object23 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {-5.5,-11.875,0}; dir = 285.016;}; class Object24 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {-7.62488,-11.75,0}; dir = 194.982;}; class Object25 {side = 8; vehicle = "B_Slingload_01_Medevac_F"; rank = ""; position[] = {-6,8.25,0}; dir = 300;}; class Object27 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {1.7594,11.376,0}; dir = 330;}; class Object28 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {2.00574,12.7427,0}; dir = 30;}; class Object29 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {-1.36926,13.2573,0}; dir = 285;}; class Object30 {side = 8; vehicle = "Land_PaperBox_open_empty_F"; rank = ""; position[] = {-7.87537,6.875,0}; dir = 300;}; class Object31 {side = 8; vehicle = "Land_PaperBox_closed_F"; rank = ""; position[] = {-6.49158,5.36523,0}; dir = 150;}; class Object32 {side = 8; vehicle = "MetalBarrel_burning_F"; rank = ""; position[] = {-1.5,0.5,0}; dir = 315;}; class Object33 {side = 8; vehicle = "AmmoCrates_NoInteractive_Small"; rank = ""; position[] = {-8.02747,5.28076,0}; dir = 240;}; class Object34 {side = 8; vehicle = "Land_Pallets_stack_F"; rank = ""; position[] = {-6.125,11.125,0}; dir = 194.999;}; class Object35 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {4.11865,-13.0493,0}; dir = 6.83019e-006;}; class Object36 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {15.4506,-8.49365,0}; dir = 90;}; class Object37 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {14.2563,-12.9507,0}; dir = 180;}; class Object38 {side = 8; vehicle = "Body"; rank = ""; position[] = {6.8501,-7.96289,0}; dir = 90;}; // Z: 0.0908942 class Object39 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {11.375,-11.75,0}; dir = 285.016;}; class Object40 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {10.5001,-11.75,0}; dir = 194.982;}; class Object41 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {14.5,-14.125,0}; dir = 285.016;}; class Object42 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {13.6251,-14.125,0}; dir = 194.982;}; class Object43 {side = 8; vehicle = "US_WarfareBFieldhHospital_Base_EP1"; rank = ""; position[] = {8.77747,-0.0498047,0}; dir = 0;}; class Object44 {side = 8; vehicle = "Land_HBarrier_large"; rank = ""; position[] = {6.7373,12.0396,0}; dir = 0;}; class Object45 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {15.7006,7.75635,0}; dir = 90;}; class Object46 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {11.3687,12.3257,0}; dir = 6.83019e-006;}; class Object47 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {15.7006,2.13135,0}; dir = 90;}; class Object48 {side = 8; vehicle = "Land_HBarrier3"; rank = ""; position[] = {15.7142,11.0317,0}; dir = 90;}; class Object49 {side = 8; vehicle = "Land_ToiletBox_F"; rank = ""; position[] = {7.12146,9.70947,0}; dir = 30.0776;}; class Object50 {side = 8; vehicle = "Land_WaterTank_F"; rank = ""; position[] = {5.12585,10.2192,0}; dir = 0.0586366;}; class Object51 {side = 8; vehicle = "Land_Sacks_heap_F"; rank = ""; position[] = {14.25,11.125,0}; dir = 195;}; class Object52 {side = 8; vehicle = "Body"; rank = ""; position[] = {9.41858,4.82324,0}; dir = 90.0001;}; // Z: 0.0926261 class Object53 {side = 8; vehicle = "Body"; rank = ""; position[] = {2.86951,0.118652,0}; dir = 75;}; class Object54 {side = 8; vehicle = "Body"; rank = ""; position[] = {2.61707,1.49707,0}; dir = 105;}; class Object55 {side = 8; vehicle = "Land_MetalBarrel_empty_F"; rank = ""; position[] = {11.1964,10.918,0}; dir = 255;}; class Object56 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {10.3746,10.7339,0}; dir = 134.965;}; class Object57 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {11.0023,10.1938,0}; dir = 105.016;}; class Object58 {side = 8; vehicle = "Land_Sacks_heap_F"; rank = ""; position[] = {14.5,9.75,0}; dir = 270;}; }; }; class MedicalMedium { name = $STR_ZECCUP_MedicalMedium; }; class MedicalSmall { name = $STR_ZECCUP_MedicalSmall; };
13,904
6,827
#include <mud/core.h> #include <19_multi_viewport/19_multi_viewport.h> #include <03_materials/03_materials.h> using namespace mud; size_t viewport_mode(Widget& parent) { std::vector<size_t> num_viewer_vals = { 1, 2, 4 }; ui::label(parent, "num viewports : "); static uint32_t choice = 1; ui::radio_switch(parent, carray<cstring, 3>{ "1", "2", "4" }, choice); return num_viewer_vals[choice]; } void ex_19_multi_viewport(Shell& app, Widget& parent, Dockbar& dockbar) { static float time = 0.f; time += 0.01f; bool multiple_scene = false; static size_t num_viewers = 2; if(Widget* dock = ui::dockitem(dockbar, "Game", carray<uint16_t, 1>{ 1U })) num_viewers = viewport_mode(*dock); Widget& layout = ui::layout(parent); Widget& first_split = ui::board(layout); Widget* second_split = num_viewers > 2 ? &ui::board(layout) : nullptr; std::vector<Viewer*> viewers = {}; if(!multiple_scene) { static Scene scene = { app.m_gfx_system }; for(size_t i = 0; i < num_viewers; ++i) viewers.push_back(&ui::viewer(i >= 2 ? *second_split : first_split, scene)); } else { for(size_t i = 0; i < num_viewers; ++i) viewers.push_back(&ui::scene_viewer(i >= 2 ? *second_split : first_split)); } for(Viewer* viewer : viewers) { ui::orbit_controller(*viewer); Gnode& scene = viewer->m_scene->begin(); for(size_t x = 0; x < 11; ++x) for(size_t y = 0; y < 11; ++y) { vec3 angles = { time + x * 0.21f, 0.f, time + y * 0.37f }; vec3 pos = { -15.f + x * 3.f, 0, -15.f + y * 3.f }; float r = ncosf(time + float(x) * 0.21f); float b = nsinf(time + float(y) * 0.37f); float g = ncosf(time); Colour color = { r, g, b }; Gnode& gnode = gfx::node(scene, {}, pos, quat(angles), vec3(1)); gfx::shape(gnode, Cube(), Symbol(color, Colour::None)); } } } #ifdef _19_MULTI_VIEWPORT_EXE void pump(Shell& app) { shell_context(app.m_ui->begin(), app.m_editor); ex_19_multi_viewport(app, *app.m_editor.m_screen, *app.m_editor.m_dockbar); } int main(int argc, char *argv[]) { Shell app(MUD_RESOURCE_PATH, exec_path(argc, argv).c_str()); app.m_gfx_system.init_pipeline(pipeline_minimal); app.run(pump); } #endif
2,170
1,025
// Distributed under the MIT License. // See LICENSE.txt for details. /// \file /// Defines function for taking the determinant of a rank-2 tensor #pragma once #include "DataStructures/Tensor/Tensor.hpp" #include "Utilities/Gsl.hpp" namespace detail { template <typename Symm, typename Index, typename = std::nullptr_t> struct DeterminantImpl; template <typename Symm, typename Index> struct DeterminantImpl<Symm, Index, Requires<Index::dim == 1>> { template <typename T> static typename T::type apply(const T& tensor) noexcept { return get<0, 0>(tensor); } }; template <typename Symm, typename Index> struct DeterminantImpl<Symm, Index, Requires<Index::dim == 2>> { template <typename T> static typename T::type apply(const T& tensor) noexcept { const auto& t00 = get<0, 0>(tensor); const auto& t01 = get<0, 1>(tensor); const auto& t10 = get<1, 0>(tensor); const auto& t11 = get<1, 1>(tensor); return t00 * t11 - t01 * t10; } }; template <typename Index> struct DeterminantImpl<Symmetry<2, 1>, Index, Requires<Index::dim == 3>> { template <typename T> static typename T::type apply(const T& tensor) noexcept { const auto& t00 = get<0, 0>(tensor); const auto& t01 = get<0, 1>(tensor); const auto& t02 = get<0, 2>(tensor); const auto& t10 = get<1, 0>(tensor); const auto& t11 = get<1, 1>(tensor); const auto& t12 = get<1, 2>(tensor); const auto& t20 = get<2, 0>(tensor); const auto& t21 = get<2, 1>(tensor); const auto& t22 = get<2, 2>(tensor); return t00 * (t11 * t22 - t12 * t21) - t01 * (t10 * t22 - t12 * t20) + t02 * (t10 * t21 - t11 * t20); } }; template <typename Index> struct DeterminantImpl<Symmetry<1, 1>, Index, Requires<Index::dim == 3>> { template <typename T> static typename T::type apply(const T& tensor) noexcept { const auto& t00 = get<0, 0>(tensor); const auto& t01 = get<0, 1>(tensor); const auto& t02 = get<0, 2>(tensor); const auto& t11 = get<1, 1>(tensor); const auto& t12 = get<1, 2>(tensor); const auto& t22 = get<2, 2>(tensor); return t00 * (t11 * t22 - t12 * t12) - t01 * (t01 * t22 - t12 * t02) + t02 * (t01 * t12 - t11 * t02); } }; template <typename Index> struct DeterminantImpl<Symmetry<2, 1>, Index, Requires<Index::dim == 4>> { template <typename T> static typename T::type apply(const T& tensor) noexcept { const auto& t00 = get<0, 0>(tensor); const auto& t01 = get<0, 1>(tensor); const auto& t02 = get<0, 2>(tensor); const auto& t03 = get<0, 3>(tensor); const auto& t10 = get<1, 0>(tensor); const auto& t11 = get<1, 1>(tensor); const auto& t12 = get<1, 2>(tensor); const auto& t13 = get<1, 3>(tensor); const auto& t20 = get<2, 0>(tensor); const auto& t21 = get<2, 1>(tensor); const auto& t22 = get<2, 2>(tensor); const auto& t23 = get<2, 3>(tensor); const auto& t30 = get<3, 0>(tensor); const auto& t31 = get<3, 1>(tensor); const auto& t32 = get<3, 2>(tensor); const auto& t33 = get<3, 3>(tensor); const auto minor1 = t22 * t33 - t23 * t32; const auto minor2 = t21 * t33 - t23 * t31; const auto minor3 = t20 * t33 - t23 * t30; const auto minor4 = t21 * t32 - t22 * t31; const auto minor5 = t20 * t32 - t22 * t30; const auto minor6 = t20 * t31 - t21 * t30; return t00 * (t11 * minor1 - t12 * minor2 + t13 * minor4) - t01 * (t10 * minor1 - t12 * minor3 + t13 * minor5) + t02 * (t10 * minor2 - t11 * minor3 + t13 * minor6) - t03 * (t10 * minor4 - t11 * minor5 + t12 * minor6); } }; template <typename Index> struct DeterminantImpl<Symmetry<1, 1>, Index, Requires<Index::dim == 4>> { template <typename T> static typename T::type apply(const T& tensor) noexcept { const auto& t00 = get<0, 0>(tensor); const auto& t01 = get<0, 1>(tensor); const auto& t02 = get<0, 2>(tensor); const auto& t03 = get<0, 3>(tensor); const auto& t11 = get<1, 1>(tensor); const auto& t12 = get<1, 2>(tensor); const auto& t13 = get<1, 3>(tensor); const auto& t22 = get<2, 2>(tensor); const auto& t23 = get<2, 3>(tensor); const auto& t33 = get<3, 3>(tensor); const auto minor1 = t22 * t33 - t23 * t23; const auto minor2 = t12 * t33 - t23 * t13; const auto minor3 = t02 * t33 - t23 * t03; const auto minor4 = t12 * t23 - t22 * t13; const auto minor5 = t02 * t23 - t22 * t03; const auto minor6 = t02 * t13 - t12 * t03; return t00 * (t11 * minor1 - t12 * minor2 + t13 * minor4) - t01 * (t01 * minor1 - t12 * minor3 + t13 * minor5) + t02 * (t01 * minor2 - t11 * minor3 + t13 * minor6) - t03 * (t01 * minor4 - t11 * minor5 + t12 * minor6); } }; } // namespace detail /// @{ /*! * \ingroup TensorGroup * \brief Computes the determinant of a rank-2 Tensor `tensor`. * * \requires That `tensor` be a rank-2 Tensor, with both indices sharing the * same dimension and type. */ template <typename T, typename Symm, typename Index0, typename Index1> void determinant( const gsl::not_null<Scalar<T>*> det_tensor, const Tensor<T, Symm, index_list<Index0, Index1>>& tensor) noexcept { static_assert(Index0::dim == Index1::dim, "Cannot take the determinant of a Tensor whose Indices are not " "of the same dimensionality."); static_assert(Index0::index_type == Index1::index_type, "Taking the determinant of a mixed Spatial and Spacetime index " "Tensor is not allowed since it's not clear what that means."); get(*det_tensor) = detail::DeterminantImpl<Symm, Index0>::apply(tensor); } template <typename T, typename Symm, typename Index0, typename Index1> Scalar<T> determinant( const Tensor<T, Symm, index_list<Index0, Index1>>& tensor) noexcept { Scalar<T> result{}; determinant(make_not_null(&result), tensor); return result; } /// @}
5,922
2,383
#include <iostream> #include <string> #include "gtest/gtest.h" #include "sequential-search.h" #include "binary-search-tree.h" #include "red-black-tree.h" TEST (SEQUENTIAL, TEST_CASE_001) { BaseSearch *search = new SequentialSearch(); EXPECT_EQ(0, 0); } TEST (BINARY_SEARCH_TREE, TEST_CASE_001) { int search_target = 8; std::string tree_elements = ""; BinarySearchTree *bst_tree = new BinarySearchTree(); BSTNode *head = bst_tree->create_node(1); BSTNode *node1 = bst_tree->create_node(2); BSTNode *node2 = bst_tree->create_node(3); BSTNode *node3 = bst_tree->create_node(4); BSTNode *node4 = bst_tree->create_node(5); BSTNode *node5 = bst_tree->create_node(6); BSTNode *node6 = bst_tree->create_node(7); BSTNode *node7 = bst_tree->create_node(8); bst_tree->insert_node(head, node1); bst_tree->insert_node(head, node2); bst_tree->insert_node(head, node3); bst_tree->insert_node(head, node4); bst_tree->insert_node(head, node5); bst_tree->insert_node(head, node6); bst_tree->insert_node(head, node7); bst_tree->inorder_print_tree (&tree_elements, head); EXPECT_STREQ("1 2 3 4 5 6 7 8 ", tree_elements.c_str()); tree_elements = ""; bst_tree->remove_node(head, 2); bst_tree->remove_node(head, 4); bst_tree->remove_node(head, 7); bst_tree->inorder_print_tree (&tree_elements, head); EXPECT_STREQ("1 3 5 6 8 ", tree_elements.c_str()); // test search BSTNode *test_search = bst_tree->search_node(head, search_target); EXPECT_EQ(search_target, test_search->data); } TEST (REDBLACKTREE, TEST_CASE_001) { RedBlackTree *red_black_tree = new RedBlackTree(); red_black_tree->version_info(); EXPECT_EQ(0, 0); } int main (int argc, char *argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
1,861
764
#include "ws.h" #include "WL_DEF.H" ws_GBuffer ws_gbuffer; std::vector<ws_PointLight> ws_active_lights; GLuint ws_create_sphere() { GLuint handle; glGenBuffers(1, &handle); glBindBuffer(GL_ARRAY_BUFFER, handle); ws_Vector3 *pVertices = new ws_Vector3[WS_SPHERE_VERT_COUNT]; int hseg = 8; int vseg = 8; auto pVerts = pVertices; { auto cos_h = cosf(1.0f / (float)hseg * (float)M_PI); auto sin_h = sinf(1.0f / (float)hseg * (float)M_PI); for (int j = 1; j < hseg - 1; ++j) { auto cos_h_next = cosf((float)(j + 1) / (float)hseg * (float)M_PI); auto sin_h_next = sinf((float)(j + 1) / (float)hseg * (float)M_PI); auto cos_v = cosf(0.0f); auto sin_v = sinf(0.0f); for (int i = 0; i < vseg; ++i) { auto cos_v_next = cosf((float)(i + 1) / (float)vseg * 2.0f * (float)M_PI); auto sin_v_next = sinf((float)(i + 1) / (float)vseg * 2.0f * (float)M_PI); pVerts->x = cos_v * sin_h; pVerts->y = sin_v * sin_h; pVerts->z = cos_h; ++pVerts; pVerts->x = cos_v * sin_h_next; pVerts->y = sin_v * sin_h_next; pVerts->z = cos_h_next; ++pVerts; pVerts->x = cos_v_next * sin_h_next; pVerts->y = sin_v_next * sin_h_next; pVerts->z = cos_h_next; ++pVerts; pVerts->x = cos_v * sin_h; pVerts->y = sin_v * sin_h; pVerts->z = cos_h; ++pVerts; pVerts->x = cos_v_next * sin_h_next; pVerts->y = sin_v_next * sin_h_next; pVerts->z = cos_h_next; ++pVerts; pVerts->x = cos_v_next * sin_h; pVerts->y = sin_v_next * sin_h; pVerts->z = cos_h; ++pVerts; cos_v = cos_v_next; sin_v = sin_v_next; } cos_h = cos_h_next; sin_h = sin_h_next; } } // Caps { auto cos_h_next = cosf(1.0f / (float)hseg * (float)M_PI); auto sin_h_next = sinf(1.0f / (float)hseg * (float)M_PI); auto cos_v = cosf(0.0f); auto sin_v = sinf(0.0f); for (int i = 0; i < vseg; ++i) { auto cos_v_next = cosf((float)(i + 1) / (float)vseg * 2.0f * (float)M_PI); auto sin_v_next = sinf((float)(i + 1) / (float)vseg * 2.0f * (float)M_PI); pVerts->x = 0.0f; pVerts->y = 0.0f; pVerts->z = 1.0f; ++pVerts; pVerts->x = cos_v * sin_h_next; pVerts->y = sin_v * sin_h_next; pVerts->z = cos_h_next; ++pVerts; pVerts->x = cos_v_next * sin_h_next; pVerts->y = sin_v_next * sin_h_next; pVerts->z = cos_h_next; ++pVerts; pVerts->x = 0.0f; pVerts->y = 0.0f; pVerts->z = -1.0f; ++pVerts; pVerts->x = cos_v_next * sin_h_next; pVerts->y = sin_v_next * sin_h_next; pVerts->z = -cos_h_next; ++pVerts; pVerts->x = cos_v * sin_h_next; pVerts->y = sin_v * sin_h_next; pVerts->z = -cos_h_next; ++pVerts; cos_v = cos_v_next; sin_v = sin_v_next; } } glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 3 * WS_SPHERE_VERT_COUNT, pVertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 3, (float *)(uintptr_t)(0)); delete[] pVertices; return handle; } ws_GBuffer ws_create_gbuffer(int w, int h) { ws_GBuffer gbuffer; glGenFramebuffers(1, &gbuffer.frameBuffer); glBindFramebuffer(GL_FRAMEBUFFER, gbuffer.frameBuffer); glActiveTexture(GL_TEXTURE0); // Albeo { glGenTextures(1, &gbuffer.albeoHandle); glBindTexture(GL_TEXTURE_2D, gbuffer.albeoHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, gbuffer.albeoHandle, 0); } // Normal { glGenTextures(1, &gbuffer.normalHandle); glBindTexture(GL_TEXTURE_2D, gbuffer.normalHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, gbuffer.normalHandle, 0); } // Depth { glGenTextures(1, &gbuffer.depthHandle); glBindTexture(GL_TEXTURE_2D, gbuffer.depthHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, gbuffer.depthHandle, 0); } // Attach the main depth buffer { glBindRenderbuffer(GL_RENDERBUFFER, ws_resources.mainRT.depth); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, w, h); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, ws_resources.mainRT.depth); } assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); return gbuffer; } void ws_resize_gbuffer(ws_GBuffer &gbuffer, int w, int h) { glBindFramebuffer(GL_FRAMEBUFFER, gbuffer.frameBuffer); glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, gbuffer.albeoHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glBindTexture(GL_TEXTURE_2D, gbuffer.normalHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glBindTexture(GL_TEXTURE_2D, gbuffer.depthHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); } void ws_draw_pointlight(const ws_PointLight& pointLight) { // Update uniforms static auto LightPosition_uniform = glGetUniformLocation(ws_resources.programPointlightP, "LightPosition"); static auto LightRadius_uniform = glGetUniformLocation(ws_resources.programPointlightP, "LightRadius"); static auto LightIntensity_uniform = glGetUniformLocation(ws_resources.programPointlightP, "LightIntensity"); static auto LightColor_uniform = glGetUniformLocation(ws_resources.programPointlightP, "LightColor"); ws_Vector3 lpos = {pointLight.position.x, pointLight.position.y, pointLight.position.z}; glUniform3fv(LightPosition_uniform, 1, &lpos.x); glUniform1f(LightRadius_uniform, pointLight.radius); glUniform1f(LightIntensity_uniform, pointLight.intensity); glUniform4fv(LightColor_uniform, 1, &pointLight.color.r); glDrawArrays(GL_TRIANGLES, 0, WS_SPHERE_VERT_COUNT); }
8,040
3,251
/* * Copyright 2020-2021 AVSystem <avsystem@avsystem.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <anjay/anjay.h> #include "./jni_wrapper.hpp" #include "./util_classes/accessor_base.hpp" #include "./util_classes/native_input_context_pointer.hpp" #include "./util_classes/objlnk.hpp" namespace details { template <typename T> struct InputCtx; template <> struct InputCtx<int32_t> { static constexpr auto Name() { return "com/avsystem/anjay/impl/NativeInputContext$IntegerContext"; } }; template <> struct InputCtx<int64_t> { static constexpr auto Name() { return "com/avsystem/anjay/impl/NativeInputContext$LongContext"; } }; template <> struct InputCtx<bool> { static constexpr auto Name() { return "com/avsystem/anjay/impl/NativeInputContext$BooleanContext"; } }; template <> struct InputCtx<float> { static constexpr auto Name() { return "com/avsystem/anjay/impl/NativeInputContext$FloatContext"; } }; template <> struct InputCtx<double> { static constexpr auto Name() { return "com/avsystem/anjay/impl/NativeInputContext$DoubleContext"; } }; template <> struct InputCtx<std::string> { static constexpr auto Name() { return "com/avsystem/anjay/impl/NativeInputContext$StringContext"; } }; template <> struct InputCtx<utils::Objlnk> { static constexpr auto Name() { return "com/avsystem/anjay/impl/NativeInputContext$ObjlnkContext"; } }; template <> struct InputCtx<uint8_t[]> { static constexpr auto Name() { return "com/avsystem/anjay/impl/NativeInputContext$BytesContext"; } }; } // namespace details class NativeInputContext { anjay_input_ctx_t *ctx_; template <typename T, typename Getter> int get_value(jni::JNIEnv &env, jni::Object<details::InputCtx<T>> &ctx, Getter &&getter) { T value; int result = getter(ctx_, &value); if (result) { return result; } auto accessor = utils::AccessorBase<details::InputCtx<T>>{ env, ctx }; accessor.template set_value<T>("value", value); return 0; } NativeInputContext(const NativeInputContext &) = delete; NativeInputContext &operator=(const NativeInputContext &) = delete; NativeInputContext(NativeInputContext &&) = delete; NativeInputContext &operator=(NativeInputContext &&) = delete; public: static constexpr auto Name() { return "com/avsystem/anjay/impl/NativeInputContext"; } static void register_native(jni::JNIEnv &env); NativeInputContext(jni::JNIEnv &env, jni::Object<utils::NativeInputContextPointer> &context); jni::jint get_i32(jni::JNIEnv &env, jni::Object<details::InputCtx<int32_t>> &ctx); jni::jint get_i64(jni::JNIEnv &env, jni::Object<details::InputCtx<int64_t>> &ctx); jni::jint get_bool(jni::JNIEnv &env, jni::Object<details::InputCtx<bool>> &ctx); jni::jint get_float(jni::JNIEnv &env, jni::Object<details::InputCtx<float>> &ctx); jni::jint get_double(jni::JNIEnv &env, jni::Object<details::InputCtx<double>> &ctx); jni::jint get_string(jni::JNIEnv &env, jni::Object<details::InputCtx<std::string>> &ctx); jni::jint get_objlnk(jni::JNIEnv &env, jni::Object<details::InputCtx<utils::Objlnk>> &ctx); jni::jint get_bytes(jni::JNIEnv &env, jni::Object<details::InputCtx<uint8_t[]>> &ctx); };
4,155
1,357
/*++ Copyright (c) 2006 Microsoft Corporation Module Name: proto_model.cpp Abstract: <abstract> Author: Leonardo de Moura (leonardo) 2007-03-08. Revision History: --*/ #include"proto_model.h" #include"model_params.hpp" #include"ast_pp.h" #include"ast_ll_pp.h" #include"var_subst.h" #include"array_decl_plugin.h" #include"well_sorted.h" #include"used_symbols.h" #include"model_v2_pp.h" proto_model::proto_model(ast_manager & m, params_ref const & p): model_core(m), m_afid(m.mk_family_id(symbol("array"))), m_eval(*this), m_rewrite(m) { register_factory(alloc(basic_factory, m)); m_user_sort_factory = alloc(user_sort_factory, m); register_factory(m_user_sort_factory); m_model_partial = model_params(p).partial(); } void proto_model::register_aux_decl(func_decl * d, func_interp * fi) { model_core::register_decl(d, fi); m_aux_decls.insert(d); } /** \brief Set new_fi as the new interpretation for f. If f_aux != 0, then assign the old interpretation of f to f_aux. If f_aux == 0, then delete the old interpretation of f. f_aux is marked as a auxiliary declaration. */ void proto_model::reregister_decl(func_decl * f, func_interp * new_fi, func_decl * f_aux) { func_interp * fi = get_func_interp(f); if (fi == 0) { register_decl(f, new_fi); } else { if (f_aux != 0) { register_decl(f_aux, fi); m_aux_decls.insert(f_aux); } else { dealloc(fi); } m_finterp.insert(f, new_fi); } } expr * proto_model::mk_some_interp_for(func_decl * d) { SASSERT(!has_interpretation(d)); expr * r = get_some_value(d->get_range()); // if t is a function, then it will be the constant function. if (d->get_arity() == 0) { register_decl(d, r); } else { func_interp * new_fi = alloc(func_interp, m_manager, d->get_arity()); new_fi->set_else(r); register_decl(d, new_fi); } return r; } bool proto_model::is_select_of_model_value(expr* e) const { return is_app_of(e, m_afid, OP_SELECT) && is_as_array(to_app(e)->get_arg(0)) && has_interpretation(array_util(m_manager).get_as_array_func_decl(to_app(to_app(e)->get_arg(0)))); } bool proto_model::eval(expr * e, expr_ref & result, bool model_completion) { m_eval.set_model_completion(model_completion); try { m_eval(e, result); #if 0 std::cout << mk_pp(e, m_manager) << "\n===>\n" << result << "\n"; #endif return true; } catch (model_evaluator_exception & ex) { (void)ex; TRACE("model_evaluator", tout << ex.msg() << "\n";); return false; } } /** \brief Evaluate the expression e in the current model, and store the result in \c result. It returns \c true if succeeded, and false otherwise. If the evaluation fails, then r contains a term that is simplified as much as possible using the interpretations available in the model. When model_completion == true, if the model does not assign an interpretation to a declaration it will build one for it. Moreover, partial functions will also be completed. So, if model_completion == true, the evaluator never fails if it doesn't contain quantifiers. */ /** \brief Replace uninterpreted constants occurring in fi->get_else() by their interpretations. */ void proto_model::cleanup_func_interp(func_interp * fi, func_decl_set & found_aux_fs) { if (fi->is_partial()) return; expr * fi_else = fi->get_else(); TRACE("model_bug", tout << "cleaning up:\n" << mk_pp(fi_else, m_manager) << "\n";); obj_map<expr, expr*> cache; expr_ref_vector trail(m_manager); ptr_buffer<expr, 128> todo; ptr_buffer<expr> args; todo.push_back(fi_else); expr * a; while (!todo.empty()) { a = todo.back(); if (is_uninterp_const(a)) { todo.pop_back(); func_decl * a_decl = to_app(a)->get_decl(); expr * ai = get_const_interp(a_decl); if (ai == 0) { ai = get_some_value(a_decl->get_range()); register_decl(a_decl, ai); } cache.insert(a, ai); } else { switch(a->get_kind()) { case AST_APP: { app * t = to_app(a); bool visited = true; args.reset(); unsigned num_args = t->get_num_args(); for (unsigned i = 0; i < num_args; ++i) { expr * arg = 0; if (!cache.find(t->get_arg(i), arg)) { visited = false; todo.push_back(t->get_arg(i)); } else { args.push_back(arg); } } if (!visited) { continue; } func_decl * f = t->get_decl(); if (m_aux_decls.contains(f)) found_aux_fs.insert(f); expr_ref new_t(m_manager); new_t = m_rewrite.mk_app(f, num_args, args.c_ptr()); if (t != new_t.get()) trail.push_back(new_t); todo.pop_back(); cache.insert(t, new_t); break; } default: SASSERT(a != 0); cache.insert(a, a); todo.pop_back(); break; } } } if (!cache.find(fi_else, a)) { UNREACHABLE(); } fi->set_else(a); } void proto_model::remove_aux_decls_not_in_set(ptr_vector<func_decl> & decls, func_decl_set const & s) { unsigned sz = decls.size(); unsigned i = 0; unsigned j = 0; for (; i < sz; i++) { func_decl * f = decls[i]; if (!m_aux_decls.contains(f) || s.contains(f)) { decls[j] = f; j++; } } decls.shrink(j); } /** \brief Replace uninterpreted constants occurring in the func_interp's get_else() by their interpretations. */ void proto_model::cleanup() { func_decl_set found_aux_fs; decl2finterp::iterator it = m_finterp.begin(); decl2finterp::iterator end = m_finterp.end(); for (; it != end; ++it) { func_interp * fi = (*it).m_value; cleanup_func_interp(fi, found_aux_fs); } // remove auxiliary declarations that are not used. if (found_aux_fs.size() != m_aux_decls.size()) { remove_aux_decls_not_in_set(m_decls, found_aux_fs); remove_aux_decls_not_in_set(m_func_decls, found_aux_fs); func_decl_set::iterator it2 = m_aux_decls.begin(); func_decl_set::iterator end2 = m_aux_decls.end(); for (; it2 != end2; ++it2) { func_decl * faux = *it2; if (!found_aux_fs.contains(faux)) { TRACE("cleanup_bug", tout << "eliminating " << faux->get_name() << "\n";); func_interp * fi = 0; m_finterp.find(faux, fi); SASSERT(fi != 0); m_finterp.erase(faux); m_manager.dec_ref(faux); dealloc(fi); } } m_aux_decls.swap(found_aux_fs); } } value_factory * proto_model::get_factory(family_id fid) { return m_factories.get_plugin(fid); } void proto_model::freeze_universe(sort * s) { SASSERT(m_manager.is_uninterp(s)); m_user_sort_factory->freeze_universe(s); } /** \brief Return the known universe of an uninterpreted sort. */ obj_hashtable<expr> const & proto_model::get_known_universe(sort * s) const { return m_user_sort_factory->get_known_universe(s); } ptr_vector<expr> const & proto_model::get_universe(sort * s) const { ptr_vector<expr> & tmp = const_cast<proto_model*>(this)->m_tmp; tmp.reset(); obj_hashtable<expr> const & u = get_known_universe(s); obj_hashtable<expr>::iterator it = u.begin(); obj_hashtable<expr>::iterator end = u.end(); for (; it != end; ++it) tmp.push_back(*it); return tmp; } unsigned proto_model::get_num_uninterpreted_sorts() const { return m_user_sort_factory->get_num_sorts(); } sort * proto_model::get_uninterpreted_sort(unsigned idx) const { SASSERT(idx < get_num_uninterpreted_sorts()); return m_user_sort_factory->get_sort(idx); } /** \brief Return true if the given sort is uninterpreted and has a finite interpretation in the model. */ bool proto_model::is_finite(sort * s) const { return m_manager.is_uninterp(s) && m_user_sort_factory->is_finite(s); } expr * proto_model::get_some_value(sort * s) { if (m_manager.is_uninterp(s)) { return m_user_sort_factory->get_some_value(s); } else { family_id fid = s->get_family_id(); value_factory * f = get_factory(fid); if (f) return f->get_some_value(s); // there is no factory for the family id, then assume s is uninterpreted. return m_user_sort_factory->get_some_value(s); } } bool proto_model::get_some_values(sort * s, expr_ref & v1, expr_ref & v2) { if (m_manager.is_uninterp(s)) { return m_user_sort_factory->get_some_values(s, v1, v2); } else { family_id fid = s->get_family_id(); value_factory * f = get_factory(fid); if (f) return f->get_some_values(s, v1, v2); else return false; } } expr * proto_model::get_fresh_value(sort * s) { if (m_manager.is_uninterp(s)) { return m_user_sort_factory->get_fresh_value(s); } else { family_id fid = s->get_family_id(); value_factory * f = get_factory(fid); if (f) return f->get_fresh_value(s); else // Use user_sort_factory if the theory has no support for model construnction. // This is needed when dummy theories are used for arithmetic or arrays. return m_user_sort_factory->get_fresh_value(s); } } void proto_model::register_value(expr * n) { sort * s = m_manager.get_sort(n); if (m_manager.is_uninterp(s)) { m_user_sort_factory->register_value(n); } else { family_id fid = s->get_family_id(); value_factory * f = get_factory(fid); if (f) f->register_value(n); } } bool proto_model::is_as_array(expr * v) const { return is_app_of(v, m_afid, OP_AS_ARRAY); } void proto_model::compress() { ptr_vector<func_decl>::iterator it = m_func_decls.begin(); ptr_vector<func_decl>::iterator end = m_func_decls.end(); for (; it != end; ++it) { func_decl * f = *it; func_interp * fi = get_func_interp(f); SASSERT(fi != 0); fi->compress(); } } /** \brief Complete the interpretation fi of f if it is partial. If f does not have an interpretation in the given model, then this is a noop. */ void proto_model::complete_partial_func(func_decl * f) { func_interp * fi = get_func_interp(f); if (fi && fi->is_partial()) { expr * else_value = 0; #if 0 // For UFBV benchmarks, setting the "else" to false is not a good idea. // TODO: find a permanent solution. A possibility is to add another option. if (m_manager.is_bool(f->get_range())) { else_value = m_manager.mk_false(); } else { else_value = fi->get_max_occ_result(); if (else_value == 0) else_value = get_some_value(f->get_range()); } #else else_value = fi->get_max_occ_result(); if (else_value == 0) else_value = get_some_value(f->get_range()); #endif fi->set_else(else_value); } } /** \brief Set the (else) field of function interpretations... */ void proto_model::complete_partial_funcs() { if (m_model_partial) return; // m_func_decls may be "expanded" when we invoke get_some_value. // So, we must not use iterators to traverse it. for (unsigned i = 0; i < m_func_decls.size(); i++) { complete_partial_func(m_func_decls[i]); } } model * proto_model::mk_model() { TRACE("proto_model", tout << "mk_model\n"; model_v2_pp(tout, *this);); model * m = alloc(model, m_manager); decl2expr::iterator it1 = m_interp.begin(); decl2expr::iterator end1 = m_interp.end(); for (; it1 != end1; ++it1) { m->register_decl(it1->m_key, it1->m_value); } decl2finterp::iterator it2 = m_finterp.begin(); decl2finterp::iterator end2 = m_finterp.end(); for (; it2 != end2; ++it2) { m->register_decl(it2->m_key, it2->m_value); m_manager.dec_ref(it2->m_key); } m_finterp.reset(); // m took the ownership of the func_interp's unsigned sz = get_num_uninterpreted_sorts(); for (unsigned i = 0; i < sz; i++) { sort * s = get_uninterpreted_sort(i); TRACE("proto_model", tout << "copying uninterpreted sorts...\n" << mk_pp(s, m_manager) << "\n";); ptr_vector<expr> const& buf = get_universe(s); m->register_usort(s, buf.size(), buf.c_ptr()); } return m; } #if 0 #include"simplifier.h" #include"basic_simplifier_plugin.h" // Auxiliary function for computing fi(args[0], ..., args[fi.get_arity() - 1]). // The result is stored in result. // Return true if succeeded, and false otherwise. // It uses the simplifier s during the computation. bool eval(func_interp & fi, simplifier & s, expr * const * args, expr_ref & result) { bool actuals_are_values = true; if (fi.num_entries() != 0) { for (unsigned i = 0; actuals_are_values && i < fi.get_arity(); i++) { actuals_are_values = fi.m().is_value(args[i]); } } func_entry * entry = fi.get_entry(args); if (entry != 0) { result = entry->get_result(); return true; } TRACE("func_interp", tout << "failed to find entry for: "; for(unsigned i = 0; i < fi.get_arity(); i++) tout << mk_pp(args[i], fi.m()) << " "; tout << "\nis partial: " << fi.is_partial() << "\n";); if (!fi.eval_else(args, result)) { return false; } if (actuals_are_values && fi.args_are_values()) { // cheap case... we are done return true; } // build symbolic result... the actuals may be equal to the args of one of the entries. basic_simplifier_plugin * bs = static_cast<basic_simplifier_plugin*>(s.get_plugin(fi.m().get_basic_family_id())); for (unsigned k = 0; k < fi.num_entries(); k++) { func_entry const * curr = fi.get_entry(k); SASSERT(!curr->eq_args(fi.m(), fi.get_arity(), args)); if (!actuals_are_values || !curr->args_are_values()) { expr_ref_buffer eqs(fi.m()); unsigned i = fi.get_arity(); while (i > 0) { --i; expr_ref new_eq(fi.m()); bs->mk_eq(curr->get_arg(i), args[i], new_eq); eqs.push_back(new_eq); } SASSERT(eqs.size() == fi.get_arity()); expr_ref new_cond(fi.m()); bs->mk_and(eqs.size(), eqs.c_ptr(), new_cond); bs->mk_ite(new_cond, curr->get_result(), result, result); } } return true; } bool proto_model::eval(expr * e, expr_ref & result, bool model_completion) { bool is_ok = true; SASSERT(is_well_sorted(m_manager, e)); TRACE("model_eval", tout << mk_pp(e, m_manager) << "\n"; tout << "sort: " << mk_pp(m_manager.get_sort(e), m_manager) << "\n";); obj_map<expr, expr*> eval_cache; expr_ref_vector trail(m_manager); sbuffer<std::pair<expr*, expr*>, 128> todo; ptr_buffer<expr> args; expr * null = static_cast<expr*>(0); todo.push_back(std::make_pair(e, null)); simplifier m_simplifier(m_manager); expr * a; expr * expanded_a; while (!todo.empty()) { std::pair<expr *, expr *> & p = todo.back(); a = p.first; expanded_a = p.second; if (expanded_a != 0) { expr * r = 0; eval_cache.find(expanded_a, r); SASSERT(r != 0); todo.pop_back(); eval_cache.insert(a, r); TRACE("model_eval", tout << "orig:\n" << mk_pp(a, m_manager) << "\n"; tout << "after beta reduction:\n" << mk_pp(expanded_a, m_manager) << "\n"; tout << "new:\n" << mk_pp(r, m_manager) << "\n";); } else { switch(a->get_kind()) { case AST_APP: { app * t = to_app(a); bool visited = true; args.reset(); unsigned num_args = t->get_num_args(); for (unsigned i = 0; i < num_args; ++i) { expr * arg = 0; if (!eval_cache.find(t->get_arg(i), arg)) { visited = false; todo.push_back(std::make_pair(t->get_arg(i), null)); } else { args.push_back(arg); } } if (!visited) { continue; } SASSERT(args.size() == t->get_num_args()); expr_ref new_t(m_manager); func_decl * f = t->get_decl(); if (!has_interpretation(f)) { // the model does not assign an interpretation to f. SASSERT(new_t.get() == 0); if (f->get_family_id() == null_family_id) { if (model_completion) { // create an interpretation for f. new_t = mk_some_interp_for(f); } else { TRACE("model_eval", tout << f->get_name() << " is uninterpreted\n";); is_ok = false; } } if (new_t.get() == 0) { // t is interpreted or model completion is disabled. m_simplifier.mk_app(f, num_args, args.c_ptr(), new_t); TRACE("model_eval", tout << mk_pp(t, m_manager) << " -> " << new_t << "\n";); trail.push_back(new_t); if (!is_app(new_t) || to_app(new_t)->get_decl() != f || is_select_of_model_value(new_t)) { // if the result is not of the form (f ...), then assume we must simplify it. expr * new_new_t = 0; if (!eval_cache.find(new_t.get(), new_new_t)) { todo.back().second = new_t; todo.push_back(std::make_pair(new_t, null)); continue; } else { new_t = new_new_t; } } } } else { // the model has an interpretaion for f. if (num_args == 0) { // t is a constant new_t = get_const_interp(f); } else { // t is a function application SASSERT(new_t.get() == 0); // try to use function graph first func_interp * fi = get_func_interp(f); SASSERT(fi->get_arity() == num_args); expr_ref r1(m_manager); // fi may be partial... if (!::eval(*fi, m_simplifier, args.c_ptr(), r1)) { SASSERT(fi->is_partial()); // fi->eval only fails when fi is partial. if (model_completion) { expr * r = get_some_value(f->get_range()); fi->set_else(r); SASSERT(!fi->is_partial()); new_t = r; } else { // f is an uninterpreted function, there is no need to use m_simplifier.mk_app new_t = m_manager.mk_app(f, num_args, args.c_ptr()); trail.push_back(new_t); TRACE("model_eval", tout << f->get_name() << " is uninterpreted\n";); is_ok = false; } } else { SASSERT(r1); trail.push_back(r1); TRACE("model_eval", tout << mk_pp(a, m_manager) << "\nevaluates to: " << r1 << "\n";); expr * r2 = 0; if (!eval_cache.find(r1.get(), r2)) { todo.back().second = r1; todo.push_back(std::make_pair(r1, null)); continue; } else { new_t = r2; } } } } TRACE("model_eval", tout << "orig:\n" << mk_pp(t, m_manager) << "\n"; tout << "new:\n" << mk_pp(new_t, m_manager) << "\n";); todo.pop_back(); SASSERT(new_t.get() != 0); eval_cache.insert(t, new_t); break; } case AST_VAR: SASSERT(a != 0); eval_cache.insert(a, a); todo.pop_back(); break; case AST_QUANTIFIER: TRACE("model_eval", tout << "found quantifier\n" << mk_pp(a, m_manager) << "\n";); is_ok = false; // evaluator does not handle quantifiers. SASSERT(a != 0); eval_cache.insert(a, a); todo.pop_back(); break; default: UNREACHABLE(); break; } } } if (!eval_cache.find(e, a)) { TRACE("model_eval", tout << "FAILED e: " << mk_bounded_pp(e, m_manager) << "\n";); UNREACHABLE(); } result = a; std::cout << mk_pp(e, m_manager) << "\n===>\n" << result << "\n"; TRACE("model_eval", ast_ll_pp(tout << "original: ", m_manager, e); ast_ll_pp(tout << "evaluated: ", m_manager, a); ast_ll_pp(tout << "reduced: ", m_manager, result.get()); tout << "sort: " << mk_pp(m_manager.get_sort(e), m_manager) << "\n"; ); SASSERT(is_well_sorted(m_manager, result.get())); return is_ok; } #endif
23,026
7,571
// 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 "remoting/test/app_remoting_service_urls.h" #include "base/logging.h" #include "base/strings/stringprintf.h" namespace { // The placeholder is the environment endpoint qualifier. No trailing slash // is added as it will be appended as needed later. const char kAppRemotingTestEndpointBase[] = "https://www-googleapis-test.sandbox.google.com/appremoting/%s"; const char kAppRemotingDevEndpointQualifier[] = "v1beta1_dev"; // Placeholder value is for the Application ID. const char kRunApplicationApi[] = "applications/%s/run"; // First placeholder value is for the Application ID. Second placeholder is for // the Host ID to report the issue for. const char kReportIssueApi[] = "applications/%s/hosts/%s/reportIssue"; } // namespace namespace remoting { namespace test { bool IsSupportedServiceEnvironment(ServiceEnvironment service_environment) { return (service_environment >= 0 && service_environment < kUnknownEnvironment); } std::string GetBaseUrl(ServiceEnvironment service_environment) { std::string base_service_url; if (service_environment == kDeveloperEnvironment) { base_service_url = base::StringPrintf(kAppRemotingTestEndpointBase, kAppRemotingDevEndpointQualifier); } return base_service_url; } std::string GetRunApplicationUrl(const std::string& extension_id, ServiceEnvironment service_environment) { std::string service_url; if (!IsSupportedServiceEnvironment(service_environment)) { return service_url; } service_url = GetBaseUrl(service_environment); if (!service_url.empty()) { std::string api_string = base::StringPrintf(kRunApplicationApi, extension_id.c_str()); service_url = base::StringPrintf("%s/%s", service_url.c_str(), api_string.c_str()); } return service_url; } std::string GetReportIssueUrl(const std::string& extension_id, const std::string& host_id, ServiceEnvironment service_environment) { std::string service_url; if (!IsSupportedServiceEnvironment(service_environment)) { return service_url; } service_url = GetBaseUrl(service_environment); if (!service_url.empty()) { std::string api_string = base::StringPrintf( kReportIssueApi, extension_id.c_str(), host_id.c_str()); service_url = base::StringPrintf("%s/%s", service_url.c_str(), api_string.c_str()); } return service_url; } } // namespace test } // namespace remoting
2,703
786
// file: send_message.cpp // // LCM example program. // // compile with: // $ g++ -o send_message send_message.cpp -llcm // // On a system with pkg-config, you can also use: // $ g++ -o send_message send_message.cpp `pkg-config --cflags --libs lcm` #include <ctime> #include <lcm/lcm-cpp.hpp> #include <unistd.h> #include <iostream> #include "moos_double_t.hpp" int main(int argc, char ** argv) { lcm::LCM lcm; if(!lcm.good()) return 1; std::time_t result = std::time(NULL); moos_lcm_bridge_types::moos_double_t msg; msg.timestamp = (long) result; //msg_time; msg.value = 17; lcm.publish("NAV_HEADING", &msg); return 0; }
681
273
// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "cpuinfo_x86.h" #include <cassert> #include <cstdio> #include <map> #include <set> #if defined(CPU_FEATURES_OS_WINDOWS) #include <windows.h> // IsProcessorFeaturePresent #endif // CPU_FEATURES_OS_WINDOWS #include "filesystem_for_testing.h" #include "gtest/gtest.h" #include "internal/cpuid_x86.h" namespace cpu_features { class FakeCpu { public: Leaf GetCpuidLeaf(uint32_t leaf_id, int ecx) const { const auto itr = cpuid_leaves_.find(std::make_pair(leaf_id, ecx)); if (itr != cpuid_leaves_.end()) { return itr->second; } return {0, 0, 0, 0}; } uint32_t GetXCR0Eax() const { return xcr0_eax_; } void SetLeaves(std::map<std::pair<uint32_t, int>, Leaf> configuration) { cpuid_leaves_ = std::move(configuration); } void SetOsBackupsExtendedRegisters(bool os_backups_extended_registers) { xcr0_eax_ = os_backups_extended_registers ? -1 : 0; } #if defined(CPU_FEATURES_OS_DARWIN) bool GetDarwinSysCtlByName(std::string name) const { return darwin_sysctlbyname_.count(name); } void SetDarwinSysCtlByName(std::string name) { darwin_sysctlbyname_.insert(name); } #endif // CPU_FEATURES_OS_DARWIN #if defined(CPU_FEATURES_OS_WINDOWS) bool GetWindowsIsProcessorFeaturePresent(DWORD ProcessorFeature) { return windows_isprocessorfeaturepresent_.count(ProcessorFeature); } void SetWindowsIsProcessorFeaturePresent(DWORD ProcessorFeature) { windows_isprocessorfeaturepresent_.insert(ProcessorFeature); } #endif // CPU_FEATURES_OS_WINDOWS private: std::map<std::pair<uint32_t, int>, Leaf> cpuid_leaves_; #if defined(CPU_FEATURES_OS_DARWIN) std::set<std::string> darwin_sysctlbyname_; #endif // CPU_FEATURES_OS_DARWIN #if defined(CPU_FEATURES_OS_WINDOWS) std::set<DWORD> windows_isprocessorfeaturepresent_; #endif // CPU_FEATURES_OS_WINDOWS uint32_t xcr0_eax_; }; static FakeCpu* g_fake_cpu_instance = nullptr; static FakeCpu& cpu() { assert(g_fake_cpu_instance != nullptr); return *g_fake_cpu_instance; } extern "C" Leaf GetCpuidLeaf(uint32_t leaf_id, int ecx) { return cpu().GetCpuidLeaf(leaf_id, ecx); } extern "C" uint32_t GetXCR0Eax(void) { return cpu().GetXCR0Eax(); } #if defined(CPU_FEATURES_OS_DARWIN) extern "C" bool GetDarwinSysCtlByName(const char* name) { return cpu().GetDarwinSysCtlByName(name); } #endif // CPU_FEATURES_OS_DARWIN #if defined(CPU_FEATURES_OS_WINDOWS) extern "C" bool GetWindowsIsProcessorFeaturePresent(DWORD ProcessorFeature) { return cpu().GetWindowsIsProcessorFeaturePresent(ProcessorFeature); } #endif // CPU_FEATURES_OS_WINDOWS namespace { class CpuidX86Test : public ::testing::Test { protected: void SetUp() override { assert(g_fake_cpu_instance == nullptr); g_fake_cpu_instance = new FakeCpu(); } void TearDown() override { delete g_fake_cpu_instance; g_fake_cpu_instance = nullptr; } }; TEST_F(CpuidX86Test, SandyBridge) { cpu().SetOsBackupsExtendedRegisters(true); cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x0000000D, 0x756E6547, 0x6C65746E, 0x49656E69}}, {{0x00000001, 0}, Leaf{0x000206A6, 0x00100800, 0x1F9AE3BF, 0xBFEBFBFF}}, {{0x00000007, 0}, Leaf{0x00000000, 0x00000000, 0x00000000, 0x00000000}}, }); const auto info = GetX86Info(); EXPECT_STREQ(info.vendor, "GenuineIntel"); EXPECT_EQ(info.family, 0x06); EXPECT_EQ(info.model, 0x02A); EXPECT_EQ(info.stepping, 0x06); // Leaf 7 is zeroed out so none of the Leaf 7 flags are set. const auto features = info.features; EXPECT_FALSE(features.erms); EXPECT_FALSE(features.avx2); EXPECT_FALSE(features.avx512f); EXPECT_FALSE(features.avx512cd); EXPECT_FALSE(features.avx512er); EXPECT_FALSE(features.avx512pf); EXPECT_FALSE(features.avx512bw); EXPECT_FALSE(features.avx512dq); EXPECT_FALSE(features.avx512vl); EXPECT_FALSE(features.avx512ifma); EXPECT_FALSE(features.avx512vbmi); EXPECT_FALSE(features.avx512vbmi2); EXPECT_FALSE(features.avx512vnni); EXPECT_FALSE(features.avx512bitalg); EXPECT_FALSE(features.avx512vpopcntdq); EXPECT_FALSE(features.avx512_4vnniw); EXPECT_FALSE(features.avx512_4fmaps); // All old cpu features should be set. EXPECT_TRUE(features.aes); EXPECT_TRUE(features.ssse3); EXPECT_TRUE(features.sse4_1); EXPECT_TRUE(features.sse4_2); EXPECT_TRUE(features.avx); EXPECT_FALSE(features.sha); EXPECT_TRUE(features.popcnt); EXPECT_FALSE(features.movbe); EXPECT_FALSE(features.rdrnd); EXPECT_FALSE(features.adx); } const int UNDEF = -1; const int KiB = 1024; const int MiB = 1024 * KiB; TEST_F(CpuidX86Test, SandyBridgeTestOsSupport) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x0000000D, 0x756E6547, 0x6C65746E, 0x49656E69}}, {{0x00000001, 0}, Leaf{0x000206A6, 0x00100800, 0x1F9AE3BF, 0xBFEBFBFF}}, {{0x00000007, 0}, Leaf{0x00000000, 0x00000000, 0x00000000, 0x00000000}}, }); // avx is disabled if os does not support backing up ymm registers. cpu().SetOsBackupsExtendedRegisters(false); EXPECT_FALSE(GetX86Info().features.avx); // avx is disabled if os does not support backing up ymm registers. cpu().SetOsBackupsExtendedRegisters(true); EXPECT_TRUE(GetX86Info().features.avx); } TEST_F(CpuidX86Test, SkyLake) { cpu().SetOsBackupsExtendedRegisters(true); cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x00000016, 0x756E6547, 0x6C65746E, 0x49656E69}}, {{0x00000001, 0}, Leaf{0x000406E3, 0x00100800, 0x7FFAFBBF, 0xBFEBFBFF}}, {{0x00000007, 0}, Leaf{0x00000000, 0x029C67AF, 0x00000000, 0x00000000}}, }); const auto info = GetX86Info(); EXPECT_STREQ(info.vendor, "GenuineIntel"); EXPECT_EQ(info.family, 0x06); EXPECT_EQ(info.model, 0x04E); EXPECT_EQ(info.stepping, 0x03); EXPECT_EQ(GetX86Microarchitecture(&info), X86Microarchitecture::INTEL_SKL); } TEST_F(CpuidX86Test, Branding) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x00000016, 0x756E6547, 0x6C65746E, 0x49656E69}}, {{0x00000001, 0}, Leaf{0x000406E3, 0x00100800, 0x7FFAFBBF, 0xBFEBFBFF}}, {{0x00000007, 0}, Leaf{0x00000000, 0x029C67AF, 0x00000000, 0x00000000}}, {{0x80000000, 0}, Leaf{0x80000008, 0x00000000, 0x00000000, 0x00000000}}, {{0x80000001, 0}, Leaf{0x00000000, 0x00000000, 0x00000121, 0x2C100000}}, {{0x80000002, 0}, Leaf{0x65746E49, 0x2952286C, 0x726F4320, 0x4D542865}}, {{0x80000003, 0}, Leaf{0x37692029, 0x3035362D, 0x43205530, 0x40205550}}, {{0x80000004, 0}, Leaf{0x352E3220, 0x7A484730, 0x00000000, 0x00000000}}, }); char brand_string[49]; FillX86BrandString(brand_string); EXPECT_STREQ(brand_string, "Intel(R) Core(TM) i7-6500U CPU @ 2.50GHz"); } TEST_F(CpuidX86Test, KabyLakeCache) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x00000016, 0x756E6547, 0x6C65746E, 0x49656E69}}, {{0x00000001, 0}, Leaf{0x000406E3, 0x00100800, 0x7FFAFBBF, 0xBFEBFBFF}}, {{0x00000004, 0}, Leaf{0x1C004121, 0x01C0003F, 0x0000003F, 0x00000000}}, {{0x00000004, 1}, Leaf{0x1C004122, 0x01C0003F, 0x0000003F, 0x00000000}}, {{0x00000004, 2}, Leaf{0x1C004143, 0x00C0003F, 0x000003FF, 0x00000000}}, {{0x00000004, 3}, Leaf{0x1C03C163, 0x02C0003F, 0x00001FFF, 0x00000002}}, {{0x00000007, 0}, Leaf{0x00000000, 0x029C67AF, 0x00000000, 0x00000000}}, {{0x80000000, 0}, Leaf{0x80000008, 0x00000000, 0x00000000, 0x00000000}}, {{0x80000001, 0}, Leaf{0x00000000, 0x00000000, 0x00000121, 0x2C100000}}, {{0x80000002, 0}, Leaf{0x65746E49, 0x2952286C, 0x726F4320, 0x4D542865}}, {{0x80000003, 0}, Leaf{0x37692029, 0x3035362D, 0x43205530, 0x40205550}}, }); const auto info = GetX86CacheInfo(); EXPECT_EQ(info.size, 4); EXPECT_EQ(info.levels[0].level, 1); EXPECT_EQ(info.levels[0].cache_type, 1); EXPECT_EQ(info.levels[0].cache_size, 32 * KiB); EXPECT_EQ(info.levels[0].ways, 8); EXPECT_EQ(info.levels[0].line_size, 64); EXPECT_EQ(info.levels[0].tlb_entries, 64); EXPECT_EQ(info.levels[0].partitioning, 1); EXPECT_EQ(info.levels[1].level, 1); EXPECT_EQ(info.levels[1].cache_type, 2); EXPECT_EQ(info.levels[1].cache_size, 32 * KiB); EXPECT_EQ(info.levels[1].ways, 8); EXPECT_EQ(info.levels[1].line_size, 64); EXPECT_EQ(info.levels[1].tlb_entries, 64); EXPECT_EQ(info.levels[1].partitioning, 1); EXPECT_EQ(info.levels[2].level, 2); EXPECT_EQ(info.levels[2].cache_type, 3); EXPECT_EQ(info.levels[2].cache_size, 256 * KiB); EXPECT_EQ(info.levels[2].ways, 4); EXPECT_EQ(info.levels[2].line_size, 64); EXPECT_EQ(info.levels[2].tlb_entries, 1024); EXPECT_EQ(info.levels[2].partitioning, 1); EXPECT_EQ(info.levels[3].level, 3); EXPECT_EQ(info.levels[3].cache_type, 3); EXPECT_EQ(info.levels[3].cache_size, 6 * MiB); EXPECT_EQ(info.levels[3].ways, 12); EXPECT_EQ(info.levels[3].line_size, 64); EXPECT_EQ(info.levels[3].tlb_entries, 8192); EXPECT_EQ(info.levels[3].partitioning, 1); } TEST_F(CpuidX86Test, HSWCache) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x00000016, 0x756E6547, 0x6C65746E, 0x49656E69}}, {{0x00000001, 0}, Leaf{0x000406E3, 0x00100800, 0x7FFAFBBF, 0xBFEBFBFF}}, {{0x00000004, 0}, Leaf{0x1C004121, 0x01C0003F, 0x0000003F, 0x00000000}}, {{0x00000004, 1}, Leaf{0x1C004122, 0x01C0003F, 0x0000003F, 0x00000000}}, {{0x00000004, 2}, Leaf{0x1C004143, 0x01C0003F, 0x000001FF, 0x00000000}}, {{0x00000004, 3}, Leaf{0x1C03C163, 0x02C0003F, 0x00001FFF, 0x00000006}}, {{0x00000007, 0}, Leaf{0x00000000, 0x029C67AF, 0x00000000, 0x00000000}}, {{0x80000000, 0}, Leaf{0x80000008, 0x00000000, 0x00000000, 0x00000000}}, {{0x80000001, 0}, Leaf{0x00000000, 0x00000000, 0x00000121, 0x2C100000}}, {{0x80000002, 0}, Leaf{0x65746E49, 0x2952286C, 0x726F4320, 0x4D542865}}, {{0x80000003, 0}, Leaf{0x37692029, 0x3035362D, 0x43205530, 0x40205550}}, }); const auto info = GetX86CacheInfo(); EXPECT_EQ(info.size, 4); EXPECT_EQ(info.levels[0].level, 1); EXPECT_EQ(info.levels[0].cache_type, 1); EXPECT_EQ(info.levels[0].cache_size, 32 * KiB); EXPECT_EQ(info.levels[0].ways, 8); EXPECT_EQ(info.levels[0].line_size, 64); EXPECT_EQ(info.levels[0].tlb_entries, 64); EXPECT_EQ(info.levels[0].partitioning, 1); EXPECT_EQ(info.levels[1].level, 1); EXPECT_EQ(info.levels[1].cache_type, 2); EXPECT_EQ(info.levels[1].cache_size, 32 * KiB); EXPECT_EQ(info.levels[1].ways, 8); EXPECT_EQ(info.levels[1].line_size, 64); EXPECT_EQ(info.levels[1].tlb_entries, 64); EXPECT_EQ(info.levels[1].partitioning, 1); EXPECT_EQ(info.levels[2].level, 2); EXPECT_EQ(info.levels[2].cache_type, 3); EXPECT_EQ(info.levels[2].cache_size, 256 * KiB); EXPECT_EQ(info.levels[2].ways, 8); EXPECT_EQ(info.levels[2].line_size, 64); EXPECT_EQ(info.levels[2].tlb_entries, 512); EXPECT_EQ(info.levels[2].partitioning, 1); EXPECT_EQ(info.levels[3].level, 3); EXPECT_EQ(info.levels[3].cache_type, 3); EXPECT_EQ(info.levels[3].cache_size, 6 * MiB); EXPECT_EQ(info.levels[3].ways, 12); EXPECT_EQ(info.levels[3].line_size, 64); EXPECT_EQ(info.levels[3].tlb_entries, 8192); EXPECT_EQ(info.levels[3].partitioning, 1); } // http://users.atw.hu/instlatx64/AuthenticAMD/AuthenticAMD0200F30_K11_Griffin_CPUID.txt TEST_F(CpuidX86Test, AMD_K11_GRIFFIN) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x00000001, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x00000001, 0}, Leaf{0x00200F30, 0x00020800, 0x00002001, 0x178BFBFF}}, {{0x80000000, 0}, Leaf{0x8000001A, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x80000001, 0}, Leaf{0x00200F30, 0x20000000, 0x0000131F, 0xEBD3FBFF}}, }); const auto info = GetX86Info(); EXPECT_STREQ(info.vendor, "AuthenticAMD"); EXPECT_EQ(info.family, 0x11); EXPECT_EQ(info.model, 0x03); EXPECT_EQ(GetX86Microarchitecture(&info), X86Microarchitecture::AMD_K11); } // http://users.atw.hu/instlatx64/AuthenticAMD/AuthenticAMD0300F10_K12_Llano_CPUID.txt TEST_F(CpuidX86Test, AMD_K12_LLANO) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x00000006, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x00000001, 0}, Leaf{0x00300F10, 0x00040800, 0x00802009, 0x178BFBFF}}, {{0x80000000, 0}, Leaf{0x8000001B, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x80000001, 0}, Leaf{0x00300F10, 0x20002B31, 0x000037FF, 0xEFD3FBFF}}, }); const auto info = GetX86Info(); EXPECT_STREQ(info.vendor, "AuthenticAMD"); EXPECT_EQ(info.family, 0x12); EXPECT_EQ(info.model, 0x01); EXPECT_EQ(GetX86Microarchitecture(&info), X86Microarchitecture::AMD_K12); } // http://users.atw.hu/instlatx64/AuthenticAMD/AuthenticAMD0500F01_K14_Bobcat_CPUID.txt TEST_F(CpuidX86Test, AMD_K14_BOBCAT_AMD0500F01) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x00000006, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x00000001, 0}, Leaf{0x00500F01, 0x00020800, 0x00802209, 0x178BFBFF}}, {{0x80000000, 0}, Leaf{0x8000001B, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x80000001, 0}, Leaf{0x00500F01, 0x00000000, 0x000035FF, 0x2FD3FBFF}}, }); const auto info = GetX86Info(); EXPECT_STREQ(info.vendor, "AuthenticAMD"); EXPECT_EQ(info.family, 0x14); EXPECT_EQ(info.model, 0x00); EXPECT_EQ(GetX86Microarchitecture(&info), X86Microarchitecture::AMD_BOBCAT); } // http://users.atw.hu/instlatx64/AuthenticAMD/AuthenticAMD0500F10_K14_Bobcat_CPUID.txt TEST_F(CpuidX86Test, AMD_K14_BOBCAT_AMD0500F10) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x00000006, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x00000001, 0}, Leaf{0x00500F10, 0x00020800, 0x00802209, 0x178BFBFF}}, {{0x00000002, 0}, Leaf{0x00000000, 0x00000000, 0x00000000, 0x00000000}}, {{0x00000003, 0}, Leaf{0x00000000, 0x00000000, 0x00000000, 0x00000000}}, {{0x00000005, 0}, Leaf{0x00000040, 0x00000040, 0x00000003, 0x00000000}}, {{0x00000006, 0}, Leaf{0x00000000, 0x00000000, 0x00000001, 0x00000000}}, {{0x80000000, 0}, Leaf{0x8000001B, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x80000001, 0}, Leaf{0x00500F10, 0x00001242, 0x000035FF, 0x2FD3FBFF}}, {{0x80000002, 0}, Leaf{0x20444D41, 0x35332D45, 0x72502030, 0x7365636F}}, {{0x80000003, 0}, Leaf{0x00726F73, 0x00000000, 0x00000000, 0x00000000}}, {{0x80000004, 0}, Leaf{0x00000000, 0x00000000, 0x00000000, 0x00000000}}, {{0x80000005, 0}, Leaf{0xFF08FF08, 0xFF280000, 0x20080140, 0x20020140}}, }); const auto info = GetX86Info(); EXPECT_STREQ(info.vendor, "AuthenticAMD"); EXPECT_EQ(info.family, 0x14); EXPECT_EQ(info.model, 0x01); EXPECT_EQ(GetX86Microarchitecture(&info), X86Microarchitecture::AMD_BOBCAT); } // http://users.atw.hu/instlatx64/AuthenticAMD/AuthenticAMD0500F20_K14_Bobcat_CPUID.txt TEST_F(CpuidX86Test, AMD_K14_BOBCAT_AMD0500F20) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x00000006, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x00000001, 0}, Leaf{0x00500F20, 0x00020800, 0x00802209, 0x178BFBFF}}, {{0x80000000, 0}, Leaf{0x8000001B, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x80000001, 0}, Leaf{0x00500F20, 0x000012E9, 0x000035FF, 0x2FD3FBFF}}, }); const auto info = GetX86Info(); EXPECT_STREQ(info.vendor, "AuthenticAMD"); EXPECT_EQ(info.family, 0x14); EXPECT_EQ(info.model, 0x02); EXPECT_EQ(GetX86Microarchitecture(&info), X86Microarchitecture::AMD_BOBCAT); } // http://users.atw.hu/instlatx64/AuthenticAMD/AuthenticAMD0670F00_K15_StoneyRidge_CPUID.txt TEST_F(CpuidX86Test, AMD_K15_EXCAVATOR_STONEY_RIDGE) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x0000000D, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x00000001, 0}, Leaf{0x00670F00, 0x00020800, 0x7ED8320B, 0x178BFBFF}}, {{0x00000007, 0}, Leaf{0x00000000, 0x000001A9, 0x00000000, 0x00000000}}, {{0x80000000, 0}, Leaf{0x8000001E, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x80000001, 0}, Leaf{0x00670F00, 0x00000000, 0x2FABBFFF, 0x2FD3FBFF}}, {{0x80000002, 0}, Leaf{0x20444D41, 0x392D3941, 0x20303134, 0x45444152}}, {{0x80000003, 0}, Leaf{0x52204E4F, 0x35202C35, 0x4D4F4320, 0x45545550}}, {{0x80000004, 0}, Leaf{0x524F4320, 0x32205345, 0x47332B43, 0x00202020}}, }); const auto info = GetX86Info(); EXPECT_STREQ(info.vendor, "AuthenticAMD"); EXPECT_EQ(info.family, 0x15); EXPECT_EQ(info.model, 0x70); EXPECT_EQ(GetX86Microarchitecture(&info), X86Microarchitecture::AMD_EXCAVATOR); char brand_string[49]; FillX86BrandString(brand_string); EXPECT_STREQ(brand_string, "AMD A9-9410 RADEON R5, 5 COMPUTE CORES 2C+3G "); } // http://users.atw.hu/instlatx64/AuthenticAMD/AuthenticAMD0600F20_K15_AbuDhabi_CPUID0.txt TEST_F(CpuidX86Test, AMD_K15_PILEDRIVER_ABU_DHABI) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x0000000D, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x00000001, 0}, Leaf{0x00600F20, 0x00100800, 0x3E98320B, 0x178BFBFF}}, {{0x00000007, 0}, Leaf{0x00000000, 0x00000008, 0x00000000, 0x00000000}}, {{0x80000000, 0}, Leaf{0x8000001E, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x80000001, 0}, Leaf{0x00600F20, 0x30000000, 0x01EBBFFF, 0x2FD3FBFF}}, {{0x80000002, 0}, Leaf{0x20444D41, 0x6574704F, 0x286E6F72, 0x20296D74}}, {{0x80000003, 0}, Leaf{0x636F7250, 0x6F737365, 0x33362072, 0x20203637}}, {{0x80000004, 0}, Leaf{0x20202020, 0x20202020, 0x20202020, 0x00202020}}, }); const auto info = GetX86Info(); EXPECT_STREQ(info.vendor, "AuthenticAMD"); EXPECT_EQ(info.family, 0x15); EXPECT_EQ(info.model, 0x02); EXPECT_EQ(GetX86Microarchitecture(&info), X86Microarchitecture::AMD_PILEDRIVER); char brand_string[49]; FillX86BrandString(brand_string); EXPECT_STREQ(brand_string, "AMD Opteron(tm) Processor 6376 "); } // http://users.atw.hu/instlatx64/AuthenticAMD/AuthenticAMD0600F20_K15_AbuDhabi_CPUID0.txt TEST_F(CpuidX86Test, AMD_K15_PILEDRIVER_ABU_DHABI_CACHE_INFO) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x0000000D, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x00000001, 0}, Leaf{0x00600F20, 0x00100800, 0x3E98320B, 0x178BFBFF}}, {{0x80000000, 0}, Leaf{0x8000001E, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x80000001, 0}, Leaf{0x00600F20, 0x30000000, 0x01EBBFFF, 0x2FD3FBFF}}, {{0x8000001D, 0}, Leaf{0x00000121, 0x00C0003F, 0x0000003F, 0x00000000}}, {{0x8000001D, 1}, Leaf{0x00004122, 0x0040003F, 0x000001FF, 0x00000000}}, {{0x8000001D, 2}, Leaf{0x00004143, 0x03C0003F, 0x000007FF, 0x00000001}}, {{0x8000001D, 3}, Leaf{0x0001C163, 0x0BC0003F, 0x000007FF, 0x00000001}}, }); const auto info = GetX86CacheInfo(); EXPECT_EQ(info.size, 4); EXPECT_EQ(info.levels[0].level, 1); EXPECT_EQ(info.levels[0].cache_type, 1); EXPECT_EQ(info.levels[0].cache_size, 16 * KiB); EXPECT_EQ(info.levels[0].ways, 4); EXPECT_EQ(info.levels[0].line_size, 64); EXPECT_EQ(info.levels[0].tlb_entries, 64); EXPECT_EQ(info.levels[0].partitioning, 1); EXPECT_EQ(info.levels[1].level, 1); EXPECT_EQ(info.levels[1].cache_type, 2); EXPECT_EQ(info.levels[1].cache_size, 64 * KiB); EXPECT_EQ(info.levels[1].ways, 2); EXPECT_EQ(info.levels[1].line_size, 64); EXPECT_EQ(info.levels[1].tlb_entries, 512); EXPECT_EQ(info.levels[1].partitioning, 1); EXPECT_EQ(info.levels[2].level, 2); EXPECT_EQ(info.levels[2].cache_type, 3); EXPECT_EQ(info.levels[2].cache_size, 2 * MiB); EXPECT_EQ(info.levels[2].ways, 16); EXPECT_EQ(info.levels[2].line_size, 64); EXPECT_EQ(info.levels[2].tlb_entries, 2048); EXPECT_EQ(info.levels[2].partitioning, 1); EXPECT_EQ(info.levels[3].level, 3); EXPECT_EQ(info.levels[3].cache_type, 3); EXPECT_EQ(info.levels[3].cache_size, 6 * MiB); EXPECT_EQ(info.levels[3].ways, 48); EXPECT_EQ(info.levels[3].line_size, 64); EXPECT_EQ(info.levels[3].tlb_entries, 2048); EXPECT_EQ(info.levels[3].partitioning, 1); } // http://users.atw.hu/instlatx64/AuthenticAMD/AuthenticAMD0600F12_K15_Interlagos_CPUID3.txt TEST_F(CpuidX86Test, AMD_K15_BULLDOZER_INTERLAGOS) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x0000000D, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x00000001, 0}, Leaf{0x00600F12, 0x000C0800, 0x1E98220B, 0x178BFBFF}}, {{0x00000007, 0}, Leaf{0x00000000, 0x00000000, 0x00000000, 0x00000000}}, {{0x80000000, 0}, Leaf{0x8000001E, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x80000001, 0}, Leaf{0x00600F12, 0x30000000, 0x01C9BFFF, 0x2FD3FBFF}}, {{0x80000002, 0}, Leaf{0x20444D41, 0x6574704F, 0x286E6F72, 0x20294D54}}, {{0x80000003, 0}, Leaf{0x636F7250, 0x6F737365, 0x32362072, 0x20203833}}, {{0x80000004, 0}, Leaf{0x20202020, 0x20202020, 0x20202020, 0x00202020}}, }); const auto info = GetX86Info(); EXPECT_STREQ(info.vendor, "AuthenticAMD"); EXPECT_EQ(info.family, 0x15); EXPECT_EQ(info.model, 0x01); EXPECT_EQ(GetX86Microarchitecture(&info), X86Microarchitecture::AMD_BULLDOZER); char brand_string[49]; FillX86BrandString(brand_string); EXPECT_STREQ(brand_string, "AMD Opteron(TM) Processor 6238 "); } // http://users.atw.hu/instlatx64/AuthenticAMD0630F81_K15_Godavari_CPUID.txt TEST_F(CpuidX86Test, AMD_K15_STREAMROLLER_GODAVARI) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x0000000D, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x00000001, 0}, Leaf{0x00630F81, 0x00040800, 0x3E98320B, 0x178BFBFF}}, {{0x00000007, 0}, Leaf{0x00000000, 0x00000000, 0x00000000, 0x00000000}}, {{0x80000000, 0}, Leaf{0x8000001E, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x80000001, 0}, Leaf{0x00630F81, 0x10000000, 0x0FEBBFFF, 0x2FD3FBFF}}, {{0x80000002, 0}, Leaf{0x20444D41, 0x372D3841, 0x4B303736, 0x64615220}}, {{0x80000003, 0}, Leaf{0x206E6F65, 0x202C3752, 0x43203031, 0x75706D6F}}, {{0x80000004, 0}, Leaf{0x43206574, 0x7365726F, 0x2B433420, 0x00204736}}, {{0x80000005, 0}, Leaf{0xFF40FF18, 0xFF40FF30, 0x10040140, 0x60030140}}, }); const auto info = GetX86Info(); EXPECT_STREQ(info.vendor, "AuthenticAMD"); EXPECT_EQ(info.family, 0x15); EXPECT_EQ(info.model, 0x38); EXPECT_EQ(info.stepping, 0x01); EXPECT_EQ(GetX86Microarchitecture(&info), X86Microarchitecture::AMD_STREAMROLLER); char brand_string[49]; FillX86BrandString(brand_string); EXPECT_STREQ(brand_string, "AMD A8-7670K Radeon R7, 10 Compute Cores 4C+6G "); } // http://users.atw.hu/instlatx64/AuthenticAMD/AuthenticAMD0700F01_K16_Kabini_CPUID.txt TEST_F(CpuidX86Test, AMD_K16_JAGUAR_KABINI) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x0000000D, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x00000001, 0}, Leaf{0x00700F01, 0x00040800, 0x3ED8220B, 0x178BFBFF}}, {{0x00000007, 0}, Leaf{0x00000000, 0x00000008, 0x00000000, 0x00000000}}, {{0x80000000, 0}, Leaf{0x8000001E, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x80000001, 0}, Leaf{0x00700F01, 0x00000000, 0x154037FF, 0x2FD3FBFF}}, {{0x80000002, 0}, Leaf{0x20444D41, 0x352D3441, 0x20303030, 0x20555041}}, {{0x80000003, 0}, Leaf{0x68746977, 0x64615220, 0x286E6F65, 0x20294D54}}, {{0x80000004, 0}, Leaf{0x47204448, 0x68706172, 0x20736369, 0x00202020}}, }); const auto info = GetX86Info(); EXPECT_STREQ(info.vendor, "AuthenticAMD"); EXPECT_EQ(info.family, 0x16); EXPECT_EQ(info.model, 0x00); EXPECT_EQ(GetX86Microarchitecture(&info), X86Microarchitecture::AMD_JAGUAR); char brand_string[49]; FillX86BrandString(brand_string); EXPECT_STREQ(brand_string, "AMD A4-5000 APU with Radeon(TM) HD Graphics "); } // http://users.atw.hu/instlatx64/AuthenticAMD/AuthenticAMD0730F01_K16_Beema_CPUID2.txt TEST_F(CpuidX86Test, AMD_K16_PUMA_BEEMA) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x0000000D, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x00000001, 0}, Leaf{0x00730F01, 0x00040800, 0x7ED8220B, 0x178BFBFF}}, {{0x00000007, 0}, Leaf{0x00000000, 0x00000008, 0x00000000, 0x00000000}}, {{0x80000000, 0}, Leaf{0x8000001E, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x80000001, 0}, Leaf{0x00730F01, 0x00000000, 0x1D4037FF, 0x2FD3FBFF}}, {{0x80000002, 0}, Leaf{0x20444D41, 0x362D3641, 0x20303133, 0x20555041}}, {{0x80000003, 0}, Leaf{0x68746977, 0x444D4120, 0x64615220, 0x206E6F65}}, {{0x80000004, 0}, Leaf{0x47203452, 0x68706172, 0x20736369, 0x00202020}}, }); const auto info = GetX86Info(); EXPECT_STREQ(info.vendor, "AuthenticAMD"); EXPECT_EQ(info.family, 0x16); EXPECT_EQ(info.model, 0x30); EXPECT_EQ(GetX86Microarchitecture(&info), X86Microarchitecture::AMD_PUMA); char brand_string[49]; FillX86BrandString(brand_string); EXPECT_STREQ(brand_string, "AMD A6-6310 APU with AMD Radeon R4 Graphics "); } // http://users.atw.hu/instlatx64/AuthenticAMD/AuthenticAMD0820F01_K17_Dali_CPUID.txt TEST_F(CpuidX86Test, AMD_K17_ZEN_DALI) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x0000000D, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x00000001, 0}, Leaf{0x00820F01, 0x00020800, 0x7ED8320B, 0x178BFBFF}}, {{0x00000007, 0}, Leaf{0x00000000, 0x209C01A9, 0x00000000, 0x00000000}}, {{0x80000000, 0}, Leaf{0x8000001F, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x80000001, 0}, Leaf{0x00820F01, 0x00000000, 0x35C233FF, 0x2FD3FBFF}}, {{0x80000002, 0}, Leaf{0x20444D41, 0x30323033, 0x69772065, 0x52206874}}, {{0x80000003, 0}, Leaf{0x6F656461, 0x7247206E, 0x69687061, 0x20207363}}, {{0x80000004, 0}, Leaf{0x20202020, 0x20202020, 0x20202020, 0x00202020}}, }); const auto info = GetX86Info(); EXPECT_STREQ(info.vendor, "AuthenticAMD"); EXPECT_EQ(info.family, 0x17); EXPECT_EQ(info.model, 0x20); EXPECT_EQ(GetX86Microarchitecture(&info), X86Microarchitecture::AMD_ZEN); char brand_string[49]; FillX86BrandString(brand_string); EXPECT_STREQ(brand_string, "AMD 3020e with Radeon Graphics "); } // http://users.atw.hu/instlatx64/AuthenticAMD/AuthenticAMD0800F82_K17_ZenP_CPUID.txt TEST_F(CpuidX86Test, AMD_K17_ZEN_PLUS_PINNACLE_RIDGE) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x0000000D, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x00000001, 0}, Leaf{0x00800F82, 0x00100800, 0x7ED8320B, 0x178BFBFF}}, {{0x00000007, 0}, Leaf{0x00000000, 0x209C01A9, 0x00000000, 0x00000000}}, {{0x80000000, 0}, Leaf{0x8000001F, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x80000001, 0}, Leaf{0x00800F82, 0x20000000, 0x35C233FF, 0x2FD3FBFF}}, {{0x80000002, 0}, Leaf{0x20444D41, 0x657A7952, 0x2037206E, 0x30303732}}, {{0x80000003, 0}, Leaf{0x69452058, 0x2D746867, 0x65726F43, 0x6F725020}}, {{0x80000004, 0}, Leaf{0x73736563, 0x2020726F, 0x20202020, 0x00202020}}, }); const auto info = GetX86Info(); EXPECT_STREQ(info.vendor, "AuthenticAMD"); EXPECT_EQ(info.family, 0x17); EXPECT_EQ(info.model, 0x08); EXPECT_EQ(GetX86Microarchitecture(&info), X86Microarchitecture::AMD_ZEN_PLUS); char brand_string[49]; FillX86BrandString(brand_string); EXPECT_STREQ(brand_string, "AMD Ryzen 7 2700X Eight-Core Processor "); } // http://users.atw.hu/instlatx64/AuthenticAMD/AuthenticAMD0840F70_K17_CPUID.txt TEST_F(CpuidX86Test, AMD_K17_ZEN2_XBOX_SERIES_X) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x00000010, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x00000001, 0}, Leaf{0x00840F70, 0x00100800, 0x7ED8320B, 0x178BFBFF}}, {{0x00000007, 0}, Leaf{0x00000000, 0x219C91A9, 0x00400004, 0x00000000}}, {{0x80000000, 0}, Leaf{0x80000020, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x80000001, 0}, Leaf{0x00840F70, 0x00000000, 0xF5C2B7FF, 0x2FD3FBFF}}, {{0x80000002, 0}, Leaf{0x20444D41, 0x30303734, 0x2D382053, 0x65726F43}}, {{0x80000003, 0}, Leaf{0x6F725020, 0x73736563, 0x4420726F, 0x746B7365}}, {{0x80000004, 0}, Leaf{0x4B20706F, 0x00007469, 0x00000000, 0x00000000}}, }); const auto info = GetX86Info(); EXPECT_STREQ(info.vendor, "AuthenticAMD"); EXPECT_EQ(info.family, 0x17); EXPECT_EQ(info.model, 0x47); EXPECT_EQ(GetX86Microarchitecture(&info), X86Microarchitecture::AMD_ZEN2); char brand_string[49]; FillX86BrandString(brand_string); EXPECT_STREQ(brand_string, "AMD 4700S 8-Core Processor Desktop Kit"); } // http://users.atw.hu/instlatx64/HygonGenuine/HygonGenuine0900F02_Hygon_CPUID3.txt TEST_F(CpuidX86Test, AMD_K18_ZEN_DHYANA) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x0000000D, 0x6F677948, 0x656E6975, 0x6E65476E}}, {{0x00000001, 0}, Leaf{0x00900F02, 0x00100800, 0x74D83209, 0x178BFBFF}}, {{0x00000007, 0}, Leaf{0x00000000, 0x009C01A9, 0x0040068C, 0x00000000}}, {{0x80000000, 0}, Leaf{0x8000001F, 0x6F677948, 0x656E6975, 0x6E65476E}}, {{0x80000001, 0}, Leaf{0x00900F02, 0x60000000, 0x35C233FF, 0x2FD3FBFF}}, {{0x80000002, 0}, Leaf{0x6F677948, 0x3843206E, 0x31332036, 0x20203538}}, {{0x80000003, 0}, Leaf{0x6F632D38, 0x50206572, 0x65636F72, 0x726F7373}}, {{0x80000004, 0}, Leaf{0x20202020, 0x20202020, 0x20202020, 0x00202020}}, }); const auto info = GetX86Info(); EXPECT_STREQ(info.vendor, "HygonGenuine"); EXPECT_EQ(info.family, 0x18); EXPECT_EQ(info.model, 0x00); EXPECT_EQ(GetX86Microarchitecture(&info), X86Microarchitecture::AMD_ZEN); char brand_string[49]; FillX86BrandString(brand_string); EXPECT_STREQ(brand_string, "Hygon C86 3185 8-core Processor "); } // http://users.atw.hu/instlatx64/HygonGenuine/HygonGenuine0900F02_Hygon_CPUID.txt TEST_F(CpuidX86Test, AMD_K18_ZEN_DHYANA_CACHE_INFO) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x0000000D, 0x6F677948, 0x656E6975, 0x6E65476E}}, {{0x00000001, 0}, Leaf{0x00900F02, 0x00100800, 0x74D83209, 0x178BFBFF}}, {{0x80000000, 0}, Leaf{0x8000001F, 0x6F677948, 0x656E6975, 0x6E65476E}}, {{0x80000001, 0}, Leaf{0x00900F02, 0x60000000, 0x35C233FF, 0x2FD3FBFF}}, {{0x8000001D, 0}, Leaf{0x00004121, 0x01C0003F, 0x0000003F, 0x00000000}}, {{0x8000001D, 1}, Leaf{0x00004122, 0x00C0003F, 0x000000FF, 0x00000000}}, {{0x8000001D, 2}, Leaf{0x00004143, 0x01C0003F, 0x000003FF, 0x00000002}}, {{0x8000001D, 3}, Leaf{0x0001C163, 0x03C0003F, 0x00001FFF, 0x00000001}}, }); const auto info = GetX86CacheInfo(); EXPECT_EQ(info.size, 4); EXPECT_EQ(info.levels[0].level, 1); EXPECT_EQ(info.levels[0].cache_type, 1); EXPECT_EQ(info.levels[0].cache_size, 32 * KiB); EXPECT_EQ(info.levels[0].ways, 8); EXPECT_EQ(info.levels[0].line_size, 64); EXPECT_EQ(info.levels[0].tlb_entries, 64); EXPECT_EQ(info.levels[0].partitioning, 1); EXPECT_EQ(info.levels[1].level, 1); EXPECT_EQ(info.levels[1].cache_type, 2); EXPECT_EQ(info.levels[1].cache_size, 64 * KiB); EXPECT_EQ(info.levels[1].ways, 4); EXPECT_EQ(info.levels[1].line_size, 64); EXPECT_EQ(info.levels[1].tlb_entries, 256); EXPECT_EQ(info.levels[1].partitioning, 1); EXPECT_EQ(info.levels[2].level, 2); EXPECT_EQ(info.levels[2].cache_type, 3); EXPECT_EQ(info.levels[2].cache_size, 512 * KiB); EXPECT_EQ(info.levels[2].ways, 8); EXPECT_EQ(info.levels[2].line_size, 64); EXPECT_EQ(info.levels[2].tlb_entries, 1024); EXPECT_EQ(info.levels[2].partitioning, 1); EXPECT_EQ(info.levels[3].level, 3); EXPECT_EQ(info.levels[3].cache_type, 3); EXPECT_EQ(info.levels[3].cache_size, 8 * MiB); EXPECT_EQ(info.levels[3].ways, 16); EXPECT_EQ(info.levels[3].line_size, 64); EXPECT_EQ(info.levels[3].tlb_entries, 8192); EXPECT_EQ(info.levels[3].partitioning, 1); } // http://users.atw.hu/instlatx64/AuthenticAMD/AuthenticAMD0A20F10_K19_Vermeer2_CPUID.txt TEST_F(CpuidX86Test, AMD_K19_ZEN3_VERMEER) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x00000010, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x00000001, 0}, Leaf{0x00A20F10, 0x01180800, 0x7ED8320B, 0x178BFBFF}}, {{0x00000007, 0}, Leaf{0x00000000, 0x219C97A9, 0x0040068C, 0x00000000}}, {{0x80000000, 0}, Leaf{0x80000023, 0x68747541, 0x444D4163, 0x69746E65}}, {{0x80000001, 0}, Leaf{0x00A20F10, 0x20000000, 0x75C237FF, 0x2FD3FBFF}}, {{0x80000002, 0}, Leaf{0x20444D41, 0x657A7952, 0x2039206E, 0x30303935}}, {{0x80000003, 0}, Leaf{0x32312058, 0x726F432D, 0x72502065, 0x7365636F}}, {{0x80000004, 0}, Leaf{0x20726F73, 0x20202020, 0x20202020, 0x00202020}}, }); const auto info = GetX86Info(); EXPECT_STREQ(info.vendor, "AuthenticAMD"); EXPECT_EQ(info.family, 0x19); EXPECT_EQ(info.model, 0x21); EXPECT_EQ(GetX86Microarchitecture(&info), X86Microarchitecture::AMD_ZEN3); char brand_string[49]; FillX86BrandString(brand_string); EXPECT_STREQ(brand_string, "AMD Ryzen 9 5900X 12-Core Processor "); } // https://github.com/InstLatx64/InstLatx64/blob/master/GenuineIntel/GenuineIntel00106A1_Nehalem_CPUID.txt TEST_F(CpuidX86Test, Nehalem) { // Pre AVX cpus don't have xsave cpu().SetOsBackupsExtendedRegisters(false); #if defined(CPU_FEATURES_OS_WINDOWS) cpu().SetWindowsIsProcessorFeaturePresent(PF_XMMI_INSTRUCTIONS_AVAILABLE); cpu().SetWindowsIsProcessorFeaturePresent(PF_XMMI64_INSTRUCTIONS_AVAILABLE); cpu().SetWindowsIsProcessorFeaturePresent(PF_SSE3_INSTRUCTIONS_AVAILABLE); #elif defined(CPU_FEATURES_OS_DARWIN) cpu().SetDarwinSysCtlByName("hw.optional.sse"); cpu().SetDarwinSysCtlByName("hw.optional.sse2"); cpu().SetDarwinSysCtlByName("hw.optional.sse3"); cpu().SetDarwinSysCtlByName("hw.optional.supplementalsse3"); cpu().SetDarwinSysCtlByName("hw.optional.sse4_1"); cpu().SetDarwinSysCtlByName("hw.optional.sse4_2"); #elif defined(CPU_FEATURES_OS_FREEBSD) auto& fs = GetEmptyFilesystem(); fs.CreateFile("/var/run/dmesg.boot", R"( ---<<BOOT>>--- Copyright (c) 1992-2020 The FreeBSD Project. FreeBSD is a registered trademark of The FreeBSD Foundation. Features=0x1783fbff<FPU,VME,DE,PSE,TSC,MSR,PAE,MCE,CX8,APIC,SEP,MTRR,PGE,MCA,CMOV,PAT,PSE36,MMX,FXSR,SSE,SSE2,HTT> Features2=0x5eda2203<SSE3,PCLMULQDQ,SSSE3,CX16,PCID,SSE4.1,SSE4.2,MOVBE,POPCNT,AESNI,XSAVE,OSXSAVE,RDRAND> real memory = 2147418112 (2047 MB) )"); #elif defined(CPU_FEATURES_OS_LINUX_OR_ANDROID) auto& fs = GetEmptyFilesystem(); fs.CreateFile("/proc/cpuinfo", R"(processor : flags : fpu mmx sse sse2 sse3 ssse3 sse4_1 sse4_2 )"); #endif cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x0000000B, 0x756E6547, 0x6C65746E, 0x49656E69}}, {{0x00000001, 0}, Leaf{0x000106A2, 0x00100800, 0x00BCE3BD, 0xBFEBFBFF}}, {{0x00000002, 0}, Leaf{0x55035A01, 0x00F0B0E3, 0x00000000, 0x09CA212C}}, {{0x00000003, 0}, Leaf{0x00000000, 0x00000000, 0x00000000, 0x00000000}}, {{0x00000004, 0}, Leaf{0x1C004121, 0x01C0003F, 0x0000003F, 0x00000000}}, {{0x00000004, 0}, Leaf{0x1C004122, 0x00C0003F, 0x0000007F, 0x00000000}}, {{0x00000004, 0}, Leaf{0x1C004143, 0x01C0003F, 0x000001FF, 0x00000000}}, {{0x00000004, 0}, Leaf{0x1C03C163, 0x03C0003F, 0x00000FFF, 0x00000002}}, {{0x00000005, 0}, Leaf{0x00000040, 0x00000040, 0x00000003, 0x00021120}}, {{0x00000006, 0}, Leaf{0x00000001, 0x00000002, 0x00000001, 0x00000000}}, {{0x00000007, 0}, Leaf{0x00000000, 0x00000000, 0x00000000, 0x00000000}}, {{0x00000008, 0}, Leaf{0x00000000, 0x00000000, 0x00000000, 0x00000000}}, {{0x00000009, 0}, Leaf{0x00000000, 0x00000000, 0x00000000, 0x00000000}}, {{0x0000000A, 0}, Leaf{0x07300403, 0x00000000, 0x00000000, 0x00000603}}, {{0x0000000B, 0}, Leaf{0x00000001, 0x00000001, 0x00000100, 0x00000000}}, {{0x0000000B, 0}, Leaf{0x00000004, 0x00000002, 0x00000201, 0x00000000}}, {{0x80000000, 0}, Leaf{0x80000008, 0x00000000, 0x00000000, 0x00000000}}, {{0x80000001, 0}, Leaf{0x00000000, 0x00000000, 0x00000001, 0x28100000}}, {{0x80000002, 0}, Leaf{0x756E6547, 0x20656E69, 0x65746E49, 0x2952286C}}, {{0x80000003, 0}, Leaf{0x55504320, 0x20202020, 0x20202020, 0x40202020}}, {{0x80000004, 0}, Leaf{0x30303020, 0x20402030, 0x37382E31, 0x007A4847}}, {{0x80000005, 0}, Leaf{0x00000000, 0x00000000, 0x00000000, 0x00000000}}, {{0x80000006, 0}, Leaf{0x00000000, 0x00000000, 0x01006040, 0x00000000}}, {{0x80000007, 0}, Leaf{0x00000000, 0x00000000, 0x00000000, 0x00000100}}, {{0x80000008, 0}, Leaf{0x00003028, 0x00000000, 0x00000000, 0x00000000}}, }); const auto info = GetX86Info(); EXPECT_STREQ(info.vendor, "GenuineIntel"); EXPECT_EQ(info.family, 0x06); EXPECT_EQ(info.model, 0x1A); EXPECT_EQ(info.stepping, 0x02); EXPECT_EQ(GetX86Microarchitecture(&info), X86Microarchitecture::INTEL_NHM); char brand_string[49]; FillX86BrandString(brand_string); EXPECT_STREQ(brand_string, "Genuine Intel(R) CPU @ 0000 @ 1.87GHz"); EXPECT_TRUE(info.features.sse); EXPECT_TRUE(info.features.sse2); EXPECT_TRUE(info.features.sse3); #if !defined(CPU_FEATURES_OS_WINDOWS) // Currently disabled on Windows as IsProcessorFeaturePresent do not support // feature detection > sse3. EXPECT_TRUE(info.features.ssse3); EXPECT_TRUE(info.features.sse4_1); EXPECT_TRUE(info.features.sse4_2); #endif // !defined(CPU_FEATURES_OS_WINDOWS) } // https://github.com/InstLatx64/InstLatx64/blob/master/GenuineIntel/GenuineIntel0030673_Silvermont3_CPUID.txt TEST_F(CpuidX86Test, Atom) { // Pre AVX cpus don't have xsave cpu().SetOsBackupsExtendedRegisters(false); #if defined(CPU_FEATURES_OS_WINDOWS) cpu().SetWindowsIsProcessorFeaturePresent(PF_XMMI_INSTRUCTIONS_AVAILABLE); cpu().SetWindowsIsProcessorFeaturePresent(PF_XMMI64_INSTRUCTIONS_AVAILABLE); cpu().SetWindowsIsProcessorFeaturePresent(PF_SSE3_INSTRUCTIONS_AVAILABLE); #elif defined(CPU_FEATURES_OS_DARWIN) cpu().SetDarwinSysCtlByName("hw.optional.sse"); cpu().SetDarwinSysCtlByName("hw.optional.sse2"); cpu().SetDarwinSysCtlByName("hw.optional.sse3"); cpu().SetDarwinSysCtlByName("hw.optional.supplementalsse3"); cpu().SetDarwinSysCtlByName("hw.optional.sse4_1"); cpu().SetDarwinSysCtlByName("hw.optional.sse4_2"); #elif defined(CPU_FEATURES_OS_FREEBSD) auto& fs = GetEmptyFilesystem(); fs.CreateFile("/var/run/dmesg.boot", R"( ---<<BOOT>>--- Copyright (c) 1992-2020 The FreeBSD Project. FreeBSD is a registered trademark of The FreeBSD Foundation. Features=0x1783fbff<FPU,VME,DE,PSE,TSC,MSR,PAE,MCE,CX8,APIC,SEP,MTRR,PGE,MCA,CMOV,PAT,PSE36,MMX,FXSR,SSE,SSE2,HTT> Features2=0x5eda2203<SSE3,PCLMULQDQ,SSSE3,CX16,PCID,SSE4.1,SSE4.2,MOVBE,POPCNT,AESNI,XSAVE,OSXSAVE,RDRAND> real memory = 2147418112 (2047 MB) )"); #elif defined(CPU_FEATURES_OS_LINUX_OR_ANDROID) auto& fs = GetEmptyFilesystem(); fs.CreateFile("/proc/cpuinfo", R"( flags : fpu mmx sse sse2 sse3 ssse3 sse4_1 sse4_2 )"); #endif cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x0000000B, 0x756E6547, 0x6C65746E, 0x49656E69}}, {{0x00000001, 0}, Leaf{0x00030673, 0x00100800, 0x41D8E3BF, 0xBFEBFBFF}}, {{0x00000002, 0}, Leaf{0x61B3A001, 0x0000FFC2, 0x00000000, 0x00000000}}, {{0x00000003, 0}, Leaf{0x00000000, 0x00000000, 0x00000000, 0x00000000}}, {{0x00000004, 0}, Leaf{0x1C000121, 0x0140003F, 0x0000003F, 0x00000001}}, {{0x00000004, 1}, Leaf{0x1C000122, 0x01C0003F, 0x0000003F, 0x00000001}}, {{0x00000004, 2}, Leaf{0x1C00C143, 0x03C0003F, 0x000003FF, 0x00000001}}, {{0x00000005, 0}, Leaf{0x00000040, 0x00000040, 0x00000003, 0x33000020}}, {{0x00000006, 0}, Leaf{0x00000005, 0x00000002, 0x00000009, 0x00000000}}, {{0x00000007, 0}, Leaf{0x00000000, 0x00002282, 0x00000000, 0x00000000}}, {{0x00000008, 0}, Leaf{0x00000000, 0x00000000, 0x00000000, 0x00000000}}, {{0x00000009, 0}, Leaf{0x00000000, 0x00000000, 0x00000000, 0x00000000}}, {{0x0000000A, 0}, Leaf{0x07280203, 0x00000000, 0x00000000, 0x00004503}}, {{0x0000000B, 0}, Leaf{0x00000001, 0x00000001, 0x00000100, 0x00000000}}, {{0x0000000B, 1}, Leaf{0x00000004, 0x00000004, 0x00000201, 0x00000000}}, {{0x80000000, 0}, Leaf{0x80000008, 0x00000000, 0x00000000, 0x00000000}}, {{0x80000001, 0}, Leaf{0x00000000, 0x00000000, 0x00000101, 0x28100000}}, {{0x80000002, 0}, Leaf{0x20202020, 0x6E492020, 0x286C6574, 0x43202952}}, {{0x80000003, 0}, Leaf{0x72656C65, 0x52286E6F, 0x50432029, 0x4A202055}}, {{0x80000004, 0}, Leaf{0x30303931, 0x20402020, 0x39392E31, 0x007A4847}}, {{0x80000005, 0}, Leaf{0x00000000, 0x00000000, 0x00000000, 0x00000000}}, {{0x80000006, 0}, Leaf{0x00000000, 0x00000000, 0x04008040, 0x00000000}}, {{0x80000007, 0}, Leaf{0x00000000, 0x00000000, 0x00000000, 0x00000100}}, {{0x80000008, 0}, Leaf{0x00003024, 0x00000000, 0x00000000, 0x00000000}}, }); const auto info = GetX86Info(); EXPECT_STREQ(info.vendor, "GenuineIntel"); EXPECT_EQ(info.family, 0x06); EXPECT_EQ(info.model, 0x37); EXPECT_EQ(info.stepping, 0x03); EXPECT_EQ(GetX86Microarchitecture(&info), X86Microarchitecture::INTEL_ATOM_SMT); char brand_string[49]; FillX86BrandString(brand_string); EXPECT_STREQ(brand_string, " Intel(R) Celeron(R) CPU J1900 @ 1.99GHz"); EXPECT_TRUE(info.features.sse); EXPECT_TRUE(info.features.sse2); EXPECT_TRUE(info.features.sse3); #if !defined(CPU_FEATURES_OS_WINDOWS) // Currently disabled on Windows as IsProcessorFeaturePresent do not support // feature detection > sse3. EXPECT_TRUE(info.features.ssse3); EXPECT_TRUE(info.features.sse4_1); EXPECT_TRUE(info.features.sse4_2); #endif // !defined(CPU_FEATURES_OS_WINDOWS) } // https://www.felixcloutier.com/x86/cpuid#example-3-1--example-of-cache-and-tlb-interpretation TEST_F(CpuidX86Test, P4_CacheInfo) { cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x00000002, 0x756E6547, 0x6C65746E, 0x49656E69}}, {{0x00000001, 0}, Leaf{0x00000F0A, 0x00010808, 0x00000000, 0x3FEBFBFF}}, {{0x00000002, 0}, Leaf{0x665B5001, 0x00000000, 0x00000000, 0x007A7000}}, }); const auto info = GetX86CacheInfo(); EXPECT_EQ(info.size, 5); EXPECT_EQ(info.levels[0].level, UNDEF); EXPECT_EQ(info.levels[0].cache_type, CPU_FEATURE_CACHE_TLB); EXPECT_EQ(info.levels[0].cache_size, 4 * KiB); EXPECT_EQ(info.levels[0].ways, UNDEF); EXPECT_EQ(info.levels[0].line_size, UNDEF); EXPECT_EQ(info.levels[0].tlb_entries, 64); EXPECT_EQ(info.levels[0].partitioning, 0); EXPECT_EQ(info.levels[1].level, UNDEF); EXPECT_EQ(info.levels[1].cache_type, CPU_FEATURE_CACHE_TLB); EXPECT_EQ(info.levels[1].cache_size, 4 * KiB); EXPECT_EQ(info.levels[1].ways, UNDEF); EXPECT_EQ(info.levels[1].line_size, UNDEF); EXPECT_EQ(info.levels[1].tlb_entries, 64); EXPECT_EQ(info.levels[1].partitioning, 0); EXPECT_EQ(info.levels[2].level, 1); EXPECT_EQ(info.levels[2].cache_type, CPU_FEATURE_CACHE_DATA); EXPECT_EQ(info.levels[2].cache_size, 8 * KiB); EXPECT_EQ(info.levels[2].ways, 4); EXPECT_EQ(info.levels[2].line_size, 64); EXPECT_EQ(info.levels[2].tlb_entries, UNDEF); EXPECT_EQ(info.levels[2].partitioning, 0); EXPECT_EQ(info.levels[3].level, 1); EXPECT_EQ(info.levels[3].cache_type, CPU_FEATURE_CACHE_INSTRUCTION); EXPECT_EQ(info.levels[3].cache_size, 12 * KiB); EXPECT_EQ(info.levels[3].ways, 8); EXPECT_EQ(info.levels[3].line_size, UNDEF); EXPECT_EQ(info.levels[3].tlb_entries, UNDEF); EXPECT_EQ(info.levels[3].partitioning, 0); EXPECT_EQ(info.levels[4].level, 2); EXPECT_EQ(info.levels[4].cache_type, CPU_FEATURE_CACHE_DATA); EXPECT_EQ(info.levels[4].cache_size, 256 * KiB); EXPECT_EQ(info.levels[4].ways, 8); EXPECT_EQ(info.levels[4].line_size, 64); EXPECT_EQ(info.levels[4].tlb_entries, UNDEF); EXPECT_EQ(info.levels[4].partitioning, 2); } // https://github.com/InstLatx64/InstLatx64/blob/master/GenuineIntel/GenuineIntel0000673_P3_KatmaiDP_CPUID.txt TEST_F(CpuidX86Test, P3) { // Pre AVX cpus don't have xsave cpu().SetOsBackupsExtendedRegisters(false); #if defined(CPU_FEATURES_OS_WINDOWS) cpu().SetWindowsIsProcessorFeaturePresent(PF_XMMI_INSTRUCTIONS_AVAILABLE); #elif defined(CPU_FEATURES_OS_DARWIN) cpu().SetDarwinSysCtlByName("hw.optional.sse"); #elif defined(CPU_FEATURES_OS_FREEBSD) auto& fs = GetEmptyFilesystem(); fs.CreateFile("/var/run/dmesg.boot", R"( ---<<BOOT>>--- Copyright (c) 1992-2020 The FreeBSD Project. FreeBSD is a registered trademark of The FreeBSD Foundation. Features=0x1783fbff<FPU,VME,DE,PSE,TSC,MSR,PAE,MCE,CX8,APIC,SEP,MTRR,PGE,MCA,CMOV,PAT,PSE36,MMX,FXSR,SSE> real memory = 2147418112 (2047 MB) )"); #elif defined(CPU_FEATURES_OS_LINUX_OR_ANDROID) auto& fs = GetEmptyFilesystem(); fs.CreateFile("/proc/cpuinfo", R"( flags : fpu mmx sse )"); #endif cpu().SetLeaves({ {{0x00000000, 0}, Leaf{0x00000003, 0x756E6547, 0x6C65746E, 0x49656E69}}, {{0x00000001, 0}, Leaf{0x00000673, 0x00000000, 0x00000000, 0x0387FBFF}}, {{0x00000002, 0}, Leaf{0x03020101, 0x00000000, 0x00000000, 0x0C040843}}, {{0x00000003, 0}, Leaf{0x00000000, 0x00000000, 0x4CECC782, 0x00006778}}, }); const auto info = GetX86Info(); EXPECT_STREQ(info.vendor, "GenuineIntel"); EXPECT_EQ(info.family, 0x06); EXPECT_EQ(info.model, 0x07); EXPECT_EQ(info.stepping, 0x03); EXPECT_EQ(GetX86Microarchitecture(&info), X86Microarchitecture::X86_UNKNOWN); char brand_string[49]; FillX86BrandString(brand_string); EXPECT_STREQ(brand_string, ""); EXPECT_TRUE(info.features.mmx); EXPECT_TRUE(info.features.sse); EXPECT_FALSE(info.features.sse2); EXPECT_FALSE(info.features.sse3); #if !defined(CPU_FEATURES_OS_WINDOWS) // Currently disabled on Windows as IsProcessorFeaturePresent do not support // feature detection > sse3. EXPECT_FALSE(info.features.ssse3); EXPECT_FALSE(info.features.sse4_1); EXPECT_FALSE(info.features.sse4_2); #endif // !defined(CPU_FEATURES_OS_WINDOWS) } // TODO(user): test what happens when xsave/osxsave are not present. // TODO(user): test what happens when xmm/ymm/zmm os support are not // present. } // namespace } // namespace cpu_features
45,964
28,216
/** * \copyright * Copyright (c) 2012-2017, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include "VectorMatrixAssembler.h" #include <cassert> #include "NumLib/DOF/DOFTableUtil.h" #include "MathLib/LinAlg/Eigen/EigenMapTools.h" #include "LocalAssemblerInterface.h" #include "CoupledSolutionsForStaggeredScheme.h" #include "Process.h" namespace ProcessLib { VectorMatrixAssembler::VectorMatrixAssembler( std::unique_ptr<AbstractJacobianAssembler>&& jacobian_assembler) : _jacobian_assembler(std::move(jacobian_assembler)) { } void VectorMatrixAssembler::preAssemble( const std::size_t mesh_item_id, LocalAssemblerInterface& local_assembler, const NumLib::LocalToGlobalIndexMap& dof_table, const double t, const GlobalVector& x) { auto const indices = NumLib::getIndices(mesh_item_id, dof_table); auto const local_x = x.get(indices); local_assembler.preAssemble(t, local_x); } void VectorMatrixAssembler::assemble( const std::size_t mesh_item_id, LocalAssemblerInterface& local_assembler, const NumLib::LocalToGlobalIndexMap& dof_table, const double t, const GlobalVector& x, GlobalMatrix& M, GlobalMatrix& K, GlobalVector& b, const CoupledSolutionsForStaggeredScheme* cpl_xs) { auto const indices = NumLib::getIndices(mesh_item_id, dof_table); _local_M_data.clear(); _local_K_data.clear(); _local_b_data.clear(); if (cpl_xs == nullptr) { auto const local_x = x.get(indices); local_assembler.assemble(t, local_x, _local_M_data, _local_K_data, _local_b_data); } else { auto local_coupled_xs0 = getPreviousLocalSolutions(*cpl_xs, indices); auto local_coupled_xs = getCurrentLocalSolutions(*cpl_xs, indices); ProcessLib::LocalCoupledSolutions local_coupled_solutions( cpl_xs->dt, cpl_xs->process_id, std::move(local_coupled_xs0), std::move(local_coupled_xs)); local_assembler.assembleWithCoupledTerm(t, _local_M_data, _local_K_data, _local_b_data, local_coupled_solutions); } auto const num_r_c = indices.size(); auto const r_c_indices = NumLib::LocalToGlobalIndexMap::RowColumnIndices(indices, indices); if (!_local_M_data.empty()) { auto const local_M = MathLib::toMatrix(_local_M_data, num_r_c, num_r_c); M.add(r_c_indices, local_M); } if (!_local_K_data.empty()) { auto const local_K = MathLib::toMatrix(_local_K_data, num_r_c, num_r_c); K.add(r_c_indices, local_K); } if (!_local_b_data.empty()) { assert(_local_b_data.size() == num_r_c); b.add(indices, _local_b_data); } } void VectorMatrixAssembler::assembleWithJacobian( std::size_t const mesh_item_id, LocalAssemblerInterface& local_assembler, NumLib::LocalToGlobalIndexMap const& dof_table, const double t, GlobalVector const& x, GlobalVector const& xdot, const double dxdot_dx, const double dx_dx, GlobalMatrix& M, GlobalMatrix& K, GlobalVector& b, GlobalMatrix& Jac, const CoupledSolutionsForStaggeredScheme* cpl_xs) { auto const indices = NumLib::getIndices(mesh_item_id, dof_table); auto const local_xdot = xdot.get(indices); _local_M_data.clear(); _local_K_data.clear(); _local_b_data.clear(); _local_Jac_data.clear(); if (cpl_xs == nullptr) { auto const local_x = x.get(indices); _jacobian_assembler->assembleWithJacobian( local_assembler, t, local_x, local_xdot, dxdot_dx, dx_dx, _local_M_data, _local_K_data, _local_b_data, _local_Jac_data); } else { auto local_coupled_xs0 = getPreviousLocalSolutions(*cpl_xs, indices); auto local_coupled_xs = getCurrentLocalSolutions(*cpl_xs, indices); ProcessLib::LocalCoupledSolutions local_coupled_solutions( cpl_xs->dt, cpl_xs->process_id, std::move(local_coupled_xs0), std::move(local_coupled_xs)); _jacobian_assembler->assembleWithJacobianAndCoupling( local_assembler, t, local_xdot, dxdot_dx, dx_dx, _local_M_data, _local_K_data, _local_b_data, _local_Jac_data, local_coupled_solutions); } auto const num_r_c = indices.size(); auto const r_c_indices = NumLib::LocalToGlobalIndexMap::RowColumnIndices(indices, indices); if (!_local_M_data.empty()) { auto const local_M = MathLib::toMatrix(_local_M_data, num_r_c, num_r_c); M.add(r_c_indices, local_M); } if (!_local_K_data.empty()) { auto const local_K = MathLib::toMatrix(_local_K_data, num_r_c, num_r_c); K.add(r_c_indices, local_K); } if (!_local_b_data.empty()) { assert(_local_b_data.size() == num_r_c); b.add(indices, _local_b_data); } if (!_local_Jac_data.empty()) { auto const local_Jac = MathLib::toMatrix(_local_Jac_data, num_r_c, num_r_c); Jac.add(r_c_indices, local_Jac); } else { OGS_FATAL( "No Jacobian has been assembled! This might be due to programming " "errors in the local assembler of the current process."); } } } // namespace ProcessLib
5,491
1,978
/** * Copyright (c) 2012 - 2014 TideSDK contributors * http://www.tidesdk.org * Includes modified sources under the Apache 2 License * Copyright (c) 2008 - 2012 Appcelerator Inc * Refer to LICENSE for details of distribution and use. **/ #include <tide/tide.h> #include "resultset_binding.h" #include <Poco/Data/MetaColumn.h> #include <Poco/DynamicAny.h> using Poco::Data::MetaColumn; namespace ti { ResultSetBinding::ResultSetBinding() : StaticBoundObject("Database.ResultSet"), eof(true) { // no results result set Bind(); } ResultSetBinding::ResultSetBinding(Poco::Data::RecordSet &r) : StaticBoundObject("ResultSet"), eof(false) { rs = new Poco::Data::RecordSet(r); Bind(); } void ResultSetBinding::Bind() { /** * @tiapi(method=True,name=Database.ResultSet.isValidRow,since=0.4) Checks whether you can call data extraction methods * @tiresult(for=Database.ResultSet.isValidRow,type=Boolean) true if the row is valid */ this->SetMethod("isValidRow",&ResultSetBinding::IsValidRow); /** * @tiapi(method=True,name=Database.ResultSet.next,since=0.4) Moves the pointer to the next row of the result set */ this->SetMethod("next",&ResultSetBinding::Next); /** * @tiapi(method=True,name=Database.ResultSet.close,since=0.4) Releases the state associated with the result set */ this->SetMethod("close",&ResultSetBinding::Close); /** * @tiapi(method=True,name=Database.ResultSet.fieldCount,since=0.4) Returns the number of fields of the result set * @tiresult(for=Database.ResultSet.fieldCount,type=Number) the number of fields of the result set */ this->SetMethod("fieldCount",&ResultSetBinding::FieldCount); /** * @tiapi(method=True,name=Database.ResultSet.rowCount,since=0.4) Returns the number of rows of the result set * @tiresult(for=Database.ResultSet.rowCount,type=Number) the number of the rows of the result set */ this->SetMethod("rowCount",&ResultSetBinding::RowCount); /** * @tiapi(method=True,name=Database.ResultSet.fieldName,since=0.4) Returns the name of the specified field in the current result set taken from the SQL statement which was executed * @tiarg(for=Database.ResultSet.fieldName,type=Number,name=fieldIndex) the zero-based index of the desired field * @tiresult(for=Database.ResultSet.fieldName,type=String) The name of the specified field */ this->SetMethod("fieldName",&ResultSetBinding::FieldName); /** * @tiapi(method=True,name=Database.ResultSet.field,since=0.4) Returns the contents of the specified field in the current row * @tiarg(for=Database.ResultSet.field,type=Number,name=fieldIndex) the zero-based index of the desired field * @tiresult(for=Database.ResultSet.field,type=Boolean|String|Number|Bytes) The content of the specified field in the current row */ this->SetMethod("field",&ResultSetBinding::Field); /** * @tiapi(method=True,name=Database.ResultSet.fieldByName,since=0.4) Returns the contents of the specified field in the current row using the name of the field as an identifier * @tiarg(for=Database.ResultSet.fieldByName,type=String,name=name) the name of the desired field * @tiresult(for=Database.ResultSet.fieldByName,type=Boolean|String|Number|Bytes) The content of the specified field in the current row */ this->SetMethod("fieldByName",&ResultSetBinding::FieldByName); } ResultSetBinding::~ResultSetBinding() { } void ResultSetBinding::IsValidRow(const ValueList& args, ValueRef result) { if (rs.isNull()) { result->SetBool(false); } else { result->SetBool(!eof); } } void ResultSetBinding::Next(const ValueList& args, ValueRef result) { if (!rs.isNull() && !eof) { eof = (rs->moveNext() == false); } } void ResultSetBinding::Close(const ValueList& args, ValueRef result) { if (!rs.isNull()) { rs = NULL; } } void ResultSetBinding::RowCount(const ValueList& args, ValueRef result) { if (rs.isNull()) { result->SetInt(0); } else { result->SetInt(rs->rowCount()); } } void ResultSetBinding::FieldCount(const ValueList& args, ValueRef result) { if (rs.isNull()) { result->SetInt(0); } else { result->SetInt(rs->columnCount()); } } void ResultSetBinding::FieldName(const ValueList& args, ValueRef result) { if (rs.isNull()) { result->SetNull(); } else { args.VerifyException("fieldName", "i"); const std::string &str = rs->columnName(args.at(0)->ToInt()); result->SetString(str.c_str()); } } void ResultSetBinding::Field(const ValueList& args, ValueRef result) { if (rs.isNull()) { result->SetNull(); } else { args.VerifyException("field", "i"); TransformValue(args.at(0)->ToInt(),result); } } void ResultSetBinding::FieldByName(const ValueList& args, ValueRef result) { result->SetNull(); if (!rs.isNull()) { args.VerifyException("fieldByName", "s"); std::string name = args.at(0)->ToString(); size_t count = rs->columnCount(); for (size_t i = 0; i<count; i++) { const std::string &str = rs->columnName(i); if (str == name) { TransformValue(i,result); break; } } } } void ResultSetBinding::TransformValue(size_t index, ValueRef result) { MetaColumn::ColumnDataType type = rs->columnType(index); Poco::DynamicAny value = rs->value(index); if (value.isEmpty()) { result->SetNull(); } else if (type == MetaColumn::FDT_STRING) { std::string str; value.convert(str); result->SetString(str); } else if (type == MetaColumn::FDT_BOOL) { bool v = false; value.convert(v); result->SetBool(v); } else if (type == MetaColumn::FDT_FLOAT || type == MetaColumn::FDT_DOUBLE) { float f = 0; value.convert(f); result->SetDouble(f); } else if (type == MetaColumn::FDT_BLOB || type == MetaColumn::FDT_UNKNOWN) { std::string str; value.convert(str); result->SetString(str); } else { // the rest of these are ints: // FDT_INT8, // FDT_UINT8, // FDT_INT16, // FDT_UINT16, // FDT_INT32, // FDT_UINT32, // FDT_INT64, // FDT_UINT64, int i; value.convert(i); result->SetInt(i); } } }
7,426
2,196
#include <CGAL/Simple_cartesian.h> #include <CGAL/Surface_mesh.h> #include <CGAL/Curves_on_surface_topology.h> #include <CGAL/Path_on_surface.h> #include <CGAL/squared_distance_3.h> #include <CGAL/draw_face_graph_with_paths.h> #include <fstream> using Mesh = CGAL::Surface_mesh<CGAL::Simple_cartesian<double>::Point_3>; using Path_on_surface = CGAL::Surface_mesh_topology::Path_on_surface<Mesh>; double cycle_length(const Mesh& mesh, const Path_on_surface& cycle) { // Compute the length of the given cycle. double res=0; for (std::size_t i=0; i<cycle.length(); ++i) { res+=std::sqrt (CGAL::squared_distance(mesh.point(mesh.vertex(mesh.edge(cycle[i]), 0)), mesh.point(mesh.vertex(mesh.edge(cycle[i]), 1)))); } return res; } void display_cycle_info(const Mesh& mesh, const Path_on_surface& cycle) { // Display information about the given cycle. if (cycle.is_empty()) { std::cout<<"Empty."<<std::endl; return; } std::cout<<"Root: "<<mesh.point(mesh.vertex(mesh.edge(cycle[0]), 0))<<"; " <<"Number of edges: "<<cycle.length()<<"; " <<"Length: "<<cycle_length(mesh, cycle)<<std::endl; } int main(int argc, char* argv[]) { std::string filename(argc==1?"data/3torus.off":argv[1]); bool draw=(argc<3?false:(std::string(argv[2])=="-draw")); Mesh sm; if(!CGAL::read_polygon_mesh(filename, sm)) { std::cout<<"Cannot read file '"<<filename<<"'. Exiting program"<<std::endl; return EXIT_FAILURE; } std::cout<<"File '"<<filename<<"' loaded. Finding edge-width of the mesh..."<<std::endl; CGAL::Surface_mesh_topology::Curves_on_surface_topology<Mesh> cst(sm, true); Path_on_surface cycle1=cst.compute_edge_width(true); CGAL::Surface_mesh_topology::Euclidean_length_weight_functor<Mesh> wf(sm); Path_on_surface cycle2=cst.compute_shortest_non_contractible_cycle(wf, true); std::cout<<"Cycle 1 (pink): "; display_cycle_info(sm, cycle1); std::cout<<"Cycle 2 (green): "; display_cycle_info(sm, cycle2); if (draw) { CGAL::draw(sm, {cycle1, cycle2}); } return EXIT_SUCCESS; }
2,091
823
#include "PrimitiveMesh.h" #include "Geometry.h" namespace Havana::Tools { namespace { using namespace Math; using namespace DirectX; using primitive_mesh_creator = void(*)(Scene&, const PrimitiveInitInfo& info); void CreatePlane(Scene& scene, const PrimitiveInitInfo& info); void CreateCube(Scene& scene, const PrimitiveInitInfo& info); void CreateUVSphere(Scene& scene, const PrimitiveInitInfo& info); void CreateICOSphere(Scene& scene, const PrimitiveInitInfo& info); void CreateCylinder(Scene& scene, const PrimitiveInitInfo& info); void CreateCapsule(Scene& scene, const PrimitiveInitInfo& info); primitive_mesh_creator creators[] { CreatePlane, CreateCube, CreateUVSphere, CreateICOSphere, CreateCylinder, CreateCapsule }; static_assert(_countof(creators) == PrimitiveMeshType::Count); struct Axis { enum: u32 { x = 0, y = 1, z = 2 }; }; Mesh CreatePlane(const PrimitiveInitInfo& info, u32 horizontalIndex = Axis::x, u32 verticalIndex = Axis::z, bool flipWinding = false, Vec3 offset = { -0.5f, 0.0f, -0.5f }, Vec2 uRange = { 0.0f, 1.0f }, Vec2 vRange = { 0.0f, 1.0f }) { assert(horizontalIndex < 3 && verticalIndex < 3); assert(horizontalIndex != verticalIndex); const u32 horizontalCount{ clamp(info.segments[horizontalIndex], 1u, 10u) }; const u32 verticalCount{ clamp(info.segments[verticalIndex], 1u, 10u) }; const f32 horizontalStep{ 1.0f / horizontalCount }; const f32 verticalStep{ 1.0f / verticalCount }; const f32 uStep{ (uRange.y - uRange.x) / horizontalCount }; const f32 vStep{ (vRange.y - vRange.x) / verticalCount }; Mesh m{}; Utils::vector<Vec2> uvs; for (u32 j{ 0 }; j <= verticalCount; j++) { for (u32 i{ 0 }; i <= horizontalCount; i++) { Vec3 position{ offset }; f32* const as_array{ &position.x }; as_array[horizontalIndex] += i * horizontalStep; as_array[verticalIndex] += j * verticalStep; m.positions.emplace_back(position.x * info.size.x, position.y * info.size.y, position.z * info.size.z); Vec2 uv{ uRange.x, 1.0f - vRange.x }; uv.x += i * uStep; uv.y -= j * vStep; uvs.emplace_back(uv); } } assert(m.positions.size() == (((u64)horizontalCount + 1)*((u64)verticalCount + 1))); const u32 rowLength{ horizontalCount + 1 }; // number of vertices in a row for (u32 j{ 0 }; j < verticalCount; j++) { u32 k{ 0 }; for (u32 i{ k }; i < horizontalCount; i++) { const u32 index[4] { i + j * rowLength, i + (j + 1) * rowLength, (i + 1) + j * rowLength, (i + 1) + (j + 1) * rowLength, }; // Triangle 1 m.rawIndices.emplace_back(index[0]); m.rawIndices.emplace_back(index[flipWinding ? 2 : 1]); m.rawIndices.emplace_back(index[flipWinding ? 1 : 2]); // Triangle 2 m.rawIndices.emplace_back(index[2]); m.rawIndices.emplace_back(index[flipWinding ? 3 : 1]); m.rawIndices.emplace_back(index[flipWinding ? 1 : 3]); } ++k; } const u32 numIndices{ 3 * 2 * horizontalCount * verticalCount }; assert(m.rawIndices.size() == numIndices); m.uvSets.resize(1); for (u32 i{ 0 }; i < numIndices; i++) { m.uvSets[0].emplace_back(uvs[m.rawIndices[i]]); } return m; } Mesh CreateUVSphere(const PrimitiveInitInfo& info) { const u32 phiCount{ clamp(info.segments[Axis::x], 3u, 64u) }; const u32 thetaCount{ clamp(info.segments[Axis::y], 2u, 64u) }; const f32 thetaStep{ pi / thetaCount }; const f32 phiStep{ twoPi / phiCount }; const u32 numVertices{ 2 + phiCount * (thetaCount - 1) }; const u32 numIndices{ 2 * 3 * phiCount + 2 * 3 * phiCount * (thetaCount - 2) }; Mesh m{}; m.name = "uvSphere"; m.positions.resize(numVertices); // Add top vertex u32 c{ 0 }; m.positions[c++] = { 0.0f, info.size.y, 0.0f }; // Add the body of the vertices for (u32 j{ 1 }; j < thetaCount; j++) { const f32 theta{ j * thetaStep }; for (u32 i{ 0 }; i < phiCount; i++) { const f32 phi{ i * phiStep }; m.positions[c++] = { info.size.x * XMScalarSin(theta) * XMScalarCos(phi), info.size.y * XMScalarCos(theta), -info.size.z * XMScalarSin(theta) * XMScalarSin(phi) }; } } // Add bottom vertex m.positions[c++] = { 0.0f, -info.size.y, 0.0f }; assert(numVertices == c); c = 0; m.rawIndices.resize(numIndices); Utils::vector<Vec2> uvs(numIndices); const f32 inverseThetaCount{ 1.0f / thetaCount }; const f32 inversePhiCount{ 1.0f / phiCount }; // Indices for top cap, connecting the north pole to the first ring // UV Coords at the same time for (u32 i{ 0 }; i < (phiCount - 1); i++) { uvs[c] = { (2 * i + 1) * 0.5f * inversePhiCount, 1.0f }; m.rawIndices[c++] = 0; uvs[c] = { i * inversePhiCount, 1.0f - inverseThetaCount }; m.rawIndices[c++] = i + 1; uvs[c] = { (i + 1) * inversePhiCount, 1.0f - inverseThetaCount }; m.rawIndices[c++] = i + 2; } uvs[c] = { 1.0f - 0.5f * inversePhiCount, 1.0f }; m.rawIndices[c++] = 0; uvs[c] = { 1.0f - inversePhiCount, 1.0f - inverseThetaCount }; m.rawIndices[c++] = phiCount; uvs[c] = { 1.0f, 1.0f - inverseThetaCount }; m.rawIndices[c++] = 1; // Indices for the section between the top and bottom rings // UV Coords at the same time for (u32 j{ 0 }; j < (thetaCount - 2); j++) { for (u32 i{ 0 }; i < (phiCount - 1); i++) { const u32 index[4] { 1 + i + j * phiCount, 1 + i + (j + 1) * phiCount, 1 + (i + 1) + (j + 1) * phiCount, 1 + (i + 1) + j * phiCount }; // Triangle 1 uvs[c] = { i * inversePhiCount, 1.0f - (j + 1) * inverseThetaCount }; m.rawIndices[c++] = index[0]; uvs[c] = { i * inversePhiCount, 1.0f - (j + 2) * inverseThetaCount }; m.rawIndices[c++] = index[1]; uvs[c] = { (i + 1) * inversePhiCount, 1.0f - (j + 2) * inverseThetaCount }; m.rawIndices[c++] = index[2]; // Triangle 2 uvs[c] = { i * inversePhiCount, 1.0f - (j + 1) * inverseThetaCount }; m.rawIndices[c++] = index[0]; uvs[c] = { (i + 1) * inversePhiCount, 1.0f - (j + 2) * inverseThetaCount }; m.rawIndices[c++] = index[2]; uvs[c] = { (i + 1) * inversePhiCount, 1.0f - (j + 1) * inverseThetaCount }; m.rawIndices[c++] = index[3]; } const u32 index[4] { phiCount + j * phiCount, phiCount + (j + 1) * phiCount, 1 + (j + 1) * phiCount, 1 + j * phiCount }; // Triangle 1 uvs[c] = { 1.0f - inversePhiCount, 1.0f - (j + 1) * inverseThetaCount }; m.rawIndices[c++] = index[0]; uvs[c] = { 1.0f - inversePhiCount, 1.0f - (j + 2) * inverseThetaCount }; m.rawIndices[c++] = index[1]; uvs[c] = { 1.0f, 1.0f - (j + 2) * inverseThetaCount }; m.rawIndices[c++] = index[2]; // Triangle 2 uvs[c] = { 1.0f - inversePhiCount, 1.0f - (j + 1) * inverseThetaCount }; m.rawIndices[c++] = index[0]; uvs[c] = { 1.0f, 1.0f - (j + 2) * inverseThetaCount }; m.rawIndices[c++] = index[2]; uvs[c] = { 1.0f, 1.0f - (j + 1) * inverseThetaCount }; m.rawIndices[c++] = index[3]; } // Indices for bottom cap, connecting the south pole to the last ring // UV Coords at the same time const u32 southPoleIndex{ (u32)m.positions.size() - 1 }; for (u32 i{ 0 }; i < (phiCount - 1); i++) { uvs[c] = { (2 * i + 1) * 0.5f * inversePhiCount, 0.0f }; m.rawIndices[c++] = southPoleIndex; uvs[c] = { (i + 1) * inversePhiCount, inverseThetaCount }; m.rawIndices[c++] = southPoleIndex - phiCount + i + 1; uvs[c] = { i * inversePhiCount, inverseThetaCount }; m.rawIndices[c++] = southPoleIndex - phiCount + i; } uvs[c] = { 1.0f - 0.5f * inversePhiCount, 0.0f }; m.rawIndices[c++] = southPoleIndex; uvs[c] = { 1.0f, inverseThetaCount }; m.rawIndices[c++] = southPoleIndex - phiCount; uvs[c] = { 1.0f - inversePhiCount, inverseThetaCount }; m.rawIndices[c++] = southPoleIndex - 1; assert(c == numIndices); m.uvSets.emplace_back(uvs); return m; } void CreatePlane(Scene& scene, const PrimitiveInitInfo& info) { LoDGroup lod{}; lod.name = "plane"; lod.meshes.emplace_back(CreatePlane(info)); scene.lodGroups.emplace_back(lod); } void CreateCube(Scene& scene, const PrimitiveInitInfo& info) {} void CreateUVSphere(Scene& scene, const PrimitiveInitInfo& info) { LoDGroup lod{}; lod.name = "uvSphere"; lod.meshes.emplace_back(CreateUVSphere(info)); scene.lodGroups.emplace_back(lod); } void CreateICOSphere(Scene& scene, const PrimitiveInitInfo& info) {} void CreateCylinder(Scene& scene, const PrimitiveInitInfo& info) {} void CreateCapsule(Scene& scene, const PrimitiveInitInfo& info) {} } // anonymous namespace EDITOR_INTERFACE void CreatePrimitiveMesh(SceneData* data, PrimitiveInitInfo* info) { assert(data && info); assert(info->type < PrimitiveMeshType::Count); Scene scene{}; creators[info->type](scene, *info); // TODO: process scene and pack to be sent to the Editor data->settings.calculateNormals = 1; ProcessScene(scene, data->settings); PackData(scene, *data); } }
9,253
4,498
/*************************************************************************** XML Configuration File Handling. Load Settings. Load & Save Hi-Scores. Copyright Chris White. See license.txt for more details. ***************************************************************************/ // see: http://www.boost.org/doc/libs/1_52_0/doc/html/boost_propertytree/tutorial.html #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <iostream> #include "main.hpp" #include "config.hpp" #include "globals.hpp" #include "setup.hpp" #include "../utils.hpp" #include "engine/ohiscore.hpp" #include "engine/audio/osoundint.hpp" // api change in boost 1.56 #include <boost/version.hpp> #if (BOOST_VERSION >= 105600) typedef boost::property_tree::xml_writer_settings<std::string> xml_writer_settings; #else typedef boost::property_tree::xml_writer_settings<char> xml_writer_settings; #endif Config config; Config::Config(void) { } Config::~Config(void) { } void Config::init() { } using boost::property_tree::ptree; ptree pt_config; void Config::load(const std::string &filename) { // Load XML file and put its contents in property tree. // No namespace qualification is needed, because of Koenig // lookup on the second argument. If reading fails, exception // is thrown. try { read_xml(filename, pt_config, boost::property_tree::xml_parser::trim_whitespace); } catch (std::exception &e) { std::cout << "Error: " << e.what() << "\n"; } // ------------------------------------------------------------------------ // Menu Settings // ------------------------------------------------------------------------ menu.enabled = pt_config.get("menu.enabled", 1); menu.road_scroll_speed = pt_config.get("menu.roadspeed", 50); // ------------------------------------------------------------------------ // Video Settings // ------------------------------------------------------------------------ video.mode = pt_config.get("video.mode", 0); // Video Mode: Default is Windowed video.scale = pt_config.get("video.window.scale", 2); // Video Scale: Default is 2x video.scanlines = pt_config.get("video.scanlines", 0); // Scanlines video.fps = pt_config.get("video.fps", 2); // Default is 60 fps video.fps_count = pt_config.get("video.fps_counter", 0); // FPS Counter video.widescreen = pt_config.get("video.widescreen", 1); // Enable Widescreen Mode video.hires = pt_config.get("video.hires", 0); // Hi-Resolution Mode video.filtering = pt_config.get("video.filtering", 0); // Open GL Filtering Mode set_fps(video.fps); // ------------------------------------------------------------------------ // Sound Settings // ------------------------------------------------------------------------ sound.enabled = pt_config.get("sound.enable", 1); sound.advertise = pt_config.get("sound.advertise", 1); sound.preview = pt_config.get("sound.preview", 1); sound.fix_samples = pt_config.get("sound.fix_samples", 1); // Custom Music for (int i = 0; i < 4; i++) { std::string xmltag = "sound.custom_music.track"; xmltag += Utils::to_string(i+1); sound.custom_music[i].enabled = pt_config.get(xmltag + ".<xmlattr>.enabled", 0); sound.custom_music[i].title = pt_config.get(xmltag + ".title", "TRACK " +Utils::to_string(i+1)); sound.custom_music[i].filename= pt_config.get(xmltag + ".filename", "track"+Utils::to_string(i+1)+".wav"); } // ------------------------------------------------------------------------ // CannonBoard Settings // ------------------------------------------------------------------------ cannonboard.enabled = pt_config.get("cannonboard.<xmlattr>.enabled", 0); cannonboard.port = pt_config.get("cannonboard.port", "COM6"); cannonboard.baud = pt_config.get("cannonboard.baud", 57600); cannonboard.debug = pt_config.get("cannonboard.debug", 0); cannonboard.cabinet = pt_config.get("cannonboard.cabinet", 0); // ------------------------------------------------------------------------ // Controls // ------------------------------------------------------------------------ controls.gear = pt_config.get("controls.gear", 0); controls.steer_speed = pt_config.get("controls.steerspeed", 3); controls.pedal_speed = pt_config.get("controls.pedalspeed", 4); controls.keyconfig[0] = pt_config.get("controls.keyconfig.up", 273); controls.keyconfig[1] = pt_config.get("controls.keyconfig.down", 274); controls.keyconfig[2] = pt_config.get("controls.keyconfig.left", 276); controls.keyconfig[3] = pt_config.get("controls.keyconfig.right", 275); controls.keyconfig[4] = pt_config.get("controls.keyconfig.acc", 122); controls.keyconfig[5] = pt_config.get("controls.keyconfig.brake", 120); controls.keyconfig[6] = pt_config.get("controls.keyconfig.gear1", 32); controls.keyconfig[7] = pt_config.get("controls.keyconfig.gear2", 32); controls.keyconfig[8] = pt_config.get("controls.keyconfig.start", 49); controls.keyconfig[9] = pt_config.get("controls.keyconfig.coin", 53); controls.keyconfig[10] = pt_config.get("controls.keyconfig.menu", 286); controls.keyconfig[11] = pt_config.get("controls.keyconfig.view", 304); controls.padconfig[0] = pt_config.get("controls.padconfig.acc", 0); controls.padconfig[1] = pt_config.get("controls.padconfig.brake", 1); controls.padconfig[2] = pt_config.get("controls.padconfig.gear1", 2); controls.padconfig[3] = pt_config.get("controls.padconfig.gear2", 2); controls.padconfig[4] = pt_config.get("controls.padconfig.start", 3); controls.padconfig[5] = pt_config.get("controls.padconfig.coin", 4); controls.padconfig[6] = pt_config.get("controls.padconfig.menu", 5); controls.padconfig[7] = pt_config.get("controls.padconfig.view", 6); controls.analog = pt_config.get("controls.analog.<xmlattr>.enabled", 0); controls.pad_id = pt_config.get("controls.pad_id", 0); controls.axis[0] = pt_config.get("controls.analog.axis.wheel", 0); controls.axis[1] = pt_config.get("controls.analog.axis.accel", 2); controls.axis[2] = pt_config.get("controls.analog.axis.brake", 3); controls.asettings[0] = pt_config.get("controls.analog.wheel.zone", 75); controls.asettings[1] = pt_config.get("controls.analog.wheel.dead", 0); controls.asettings[2] = pt_config.get("controls.analog.pedals.dead", 0); controls.haptic = pt_config.get("controls.analog.haptic.<xmlattr>.enabled", 0); controls.max_force = pt_config.get("controls.analog.haptic.max_force", 9000); controls.min_force = pt_config.get("controls.analog.haptic.min_force", 8500); controls.force_duration= pt_config.get("controls.analog.haptic.force_duration", 20); // ------------------------------------------------------------------------ // Engine Settings // ------------------------------------------------------------------------ engine.dip_time = pt_config.get("engine.time", 0); engine.dip_traffic = pt_config.get("engine.traffic", 1); engine.freeze_timer = engine.dip_time == 4; engine.disable_traffic = engine.dip_traffic == 4; engine.dip_time &= 3; engine.dip_traffic &= 3; engine.freeplay = pt_config.get("engine.freeplay", 0) != 0; engine.jap = pt_config.get("engine.japanese_tracks", 0); engine.prototype = pt_config.get("engine.prototype", 0); // Additional Level Objects engine.level_objects = pt_config.get("engine.levelobjects", 1); engine.randomgen = pt_config.get("engine.randomgen", 1); engine.fix_bugs_backup = engine.fix_bugs = pt_config.get("engine.fix_bugs", 1) != 0; engine.fix_timer = pt_config.get("engine.fix_timer", 0) != 0; engine.layout_debug = pt_config.get("engine.layout_debug", 0) != 0; engine.new_attract = pt_config.get("engine.new_attract", 1) != 0; // ------------------------------------------------------------------------ // Time Trial Mode // ------------------------------------------------------------------------ ttrial.laps = pt_config.get("time_trial.laps", 5); ttrial.traffic = pt_config.get("time_trial.traffic", 3); cont_traffic = pt_config.get("continuous.traffic", 3); } bool Config::save(const std::string &filename) { // Save stuff pt_config.put("video.mode", video.mode); pt_config.put("video.window.scale", video.scale); pt_config.put("video.scanlines", video.scanlines); pt_config.put("video.fps", video.fps); pt_config.put("video.widescreen", video.widescreen); pt_config.put("video.hires", video.hires); pt_config.put("sound.enable", sound.enabled); pt_config.put("sound.advertise", sound.advertise); pt_config.put("sound.preview", sound.preview); pt_config.put("sound.fix_samples", sound.fix_samples); pt_config.put("controls.gear", controls.gear); pt_config.put("controls.steerspeed", controls.steer_speed); pt_config.put("controls.pedalspeed", controls.pedal_speed); pt_config.put("controls.keyconfig.up", controls.keyconfig[0]); pt_config.put("controls.keyconfig.down", controls.keyconfig[1]); pt_config.put("controls.keyconfig.left", controls.keyconfig[2]); pt_config.put("controls.keyconfig.right", controls.keyconfig[3]); pt_config.put("controls.keyconfig.acc", controls.keyconfig[4]); pt_config.put("controls.keyconfig.brake", controls.keyconfig[5]); pt_config.put("controls.keyconfig.gear1", controls.keyconfig[6]); pt_config.put("controls.keyconfig.gear2", controls.keyconfig[7]); pt_config.put("controls.keyconfig.start", controls.keyconfig[8]); pt_config.put("controls.keyconfig.coin", controls.keyconfig[9]); pt_config.put("controls.keyconfig.menu", controls.keyconfig[10]); pt_config.put("controls.keyconfig.view", controls.keyconfig[11]); pt_config.put("controls.padconfig.acc", controls.padconfig[0]); pt_config.put("controls.padconfig.brake", controls.padconfig[1]); pt_config.put("controls.padconfig.gear1", controls.padconfig[2]); pt_config.put("controls.padconfig.gear2", controls.padconfig[3]); pt_config.put("controls.padconfig.start", controls.padconfig[4]); pt_config.put("controls.padconfig.coin", controls.padconfig[5]); pt_config.put("controls.padconfig.menu", controls.padconfig[6]); pt_config.put("controls.padconfig.view", controls.padconfig[7]); pt_config.put("controls.analog.<xmlattr>.enabled", controls.analog); pt_config.put("engine.time", engine.freeze_timer ? 4 : engine.dip_time); pt_config.put("engine.traffic", engine.disable_traffic ? 4 : engine.dip_traffic); pt_config.put("engine.japanese_tracks", engine.jap); pt_config.put("engine.prototype", engine.prototype); pt_config.put("engine.levelobjects", engine.level_objects); pt_config.put("engine.new_attract", engine.new_attract); pt_config.put("time_trial.laps", ttrial.laps); pt_config.put("time_trial.traffic", ttrial.traffic); pt_config.put("continuous.traffic", cont_traffic), ttrial.laps = pt_config.get("time_trial.laps", 5); ttrial.traffic = pt_config.get("time_trial.traffic", 3); cont_traffic = pt_config.get("continuous.traffic", 3); try { write_xml(filename, pt_config, std::locale(), xml_writer_settings('\t', 1)); // Tab space 1 } catch (std::exception &e) { std::cout << "Error saving config: " << e.what() << "\n"; return false; } return true; } void Config::load_scores(const std::string &filename) { // Create empty property tree object ptree pt; try { read_xml(engine.jap ? filename + "_jap.xml" : filename + ".xml" , pt, boost::property_tree::xml_parser::trim_whitespace); } catch (std::exception &e) { e.what(); return; } // Game Scores for (int i = 0; i < ohiscore.NO_SCORES; i++) { score_entry* e = &ohiscore.scores[i]; std::string xmltag = "score"; xmltag += Utils::to_string(i); e->score = Utils::from_hex_string(pt.get<std::string>(xmltag + ".score", "0")); e->initial1 = pt.get(xmltag + ".initial1", ".")[0]; e->initial2 = pt.get(xmltag + ".initial2", ".")[0]; e->initial3 = pt.get(xmltag + ".initial3", ".")[0]; e->maptiles = Utils::from_hex_string(pt.get<std::string>(xmltag + ".maptiles", "20202020")); e->time = Utils::from_hex_string(pt.get<std::string>(xmltag + ".time" , "0")); if (e->initial1 == '.') e->initial1 = 0x20; if (e->initial2 == '.') e->initial2 = 0x20; if (e->initial3 == '.') e->initial3 = 0x20; } } void Config::save_scores(const std::string &filename) { // Create empty property tree object ptree pt; for (int i = 0; i < ohiscore.NO_SCORES; i++) { score_entry* e = &ohiscore.scores[i]; std::string xmltag = "score"; xmltag += Utils::to_string(i); pt.put(xmltag + ".score", Utils::to_hex_string(e->score)); pt.put(xmltag + ".initial1", e->initial1 == 0x20 ? "." : Utils::to_string((char) e->initial1)); // use . to represent space pt.put(xmltag + ".initial2", e->initial2 == 0x20 ? "." : Utils::to_string((char) e->initial2)); pt.put(xmltag + ".initial3", e->initial3 == 0x20 ? "." : Utils::to_string((char) e->initial3)); pt.put(xmltag + ".maptiles", Utils::to_hex_string(e->maptiles)); pt.put(xmltag + ".time", Utils::to_hex_string(e->time)); } try { write_xml(engine.jap ? filename + "_jap.xml" : filename + ".xml", pt, std::locale(), xml_writer_settings('\t', 1)); // Tab space 1 } catch (std::exception &e) { std::cout << "Error saving hiscores: " << e.what() << "\n"; } } void Config::load_tiletrial_scores() { const std::string filename = FILENAME_TTRIAL; // Counter value that represents 1m 15s 0ms static const uint16_t COUNTER_1M_15 = 0x11D0; // Create empty property tree object ptree pt; try { read_xml(engine.jap ? filename + "_jap.xml" : filename + ".xml" , pt, boost::property_tree::xml_parser::trim_whitespace); } catch (std::exception &e) { for (int i = 0; i < 15; i++) ttrial.best_times[i] = COUNTER_1M_15; e.what(); return; } // Time Trial Scores for (int i = 0; i < 15; i++) { ttrial.best_times[i] = pt.get("time_trial.score" + Utils::to_string(i), COUNTER_1M_15); } } void Config::save_tiletrial_scores() { const std::string filename = FILENAME_TTRIAL; // Create empty property tree object ptree pt; // Time Trial Scores for (int i = 0; i < 15; i++) { pt.put("time_trial.score" + Utils::to_string(i), ttrial.best_times[i]); } try { write_xml(engine.jap ? filename + "_jap.xml" : filename + ".xml", pt, std::locale(), xml_writer_settings('\t', 1)); // Tab space 1 } catch (std::exception &e) { std::cout << "Error saving hiscores: " << e.what() << "\n"; } } bool Config::clear_scores() { // Init Default Hiscores ohiscore.init_def_scores(); int clear = 0; // Remove XML files if they exist clear += remove(std::string(FILENAME_SCORES).append(".xml").c_str()); clear += remove(std::string(FILENAME_SCORES).append("_jap.xml").c_str()); clear += remove(std::string(FILENAME_TTRIAL).append(".xml").c_str()); clear += remove(std::string(FILENAME_TTRIAL).append("_jap.xml").c_str()); clear += remove(std::string(FILENAME_CONT).append(".xml").c_str()); clear += remove(std::string(FILENAME_CONT).append("_jap.xml").c_str()); // remove returns 0 on success return clear == 6; } void Config::set_fps(int fps) { video.fps = fps; // Set core FPS to 30fps or 60fps this->fps = video.fps == 0 ? 30 : 60; // Original game ticks sprites at 30fps but background scroll at 60fps tick_fps = video.fps < 2 ? 30 : 60; cannonball::frame_ms = 1000.0 / this->fps; #ifdef COMPILE_SOUND_CODE if (config.sound.enabled) cannonball::audio.stop_audio(); osoundint.init(); if (config.sound.enabled) cannonball::audio.start_audio(); #endif }
16,935
5,783
// 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 "chrome/browser/ui/tabs/tab_strip_model_stats_recorder.h" #include <algorithm> #include <utility> #include "base/check.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/notreached.h" #include "base/supports_user_data.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" TabStripModelStatsRecorder::TabStripModelStatsRecorder() : browser_tab_strip_tracker_(this, nullptr) { browser_tab_strip_tracker_.Init(); } TabStripModelStatsRecorder::~TabStripModelStatsRecorder() { } class TabStripModelStatsRecorder::TabInfo : public base::SupportsUserData::Data { public: ~TabInfo() override; void UpdateState(TabState new_state); TabState state() const { return current_state_; } static TabInfo* Get(content::WebContents* contents) { TabInfo* info = static_cast<TabStripModelStatsRecorder::TabInfo*>( contents->GetUserData(kKey)); if (!info) { info = new TabInfo(); contents->SetUserData(kKey, base::WrapUnique(info)); } return info; } private: TabState current_state_ = TabState::INITIAL; static const char kKey[]; }; const char TabStripModelStatsRecorder::TabInfo::kKey[] = "WebContents TabInfo"; TabStripModelStatsRecorder::TabInfo::~TabInfo() {} void TabStripModelStatsRecorder::TabInfo::UpdateState(TabState new_state) { if (new_state == current_state_) return; // Avoid state transition from CLOSED. // When tab is closed, we receive TabStripModelObserver::TabClosingAt and then // TabStripModelStatsRecorder::ActiveTabChanged. // Here we ignore CLOSED -> INACTIVE state transition from last // ActiveTabChanged. if (current_state_ == TabState::CLOSED) return; switch (current_state_) { case TabState::INITIAL: break; case TabState::ACTIVE: UMA_HISTOGRAM_ENUMERATION("Tabs.StateTransfer.Target_Active", static_cast<int>(new_state), static_cast<int>(TabState::MAX)); break; case TabState::INACTIVE: UMA_HISTOGRAM_ENUMERATION("Tabs.StateTransfer.Target_Inactive", static_cast<int>(new_state), static_cast<int>(TabState::MAX)); break; case TabState::CLOSED: case TabState::MAX: NOTREACHED(); break; } current_state_ = new_state; } void TabStripModelStatsRecorder::OnTabClosing(content::WebContents* contents) { TabInfo::Get(contents)->UpdateState(TabState::CLOSED); // Avoid having stale pointer in active_tab_history_ std::replace(active_tab_history_.begin(), active_tab_history_.end(), contents, static_cast<content::WebContents*>(nullptr)); } void TabStripModelStatsRecorder::OnActiveTabChanged( content::WebContents* old_contents, content::WebContents* new_contents, int reason) { if (reason & TabStripModelObserver::CHANGE_REASON_REPLACED) { // We already handled tab clobber at TabReplacedAt notification. return; } if (old_contents) TabInfo::Get(old_contents)->UpdateState(TabState::INACTIVE); DCHECK(new_contents); TabInfo* tab_info = TabInfo::Get(new_contents); bool was_inactive = tab_info->state() == TabState::INACTIVE; tab_info->UpdateState(TabState::ACTIVE); // A UMA Histogram must be bounded by some number. // We chose 64 as our bound as 99.5% of the users open <64 tabs. const int kMaxTabHistory = 64; auto it = std::find(active_tab_history_.cbegin(), active_tab_history_.cend(), new_contents); int age = (it != active_tab_history_.cend()) ? (it - active_tab_history_.cbegin()) : (kMaxTabHistory - 1); if (was_inactive) { UMA_HISTOGRAM_ENUMERATION( "Tabs.StateTransfer.NumberOfOtherTabsActivatedBeforeMadeActive", std::min(age, kMaxTabHistory - 1), kMaxTabHistory); } active_tab_history_.insert(active_tab_history_.begin(), new_contents); if (active_tab_history_.size() > kMaxTabHistory) active_tab_history_.resize(kMaxTabHistory); } void TabStripModelStatsRecorder::OnTabReplaced( content::WebContents* old_contents, content::WebContents* new_contents) { DCHECK(old_contents != new_contents); *TabInfo::Get(new_contents) = *TabInfo::Get(old_contents); std::replace(active_tab_history_.begin(), active_tab_history_.end(), old_contents, new_contents); } void TabStripModelStatsRecorder::OnTabStripModelChanged( TabStripModel* tab_strip_model, const TabStripModelChange& change, const TabStripSelectionChange& selection) { if (change.type() == TabStripModelChange::kRemoved) { for (const auto& contents : change.GetRemove()->contents) { if (contents.remove_reason == TabStripModelChange::RemoveReason::kDeleted) OnTabClosing(contents.contents); } } else if (change.type() == TabStripModelChange::kReplaced) { auto* replace = change.GetReplace(); OnTabReplaced(replace->old_contents, replace->new_contents); } if (!selection.active_tab_changed() || tab_strip_model->empty()) return; OnActiveTabChanged(selection.old_contents, selection.new_contents, selection.reason); }
5,428
1,775
/* * This file is part of the Micro Python project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2015 Damien P. George * * 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. */ extern "C" { #include "microbit/modmicrobit.h" #include "py/mphal.h" #include "microbitimage.h" #include "microbitdisplay.h" static const mp_float_t bright[7] = { 0.0, 1.0/9, 2.0/9, 4.0/9, 6.0/9, 7.0/9, 1.0, }; void love(int interval = 25 /* ms */) { microbit_image_obj_t *hearts[MP_ARRAY_SIZE(bright)]; for (uint i = 0; i < MP_ARRAY_SIZE(bright); i++) { hearts[i] = microbit_image_dim(HEART_IMAGE, bright[i]); } for (int iteration = 0; iteration < 8; iteration++) { // pause between double beats of the heart if (iteration && (iteration & 1) == 0) { mp_hal_delay_ms(20 * interval); } // pulse heart to max brightness for(uint step = 0; step < MP_ARRAY_SIZE(bright); ++step) { microbit_display_show(&microbit_display_obj, hearts[step]); mp_hal_delay_ms(interval); } // pulse heart to min brightness for(int step = MP_ARRAY_SIZE(bright) - 1; step >= 0; --step) { microbit_display_show(&microbit_display_obj, hearts[step]); mp_hal_delay_ms(interval); } } microbit_display_clear(); } STATIC mp_obj_t love_badaboom(void) { // make love(); // ! war return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_0(love___init___obj, love_badaboom); MP_DEFINE_CONST_FUN_OBJ_0(love_badaboom_obj, love_badaboom); STATIC const mp_map_elem_t love_module_globals_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_love) }, { MP_OBJ_NEW_QSTR(MP_QSTR___init__), (mp_obj_t)&love___init___obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_badaboom), (mp_obj_t)&love_badaboom_obj }, }; STATIC MP_DEFINE_CONST_DICT(love_module_globals, love_module_globals_table); const mp_obj_module_t love_module = { .base = { &mp_type_module }, .name = MP_QSTR_love, .globals = (mp_obj_dict_t*)&love_module_globals, }; }
3,130
1,183
/* Ricochet - https://ricochet.im/ * Copyright (C) 2014, John Brooks <john.brooks@dereferenced.net> * * 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 names of the copyright owners nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Connection_p.h" #include "ControlChannel.h" #include "utils/Useful.h" #include <QTcpSocket> #include <QTimer> #include <QtEndian> #include <QDebug> using namespace Protocol; Connection::Connection(QTcpSocket *socket, Direction direction) : QObject() , d(new ConnectionPrivate(this)) { d->setSocket(socket, direction); } ConnectionPrivate::ConnectionPrivate(Connection *qq) : QObject(qq) , q(qq) , socket(0) , direction(Connection::ClientSide) , purpose(Connection::Purpose::Unknown) , wasClosed(false) , handshakeDone(false) , nextOutboundChannelId(-1) { ageTimer.start(); QTimer *timeout = new QTimer(this); timeout->setSingleShot(true); timeout->setInterval(UnknownPurposeTimeout * 1000); connect(timeout, &QTimer::timeout, this, [this,timeout]() { if (purpose == Connection::Purpose::Unknown) { qDebug() << "Closing connection" << q << "with unknown purpose after timeout"; q->close(); } timeout->deleteLater(); } ); timeout->start(); } Connection::~Connection() { qDebug() << this << "Destroying connection"; // When we call closeImmediately, the list of channels will be cleared. // In the normal case, they will all use deleteLater to be freed at the // next event loop. Since the connection is being destructed immediately, // and we want to be certain that channels don't outlive it, copy the // list before it's cleared and delete them immediately afterwards. auto channels = d->channels; d->closeImmediately(); // These would be deleted by QObject ownership as well, but we want to // give them a chance to destruct before the connection d pointer is reset. foreach (Channel *c, channels) delete c; // Reset d pointer, so we'll crash nicely if anything tries to call // into Connection after this. d = 0; } ConnectionPrivate::~ConnectionPrivate() { // Reset q pointer, for the same reason as above q = 0; } Connection::Direction Connection::direction() const { return d->direction; } bool Connection::isConnected() const { bool re = d->socket && d->socket->state() == QAbstractSocket::ConnectedState; if (d->wasClosed) { Q_ASSERT(!re); } return re; } QString Connection::serverHostname() const { QString hostname; if (direction() == ClientSide) hostname = d->socket->peerName(); else if (direction() == ServerSide) hostname = d->socket->property("localHostname").toString(); if (!hostname.endsWith(QStringLiteral(".onion"))) { BUG() << "Connection does not have a valid server hostname:" << hostname; return QString(); } return hostname; } int Connection::age() const { return qRound(d->ageTimer.elapsed() / 1000.0); } void ConnectionPrivate::setSocket(QTcpSocket *s, Connection::Direction d) { if (socket) { BUG() << "Connection already has a socket"; return; } socket = s; direction = d; connect(socket, &QAbstractSocket::disconnected, this, &ConnectionPrivate::socketDisconnected); connect(socket, &QIODevice::readyRead, this, &ConnectionPrivate::socketReadable); socket->setParent(q); if (socket->state() != QAbstractSocket::ConnectedState) { BUG() << "Connection created with socket in a non-connected state" << socket->state(); } Channel *control = new ControlChannel(direction == Connection::ClientSide ? Channel::Outbound : Channel::Inbound, q); // Closing the control channel must also close the connection connect(control, &Channel::invalidated, q, &Connection::close); insertChannel(control); if (!control->isOpened() || control->identifier() != 0 || q->channel(0) != control) { BUG() << "Control channel on new connection is not set up properly"; q->close(); return; } if (direction == Connection::ClientSide) { // The server side is implicitly authenticated (by the transport) as the correct service, so grant that QString serverName = q->serverHostname(); if (serverName.isEmpty()) { BUG() << "Server side of connection doesn't have an authenticated name, aborting"; q->close(); return; } q->grantAuthentication(Connection::HiddenServiceAuth, serverName); // Send the introduction version handshake message char intro[] = { 0x49, 0x4D, 0x02, ProtocolVersion, 0 }; if (socket->write(intro, sizeof(intro)) < (int)sizeof(intro)) { qDebug() << "Failed writing introduction message to socket"; q->close(); return; } } } void Connection::close() { if (isConnected()) { Q_ASSERT(!d->wasClosed); qDebug() << "Disconnecting socket for connection" << this; d->socket->disconnectFromHost(); // If not fully closed in 5 seconds, abort QTimer *timeout = new QTimer(this); timeout->setSingleShot(true); connect(timeout, &QTimer::timeout, d, &ConnectionPrivate::closeImmediately); timeout->start(5000); } } void ConnectionPrivate::closeImmediately() { if (socket) socket->abort(); if (!wasClosed) { BUG() << "Socket was forcefully closed but never emitted closed signal"; wasClosed = true; emit q->closed(); } if (!channels.isEmpty()) { foreach (Channel *c, channels) qDebug() << "Open channel:" << c << c->type() << c->connection(); BUG() << "Channels remain open after forcefully closing connection socket"; } } void ConnectionPrivate::socketDisconnected() { qDebug() << "Connection" << this << "disconnected"; closeAllChannels(); if (!wasClosed) { wasClosed = true; emit q->closed(); } } void ConnectionPrivate::socketReadable() { if (!handshakeDone) { qint64 available = socket->bytesAvailable(); if (direction == Connection::ClientSide && available >= 1) { // Expecting a single byte in response with the chosen version uchar version = ProtocolVersionFailed; if (socket->read(reinterpret_cast<char*>(&version), 1) < 1) { qDebug() << "Connection socket error" << socket->error() << "during read:" << socket->errorString(); socket->abort(); return; } handshakeDone = true; if (version == 0) { qDebug() << "Server in outbound connection is using the version 1.0 protocol"; emit q->oldVersionNegotiated(socket); q->close(); return; } else if (version != ProtocolVersion) { qDebug() << "Version negotiation failed on outbound connection"; emit q->versionNegotiationFailed(); socket->abort(); return; } else emit q->ready(); } else if (direction == Connection::ServerSide && available >= 3) { // Expecting at least 3 bytes uchar intro[3] = { 0 }; qint64 re = socket->peek(reinterpret_cast<char*>(intro), sizeof(intro)); if (re < (int)sizeof(intro)) { qDebug() << "Connection socket error" << socket->error() << "during read:" << socket->errorString(); socket->abort(); return; } quint8 nVersions = intro[2]; if (intro[0] != 0x49 || intro[1] != 0x4D || nVersions == 0) { qDebug() << "Invalid introduction sequence on inbound connection"; socket->abort(); return; } if (available < (qint64)sizeof(intro) + nVersions) return; // Discard intro header re = socket->read(reinterpret_cast<char*>(intro), sizeof(intro)); QByteArray versions(nVersions, 0); re = socket->read(versions.data(), versions.size()); if (re != versions.size()) { qDebug() << "Connection socket error" << socket->error() << "during read:" << socket->errorString(); socket->abort(); return; } quint8 selectedVersion = ProtocolVersionFailed; foreach (quint8 v, versions) { if (v == ProtocolVersion) { selectedVersion = v; break; } } re = socket->write(reinterpret_cast<char*>(&selectedVersion), 1); if (re != 1) { qDebug() << "Connection socket error" << socket->error() << "during write:" << socket->errorString(); socket->abort(); return; } handshakeDone = true; if (selectedVersion != ProtocolVersion) { qDebug() << "Version negotiation failed on inbound connection"; emit q->versionNegotiationFailed(); // Close gracefully to allow the response to write q->close(); return; } else emit q->ready(); } else { return; } } qint64 available; while ((available = socket->bytesAvailable()) >= PacketHeaderSize) { uchar header[PacketHeaderSize]; // Peek at the header first, to read the size of the packet and make sure // the entire thing is available within the buffer. qint64 re = socket->peek(reinterpret_cast<char*>(header), PacketHeaderSize); if (re < 0) { qDebug() << "Connection socket error" << socket->error() << "during read:" << socket->errorString(); socket->abort(); return; } else if (re < PacketHeaderSize) { BUG() << "Socket had" << available << "bytes available but peek only returned" << re; return; } Q_STATIC_ASSERT(PacketHeaderSize == 4); quint16 packetSize = qFromBigEndian<quint16>(header); quint16 channelId = qFromBigEndian<quint16>(&header[2]); if (packetSize < PacketHeaderSize) { qWarning() << "Corrupted data from connection (packet size is too small); disconnecting"; socket->abort(); return; } if (packetSize > available) break; // Read header out of the buffer and discard re = socket->read(reinterpret_cast<char*>(header), PacketHeaderSize); if (re != PacketHeaderSize) { if (re < 0) { qDebug() << "Connection socket error" << socket->error() << "during read:" << socket->errorString(); } else { // Because of QTcpSocket buffering, we can expect that up to 'available' bytes // will read. Treat anything less as an error condition. BUG() << "Socket read was unexpectedly small;" << available << "bytes should've been available but we read" << re; } socket->abort(); return; } // Read data QByteArray data(packetSize - PacketHeaderSize, 0); re = (data.size() == 0) ? 0 : socket->read(data.data(), data.size()); if (re != data.size()) { if (re < 0) { qDebug() << "Connection socket error" << socket->error() << "during read:" << socket->errorString(); } else { // As above BUG() << "Socket read was unexpectedly small;" << available << "bytes should've been available but we read" << re; } socket->abort(); return; } Channel *channel = q->channel(channelId); if (!channel) { // XXX We should sanity-check and rate limit these responses better if (data.isEmpty()) { qDebug() << "Ignoring channel close message for non-existent channel" << channelId; } else { qDebug() << "Ignoring" << data.size() << "byte packet for non-existent channel" << channelId; // Send channel close message writePacket(channelId, QByteArray()); } continue; } if (channel->connection() != q) { // If this fails, something is extremely broken. It may be dangerous to continue // processing any data at all. Crash gracefully. BUG() << "Channel" << channelId << "found on connection" << this << "but its connection is" << channel->connection(); qFatal("Connection mismatch while handling packet"); return; } if (data.isEmpty()) { channel->closeChannel(); } else { channel->receivePacket(data); } } } bool ConnectionPrivate::writePacket(Channel *channel, const QByteArray &data) { if (channel->connection() != q) { // As above, dangerously broken, crash the process to avoid damage BUG() << "Writing packet for channel" << channel->identifier() << "on connection" << this << "but its connection is" << channel->connection(); qFatal("Connection mismatch while writing packet"); return false; } return writePacket(channel->identifier(), data); } bool ConnectionPrivate::writePacket(int channelId, const QByteArray &data) { if (channelId < 0 || channelId > UINT16_MAX) { BUG() << "Cannot write packet for channel with invalid identifier" << channelId; return false; } if (data.size() > PacketMaxDataSize) { BUG() << "Cannot write oversized packet of" << data.size() << "bytes to channel" << channelId; return false; } if (!q->isConnected()) { qDebug() << "Cannot write packet to closed connection"; return false; } Q_STATIC_ASSERT(PacketHeaderSize + PacketMaxDataSize <= UINT16_MAX); Q_STATIC_ASSERT(PacketHeaderSize == 4); uchar header[PacketHeaderSize] = { 0 }; qToBigEndian(static_cast<quint16>(PacketHeaderSize + data.size()), header); qToBigEndian(static_cast<quint16>(channelId), &header[2]); qint64 re = socket->write(reinterpret_cast<char*>(header), PacketHeaderSize); if (re != PacketHeaderSize) { qDebug() << "Connection socket error" << socket->error() << "during write:" << socket->errorString(); socket->abort(); return false; } re = socket->write(data); if (re != data.size()) { qDebug() << "Connection socket error" << socket->error() << "during write:" << socket->errorString(); socket->abort(); return false; } return true; } int ConnectionPrivate::availableOutboundChannelId() { // Server opens even-nubmered channels, client opens odd-numbered bool evenNumbered = (direction == Connection::ServerSide); const int minId = evenNumbered ? 2 : 1; const int maxId = evenNumbered ? (UINT16_MAX-1) : UINT16_MAX; if (nextOutboundChannelId < minId || nextOutboundChannelId > maxId) nextOutboundChannelId = minId; // Find an unused id, trying a maximum of 100 times, using a random step to avoid collision for (int i = 0; i < 100 && channels.contains(nextOutboundChannelId); i++) { nextOutboundChannelId += 1 + (qrand() % 200); if (evenNumbered) nextOutboundChannelId += nextOutboundChannelId % 2; if (nextOutboundChannelId > maxId) nextOutboundChannelId = minId; } if (channels.contains(nextOutboundChannelId)) { // Abort the connection if we still couldn't find an id, because it's probably a nasty bug BUG() << "Can't find an available outbound channel ID for connection; aborting connection"; socket->abort(); return -1; } if (nextOutboundChannelId < minId || nextOutboundChannelId > maxId) { BUG() << "Selected a channel id that isn't within range"; return -1; } if (evenNumbered == bool(nextOutboundChannelId % 2)) { BUG() << "Selected a channel id that isn't valid for this side of the connection"; return -1; } int re = nextOutboundChannelId; nextOutboundChannelId += 2; return re; } bool ConnectionPrivate::isValidAvailableChannelId(int id, Connection::Direction side) { if (id < 1 || id > UINT16_MAX) return false; bool evenNumbered = bool(id % 2); if (evenNumbered == (side == Connection::ServerSide)) return false; if (channels.contains(id)) return false; return true; } bool ConnectionPrivate::insertChannel(Channel *channel) { if (channel->connection() != q) { BUG() << "Connection tried to insert a channel assigned to a different connection"; return false; } if (channel->identifier() < 0) { BUG() << "Connection tried to insert a channel without a valid identifier"; return false; } if (channels.contains(channel->identifier())) { BUG() << "Connection tried to insert a channel with a duplicate id" << channel->identifier() << "- we have" << channels.value(channel->identifier()) << "and inserted" << channel; return false; } if (channel->parent() != q) { BUG() << "Connection inserted a channel without expected parent object. Fixing."; channel->setParent(q); } channels.insert(channel->identifier(), channel); return true; } void ConnectionPrivate::removeChannel(Channel *channel) { if (channel->connection() != q) { BUG() << "Connection tried to remove a channel assigned to a different connection"; return; } // Out of caution, find the channel by pointer instead of identifier. This will make sure // it's always removed from the list, even if the identifier was somehow reset or lost. for (auto it = channels.begin(); it != channels.end(); ) { if (*it == channel) it = channels.erase(it); else it++; } } void ConnectionPrivate::closeAllChannels() { // Takes a copy, won't be broken by removeChannel calls foreach (Channel *channel, channels) channel->closeChannel(); if (!channels.isEmpty()) BUG() << "Channels remain open on connection after calling closeAllChannels"; } QHash<int,Channel*> Connection::channels() { return d->channels; } Channel *Connection::channel(int identifier) { return d->channels.value(identifier); } Connection::Purpose Connection::purpose() const { return d->purpose; } bool Connection::setPurpose(Purpose value) { if (d->purpose == value) return true; switch (value) { case Purpose::Unknown: BUG() << "A connection can't reset to unknown purpose"; return false; case Purpose::KnownContact: if (!hasAuthenticated(HiddenServiceAuth)) { BUG() << "Connection purpose cannot be KnownContact without authenticating a service"; return false; } break; case Purpose::OutboundRequest: if (d->direction != ClientSide) { BUG() << "Connection purpose cannot be OutboundRequest on an inbound connection"; return false; } else if (d->purpose != Purpose::Unknown) { BUG() << "Connection purpose cannot change from" << int(d->purpose) << "to OutboundRequest"; return false; } break; case Purpose::InboundRequest: if (d->direction != ServerSide) { BUG() << "Connection purpose cannot be InboundRequest on an outbound connection"; return false; } else if (d->purpose != Purpose::Unknown) { BUG() << "Connection purpose cannot change from" << int(d->purpose) << "to InboundRequest"; return false; } break; default: BUG() << "Purpose type" << int(value) << "is not defined"; return false; } Purpose old = d->purpose; d->purpose = value; emit purposeChanged(d->purpose, old); return true; } bool Connection::hasAuthenticated(AuthenticationType type) const { return d->authentication.contains(type); } bool Connection::hasAuthenticatedAs(AuthenticationType type, const QString &identity) const { auto it = d->authentication.find(type); if (!identity.isEmpty() && it != d->authentication.end()) return *it == identity; return false; } QString Connection::authenticatedIdentity(AuthenticationType type) const { return d->authentication.value(type); } void Connection::grantAuthentication(AuthenticationType type, const QString &identity) { if (hasAuthenticated(type)) { BUG() << "Tried to redundantly grant" << type << "authentication to connection"; return; } qDebug() << "Granting" << type << "authentication as" << identity << "to connection"; d->authentication.insert(type, identity); emit authenticated(type, identity); }
22,847
6,401
//! @file Font.hpp #pragma once #include "../main.hpp" class Font { private: Font() = default; Font(const char* _name); Font(const Font&) = delete; Font(Font&&) = delete; virtual ~Font(); Font& operator=(const Font&) = delete; Font& operator=(Font&&) = delete; public: //! built-in font static const char* defaultFont; const char* getName() const { return name.c_str(); } TTF_Font* getTTF() { return font; } //! get the size of the given text string in pixels //! @param str the utf-8 string to get the size of //! @param out_w the integer to hold the width //! @param out_h the integer to hold the height //! @return 0 on success, non-zero on error int sizeText(const char* str, int* out_w, int* out_h) const; //! get the height of the font //! @return the font height in pixels int height() const; //! get a Font object from the engine //! @param name The Font name //! @return the Font or nullptr if it could not be retrieved static Font* get(const char* name); //! dump engine's font cache static void dumpCache(); private: std::string name; TTF_Font* font = nullptr; int pointSize = 16; };
1,136
396
// Copyright (c) 2020 [Your Name]. All rights reserved. #include <sudoku/sudoku_parser.h> #include <iostream> #include <fstream> void HandleFile(std::string puzzle); int main(int argc, char** argv) { // There is always at least 1 argument -- the name of the program which we // don't care about if (argc == 1) { std::cout << "Please input a file " << std::endl; std::string file; std::cin >> file; HandleFile(file); } else { for (int i = 1; i < argc; i++) { HandleFile(argv[i]); } } } void HandleFile(std::string puzzle) { std::ifstream puzzle_stream(puzzle); if (puzzle_stream.fail()) { std::cout << "\nInvalid file" << std::endl; } else { sudoku_parser parser; std::istream& input_stream = puzzle_stream; std::ostream& output_stream = std::cout; input_stream >> parser; output_stream << parser; } }
876
315
/** * \file * * \copyright * Copyright (c) 2012-2019, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include "PorousMediaProperties.h" namespace ProcessLib { namespace RichardsComponentTransport { int PorousMediaProperties::getMaterialID(SpatialPosition const& pos) const { int const element_id = pos.getElementID().get(); return _material_ids[element_id]; } MaterialLib::PorousMedium::Porosity const& PorousMediaProperties::getPorosity( double /*t*/, SpatialPosition const& pos) const { return *_porosity_models[getMaterialID(pos)]; } MaterialLib::PorousMedium::Permeability const& PorousMediaProperties::getIntrinsicPermeability( double /*t*/, SpatialPosition const& pos) const { return *_intrinsic_permeability_models[getMaterialID(pos)]; } MaterialLib::PorousMedium::Storage const& PorousMediaProperties::getSpecificStorage(double /*t*/, SpatialPosition const& pos) const { return *_specific_storage_models[getMaterialID(pos)]; } MaterialLib::PorousMedium::CapillaryPressureSaturation const& PorousMediaProperties::getCapillaryPressureSaturationModel( double /*t*/, SpatialPosition const& pos) const { return *_capillary_pressure_saturation_models[getMaterialID(pos)]; } MaterialLib::PorousMedium::RelativePermeability const& PorousMediaProperties::getRelativePermeability( double /*t*/, SpatialPosition const& pos) const { return *_relative_permeability_models[getMaterialID(pos)]; } } // namespace RichardsComponentTransport } // namespace ProcessLib
1,733
534
#include <iostream> #include <cmath> #include <iomanip> using namespace std; int foo_1_6_11z() { double a, b, c, d, e, f, x, y; cin >> a; cin >> b; cin >> c; cin >> d; cin >> e; cin >> f; x = (e*d - b*f) / (d*a - b*c); y = (a*f - e*c) / (d*a - b*c); cout << x << " " << y << endl; }
329
162
#include <imgui/imgui.h> #include "terrain_editor.h" #include "editor/asset_browser.h" #include "editor/asset_compiler.h" #include "editor/entity_folders.h" #include "editor/prefab_system.h" #include "editor/studio_app.h" #include "editor/utils.h" #include "engine/crc32.h" #include "engine/crt.h" #include "engine/engine.h" #include "engine/geometry.h" #include "engine/log.h" #include "engine/os.h" #include "engine/path.h" #include "engine/prefab.h" #include "engine/profiler.h" #include "engine/resource_manager.h" #include "engine/universe.h" #include "physics/physics_scene.h" #include "renderer/culling_system.h" #include "renderer/editor/composite_texture.h" #include "renderer/material.h" #include "renderer/model.h" #include "renderer/render_scene.h" #include "renderer/renderer.h" #include "renderer/terrain.h" #include "renderer/texture.h" #include "stb/stb_image.h" namespace Lumix { static const ComponentType MODEL_INSTANCE_TYPE = reflection::getComponentType("model_instance"); static const ComponentType TERRAIN_TYPE = reflection::getComponentType("terrain"); static const ComponentType HEIGHTFIELD_TYPE = reflection::getComponentType("physical_heightfield"); static const char* HEIGHTMAP_SLOT_NAME = "Heightmap"; static const char* SPLATMAP_SLOT_NAME = "Splatmap"; static const char* DETAIL_ALBEDO_SLOT_NAME = "Detail albedo"; static const char* DETAIL_NORMAL_SLOT_NAME = "Detail normal"; static const float MIN_BRUSH_SIZE = 0.5f; struct PaintTerrainCommand final : IEditorCommand { struct Rectangle { int from_x; int from_y; int to_x; int to_y; }; PaintTerrainCommand(WorldEditor& editor, TerrainEditor::ActionType action_type, u16 grass_mask, u64 textures_mask, const DVec3& hit_pos, const Array<bool>& mask, float radius, float rel_amount, u16 flat_height, Vec3 color, EntityRef terrain, u32 layers_mask, Vec2 fixed_value, bool can_be_merged) : m_world_editor(editor) , m_terrain(terrain) , m_can_be_merged(can_be_merged) , m_new_data(editor.getAllocator()) , m_old_data(editor.getAllocator()) , m_items(editor.getAllocator()) , m_action_type(action_type) , m_textures_mask(textures_mask) , m_grass_mask(grass_mask) , m_mask(editor.getAllocator()) , m_flat_height(flat_height) , m_layers_masks(layers_mask) , m_fixed_value(fixed_value) { m_mask.resize(mask.size()); for (int i = 0; i < mask.size(); ++i) { m_mask[i] = mask[i]; } m_width = m_height = m_x = m_y = -1; Universe& universe = *editor.getUniverse(); const Transform entity_transform = universe.getTransform(terrain).inverted(); RenderScene* scene = (RenderScene*)universe.getScene(TERRAIN_TYPE); DVec3 local_pos = entity_transform.transform(hit_pos); float terrain_size = scene->getTerrainSize(terrain).x; local_pos = local_pos / terrain_size; local_pos.y = -1; Item& item = m_items.emplace(); item.m_local_pos = Vec3(local_pos); item.m_radius = radius / terrain_size; item.m_amount = rel_amount; item.m_color = color; } bool execute() override { if (m_new_data.empty()) { saveOldData(); generateNewData(); } applyData(m_new_data); return true; } void undo() override { applyData(m_old_data); } const char* getType() override { return "paint_terrain"; } bool merge(IEditorCommand& command) override { if (!m_can_be_merged) { return false; } PaintTerrainCommand& my_command = static_cast<PaintTerrainCommand&>(command); if (m_terrain == my_command.m_terrain && m_action_type == my_command.m_action_type && m_textures_mask == my_command.m_textures_mask && m_layers_masks == my_command.m_layers_masks) { my_command.m_items.push(m_items.back()); my_command.resizeData(); my_command.rasterItem(getDestinationTexture(), my_command.m_new_data, m_items.back()); return true; } return false; } private: struct Item { Rectangle getBoundingRectangle(int texture_size) const { Rectangle r; r.from_x = maximum(0, int(texture_size * (m_local_pos.x - m_radius) - 0.5f)); r.from_y = maximum(0, int(texture_size * (m_local_pos.z - m_radius) - 0.5f)); r.to_x = minimum(texture_size, int(texture_size * (m_local_pos.x + m_radius) + 0.5f)); r.to_y = minimum(texture_size, int(texture_size * (m_local_pos.z + m_radius) + 0.5f)); return r; } float m_radius; float m_amount; Vec3 m_local_pos; Vec3 m_color; }; private: Texture* getDestinationTexture() { const char* uniform_name; switch (m_action_type) { case TerrainEditor::REMOVE_GRASS: case TerrainEditor::LAYER: uniform_name = SPLATMAP_SLOT_NAME; break; default: uniform_name = HEIGHTMAP_SLOT_NAME; break; } RenderScene* scene = (RenderScene*)m_world_editor.getUniverse()->getScene(TERRAIN_TYPE); return scene->getTerrainMaterial(m_terrain)->getTextureByName(uniform_name); } u16 computeAverage16(const Texture* texture, int from_x, int to_x, int from_y, int to_y) { ASSERT(texture->format == gpu::TextureFormat::R16); u32 sum = 0; int texture_width = texture->width; for (int i = from_x, end = to_x; i < end; ++i) { for (int j = from_y, end2 = to_y; j < end2; ++j) { sum += ((u16*)texture->getData())[(i + j * texture_width)]; } } return u16(sum / (to_x - from_x) / (to_y - from_y)); } float getAttenuation(Item& item, int i, int j, int texture_size) const { float dist = ((texture_size * item.m_local_pos.x - 0.5f - i) * (texture_size * item.m_local_pos.x - 0.5f - i) + (texture_size * item.m_local_pos.z - 0.5f - j) * (texture_size * item.m_local_pos.z - 0.5f - j)); dist = powf(dist, 4); float max_dist = powf(texture_size * item.m_radius, 8); return 1.0f - minimum(dist / max_dist, 1.0f); } bool isMasked(float x, float y) { if (m_mask.size() == 0) return true; int s = int(sqrtf((float)m_mask.size())); int ix = int(x * s); int iy = int(y * s); return m_mask[int(ix + x * iy)]; } void rasterLayerItem(Texture* texture, Array<u8>& data, Item& item) { int texture_size = texture->width; Rectangle r = item.getBoundingRectangle(texture_size); if (texture->format != gpu::TextureFormat::RGBA8) { ASSERT(false); return; } float fx = 0; float fstepx = 1.0f / (r.to_x - r.from_x); float fstepy = 1.0f / (r.to_y - r.from_y); u8 tex[64]; u32 tex_count = 0; for (u8 i = 0; i < 64; ++i) { if (m_textures_mask & ((u64)1 << i)) { tex[tex_count] = i; ++tex_count; } } if (tex_count == 0) return; for (int i = r.from_x, end = r.to_x; i < end; ++i, fx += fstepx) { float fy = 0; for (int j = r.from_y, end2 = r.to_y; j < end2; ++j, fy += fstepy) { if (!isMasked(fx, fy)) continue; const int offset = 4 * (i - m_x + (j - m_y) * m_width); for (u32 layer = 0; layer < 2; ++layer) { if ((m_layers_masks & (1 << layer)) == 0) continue; const float attenuation = getAttenuation(item, i, j, texture_size); int add = int(attenuation * item.m_amount * 255); if (add <= 0) continue; if (((u64)1 << data[offset]) & m_textures_mask) { if (layer == 1) { if (m_fixed_value.x >= 0) { data[offset + 1] = (u8)clamp(randFloat(m_fixed_value.x, m_fixed_value.y) * 255.f, 0.f, 255.f); } else { data[offset + 1] += minimum(255 - data[offset + 1], add); } } } else { if (layer == 1) { if (m_fixed_value.x >= 0) { data[offset + 1] = (u8)clamp(randFloat(m_fixed_value.x, m_fixed_value.y) * 255.f, 0.f, 255.f); } else { data[offset + 1] = add; } } data[offset] = tex[rand() % tex_count]; } } } } } void rasterGrassItem(Texture* texture, Array<u8>& data, Item& item, bool remove) { int texture_size = texture->width; Rectangle r = item.getBoundingRectangle(texture_size); if (texture->format != gpu::TextureFormat::RGBA8) { ASSERT(false); return; } float fx = 0; float fstepx = 1.0f / (r.to_x - r.from_x); float fstepy = 1.0f / (r.to_y - r.from_y); for (int i = r.from_x, end = r.to_x; i < end; ++i, fx += fstepx) { float fy = 0; for (int j = r.from_y, end2 = r.to_y; j < end2; ++j, fy += fstepy) { if (isMasked(fx, fy)) { int offset = 4 * (i - m_x + (j - m_y) * m_width) + 2; float attenuation = getAttenuation(item, i, j, texture_size); int add = int(attenuation * item.m_amount * 255); if (add > 0) { u16* tmp = ((u16*)&data[offset]); if (remove) { *tmp &= ~m_grass_mask; } else { *tmp |= m_grass_mask; } } } } } } void rasterSmoothHeightItem(Texture* texture, Array<u8>& data, Item& item) { ASSERT(texture->format == gpu::TextureFormat::R16); int texture_size = texture->width; Rectangle rect = item.getBoundingRectangle(texture_size); float avg = computeAverage16(texture, rect.from_x, rect.to_x, rect.from_y, rect.to_y); for (int i = rect.from_x, end = rect.to_x; i < end; ++i) { for (int j = rect.from_y, end2 = rect.to_y; j < end2; ++j) { float attenuation = getAttenuation(item, i, j, texture_size); int offset = i - m_x + (j - m_y) * m_width; u16 x = ((u16*)texture->getData())[(i + j * texture_size)]; x += u16((avg - x) * item.m_amount * attenuation); ((u16*)&data[0])[offset] = x; } } } void rasterFlatHeightItem(Texture* texture, Array<u8>& data, Item& item) { ASSERT(texture->format == gpu::TextureFormat::R16); int texture_size = texture->width; Rectangle rect = item.getBoundingRectangle(texture_size); for (int i = rect.from_x, end = rect.to_x; i < end; ++i) { for (int j = rect.from_y, end2 = rect.to_y; j < end2; ++j) { int offset = i - m_x + (j - m_y) * m_width; float dist = sqrtf( (texture_size * item.m_local_pos.x - 0.5f - i) * (texture_size * item.m_local_pos.x - 0.5f - i) + (texture_size * item.m_local_pos.z - 0.5f - j) * (texture_size * item.m_local_pos.z - 0.5f - j)); float t = (dist - texture_size * item.m_radius * item.m_amount) / (texture_size * item.m_radius * (1 - item.m_amount)); t = clamp(1 - t, 0.0f, 1.0f); u16 old_value = ((u16*)&data[0])[offset]; ((u16*)&data[0])[offset] = (u16)(m_flat_height * t + old_value * (1-t)); } } } void rasterItem(Texture* texture, Array<u8>& data, Item& item) { if (m_action_type == TerrainEditor::LAYER || m_action_type == TerrainEditor::REMOVE_GRASS) { if (m_textures_mask) { rasterLayerItem(texture, data, item); } if (m_grass_mask) { rasterGrassItem(texture, data, item, m_action_type == TerrainEditor::REMOVE_GRASS); } return; } else if (m_action_type == TerrainEditor::SMOOTH_HEIGHT) { rasterSmoothHeightItem(texture, data, item); return; } else if (m_action_type == TerrainEditor::FLAT_HEIGHT) { rasterFlatHeightItem(texture, data, item); return; } ASSERT(texture->format == gpu::TextureFormat::R16); int texture_size = texture->width; Rectangle rect = item.getBoundingRectangle(texture_size); const float STRENGTH_MULTIPLICATOR = 256.0f; float amount = maximum(item.m_amount * item.m_amount * STRENGTH_MULTIPLICATOR, 1.0f); for (int i = rect.from_x, end = rect.to_x; i < end; ++i) { for (int j = rect.from_y, end2 = rect.to_y; j < end2; ++j) { float attenuation = getAttenuation(item, i, j, texture_size); int offset = i - m_x + (j - m_y) * m_width; int add = int(attenuation * amount); u16 x = ((u16*)texture->getData())[(i + j * texture_size)]; x += m_action_type == TerrainEditor::RAISE_HEIGHT ? minimum(add, 0xFFFF - x) : maximum(-add, -x); ((u16*)&data[0])[offset] = x; } } } void generateNewData() { auto texture = getDestinationTexture(); const u32 bpp = gpu::getBytesPerPixel(texture->format); Rectangle rect; getBoundingRectangle(texture, rect); m_new_data.resize(bpp * maximum(1, (rect.to_x - rect.from_x) * (rect.to_y - rect.from_y))); if(m_old_data.size() > 0) { memcpy(&m_new_data[0], &m_old_data[0], m_new_data.size()); } for (int item_index = 0; item_index < m_items.size(); ++item_index) { Item& item = m_items[item_index]; rasterItem(texture, m_new_data, item); } } void saveOldData() { auto texture = getDestinationTexture(); const u32 bpp = gpu::getBytesPerPixel(texture->format); Rectangle rect; getBoundingRectangle(texture, rect); m_x = rect.from_x; m_y = rect.from_y; m_width = rect.to_x - rect.from_x; m_height = rect.to_y - rect.from_y; m_old_data.resize(bpp * (rect.to_x - rect.from_x) * (rect.to_y - rect.from_y)); int index = 0; for (int j = rect.from_y, end2 = rect.to_y; j < end2; ++j) { for (int i = rect.from_x, end = rect.to_x; i < end; ++i) { for (u32 k = 0; k < bpp; ++k) { m_old_data[index] = texture->getData()[(i + j * texture->width) * bpp + k]; ++index; } } } } void applyData(Array<u8>& data) { auto texture = getDestinationTexture(); const u32 bpp = gpu::getBytesPerPixel(texture->format); for (int j = m_y; j < m_y + m_height; ++j) { for (int i = m_x; i < m_x + m_width; ++i) { int index = bpp * (i + j * texture->width); for (u32 k = 0; k < bpp; ++k) { texture->getData()[index + k] = data[bpp * (i - m_x + (j - m_y) * m_width) + k]; } } } texture->onDataUpdated(m_x, m_y, m_width, m_height); if (m_action_type != TerrainEditor::LAYER && m_action_type != TerrainEditor::REMOVE_GRASS) { IScene* scene = m_world_editor.getUniverse()->getScene(crc32("physics")); if (!scene) return; auto* phy_scene = static_cast<PhysicsScene*>(scene); if (!scene->getUniverse().hasComponent(m_terrain, HEIGHTFIELD_TYPE)) return; phy_scene->updateHeighfieldData(m_terrain, m_x, m_y, m_width, m_height, &data[0], bpp); } } void resizeData() { Array<u8> new_data(m_world_editor.getAllocator()); Array<u8> old_data(m_world_editor.getAllocator()); auto texture = getDestinationTexture(); Rectangle rect; getBoundingRectangle(texture, rect); int new_w = rect.to_x - rect.from_x; const u32 bpp = gpu::getBytesPerPixel(texture->format); new_data.resize(bpp * new_w * (rect.to_y - rect.from_y)); old_data.resize(bpp * new_w * (rect.to_y - rect.from_y)); // original for (int row = rect.from_y; row < rect.to_y; ++row) { memcpy(&new_data[(row - rect.from_y) * new_w * bpp], &texture->getData()[row * bpp * texture->width + rect.from_x * bpp], bpp * new_w); memcpy(&old_data[(row - rect.from_y) * new_w * bpp], &texture->getData()[row * bpp * texture->width + rect.from_x * bpp], bpp * new_w); } // new for (int row = 0; row < m_height; ++row) { memcpy(&new_data[((row + m_y - rect.from_y) * new_w + m_x - rect.from_x) * bpp], &m_new_data[row * bpp * m_width], bpp * m_width); memcpy(&old_data[((row + m_y - rect.from_y) * new_w + m_x - rect.from_x) * bpp], &m_old_data[row * bpp * m_width], bpp * m_width); } m_x = rect.from_x; m_y = rect.from_y; m_height = rect.to_y - rect.from_y; m_width = rect.to_x - rect.from_x; m_new_data.swap(new_data); m_old_data.swap(old_data); } void getBoundingRectangle(Texture* texture, Rectangle& rect) { int s = texture->width; Item& item = m_items[0]; rect.from_x = maximum(int(s * (item.m_local_pos.x - item.m_radius) - 0.5f), 0); rect.from_y = maximum(int(s * (item.m_local_pos.z - item.m_radius) - 0.5f), 0); rect.to_x = minimum(1 + int(s * (item.m_local_pos.x + item.m_radius) + 0.5f), texture->width); rect.to_y = minimum(1 + int(s * (item.m_local_pos.z + item.m_radius) + 0.5f), texture->height); for (int i = 1; i < m_items.size(); ++i) { Item& item = m_items[i]; rect.from_x = minimum(int(s * (item.m_local_pos.x - item.m_radius) - 0.5f), rect.from_x); rect.to_x = maximum(1 + int(s * (item.m_local_pos.x + item.m_radius) + 0.5f), rect.to_x); rect.from_y = minimum(int(s * (item.m_local_pos.z - item.m_radius) - 0.5f), rect.from_y); rect.to_y = maximum(1 + int(s * (item.m_local_pos.z + item.m_radius) + 0.5f), rect.to_y); } rect.from_x = maximum(rect.from_x, 0); rect.to_x = minimum(rect.to_x, texture->width); rect.from_y = maximum(rect.from_y, 0); rect.to_y = minimum(rect.to_y, texture->height); } private: WorldEditor& m_world_editor; Array<u8> m_new_data; Array<u8> m_old_data; u64 m_textures_mask; u16 m_grass_mask; int m_width; int m_height; int m_x; int m_y; TerrainEditor::ActionType m_action_type; Array<Item> m_items; EntityRef m_terrain; Array<bool> m_mask; u16 m_flat_height; u32 m_layers_masks; Vec2 m_fixed_value; bool m_can_be_merged; }; TerrainEditor::~TerrainEditor() { m_app.removeAction(&m_smooth_terrain_action); m_app.removeAction(&m_lower_terrain_action); m_app.removeAction(&m_remove_grass_action); m_app.removeAction(&m_remove_entity_action); if (m_brush_texture) { m_brush_texture->destroy(); LUMIX_DELETE(m_app.getAllocator(), m_brush_texture); } m_app.removePlugin(*this); } TerrainEditor::TerrainEditor(StudioApp& app) : m_app(app) , m_color(1, 1, 1) , m_current_brush(0) , m_selected_prefabs(app.getAllocator()) , m_brush_mask(app.getAllocator()) , m_brush_texture(nullptr) , m_flat_height(0) , m_is_enabled(false) , m_size_spread(1, 1) , m_y_spread(0, 0) , m_albedo_composite(app.getAllocator()) { m_smooth_terrain_action.init("Smooth terrain", "Terrain editor - smooth", "smoothTerrain", "", false); m_lower_terrain_action.init("Lower terrain", "Terrain editor - lower", "lowerTerrain", "", false); m_remove_grass_action.init("Remove grass from terrain", "Terrain editor - remove grass", "removeGrassFromTerrain", "", false); m_remove_entity_action.init("Remove entities from terrain", "Terrain editor - remove entities", "removeEntitiesFromTerrain", "", false); app.addAction(&m_smooth_terrain_action); app.addAction(&m_lower_terrain_action); app.addAction(&m_remove_grass_action); app.addAction(&m_remove_entity_action); app.addPlugin(*this); m_terrain_brush_size = 10; m_terrain_brush_strength = 0.1f; m_textures_mask = 0b1; m_layers_mask = 0b1; m_grass_mask = 1; m_is_align_with_normal = false; m_is_rotate_x = false; m_is_rotate_y = false; m_is_rotate_z = false; m_rotate_x_spread = m_rotate_y_spread = m_rotate_z_spread = Vec2(0, PI * 2); } void TerrainEditor::increaseBrushSize() { if (m_terrain_brush_size < 10) { ++m_terrain_brush_size; return; } m_terrain_brush_size = minimum(100.0f, m_terrain_brush_size + 10); } void TerrainEditor::decreaseBrushSize() { if (m_terrain_brush_size < 10) { m_terrain_brush_size = maximum(MIN_BRUSH_SIZE, m_terrain_brush_size - 1.0f); return; } m_terrain_brush_size = maximum(MIN_BRUSH_SIZE, m_terrain_brush_size - 10.0f); } void TerrainEditor::drawCursor(RenderScene& scene, EntityRef entity, const DVec3& center) const { PROFILE_FUNCTION(); Terrain* terrain = scene.getTerrain(entity); constexpr int SLICE_COUNT = 30; constexpr float angle_step = PI * 2 / SLICE_COUNT; if (m_mode == Mode::HEIGHT && m_is_flat_height && ImGui::GetIO().KeyCtrl) { scene.addDebugCross(center, 1.0f, 0xff0000ff); return; } float brush_size = m_terrain_brush_size; const Vec3 local_center = Vec3(getRelativePosition(center, entity, scene.getUniverse())); const Transform terrain_transform = scene.getUniverse().getTransform(entity); for (int i = 0; i < SLICE_COUNT + 1; ++i) { const float angle = i * angle_step; const float next_angle = i * angle_step + angle_step; Vec3 local_from = local_center + Vec3(cosf(angle), 0, sinf(angle)) * brush_size; local_from.y = terrain->getHeight(local_from.x, local_from.z); local_from.y += 0.25f; Vec3 local_to = local_center + Vec3(cosf(next_angle), 0, sinf(next_angle)) * brush_size; local_to.y = terrain->getHeight(local_to.x, local_to.z); local_to.y += 0.25f; const DVec3 from = terrain_transform.transform(local_from); const DVec3 to = terrain_transform.transform(local_to); scene.addDebugLine(from, to, 0xffff0000); } const Vec3 rel_pos = Vec3(terrain_transform.inverted().transform(center)); const i32 w = terrain->getWidth(); const i32 h = terrain->getHeight(); const float scale = terrain->getXZScale(); const IVec3 p = IVec3(rel_pos / scale); const i32 half_extents = i32(1 + brush_size / scale); for (i32 j = p.z - half_extents; j <= p.z + half_extents; ++j) { for (i32 i = p.x - half_extents; i <= p.x + half_extents; ++i) { DVec3 p00(i * scale, 0, j * scale); DVec3 p10((i + 1) * scale, 0, j * scale); DVec3 p11((i + 1) * scale, 0, (j + 1) * scale); DVec3 p01(i * scale, 0, (j + 1) * scale); p00.y = terrain->getHeight(i, j); p10.y = terrain->getHeight(i + 1, j); p11.y = terrain->getHeight(i + 1, j + 1); p01.y = terrain->getHeight(i, j + 1); p00 = terrain_transform.transform(p00); p10 = terrain_transform.transform(p10); p01 = terrain_transform.transform(p01); p11 = terrain_transform.transform(p11); scene.addDebugLine(p10, p01, 0xff800000); scene.addDebugLine(p10, p11, 0xff800000); scene.addDebugLine(p00, p10, 0xff800000); scene.addDebugLine(p01, p11, 0xff800000); scene.addDebugLine(p00, p01, 0xff800000); } } } DVec3 TerrainEditor::getRelativePosition(const DVec3& world_pos, EntityRef terrain, Universe& universe) const { const Transform transform = universe.getTransform(terrain); const Transform inv_transform = transform.inverted(); return inv_transform.transform(world_pos); } u16 TerrainEditor::getHeight(const DVec3& world_pos, RenderScene* scene, EntityRef terrain) const { const DVec3 rel_pos = getRelativePosition(world_pos, terrain, scene->getUniverse()); ComponentUID cmp; cmp.entity = terrain; cmp.scene = scene; cmp.type = TERRAIN_TYPE; Texture* heightmap = getMaterial(cmp)->getTextureByName(HEIGHTMAP_SLOT_NAME); if (!heightmap) return 0; u16* data = (u16*)heightmap->getData(); float scale = scene->getTerrainXZScale(terrain); return data[int(rel_pos.x / scale) + int(rel_pos.z / scale) * heightmap->width]; } bool TerrainEditor::onMouseDown(UniverseView& view, int x, int y) { if (!m_is_enabled) return false; WorldEditor& editor = view.getEditor(); const Array<EntityRef>& selected_entities = editor.getSelectedEntities(); if (selected_entities.size() != 1) return false; Universe& universe = *editor.getUniverse(); bool is_terrain = universe.hasComponent(selected_entities[0], TERRAIN_TYPE); if (!is_terrain) return false; RenderScene* scene = (RenderScene*)universe.getScene(TERRAIN_TYPE); DVec3 origin; Vec3 dir; view.getViewport().getRay({(float)x, (float)y}, origin, dir); const RayCastModelHit hit = scene->castRayTerrain(selected_entities[0], origin, dir); if (!hit.is_hit) return false; const DVec3 hit_pos = hit.origin + hit.dir * hit.t; switch(m_mode) { case Mode::ENTITY: if (m_remove_entity_action.isActive()) { removeEntities(hit_pos, editor); } else { paintEntities(hit_pos, editor, selected_entities[0]); } break; case Mode::HEIGHT: if (m_is_flat_height) { if (ImGui::GetIO().KeyCtrl) { m_flat_height = getHeight(hit_pos, scene, selected_entities[0]); } else { paint(hit_pos, TerrainEditor::FLAT_HEIGHT, false, selected_entities[0], editor); } } else { TerrainEditor::ActionType action = TerrainEditor::RAISE_HEIGHT; if (m_lower_terrain_action.isActive()) { action = TerrainEditor::LOWER_HEIGHT; } else if (m_smooth_terrain_action.isActive()) { action = TerrainEditor::SMOOTH_HEIGHT; } paint(hit_pos, action, false, selected_entities[0], editor); break; } break; case Mode::LAYER: TerrainEditor::ActionType action = TerrainEditor::LAYER; if (m_remove_grass_action.isActive()) { action = TerrainEditor::REMOVE_GRASS; } paint(hit_pos, action, false, selected_entities[0], editor); break; } return true; } static void getProjections(const Vec3& axis, const Vec3 vertices[8], float& min, float& max) { max = dot(vertices[0], axis); min = max; for(int i = 1; i < 8; ++i) { float d = dot(vertices[i], axis); min = minimum(d, min); max = maximum(d, max); } } static bool overlaps(float min1, float max1, float min2, float max2) { return (min1 <= min2 && min2 <= max1) || (min2 <= min1 && min1 <= max2); } static bool testOBBCollision(const AABB& a, const Matrix& mtx_b, const AABB& b) { Vec3 box_a_points[8]; Vec3 box_b_points[8]; a.getCorners(Matrix::IDENTITY, box_a_points); b.getCorners(mtx_b, box_b_points); const Vec3 normals[] = {Vec3(1, 0, 0), Vec3(0, 1, 0), Vec3(0, 0, 1)}; for(int i = 0; i < 3; i++) { float box_a_min, box_a_max, box_b_min, box_b_max; getProjections(normals[i], box_a_points, box_a_min, box_a_max); getProjections(normals[i], box_b_points, box_b_min, box_b_max); if(!overlaps(box_a_min, box_a_max, box_b_min, box_b_max)) { return false; } } Vec3 normals_b[] = { normalize(mtx_b.getXVector()), normalize(mtx_b.getYVector()), normalize(mtx_b.getZVector())}; for(int i = 0; i < 3; i++) { float box_a_min, box_a_max, box_b_min, box_b_max; getProjections(normals_b[i], box_a_points, box_a_min, box_a_max); getProjections(normals_b[i], box_b_points, box_b_min, box_b_max); if(!overlaps(box_a_min, box_a_max, box_b_min, box_b_max)) { return false; } } return true; } void TerrainEditor::removeEntities(const DVec3& hit_pos, WorldEditor& editor) const { if (m_selected_prefabs.empty()) return; PrefabSystem& prefab_system = editor.getPrefabSystem(); PROFILE_FUNCTION(); Universe& universe = *editor.getUniverse(); RenderScene* scene = static_cast<RenderScene*>(universe.getScene(TERRAIN_TYPE)); ShiftedFrustum frustum; frustum.computeOrtho(hit_pos, Vec3(0, 0, 1), Vec3(0, 1, 0), m_terrain_brush_size, m_terrain_brush_size, -m_terrain_brush_size, m_terrain_brush_size); const AABB brush_aabb(Vec3(-m_terrain_brush_size), Vec3(m_terrain_brush_size)); CullResult* meshes = scene->getRenderables(frustum, RenderableTypes::MESH); if(meshes) { meshes->merge(scene->getRenderables(frustum, RenderableTypes::MESH_GROUP)); } else { meshes = scene->getRenderables(frustum, RenderableTypes::MESH_GROUP); } if(meshes) { meshes->merge(scene->getRenderables(frustum, RenderableTypes::MESH_MATERIAL_OVERRIDE)); } else { meshes = scene->getRenderables(frustum, RenderableTypes::MESH_MATERIAL_OVERRIDE); } if(!meshes) return; editor.beginCommandGroup("remove_entities"); if (m_selected_prefabs.empty()) { meshes->forEach([&](EntityRef entity){ if (prefab_system.getPrefab(entity) == 0) return; const Model* model = scene->getModelInstanceModel(entity); const AABB entity_aabb = model ? model->getAABB() : AABB(Vec3::ZERO, Vec3::ZERO); const bool collide = testOBBCollision(brush_aabb, universe.getRelativeMatrix(entity, hit_pos), entity_aabb); if (collide) editor.destroyEntities(&entity, 1); }); } else { meshes->forEach([&](EntityRef entity){ for (auto* res : m_selected_prefabs) { if ((prefab_system.getPrefab(entity) & 0xffffFFFF) == res->getPath().getHash()) { const Model* model = scene->getModelInstanceModel(entity); const AABB entity_aabb = model ? model->getAABB() : AABB(Vec3::ZERO, Vec3::ZERO); const bool collide = testOBBCollision(brush_aabb, universe.getRelativeMatrix(entity, hit_pos), entity_aabb); if (collide) editor.destroyEntities(&entity, 1); } } }); } editor.endCommandGroup(); meshes->free(scene->getEngine().getPageAllocator()); } static bool isOBBCollision(RenderScene& scene, const CullResult* meshes, const Transform& model_tr, Model* model, bool ignore_not_in_folder, const EntityFolders& folders, EntityFolders::FolderID folder) { float radius_a_squared = model->getOriginBoundingRadius() * model_tr.scale; radius_a_squared = radius_a_squared * radius_a_squared; Universe& universe = scene.getUniverse(); Span<const ModelInstance> model_instances = scene.getModelInstances(); const Transform* transforms = universe.getTransforms(); while(meshes) { const EntityRef* entities = meshes->entities; for (u32 i = 0, c = meshes->header.count; i < c; ++i) { const EntityRef mesh = entities[i]; // we resolve collisions when painting by removing recently added mesh, but we do not refresh `meshes` // so it can contain invalid entities if (!universe.hasEntity(mesh)) continue; const ModelInstance& model_instance = model_instances[mesh.index]; const Transform& tr_b = transforms[mesh.index]; const float radius_b = model_instance.model->getOriginBoundingRadius() * tr_b.scale; const float radius_squared = radius_a_squared + radius_b * radius_b; if (squaredLength(model_tr.pos - tr_b.pos) < radius_squared) { const Transform rel_tr = model_tr.inverted() * tr_b; Matrix mtx = rel_tr.rot.toMatrix(); mtx.multiply3x3(rel_tr.scale); mtx.setTranslation(Vec3(rel_tr.pos)); if (testOBBCollision(model->getAABB(), mtx, model_instance.model->getAABB())) { if (ignore_not_in_folder && folders.getFolder(EntityRef{mesh.index}) != folder) { continue; } return true; } } } meshes = meshes->header.next; } return false; } static bool areAllReady(Span<PrefabResource*> prefabs) { for (PrefabResource* p : prefabs) if (!p->isReady()) return false; return true; } void TerrainEditor::paintEntities(const DVec3& hit_pos, WorldEditor& editor, EntityRef terrain) const { PROFILE_FUNCTION(); if (m_selected_prefabs.empty()) return; if (!areAllReady(m_selected_prefabs)) return; auto& prefab_system = editor.getPrefabSystem(); editor.beginCommandGroup("paint_entities"); { Universe& universe = *editor.getUniverse(); RenderScene* scene = static_cast<RenderScene*>(universe.getScene(TERRAIN_TYPE)); const Transform terrain_tr = universe.getTransform(terrain); const Transform inv_terrain_tr = terrain_tr.inverted(); ShiftedFrustum frustum; frustum.computeOrtho(hit_pos, Vec3(0, 0, 1), Vec3(0, 1, 0), m_terrain_brush_size, m_terrain_brush_size, -m_terrain_brush_size, m_terrain_brush_size); CullResult* meshes = scene->getRenderables(frustum, RenderableTypes::MESH); if (meshes) meshes->merge(scene->getRenderables(frustum, RenderableTypes::MESH_GROUP)); else meshes = scene->getRenderables(frustum, RenderableTypes::MESH_GROUP); if (meshes) meshes->merge(scene->getRenderables(frustum, RenderableTypes::MESH_MATERIAL_OVERRIDE)); else meshes = scene->getRenderables(frustum, RenderableTypes::MESH_MATERIAL_OVERRIDE); const EntityFolders& folders = editor.getEntityFolders(); const EntityFolders::FolderID folder = folders.getSelectedFolder(); Vec2 size = scene->getTerrainSize(terrain); float scale = 1.0f - maximum(0.01f, m_terrain_brush_strength); for (int i = 0; i <= m_terrain_brush_size * m_terrain_brush_size / 100.0f * m_terrain_brush_strength; ++i) { const float angle = randFloat(0, PI * 2); const float dist = randFloat(0, 1.0f) * m_terrain_brush_size; const float y = randFloat(m_y_spread.x, m_y_spread.y); DVec3 pos(hit_pos.x + cosf(angle) * dist, 0, hit_pos.z + sinf(angle) * dist); const Vec3 terrain_pos = Vec3(inv_terrain_tr.transform(pos)); if (terrain_pos.x >= 0 && terrain_pos.z >= 0 && terrain_pos.x <= size.x && terrain_pos.z <= size.y) { pos.y = scene->getTerrainHeightAt(terrain, terrain_pos.x, terrain_pos.z) + y; pos.y += terrain_tr.pos.y; Quat rot(0, 0, 0, 1); if(m_is_align_with_normal) { Vec3 normal = scene->getTerrainNormalAt(terrain, terrain_pos.x, terrain_pos.z); Vec3 dir = normalize(cross(normal, Vec3(1, 0, 0))); Matrix mtx = Matrix::IDENTITY; mtx.setXVector(cross(normal, dir)); mtx.setYVector(normal); mtx.setXVector(dir); rot = mtx.getRotation(); } else { if (m_is_rotate_x) { float angle = randFloat(m_rotate_x_spread.x, m_rotate_x_spread.y); Quat q(Vec3(1, 0, 0), angle); rot = q * rot; } if (m_is_rotate_y) { float angle = randFloat(m_rotate_y_spread.x, m_rotate_y_spread.y); Quat q(Vec3(0, 1, 0), angle); rot = q * rot; } if (m_is_rotate_z) { float angle = randFloat(m_rotate_z_spread.x, m_rotate_z_spread.y); Quat q(rot.rotate(Vec3(0, 0, 1)), angle); rot = q * rot; } } float size = randFloat(m_size_spread.x, m_size_spread.y); int random_idx = rand(0, m_selected_prefabs.size() - 1); if (!m_selected_prefabs[random_idx]) continue; const EntityPtr entity = prefab_system.instantiatePrefab(*m_selected_prefabs[random_idx], pos, rot, size); if (entity.isValid()) { if (universe.hasComponent((EntityRef)entity, MODEL_INSTANCE_TYPE)) { Model* model = scene->getModelInstanceModel((EntityRef)entity); const Transform tr = { pos, rot, size * scale }; if (isOBBCollision(*scene, meshes, tr, model, m_ignore_entities_not_in_folder, folders, folder)) { editor.undo(); } } } } } meshes->free(m_app.getEngine().getPageAllocator()); } editor.endCommandGroup(); } void TerrainEditor::onMouseMove(UniverseView& view, int x, int y, int, int) { if (!m_is_enabled) return; WorldEditor& editor = view.getEditor(); const Array<EntityRef>& selected_entities = editor.getSelectedEntities(); if (selected_entities.size() != 1) return; const EntityRef entity = selected_entities[0]; Universe& universe = *editor.getUniverse(); if (!universe.hasComponent(entity, TERRAIN_TYPE)) return; RenderScene* scene = (RenderScene*)universe.getScene(TERRAIN_TYPE); DVec3 origin; Vec3 dir; view.getViewport().getRay({(float)x, (float)y}, origin, dir); const RayCastModelHit hit = scene->castRayTerrain(entity, origin, dir); if (!hit.is_hit) return; if (hit.entity != entity) return; const DVec3 hit_pos = hit.origin + hit.dir * hit.t; switch(m_mode) { case Mode::ENTITY: if (m_remove_entity_action.isActive()) { removeEntities(hit_pos, editor); } else { paintEntities(hit_pos, editor, entity); } break; case Mode::HEIGHT: if (m_is_flat_height) { if (ImGui::GetIO().KeyCtrl) { m_flat_height = getHeight(hit_pos, scene, entity); } else { paint(hit_pos, TerrainEditor::FLAT_HEIGHT, true, selected_entities[0], editor); } } else { TerrainEditor::ActionType action = TerrainEditor::RAISE_HEIGHT; if (m_lower_terrain_action.isActive()) { action = TerrainEditor::LOWER_HEIGHT; } else if (m_smooth_terrain_action.isActive()) { action = TerrainEditor::SMOOTH_HEIGHT; } paint(hit_pos, action, true, selected_entities[0], editor); break; } break; case Mode::LAYER: TerrainEditor::ActionType action = TerrainEditor::LAYER; if (m_remove_grass_action.isActive()) { action = TerrainEditor::REMOVE_GRASS; } paint(hit_pos, action, true, selected_entities[0], editor); break; } } Material* TerrainEditor::getMaterial(ComponentUID cmp) const { if (!cmp.isValid()) return nullptr; auto* scene = static_cast<RenderScene*>(cmp.scene); return scene->getTerrainMaterial((EntityRef)cmp.entity); } static Array<u8> getFileContent(const char* path, IAllocator& allocator) { Array<u8> res(allocator); os::InputFile file; if (!file.open(path)) return res; res.resize((u32)file.size()); if (!file.read(res.begin(), res.byte_size())) res.clear(); file.close(); return res; } void TerrainEditor::layerGUI(ComponentUID cmp) { m_mode = Mode::LAYER; RenderScene* scene = static_cast<RenderScene*>(cmp.scene); Material* material = scene->getTerrainMaterial((EntityRef)cmp.entity); if (!material) return; if (material->getTextureByName(SPLATMAP_SLOT_NAME) && ImGuiEx::ToolbarButton(m_app.getBigIconFont(), ICON_FA_SAVE, ImGui::GetStyle().Colors[ImGuiCol_Text], "Save")) { material->getTextureByName(SPLATMAP_SLOT_NAME)->save(); } if (m_brush_texture) { ImGui::Image(m_brush_texture->handle, ImVec2(100, 100)); if (ImGuiEx::ToolbarButton(m_app.getBigIconFont(), ICON_FA_TIMES, ImGui::GetStyle().Colors[ImGuiCol_Text], "Clear brush mask")) { m_brush_texture->destroy(); LUMIX_DELETE(m_app.getAllocator(), m_brush_texture); m_brush_mask.clear(); m_brush_texture = nullptr; } ImGui::SameLine(); } ImGui::SameLine(); if (ImGuiEx::ToolbarButton(m_app.getBigIconFont(), ICON_FA_MASK, ImGui::GetStyle().Colors[ImGuiCol_Text], "Select brush mask")) { char filename[LUMIX_MAX_PATH]; if (os::getOpenFilename(Span(filename), "All\0*.*\0", nullptr)) { int image_width; int image_height; int image_comp; Array<u8> tmp = getFileContent(filename, m_app.getAllocator()); auto* data = stbi_load_from_memory(tmp.begin(), tmp.byte_size(), &image_width, &image_height, &image_comp, 4); if (data) { m_brush_mask.resize(image_width * image_height); for (int j = 0; j < image_width; ++j) { for (int i = 0; i < image_width; ++i) { m_brush_mask[i + j * image_width] = data[image_comp * (i + j * image_width)] > 128; } } Engine& engine = m_app.getEngine(); ResourceManagerHub& rm = engine.getResourceManager(); if (m_brush_texture) { m_brush_texture->destroy(); LUMIX_DELETE(m_app.getAllocator(), m_brush_texture); } Lumix::IPlugin* plugin = engine.getPluginManager().getPlugin("renderer"); Renderer& renderer = *static_cast<Renderer*>(plugin); m_brush_texture = LUMIX_NEW(m_app.getAllocator(), Texture)( Path("brush_texture"), *rm.get(Texture::TYPE), renderer, m_app.getAllocator()); m_brush_texture->create(image_width, image_height, gpu::TextureFormat::RGBA8, data, image_width * image_height * 4); stbi_image_free(data); } } } char grass_mode_shortcut[64]; if (m_remove_entity_action.shortcutText(Span(grass_mode_shortcut))) { ImGuiEx::Label(StaticString<64>("Grass mode (", grass_mode_shortcut, ")")); ImGui::TextUnformatted(m_remove_entity_action.isActive() ? "Remove" : "Add"); } int type_count = scene->getGrassCount((EntityRef)cmp.entity); for (int i = 0; i < type_count; ++i) { ImGui::SameLine(); if (i == 0 || ImGui::GetContentRegionAvail().x < 50) ImGui::NewLine(); bool b = (m_grass_mask & (1 << i)) != 0; m_app.getAssetBrowser().tile(scene->getGrassPath((EntityRef)cmp.entity, i), b); if (ImGui::IsItemClicked()) { if (!ImGui::GetIO().KeyCtrl) m_grass_mask = 0; if (b) { m_grass_mask &= ~(1 << i); } else { m_grass_mask |= 1 << i; } } } Texture* albedo = material->getTextureByName(DETAIL_ALBEDO_SLOT_NAME); Texture* normal = material->getTextureByName(DETAIL_NORMAL_SLOT_NAME); if (!albedo) { ImGui::Text("No detail albedo in material %s", material->getPath().c_str()); return; } if (albedo->isFailure()) { ImGui::Text("%s failed to load", albedo->getPath().c_str()); return; } if (!albedo->isReady()) { ImGui::Text("Loading %s...", albedo->getPath().c_str()); return; } if (!normal) { ImGui::Text("No detail normal in material %s", material->getPath().c_str()); return; } if (normal->isFailure()) { ImGui::Text("%s failed to load", normal->getPath().c_str()); return; } if (!normal->isReady()) { ImGui::Text("Loading %s...", normal->getPath().c_str()); return; } if (albedo->depth != normal->depth) { ImGui::TextWrapped(ICON_FA_EXCLAMATION_TRIANGLE " albedo texture %s has different number of layers than normal texture %s" , albedo->getPath().c_str() , normal->getPath().c_str()); } bool primary = m_layers_mask & 0b1; bool secondary = m_layers_mask & 0b10; // TODO shader does not handle secondary surfaces now, so pretend they don't exist // uncomment once shader is ready m_layers_mask = 0xb11; /*ImGuiEx::Label("Primary surface"); ImGui::Checkbox("##prim", &primary); ImGuiEx::Label("Secondary surface"); ImGui::Checkbox("##sec", &secondary); if (secondary) { bool use = m_fixed_value.x >= 0; ImGuiEx::Label("Use fixed value"); if (ImGui::Checkbox("##fxd", &use)) { m_fixed_value.x = use ? 0.f : -1.f; } if (m_fixed_value.x >= 0) { ImGuiEx::Label("Min/max"); ImGui::DragFloatRange2("##minmax", &m_fixed_value.x, &m_fixed_value.y, 0.01f, 0, 1); } }*/ FileSystem& fs = m_app.getEngine().getFileSystem(); if (albedo->getPath() != m_albedo_composite_path) { m_albedo_composite.loadSync(fs, albedo->getPath()); m_albedo_composite_path = albedo->getPath(); } m_layers_mask = (primary ? 1 : 0) | (secondary ? 0b10 : 0); for (i32 i = 0; i < m_albedo_composite.layers.size(); ++i) { ImGui::SameLine(); if (i == 0 || ImGui::GetContentRegionAvail().x < 50) ImGui::NewLine(); bool b = m_textures_mask & ((u64)1 << i); m_app.getAssetBrowser().tile(m_albedo_composite.layers[i].red.path, b); if (ImGui::IsItemClicked()) { if (!ImGui::GetIO().KeyCtrl) m_textures_mask = 0; if (b) m_textures_mask &= ~((u64)1 << i); else m_textures_mask |= (u64)1 << i; } if (ImGui::IsItemClicked(ImGuiMouseButton_Right)) { ImGui::OpenPopup(StaticString<8>("ctx", i)); } if (ImGui::BeginPopup(StaticString<8>("ctx", i))) { if (ImGui::Selectable("Remove surface")) { compositeTextureRemoveLayer(albedo->getPath(), i); compositeTextureRemoveLayer(normal->getPath(), i); m_albedo_composite_path = ""; } ImGui::EndPopup(); } } if (albedo->depth < 255) { if (ImGui::Button(ICON_FA_PLUS "Add surface")) ImGui::OpenPopup("Add surface"); } ImGui::SetNextWindowSizeConstraints(ImVec2(200, 100), ImVec2(FLT_MAX, FLT_MAX)); if (ImGui::BeginPopupModal("Add surface")) { ImGuiEx::Label("Albedo"); m_app.getAssetBrowser().resourceInput("albedo", Span(m_add_layer_popup.albedo), Texture::TYPE); ImGuiEx::Label("Normal"); m_app.getAssetBrowser().resourceInput("normal", Span(m_add_layer_popup.normal), Texture::TYPE); if (ImGui::Button(ICON_FA_PLUS "Add")) { saveCompositeTexture(albedo->getPath(), m_add_layer_popup.albedo); saveCompositeTexture(normal->getPath(), m_add_layer_popup.normal); m_albedo_composite_path = ""; } ImGui::SameLine(); if (ImGui::Button(ICON_FA_TIMES "Cancel")) { ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } } void TerrainEditor::compositeTextureRemoveLayer(const Path& path, i32 layer) const { CompositeTexture texture(m_app.getAllocator()); FileSystem& fs = m_app.getEngine().getFileSystem(); if (!texture.loadSync(fs, path)) { logError("Failed to load ", path); } else { texture.layers.erase(layer); if (!texture.save(fs, path)) { logError("Failed to save ", path); } } } void TerrainEditor::saveCompositeTexture(const Path& path, const char* channel) const { CompositeTexture texture(m_app.getAllocator()); FileSystem& fs = m_app.getEngine().getFileSystem(); if (!texture.loadSync(fs, path)) { logError("Failed to load ", path); } else { CompositeTexture::Layer new_layer; new_layer.red.path = channel; new_layer.red.src_channel = 0; new_layer.green.path = channel; new_layer.green.src_channel = 1; new_layer.blue.path = channel; new_layer.blue.src_channel = 2; new_layer.alpha.path = channel; new_layer.alpha.src_channel = 3; texture.layers.push(new_layer); if (!texture.save(fs, path)) { logError("Failed to save ", path); } } } void TerrainEditor::entityGUI() { m_mode = Mode::ENTITY; ImGuiEx::Label("Ignore other folders (?)"); if (ImGui::IsItemHovered()) { ImGui::SetTooltip("When placing entities, ignore collisions with " "entities in other folders than the currently selected folder " "in hierarchy view"); } ImGui::Checkbox("##ignore_filter", &m_ignore_entities_not_in_folder); static char filter[100] = {0}; const float w = ImGui::CalcTextSize(ICON_FA_TIMES).x + ImGui::GetStyle().ItemSpacing.x * 2; ImGui::SetNextItemWidth(-w); ImGui::InputTextWithHint("##filter", "Filter", filter, sizeof(filter)); ImGui::SameLine(); if (ImGuiEx::IconButton(ICON_FA_TIMES, "Clear filter")) { filter[0] = '\0'; } static ImVec2 size(-1, 200); if (ImGui::ListBoxHeader("##prefabs", size)) { auto& resources = m_app.getAssetCompiler().lockResources(); u32 count = 0; for (const AssetCompiler::ResourceItem& res : resources) { if (res.type != PrefabResource::TYPE) continue; ++count; if (filter[0] != 0 && stristr(res.path.c_str(), filter) == nullptr) continue; int selected_idx = m_selected_prefabs.find([&](PrefabResource* r) -> bool { return r && r->getPath() == res.path; }); bool selected = selected_idx >= 0; const char* loading_str = selected_idx >= 0 && m_selected_prefabs[selected_idx]->isEmpty() ? " - loading..." : ""; StaticString<LUMIX_MAX_PATH + 15> label(res.path.c_str(), loading_str); if (ImGui::Selectable(label, &selected)) { if (selected) { ResourceManagerHub& manager = m_app.getEngine().getResourceManager(); PrefabResource* prefab = manager.load<PrefabResource>(res.path); if (!ImGui::GetIO().KeyShift) { for (PrefabResource* res : m_selected_prefabs) res->decRefCount(); m_selected_prefabs.clear(); } m_selected_prefabs.push(prefab); } else { PrefabResource* prefab = m_selected_prefabs[selected_idx]; if (!ImGui::GetIO().KeyShift) { for (PrefabResource* res : m_selected_prefabs) res->decRefCount(); m_selected_prefabs.clear(); } else { m_selected_prefabs.swapAndPop(selected_idx); prefab->decRefCount(); } } } } if (count == 0) ImGui::TextUnformatted("No prefabs"); m_app.getAssetCompiler().unlockResources(); ImGui::ListBoxFooter(); } ImGuiEx::HSplitter("after_prefab", &size); if(ImGui::Checkbox("Align with normal", &m_is_align_with_normal)) { if(m_is_align_with_normal) m_is_rotate_x = m_is_rotate_y = m_is_rotate_z = false; } if (ImGui::Checkbox("Rotate around X", &m_is_rotate_x)) { if (m_is_rotate_x) m_is_align_with_normal = false; } if (m_is_rotate_x) { Vec2 tmp = m_rotate_x_spread; tmp.x = radiansToDegrees(tmp.x); tmp.y = radiansToDegrees(tmp.y); if (ImGui::DragFloatRange2("Rotate X spread", &tmp.x, &tmp.y)) { m_rotate_x_spread.x = degreesToRadians(tmp.x); m_rotate_x_spread.y = degreesToRadians(tmp.y); } } if (ImGui::Checkbox("Rotate around Y", &m_is_rotate_y)) { if (m_is_rotate_y) m_is_align_with_normal = false; } if (m_is_rotate_y) { Vec2 tmp = m_rotate_y_spread; tmp.x = radiansToDegrees(tmp.x); tmp.y = radiansToDegrees(tmp.y); if (ImGui::DragFloatRange2("Rotate Y spread", &tmp.x, &tmp.y)) { m_rotate_y_spread.x = degreesToRadians(tmp.x); m_rotate_y_spread.y = degreesToRadians(tmp.y); } } if(ImGui::Checkbox("Rotate around Z", &m_is_rotate_z)) { if(m_is_rotate_z) m_is_align_with_normal = false; } if (m_is_rotate_z) { Vec2 tmp = m_rotate_z_spread; tmp.x = radiansToDegrees(tmp.x); tmp.y = radiansToDegrees(tmp.y); if (ImGui::DragFloatRange2("Rotate Z spread", &tmp.x, &tmp.y)) { m_rotate_z_spread.x = degreesToRadians(tmp.x); m_rotate_z_spread.y = degreesToRadians(tmp.y); } } ImGui::DragFloatRange2("Size spread", &m_size_spread.x, &m_size_spread.y, 0.01f); m_size_spread.x = minimum(m_size_spread.x, m_size_spread.y); ImGui::DragFloatRange2("Y spread", &m_y_spread.x, &m_y_spread.y, 0.01f); m_y_spread.x = minimum(m_y_spread.x, m_y_spread.y); } void TerrainEditor::exportToOBJ(ComponentUID cmp) const { char filename[LUMIX_MAX_PATH]; if (!os::getSaveFilename(Span(filename), "Wavefront obj\0*.obj", "obj")) return; os::OutputFile file; if (!file.open(filename)) { logError("Failed to open ", filename); return; } char basename[LUMIX_MAX_PATH]; copyString(Span(basename), Path::getBasename(filename)); auto* scene = static_cast<RenderScene*>(cmp.scene); const EntityRef e = (EntityRef)cmp.entity; const Texture* hm = getMaterial(cmp)->getTextureByName(HEIGHTMAP_SLOT_NAME); OutputMemoryStream blob(m_app.getAllocator()); blob.reserve(8 * 1024 * 1024); blob << "mtllib " << basename << ".mtl\n"; blob << "o Terrain\n"; const float xz_scale = scene->getTerrainXZScale(e); const float y_scale = scene->getTerrainYScale(e); ASSERT(hm->format == gpu::TextureFormat::R16); const u16* hm_data = (const u16*)hm->getData(); for (u32 j = 0; j < hm->height; ++j) { for (u32 i = 0; i < hm->width; ++i) { const float height = hm_data[i + j * hm->width] / float(0xffff) * y_scale; blob << "v " << i * xz_scale << " " << height << " " << j * xz_scale << "\n"; } } for (u32 j = 0; j < hm->height; ++j) { for (u32 i = 0; i < hm->width; ++i) { blob << "vt " << i / float(hm->width - 1) << " " << j / float(hm->height - 1) << "\n"; } } blob << "usemtl Material\n"; auto write_face_vertex = [&](u32 idx){ blob << idx << "/" << idx; }; for (u32 j = 0; j < hm->height - 1; ++j) { for (u32 i = 0; i < hm->width - 1; ++i) { const u32 idx = i + j * hm->width + 1; blob << "f "; write_face_vertex(idx); blob << " "; write_face_vertex(idx + 1); blob << " "; write_face_vertex(idx + 1 + hm->width); blob << "\n"; blob << "f "; write_face_vertex(idx); blob << " "; write_face_vertex(idx + 1 + hm->width); blob << " "; write_face_vertex(idx + hm->width); blob << "\n"; } } if (!file.write(blob.data(), blob.size())) { logError("Failed to write ", filename); } file.close(); char dir[LUMIX_MAX_PATH]; copyString(Span(dir), Path::getDir(filename)); StaticString<LUMIX_MAX_PATH> mtl_filename(dir, basename, ".mtl"); if (!file.open(mtl_filename)) { logError("Failed to open ", mtl_filename); return; } blob.clear(); blob << "newmtl Material"; if (!file.write(blob.data(), blob.size())) { logError("Failed to write ", mtl_filename); } file.close(); } void TerrainEditor::onGUI(ComponentUID cmp, WorldEditor& editor) { ASSERT(cmp.type == TERRAIN_TYPE); auto* scene = static_cast<RenderScene*>(cmp.scene); ImGui::Unindent(); if (!ImGui::CollapsingHeader("Terrain editor")) { ImGui::Indent(); return; } ImGui::Indent(); ImGuiEx::Label("Enable"); ImGui::Checkbox("##ed_enabled", &m_is_enabled); if (!m_is_enabled) return; Material* material = getMaterial(cmp); if (!material) { ImGui::Text("No material"); return; } if (!material->getTextureByName(HEIGHTMAP_SLOT_NAME)) { ImGui::Text("No heightmap"); return; } if (ImGui::Button(ICON_FA_FILE_EXPORT)) exportToOBJ(cmp); ImGuiEx::Label("Brush size"); ImGui::DragFloat("##br_size", &m_terrain_brush_size, 1, MIN_BRUSH_SIZE, FLT_MAX); ImGuiEx::Label("Brush strength"); ImGui::SliderFloat("##br_str", &m_terrain_brush_strength, 0, 1.0f); if (ImGui::BeginTabBar("brush_type")) { if (ImGui::BeginTabItem("Height")) { m_mode = Mode::HEIGHT; if (ImGuiEx::ToolbarButton(m_app.getBigIconFont(), ICON_FA_SAVE, ImGui::GetStyle().Colors[ImGuiCol_Text], "Save")) { material->getTextureByName(HEIGHTMAP_SLOT_NAME)->save(); } ImGuiEx::Label("Mode"); if (m_is_flat_height) { ImGui::TextUnformatted("flat"); } else if (m_smooth_terrain_action.isActive()) { char shortcut[64]; if (m_smooth_terrain_action.shortcutText(Span(shortcut))) { ImGui::Text("smooth (%s)", shortcut); } else { ImGui::TextUnformatted("smooth"); } } else if (m_lower_terrain_action.isActive()) { char shortcut[64]; if (m_lower_terrain_action.shortcutText(Span(shortcut))) { ImGui::Text("lower (%s)", shortcut); } else { ImGui::TextUnformatted("lower"); } } else { ImGui::TextUnformatted("raise"); } ImGui::Checkbox("Flat", &m_is_flat_height); if (m_is_flat_height) { ImGui::SameLine(); ImGui::Text("- Press Ctrl to pick height"); } ImGui::EndTabItem(); } if (ImGui::BeginTabItem("Surface and grass")) { layerGUI(cmp); ImGui::EndTabItem(); } if (ImGui::BeginTabItem("Entity")) { entityGUI(); ImGui::EndTabItem(); } ImGui::EndTabBar(); } if (!cmp.isValid() || !m_is_enabled) { return; } const Vec2 mp = editor.getView().getMousePos(); Universe& universe = *editor.getUniverse(); for(auto entity : editor.getSelectedEntities()) { if (!universe.hasComponent(entity, TERRAIN_TYPE)) continue; RenderScene* scene = static_cast<RenderScene*>(universe.getScene(TERRAIN_TYPE)); DVec3 origin; Vec3 dir; editor.getView().getViewport().getRay(mp, origin, dir); const RayCastModelHit hit = scene->castRayTerrain(entity, origin, dir); if(hit.is_hit) { DVec3 center = hit.origin + hit.dir * hit.t; drawCursor(*scene, entity, center); return; } } } void TerrainEditor::paint(const DVec3& hit_pos, ActionType action_type, bool old_stroke, EntityRef terrain, WorldEditor& editor) const { UniquePtr<PaintTerrainCommand> command = UniquePtr<PaintTerrainCommand>::create(editor.getAllocator(), editor, action_type, m_grass_mask, (u64)m_textures_mask, hit_pos, m_brush_mask, m_terrain_brush_size, m_terrain_brush_strength, m_flat_height, m_color, terrain, m_layers_mask, m_fixed_value, old_stroke); editor.executeCommand(command.move()); } } // namespace Lumix
53,038
23,625
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.Networking.UnityWebRequest #include "UnityEngine/Networking/UnityWebRequest.hpp" // Including type: System.Enum #include "System/Enum.hpp" // Completed includes // Type namespace: UnityEngine.Networking namespace UnityEngine::Networking { // Size: 0x4 #pragma pack(push, 1) // Autogenerated type: UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError // [TokenAttribute] Offset: FFFFFFFF struct UnityWebRequest::UnityWebRequestError/*, public System::Enum*/ { public: // public System.Int32 value__ // Size: 0x4 // Offset: 0x0 int value; // Field size check static_assert(sizeof(int) == 0x4); // Creating value type constructor for type: UnityWebRequestError constexpr UnityWebRequestError(int value_ = {}) noexcept : value{value_} {} // Creating interface conversion operator: operator System::Enum operator System::Enum() noexcept { return *reinterpret_cast<System::Enum*>(this); } // Creating conversion operator: operator int constexpr operator int() const noexcept { return value; } // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError OK static constexpr const int OK = 0; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError OK static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_OK(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError OK static void _set_OK(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Unknown static constexpr const int Unknown = 1; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Unknown static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_Unknown(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Unknown static void _set_Unknown(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SDKError static constexpr const int SDKError = 2; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SDKError static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_SDKError(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SDKError static void _set_SDKError(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError UnsupportedProtocol static constexpr const int UnsupportedProtocol = 3; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError UnsupportedProtocol static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_UnsupportedProtocol(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError UnsupportedProtocol static void _set_UnsupportedProtocol(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError MalformattedUrl static constexpr const int MalformattedUrl = 4; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError MalformattedUrl static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_MalformattedUrl(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError MalformattedUrl static void _set_MalformattedUrl(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotResolveProxy static constexpr const int CannotResolveProxy = 5; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotResolveProxy static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_CannotResolveProxy(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotResolveProxy static void _set_CannotResolveProxy(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotResolveHost static constexpr const int CannotResolveHost = 6; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotResolveHost static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_CannotResolveHost(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotResolveHost static void _set_CannotResolveHost(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotConnectToHost static constexpr const int CannotConnectToHost = 7; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotConnectToHost static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_CannotConnectToHost(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotConnectToHost static void _set_CannotConnectToHost(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError AccessDenied static constexpr const int AccessDenied = 8; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError AccessDenied static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_AccessDenied(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError AccessDenied static void _set_AccessDenied(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError GenericHttpError static constexpr const int GenericHttpError = 9; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError GenericHttpError static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_GenericHttpError(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError GenericHttpError static void _set_GenericHttpError(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError WriteError static constexpr const int WriteError = 10; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError WriteError static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_WriteError(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError WriteError static void _set_WriteError(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError ReadError static constexpr const int ReadError = 11; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError ReadError static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_ReadError(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError ReadError static void _set_ReadError(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError OutOfMemory static constexpr const int OutOfMemory = 12; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError OutOfMemory static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_OutOfMemory(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError OutOfMemory static void _set_OutOfMemory(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Timeout static constexpr const int Timeout = 13; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Timeout static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_Timeout(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Timeout static void _set_Timeout(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError HTTPPostError static constexpr const int HTTPPostError = 14; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError HTTPPostError static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_HTTPPostError(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError HTTPPostError static void _set_HTTPPostError(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCannotConnect static constexpr const int SSLCannotConnect = 15; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCannotConnect static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_SSLCannotConnect(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCannotConnect static void _set_SSLCannotConnect(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Aborted static constexpr const int Aborted = 16; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Aborted static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_Aborted(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Aborted static void _set_Aborted(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError TooManyRedirects static constexpr const int TooManyRedirects = 17; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError TooManyRedirects static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_TooManyRedirects(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError TooManyRedirects static void _set_TooManyRedirects(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError ReceivedNoData static constexpr const int ReceivedNoData = 18; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError ReceivedNoData static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_ReceivedNoData(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError ReceivedNoData static void _set_ReceivedNoData(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLNotSupported static constexpr const int SSLNotSupported = 19; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLNotSupported static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_SSLNotSupported(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLNotSupported static void _set_SSLNotSupported(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError FailedToSendData static constexpr const int FailedToSendData = 20; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError FailedToSendData static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_FailedToSendData(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError FailedToSendData static void _set_FailedToSendData(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError FailedToReceiveData static constexpr const int FailedToReceiveData = 21; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError FailedToReceiveData static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_FailedToReceiveData(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError FailedToReceiveData static void _set_FailedToReceiveData(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCertificateError static constexpr const int SSLCertificateError = 22; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCertificateError static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_SSLCertificateError(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCertificateError static void _set_SSLCertificateError(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCipherNotAvailable static constexpr const int SSLCipherNotAvailable = 23; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCipherNotAvailable static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_SSLCipherNotAvailable(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCipherNotAvailable static void _set_SSLCipherNotAvailable(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCACertError static constexpr const int SSLCACertError = 24; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCACertError static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_SSLCACertError(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCACertError static void _set_SSLCACertError(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError UnrecognizedContentEncoding static constexpr const int UnrecognizedContentEncoding = 25; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError UnrecognizedContentEncoding static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_UnrecognizedContentEncoding(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError UnrecognizedContentEncoding static void _set_UnrecognizedContentEncoding(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError LoginFailed static constexpr const int LoginFailed = 26; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError LoginFailed static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_LoginFailed(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError LoginFailed static void _set_LoginFailed(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLShutdownFailed static constexpr const int SSLShutdownFailed = 27; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLShutdownFailed static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_SSLShutdownFailed(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLShutdownFailed static void _set_SSLShutdownFailed(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError NoInternetConnection static constexpr const int NoInternetConnection = 28; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError NoInternetConnection static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_NoInternetConnection(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError NoInternetConnection static void _set_NoInternetConnection(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // Get instance field reference: public System.Int32 value__ int& dyn_value__(); }; // UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError #pragma pack(pop) static check_size<sizeof(UnityWebRequest::UnityWebRequestError), 0 + sizeof(int)> __UnityEngine_Networking_UnityWebRequest_UnityWebRequestErrorSizeCheck; static_assert(sizeof(UnityWebRequest::UnityWebRequestError) == 0x4); } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError, "UnityEngine.Networking", "UnityWebRequest/UnityWebRequestError"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
21,971
5,974
#include "estimators.h"
24
11
//////////////////////////////////////////////////////////////////////////////// // TensionFieldTheory.hh //////////////////////////////////////////////////////////////////////////////// /*! @file // Implements a field theory relaxed energy density for a fully generic, // potentially anisotropic, 2D "C-based" energy density. Here "C-based" means // the energy density is expressed in terms of the Cauchy-Green deformation // tensor. // Our implementation is based on the applied math paper // [Pipkin1994:"Relaxed energy densities for large deformations of membranes"] // whose optimality criterion for the wrinkling strain we use to obtain a // slightly less expensive optimization formulation. // // We implement the second derivatives needed for a Newton-based equilibrium // solver; these are nontrivial since they must account for the dependence of // the wrinkling strain on C. */ // Author: Julian Panetta (jpanetta), julian.panetta@gmail.com // Created: 06/28/2020 19:01:21 //////////////////////////////////////////////////////////////////////////////// #ifndef TENSIONFIELDTHEORY_HH #define TENSIONFIELDTHEORY_HH #include <Eigen/Dense> #include <MeshFEM/Types.hh> #include <stdexcept> #include <iostream> #include <MeshFEM/newton_optimizer/dense_newton.hh> template<class _Psi> struct IsotropicWrinkleStrainProblem { using Psi = _Psi; using Real = typename Psi::Real; using VarType = Eigen::Matrix<Real, 1, 1>; using HessType = Eigen::Matrix<Real, 1, 1>; using M2d = Mat2_T<Real>; IsotropicWrinkleStrainProblem(Psi &psi, const M2d &C, const Vec2_T<Real> &n) : m_psi(psi), m_C(C), m_nn(n * n.transpose()) { } void setC(const M2d &C) { m_C = C; } const M2d &getC() const { return m_C; } size_t numVars() const { return 1; } void setVars(const VarType &vars) { m_a = vars; m_psi.setC(m_C + m_a[0] * m_nn); } const VarType &getVars() const { return m_a; } Real energy() const { return m_psi.energy(); } VarType gradient() const { return VarType(0.5 * doubleContract(m_nn, m_psi.PK2Stress()) ); } HessType hessian() const { return HessType(0.5 * doubleContract(m_psi.delta_PK2Stress(m_nn), m_nn)); } void solve() { dense_newton(*this, /* maxIter = */ 100, /*gradTol = */1e-14, /* verbose = */ false); } EIGEN_MAKE_ALIGNED_OPERATOR_NEW private: VarType m_a = VarType::Zero(); Psi &m_psi; M2d m_C, m_nn; }; template<class _Psi> struct AnisotropicWrinkleStrainProblem { using Psi = _Psi; using Real = typename Psi::Real; using VarType = Vec2_T<Real>; using HessType = Mat2_T<Real>; using M2d = Mat2_T<Real>; AnisotropicWrinkleStrainProblem(Psi &psi, const M2d &C, const VarType &n) : m_psi(psi), m_C(C), m_ntilde(n) { } void setC(const M2d &C) { m_C = C; } const M2d &getC() const { return m_C; } size_t numVars() const { return 2; } void setVars(const VarType &vars) { m_ntilde = vars; m_psi.setC(m_C + m_ntilde * m_ntilde.transpose()); } const VarType &getVars() const { return m_ntilde; } Real energy() const { return m_psi.energy(); } // S : (0.5 * (n delta_n^T + delta_n n^T)) // = S : n delta_n^T = (S n) . delta_n VarType gradient() const { return m_psi.PK2Stress() * m_ntilde; } // psi(n * n^T) // dpsi = n^T psi'(n * n^T) . dn // d2psi = dn_a^T psi'(n * n^T) . dn_b + n^T (psi'' : (n * dn_a^T)) . dn_b // = psi' : (dn_a dn_b^T) + ... HessType hessian() const { HessType h = m_psi.PK2Stress(); // psi' : (dn_a dn_b^T) M2d dnn(M2d::Zero()); dnn.col(0) = m_ntilde; h.row(0) += m_ntilde.transpose() * m_psi.delta_PK2Stress(symmetrized_x2(dnn)); dnn.col(0).setZero(); dnn.col(1) = m_ntilde; h.row(1) += m_ntilde.transpose() * m_psi.delta_PK2Stress(symmetrized_x2(dnn)); if (h.array().isNaN().any()) throw std::runtime_error("NaN Hessian"); if (std::abs(h(0, 1) - h(1, 0)) > 1e-10 * std::abs(h(1, 0)) + 1e-10) throw std::runtime_error("Asymmetric Hessian"); return h; } void solve() { dense_newton(*this, /* maxIter = */ 100, /*gradTol = */1e-14, /* verbose = */ false); } EIGEN_MAKE_ALIGNED_OPERATOR_NEW private: Psi &m_psi; M2d m_C; VarType m_ntilde = VarType::Zero(); }; // Define a relaxed 2D C-based energy based on a given 2D C-based energy `Psi_C` template<class Psi_C> struct RelaxedEnergyDensity { static_assert(Psi_C::EDType == EDensityType::CBased, "Tension field theory only works on C-based energy densities"); static constexpr size_t N = Psi_C::N; static constexpr size_t Dimension = N; static constexpr EDensityType EDType = EDensityType::CBased; using Matrix = typename Psi_C::Matrix; using Real = typename Psi_C::Real; using ES = Eigen::SelfAdjointEigenSolver<Matrix>; using V2d = Vec2_T<Real>; static_assert(N == 2, "Tension field theory relaxation only defined for 2D energies"); static std::string name() { return std::string("Relaxed") + Psi_C::name(); } // Forward all constructor arguments to m_psi template<class... Args> RelaxedEnergyDensity(Args&&... args) : m_psi(std::forward<Args>(args)...), m_anisoProb(m_psi, Matrix::Identity(), V2d::Zero()) { } // We need a custom copy constructor since m_anisoProb contains a // reference to this->m_psi RelaxedEnergyDensity(const RelaxedEnergyDensity &b) : m_psi(b.m_psi), m_anisoProb(m_psi, Matrix::Identity(), V2d::Zero()) { setC(b.m_C); } // Note: UninitializedDeformationTag argument must be a rvalue reference so it exactly // matches the type passed by the constructor call // RelaxedEnergyDensity(b, UninitializedDeformationTag()); otherwise the // perfect forwarding constructor above will be preferred for this call, // incorrectly forwarding b to Psi's constructor. RelaxedEnergyDensity(const RelaxedEnergyDensity &b, UninitializedDeformationTag &&) : m_psi(b.m_psi, UninitializedDeformationTag()), m_anisoProb(m_psi, Matrix::Identity(), V2d::Zero()) { setC(b.m_C); } void setC(const Matrix &C) { m_C = C; if (!relaxationEnabled()) { m_psi.setC(C); return; } // Note: Eigen guarantees eigenvalues are sorted in ascending order. ES C_eigs(C); // std::cout << "C eigenvalues: " << C_eigs.eigenvalues().transpose() << std::endl; // Detect full compression if (C_eigs.eigenvalues()[1] < 1) { m_tensionState = 0; m_wrinkleStrain = -C; return; } m_psi.setC(C); ES S_eigs(m_psi.PK2Stress()); // Detect full tension // std::cout << "S eigenvalues: " << S_eigs.eigenvalues().transpose() << std::endl; if (S_eigs.eigenvalues()[0] >= -1e-12) { m_tensionState = 2; m_wrinkleStrain.setZero(); return; } // Handle partial tension m_tensionState = 1; // In the isotropic case, principal stress and strain directions // coincide, and the wrinkling strain must be in the form // a n n^T, where n is the eigenvector corresponding to the smallest // stress eigenvalue and a > 0 is an unknown. // This simplifies the determination of wrinkling strain to a convex // 1D optimization problem that we solve with Newton's method. V2d n = S_eigs.eigenvectors().col(0); using IWSP = IsotropicWrinkleStrainProblem<Psi_C>; IWSP isoProb(m_psi, C, n); // std::cout << "Solving isotropic wrinkle strain problem" << std::endl; isoProb.setVars(typename IWSP::VarType{0.0}); isoProb.solve(); Real a = isoProb.getVars()[0]; if (a < 0) throw std::runtime_error("Invalid wrinkle strain"); // We use this isotropic assumption to obtain initial guess for the // anisotropic case, where the wrinkling strain is in the form // n_tilde n_tilde^T // with a 2D vector n_tilde as the unknown. m_anisoProb.setC(C); // std::cout << "Solving anisotropic wrinkle strain problem" << std::endl; m_anisoProb.setVars(std::sqrt(a) * n); m_anisoProb.solve(); auto ntilde = m_anisoProb.getVars(); m_wrinkleStrain = -ntilde * ntilde.transpose(); // { // ES S_eigs_new(m_psi.PK2Stress()); // std::cout << "new S eigenvalues: " << S_eigs_new.eigenvalues().transpose() << std::endl; // } } Real energy() const { if (relaxationEnabled() && fullCompression()) return 0.0; return m_psi.energy(); } Matrix PK2Stress() const { if (relaxationEnabled() && fullCompression()) return Matrix::Zero(); // By envelope theorem, the wrinkling strain's perturbation can be // neglected, and the stress is simply the stress of the underlying // material model evaluated on the "elastic strain". return m_psi.PK2Stress(); } template<class Mat_> Matrix delta_PK2Stress(const Mat_ &dC) const { if (!relaxationEnabled() || fullTension()) return m_psi.delta_PK2Stress(dC); if (fullCompression()) return Matrix::Zero(); // n solves m_anisoProb: // (psi') n = 0 // delta_n solves: // (psi'' : dC + n delta n) n + (psi') delta_n = 0 // (psi'' : n delta_n) n + (psi') delta_n = -(psi'' : dC) n // H delta_n = -(psi'' : dC) n auto ntilde = m_anisoProb.getVars(); V2d delta_n = -m_anisoProb.hessian().inverse() * (m_psi.delta_PK2Stress(dC.matrix()) * ntilde); // In the partial tension case, we need to account for the wrinkling // strain perturbation. return m_psi.delta_PK2Stress(dC.matrix() + ntilde * delta_n.transpose() + delta_n * ntilde.transpose()); } template<class Mat_, class Mat2_> Matrix delta2_PK2Stress(const Mat_ &/* dF_a */, const Mat2_ &/* dF_b */) const { throw std::runtime_error("Unimplemented"); } V2d principalBiotStrains() const { ES es(m_C); return es.eigenvalues().array().sqrt() - 1.0; } const Matrix &wrinkleStrain() const { return m_wrinkleStrain; } bool fullCompression() const { return m_tensionState == 0; } bool partialTension() const { return m_tensionState == 1; } bool fullTension() const { return m_tensionState == 2; } int tensionState() const { return m_tensionState; } // Copying is super dangerous since we m_anisoProb uses a reference to m_psi... RelaxedEnergyDensity &operator=(const RelaxedEnergyDensity &) = delete; // Direct access to the energy density for debugging or // to change the material properties Psi_C &psi() { return m_psi; } const Psi_C &psi() const { return m_psi; } // Turn on or off the tension field theory approximation void setRelaxationEnabled(bool enable) { m_relaxationEnabled = enable; setC(m_C); } bool relaxationEnabled() const { return m_relaxationEnabled; } void copyMaterialProperties(const RelaxedEnergyDensity &other) { psi().copyMaterialProperties(other.psi()); } EIGEN_MAKE_ALIGNED_OPERATOR_NEW private: // Tension state: // 0: compression in all directions // 1: partial tension // 2: tension in all directions int m_tensionState = 2; Psi_C m_psi; Matrix m_wrinkleStrain = Matrix::Zero(), m_C = Matrix::Identity(); // full Cauchy-Green deformation tensor. AnisotropicWrinkleStrainProblem<Psi_C> m_anisoProb; bool m_relaxationEnabled = true; }; #endif /* end of include guard: TENSIONFIELDTHEORY_HH */
11,956
4,179
#include "XBaseParser.h" #include <vector> #include <string> #include <memory.h> #include <stdio.h> #include <stdlib.h> #if defined(_MSC_VER) || defined(__MINGW32__) #include <io.h> #else #include <unistd.h> #endif #include <fcntl.h> #include <osg/Notify> namespace ESRIShape { void XBaseHeader::print() { osg::notify(osg::INFO) << "VersionNumber = " << (int) _versionNumber << std::endl << "LastUpdate = " << 1900 + (int) _lastUpdate[0] << "/" << (int) _lastUpdate[1] << "/" << (int) _lastUpdate[2] << std::endl << "NumRecord = " << _numRecord << std::endl << "HeaderLength = " << _headerLength << std::endl << "RecordLength = " << _recordLength << std::endl; } bool XBaseHeader::read(int fd) { int nbytes = 0; if ((nbytes = ::read( fd, &_versionNumber, sizeof(_versionNumber))) <= 0) return false; if ((nbytes = ::read( fd, &_lastUpdate, sizeof(_lastUpdate))) <= 0) return false; if ((nbytes = ::read( fd, &_numRecord, sizeof(_numRecord))) <= 0) return false; if ((nbytes = ::read( fd, &_headerLength, sizeof(_headerLength))) <= 0) return false; if ((nbytes = ::read( fd, &_recordLength, sizeof(_recordLength))) <= 0) return false; if ((nbytes = ::read( fd, &_reserved, sizeof(_reserved))) <= 0) return false; if ((nbytes = ::read( fd, &_incompleteTransaction, sizeof(_incompleteTransaction))) <= 0) return false; if ((nbytes = ::read( fd, &_encryptionFlag, sizeof(_encryptionFlag))) <= 0) return false; if ((nbytes = ::read( fd, &_freeRecordThread, sizeof(_freeRecordThread))) <= 0) return false; if ((nbytes = ::read( fd, &_reservedMultiUser, sizeof(_reservedMultiUser))) <= 0) return false; if ((nbytes = ::read( fd, &_mdxflag, sizeof(_mdxflag))) <= 0) return false; if ((nbytes = ::read( fd, &_languageDriver, sizeof(_languageDriver))) <= 0) return false; if ((nbytes = ::read( fd, &_reserved2, sizeof(_reserved2))) <= 0) return false; return true; } void XBaseFieldDescriptor::print() { osg::notify(osg::INFO) << "name = " << _name << std::endl << "type = " << _fieldType << std::endl << "length = " << (int) _fieldLength << std::endl << "decimalCount = " << (int) _decimalCount << std::endl << "workAreaID = " << (int) _workAreaID << std::endl << "setFieldFlag = " << (int) _setFieldFlag << std::endl << "indexFieldFlag = " << (int) _indexFieldFlag << std::endl; } bool XBaseFieldDescriptor::read(int fd) { int nbytes = 0; if ((nbytes = ::read( fd, &_name, sizeof(_name))) <= 0) return false; if ((nbytes = ::read( fd, &_fieldType, sizeof(_fieldType))) <= 0) return false; if ((nbytes = ::read( fd, &_fieldDataAddress, sizeof(_fieldDataAddress))) <= 0) return false; if ((nbytes = ::read( fd, &_fieldLength, sizeof(_fieldLength))) <= 0) return false; if ((nbytes = ::read( fd, &_decimalCount, sizeof(_decimalCount))) <= 0) return false; if ((nbytes = ::read( fd, &_reservedMultiUser, sizeof(_reservedMultiUser))) <= 0) return false; if ((nbytes = ::read( fd, &_workAreaID, sizeof(_workAreaID))) <= 0) return false; if ((nbytes = ::read( fd, &_reservedMultiUser2, sizeof(_reservedMultiUser2))) <= 0) return false; if ((nbytes = ::read( fd, &_setFieldFlag, sizeof(_setFieldFlag))) <= 0) return false; if ((nbytes = ::read( fd, &_reserved, sizeof(_reserved))) <= 0) return false; if ((nbytes = ::read( fd, &_indexFieldFlag, sizeof(_indexFieldFlag))) <= 0) return false; return true; } XBaseParser::XBaseParser(const std::string fileName): _valid(false) { int fd = 0; if (fileName.empty() == false) { #ifdef WIN32 if( (fd = open( fileName.c_str(), O_RDONLY | O_BINARY )) <= 0 ) #else if( (fd = ::open( fileName.c_str(), O_RDONLY )) <= 0 ) #endif { perror( fileName.c_str() ); return ; } } _valid = parse(fd); } bool XBaseParser::parse(int fd) { int nbytes; XBaseHeader _xBaseHeader; std::vector<XBaseFieldDescriptor> _xBaseFieldDescriptorList; XBaseFieldDescriptor _xBaseFieldDescriptorTmp; // ** read the header if (_xBaseHeader.read(fd) == false) return false; // _xBaseHeader.print(); // ** read field descriptor bool fieldDescriptorDone = false; Byte nullTerminator; while (fieldDescriptorDone == false) { // ** store the field descriptor if (_xBaseFieldDescriptorTmp.read(fd) == false) return false; _xBaseFieldDescriptorList.push_back(_xBaseFieldDescriptorTmp); // _xBaseFieldDescriptorTmp.print(); // ** check the terminator if ((nbytes = ::read( fd, &nullTerminator, sizeof(nullTerminator))) <= 0) return false; if (nullTerminator == 0x0D) fieldDescriptorDone = true; else ::lseek( fd, -1, SEEK_CUR); } // ** move to the end of the Header ::lseek( fd, _xBaseHeader._headerLength + 1, SEEK_SET); // ** reserve AttributeListList _shapeAttributeListList.reserve(_xBaseHeader._numRecord); // ** read each record and store them in the ShapeAttributeListList char* record = new char[_xBaseHeader._recordLength]; std::vector<XBaseFieldDescriptor>::iterator it, end = _xBaseFieldDescriptorList.end(); for (Integer i = 0; i < _xBaseHeader._numRecord; ++i) { if ((nbytes = ::read( fd, record, _xBaseHeader._recordLength)) <= 0) return false; char * recordPtr = record; osgSim::ShapeAttributeList * shapeAttributeList = new osgSim::ShapeAttributeList; shapeAttributeList->reserve(_xBaseFieldDescriptorList.size()); for (it = _xBaseFieldDescriptorList.begin(); it != end; ++it) { switch (it->_fieldType) { case 'C': { char* str = new char[it->_fieldLength + 1]; memcpy(str, recordPtr, it->_fieldLength); str[it->_fieldLength] = 0; shapeAttributeList->push_back(osgSim::ShapeAttribute((const char *) it->_name, (char*) str)); delete [] str; break; } case 'N': { char* number = new char[it->_fieldLength + 1]; memcpy(number, recordPtr, it->_fieldLength); number[it->_fieldLength] = 0; shapeAttributeList->push_back(osgSim::ShapeAttribute((const char *) it->_name, (int) atoi(number))); delete [] number; break; } case 'I': { int number; memcpy(&number, record, it->_fieldLength); shapeAttributeList->push_back(osgSim::ShapeAttribute((const char *) it->_name, (int) number)); break; } case 'O': { double number; memcpy(&number, record, it->_fieldLength); shapeAttributeList->push_back(osgSim::ShapeAttribute((const char *) it->_name, (double) number)); break; } default: { osg::notify(osg::WARN) << "ESRIShape::XBaseParser : record type " << it->_fieldType << "not supported, skipped" << std::endl; shapeAttributeList->push_back(osgSim::ShapeAttribute((const char *) it->_name, (double) 0)); break; } } recordPtr += it->_fieldLength; } _shapeAttributeListList.push_back(shapeAttributeList); } delete [] record; close (fd); return true; } }
8,119
2,513
/* * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Dathrohan_Balnazzar SD%Complete: 95 SDComment: Possibly need to fix/improve summons after death SDCategory: Stratholme EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" enum eEnums { //Dathrohan spells SPELL_CRUSADERSHAMMER = 17286, //AOE stun SPELL_CRUSADERSTRIKE = 17281, SPELL_HOLYSTRIKE = 17284, //weapon dmg +3 //Transform SPELL_BALNAZZARTRANSFORM = 17288, //restore full HP/mana, trigger spell Balnazzar Transform Stun //Balnazzar spells SPELL_SHADOWSHOCK = 17399, SPELL_MINDBLAST = 17287, SPELL_PSYCHICSCREAM = 13704, SPELL_SLEEP = 12098, SPELL_MINDCONTROL = 15690, NPC_DATHROHAN = 10812, NPC_BALNAZZAR = 10813, NPC_ZOMBIE = 10698 //probably incorrect }; struct SummonDef { float m_fX, m_fY, m_fZ, m_fOrient; }; SummonDef m_aSummonPoint[]= { {3444.156f, -3090.626f, 135.002f, 2.240f}, //G1 front, left {3449.123f, -3087.009f, 135.002f, 2.240f}, //G1 front, right {3446.246f, -3093.466f, 135.002f, 2.240f}, //G1 back left {3451.160f, -3089.904f, 135.002f, 2.240f}, //G1 back, right {3457.995f, -3080.916f, 135.002f, 3.784f}, //G2 front, left {3454.302f, -3076.330f, 135.002f, 3.784f}, //G2 front, right {3460.975f, -3078.901f, 135.002f, 3.784f}, //G2 back left {3457.338f, -3073.979f, 135.002f, 3.784f} //G2 back, right }; class boss_dathrohan_balnazzar : public CreatureScript { public: boss_dathrohan_balnazzar() : CreatureScript("boss_dathrohan_balnazzar") { } CreatureAI* GetAI(Creature* creature) const { return new boss_dathrohan_balnazzarAI (creature); } struct boss_dathrohan_balnazzarAI : public ScriptedAI { boss_dathrohan_balnazzarAI(Creature* creature) : ScriptedAI(creature) {} uint32 m_uiCrusadersHammer_Timer; uint32 m_uiCrusaderStrike_Timer; uint32 m_uiMindBlast_Timer; uint32 m_uiHolyStrike_Timer; uint32 m_uiShadowShock_Timer; uint32 m_uiPsychicScream_Timer; uint32 m_uiDeepSleep_Timer; uint32 m_uiMindControl_Timer; bool m_bTransformed; void Reset() { m_uiCrusadersHammer_Timer = 8000; m_uiCrusaderStrike_Timer = 12000; m_uiMindBlast_Timer = 6000; m_uiHolyStrike_Timer = 18000; m_uiShadowShock_Timer = 4000; m_uiPsychicScream_Timer = 16000; m_uiDeepSleep_Timer = 20000; m_uiMindControl_Timer = 10000; m_bTransformed = false; if (me->GetEntry() == NPC_BALNAZZAR) me->UpdateEntry(NPC_DATHROHAN); } void JustDied(Unit* /*killer*/) { static uint32 uiCount = sizeof(m_aSummonPoint)/sizeof(SummonDef); for (uint8 i=0; i<uiCount; ++i) me->SummonCreature(NPC_ZOMBIE, m_aSummonPoint[i].m_fX, m_aSummonPoint[i].m_fY, m_aSummonPoint[i].m_fZ, m_aSummonPoint[i].m_fOrient, TEMPSUMMON_TIMED_DESPAWN, HOUR*IN_MILLISECONDS); } void EnterCombat(Unit* /*who*/) { } void UpdateAI(const uint32 uiDiff) { if (!UpdateVictim()) return; //START NOT TRANSFORMED if (!m_bTransformed) { //MindBlast if (m_uiMindBlast_Timer <= uiDiff) { DoCast(me->getVictim(), SPELL_MINDBLAST); m_uiMindBlast_Timer = urand(15000, 20000); } else m_uiMindBlast_Timer -= uiDiff; //CrusadersHammer if (m_uiCrusadersHammer_Timer <= uiDiff) { DoCast(me->getVictim(), SPELL_CRUSADERSHAMMER); m_uiCrusadersHammer_Timer = 12000; } else m_uiCrusadersHammer_Timer -= uiDiff; //CrusaderStrike if (m_uiCrusaderStrike_Timer <= uiDiff) { DoCast(me->getVictim(), SPELL_CRUSADERSTRIKE); m_uiCrusaderStrike_Timer = 15000; } else m_uiCrusaderStrike_Timer -= uiDiff; //HolyStrike if (m_uiHolyStrike_Timer <= uiDiff) { DoCast(me->getVictim(), SPELL_HOLYSTRIKE); m_uiHolyStrike_Timer = 15000; } else m_uiHolyStrike_Timer -= uiDiff; //BalnazzarTransform if (HealthBelowPct(40)) { if (me->IsNonMeleeSpellCasted(false)) me->InterruptNonMeleeSpells(false); //restore hp, mana and stun DoCast(me, SPELL_BALNAZZARTRANSFORM); me->UpdateEntry(NPC_BALNAZZAR); m_bTransformed = true; } } else { //MindBlast if (m_uiMindBlast_Timer <= uiDiff) { DoCast(me->getVictim(), SPELL_MINDBLAST); m_uiMindBlast_Timer = urand(15000, 20000); } else m_uiMindBlast_Timer -= uiDiff; //ShadowShock if (m_uiShadowShock_Timer <= uiDiff) { DoCast(me->getVictim(), SPELL_SHADOWSHOCK); m_uiShadowShock_Timer = 11000; } else m_uiShadowShock_Timer -= uiDiff; //PsychicScream if (m_uiPsychicScream_Timer <= uiDiff) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) DoCast(target, SPELL_PSYCHICSCREAM); m_uiPsychicScream_Timer = 20000; } else m_uiPsychicScream_Timer -= uiDiff; //DeepSleep if (m_uiDeepSleep_Timer <= uiDiff) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) DoCast(target, SPELL_SLEEP); m_uiDeepSleep_Timer = 15000; } else m_uiDeepSleep_Timer -= uiDiff; //MindControl if (m_uiMindControl_Timer <= uiDiff) { DoCast(me->getVictim(), SPELL_MINDCONTROL); m_uiMindControl_Timer = 15000; } else m_uiMindControl_Timer -= uiDiff; } DoMeleeAttackIfReady(); } }; }; void AddSC_boss_dathrohan_balnazzar() { new boss_dathrohan_balnazzar(); }
7,764
2,933
/* This file is part of LeagueSkinChanger by b3akers, licensed under the MIT license: * * MIT License * * Copyright (c) b3akers 2020 * * 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 "game_classes.hpp" #include "encryption.hpp" #include "fnv_hash.hpp" #include <Windows.h> void character_data_stack::push( const char* model, int32_t skin ) { static const auto Push = reinterpret_cast<int( __thiscall* )( void*, const char* model, int32_t skinid, int32_t, bool update_spells, bool dont_update_hud, bool, bool change_particle, bool, char, const char*, int32_t, const char*, int32_t )>( std::uintptr_t( GetModuleHandle( nullptr ) ) + offsets::functions::CharacterDataStack__Push ); Push( this, model, skin, 0, false, false, false, true, false, -1, "\x00", 0, "\x00", 0 ); } void character_data_stack::update( bool change ) { static const auto Update = reinterpret_cast<void( __thiscall* )( void*, bool )>( std::uintptr_t( GetModuleHandle( nullptr ) ) + offsets::functions::CharacterDataStack__Update ); Update( this, change ); } void obj_ai_base::change_skin( const char* model, int32_t skin ) { //Update skinid in object class to appear name in scoreboard and fix for some things // reinterpret_cast<xor_value<int32_t>*>( std::uintptr_t( this ) + offsets::ai_base::SkinId )->encrypt( skin ); this->get_character_data_stack( )->base_skin.skin = skin; //Lux has same skinid but diff model we have to handle it, game receives packets and calls Push function to change skin we do same but don't pushing new class but modify existing // if ( fnv::hash_runtime( this->get_character_data_stack( )->base_skin.model.str ) == FNV( "Lux" ) ) { if ( skin == 7 ) { if ( this->get_character_data_stack( )->stack.empty( ) ) { this->get_character_data_stack( )->push( model, skin ); return; } auto& last = this->get_character_data_stack( )->stack.back( ); last.skin = skin; last.model.str = model; last.model.length = strlen( model ); last.model.capacity = last.model.length + 1; } else { //Make sure that stack for lux is cleared // this->get_character_data_stack( )->stack.clear( ); } } this->get_character_data_stack( )->update( true ); } obj_ai_base* obj_ai_minion::get_owner( ) { static const auto GetOwnerObject = reinterpret_cast<obj_ai_base * ( __thiscall* )( void* )>( std::uintptr_t( GetModuleHandle( nullptr ) ) + offsets::functions::GetOwnerObject ); return GetOwnerObject( this ); } bool obj_ai_minion::is_lane_minion( ) { return reinterpret_cast<xor_value<bool>*>( std::uintptr_t( this ) + offsets::ai_minion::IsLaneMinion )->decrypt( ); }
3,624
1,289
/* * Copyright (c) 2015 Juniper Networks, Inc. All rights reserved. */ #include "base/os.h" #include "testing/gunit.h" #include <base/logging.h> #include <io/event_manager.h> #include <io/test/event_manager_test.h> #include <tbb/task.h> #include <base/task.h> #include <cmn/agent_cmn.h> #include "cfg/cfg_init.h" #include "cfg/cfg_interface.h" #include "pkt/pkt_init.h" #include "services/services_init.h" #include "vrouter/ksync/ksync_init.h" #include "oper/interface_common.h" #include "oper/nexthop.h" #include "oper/tunnel_nh.h" #include "route/route.h" #include "oper/vrf.h" #include "oper/mpls.h" #include "oper/vm.h" #include "oper/vn.h" #include "filter/acl.h" #include "test_cmn_util.h" #include "vr_types.h" #include "xmpp/xmpp_init.h" #include "xmpp/test/xmpp_test_util.h" #include "vr_types.h" #include "control_node_mock.h" #include "xml/xml_pugi.h" #include "controller/controller_peer.h" #include "controller/controller_export.h" #include "controller/controller_vrf_export.h" #include "ovs_tor_agent/ovsdb_client/ovsdb_route_peer.h" #include "ovs_tor_agent/ovsdb_client/physical_switch_ovsdb.h" #include "ovs_tor_agent/ovsdb_client/logical_switch_ovsdb.h" #include "ovs_tor_agent/ovsdb_client/physical_port_ovsdb.h" #include "ovs_tor_agent/ovsdb_client/vrf_ovsdb.h" #include "ovs_tor_agent/ovsdb_client/vlan_port_binding_ovsdb.h" #include "ovs_tor_agent/ovsdb_client/unicast_mac_local_ovsdb.h" #include "test_ovs_agent_init.h" #include <ovsdb_types.h> using namespace pugi; using namespace OVSDB; EventManager evm1; ServerThread *thread1; test::ControlNodeMock *bgp_peer1; EventManager evm2; ServerThread *thread2; test::ControlNodeMock *bgp_peer2; void RouterIdDepInit(Agent *agent) { Agent::GetInstance()->controller()->Connect(); } class OvsBaseTest : public ::testing::Test { protected: OvsBaseTest() { } virtual void SetUp() { agent_ = Agent::GetInstance(); init_ = static_cast<TestOvsAgentInit *>(client->agent_init()); peer_manager_ = init_->ovs_peer_manager(); WAIT_FOR(100, 10000, (tcp_session_ = static_cast<OvsdbClientTcpSession *> (init_->ovsdb_client()->NextSession(NULL))) != NULL); WAIT_FOR(100, 10000, (tcp_session_->client_idl() != NULL)); WAIT_FOR(100, 10000, (tcp_session_->status() == string("Established"))); client->WaitForIdle(); WAIT_FOR(100, 10000, (!tcp_session_->client_idl()->IsMonitorInProcess())); client->WaitForIdle(); } virtual void TearDown() { } Agent *agent_; TestOvsAgentInit *init_; OvsPeerManager *peer_manager_; OvsdbClientTcpSession *tcp_session_; }; TEST_F(OvsBaseTest, connection) { WAIT_FOR(100, 10000, (tcp_session_->status() == string("Established"))); OvsdbClientReq *req = new OvsdbClientReq(); req->HandleRequest(); client->WaitForIdle(); req->Release(); } TEST_F(OvsBaseTest, physical_router) { PhysicalSwitchTable *table = tcp_session_->client_idl()->physical_switch_table(); PhysicalSwitchEntry key(table, "test-router"); WAIT_FOR(100, 10000, (table->FindActiveEntry(&key) != NULL)); OvsdbPhysicalSwitchReq *req = new OvsdbPhysicalSwitchReq(); req->HandleRequest(); client->WaitForIdle(); req->Release(); } TEST_F(OvsBaseTest, physical_port) { PhysicalPortTable *table = tcp_session_->client_idl()->physical_port_table(); PhysicalPortEntry key(table, "test-router", "ge-0/0/0"); WAIT_FOR(100, 10000, (table->FindActiveEntry(&key) != NULL)); PhysicalPortEntry key1(table, "test-router", "ge-0/0/1"); WAIT_FOR(100, 10000, (table->FindActiveEntry(&key1) != NULL)); PhysicalPortEntry key2(table, "test-router", "ge-0/0/2"); WAIT_FOR(100, 10000, (table->FindActiveEntry(&key2) != NULL)); PhysicalPortEntry key3(table, "test-router", "ge-0/0/3"); WAIT_FOR(100, 10000, (table->FindActiveEntry(&key3) != NULL)); PhysicalPortEntry key4(table, "test-router", "ge-0/0/4"); WAIT_FOR(100, 10000, (table->FindActiveEntry(&key4) != NULL)); PhysicalPortEntry key5(table, "test-router", "ge-0/0/47"); WAIT_FOR(100, 10000, (table->FindActiveEntry(&key5) != NULL)); OvsdbPhysicalPortReq *req = new OvsdbPhysicalPortReq(); req->HandleRequest(); client->WaitForIdle(); req->Release(); } TEST_F(OvsBaseTest, VrfAuditRead) { VrfOvsdbObject *table = tcp_session_->client_idl()->vrf_ovsdb(); VrfOvsdbEntry vrf_key(table, UuidToString(MakeUuid(1))); WAIT_FOR(1000, 10000, (table->Find(&vrf_key) != NULL)); OvsdbLogicalSwitchReq *req = new OvsdbLogicalSwitchReq(); req->HandleRequest(); client->WaitForIdle(); req->Release(); OvsdbMulticastMacLocalReq *mcast_req = new OvsdbMulticastMacLocalReq(); mcast_req->HandleRequest(); client->WaitForIdle(); mcast_req->Release(); OvsdbUnicastMacRemoteReq *mac_req = new OvsdbUnicastMacRemoteReq(); mac_req->HandleRequest(); client->WaitForIdle(); mac_req->Release(); } TEST_F(OvsBaseTest, VlanPortBindingAuditRead) { VlanPortBindingTable *table = tcp_session_->client_idl()->vlan_port_table(); VlanPortBindingEntry key(table, "test-router", "ge-0/0/0", 100, ""); WAIT_FOR(1000, 10000, (table->Find(&key) != NULL)); OvsdbVlanPortBindingReq *req = new OvsdbVlanPortBindingReq(); req->HandleRequest(); client->WaitForIdle(); req->Release(); } TEST_F(OvsBaseTest, connection_close) { // Take reference to idl so that session object itself is not deleted. OvsdbClientIdlPtr tcp_idl = tcp_session_->client_idl(); tcp_session_->TriggerClose(); client->WaitForIdle(); // Validate that keepalive timer has stopped, for the idl WAIT_FOR(100, 10000, (tcp_idl->IsKeepAliveTimerActive() == false)); UnicastMacLocalOvsdb *ucast_local_table = tcp_idl->unicast_mac_local_ovsdb(); // Validate that vrf re-eval queue of unicast mac local // table has stopped WAIT_FOR(100, 10000, (ucast_local_table->IsVrfReEvalQueueActive() == false)); // release idl reference tcp_idl = NULL; WAIT_FOR(100, 10000, (tcp_session_ = static_cast<OvsdbClientTcpSession *> (init_->ovsdb_client()->NextSession(NULL))) != NULL); } int main(int argc, char *argv[]) { GETUSERARGS(); // override with true to initialize ovsdb server and client ksync_init = true; client = OvsTestInit(init_file, ksync_init); int ret = RUN_ALL_TESTS(); TestShutdown(); return ret; }
6,573
2,593
/** * Copyright (c) 2019 Intel Corporation * * 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 <stdio.h> #include <time.h> #include <iostream> #include <sstream> #include <string> #include "BdevStats.h" namespace DaqDB { /* * BdevStats */ std::ostringstream &BdevStats::formatWriteBuf(std::ostringstream &buf, const char *bdev_addr) { buf << "bdev_addr[" << bdev_addr << "] write_compl_cnt[" << write_compl_cnt << "] write_err_cnt[" << write_err_cnt << "] outs_io_cnt[" << outstanding_io_cnt << "]"; return buf; } std::ostringstream &BdevStats::formatReadBuf(std::ostringstream &buf, const char *bdev_addr) { buf << "bdev_addr[" << bdev_addr << "] read_compl_cnt[" << read_compl_cnt << "] read_err_cnt[" << read_err_cnt << "] outs_io_cnt[" << outstanding_io_cnt << "]"; return buf; } void BdevStats::printWritePer(std::ostream &os, const char *bdev_addr) { if (!(write_compl_cnt % quant_per)) { std::ostringstream buf; char time_buf[128]; time_t now = time(0); strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S.000", localtime(&now)); os << formatWriteBuf(buf, bdev_addr).str() << " " << time_buf << std::endl; } } void BdevStats::printReadPer(std::ostream &os, const char *bdev_addr) { if (!(read_compl_cnt % quant_per)) { std::ostringstream buf; char time_buf[128]; time_t now = time(0); strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S.000", localtime(&now)); os << formatReadBuf(buf, bdev_addr).str() << " " << time_buf << std::endl; } } } // namespace DaqDB
2,298
783
#include <stdio.h> char word[1005][1005]; int main() { int n, m, i, j; int idx[1005]; while(scanf("%d %d", &n, &m) == 2) { while(getchar() != '\n'); gets(word[0]); idx[0] = 0; for(i = 1; i < n; i++) { int cnt = 0; gets(word[i]); for(j = 0; j < m; j++) if(word[i][j] != word[0][j]) cnt++; idx[cnt] = i; } for(i = 0; i < n; i++) puts(word[idx[i]]); } return 0; } /* 6 5 remar pitos remas remos retos ritos 5 4 pato lisa pata pita pisa */
601
266
#pragma once #include "../base_def.hpp" #include "LolLootPlayerLoot.hpp" namespace lol { struct LolLootPlayerLootMap { int64_t version; std::map<std::string, LolLootPlayerLoot> playerLoot; }; inline void to_json(json& j, const LolLootPlayerLootMap& v) { j["version"] = v.version; j["playerLoot"] = v.playerLoot; } inline void from_json(const json& j, LolLootPlayerLootMap& v) { v.version = j.at("version").get<int64_t>(); v.playerLoot = j.at("playerLoot").get<std::map<std::string, LolLootPlayerLoot>>(); } }
551
226
#include <stdio.h> #include <unistd.h> #include "tool/cli/CliRecv.h" #include "tool/cli/CliSend.h" int main(int argc, char* argv[]) { int pid = getpid(); air::CliResult* cli_result = new air::CliResult{}; air::CliSend* cli_send = new air::CliSend{cli_result, pid}; air::CliRecv* cli_recv = new air::CliRecv{cli_result, pid}; int num_cmd{0}; int target_pid{-1}; num_cmd = cli_send->Send(argc, argv, target_pid); if (0 < num_cmd) { cli_recv->Receive(num_cmd, target_pid); } cli_result->PrintCliResult(); delete cli_send; delete cli_recv; delete cli_result; }
629
262
// Copyright 2019 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 "google_apis/gaia/core_account_id.h" #include "base/check.h" namespace { // Returns whether the string looks like an email (the test is // crude an only checks whether it includes an '@'). bool IsEmailString(const std::string& string) { return string.find('@') != std::string::npos; } } // anonymous namespace CoreAccountId::CoreAccountId() = default; CoreAccountId::CoreAccountId(const CoreAccountId&) = default; CoreAccountId::CoreAccountId(CoreAccountId&&) noexcept = default; CoreAccountId::~CoreAccountId() = default; CoreAccountId& CoreAccountId::operator=(const CoreAccountId&) = default; CoreAccountId& CoreAccountId::operator=(CoreAccountId&&) noexcept = default; // static CoreAccountId CoreAccountId::FromGaiaId(const std::string& gaia_id) { if (gaia_id.empty()) return CoreAccountId(); DCHECK(!IsEmailString(gaia_id)) << "Expected a Gaia ID and got an email [actual = " << gaia_id << "]"; return CoreAccountId::FromString(gaia_id); } // static CoreAccountId CoreAccountId::FromEmail(const std::string& email) { if (email.empty()) return CoreAccountId(); DCHECK(IsEmailString(email)) << "Expected an email [actual = " << email << "]"; return CoreAccountId::FromString(email); } // static CoreAccountId CoreAccountId::FromString(const std::string value) { CoreAccountId account_id; account_id.id_ = value; return account_id; } bool CoreAccountId::empty() const { return id_.empty(); } bool CoreAccountId::IsEmail() const { return IsEmailString(id_); } const std::string& CoreAccountId::ToString() const { return id_; } bool operator<(const CoreAccountId& lhs, const CoreAccountId& rhs) { return lhs.ToString() < rhs.ToString(); } bool operator==(const CoreAccountId& lhs, const CoreAccountId& rhs) { return lhs.ToString() == rhs.ToString(); } bool operator!=(const CoreAccountId& lhs, const CoreAccountId& rhs) { return lhs.ToString() != rhs.ToString(); } std::ostream& operator<<(std::ostream& out, const CoreAccountId& a) { return out << a.ToString(); } std::vector<std::string> ToStringList( const std::vector<CoreAccountId>& account_ids) { std::vector<std::string> account_ids_string; for (const auto& account_id : account_ids) account_ids_string.push_back(account_id.ToString()); return account_ids_string; }
2,488
803
// Copyright 2014 MongoDB 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. #pragma once #include <bsoncxx/document/view.hpp> #include <bsoncxx/stdx/optional.hpp> #include <mongocxx/stdx.hpp> #include <mongocxx/write_concern.hpp> #include <mongocxx/config/prelude.hpp> namespace mongocxx { MONGOCXX_INLINE_NAMESPACE_BEGIN namespace options { /// /// Class representing the optional arguments to a MongoDB insert operation /// class MONGOCXX_API insert { public: /// /// Sets the bypass_document_validation option. /// If true, allows the write to opt-out of document level validation. /// /// @note /// On servers >= 3.2, the server applies validation by default. On servers < 3.2, this option /// is ignored. /// /// @param bypass_document_validation /// Whether or not to bypass document validation /// insert& bypass_document_validation(bool bypass_document_validation); /// /// Gets the current value of the bypass_document_validation option. /// /// @return The optional value of the bypass_document_validation option. /// const stdx::optional<bool>& bypass_document_validation() const; /// /// Sets the write_concern for this operation. /// /// @param wc /// The new write_concern. /// /// @see https://docs.mongodb.com/master/core/write-concern/ /// insert& write_concern(class write_concern wc); /// /// The current write_concern for this operation. /// /// @return The current write_concern. /// /// @see https://docs.mongodb.com/master/core/write-concern/ /// const stdx::optional<class write_concern>& write_concern() const; /// /// @note: This applies only to insert_many and is ignored for insert_one. /// /// If true, when an insert fails, return without performing the remaining /// writes. If false, when a write fails, continue with the remaining /// writes, if any. Inserts can be performed in any order if this is false. /// Defaults to true. /// /// @param ordered /// Whether or not the insert_many will be ordered. /// /// @see https://docs.mongodb.com/master/reference/method/db.collection.insert/ /// insert& ordered(bool ordered); /// /// The current ordered value for this operation. /// /// @return The current ordered value. /// /// @see https://docs.mongodb.com/master/reference/method/db.collection.insert/ /// const stdx::optional<bool>& ordered() const; private: stdx::optional<class write_concern> _write_concern; stdx::optional<bool> _ordered; stdx::optional<bool> _bypass_document_validation; }; } // namespace options MONGOCXX_INLINE_NAMESPACE_END } // namespace mongocxx #include <mongocxx/config/postlude.hpp>
3,328
1,011
#include <gtest/gtest.h> #include <eigenml/decision_tree/decision_tree_traits.hpp> #include <eigenml/decision_tree/splitting/find_thresholds.hpp> #include <eigenml/decision_tree/splitting/criteria.hpp> using namespace eigenml; using namespace eigenml::decision_tree; typedef tree_traits<ModelType::kSupervisedClassifier, Matrix, Matrix> classification_tree_traits; TEST(ThresholdFinding, Entropy) { classification_tree_traits::DistributionType hist; hist.add_sample(0, 10); hist.add_sample(1, 10); ValueAndWeight v = entropy(hist); ASSERT_DOUBLE_EQ(v.first, 1); ASSERT_DOUBLE_EQ(v.second, 20); } TEST(ThresholdFinding, Gini) { classification_tree_traits::DistributionType hist; hist.add_sample(0, 10); hist.add_sample(1, 10); ValueAndWeight v = gini(hist); ASSERT_DOUBLE_EQ(v.first, 0.5); ASSERT_DOUBLE_EQ(v.second, 20); } TEST(ThresholdFinding, SimplethresholdEntropy) { size_t N = 2; Matrix X(N, 1); Vector Y(N); X << 1, 2; Y << 0, 1; IdxVector idx{0, 1}; IdxVector sorted{0, 1}; typedef classification_tree_traits::DistributionType DistributionType; typedef classification_tree_traits::CriterionType CriterionType; auto criterion = CriterionType(entropy<DistributionType>); ThresholdFinder<DistributionType, CriterionType, Matrix, Vector> splitter; ThresholdSplit split = splitter.find_threshold(X, Y, 0, idx, sorted, criterion); ASSERT_DOUBLE_EQ(1, split.threshold); ASSERT_DOUBLE_EQ(2, split.gain); ASSERT_EQ(0, split.feature_index); ASSERT_EQ(0, split.threshold_index); } TEST(ThresholdFinding, SimplethresholdGini) { size_t N = 2; Matrix X(N, 1); Vector Y(N); X << 1, 2; Y << 0, 1; IdxVector idx{0, 1}; IdxVector sorted{0, 1}; typedef classification_tree_traits::DistributionType DistributionType; typedef classification_tree_traits::CriterionType CriterionType; auto criterion = CriterionType(gini<DistributionType>); ThresholdFinder<DistributionType, CriterionType, Matrix, Vector> splitter; ThresholdSplit split = splitter.find_threshold(X, Y, 0, idx, sorted, criterion); ASSERT_DOUBLE_EQ(1, split.threshold); ASSERT_DOUBLE_EQ(1, split.gain); ASSERT_EQ(0, split.feature_index); ASSERT_EQ(0, split.threshold_index); }
2,320
891
// Copyright 2020 The Pigweed Authors // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // https://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 "pw_log_rpc/log_filter.h" #include "pw_log/levels.h" #include "pw_protobuf/decoder.h" #include "pw_status/try.h" namespace pw::log_rpc { namespace { // Returns true if the provided log parameters match the given filter rule. bool IsRuleMet(const Filter::Rule& rule, uint32_t level, ConstByteSpan module, uint32_t flags, ConstByteSpan thread) { if (level < static_cast<uint32_t>(rule.level_greater_than_or_equal)) { return false; } if ((rule.any_flags_set != 0) && ((flags & rule.any_flags_set) == 0)) { return false; } if (!rule.module_equals.empty() && !std::equal(module.begin(), module.end(), rule.module_equals.begin(), rule.module_equals.end())) { return false; } if (!rule.thread_equals.empty() && !std::equal(thread.begin(), thread.end(), rule.thread_equals.begin(), rule.thread_equals.end())) { return false; } return true; } } // namespace Status Filter::UpdateRulesFromProto(ConstByteSpan buffer) { if (rules_.empty()) { return Status::FailedPrecondition(); } // Reset rules. for (auto& rule : rules_) { rule = {}; } protobuf::Decoder decoder(buffer); Status status; for (size_t i = 0; (i < rules_.size()) && (status = decoder.Next()).ok(); ++i) { ConstByteSpan rule_buffer; PW_TRY(decoder.ReadBytes(&rule_buffer)); protobuf::Decoder rule_decoder(rule_buffer); while ((status = rule_decoder.Next()).ok()) { switch ( static_cast<log::FilterRule::Fields>(rule_decoder.FieldNumber())) { case log::FilterRule::Fields::LEVEL_GREATER_THAN_OR_EQUAL: PW_TRY(rule_decoder.ReadUint32(reinterpret_cast<uint32_t*>( &rules_[i].level_greater_than_or_equal))); break; case log::FilterRule::Fields::MODULE_EQUALS: { ConstByteSpan module; PW_TRY(rule_decoder.ReadBytes(&module)); if (module.size() > rules_[i].module_equals.max_size()) { return Status::InvalidArgument(); } rules_[i].module_equals.assign(module.begin(), module.end()); } break; case log::FilterRule::Fields::ANY_FLAGS_SET: PW_TRY(rule_decoder.ReadUint32(&rules_[i].any_flags_set)); break; case log::FilterRule::Fields::ACTION: PW_TRY(rule_decoder.ReadUint32( reinterpret_cast<uint32_t*>(&rules_[i].action))); break; case log::FilterRule::Fields::THREAD_EQUALS: { ConstByteSpan thread; PW_TRY(rule_decoder.ReadBytes(&thread)); if (thread.size() > rules_[i].thread_equals.max_size()) { return Status::InvalidArgument(); } rules_[i].thread_equals.assign(thread.begin(), thread.end()); } break; } } } return status.IsOutOfRange() ? OkStatus() : status; } bool Filter::ShouldDropLog(ConstByteSpan entry) const { if (rules_.empty()) { return false; } uint32_t log_level = 0; ConstByteSpan log_module; ConstByteSpan log_thread; uint32_t log_flags = 0; protobuf::Decoder decoder(entry); while (decoder.Next().ok()) { switch (static_cast<log::LogEntry::Fields>(decoder.FieldNumber())) { case log::LogEntry::Fields::LINE_LEVEL: if (decoder.ReadUint32(&log_level).ok()) { log_level &= PW_LOG_LEVEL_BITMASK; } break; case log::LogEntry::Fields::MODULE: decoder.ReadBytes(&log_module).IgnoreError(); break; case log::LogEntry::Fields::FLAGS: decoder.ReadUint32(&log_flags).IgnoreError(); break; case log::LogEntry::Fields::THREAD: decoder.ReadBytes(&log_thread).IgnoreError(); break; default: break; } } // Follow the action of the first rule whose condition is met. for (const auto& rule : rules_) { if (rule.action == Filter::Rule::Action::kInactive) { continue; } if (IsRuleMet(rule, log_level, log_module, log_flags, log_thread)) { return rule.action == Filter::Rule::Action::kDrop; } } return false; } } // namespace pw::log_rpc
5,021
1,588
// Copyright 2018 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 "ash/system/unified/unified_system_tray_view.h" #include "ash/public/cpp/app_list/app_list_features.h" #include "ash/system/tray/interacted_by_tap_recorder.h" #include "ash/system/tray/tray_constants.h" #include "ash/system/unified/feature_pod_button.h" #include "ash/system/unified/feature_pods_container_view.h" #include "ash/system/unified/top_shortcuts_view.h" #include "ash/system/unified/unified_message_center_view.h" #include "ash/system/unified/unified_system_info_view.h" #include "ash/system/unified/unified_system_tray_controller.h" #include "ash/system/unified/unified_system_tray_model.h" #include "ui/message_center/message_center.h" #include "ui/views/background.h" #include "ui/views/layout/box_layout.h" #include "ui/views/painter.h" namespace ash { namespace { std::unique_ptr<views::Background> CreateUnifiedBackground() { return views::CreateBackgroundFromPainter( views::Painter::CreateSolidRoundRectPainter( app_list::features::IsBackgroundBlurEnabled() ? kUnifiedMenuBackgroundColorWithBlur : kUnifiedMenuBackgroundColor, kUnifiedTrayCornerRadius)); } class DetailedViewContainer : public views::View { public: DetailedViewContainer() = default; ~DetailedViewContainer() override = default; void Layout() override { for (int i = 0; i < child_count(); ++i) child_at(i)->SetBoundsRect(GetContentsBounds()); views::View::Layout(); } private: DISALLOW_COPY_AND_ASSIGN(DetailedViewContainer); }; } // namespace UnifiedSlidersContainerView::UnifiedSlidersContainerView( bool initially_expanded) : expanded_amount_(initially_expanded ? 1.0 : 0.0) { SetVisible(initially_expanded); } UnifiedSlidersContainerView::~UnifiedSlidersContainerView() = default; void UnifiedSlidersContainerView::SetExpandedAmount(double expanded_amount) { DCHECK(0.0 <= expanded_amount && expanded_amount <= 1.0); SetVisible(expanded_amount > 0.0); expanded_amount_ = expanded_amount; PreferredSizeChanged(); UpdateOpacity(); } void UnifiedSlidersContainerView::Layout() { int y = 0; for (int i = 0; i < child_count(); ++i) { views::View* child = child_at(i); int height = child->GetHeightForWidth(kTrayMenuWidth); child->SetBounds(0, y, kTrayMenuWidth, height); y += height; } } gfx::Size UnifiedSlidersContainerView::CalculatePreferredSize() const { int height = 0; for (int i = 0; i < child_count(); ++i) height += child_at(i)->GetHeightForWidth(kTrayMenuWidth); return gfx::Size(kTrayMenuWidth, height * expanded_amount_); } void UnifiedSlidersContainerView::UpdateOpacity() { for (int i = 0; i < child_count(); ++i) { views::View* child = child_at(i); double opacity = 1.0; if (child->y() > height()) opacity = 0.0; else if (child->bounds().bottom() < height()) opacity = 1.0; else opacity = static_cast<double>(height() - child->y()) / child->height(); child->layer()->SetOpacity(opacity); } } UnifiedSystemTrayView::UnifiedSystemTrayView( UnifiedSystemTrayController* controller, bool initially_expanded) : controller_(controller), message_center_view_( new UnifiedMessageCenterView(message_center::MessageCenter::Get())), top_shortcuts_view_(new TopShortcutsView(controller_)), feature_pods_container_(new FeaturePodsContainerView(initially_expanded)), sliders_container_(new UnifiedSlidersContainerView(initially_expanded)), system_info_view_(new UnifiedSystemInfoView()), system_tray_container_(new views::View()), detailed_view_container_(new DetailedViewContainer()), interacted_by_tap_recorder_( std::make_unique<InteractedByTapRecorder>(this)) { DCHECK(controller_); auto* layout = SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::kVertical, gfx::Insets(), kUnifiedNotificationCenterSpacing)); SetBackground(CreateUnifiedBackground()); SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false); AddChildView(message_center_view_); layout->SetFlexForView(message_center_view_, 1); system_tray_container_->SetLayoutManager( std::make_unique<views::BoxLayout>(views::BoxLayout::kVertical)); system_tray_container_->SetBackground(CreateUnifiedBackground()); AddChildView(system_tray_container_); system_tray_container_->AddChildView(top_shortcuts_view_); system_tray_container_->AddChildView(feature_pods_container_); system_tray_container_->AddChildView(sliders_container_); system_tray_container_->AddChildView(system_info_view_); detailed_view_container_->SetVisible(false); AddChildView(detailed_view_container_); } UnifiedSystemTrayView::~UnifiedSystemTrayView() = default; void UnifiedSystemTrayView::SetMaxHeight(int max_height) { message_center_view_->SetMaxHeight(max_height); } void UnifiedSystemTrayView::AddFeaturePodButton(FeaturePodButton* button) { feature_pods_container_->AddChildView(button); } void UnifiedSystemTrayView::AddSliderView(views::View* slider_view) { slider_view->SetPaintToLayer(); slider_view->layer()->SetFillsBoundsOpaquely(false); sliders_container_->AddChildView(slider_view); } void UnifiedSystemTrayView::SetDetailedView(views::View* detailed_view) { auto system_tray_size = system_tray_container_->GetPreferredSize(); system_tray_container_->SetVisible(false); detailed_view_container_->RemoveAllChildViews(true /* delete_children */); detailed_view_container_->AddChildView(detailed_view); detailed_view_container_->SetPreferredSize(system_tray_size); detailed_view_container_->SetVisible(true); detailed_view->InvalidateLayout(); Layout(); } void UnifiedSystemTrayView::SetExpandedAmount(double expanded_amount) { DCHECK(0.0 <= expanded_amount && expanded_amount <= 1.0); if (expanded_amount == 1.0 || expanded_amount == 0.0) top_shortcuts_view_->SetExpanded(expanded_amount == 1.0); feature_pods_container_->SetExpandedAmount(expanded_amount); sliders_container_->SetExpandedAmount(expanded_amount); PreferredSizeChanged(); // It is possible that the ratio between |message_center_view_| and others // can change while the bubble size remain unchanged. Layout(); } void UnifiedSystemTrayView::OnGestureEvent(ui::GestureEvent* event) { gfx::Point screen_location = event->location(); ConvertPointToScreen(this, &screen_location); switch (event->type()) { case ui::ET_GESTURE_SCROLL_BEGIN: controller_->BeginDrag(screen_location); event->SetHandled(); break; case ui::ET_GESTURE_SCROLL_UPDATE: controller_->UpdateDrag(screen_location); event->SetHandled(); break; case ui::ET_GESTURE_END: controller_->EndDrag(screen_location); event->SetHandled(); break; default: break; } } void UnifiedSystemTrayView::ChildPreferredSizeChanged(views::View* child) { // Size change is always caused by SetExpandedAmount except for // |message_center_view_|. So we only have to call PreferredSizeChanged() // here when the child is |message_center_view_|. if (child == message_center_view_) PreferredSizeChanged(); } } // namespace ash
7,348
2,405
// Copyright (c) 2012-2017 VideoStitch SAS // Copyright (c) 2018 stitchEm #include "export.hpp" #include "videoReader.hpp" #include "netStreamReader.hpp" #include "avWriter.hpp" #include "libvideostitch/logging.hpp" #include "libvideostitch/output.hpp" #include "libvideostitch/plugin.hpp" #include "libvideostitch/ptv.hpp" #include "libvideostitch/status.hpp" #include <ostream> /** \name Services for reader plugin. */ //\{ extern "C" VS_PLUGINS_EXPORT VideoStitch::Potential<VideoStitch::Input::Reader>* createReaderFn( VideoStitch::Ptv::Value const* config, VideoStitch::Plugin::VSReaderPlugin::Config runtime) { if (VideoStitch::Input::FFmpegReader::handles(config->asString()) || VideoStitch::Input::netStreamReader::handles(config->asString())) { auto potLibAvReader = VideoStitch::Input::LibavReader::create(config->asString(), runtime); if (potLibAvReader.ok()) { return new VideoStitch::Potential<VideoStitch::Input::Reader>(potLibAvReader.release()); } else { return new VideoStitch::Potential<VideoStitch::Input::Reader>(potLibAvReader.status()); } } return new VideoStitch::Potential<VideoStitch::Input::Reader>{VideoStitch::Origin::Input, VideoStitch::ErrType::InvalidConfiguration, "Reader doesn't handle this configuration"}; } extern "C" VS_PLUGINS_EXPORT bool handleReaderFn(VideoStitch::Ptv::Value const* config) { if (config && config->getType() == VideoStitch::Ptv::Value::STRING) { return (VideoStitch::Input::FFmpegReader::handles(config->asString()) || VideoStitch::Input::netStreamReader::handles(config->asString())); } else { return false; } } extern "C" VS_PLUGINS_EXPORT VideoStitch::Input::ProbeResult probeReaderFn(std::string const& p_filename) { return VideoStitch::Input::LibavReader::probe(p_filename); } //\} /** \name Services for writer plugin. */ //\{ extern "C" VS_PLUGINS_EXPORT VideoStitch::Potential<VideoStitch::Output::Output>* createWriterFn( VideoStitch::Ptv::Value const* config, VideoStitch::Plugin::VSWriterPlugin::Config run_time) { VideoStitch::Output::Output* lReturn = nullptr; VideoStitch::Output::BaseConfig baseConfig; const VideoStitch::Status parseStatus = baseConfig.parse(*config); if (parseStatus.ok()) { lReturn = VideoStitch::Output::LibavWriter::create(*config, run_time.name, baseConfig.baseName, run_time.width, run_time.height, run_time.framerate, run_time.rate, run_time.depth, run_time.layout); if (lReturn) { return new VideoStitch::Potential<VideoStitch::Output::Output>(lReturn); } return new VideoStitch::Potential<VideoStitch::Output::Output>( VideoStitch::Origin::Output, VideoStitch::ErrType::InvalidConfiguration, "Could not create av writer"); } return new VideoStitch::Potential<VideoStitch::Output::Output>( VideoStitch::Origin::Output, VideoStitch::ErrType::InvalidConfiguration, "Could not parse AV Writer configuration", parseStatus); } extern "C" VS_PLUGINS_EXPORT bool handleWriterFn(VideoStitch::Ptv::Value const* config) { bool lReturn(false); VideoStitch::Output::BaseConfig baseConfig; if (baseConfig.parse(*config).ok()) { lReturn = (!strcmp(baseConfig.strFmt, "mp4") || !strcmp(baseConfig.strFmt, "mov")); } else { // TODOLATERSTATUS VideoStitch::Logger::get(VideoStitch::Logger::Verbose) << "avPlugin: cannot parse BaseConfnig" << std::endl; } return lReturn; } //\} #ifdef TestLinking int main() { /** This code is not expected to run: it's just a way to check all required symbols will be in library. */ VideoStitch::Ptv::Value const* config = 0; { VideoStitch::Plugin::VSReaderPlugin::Config runtime; createReaderFn(config, runtime); } handleReaderFn(config); probeReaderFn(std::string()); VideoStitch::Plugin::VSWriterPlugin::Config runtime; createWriterFn(config, runtime); handleWriterFn(config); return 0; } #endif
4,150
1,298
// Copyright (C) 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "icing/index/main/posting-list-used.h" #include <fcntl.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <algorithm> #include <cstdint> #include <deque> #include <iterator> #include <memory> #include <random> #include <string> #include <vector> #include "icing/text_classifier/lib3/utils/base/status.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "icing/index/main/posting-list-utils.h" #include "icing/legacy/index/icing-bit-util.h" #include "icing/schema/section.h" #include "icing/store/document-id.h" #include "icing/testing/common-matchers.h" #include "icing/testing/hit-test-utils.h" using std::reverse; using std::vector; using testing::ElementsAre; using testing::ElementsAreArray; using testing::Eq; using testing::IsEmpty; using testing::Le; using testing::Lt; namespace icing { namespace lib { struct HitElt { HitElt() = default; explicit HitElt(const Hit &hit_in) : hit(hit_in) {} static Hit get_hit(const HitElt &hit_elt) { return hit_elt.hit; } Hit hit; }; TEST(PostingListTest, PostingListUsedPrependHitNotFull) { static const int kNumHits = 2551; static const size_t kHitsSize = kNumHits * sizeof(Hit); std::unique_ptr<char[]> hits_buf = std::make_unique<char[]>(kHitsSize); ICING_ASSERT_OK_AND_ASSIGN( PostingListUsed pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf.get()), kHitsSize)); // Make used. Hit hit0(/*section_id=*/0, 0, /*term_frequency=*/56); pl_used.PrependHit(hit0); // Size = sizeof(uncompressed hit0) int expected_size = sizeof(Hit); EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit0))); Hit hit1(/*section_id=*/0, 1, Hit::kDefaultTermFrequency); pl_used.PrependHit(hit1); // Size = sizeof(uncompressed hit1) // + sizeof(hit0-hit1) + sizeof(hit0::term_frequency) expected_size += 2 + sizeof(Hit::TermFrequency); EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit1, hit0))); Hit hit2(/*section_id=*/0, 2, /*term_frequency=*/56); pl_used.PrependHit(hit2); // Size = sizeof(uncompressed hit2) // + sizeof(hit1-hit2) // + sizeof(hit0-hit1) + sizeof(hit0::term_frequency) expected_size += 2; EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit2, hit1, hit0))); Hit hit3(/*section_id=*/0, 3, Hit::kDefaultTermFrequency); pl_used.PrependHit(hit3); // Size = sizeof(uncompressed hit3) // + sizeof(hit2-hit3) + sizeof(hit2::term_frequency) // + sizeof(hit1-hit2) // + sizeof(hit0-hit1) + sizeof(hit0::term_frequency) expected_size += 2 + sizeof(Hit::TermFrequency); EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit3, hit2, hit1, hit0))); } TEST(PostingListTest, PostingListUsedPrependHitAlmostFull) { constexpr int kHitsSize = 2 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf = std::make_unique<char[]>(kHitsSize); ICING_ASSERT_OK_AND_ASSIGN( PostingListUsed pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf.get()), kHitsSize)); // Fill up the compressed region. // Transitions: // Adding hit0: EMPTY -> NOT_FULL // Adding hit1: NOT_FULL -> NOT_FULL // Adding hit2: NOT_FULL -> NOT_FULL Hit hit0(/*section_id=*/0, 0, Hit::kDefaultTermFrequency); Hit hit1 = CreateHit(hit0, /*desired_byte_length=*/2); Hit hit2 = CreateHit(hit1, /*desired_byte_length=*/2); ICING_EXPECT_OK(pl_used.PrependHit(hit0)); ICING_EXPECT_OK(pl_used.PrependHit(hit1)); ICING_EXPECT_OK(pl_used.PrependHit(hit2)); // Size used will be 2+2+4=8 bytes int expected_size = sizeof(Hit::Value) + 2 + 2; EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit2, hit1, hit0))); // Add one more hit to transition NOT_FULL -> ALMOST_FULL Hit hit3 = CreateHit(hit2, /*desired_byte_length=*/3); ICING_EXPECT_OK(pl_used.PrependHit(hit3)); // Compressed region would be 2+2+3+4=11 bytes, but the compressed region is // only 10 bytes. So instead, the posting list will transition to ALMOST_FULL. // The in-use compressed region will actually shrink from 8 bytes to 7 bytes // because the uncompressed version of hit2 will be overwritten with the // compressed delta of hit2. hit3 will be written to one of the special hits. // Because we're in ALMOST_FULL, the expected size is the size of the pl minus // the one hit used to mark the posting list as ALMOST_FULL. expected_size = kHitsSize - sizeof(Hit); EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit3, hit2, hit1, hit0))); // Add one more hit to transition ALMOST_FULL -> ALMOST_FULL Hit hit4 = CreateHit(hit3, /*desired_byte_length=*/2); ICING_EXPECT_OK(pl_used.PrependHit(hit4)); // There are currently 7 bytes in use in the compressed region. hit3 will have // a 2-byte delta. That delta will fit in the compressed region (which will // now have 9 bytes in use), hit4 will be placed in one of the special hits // and the posting list will remain in ALMOST_FULL. EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit4, hit3, hit2, hit1, hit0))); // Add one more hit to transition ALMOST_FULL -> FULL Hit hit5 = CreateHit(hit4, /*desired_byte_length=*/2); ICING_EXPECT_OK(pl_used.PrependHit(hit5)); // There are currently 9 bytes in use in the compressed region. hit4 will have // a 2-byte delta which will not fit in the compressed region. So hit4 will // remain in one of the special hits and hit5 will occupy the other, making // the posting list FULL. EXPECT_THAT(pl_used.BytesUsed(), Le(kHitsSize)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit5, hit4, hit3, hit2, hit1, hit0))); // The posting list is FULL. Adding another hit should fail. Hit hit6 = CreateHit(hit5, /*desired_byte_length=*/1); EXPECT_THAT(pl_used.PrependHit(hit6), StatusIs(libtextclassifier3::StatusCode::RESOURCE_EXHAUSTED)); } TEST(PostingListTest, PostingListUsedMinSize) { std::unique_ptr<char[]> hits_buf = std::make_unique<char[]>(posting_list_utils::min_posting_list_size()); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf.get()), posting_list_utils::min_posting_list_size())); // PL State: EMPTY EXPECT_THAT(pl_used.BytesUsed(), Eq(0)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(IsEmpty())); // Add a hit, PL should shift to ALMOST_FULL state Hit hit0(/*section_id=*/0, 0, /*term_frequency=*/0, /*is_in_prefix_section=*/false, /*is_prefix_hit=*/true); ICING_EXPECT_OK(pl_used.PrependHit(hit0)); // Size = sizeof(uncompressed hit0) int expected_size = sizeof(Hit); EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit0))); // Add the smallest hit possible - no term_frequency and a delta of 1. PL // should shift to FULL state. Hit hit1(/*section_id=*/0, 0, /*term_frequency=*/0, /*is_in_prefix_section=*/true, /*is_prefix_hit=*/false); ICING_EXPECT_OK(pl_used.PrependHit(hit1)); // Size = sizeof(uncompressed hit1) + sizeof(uncompressed hit0) expected_size += sizeof(Hit); EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit1, hit0))); // Try to add the smallest hit possible. Should fail Hit hit2(/*section_id=*/0, 0, /*term_frequency=*/0, /*is_in_prefix_section=*/false, /*is_prefix_hit=*/false); EXPECT_THAT(pl_used.PrependHit(hit2), StatusIs(libtextclassifier3::StatusCode::RESOURCE_EXHAUSTED)); EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit1, hit0))); } TEST(PostingListTest, PostingListPrependHitArrayMinSizePostingList) { constexpr int kFinalSize = 1025; std::unique_ptr<char[]> hits_buf = std::make_unique<char[]>(kFinalSize); // Min Size = 10 int size = posting_list_utils::min_posting_list_size(); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf.get()), size)); std::vector<HitElt> hits_in; hits_in.emplace_back(Hit(1, 0, Hit::kDefaultTermFrequency)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); std::reverse(hits_in.begin(), hits_in.end()); // Add five hits. The PL is in the empty state and an empty min size PL can // only fit two hits. So PrependHitArray should fail. uint32_t num_can_prepend = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( &hits_in[0], hits_in.size(), false); EXPECT_THAT(num_can_prepend, Eq(2)); int can_fit_hits = num_can_prepend; // The PL has room for 2 hits. We should be able to add them without any // problem, transitioning the PL from EMPTY -> ALMOST_FULL -> FULL const HitElt *hits_in_ptr = hits_in.data() + (hits_in.size() - 2); num_can_prepend = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( hits_in_ptr, can_fit_hits, false); EXPECT_THAT(num_can_prepend, Eq(can_fit_hits)); EXPECT_THAT(size, Eq(pl_used.BytesUsed())); std::deque<Hit> hits_pushed; std::transform(hits_in.rbegin(), hits_in.rend() - hits_in.size() + can_fit_hits, std::front_inserter(hits_pushed), HitElt::get_hit); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAreArray(hits_pushed))); } TEST(PostingListTest, PostingListPrependHitArrayPostingList) { // Size = 30 int size = 3 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf.get()), size)); std::vector<HitElt> hits_in; hits_in.emplace_back(Hit(1, 0, Hit::kDefaultTermFrequency)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); std::reverse(hits_in.begin(), hits_in.end()); // The last hit is uncompressed and the four before it should only take one // byte. Total use = 8 bytes. // ---------------------- // 29 delta(Hit #1) // 28 delta(Hit #2) // 27 delta(Hit #3) // 26 delta(Hit #4) // 25-22 Hit #5 // 21-10 <unused> // 9-5 kSpecialHit // 4-0 Offset=22 // ---------------------- int byte_size = sizeof(Hit::Value) + hits_in.size() - 1; // Add five hits. The PL is in the empty state and should be able to fit all // five hits without issue, transitioning the PL from EMPTY -> NOT_FULL. uint32_t num_could_fit = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( &hits_in[0], hits_in.size(), false); EXPECT_THAT(num_could_fit, Eq(hits_in.size())); EXPECT_THAT(byte_size, Eq(pl_used.BytesUsed())); std::deque<Hit> hits_pushed; std::transform(hits_in.rbegin(), hits_in.rend(), std::front_inserter(hits_pushed), HitElt::get_hit); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAreArray(hits_pushed))); Hit first_hit = CreateHit(hits_in.begin()->hit, /*desired_byte_length=*/1); hits_in.clear(); hits_in.emplace_back(first_hit); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/2)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/2)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/3)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/2)); std::reverse(hits_in.begin(), hits_in.end()); // Size increased by the deltas of these hits (1+2+1+2+3+2) = 11 bytes // ---------------------- // 29 delta(Hit #1) // 28 delta(Hit #2) // 27 delta(Hit #3) // 26 delta(Hit #4) // 25 delta(Hit #5) // 24-23 delta(Hit #6) // 22 delta(Hit #7) // 21-20 delta(Hit #8) // 19-17 delta(Hit #9) // 16-15 delta(Hit #10) // 14-11 Hit #11 // 10 <unused> // 9-5 kSpecialHit // 4-0 Offset=11 // ---------------------- byte_size += 11; // Add these 6 hits. The PL is currently in the NOT_FULL state and should // remain in the NOT_FULL state. num_could_fit = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( &hits_in[0], hits_in.size(), false); EXPECT_THAT(num_could_fit, Eq(hits_in.size())); EXPECT_THAT(byte_size, Eq(pl_used.BytesUsed())); // All hits from hits_in were added. std::transform(hits_in.rbegin(), hits_in.rend(), std::front_inserter(hits_pushed), HitElt::get_hit); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAreArray(hits_pushed))); first_hit = CreateHit(hits_in.begin()->hit, /*desired_byte_length=*/3); hits_in.clear(); hits_in.emplace_back(first_hit); // ---------------------- // 29 delta(Hit #1) // 28 delta(Hit #2) // 27 delta(Hit #3) // 26 delta(Hit #4) // 25 delta(Hit #5) // 24-23 delta(Hit #6) // 22 delta(Hit #7) // 21-20 delta(Hit #8) // 19-17 delta(Hit #9) // 16-15 delta(Hit #10) // 14-12 delta(Hit #11) // 11-10 <unused> // 9-5 Hit #12 // 4-0 kSpecialHit // ---------------------- byte_size = 25; // Add this 1 hit. The PL is currently in the NOT_FULL state and should // transition to the ALMOST_FULL state - even though there is still some // unused space. num_could_fit = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( &hits_in[0], hits_in.size(), false); EXPECT_THAT(num_could_fit, Eq(hits_in.size())); EXPECT_THAT(byte_size, Eq(pl_used.BytesUsed())); // All hits from hits_in were added. std::transform(hits_in.rbegin(), hits_in.rend(), std::front_inserter(hits_pushed), HitElt::get_hit); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAreArray(hits_pushed))); first_hit = CreateHit(hits_in.begin()->hit, /*desired_byte_length=*/1); hits_in.clear(); hits_in.emplace_back(first_hit); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/2)); std::reverse(hits_in.begin(), hits_in.end()); // ---------------------- // 29 delta(Hit #1) // 28 delta(Hit #2) // 27 delta(Hit #3) // 26 delta(Hit #4) // 25 delta(Hit #5) // 24-23 delta(Hit #6) // 22 delta(Hit #7) // 21-20 delta(Hit #8) // 19-17 delta(Hit #9) // 16-15 delta(Hit #10) // 14-12 delta(Hit #11) // 11 delta(Hit #12) // 10 <unused> // 9-5 Hit #13 // 4-0 Hit #14 // ---------------------- // Add these 2 hits. The PL is currently in the ALMOST_FULL state. Adding the // first hit should keep the PL in ALMOST_FULL because the delta between Hit // #12 and Hit #13 (1 byte) can fit in the unused area (2 bytes). Adding the // second hit should tranisition to the FULL state because the delta between // Hit #13 and Hit #14 (2 bytes) is larger than the remaining unused area // (1 byte). num_could_fit = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( &hits_in[0], hits_in.size(), false); EXPECT_THAT(num_could_fit, Eq(hits_in.size())); EXPECT_THAT(size, Eq(pl_used.BytesUsed())); // All hits from hits_in were added. std::transform(hits_in.rbegin(), hits_in.rend(), std::front_inserter(hits_pushed), HitElt::get_hit); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAreArray(hits_pushed))); } TEST(PostingListTest, PostingListPrependHitArrayTooManyHits) { static constexpr int kNumHits = 128; static constexpr int kDeltaSize = 1; static constexpr int kTermFrequencySize = 1; static constexpr size_t kHitsSize = ((kNumHits * (kDeltaSize + kTermFrequencySize)) / 5) * 5; std::unique_ptr<char[]> hits_buf = std::make_unique<char[]>(kHitsSize); // Create an array with one too many hits vector<Hit> hits_in_too_many = CreateHits(kNumHits + 1, /*desired_byte_length=*/1); vector<HitElt> hit_elts_in_too_many; for (const Hit &hit : hits_in_too_many) { hit_elts_in_too_many.emplace_back(hit); } ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf.get()), posting_list_utils::min_posting_list_size())); // PrependHitArray should fail because hit_elts_in_too_many is far too large // for the minimum size pl. uint32_t num_could_fit = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( &hit_elts_in_too_many[0], hit_elts_in_too_many.size(), false); ASSERT_THAT(num_could_fit, Lt(hit_elts_in_too_many.size())); ASSERT_THAT(pl_used.BytesUsed(), Eq(0)); ASSERT_THAT(pl_used.GetHits(), IsOkAndHolds(IsEmpty())); ICING_ASSERT_OK_AND_ASSIGN( pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf.get()), kHitsSize)); // PrependHitArray should fail because hit_elts_in_too_many is one hit too // large for this pl. num_could_fit = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( &hit_elts_in_too_many[0], hit_elts_in_too_many.size(), false); ASSERT_THAT(num_could_fit, Lt(hit_elts_in_too_many.size())); ASSERT_THAT(pl_used.BytesUsed(), Eq(0)); ASSERT_THAT(pl_used.GetHits(), IsOkAndHolds(IsEmpty())); } TEST(PostingListTest, PostingListStatusJumpFromNotFullToFullAndBack) { const uint32_t pl_size = 3 * sizeof(Hit); char hits_buf[pl_size]; ICING_ASSERT_OK_AND_ASSIGN( PostingListUsed pl, PostingListUsed::CreateFromUnitializedRegion(hits_buf, pl_size)); ICING_ASSERT_OK(pl.PrependHit(Hit(Hit::kInvalidValue - 1, 0))); uint32_t bytes_used = pl.BytesUsed(); // Status not full. ASSERT_THAT(bytes_used, Le(pl_size - posting_list_utils::kSpecialHitsSize)); ICING_ASSERT_OK(pl.PrependHit(Hit(Hit::kInvalidValue >> 2, 0))); // Status should jump to full directly. ASSERT_THAT(pl.BytesUsed(), Eq(pl_size)); pl.PopFrontHits(1); // Status should return to not full as before. ASSERT_THAT(pl.BytesUsed(), Eq(bytes_used)); } TEST(PostingListTest, DeltaOverflow) { char hits_buf[1000]; ICING_ASSERT_OK_AND_ASSIGN( PostingListUsed pl, PostingListUsed::CreateFromUnitializedRegion(hits_buf, 4 * sizeof(Hit))); static const Hit::Value kOverflow[4] = { Hit::kInvalidValue >> 2, (Hit::kInvalidValue >> 2) * 2, (Hit::kInvalidValue >> 2) * 3, Hit::kInvalidValue - 1, }; // Fit at least 4 ordinary values. for (Hit::Value v = 0; v < 4; v++) { ICING_EXPECT_OK(pl.PrependHit(Hit(4 - v))); } // Cannot fit 4 overflow values. ICING_ASSERT_OK_AND_ASSIGN(pl, PostingListUsed::CreateFromUnitializedRegion( hits_buf, 4 * sizeof(Hit))); ICING_EXPECT_OK(pl.PrependHit(Hit(kOverflow[3]))); ICING_EXPECT_OK(pl.PrependHit(Hit(kOverflow[2]))); // Can fit only one more. ICING_EXPECT_OK(pl.PrependHit(Hit(kOverflow[1]))); EXPECT_THAT(pl.PrependHit(Hit(kOverflow[0])), StatusIs(libtextclassifier3::StatusCode::RESOURCE_EXHAUSTED)); } TEST(PostingListTest, MoveFrom) { int size = 3 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf1 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used1, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf1.get()), size)); std::vector<Hit> hits1 = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/1); for (const Hit &hit : hits1) { ICING_ASSERT_OK(pl_used1.PrependHit(hit)); } std::unique_ptr<char[]> hits_buf2 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used2, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf2.get()), size)); std::vector<Hit> hits2 = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/2); for (const Hit &hit : hits2) { ICING_ASSERT_OK(pl_used2.PrependHit(hit)); } ICING_ASSERT_OK(pl_used2.MoveFrom(&pl_used1)); EXPECT_THAT(pl_used2.GetHits(), IsOkAndHolds(ElementsAreArray(hits1.rbegin(), hits1.rend()))); EXPECT_THAT(pl_used1.GetHits(), IsOkAndHolds(IsEmpty())); } TEST(PostingListTest, MoveFromNullArgumentReturnsInvalidArgument) { int size = 3 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf1 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used1, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf1.get()), size)); std::vector<Hit> hits = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/1); for (const Hit &hit : hits) { ICING_ASSERT_OK(pl_used1.PrependHit(hit)); } EXPECT_THAT(pl_used1.MoveFrom(/*other=*/nullptr), StatusIs(libtextclassifier3::StatusCode::FAILED_PRECONDITION)); EXPECT_THAT(pl_used1.GetHits(), IsOkAndHolds(ElementsAreArray(hits.rbegin(), hits.rend()))); } TEST(PostingListTest, MoveFromInvalidPostingListReturnsInvalidArgument) { int size = 3 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf1 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used1, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf1.get()), size)); std::vector<Hit> hits1 = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/1); for (const Hit &hit : hits1) { ICING_ASSERT_OK(pl_used1.PrependHit(hit)); } std::unique_ptr<char[]> hits_buf2 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used2, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf2.get()), size)); std::vector<Hit> hits2 = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/2); for (const Hit &hit : hits2) { ICING_ASSERT_OK(pl_used2.PrependHit(hit)); } // Write invalid hits to the beginning of pl_used1 to make it invalid. Hit invalid_hit; Hit *first_hit = reinterpret_cast<Hit *>(hits_buf1.get()); *first_hit = invalid_hit; ++first_hit; *first_hit = invalid_hit; EXPECT_THAT(pl_used2.MoveFrom(&pl_used1), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT)); EXPECT_THAT(pl_used2.GetHits(), IsOkAndHolds(ElementsAreArray(hits2.rbegin(), hits2.rend()))); } TEST(PostingListTest, MoveToInvalidPostingListReturnsInvalidArgument) { int size = 3 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf1 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used1, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf1.get()), size)); std::vector<Hit> hits1 = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/1); for (const Hit &hit : hits1) { ICING_ASSERT_OK(pl_used1.PrependHit(hit)); } std::unique_ptr<char[]> hits_buf2 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used2, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf2.get()), size)); std::vector<Hit> hits2 = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/2); for (const Hit &hit : hits2) { ICING_ASSERT_OK(pl_used2.PrependHit(hit)); } // Write invalid hits to the beginning of pl_used2 to make it invalid. Hit invalid_hit; Hit *first_hit = reinterpret_cast<Hit *>(hits_buf2.get()); *first_hit = invalid_hit; ++first_hit; *first_hit = invalid_hit; EXPECT_THAT(pl_used2.MoveFrom(&pl_used1), StatusIs(libtextclassifier3::StatusCode::FAILED_PRECONDITION)); EXPECT_THAT(pl_used1.GetHits(), IsOkAndHolds(ElementsAreArray(hits1.rbegin(), hits1.rend()))); } TEST(PostingListTest, MoveToPostingListTooSmall) { int size = 3 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf1 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used1, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf1.get()), size)); std::vector<Hit> hits1 = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/1); for (const Hit &hit : hits1) { ICING_ASSERT_OK(pl_used1.PrependHit(hit)); } std::unique_ptr<char[]> hits_buf2 = std::make_unique<char[]>(posting_list_utils::min_posting_list_size()); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used2, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf2.get()), posting_list_utils::min_posting_list_size())); std::vector<Hit> hits2 = CreateHits(/*num_hits=*/1, /*desired_byte_length=*/2); for (const Hit &hit : hits2) { ICING_ASSERT_OK(pl_used2.PrependHit(hit)); } EXPECT_THAT(pl_used2.MoveFrom(&pl_used1), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT)); EXPECT_THAT(pl_used1.GetHits(), IsOkAndHolds(ElementsAreArray(hits1.rbegin(), hits1.rend()))); EXPECT_THAT(pl_used2.GetHits(), IsOkAndHolds(ElementsAreArray(hits2.rbegin(), hits2.rend()))); } TEST(PostingListTest, PopHitsWithScores) { int size = 2 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf1 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf1.get()), size)); // This posting list is 20-bytes. Create four hits that will have deltas of // two bytes each and all of whom will have a non-default score. This posting // list will be almost_full. // // ---------------------- // 19 score(Hit #0) // 18-17 delta(Hit #0) // 16 score(Hit #1) // 15-14 delta(Hit #1) // 13 score(Hit #2) // 12-11 delta(Hit #2) // 10 <unused> // 9-5 Hit #3 // 4-0 kInvalidHitVal // ---------------------- Hit hit0(/*section_id=*/0, /*document_id=*/0, /*score=*/5); Hit hit1 = CreateHit(hit0, /*desired_byte_length=*/2); Hit hit2 = CreateHit(hit1, /*desired_byte_length=*/2); Hit hit3 = CreateHit(hit2, /*desired_byte_length=*/2); ICING_ASSERT_OK(pl_used.PrependHit(hit0)); ICING_ASSERT_OK(pl_used.PrependHit(hit1)); ICING_ASSERT_OK(pl_used.PrependHit(hit2)); ICING_ASSERT_OK(pl_used.PrependHit(hit3)); ICING_ASSERT_OK_AND_ASSIGN(std::vector<Hit> hits_out, pl_used.GetHits()); EXPECT_THAT(hits_out, ElementsAre(hit3, hit2, hit1, hit0)); // Now, pop the last hit. The posting list should contain the first three // hits. // // ---------------------- // 19 score(Hit #0) // 18-17 delta(Hit #0) // 16 score(Hit #1) // 15-14 delta(Hit #1) // 13-10 <unused> // 9-5 Hit #2 // 4-0 kInvalidHitVal // ---------------------- ICING_ASSERT_OK(pl_used.PopFrontHits(1)); ICING_ASSERT_OK_AND_ASSIGN(hits_out, pl_used.GetHits()); EXPECT_THAT(hits_out, ElementsAre(hit2, hit1, hit0)); } } // namespace lib } // namespace icing
29,450
11,514
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2015, xuewen.chu * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of xuewen.chu nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL xuewen.chu BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ***** END LICENSE BLOCK ***** */ #include "ftr/sys.h" #include "ftr/util/buffer.h" #include "font-1.h" #include "native-font.h" #include "ftr/bezier.h" #include "ftr/texture.h" #include "ftr/display-port.h" #include "ftr/draw.h" #include "ftr/app.h" #include "ftr/app-1.h" #include "font.cc.levels.inl" #include "font.cc.all.inl" #ifndef FX_SUPPORT_MAX_TEXTURE_FONT_SIZE #define FX_SUPPORT_MAX_TEXTURE_FONT_SIZE 512 #endif FX_NS(ftr) static String THIN_("thin"); static String ULTRALIGHT_("ultralight"); static String BOOK_("book"); static String LIGHT_("light"); static String REGULAR_("regular"); static String NORMAL_("normal"); static String MEDIUM_("medium"); static String DEMI_("demi"); static String SEMIBOLD_("semibold"); static String ROMAN_("roman"); static String BOLD_("bold"); static String CONDENSED_("condensed"); static String HEAVY_("heavy"); static String BLACK_("black"); static String ITALIC_("italic"); static String OBLIQUE_("oblique"); /** * @class FontPool::Inl */ class FontPool::Inl: public FontPool { public: #define _inl_pool(self) static_cast<FontPool::Inl*>(self) /** * @func initialize_default_fonts() */ void initialize_default_fonts(); /** * @fucn m_add_font */ bool register_font( cString& family_name, cString& font_name, TextStyleEnum style, uint num_glyphs, uint face_index, int height, /* text height in 26.6 frac. pixels */ int max_advance, /* max horizontal advance, in 26.6 pixels */ int ascender, /* ascender in 26.6 frac. pixels */ int descender, /* descender in 26.6 frac. pixels */ int underline_position, int underline_thickness, cString& path, FontFromData::Data* data ) { if ( ! path.is_empty() ) { // 文件 if ( ! FileHelper::is_file_sync(path) ) return false; m_paths[path] = family_name; } else if ( !data || !data->value ) { return false; } String font_name_ = font_name; /* FX_DEBUG("family_name:%s, font_name:%s, %s, ------%dkb%s", *family_name, *font_name, *path, uint(FileHelper::stat_sync(path).size() / 1024), m_fonts.has(font_name) ? "+++++++++++": ""); */ for (int i = 1; m_fonts.has(font_name_); i++ ) { // 重复的字体名称 font_name_ = font_name + "_" + i; } FontFamily* family = nullptr; auto i = m_familys.find(family_name); if ( i != m_familys.end() ) { family = i.value(); } else { family = new FontFamily(family_name); m_familys[family_name] = family; m_blend_fonts[family_name] = family; // 替换别名 } Font* font = nullptr; if ( path.is_empty() ) { font = new FontFromData(data); } else { font = new FontFromFile(path); } _inl_font(font)->initialize(this, family, font_name_, style, num_glyphs, face_index, height, max_advance, ascender, descender, underline_position, underline_thickness, (FT_Library)m_ft_lib); m_fonts[font_name_] = font; if ( font_name_ != family_name ) { // 与家族名称相同忽略 m_blend_fonts[font_name_] = font; } _inl_family(family)->add_font(font); return true; } bool register_font(FontFromData::Data* font_data, cString& family_alias) { Handle<FontFromData::Data> _font_data = font_data; const FT_Byte* data = font_data->value; FT_Face face; FT_Error err = FT_New_Memory_Face((FT_Library)m_ft_lib, data, font_data->length, 0, &face); if (err) { FX_ERR("Unable to load font, Freetype2 error code: %d", err); } else if (!face->family_name) { FX_ERR("Unable to load font, not family name"); } else { FT_Long num_faces = face->num_faces; String family_name = face->family_name; int face_index = 0; while (1) { if (face->charmap && face->charmap->encoding == FT_ENCODING_UNICODE && // 必须要有unicode编码表 FT_IS_SCALABLE(face) // 必须为矢量字体 ) { // 以64 pem 为标准 float ratio = face->units_per_EM / 4096.0 /*( 64 * 64 = 4096 )*/; int height = face->height / ratio; int max_advance_width = face->max_advance_width / ratio; int ascender = face->ascender / ratio; int descender = -face->descender / ratio; int underline_position = face->underline_position; int underline_thickness = face->underline_thickness; String name = FT_Get_Postscript_Name(face); if (! register_font(family_name, name, parse_style_flags(name, face->style_name), (uint)face->num_glyphs, face_index, height, max_advance_width, ascender, descender, underline_position, underline_thickness, String(), font_data) ) { return false; } } face_index++; FT_Done_Face(face); if (face_index < num_faces) { err = FT_New_Memory_Face((FT_Library)m_ft_lib, data, font_data->length, face_index, &face); if (err) { FX_ERR("Unable to load font, Freetype2 error code: %d", err); return false; } } else { break; } } // set family_alias set_family_alias(family_name, family_alias); return true; } return false; } /** * @func display_port_change_handle */ void display_port_change_handle(Event<>& evt) { Vec2 scale_value = m_display_port->scale_value(); float scale = FX_MAX(scale_value[0], scale_value[1]); if ( scale != m_display_port_scale ) { if ( m_display_port_scale != 0.0 ) { // 缩放改变影响字型纹理,所有全部清理 clear(true); } m_display_port_scale = scale; m_draw_ctx->host()->render_loop()->post(Cb([this](CbD& e) { m_draw_ctx->refresh_font_pool(this); _inl_app(m_draw_ctx->host())->refresh_display(); })); Vec2 size = m_display_port->size(); uint font_size = sqrtf(size.width() * size.height()) / 10; // 最大纹理字体不能超过上下文支持的大小 if (font_size >= FX_SUPPORT_MAX_TEXTURE_FONT_SIZE) { m_max_glyph_texture_size = FX_SUPPORT_MAX_TEXTURE_FONT_SIZE; } else { m_max_glyph_texture_size = font_glyph_texture_levels_idx[font_size].max_font_size; } } } static bool has_italic_style(cString& style_name) { return style_name.index_of(ITALIC_) != -1 || style_name.index_of(OBLIQUE_) != -1; } /** * @func parse_style_flag() */ static TextStyleEnum parse_style_flags(cString& name, cString& style_name) { String str = style_name.to_lower_case(); if ( str.index_of(THIN_) != -1 ) { return has_italic_style(str) ? TextStyleEnum::THIN_ITALIC : TextStyleEnum::THIN; } if ( str.index_of(ULTRALIGHT_) != -1 || str.index_of(BOOK_) != -1 ) { return has_italic_style(str) ? TextStyleEnum::ULTRALIGHT_ITALIC : TextStyleEnum::ULTRALIGHT; } if ( str.index_of(LIGHT_) != -1 ) { return has_italic_style(str) ? TextStyleEnum::LIGHT_ITALIC : TextStyleEnum::LIGHT; } if ( str.index_of(REGULAR_) != -1 || str.index_of(NORMAL_) != -1 ) { return has_italic_style(str) ? TextStyleEnum::ITALIC : TextStyleEnum::REGULAR; } if ( str.index_of(MEDIUM_) != -1 || str.index_of(DEMI_) != -1 ) { return has_italic_style(str) ? TextStyleEnum::MEDIUM_ITALIC : TextStyleEnum::MEDIUM; } if ( str.index_of(SEMIBOLD_) != -1 || str.index_of(ROMAN_) != -1 ) { return has_italic_style(str) ? TextStyleEnum::SEMIBOLD_ITALIC : TextStyleEnum::SEMIBOLD; } if ( str.index_of(BOLD_) != -1 || str.index_of(CONDENSED_) != -1 ) { return has_italic_style(str) ? TextStyleEnum::BOLD_ITALIC : TextStyleEnum::BOLD; } if ( str.index_of(HEAVY_) != -1 ) { return has_italic_style(str) ? TextStyleEnum::HEAVY_ITALIC : TextStyleEnum::HEAVY; } if ( str.index_of(BLACK_) != -1 ) { return has_italic_style(str) ? TextStyleEnum::BLACK_ITALIC : TextStyleEnum::BLACK; } return TextStyleEnum::OTHER; } /** * @func inl_read_font_file */ static Handle<FontPool::SimpleFontFamily> inl_read_font_file(cString& path, FT_Library lib) { FT_Face face; FT_Error err = FT_New_Face(lib, Path::fallback_c(path), 0, &face); if (err) { FX_WARN("Unable to load font file \"%s\", Freetype2 error code: %d", *path, err); } else if (!face->family_name) { FX_WARN("Unable to load font file \"%s\", not family name", *path); } else { FT_Long num_faces = face->num_faces; Handle<FontPool::SimpleFontFamily> sff = new FontPool::SimpleFontFamily(); sff->path = path; sff->family = face->family_name; int face_index = 0; while (1) { if (face->charmap && face->charmap->encoding == FT_ENCODING_UNICODE && // 必须要有unicode编码表 FT_IS_SCALABLE(face) // 必须为矢量字体 ) { FT_Set_Char_Size(face, 0, 64 * 64, 72, 72); // 以64 pt 为标准 float ratio = face->units_per_EM / 4096.0 /*( 64 * 64 = 4096 )*/; int height = face->height / ratio; int max_advance_width = face->max_advance_width / ratio; int ascender = face->ascender / ratio; int descender = -face->descender / ratio; int underline_position = face->underline_position; int underline_thickness = face->underline_thickness; String name = FT_Get_Postscript_Name(face); DLOG("------------inl_read_font_file, %s, %s", *name, face->style_name); sff->fonts.push({ name, parse_style_flags(name, face->style_name), (uint)face->num_glyphs, height, max_advance_width, ascender, descender, underline_position, underline_thickness }); } face_index++; FT_Done_Face(face); if (face_index < num_faces) { err = FT_New_Face(lib, Path::fallback_c(path), face_index, &face); if (err) { FX_WARN("Unable to load font file \"%s\", Freetype2 error code: %d", *path, err); break; } } else { if (sff->fonts.length()) return sff; else break; } } } return Handle<FontPool::SimpleFontFamily>(); } }; /** * @constructor */ FontPool::FontPool(Draw* ctx) : m_ft_lib(nullptr) , m_draw_ctx(ctx) , m_display_port(nullptr) , m_total_data_size(0) , m_max_glyph_texture_size(0) , m_display_port_scale(0) { ASSERT(m_draw_ctx); FT_Init_FreeType((FT_Library*)&m_ft_lib); { // 载入内置字体 uint count = sizeof(native_fonts_) / sizeof(Native_font_data_); for (uint i = 0 ; i < count; i++) { WeakBuffer data((cchar*)native_fonts_[i].data, native_fonts_[i].count); auto font_data = new FontFromData::Data(data); // LOG("register_font,%d", i); _inl_pool(this)->register_font(font_data, i == 1 ? "icon" : String()); // LOG("register_font ok,%d", i); } if ( m_familys.has("langou") ) { // LOG("m_familys.has langou ok"); // 这个内置字体必须载入成功,否则退出程序 // 把载入的一个内置字体做为默认备用字体,当没有任何字体可用时候,使用这个内置字体 m_spare_family = m_familys["langou"]; } else { FX_FATAL("Unable to initialize ftr font"); } } { // 载入系统字体 const Array<SimpleFontFamily>& arr = system_font_family(); for (auto i = arr.begin(), e = arr.end(); i != e; i++) { const SimpleFontFamily& sffd = i.value(); for (uint i = 0; i < sffd.fonts.length(); i++) { const SimpleFont& sfd = sffd.fonts[i]; _inl_pool(this)->register_font(sffd.family, sfd.name, sfd.style, sfd.num_glyphs, i, sfd.height, sfd.max_advance, sfd.ascender, sfd.descender, sfd.underline_position, sfd.underline_thickness, sffd.path, nullptr); // end for } } } _inl_pool(this)->initialize_default_fonts(); // 设置默认字体列表 } /** * @destructor */ FontPool::~FontPool() { for ( auto& i : m_familys ) { Release(i.value()); // delete } for ( auto& i : m_fonts ) { Release(i.value()); // delete } for ( auto& i : m_tables ) { Release(i.value()); // delete } m_familys.clear(); m_fonts.clear(); m_tables.clear(); m_blend_fonts.clear(); m_default_fonts.clear(); FT_Done_FreeType((FT_Library)m_ft_lib); m_ft_lib = nullptr; if ( m_display_port ) { m_display_port->FX_OFF(change, &Inl::display_port_change_handle, _inl_pool(this)); } } /** * @func set_default_fonts # 尝试设置默认字体 * @arg first {const Array<String>*} # 第一字体列表 * @arg ... {const Array<String>*} # 第2/3/4..字体列表 */ void FontPool::set_default_fonts(const Array<String>* first, ...) { m_default_fonts.clear(); Map<String, bool> has; auto end = m_blend_fonts.end(); for (uint i = 0; i < first->length(); i++) { auto j = m_blend_fonts.find(first->item(i)); if (j != end) { has.set(j.value()->name(), true); m_default_fonts.push(j.value()); break; } } va_list arg; va_start(arg, first); const Array<String>* ls = va_arg(arg, const Array<String>*); while (ls) { for (uint i = 0; i < ls->length(); i++) { auto j = m_blend_fonts.find(ls->item(i)); if (j != end) { if ( ! has.has(j.value()->name()) ) { has.set(j.value()->name(), true); m_default_fonts.push(j.value()); } break; } } ls = va_arg(arg, const Array<String>*); } va_end(arg); if ( !has.has(m_spare_family->name()) ) { m_default_fonts.push(m_spare_family); } } /** * @func set_default_fonts # 在当前字体库找到字体名称,设置才能生效 * @arg fonts {const Array<String>&} # 要设置的默认字体的名称 */ void FontPool::set_default_fonts(const Array<String>& fonts) { m_default_fonts.clear(); Map<String, bool> has; auto end = m_blend_fonts.end(); for (uint i = 0; i < fonts.length(); i++) { auto j = m_blend_fonts.find(fonts[i].trim()); if (j != end) { if ( ! has.has(j.value()->name()) ) { has.set(j.value()->name(), true); m_default_fonts.push(j.value()); } } } if ( !has.has(m_spare_family->name()) ) { m_default_fonts.push(m_spare_family); } } /** * @func default_font_names */ Array<String> FontPool::default_font_names() const { Array<String> rev; for (uint i = 0; i < m_default_fonts.length(); i++) rev.push(m_default_fonts[i]->name()); return rev; } /** * @func font_names() */ Array<String> FontPool::font_names(cString& family_name) const { FontFamily* ff = const_cast<FontPool*>(this)->get_font_family(family_name); return ff ? ff->font_names() : Array<String>(); } /** * @func get_font_family() */ FontFamily* FontPool::get_font_family(cString& family_name) { auto i = m_familys.find(family_name); return i == m_familys.end() ? NULL : i.value(); } /** * @func get_font # 通过名称获得一个字体对像 * @arg name {cString&} # 字体名称或家族名称 * @arg [style = fs_regular] {Font::TextStyle} * @ret {Font*} */ Font* FontPool::get_font(cString& name, TextStyleEnum style) { auto i = m_blend_fonts.find(name); return i == m_blend_fonts.end() ? NULL : i.value()->font(style); } /** * @func get_group # 通过字体名称列表获取字型集合 * @arg id {cFFID} # cFFID * @arg [style = fs_regular] {Font::TextStyle} # 使用的字体家族才生效 */ FontGlyphTable* FontPool::get_table(cFFID ffid, TextStyleEnum style) { ASSERT(ffid); uint code = ffid->code() + (uint)style; auto i = m_tables.find(code); if ( !i.is_null() ) { return i.value(); } FontGlyphTable* table = new FontGlyphTable(); _inl_table(table)->initialize(ffid, style, this); m_tables.set(code, table); return table; } /** * @func get_table # 获取默认字型集合 * @arg [style = fs_regular] {TextStyleEnum} */ FontGlyphTable* FontPool::get_table(TextStyleEnum style) { return get_table(get_font_familys_id(String()), style); } /** * @func register_font # 通过Buffer数据注册字体 * @arg buff {cBuffer} # 字体数据 * @arg [family_alias = String()] {cString&} # 给所属家族添加一个别名 */ bool FontPool::register_font(Buffer buff, cString& family_alias) { DLOG("register_font,%d", buff.length()); return _inl_pool(this)->register_font(new FontFromData::Data(buff), family_alias); } /** * @func register_font_file # 注册本地字体文件 * @arg path {cString&} # 字体文件的本地路径 * @arg [family_alias = String()] {cString&} # 给所属家族添加一个别名 */ bool FontPool::register_font_file(cString& path, cString& family_alias) { if (!m_paths.has(path) ) { // Handle<SimpleFontFamily> sffd = Inl::inl_read_font_file(path, (FT_Library)m_ft_lib); if ( !sffd.is_null() ) { for (uint i = 0; i < sffd->fonts.length(); i++) { SimpleFont& sfd = sffd->fonts[i]; if (! _inl_pool(this)->register_font(sffd->family, sfd.name, sfd.style, sfd.num_glyphs, i, sfd.height, sfd.max_advance, sfd.ascender, sfd.descender, sfd.underline_position, sfd.underline_thickness, sffd->path, nullptr) ) { return false; } } // set family_alias set_family_alias(sffd->family, family_alias); return true; } } return false; } /** * @func set_family_alias */ void FontPool::set_family_alias(cString& family, cString& alias) { if ( ! alias.is_empty() ) { auto i = m_blend_fonts.find(family); if (i != m_blend_fonts.end() && !m_blend_fonts.has(alias)) { m_blend_fonts[alias] = i.value(); // 设置一个别名 } } } /** * @func clear(full) 释放池中不用的字体数据 * @arg [full = false] {bool} # 全面清理资源尽可能最大程度清理 */ void FontPool::clear(bool full) { for ( auto& i : m_tables ) { _inl_table(i.value())->clear_table(); } for ( auto& i : m_fonts ) { _inl_font(i.value())->clear(full); } } /** * @func set_display_port */ void FontPool::set_display_port(DisplayPort* display_port) { ASSERT(!m_display_port); display_port->FX_ON(change, &Inl::display_port_change_handle, _inl_pool(this)); m_display_port = display_port; } /** * @func get_glyph_texture_level 通过字体尺寸获取纹理等级,与纹理大小font_size */ FGTexureLevel FontPool::get_glyph_texture_level(float& font_size_out) { if (font_size_out > m_max_glyph_texture_size) { return FontGlyph::LEVEL_NONE; } uint index = ceilf(font_size_out); FontGlyphTextureLevel leval = font_glyph_texture_levels_idx[index]; font_size_out = leval.max_font_size; return leval.level; } /** * @func get_family_name(path) get current register family name by font file path */ String FontPool::get_family_name(cString& path) const { auto it = m_paths.find(path); if ( it.is_null() ) { return String(); } return it.value(); } /** * @func get_glyph_texture_level # 根据字体尺寸获取纹理等级 */ float FontPool::get_glyph_texture_size(FGTexureLevel leval) { ASSERT( leval < FontGlyph::LEVEL_NONE ); const float glyph_texture_levels_size[13] = { 10, 12, 14, 16, 18, 20, 25, 32, 64, 128, 256, 512, 0 }; return glyph_texture_levels_size[leval]; } /** * @func default_font_familys_id */ static cFFID default_font_familys_id() { static FontFamilysID* id = nullptr; // default group i if ( ! id ) { id = new FontFamilysID(); _inl_ff_id(id)->initialize(Array<String>()); } return id; } /** * @func get_font_familys_id */ cFFID FontPool::get_font_familys_id(const Array<String> fonts) { static Map<uint, FontFamilysID*> ffids; // global groups // TODO: 这里如果是同一个字体的不同别名会导致不相同的`ID` if ( fonts.length() ) { FontFamilysID id; _inl_ff_id(&id)->initialize(fonts); auto it = ffids.find(id.code()); if (it != ffids.end()) { return it.value(); } else { FontFamilysID* id_p = new FontFamilysID(move( id )); ffids.set ( id_p->code(), id_p ); return id_p; } } else { return default_font_familys_id(); } } /** * @func read_font_file */ Handle<FontPool::SimpleFontFamily> FontPool::read_font_file(cString& path) { FT_Library lib; FT_Init_FreeType(&lib); ScopeClear clear([&lib]() { FT_Done_FreeType(lib); }); return Inl::inl_read_font_file(path, lib); } /** * @func get_font_familys_id */ cFFID FontPool::get_font_familys_id(cString fonts) { if ( fonts.is_empty() ) { return default_font_familys_id(); } else { Array<String> ls = fonts.split(','); Array<String> ls2; for (int i = 0, len = ls.length(); i < len; i++) { String name = ls[i].trim(); if ( ! name.is_empty() ) { ls2.push(name); } } return get_font_familys_id(ls2); } } FX_END #include "font.cc.init.inl"
21,557
9,958
/** * PowerMeter API * API * * The version of the OpenAPI document: 2021.4.1 * * NOTE: This class is auto generated by OpenAPI-Generator 4.3.1. * https://openapi-generator.tech * Do not edit the class manually. */ #include "PinEnergy.h" namespace powermeter { namespace model { PinEnergy::PinEnergy() { m_Id = 0; m_IdIsSet = false; m_Pin = 0; m_PinIsSet = false; m_Pin_name = utility::conversions::to_string_t(""); m_Pin_nameIsSet = false; m_Related_pin = 0; m_Related_pinIsSet = false; m_Related_pin_name = utility::conversions::to_string_t(""); m_Related_pin_nameIsSet = false; m_Supply = 0; m_SupplyIsSet = false; m_Supply_name = utility::conversions::to_string_t(""); m_Supply_nameIsSet = false; m_Process = utility::conversions::to_string_t(""); m_ProcessIsSet = false; m_Rc = utility::conversions::to_string_t(""); m_RcIsSet = false; m_Voltage = 0.0; m_VoltageIsSet = false; m_Temperature = 0; m_TemperatureIsSet = false; m_When = utility::conversions::to_string_t(""); m_WhenIsSet = false; m_Index1IsSet = false; m_Variable1 = utility::conversions::to_string_t(""); m_Variable1IsSet = false; m_Index2IsSet = false; m_Variable2 = utility::conversions::to_string_t(""); m_Variable2IsSet = false; m_Rise_energyIsSet = false; m_Fall_energyIsSet = false; m_ModesIsSet = false; } PinEnergy::~PinEnergy() { } void PinEnergy::validate() { // TODO: implement validation } web::json::value PinEnergy::toJson() const { web::json::value val = web::json::value::object(); if(m_IdIsSet) { val[utility::conversions::to_string_t("id")] = ModelBase::toJson(m_Id); } if(m_PinIsSet) { val[utility::conversions::to_string_t("pin")] = ModelBase::toJson(m_Pin); } if(m_Pin_nameIsSet) { val[utility::conversions::to_string_t("pin_name")] = ModelBase::toJson(m_Pin_name); } if(m_Related_pinIsSet) { val[utility::conversions::to_string_t("related_pin")] = ModelBase::toJson(m_Related_pin); } if(m_Related_pin_nameIsSet) { val[utility::conversions::to_string_t("related_pin_name")] = ModelBase::toJson(m_Related_pin_name); } if(m_SupplyIsSet) { val[utility::conversions::to_string_t("supply")] = ModelBase::toJson(m_Supply); } if(m_Supply_nameIsSet) { val[utility::conversions::to_string_t("supply_name")] = ModelBase::toJson(m_Supply_name); } if(m_ProcessIsSet) { val[utility::conversions::to_string_t("process")] = ModelBase::toJson(m_Process); } if(m_RcIsSet) { val[utility::conversions::to_string_t("rc")] = ModelBase::toJson(m_Rc); } if(m_VoltageIsSet) { val[utility::conversions::to_string_t("voltage")] = ModelBase::toJson(m_Voltage); } if(m_TemperatureIsSet) { val[utility::conversions::to_string_t("temperature")] = ModelBase::toJson(m_Temperature); } if(m_WhenIsSet) { val[utility::conversions::to_string_t("when")] = ModelBase::toJson(m_When); } if(m_Index1IsSet) { val[utility::conversions::to_string_t("index1")] = ModelBase::toJson(m_Index1); } if(m_Variable1IsSet) { val[utility::conversions::to_string_t("variable1")] = ModelBase::toJson(m_Variable1); } if(m_Index2IsSet) { val[utility::conversions::to_string_t("index2")] = ModelBase::toJson(m_Index2); } if(m_Variable2IsSet) { val[utility::conversions::to_string_t("variable2")] = ModelBase::toJson(m_Variable2); } if(m_Rise_energyIsSet) { val[utility::conversions::to_string_t("rise_energy")] = ModelBase::toJson(m_Rise_energy); } if(m_Fall_energyIsSet) { val[utility::conversions::to_string_t("fall_energy")] = ModelBase::toJson(m_Fall_energy); } if(m_ModesIsSet) { val[utility::conversions::to_string_t("modes")] = ModelBase::toJson(m_Modes); } return val; } bool PinEnergy::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("id")); if(!fieldValue.is_null()) { int32_t refVal_id; ok &= ModelBase::fromJson(fieldValue, refVal_id); setId(refVal_id); } } if(val.has_field(utility::conversions::to_string_t("pin"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("pin")); if(!fieldValue.is_null()) { int32_t refVal_pin; ok &= ModelBase::fromJson(fieldValue, refVal_pin); setPin(refVal_pin); } } if(val.has_field(utility::conversions::to_string_t("pin_name"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("pin_name")); if(!fieldValue.is_null()) { utility::string_t refVal_pin_name; ok &= ModelBase::fromJson(fieldValue, refVal_pin_name); setPinName(refVal_pin_name); } } if(val.has_field(utility::conversions::to_string_t("related_pin"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("related_pin")); if(!fieldValue.is_null()) { int32_t refVal_related_pin; ok &= ModelBase::fromJson(fieldValue, refVal_related_pin); setRelatedPin(refVal_related_pin); } } if(val.has_field(utility::conversions::to_string_t("related_pin_name"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("related_pin_name")); if(!fieldValue.is_null()) { utility::string_t refVal_related_pin_name; ok &= ModelBase::fromJson(fieldValue, refVal_related_pin_name); setRelatedPinName(refVal_related_pin_name); } } if(val.has_field(utility::conversions::to_string_t("supply"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("supply")); if(!fieldValue.is_null()) { int32_t refVal_supply; ok &= ModelBase::fromJson(fieldValue, refVal_supply); setSupply(refVal_supply); } } if(val.has_field(utility::conversions::to_string_t("supply_name"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("supply_name")); if(!fieldValue.is_null()) { utility::string_t refVal_supply_name; ok &= ModelBase::fromJson(fieldValue, refVal_supply_name); setSupplyName(refVal_supply_name); } } if(val.has_field(utility::conversions::to_string_t("process"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("process")); if(!fieldValue.is_null()) { utility::string_t refVal_process; ok &= ModelBase::fromJson(fieldValue, refVal_process); setProcess(refVal_process); } } if(val.has_field(utility::conversions::to_string_t("rc"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("rc")); if(!fieldValue.is_null()) { utility::string_t refVal_rc; ok &= ModelBase::fromJson(fieldValue, refVal_rc); setRc(refVal_rc); } } if(val.has_field(utility::conversions::to_string_t("voltage"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("voltage")); if(!fieldValue.is_null()) { double refVal_voltage; ok &= ModelBase::fromJson(fieldValue, refVal_voltage); setVoltage(refVal_voltage); } } if(val.has_field(utility::conversions::to_string_t("temperature"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("temperature")); if(!fieldValue.is_null()) { int32_t refVal_temperature; ok &= ModelBase::fromJson(fieldValue, refVal_temperature); setTemperature(refVal_temperature); } } if(val.has_field(utility::conversions::to_string_t("when"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("when")); if(!fieldValue.is_null()) { utility::string_t refVal_when; ok &= ModelBase::fromJson(fieldValue, refVal_when); setWhen(refVal_when); } } if(val.has_field(utility::conversions::to_string_t("index1"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("index1")); if(!fieldValue.is_null()) { std::vector<double> refVal_index1; ok &= ModelBase::fromJson(fieldValue, refVal_index1); setIndex1(refVal_index1); } } if(val.has_field(utility::conversions::to_string_t("variable1"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("variable1")); if(!fieldValue.is_null()) { utility::string_t refVal_variable1; ok &= ModelBase::fromJson(fieldValue, refVal_variable1); setVariable1(refVal_variable1); } } if(val.has_field(utility::conversions::to_string_t("index2"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("index2")); if(!fieldValue.is_null()) { std::vector<double> refVal_index2; ok &= ModelBase::fromJson(fieldValue, refVal_index2); setIndex2(refVal_index2); } } if(val.has_field(utility::conversions::to_string_t("variable2"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("variable2")); if(!fieldValue.is_null()) { utility::string_t refVal_variable2; ok &= ModelBase::fromJson(fieldValue, refVal_variable2); setVariable2(refVal_variable2); } } if(val.has_field(utility::conversions::to_string_t("rise_energy"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("rise_energy")); if(!fieldValue.is_null()) { std::vector<double> refVal_rise_energy; ok &= ModelBase::fromJson(fieldValue, refVal_rise_energy); setRiseEnergy(refVal_rise_energy); } } if(val.has_field(utility::conversions::to_string_t("fall_energy"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("fall_energy")); if(!fieldValue.is_null()) { std::vector<double> refVal_fall_energy; ok &= ModelBase::fromJson(fieldValue, refVal_fall_energy); setFallEnergy(refVal_fall_energy); } } if(val.has_field(utility::conversions::to_string_t("modes"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("modes")); if(!fieldValue.is_null()) { std::vector<int32_t> refVal_modes; ok &= ModelBase::fromJson(fieldValue, refVal_modes); setModes(refVal_modes); } } return ok; } void PinEnergy::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const { utility::string_t namePrefix = prefix; if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { namePrefix += utility::conversions::to_string_t("."); } if(m_IdIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("id"), m_Id)); } if(m_PinIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("pin"), m_Pin)); } if(m_Pin_nameIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("pin_name"), m_Pin_name)); } if(m_Related_pinIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("related_pin"), m_Related_pin)); } if(m_Related_pin_nameIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("related_pin_name"), m_Related_pin_name)); } if(m_SupplyIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("supply"), m_Supply)); } if(m_Supply_nameIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("supply_name"), m_Supply_name)); } if(m_ProcessIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("process"), m_Process)); } if(m_RcIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("rc"), m_Rc)); } if(m_VoltageIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("voltage"), m_Voltage)); } if(m_TemperatureIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("temperature"), m_Temperature)); } if(m_WhenIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("when"), m_When)); } if(m_Index1IsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("index1"), m_Index1)); } if(m_Variable1IsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("variable1"), m_Variable1)); } if(m_Index2IsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("index2"), m_Index2)); } if(m_Variable2IsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("variable2"), m_Variable2)); } if(m_Rise_energyIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("rise_energy"), m_Rise_energy)); } if(m_Fall_energyIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("fall_energy"), m_Fall_energy)); } if(m_ModesIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("modes"), m_Modes)); } } bool PinEnergy::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) { bool ok = true; utility::string_t namePrefix = prefix; if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { namePrefix += utility::conversions::to_string_t("."); } if(multipart->hasContent(utility::conversions::to_string_t("id"))) { int32_t refVal_id; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("id")), refVal_id ); setId(refVal_id); } if(multipart->hasContent(utility::conversions::to_string_t("pin"))) { int32_t refVal_pin; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("pin")), refVal_pin ); setPin(refVal_pin); } if(multipart->hasContent(utility::conversions::to_string_t("pin_name"))) { utility::string_t refVal_pin_name; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("pin_name")), refVal_pin_name ); setPinName(refVal_pin_name); } if(multipart->hasContent(utility::conversions::to_string_t("related_pin"))) { int32_t refVal_related_pin; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("related_pin")), refVal_related_pin ); setRelatedPin(refVal_related_pin); } if(multipart->hasContent(utility::conversions::to_string_t("related_pin_name"))) { utility::string_t refVal_related_pin_name; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("related_pin_name")), refVal_related_pin_name ); setRelatedPinName(refVal_related_pin_name); } if(multipart->hasContent(utility::conversions::to_string_t("supply"))) { int32_t refVal_supply; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("supply")), refVal_supply ); setSupply(refVal_supply); } if(multipart->hasContent(utility::conversions::to_string_t("supply_name"))) { utility::string_t refVal_supply_name; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("supply_name")), refVal_supply_name ); setSupplyName(refVal_supply_name); } if(multipart->hasContent(utility::conversions::to_string_t("process"))) { utility::string_t refVal_process; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("process")), refVal_process ); setProcess(refVal_process); } if(multipart->hasContent(utility::conversions::to_string_t("rc"))) { utility::string_t refVal_rc; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("rc")), refVal_rc ); setRc(refVal_rc); } if(multipart->hasContent(utility::conversions::to_string_t("voltage"))) { double refVal_voltage; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("voltage")), refVal_voltage ); setVoltage(refVal_voltage); } if(multipart->hasContent(utility::conversions::to_string_t("temperature"))) { int32_t refVal_temperature; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("temperature")), refVal_temperature ); setTemperature(refVal_temperature); } if(multipart->hasContent(utility::conversions::to_string_t("when"))) { utility::string_t refVal_when; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("when")), refVal_when ); setWhen(refVal_when); } if(multipart->hasContent(utility::conversions::to_string_t("index1"))) { std::vector<double> refVal_index1; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("index1")), refVal_index1 ); setIndex1(refVal_index1); } if(multipart->hasContent(utility::conversions::to_string_t("variable1"))) { utility::string_t refVal_variable1; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("variable1")), refVal_variable1 ); setVariable1(refVal_variable1); } if(multipart->hasContent(utility::conversions::to_string_t("index2"))) { std::vector<double> refVal_index2; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("index2")), refVal_index2 ); setIndex2(refVal_index2); } if(multipart->hasContent(utility::conversions::to_string_t("variable2"))) { utility::string_t refVal_variable2; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("variable2")), refVal_variable2 ); setVariable2(refVal_variable2); } if(multipart->hasContent(utility::conversions::to_string_t("rise_energy"))) { std::vector<double> refVal_rise_energy; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("rise_energy")), refVal_rise_energy ); setRiseEnergy(refVal_rise_energy); } if(multipart->hasContent(utility::conversions::to_string_t("fall_energy"))) { std::vector<double> refVal_fall_energy; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("fall_energy")), refVal_fall_energy ); setFallEnergy(refVal_fall_energy); } if(multipart->hasContent(utility::conversions::to_string_t("modes"))) { std::vector<int32_t> refVal_modes; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("modes")), refVal_modes ); setModes(refVal_modes); } return ok; } int32_t PinEnergy::getId() const { return m_Id; } void PinEnergy::setId(int32_t value) { m_Id = value; m_IdIsSet = true; } bool PinEnergy::idIsSet() const { return m_IdIsSet; } void PinEnergy::unsetId() { m_IdIsSet = false; } int32_t PinEnergy::getPin() const { return m_Pin; } void PinEnergy::setPin(int32_t value) { m_Pin = value; m_PinIsSet = true; } bool PinEnergy::pinIsSet() const { return m_PinIsSet; } void PinEnergy::unsetPin() { m_PinIsSet = false; } utility::string_t PinEnergy::getPinName() const { return m_Pin_name; } void PinEnergy::setPinName(const utility::string_t& value) { m_Pin_name = value; m_Pin_nameIsSet = true; } bool PinEnergy::pinNameIsSet() const { return m_Pin_nameIsSet; } void PinEnergy::unsetPin_name() { m_Pin_nameIsSet = false; } int32_t PinEnergy::getRelatedPin() const { return m_Related_pin; } void PinEnergy::setRelatedPin(int32_t value) { m_Related_pin = value; m_Related_pinIsSet = true; } bool PinEnergy::relatedPinIsSet() const { return m_Related_pinIsSet; } void PinEnergy::unsetRelated_pin() { m_Related_pinIsSet = false; } utility::string_t PinEnergy::getRelatedPinName() const { return m_Related_pin_name; } void PinEnergy::setRelatedPinName(const utility::string_t& value) { m_Related_pin_name = value; m_Related_pin_nameIsSet = true; } bool PinEnergy::relatedPinNameIsSet() const { return m_Related_pin_nameIsSet; } void PinEnergy::unsetRelated_pin_name() { m_Related_pin_nameIsSet = false; } int32_t PinEnergy::getSupply() const { return m_Supply; } void PinEnergy::setSupply(int32_t value) { m_Supply = value; m_SupplyIsSet = true; } bool PinEnergy::supplyIsSet() const { return m_SupplyIsSet; } void PinEnergy::unsetSupply() { m_SupplyIsSet = false; } utility::string_t PinEnergy::getSupplyName() const { return m_Supply_name; } void PinEnergy::setSupplyName(const utility::string_t& value) { m_Supply_name = value; m_Supply_nameIsSet = true; } bool PinEnergy::supplyNameIsSet() const { return m_Supply_nameIsSet; } void PinEnergy::unsetSupply_name() { m_Supply_nameIsSet = false; } utility::string_t PinEnergy::getProcess() const { return m_Process; } void PinEnergy::setProcess(const utility::string_t& value) { m_Process = value; m_ProcessIsSet = true; } bool PinEnergy::processIsSet() const { return m_ProcessIsSet; } void PinEnergy::unsetProcess() { m_ProcessIsSet = false; } utility::string_t PinEnergy::getRc() const { return m_Rc; } void PinEnergy::setRc(const utility::string_t& value) { m_Rc = value; m_RcIsSet = true; } bool PinEnergy::rcIsSet() const { return m_RcIsSet; } void PinEnergy::unsetRc() { m_RcIsSet = false; } double PinEnergy::getVoltage() const { return m_Voltage; } void PinEnergy::setVoltage(double value) { m_Voltage = value; m_VoltageIsSet = true; } bool PinEnergy::voltageIsSet() const { return m_VoltageIsSet; } void PinEnergy::unsetVoltage() { m_VoltageIsSet = false; } int32_t PinEnergy::getTemperature() const { return m_Temperature; } void PinEnergy::setTemperature(int32_t value) { m_Temperature = value; m_TemperatureIsSet = true; } bool PinEnergy::temperatureIsSet() const { return m_TemperatureIsSet; } void PinEnergy::unsetTemperature() { m_TemperatureIsSet = false; } utility::string_t PinEnergy::getWhen() const { return m_When; } void PinEnergy::setWhen(const utility::string_t& value) { m_When = value; m_WhenIsSet = true; } bool PinEnergy::whenIsSet() const { return m_WhenIsSet; } void PinEnergy::unsetWhen() { m_WhenIsSet = false; } std::vector<double>& PinEnergy::getIndex1() { return m_Index1; } void PinEnergy::setIndex1(std::vector<double> value) { m_Index1 = value; m_Index1IsSet = true; } bool PinEnergy::index1IsSet() const { return m_Index1IsSet; } void PinEnergy::unsetIndex1() { m_Index1IsSet = false; } utility::string_t PinEnergy::getVariable1() const { return m_Variable1; } void PinEnergy::setVariable1(const utility::string_t& value) { m_Variable1 = value; m_Variable1IsSet = true; } bool PinEnergy::variable1IsSet() const { return m_Variable1IsSet; } void PinEnergy::unsetVariable1() { m_Variable1IsSet = false; } std::vector<double>& PinEnergy::getIndex2() { return m_Index2; } void PinEnergy::setIndex2(std::vector<double> value) { m_Index2 = value; m_Index2IsSet = true; } bool PinEnergy::index2IsSet() const { return m_Index2IsSet; } void PinEnergy::unsetIndex2() { m_Index2IsSet = false; } utility::string_t PinEnergy::getVariable2() const { return m_Variable2; } void PinEnergy::setVariable2(const utility::string_t& value) { m_Variable2 = value; m_Variable2IsSet = true; } bool PinEnergy::variable2IsSet() const { return m_Variable2IsSet; } void PinEnergy::unsetVariable2() { m_Variable2IsSet = false; } std::vector<double>& PinEnergy::getRiseEnergy() { return m_Rise_energy; } void PinEnergy::setRiseEnergy(std::vector<double> value) { m_Rise_energy = value; m_Rise_energyIsSet = true; } bool PinEnergy::riseEnergyIsSet() const { return m_Rise_energyIsSet; } void PinEnergy::unsetRise_energy() { m_Rise_energyIsSet = false; } std::vector<double>& PinEnergy::getFallEnergy() { return m_Fall_energy; } void PinEnergy::setFallEnergy(std::vector<double> value) { m_Fall_energy = value; m_Fall_energyIsSet = true; } bool PinEnergy::fallEnergyIsSet() const { return m_Fall_energyIsSet; } void PinEnergy::unsetFall_energy() { m_Fall_energyIsSet = false; } std::vector<int32_t>& PinEnergy::getModes() { return m_Modes; } void PinEnergy::setModes(std::vector<int32_t> value) { m_Modes = value; m_ModesIsSet = true; } bool PinEnergy::modesIsSet() const { return m_ModesIsSet; } void PinEnergy::unsetModes() { m_ModesIsSet = false; } } }
26,817
9,751
/************************************************************************* * * * Vega FEM Simulation Library Version 4.0 * * * * "getopts" library , Copyright (C) 2018 USC * * All rights reserved. * * * * Code authors: Yijing Li, Jernej Barbic * * http://www.jernejbarbic.com/vega * * * * Research: Jernej Barbic, Hongyi Xu, Yijing Li, * * Danyong Zhao, Bohan Wang, * * Fun Shing Sin, Daniel Schroeder, * * Doug L. James, Jovan Popovic * * * * Funding: National Science Foundation, Link Foundation, * * Singapore-MIT GAMBIT Game Lab, * * Zumberge Research and Innovation Fund at USC, * * Sloan Foundation, Okawa Foundation, * * USC Annenberg Foundation * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the BSD-style license that is * * included with this library in the file LICENSE.txt * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * * LICENSE.TXT for more details. * * * *************************************************************************/ #include "commandLineParser.h" #include <iostream> #include <string> #include <stdlib.h> #include <string.h> #include <errno.h> #include <stdio.h> using namespace std; CommandLineParser::CommandLineParser() {} void CommandLineParser::addOption(const string & name, int & value) { entries.push_back(Entry(name, INT, (void*)&value)); } void CommandLineParser::addOption(const string & name, char * value) { entries.push_back(Entry(name, CSTR, (void*)value)); } void CommandLineParser::addOption(const string & name, bool & value) { entries.push_back(Entry(name, BOOL, (void*)&value)); } void CommandLineParser::addOption(const std::string & name, vegalong & value) { entries.push_back(Entry(name, LONG, (void*)&value)); } void CommandLineParser::addOption(const std::string & name, float & value) { entries.push_back(Entry(name, FLOAT, (void*)&value)); } void CommandLineParser::addOption(const std::string & name, double & value) { entries.push_back(Entry(name, DOUBLE, (void*)&value)); } void CommandLineParser::addOption(const std::string & name, std::string & value) { entries.push_back(Entry(name, STRING, (void*)&value)); } int CommandLineParser::parse(int argc, char ** argv, int numSkipArg) { return parse(argc, (const char**)argv, numSkipArg); } int CommandLineParser::parse(int argc, const char ** argv, int numSkipArg) { for (int i = numSkipArg; i < argc; i++) { const char * arg = argv[i]; // option begins with '-' or '/' if ((*arg != '-') && (*arg != '/')) return (i); arg++; // skip '-' or '/' for (size_t j = 0; j < entries.size(); j++) //find options for this arg { //options are case sensitive!! size_t l = entries[j].name.size(); //printf("%s\n", opttable[j].sw); if (strncmp(arg, entries[j].name.data(), l) == 0) //found this option { const char * var = nullptr; //pointers to the input data for this option // bool standAloneData = false; // whether the data for this arg is in a separate string, like -v 123 // There's ambiguity when a negative number arg is next to a switch, like -f -48.9 // For now we only intepret it as two successive switches // A smarter implementation could be to forbid switch name to start with numbers, and check whether the second "switch" // starts with "-\d" // if a data string follows this arg string, like: -v 123 if ( (strlen(arg) == l) && ( (i+1 < argc) && (argv[i+1] != nullptr) && ( argv[i+1][0] != '-' && argv[i+1][0] != '/' ) ) ) { // go to the next data string i++; var = argv[i]; // standAloneData = true; } else { //copy the rest in this arg string, like: -v123 if ( ( *(arg+l)=='=' ) || (*(arg+l)==' ') ) // accept '=' or ' ' after the switch var = arg + l + 1; else var = arg + l; } // if (*var == '\0') // continue; //printf("%d %s\n",i, var); switch (entries[j].type) { case INT : if (*var != '\0') { *((int *)entries[j].value) = (int)strtol(var,nullptr,10); if (errno == ERANGE) return (i); } else // the data is absent. We consider it an error return i; break; case LONG : if (*var != '\0') { *((vegalong *)entries[j].value) = strtol(var,nullptr,10); if (errno == ERANGE) return (i); } else return i; break; case FLOAT : if (*var != '\0') { *((float *)entries[j].value) = (float)strtod(var,nullptr); if (errno == ERANGE) return (i); } else return i; break; case DOUBLE : if (*var != '\0') { *((double *)entries[j].value) = strtod(var,nullptr); if (errno == ERANGE) return (i); } else return i; break; // case OPTSUBOPT : // //option with more than 1 char as suboptions: // // /oail or /op // strcpy((char *)opttable[j].var, arg+l); // arg += strlen(arg)-1; // break; case CSTR : if (*var != '\0') strcpy((char *)entries[j].value, var); else return i; break; case STRING : if (*var != '\0') *((string*)(entries[j].value)) = var; else return i; break; case BOOL : //check a + or - after the sw: "/a- /b+" { bool boolValue = true; if ( *var == '-' ) boolValue = false; else boolValue = true; *((bool *)entries[j].value) = boolValue; break; } } break; //break the for } // end if (strncmp(arg, entries[j].name.data(), l) == 0) //found this option } // end for (size_t j = 0; j < entries.size(); j++) } return argc; } CommandLineParser::Entry::Entry(const std::string & n, Type t, void * v) : name(n), type(t), value(v) {}
7,643
2,167
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html #include "precomp.hpp" #include "opencl_kernels_core.hpp" namespace cv { namespace hal { #if CV_NEON template<typename T> struct VSplit2; template<typename T> struct VSplit3; template<typename T> struct VSplit4; #define SPLIT2_KERNEL_TEMPLATE(name, data_type, reg_type, load_func, store_func) \ template<> \ struct name<data_type> \ { \ void operator()(const data_type* src, data_type* dst0, \ data_type* dst1) const \ { \ reg_type r = load_func(src); \ store_func(dst0, r.val[0]); \ store_func(dst1, r.val[1]); \ } \ } #define SPLIT3_KERNEL_TEMPLATE(name, data_type, reg_type, load_func, store_func) \ template<> \ struct name<data_type> \ { \ void operator()(const data_type* src, data_type* dst0, data_type* dst1, \ data_type* dst2) const \ { \ reg_type r = load_func(src); \ store_func(dst0, r.val[0]); \ store_func(dst1, r.val[1]); \ store_func(dst2, r.val[2]); \ } \ } #define SPLIT4_KERNEL_TEMPLATE(name, data_type, reg_type, load_func, store_func) \ template<> \ struct name<data_type> \ { \ void operator()(const data_type* src, data_type* dst0, data_type* dst1, \ data_type* dst2, data_type* dst3) const \ { \ reg_type r = load_func(src); \ store_func(dst0, r.val[0]); \ store_func(dst1, r.val[1]); \ store_func(dst2, r.val[2]); \ store_func(dst3, r.val[3]); \ } \ } SPLIT2_KERNEL_TEMPLATE(VSplit2, uchar , uint8x16x2_t, vld2q_u8 , vst1q_u8 ); SPLIT2_KERNEL_TEMPLATE(VSplit2, ushort, uint16x8x2_t, vld2q_u16, vst1q_u16); SPLIT2_KERNEL_TEMPLATE(VSplit2, int , int32x4x2_t, vld2q_s32, vst1q_s32); SPLIT2_KERNEL_TEMPLATE(VSplit2, int64 , int64x1x2_t, vld2_s64 , vst1_s64 ); SPLIT3_KERNEL_TEMPLATE(VSplit3, uchar , uint8x16x3_t, vld3q_u8 , vst1q_u8 ); SPLIT3_KERNEL_TEMPLATE(VSplit3, ushort, uint16x8x3_t, vld3q_u16, vst1q_u16); SPLIT3_KERNEL_TEMPLATE(VSplit3, int , int32x4x3_t, vld3q_s32, vst1q_s32); SPLIT3_KERNEL_TEMPLATE(VSplit3, int64 , int64x1x3_t, vld3_s64 , vst1_s64 ); SPLIT4_KERNEL_TEMPLATE(VSplit4, uchar , uint8x16x4_t, vld4q_u8 , vst1q_u8 ); SPLIT4_KERNEL_TEMPLATE(VSplit4, ushort, uint16x8x4_t, vld4q_u16, vst1q_u16); SPLIT4_KERNEL_TEMPLATE(VSplit4, int , int32x4x4_t, vld4q_s32, vst1q_s32); SPLIT4_KERNEL_TEMPLATE(VSplit4, int64 , int64x1x4_t, vld4_s64 , vst1_s64 ); #elif CV_SSE2 template <typename T> struct VSplit2 { VSplit2() : support(false) { } void operator()(const T *, T *, T *) const { } bool support; }; template <typename T> struct VSplit3 { VSplit3() : support(false) { } void operator()(const T *, T *, T *, T *) const { } bool support; }; template <typename T> struct VSplit4 { VSplit4() : support(false) { } void operator()(const T *, T *, T *, T *, T *) const { } bool support; }; #define SPLIT2_KERNEL_TEMPLATE(data_type, reg_type, cast_type, _mm_deinterleave, flavor) \ template <> \ struct VSplit2<data_type> \ { \ enum \ { \ ELEMS_IN_VEC = 16 / sizeof(data_type) \ }; \ \ VSplit2() \ { \ support = checkHardwareSupport(CV_CPU_SSE2); \ } \ \ void operator()(const data_type * src, \ data_type * dst0, data_type * dst1) const \ { \ reg_type v_src0 = _mm_loadu_##flavor((cast_type const *)(src)); \ reg_type v_src1 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC)); \ reg_type v_src2 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 2)); \ reg_type v_src3 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 3)); \ \ _mm_deinterleave(v_src0, v_src1, v_src2, v_src3); \ \ _mm_storeu_##flavor((cast_type *)(dst0), v_src0); \ _mm_storeu_##flavor((cast_type *)(dst0 + ELEMS_IN_VEC), v_src1); \ _mm_storeu_##flavor((cast_type *)(dst1), v_src2); \ _mm_storeu_##flavor((cast_type *)(dst1 + ELEMS_IN_VEC), v_src3); \ } \ \ bool support; \ } #define SPLIT3_KERNEL_TEMPLATE(data_type, reg_type, cast_type, _mm_deinterleave, flavor) \ template <> \ struct VSplit3<data_type> \ { \ enum \ { \ ELEMS_IN_VEC = 16 / sizeof(data_type) \ }; \ \ VSplit3() \ { \ support = checkHardwareSupport(CV_CPU_SSE2); \ } \ \ void operator()(const data_type * src, \ data_type * dst0, data_type * dst1, data_type * dst2) const \ { \ reg_type v_src0 = _mm_loadu_##flavor((cast_type const *)(src)); \ reg_type v_src1 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC)); \ reg_type v_src2 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 2)); \ reg_type v_src3 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 3)); \ reg_type v_src4 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 4)); \ reg_type v_src5 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 5)); \ \ _mm_deinterleave(v_src0, v_src1, v_src2, \ v_src3, v_src4, v_src5); \ \ _mm_storeu_##flavor((cast_type *)(dst0), v_src0); \ _mm_storeu_##flavor((cast_type *)(dst0 + ELEMS_IN_VEC), v_src1); \ _mm_storeu_##flavor((cast_type *)(dst1), v_src2); \ _mm_storeu_##flavor((cast_type *)(dst1 + ELEMS_IN_VEC), v_src3); \ _mm_storeu_##flavor((cast_type *)(dst2), v_src4); \ _mm_storeu_##flavor((cast_type *)(dst2 + ELEMS_IN_VEC), v_src5); \ } \ \ bool support; \ } #define SPLIT4_KERNEL_TEMPLATE(data_type, reg_type, cast_type, _mm_deinterleave, flavor) \ template <> \ struct VSplit4<data_type> \ { \ enum \ { \ ELEMS_IN_VEC = 16 / sizeof(data_type) \ }; \ \ VSplit4() \ { \ support = checkHardwareSupport(CV_CPU_SSE2); \ } \ \ void operator()(const data_type * src, data_type * dst0, data_type * dst1, \ data_type * dst2, data_type * dst3) const \ { \ reg_type v_src0 = _mm_loadu_##flavor((cast_type const *)(src)); \ reg_type v_src1 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC)); \ reg_type v_src2 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 2)); \ reg_type v_src3 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 3)); \ reg_type v_src4 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 4)); \ reg_type v_src5 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 5)); \ reg_type v_src6 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 6)); \ reg_type v_src7 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 7)); \ \ _mm_deinterleave(v_src0, v_src1, v_src2, v_src3, \ v_src4, v_src5, v_src6, v_src7); \ \ _mm_storeu_##flavor((cast_type *)(dst0), v_src0); \ _mm_storeu_##flavor((cast_type *)(dst0 + ELEMS_IN_VEC), v_src1); \ _mm_storeu_##flavor((cast_type *)(dst1), v_src2); \ _mm_storeu_##flavor((cast_type *)(dst1 + ELEMS_IN_VEC), v_src3); \ _mm_storeu_##flavor((cast_type *)(dst2), v_src4); \ _mm_storeu_##flavor((cast_type *)(dst2 + ELEMS_IN_VEC), v_src5); \ _mm_storeu_##flavor((cast_type *)(dst3), v_src6); \ _mm_storeu_##flavor((cast_type *)(dst3 + ELEMS_IN_VEC), v_src7); \ } \ \ bool support; \ } SPLIT2_KERNEL_TEMPLATE( uchar, __m128i, __m128i, _mm_deinterleave_epi8, si128); SPLIT2_KERNEL_TEMPLATE(ushort, __m128i, __m128i, _mm_deinterleave_epi16, si128); SPLIT2_KERNEL_TEMPLATE( int, __m128, float, _mm_deinterleave_ps, ps); SPLIT3_KERNEL_TEMPLATE( uchar, __m128i, __m128i, _mm_deinterleave_epi8, si128); SPLIT3_KERNEL_TEMPLATE(ushort, __m128i, __m128i, _mm_deinterleave_epi16, si128); SPLIT3_KERNEL_TEMPLATE( int, __m128, float, _mm_deinterleave_ps, ps); SPLIT4_KERNEL_TEMPLATE( uchar, __m128i, __m128i, _mm_deinterleave_epi8, si128); SPLIT4_KERNEL_TEMPLATE(ushort, __m128i, __m128i, _mm_deinterleave_epi16, si128); SPLIT4_KERNEL_TEMPLATE( int, __m128, float, _mm_deinterleave_ps, ps); #endif template<typename T> static void split_( const T* src, T** dst, int len, int cn ) { int k = cn % 4 ? cn % 4 : 4; int i, j; if( k == 1 ) { T* dst0 = dst[0]; if(cn == 1) { memcpy(dst0, src, len * sizeof(T)); } else { for( i = 0, j = 0 ; i < len; i++, j += cn ) dst0[i] = src[j]; } } else if( k == 2 ) { T *dst0 = dst[0], *dst1 = dst[1]; i = j = 0; #if CV_NEON if(cn == 2) { int inc_i = (sizeof(T) == 8)? 1: 16/sizeof(T); int inc_j = 2 * inc_i; VSplit2<T> vsplit; for( ; i < len - inc_i; i += inc_i, j += inc_j) vsplit(src + j, dst0 + i, dst1 + i); } #elif CV_SSE2 if (cn == 2) { int inc_i = 32/sizeof(T); int inc_j = 2 * inc_i; VSplit2<T> vsplit; if (vsplit.support) { for( ; i <= len - inc_i; i += inc_i, j += inc_j) vsplit(src + j, dst0 + i, dst1 + i); } } #endif for( ; i < len; i++, j += cn ) { dst0[i] = src[j]; dst1[i] = src[j+1]; } } else if( k == 3 ) { T *dst0 = dst[0], *dst1 = dst[1], *dst2 = dst[2]; i = j = 0; #if CV_NEON if(cn == 3) { int inc_i = (sizeof(T) == 8)? 1: 16/sizeof(T); int inc_j = 3 * inc_i; VSplit3<T> vsplit; for( ; i <= len - inc_i; i += inc_i, j += inc_j) vsplit(src + j, dst0 + i, dst1 + i, dst2 + i); } #elif CV_SSE2 if (cn == 3) { int inc_i = 32/sizeof(T); int inc_j = 3 * inc_i; VSplit3<T> vsplit; if (vsplit.support) { for( ; i <= len - inc_i; i += inc_i, j += inc_j) vsplit(src + j, dst0 + i, dst1 + i, dst2 + i); } } #endif for( ; i < len; i++, j += cn ) { dst0[i] = src[j]; dst1[i] = src[j+1]; dst2[i] = src[j+2]; } } else { T *dst0 = dst[0], *dst1 = dst[1], *dst2 = dst[2], *dst3 = dst[3]; i = j = 0; #if CV_NEON if(cn == 4) { int inc_i = (sizeof(T) == 8)? 1: 16/sizeof(T); int inc_j = 4 * inc_i; VSplit4<T> vsplit; for( ; i <= len - inc_i; i += inc_i, j += inc_j) vsplit(src + j, dst0 + i, dst1 + i, dst2 + i, dst3 + i); } #elif CV_SSE2 if (cn == 4) { int inc_i = 32/sizeof(T); int inc_j = 4 * inc_i; VSplit4<T> vsplit; if (vsplit.support) { for( ; i <= len - inc_i; i += inc_i, j += inc_j) vsplit(src + j, dst0 + i, dst1 + i, dst2 + i, dst3 + i); } } #endif for( ; i < len; i++, j += cn ) { dst0[i] = src[j]; dst1[i] = src[j+1]; dst2[i] = src[j+2]; dst3[i] = src[j+3]; } } for( ; k < cn; k += 4 ) { T *dst0 = dst[k], *dst1 = dst[k+1], *dst2 = dst[k+2], *dst3 = dst[k+3]; for( i = 0, j = k; i < len; i++, j += cn ) { dst0[i] = src[j]; dst1[i] = src[j+1]; dst2[i] = src[j+2]; dst3[i] = src[j+3]; } } } void split8u(const uchar* src, uchar** dst, int len, int cn ) { CALL_HAL(split8u, cv_hal_split8u, src,dst, len, cn) split_(src, dst, len, cn); } void split16u(const ushort* src, ushort** dst, int len, int cn ) { CALL_HAL(split16u, cv_hal_split16u, src,dst, len, cn) split_(src, dst, len, cn); } void split32s(const int* src, int** dst, int len, int cn ) { CALL_HAL(split32s, cv_hal_split32s, src,dst, len, cn) split_(src, dst, len, cn); } void split64s(const int64* src, int64** dst, int len, int cn ) { CALL_HAL(split64s, cv_hal_split64s, src,dst, len, cn) split_(src, dst, len, cn); } }} // cv::hal:: /****************************************************************************************\ * split & merge * \****************************************************************************************/ typedef void (*SplitFunc)(const uchar* src, uchar** dst, int len, int cn); static SplitFunc getSplitFunc(int depth) { static SplitFunc splitTab[] = { (SplitFunc)GET_OPTIMIZED(cv::hal::split8u), (SplitFunc)GET_OPTIMIZED(cv::hal::split8u), (SplitFunc)GET_OPTIMIZED(cv::hal::split16u), (SplitFunc)GET_OPTIMIZED(cv::hal::split16u), (SplitFunc)GET_OPTIMIZED(cv::hal::split32s), (SplitFunc)GET_OPTIMIZED(cv::hal::split32s), (SplitFunc)GET_OPTIMIZED(cv::hal::split64s), 0 }; return splitTab[depth]; } #ifdef HAVE_IPP namespace cv { static bool ipp_split(const Mat& src, Mat* mv, int channels) { #ifdef HAVE_IPP_IW CV_INSTRUMENT_REGION_IPP() if(channels != 3 && channels != 4) return false; if(src.dims <= 2) { IppiSize size = ippiSize(src.size()); void *dstPtrs[4] = {NULL}; size_t dstStep = mv[0].step; for(int i = 0; i < channels; i++) { dstPtrs[i] = mv[i].ptr(); if(dstStep != mv[i].step) return false; } return CV_INSTRUMENT_FUN_IPP(llwiCopySplit, src.ptr(), (int)src.step, dstPtrs, (int)dstStep, size, (int)src.elemSize1(), channels, 0) >= 0; } else { const Mat *arrays[5] = {NULL}; uchar *ptrs[5] = {NULL}; arrays[0] = &src; for(int i = 1; i < channels; i++) { arrays[i] = &mv[i-1]; } NAryMatIterator it(arrays, ptrs); IppiSize size = { (int)it.size, 1 }; for( size_t i = 0; i < it.nplanes; i++, ++it ) { if(CV_INSTRUMENT_FUN_IPP(llwiCopySplit, ptrs[0], 0, (void**)&ptrs[1], 0, size, (int)src.elemSize1(), channels, 0) < 0) return false; } return true; } #else CV_UNUSED(src); CV_UNUSED(mv); CV_UNUSED(channels); return false; #endif } } #endif void cv::split(const Mat& src, Mat* mv) { CV_INSTRUMENT_REGION() int k, depth = src.depth(), cn = src.channels(); if( cn == 1 ) { src.copyTo(mv[0]); return; } for( k = 0; k < cn; k++ ) { mv[k].create(src.dims, src.size, depth); } CV_IPP_RUN_FAST(ipp_split(src, mv, cn)); SplitFunc func = getSplitFunc(depth); CV_Assert( func != 0 ); size_t esz = src.elemSize(), esz1 = src.elemSize1(); size_t blocksize0 = (BLOCK_SIZE + esz-1)/esz; AutoBuffer<uchar> _buf((cn+1)*(sizeof(Mat*) + sizeof(uchar*)) + 16); const Mat** arrays = (const Mat**)(uchar*)_buf; uchar** ptrs = (uchar**)alignPtr(arrays + cn + 1, 16); arrays[0] = &src; for( k = 0; k < cn; k++ ) { arrays[k+1] = &mv[k]; } NAryMatIterator it(arrays, ptrs, cn+1); size_t total = it.size; size_t blocksize = std::min((size_t)CV_SPLIT_MERGE_MAX_BLOCK_SIZE(cn), cn <= 4 ? total : std::min(total, blocksize0)); for( size_t i = 0; i < it.nplanes; i++, ++it ) { for( size_t j = 0; j < total; j += blocksize ) { size_t bsz = std::min(total - j, blocksize); func( ptrs[0], &ptrs[1], (int)bsz, cn ); if( j + blocksize < total ) { ptrs[0] += bsz*esz; for( k = 0; k < cn; k++ ) ptrs[k+1] += bsz*esz1; } } } } #ifdef HAVE_OPENCL namespace cv { static bool ocl_split( InputArray _m, OutputArrayOfArrays _mv ) { int type = _m.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type), rowsPerWI = ocl::Device::getDefault().isIntel() ? 4 : 1; String dstargs, processelem, indexdecl; for (int i = 0; i < cn; ++i) { dstargs += format("DECLARE_DST_PARAM(%d)", i); indexdecl += format("DECLARE_INDEX(%d)", i); processelem += format("PROCESS_ELEM(%d)", i); } ocl::Kernel k("split", ocl::core::split_merge_oclsrc, format("-D T=%s -D OP_SPLIT -D cn=%d -D DECLARE_DST_PARAMS=%s" " -D PROCESS_ELEMS_N=%s -D DECLARE_INDEX_N=%s", ocl::memopTypeToStr(depth), cn, dstargs.c_str(), processelem.c_str(), indexdecl.c_str())); if (k.empty()) return false; Size size = _m.size(); _mv.create(cn, 1, depth); for (int i = 0; i < cn; ++i) _mv.create(size, depth, i); std::vector<UMat> dst; _mv.getUMatVector(dst); int argidx = k.set(0, ocl::KernelArg::ReadOnly(_m.getUMat())); for (int i = 0; i < cn; ++i) argidx = k.set(argidx, ocl::KernelArg::WriteOnlyNoSize(dst[i])); k.set(argidx, rowsPerWI); size_t globalsize[2] = { (size_t)size.width, ((size_t)size.height + rowsPerWI - 1) / rowsPerWI }; return k.run(2, globalsize, NULL, false); } } #endif void cv::split(InputArray _m, OutputArrayOfArrays _mv) { CV_INSTRUMENT_REGION() CV_OCL_RUN(_m.dims() <= 2 && _mv.isUMatVector(), ocl_split(_m, _mv)) Mat m = _m.getMat(); if( m.empty() ) { _mv.release(); return; } CV_Assert( !_mv.fixedType() || _mv.empty() || _mv.type() == m.depth() ); int depth = m.depth(), cn = m.channels(); _mv.create(cn, 1, depth); for (int i = 0; i < cn; ++i) _mv.create(m.dims, m.size.p, depth, i); std::vector<Mat> dst; _mv.getMatVector(dst); split(m, &dst[0]); }
25,244
8,300
#ifndef acommon_filter_char_hh #define acommon_filter_char_hh // This file is part of The New Aspell // Copyright (C) 2002 by Kevin Atkinson under the GNU LGPL license // version 2.0 or 2.1. You should have received a copy of the LGPL // license along with this library if you did not you can find // it at http://www.gnu.org/. namespace acommon { struct FilterChar { unsigned int chr; unsigned int width; // width must always be < 256 typedef unsigned int Chr; typedef unsigned int Width; explicit FilterChar(Chr c = 0, Width w = 1) : chr(c), width(w) {} FilterChar(Chr c, FilterChar o) : chr(c), width(o.width) {} static Width sum(const FilterChar * o, const FilterChar * stop) { Width total = 0; for (; o != stop; ++o) total += o->width; return total; } static Width sum(const FilterChar * o, unsigned int size) { return sum(o, o+size); } FilterChar(Chr c, const FilterChar * o, unsigned int size) : chr(c), width(sum(o,size)) {} FilterChar(Chr c, const FilterChar * o, const FilterChar * stop) : chr(c), width(sum(o,stop)) {} operator Chr () const {return chr;} FilterChar & operator= (Chr c) {chr = c; return *this;} }; static inline bool operator==(FilterChar lhs, FilterChar rhs) { return lhs.chr == rhs.chr; } static inline bool operator!=(FilterChar lhs, FilterChar rhs) { return lhs.chr != rhs.chr; } } #endif
1,464
490
// container-with-most-water // Problem Statement: https://leetcode.com/problems/container-with-most-water #include<bits/stdc++.h> using namespace std; class Solution { public: int maxArea(vector<int>& height) { if(height.size() < 1) return 0; int left = 0; int right = height.size() - 1; int result = 0; while(left < right){ int area = (height[left] < height[right]) ? (height[left] * (right - left)) : (height[right] * (right -left)); result = (area > result) ? area : result; (height[left] < height[right]) ? left++ : right--; } return result; } };
704
221
/* * Copyright (c) 2021 Florian Dollinger - dollinger.florian@gmx.de * All rights reserved. */ // Copyright (c) 2018 - for information on the respective copyright owner // see the NOTICE file and/or the repository https://github.com/boschresearch/fmi_adapter. // // 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 "fmi_adapter/FMU.h" #include <cstdlib> #include <algorithm> #include <exception> #include <fstream> #include <functional> #include <iostream> #include <utility> #include <variant> #include <dirent.h> #include <unistd.h> #include <fmilib.h> #include <boost/regex.hpp> // !!!!!!! !!!!! !!!!!! !!!!! // !!! !!! !!! !!! !!! !!! !!! // !!! !!! !!! !!! !!! !!! !!! // !!! !!!!! !!!!!! !!!!! // TODO: * Add fmi2_base_type_str and enum? namespace fmi_adapter { namespace helpers { bool canWriteToFolder(const std::string& path) { DIR* dir = opendir(path.c_str()); if (dir == nullptr) { return false; } closedir(dir); return (access(path.c_str(), W_OK) == 0); } bool canReadFromFile(const std::string& path) { std::ifstream stream(path.c_str()); if (stream.is_open() && stream.good()) { stream.close(); return true; } else { return false; } } } // namespace helpers // Conversion: ROS Parameter <-> FMI // unspecialized case: just cast it template <typename Tin, typename Tout> Tout FMU::convert(Tin value) { return (Tout)value; } // unspecialized cases: where casting doesn't work template <> fmi2_boolean_t FMU::convert<bool, fmi2_boolean_t>(bool value) { return value == true ? fmi2_true : fmi2_false; } template <> bool FMU::convert<fmi2_boolean_t, bool>(fmi2_boolean_t value) { return value == fmi2_true ? true : false; } template <> fmi2_boolean_t FMU::convert<uint8_t, fmi2_boolean_t>(uint8_t value) { return value == 1 ? fmi2_true : fmi2_false; } template <> uint8_t FMU::convert<fmi2_boolean_t, uint8_t>(fmi2_boolean_t value) { return value == fmi2_true ? 1 : 0; } /** * @brief Constructor for a FMU::FMU object * * @param fmuPath * @param stepSize * @param interpolateInput * @param tmpPath */ FMU::FMU(const std::string& fmuName, const std::string& fmuPath, ros::Duration stepSize, bool interpolateInput, const std::string& tmpPath) : fmuName_(fmuName), fmuPath_(fmuPath), stepSize_(stepSize), interpolateInput_(interpolateInput), tmpPath_(tmpPath) { if (stepSize == ros::Duration(0.0)) { // Use step-size from FMU. See end of ctor. } else if (stepSize < ros::Duration(0.0)) { throw std::invalid_argument("Step size must be positive!"); } if (!helpers::canReadFromFile(fmuPath)) { throw std::invalid_argument("Given FMU file '" + fmuPath + "' not found or cannot be read!"); } if (tmpPath_.empty()) { char pathPattern[] = "/tmp/fmi_adapter_XXXXXX"; tmpPath_ = mkdtemp(pathPattern); removeTmpPathInDtor_ = true; } if (!helpers::canWriteToFolder(tmpPath_)) { throw std::invalid_argument("Cannot access tmp folder '" + tmpPath_ + "'!"); } // Some of the following lines have been taken from FMILibrary 2.3.0 src/test/fmi2_import_cs_test.c // under BSD style license. jmCallbacks_ = new jm_callbacks; jmCallbacks_->malloc = malloc; jmCallbacks_->calloc = calloc; jmCallbacks_->realloc = realloc; jmCallbacks_->free = free; jmCallbacks_->logger = jm_default_logger; jmCallbacks_->log_level = jm_log_level_error; jmCallbacks_->context = 0; context_ = fmi_import_allocate_context(jmCallbacks_); fmi_version_enu_t fmuVersion = fmi_import_get_fmi_version(context_, fmuPath_.c_str(), tmpPath_.c_str()); if (fmuVersion != fmi_version_2_0_enu) { throw std::invalid_argument("Could not load the FMU or the FMU does not meet the FMI 2.0 standard!"); } fmu_ = fmi2_import_parse_xml(context_, tmpPath_.c_str(), 0); if (!fmu_) { throw std::invalid_argument("Could not parse XML description of FMU!"); } if (fmi2_import_get_fmu_kind(fmu_) != fmi2_fmu_kind_cs) { throw std::invalid_argument("Given FMU is not for co-simulation!"); } fmi2_callback_functions_t* fmiCallbacks = new fmi2_callback_functions_t; fmiCallbacks->logger = fmi2_log_forwarding; fmiCallbacks->allocateMemory = calloc; fmiCallbacks->freeMemory = free; fmiCallbacks->componentEnvironment = fmu_; fmiCallbacks_ = fmiCallbacks; jm_status_enu_t jmStatus = fmi2_import_create_dllfmu(fmu_, fmi2_fmu_kind_cs, fmiCallbacks); if (jmStatus == jm_status_error) { throw std::runtime_error("Creation of dllfmu failed!"); } const fmi2_string_t instanceName = fmi2_import_get_model_name(fmu_); const fmi2_string_t fmuLocation = nullptr; // Indicates that FMU should get path to the unzipped location. const fmi2_boolean_t visible = fmi2_false; const fmi2_real_t relativeTol = 1e-4; jmStatus = fmi2_import_instantiate(fmu_, instanceName, fmi2_cosimulation, fmuLocation, visible); assert(jmStatus != jm_status_error); const fmi2_real_t startTime = 0.0; const fmi2_real_t stopTime = -1.0; fmi2_status_t fmiStatus = fmi2_import_setup_experiment(fmu_, fmi2_true, relativeTol, startTime, fmi2_false, stopTime); if (fmiStatus != fmi2_status_ok) { throw std::runtime_error("fmi2_import_setup_experiment failed!"); } fmiStatus = fmi2_import_enter_initialization_mode(fmu_); if (fmiStatus != fmi2_status_ok) { throw std::runtime_error("fmi2_import_enter_initialization_mode failed!"); } if (stepSize == ros::Duration(0.0)) { stepSize_ = ros::Duration(fmi2_import_get_default_experiment_step(fmu_)); if (stepSize_ <= ros::Duration(0.0)) { throw std::invalid_argument("Default experiment step size from FMU is not positive!"); } ROS_INFO("No step-size argument given. Using default from FMU, which is %fs.", stepSize_.toSec()); } // caching the FMU variables once, just update them later on cacheVariables_(); } /** * @brief Dectruction of a FMU::FMU object * */ FMU::~FMU() { fmi2_import_terminate(fmu_); fmi2_import_free_instance(fmu_); fmi2_import_destroy_dllfmu(fmu_); fmi2_import_free(fmu_); fmi_import_free_context(context_); delete jmCallbacks_; delete static_cast<fmi2_callback_functions_t*>(fmiCallbacks_); if (removeTmpPathInDtor_) { // TODO(Ralph) Remove folder fmi_adapter_XXXXXX from /tmp. // Such function is not provided by Posix or C++11/14. // Possibly use boost::filesystem::remove_all. Then other // filesystem functions used here and use of "/tmp" may be // replaced by corresponding functions from boost::filesystem. } } /** * @brief Rosify a given variable name * Converts a given variable name to the format used by ROS * * @param name * @return std::string */ std::string FMU::rosifyName(const std::string& name) { std::string result = name; boost::regex reInvalidCharacters("[^a-zA-Z0-9_]"); result = boost::regex_replace(name, reInvalidCharacters, "_"); return result; } bool FMU::canHandleVariableCommunicationStepSize() const { return static_cast<bool>(fmi2_import_get_capability(fmu_, fmi2_cs_canHandleVariableCommunicationStepSize)); } ros::Duration FMU::getDefaultExperimentStep() const { return ros::Duration(fmi2_import_get_default_experiment_step(fmu_)); } /** * @brief Exits the initialization mode * Moreover, starts the simulation of the wrapped FMU. Uses the given timestamp * as start time for the simulation. The FMU internally starts at time 0. * * All times passed to setValue(...) and doStep*(...) are translated correspondingly. * * @param externalStartTime time where the simulation starts (e.g. the current time from ROS) */ void FMU::exitInitializationMode(ros::Time externalStartTime) { if (!inInitializationMode_) { throw std::runtime_error("FMU is no longer in initialization mode!"); } fmi2_status_t fmiStatus = fmi2_import_exit_initialization_mode(fmu_); if (fmiStatus != fmi2_status_ok) { throw std::runtime_error("fmi2_import_exit_initialization_mode failed!"); } inInitializationMode_ = false; // The ROS simulation time starts earlier than the FMUs internal time // because the FMUs are loaded a bit later. Therefore, remember the time // where it started in order to know how much to calculate later on // in doStepsUtil (since the ros time is passed, not the fmu time) rosStartTime_ = externalStartTime; // TODO: What is it good for? Document! for (auto& [name, variable] : cachedVariables_ | boost::adaptors::filtered(fmi_adapter::FMUVariable::varInput_filter)) { (void)name; std::map<ros::Time, valueVariantTypes>& inputValues = inputValuesByVariable_[variable->getVariablePointerRaw()]; if (inputValues.empty() || inputValues.begin()->first > externalStartTime) { auto value = variable->getValue(); inputValues[externalStartTime] = value; } } } void FMU::doStep_(const ros::Duration& stepSize) { assert(fmu_ != nullptr); for (auto& [name, variable] : cachedVariables_ | boost::adaptors::filtered(fmi_adapter::FMUVariable::varInput_filter)) { (void)name; std::map<ros::Time, valueVariantTypes>& inputValuesByTime = inputValuesByVariable_[variable->getVariablePointerRaw()]; // Make sure that there are InputValues, at least for the simulation start assert(!inputValuesByTime.empty() && (inputValuesByTime.begin()->first - rosStartTime_).toSec() <= fmuTime_); // Remove Values in the past while (inputValuesByTime.size() >= 2 && (std::next(inputValuesByTime.begin())->first - rosStartTime_).toSec() <= fmuTime_) { inputValuesByTime.erase(inputValuesByTime.begin()); } // Make sure that there are STILL InputValues, at least for the simulation start assert(!inputValuesByTime.empty() && (inputValuesByTime.begin()->first - rosStartTime_).toSec() <= fmuTime_); valueVariantTypes value = inputValuesByTime.begin()->second; // TODO: Interpolation // if (interpolateInput_ && inputValues.size() > 1) { // double t0 = (inputValues.begin()->first - rosStartTime_).toSec(); // double t1 = (std::next(inputValues.begin())->first - rosStartTime_).toSec(); // double weight = (t1 - fmuTime_) / (t1 - t0); // valueVariantTypes x0 = value; // valueVariantTypes x1 = std::next(inputValues.begin())->second; // value = weight * x0 + (1.0 - weight) * x1; // } variable->setValue(value); } const fmi2_boolean_t doStep = fmi2_true; fmi2_status_t fmiStatus = fmi2_import_do_step(fmu_, fmuTime_, stepSize.toSec(), doStep); if (fmiStatus != fmi2_status_ok) { throw std::runtime_error("fmi2_import_do_step failed!"); } fmuTime_ += stepSize.toSec(); } ros::Time FMU::doStep() { if (inInitializationMode_) { throw std::runtime_error("FMU is still in initialization mode!"); } doStep_(stepSize_); return getSimTimeForROS_(); } ros::Time FMU::doStep(const ros::Duration& stepSize) { if (stepSize <= ros::Duration(0.0)) { throw std::invalid_argument("Step size must be positive!"); } if (inInitializationMode_) { throw std::runtime_error("FMU is still in initialization mode!"); } doStep_(stepSize); return getSimTimeForROS_(); } ros::Time FMU::doStepsUntil(const ros::Time rosUntilTime) { if (inInitializationMode_) { throw std::runtime_error("FMU is still in initialization mode!"); } double targetFMUTime = (rosUntilTime - rosStartTime_).toSec(); if (targetFMUTime < fmuTime_ - stepSize_.toSec() / 2.0) { // Subtract stepSize/2 for rounding. ROS_ERROR("Given time %f is before current simulation time %f!", targetFMUTime, fmuTime_); throw std::invalid_argument("Given time is before current simulation time!"); } while (fmuTime_ + stepSize_.toSec() / 2.0 < targetFMUTime) { doStep_(stepSize_); } return getSimTimeForROS_(); } ros::Time FMU::getSimulationTime() const { if (inInitializationMode_) { throw std::runtime_error("FMU is still in initialization mode!"); } return getSimTimeForROS_(); } /** * @brief Set the value for a specific FMU input variable at a given time (e.g. now) * This Function is currently used internally * * @param variable * @param time * @param value */ void FMU::_setInputValueRaw(fmi2_import_variable_t* variable, ros::Time time, valueVariantTypes value) { if (fmi2_import_get_causality(variable) != fmi2_causality_enu_input) { throw std::invalid_argument("Given variable is not an input variable!"); } std::string name = rosifyName(fmi2_import_get_variable_name(variable)); inputValuesByVariable_[variable].insert(std::make_pair(time, value)); } /** * @brief Set the value for a specific FMU input variable at a given time (e.g. now) * This function is called in a callback of a subscription to the inputs of the wrapping node * to propagate the values to the FMU * * @param variableName * @param time * @param value */ void FMU::setInputValue(std::string variableName, ros::Time time, valueVariantTypes value) { fmi2_import_variable_t* variable = fmi2_import_get_variable_by_name(fmu_, variableName.c_str()); if (variable == nullptr) { throw std::invalid_argument("Unknown variable name!"); } _setInputValueRaw(variable, time, value); } /** * @brief Initializes the Adapter Node from ROS Parameters * This Function is reading out the Parameter Values from the ROS Parameter Server * and is setting every FMU variable accordingly. * * @param handle to the ROSNode */ void FMU::initializeFromROSParameters(const ros::NodeHandle& handle) { for (auto& [name, variable] : cachedVariables_) { (void)name; // get a representation of the current type auto variableValue = variable->getValue(); // call ROS::getParam on the active type, store the result in variableValue, if any std::visit([handle, variable](auto& activeVariant) { handle.getParam(variable->getNameRos(), activeVariant); }, variableValue); // write back the ROS param value to the variable variable->setValue(variableValue); } } /** * @brief Get the Variables From FMU object as raw * This helper functions returns all variables with a certain property defined by an optional filter. * */ void FMU::cacheVariables_() { cachedVariables_.clear(); fmi2_import_variable_list_t* variableList = fmi2_import_get_variable_list(fmu_, 0); const size_t variablesCount = fmi2_import_get_variable_list_size(variableList); for (size_t index = 0; index < variablesCount; ++index) { fmi2_import_variable_t* variable = fmi2_import_get_variable(variableList, index); std::string variableName = std::string(fmi2_import_get_variable_name(variable)); cachedVariables_.insert(std::make_pair(variableName, std::make_shared<FMUVariable>(fmu_, variable))); } fmi2_import_free_variable_list(variableList); return; } std::map<std::string, std::shared_ptr<FMUVariable>> FMU::getCachedVariables() const { assert(fmu_); return cachedVariables_; } std::shared_ptr<FMUVariable> FMU::getCachedVariable(std::string name) { assert(fmu_); return cachedVariables_.at(name); } fmi2_import_t* FMU::getRawFMU() { assert(fmu_); return fmu_; } } // namespace fmi_adapter
15,681
5,345
/* * Copyright (c) 2008-2016, Integrity Project Ltd. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the Integrity Project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE */ /* * Stack.cpp * * Implementation file * * Author: Elad Raz <e@eladraz.com> */ #include "xStl/types.h" #include "data/exceptions.h" #include "runnable/Stack.h" template <class T, class Itr> void StackInfrastructor<T, Itr>::pop2null(uint amount) { if (amount == 0) return; if (isEmpty()) XSTL_THROW(ClrStackError); for (uint i = 0; i < amount; i++) { Itr b(m_stack.begin()); m_stack.remove(b); } } template <class T, class Itr> void StackInfrastructor<T, Itr>::push(const T& var) { m_stack.insert(var); } template <class T, class Itr> const T& StackInfrastructor<T, Itr>::peek() const { if (isEmpty()) XSTL_THROW(ClrStackError); return *m_stack.begin(); } template <class T, class Itr> T& StackInfrastructor<T, Itr>::getArg(uint index) { Itr j = m_stack.begin(); while (index > 0) { if (j == m_stack.end()) XSTL_THROW(ClrStackError); ++j; --index; } return *j; } template <class T, class Itr> T& StackInfrastructor<T, Itr>::tos() { if (isEmpty()) XSTL_THROW(ClrStackError); return *m_stack.begin(); } template <class T, class Itr> bool StackInfrastructor<T, Itr>::isEmpty() const { return m_stack.begin() == m_stack.end(); } template <class T, class Itr> uint StackInfrastructor<T, Itr>::getStackCount() const { return m_stack.length(); } template <class T, class Itr> cList<T>& StackInfrastructor<T, Itr>::getList() { return m_stack; } template <class T, class Itr> const Itr StackInfrastructor<T, Itr>::getTosPosition() { return m_stack.begin(); } template <class T, class Itr> void StackInfrastructor<T, Itr>::revertStack(const Itr& pos) { while (m_stack.begin() != pos) { if (isEmpty()) { // Error with stack reverting CHECK_FAIL(); } m_stack.remove(m_stack.begin()); } } template <class T, class Itr> void StackInfrastructor<T, Itr>::clear() { m_stack.removeAll(); }
3,559
1,313
// Copyright (c), Firelight Technologies Pty, Ltd. 2012-2019. #include "FMODEvent.h" #include "FMODStudioModule.h" #include "fmod_studio.hpp" UFMODEvent::UFMODEvent(const FObjectInitializer &ObjectInitializer) : Super(ObjectInitializer) { } /** Get tags to show in content view */ void UFMODEvent::GetAssetRegistryTags(TArray<FAssetRegistryTag> &OutTags) const { Super::GetAssetRegistryTags(OutTags); if (IFMODStudioModule::Get().AreBanksLoaded()) { FMOD::Studio::EventDescription *EventDesc = IFMODStudioModule::Get().GetEventDescription(this, EFMODSystemContext::Max); bool bOneshot = false; bool bStream = false; bool b3D = false; if (EventDesc) { EventDesc->isOneshot(&bOneshot); EventDesc->isStream(&bStream); EventDesc->is3D(&b3D); } OutTags.Add(UObject::FAssetRegistryTag("Oneshot", bOneshot ? TEXT("True") : TEXT("False"), UObject::FAssetRegistryTag::TT_Alphabetical)); OutTags.Add(UObject::FAssetRegistryTag("Streaming", bStream ? TEXT("True") : TEXT("False"), UObject::FAssetRegistryTag::TT_Alphabetical)); OutTags.Add(UObject::FAssetRegistryTag("3D", b3D ? TEXT("True") : TEXT("False"), UObject::FAssetRegistryTag::TT_Alphabetical)); } } FString UFMODEvent::GetDesc() { return FString::Printf(TEXT("Event %s"), *AssetGuid.ToString(EGuidFormats::DigitsWithHyphensInBraces)); } void UFMODEvent::GetParameterDescriptions(TArray<FMOD_STUDIO_PARAMETER_DESCRIPTION> &Parameters) const { if (IFMODStudioModule::Get().AreBanksLoaded()) { FMOD::Studio::EventDescription *EventDesc = IFMODStudioModule::Get().GetEventDescription(this, EFMODSystemContext::Auditioning); if (EventDesc) { int ParameterCount; EventDesc->getParameterDescriptionCount(&ParameterCount); Parameters.SetNumUninitialized(ParameterCount); for (int ParameterIndex = 0; ParameterIndex < ParameterCount; ++ParameterIndex) { EventDesc->getParameterDescriptionByIndex(ParameterIndex, &Parameters[ParameterIndex]); } } } }
2,229
700
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2016 Daniele Panozzo <daniele.panozzo@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "readPNG.h" #include <stb_image.h> IGL_INLINE bool igl::png::readPNG( const std::string png_file, Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& R, Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& G, Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& B, Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& A ) { int cols,rows,n; unsigned char *data = stbi_load(png_file.c_str(), &cols, &rows, &n, 4); if(data == NULL) { return false; } R.resize(cols,rows); G.resize(cols,rows); B.resize(cols,rows); A.resize(cols,rows); for (unsigned i=0; i<rows; ++i) { for (unsigned j=0; j<cols; ++j) { R(j,rows-1-i) = data[4*(j + cols * i) + 0]; G(j,rows-1-i) = data[4*(j + cols * i) + 1]; B(j,rows-1-i) = data[4*(j + cols * i) + 2]; A(j,rows-1-i) = data[4*(j + cols * i) + 3]; } } stbi_image_free(data); return true; } #ifdef IGL_STATIC_LIBRARY // Explicit template instantiation // generated by autoexplicit.sh #endif
1,379
557
#include <boost/coroutine/all.hpp> #include <cstdlib> #include <iostream> #include <boost/bind.hpp> #include "X.h" typedef boost::coroutines::asymmetric_coroutine< X& >::pull_type pull_coro_t; typedef boost::coroutines::asymmetric_coroutine< X& >::push_type push_coro_t; void fn1( push_coro_t & sink) { for ( int i = 0; i < 10; ++i) { X x( i); sink( x); } } void fn2( pull_coro_t & source) { while ( source) { X & x = source.get(); std::cout << "i = " << x.i << std::endl; source(); } } int main( int argc, char * argv[]) { { pull_coro_t source( fn1); while ( source) { X & x = source.get(); std::cout << "i = " << x.i << std::endl; source(); } } { push_coro_t sink( fn2); for ( int i = 0; i < 10; ++i) { X x( i); sink( x); } } std::cout << "Done" << std::endl; return EXIT_SUCCESS; }
994
396
// $flisboac 2018-01-14 #include "adl_catch.hpp" #include "adl/oct/cpu/closure_oper.hpp" #include "adl/oct/cpu/add_cons_close_oper.hpp" #include "adl/oct/cons.hpp" #include "adl/oct/system.hpp" #include "adl/oct/cpu/dense_dbm.hpp" #include "adl/oct/cpu/seq_context.hpp" using namespace adl::oct; using namespace adl::oct::cpu; using namespace adl::literals; using namespace adl::operators; using namespace adl::dsl; template <typename DbmType, typename OperType> static void add_cons(char const* type_name, DbmType& dbm, OperType&& oper) { using limits = typename DbmType::constant_limits; using constant_type = typename DbmType::constant_type; auto cons_close_sat = oper.get(); INFO("type_name = " << type_name << ", dbm = " << dbm.to_string()); REQUIRE((cons_close_sat)); for (auto k = dbm.first_var(); k <= dbm.last_var(); k++) { INFO(limits::raw_value(dbm.at(k, k))); REQUIRE( (dbm.at(k, k) == 0) ); // closure INFO(limits::raw_value(dbm.at(k, -k))); REQUIRE( (limits::is_even(dbm.at(k, -k))) ); // tight closure (unary constraints, all even) for (auto i = dbm.first_var(); i <= dbm.last_var(); i++) { INFO("dbm.at(k, i) = " << limits::raw_value(dbm.at(k, i))); INFO("dbm.at(k, -k) = " << limits::raw_value(dbm.at(k, -k))); INFO("dbm.at(-i, i) = " << limits::raw_value(dbm.at(-i, i))); REQUIRE( (dbm.at(k, i) <= (dbm.at(k, -k) / 2) + (dbm.at(-i, i) / 2)) ); // strong closure for (auto j = dbm.first_var(); j <= dbm.last_var(); j++) { REQUIRE( (dbm.at(i, j) <= dbm.at(i, k) + dbm.at(k, j)) ); // closure } } } }; template <typename FloatType> static void do_test(char const* type_name) { using limits = constant_limits<FloatType>; auto xi = 1_ov; auto xj = 2_ov; auto xdi = xi.to_counterpart(); auto xdj = xj.to_counterpart(); auto context = cpu::seq_context::make(); auto dbm = context.make_dbm<cpu::dense_dbm, FloatType>(xj); dbm.assign({ xi <= FloatType(3.0), xj <= FloatType(2.0), xi + xj <= FloatType(6.0) }); auto queue = context.make_queue(); auto closure = queue.make_oper<cpu::closure_oper>(dbm); REQUIRE( (closure.get()) ); add_cons( type_name, dbm, queue.make_oper<cpu::add_cons_close_oper>(dbm, -xi <= FloatType(3.0)) ); add_cons( type_name, dbm, queue.make_oper<cpu::add_cons_close_oper>(dbm, -xi - xj <= FloatType(5.0)) ); } TEST_CASE("unit:adl/oct/cpu/add_cons_close_oper.hpp", "[unit][oper][adl][adl/oct][adl/oct/cpu]") { //do_test<int>("int"); // TBD do_test<float>("float"); do_test<double>("double"); do_test<long double>("long double"); do_test<float_int>("float_int"); do_test<double_int>("double_int"); do_test<ldouble_int>("ldouble_int"); }
2,841
1,143
// Copyright Carl Philipp Reh 2006 - 2019. // 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 <sge/opengl/call.hpp> #include <sge/opengl/check_state.hpp> #include <sge/opengl/color_base_type.hpp> #include <sge/opengl/color_order.hpp> #include <sge/opengl/common.hpp> #include <sge/opengl/internal_color_format.hpp> #include <sge/opengl/texture/binding_fwd.hpp> #include <sge/opengl/texture/buffer_type.hpp> #include <sge/opengl/texture/surface_config_fwd.hpp> #include <sge/opengl/texture/funcs/set_2d.hpp> #include <sge/renderer/const_raw_pointer.hpp> #include <sge/renderer/dim2.hpp> #include <sge/renderer/texture/creation_failed.hpp> #include <sge/renderer/texture/mipmap/level.hpp> #include <fcppt/text.hpp> #include <fcppt/cast/size.hpp> #include <fcppt/cast/to_signed.hpp> #include <fcppt/cast/to_void_ptr.hpp> #include <fcppt/math/dim/output.hpp> void sge::opengl::texture::funcs::set_2d( sge::opengl::texture::binding const &, sge::opengl::texture::surface_config const &, sge::opengl::texture::buffer_type const _buffer_type, sge::opengl::color_order const _format, sge::opengl::color_base_type const _format_type, sge::opengl::internal_color_format const _internal_format, sge::renderer::texture::mipmap::level const _level, sge::renderer::dim2 const &_dim, sge::renderer::const_raw_pointer const _src) { sge::opengl::call( ::glTexImage2D, _buffer_type.get(), fcppt::cast::to_signed(_level.get()), _internal_format.get(), fcppt::cast::size<GLsizei>(fcppt::cast::to_signed(_dim.w())), fcppt::cast::size<GLsizei>(fcppt::cast::to_signed(_dim.h())), 0, _format.get(), _format_type.get(), fcppt::cast::to_void_ptr(_src)); SGE_OPENGL_CHECK_STATE( (fcppt::format(FCPPT_TEXT("Creation of texture with size %1% failed!")) % _dim).str(), sge::renderer::texture::creation_failed) }
2,032
807
#include "mainwindow.h" #include "ui_mainwindow.h" #include "droplabel.h" #include "processdialog.h" #include "preferencesdialog.h" #include "aboutdialog.h" #include "processmodemodel.h" #include <QFileDialog> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), m_settings(new Waifu2xConverterQtSettings), m_procmode(new ProcessModeModel) { ui->setupUi(this); init(); } MainWindow::~MainWindow() { delete ui; } ProcessModeModel* MainWindow::processModeModel(){ return m_procmode; } void MainWindow::browseImage() { QFileDialog dialog(this, tr("Select image"), m_settings->lastUsedDir()); dialog.setAcceptMode(QFileDialog::AcceptOpen); dialog.setMimeTypeFilters({"image/jpeg", "image/png", "application/octet-stream"}); if (dialog.exec() == QFileDialog::Accepted){ QString filePath = dialog.selectedFiles().first(); m_settings->setLastUsedDir(QDir(filePath).absolutePath()); processImage(filePath); } } void MainWindow::processImage(const QString &imageFileName) { QString outputFileName; if (m_settings->isUseCustomFileName()) { outputFileName = browseSaveLocation(imageFileName); if (outputFileName.isEmpty()) return; } ProcessDialog dialog(imageFileName, ui->threadsBox->value(), ui->scaleRatioBox->value(), ui->noiseReductionLevel->value(), ui->imageProcessingModeBox->currentData().toString(), outputFileName, m_settings->modelDirectory(), this); dialog.exec(); } QString MainWindow::browseSaveLocation(const QString &inputImageFileName) { QDir dir(inputImageFileName); QString fileExtension; QFileDialog dialog(this, tr("Save")); dir.cdUp(); if (inputImageFileName.contains(".")) fileExtension = inputImageFileName.split(".").last(); dialog.setAcceptMode(QFileDialog::AcceptSave); dialog.setDirectory(dir.absolutePath()); dialog.selectFile(inputImageFileName); dialog.exec(); return dialog.selectedFiles().isEmpty() ? QString() : dialog.selectedFiles().first(); } void MainWindow::closeEvent(QCloseEvent *) { save(); } void MainWindow::save() { m_settings->setThreadsCount(ui->threadsBox->value()); m_settings->setScaleRatio(ui->scaleRatioBox->value()); m_settings->setNoiseReductionLevel(ui->noiseReductionLevel->value()); m_settings->setImageProcessingMode(ui->imageProcessingModeBox->currentData().toString()); } void MainWindow::toggleOptions(int boxIndex){ QString currentData = ui->imageProcessingModeBox->itemData(boxIndex).toString(); ui->noiseReductionLevel->setEnabled(currentData.contains("noise")); ui->scaleRatioBox->setEnabled(currentData.contains("scale")); } void MainWindow::init() { qApp->setApplicationDisplayName(tr("Waifu2x Converter Qt")); setWindowTitle(QApplication::applicationDisplayName()); auto* dropLabel = new DropLabel(this); ui->imageProcessingModeBox->setModel(m_procmode); connect(ui->action_Preferences, &QAction::triggered, [&]() { PreferencesDialog dialog; dialog.exec(); }); connect(ui->imageProcessingModeBox, SIGNAL(currentIndexChanged(int)),SLOT(toggleOptions(int))); connect(dropLabel, SIGNAL(fileDropped(QString)), this, SLOT(processImage(QString))); connect(ui->browseButton, SIGNAL(clicked(bool)), this, SLOT(browseImage())); connect(ui->action_Open_image, &QAction::triggered, this, &MainWindow::browseImage); connect(ui->action_About_waifu2x_converter_qt, &QAction::triggered, [&]() { AboutDialog dialog; dialog.exec(); }); connect(ui->actionAbout_Qt, &QAction::triggered, qApp, &QApplication::aboutQt); connect(ui->actionE_xit, &QAction::triggered, qApp, &QApplication::quit); ui->browseButton->setIcon(style()->standardIcon((QStyle::SP_DirOpenIcon))); ui->action_Open_image->setIcon(style()->standardIcon(QStyle::SP_DirOpenIcon)); ui->actionE_xit->setIcon(style()->standardIcon(QStyle::SP_DialogCloseButton)); ui->action_About_waifu2x_converter_qt->setIcon(style()->standardIcon(QStyle::SP_DialogHelpButton)); ui->dropLayout->insertWidget(0, dropLabel, 10); ui->threadsBox->setValue(m_settings->threadsCount()); ui->scaleRatioBox->setValue(m_settings->scaleRatio()); ui->noiseReductionLevel->setValue(m_settings->noiseReductionLevel()); int currDataIndex = ui->imageProcessingModeBox->findData(m_settings->imageProcessingMode()); ui->imageProcessingModeBox->setCurrentIndex(currDataIndex); }
4,818
1,458
#include "pch.h" #include "DependencyDestructor.h" DependencyDestructor::DependencyDestructor(UniqueFunction<void(Object&, void*)> aDestroyFunc) noexcept : myDestroyFunc(std::move(aDestroyFunc)) {} void DependencyDestructor::Destroy(Object& aObject, SComponent& aComponent) { myDestroyFunc(aObject, &aComponent); } void DependencyDestructor::Destroy(Object& aObject, _BaseFunctionality& aFunctionality) { myDestroyFunc(aObject, &aFunctionality); }
454
160
/* * The MIT License (MIT) * * Copyright (c) 2017 Sylko Olzscher * */ #ifndef CYNG_ASYNC_TASK_BUILDER_HPP #define CYNG_ASYNC_TASK_BUILDER_HPP #include <cyng/async/task/task.hpp> #include <cyng/async/mux.h> #include <chrono> namespace cyng { namespace async { /** * Create a new task class */ template < typename T, typename ...Args > auto make_task(mux& m, Args &&... args) -> std::shared_ptr<task < T >> { typedef task < T > task_type; return std::make_shared< task_type >(m, std::forward<Args>(args)...); } /** * There are three options to start a task: * (1) sync - insert task into task list and call run() method * in the same thread. * * (2) async - insert task into task list and call run() method * in another thread. * * (3) delayed - insert task into task list and call run() method * from a timer callback. */ template < typename T, typename ...Args > std::pair<std::size_t, bool> start_task_sync(mux& m, Args &&... args) { auto tp = make_task<T>(m, std::forward<Args>(args)...); return std::make_pair(tp->get_id(), m.insert(tp, sync())); } template < typename T, typename ...Args > std::size_t start_task_detached(mux& m, Args &&... args) { auto tp = make_task<T>(m, std::forward<Args>(args)...); return (m.insert(tp, detach())) ? tp->get_id() : NO_TASK ; } template < typename T, typename R, typename P, typename ...Args > std::pair<std::size_t, bool> start_task_delayed(mux& m, std::chrono::duration<R, P> d, Args &&... args) { auto tp = make_task<T>(m, std::forward<Args>(args)...); if (m.insert(tp, none())) { tp->suspend(d); return std::make_pair(tp->get_id(), true); } return std::make_pair(tp->get_id(), false); } inline std::pair<std::size_t, bool> start_task_sync(mux& m, shared_task tp) { return std::make_pair(tp->get_id(), m.insert(tp, sync())); } } // async } #endif // CYNG_ASYNC_TASK_BUILDER_HPP
1,991
882
// WARNING: THIS FILE IS AUTOGENERATED! As such, it should not be edited. // Edits need to be made to the proto files // (see // https://github.com/mavlink/MAVSDK-Proto/blob/master/protos/action_server/action_server.proto) #include <iomanip> #include "action_server_impl.h" #include "plugins/action_server/action_server.h" namespace mavsdk { using AllowableFlightModes = ActionServer::AllowableFlightModes; using ArmDisarm = ActionServer::ArmDisarm; ActionServer::ActionServer(System& system) : PluginBase(), _impl{std::make_unique<ActionServerImpl>(system)} {} ActionServer::ActionServer(std::shared_ptr<System> system) : PluginBase(), _impl{std::make_unique<ActionServerImpl>(system)} {} ActionServer::~ActionServer() {} void ActionServer::subscribe_arm_disarm(ArmDisarmCallback callback) { _impl->subscribe_arm_disarm(callback); } void ActionServer::subscribe_flight_mode_change(FlightModeChangeCallback callback) { _impl->subscribe_flight_mode_change(callback); } void ActionServer::subscribe_takeoff(TakeoffCallback callback) { _impl->subscribe_takeoff(callback); } void ActionServer::subscribe_land(LandCallback callback) { _impl->subscribe_land(callback); } void ActionServer::subscribe_reboot(RebootCallback callback) { _impl->subscribe_reboot(callback); } void ActionServer::subscribe_shutdown(ShutdownCallback callback) { _impl->subscribe_shutdown(callback); } void ActionServer::subscribe_terminate(TerminateCallback callback) { _impl->subscribe_terminate(callback); } ActionServer::Result ActionServer::set_allow_takeoff(bool allow_takeoff) const { return _impl->set_allow_takeoff(allow_takeoff); } ActionServer::Result ActionServer::set_armable(bool armable, bool force_armable) const { return _impl->set_armable(armable, force_armable); } ActionServer::Result ActionServer::set_disarmable(bool disarmable, bool force_disarmable) const { return _impl->set_disarmable(disarmable, force_disarmable); } ActionServer::Result ActionServer::set_allowable_flight_modes(AllowableFlightModes flight_modes) const { return _impl->set_allowable_flight_modes(flight_modes); } ActionServer::AllowableFlightModes ActionServer::get_allowable_flight_modes() const { return _impl->get_allowable_flight_modes(); } bool operator==( const ActionServer::AllowableFlightModes& lhs, const ActionServer::AllowableFlightModes& rhs) { return (rhs.can_auto_mode == lhs.can_auto_mode) && (rhs.can_guided_mode == lhs.can_guided_mode) && (rhs.can_stabilize_mode == lhs.can_stabilize_mode); } std::ostream& operator<<(std::ostream& str, ActionServer::AllowableFlightModes const& allowable_flight_modes) { str << std::setprecision(15); str << "allowable_flight_modes:" << '\n' << "{\n"; str << " can_auto_mode: " << allowable_flight_modes.can_auto_mode << '\n'; str << " can_guided_mode: " << allowable_flight_modes.can_guided_mode << '\n'; str << " can_stabilize_mode: " << allowable_flight_modes.can_stabilize_mode << '\n'; str << '}'; return str; } bool operator==(const ActionServer::ArmDisarm& lhs, const ActionServer::ArmDisarm& rhs) { return (rhs.arm == lhs.arm) && (rhs.force == lhs.force); } std::ostream& operator<<(std::ostream& str, ActionServer::ArmDisarm const& arm_disarm) { str << std::setprecision(15); str << "arm_disarm:" << '\n' << "{\n"; str << " arm: " << arm_disarm.arm << '\n'; str << " force: " << arm_disarm.force << '\n'; str << '}'; return str; } std::ostream& operator<<(std::ostream& str, ActionServer::Result const& result) { switch (result) { case ActionServer::Result::Unknown: return str << "Unknown"; case ActionServer::Result::Success: return str << "Success"; case ActionServer::Result::NoSystem: return str << "No System"; case ActionServer::Result::ConnectionError: return str << "Connection Error"; case ActionServer::Result::Busy: return str << "Busy"; case ActionServer::Result::CommandDenied: return str << "Command Denied"; case ActionServer::Result::CommandDeniedLandedStateUnknown: return str << "Command Denied Landed State Unknown"; case ActionServer::Result::CommandDeniedNotLanded: return str << "Command Denied Not Landed"; case ActionServer::Result::Timeout: return str << "Timeout"; case ActionServer::Result::VtolTransitionSupportUnknown: return str << "Vtol Transition Support Unknown"; case ActionServer::Result::NoVtolTransitionSupport: return str << "No Vtol Transition Support"; case ActionServer::Result::ParameterError: return str << "Parameter Error"; default: return str << "Unknown"; } } std::ostream& operator<<(std::ostream& str, ActionServer::FlightMode const& flight_mode) { switch (flight_mode) { case ActionServer::FlightMode::Unknown: return str << "Unknown"; case ActionServer::FlightMode::Ready: return str << "Ready"; case ActionServer::FlightMode::Takeoff: return str << "Takeoff"; case ActionServer::FlightMode::Hold: return str << "Hold"; case ActionServer::FlightMode::Mission: return str << "Mission"; case ActionServer::FlightMode::ReturnToLaunch: return str << "Return To Launch"; case ActionServer::FlightMode::Land: return str << "Land"; case ActionServer::FlightMode::Offboard: return str << "Offboard"; case ActionServer::FlightMode::FollowMe: return str << "Follow Me"; case ActionServer::FlightMode::Manual: return str << "Manual"; case ActionServer::FlightMode::Altctl: return str << "Altctl"; case ActionServer::FlightMode::Posctl: return str << "Posctl"; case ActionServer::FlightMode::Acro: return str << "Acro"; case ActionServer::FlightMode::Stabilized: return str << "Stabilized"; default: return str << "Unknown"; } } } // namespace mavsdk
6,281
1,908
#include <GL/glut.h> #include <stdlib.h> #include <time.h> #include <ctime> #include "spaceship.hpp" MySpaceShip::MySpaceShip() { //Setup Quadric Object pObj = gluNewQuadric(); gluQuadricNormals(pObj, GLU_SMOOTH); posx = 0.0f; posy = 10.0f; posz = 2.0f; roty = 0.0f; //initial velocity (in unit per second) velx = 0.0f; vely = 3.0f; velz = 0.0f; //velroty = 10.0f; } MySpaceShip::~MySpaceShip() { gluDeleteQuadric(pObj); } void MySpaceShip::draw() { glTranslatef(posx, posy, posz); glRotatef(timetick, 0.0f, 1.0f, 0.0f); srand(time(NULL)); glDisable(GL_CULL_FACE); //front glPushMatrix(); glTranslatef(0.0f, 10.0f, 0.0f); glColor3f(0.1f, 0.1f, 0.1f); gluCylinder(pObj, 5.0f, 0.0f, 10, 26, 5); glPopMatrix(); //body glPushMatrix(); glTranslatef(0.0f, 10.0f, -15.0f); glColor3f(rand()%45*0.1, rand()%45*0.1,rand()%45 * 0.01 ); gluCylinder(pObj, 5.0f, 5.0f, 15, 26, 5); glPopMatrix(); //back glPushMatrix(); glTranslatef(0.0f, 10.0f, -15.0f); glColor3f(1.0f, 1.0f, 1.0f); gluDisk(pObj, 0.0f, 5.0f, 26, 5); glPopMatrix(); //top mirror glPushMatrix(); glTranslatef(0.0f, 14.0f, -8.0f); glColor3f(0.0f, 1.0f, 1.0f); gluSphere(pObj,4.0f, 20, 20); glPopMatrix(); //left wing alpha glPushMatrix(); glTranslatef(10.0f, 10.0f, -2.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.1f, 0.1f, 0.1f); gluCylinder(pObj, 3.0f, 3.0f, 3, 26, 5); //fan1 glTranslatef(0.0f, -3.0f, 2.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); //fan2 glTranslatef(3.0f, 1.0f, 3.0f); glRotatef(-90, 0.0f, 1.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); glPopMatrix(); //left wing beta glPushMatrix(); glTranslatef(10.0f, 10.0f, -12.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.1f, 0.1f, 0.1f); gluCylinder(pObj, 3.0f, 3.0f, 3, 26, 5); //fan1 glTranslatef(0.0f, -3.0f, 2.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); //fan2 glTranslatef(3.0f, 1.0f, 3.0f); glRotatef(-90, 0.0f, 1.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); glPopMatrix(); //right wing alpha glPushMatrix(); glTranslatef(-10.0f, 10.0f, -2.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.1f, 0.1f, 0.1f); gluCylinder(pObj, 3.0f, 3.0f, 3, 26, 5); //fan1 glTranslatef(0.0f, -3.0f, 2.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); //fan2 glTranslatef(3.0f, 1.0f, 3.0f); glRotatef(-90, 0.0f, 1.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); glPopMatrix(); //right wing beta glPushMatrix(); glTranslatef(-10.0f, 10.0f, -12.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.1f, 0.1f, 0.1f); gluCylinder(pObj, 3.0f, 3.0f, 3, 26, 5); //fan1 glTranslatef(0.0f, -3.0f, 2.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); //fan2 glTranslatef(3.0f, 1.0f, 3.0f); glRotatef(-90, 0.0f, 1.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); glPopMatrix(); //exhaust pipe glPushMatrix(); glTranslatef(0.0f, 10.0f, -20.0f); glColor3f(0.1f, 0.1f, 0.1f); gluCylinder(pObj, 4.0f, 2.0f, 6, 26, 5); glPopMatrix(); //EP back glPushMatrix(); glTranslatef(0.0f, 10.0f, -20.0f); glColor3f(1.0f, 0.0f, 0.0f); gluDisk(pObj, 0.0f, 4.0f, 26, 5); glPopMatrix(); glEnable(GL_CULL_FACE); } void MySpaceShip::Movespaceship() { glPushMatrix(); glTranslatef(0.0f , tickMove , 0.0f ); //glRotatef(roty, 0.0f, 1.0f, 0.0f); draw(); glPopMatrix(); } void MySpaceShip::drawfence() { glDisable(GL_CULL_FACE); glPushMatrix(); glColor3f(1.0f, 1.0f, 0.0f); glTranslatef(0.0f, 0.0f, 0.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); gluCylinder(pObj, 25.0f, 25.0f, 7, 26, 5); glPopMatrix(); } //elapsetime in milisec void MySpaceShip::tickTime(long int elapseTime) { ticktick++; if(ticktick == 30){ if(tickMove < 51.0 && moveUp == 1){ ticktick =0; tickMove+= 5.0; if(tickMove >= 51.0) moveUp = 0; }else if(moveUp == 0){ ticktick=0; tickMove-= 5.0; if(tickMove < 0.0){ moveUp = 1; } } } }
4,753
2,769
#pragma once #include <graphene/chain/protocol/base.hpp> #include <graphene/chain/sidechain_defs.hpp> #include <fc/safe.hpp> namespace graphene { namespace chain { struct son_wallet_withdraw_create_operation : public base_operation { struct fee_parameters_type { uint64_t fee = 0; }; asset fee; account_id_type payer; son_id_type son_id; fc::time_point_sec timestamp; uint32_t block_num; sidechain_type sidechain; std::string peerplays_uid; std::string peerplays_transaction_id; chain::account_id_type peerplays_from; chain::asset peerplays_asset; sidechain_type withdraw_sidechain; std::string withdraw_address; std::string withdraw_currency; safe<int64_t> withdraw_amount; account_id_type fee_payer()const { return payer; } share_type calculate_fee(const fee_parameters_type& k)const { return 0; } }; struct son_wallet_withdraw_process_operation : public base_operation { struct fee_parameters_type { uint64_t fee = 0; }; asset fee; account_id_type payer; son_wallet_withdraw_id_type son_wallet_withdraw_id; account_id_type fee_payer()const { return payer; } share_type calculate_fee(const fee_parameters_type& k)const { return 0; } }; } } // namespace graphene::chain FC_REFLECT(graphene::chain::son_wallet_withdraw_create_operation::fee_parameters_type, (fee) ) FC_REFLECT(graphene::chain::son_wallet_withdraw_create_operation, (fee)(payer) (son_id) (timestamp) (block_num) (sidechain) (peerplays_uid) (peerplays_transaction_id) (peerplays_from) (peerplays_asset) (withdraw_sidechain) (withdraw_address) (withdraw_currency) (withdraw_amount) ) FC_REFLECT(graphene::chain::son_wallet_withdraw_process_operation::fee_parameters_type, (fee) ) FC_REFLECT(graphene::chain::son_wallet_withdraw_process_operation, (fee)(payer) (son_wallet_withdraw_id) )
2,006
667
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/arm/math/im2sequence.h" #include <arm_neon.h> #include "lite/utils/cp_logging.h" namespace paddle { namespace lite { namespace arm { namespace math { void im2sequence(const float* input, const int input_c, const int input_h, const int input_w, const int kernel_h, const int kernel_w, const int pad_top, const int pad_bottom, const int pad_left, const int pad_right, const int stride_h, const int stride_w, const int out_h, const int out_w, float* out, Context<TARGET(kARM)>* ctx) { int window_size = kernel_h * kernel_w; int out_rows = out_h * out_w; int out_cols = input_c * window_size; int H_pad = input_h + pad_top + pad_bottom; int W_pad = input_w + pad_left + pad_right; for (int h_id = 0; h_id < out_h; h_id++) { for (int w_id = 0; w_id < out_w; w_id++) { // consider dilation. int start_h = h_id * stride_h - pad_top; int start_w = w_id * stride_w - pad_left; for (int c_id = 0; c_id < input_c; c_id++) { for (int k_h_id = 0; k_h_id < kernel_h; k_h_id++) { int in_h_id = start_h + k_h_id; bool exceed_flag = (in_h_id < 0) || (in_h_id >= H_pad); int out_start_id = (h_id * out_w + w_id) * out_cols + c_id * window_size; for (int k_w_id = 0; k_w_id < kernel_w; k_w_id++) { int in_w_id = start_w + k_w_id; exceed_flag = exceed_flag || (in_w_id < 0) || (in_w_id >= W_pad); int input_id = (c_id * input_h + in_h_id) * input_w + in_w_id; int out_id = out_start_id + k_h_id * kernel_w + k_w_id; out[out_id] = exceed_flag ? 0.f : input[input_id]; } } } } } } } // namespace math } // namespace arm } // namespace lite } // namespace paddle
2,633
916
/* Idea: - Dynamic Programming - If you reach the base case in the recursion, then you have an answer, so print it. - This method work if the dynamic programming answer is true or false. */ #include <bits/stdc++.h> using namespace std; int const N = 1e5 + 1; int n, a[N], dp[N][6]; vector<int> sol; int rec(int idx, int prv) { if(idx == n) { for(int i = 0; i < sol.size(); ++i) printf("%s%d", i == 0 ? "" : " ", sol[i]); puts(""); exit(0); } int &ret = dp[idx][prv]; if(ret != -1) return ret; ret = 0; if(a[idx] == a[idx - 1]) { for(int i = 1; i <= 5; ++i) if(i != prv) { sol.push_back(i); rec(idx + 1, i); sol.pop_back(); } } if(a[idx] > a[idx - 1]) { for(int i = prv + 1; i <= 5; ++i) { sol.push_back(i); rec(idx + 1, i); sol.pop_back(); } } if(a[idx] < a[idx - 1]) { for(int i = prv - 1; i >= 1; --i) { sol.push_back(i); rec(idx + 1, i); sol.pop_back(); } } return ret; } int main() { scanf("%d", &n); for(int i = 0; i < n; ++i) scanf("%d", a + i); memset(dp, -1, sizeof dp); for(int i = 1; i <= 5; ++i) { sol.push_back(i); if(rec(1, i)) return 0; sol.pop_back(); } puts("-1"); return 0; }
1,305
592
//***************************************************************************** // Copyright 2017-2020 Intel Corporation // // 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. //***************************************************************************** #pragma once #include <cstdint> #include <string> #include "core/operator_set.hpp" #include "utils/onnx_importer_visibility.hpp" namespace ngraph { namespace onnx_import { /// \brief Registers ONNX custom operator. /// The function performs the registration of external ONNX operator /// which is not part of ONNX importer. /// /// \note The operator must be registered before calling /// "import_onnx_model" functions. /// /// \param name The ONNX operator name. /// \param version The ONNX operator set version. /// \param domain The domain the ONNX operator is registered to. /// \param fn The function providing the implementation of the operator /// which transforms the single ONNX operator to an nGraph sub-graph. ONNX_IMPORTER_API void register_operator(const std::string& name, std::int64_t version, const std::string& domain, Operator fn); } // namespace onnx_import } // namespace ngraph
1,987
494
#include "../../include/gui/PlayingScreen.h" /* Derived-screen-specific additional frame processing for display*/ void PlayingScreen::processFrame(Mat& frame, const TrackingInfo& tracker) const { drawTrackingMarker ( frame, tracker.current() ); } void PlayingScreen::drawTrackingMarker(Mat& frame, const Point& center) const { /* "FREQUENCY POINTER" */ circle ( frame, center, dynconf.trackingMarkerRadius*0.25, StaticConfiguration::trackingMarkerColor, 10, CV_AA ); }
555
169
/** * @brief Parallel TDMA test subroutine * @author Ji-Hoon Kang (jhkang@kisti.re.kr), Korea Institute of Science and Technology Information * @date 15 January 2019 * @version 0.1 * @par Copyright Copyright (c) 2019 by Ji-Hoon Kang. All rights reserved. * @par License This project is release under the terms of the MIT License (see LICENSE in ) */ #include <iostream> #include <iomanip> #include <cmath> #include <mpi.h> #include <cstdlib> #include "tdma_parallel.h" using namespace std; const int n = 32; int main(int argc, char *argv[]) { int i, l, k; int nprocs, myrank; int n_mpi; tdma_parallel tdma; MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); MPI_Comm_rank(MPI_COMM_WORLD, &myrank); n_mpi = n / nprocs; double *a_mpi = new double[n_mpi+2]; double *b_mpi = new double[n_mpi+2]; double *c_mpi = new double[n_mpi+2]; double *x_mpi = new double[n_mpi+2]; double *r_mpi = new double[n_mpi+2]; double *a_ver = new double[n_mpi+2]; double *b_ver = new double[n_mpi+2]; double *c_ver = new double[n_mpi+2]; double *r_ver = new double[n_mpi+2]; for(i=0;i<n_mpi+2;i++) { a_mpi[i] = 0.; b_mpi[i] = 1.; c_mpi[i] = 0.; r_mpi[i] = 0.; x_mpi[i] = 0.; } for(i=1;i<n_mpi+1;i++) { a_mpi[i] = 1.0; +0.01*(i+myrank*n_mpi); c_mpi[i] = 1.0; +0.02*(i+myrank*n_mpi); b_mpi[i] = -(a_mpi[i]+c_mpi[i])-0.1-0.02*(i+myrank*n_mpi)*(i+myrank*n_mpi); r_mpi[i] = (double)(i-1+myrank*n_mpi); a_ver[i] = a_mpi[i]; b_ver[i] = b_mpi[i]; c_ver[i] = c_mpi[i]; r_ver[i] = r_mpi[i]; } tdma.setup(n, nprocs, myrank); // tdma.cr_pcr_solver(a_mpi,b_mpi,c_mpi,r_mpi,x_mpi); tdma.Thomas_pcr_solver(a_mpi,b_mpi,c_mpi,r_mpi,x_mpi); tdma.verify_solution(a_ver,b_ver,c_ver,r_ver,x_mpi); delete[] x_mpi; delete[] r_mpi; delete[] a_mpi; delete[] b_mpi; delete[] c_mpi; delete[] a_ver; delete[] b_ver; delete[] c_ver; if(MPI_Finalize()) { cout << "MPI _Finalize error" << endl; exit(0); } return 0; }
2,233
1,052
// Copyright (c) 2020-2021 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <bench/bench.h> #include <coins.h> #include <dsproof/dsproof.h> #include <key.h> #include <primitives/transaction.h> #include <random.h> #include <policy/policy.h> #include <script/script.h> #include <script/sighashtype.h> #include <script/sign.h> #include <script/standard.h> #include <limits> #include <optional> #include <vector> static void DoubleSpendProofCreate(benchmark::State &state) { CKey privKey, privKey2, privKey3; privKey.MakeNewKey(true); privKey2.MakeNewKey(true); privKey3.MakeNewKey(true); CMutableTransaction tx1, tx2; // make 2 huge tx's spending different fake inputs const uint64_t n_inputs = 3000; for (uint64_t i = 0; i < (n_inputs - 1); ++i) { tx1.vin.emplace_back(COutPoint{TxId(GetRandHash()), uint32_t(GetRand(n_inputs))}); tx2.vin.emplace_back(COutPoint{TxId(GetRandHash()), uint32_t(GetRand(n_inputs))}); } // make sure they spend a common input at the very end const COutPoint dupe{TxId(GetRandHash()), uint32_t(GetRand(n_inputs))}; tx1.vin.emplace_back(dupe); tx2.vin.emplace_back(tx1.vin.back()); tx1.vout.emplace_back(3 * COIN, GetScriptForDestination(privKey2.GetPubKey().GetID())); tx2.vout.emplace_back(2 * COIN, GetScriptForDestination(privKey3.GetPubKey().GetID())); std::optional<CTxOut> commonTxOut; // Sign transactions properly const SigHashType sigHashType = SigHashType().withForkId(); FlatSigningProvider keyStore; keyStore.pubkeys.emplace(privKey.GetPubKey().GetID(), privKey.GetPubKey()); keyStore.keys.emplace(privKey.GetPubKey().GetID(), privKey); for (auto *ptx : {&tx1, &tx2}) { auto &tx = *ptx; size_t i = 0; for (auto & txin : tx.vin) { const Coin coin(CTxOut{1 * COIN, GetScriptForDestination(privKey.GetPubKey().GetID())}, 123, false); SignatureData sigdata = DataFromTransaction(tx, i, coin.GetTxOut()); ProduceSignature(keyStore, MutableTransactionSignatureCreator(&tx, i, coin.GetTxOut().nValue, sigHashType), coin.GetTxOut().scriptPubKey, sigdata); UpdateInput(txin, sigdata); ++i; if (i == tx.vin.size() && !commonTxOut) commonTxOut = coin.GetTxOut(); } } assert(bool(commonTxOut)); const CTransaction ctx1{tx1}, ctx2{tx2}; while (state.KeepRunning()) { auto proof = DoubleSpendProof::create(ctx1, ctx2, dupe, &*commonTxOut); assert(!proof.isEmpty()); } } BENCHMARK(DoubleSpendProofCreate, 490);
2,787
1,017
#include "CameraController.h" #include "GraphicsSystem.h" #include "OgreCamera.h" #include "OgreWindow.h" using namespace Demo; namespace Demo { CameraController::CameraController( GraphicsSystem *graphicsSystem, bool useSceneNode ) : mUseSceneNode( useSceneNode ), mSpeedMofifier( false ), mCameraYaw( 0 ), mCameraPitch( 0 ), mCameraBaseSpeed( 10 ), mCameraSpeedBoost( 5 ), mGraphicsSystem( graphicsSystem ) { memset( mWASD, 0, sizeof(mWASD) ); memset( mSlideUpDown, 0, sizeof(mSlideUpDown) ); } //----------------------------------------------------------------------------------- void CameraController::update( float timeSinceLast ) { Ogre::Camera *camera = mGraphicsSystem->getCamera(); if( mCameraYaw != 0.0f || mCameraPitch != 0.0f ) { if( mUseSceneNode ) { Ogre::Node *cameraNode = camera->getParentNode(); // Update now as yaw needs the derived orientation. cameraNode->_getFullTransformUpdated(); cameraNode->yaw( Ogre::Radian( mCameraYaw ), Ogre::Node::TS_WORLD ); cameraNode->pitch( Ogre::Radian( mCameraPitch ) ); } else { camera->yaw( Ogre::Radian( mCameraYaw ) ); camera->pitch( Ogre::Radian( mCameraPitch ) ); } mCameraYaw = 0.0f; mCameraPitch = 0.0f; } int camMovementZ = mWASD[2] - mWASD[0]; int camMovementX = mWASD[3] - mWASD[1]; int slideUpDown = mSlideUpDown[0] - mSlideUpDown[1]; if( camMovementZ || camMovementX || slideUpDown ) { Ogre::Vector3 camMovementDir( camMovementX, slideUpDown, camMovementZ ); camMovementDir.normalise(); camMovementDir *= timeSinceLast * mCameraBaseSpeed * (1 + mSpeedMofifier * mCameraSpeedBoost); if( mUseSceneNode ) { Ogre::Node *cameraNode = camera->getParentNode(); cameraNode->translate( camMovementDir, Ogre::Node::TS_LOCAL ); } else { camera->moveRelative( camMovementDir ); } } } //----------------------------------------------------------------------------------- bool CameraController::keyPressed( const SDL_KeyboardEvent &arg ) { if( arg.keysym.scancode == SDL_SCANCODE_LSHIFT ) mSpeedMofifier = true; if( arg.keysym.scancode == SDL_SCANCODE_W ) mWASD[0] = true; else if( arg.keysym.scancode == SDL_SCANCODE_A ) mWASD[1] = true; else if( arg.keysym.scancode == SDL_SCANCODE_S ) mWASD[2] = true; else if( arg.keysym.scancode == SDL_SCANCODE_D ) mWASD[3] = true; else if( arg.keysym.scancode == SDL_SCANCODE_PAGEUP || arg.keysym.scancode == SDL_SCANCODE_E ) mSlideUpDown[0] = true; else if( arg.keysym.scancode == SDL_SCANCODE_PAGEDOWN || arg.keysym.scancode == SDL_SCANCODE_Q ) mSlideUpDown[1] = true; else return false; return true; } //----------------------------------------------------------------------------------- bool CameraController::keyReleased( const SDL_KeyboardEvent &arg ) { if( arg.keysym.scancode == SDL_SCANCODE_LSHIFT ) mSpeedMofifier = false; if( arg.keysym.scancode == SDL_SCANCODE_W ) mWASD[0] = false; else if( arg.keysym.scancode == SDL_SCANCODE_A ) mWASD[1] = false; else if( arg.keysym.scancode == SDL_SCANCODE_S ) mWASD[2] = false; else if( arg.keysym.scancode == SDL_SCANCODE_D ) mWASD[3] = false; else if( arg.keysym.scancode == SDL_SCANCODE_PAGEUP || arg.keysym.scancode == SDL_SCANCODE_E ) mSlideUpDown[0] = false; else if( arg.keysym.scancode == SDL_SCANCODE_PAGEDOWN || arg.keysym.scancode == SDL_SCANCODE_Q ) mSlideUpDown[1] = false; else return false; return true; } //----------------------------------------------------------------------------------- void CameraController::mouseMoved( const SDL_Event &arg ) { float width = static_cast<float>( mGraphicsSystem->getRenderWindow()->getWidth() ); float height = static_cast<float>( mGraphicsSystem->getRenderWindow()->getHeight() ); mCameraYaw += -arg.motion.xrel / width; mCameraPitch += -arg.motion.yrel / height; } }
4,650
1,478
/************************************************************ ************************************************************/ #include "fft.h" /************************************************************ ************************************************************/ /****************************** ******************************/ FFT::FFT() { } /****************************** ******************************/ FFT::~FFT() { } /****************************** ******************************/ void FFT::threadedFunction() { while(isThreadRunning()) { lock(); unlock(); sleep(THREAD_SLEEP_MS); } } /****************************** ******************************/ void FFT::setup(int AUDIO_BUF_SIZE) { /******************** ■std::vectorのresizeとassignの違い (C++) https://minus9d.hatenablog.com/entry/2021/02/07/175159 ********************/ vol_l.assign(AUDIO_BUF_SIZE, 0.0); vol_r.assign(AUDIO_BUF_SIZE, 0.0); } /****************************** ******************************/ void FFT::update() { } /****************************** ******************************/ void FFT::draw() { } /****************************** ******************************/ void FFT::SetVol(ofSoundBuffer & buffer) { lock(); if( (vol_l.size() < buffer.getNumFrames()) || (vol_r.size() < buffer.getNumFrames()) ){ printf("size of vol vector not enough\n"); fflush(stdout); }else{ for (size_t i = 0; i < buffer.getNumFrames(); i++){ vol_l[i] = buffer[i*2 + 0]; vol_r[i] = buffer[i*2 + 1]; } } unlock(); } /****************************** ******************************/ void FFT::GetVol(ofSoundBuffer & buffer, bool b_EnableAudioOut) { lock(); if( (vol_l.size() < buffer.getNumFrames()) || (vol_r.size() < buffer.getNumFrames()) ){ printf("size of vol vector not enough\n"); fflush(stdout); }else{ for (size_t i = 0; i < buffer.getNumFrames(); i++){ if(b_EnableAudioOut){ buffer[i*2 + 0] = vol_l[i]; buffer[i*2 + 1] = vol_r[i]; }else{ buffer[i*2 + 0] = 0; buffer[i*2 + 1] = 0; } } } unlock(); }
2,075
803
/* Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive, for example, "Aa" is not considered a palindrome here. Example 1: Input: s = "abccccdd" Output: 7 Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7. Example 2: Input: s = "a" Output: 1 Example 3: Input: s = "bb" Output: 2 Constraints: 1 <= s.length <= 2000 s consists of lowercase and/or uppercase English letters only. */ // all even chars can be used to construct the string, but only one odd char can be added at last class Solution { public: int longestPalindrome(string s) { unordered_map<char,int> ch2freq; int res = 0; bool remainder = false; for ( auto c : s ) ch2freq[c]++; for ( auto it : ch2freq ) { if ( it.second % 2 ) { remainder = true; } res += (it.second / 2) * 2; } if ( remainder ) res++; return res; } };
1,132
361
/* GammaTable.cpp */ //---------------------------------------------------------------------------------------- // // Project: CCore 3.00 // // Tag: Desktop // // License: Boost Software License - Version 1.0 - August 17th, 2003 // // see http://www.boost.org/LICENSE_1_0.txt or the local copy // // Copyright (c) 2016 Sergey Strukov. All rights reserved. // //---------------------------------------------------------------------------------------- #include <CCore/inc/video/GammaTable.h> #include <math.h> namespace CCore { namespace Video { /* class GammaTable */ template <UIntType UInt> void GammaTable::Fill(PtrLen<UInt> table,double order) { double M=table.len-1; double V=MaxUInt<UInt>; for(ulen i=0; i<table.len ;i++) { double x=i/M; double y=pow(x,order); table[i]=UInt( round(V*y) ); } } GammaTable::GammaTable() noexcept { } GammaTable::~GammaTable() { } void GammaTable::fill(double order) { static const ulen DirectLen = ulen(1)<<8 ; static const ulen InverseLen = ulen(1)<<16 ; if( !direct.getLen() ) { SimpleArray<uint16> direct_(DirectLen); SimpleArray<uint8> inverse_(InverseLen); direct=std::move(direct_); inverse=std::move(inverse_); } Fill(Range(direct),order); Fill(Range(inverse),1/order); this->order=order; } } // namespace Video } // namespace CCore
1,385
489
/* * This file is part of lslidar_c16 driver. * * The driver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The driver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with the driver. If not, see <http://www.gnu.org/licenses/>. */ #include "lslidar_c16_driver/input.h" extern volatile sig_atomic_t flag; namespace lslidar_c16_driver { static const size_t packet_size = sizeof(lslidar_c16_msgs::LslidarC16Packet().data); //////////////////////////////////////////////////////////////////////// // Input base class implementation //////////////////////////////////////////////////////////////////////// /** @brief constructor * * @param private_nh ROS private handle for calling node. * @param port UDP port number. */ Input::Input(ros::NodeHandle private_nh, uint16_t port) : private_nh_(private_nh), port_(port) { npkt_update_flag_ = false; cur_rpm_ = 0; return_mode_ = 1; private_nh.param("device_ip", devip_str_, std::string("")); if (!devip_str_.empty()) ROS_INFO_STREAM("Only accepting packets from IP address: " << devip_str_); } int Input::getRpm(void) { return cur_rpm_; } int Input::getReturnMode(void) { return return_mode_; } bool Input::getUpdateFlag(void) { return npkt_update_flag_; } void Input::clearUpdateFlag(void) { npkt_update_flag_ = false; } //////////////////////////////////////////////////////////////////////// // InputSocket class implementation //////////////////////////////////////////////////////////////////////// /** @brief constructor * * @param private_nh ROS private handle for calling node. * @param port UDP port number */ InputSocket::InputSocket(ros::NodeHandle private_nh, uint16_t port) : Input(private_nh, port) { sockfd_ = -1; if (!devip_str_.empty()) { inet_aton(devip_str_.c_str(), &devip_); } ROS_INFO_STREAM("Opening UDP socket: port " << port); sockfd_ = socket(PF_INET, SOCK_DGRAM, 0); if (sockfd_ == -1) { perror("socket"); // TODO: ROS_ERROR errno return; } int opt = 1; if (setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR, (const void*)&opt, sizeof(opt))) { perror("setsockopt error!\n"); return; } sockaddr_in my_addr; // my address information memset(&my_addr, 0, sizeof(my_addr)); // initialize to zeros my_addr.sin_family = AF_INET; // host byte order my_addr.sin_port = htons(port); // port in network byte order my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill in my IP if (bind(sockfd_, (sockaddr*)&my_addr, sizeof(sockaddr)) == -1) { perror("bind"); // TODO: ROS_ERROR errno return; } if (fcntl(sockfd_, F_SETFL, O_NONBLOCK | FASYNC) < 0) { perror("non-block"); return; } } /** @brief destructor */ InputSocket::~InputSocket(void) { (void)close(sockfd_); } /** @brief Get one lslidar packet. */ int InputSocket::getPacket(lslidar_c16_msgs::LslidarC16Packet* pkt, const double time_offset) { double time1 = ros::Time::now().toSec(); struct pollfd fds[1]; fds[0].fd = sockfd_; fds[0].events = POLLIN; static const int POLL_TIMEOUT = 1200; // one second (in msec) sockaddr_in sender_address; socklen_t sender_address_len = sizeof(sender_address); while (flag == 1) // while (true) { // Receive packets that should now be available from the // socket using a blocking read. // poll() until input available do { int retval = poll(fds, 1, POLL_TIMEOUT); if (retval < 0) // poll() error? { if (errno != EINTR) ROS_ERROR("poll() error: %s", strerror(errno)); return 1; } if (retval == 0) // poll() timeout? { time_t curTime = time(NULL); struct tm *curTm = localtime(&curTime); char bufTime[30] = {0}; sprintf(bufTime,"%d-%d-%d %d:%d:%d", curTm->tm_year+1900, curTm->tm_mon+1, curTm->tm_mday, curTm->tm_hour, curTm->tm_min, curTm->tm_sec); ROS_WARN_THROTTLE(2, "%s lslidar poll() timeout", bufTime); /* char buffer_data[8] = "re-con"; memset(&sender_address, 0, sender_address_len); // initialize to zeros sender_address.sin_family = AF_INET; // host byte order sender_address.sin_port = htons(MSOP_DATA_PORT_NUMBER); // port in network byte order, set any value sender_address.sin_addr.s_addr = devip_.s_addr; // automatically fill in my IP sendto(sockfd_, &buffer_data, strlen(buffer_data), 0, (sockaddr*)&sender_address, sender_address_len); */ return 1; } if ((fds[0].revents & POLLERR) || (fds[0].revents & POLLHUP) || (fds[0].revents & POLLNVAL)) // device error? { ROS_ERROR("poll() reports lslidar error"); return 1; } } while ((fds[0].revents & POLLIN) == 0); ssize_t nbytes = recvfrom(sockfd_, &pkt->data[0], packet_size, 0, (sockaddr*)&sender_address, &sender_address_len); if (nbytes < 0) { if (errno != EWOULDBLOCK) { perror("recvfail"); ROS_INFO("recvfail"); return 1; } } else if ((size_t)nbytes == packet_size) { if (devip_str_ != "" && sender_address.sin_addr.s_addr != devip_.s_addr) continue; else break; // done } ROS_DEBUG_STREAM("incomplete lslidar packet read: " << nbytes << " bytes"); } if (flag == 0) { abort(); } if (pkt->data[0] == 0xA5 && pkt->data[1] == 0xFF && pkt->data[2] == 0x00 && pkt->data[3] == 0x5A) {//difop int rpm = (pkt->data[8]<<8)|pkt->data[9]; //ROS_INFO("rpm=%d",rpm); int mode = 1; if (cur_rpm_ != rpm || return_mode_ != mode) { cur_rpm_ = rpm; return_mode_ = mode; npkt_update_flag_ = true; } } // Average the times at which we begin and end reading. Use that to // estimate when the scan occurred. Add the time offset. double time2 = ros::Time::now().toSec(); pkt->stamp = ros::Time((time2 + time1) / 2.0 + time_offset); return 0; } //////////////////////////////////////////////////////////////////////// // InputPCAP class implementation //////////////////////////////////////////////////////////////////////// /** @brief constructor * * @param private_nh ROS private handle for calling node. * @param port UDP port number * @param packet_rate expected device packet frequency (Hz) * @param filename PCAP dump file name */ InputPCAP::InputPCAP(ros::NodeHandle private_nh, uint16_t port, double packet_rate, std::string filename, bool read_once, bool read_fast, double repeat_delay) : Input(private_nh, port), packet_rate_(packet_rate), filename_(filename) { pcap_ = NULL; empty_ = true; // get parameters using private node handle private_nh.param("read_once", read_once_, false); private_nh.param("read_fast", read_fast_, false); private_nh.param("repeat_delay", repeat_delay_, 0.0); if (read_once_) ROS_INFO("Read input file only once."); if (read_fast_) ROS_INFO("Read input file as quickly as possible."); if (repeat_delay_ > 0.0) ROS_INFO("Delay %.3f seconds before repeating input file.", repeat_delay_); // Open the PCAP dump file // ROS_INFO("Opening PCAP file \"%s\"", filename_.c_str()); ROS_INFO_STREAM("Opening PCAP file " << filename_); if ((pcap_ = pcap_open_offline(filename_.c_str(), errbuf_)) == NULL) { ROS_FATAL("Error opening lslidar socket dump file."); return; } std::stringstream filter; if (devip_str_ != "") // using specific IP? { filter << "src host " << devip_str_ << " && "; } filter << "udp dst port " << port; pcap_compile(pcap_, &pcap_packet_filter_, filter.str().c_str(), 1, PCAP_NETMASK_UNKNOWN); } /** destructor */ InputPCAP::~InputPCAP(void) { pcap_close(pcap_); } /** @brief Get one lslidar packet. */ int InputPCAP::getPacket(lslidar_c16_msgs::LslidarC16Packet* pkt, const double time_offset) { struct pcap_pkthdr* header; const u_char* pkt_data; // while (flag == 1) while (true) { int res; if ((res = pcap_next_ex(pcap_, &header, &pkt_data)) >= 0) { // Skip packets not for the correct port and from the // selected IP address. if (!devip_str_.empty() && (0 == pcap_offline_filter(&pcap_packet_filter_, header, pkt_data))) continue; // Keep the reader from blowing through the file. if (read_fast_ == false) packet_rate_.sleep(); memcpy(&pkt->data[0], pkt_data + 42, packet_size); if (pkt->data[0] == 0xA5 && pkt->data[1] == 0xFF && pkt->data[2] == 0x00 && pkt->data[3] == 0x5A) {//difop int rpm = (pkt->data[8]<<8)|pkt->data[9]; int mode = 1; if ((pkt->data[45] == 0x08 && pkt->data[46] == 0x02 && pkt->data[47] >= 0x09) || (pkt->data[45] > 0x08) || (pkt->data[45] == 0x08 && pkt->data[46] > 0x02)) { if (pkt->data[300] != 0x01 && pkt->data[300] != 0x02) { mode = 0; } } if (cur_rpm_ != rpm || return_mode_ != mode) { cur_rpm_ = rpm; return_mode_ = mode; npkt_update_flag_ = true; } } pkt->stamp = ros::Time::now(); // time_offset not considered here, as no // synchronization required empty_ = false; return 0; // success } if (empty_) // no data in file? { ROS_WARN("Error %d reading lslidar packet: %s", res, pcap_geterr(pcap_)); return -1; } if (read_once_) { ROS_INFO("end of file reached -- done reading."); return -1; } if (repeat_delay_ > 0.0) { ROS_INFO("end of file reached -- delaying %.3f seconds.", repeat_delay_); usleep(rint(repeat_delay_ * 1000000.0)); } ROS_DEBUG("replaying lslidar dump file"); // I can't figure out how to rewind the file, because it // starts with some kind of header. So, close the file // and reopen it with pcap. pcap_close(pcap_); pcap_ = pcap_open_offline(filename_.c_str(), errbuf_); empty_ = true; // maybe the file disappeared? } // loop back and try again if (flag == 0) { abort(); } } }
10,695
3,898
/*---------------------------------------------------------------------------*\ Copyright (C) 2011 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CAELUS. If not, see <http://www.gnu.org/licenses/>. Class CML::HashSet Description A HashTable with keys but without contents. Typedef CML::wordHashSet Description A HashSet with (the default) word keys. Typedef CML::labelHashSet Description A HashSet with label keys. \*---------------------------------------------------------------------------*/ #ifndef HashSet_H #define HashSet_H #include "HashTable.hpp" #include "nil.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { /*---------------------------------------------------------------------------*\ Class HashSet Declaration \*---------------------------------------------------------------------------*/ template<class Key=word, class Hash=string::hash> class HashSet : public HashTable<nil, Key, Hash> { public: typedef typename HashTable<nil, Key, Hash>::iterator iterator; typedef typename HashTable<nil, Key, Hash>::const_iterator const_iterator; // Constructors //- Construct given initial size HashSet(const label size = 128) : HashTable<nil, Key, Hash>(size) {} //- Construct from Istream HashSet(Istream& is) : HashTable<nil, Key, Hash>(is) {} //- Construct from UList of Key HashSet(const UList<Key>&); //- Construct as copy HashSet(const HashSet<Key, Hash>& hs) : HashTable<nil, Key, Hash>(hs) {} //- Construct by transferring the parameter contents HashSet(const Xfer<HashSet<Key, Hash> >& hs) : HashTable<nil, Key, Hash>(hs) {} //- Construct by transferring the parameter contents HashSet(const Xfer<HashTable<nil, Key, Hash> >& hs) : HashTable<nil, Key, Hash>(hs) {} //- Construct from the keys of another HashTable, // the type of values held is arbitrary. template<class AnyType, class AnyHash> HashSet(const HashTable<AnyType, Key, AnyHash>&); // Member Functions // Edit //- Insert a new entry bool insert(const Key& key) { return HashTable<nil, Key, Hash>::insert(key, nil()); } //- Insert keys from a UList of Key // Return the number of new elements inserted label insert(const UList<Key>&); //- Same as insert (cannot overwrite nil content) bool set(const Key& key) { return insert(key); } //- Same as insert (cannot overwrite nil content) label set(const UList<Key>& lst) { return insert(lst); } //- Unset the specified key - same as erase bool unset(const Key& key) { return HashTable<nil, Key, Hash>::erase(key); } // Member Operators //- Return true if the entry exists, same as found() inline bool operator[](const Key&) const; //- Equality. Two hashtables are equal when their contents are equal. // Independent of table size or order. bool operator==(const HashSet<Key, Hash>&) const; //- The opposite of the equality operation. bool operator!=(const HashSet<Key, Hash>&) const; //- Combine entries from HashSets void operator|=(const HashSet<Key, Hash>&); //- Only retain entries found in both HashSets void operator&=(const HashSet<Key, Hash>&); //- Only retain unique entries (xor) void operator^=(const HashSet<Key, Hash>&); //- Add entries listed in the given HashSet to this HashSet inline void operator+=(const HashSet<Key, Hash>& rhs) { this->operator|=(rhs); } //- Remove entries listed in the given HashSet from this HashSet void operator-=(const HashSet<Key, Hash>&); }; // Global Operators //- Combine entries from HashSets template<class Key, class Hash> HashSet<Key,Hash> operator| ( const HashSet<Key,Hash>& hash1, const HashSet<Key,Hash>& hash2 ); //- Create a HashSet that only contains entries found in both HashSets template<class Key, class Hash> HashSet<Key,Hash> operator& ( const HashSet<Key,Hash>& hash1, const HashSet<Key,Hash>& hash2 ); //- Create a HashSet that only contains unique entries (xor) template<class Key, class Hash> HashSet<Key,Hash> operator^ ( const HashSet<Key,Hash>& hash1, const HashSet<Key,Hash>& hash2 ); //- A HashSet with word keys. typedef HashSet<> wordHashSet; //- A HashSet with label keys. typedef HashSet<label, Hash<label> > labelHashSet; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace CML // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #ifndef HashSet_C #define HashSet_C #include "HashSet.hpp" // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // template<class Key, class Hash> CML::HashSet<Key, Hash>::HashSet(const UList<Key>& lst) : HashTable<nil, Key, Hash>(2*lst.size()) { forAll(lst, elemI) { this->insert(lst[elemI]); } } template<class Key, class Hash> template<class AnyType, class AnyHash> CML::HashSet<Key, Hash>::HashSet ( const HashTable<AnyType, Key, AnyHash>& h ) : HashTable<nil, Key, Hash>(h.size()) { for ( typename HashTable<AnyType, Key, AnyHash>::const_iterator cit = h.cbegin(); cit != h.cend(); ++cit ) { this->insert(cit.key()); } } // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // template<class Key, class Hash> CML::label CML::HashSet<Key, Hash>::insert(const UList<Key>& lst) { label count = 0; forAll(lst, elemI) { if (this->insert(lst[elemI])) { ++count; } } return count; } // * * * * * * * * * * * * * * * Member Operators * * * * * * * * * * * * * // template<class Key, class Hash> inline bool CML::HashSet<Key, Hash>::operator[](const Key& key) const { return this->found(key); } template<class Key, class Hash> bool CML::HashSet<Key, Hash>::operator==(const HashSet<Key, Hash>& rhs) const { // Are all lhs elements in rhs? for (const_iterator iter = this->cbegin(); iter != this->cend(); ++iter) { if (!rhs.found(iter.key())) { return false; } } // Are all rhs elements in lhs? for (const_iterator iter = rhs.cbegin(); iter != rhs.cend(); ++iter) { if (!this->found(iter.key())) { return false; } } return true; } template<class Key, class Hash> bool CML::HashSet<Key, Hash>::operator!=(const HashSet<Key, Hash>& rhs) const { return !(this->operator==(rhs)); } template<class Key, class Hash> void CML::HashSet<Key, Hash>::operator|=(const HashSet<Key, Hash>& rhs) { // Add rhs elements into lhs for (const_iterator iter = rhs.cbegin(); iter != rhs.cend(); ++iter) { this->insert(iter.key()); } } template<class Key, class Hash> void CML::HashSet<Key, Hash>::operator&=(const HashSet<Key, Hash>& rhs) { // Remove elements not also found in rhs for (iterator iter = this->begin(); iter != this->end(); ++iter) { if (!rhs.found(iter.key())) { this->erase(iter); } } } template<class Key, class Hash> void CML::HashSet<Key, Hash>::operator^=(const HashSet<Key, Hash>& rhs) { // Add missed rhs elements, remove duplicate elements for (const_iterator iter = rhs.cbegin(); iter != rhs.cend(); ++iter) { if (this->found(iter.key())) { this->erase(iter.key()); } else { this->insert(iter.key()); } } } // same as HashTable::erase() template<class Key, class Hash> void CML::HashSet<Key, Hash>::operator-=(const HashSet<Key, Hash>& rhs) { // Remove rhs elements from lhs for (const_iterator iter = rhs.cbegin(); iter != rhs.cend(); ++iter) { this->erase(iter.key()); } } /* * * * * * * * * * * * * * * * Global operators * * * * * * * * * * * * * */ template<class Key, class Hash> CML::HashSet<Key, Hash> CML::operator| ( const HashSet<Key, Hash>& hash1, const HashSet<Key, Hash>& hash2 ) { HashSet<Key, Hash> out(hash1); out |= hash2; return out; } template<class Key, class Hash> CML::HashSet<Key, Hash> CML::operator& ( const HashSet<Key, Hash>& hash1, const HashSet<Key, Hash>& hash2 ) { HashSet<Key, Hash> out(hash1); out &= hash2; return out; } template<class Key, class Hash> CML::HashSet<Key, Hash> CML::operator^ ( const HashSet<Key, Hash>& hash1, const HashSet<Key, Hash>& hash2 ) { HashSet<Key, Hash> out(hash1); out ^= hash2; return out; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
10,047
3,228
// // FILE NAME: GenProtoS_CallResponse.cpp // // AUTHOR: Dean Roddey // // CREATED: 11/24/2003 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file implements a simple class that represents a call/response // exchange with the target device. // // CAVEATS/GOTCHAS: // // LOG: // // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include "GenProtoS_.hpp" // --------------------------------------------------------------------------- // Magic macros // --------------------------------------------------------------------------- RTTIDecls(TGenProtoCallRep,TObject) // --------------------------------------------------------------------------- // CLASS: TGenProtoCallRep // PREFIX: clrp // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TGenProtoCallRep: Constructors and Destructor // --------------------------------------------------------------------------- TGenProtoCallRep::TGenProtoCallRep() : m_c4MillisPeriod(0) , m_c4MillisToWait(0) , m_c4NextPoll(TTime::c4Millis()) , m_pqryToSend(nullptr) , m_prepToExpect(nullptr) { } TGenProtoCallRep:: TGenProtoCallRep( TGenProtoQuery* const pqryToSend , TGenProtoReply* const prepToExpect , const tCIDLib::TCard4 c4MillisToWait) : m_c4MillisPeriod(0) , m_c4MillisToWait(c4MillisToWait) , m_c4NextPoll(TTime::c4Millis()) , m_pqryToSend(pqryToSend) , m_prepToExpect(prepToExpect) { } TGenProtoCallRep:: TGenProtoCallRep( TGenProtoQuery* const pqryToSend , TGenProtoReply* const prepToExpect , const tCIDLib::TCard4 c4MillisToWait , const tCIDLib::TCard4 c4MillisPeriod) : m_c4MillisPeriod(c4MillisPeriod) , m_c4MillisToWait(c4MillisToWait) , m_c4NextPoll(TTime::c4Millis()) , m_pqryToSend(pqryToSend) , m_prepToExpect(prepToExpect) { } TGenProtoCallRep::TGenProtoCallRep(const TGenProtoCallRep& clrpToCopy) : m_c4MillisPeriod(clrpToCopy.m_c4MillisPeriod) , m_c4MillisToWait(clrpToCopy.m_c4MillisToWait) , m_c4NextPoll(clrpToCopy.m_c4NextPoll) , m_pqryToSend(clrpToCopy.m_pqryToSend) , m_prepToExpect(clrpToCopy.m_prepToExpect) { } TGenProtoCallRep::~TGenProtoCallRep() { // We don't own the query/reply pointers, so do nothing } // --------------------------------------------------------------------------- // TGenProtoCallRep: Public operators // --------------------------------------------------------------------------- TGenProtoCallRep& TGenProtoCallRep::operator=(const TGenProtoCallRep& clrpToAssign) { if (this != &clrpToAssign) { // We don't own the query and reply pointers, so we can shallow copy m_c4MillisPeriod = clrpToAssign.m_c4MillisPeriod; m_c4MillisToWait = clrpToAssign.m_c4MillisToWait; m_c4NextPoll = clrpToAssign.m_c4NextPoll; m_pqryToSend = clrpToAssign.m_pqryToSend; m_prepToExpect = clrpToAssign.m_prepToExpect; } return *this; } // --------------------------------------------------------------------------- // TGenProtoCallRep: Public, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TBoolean TGenProtoCallRep::bExpectsReply() const { return (m_prepToExpect != nullptr); } tCIDLib::TCard4 TGenProtoCallRep::c4MillisPeriod() const { return m_c4MillisPeriod; } tCIDLib::TCard4 TGenProtoCallRep::c4MillisToWait() const { return m_c4MillisToWait; } tCIDLib::TCard4 TGenProtoCallRep::c4NextPollTime() const { return m_c4NextPoll; } const TGenProtoQuery& TGenProtoCallRep::qryToSend() const { CIDAssert(m_pqryToSend != nullptr, L"m_pqryToSend data is null"); return *m_pqryToSend; } TGenProtoQuery& TGenProtoCallRep::qryToSend() { CIDAssert(m_pqryToSend != nullptr, L"m_pqryToSend data is null"); return *m_pqryToSend; } const TGenProtoReply& TGenProtoCallRep::repToExpect() const { // This is optional, so throw if not set if (!m_prepToExpect) { facGenProtoS().ThrowErr ( CID_FILE , CID_LINE , kGPDErrs::errcRunT_NoReplyDefined , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::NotReady , m_pqryToSend->strKey() ); } return *m_prepToExpect; } TGenProtoReply& TGenProtoCallRep::repToExpect() { // This is optional, so throw if not set if (!m_prepToExpect) { facGenProtoS().ThrowErr ( CID_FILE , CID_LINE , kGPDErrs::errcRunT_NoReplyDefined , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::NotReady , m_pqryToSend->strKey() ); } return *m_prepToExpect; } tCIDLib::TVoid TGenProtoCallRep::ResetPollTime() { m_c4NextPoll = TTime::c4Millis() + m_c4MillisPeriod; } tCIDLib::TVoid TGenProtoCallRep::Set( TGenProtoQuery* const pqryToSend , TGenProtoReply* const prepToExpect , const tCIDLib::TCard4 c4MillisToWait) { // We don't own the pointers, so no cleanup of old code is required m_c4MillisToWait = c4MillisToWait; m_pqryToSend = pqryToSend; m_prepToExpect = prepToExpect; }
5,797
2,043
#include "ltr559.hpp" #include <algorithm> namespace pimoroni { lookup::lookup(std::initializer_list<uint16_t> values) : lut(values) { } uint8_t lookup::index(uint16_t value) { auto it = find(lut.begin(), lut.end(), value); if(it == lut.end()) return 0; return it - lut.begin(); } uint16_t lookup::value(uint8_t index) { return lut[index]; } pimoroni::lookup LTR559::lookup_led_current({5, 10, 20, 50, 100}); pimoroni::lookup LTR559::lookup_led_duty_cycle({25, 50, 75, 100}); pimoroni::lookup LTR559::lookup_led_pulse_freq({30, 40, 50, 60, 70, 80, 90, 100}); pimoroni::lookup LTR559::lookup_proximity_meas_rate({10, 50, 70, 100, 200, 500, 1000, 2000}); pimoroni::lookup LTR559::lookup_light_integration_time({100, 50, 200, 400, 150, 250, 300, 350}); pimoroni::lookup LTR559::lookup_light_repeat_rate({50, 100, 200, 500, 1000, 2000}); pimoroni::lookup LTR559::lookup_light_gain({1, 2, 4, 8, 0, 0, 48, 96}); bool LTR559::init() { i2c_init(i2c, 400000); gpio_set_function(sda, GPIO_FUNC_I2C); gpio_pull_up(sda); gpio_set_function(scl, GPIO_FUNC_I2C); gpio_pull_up(scl); if(interrupt != PIN_UNUSED) { gpio_set_function(interrupt, GPIO_FUNC_SIO); gpio_set_dir(interrupt, GPIO_IN); gpio_pull_up(interrupt); } reset(); interrupts(true, true); // 50mA, 1.0 duty cycle, 30Hz, 1 pulse proximity_led(50, 1.0, 30, 1); // enabled, gain 4x light_control(true, 4); // enabled, saturation indicator enabled proximity_control(true, true); // 100ms measurement rate proximity_measurement_rate(100); // 50ms integration time and repeat rate light_measurement_rate(50, 50); light_threshold(0xFFFF, 0x0000); proximity_threshold(0x7FFF, 0x7FFF); proximity_offset(0); return true; } void LTR559::reset() { set_bits(LTR559_ALS_CONTROL, LTR559_ALS_CONTROL_SW_RESET_BIT); while(get_bits(LTR559_ALS_CONTROL, LTR559_ALS_CONTROL_SW_RESET_BIT)) { sleep_ms(100); } } i2c_inst_t* LTR559::get_i2c() const { return i2c; } int LTR559::get_sda() const { return sda; } int LTR559::get_scl() const { return scl; } int LTR559::get_int() const { return interrupt; } uint8_t LTR559::part_id() { uint8_t part_id; read_bytes(LTR559_PART_ID, &part_id, 1); return (part_id >> LTR559_PART_ID_PART_NUMBER_SHIFT) & LTR559_PART_ID_PART_NUMBER_MASK; } uint8_t LTR559::revision_id() { uint8_t revision_id; read_bytes(LTR559_PART_ID, &revision_id, 1); return revision_id & LTR559_PART_ID_REVISION_MASK; } uint8_t LTR559::manufacturer_id() { uint8_t manufacturer; read_bytes(LTR559_MANUFACTURER_ID, &manufacturer, 1); return manufacturer; } bool LTR559::get_reading() { bool has_updated = false; uint8_t status; this->read_bytes(LTR559_ALS_PS_STATUS, &status, 1); bool als_int = (status >> LTR559_ALS_PS_STATUS_ALS_INTERRUPT_BIT) & 0b1; bool ps_int = (status >> LTR559_ALS_PS_STATUS_PS_INTERRUPT_BIT) & 0b1; bool als_data = (status >> LTR559_ALS_PS_STATUS_ALS_DATA_BIT) & 0b1; bool ps_data = (status >> LTR559_ALS_PS_STATUS_PS_DATA_BIT) & 0b1; if(ps_int || ps_data) { has_updated = true; uint16_t ps0; read_bytes(LTR559_PS_DATA, (uint8_t *)&ps0, 2); ps0 &= LTR559_PS_DATA_MASK; data.proximity = ps0; } if(als_int || als_data) { has_updated = true; uint16_t als[2]; read_bytes(LTR559_ALS_DATA_CH1, (uint8_t *)&als, 4); data.als0 = als[1]; data.als1 = als[0]; data.gain = this->lookup_light_gain.value((status >> LTR559_ALS_PS_STATUS_ALS_GAIN_SHIFT) & LTR559_ALS_PS_STATUS_ALS_GAIN_MASK); data.ratio = 101.0f; if((uint32_t)data.als0 + data.als1 > 0) { data.ratio = (float)data.als1 * 100.0f / ((float)data.als1 + data.als0); } uint8_t ch_idx = 3; if(this->data.ratio < 45) ch_idx = 0; else if(data.ratio < 64) ch_idx = 1; else if (data.ratio < 85) ch_idx = 2; float lux = ((int32_t)data.als0 * ch0_c[ch_idx]) - ((int32_t)data.als1 * ch1_c[ch_idx]); lux /= (float)this->data.integration_time / 100.0f; lux /= (float)this->data.gain; data.lux = (uint16_t)(lux / 10000.0f); } return has_updated; } void LTR559::interrupts(bool light, bool proximity) { uint8_t buf = 0; buf |= 0b1 << LTR559_INTERRUPT_POLARITY_BIT; buf |= (uint8_t)light << LTR559_INTERRUPT_ALS_BIT; buf |= (uint8_t)proximity << LTR559_INTERRUPT_PS_BIT; write_bytes(LTR559_INTERRUPT, &buf, 1); } void LTR559::proximity_led(uint8_t current, uint8_t duty_cycle, uint8_t pulse_freq, uint8_t num_pulses) { current = lookup_led_current.index(current); duty_cycle = lookup_led_duty_cycle.index(duty_cycle); duty_cycle <<= LTR559_PS_LED_DUTY_CYCLE_SHIFT; pulse_freq = lookup_led_pulse_freq.index(pulse_freq); pulse_freq <<= LTR559_PS_LED_PULSE_FREQ_SHIFT; uint8_t buf = current | duty_cycle | pulse_freq; write_bytes(LTR559_PS_LED, &buf, 1); buf = num_pulses & LTR559_PS_N_PULSES_MASK; write_bytes(LTR559_PS_N_PULSES, &buf, 1); } void LTR559::light_control(bool active, uint8_t gain) { uint8_t buf = 0; gain = lookup_light_gain.index(gain); buf |= gain << LTR559_ALS_CONTROL_GAIN_SHIFT; if(active) buf |= (0b1 << LTR559_ALS_CONTROL_MODE_BIT); else buf &= ~(0b1 << LTR559_ALS_CONTROL_MODE_BIT); write_bytes(LTR559_ALS_CONTROL, &buf, 1); } void LTR559::proximity_control(bool active, bool saturation_indicator) { uint8_t buf = 0; read_bytes(LTR559_PS_CONTROL, &buf, 1); if(active) buf |= LTR559_PS_CONTROL_ACTIVE_MASK; else buf &= ~LTR559_PS_CONTROL_ACTIVE_MASK; if(saturation_indicator) buf |= 0b1 << LTR559_PS_CONTROL_SATURATION_INDICATOR_ENABLE_BIT; else buf &= ~(0b1 << LTR559_PS_CONTROL_SATURATION_INDICATOR_ENABLE_BIT); write_bytes(LTR559_PS_CONTROL, &buf, 1); } void LTR559::light_threshold(uint16_t lower, uint16_t upper) { lower = __builtin_bswap16(lower); upper = __builtin_bswap16(upper); write_bytes(LTR559_ALS_THRESHOLD_LOWER, (uint8_t *)&lower, 2); write_bytes(LTR559_ALS_THRESHOLD_UPPER, (uint8_t *)&upper, 2); } void LTR559::proximity_threshold(uint16_t lower, uint16_t upper) { lower = uint16_to_bit12(lower); upper = uint16_to_bit12(upper); write_bytes(LTR559_PS_THRESHOLD_LOWER, (uint8_t *)&lower, 2); write_bytes(LTR559_PS_THRESHOLD_UPPER, (uint8_t *)&upper, 2); } void LTR559::light_measurement_rate(uint16_t integration_time, uint16_t rate) { data.integration_time = integration_time; integration_time = lookup_light_integration_time.index(integration_time); rate = lookup_light_repeat_rate.index(rate); uint8_t buf = 0; buf |= rate; buf |= integration_time << LTR559_ALS_MEAS_RATE_INTEGRATION_TIME_SHIFT; write_bytes(LTR559_ALS_MEAS_RATE, &buf, 1); } void LTR559::proximity_measurement_rate(uint16_t rate) { uint8_t buf = lookup_proximity_meas_rate.index(rate); write_bytes(LTR559_PS_MEAS_RATE, &buf, 1); } void LTR559::proximity_offset(uint16_t offset) { offset &= LTR559_PS_OFFSET_MASK; write_bytes(LTR559_PS_OFFSET, (uint8_t *)&offset, 1); } uint16_t LTR559::bit12_to_uint16(uint16_t value) { return ((value & 0xFF00) >> 8) | ((value & 0x000F) << 8); } uint16_t LTR559::uint16_to_bit12(uint16_t value) { return ((value & 0xFF) << 8) | ((value & 0xF00) >> 8); } // i2c functions int LTR559::write_bytes(uint8_t reg, uint8_t *buf, int len) { uint8_t buffer[len + 1]; buffer[0] = reg; for(int x = 0; x < len; x++) { buffer[x + 1] = buf[x]; } return i2c_write_blocking(i2c, address, buffer, len + 1, false); }; int LTR559::read_bytes(uint8_t reg, uint8_t *buf, int len) { i2c_write_blocking(i2c, address, &reg, 1, true); i2c_read_blocking(i2c, address, buf, len, false); return len; }; uint8_t LTR559::get_bits(uint8_t reg, uint8_t shift, uint8_t mask) { uint8_t value; read_bytes(reg, &value, 1); return value & (mask << shift); } void LTR559::set_bits(uint8_t reg, uint8_t shift, uint8_t mask) { uint8_t value; read_bytes(reg, &value, 1); value |= mask << shift; write_bytes(reg, &value, 1); } void LTR559::clear_bits(uint8_t reg, uint8_t shift, uint8_t mask) { uint8_t value; read_bytes(reg, &value, 1); value &= ~(mask << shift); write_bytes(reg, &value, 1); } }
8,607
4,126
#include<iostream> using namespace std; int main() { int ncase; cin>>ncase; while(ncase--) { int q1,r1,q2,r2; cin>>q1>>r1>>q2>>r2; int divisor[2000] = {},smaller,larger; if(q1 - r1 > q2 - r2) { larger = q1 - r1; smaller = q2 - r2; } else { larger = q2 - r2; smaller = q1 - r1; } int i; for(i = 1; i <= smaller; i++) { if(smaller % i == 0 && larger % i == 0) divisor[i]++; else continue; } for(i=1;i<=smaller;i++) { if(divisor[i]!=0) cout<<i<<" "; } } return 0; }
749
278
#include "widget.h" Widget::Widget(QWidget *parent): QWidget(parent) { QVBoxLayout *l = new QVBoxLayout(this); le = new QLineEdit(this); label = new QLabel("Placeholder",this); labelTime = new QLabel(this); le->setValidator(new QIntValidator(0,100000,this)); l->addWidget(le); l->addWidget(labelTime); l->addWidget(label); w = new WindowHandler("osu.exe"); connect(le,SIGNAL(returnPressed()),this,SLOT(setPid())); QTimer *t = new QTimer(this); t->setInterval(50); connect(t,SIGNAL(timeout()),this,SLOT(refreshScreen())); t->start(); } Widget::~Widget() { } void Widget::setPid() { w->setPid(le->text().toLong()); } void Widget::refreshScreen() { QTime t; t.start(); QPixmap p = w->getProcessScreen(); labelTime->setText(QString::number(t.elapsed()) + QString("ms")); label->setPixmap(p.scaled(600,600,Qt::KeepAspectRatio)); }
916
353