blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
13d2f674c7ab634ab579a347e914f2f12be1f784
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/PhysicsAnalysis/D3PDMaker/CaloD3PDMaker/src/SGTileModuleBitsGetterTool.h
09b82dca7748586d5ca831848f48c3d3e7a0fdf2
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
1,476
h
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ /* * File: SGTileModuleBitsGetterTool.h * Author: stephen * * Created on March 15, 2012, 2:52 PM */ #ifndef SGTILEMODULEBITSGETTERTOOL_H #define SGTILEMODULEBITSGETTERTOOL_H #include "D3PDMakerUtils/SGCollectionGetterTool.h" #include "TileEvent/TileRawChannelContainer.h" #include "SGTileRawChannelGetterTool.h" //requires the template specialization namespace D3PD{ class SGTileModuleBitsGetterTool: public SGCollectionGetterTool<TileRawChannelContainer> { public: typedef D3PD::SGCollectionGetterTool<TileRawChannelContainer> Base; /** * @brief Standard Gaudi tool constructor. * @param type The name of the tool type. * @param name The tool name. * @param parent The tool's Gaudi parent. */ SGTileModuleBitsGetterTool(const std::string& type, const std::string& name, const IInterface* parent); virtual ~SGTileModuleBitsGetterTool(); StatusCode initialize(); size_t sizeHint(bool allowMissing=false); StatusCode reset(bool allowMissing=false); const void* nextUntyped(); const std::type_info& typeinfo() const; const std::type_info& elementTypeinfo() const; private: TileRawChannelContainer::const_iterator m_evtItr,m_evtEnd; }; } #endif /* SGTILEMODULEBITSGETTERTOOL_H */
9d5f9ebe2812cc89b4613750650985474d8e7611
643e3415a981b504a61985d1f370ca10c13fbf72
/Tests/RuntimeInterruptTest.cpp
88be5dcac482ef8158cd7b9c7030ce1c7ed2bed6
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
diskoverltd/omniscidb
40bcb77da49e34a5a3dda66c2c05e6cfdd7b2054
fed61748af465a55eb7965fceb0a0c7a8dec80f8
refs/heads/master
2021-01-14T19:39:56.700850
2020-05-15T20:31:22
2020-05-15T20:31:22
242,733,293
0
0
Apache-2.0
2020-02-24T12:41:13
2020-02-24T12:41:12
null
UTF-8
C++
false
false
15,292
cpp
/* * Copyright 2020, OmniSci, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "TestHelpers.h" #include <gtest/gtest.h> #include <boost/program_options.hpp> #include <exception> #include <future> #include <stdexcept> #include "Catalog/Catalog.h" #include "QueryEngine/CompilationOptions.h" #include "QueryEngine/Execute.h" #include "QueryEngine/ResultSet.h" #include "QueryRunner/QueryRunner.h" #include "Shared/Logger.h" #include "Shared/StringTransform.h" using QR = QueryRunner::QueryRunner; unsigned INTERRUPT_CHECK_FREQ = 10; #ifndef BASE_PATH #define BASE_PATH "./tmp" #endif bool g_cpu_only{false}; // nested loop over 1M * 1M std::string test_query_large{"SELECT count(1) FROM t_large t1, t_large t2;"}; // nested loop over 100k * 100k std::string test_query_medium{"SELECT count(1) FROM t_medium t1, t_medium t2;"}; // nested loop over 1k * 1k std::string test_query_small{"SELECT count(1) FROM t_small t1, t_small t2;"}; bool skip_tests(const ExecutorDeviceType device_type) { #ifdef HAVE_CUDA return device_type == ExecutorDeviceType::GPU && !(QR::get()->gpusPresent()); #else return device_type == ExecutorDeviceType::GPU; #endif } namespace { std::shared_ptr<ResultSet> run_query(const std::string& query_str, std::shared_ptr<Executor> executor, const ExecutorDeviceType device_type, const std::string& session_id = "") { if (session_id.length() != 32) { LOG(ERROR) << "Incorrect or missing session info."; } return QR::get()->runSQLWithAllowingInterrupt( query_str, executor, session_id, device_type, INTERRUPT_CHECK_FREQ); } inline void run_ddl_statement(const std::string& create_table_stmt) { QR::get()->runDDLStatement(create_table_stmt); } int create_and_populate_table() { try { run_ddl_statement("DROP TABLE IF EXISTS t_large;"); run_ddl_statement("DROP TABLE IF EXISTS t_medium;"); run_ddl_statement("DROP TABLE IF EXISTS t_small;"); run_ddl_statement("CREATE TABLE t_large (x int not null);"); run_ddl_statement("CREATE TABLE t_medium (x int not null);"); run_ddl_statement("CREATE TABLE t_small (x int not null);"); // write a temporary datafile used in the test // because "INSERT INTO ..." stmt for this takes too much time // and add pre-generated dataset increases meaningless LOC of this test code const auto file_path_small = boost::filesystem::path("../../Tests/Import/datafiles/interrupt_table_small.txt"); if (boost::filesystem::exists(file_path_small)) { boost::filesystem::remove(file_path_small); } std::ofstream small_out(file_path_small.string()); for (int i = 0; i < 1000; i++) { if (small_out.is_open()) { small_out << "1\n"; } } small_out.close(); const auto file_path_medium = boost::filesystem::path( "../../Tests/Import/datafiles/interrupt_table_medium.txt"); if (boost::filesystem::exists(file_path_medium)) { boost::filesystem::remove(file_path_medium); } std::ofstream medium_out(file_path_medium.string()); for (int i = 0; i < 100000; i++) { if (medium_out.is_open()) { medium_out << "1\n"; } } medium_out.close(); const auto file_path_large = boost::filesystem::path("../../Tests/Import/datafiles/interrupt_table_large.txt"); if (boost::filesystem::exists(file_path_large)) { boost::filesystem::remove(file_path_large); } std::ofstream large_out(file_path_large.string()); for (int i = 0; i < 1000000; i++) { if (large_out.is_open()) { large_out << "1\n"; } } large_out.close(); std::string import_small_table_str{ "COPY t_small FROM '../../Tests/Import/datafiles/interrupt_table_small.txt' WITH " "(header='false')"}; std::string import_medium_table_str{ "COPY t_medium FROM '../../Tests/Import/datafiles/interrupt_table_medium.txt' " "WITH (header='false')"}; std::string import_large_table_str{ "COPY t_large FROM '../../Tests/Import/datafiles/interrupt_table_large.txt' WITH " "(header='false')"}; run_ddl_statement(import_small_table_str); run_ddl_statement(import_medium_table_str); run_ddl_statement(import_large_table_str); } catch (...) { LOG(ERROR) << "Failed to (re-)create table"; return -1; } return 0; } int drop_table() { try { run_ddl_statement("DROP TABLE IF EXISTS t_large;"); run_ddl_statement("DROP TABLE IF EXISTS t_medium;"); run_ddl_statement("DROP TABLE IF EXISTS t_small;"); boost::filesystem::remove("../../Tests/Import/datafiles/interrupt_table_small.txt"); boost::filesystem::remove("../../Tests/Import/datafiles/interrupt_table_medium.txt"); boost::filesystem::remove("../../Tests/Import/datafiles/interrupt_table_large.txt"); } catch (...) { LOG(ERROR) << "Failed to drop table"; return -1; } return 0; } template <class T> T v(const TargetValue& r) { auto scalar_r = boost::get<ScalarTargetValue>(&r); CHECK(scalar_r); auto p = boost::get<T>(scalar_r); CHECK(p); return *p; } } // namespace #define SKIP_NO_GPU() \ if (skip_tests(dt)) { \ CHECK(dt == ExecutorDeviceType::GPU); \ LOG(WARNING) << "GPU not available, skipping GPU tests"; \ continue; \ } TEST(Interrupt, Kill_RunningQuery) { for (auto dt : {ExecutorDeviceType::CPU, ExecutorDeviceType::GPU}) { auto executor = QR::get()->getExecutor(); bool startQueryExec = false; executor->enableRuntimeQueryInterrupt(INTERRUPT_CHECK_FREQ); std::shared_ptr<ResultSet> res1 = nullptr; std::exception_ptr exception_ptr = nullptr; try { SKIP_NO_GPU(); std::string query_session = generate_random_string(32); // we first run the query as async function call auto query_thread1 = std::async(std::launch::async, [&] { std::shared_ptr<ResultSet> res = nullptr; try { res = run_query(test_query_large, executor, dt, query_session); } catch (...) { exception_ptr = std::current_exception(); } return res; }); // wait until our server starts to process the first query std::string curRunningSession = ""; while (!startQueryExec) { mapd_shared_lock<mapd_shared_mutex> session_read_lock(executor->getSessionLock()); std::this_thread::sleep_for(std::chrono::milliseconds(10)); curRunningSession = executor->getCurrentQuerySession(session_read_lock); if (curRunningSession == query_session) { startQueryExec = true; } session_read_lock.unlock(); } // then, after query execution is started, we try to interrupt the running query // by providing the interrupt signal with the running session info executor->interrupt(query_session, query_session); res1 = query_thread1.get(); if (exception_ptr != nullptr) { std::rethrow_exception(exception_ptr); } else { // when we reach here, it means the query is finished without interrupted // due to some reasons, i.e., very fast query execution // so, instead, we check whether query result is correct CHECK_EQ(1, (int64_t)res1.get()->rowCount()); auto crt_row = res1.get()->getNextRow(false, false); auto ret_val = v<int64_t>(crt_row[0]); CHECK_EQ((int64_t)1000000 * 1000000, ret_val); } } catch (const std::runtime_error& e) { std::string expected_err_msg = "Query execution has been interrupted"; std::string received_err_msg = e.what(); bool check = (expected_err_msg == received_err_msg) ? true : false; CHECK(check); } } } TEST(Interrupt, Kill_PendingQuery) { for (auto dt : {ExecutorDeviceType::CPU, ExecutorDeviceType::GPU}) { std::future<std::shared_ptr<ResultSet>> query_thread1; std::future<std::shared_ptr<ResultSet>> query_thread2; auto executor = QR::get()->getExecutor(); executor->enableRuntimeQueryInterrupt(INTERRUPT_CHECK_FREQ); bool startQueryExec = false; std::exception_ptr exception_ptr1 = nullptr; std::exception_ptr exception_ptr2 = nullptr; std::shared_ptr<ResultSet> res1 = nullptr; std::shared_ptr<ResultSet> res2 = nullptr; try { SKIP_NO_GPU(); std::string session1 = generate_random_string(32); std::string session2 = generate_random_string(32); // we first run the query as async function call query_thread1 = std::async(std::launch::async, [&] { std::shared_ptr<ResultSet> res = nullptr; try { res = run_query(test_query_medium, executor, dt, session1); } catch (...) { exception_ptr1 = std::current_exception(); } return res; }); // make sure our server recognizes a session for running query correctly std::string curRunningSession = ""; while (!startQueryExec) { mapd_shared_lock<mapd_shared_mutex> session_read_lock(executor->getSessionLock()); curRunningSession = executor->getCurrentQuerySession(session_read_lock); if (curRunningSession == session1) { startQueryExec = true; } session_read_lock.unlock(); } query_thread2 = std::async(std::launch::async, [&] { std::shared_ptr<ResultSet> res = nullptr; try { // run pending query as async call res = run_query(test_query_medium, executor, dt, session2); } catch (...) { exception_ptr2 = std::current_exception(); } return res; }); // then, we try to interrupt the pending query // by providing the interrupt signal with the pending query's session info if (startQueryExec) { executor->interrupt(session2, session2); } res2 = query_thread2.get(); res1 = query_thread1.get(); if (exception_ptr2 != nullptr) { // pending query throws an runtime exception due to query interrupt std::rethrow_exception(exception_ptr2); } if (exception_ptr1 != nullptr) { // running query should never return the runtime exception CHECK(false); } } catch (const std::runtime_error& e) { // catch exception due to runtime query interrupt // and compare thrown message to confirm that // this exception comes from our interrupt request std::string expected_err_msg = "Query execution has been interrupted (pending query)"; std::string received_err_msg = e.what(); bool check = (expected_err_msg == received_err_msg) ? true : false; CHECK(check); } // check running query's result CHECK_EQ(1, (int64_t)res1.get()->rowCount()); auto crt_row = res1.get()->getNextRow(false, false); auto ret_val = v<int64_t>(crt_row[0]); CHECK_EQ((int64_t)100000 * 100000, ret_val); } } TEST(Interrupt, Make_PendingQuery_Run) { for (auto dt : {ExecutorDeviceType::CPU, ExecutorDeviceType::GPU}) { std::future<std::shared_ptr<ResultSet>> query_thread1; std::future<std::shared_ptr<ResultSet>> query_thread2; auto executor = QR::get()->getExecutor(); executor->enableRuntimeQueryInterrupt(INTERRUPT_CHECK_FREQ); bool startQueryExec = false; std::exception_ptr exception_ptr1 = nullptr; std::exception_ptr exception_ptr2 = nullptr; std::shared_ptr<ResultSet> res1 = nullptr; std::shared_ptr<ResultSet> res2 = nullptr; try { SKIP_NO_GPU(); std::string session1 = generate_random_string(32); std::string session2 = generate_random_string(32); // we first run the query as async function call query_thread1 = std::async(std::launch::async, [&] { std::shared_ptr<ResultSet> res = nullptr; try { res = run_query(test_query_large, executor, dt, session1); } catch (...) { exception_ptr1 = std::current_exception(); } return res; }); // make sure our server recognizes a session for running query correctly std::string curRunningSession = ""; while (!startQueryExec) { mapd_shared_lock<mapd_shared_mutex> session_read_lock(executor->getSessionLock()); curRunningSession = executor->getCurrentQuerySession(session_read_lock); if (curRunningSession == session1) { startQueryExec = true; } session_read_lock.unlock(); } query_thread2 = std::async(std::launch::async, [&] { std::shared_ptr<ResultSet> res = nullptr; try { // run pending query as async call res = run_query(test_query_small, executor, dt, session2); } catch (...) { exception_ptr2 = std::current_exception(); } return res; }); // then, we try to interrupt the running query // by providing the interrupt signal with the running query's session info // so we can expect that running query session releases all H/W resources and locks, // and so pending query takes them for its query execution (becomes running query) if (startQueryExec) { executor->interrupt(session1, session1); } res2 = query_thread2.get(); res1 = query_thread1.get(); if (exception_ptr1 != nullptr) { std::rethrow_exception(exception_ptr1); } if (exception_ptr2 != nullptr) { // pending query should never return the runtime exception // because it is executed after running query is interrupted CHECK(false); } } catch (const std::runtime_error& e) { // catch exception due to runtime query interrupt // and compare thrown message to confirm that // this exception comes from our interrupt request std::string expected_err_msg = "Query execution has been interrupted"; std::string received_err_msg = e.what(); bool check = (expected_err_msg == received_err_msg) ? true : false; CHECK(check); } // check running query's result CHECK_EQ(1, (int64_t)res2.get()->rowCount()); auto crt_row = res2.get()->getNextRow(false, false); auto ret_val = v<int64_t>(crt_row[0]); CHECK_EQ((int64_t)1000 * 1000, ret_val); } } int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); TestHelpers::init_logger_stderr_only(argc, argv); QR::init(BASE_PATH); int err{0}; try { err = create_and_populate_table(); err = RUN_ALL_TESTS(); err = drop_table(); } catch (const std::exception& e) { LOG(ERROR) << e.what(); } QR::reset(); return err; }
a2245ec0babbdd5ebc3fd2cbd934cf31bb7b5963
592f58c86b27e03701a9cc6b2cae5b67ce56f94a
/allocator_tests/nedmalloc.h
991e42e28fcbe83a4895e50b85fd180fbf32c3c1
[]
no_license
neoxack/quick-server
e1c2bef97885fac1430d67b3931b043ef0c38aad
6604ba413254cac8878f22cb6a4b13d65fe4801f
refs/heads/master
2020-04-14T21:03:40.736453
2013-05-08T00:03:28
2013-05-08T00:03:28
7,924,288
1
0
null
null
null
null
UTF-8
C++
false
false
61,295
h
/* nedalloc, an alternative malloc implementation for multiple threads without lock contention based on dlmalloc v2.8.4. (C) 2005-2010 Niall Douglas Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef NEDMALLOC_H #define NEDMALLOC_H /*! \file nedmalloc.h \brief Defines the functionality provided by nedalloc. */ /*! \mainpage <a href="../../Readme.html">Please see the Readme.html</a> */ /*! \def NEDMALLOC_DEBUG \brief Defines the assertion checking performed by nedalloc NEDMALLOC_DEBUG can be defined to cause DEBUG to be set differently for nedmalloc than for the rest of the build. Remember to set NDEBUG to disable all assertion checking too. */ /*! \def ENABLE_LARGE_PAGES \brief Defines whether nedalloc uses large pages (>=2Mb) ENABLE_LARGE_PAGES enables support for requesting memory from the system in large (typically >=2Mb) pages if the host OS supports this. These occupy just a single TLB entry and can significantly improve performance in large working set applications. */ /*! \def ENABLE_FAST_HEAP_DETECTION \brief Defines whether nedalloc takes platform specific shortcuts when detecting foreign blocks. ENABLE_FAST_HEAP_DETECTION enables special logic to detect blocks allocated by the system heap. This avoids 1.5%-2% overhead when checking for non-nedmalloc blocks, but it assumes that the NT and glibc heaps function in a very specific fashion which may not hold true across OS upgrades. */ /*! \def HAVE_CPP0XRVALUEREFS \ingroup C++ \brief Enables rvalue references Define to enable the usage of rvalue references which enables move semantics and other things. Automatically defined if __cplusplus indicates a C++0x compiler, otherwise you'll need to set it yourself. */ /*! \def HAVE_CPP0XVARIADICTEMPLATES \ingroup C++ \brief Enables variadic templates Define to enable the usage of variadic templates which enables the use of arbitrary numbers of policies and other useful things. Automatically defined if __cplusplus indicates a C++0x compiler, otherwise you'll need to set it yourself. */ /*! \def HAVE_CPP0XSTATICASSERT \ingroup C++ \brief Enables static assertions Define to enable the usage of static assertions. Automatically defined if __cplusplus indicates a C++0x compiler, otherwise you'll need to set it yourself. */ /*! \def HAVE_CPP0XTYPETRAITS \ingroup C++ \brief Enables type traits Define to enable the usage of &lt;type_traits&gt;. Automatically defined if __cplusplus indicates a C++0x compiler, otherwise you'll need to set it yourself. */ #if __cplusplus > 199711L || defined(HAVE_CPP0X) /* Do we have C++0x? */ #undef HAVE_CPP0XRVALUEREFS #define HAVE_CPP0XRVALUEREFS 1 #undef HAVE_CPP0XVARIADICTEMPLATES #define HAVE_CPP0XVARIADICTEMPLATES 1 #undef HAVE_CPP0XSTATICASSERT #define HAVE_CPP0XSTATICASSERT 1 #undef HAVE_CPP0XTYPETRAITS #define HAVE_CPP0XTYPETRAITS 1 #endif #include <stddef.h> /* for size_t */ /*! \def NEDMALLOCEXTSPEC \brief Defines how nedalloc's API is to be made visible. NEDMALLOCEXTSPEC can be defined to be __declspec(dllexport) or __attribute__ ((visibility("default"))) or whatever you like. It defaults to extern unless NEDMALLOC_DLL_EXPORTS is set as it would be when building nedmalloc.dll. */ #ifndef NEDMALLOCEXTSPEC #ifdef NEDMALLOC_DLL_EXPORTS #ifdef WIN32 #define NEDMALLOCEXTSPEC extern __declspec(dllexport) #elif defined(__GNUC__) #define NEDMALLOCEXTSPEC extern __attribute__ ((visibility("default"))) #endif #ifndef ENABLE_TOLERANT_NEDMALLOC #define ENABLE_TOLERANT_NEDMALLOC 1 #endif #else #define NEDMALLOCEXTSPEC extern #endif #endif /*! \def NEDMALLOCDEPRECATED \brief Defined to mark an API as deprecated */ #ifndef NEDMALLOCDEPRECATED #if defined(_MSC_VER) && !defined(__GCCXML__) #define NEDMALLOCDEPRECATED __declspec(deprecated) #elif defined(__GNUC__) && !defined(__GCCXML__) #define NEDMALLOCDEPRECATED __attribute ((deprecated)) #else //! Marks a function as being deprecated #define NEDMALLOCDEPRECATED #endif #endif /*! \def RESTRICT \brief Defined to the restrict keyword or equivalent if available */ #ifndef RESTRICT #if __STDC_VERSION__ >= 199901L /* C99 or better */ #define RESTRICT restrict #else #if defined(_MSC_VER) && _MSC_VER>=1400 #define RESTRICT __restrict #endif #ifdef __GNUC__ #define RESTRICT __restrict #endif #endif #ifndef RESTRICT #define RESTRICT #endif #endif #if defined(_MSC_VER) && _MSC_VER>=1400 #define NEDMALLOCPTRATTR __declspec(restrict) #define NEDMALLOCNOALIASATTR __declspec(noalias) #endif #ifdef __GNUC__ #define NEDMALLOCPTRATTR __attribute__ ((malloc)) #endif /*! \def NEDMALLOCPTRATTR \brief Defined to the specifier for a pointer which points to a memory block. Like NEDMALLOCNOALIASATTR, but sadly not identical. */ #ifndef NEDMALLOCPTRATTR #define NEDMALLOCPTRATTR #endif /*! \def NEDMALLOCNOALIASATTR \brief Defined to the specifier for a pointer which does not alias any other variable. */ #ifndef NEDMALLOCNOALIASATTR #define NEDMALLOCNOALIASATTR #endif /*! \def USE_MAGIC_HEADERS \brief Defines whether nedalloc should use magic headers in foreign heap block detection USE_MAGIC_HEADERS causes nedalloc to allocate an extra three sizeof(size_t) to each block. nedpfree() and nedprealloc() can then automagically know when to free a system allocated block. Enabling this typically adds 20-50% to application memory usage, and is mandatory if USE_ALLOCATOR is not 1. */ #ifndef USE_MAGIC_HEADERS #define USE_MAGIC_HEADERS 0 #endif /*! \def USE_ALLOCATOR \brief Defines the underlying allocator to use USE_ALLOCATOR can be one of these settings (it defaults to 1): 0: System allocator (nedmalloc now simply acts as a threadcache) which is very useful for testing with valgrind and Glowcode. WARNING: Intended for DEBUG USE ONLY - not all functions work correctly. 1: dlmalloc */ #ifndef USE_ALLOCATOR #define USE_ALLOCATOR 1 /* dlmalloc */ #endif #if !USE_ALLOCATOR && !USE_MAGIC_HEADERS #error If you are using the system allocator then you MUST use magic headers #endif /*! \def REPLACE_SYSTEM_ALLOCATOR \brief Defines whether to replace the system allocator (malloc(), free() et al) with nedalloc's implementation. REPLACE_SYSTEM_ALLOCATOR on POSIX causes nedalloc's functions to be called malloc, free etc. instead of nedmalloc, nedfree etc. You may or may not want this. On Windows it causes nedmalloc to patch all loaded DLLs and binaries to replace usage of the system allocator. Always turns on ENABLE_TOLERANT_NEDMALLOC. */ #ifdef REPLACE_SYSTEM_ALLOCATOR #if USE_ALLOCATOR==0 #error Cannot combine using the system allocator with replacing the system allocator #endif #ifndef ENABLE_TOLERANT_NEDMALLOC #define ENABLE_TOLERANT_NEDMALLOC 1 #endif #ifndef WIN32 /* We have a dedicated patcher for Windows */ #define nedmalloc malloc #define nedmalloc2 malloc2 #define nedcalloc calloc #define nedrealloc realloc #define nedrealloc2 realloc2 #define nedfree free #define nedfree2 free2 #define nedmemalign memalign #define nedmallinfo mallinfo #define nedmallopt mallopt #define nedmalloc_trim malloc_trim #define nedmalloc_stats malloc_stats #define nedmalloc_footprint malloc_footprint #define nedindependent_calloc independent_calloc #define nedindependent_comalloc independent_comalloc #ifdef __GNUC__ #define nedmemsize malloc_usable_size #endif #endif #endif /*! \def ENABLE_TOLERANT_NEDMALLOC \brief Defines whether nedalloc should check for blocks from the system allocator. ENABLE_TOLERANT_NEDMALLOC is automatically turned on if REPLACE_SYSTEM_ALLOCATOR is set or the Windows DLL is being built. This causes nedmalloc to detect when a system allocator block is passed to it and to handle it appropriately. Note that without USE_MAGIC_HEADERS there is a very tiny chance that nedmalloc will segfault on non-Windows builds (it uses Win32 SEH to trap segfaults on Windows and there is no comparable system on POSIX). */ #if defined(__cplusplus) extern "C" { #endif /*! \brief Returns information about a memory pool */ struct nedmallinfo { size_t arena; /*!< non-mmapped space allocated from system */ size_t ordblks; /*!< number of free chunks */ size_t smblks; /*!< always 0 */ size_t hblks; /*!< always 0 */ size_t hblkhd; /*!< space in mmapped regions */ size_t usmblks; /*!< maximum total allocated space */ size_t fsmblks; /*!< always 0 */ size_t uordblks; /*!< total allocated space */ size_t fordblks; /*!< total free space */ size_t keepcost; /*!< releasable (via malloc_trim) space */ }; #if defined(__cplusplus) } #endif /*! \def NO_NED_NAMESPACE \brief Defines the use of the nedalloc namespace for the C functions. NO_NED_NAMESPACE prevents the functions from being defined in the nedalloc namespace when in C++ (uses the global C namespace instead). */ /*! \def THROWSPEC \brief Defined to throw() or noexcept(true) (as in, throws nothing) under C++, otherwise nothing. */ #if defined(__cplusplus) #if !defined(NO_NED_NAMESPACE) namespace nedalloc { #else extern "C" { #endif #if __cplusplus > 199711L #define THROWSPEC noexcept(true) #else #define THROWSPEC throw() #endif #else #define THROWSPEC #endif /* These are the global functions */ /*! \defgroup v2malloc The v2 malloc API \warning This API is being completely retired in v1.10 beta 2 and replaced with the API being developed for inclusion into the C1X programming language standard For the v1.10 release which was generously sponsored by <a href="http://www.ara.com/" target="_blank">Applied Research Associates (USA)</a>, a new general purpose allocator API was designed which is intended to remedy many of the long standing problems and inefficiencies introduced by the ISO C allocator API. Internally nedalloc's implementations of nedmalloc(), nedcalloc(), nedmemalign() and nedrealloc() call into this API: <ul> <li><code>void* malloc2(size_t bytes, size_t alignment, unsigned flags)</code></li> <li><code>void* realloc2(void* mem, size_t bytes, size_t alignment, unsigned flags)</code></li> <li><code>void free2(void* mem, unsigned flags)</code></li> </ul> If nedmalloc.h is being included by C++ code, the alignment and flags parameters default to zero which makes the new API identical to the old API (roll on the introduction of default parameters to C!). The ability for realloc2() to take an alignment is <em>particularly</em> useful for extending aligned vector arrays such as SSE/AVX vector arrays. Hitherto SSE/AVX vector code had to jump through all sorts of unpleasant hoops to maintain alignment :(. Note that using any of these flags other than M2_ZERO_MEMORY or any alignment other than zero inhibits the threadcache. Currently MREMAP support is limited to Linux and Windows. Patches implementing support for other platforms are welcome. On Linux the non portable mremap() kernel function is currently used, so in fact the M2_RESERVE_* options are currently ignored. On Windows, there are two different MREMAP implementations which are chosen according to whether a 32 bit or a 64 bit build is being performed. The 32 bit implementation is based on Win32 file mappings where it reserves the address space within the Windows VM system, so you can safely specify silly reservation quantities like 2Gb per block and not exhaust local process address space. Note however that on x86 this costs 2Kb (1Kb if PAE is off) of kernel memory per Mb reserved, and as kernel memory has a hard limit of 447Mb on x86 you will find the total address space reservable in the system is limited. On x64, or if you define WIN32_DIRECT_USE_FILE_MAPPINGS=0 on x86, a much faster implementation of using VirtualAlloc(MEM_RESERVE) to directly reserve the address space is used. When using M2_RESERVE_* with realloc2(), the setting only takes effect when the mmapped chunk has exceeded its reservation space and a new reservation space needs to be created. */ #ifndef M2_FLAGS_DEFINED #define M2_FLAGS_DEFINED /*! \def M2_ZERO_MEMORY \ingroup v2malloc \brief Sets the contents of the allocated block (or any increase in the allocated block) to zero. Note that this zeroes only the increase from what dlmalloc thinks the chunk's size is, so if you realloc2() a block which wasn't allocated using malloc2() using this flag then you may have garbage just before the newly extended space. \li <strong>Rationale:</strong> Memory returned by the system is guaranteed to be zero on most platforms, and hence dlmalloc knows when it can skip zeroing memory. This improves performance. */ #define M2_ZERO_MEMORY (1<<0) /*! \def M2_PREVENT_MOVE \ingroup v2malloc \brief Cause realloc2() to attempt to extend a block in place, but to never move it. \li <strong>Rationale:</strong> C++ makes almost no use of realloc(), even for contiguous arrays such as std::vector<> because most C++ objects cannot be relocated in memory without a copy or rvalue construction (though some clever STL implementations specialise for Plain Old Data (POD) types, and use realloc() then and only then). This flag allows C++ containers to speculatively try to extend in place, thus improving performance <em>especially</em> for large allocations which will use mmap(). */ #define M2_PREVENT_MOVE (1<<1) /*! \def M2_ALWAYS_MMAP \ingroup v2malloc \brief Always allocate as though mmap_threshold were being exceeded. In the case of realloc2(), note that setting this bit will not necessarily mmap a chunk which isn't already mmapped, but it will force a mmapped chunk if new memory needs allocating. \li <strong>Rationale:</strong> If you know that an array you are allocating is going to be repeatedly extended up into the hundred of kilobytes range, then you can avoid the constant memory copying into larger blocks by specifying this flag at the beginning along with one of the M2_RESERVE_* flags below. This can <strong>greatly</strong> improve performance for large arrays. */ #define M2_ALWAYS_MMAP (1<<2) #define M2_RESERVED1 (1<<3) #define M2_RESERVED2 (1<<4) #define M2_RESERVED3 (1<<5) #define M2_RESERVED4 (1<<6) #define M2_RESERVED5 (1<<7) #define M2_RESERVE_ISMULTIPLIER (1<<15) /* 7 bits is given to the address reservation specifier. This lets you set a multiplier (bit 15 set) or a 1<< shift value. */ #define M2_RESERVE_MASK 0x00007f00 /*! \def M2_RESERVE_MULT(n) \ingroup v2malloc \brief Reserve n times as much address space such that mmapped realloc2(size <= n * original size) avoids memory copying and hence is much faster. */ #define M2_RESERVE_MULT(n) (M2_RESERVE_ISMULTIPLIER|(((n)<<8)&M2_RESERVE_MASK)) /*! \def M2_RESERVE_SHIFT(n) \ingroup v2malloc \brief Reserve (1<<n) bytes of address space such that mmapped realloc2(size <= (1<<n)) avoids memory copying and hence is much faster. */ #define M2_RESERVE_SHIFT(n) (((n)<<8)&M2_RESERVE_MASK) #define M2_FLAGS_MASK 0x0000ffff #define M2_CUSTOM_FLAGS_BEGIN (1<<16) #define M2_CUSTOM_FLAGS_MASK 0xffff0000 /*! \def NM_SKIP_TOLERANCE_CHECKS \ingroup v2malloc \brief Causes nedmalloc to not inspect the block being passed to see if it belongs to the system allocator. Can improve speed by up to 10%. */ #define NM_SKIP_TOLERANCE_CHECKS (1<<31) #endif /* M2_FLAGS_DEFINED */ #if defined(__cplusplus) /*! \brief Gets the usable size of an allocated block. Note this will always be bigger than what was asked for due to rounding etc. Optionally returns 1 in isforeign if the block came from the system allocator - note that there is a small (>0.01%) but real chance of segfault on non-Windows systems when passing non-nedmalloc blocks if you don't use USE_MAGIC_HEADERS. */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR size_t nedblksize(int *RESTRICT isforeign, void *RESTRICT mem, unsigned flags=0) THROWSPEC; #else NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR size_t nedblksize(int *RESTRICT isforeign, void *RESTRICT mem, unsigned flags) THROWSPEC; #endif /*! \brief Identical to nedblksize() except without the isforeign */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR size_t nedmemsize(void *RESTRICT mem) THROWSPEC; /*! \brief Equivalent to nedpsetvalue((nedpool *) 0, v) */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR void nedsetvalue(void *v) THROWSPEC; /*! \brief Equivalent to nedpmalloc2((nedpool *) 0, size, 0, 0) */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedmalloc(size_t size) THROWSPEC; /*! \brief Equivalent to nedpmalloc2((nedpool *) 0, no*size, 0, M2_ZERO_MEMORY) */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedcalloc(size_t no, size_t size) THROWSPEC; /*! \brief Equivalent to nedprealloc2((nedpool *) 0, size, mem, size, 0, M2_RESERVE_MULT(8)) */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedrealloc(void *mem, size_t size) THROWSPEC; /*! \brief Equivalent to nedpfree2((nedpool *) 0, mem, 0) */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR void nedfree(void *mem) THROWSPEC; /*! \brief Equivalent to nedpmalloc2((nedpool *) 0, size, alignment, 0) */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedmemalign(size_t alignment, size_t bytes) THROWSPEC; #if defined(__cplusplus) /*! \ingroup v2malloc \brief Equivalent to nedpmalloc2((nedpool *) 0, size, alignment, flags) */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedmalloc2(size_t size, size_t alignment=0, unsigned flags=0) THROWSPEC; /*! \ingroup v2malloc \brief Equivalent to nedprealloc2((nedpool *) 0, mem, size, alignment, flags) */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedrealloc2(void *mem, size_t size, size_t alignment=0, unsigned flags=0) THROWSPEC; /*! \ingroup v2malloc \brief Equivalent to nedpfree2((nedpool *) 0, mem, flags) */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR void nedfree2(void *mem, unsigned flags=0) THROWSPEC; #else NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedmalloc2(size_t size, size_t alignment, unsigned flags) THROWSPEC; NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedrealloc2(void *mem, size_t size, size_t alignment, unsigned flags) THROWSPEC; NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR void nedfree2(void *mem, unsigned flags) THROWSPEC; #endif /*! \brief Equivalent to nedpmallinfo((nedpool *) 0) */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR struct nedmallinfo nedmallinfo(void) THROWSPEC; /*! \brief Equivalent to nedpmallopt((nedpool *) 0, parno, value) */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR int nedmallopt(int parno, int value) THROWSPEC; /*! \brief Returns the internal allocation granularity and the magic header XOR used for internal consistency checks. */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR void* nedmalloc_internals(size_t *granularity, size_t *magic) THROWSPEC; /*! \brief Equivalent to nedpmalloc_trim((nedpool *) 0, pad) */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR int nedmalloc_trim(size_t pad) THROWSPEC; /*! \brief Equivalent to nedpmalloc_stats((nedpool *) 0) */ NEDMALLOCEXTSPEC void nedmalloc_stats(void) THROWSPEC; /*! \brief Equivalent to nedpmalloc_footprint((nedpool *) 0) */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR size_t nedmalloc_footprint(void) THROWSPEC; /*! \brief Equivalent to nedpindependent_calloc((nedpool *) 0, elemsno, elemsize, chunks) */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void **nedindependent_calloc(size_t elemsno, size_t elemsize, void **chunks) THROWSPEC; /*! \brief Equivalent to nedpindependent_comalloc((nedpool *) 0, elems, sizes, chunks) */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void **nedindependent_comalloc(size_t elems, size_t *sizes, void **chunks) THROWSPEC; /*! \brief Destroys the system memory pool used by the functions above. Useful for when you have nedmalloc in a DLL you're about to unload. If you call ANY nedmalloc functions after calling this you will get a fatal exception! */ NEDMALLOCEXTSPEC void neddestroysyspool() THROWSPEC; /*! \brief A nedpool type */ struct nedpool_t; /*! \brief A nedpool type */ typedef struct nedpool_t nedpool; /*! \brief Creates a memory pool for use with the nedp* functions below. Capacity is how much to allocate immediately (if you know you'll be allocating a lot of memory very soon) which you can leave at zero. Threads specifies how many threads will *normally* be accessing the pool concurrently. Setting this to zero means it extends on demand, but be careful of this as it can rapidly consume system resources where bursts of concurrent threads use a pool at once. */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR nedpool *nedcreatepool(size_t capacity, int threads) THROWSPEC; /*! \brief Destroys a memory pool previously created by nedcreatepool(). */ NEDMALLOCEXTSPEC void neddestroypool(nedpool *p) THROWSPEC; /*! \brief Returns a zero terminated snapshot of threadpools existing at the time of call. Call nedfree() on the returned list when you are done. Returns zero if there is only the system pool in existence. */ NEDMALLOCEXTSPEC nedpool **nedpoollist() THROWSPEC; /*! \brief Sets a value to be associated with a pool. You can retrieve this value by passing any memory block allocated from that pool. */ NEDMALLOCEXTSPEC void nedpsetvalue(nedpool *p, void *v) THROWSPEC; /*! \brief Gets a previously set value using nedpsetvalue() or zero if memory is unknown. Optionally can also retrieve pool. You can detect an unknown block by the return being zero and *p being unmodifed. */ NEDMALLOCEXTSPEC void *nedgetvalue(nedpool **p, void *mem) THROWSPEC; /*! \brief Trims the thread cache for the calling thread, returning any existing cache data to the central pool. Remember to ALWAYS call with zero if you used the system pool. Setting disable to non-zero replicates neddisablethreadcache(). */ NEDMALLOCEXTSPEC void nedtrimthreadcache(nedpool *p, int disable) THROWSPEC; /*! \brief Disables the thread cache for the calling thread, returning any existing cache data to the central pool. Remember to ALWAYS call with zero if you used the system pool. */ NEDMALLOCEXTSPEC void neddisablethreadcache(nedpool *p) THROWSPEC; /*! \brief Releases all memory in all threadcaches in the pool, and writes all accumulated memory operations to the log if enabled. You can pass zero for filepath to use the compiled default, or else a char[MAX_PATH] containing the path you wish to use for the log file. The log file is always appended to if it already exists. After writing the logs, the logging ability is disabled for that pool. \warning Do NOT call this if the pool is in use - this call is NOT threadsafe. */ NEDMALLOCEXTSPEC size_t nedflushlogs(nedpool *p, char *filepath) THROWSPEC; /*! \brief Equivalent to nedpmalloc2(p, size, 0, 0) */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedpmalloc(nedpool *p, size_t size) THROWSPEC; /*! \brief Equivalent to nedpmalloc2(p, no*size, 0, M2_ZERO_MEMORY) */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedpcalloc(nedpool *p, size_t no, size_t size) THROWSPEC; /*! \brief Equivalent to nedprealloc2(p, mem, size, 0, M2_RESERVE_MULT(8)) */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedprealloc(nedpool *p, void *mem, size_t size) THROWSPEC; /*! \brief Equivalent to nedpfree2(p, mem, 0) */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR void nedpfree(nedpool *p, void *mem) THROWSPEC; /*! \brief Equivalent to nedpmalloc2(p, bytes, alignment, 0) */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedpmemalign(nedpool *p, size_t alignment, size_t bytes) THROWSPEC; #if defined(__cplusplus) /*! \ingroup v2malloc \brief Allocates a block of memory sized \em size from pool \em p, aligned to \em alignment and according to the flags \em flags. */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedpmalloc2(nedpool *p, size_t size, size_t alignment=0, unsigned flags=0) THROWSPEC; /*! \ingroup v2malloc \brief Resizes the block of memory at \em mem in pool \em p to size \em size, aligned to \em alignment and according to the flags \em flags. */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedprealloc2(nedpool *p, void *mem, size_t size, size_t alignment=0, unsigned flags=0) THROWSPEC; /*! \brief Frees the block \em mem from the pool \em p according to flags \em flags. */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR void nedpfree2(nedpool *p, void *mem, unsigned flags=0) THROWSPEC; #else NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedpmalloc2(nedpool *p, size_t size, size_t alignment, unsigned flags) THROWSPEC; NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedprealloc2(nedpool *p, void *mem, size_t size, size_t alignment, unsigned flags) THROWSPEC; NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR void nedpfree2(nedpool *p, void *mem, unsigned flags) THROWSPEC; #endif /*! \brief Returns information about the memory pool */ NEDMALLOCEXTSPEC struct nedmallinfo nedpmallinfo(nedpool *p) THROWSPEC; /*! \brief Changes the operational parameters of the memory pool */ NEDMALLOCEXTSPEC int nedpmallopt(nedpool *p, int parno, int value) THROWSPEC; /*! \brief Tries to release as much free memory back to the system as possible, leaving \em pad remaining per threadpool. */ NEDMALLOCEXTSPEC int nedpmalloc_trim(nedpool *p, size_t pad) THROWSPEC; /*! \brief Prints some operational statistics to stdout. */ NEDMALLOCEXTSPEC void nedpmalloc_stats(nedpool *p) THROWSPEC; /*! \brief Returns how much memory is currently in use by the memory pool */ NEDMALLOCEXTSPEC size_t nedpmalloc_footprint(nedpool *p) THROWSPEC; /*! \brief Returns a series of guaranteed consecutive cleared memory allocations. independent_calloc is similar to calloc, but instead of returning a single cleared space, it returns an array of pointers to n_elements independent elements that can hold contents of size elem_size, each of which starts out cleared, and can be independently freed, realloc'ed etc. The elements are guaranteed to be adjacently allocated (this is not guaranteed to occur with multiple callocs or mallocs), which may also improve cache locality in some applications. The "chunks" argument is optional (i.e., may be null, which is probably the most typical usage). If it is null, the returned array is itself dynamically allocated and should also be freed when it is no longer needed. Otherwise, the chunks array must be of at least n_elements in length. It is filled in with the pointers to the chunks. In either case, independent_calloc returns this pointer array, or null if the allocation failed. If n_elements is zero and "chunks" is null, it returns a chunk representing an array with zero elements (which should be freed if not wanted). Each element must be individually freed when it is no longer needed. If you'd like to instead be able to free all at once, you should instead use regular calloc and assign pointers into this space to represent elements. (In this case though, you cannot independently free elements.) independent_calloc simplifies and speeds up implementations of many kinds of pools. It may also be useful when constructing large data structures that initially have a fixed number of fixed-sized nodes, but the number is not known at compile time, and some of the nodes may later need to be freed. For example: struct Node { int item; struct Node* next; }; struct Node* build_list() { struct Node** pool; int n = read_number_of_nodes_needed(); if (n <= 0) return 0; pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0); if (pool == 0) die(); // organize into a linked list... struct Node* first = pool[0]; for (i = 0; i < n-1; ++i) pool[i]->next = pool[i+1]; free(pool); // Can now free the array (or not, if it is needed later) return first; } */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void **nedpindependent_calloc(nedpool *p, size_t elemsno, size_t elemsize, void **chunks) THROWSPEC; /*! \brief Returns a series of guaranteed consecutive allocations. independent_comalloc allocates, all at once, a set of n_elements chunks with sizes indicated in the "sizes" array. It returns an array of pointers to these elements, each of which can be independently freed, realloc'ed etc. The elements are guaranteed to be adjacently allocated (this is not guaranteed to occur with multiple callocs or mallocs), which may also improve cache locality in some applications. The "chunks" argument is optional (i.e., may be null). If it is null the returned array is itself dynamically allocated and should also be freed when it is no longer needed. Otherwise, the chunks array must be of at least n_elements in length. It is filled in with the pointers to the chunks. In either case, independent_comalloc returns this pointer array, or null if the allocation failed. If n_elements is zero and chunks is null, it returns a chunk representing an array with zero elements (which should be freed if not wanted). Each element must be individually freed when it is no longer needed. If you'd like to instead be able to free all at once, you should instead use a single regular malloc, and assign pointers at particular offsets in the aggregate space. (In this case though, you cannot independently free elements.) independent_comallac differs from independent_calloc in that each element may have a different size, and also that it does not automatically clear elements. independent_comalloc can be used to speed up allocation in cases where several structs or objects must always be allocated at the same time. For example: struct Head { ... } struct Foot { ... } void send_message(char* msg) { int msglen = strlen(msg); size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) }; void* chunks[3]; if (independent_comalloc(3, sizes, chunks) == 0) die(); struct Head* head = (struct Head*)(chunks[0]); char* body = (char*)(chunks[1]); struct Foot* foot = (struct Foot*)(chunks[2]); // ... } In general though, independent_comalloc is worth using only for larger values of n_elements. For small values, you probably won't detect enough difference from series of malloc calls to bother. Overuse of independent_comalloc can increase overall memory usage, since it cannot reuse existing noncontiguous small chunks that might be available for some of the elements. */ NEDMALLOCEXTSPEC NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void **nedpindependent_comalloc(nedpool *p, size_t elems, size_t *sizes, void **chunks) THROWSPEC; #if defined(__cplusplus) } /* namespace or extern "C" */ #include <new> #include <memory> #ifdef HAVE_CPP0XTYPETRAITS #include <type_traits> #endif // Touch into existence for future platforms namespace std { namespace tr1 { } } /*! \defgroup C++ C++ language support Thanks to the generous support of Applied Research Associates (USA), nedalloc has extensive C++ language support which uses C++ metaprogramming techniques to provide a policy driven STL container reimplementor. The metaprogramming silently overrides or replaces the STL implementation on your system (MSVC and GCC are the two currently supported) to \b substantially improve the performance of STL containers by making use of nedalloc's additional features. Sounds difficult to use? Not really. Simply do this: \code using namespace nedalloc; typedef nedallocatorise<std::vector, unsigned int, nedpolicy::typeIsPOD<true>::policy, nedpolicy::mmap<>::policy, nedpolicy::reserveN<26>::policy // 1<<26 = 64Mb. 10,000,000 * sizeof(unsigned int) = 38Mb. >::value myvectortype; myvectortype a; for(int n=0; n<10000000; n++) a.push_back(n); \endcode The metaprogramming requires a new C++ compiler (> year 2008), and it will readily make use of a C++0x compiler where it will use rvalue referencing, variadic templates, type traits and more. Visual Studio 2008 or later is sufficent, as is GCC v4.4 or later. nedalloc's metaprogramming is designed to be extensible, so the rest of this page is intended for those wishing to customise the metaprogramming. If you simply wish to know how to use the nedalloc::nedallocator STL allocator or the nedalloc::nedallocatorise STL reimplementor, please refer to test.cpp which gives several examples of usage. <h2>Extending the metaprogramming:</h2> A nedallocator policy looks as follows: \code namespace nedpolicy { template<size_t size, size_t alignment> struct sizedalign { template<class Base> class policy : public Base { template<class implementation> friend class nedallocatorI::baseimplementation; protected: size_t policy_alignment(size_t bytes) const { return (bytes < size) ? alignment : 0; } }; }; } \endcode The policy above implements a size based alignment, so if the block being allocated is less than \em size then it causes \em alignment to be used, otherwise it does not align. The sizedalign struct is merely a template parameter encapsulator used to capture additional parameters, so the real policy is in fact the class policy held within in. If you did not need to specify any additional parameters e.g. if you were defining policy_nedpool(), then you would directly define a policy returning your nedpool and pass it directly to nedallocator<>. The primary policy functions which are intended to be overridden are listed in nedalloc::nedallocatorI::baseimplementation in nedmalloc.h and are prefixed by "policy_". However, there is absolutely no reason why the meatier functions such as nedalloc::nedallocatorI::baseimplementation::allocate() cannot be overriden, and indeed some of the policies defined in nedmalloc.h do just that. Policy composition is handled by a dedicated recursive variadic template called nedalloc::nedallocatorI::policycompositor. If you have \em really specialised needs, you can partially specialise this class to make it do all sorts of interesting things - hence its separation into its own class. */ /*! \brief The nedalloc namespace */ namespace nedalloc { /*! \def NEDSTATIC_ASSERT(expr, msg) \brief Generates a static assertion if (expr)==0 at compile time. Make SURE your message contains no spaces or anything else which would make it an invalid variable name. */ #ifndef HAVE_CPP0XSTATICASSERT template<bool> struct StaticAssert; template<> struct StaticAssert<true> { StaticAssert() { } }; #define NEDSTATIC_ASSERT(expr, msg) \ nedalloc::StaticAssert<(expr)!=0> ERROR_##msg #else #define NEDSTATIC_ASSERT(expr, msg) static_assert((expr)!=0, #msg ) #endif /*! \brief The policy namespace in which all nedallocator policies live. */ namespace nedpolicy { /*! \class empty \ingroup C++ \brief An empty policy which does nothing. */ template<class Base> class empty : public Base { }; } /*! \brief The implementation namespace where the internals live. */ namespace nedallocatorI { using namespace std; using namespace tr1; /* Roll on variadic templates is all I can say! */ #ifdef HAVE_CPP0XVARIADICTEMPLATES template<class Impl, template<class> class... policies> class policycompositor; template<class Impl, template<class> class A, template<class> class... policies> class policycompositor<Impl, A, policies...> { typedef policycompositor<Impl, policies...> temp; public: typedef A<typename temp::value> value; }; #else template<class Impl, template<class> class A=nedpolicy::empty, template<class> class B=nedpolicy::empty, template<class> class C=nedpolicy::empty, template<class> class D=nedpolicy::empty, template<class> class E=nedpolicy::empty, template<class> class F=nedpolicy::empty, template<class> class G=nedpolicy::empty, template<class> class H=nedpolicy::empty, template<class> class I=nedpolicy::empty, template<class> class J=nedpolicy::empty, template<class> class K=nedpolicy::empty, template<class> class L=nedpolicy::empty, template<class> class M=nedpolicy::empty, template<class> class N=nedpolicy::empty, template<class> class O=nedpolicy::empty > class policycompositor { typedef policycompositor<Impl, B, C, D, E, F, G, H, I, J, K, L, M, N, O> temp; public: typedef A<typename temp::value> value; }; #endif template<class Impl> class policycompositor<Impl> { public: typedef Impl value; }; } template<typename T, #ifdef HAVE_CPP0XVARIADICTEMPLATES template<class> class... policies #else template<class> class policy1=nedpolicy::empty, template<class> class policy2=nedpolicy::empty, template<class> class policy3=nedpolicy::empty, template<class> class policy4=nedpolicy::empty, template<class> class policy5=nedpolicy::empty, template<class> class policy6=nedpolicy::empty, template<class> class policy7=nedpolicy::empty, template<class> class policy8=nedpolicy::empty, template<class> class policy9=nedpolicy::empty, template<class> class policy10=nedpolicy::empty, template<class> class policy11=nedpolicy::empty, template<class> class policy12=nedpolicy::empty, template<class> class policy13=nedpolicy::empty, template<class> class policy14=nedpolicy::empty, template<class> class policy15=nedpolicy::empty #endif > class nedallocator; namespace nedallocatorI { /*! \brief The base implementation class */ template<class implementation> class baseimplementation { //NEDSTATIC_ASSERT(false, Bad_policies_specified); }; /*! \brief The base implementation class */ template<typename T, #ifdef HAVE_CPP0XVARIADICTEMPLATES template<class> class... policies #else template<class> class policy1, template<class> class policy2, template<class> class policy3, template<class> class policy4, template<class> class policy5, template<class> class policy6, template<class> class policy7, template<class> class policy8, template<class> class policy9, template<class> class policy10, template<class> class policy11, template<class> class policy12, template<class> class policy13, template<class> class policy14, template<class> class policy15 #endif > class baseimplementation<nedallocator<T, #ifdef HAVE_CPP0XVARIADICTEMPLATES policies... #else policy1, policy2, policy3, policy4, policy5, policy6, policy7, policy8, policy9, policy10, policy11, policy12, policy13, policy14, policy15 #endif > > { protected: //! \brief The most derived nedallocator implementation type typedef nedallocator<T, #ifdef HAVE_CPP0XVARIADICTEMPLATES policies... #else policy1, policy2, policy3, policy4, policy5, policy6, policy7, policy8, policy9, policy10, policy11, policy12, policy13, policy14, policy15 #endif > implementationType; //! \brief Returns a this for the most derived nedallocator implementation type implementationType *_this() { return static_cast<implementationType *>(this); } //! \brief Returns a this for the most derived nedallocator implementation type const implementationType *_this() const { return static_cast<const implementationType *>(this); } //! \brief Specifies the nedpool to use. Defaults to zero (the system pool). nedpool *policy_nedpool(size_t bytes) const { return 0; } //! \brief Specifies the granularity to use. Defaults to \em bytes (no granularity). size_t policy_granularity(size_t bytes) const { return bytes; } //! \brief Specifies the alignment to use. Defaults to zero (no alignment). size_t policy_alignment(size_t bytes) const { return 0; } //! \brief Specifies the flags to use. Defaults to zero (no flags). unsigned policy_flags(size_t bytes) const { return 0; } //! \brief Specifies what to do when the allocation fails. Defaults to throwing std::bad_alloc. void policy_throwbadalloc(size_t bytes) const { throw std::bad_alloc(); } //! \brief Specifies if the type is POD. Is std::is_pod<T>::value on C++0x compilers, otherwise false. static const bool policy_typeIsPOD= #ifdef HAVE_CPP0XTYPETRAITS is_pod<T>::value; #else false; #endif public: typedef T *pointer; typedef const T *const_pointer; typedef T &reference; typedef const T &const_reference; typedef T value_type; typedef size_t size_type; typedef ptrdiff_t difference_type; T *address(T &r) const { return &r; } const T *address(const T &s) const { return &s; } size_t max_size() const { return (static_cast<size_t>(0) - static_cast<size_t>(1)) / sizeof(T); } bool operator!=(const baseimplementation &other) const { return !(*this == other); } bool operator==(const baseimplementation &other) const { return true; } void construct(T *const p, const T &t) const { void *const _p = static_cast<void *>(p); new (_p) T(t); } void destroy(T *const p) const { p->~T(); } baseimplementation() { } baseimplementation(const baseimplementation &) { } #ifdef HAVE_CPP0XRVALUEREFS baseimplementation(baseimplementation &&) { } #endif template<typename U> struct rebind { typedef nedallocator<U, #ifdef HAVE_CPP0XVARIADICTEMPLATES policies... #else policy1, policy2, policy3, policy4, policy5, policy6, policy7, policy8, policy9, policy10, policy11, policy12, policy13, policy14, policy15 #endif > other; }; template<typename U> baseimplementation(const nedallocator<U, #ifdef HAVE_CPP0XVARIADICTEMPLATES policies... #else policy1, policy2, policy3, policy4, policy5, policy6, policy7, policy8, policy9, policy10, policy11, policy12, policy13, policy14, policy15 #endif > &) { } T *allocate(const size_t n) const { // Leave these spelled out to aid debugging const size_t t_size = sizeof(T); size_t size = _this()->policy_granularity(n*t_size); nedpool *pool = _this()->policy_nedpool(size); size_t alignment = _this()->policy_alignment(size); unsigned flags = _this()->policy_flags(size); void *ptr = nedpmalloc2(pool, size, alignment, flags); if(!ptr) _this()->policy_throwbadalloc(size); return static_cast<T *>(ptr); } void deallocate(T *p, const size_t n) const { nedpfree(0/*not needed*/, p); } template<typename U> T *allocate(const size_t n, const U * /* hint */) const { return allocate(n); } private: baseimplementation &operator=(const baseimplementation &); }; } namespace nedpolicy { /*! \class granulate \ingroup C++ \brief A policy setting the granularity of the allocated memory. Memory is sized according to (size+granularity-1) & ~(granularity-1). In other words, granularity \b must be a power of two. */ template<size_t granularity> struct granulate { template<class Base> class policy : public Base { template<class implementation> friend class nedallocatorI::baseimplementation; protected: size_t policy_granularity(size_t bytes) const { return (bytes+granularity-1) & ~(granularity-1); } }; }; /*! \class align \ingroup C++ \brief A policy setting the alignment of the allocated memory. */ template<size_t alignment> struct align { template<class Base> class policy : public Base { template<class implementation> friend class nedallocatorI::baseimplementation; protected: size_t policy_alignment(size_t bytes) const { return alignment; } }; }; /*! \class zero \ingroup C++ \brief A policy causing the zeroing of the allocated memory. */ template<bool dozero=true> struct zero { template<class Base> class policy : public Base { template<class implementation> friend class nedallocatorI::baseimplementation; protected: unsigned policy_flags(size_t bytes) const { return dozero ? Base::policy_flags(bytes)|M2_ZERO_MEMORY : Base::policy_flags(bytes); } }; }; /*! \class preventmove \ingroup C++ \brief A policy preventing the moving of the allocated memory. */ template<bool doprevent=true> struct preventmove { template<class Base> class policy : public Base { template<class implementation> friend class nedallocatorI::baseimplementation; protected: unsigned policy_flags(size_t bytes) const { return doprevent ? Base::policy_flags(bytes)|M2_PREVENT_MOVE : Base::policy_flags(bytes); } }; }; /*! \class mmap \ingroup C++ \brief A policy causing the mmapping of the allocated memory. */ template<bool dommap=true> struct mmap { template<class Base> class policy : public Base { template<class implementation> friend class nedallocatorI::baseimplementation; protected: unsigned policy_flags(size_t bytes) const { return dommap ? Base::policy_flags(bytes)|M2_ALWAYS_MMAP : Base::policy_flags(bytes); } }; }; /*! \class reserveX \ingroup C++ \brief A policy causing the address reservation of X times the allocated memory. */ template<size_t X> struct reserveX { template<class Base> class policy : public Base { template<class implementation> friend class nedallocatorI::baseimplementation; protected: unsigned policy_flags(size_t bytes) const { return Base::policy_flags(bytes)|M2_RESERVE_MULT(X); } }; }; /*! \class reserveN \ingroup C++ \brief A policy causing the address reservation of (1<<N) bytes of memory. */ template<size_t N> struct reserveN { template<class Base> class policy : public Base { template<class implementation> friend class nedallocatorI::baseimplementation; protected: unsigned policy_flags(size_t bytes) const { return Base::policy_flags(bytes)|M2_RESERVE_SHIFT(N); } }; }; /*! \class badalloc \ingroup C++ \brief A policy specifying what to throw when an allocation failure occurs. A type specialisation exists for badalloc<void> which is equivalent to new(nothrow) i.e. return zero and don't throw anything. */ template<typename T> struct badalloc { template<class Base> class policy : public Base { template<class implementation> friend class nedallocatorI::baseimplementation; protected: void policy_throwbadalloc(size_t bytes) const { throw T(); } }; }; template<> struct badalloc<void> { template<class Base> class policy : public Base { template<class implementation> friend class nedallocatorI::baseimplementation; protected: void policy_throwbadalloc(size_t bytes) const { } }; }; /*! \class typeIsPOD \ingroup C++ \brief A policy forcing the treatment of the type as Plain Old Data (POD) On C++0x compilers, the &lt;type_traits&gt; is_pod<type>::value is used by default. However, for earlier compilers and for types where is_pod<>::value returns false even though the type actually is POD (for example, if you declare a constructor you lose PODness even if the data contents are still POD), you can force PODness one way or another. When treated as POD, memcpy() is used instead of copy construction and realloc() is permitted to move the memory contents when resizing. */ template<bool ispod> struct typeIsPOD { template<class Base> class policy : public Base { template<class implementation> friend class nedallocatorI::baseimplementation; protected: static const bool policy_typeIsPOD=ispod; }; }; } /*! \class nedallocator \ingroup C++ \brief A policy driven STL allocator which uses nedmalloc One of the lesser known features of STL container classes is their ability to take an allocator implementation class, so where you had std::vector<Foo> you can now have std::vector<Foo, nedalloc::nedallocator< std::vector<Foo> > such that std::vector<> will now use nedalloc as the policy specifies. You <b>almost certainly</b> don't want to use this directly except in the naive case. See nedalloc::nedallocatorise to see what I mean. */ template<typename T, #ifdef HAVE_CPP0XVARIADICTEMPLATES template<class> class... policies #else template<class> class policy1, template<class> class policy2, template<class> class policy3, template<class> class policy4, template<class> class policy5, template<class> class policy6, template<class> class policy7, template<class> class policy8, template<class> class policy9, template<class> class policy10, template<class> class policy11, template<class> class policy12, template<class> class policy13, template<class> class policy14, template<class> class policy15 #endif > class nedallocator : public nedallocatorI::policycompositor< #ifdef HAVE_CPP0XVARIADICTEMPLATES nedallocatorI::baseimplementation<nedallocator<T, policies...> >, policies... #else nedallocatorI::baseimplementation<nedallocator<T, policy1, policy2, policy3, policy4, policy5, policy6, policy7, policy8, policy9, policy10, policy11, policy12, policy13, policy14, policy15 > >, policy1, policy2, policy3, policy4, policy5, policy6, policy7, policy8, policy9, policy10, policy11, policy12, policy13, policy14, policy15 #endif >::value { typedef typename nedallocatorI::policycompositor< #ifdef HAVE_CPP0XVARIADICTEMPLATES nedallocatorI::baseimplementation<nedallocator<T, policies...> >, policies... #else nedallocatorI::baseimplementation<nedallocator<T, policy1, policy2, policy3, policy4, policy5, policy6, policy7, policy8, policy9, policy10, policy11, policy12, policy13, policy14, policy15 > >, policy1, policy2, policy3, policy4, policy5, policy6, policy7, policy8, policy9, policy10, policy11, policy12, policy13, policy14, policy15 #endif >::value Base; public: nedallocator() { } nedallocator(const nedallocator &o) : Base(o) { } #ifdef HAVE_CPP0XRVALUEREFS nedallocator(nedallocator &&o) : Base(std::move(o)) { } #endif /* This templated constructor and rebind() are used by MSVC's secure iterator checker. I think it's best to not copy state even though it may break policies which store data. */ template<typename U> nedallocator(const nedallocator<U, #ifdef HAVE_CPP0XVARIADICTEMPLATES policies... #else policy1, policy2, policy3, policy4, policy5, policy6, policy7, policy8, policy9, policy10, policy11, policy12, policy13, policy14, policy15 #endif > &o) { } #ifdef HAVE_CPP0XRVALUEREFS template<typename U> nedallocator(nedallocator<U, #ifdef HAVE_CPP0XVARIADICTEMPLATES policies... #else policy1, policy2, policy3, policy4, policy5, policy6, policy7, policy8, policy9, policy10, policy11, policy12, policy13, policy14, policy15 #endif > &&o) { } #endif template<typename U> struct rebind { typedef nedallocator<U, #ifdef HAVE_CPP0XVARIADICTEMPLATES policies... #else policy1, policy2, policy3, policy4, policy5, policy6, policy7, policy8, policy9, policy10, policy11, policy12, policy13, policy14, policy15 #endif > other; }; }; namespace nedallocatorI { // Holds a static allocator instance shared by anything allocating from allocator template<class allocator> struct StaticAllocator { static allocator &get() { static allocator a; return a; } }; // RAII holder for a Newed object template<typename T, class allocator> struct PtrHolder { T *mem; PtrHolder(T *_mem) : mem(_mem) { } ~PtrHolder() { if(mem) { allocator &a=nedallocatorI::StaticAllocator<allocator>::get(); a.deallocate(mem, sizeof(T)); mem=0; } } T *release() { T *ret=mem; mem=0; return ret; } T *operator *() { return mem; } const T *operator *() const { return mem; } }; } /*! \brief Allocates the memory for an instance of object \em T and constructs it. If an exception is thrown during construction, the memory is freed before rethrowing the exception. Usage is very simple: \code SSEVectorType *foo1=New<SSEVectorType>(4, 5, 6, 7); \endcode */ #ifdef HAVE_CPP0XVARIADICTEMPLATES template<typename T, class allocator=nedallocator<T>, typename... Parameters> inline T *New(const Parameters&... parameters) #else template<typename T, class allocator> inline T *New() #endif { allocator &a=nedallocatorI::StaticAllocator<allocator>::get(); nedallocatorI::PtrHolder<T, allocator> ret(a.allocate(sizeof(T))); if(*ret) { #ifdef HAVE_CPP0XVARIADICTEMPLATES new((void *) *ret) T(parameters...); #else new((void *) *ret) T; #endif } return ret.release(); } #ifndef HAVE_CPP0XVARIADICTEMPLATES // Extremely annoying not to have default template arguments for functions pre-C++0x template<typename T> inline T *New() { return New<T, nedallocator<T> >(); } // Also, it's painful to replicate function overloads :( #define NEDMALLOC_NEWIMPL \ template<typename T, class allocator, NEDMALLOC_NEWIMPLTYPES> inline T *New(NEDMALLOC_NEWIMPLPARSDEFS) \ { \ allocator &a=nedallocatorI::StaticAllocator<allocator>::get(); \ nedallocatorI::PtrHolder<T, allocator> ret(a.allocate(sizeof(T))); \ if(*ret) \ { \ new((void *) *ret) T(NEDMALLOC_NEWIMPLPARS); \ } \ return ret.release(); \ } \ template<typename T, NEDMALLOC_NEWIMPLTYPES> inline T *New(NEDMALLOC_NEWIMPLPARSDEFS)\ { \ return New<T, nedallocator<T> >(NEDMALLOC_NEWIMPLPARS); \ } #define NEDMALLOC_NEWIMPLTYPES typename P1 #define NEDMALLOC_NEWIMPLPARSDEFS const P1 &p1 #define NEDMALLOC_NEWIMPLPARS p1 NEDMALLOC_NEWIMPL #undef NEDMALLOC_NEWIMPLTYPES #undef NEDMALLOC_NEWIMPLPARSDEFS #undef NEDMALLOC_NEWIMPLPARS #define NEDMALLOC_NEWIMPLTYPES typename P1, typename P2 #define NEDMALLOC_NEWIMPLPARSDEFS const P1 &p1, const P2 &p2 #define NEDMALLOC_NEWIMPLPARS p1, p2 NEDMALLOC_NEWIMPL #undef NEDMALLOC_NEWIMPLTYPES #undef NEDMALLOC_NEWIMPLPARSDEFS #undef NEDMALLOC_NEWIMPLPARS #define NEDMALLOC_NEWIMPLTYPES typename P1, typename P2, typename P3 #define NEDMALLOC_NEWIMPLPARSDEFS const P1 &p1, const P2 &p2, const P3 &p3 #define NEDMALLOC_NEWIMPLPARS p1, p2, p3 NEDMALLOC_NEWIMPL #undef NEDMALLOC_NEWIMPLTYPES #undef NEDMALLOC_NEWIMPLPARSDEFS #undef NEDMALLOC_NEWIMPLPARS #define NEDMALLOC_NEWIMPLTYPES typename P1, typename P2, typename P3, typename P4 #define NEDMALLOC_NEWIMPLPARSDEFS const P1 &p1, const P2 &p2, const P3 &p3, const P4 &p4 #define NEDMALLOC_NEWIMPLPARS p1, p2, p3, p4 NEDMALLOC_NEWIMPL #undef NEDMALLOC_NEWIMPLTYPES #undef NEDMALLOC_NEWIMPLPARSDEFS #undef NEDMALLOC_NEWIMPLPARS #define NEDMALLOC_NEWIMPLTYPES typename P1, typename P2, typename P3, typename P4, typename P5 #define NEDMALLOC_NEWIMPLPARSDEFS const P1 &p1, const P2 &p2, const P3 &p3, const P4 &p4, const P5 &p5 #define NEDMALLOC_NEWIMPLPARS p1, p2, p3, p4, p5 NEDMALLOC_NEWIMPL #undef NEDMALLOC_NEWIMPLTYPES #undef NEDMALLOC_NEWIMPLPARSDEFS #undef NEDMALLOC_NEWIMPLPARS #undef NEDMALLOC_NEWIMPL #endif /*! \brief Destructs an instance of object T, and releases the memory used to store it. */ template<class allocator, typename T> inline void Delete(const T *_obj) { T *obj=const_cast<T *>(_obj); allocator &a=nedallocatorI::StaticAllocator<allocator>::get(); obj->~T(); a.deallocate(obj, sizeof(T)); } template<typename T> inline void Delete(const T *obj) { Delete<nedallocator<T> >(obj); } /*! \class nedallocatorise \ingroup C++ \brief Reimplements a given STL container to make full and efficient usage of nedalloc \param stlcontainer The STL container you wish to reimplement \param T The type to be contained \param policies... Any policies you want applied to the allocator This is a clever bit of C++ metaprogramming if I do say so myself! What it does is to specialise a STL container implementation to make full use of nedalloc's advanced facilities, so for example if you do: \code using namespace nedalloc; typedef nedallocatorise<std::vector, unsigned int, nedpolicy::typeIsPOD<true>::policy, nedpolicy::mmap<>::policy, nedpolicy::reserveN<26>::policy // 1<<26 = 64Mb. 10,000,000 * sizeof(unsigned int) = 38Mb. >::value myvectortype; myvectortype a; for(int n=0; n<10000000; n++) a.push_back(n); \endcode What happens here is that nedallocatorise reimplements the parts of std::vector which extend and shrink the actual memory allocation. Because the typeIsPOD policy is specified, it means that realloc() rather than realloc(M2_PREVENT_MOVE) can be used. Also, because the mmap and the reserveN policies are specified, std::vector immediately reserves 64Mb of address space and forces the immediate use of mmap(). This allows you to push_back() a lot of data very, very quickly indeed. You will also find that pop_back() actually reduces the allocation now (most implementations don't bother ever releasing memory except when reaching empty or when resize() is called). When mmapped, reserve() is automatically held at a minimum of &lt;page size&gt;/sizeof(type) though larger values are respected. test.cpp has a benchmark of the speed differences you may realise, plus an example of usage. */ template<template<typename, class> class stlcontainer, typename T, #ifdef HAVE_CPP0XVARIADICTEMPLATES template<class> class... policies #else template<class> class policy1=nedpolicy::empty, template<class> class policy2=nedpolicy::empty, template<class> class policy3=nedpolicy::empty, template<class> class policy4=nedpolicy::empty, template<class> class policy5=nedpolicy::empty, template<class> class policy6=nedpolicy::empty, template<class> class policy7=nedpolicy::empty, template<class> class policy8=nedpolicy::empty, template<class> class policy9=nedpolicy::empty, template<class> class policy10=nedpolicy::empty, template<class> class policy11=nedpolicy::empty, template<class> class policy12=nedpolicy::empty, template<class> class policy13=nedpolicy::empty, template<class> class policy14=nedpolicy::empty, template<class> class policy15=nedpolicy::empty #endif > class nedallocatorise { public: //! The reimplemented STL container type typedef stlcontainer<T, nedallocator<T, #ifdef HAVE_CPP0XVARIADICTEMPLATES policies... #else policy1, policy2, policy3, policy4, policy5, policy6, policy7, policy8, policy9, policy10, policy11, policy12, policy13, policy14, policy15 #endif > > value; }; } /* namespace */ #endif /* Some miscellaneous dlmalloc option documentation */ #ifdef DOXYGEN_IS_PARSING_ME /* Just some false defines to keep doxygen happy */ #define NEDMALLOC_DEBUG DEBUG #define ENABLE_LARGE_PAGES undef #define ENABLE_FAST_HEAP_DETECTION undef #define REPLACE_SYSTEM_ALLOCATOR undef #define ENABLE_TOLERANT_NEDMALLOC undef #define NO_NED_NAMESPACE undef /*! \def MALLOC_ALIGNMENT \brief Defines what alignment normally returned blocks should use. Is 16 bytes on Mac OS X, otherwise 8 bytes. */ #define MALLOC_ALIGNMENT 8 /*! \def USE_LOCKS \brief Defines the threadsafety of nedalloc USE_LOCKS can be 2 if you want to define your own MLOCK_T, INITIAL_LOCK, ACQUIRE_LOCK, RELEASE_LOCK, TRY_LOCK, IS_LOCKED and NULL_LOCK_INITIALIZER. */ #define USE_LOCKS 1 /*! \def DEFAULT_GRANULARITY \brief Defines the granularity in which to request or free system memory. */ #define DEFAULT_GRANULARITY (2*1024*1024) /*! \def DEFAULT_TRIM_THRESHOLD \brief Defines how much memory must be free before returning it to the system. */ #define DEFAULT_TRIM_THRESHOLD (2*1024*1024) /*! \def DEFAULT_MMAP_THRESHOLD \brief Defines the threshold above which mmap() is used to perform direct allocation. */ #define DEFAULT_MMAP_THRESHOLD (256*1024) /*! \def MAX_RELEASE_CHECK_RATE \brief Defines how many free() ops should occur before checking how much free memory there is. */ #define MAX_RELEASE_CHECK_RATE 4095 /*! \def NEDMALLOC_FORCERESERVE \brief Lets you force address space reservation in the \b standard malloc API Note that by default realloc() sets M2_RESERVE_MULT(8) when thunking to realloc2(), so you probably don't need to override this */ #define NEDMALLOC_FORCERESERVE(p, mem, size) 0 /*! \def NEDMALLOC_TESTLOGENTRY \brief Used to determine whether a given memory operation should be logged. */ #define NEDMALLOC_TESTLOGENTRY(tc, np, type, mspace, size, mem, alignment, flags, returned) ((type)&ENABLE_LOGGING) /*! \def NEDMALLOC_STACKBACKTRACEDEPTH \brief Turns on stack backtracing in the logger. You almost certainly want to constrain what gets logged using NEDMALLOC_TESTLOGENTRY if you turn this on as the sheer volume of data output can make execution very slow. */ #define NEDMALLOC_STACKBACKTRACEDEPTH 0 #endif #endif
697b70dbdd80998e7386e2c28bd510fb3c92e40a
b31be7b41f83100a39deeb33a26045d0e28abdff
/tryouts/peek.cpp
c76ed04668b4bd96ce1ec306e57689ffd4a0ce21
[]
no_license
bintrue/sandbox
31564a1fd322b3f032bbeae20bd45bf35dd40521
69e455d29803ea20c00ac74c15476638ff70296c
refs/heads/master
2020-06-01T16:07:34.043273
2012-07-19T08:12:38
2012-07-19T08:12:38
1,194,060
0
0
null
2012-07-20T21:30:40
2010-12-23T19:45:32
C++
UTF-8
C++
false
false
427
cpp
#include <iostream> int main() { char c; std::cin >> std::ws; c = std::cin.peek(); std::cout << "__" << c << "__" << std::endl; if ( '0' <= c && c <= '9' ) { int number; std::cin >> number; std::cout << "This is a number: " << number << std::endl; } else if ( 'q' == c ) { std::cout << "quitting now..." << std::endl; } else { std::cout << "Invalid input." << std::endl; } }
44026d15e60983628485aebd305313097ff1dfef
1403478a1350c1dac732bef2d3d86f5f33aff636
/c-plus2/コンストラクタとデストラクタ/car.cpp
ba4c8f6c814af113fb4005d69d84f0947216edae
[]
no_license
esakik/c-plus2-grammar
7957e19168577b4de87e254f331e25b78c0bcfb0
968efff080bc641af1c35fe08970c44f626bfa89
refs/heads/master
2021-05-23T08:15:44.076289
2020-04-10T10:05:07
2020-04-10T10:05:07
253,193,303
0
0
null
null
null
null
UTF-8
C++
false
false
834
cpp
#include "car.h" #include <iostream> using namespace std; // コンストラクタ(インスタンスが生成された時に一度だけ呼ばれる) CCar::CCar() : m_fuel(0), m_migration(0) { cout << "CCarオブジェクト生成" << endl; } // デストラクタ(インスタンスが破棄された時に一度だけ呼ばれる) CCar::~CCar() { cout << "CCarオブジェクト破棄" << endl; } void CCar::move() { // 燃料があるなら移動 if (m_fuel > 0) { m_migration++; // 距離移動 m_fuel--; // 燃料消費 } cout << "移動距離:" << m_migration << endl; cout << "燃料" << m_fuel << endl; } // 燃料補給メソッド void CCar::supply(int fuel) { if (fuel >= 0) { m_fuel += fuel; // 燃料補給 } cout << "燃料" << m_fuel << endl; }
4af106c33356141814176ebf5c0dc62e377f551e
f1d6286566190160fca9e0601636b2e65820c6ee
/src/collider.cpp
a7ae13db6461cf23b5ec5ed1d5ff9a19784bc9aa
[]
no_license
Sisyphe/Bomber
b40538a315918b1f207acb32879971a6a9e85fde
e2f1206c7d1b64b2fa9610f222418aa9704ddbb7
refs/heads/master
2016-09-05T19:40:19.801979
2013-02-27T18:48:43
2013-02-27T18:48:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
24
cpp
#include "collider.h"
4ad44966938ee6ad289ee0fd785dfe1d147a755e
56fcab9393f0ec379e2abb00d2d8eda36f64e823
/uintah/kokkos_src_original/Core/Math/MiscMath.cc
5bf8b87a50b6f07e80859480f185496358c2ba04
[ "MIT", "CC-BY-4.0" ]
permissive
damu1000/hypre_ep
4a13a5545ac90b231ca9e0f29f23f041f344afb9
a6701de3d455fa4ee95ac7d79608bffa3eb115ee
refs/heads/master
2023-04-11T11:38:21.157249
2021-08-16T21:50:44
2021-08-16T21:50:44
41,874,948
2
1
null
null
null
null
UTF-8
C++
false
false
4,020
cc
/* * The MIT License * * Copyright (c) 1997-2017 The University of Utah * * 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. */ /* * MiscMath.cc * * Written by: * Michael Callahan * Department of Computer Science * University of Utah * June 2004 * */ #include <iostream> using namespace std; #include <cstdio> #include <Core/Math/MiscMath.h> #include <Core/Math/Expon.h> #include <cmath> #ifdef __digital__ # include <fp_class.h> #endif namespace Uintah { double MakeReal(double value) { if (!std::isfinite(value)) { int is_inf = 0; #ifdef __digital__ // on dec, we have fp_class which can tell us if a number is +/- infinity int fpclass = fp_class(value); if (fpclass == FP_POS_INF) is_inf = 1; if (fpclass == FP_NEG_INF) is_inf = -1; #elif defined(__sgi) fpclass_t c = fpclass(value); if (c == FP_PINF) is_inf = 1; if (c == FP_NINF) is_inf = -1; #else # if defined( _AIX ) || defined( __PGI ) is_inf = isinf(value); # else is_inf = std::isinf(value); # endif #endif if (is_inf == 1) value = (double)(0x7fefffffffffffffULL); if (is_inf == -1) value = (double)(0x0010000000000000ULL); else value = 0.0; // Assumed NaN } return value; } void findFactorsNearRoot(const int value, int &factor1, int &factor2) { int f1,f2; f1 = f2 = (int) Sqrt((double)value); // now we are basically looking for a pair of multiples that are closest to // the square root. while ((f1 * f2) != value) { // look for another multiple for(int i = f1+1; i <= value; i++) { if (value%i == 0) { // we've found a root f1 = i; f2 = value/f1; break; } } } factor1 = f1; factor2 = f2; } //Computes the cubed root of a using Halley's algorithm. The initial guess //is set to the parameter provided, if no parameter is provided then the //result of the last call is used as the initial guess. INT_MIN is used //as a sentinal to signal that no guess was provided. double cubeRoot(double a, double guess) { double xold; static double xnew=1; //start initial guess at last answer double small_num=5*DBL_EPSILON; if(guess!=DBL_MIN) xnew=guess; double atimes2=a*2.0; double x3; double diff=DBL_MAX, last_diff; //do a couple of iterations without checking the convergence criteria xold=xnew; x3=xold*xold*xold; xnew=xold*(x3+atimes2)/(2*x3+a); xold=xnew; x3=xold*xold*xold; xnew=xold*(x3+atimes2)/(2*x3+a); xold=xnew; x3=xold*xold*xold; xnew=xold*(x3+atimes2)/(2*x3+a); diff=fabs(xold-xnew); do { xold=xnew; x3=xold*xold*xold; xnew=xold*(x3+atimes2)/(2*x3+a); last_diff=diff; diff=fabs(xold-xnew); //terminate if the /*absolute or*/ relative difference is less than machine precision or if the convergence has stopped } while(/*diff>small_num &&*/ diff>small_num*xold && last_diff>diff); if(last_diff<diff) return xold; else return xnew; } } // End namespace Uintah
23757bfe65a030a9a23dfacc44dc7335108f2839
8d6e1eaa428044dfeb0a5b4e22e114b94d3c8053
/HumanPlayer.cpp
a3f41a8e4813d64afb57638d9c6941651ea929ea
[ "MIT" ]
permissive
nirklinger/Tetris
582217ae629232b5c7ab2a134cd99afcf0d34c96
a4a51abda31f8dcab0e11ac9273497e8c994503f
refs/heads/main
2023-05-03T18:56:52.132609
2021-05-16T09:37:27
2021-05-16T09:37:27
351,939,906
0
0
MIT
2021-05-16T09:37:28
2021-03-26T23:48:57
C++
UTF-8
C++
false
false
1,042
cpp
#include "HumanPlayer.h" HumanPlayer::HumanPlayer(int offsetX, int offsetY, bool isLeftSide) : Board(offsetX, offsetY), isLeftSide(isLeftSide) {} void HumanPlayer::actOnNextKey(char key) { if (isLeftSide) checkLeftPlayerKeyHit(key); else checkRightPlayerKeyHit(key); } void HumanPlayer::checkLeftPlayerKeyHit(char key) { if (key == 'W' || key == 'w') { rotateCounterClockwise(); } else if (key == 'S' || key == 's') { rotateClockwise(); } else if (key == 'D' || key == 'd') { moveRight(); } else if (key == 'A' || key == 'a') { moveLeft(); } else if (key == 'X' || key == 'x') { shouldDropBlock = true; } } void HumanPlayer::checkRightPlayerKeyHit(char key) { if (key == 'I' || key == 'i') { rotateCounterClockwise(); } else if (key == 'K' || key == 'k') { rotateClockwise(); } else if (key == 'L' || key == 'l') { moveRight(); } else if (key == 'J' || key == 'j') { moveLeft(); } else if (key == 'M' || key == 'm') { shouldDropBlock = true; } }
df5e18c76f571bc46a554784ce31d0465e66092b
1834c0796ee324243f550357c67d8bcd7c94de17
/SDK/TCF_AL_VelticiteMineral_Wall_BP_classes.hpp
b469d445a9a9f31b8a1f9ec5e5313f5051800f21
[]
no_license
DarkCodez/TCF-SDK
ce41cc7dab47c98b382ad0f87696780fab9898d2
134a694d3f0a42ea149a811750fcc945437a70cc
refs/heads/master
2023-08-25T20:54:04.496383
2021-10-25T11:26:18
2021-10-25T11:26:18
423,337,506
1
0
null
2021-11-01T04:31:21
2021-11-01T04:31:20
null
UTF-8
C++
false
false
769
hpp
#pragma once // The Cycle Frontier (1.X) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "TCF_AL_VelticiteMineral_Wall_BP_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass AL_VelticiteMineral_Wall_BP.AL_VelticiteMineral_Wall_BP_C // 0x0000 (0x0472 - 0x0472) class AAL_VelticiteMineral_Wall_BP_C : public AAL_Mineral_Base_BP_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass AL_VelticiteMineral_Wall_BP.AL_VelticiteMineral_Wall_BP_C")); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
7f1417afa33880ee1eefb5da53b25d9560ddd010
2c60bd602867302c2a1fc746e23a97d2fbed44d5
/russia2.cpp
3cb287921e84f028e26dc0de6c6727d623701006
[]
no_license
tangkevkev/algolab
40aff570c73dfe39e4ffc899213fb31d45b22d5b
1b5c7130e1e4a16bc0dc05e2ac963141bd9b6443
refs/heads/main
2023-01-22T00:16:21.203439
2020-12-06T15:28:12
2020-12-06T15:28:12
318,654,341
0
0
null
null
null
null
UTF-8
C++
false
false
2,554
cpp
#include <iostream> #include <vector> typedef std::vector<int> VI; typedef std::vector<VI> VVI; void rec(int left_index, int right_index, int player_index, int m, int k, std::vector<int> &sovereigns, VVI &DP) { //If already visited, no need to recompute if (DP[left_index][right_index] != -1) return; if (left_index == right_index) { if (player_index == k) { DP[left_index][right_index] = sovereigns[left_index]; } else { DP[left_index][right_index] = 0; } return; } //The next player's index int next_player_index = (player_index + 1) % m; //Compute the outcoming when taking the left coin rec(left_index + 1, right_index, next_player_index, m, k, sovereigns, DP); //Compute the outcomings when taking the right coin rec(left_index, right_index - 1, next_player_index, m, k, sovereigns, DP); //Store the results int left_value = DP[left_index + 1][right_index]; int right_value = DP[left_index][right_index - 1]; //Play optimally for k if (player_index == k) { //If taking the left coin is better than taking the right if (left_value + sovereigns[left_index] > right_value + sovereigns[right_index]) { DP[left_index][right_index] = left_value + sovereigns[left_index]; } else { DP[left_index][right_index] = right_value + sovereigns[right_index]; } } else { //Play for the worst outcome of player k if (left_value > right_value) { DP[left_index][right_index] = right_value; } else { DP[left_index][right_index] = left_value; } } } void testcase() { int n, m, k; std::cin >> n; std::cin >> m; std::cin >> k; std::vector<int> sovereigns; for (int i = 0; i < n; i++) { int val; std::cin >> val; sovereigns.push_back(val); } //create n x n Matrix initialized with -1 //Entry DP(i,j) is equal to the earning of player k, assuming k has played optimally for himself and all other player //play such that k earns minimal, for the remaining sovereigns between index i and j VVI DP(n, VI(n, -1)); rec(0, n - 1, 0, m, k, sovereigns, DP); std::cout << DP[0][n - 1] << std::endl; } int main() { std::ios_base::sync_with_stdio(false); int t; std::cin >> t; for (int i = 0; i < t; i++) { testcase(); } }
efffaf6afc03171f3a432f9b887f54abdb9e05f9
15410816be3bead66bff0fd86865e99ab6924266
/Fungsi/belajar fungsi2.cpp
4b56de691cf93050f2a8c60fb928432f9afeec12
[]
no_license
fadillaharsa/Algoritma-Pemrograman
a264be7b41a440be0ed0d668db4ee5ad9ceae7dd
fa11f08bff7a380b2fca0c7f34319a2520b94397
refs/heads/master
2022-04-14T21:15:28.001401
2020-04-14T14:36:09
2020-04-14T14:36:09
255,634,269
0
0
null
null
null
null
UTF-8
C++
false
false
424
cpp
/* BELAJAR FUNGSI 1 NOVEMBER 2017 PERTEMUAN 8 FUNGSI buat memodularkan perogram, per part gitu 1. Membalikan nilai 2. Tidak membalikan nilai */ #include <iostream> using namespace std; void pangkat (int angka, int& hasil) { hasil=angka*angka; } main() { int angka1,hasil1; cin>>angka1; pangkat(angka1,hasil1); cout<<hasil1<<endl; int angka2,hasil2; cin>>angka2; pangkat(angka2,hasil2); cout<<hasil2<<endl; }
09b5e065116b11c022c28589dd1b39d9821727ab
584be23b7da050661dc953f6dcbf5af9624f41aa
/BullCowGame/FBullCowGame.cpp
7239a71b9839a530bfa84b7144eeb0b7d6ffed70
[]
no_license
izabellaszabo/BullCowGame
877b4941251e6c5af1113d49b251eac4cf81fa89
c80eddebf6790285860056257cc781eab6bf5382
refs/heads/master
2020-11-24T06:37:19.757036
2019-12-14T12:12:04
2019-12-14T12:12:04
228,011,935
0
0
null
null
null
null
UTF-8
C++
false
false
2,018
cpp
#pragma once #include "FBullCowGame.h" #include <map> // To make syntax Unreal friendly #define TMap std::map using FString = std::string; using int32 = int; FBullCowGame::FBullCowGame() { Reset(); } int32 FBullCowGame::GetCurrentTry() const { return MyCurrentTry; } int32 FBullCowGame::GetHiddenWordLength() const { return MyHiddenWord.length(); } bool FBullCowGame::IsGameWon() const { return bGameIsWon; } EGuessStatus FBullCowGame::CheckGuessValidity (FString Guess) const { if (!IsIsogram(Guess)) return EGuessStatus::Not_Isogram; else if (!IsLowercase(Guess)) return EGuessStatus::Not_Lowercase; else if (Guess.length() != GetHiddenWordLength()) return EGuessStatus::Wrong_Length; return EGuessStatus::OK; } int32 FBullCowGame::GetMaxTries() const { TMap<int32, int32> WordLenthToMaxTries{ {3,4}, {4,7}, {5,10}, {6,16}, {7,20} }; return WordLenthToMaxTries[GetHiddenWordLength()]; } void FBullCowGame::Reset() { const FString HIDDEN_WORD = "planet"; // this MUST be an isogram MyHiddenWord = HIDDEN_WORD; MyCurrentTry = 1; bGameIsWon = false; } FBullCowCount FBullCowGame::SubmitValidGuess(FString Guess) { FBullCowCount BullCowCount; int32 WordLength = MyHiddenWord.length(); MyCurrentTry++; for (int32 MHWChar = 0; MHWChar < WordLength; MHWChar++) { for (int32 GChar = 0; GChar < WordLength; GChar++) { if (Guess[GChar] == MyHiddenWord[MHWChar]) { if (MHWChar == GChar) { BullCowCount.Bulls++; } else { BullCowCount.Cows++; } } } } if (BullCowCount.Bulls == WordLength) bGameIsWon = true; return BullCowCount; } bool FBullCowGame::IsIsogram(FString Word) const { if (Word.length() <= 1) return true; TMap<char, bool> LetterSeen; for (auto Letter : Word) { Letter = tolower(Letter); if (LetterSeen[Letter] == true) return false; else LetterSeen[Letter] = true; } return true; } bool FBullCowGame::IsLowercase(FString Word) const { for (auto Letter : Word) if (isupper(Letter)) return false; return true; }
2ac66532931c6534d7c02b6fe09203866c6c65be
7360252cf1c347a096fa57fe430f4685d3d037a8
/algorithm_cpp/Baek1966.cpp
31fbe040941d8b9f87b4435d1d2b6d8506b0e37c
[]
no_license
suwonY/SURISURI_IT
126f4caaf717bb24126d0dd0ac1687d74b304413
6c45106e4ffedb5c1e64456e17d76fc26a62de2d
refs/heads/master
2021-12-30T12:07:02.700251
2021-12-02T01:59:49
2021-12-02T01:59:49
112,294,179
0
0
null
null
null
null
UHC
C++
false
false
1,038
cpp
#include<iostream> #include<deque> #include<algorithm> #include<memory> #include<vector> using namespace std; class Node { public: int num, val; Node() { num = val = -1; } Node(int num, int val) { this->num = num; this->val = val; } }; int n, m, t, ans; int main() { cin >> t; for (int k = 0; k < t; k++) { cin >> n >> m; deque<Node> q; vector<int> a; for (int i = 0; i < n; i++) { int temp = 0; cin >> temp; q.push_back(Node(i, temp)); a.push_back(temp); } sort(a.begin(), a.end()); int temp = -1; //나와야할 가중치 ans = 1; while (true) { Node now = q.front(); int num = now.num; int val = now.val; if (temp == -1) { temp = a.back(); a.pop_back(); } if (val == temp) { //해당 가중치가 나왔다면 if (num == m) break; q.pop_front(); ++ans; temp = a.back(); a.pop_back(); continue; } if (val != temp) { Node temp = q.front(); q.pop_front(); q.push_back(temp); } } cout << ans << endl; } return 0; }
074e3e816cf2c21f0dfd14e2ea5aa7d730ae0ec0
cbbcfcb52e48025cb6c83fbdbfa28119b90efbd2
/codechef/snackB/A.cpp
0c4cf8f53699847f7ae19b8529f122614f5b4c3c
[]
no_license
dmehrab06/Time_wasters
c1198b9f2f24e06bfb2199253c74a874696947a8
a158f87fb09d880dd19582dce55861512e951f8a
refs/heads/master
2022-04-02T10:57:05.105651
2019-12-05T20:33:25
2019-12-05T20:33:25
104,850,524
0
1
null
null
null
null
UTF-8
C++
false
false
3,539
cpp
/*-------property of the half blood prince-----*/ #include <bits/stdc++.h> #include <dirent.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/detail/standard_policies.hpp> #define MIN(X,Y) X<Y?X:Y #define MAX(X,Y) X>Y?X:Y #define ISNUM(a) ('0'<=(a) && (a)<='9') #define ISCAP(a) ('A'<=(a) && (a)<='Z') #define ISSML(a) ('a'<=(a) && (a)<='z') #define ISALP(a) (ISCAP(a) || ISSML(a)) #define MXX 10000000000 #define MNN -MXX #define ISVALID(X,Y,N,M) ((X)>=1 && (X)<=(N) && (Y)>=1 && (Y)<=(M)) #define LLI long long int #define VI vector<int> #define VLLI vector<long long int> #define MII map<int,int> #define SI set<int> #define PB push_back #define MSI map<string,int> #define PII pair<int,int> #define PLLI pair<LLI,LLI> #define FREP(i,I,N) for(int (i)=(int)(I);(i)<=(int)(N);(i)++) #define eps 0.0000000001 #define RFREP(i,N,I) for(int (i)=(int)(N);(i)>=(int)(I);(i)--) #define SORTV(VEC) sort(VEC.begin(),VEC.end()) #define SORTVCMP(VEC,cmp) sort(VEC.begin(),VEC.end(),cmp) #define REVV(VEC) reverse(VEC.begin(),VEC.end()) #define INRANGED(val,l,r) (((l)<(val) || fabs((val)-(l))<eps) && ((val)<(r) || fabs((val)-(r))<eps)) using namespace std; using namespace __gnu_pbds; //int dx[]={1,0,-1,0};int dy[]={0,1,0,-1}; //4 Direction //int dx[]={1,1,0,-1,-1,-1,0,1};int dy[]={0,1,1,1,0,-1,-1,-1};//8 direction //int dx[]={2,1,-1,-2,-2,-1,1,2};int dy[]={1,2,2,1,-1,-2,-2,-1};//Knight Direction //int dx[]={2,1,-1,-2,-1,1};int dy[]={0,1,1,0,-1,-1}; //Hexagonal Direction typedef tree < int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update > ordered_set; int available1[103]; int available2[103]; int moneaten1[103]; int moneaten2[103]; int main(){ int t; cin>>t; while(t--){ string s; cin>>s; int mon=0; int snak=0; memset(available1,0,sizeof(available1)); memset(available2,0,sizeof(available2)); memset(moneaten1,0,sizeof(moneaten1)); memset(moneaten2,0,sizeof(moneaten2)); FREP(i,0,s.size()-1){ if(s[i]=='s'){ available1[i]=1; available2[i]=1; } if(s[i]=='s')snak++; if(s[i]=='m')mon++; } int eaten1=0; FREP(i,0,s.size()-2){ if(s[i]=='m' && s[i+1]=='s' && available1[i+1]==1 && moneaten1[i]==0){ // cout<<"paisi\n"; moneaten1[i]=1; eaten1++; available1[i+1]=0; } } RFREP(i,s.size()-1,1){ if(s[i]=='m' && s[i-1]=='s' && available1[i-1]==1 && moneaten1[i]==0){ moneaten1[i]=1; eaten1++; available1[i-1]=0; } } // cout<<eaten1<<"\n"; int eaten2=0; FREP(i,0,s.size()-2){ if(s[i]=='m' && s[i+1]=='s' && available2[i+1]==1 && moneaten2[i]==0){ moneaten2[i]=1; eaten2++; available2[i+1]=0; } } RFREP(i,s.size()-1,1){ if(s[i]=='m' && s[i-1]=='s' && available2[i-1]==1 && moneaten2[i]==0){ moneaten2[i]=1; eaten2++; available2[i-1]=0; } } //cout<<eaten2<<"\n"; snak-=max(eaten1,eaten2); if(snak==mon){ cout<<"tie\n"; } else if(snak>mon){ cout<<"snakes\n"; } else{ cout<<"mongooses\n"; } } return 0; }
a94abb468e013fb32f48b098b819ba90fe534e65
7f5524fff1f8a37446b3c0eb5e567d3de99bc369
/Array/Search a 2-D Matrix/Optimal.cpp
7fa1e66e14e26d6610b55a7de047aff885f2383f
[]
no_license
Ameyyy4/Problem-Solving
c6b436526192cd381010b9eaeb469a9464f05dc2
354d348d5d4b9314dcd46230276dabd36ea5406f
refs/heads/master
2023-01-06T01:42:52.162773
2020-11-11T05:24:08
2020-11-11T05:24:08
280,630,258
0
0
null
null
null
null
UTF-8
C++
false
false
2,242
cpp
// GFG Question // TC : O(row+col) soln // SC : O(1) #include <iostream> #include <vector> using namespace std; int searchmatrix(vector< vector<int> >& matrix, int target) { int R_index = 0; int C_index = matrix[0].size() - 1; while(R_index<matrix.size() && C_index>-1) { if(target == matrix[R_index][C_index]) { return 1; } if(target > matrix[R_index][C_index]) { R_index++; continue; } if(target < matrix[R_index][C_index]) { C_index--; continue; } } if(R_index == matrix.size() || C_index == -1) { return 0; } } // Leetcode Question // Special Case of null that is matrix.size() = 0 // Case : [], 0 // TC : O(log(row+col)) soln // SC : O(1) // DOUBT : How to implement binarysearch in 2-d vector? My approach last col and then in row bool searchMatrix(vector<vector<int>>& matrix, int target) { if(matrix.size() == 0) return 0; int First = 0; int Last = matrix[0].size()*matrix.size() - 1; int col = matrix[0].size(); int mid; while(First<=Last) { mid = First + (Last-First)/2; if(matrix[mid/col][mid%col] == target) return 1; if(matrix[mid/col][mid%col] > target) { Last = mid - 1; // Trick : Earlier I was doing Last = (Last + mid)/2 continue; } if(matrix[mid/col][mid%col] < target) { First = mid + 1; //Trick : Earlier I was doing First = (Last + mid)/2 which caused infinite Loop continue; } } return 0; } int main() { //code int t; cin>>t; int row; int col; int temp; for(int i=0; i<t; i++) { cin>>row>>col; vector< vector<int> > matrix(row); for(int i=0; i<row; i++) { matrix[i] = vector<int> (col); for(int j = 0; j<matrix[i].size(); j++) { cin>>temp; matrix[i][j] = temp; } } cin>>temp; cout<<searchmatrix( matrix, temp)<<endl; } return 0; }
ec759cde60d3c1c01a40d1190af8ff37083c53f8
423aafe8a00a106778340bac1d745bfd9e8b97d3
/src/drafted/governance-types.h
04c5dc16a90c3e72db961c46bb8b00a8b1230f9a
[ "MIT" ]
permissive
tauruspay/taurus
be3362e65bd5706446d6229617d87a7921f3aed7
54961c940f27008304c7e8bb05b42975a85984f0
refs/heads/master
2021-05-02T12:12:41.338358
2018-07-19T14:05:41
2018-07-19T14:05:41
120,737,983
1
1
MIT
2018-02-11T15:12:31
2018-02-08T09:11:26
C++
UTF-8
C++
false
false
1,321
h
/* Main governance types are 1-to-1 matched with governance classes - subtypes like a DAO is a categorical classification (extendable) - see governance-classes.h for more information */ enum GovernanceObjectType { // Programmatic Functionality Types Root = -3, AllTypes = -2, Error = -1, // --- Zero --- // Actions ValueOverride = 1, // ------------------------------- // TaurusNetwork - is the root node TaurusNetwork = 1000, TaurusNetworkVariable = 1001, Category = 1002, // Actors // -- note: DAOs can't own property... property must be owned by // -- legal entities in the local jurisdiction // -- this is the main reason for a two tiered company structure // -- people that operate DAOs will own companies which can own things legally Group = 2000, User = 2001, Company = 2002, // Project - Generic Base Project = 3000, ProjectReport = 3001, ProjectMilestone = 3002, // Budgets & Funding Proposal = 4000, Contract = 4001 }; // Functions for converting between the governance types and strings extern GovernanceObjectType GovernanceStringToType(std::string strType); extern std::string GovernanceTypeToString(GovernanceObjectType type); #endif
4db86304f4854bc987c2fa828eda65b56f94cab6
339640c627ca18d624c74f333938db4d8c72ce53
/src/main.h
28fcc838c082760e92561b30a0b981785e7d4dbf
[ "MIT" ]
permissive
bitcoini/bitcoini-source
1d3a03877326a4446c6dbf6e266727de6a2f48a7
f56f567ac124464953e8a39e5fa6397c012fc8d0
refs/heads/master
2021-07-06T07:21:58.591894
2017-09-26T07:34:11
2017-09-26T07:34:11
104,851,432
0
0
null
null
null
null
UTF-8
C++
false
false
45,214
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_MAIN_H #define BITCOIN_MAIN_H #include "bignum.h" #include "sync.h" #include "net.h" #include "script.h" #include "scrypt.h" #include "zerocoin/Zerocoin.h" #include <list> class CWallet; class CBlock; class CBlockIndex; class CKeyItem; class CReserveKey; class COutPoint; class CAddress; class CInv; class CRequestTracker; class CNode; class CTxMemPool; static const int LAST_POW_BLOCK = 1000; /** The maximum allowed size for a serialized block, in bytes (network rule) */ static const unsigned int MAX_BLOCK_SIZE = 1000000; /** The maximum size for mined blocks */ static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2; /** The maximum size for transactions we're willing to relay/mine **/ static const unsigned int MAX_STANDARD_TX_SIZE = MAX_BLOCK_SIZE_GEN/5; /** The maximum allowed number of signature check operations in a block (network rule) */ static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50; /** The maximum number of orphan transactions kept in memory */ static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100; /** The maximum number of entries in an 'inv' protocol message */ static const unsigned int MAX_INV_SZ = 50000; /** Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) */ static const int64_t MIN_TX_FEE = 10000; /** Fees smaller than this (in satoshi) are considered zero fee (for relaying) */ static const int64_t MIN_RELAY_TX_FEE = MIN_TX_FEE; /** No amount larger than this (in satoshi) is valid */ static const int64_t MAX_MONEY = 21212121 * COIN; inline bool MoneyRange(int64_t nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); } /** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */ static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC static const int64_t COIN_YEAR_REWARD = 10 * CENT; static const uint256 hashGenesisBlock("0x00000866d70101cb8c39b8e59e1ed232d826b72251263a5be679a2d62826702a"); static const uint256 hashGenesisBlockTestNet("0x00000866d70101cb8c39b8e59e1ed232d826b72251263a5be679a2d62826702a"); inline int64_t PastDrift(int64_t nTime) { return nTime - 10 * 60; } // up to 10 minutes from the past inline int64_t FutureDrift(int64_t nTime) { return nTime + 10 * 60; } // up to 10 minutes from the future extern libzerocoin::Params* ZCParams; extern CScript COINBASE_FLAGS; extern CCriticalSection cs_main; extern std::map<uint256, CBlockIndex*> mapBlockIndex; extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen; extern CBlockIndex* pindexGenesisBlock; extern unsigned int nTargetSpacing; extern unsigned int nStakeMinAge; extern unsigned int nStakeMaxAge; extern unsigned int nNodeLifespan; extern int nCoinbaseMaturity; extern int nBestHeight; extern uint256 nBestChainTrust; extern uint256 nBestInvalidTrust; extern uint256 hashBestChain; extern CBlockIndex* pindexBest; extern unsigned int nTransactionsUpdated; extern uint64_t nLastBlockTx; extern uint64_t nLastBlockSize; extern int64_t nLastCoinStakeSearchInterval; extern const std::string strMessageMagic; extern int64_t nTimeBestReceived; extern CCriticalSection cs_setpwalletRegistered; extern std::set<CWallet*> setpwalletRegistered; extern unsigned char pchMessageStart[4]; extern std::map<uint256, CBlock*> mapOrphanBlocks; // Settings extern int64_t nTransactionFee; extern int64_t nReserveBalance; extern int64_t nMinimumInputValue; extern bool fUseFastIndex; extern unsigned int nDerivationMethodIndex; extern bool fEnforceCanonical; // Minimum disk space required - used in CheckDiskSpace() static const uint64_t nMinDiskSpace = 52428800; class CReserveKey; class CTxDB; class CTxIndex; void RegisterWallet(CWallet* pwalletIn); void UnregisterWallet(CWallet* pwalletIn); void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true); bool ProcessBlock(CNode* pfrom, CBlock* pblock); bool CheckDiskSpace(uint64_t nAdditionalBytes=0); FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb"); FILE* AppendBlockFile(unsigned int& nFileRet); bool LoadBlockIndex(bool fAllowNew=true); void PrintBlockTree(); CBlockIndex* FindBlockByHeight(int nHeight); bool ProcessMessages(CNode* pfrom); bool SendMessages(CNode* pto, bool fSendTrickle); bool LoadExternalBlockFile(FILE* fileIn); bool CheckProofOfWork(uint256 hash, unsigned int nBits); unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake); int64_t GetProofOfWorkReward(int64_t nFees); int64_t GetProofOfStakeReward(int64_t nCoinAge, int64_t nFees); unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime); unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime); int GetNumBlocksOfPeers(); bool IsInitialBlockDownload(); std::string GetWarnings(std::string strFor); bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock); uint256 WantedByOrphan(const CBlock* pblockOrphan); const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake); void StakeMiner(CWallet *pwallet); void ResendWalletTransactions(bool fForce = false); /** (try to) add transaction to memory pool **/ bool AcceptToMemoryPool(CTxMemPool& pool, CTransaction &tx, bool* pfMissingInputs); bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut); /** Position on disk for a particular transaction. */ class CDiskTxPos { public: unsigned int nFile; unsigned int nBlockPos; unsigned int nTxPos; CDiskTxPos() { SetNull(); } CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn) { nFile = nFileIn; nBlockPos = nBlockPosIn; nTxPos = nTxPosIn; } IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); ) void SetNull() { nFile = (unsigned int) -1; nBlockPos = 0; nTxPos = 0; } bool IsNull() const { return (nFile == (unsigned int) -1); } friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b) { return (a.nFile == b.nFile && a.nBlockPos == b.nBlockPos && a.nTxPos == b.nTxPos); } friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b) { return !(a == b); } std::string ToString() const { if (IsNull()) return "null"; else return strprintf("(nFile=%u, nBlockPos=%u, nTxPos=%u)", nFile, nBlockPos, nTxPos); } void print() const { printf("%s", ToString().c_str()); } }; /** An inpoint - a combination of a transaction and an index n into its vin */ class CInPoint { public: CTransaction* ptx; unsigned int n; CInPoint() { SetNull(); } CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; } void SetNull() { ptx = NULL; n = (unsigned int) -1; } bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); } }; /** An outpoint - a combination of a transaction hash and an index n into its vout */ class COutPoint { public: uint256 hash; unsigned int n; COutPoint() { SetNull(); } COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; } IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); ) void SetNull() { hash = 0; n = (unsigned int) -1; } bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); } friend bool operator<(const COutPoint& a, const COutPoint& b) { return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n)); } friend bool operator==(const COutPoint& a, const COutPoint& b) { return (a.hash == b.hash && a.n == b.n); } friend bool operator!=(const COutPoint& a, const COutPoint& b) { return !(a == b); } std::string ToString() const { return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n); } void print() const { printf("%s\n", ToString().c_str()); } }; /** An input of a transaction. It contains the location of the previous * transaction's output that it claims and a signature that matches the * output's public key. */ class CTxIn { public: COutPoint prevout; CScript scriptSig; unsigned int nSequence; CTxIn() { nSequence = std::numeric_limits<unsigned int>::max(); } explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max()) { prevout = prevoutIn; scriptSig = scriptSigIn; nSequence = nSequenceIn; } CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max()) { prevout = COutPoint(hashPrevTx, nOut); scriptSig = scriptSigIn; nSequence = nSequenceIn; } IMPLEMENT_SERIALIZE ( READWRITE(prevout); READWRITE(scriptSig); READWRITE(nSequence); ) bool IsFinal() const { return (nSequence == std::numeric_limits<unsigned int>::max()); } friend bool operator==(const CTxIn& a, const CTxIn& b) { return (a.prevout == b.prevout && a.scriptSig == b.scriptSig && a.nSequence == b.nSequence); } friend bool operator!=(const CTxIn& a, const CTxIn& b) { return !(a == b); } std::string ToStringShort() const { return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n); } std::string ToString() const { std::string str; str += "CTxIn("; str += prevout.ToString(); if (prevout.IsNull()) str += strprintf(", coinbase %s", HexStr(scriptSig).c_str()); else str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str()); if (nSequence != std::numeric_limits<unsigned int>::max()) str += strprintf(", nSequence=%u", nSequence); str += ")"; return str; } void print() const { printf("%s\n", ToString().c_str()); } }; /** An output of a transaction. It contains the public key that the next input * must be able to sign with to claim it. */ class CTxOut { public: int64_t nValue; CScript scriptPubKey; CTxOut() { SetNull(); } CTxOut(int64_t nValueIn, CScript scriptPubKeyIn) { nValue = nValueIn; scriptPubKey = scriptPubKeyIn; } IMPLEMENT_SERIALIZE ( READWRITE(nValue); READWRITE(scriptPubKey); ) void SetNull() { nValue = -1; scriptPubKey.clear(); } bool IsNull() { return (nValue == -1); } void SetEmpty() { nValue = 0; scriptPubKey.clear(); } bool IsEmpty() const { return (nValue == 0 && scriptPubKey.empty()); } uint256 GetHash() const { return SerializeHash(*this); } friend bool operator==(const CTxOut& a, const CTxOut& b) { return (a.nValue == b.nValue && a.scriptPubKey == b.scriptPubKey); } friend bool operator!=(const CTxOut& a, const CTxOut& b) { return !(a == b); } std::string ToStringShort() const { return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str()); } std::string ToString() const { if (IsEmpty()) return "CTxOut(empty)"; return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str()); } void print() const { printf("%s\n", ToString().c_str()); } }; enum GetMinFee_mode { GMF_BLOCK, GMF_RELAY, GMF_SEND, }; typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx; /** The basic transaction that is broadcasted on the network and contained in * blocks. A transaction can contain multiple inputs and outputs. */ class CTransaction { public: static const int CURRENT_VERSION=1; int nVersion; unsigned int nTime; std::vector<CTxIn> vin; std::vector<CTxOut> vout; unsigned int nLockTime; // Denial-of-service detection: mutable int nDoS; bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; } CTransaction() { SetNull(); } IMPLEMENT_SERIALIZE ( READWRITE(this->nVersion); nVersion = this->nVersion; READWRITE(nTime); READWRITE(vin); READWRITE(vout); READWRITE(nLockTime); ) void SetNull() { nVersion = CTransaction::CURRENT_VERSION; nTime = GetAdjustedTime(); vin.clear(); vout.clear(); nLockTime = 0; nDoS = 0; // Denial-of-service prevention } bool IsNull() const { return (vin.empty() && vout.empty()); } uint256 GetHash() const { return SerializeHash(*this); } bool IsNewerThan(const CTransaction& old) const { if (vin.size() != old.vin.size()) return false; for (unsigned int i = 0; i < vin.size(); i++) if (vin[i].prevout != old.vin[i].prevout) return false; bool fNewer = false; unsigned int nLowest = std::numeric_limits<unsigned int>::max(); for (unsigned int i = 0; i < vin.size(); i++) { if (vin[i].nSequence != old.vin[i].nSequence) { if (vin[i].nSequence <= nLowest) { fNewer = false; nLowest = vin[i].nSequence; } if (old.vin[i].nSequence < nLowest) { fNewer = true; nLowest = old.vin[i].nSequence; } } } return fNewer; } bool IsCoinBase() const { return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1); } bool IsCoinStake() const { // ppcoin: the coin stake transaction is marked with the first output empty return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty()); } /** Check for standard transaction types @param[in] mapInputs Map of previous transactions that have outputs we're spending @return True if all inputs (scriptSigs) use only standard transaction forms @see CTransaction::FetchInputs */ bool AreInputsStandard(const MapPrevTx& mapInputs) const; /** Count ECDSA signature operations the old-fashioned (pre-0.6) way @return number of sigops this transaction's outputs will produce when spent @see CTransaction::FetchInputs */ unsigned int GetLegacySigOpCount() const; /** Count ECDSA signature operations in pay-to-script-hash inputs. @param[in] mapInputs Map of previous transactions that have outputs we're spending @return maximum number of sigops required to validate this transaction's inputs @see CTransaction::FetchInputs */ unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const; /** Amount of bitcoins spent by this transaction. @return sum of all outputs (note: does not include fees) */ int64_t GetValueOut() const { int64_t nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, vout) { nValueOut += txout.nValue; if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut)) throw std::runtime_error("CTransaction::GetValueOut() : value out of range"); } return nValueOut; } /** Amount of bitcoins coming in to this transaction Note that lightweight clients may not know anything besides the hash of previous transactions, so may not be able to calculate this. @param[in] mapInputs Map of previous transactions that have outputs we're spending @return Sum of value of all inputs (scriptSigs) @see CTransaction::FetchInputs */ int64_t GetValueIn(const MapPrevTx& mapInputs) const; int64_t GetMinFee(unsigned int nBlockSize=1, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const; bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL) { CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION); if (!filein) return error("CTransaction::ReadFromDisk() : OpenBlockFile failed"); // Read transaction if (fseek(filein, pos.nTxPos, SEEK_SET) != 0) return error("CTransaction::ReadFromDisk() : fseek failed"); try { filein >> *this; } catch (std::exception &e) { return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__); } // Return file pointer if (pfileRet) { if (fseek(filein, pos.nTxPos, SEEK_SET) != 0) return error("CTransaction::ReadFromDisk() : second fseek failed"); *pfileRet = filein.release(); } return true; } friend bool operator==(const CTransaction& a, const CTransaction& b) { return (a.nVersion == b.nVersion && a.nTime == b.nTime && a.vin == b.vin && a.vout == b.vout && a.nLockTime == b.nLockTime); } friend bool operator!=(const CTransaction& a, const CTransaction& b) { return !(a == b); } std::string ToStringShort() const { std::string str; str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user")); return str; } std::string ToString() const { std::string str; str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction"); str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%d)\n", GetHash().ToString().substr(0,10).c_str(), nTime, nVersion, vin.size(), vout.size(), nLockTime); for (unsigned int i = 0; i < vin.size(); i++) str += " " + vin[i].ToString() + "\n"; for (unsigned int i = 0; i < vout.size(); i++) str += " " + vout[i].ToString() + "\n"; return str; } void print() const { printf("%s", ToString().c_str()); } bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet); bool ReadFromDisk(CTxDB& txdb, COutPoint prevout); bool ReadFromDisk(COutPoint prevout); bool DisconnectInputs(CTxDB& txdb); /** Fetch from memory and/or disk. inputsRet keys are transaction hashes. @param[in] txdb Transaction database @param[in] mapTestPool List of pending changes to the transaction index database @param[in] fBlock True if being called to add a new best-block to the chain @param[in] fMiner True if being called by CreateNewBlock @param[out] inputsRet Pointers to this transaction's inputs @param[out] fInvalid returns true if transaction is invalid @return Returns true if all inputs are in txdb or mapTestPool */ bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool, bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid); /** Sanity check previous transactions, then, if all checks succeed, mark them as spent by this transaction. @param[in] inputs Previous transactions (from FetchInputs) @param[out] mapTestPool Keeps track of inputs that need to be updated on disk @param[in] posThisTx Position of this transaction on disk @param[in] pindexBlock @param[in] fBlock true if called from ConnectBlock @param[in] fMiner true if called from CreateNewBlock @return Returns true if all checks succeed */ bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs, std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock, bool fBlock, bool fMiner); bool CheckTransaction() const; bool GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const; // ppcoin: get transaction coin age protected: const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const; }; /** Check for standard transaction types @return True if all outputs (scriptPubKeys) use only standard transaction forms */ bool IsStandardTx(const CTransaction& tx); bool IsFinalTx(const CTransaction &tx, int nBlockHeight = 0, int64_t nBlockTime = 0); /** A transaction with a merkle branch linking it to the block chain. */ class CMerkleTx : public CTransaction { private: int GetDepthInMainChainINTERNAL(CBlockIndex* &pindexRet) const; public: uint256 hashBlock; std::vector<uint256> vMerkleBranch; int nIndex; // memory only mutable bool fMerkleVerified; CMerkleTx() { Init(); } CMerkleTx(const CTransaction& txIn) : CTransaction(txIn) { Init(); } void Init() { hashBlock = 0; nIndex = -1; fMerkleVerified = false; } IMPLEMENT_SERIALIZE ( nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action); nVersion = this->nVersion; READWRITE(hashBlock); READWRITE(vMerkleBranch); READWRITE(nIndex); ) int SetMerkleBranch(const CBlock* pblock=NULL); // Return depth of transaction in blockchain: // -1 : not in blockchain, and not in memory pool (conflicted transaction) // 0 : in memory pool, waiting to be included in a block // >=1 : this many blocks deep in the main chain int GetDepthInMainChain(CBlockIndex* &pindexRet) const; int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); } bool IsInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChainINTERNAL(pindexRet) > 0; } int GetBlocksToMaturity() const; bool AcceptToMemoryPool(); }; /** A txdb record that contains the disk location of a transaction and the * locations of transactions that spend its outputs. vSpent is really only * used as a flag, but having the location is very helpful for debugging. */ class CTxIndex { public: CDiskTxPos pos; std::vector<CDiskTxPos> vSpent; CTxIndex() { SetNull(); } CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs) { pos = posIn; vSpent.resize(nOutputs); } IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(pos); READWRITE(vSpent); ) void SetNull() { pos.SetNull(); vSpent.clear(); } bool IsNull() { return pos.IsNull(); } friend bool operator==(const CTxIndex& a, const CTxIndex& b) { return (a.pos == b.pos && a.vSpent == b.vSpent); } friend bool operator!=(const CTxIndex& a, const CTxIndex& b) { return !(a == b); } int GetDepthInMainChain() const; }; /** Nodes collect new transactions into a block, hash them into a hash tree, * and scan through nonce values to make the block's hash satisfy proof-of-work * requirements. When they solve the proof-of-work, they broadcast the block * to everyone and the block is added to the block chain. The first transaction * in the block is a special one that creates a new coin owned by the creator * of the block. * * Blocks are appended to blk0001.dat files on disk. Their location on disk * is indexed by CBlockIndex objects in memory. */ class CBlock { public: // header static const int CURRENT_VERSION=6; int nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; // network and disk std::vector<CTransaction> vtx; // ppcoin: block signature - signed by one of the coin base txout[N]'s owner std::vector<unsigned char> vchBlockSig; // memory only mutable std::vector<uint256> vMerkleTree; // Denial-of-service detection: mutable int nDoS; bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; } CBlock() { SetNull(); } IMPLEMENT_SERIALIZE ( READWRITE(this->nVersion); nVersion = this->nVersion; READWRITE(hashPrevBlock); READWRITE(hashMerkleRoot); READWRITE(nTime); READWRITE(nBits); READWRITE(nNonce); // ConnectBlock depends on vtx following header to generate CDiskTxPos if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY))) { READWRITE(vtx); READWRITE(vchBlockSig); } else if (fRead) { const_cast<CBlock*>(this)->vtx.clear(); const_cast<CBlock*>(this)->vchBlockSig.clear(); } ) void SetNull() { nVersion = CBlock::CURRENT_VERSION; hashPrevBlock = 0; hashMerkleRoot = 0; nTime = 0; nBits = 0; nNonce = 0; vtx.clear(); vchBlockSig.clear(); vMerkleTree.clear(); nDoS = 0; } bool IsNull() const { return (nBits == 0); } uint256 GetHash() const { return GetPoWHash(); } uint256 GetPoWHash() const { return scrypt_blockhash(CVOIDBEGIN(nVersion)); } int64_t GetBlockTime() const { return (int64_t)nTime; } void UpdateTime(const CBlockIndex* pindexPrev); // entropy bit for stake modifier if chosen by modifier unsigned int GetStakeEntropyBit() const { // Take last bit of block hash as entropy bit unsigned int nEntropyBit = ((GetHash().Get64()) & 1llu); if (fDebug && GetBoolArg("-printstakemodifier")) printf("GetStakeEntropyBit: hashBlock=%s nEntropyBit=%u\n", GetHash().ToString().c_str(), nEntropyBit); return nEntropyBit; } // ppcoin: two types of block: proof-of-work or proof-of-stake bool IsProofOfStake() const { return (vtx.size() > 1 && vtx[1].IsCoinStake()); } bool IsProofOfWork() const { return !IsProofOfStake(); } std::pair<COutPoint, unsigned int> GetProofOfStake() const { return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0); } // ppcoin: get max transaction timestamp int64_t GetMaxTransactionTime() const { int64_t maxTransactionTime = 0; BOOST_FOREACH(const CTransaction& tx, vtx) maxTransactionTime = std::max(maxTransactionTime, (int64_t)tx.nTime); return maxTransactionTime; } uint256 BuildMerkleTree() const { vMerkleTree.clear(); BOOST_FOREACH(const CTransaction& tx, vtx) vMerkleTree.push_back(tx.GetHash()); int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { for (int i = 0; i < nSize; i += 2) { int i2 = std::min(i+1, nSize-1); vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]), BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2]))); } j += nSize; } return (vMerkleTree.empty() ? 0 : vMerkleTree.back()); } std::vector<uint256> GetMerkleBranch(int nIndex) const { if (vMerkleTree.empty()) BuildMerkleTree(); std::vector<uint256> vMerkleBranch; int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { int i = std::min(nIndex^1, nSize-1); vMerkleBranch.push_back(vMerkleTree[j+i]); nIndex >>= 1; j += nSize; } return vMerkleBranch; } static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex) { if (nIndex == -1) return 0; BOOST_FOREACH(const uint256& otherside, vMerkleBranch) { if (nIndex & 1) hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash)); else hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside)); nIndex >>= 1; } return hash; } bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet) { // Open history file to append CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION); if (!fileout) return error("CBlock::WriteToDisk() : AppendBlockFile failed"); // Write index header unsigned int nSize = fileout.GetSerializeSize(*this); fileout << FLATDATA(pchMessageStart) << nSize; // Write block long fileOutPos = ftell(fileout); if (fileOutPos < 0) return error("CBlock::WriteToDisk() : ftell failed"); nBlockPosRet = fileOutPos; fileout << *this; // Flush stdio buffers and commit to disk before returning fflush(fileout); if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0) FileCommit(fileout); return true; } bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true) { SetNull(); // Open history file to read CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION); if (!filein) return error("CBlock::ReadFromDisk() : OpenBlockFile failed"); if (!fReadTransactions) filein.nType |= SER_BLOCKHEADERONLY; // Read block try { filein >> *this; } catch (std::exception &e) { return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__); } // Check the header if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetPoWHash(), nBits)) return error("CBlock::ReadFromDisk() : errors in block header"); return true; } void print() const { printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu", vchBlockSig=%s)\n", GetHash().ToString().c_str(), nVersion, hashPrevBlock.ToString().c_str(), hashMerkleRoot.ToString().c_str(), nTime, nBits, nNonce, vtx.size(), HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str()); for (unsigned int i = 0; i < vtx.size(); i++) { printf(" "); vtx[i].print(); } printf(" vMerkleTree: "); for (unsigned int i = 0; i < vMerkleTree.size(); i++) printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str()); printf("\n"); } bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex); bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false); bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true); bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew); bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos, const uint256& hashProof); bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=true) const; bool AcceptBlock(); bool GetCoinAge(uint64_t& nCoinAge) const; // ppcoin: calculate total coin age spent in block bool SignBlock(CWallet& keystore, int64_t nFees); bool CheckBlockSignature() const; private: bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew); }; /** The block chain is a tree shaped structure starting with the * genesis block at the root, with each block potentially having multiple * candidates to be the next block. pprev and pnext link a path through the * main/longest chain. A blockindex may have multiple pprev pointing back * to it, but pnext will only point forward to the longest branch, or will * be null if the block is not part of the longest chain. */ class CBlockIndex { public: const uint256* phashBlock; CBlockIndex* pprev; CBlockIndex* pnext; unsigned int nFile; unsigned int nBlockPos; uint256 nChainTrust; // ppcoin: trust score of block chain int nHeight; int64_t nMint; int64_t nMoneySupply; unsigned int nFlags; // ppcoin: block index flags enum { BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier }; uint64_t nStakeModifier; // hash modifier for proof-of-stake unsigned int nStakeModifierChecksum; // checksum of index; in-memeory only // proof-of-stake specific fields COutPoint prevoutStake; unsigned int nStakeTime; uint256 hashProof; // block header int nVersion; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; CBlockIndex() { phashBlock = NULL; pprev = NULL; pnext = NULL; nFile = 0; nBlockPos = 0; nHeight = 0; nChainTrust = 0; nMint = 0; nMoneySupply = 0; nFlags = 0; nStakeModifier = 0; nStakeModifierChecksum = 0; hashProof = 0; prevoutStake.SetNull(); nStakeTime = 0; nVersion = 0; hashMerkleRoot = 0; nTime = 0; nBits = 0; nNonce = 0; } CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block) { phashBlock = NULL; pprev = NULL; pnext = NULL; nFile = nFileIn; nBlockPos = nBlockPosIn; nHeight = 0; nChainTrust = 0; nMint = 0; nMoneySupply = 0; nFlags = 0; nStakeModifier = 0; nStakeModifierChecksum = 0; hashProof = 0; if (block.IsProofOfStake()) { SetProofOfStake(); prevoutStake = block.vtx[1].vin[0].prevout; nStakeTime = block.vtx[1].nTime; } else { prevoutStake.SetNull(); nStakeTime = 0; } nVersion = block.nVersion; hashMerkleRoot = block.hashMerkleRoot; nTime = block.nTime; nBits = block.nBits; nNonce = block.nNonce; } CBlock GetBlockHeader() const { CBlock block; block.nVersion = nVersion; if (pprev) block.hashPrevBlock = pprev->GetBlockHash(); block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block; } uint256 GetBlockHash() const { return *phashBlock; } int64_t GetBlockTime() const { return (int64_t)nTime; } uint256 GetBlockTrust() const; bool IsInMainChain() const { return (pnext || this == pindexBest); } bool CheckIndex() const { return true; } int64_t GetPastTimeLimit() const { return GetMedianTimePast(); } enum { nMedianTimeSpan=11 }; int64_t GetMedianTimePast() const { int64_t pmedian[nMedianTimeSpan]; int64_t* pbegin = &pmedian[nMedianTimeSpan]; int64_t* pend = &pmedian[nMedianTimeSpan]; const CBlockIndex* pindex = this; for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev) *(--pbegin) = pindex->GetBlockTime(); std::sort(pbegin, pend); return pbegin[(pend - pbegin)/2]; } /** * Returns true if there are nRequired or more blocks of minVersion or above * in the last nToCheck blocks, starting at pstart and going backwards. */ static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck); bool IsProofOfWork() const { return !(nFlags & BLOCK_PROOF_OF_STAKE); } bool IsProofOfStake() const { return (nFlags & BLOCK_PROOF_OF_STAKE); } void SetProofOfStake() { nFlags |= BLOCK_PROOF_OF_STAKE; } unsigned int GetStakeEntropyBit() const { return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1); } bool SetStakeEntropyBit(unsigned int nEntropyBit) { if (nEntropyBit > 1) return false; nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0); return true; } bool GeneratedStakeModifier() const { return (nFlags & BLOCK_STAKE_MODIFIER); } void SetStakeModifier(uint64_t nModifier, bool fGeneratedStakeModifier) { nStakeModifier = nModifier; if (fGeneratedStakeModifier) nFlags |= BLOCK_STAKE_MODIFIER; } std::string ToString() const { return strprintf("CBlockIndex(nprev=%p, pnext=%p, nFile=%u, nBlockPos=%-6d nHeight=%d, nMint=%s, nMoneySupply=%s, nFlags=(%s)(%d)(%s), nStakeModifier=%016"PRIx64", nStakeModifierChecksum=%08x, hashProof=%s, prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)", pprev, pnext, nFile, nBlockPos, nHeight, FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(), GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW", nStakeModifier, nStakeModifierChecksum, hashProof.ToString().c_str(), prevoutStake.ToString().c_str(), nStakeTime, hashMerkleRoot.ToString().c_str(), GetBlockHash().ToString().c_str()); } void print() const { printf("%s\n", ToString().c_str()); } }; /** Used to marshal pointers into hashes for db storage. */ class CDiskBlockIndex : public CBlockIndex { private: uint256 blockHash; public: uint256 hashPrev; uint256 hashNext; CDiskBlockIndex() { hashPrev = 0; hashNext = 0; blockHash = 0; } explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) { hashPrev = (pprev ? pprev->GetBlockHash() : 0); hashNext = (pnext ? pnext->GetBlockHash() : 0); } IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(hashNext); READWRITE(nFile); READWRITE(nBlockPos); READWRITE(nHeight); READWRITE(nMint); READWRITE(nMoneySupply); READWRITE(nFlags); READWRITE(nStakeModifier); if (IsProofOfStake()) { READWRITE(prevoutStake); READWRITE(nStakeTime); } else if (fRead) { const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull(); const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0; } READWRITE(hashProof); // block header READWRITE(this->nVersion); READWRITE(hashPrev); READWRITE(hashMerkleRoot); READWRITE(nTime); READWRITE(nBits); READWRITE(nNonce); READWRITE(blockHash); ) uint256 GetBlockHash() const { if (fUseFastIndex && (nTime < GetAdjustedTime() - 24 * 60 * 60) && blockHash != 0) return blockHash; CBlock block; block.nVersion = nVersion; block.hashPrevBlock = hashPrev; block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash(); return blockHash; } std::string ToString() const { std::string str = "CDiskBlockIndex("; str += CBlockIndex::ToString(); str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)", GetBlockHash().ToString().c_str(), hashPrev.ToString().c_str(), hashNext.ToString().c_str()); return str; } void print() const { printf("%s\n", ToString().c_str()); } }; /** Describes a place in the block chain to another node such that if the * other node doesn't have the same branch, it can find a recent common trunk. * The further back it is, the further before the fork it may be. */ class CBlockLocator { protected: std::vector<uint256> vHave; public: CBlockLocator() { } explicit CBlockLocator(const CBlockIndex* pindex) { Set(pindex); } explicit CBlockLocator(uint256 hashBlock) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end()) Set((*mi).second); } CBlockLocator(const std::vector<uint256>& vHaveIn) { vHave = vHaveIn; } IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(vHave); ) void SetNull() { vHave.clear(); } bool IsNull() { return vHave.empty(); } void Set(const CBlockIndex* pindex) { vHave.clear(); int nStep = 1; while (pindex) { vHave.push_back(pindex->GetBlockHash()); // Exponentially larger steps back for (int i = 0; pindex && i < nStep; i++) pindex = pindex->pprev; if (vHave.size() > 10) nStep *= 2; } vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)); } int GetDistanceBack() { // Retrace how far back it was in the sender's branch int nDistance = 0; int nStep = 1; BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return nDistance; } nDistance += nStep; if (nDistance > 10) nStep *= 2; } return nDistance; } CBlockIndex* GetBlockIndex() { // Find the first block the caller has in the main chain BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return pindex; } } return pindexGenesisBlock; } uint256 GetBlockHash() { // Find the first block the caller has in the main chain BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return hash; } } return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet); } int GetHeight() { CBlockIndex* pindex = GetBlockIndex(); if (!pindex) return 0; return pindex->nHeight; } }; class CTxMemPool { public: mutable CCriticalSection cs; std::map<uint256, CTransaction> mapTx; std::map<COutPoint, CInPoint> mapNextTx; bool addUnchecked(const uint256& hash, CTransaction &tx); bool remove(const CTransaction &tx, bool fRecursive = false); bool removeConflicts(const CTransaction &tx); void clear(); void queryHashes(std::vector<uint256>& vtxid); unsigned long size() const { LOCK(cs); return mapTx.size(); } bool exists(uint256 hash) const { LOCK(cs); return (mapTx.count(hash) != 0); } bool lookup(uint256 hash, CTransaction& result) const { LOCK(cs); std::map<uint256, CTransaction>::const_iterator i = mapTx.find(hash); if (i == mapTx.end()) return false; result = i->second; return true; } }; extern CTxMemPool mempool; #endif
c938efaaca1078e08eb951e4b9bee6440f5de669
23e2509351b7cdbdabde9090981cf113ec7f76df
/Source/EscapeGame/DoorOpen.h
16fba3ef6b3b32efad32c9ab032af705e4bc96f5
[]
no_license
GameDevelopmentCourses/EscapeGame-4.26
b15962ee4d46620992f5f96b230691b76db6822d
729d470b14484c38e39faefb82925b620fd166ce
refs/heads/main
2023-06-30T18:49:38.980611
2021-08-01T14:07:20
2021-08-01T14:07:20
391,644,541
0
0
null
null
null
null
UTF-8
C++
false
false
1,270
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "Engine.h" #include "CoreMinimal.h" #include "Components/ActorComponent.h" #include "DoorOpen.generated.h" UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class ESCAPEGAME_API UDoorOpen : public UActorComponent { GENERATED_BODY() public: // Sets default values for this component's properties UDoorOpen(); protected: // Called when the game starts virtual void BeginPlay() override; public: // Called every frame virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override; private: //Set Time For Door To Remain Open UPROPERTY(EditAnywhere,Category="DoorProperties") float DoorOpenTime = 2; //Collision Box To Place Objects UPROPERTY(EditAnywhere,Category="DoorProperties") ATriggerVolume* PressurePlate = nullptr; //Weight Require To Open Door UPROPERTY(EditAnywhere,Category="DoorProperties") float TriggerWeight=50; //Door Open Func void OpenDoor() const; //Door CLose FUnc void DoorClose() const; //Return Total Mass of Actors Overlapping Trigger Space float GetWeightOfActorsOverlapping() const; //Reference To Self; AActor* Door; };
93e3fa0e3c116ef663b63b9026061f9ac306404f
80aa687b6ef57dfc6c4b1267a2455d387af9aee2
/TEMA-2 VETOR/ex2.cpp
3b0c2f1769216cbe9d2ec216a5423c41c6283976
[]
no_license
daniel0ferraz/ProgramacaoEstruturada
1bc65b82b291bae3614386fc39277488d5166b8e
f5ad6f0291423eb18e677186d76b0d7bb488111a
refs/heads/master
2023-01-25T05:32:37.938098
2020-12-01T18:01:25
2020-12-01T18:01:25
290,472,150
2
0
null
null
null
null
UTF-8
C++
false
false
233
cpp
#include<stdio.h> #include<stdlib.h> main() { int i,vetor[3]; vetor[0] = 3; vetor[1] = 12; vetor[2] = 4; i = 0; while (i < 3) { printf("%d\n",vetor[i]); i = i + 1; } system("pause"); }
8af7ba840fb39e08adf660ce3485f5f9991e2cfd
1d9e35b1194ee1c1184373c16bd7e5fbdeff06ff
/canGw_simple1/canGw_simple1.ino
51db0ba45c6621c0273b1896918139fed20f1412
[]
no_license
BOBILLEChristophe/canGw_simple1
9e6ff4f954ce5ffaf8d7d7bab0aabf04fc193f92
dc2df6a9ff08b34262926a906aa6c0dd60c764fe
refs/heads/master
2021-07-09T13:48:37.249642
2020-12-11T21:54:28
2020-12-11T21:54:28
219,967,836
0
0
null
null
null
null
UTF-8
C++
false
false
3,031
ino
/* Passerelle Wifi/CAN avec un ESP32 et un module SN65HVD230 CAN Bus Transceiver https://www.ebay.fr/itm/1pcs-SN65HVD230-CAN-bus-transceiver Ce projet est une passerelle simple entre un reseau ETHERNET/WiFi et un bus CAN en simplex. Pour les besoins en communication bi-directionnelle, une seconde passerelle similaire a celle-ci pourra etre utilisee. Christophe BOBILLE sept 2018 - nov 2019 [email protected] Les messages echanges sont de type : unsigned char mInputMsg[] = "0x25 0 3 0x93 0x00 0x9F"; ou avec identifiant long : unsigned char mInputMsg[] = "0xFF00112 1 3 0x93 0x00 0x9F"; avec des champs d'arbitrage sur 11 ou 29 bits le champ de donnees peut varier de 0 (trame de requete) a 8 octets. Bibliotheques : - <ESP32CAN.h> @ https://github.com/nhatuan84/esp32-can-protocol-demo */ #define VERSION "1.0" #define PROJECT "canGw_simple1" #include <Arduino.h> #include <HardwareSerial.h> #include "Config.h" #include "CanCtrl.h" #include <WiFi.h> const char* ssid = WIFI_SSID; const char* password = WIFI_PSW; WiFiServer server(12560); GW_Can canCtrl; // Instance de GW_Can /*__________________________________________________________SETUP__________________________________________________________*/ void setup() { // Port serie pour debug dbg_output.begin(SERIAL_BAUDRATE, SERIAL_8N1, DBG_RX_PIN_ID, DBG_TX_PIN_ID); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); dbg_output.print("."); } server.begin(); dbg_output.println(""); dbg_output.println("WiFi connected."); dbg_output.println("IP address: "); dbg_output.println(WiFi.localIP()); dbg_output.setDebugOutput(true); // Debug + complet // Infos du projet dbg_output.print("\n\n\n"); dbg_output.print("Project : "); dbg_output.print(PROJECT); dbg_output.print("\nVersion : "); dbg_output.print(VERSION); dbg_output.print("\nCompiled : "); dbg_output.print(__DATE__); dbg_output.print(" "); dbg_output.print(__TIME__); dbg_output.print("\n\n"); //Bus CAN int err = canCtrl.begin(); switch (err) { case 0 : dbg_output.print("CAN ok !\n\n"); break; case -1 : dbg_output.print("Probleme de connexion CAN !\n"); dbg_output.print("Programme interrompu."); return; } dbg_output.print("End of setup.\n\n"); } // End setup /*__________________________________________________________LOOP__________________________________________________________*/ void loop() { static int err = 1; WiFiClient client = server.available(); if (client) { dbg_output.print("New Client.\n"); while (client.connected()) { //if (RECEIVE_FROM_CAN) { //INCOMING messages sur le bus CAN et envoi sur le port Serial et wifi err = canCtrl.msgRx(); switch (err) { case 0 : client.print(canCtrl.getInputMsg()); } //} // -> end RECEIVE_FROM_CAN delay(1); } } } // End loop
0b1739ebcebbe3d110ec16414379e33da27cd908
903dac660b0db25b05ac375a5916f023ef199fc0
/include/HE1NDecrypter.h
a6f8507c7d5c48b56862f61a8fb14bd174b4753d
[]
no_license
TANGO-Project/cryptsdc
d6af5dd9e4252462cabf383fd52b9814d0dc0a29
4428fc289c97818d58a8010593636c64bde56e82
refs/heads/master
2020-03-28T05:57:34.072152
2018-10-23T13:29:24
2018-10-23T13:29:24
147,806,026
0
0
null
null
null
null
UTF-8
C++
false
false
1,276
h
/* * Copyright 2018 James Dyer * * 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. * * This is being developed for the TANGO Project: http://tango-project.eu */ #ifndef HE1NDECRYPTER_H #define HE1NDECRYPTER_H #include <string> #include <NTL/ZZ.h> #include <NTL/vec_ZZ.h> #include "HOMDecipher.hpp" class HE1NDecrypter : public HOMDecipher<NTL::ZZ_p,NTL::ZZ> { private: /** * A secret cipher parameter */ NTL::ZZ kappa; public: /** * Set the secret parameters \c p and \c kappa from the given vector. * @param key A vector */ void setKey(NTL::vec_ZZ& key); void readSecretsFromJSON(std::string& json) override; NTL::ZZ decrypt(NTL::ZZ_p& ciphertext) override; HE1NDecrypter(){}; virtual ~HE1NDecrypter(){}; }; #endif
b4e107a18df3cb0584709ce133c23b5064eecf1a
c99901dd9b75e1a280d3516f3c4396f1f869957b
/10591.cpp
e5572c055217ffb97c185ea53f772246d902070d
[]
no_license
BornaliSaha/UVa-Problems
5433dd598998426062e97de974ab24ce0f9c6639
65a15c9db3017b122d01f64be85737242ee754ce
refs/heads/main
2023-07-19T01:44:51.921884
2021-09-05T13:31:42
2021-09-05T13:31:42
389,076,386
0
0
null
null
null
null
UTF-8
C++
false
false
801
cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll; int main() { int p,n,mod=0,cp,sum=0; while((scanf("%d",&p))==1) { for(int i=1;i<=p;i++) { scanf("%d",&n); cp=n,sum=0; while(n<9 || n>9) { if(n<=9) { sum=n; break; } while(n!=0) { mod=n%10; sum+=(mod * mod); n/=10; } n=sum; sum=0; } if(sum==1||sum==7) printf("Case #%d: %d is a Happy number.\n",i,cp); else printf("Case #%d: %d is an Unhappy number.\n",i,cp); } } }
858d8594b6eecf91484ed2b59c4a8f0ff1b255dc
c4e6eff8b84cf9d0f236d250bbe330ae913b876e
/position.cpp
35bc2ed2e73692144b16fa0f7a60c873bd8a86c8
[ "Unlicense" ]
permissive
jeremimucha/sages_asciichess
df609f6586c85a0a56914eb2134aca5f0633159f
3005b345ced52992aadae60338dc1fe7b88b1d76
refs/heads/master
2023-05-10T22:44:15.268289
2019-09-11T13:35:29
2019-09-11T13:35:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
835
cpp
#include "position.hpp" #include "settings.hpp" #include <string> #include <stdexcept> #include <iostream> namespace { using namespace std::string_literals; inline unsigned col_index(char ch) { const unsigned result{ch - 'a'}; if (result > ChessboardWidth) { throw std::runtime_error{"Invalid column index"s + ch}; } return result; } } // namespace Position::Position(char col, unsigned row) : row_{row-1}, col_{col_index(col)} { if (row_ > ChessboardHeight) { throw std::runtime_error{"Invalid row index"s + std::to_string(row_)}; } std::cerr << __FUNCTION__ << ": row = " << row_ << ", col = " << col_ << "\n"; } std::pair<int, int> Position::compare(Position other) const noexcept { return {row_ - other.row_, col_ - other.col_}; }
51152feef6106fe78278594ef9b5da9d68e4d7a6
04b1803adb6653ecb7cb827c4f4aa616afacf629
/extensions/common/features/manifest_feature.cc
4d36d5278d161f4eb8ff2ec9da5e99da50c73802
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
1,239
cc
// Copyright 2014 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 "extensions/common/features/manifest_feature.h" #include "extensions/common/manifest.h" namespace extensions { ManifestFeature::ManifestFeature() { } ManifestFeature::~ManifestFeature() { } Feature::Availability ManifestFeature::IsAvailableToContext( const Extension* extension, Feature::Context context, const GURL& url, Feature::Platform platform) const { Availability availability = SimpleFeature::IsAvailableToContext(extension, context, url, platform); if (!availability.is_available()) return availability; // We know we can skip manifest()->GetKey() here because we just did the same // validation it would do above. if (extension && !extension->manifest()->value()->HasKey(name())) return CreateAvailability(NOT_PRESENT, extension->GetType()); return CreateAvailability(IS_AVAILABLE); } } // namespace extensions
8464bdbae789cd3a830de21970044b6bacef3752
ed5669151a0ebe6bcc8c4b08fc6cde6481803d15
/magma-1.5.0/testing/testing_dtrmm.cpp
64ccf3e189720050de0af7f446efa18a11c71407
[]
no_license
JieyangChen7/DVFS-MAGMA
1c36344bff29eeb0ce32736cadc921ff030225d4
e7b83fe3a51ddf2cad0bed1d88a63f683b006f54
refs/heads/master
2021-09-26T09:11:28.772048
2018-05-27T01:45:43
2018-05-27T01:45:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,456
cpp
/* -- MAGMA (version 1.5.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date September 2014 @generated from testing_ztrmm.cpp normal z -> d, Wed Sep 17 15:08:40 2014 @author Chongxiao Cao */ // includes, system #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <cuda_runtime_api.h> #include <cublas_v2.h> // includes, project #include "flops.h" #include "magma.h" #include "magma_lapack.h" #include "testings.h" /* //////////////////////////////////////////////////////////////////////////// -- Testing dtrmm */ int main( int argc, char** argv) { TESTING_INIT(); real_Double_t gflops, cublas_perf, cublas_time, cpu_perf, cpu_time; double cublas_error, Cnorm, work[1]; magma_int_t M, N; magma_int_t Ak; magma_int_t sizeA, sizeB; magma_int_t lda, ldb, ldda, lddb; magma_int_t ione = 1; magma_int_t ISEED[4] = {0,0,0,1}; double *h_A, *h_B, *h_Bcublas; double *d_A, *d_B; double c_neg_one = MAGMA_D_NEG_ONE; double alpha = MAGMA_D_MAKE( 0.29, -0.86 ); magma_int_t status = 0; magma_opts opts; parse_opts( argc, argv, &opts ); opts.lapack |= opts.check; // check (-c) implies lapack (-l) double tol = opts.tolerance * lapackf77_dlamch("E"); printf("If running lapack (option --lapack), CUBLAS error is computed\n" "relative to CPU BLAS result.\n\n"); printf("side = %s, uplo = %s, transA = %s, diag = %s \n", lapack_side_const(opts.side), lapack_uplo_const(opts.uplo), lapack_trans_const(opts.transA), lapack_diag_const(opts.diag) ); printf(" M N CUBLAS Gflop/s (ms) CPU Gflop/s (ms) CUBLAS error\n"); printf("==================================================================\n"); for( int itest = 0; itest < opts.ntest; ++itest ) { for( int iter = 0; iter < opts.niter; ++iter ) { M = opts.msize[itest]; N = opts.nsize[itest]; gflops = FLOPS_DTRMM(opts.side, M, N) / 1e9; if ( opts.side == MagmaLeft ) { lda = M; Ak = M; } else { lda = N; Ak = N; } ldb = M; ldda = ((lda+31)/32)*32; lddb = ((ldb+31)/32)*32; sizeA = lda*Ak; sizeB = ldb*N; TESTING_MALLOC_CPU( h_A, double, lda*Ak ); TESTING_MALLOC_CPU( h_B, double, ldb*N ); TESTING_MALLOC_CPU( h_Bcublas, double, ldb*N ); TESTING_MALLOC_DEV( d_A, double, ldda*Ak ); TESTING_MALLOC_DEV( d_B, double, lddb*N ); /* Initialize the matrices */ lapackf77_dlarnv( &ione, ISEED, &sizeA, h_A ); lapackf77_dlarnv( &ione, ISEED, &sizeB, h_B ); /* ===================================================================== Performs operation using CUBLAS =================================================================== */ magma_dsetmatrix( Ak, Ak, h_A, lda, d_A, ldda ); magma_dsetmatrix( M, N, h_B, ldb, d_B, lddb ); // note cublas does trmm out-of-place (i.e., adds output matrix C), // but allows C=B to do in-place. cublas_time = magma_sync_wtime( NULL ); cublasDtrmm( handle, cublas_side_const(opts.side), cublas_uplo_const(opts.uplo), cublas_trans_const(opts.transA), cublas_diag_const(opts.diag), M, N, &alpha, d_A, ldda, d_B, lddb, d_B, lddb ); cublas_time = magma_sync_wtime( NULL ) - cublas_time; cublas_perf = gflops / cublas_time; magma_dgetmatrix( M, N, d_B, lddb, h_Bcublas, ldb ); /* ===================================================================== Performs operation using CPU BLAS =================================================================== */ if ( opts.lapack ) { cpu_time = magma_wtime(); blasf77_dtrmm( lapack_side_const(opts.side), lapack_uplo_const(opts.uplo), lapack_trans_const(opts.transA), lapack_diag_const(opts.diag), &M, &N, &alpha, h_A, &lda, h_B, &ldb ); cpu_time = magma_wtime() - cpu_time; cpu_perf = gflops / cpu_time; } /* ===================================================================== Check the result =================================================================== */ if ( opts.lapack ) { // compute relative error for both magma & cublas, relative to lapack, // |C_magma - C_lapack| / |C_lapack| Cnorm = lapackf77_dlange( "M", &M, &N, h_B, &ldb, work ); blasf77_daxpy( &sizeB, &c_neg_one, h_B, &ione, h_Bcublas, &ione ); cublas_error = lapackf77_dlange( "M", &M, &N, h_Bcublas, &ldb, work ) / Cnorm; printf("%5d %5d %7.2f (%7.2f) %7.2f (%7.2f) %8.2e %s\n", (int) M, (int) N, cublas_perf, 1000.*cublas_time, cpu_perf, 1000.*cpu_time, cublas_error, (cublas_error < tol ? "ok" : "failed")); status += ! (cublas_error < tol); } else { printf("%5d %5d %7.2f (%7.2f) --- ( --- ) --- ---\n", (int) M, (int) N, cublas_perf, 1000.*cublas_time); } TESTING_FREE_CPU( h_A ); TESTING_FREE_CPU( h_B ); TESTING_FREE_CPU( h_Bcublas ); TESTING_FREE_DEV( d_A ); TESTING_FREE_DEV( d_B ); fflush( stdout ); } if ( opts.niter > 1 ) { printf( "\n" ); } } TESTING_FINALIZE(); return status; }
ac2faf44cd5f13ccb29355a347b7fbcd590995ed
5947865dc56dc2906951f21b780db5dc901848c5
/Practice/Maximum Tip Calculator.cpp
790d296abe23492d54dbe58c9d2f55a9b2f5414a
[]
no_license
nishu112/Geek-Codes
6d9cad76291d7c56900bd988c0c123db6d900c36
f7eece428655c1f656e402b321260f234de62153
refs/heads/master
2021-10-07T09:31:13.379816
2018-12-04T16:36:54
2018-12-04T16:36:54
121,122,751
0
0
null
null
null
null
UTF-8
C++
false
false
2,056
cpp
#include <bits/stdc++.h> using namespace std; class priorityStructure{ public: priorityStructure(int x,int y):index(x),diff(y){ } int index; int diff; }; bool operator<(const priorityStructure &l, const priorityStructure & r) { return l.diff < r.diff; } void solve(){ int n,X,Y; cin>>n>>X>>Y; vector<int> A(n),B(n); vector<int> visit(n,0);// i am storing the the waiter values in this 1 means 1st waiter and 2 means second waiter // initially put 0 in this for(int i=0;i<n;++i) cin>>A[i]; for(int i=0;i<n;++i) cin>>B[i]; priority_queue<priorityStructure> pq; for(int i=0;i<n;++i) pq.push(priorityStructure(i,abs(A[i]-B[i])));// insert all the index and corresponding absolute difference // i am using difference values to set maximum priority // max diff means max priority // so if we have 2 same corresponding values //then that index value have the lowest priorty (because we can choose any waiter for that because values are same while(!pq.empty() && X&& Y){ if(A[pq.top().index]<B[pq.top().index])//now for the max difference checking that from which array A or B we can get { //get max values visit[pq.top().index]=2; //we assign waiter 2 for pq.top().index (index) --Y;// decrement the number of orders a waiter can take because } else { visit[pq.top().index]=1;//same goes here --X; } pq.pop(); } while(X && !pq.empty())// case when number of orders for waiter B becomes 0 { visit[pq.top().index]=1;//keep assigning task to waiter 1 pq.pop(); --X; } while(Y && !pq.empty())//similar case { visit[pq.top().index]=2; pq.pop(); --Y; } int Ans=0; for(int i=0;i<n;++i)//now calculate total answer based on the data we stored in visit { if(visit[i]==1) Ans+=A[i]; else Ans+=B[i]; } cout<<Ans<<"\n"; } int main(int argc, char **argv) { //std::ios::sync_with_stdio(false); int t; cin>>t; while(t--) { solve(); } return 0; }
7e7dd6d093eb21d8ee026ac42b940f1766a70550
cf8ddfc720bf6451c4ef4fa01684327431db1919
/SDK/ARKSurvivalEvolved_DmgType_Phoenix_parameters.hpp
9d7351c187d53fede540ecf60649238e0faf1b66
[ "MIT" ]
permissive
git-Charlie/ARK-SDK
75337684b11e7b9f668da1f15e8054052a3b600f
c38ca9925309516b2093ad8c3a70ed9489e1d573
refs/heads/master
2023-06-20T06:30:33.550123
2021-07-11T13:41:45
2021-07-11T13:41:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
388
hpp
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_DmgType_Phoenix_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- } #ifdef _MSC_VER #pragma pack(pop) #endif
7118d203ce3359f20a924552088bf2cbc3c7996f
842fc50b0afcb643eacbc757eb5983ed2b38d991
/剑指 Offer 36. 二叉搜索树与双向链表/Offer_36.cpp
7daf2169d74c2bf49b344110e231ef8303335861
[]
no_license
Asutorufa/leetcode_practice
449fc545c100bd3d430df59dec11cb039db7a13b
481636ecd7a0b40224c388b81ce220daa7cdd24a
refs/heads/master
2020-11-27T03:30:50.227840
2020-10-01T12:19:11
2020-10-01T12:19:11
229,287,937
0
0
null
null
null
null
UTF-8
C++
false
false
5,729
cpp
#include <iostream> #include <vector> #include <queue> /** 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。 为了让您更好地理解问题,以下面的二叉搜索树为例: ![](https://assets.leetcode.com/uploads/2018/10/12/bstdlloriginalbst.png) 我们希望将这个二叉搜索树转化为双向循环链表。 链表中的每个节点都有一个前驱和后继指针。 对于双向循环链表,第一个节点的前驱是最后一个节点,最后一个节点的后继是第一个节点。 下图展示了上面的二叉搜索树转化成的链表。“head” 表示指向链表中有最小元素的节点。 ![](https://assets.leetcode.com/uploads/2018/10/12/bstdllreturndll.png) 特别地,我们希望可以就地完成转换操作。 当转化完成以后,树中节点的左指针需要指向前驱,树中节点的右指针需要指向后继。 还需要返回链表中的第一个节点的指针。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ /* // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node() {} Node(int _val) { val = _val; left = NULL; right = NULL; } Node(int _val, Node* _left, Node* _right) { val = _val; left = _left; right = _right; } }; */ class Node { public: int val; Node *left; Node *right; Node() {} Node(int _val) { val = _val; left = NULL; right = NULL; } Node(int _val, Node *_left, Node *_right) { val = _val; left = _left; right = _right; } static void print_link(Node *root) { while (root != NULL) { std::cout << root->val << " -> "; root = root->right; } std::cout << std::endl; } static void print_link2(Node *root) { while (root != NULL) { std::cout << root->val << " -> "; root = root->left; } std::cout << std::endl; } static void print_loop_link(Node *root) { if (root == NULL) return; int start = root->val; std::cout << root->val << " -> "; root = root->right; while (true) { if (root->val == start) break; std::cout << root->val << " -> "; root = root->right; } std::cout << "loop -> "; start = root->val; std::cout << root->val << " -> "; root = root->left; while (true) { if (root->val == start) break; std::cout << root->val << " -> "; root = root->left; } std::cout << std::endl; } }; class Solution { public: Node *pre, *head; Node *treeToDoublyList(Node *root) { if (root == NULL) return NULL; pre = NULL, head = NULL; // make pre and head is NULL at start trans(root); head->left = pre; pre->right = head; return head; } void trans(Node *root) { if (root == NULL) { return; } trans(root->left); if (pre != NULL) pre->right = root; else head = root; root->left = pre; pre = root; trans(root->right); } }; class CreateTree { public: static Node *create(std::vector<int> a, int k) { if (a.size() == 0 || a.size() - 1 < k) { return NULL; } if (a[k] == 0) { return NULL; } // std::cout << a[k] << std::endl; Node *root = new Node(a[k]); root->left = create(a, k * 2 + 1); root->right = create(a, k * 2 + 2); return root; } static void print_tree(Node *root) { if (root == NULL) { return; } std::cout << root->val << " -> "; print_tree(root->left); print_tree(root->right); } static void pre_print(Node *root) { if (root == NULL) { return; } pre_print(root->left); std::cout << root->val << " -> "; pre_print(root->right); } static void level_print(Node *root) { std::queue<Node *> qu; qu.push(root); while (true) { int l = qu.size(); if (l == 0) { break; } // std::cout << "queue size: " << l << std::endl; for (int i = 0; i < l; i++) { Node *tmp = qu.front(); qu.pop(); std::cout << tmp->val << " -> "; if (tmp->left != NULL) { qu.push(tmp->left); } if (tmp->right != NULL) { qu.push(tmp->right); } } } std::cout << std::endl; } }; int main() { std::vector<int> x = {4, 2, 5, 1, 3}; Solution s = Solution(); s.trans(CreateTree::create(x, 0)); Node::print_link(s.head); Node::print_link2(s.pre); Node::print_loop_link(s.treeToDoublyList(CreateTree::create(x, 0))); std::vector<int> x2 = {4, 6, 5, 1, 3}; Node::print_loop_link(s.treeToDoublyList(CreateTree::create(x2, 0))); return 0; }
6cca8686992450a2cbbcc743cc0e38b67ab52fdb
9a3fd403e16941232f9d48c837ebe494b5f34023
/Source/cmPropertyDefinitionMap.cxx
822f061cad3c6665ae0b49423f778a1e21d2f33f
[ "BSD-3-Clause" ]
permissive
AnomalousMedical/CMake-OldFork
9f7735199073525ab5f6b9074829af4abffac65b
1bf1d8d1c8de2f7156a47ecf883408574c031ac1
refs/heads/master
2021-06-11T11:15:48.950407
2017-03-11T17:07:10
2017-03-11T17:07:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,641
cxx
/*============================================================================ CMake - Cross Platform Makefile Generator Copyright 2000-2009 Kitware, Inc., Insight Software Consortium Distributed under the OSI-approved BSD License (the "License"); see accompanying file Copyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more information. ============================================================================*/ #include "cmPropertyDefinitionMap.h" #include "cmSystemTools.h" #include "cmDocumentationSection.h" void cmPropertyDefinitionMap ::DefineProperty(const std::string& name, cmProperty::ScopeType scope, const char *ShortDescription, const char *FullDescription, bool chain) { cmPropertyDefinitionMap::iterator it = this->find(name); cmPropertyDefinition *prop; if (it == this->end()) { prop = &(*this)[name]; prop->DefineProperty(name,scope,ShortDescription, FullDescription, chain); } } bool cmPropertyDefinitionMap::IsPropertyDefined(const std::string& name) { cmPropertyDefinitionMap::iterator it = this->find(name); if (it == this->end()) { return false; } return true; } bool cmPropertyDefinitionMap::IsPropertyChained(const std::string& name) { cmPropertyDefinitionMap::iterator it = this->find(name); if (it == this->end()) { return false; } return it->second.IsChained(); }
[ "AndrewPiper@7b0d72ad-f3cb-b44e-b30e-0ca2391ac3a1" ]
AndrewPiper@7b0d72ad-f3cb-b44e-b30e-0ca2391ac3a1
7aabde2f3416cde930891a0a3846c2d1f05f6861
84dfcf83442e80a683d1731d51505b373dce742d
/program1/main.cpp
832d72719a25200232a705f05fde811f181d3175
[]
no_license
cliffordkallem/CSCI441
e2d577cdd41bdb5efc5a01646e7ce1ae5fd54af0
c35bf9428917e51673251365635fc808d5f529f0
refs/heads/master
2021-01-19T10:59:34.767292
2015-03-25T14:35:15
2015-03-25T14:35:15
32,869,766
0
0
null
null
null
null
UTF-8
C++
false
false
455
cpp
#include <QApplication> #include "glwidget.h" int main(int argc, char** argv) { QApplication a(argc, argv); QSurfaceFormat format; format.setVersion(3,3); format.setProfile(QSurfaceFormat::CoreProfile); QSurfaceFormat::setDefaultFormat(format); GLWidget glWidget; glWidget.resize(640,480); glWidget.show(); if(argc >2) { glWidget.in = argv[1]; glWidget.input = true; } return a.exec(); }
fcf364b099f6158ef5ae07b226c0e5a13e71cc56
59e17bb252450b391d0de4e0732f6ebd5c31cf8a
/1080. Max Area of Island/1080. Max Area of Island.cpp
48940a47aa40087ae833b7d0cddfe31c9759eb4f
[ "Apache-2.0" ]
permissive
YaoPengCN/MyLintCodeSolutions
b4960643cc8c4da4ef6c17157e3171d10c609fa1
a04c60c2988efa4a55532192ee5126b1d35255f1
refs/heads/master
2021-06-14T10:04:33.829920
2021-03-05T01:36:51
2021-03-05T01:36:51
159,300,765
0
0
null
null
null
null
UTF-8
C++
false
false
1,881
cpp
/** * 1080. Max Area of Island * Difficulty * Easy * * Description * Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical). * You may assume all four edges of the grid are surrounded by water. * Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.) * * Clarification * The size() of each dimension in the given grid does not exceed 50. * * Example * Example 1 * input: * [[0,0,1,0,0,0,0,1,0,0,0,0,0], * [0,0,0,0,0,0,0,1,1,1,0,0,0], * [0,1,1,0,1,0,0,0,0,0,0,0,0], * [0,1,0,0,1,1,0,0,1,0,1,0,0], * [0,1,0,0,1,1,0,0,1,1,1,0,0], * [0,0,0,0,0,0,0,0,0,0,1,0,0], * [0,0,0,0,0,0,0,1,1,1,0,0,0], * [0,0,0,0,0,0,0,1,1,0,0,0,0]] * output: * 6 * Explanation: * Note the answer is not 11, because the island must be connected 4-directionally. * * Example 2 * input: [[0,0,0,0,0,0,0,0]] * output: 0 * * Related Problems * 1225. Island Perimeter * */ /** * DFS * Running Time: 50ms */ class Solution { public: /** * @param grid: a 2D array * @return: the maximum area of an island in the given 2D array */ int maxAreaOfIsland(vector<vector<int>> &grid) { int maxArea = 0; for (int i = 0; i != grid.size(); i++) for (int j = 0; j != grid[i].size(); j++) if (grid[i][j] == 1) maxArea = max(maxArea, dfs(grid, i, j)); return maxArea; } private: int dfs(vector<vector<int>> &grid, int i, int j) { int currentArea = 0; if (i < 0 || i >= grid.size() || j < 0 || j >= grid[i].size() || grid[i][j] == 0) { return 0; } else { currentArea = 1; grid[i][j] = 0; currentArea += dfs(grid, i + 1, j); currentArea += dfs(grid, i - 1, j); currentArea += dfs(grid, i, j + 1); currentArea += dfs(grid, i, j - 1); } return currentArea; } };
26780de793fd6840efbf92b43c7fe459217520e4
37596f223cf5115178a5a218fecf422bc545de78
/lucky number.cpp
24a44684541cb02e74273909c7f7c69063b15918
[]
no_license
fahim-ahmed-7861/competitive-programming
85cc4a61ce643d07446c36848b1f55789ee978f3
7c3e649756a426cceb588b5b119d40a5a94c80b4
refs/heads/master
2022-12-31T10:45:15.798645
2020-10-21T14:37:38
2020-10-21T14:37:38
306,051,853
0
0
null
null
null
null
UTF-8
C++
false
false
1,799
cpp
/* -ensure correct output format -ensure printing required output -reread the problem statement */ #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<ll,ll>pll; typedef pair<ll,pair<ll,ll>>plll; #define fastread() (ios_base:: sync_with_stdio(false),cin.tie(NULL)); #define vll(v) v.begin(),v.end() #define all(x) x.rbegin(),x.rend() #define min3(a, b, c) min(a, min(b, c)) #define max3(a, b, c) max(a, max(b, c)) #define F first #define S second #define in freopen("input.txt", "r", stdin) #define out freopen("output.txt", "w", stdout) #define minheap int,vector<int>,greater<int> #define pb push_back #define eb emplace_back #define ischar(x) (('a' <= x && x <= 'z') || ('A' <= x && x <= 'Z')) #define isvowel(ch) ((ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')||(ch=='A'|| ch=='E' || ch=='I'|| ch=='O'|| ch=='U')) #define bug cout<<"BUG"<<endl; const int Max = 2e6 + 10; const int Mod = 1e9 + 7; const double PI =3.141592653589793238463; bool compare(const pair<ll,ll> &a, const pair<ll,ll> &b) { return (a.first > b.first); } ll lcm(ll a,ll b) { if(a==0 || b==0)return 0; return a/__gcd(a,b)*b; } void input(ll ara[],ll n) { for(ll i=0; i<n; i++)cin>>ara[i]; } void print(ll ara[],ll n) { for(ll i=0; i<n; i++) cout<<ara[i]<<" "; cout<<endl; } bool islucky(ll n,ll cnt) { if(cnt>n)return true; if(n%cnt==0)return false; n-=(n/cnt); cnt++; return islucky(n,cnt); } int main() { fastread(); ll i,j,n,m,p,a,sum=0,k,t,b,c,d,cnt=0,q,l,r,ans=0; bool flag=false; string str; for(n=1; n<=100; n++){ if(islucky(n,2)) cout<<n<<" YES"<<endl; // else cout<<n<<" NO"<<endl; } }
dc5d79c0d62a230295528813b63d3a0bb316b8c3
c2b161ce52e127f7036882f0ffa523f520dc1c87
/programs/tests/serial_setdtr.cpp
43e4524577c96bc9789015d0085503538b2d05cf
[]
no_license
dmosher42/cosmos-core
9991e7268044fa3b139716a48e3bf3c707ea3422
625d1de84eded5ff69b2870a9cbf57c1a6476f89
refs/heads/master
2023-03-21T17:26:05.288081
2021-01-28T00:12:33
2021-01-28T00:12:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
780
cpp
#include "support/configCosmos.h" #include "device/serial/serialclass.h" #include "support/elapsedtime.h" int main(int argc, char *argv[]) { // bool xonxoff = false; // bool rtscts = false; string name = "/dev/ttyUSB0"; int32_t baud = 115200; size_t parity = 0; size_t bits = 8; size_t stop = 1; bool dtr_state = false; double wait_time = 0.; switch (argc) { case 4: wait_time = atof(argv[3]); case 3: if (!strcmp(argv[2], "on")) { dtr_state = true; } else { dtr_state = false; } case 2: name = argv[1]; } Serial *port = new Serial(name, baud, bits, parity, stop); port->set_dtr(dtr_state); COSMOS_SLEEP(wait_time); }
f662158e5ccb7a8f22c1bb2964685abe05d8267c
371decee2d9e210f1cb1f6e38136b5bd83ce120a
/array/026.cpp
99b356983c7731f99783303b1fd2c80e64c386a1
[ "MIT" ]
permissive
aayushgoyal/Programming-Puzzles
0c8ec14b5e523dca9da4b71f6a1544732805aaed
d20899e9edc77bed0884921f0ce7ccb946e0bbad
refs/heads/master
2020-12-03T00:10:02.209255
2016-10-01T13:20:02
2016-10-01T13:20:02
95,995,548
1
0
null
2017-07-02T01:16:49
2017-07-02T01:16:49
null
UTF-8
C++
false
false
754
cpp
// Maximum element in the array which is first increasing and then decreasing #include <iostream> #include <vector> using namespace std; int _findMax(const vector<int> &a,int low,int high) { if(low == high) return low; if(high == low+1) { if(a[low] > a[high]) return low; else return high; } int mid = low + (high-low)/2; if(a[mid] > a[mid+1] && a[mid] > a[mid-1]) return mid; else if(a[mid]>a[mid+1] && a[mid]<a[mid-1]) return _findMax(a,low,mid-1); else if(a[mid]<a[mid+1] && a[mid]>a[mid-1]) return _findMax(a,mid+1,high); } int findMax(const vector<int> &a) { if(a.size() == 0) return -1; return _findMax(a,0,a.size()-1); } int main() { vector<int> a = {1,2,3,4,5,3,2,1}; cout << findMax(a) << "\n"; return 0; }
64d65fc32e80f07671b0545e01f3c3c64f23b901
916ef1b31f0b683de4f043626d9df59f37edbbc4
/atcoder/03_Educational-DP-Contest/D-Knapsack1/D_002.cpp
b8254e97a2cb57ea861d038283b490b8f1b16804
[]
no_license
solareenlo/cpp
56cc33673d30dd4a4031e4b81cec16b08b3490e0
f78f8a098849938153e6e3a282737e067dbe2c58
refs/heads/master
2021-03-31T04:31:39.420394
2020-11-29T22:22:25
2020-11-29T22:22:25
248,076,420
0
0
null
null
null
null
UTF-8
C++
false
false
647
cpp
#include <bits/stdc++.h> #define REP(i, n) for (int i = 0; i < (n); i++) using namespace std; using ll = long long; template<class T> inline bool chmax(T &a, T b) { if (a < b) a = b; return true; return false; } int main() { cin.tie(0); ios::sync_with_stdio(false); int N, W; cin >> N >> W; vector<int> w(N), v(N); REP(i, N) cin >> w[i] >> v[i]; vector<vector<ll> > dp(N + 1, vector<ll>(W + 1, 0)); REP(i, N) REP(j, W + 1) { if (j - w[i] >= 0) chmax(dp[i + 1][j], dp[i][j - w[i]] + v[i]); chmax(dp[i + 1][j], dp[i][j]); } cout << dp[N][W] << '\n'; return 0; }
39e36822d68e6fd4a554124385d7fd43d4631f04
e682c542cb4a5f117293d82efb511ddfa42517fc
/codeforces/presents.cpp
cacac8ddd6cca46538c99106a76b9f8bf0a404a6
[]
no_license
jssosa10/maratones
d7d6b45712444d256d9c9e68d5cccca741f54fa9
44b6aca9e727e557f0224ff314c9ba2369217721
refs/heads/master
2021-01-20T02:48:02.723147
2018-03-21T16:34:58
2018-03-21T16:34:58
101,334,745
1
0
null
null
null
null
UTF-8
C++
false
false
502
cpp
/* * I won't be broken * I won't be tortured * I won't be beaten down * I have the answer * I can take the pressure * I will turn it all around * Lift me up above this * The flames and the ashes * Lift me up and help me to fly away */ #include <bits/stdc++.h> using namespace std; int n,a[105],b[105]; int main(){ scanf("%d",&n); for(int i = 0; i<n; i++){ scanf("%d",a+i); b[a[i]-1]=i+1; } printf("%d",b[0]); for(int i = 1; i<n;i++) printf(" %d",b[i]); printf("\n"); return 0; }
6f7924c4e087eea538952a5bd256692e35f2fd3b
434de139eabf2f592640c634c8380e08b78edff5
/Game/include/Components/BombTicker.hpp
521c77da7fffebfaec6c7562c895178f69ec8ecd
[]
no_license
victorneuret/OOP_indie_studio_2018
daa6de594050400ff03463b54930633ab205fe84
cba7a64d01b3a0a86df898f6b83619573aafd87a
refs/heads/master
2020-05-21T07:17:48.294564
2019-06-16T21:11:53
2019-06-16T21:11:53
185,955,289
0
2
null
null
null
null
UTF-8
C++
false
false
418
hpp
/* ** EPITECH PROJECT, 2019 ** bomberman ** File description: ** BombTicking.hpp */ #pragma once #include "ECS/Abstracts/ASystem.hpp" namespace Game::System { class BombTicker; } class Game::System::BombTicker : public Engine::ECS::ASystem { public: BombTicker(); BombTicker(const BombTicker &) = delete; BombTicker &operator=(const BombTicker &) = delete; void update(double dt) override; };
3e12b62540f813ccda8468f0764bf7fc1d16bee4
43888f81dac0d6dc55156c22e1235ffa34d37e8c
/Source/ShootThemUp/Private/Player/STUPlayerCharacter.cpp
fc2f84ddf2de94a399a95e3449c22b26451f5ad7
[]
no_license
RuslanArk/Shooter-Studying
4f879863d1605535e8e3dbdfe98af285923bc8f6
010d2123bc766f6b385b5a2b9e578608bf0aa679
refs/heads/master
2023-08-03T02:53:38.028744
2021-09-25T07:21:01
2021-09-25T07:21:01
369,518,577
1
0
null
null
null
null
UTF-8
C++
false
false
4,842
cpp
// Shoot Them Up, All right Reserved #include "Player/STUPlayerCharacter.h" #include "Camera/CameraComponent.h" #include "Components/CapsuleComponent.h" #include "Components/InputComponent.h" #include "Components/SphereComponent.h" #include "GameFramework/SpringArmComponent.h" #include "Components/STUWeaponComponent.h" ASTUPlayerCharacter::ASTUPlayerCharacter(const FObjectInitializer& ObjInit) : Super(ObjInit) { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; SpringArmComponent = CreateDefaultSubobject<USpringArmComponent>("SpringArmComponent"); SpringArmComponent->SetupAttachment(GetRootComponent()); SpringArmComponent->bUsePawnControlRotation = true; SpringArmComponent->SocketOffset = FVector(0.0f, 100.f, 80.f); CameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComponent")); CameraComponent->SetupAttachment(SpringArmComponent); CameraCollisionComponent = CreateDefaultSubobject<USphereComponent>("CameraCollisionComponent"); CameraCollisionComponent->SetupAttachment(CameraComponent); CameraCollisionComponent->SetSphereRadius(10.0f); CameraCollisionComponent->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Overlap); } void ASTUPlayerCharacter::BeginPlay() { Super::BeginPlay(); check(CameraCollisionComponent); CameraCollisionComponent->OnComponentBeginOverlap.AddDynamic(this, &ASTUPlayerCharacter::OnCameraCollisionBeginOverlap); CameraCollisionComponent->OnComponentEndOverlap.AddDynamic(this, &ASTUPlayerCharacter::OnCameraCollisionEndOverlap); } void ASTUPlayerCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); check(PlayerInputComponent); check(WeaponComponent); PlayerInputComponent->BindAxis("MoveForward", this, &ASTUPlayerCharacter::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &ASTUPlayerCharacter::MoveRight); PlayerInputComponent->BindAxis("LookUp", this, &ASTUBaseCharacter::AddControllerPitchInput); PlayerInputComponent->BindAxis("TurnAround", this, &ASTUBaseCharacter::AddControllerYawInput); PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ASTUPlayerCharacter::Jump); PlayerInputComponent->BindAction("Run", IE_Pressed, this, &ASTUPlayerCharacter::OnStartRunning); PlayerInputComponent->BindAction("Run", IE_Released, this, &ASTUPlayerCharacter::OnStopRunning); PlayerInputComponent->BindAction("Fire", IE_Pressed, WeaponComponent, &USTUWeaponComponent::StartFire); PlayerInputComponent->BindAction("Fire", IE_Released, WeaponComponent, &USTUWeaponComponent::StopFire); PlayerInputComponent->BindAction("NextWeapon", IE_Pressed, WeaponComponent, &USTUWeaponComponent::NextWeapon); PlayerInputComponent->BindAction("Reload", IE_Pressed, WeaponComponent, &USTUWeaponComponent::Reload); DECLARE_DELEGATE_OneParam(FZoomInputSignature, bool); PlayerInputComponent->BindAction<FZoomInputSignature>("Zoom", IE_Pressed, WeaponComponent, &USTUWeaponComponent::Zoom, true); PlayerInputComponent->BindAction<FZoomInputSignature>("Zoom", IE_Released, WeaponComponent, &USTUWeaponComponent::Zoom, false); } void ASTUPlayerCharacter::MoveForward(float Amount) { bIsMovingForward = Amount > 0.0f; if (Amount == 0.0f) return; AddMovementInput(GetActorForwardVector(), Amount); } void ASTUPlayerCharacter::MoveRight(float Amount) { if (Amount == 0.0f) return; AddMovementInput(GetActorRightVector(), Amount); } void ASTUPlayerCharacter::OnStartRunning() { bRunning = true; } void ASTUPlayerCharacter::OnStopRunning() { bRunning = false; } bool ASTUPlayerCharacter::IsRunning() const { return bIsMovingForward && bRunning && !GetVelocity().IsZero(); } void ASTUPlayerCharacter::OnDeath() { Super::OnDeath(); if (Controller) { Controller->ChangeState(NAME_Spectating); } } void ASTUPlayerCharacter::OnCameraCollisionBeginOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { CheckCameraOverlap(); } void ASTUPlayerCharacter::OnCameraCollisionEndOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex) { CheckCameraOverlap(); } void ASTUPlayerCharacter::CheckCameraOverlap() { const bool HideMesh = CameraCollisionComponent->IsOverlappingComponent(GetCapsuleComponent()); GetMesh()->SetOwnerNoSee(HideMesh); TArray<USceneComponent*> MeshChildren; GetMesh()->GetChildrenComponents(true, MeshChildren); for (auto MeshChild : MeshChildren) { const auto MeshChildGeometry = Cast<UPrimitiveComponent>(MeshChild); if (MeshChildGeometry) { MeshChildGeometry->SetOwnerNoSee(HideMesh); } } }
f937a0554e18e42f85196f711461432e5405f171
bd6156f4844b860d47b6e50e7a4d7021cdc0ce02
/TdP2/client/src/CaricaGiocoDialog.cpp
802063c75508b5deb42f844ce3509708f3250162
[]
no_license
matteosan1/workspace
e178c9843e62d78762420c217bc603819dc96b10
f9a2dedfb821b889d037f7642fa5e2cb581b4779
refs/heads/master
2021-07-20T04:26:40.187162
2021-06-24T20:13:46
2021-06-24T20:13:46
149,867,932
0
0
null
null
null
null
UTF-8
C++
false
false
1,649
cpp
#include "CaricaGiocoDialog.h" #include <QMessageBox> CaricaGiocoDialog::CaricaGiocoDialog(QStringList nomi, QStringList date, QWidget* parent) : QDialog(parent), n(nomi), d(date) { ui.setupUi(this); ui.tableFile->setRowCount(n.size()); ui.tableFile->setColumnCount(2); ui.tableFile->setEditTriggers(QAbstractItemView::NoEditTriggers); ui.tableFile->setSelectionBehavior(QAbstractItemView::SelectRows); ui.tableFile->setSelectionMode(QAbstractItemView::SingleSelection); QStringList headerLabels; headerLabels << "Nome" << "Data Creazione"; ui.tableFile->setHorizontalHeaderLabels(headerLabels); populateTable(); ui.tableFile->resizeColumnsToContents(); //ui.cavalliView->resize(500, 300); // ui.tableFile->show(); connect(ui.tableFile, SIGNAL(itemSelectionChanged()), this,SLOT(enableButton())); connect(ui.caricaButton, SIGNAL(clicked()), this, SLOT(load())); connect(ui.cancellaButton, SIGNAL(clicked()), this, SLOT(esci())); } void CaricaGiocoDialog::load() { QDialog::done(2); } void CaricaGiocoDialog::esci() { QDialog::done(3); } void CaricaGiocoDialog::populateTable() { for(int i=0; i<n.size(); ++i) { QTableWidgetItem* item0 = new QTableWidgetItem(n[i]); QTableWidgetItem* item1 = new QTableWidgetItem(d[i]); ui.tableFile->setItem(i, 0, item0); ui.tableFile->setItem(i, 1, item1); } } CaricaGiocoDialog::~CaricaGiocoDialog() {} void CaricaGiocoDialog::enableButton() { ui.caricaButton->setEnabled(true); } int CaricaGiocoDialog::getSelection() { int result = ui.tableFile->currentRow(); return result; }
2b4a318054c712211900edd9bf734b787bb42f23
e5bf87d662451ff0de4bcd7d4290501e4562f2d6
/include/tape.hpp
4bf6afdb869ec84c63f5fedbef5c983f799742fd
[]
no_license
alu0101133201/TuringMachine
7d50292058080cf05392725b118b0660ad59a222
f3e4400a8d2b238ba330bdea7f1e0226c88ec8b5
refs/heads/master
2023-01-08T22:51:12.529893
2020-11-13T22:45:09
2020-11-13T22:45:09
309,473,932
0
0
null
null
null
null
UTF-8
C++
false
false
589
hpp
/** * Fichero que define la clase cinta * ULL - Complejidad Computaciones * Sergio Guerra Arencibia * 02/11/2020 */ #pragma once #include <vector> #include <iostream> #include <string> class Tape { private: std::vector<std::string> symbols; int head; public: Tape(); ~Tape(); void loadStrings(std::vector<std::string> stringsToLoad, std::string white); void moveRight(void); void moveLeft(void); std::string getSymbol(void); int getCurrentSize(void); void writeSymbol(std::string symb); std::ostream& write(std::ostream &os); };
eea5e912a02b7c1fc4ef76be2da985c959e408a9
6075861fe269c3fa3967ed96be8ee32d98a797dd
/Source/FPSGame/Private/LaunchPadActor.cpp
8108e161f9958c7620b625eb71c5513e451467f2
[]
no_license
darioslave1/UE4Templates
9f7b7203d40720a7c10d91eef57d5b52713f86eb
f9f1726d73f91e3df59635df6c20e5440b8a15c3
refs/heads/master
2021-09-07T15:11:02.476765
2018-02-24T18:06:23
2018-02-24T18:06:23
116,733,498
1
0
null
null
null
null
UTF-8
C++
false
false
1,796
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "LaunchPadActor.h" #include "Components/BoxComponent.h" #include "Components/StaticMeshComponent.h" #include "GameFramework/Character.h" #include "Particles/ParticleSystem.h" #include "Kismet/GameplayStatics.h" // Sets default values ALaunchPadActor::ALaunchPadActor() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; LaunchPadMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("LaunchPadMesh")); RootComponent = LaunchPadMesh; CollisionBox = CreateDefaultSubobject<UBoxComponent>(TEXT("Collision")); CollisionBox->SetupAttachment(RootComponent); CollisionBox->OnComponentBeginOverlap.AddDynamic(this, &ALaunchPadActor::LaunchActor); LaunchStrenght = 2000.f; LaunchPitch = 45.f; } // Called when the game starts or when spawned void ALaunchPadActor::BeginPlay() { Super::BeginPlay(); } void ALaunchPadActor::LaunchActor(UPrimitiveComponent * OverlappedComponent, AActor * OtherActor, UPrimitiveComponent * OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult) { FRotator Rot = LaunchPadMesh->GetComponentRotation() + FRotator(LaunchPitch, 0.f, 0.f); FVector Impulse(Rot.Vector() * LaunchStrenght); ACharacter* Character = Cast<ACharacter>(OtherActor); if (Character) { Character->LaunchCharacter(Impulse, true, true); UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), LaunchParticleEffect, Character->GetActorLocation()); } else { if (OtherComp->IsSimulatingPhysics()) { OtherComp->AddImpulse(Impulse, NAME_None, true); } } } // Called every frame void ALaunchPadActor::Tick(float DeltaTime) { Super::Tick(DeltaTime); }
bb66c7985ffd9597e18e00b8beecdc54867b2d96
bcaf817dbcf3510252b634b8c90f123e6b056121
/src-qdbf/qdbffield.h
ae049edbb0084767ac786ddb9ae3e25531f4b351
[]
no_license
tianyayouge/keme5
16ba5dbc8b33f2f8af3002f4760a329954b11fc0
b0e4d39c359a925328d6da0df1b69fd889ed7d3d
refs/heads/master
2023-05-07T13:02:59.544384
2018-09-16T16:53:11
2018-09-16T16:55:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,729
h
#ifndef QDBFFIELD_H #define QDBFFIELD_H #include "qdbf_global.h" #include <QtCore/QVariant> namespace QDbf { namespace Internal { class QDbfFieldPrivate; class QDbfTablePrivate; } class QDBF_EXPORT QDbfField { public: QDbfField(const QString &fieldName = QString::null, QVariant::Type type = QVariant::Invalid); QDbfField(const QDbfField &other); bool operator==(const QDbfField &other) const; inline bool operator!=(const QDbfField &other) const { return !operator==(other); } QDbfField &operator=(const QDbfField &other); ~QDbfField(); enum QDbfType { UnknownDataType = -1, Character, Date, FloatingPoint, Logical, //Memo, Number }; void setValue(const QVariant &value); inline QVariant value() const { return val; } void setName(const QString &name); QString name() const; bool isNull() const; void setReadOnly(bool readOnly); bool isReadOnly() const; void clear(); void setType(QVariant::Type type); QVariant::Type type() const; void setQDbfType(QDbfType type); QDbfType dbfType() const; void setLength(int fieldLength); int length() const; void setPrecision(int precision); int precision() const; void setOffset(int offset); int offset() const; void setDefaultValue(const QVariant &value); QVariant defaultValue() const; private: Internal::QDbfFieldPrivate *d; QVariant val; void detach(); friend class Internal::QDbfTablePrivate; }; } // namespace QDbf QDebug operator<<(QDebug, const QDbf::QDbfField&); #endif // QDBFFIELD_H
a72aa5eff6baaf390dbac98566d4b0920fa45f55
e987e9ad77ed0c04546ecbe039e221a4c466c299
/CSIDevDocs/code-snippets/example2.cpp
c4228a55a8e967716a13b246c151e906cc75aae2
[ "CC-BY-4.0", "MIT" ]
permissive
isabella232/DevRelAXEValidationsPPEv3
034d6c135227674c9de64c916a4b9093280658d3
3ffb3c3e0f8753588048218ff18ef8678cd17ab6
refs/heads/master
2022-12-18T15:58:29.795546
2020-09-25T18:26:10
2020-09-25T18:26:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,164
cpp
//<Snippet1> using namespace System; using namespace System::Collections::Generic; public ref class Example { public: static void Main() { //<Snippet2> // Create a new dictionary of strings, with string keys, // and access it through the IDictionary generic interface. IDictionary<String^, String^>^ openWith = gcnew Dictionary<String^, String^>(); // Add some elements to the dictionary. There are no // duplicate keys, but some of the values are duplicates. openWith->Add("txt", "notepad.exe"); openWith->Add("bmp", "paint.exe"); openWith->Add("dib", "paint.exe"); openWith->Add("rtf", "wordpad.exe"); // The Add method throws an exception if the new key is // already in the dictionary. try { openWith->Add("txt", "winword.exe"); } catch (ArgumentException^) { Console::WriteLine("An element with Key = \"txt\" already exists."); } //</Snippet2> //<Snippet3> // The Item property is another name for the indexer, so you // can omit its name when accessing elements. Console::WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]); // The indexer can be used to change the value associated // with a key. openWith["rtf"] = "winword.exe"; Console::WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]); // If a key does not exist, setting the indexer for that key // adds a new key/value pair. openWith["doc"] = "winword.exe"; //</Snippet3> //<Snippet4> // The indexer throws an exception if the requested key is // not in the dictionary. try { Console::WriteLine("For key = \"tif\", value = {0}.", openWith["tif"]); } catch (KeyNotFoundException^) { Console::WriteLine("Key = \"tif\" is not found."); } //</Snippet4> //<Snippet5> // When a program often has to try keys that turn out not to // be in the dictionary, TryGetValue can be a more efficient // way to retrieve values. String^ value = ""; if (openWith->TryGetValue("tif", value)) { Console::WriteLine("For key = \"tif\", value = {0}.", value); } else { Console::WriteLine("Key = \"tif\" is not found."); } //</Snippet5> //<Snippet6> // ContainsKey can be used to test keys before inserting // them. if (!openWith->ContainsKey("ht")) { openWith->Add("ht", "hypertrm.exe"); Console::WriteLine("Value added for key = \"ht\": {0}", openWith["ht"]); } //</Snippet6> //<Snippet7> // When you use foreach to enumerate dictionary elements, // the elements are retrieved as KeyValuePair objects. Console::WriteLine(); for each( KeyValuePair<String^, String^> kvp in openWith ) { Console::WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } //</Snippet7> //<Snippet8> // To get the values alone, use the Values property. ICollection<String^>^ icoll = openWith->Values; // The elements of the ValueCollection are strongly typed // with the type that was specified for dictionary values. Console::WriteLine(); for each( String^ s in icoll ) { Console::WriteLine("Value = {0}", s); } //</Snippet8> //<Snippet9> // To get the keys alone, use the Keys property. icoll = openWith->Keys; // The elements of the ValueCollection are strongly typed // with the type that was specified for dictionary values. Console::WriteLine(); for each( String^ s in icoll ) { Console::WriteLine("Key = {0}", s); } //</Snippet9> //<Snippet10> // Use the Remove method to remove a key/value pair. Console::WriteLine("\nRemove(\"doc\")"); openWith->Remove("doc"); if (!openWith->ContainsKey("doc")) { Console::WriteLine("Key \"doc\" is not found."); } //</Snippet10> } }; int main() { Example::Main(); } /* This code example produces the following output: An element with Key = "txt" already exists. For key = "rtf", value = wordpad.exe. For key = "rtf", value = winword.exe. Key = "tif" is not found. Key = "tif" is not found. Value added for key = "ht": hypertrm.exe Key = txt, Value = notepad.exe Key = bmp, Value = paint.exe Key = dib, Value = paint.exe Key = rtf, Value = winword.exe Key = doc, Value = winword.exe Key = ht, Value = hypertrm.exe Value = notepad.exe Value = paint.exe Value = paint.exe Value = winword.exe Value = winword.exe Value = hypertrm.exe Key = txt Key = bmp Key = dib Key = rtf Key = doc Key = ht Remove("doc") Key "doc" is not found. */ //</ Snippet1 >
3db922da612da7a9a4b1a3574ba823d0552a33ad
7e23d9464639a2188e92cde1e7dc13e2e38d811e
/Examples/Chap05/5.4_SobelExample.cpp
5dae4e42cb567c6159611943f478f413969ecded
[]
no_license
zzudianzi/VTK
60911e617c498cdfea20fa693b08e24ff513d6b0
2730d2e8c144b3e09f64c4c9603dbe18b1535619
refs/heads/master
2021-01-01T17:44:54.172765
2017-07-24T10:20:16
2017-07-24T10:20:16
98,145,686
2
1
null
null
null
null
GB18030
C++
false
false
5,012
cpp
/********************************************************************** 文件名: 5.4_SobelExample.cpp Copyright (c) 张晓东, 罗火灵. All rights reserved. 更多信息请访问: http://www.vtkchina.org (VTK中国) http://blog.csdn.net/www_doling_net (东灵工作室) **********************************************************************/ #include <vtkSmartPointer.h> #include <vtkImageMathematics.h> #include <vtkImageData.h> #include <vtkImageSobel2D.h> #include <vtkImageMagnitude.h> #include <vtkImageExtractComponents.h> #include <vtkImageShiftScale.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkInteractorStyleImage.h> #include <vtkRenderer.h> #include <vtkImageActor.h> #include <vtkJPEGReader.h> //测试图像:../data/lena-gray.jpg int main(int argc, char* argv[]) { if (argc < 2) { std::cout<<argv[0]<<" "<<"ImageFile(*.jpg)"<<std::endl; return EXIT_FAILURE; } vtkSmartPointer<vtkJPEGReader> reader = vtkSmartPointer<vtkJPEGReader>::New(); reader->SetFileName(argv[1]); reader->Update(); vtkSmartPointer<vtkImageSobel2D> sobelFilter = vtkSmartPointer<vtkImageSobel2D>::New(); sobelFilter->SetInputConnection(reader->GetOutputPort()); vtkSmartPointer<vtkImageExtractComponents> extractXFilter = vtkSmartPointer<vtkImageExtractComponents>::New(); extractXFilter->SetComponents(0); extractXFilter->SetInputConnection(sobelFilter->GetOutputPort()); extractXFilter->Update(); double xRange[2]; extractXFilter->GetOutput()->GetScalarRange(xRange); vtkSmartPointer<vtkImageMathematics> xImageAbs = vtkSmartPointer<vtkImageMathematics>::New(); xImageAbs->SetOperationToAbsoluteValue(); xImageAbs->SetInputConnection(extractXFilter->GetOutputPort()); xImageAbs->Update(); vtkSmartPointer<vtkImageShiftScale> xShiftScale = vtkSmartPointer<vtkImageShiftScale>::New(); xShiftScale->SetOutputScalarTypeToUnsignedChar(); xShiftScale->SetScale( 255 / xRange[1] ); xShiftScale->SetInputConnection(xImageAbs->GetOutputPort()); xShiftScale->Update(); vtkSmartPointer<vtkImageExtractComponents> extractYFilter = vtkSmartPointer<vtkImageExtractComponents>::New(); extractYFilter->SetComponents(1); extractYFilter->SetInputConnection(sobelFilter->GetOutputPort()); extractYFilter->Update(); double yRange[2]; extractYFilter->GetOutput()->GetScalarRange(yRange); vtkSmartPointer<vtkImageMathematics> yImageAbs = vtkSmartPointer<vtkImageMathematics>::New(); yImageAbs->SetOperationToAbsoluteValue(); yImageAbs->SetInputConnection(extractYFilter->GetOutputPort()); yImageAbs->Update(); vtkSmartPointer<vtkImageShiftScale> yShiftScale = vtkSmartPointer<vtkImageShiftScale>::New(); yShiftScale->SetOutputScalarTypeToUnsignedChar(); yShiftScale->SetScale( 255 / yRange[1] ); yShiftScale->SetInputConnection(yImageAbs->GetOutputPort()); yShiftScale->Update(); vtkSmartPointer<vtkImageActor> originalActor = vtkSmartPointer<vtkImageActor>::New(); originalActor->SetInput(reader->GetOutput()); vtkSmartPointer<vtkImageActor> xActor = vtkSmartPointer<vtkImageActor>::New(); xActor->SetInput(xShiftScale->GetOutput()); vtkSmartPointer<vtkImageActor> yActor = vtkSmartPointer<vtkImageActor>::New(); yActor->SetInput(yShiftScale->GetOutput()); double originalViewport[4] = {0.0, 0.0, 0.33, 1.0}; double xViewport[4] = {0.33, 0.0, 0.66, 1.0}; double yViewport[4] = {0.66, 0.0, 1.0, 1.0}; vtkSmartPointer<vtkRenderer> originalRenderer = vtkSmartPointer<vtkRenderer>::New(); originalRenderer->SetViewport(originalViewport); originalRenderer->AddActor(originalActor); originalRenderer->ResetCamera(); originalRenderer->SetBackground(1.0, 1.0, 1.0); vtkSmartPointer<vtkRenderer> xRenderer = vtkSmartPointer<vtkRenderer>::New(); xRenderer->SetViewport(xViewport); xRenderer->AddActor(xActor); xRenderer->ResetCamera(); xRenderer->SetBackground(1.0, 1.0, 1.0); vtkSmartPointer<vtkRenderer> yRenderer = vtkSmartPointer<vtkRenderer>::New(); yRenderer->SetViewport(yViewport); yRenderer->AddActor(yActor); yRenderer->ResetCamera(); yRenderer->SetBackground(1.0, 1.0, 1.0); vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->SetSize(1200, 300); renderWindow->AddRenderer(originalRenderer); renderWindow->AddRenderer(xRenderer); renderWindow->AddRenderer(yRenderer); renderWindow->Render(); renderWindow->SetWindowName("SobelExample"); vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); vtkSmartPointer<vtkInteractorStyleImage> style = vtkSmartPointer<vtkInteractorStyleImage>::New(); renderWindowInteractor->SetInteractorStyle(style); renderWindowInteractor->SetRenderWindow(renderWindow); renderWindowInteractor->Initialize(); renderWindowInteractor->Start(); return EXIT_SUCCESS; }
cb56c5b6a90d77343b06726c0fb9018cc78a42fb
61c88c34e87e3be2cf3e3ba1e21407218e3a130f
/visionQT_test1/removeoutliers.h
7b45434732a269767e3ddfd456578f81b8255b01
[]
no_license
InkChan/3Dvision
af48285269251f39c068d5b8c72cf221a4f1e5bd
14fd49294241c36ad77342b04741d75db434d5bc
refs/heads/master
2020-06-02T11:42:50.428388
2019-08-05T10:45:49
2019-08-05T10:45:49
191,143,444
2
0
null
null
null
null
WINDOWS-1252
C++
false
false
721
h
#ifndef REMOVEOUTLIERS_H #define REMOVEOUTLIERS_H #include "moudleWidget.h" #include "litcontrol.h" #include "qlabel.h" #include "HalconCpp.h" #include "HDevThread.h" class RemoveOutliers : public MoudleWidget { Q_OBJECT public: RemoveOutliers(HImage img, QWidget *parent = 0); ~RemoveOutliers(); void process(HImage img); /*HalconCpp::HImage QImageToHImage(QImage *inImage);*/ private: LitControl *algorithmControl; //Ëã·¨ LitControl *fillHolesControl; //¿×¶´Ìî³ä LitControl *maskSizeControl; //ÑÚÂë³ß´ç QLabel *algorithmLabel; //Ëã·¨±êÇ© QLabel *fillHolesLabel; //¿×¶´±êÇ© QLabel *maskLabel; //ÑÚĤ±êÇ© }; #endif // REMOVEOUTLIERS_H
d4c5bef4f1a973d7f7f31ebdf6f086fb162cc775
6e882a3a0819b6257f602058b3913cf65376668a
/BSH/once_upon_a_time/15778/main.cpp
dd12fe964128fdc79e3e0ab8836d5cb78d04e518
[]
no_license
hyperpace/study_algo_gangnam
79e4ffda3306cdd2d7572bd722a5b5ece5469eb5
34b017bcd68c67fffcae85a14a17baa4f2e4eb74
refs/heads/master
2021-06-12T12:37:31.694167
2021-03-20T09:58:54
2021-03-20T09:58:54
164,384,323
0
5
null
2021-03-20T09:58:54
2019-01-07T05:50:18
Jupyter Notebook
UTF-8
C++
false
false
2,989
cpp
#include <iostream> #include <string> #include <queue> using namespace std; struct node { vector<bool> loc; int team_num; // 0 없는거, 1 대문자 팀, 2 소문자 팀 int node_num; int x; int y; int next_node; int short_cut = -1; }; int get_forward(string command) { int ans = 0; for (int i = 0; i < 4; i++) if (command[i] == 'F') ans += 1; if (ans == 0) ans = 5; return ans; } int get_team(char a) { if ('a' <= a && a <= 'z') return 0; else return 1; } void init_board(node board[29]) { //short_cut 정리 (board + 5)->short_cut = 20; (board + 10)->short_cut = 25; (board + 22)->short_cut = 27; //next for (int i = 0; i < 19; i++) (board + i)->next_node = i + 1; (board + 19)->next_node = 0; } int main() { string display; display = "..----..----..----..----..----..\n" ".. .. .. .. .. ..\n" "| \\ / |\n" "| \\ / |\n" "| \\ / |\n" "| .. .. |\n" ".. .. .. ..\n" ".. \\ / ..\n" "| \\ / |\n" "| \\ / |\n" "| .. .. |\n" "| .. .. |\n" ".. \\ / ..\n" ".. \\ / ..\n" "| \\ / |\n" "| .. |\n" "| .. |\n" "| / \\ |\n" ".. / \\ ..\n" ".. / \\ ..\n" "| .. .. |\n" "| .. .. |\n" "| / \\ |\n" "| / \\ |\n" ".. / \\ ..\n" ".. .. .. ..\n" "| .. .. |\n" "| / \\ |\n" "| / \\ |\n" "| / \\ |\n" ".. .. .. .. .. ..\n" "..----..----..----..----..----.."; int N; cin >> N; node board[29]; init_board(board); int teamA[4]; // -1은 출발점 int teamB[4]; // -2는 끝난 거 char piece; string command; for (int i = 0; i < N; i++) { cin >> piece >> command; int forward = get_forward(command); int team = get_team(piece); //0은 소문자팀, 1은 대문자 팀팀 if (team == 0) { } else { } } return 0; }
3e3b8e7f037d1fc751a7aceeac5ee975a60e6569
f7c673d103a0a7261246dbdde75490f8eed918ab
/source/EditorCore/task/CreateTransitiveTask.cpp
952b04e760ea929f70be30c7a883fa8bbf97991d
[]
no_license
phisn/PixelJumper2
2c69faf83c09136b81befd7a930c19ea0ab521f6
842878cb3e44113cc2753abe889de62921242266
refs/heads/master
2022-11-14T04:44:00.690120
2020-07-06T09:38:38
2020-07-06T09:38:38
277,490,158
0
0
null
2020-07-06T09:38:42
2020-07-06T08:48:52
C++
UTF-8
C++
false
false
34
cpp
#include "CreateTransitiveTask.h"
a158186ad6965903129a0c4207c16bdd552799f8
5f9f5f16d84dab6f2d27859ce6d8530312d96da6
/Ishavsfiske/FishingMode.h
7424a569283a25d493ad2a5f91d66d01a18acb54
[]
no_license
thenohatcat/Ishavsfiske
7f2f12796f83d9fc009db4c60bc480685a8adec7
ed0dff7f66799e4ff2283ac36180aa99b8112331
refs/heads/master
2021-01-19T06:04:54.708772
2014-03-10T23:44:37
2014-03-10T23:44:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,325
h
//Version: 0.1.4 //Author: Jakob Pipping //Contributors: #ifndef INC_FISHINGMODE_H #define INC_FISHINGMODE_H #ifdef ISHAV_0_1_4 #include <Angler\Game.h> #include <Angler\Node.h> #include <Angler\Translation.h> #include "IceBreaker.h" #include "FishingBoat.h" #include "Map.h" #include "School.h" #include "MsgBox.h" namespace Ishavsfiske { class FishingMode : public Angler::Node { public: FishingMode(unsigned long id, Angler::Node *parent, Ishavsfiske::IshavsfiskeGame *owner); FishingMode(unsigned long id, Ishavsfiske::IshavsfiskeGame *owner); void collide(Node *nodeA, Node *nodeB); void input(float time, float deltaTime); void loadContent(); void init(); IceBreaker *getIceBreaker(); FishingBoat *getShipFishing(); void draw(Angler::Game* context, Angler::Graphics::GraphicsEngine* graphics, float time, float deltaTime); void update(Angler::Game* context, float time, float deltaTime, bool changed = false); void fish(int dir, School* school); void repair(int dir); void breakIce(); protected: void mEnable(bool enabled); private: sf::Sound *mCollFishingSound, *mCollBreakerSound, *mCollIceSound, *mEngineSound; sf::SoundBuffer *mCollFishingBuff, *mCollBreakerBuff, *mCollIceBuff, *mEngineBuff; sf::Texture *mTXMap, *mTXUI, *mTXSchool, *mUIFont, *mTXGameOver; sf::Sound *mRepair; sf::SoundBuffer *mRepairBuff; sf::Sound *mMusic; sf::SoundBuffer *mMusicFishingBuff; sf::Sound *mSeaAmbient; sf::SoundBuffer *mSeaAmbientBuff; sf::Sound *mTutorialSound; sf::SoundBuffer *mTutorialBuff; Angler::Nodes::Translation *mFishBase; void mMoveFrame(float fishingDX, float fishingDY, float breakerDX, float breakerDY, bool fishingX, bool fishingY, bool moveMapX, bool moveMapY); int mSchoolID; std::vector<School*> mSchools; Map *mMap; Ship *mShipFishing, *mShipBreaker; Ishavsfiske::IshavsfiskeGame *mOwner; void mUpdateTutorial(Angler::Game* context, float time, float deltaTime); bool mDoRepair; bool mDoFish; MsgBox *mMsgBox; Font *mFont; int mTutorialStage; float mTutorialStageTime; bool mShowTimer; bool mShowCounter; bool mCanRepair; bool mCanFish; bool mMapFrozen; bool mSpawnFish; bool mRunTimer; float mTimer; }; } #else #error FishingMode.h: Wrong version 0.1.4 #endif #endif
49d6d1655fbba7638949190b8f900b9c063a8bbd
0c247b54c79ff4486b293d951f33c050385c236c
/src/Cxx/Visualization/Legend.cxx
d34095a3667ca7975104fe563d893f6d37f76cbf
[ "Apache-2.0" ]
permissive
adithyakoundinya/VTKExamples
9a84c0c6ff446981d5bd10af49016573a965d367
aa8509b376d159d19b6769180b27a34f5e37f5c3
refs/heads/master
2021-10-08T14:34:40.669466
2018-12-12T22:56:50
2018-12-12T22:56:50
161,281,949
1
0
Apache-2.0
2018-12-13T01:13:33
2018-12-11T05:30:15
HTML
UTF-8
C++
false
false
2,739
cxx
#include <vtkVersion.h> #include <vtkPolyDataMapper.h> #include <vtkActor.h> #include <vtkRenderWindow.h> #include <vtkRenderer.h> #include <vtkRenderWindowInteractor.h> #include <vtkPolyData.h> #include <vtkCubeSource.h> #include <vtkSphereSource.h> #include <vtkLegendBoxActor.h> #include <vtkNamedColors.h> #include <vtkSmartPointer.h> int main (int, char *[]) { vtkSmartPointer<vtkSphereSource> sphereSource = vtkSmartPointer<vtkSphereSource>::New(); sphereSource->SetCenter(0.0, 0.0, 0.0); sphereSource->SetRadius(5000.0); sphereSource->Update(); vtkPolyData* polydata = sphereSource->GetOutput(); // Create a mapper vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); #if VTK_MAJOR_VERSION <= 5 mapper->SetInput(polydata); #else mapper->SetInputData(polydata); #endif // Create an actor vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New(); actor->SetMapper(mapper); // A renderer and render window vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New(); vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->AddRenderer(renderer); // An interactor vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); renderWindowInteractor->SetRenderWindow(renderWindow); vtkSmartPointer<vtkLegendBoxActor> legend = vtkSmartPointer<vtkLegendBoxActor>::New(); legend->SetNumberOfEntries(2); vtkSmartPointer<vtkNamedColors> colors = vtkSmartPointer<vtkNamedColors>::New(); double color[4]; vtkSmartPointer<vtkCubeSource> legendBox = vtkSmartPointer<vtkCubeSource>::New(); legendBox->Update(); colors->GetColor("tomato", color); legend->SetEntry(0, legendBox->GetOutput(), "Box", color); colors->GetColor("banana", color); legend->SetEntry(1, sphereSource->GetOutput(), "Ball", color); // place legend in lower right legend->GetPositionCoordinate()->SetCoordinateSystemToView(); legend->GetPositionCoordinate()->SetValue(.5, -1.0); legend->GetPosition2Coordinate()->SetCoordinateSystemToView(); legend->GetPosition2Coordinate()->SetValue(1.0, -0.5); legend->UseBackgroundOn(); double background[4]; colors->GetColor("warm_grey", background); legend->SetBackgroundColor(background); // Add the actors to the scene renderer->AddActor(actor); renderer->AddActor(legend); renderer->SetBackground(0,1,1); // Background color cyan // Render an image (lights and cameras are created automatically) renderWindow->Render(); // Begin mouse interaction renderWindowInteractor->Start(); return EXIT_SUCCESS; }
5548cb01afe4e435a94e47826e33c98961017184
71b54fba80ee4dd7c44afed21c36849cbd150e2d
/Projects/IndividualProject/PokerGame/pokerclient.cpp
c0c413e2fe78453a3a368f0d951a9951b528d555
[]
no_license
ZelaiWang/CSC-17B
929dbde50037c9a6dc8c21b15fad6138e7e63d49
08871aea1139ad1658a41b51616cc18b8a1f0e56
refs/heads/master
2020-07-03T06:26:03.179213
2015-12-16T03:07:39
2015-12-16T03:07:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,217
cpp
#include "pokerclient.h" /** * Reference to the function declaration * @brief PokerClient::PokerClient */ PokerClient::PokerClient() { tcpSocket = new QTcpSocket(); //Handle connected event connect(tcpSocket, SIGNAL(connected()), this, SLOT(sendData())); //Handle connection errors connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(processError())); connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(processError())); } /** * Reference to the function declaration * @brief PokerClient::save * @param object * @param score */ void PokerClient::save(QString object, int score) { this->object = object; this->score = QString::number(score); tcpSocket->connectToHost(QHostAddress::LocalHost, 2015); } /** * Reference to the function declaration * @brief PokerClient::sendData */ void PokerClient::sendData() { QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out << object << score; tcpSocket->write(block); tcpSocket->close(); } /** * Reference to the function declaration * @brief PokerClient::processError */ void PokerClient::processError() { tcpSocket->close(); }
4fea29e8804e5cf30f90ef0df0229dee13513686
975d511f467bf378f0b017592ec01e5e0589f1ff
/LabTool/functions.h
ecde5fdfd81011f00a7fb16ab279ec0706a6020b
[ "MIT" ]
permissive
Alexey-Ul/Hisoutensoku-LabTool
648b8a0e6d6747dae0c211f2b45090647b74f152
1f43b8a9547eed39c40af465ca45a843060089a5
refs/heads/master
2020-09-02T09:22:24.090036
2019-09-16T09:46:58
2019-09-16T09:46:58
219,189,270
0
0
null
2019-11-02T17:30:01
2019-11-02T17:30:01
null
UTF-8
C++
false
false
3,935
h
#pragma once #define LEFT_CORNER_P1 79.0f #define LEFT_NEAR_P1 379.0f #define MIDSCREEN_P1 601.0f #define RIGHT_NEAR_P1 901.0f #define RIGHT_CORNER_P1 1201.0f #define LEFT_CORNER_P2 40.0f #define LEFT_NEAR_P2 340.0f #define MIDSCREEN_P2 640.0f #define RIGHT_NEAR_P2 940.0f #define RIGHT_CORNER_P2 1240.0f // Very Light - Light - Medium - Heavy (shifted compared to the usual notations) #define VERYLIGHT_RB_TIME 10 #define LIGHT_RB_TIME 16 #define MEDIUM_RB_TIME 22 #define HEAVY_RB_TIME 28 #define VERYLIGHT_WB_TIME 12 #define LIGHT_WB_TIME 20 #define MEDIUM_WB_TIME 28 #define AIR_B_TIME 20 #define GUARDCRUSH 143 #define AIR_GUARDCRUSH 145 #define STAND_VL_RB 150 #define STAND_L_RB 151 #define STAND_M_RB 152 #define STAND_H_RB 153 #define CROUCH_VL_RB 154 #define CROUCH_L_RB 155 #define CROUCH_M_RB 156 #define CROUCH_H_RB 157 #define AIRBLOCK 158 #define STAND_VL_WB 159 #define STAND_L_WB 160 #define STAND_M_WB 161 #define CROUCH_L_WB 164 #define CROUCH_M_WB 165 #define FORWARD_TECH 197 #define BACKWARD_TECH 198 #define NEUTRAL_TECH 199 /* Keymaps of both players */ #define SWRS_ADDR_1PKEYMAP 0x00898940 #define SWRS_ADDR_2PKEYMAP 0x0089912C enum SAVESTATE_MODE { NONE, CONSERVED, CONTINUED }; namespace KeymapIndex { enum KeymapIndex : int { up, down, left, right, A, B, C, D, sw, sc }; } enum tech_select : int { neutral, left, right, random }; enum reversal_select : int { nothing, jump, highjump, backdash, mash4A, d623B, spellcard }; enum first_select : int { noblocking, standing, crouching }; enum BE_select : int { noBE, BEdown, BEdownside, BEside, BEback }; /* KEYS */ typedef struct { UINT save_pos; UINT reset_pos; UINT display_states; UINT randomCH; UINT reset_skills; UINT tech_macro; UINT wakeup_macro; UINT firstblock_macro; UINT BE_macro; } Keys; typedef struct { bool display_states; bool save_pos; bool reset_pos; bool randomCH; bool reset_skills; int tech_macro; int wakeup_macro; int firstblock_macro; int BE_macro; } Toggle_key; typedef struct { bool set_pos; bool save_pos; bool tech_macro; bool wakeup_macro; bool firstblock_macro; bool BE_macro; } Held_key; /* PLAYER */ typedef struct { int frame_advantage; bool blockstring; int hjc_advantage; bool hjc_blockstring; int isIdle; bool untight_nextframe; bool already_CH; int tech_mode; int wakeup_mode; int firstblock_mode; int BE_mode; int wakeup_count_p1; int wakeup_count_p2; } Misc_state; typedef struct { int up; int down; int left; int right; int A; int B; int C; int D; int sw; int sc; } Commands; typedef struct { float x; float y; float xspeed; float yspeed; float gravity; int direction; } Position; typedef struct { void *p; int index; int x_pressed;//left is -, right is + int y_pressed;//down is -, up is + Position position; void* framedata; int frameflag; short current_sequence; short elapsed_in_subseq; short health; short spirit; short untech; char card; } Player; extern Keys savestate_keys; extern Toggle_key toggle_keys; extern Held_key held_keys; extern Misc_state misc_states; /* UPDATE FUNCTIONS */ void update_position(Player *); void update_playerinfo(Player *, int, int); /* POSITION FUNCTIONS */ Position init_pos(float); Position save_checkpoint(Player *); void set_position(Player *, Position, int); void position_management(Player *, Player *); /* FRAMECOUNT FUNCTIONS */ void gap_count(Player *); void frameadvantage_count(Player *, Player *); void hjcadvantage_count(Player *, Player *); bool untight_check(Player *); void is_tight(Player *); /* MACROS */ void random_CH(Player *); void block_1st_hit(Player *, int *); void send_inputs(Commands, Commands); void tech(Player *, int *, int *); void macros(Player *, Player *); /* MISCELLANEOUS */ void state_display(Player *); void set_health(Player *, short); void set_spirit(Player *, short, short); void reset_skills(Player *);
ec4f9ae315e27c61bb70c177ad6a944e7ce3f563
8420523466c9f6ab0edf6ff556c09c5a49edc1cb
/src/eedit/eediterrortoolbox.cpp
5e6fd9cab162b60cc5cdaf1d7226d31f9c2971b7
[]
no_license
huigou/planeshift
fb31a43ff1fad0e1b69d9683d0e1e8a0945d8fd3
78afce50bccf755ec4ded0c6bc91ae3c80bc5eba
refs/heads/master
2020-05-25T15:47:26.462741
2016-06-15T20:34:37
2016-06-15T20:34:37
64,410,081
2
3
null
null
null
null
UTF-8
C++
false
false
6,354
cpp
/* * Author: Andrew Robberts * * Copyright (C) 2003 Atomic Blue ([email protected], http://www.atomicblue.org) * * * 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 (version 2 of the License) * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include <psconfig.h> #include "eediterrortoolbox.h" #include "eeditglobals.h" #include "eeditreporter.h" #include "paws/pawsmanager.h" #include "paws/pawsbutton.h" #include "paws/pawstextbox.h" #include "paws/pawscheckbox.h" EEditErrorToolbox::EEditErrorToolbox() : scfImplementationType(this) { errorText = 0; loadingEffects = false; } EEditErrorToolbox::~EEditErrorToolbox() { editApp->SetConfigBool("EEdit.Errors.OnlyEffects", onlyEffectErrors->GetState()); editApp->SetConfigBool("EEdit.Errors.ShowErrors", showErrors->GetState()); editApp->SetConfigBool("EEdit.Errors.ShowWarnings", showWarnings->GetState()); editApp->SetConfigBool("EEdit.Errors.ShowNotifications", showNotifications->GetState()); } const int BUG_COLOUR[] = { 255, 0, 255 }; const int ERROR_COLOUR[] = { 255, 0, 0 }; const int WARNING_COLOUR[] = { 255, 255, 0 }; const int NOTIFY_COLOUR[] = { 255, 255, 255 }; const int DEBUG_COLOUR[] = { 0, 255, 255 }; void EEditErrorToolbox::AddError(int severity, const char * msgId, const char * description) { if (errorText == 0) return; int colour = -1; switch (severity) { case CS_REPORTER_SEVERITY_BUG: colour = editApp->GetGraphics2D()->FindRGB(BUG_COLOUR[0], BUG_COLOUR[1], BUG_COLOUR[2]); break; case CS_REPORTER_SEVERITY_ERROR: colour = editApp->GetGraphics2D()->FindRGB(ERROR_COLOUR[0], ERROR_COLOUR[1], ERROR_COLOUR[2]); break; case CS_REPORTER_SEVERITY_WARNING: colour = editApp->GetGraphics2D()->FindRGB(WARNING_COLOUR[0], WARNING_COLOUR[1], WARNING_COLOUR[2]); break; case CS_REPORTER_SEVERITY_NOTIFY: colour = editApp->GetGraphics2D()->FindRGB(NOTIFY_COLOUR[0], NOTIFY_COLOUR[1], NOTIFY_COLOUR[2]); break; case CS_REPORTER_SEVERITY_DEBUG: colour = editApp->GetGraphics2D()->FindRGB(DEBUG_COLOUR[0], DEBUG_COLOUR[1], DEBUG_COLOUR[2]); break; } char msg[1024]; msg[0] = '\0'; int msgIndex = 0; int index = 0; while (description[index] != '\0') { if (description[index] == '\n') { msg[msgIndex] = '\0'; msgIndex = 0; errors.Push(EEditError(msg, colour, severity, loadingEffects)); DisplayError(errors.Top()); } else msg[msgIndex++] = description[index]; ++index; } msg[msgIndex] = '\0'; errors.Push(EEditError(msg, colour, severity, loadingEffects)); DisplayError(errors.Top()); Show(); } void EEditErrorToolbox::SetLoadingEffects(bool isLoadingEffects) { loadingEffects = isLoadingEffects; } void EEditErrorToolbox::Clear() { errorText->Clear(); errors.DeleteAll(); } void EEditErrorToolbox::ResetFilter() { errorText->Clear(); for (size_t a=0; a<errors.GetSize(); ++a) DisplayError(errors[a]); } void EEditErrorToolbox::Update(unsigned int elapsed) { } size_t EEditErrorToolbox::GetType() const { return T_ERROR; } const char * EEditErrorToolbox::GetName() const { return "Errors"; } bool EEditErrorToolbox::PostSetup() { errorText = (pawsMessageTextBox *) FindWidget("errors"); CS_ASSERT(errorText); clearButton = (pawsButton *) FindWidget("clear"); CS_ASSERT(clearButton); hideButton = (pawsButton *) FindWidget("hide"); CS_ASSERT(hideButton); onlyEffectErrors = (pawsCheckBox *) FindWidget("only_effect_errors"); CS_ASSERT(onlyEffectErrors); showErrors = (pawsCheckBox *) FindWidget("show_errors"); CS_ASSERT(showErrors); showWarnings = (pawsCheckBox *) FindWidget("show_warnings"); CS_ASSERT(showWarnings); showNotifications = (pawsCheckBox *) FindWidget("show_notifys"); CS_ASSERT(showNotifications); onlyEffectErrors->SetState(editApp->GetConfigBool("EEdit.Errors.OnlyEffects", false)); showErrors->SetState(editApp->GetConfigBool("EEdit.Errors.ShowErrors", true)); showWarnings->SetState(editApp->GetConfigBool("EEdit.Errors.ShowWarnings", true)); showNotifications->SetState(editApp->GetConfigBool("EEdit.Errors.ShowNotifications", true)); editApp->GetReporter()->SetErrorToolbox(this); return true; } bool EEditErrorToolbox::OnButtonPressed(int mouseButton, int keyModifier, pawsWidget * widget) { if (widget == clearButton) { Clear(); return true; } else if (widget == hideButton) { Clear(); Hide(); return true; } else if (widget == onlyEffectErrors || widget == showErrors || widget == showWarnings || widget == showNotifications) { ResetFilter(); return true; } return false; } void EEditErrorToolbox::Show() { SetRelativeFramePos(editApp->GetGraphics2D()->GetWidth()/2 - GetActualWidth(screenFrame.Width())/2, editApp->GetGraphics2D()->GetHeight()/2 - GetActualHeight(screenFrame.Height())/2); pawsWidget::Show(); } void EEditErrorToolbox::DisplayError(const EEditError & error) { if (onlyEffectErrors->GetState() && !error.isEffectError) return; if (error.severity == CS_REPORTER_SEVERITY_ERROR && !showErrors->GetState()) return; if (error.severity == CS_REPORTER_SEVERITY_WARNING && !showWarnings->GetState()) return; if (error.severity == CS_REPORTER_SEVERITY_NOTIFY && !showNotifications->GetState()) return; errorText->AddMessage(error.desc, error.colour); }
[ "mgist@2752fbe2-5038-0410-9d0a-88578062bcef" ]
mgist@2752fbe2-5038-0410-9d0a-88578062bcef
0d934d18507241fa4a94de39a373f32c2bf90ee0
f5bd250b8bbd0977e262e8e2d79f0a9829cc0813
/fakengine/dimension/Vector3D.hpp
6bcb94ca31fe0111def962a67c3754cc59ab0707
[]
no_license
itbestbear/fakengine
0d56599ebbecb32c26fae63723582b220f05e9fa
46490fee5ad6be9c956e9e1c7368936e11e0350a
refs/heads/master
2022-01-18T17:08:11.045106
2019-05-09T08:27:06
2019-05-09T08:27:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,175
hpp
#pragma once template <typename T> class vector4d; template <typename T> class point2d; template <typename T> class size2d; //! Axis direction types. enum EAxisTypes { AXIS_X_POSITIVE = 0, AXIS_X_NEGATIVE, AXIS_Y_POSITIVE, AXIS_Y_NEGATIVE, AXIS_Z_POSITIVE, AXIS_Z_NEGATIVE, }; /** Vector 3D class which has the three components X, Y and Z. This is the main class used for 3D scene directions, positions, scaling etc. */ template <typename T> class vector3d { public: force_inline vector3d() : X(0), Y(0), Z(0) { } force_inline vector3d(const T &Size) : X(Size), Y(Size), Z(Size) { } force_inline vector3d(const T &VecX, const T &VecY, const T &VecZ) : X(VecX), Y(VecY), Z(VecZ) { } force_inline vector3d(const T &VecX, const T &VecY, const T &VecZ, const T &VecW) : X(VecX*VecW), Y(VecY*VecW), Z(VecZ*VecW) { } force_inline vector3d(const vector3d<T> &Other) : X(Other.X), Y(Other.Y), Z(Other.Z) { } force_inline vector3d(const vector4d<T> &Other); force_inline vector3d(const point2d<T> &Other); force_inline vector3d(const size2d<T> &Other); force_inline ~vector3d() { } /* === Operators - comparisions === */ force_inline bool operator == (const vector3d<T> &other) const { return Equal(X, other.X) && Equal(Y, other.Y) && Equal(Z, other.Z); } force_inline bool operator != (const vector3d<T> &other) const { return !Equal(X, other.X) || !Equal(Y, other.Y) || !Equal(Z, other.Z); } force_inline bool operator <= (const vector3d<T> &other) const { return ( X < other.X || Equal(X, other.X) ) || ( Equal(X, other.X) && ( Y < other.Y || Equal(Y, other.Y) ) ) || ( Equal(X, other.X) && Equal(Y, other.Y) && ( Z < other.Z || Equal(Z, other.Z) ) ); } force_inline bool operator >= (const vector3d<T> &other) const { return ( X > other.X || Equal(X, other.X) ) || ( Equal(X, other.X) && (Y > other.Y || Equal(Y, other.Y) ) ) || ( Equal(X, other.X) && Equal(Y, other.Y) && ( Z > other.Z || Equal(Z, other.Z) ) ); } force_inline bool operator < (const vector3d<T> &other) const { return ( X < other.X && !Equal(X, other.X) ) || ( Equal(X, other.X) && Y < other.Y && !Equal(Y, other.Y) ) || ( Equal(X, other.X) && Equal(Y, other.Y) && Z < other.Z && !Equal(Z, other.Z) ); } force_inline bool operator > (const vector3d<T> &other) const { return ( X > other.X && !Equal(X, other.X) ) || ( Equal(X, other.X) && Y > other.Y && !Equal(Y, other.Y) ) || ( Equal(X, other.X) && Equal(Y, other.Y) && Z > other.Z && !Equal(Z, other.Z) ); } /* === Operators - addition, subtraction, division, multiplication === */ //! Pre-increment operator. force_inline vector3d<T>& operator ++ () { ++X; ++Y; ++Z; return *this; } //! Post-increment operator. force_inline vector3d<T>& operator ++ (int) { const vector3d<T> Tmp(*this); ++*this; return Tmp; } //! Pre-decrement operator. force_inline vector3d<T>& operator -- () { --X; --Y; --Z; return *this; } //! Post-decrement operator. force_inline vector3d<T>& operator -- (int) { const vector3d<T> Tmp(*this); --*this; return Tmp; } force_inline vector3d<T> operator + (const vector3d<T> &other) const { return vector3d<T>(X + other.X, Y + other.Y, Z + other.Z); } force_inline vector3d<T>& operator += (const vector3d<T> &other) { X += other.X; Y += other.Y; Z += other.Z; return *this; } force_inline vector3d<T> operator - (const vector3d<T> &other) const { return vector3d<T>(X - other.X, Y - other.Y, Z - other.Z); } force_inline vector3d<T>& operator -= (const vector3d<T> &other) { X -= other.X; Y -= other.Y; Z -= other.Z; return *this; } force_inline vector3d<T> operator / (const vector3d<T> &other) const { return vector3d<T>(X / other.X, Y / other.Y, Z / other.Z); } force_inline vector3d<T>& operator /= (const vector3d<T> &other) { X /= other.X; Y /= other.Y; Z /= other.Z; return *this; } force_inline vector3d<T> operator * (const vector3d<T> &other) const { return vector3d<T>(X * other.X, Y * other.Y, Z * other.Z); } force_inline vector3d<T>& operator *= (const vector3d<T> &other) { X *= other.X; Y *= other.Y; Z *= other.Z; return *this; } force_inline vector3d<T> operator * (const T &Size) const { return vector3d<T>(X * Size, Y * Size, Z * Size); } force_inline vector3d<T>& operator *= (const T &Size) { X *= Size; Y *= Size; Z *= Size; return *this; } force_inline vector3d<T> operator / (const T &Size) const { return *this * (T(1) / Size); } force_inline vector3d<T>& operator /= (const T &Size) { return *this *= (T(1) / Size); } force_inline vector3d<T> operator - () const { return vector3d<T>(-X, -Y, -Z); } /* === Additional operators === */ force_inline const T operator [] (uint32_t i) const { return i < 3 ? *(&X + i) : static_cast<T>(0.0); } force_inline T& operator [] (uint32_t i) { return *(&X + i); } /* === Extra functions === */ //! Returns the dot (or rather scalar) product between this and the given vector. force_inline T dot(const vector3d<T> &other) const { return X*other.X + Y*other.Y + Z*other.Z; } //! Returns the cross (or rather vector) product between this and the given vector. force_inline vector3d<T> cross(const vector3d<T> &other) const { return vector3d<T>( Y*other.Z - other.Y*Z, Z*other.X - other.Z*X, X*other.Y - other.X*Y ); } //! Returns the vector's length. force_inline T getLength() const { return sqrt(X*X + Y*Y + Z*Z); } //! Returns the square of the vector's length (Can be used for faster comparision between two distances). force_inline T getLengthSq() const { return X*X + Y*Y + Z*Z; } //! Returns the angle (in degrees) between this and the given vector. force_inline T getAngle(const vector3d<T> &other) const { return static_cast<T>(ACos( dot(other) / (getLength()*other.getLength()) )); } force_inline vector3d<T>& setInvert() { X = -X; Y = -Y; Z = -Z; return *this; } force_inline vector3d<T> getInvert() const { return vector3d<T>(-X, -Y, -Z); } force_inline vector3d<T>& setRound(int32_t Precision) { Precision = static_cast<int32_t>(pow(10, Precision)); X = static_cast<T>(static_cast<int32_t>(X*Precision)) / Precision; Y = static_cast<T>(static_cast<int32_t>(Y*Precision)) / Precision; Z = static_cast<T>(static_cast<int32_t>(Z*Precision)) / Precision; return *this; } force_inline vector3d<T> getRound(int32_t Precision) const { Precision = static_cast<int32_t>(pow(10, Precision)); return vector3d<T>( static_cast<T>(static_cast<int32_t>(X*Precision)) / Precision, static_cast<T>(static_cast<int32_t>(Y*Precision)) / Precision, static_cast<T>(static_cast<int32_t>(Z*Precision)) / Precision ); } force_inline bool equal(const vector3d<T> &other, float Tolerance = ROUNDING_ERROR) const { return (X + Tolerance > other.X) && (X - Tolerance < other.X) && (Y + Tolerance > other.Y) && (Y - Tolerance < other.Y) && (Z + Tolerance > other.Z) && (Z - Tolerance < other.Z); } force_inline bool empty() const { return equal(0); } force_inline void make2DProjection(int32_t ScreenWidth, int32_t ScreenHeight) { X = X * static_cast<float>(ScreenWidth /2) + ScreenWidth /2; Y = - Y * static_cast<float>(ScreenHeight/2) + ScreenHeight/2; Z = T(0); } force_inline void make2DProjection(float FOV, int32_t ScreenWidth, int32_t ScreenHeight) { X = X / Z * FOV + ScreenWidth /2; Y = - Y / Z * FOV + ScreenHeight/2; } force_inline vector3d<T>& setAbs() { X = X > 0 ? X : -X; Y = Y > 0 ? Y : -Y; Z = Z > 0 ? Z : -Z; return *this; } force_inline vector3d<T> getAbs() const { return vector3d<T>( X > 0 ? X : -X, Y > 0 ? Y : -Y, Z > 0 ? Z : -Z ); } force_inline vector3d<T>& normalize() { T n = X*X + Y*Y + Z*Z; if (n == T(0) || n == T(1)) return *this; n = T(1) / sqrt(n); X *= n; Y *= n; Z *= n; return *this; } force_inline vector3d<T>& sign() { if (X > 0) X = 1; else if (X < 0) X = -1; if (Y > 0) Y = 1; else if (Y < 0) Y = -1; if (Z > 0) Z = 1; else if (Z < 0) Z = -1; return *this; } force_inline vector3d<T>& setLength(const T &Length) { normalize(); *this *= Length; return *this; } force_inline T getDistanceFromSq(const vector3d<T> &other) const { return vector3d<T>(X - other.X, Y - other.Y, Z - other.Z).getLengthSq(); } force_inline bool isBetweenPoints(const vector3d<T> &Begin, const vector3d<T> &End) const { const T Temp = (End - Begin).getLengthSq(); return getDistanceFromSq(Begin) <= Temp && getDistanceFromSq(End) <= Temp; } force_inline bool isPointInsideSphere(const vector3d<T> &Center, const float Radius) const { return Pow2(X - Center.X) + Pow2(Y - Center.Y) + Pow2(Z - Center.Z) < Pow2(Radius); } force_inline vector3d<T> getInterpolatedQuadratic(const vector3d<T> &v2, const vector3d<T> &v3, const T d) const { const T inv = static_cast<T>(1.0) - d; const T mul0 = inv * inv; const T mul1 = static_cast<T>(2.0) * d * inv; const T mul2 = d * d; return vector3d<T>( X * mul0 + v2.X * mul1 + v3.X * mul2, Y * mul0 + v2.Y * mul1 + v3.Y * mul2, Z * mul0 + v2.Z * mul1 + v3.Z * mul2 ); } force_inline vector3d<T> getRotatedAxis(const T &Angle, vector3d<T> Axis) const { if (Angle == T(0)) return *this; Axis.normalize(); vector3d<T> rotMatrixRow1, rotMatrixRow2, rotMatrixRow3; T sinAngle = sin(Angle*DEG); T cosAngle = cos(Angle*DEG); T cosAngleInv = 1.0f - cosAngle; rotMatrixRow1.X = Axis.X*Axis.X + cosAngle*(1.0f - Axis.X*Axis.X); rotMatrixRow1.Y = Axis.X*Axis.Y*cosAngleInv - sinAngle*Axis.Z; rotMatrixRow1.Z = Axis.X*Axis.Z*cosAngleInv + sinAngle*Axis.Y; rotMatrixRow2.X = Axis.X*Axis.Y*cosAngleInv + sinAngle*Axis.Z; rotMatrixRow2.Y = Axis.Y*Axis.Y + cosAngle*(1.0f - Axis.Y*Axis.Y); rotMatrixRow2.Z = Axis.Y*Axis.Z*cosAngleInv - sinAngle*Axis.X; rotMatrixRow3.X = Axis.X*Axis.Z*cosAngleInv - sinAngle*Axis.Y; rotMatrixRow3.Y = Axis.Y*Axis.Z*cosAngleInv + sinAngle*Axis.X; rotMatrixRow3.Z = Axis.Z*Axis.Z + cosAngle*(1.0f - Axis.Z*Axis.Z); return vector3d<T>( dot(rotMatrixRow1), dot(rotMatrixRow2), dot(rotMatrixRow3) ); } //! Returns the direction type of the dominant axis. force_inline EAxisTypes getAxisType() const { const vector3d<T> AbsDir(getAbs()); if (AbsDir.X >= AbsDir.Y && AbsDir.X >= AbsDir.Z) return (X > 0 ? AXIS_X_POSITIVE : AXIS_X_NEGATIVE); else if (AbsDir.Y >= AbsDir.X && AbsDir.Y >= AbsDir.Z) return (Y > 0 ? AXIS_Y_POSITIVE : AXIS_Y_NEGATIVE); return (Z > 0 ? AXIS_Z_POSITIVE : AXIS_Z_NEGATIVE); } //! Returns a normal vector to this vector. force_inline vector3d<T> getNormal() const { if (X > Y && X > Z) return vector3d<T>(Y, -X, 0); else if (Y > X && Y > Z) return vector3d<T>(0, Z, -Y); return vector3d<T>(-Z, 0, X); } //! Returns the smalest vector component. force_inline T getMin() const { if (X <= Y && X <= Z) return X; if (Y <= X && Y <= Z) return Y; return Z; } //! Returns the greatest vector component. force_inline T getMax() const { if (X >= Y && X >= Z) return X; if (Y >= X && Y >= Z) return Y; return Z; } //! Returns the volume of the bounding box clamped by this vector (X*Y*Z). force_inline T getVolume() const { return X*Y*Z; } /** Just returns this vector. This is only required that this call can be used for several templates. Write your own vertex class for example and add this function so that it can be used for polygon clipping as well. Some templates expect a class with this function (e.g. 'CollisionLibrary::clipPolygon'). \see CollisionLibrary::clipPolygon */ force_inline vector3d<T> getCoord() const { return *this; } template <typename B> force_inline vector3d<B> cast() const { return vector3d<B>(static_cast<B>(X), static_cast<B>(Y), static_cast<B>(Z)); } static force_inline bool isPointOnSameSide( const vector3d<T> &P1, const vector3d<T> &P2, const vector3d<T> &A, const vector3d<T> &B) { vector3d<T> Difference(B - A); vector3d<T> P3 = Difference.cross(P1 - A); vector3d<T> P4 = Difference.cross(P2 - A); return P3.dot(P4) >= T(0); } /* === Members === */ T X, Y, Z; }; typedef vector3d<int32_t> vector3di; typedef vector3d<float> vector3df; /* * vector4d class */ //! \todo Write this in an own class and don't inherit from "vector3d". template <typename T> class vector4d : public vector3d<T> { public: force_inline vector4d() : vector3d<T>(), W(1) { } force_inline vector4d(T Size) : vector3d<T>(Size), W(1) { } force_inline vector4d(T VecX, T VecY, T VecZ, T VecW = static_cast<T>(1)) : vector3d<T>(VecX, VecY, VecZ), W(VecW) { } force_inline vector4d(const vector3d<T> &other, T VecW = static_cast<T>(1)) : vector3d<T>(other.X, other.Y, other.Z), W(VecW) { } force_inline vector4d(const vector4d<T> &other) : vector3d<T>(other.X, other.Y, other.Z), W(other.W) { } force_inline ~vector4d() { } /* Members */ T W; }; template <typename T> force_inline vector3d<T>::vector3d(const vector4d<T> &Other) : X(Other.X), Y(Other.Y), Z(Other.Z) { } typedef vector4d<int32_t> vector4di; typedef vector4d<float> vector4df; // ================================================================================ //! Returns the distance between the two given 3D points. template <typename T> force_inline T getDistance(const vector3d<T> &PosA, const vector3d<T> &PosB) { return Sqrt(Pow2(PosB.X - PosA.X) + Pow2(PosB.Y - PosA.Y) + Pow2(PosB.Z - PosA.Z)); }
[ "esrrhs@localhost" ]
esrrhs@localhost
885e8b85328900dc8171d47081d0ac4e7ac1cb56
8f1cb14ceb23006a3c9bdf9e5c63ede1de7f23b2
/Unreal/UnMesh3.cpp
be98910e573d4155ba1fe0365c2ddabcfaa20c26
[ "BSD-3-Clause" ]
permissive
Rikoshet-234/UModel
51a06285be3b6c346b1dad12657faea5acda1810
d1130ca345d643afef53662607bba7787b21eec9
refs/heads/master
2020-07-04T05:31:42.168229
2019-08-02T14:38:01
2019-08-02T14:38:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
90,488
cpp
#include "Core.h" #if UNREAL3 #include "UnrealClasses.h" #include "UnMesh3.h" #include "UnMeshTypes.h" #include "UnMathTools.h" // for FRotator to FCoords #include "UnMaterial3.h" #include "SkeletalMesh.h" #include "StaticMesh.h" #include "TypeConvert.h" //#define DEBUG_SKELMESH 1 //#define DEBUG_STATICMESH 1 #if DEBUG_SKELMESH #define DBG_SKEL(...) appPrintf(__VA_ARGS__); #else #define DBG_SKEL(...) #endif #if DEBUG_STATICMESH #define DBG_STAT(...) appPrintf(__VA_ARGS__); #else #define DBG_STAT(...) #endif //!! RENAME to CopyNormals/ConvertNormals/PutNormals/RepackNormals etc void UnpackNormals(const FPackedNormal SrcNormal[3], CMeshVertex &V) { // tangents: convert to FVector (unpack) then cast to CVec3 V.Tangent = CVT(SrcNormal[0]); V.Normal = CVT(SrcNormal[2]); // new UE3 version - binormal is not serialized and restored in vertex shader if (SrcNormal[1].Data != 0) { // pack binormal sign into Normal.W FVector Tangent = SrcNormal[0]; FVector Binormal = SrcNormal[1]; FVector Normal = SrcNormal[2]; CVec3 ComputedBinormal; cross(CVT(Normal), CVT(Tangent), ComputedBinormal); float Sign = dot(CVT(Binormal), ComputedBinormal); V.Normal.SetW(Sign > 0 ? 1.0f : -1.0f); } } /*----------------------------------------------------------------------------- USkeletalMesh -----------------------------------------------------------------------------*/ #define NUM_INFLUENCES_UE3 4 #define NUM_UV_SETS_UE3 4 #if NUM_INFLUENCES_UE3 != NUM_INFLUENCES #error NUM_INFLUENCES_UE3 and NUM_INFLUENCES are not matching! #endif #if NUM_UV_SETS_UE3 > MAX_MESH_UV_SETS #error NUM_UV_SETS_UE3 too large! #endif // Implement constructor in cpp to avoid inlining (it's large enough). // It's useful to declare TArray<> structures as forward declarations in header file. USkeletalMesh3::USkeletalMesh3() : bHasVertexColors(false) , ConvertedMesh(NULL) #if BATMAN , EnableTwistBoneFixers(true) , EnableClavicleFixer(true) #endif {} USkeletalMesh3::~USkeletalMesh3() { delete ConvertedMesh; } #if MURDERED struct FSkelMeshSection_MurderedUnk { TArray<byte> unk1, unk2; friend FArchive& operator<<(FArchive &Ar, FSkelMeshSection_MurderedUnk &V) { Ar << V.unk1 << V.unk2; Ar.Seek(Ar.Tell() + 8 * sizeof(int16) + 2 * sizeof(int32) + 5 * sizeof(int16)); return Ar; } }; #endif // MURDERED struct FSkelMeshSection3 { int16 MaterialIndex; int16 ChunkIndex; int FirstIndex; int NumTriangles; byte unk2; friend FArchive& operator<<(FArchive &Ar, FSkelMeshSection3 &S) { guard(FSkelMeshSection3<<); if (Ar.ArVer < 215) { // UE2 fields int16 FirstIndex; int16 unk1, unk2, unk3, unk4, unk5, unk6; TArray<int16> unk8; Ar << S.MaterialIndex << FirstIndex << unk1 << unk2 << unk3 << unk4 << unk5 << unk6 << S.NumTriangles; if (Ar.ArVer < 202) Ar << unk8; // ArVer<202 -- from EndWar S.FirstIndex = FirstIndex; S.ChunkIndex = 0; return Ar; } #if MURDERED if (Ar.Game == GAME_Murdered && Ar.ArLicenseeVer >= 85) { byte flag; Ar << flag; if (flag) { TArray<FSkelMeshSection_MurderedUnk> unk1; int unk2; Ar << unk1 << unk2; } } #endif // MURDERED Ar << S.MaterialIndex << S.ChunkIndex << S.FirstIndex; #if BATMAN if (Ar.Game == GAME_Batman3) goto old_section; // Batman1 and 2 has version smaller than 806; Batman3 has outdated code, but Batman4 - new one #endif #if MKVSDC if (Ar.Game == GAME_MK && Ar.ArVer >= 677) goto new_section; // MK X #endif if (Ar.ArVer < 806) { old_section: // NumTriangles is 16-bit here uint16 NumTriangles; Ar << NumTriangles; S.NumTriangles = NumTriangles; } else { new_section: // NumTriangles is int Ar << S.NumTriangles; } #if MCARTA if (Ar.Game == GAME_MagnaCarta && Ar.ArLicenseeVer >= 20) { int fC; Ar << fC; } #endif // MCARTA #if BLADENSOUL if (Ar.Game == GAME_BladeNSoul && Ar.ArVer >= 571) goto new_ver; #endif if (Ar.ArVer >= 599) { new_ver: Ar << S.unk2; } #if MASSEFF if (Ar.Game == GAME_MassEffect3 && Ar.ArLicenseeVer >= 135) { byte SomeFlag; Ar << SomeFlag; assert(SomeFlag == 0); // has extra data here in a case of SomeFlag != 0 } #endif // MASSEFF #if BIOSHOCK3 if (Ar.Game == GAME_Bioshock3) { //!! the same code as for MassEffect3, combine? byte SomeFlag; Ar << SomeFlag; assert(SomeFlag == 0); // has extra data here in a case of SomeFlag != 0 } #endif // BIOSHOCK3 #if REMEMBER_ME if (Ar.Game == GAME_RememberMe && Ar.ArLicenseeVer >= 17) { byte SomeFlag; TArray<byte> SomeArray; Ar << SomeFlag; if (SomeFlag) Ar << SomeArray; } #endif // REMEMBER_ME #if LOST_PLANET3 if (Ar.Game == GAME_LostPlanet3 && Ar.ArLicenseeVer >= 75) { byte SomeFlag; Ar << SomeFlag; assert(SomeFlag == 0); // array of 40-byte structures (serialized size = 36) } #endif // LOST_PLANET3 #if XCOM if (Ar.Game == GAME_XcomB) { int SomeFlag; Ar << SomeFlag; assert(SomeFlag == 0); // extra data } #endif // XCOM return Ar; unguard; } }; // This class is used now for UStaticMesh only struct FIndexBuffer3 { TArray<uint16> Indices; friend FArchive& operator<<(FArchive &Ar, FIndexBuffer3 &I) { guard(FIndexBuffer3<<); int unk; // Revision? I.Indices.BulkSerialize(Ar); if (Ar.ArVer < 297) Ar << unk; // at older version compatible with FRawIndexBuffer return Ar; unguard; } }; struct FSkelIndexBuffer3 // differs from FIndexBuffer3 since version 806 - has ability to store int indices { TArray<uint16> Indices16; TArray<uint32> Indices32; FORCEINLINE bool Is32Bit() const { return (Indices32.Num() != 0); } friend FArchive& operator<<(FArchive &Ar, FSkelIndexBuffer3 &I) { guard(FSkelIndexBuffer3<<); byte ItemSize = 2; #if BATMAN if ((Ar.Game == GAME_Batman2 || Ar.Game == GAME_Batman3) && Ar.ArLicenseeVer >= 45) { int unk34; Ar << unk34; goto old_index_buffer; } #endif // BATMAN #if MKVSDC if (Ar.Game == GAME_MK && Ar.ArVer >= 677) { // MK X Ar << I.Indices16 << I.Indices32; return Ar; } #endif // MKVSDC if (Ar.ArVer >= 806) { int f0; Ar << f0 << ItemSize; } #if PLA if (Ar.Game == GAME_PLA && Ar.ArVer >= 900) { FGuid unk; Ar << unk; } #endif // PLA old_index_buffer: if (ItemSize == 2) { I.Indices16.BulkSerialize(Ar); } else { #if DMC if (Ar.Game == GAME_DmC && ItemSize == 0) return Ar; #endif // DMC if (ItemSize != 4) appPrintf("WARNING: FMultisizeIndexContainer data size %d, assuming int32\n", ItemSize); I.Indices32.BulkSerialize(Ar); } int unk; if (Ar.ArVer < 297) Ar << unk; // at older version compatible with FRawIndexBuffer return Ar; unguard; } }; struct FRigidVertex3 { FVector Pos; FPackedNormal Normal[3]; FMeshUVFloat UV[NUM_UV_SETS_UE3]; byte BoneIndex; int Color; friend FArchive& operator<<(FArchive &Ar, FRigidVertex3 &V) { int NumUVSets = 1; #if ENDWAR if (Ar.Game == GAME_EndWar) { // End War uses 4-component FVector everywhere, but here it is 3-component Ar << V.Pos.X << V.Pos.Y << V.Pos.Z; goto normals; } #endif // ENDWAR Ar << V.Pos; #if CRIMECRAFT if (Ar.Game == GAME_CrimeCraft) { if (Ar.ArLicenseeVer >= 1) Ar.Seek(Ar.Tell() + sizeof(float)); if (Ar.ArLicenseeVer >= 2) NumUVSets = 4; } #endif // CRIMECRAFT #if DUNDEF if (Ar.Game == GAME_DunDef && Ar.ArLicenseeVer >= 21) NumUVSets = 4; #endif // DUNDEF // note: version prior 477 have different normal/tangent format (same layout, but different // data meaning) normals: Ar << V.Normal[0] << V.Normal[1] << V.Normal[2]; #if R6VEGAS if (Ar.Game == GAME_R6Vegas2 && Ar.ArLicenseeVer >= 63) { FMeshUVHalf hUV; Ar << hUV; V.UV[0] = hUV; // convert goto influences; } #endif // R6VEGAS // UVs if (Ar.ArVer >= 709) NumUVSets = 4; #if MEDGE if (Ar.Game == GAME_MirrorEdge && Ar.ArLicenseeVer >= 13) NumUVSets = 3; #endif #if MKVSDC || STRANGLE || TRANSFORMERS if ((Ar.Game == GAME_MK && Ar.ArLicenseeVer >= 11) || Ar.Game == GAME_Strangle || // Stranglehold check MidwayVer >= 17 (Ar.Game == GAME_Transformers && Ar.ArLicenseeVer >= 55)) NumUVSets = 2; #endif #if FRONTLINES if (Ar.Game == GAME_Frontlines) { if (Ar.ArLicenseeVer >= 3 && Ar.ArLicenseeVer <= 52) // Frontlines (the code in Homefront uses different version comparison!) NumUVSets = 2; else if (Ar.ArLicenseeVer > 52) { byte Num; Ar << Num; NumUVSets = Num; } } #endif // FRONTLINES // UV for (int i = 0; i < NumUVSets; i++) Ar << V.UV[i]; if (Ar.ArVer >= 710) Ar << V.Color; // default 0xFFFFFFFF #if MCARTA if (Ar.Game == GAME_MagnaCarta && Ar.ArLicenseeVer >= 5) { int f20; Ar << f20; } #endif // MCARTA influences: Ar << V.BoneIndex; #if FRONTLINES if (Ar.Game == GAME_Frontlines && Ar.ArLicenseeVer >= 88) { int unk24; Ar << unk24; } #endif // FRONTLINES return Ar; } }; struct FSoftVertex3 { FVector Pos; FPackedNormal Normal[3]; FMeshUVFloat UV[NUM_UV_SETS_UE3]; byte BoneIndex[NUM_INFLUENCES_UE3]; byte BoneWeight[NUM_INFLUENCES_UE3]; int Color; friend FArchive& operator<<(FArchive &Ar, FSoftVertex3 &V) { int i; int NumUVSets = 1; #if ENDWAR if (Ar.Game == GAME_EndWar) { // End War uses 4-component FVector everywhere, but here it is 3-component Ar << V.Pos.X << V.Pos.Y << V.Pos.Z; goto normals; } #endif // ENDWAR Ar << V.Pos; #if CRIMECRAFT if (Ar.Game == GAME_CrimeCraft) { if (Ar.ArLicenseeVer >= 1) Ar.Seek(Ar.Tell() + sizeof(float)); if (Ar.ArLicenseeVer >= 2) NumUVSets = 4; } #endif // CRIMECRAFT #if DUNDEF if (Ar.Game == GAME_DunDef && Ar.ArLicenseeVer >= 21) NumUVSets = 4; #endif // DUNDEF // note: version prior 477 have different normal/tangent format (same layout, but different // data meaning) normals: Ar << V.Normal[0] << V.Normal[1] << V.Normal[2]; #if R6VEGAS if (Ar.Game == GAME_R6Vegas2 && Ar.ArLicenseeVer >= 63) { FMeshUVHalf hUV; Ar << hUV; V.UV[0] = hUV; // convert goto influences; } #endif // R6VEGAS // UVs if (Ar.ArVer >= 709) NumUVSets = 4; #if MEDGE if (Ar.Game == GAME_MirrorEdge && Ar.ArLicenseeVer >= 13) NumUVSets = 3; #endif #if MKVSDC || STRANGLE || TRANSFORMERS if ((Ar.Game == GAME_MK && Ar.ArLicenseeVer >= 11) || Ar.Game == GAME_Strangle || // Stranglehold check MidwayVer >= 17 (Ar.Game == GAME_Transformers && Ar.ArLicenseeVer >= 55)) NumUVSets = 2; #endif #if FRONTLINES if (Ar.Game == GAME_Frontlines) { if (Ar.ArLicenseeVer >= 3 && Ar.ArLicenseeVer <= 52) // Frontlines (the code in Homefront uses different version comparison!) NumUVSets = 2; else if (Ar.ArLicenseeVer > 52) { byte Num; Ar << Num; NumUVSets = Num; } } #endif // FRONTLINES // UV for (int i = 0; i < NumUVSets; i++) Ar << V.UV[i]; if (Ar.ArVer >= 710) Ar << V.Color; // default 0xFFFFFFFF #if FRONTLINES if (Ar.Game == GAME_Frontlines && Ar.ArLicenseeVer >= 88) { int unk24; Ar << unk24; } #endif // FRONTLINES influences: if (Ar.ArVer >= 333) { for (i = 0; i < NUM_INFLUENCES_UE3; i++) Ar << V.BoneIndex[i]; for (i = 0; i < NUM_INFLUENCES_UE3; i++) Ar << V.BoneWeight[i]; } else { for (i = 0; i < NUM_INFLUENCES_UE3; i++) Ar << V.BoneIndex[i] << V.BoneWeight[i]; } #if MCARTA if (Ar.Game == GAME_MagnaCarta && Ar.ArLicenseeVer >= 5) { int f28; Ar << f28; } #endif // MCARTA return Ar; } }; #if MKVSDC struct FMesh3Unk4_MK { uint16 data[4]; friend FArchive& operator<<(FArchive &Ar, FMesh3Unk4_MK &S) { return Ar << S.data[0] << S.data[1] << S.data[2] << S.data[3]; } }; #endif // MKVSDC struct FSkelMeshChunk3 { int FirstVertex; TArray<FRigidVertex3> RigidVerts; TArray<FSoftVertex3> SoftVerts; TArray<int16> Bones; int NumRigidVerts; int NumSoftVerts; int MaxInfluences; friend FArchive& operator<<(FArchive &Ar, FSkelMeshChunk3 &V) { guard(FSkelMeshChunk3<<); Ar << V.FirstVertex << V.RigidVerts << V.SoftVerts; #if MKVSDC if (Ar.Game == GAME_MK && Ar.ArVer >= 459) { TArray<FMesh3Unk4_MK> unk1C, unk28; Ar << unk1C << unk28; } #endif // MKVSDC Ar << V.Bones; if (Ar.ArVer >= 333) { Ar << V.NumRigidVerts << V.NumSoftVerts; // note: NumRigidVerts and NumSoftVerts may be non-zero while corresponding // arrays are empty - that's when GPU skin only left } else { V.NumRigidVerts = V.RigidVerts.Num(); V.NumSoftVerts = V.SoftVerts.Num(); } #if ARMYOF2 if (Ar.Game == GAME_ArmyOf2 && Ar.ArLicenseeVer >= 7) { TArray<FMeshUVFloat> extraUV; extraUV.BulkSerialize(Ar); } #endif // ARMYOF2 if (Ar.ArVer >= 362) Ar << V.MaxInfluences; #if TRANSFORMERS if (Ar.Game == GAME_Transformers && Ar.ArLicenseeVer >= 55) { int NumTexCoords; Ar << NumTexCoords; } #endif // TRANSFORMERS DBG_SKEL("Chunk: FirstVert=%d RigidVerts=%d (%d) SoftVerts=%d (%d) MaxInfs=%d\n", V.FirstVertex, V.RigidVerts.Num(), V.NumRigidVerts, V.SoftVerts.Num(), V.NumSoftVerts, V.MaxInfluences); return Ar; unguard; } }; struct FEdge3 { int iVertex[2]; int iFace[2]; friend FArchive& operator<<(FArchive &Ar, FEdge3 &V) { #if BATMAN if (Ar.Game == GAME_Batman && Ar.ArLicenseeVer >= 5) { int16 iVertex[2], iFace[2]; Ar << iVertex[0] << iVertex[1] << iFace[0] << iFace[1]; V.iVertex[0] = iVertex[0]; V.iVertex[1] = iVertex[1]; V.iFace[0] = iFace[0]; V.iFace[1] = iFace[1]; return Ar; } #endif // BATMAN return Ar << V.iVertex[0] << V.iVertex[1] << V.iFace[0] << V.iFace[1]; } }; // Structure holding normals and bone influeces struct FGPUVert3Common { FPackedNormal Normal[3]; byte BoneIndex[NUM_INFLUENCES_UE3]; byte BoneWeight[NUM_INFLUENCES_UE3]; void Serialize(FArchive &Ar) { #if AVA if (Ar.Game == GAME_AVA) goto new_ver; #endif if (Ar.ArVer < 494) Ar << Normal[0] << Normal[1] << Normal[2]; else { new_ver: Ar << Normal[0] << Normal[2]; } #if CRIMECRAFT || FRONTLINES if ((Ar.Game == GAME_CrimeCraft && Ar.ArLicenseeVer >= 1) || (Ar.Game == GAME_Frontlines && Ar.ArLicenseeVer >= 88)) Ar.Seek(Ar.Tell() + sizeof(float)); // pad or vertex color? #endif int i; for (i = 0; i < NUM_INFLUENCES_UE3; i++) Ar << BoneIndex[i]; for (i = 0; i < NUM_INFLUENCES_UE3; i++) Ar << BoneWeight[i]; #if GUILTY if (Ar.Game == GAME_Guilty && Ar.ArLicenseeVer >= 1) { int unk; // probably vertex color - this was removed from FStaticLODModel3 serializer Ar << unk; } #endif // GUILTY } }; static int GNumGPUUVSets = 1; struct FGPUVert3Half : FGPUVert3Common { FVector Pos; FMeshUVHalf UV[NUM_UV_SETS_UE3]; friend FArchive& operator<<(FArchive &Ar, FGPUVert3Half &V) { if (Ar.ArVer < 592) Ar << V.Pos; V.Serialize(Ar); if (Ar.ArVer >= 592) Ar << V.Pos; for (int i = 0; i < GNumGPUUVSets; i++) Ar << V.UV[i]; return Ar; } }; struct FGPUVert3Float : FGPUVert3Common { FVector Pos; FMeshUVFloat UV[NUM_UV_SETS_UE3]; FGPUVert3Float& operator=(const FSoftVertex3 &S) { int i; Pos = S.Pos; Normal[0] = S.Normal[0]; Normal[1] = S.Normal[1]; Normal[2] = S.Normal[2]; for (i = 0; i < NUM_UV_SETS_UE3; i++) UV[i] = S.UV[i]; for (i = 0; i < NUM_INFLUENCES_UE3; i++) { BoneIndex[i] = S.BoneIndex[i]; BoneWeight[i] = S.BoneWeight[i]; } return *this; } friend FArchive& operator<<(FArchive &Ar, FGPUVert3Float &V) { if (Ar.ArVer < 592) Ar << V.Pos; V.Serialize(Ar); if (Ar.ArVer >= 592) Ar << V.Pos; for (int i = 0; i < GNumGPUUVSets; i++) Ar << V.UV[i]; return Ar; } }; struct FGPUVert3PackedHalf : FGPUVert3Common { FVectorIntervalFixed32GPU Pos; FMeshUVHalf UV[NUM_UV_SETS_UE3]; friend FArchive& operator<<(FArchive &Ar, FGPUVert3PackedHalf &V) { V.Serialize(Ar); Ar << V.Pos; for (int i = 0; i < GNumGPUUVSets; i++) Ar << V.UV[i]; return Ar; } }; struct FGPUVert3PackedFloat : FGPUVert3Common { FVectorIntervalFixed32GPU Pos; FMeshUVFloat UV[NUM_UV_SETS_UE3]; friend FArchive& operator<<(FArchive &Ar, FGPUVert3PackedFloat &V) { V.Serialize(Ar); Ar << V.Pos; for (int i = 0; i < GNumGPUUVSets; i++) Ar << V.UV[i]; return Ar; } }; #if BATMAN struct FGPUVertBat4_HalfUV_Pos48 : FGPUVert3Common { FVectorIntervalFixed64 Pos; FMeshUVHalf UV[NUM_UV_SETS_UE3]; friend FArchive& operator<<(FArchive &Ar, FGPUVertBat4_HalfUV_Pos48 &V) { V.Serialize(Ar); Ar << V.Pos; for (int i = 0; i < GNumGPUUVSets; i++) Ar << V.UV[i]; return Ar; } }; struct FGPUVertBat4_HalfUV_Pos32 : FGPUVert3Common { FVectorIntervalFixed32Bat4 Pos; FMeshUVHalf UV[NUM_UV_SETS_UE3]; friend FArchive& operator<<(FArchive &Ar, FGPUVertBat4_HalfUV_Pos32 &V) { V.Serialize(Ar); Ar << V.Pos; for (int i = 0; i < GNumGPUUVSets; i++) Ar << V.UV[i]; return Ar; } }; #endif // BATMAN struct FSkeletalMeshVertexBuffer3 { int NumUVSets; int bUseFullPrecisionUVs; // 0 = half, 1 = float; copy of corresponding USkeletalMesh field // compressed position data int bUsePackedPosition; // 1 = packed FVector (32-bit), 0 = FVector (96-bit) FVector MeshOrigin; FVector MeshExtension; // vertex sets TArray<FGPUVert3Half> VertsHalf; // only one of these vertex sets are used TArray<FGPUVert3Float> VertsFloat; TArray<FGPUVert3PackedHalf> VertsHalfPacked; TArray<FGPUVert3PackedFloat> VertsFloatPacked; inline int GetVertexCount() const { if (VertsHalf.Num()) return VertsHalf.Num(); if (VertsFloat.Num()) return VertsFloat.Num(); if (VertsHalfPacked.Num()) return VertsHalfPacked.Num(); if (VertsFloatPacked.Num()) return VertsFloatPacked.Num(); return 0; } friend FArchive& operator<<(FArchive &Ar, FSkeletalMeshVertexBuffer3 &S) { guard(FSkeletalMeshVertexBuffer3<<); DBG_SKEL("Reading GPU skin\n"); if (Ar.IsLoading) S.bUsePackedPosition = false; bool AllowPackedPosition = false; S.NumUVSets = GNumGPUUVSets = 1; #if HUXLEY if (Ar.Game == GAME_Huxley) goto old_version; #endif #if AVA if (Ar.Game == GAME_AVA) { // different ArVer to check if (Ar.ArVer < 441) goto old_version; else goto new_version; } #endif // AVA #if FRONTLINES if (Ar.Game == GAME_Frontlines) { if (Ar.ArLicenseeVer < 11) goto old_version; if (Ar.ArVer < 493 ) S.bUseFullPrecisionUVs = true; else Ar << S.bUseFullPrecisionUVs; int VertexSize, NumVerts; Ar << S.NumUVSets << VertexSize << NumVerts; assert(S.NumUVSets > 0 && S.NumUVSets < 32); // just verify for some reasonable value GNumGPUUVSets = S.NumUVSets; goto serialize_verts; } #endif // FRONTLINES #if ARMYOF2 if (Ar.Game == GAME_ArmyOf2 && Ar.ArLicenseeVer >= 74) { int UseNewFormat; Ar << UseNewFormat; if (UseNewFormat) { appError("ArmyOfTwo: new vertex format!"); return Ar; } } #endif // ARMYOF2 if (Ar.ArVer < 493) { old_version: // old version - FSoftVertex3 array TArray<FSoftVertex3> Verts; Verts.BulkSerialize(Ar); DBG_SKEL("... %d verts in old format\n", Verts.Num()); // convert verts CopyArray(S.VertsFloat, Verts); S.bUseFullPrecisionUVs = true; return Ar; } // new version new_version: // serialize type information #if MEDGE if (Ar.Game == GAME_MirrorEdge && Ar.ArLicenseeVer >= 15) goto get_UV_count; #endif #if TRANSFORMERS if (Ar.Game == GAME_Transformers && Ar.ArLicenseeVer >= 55) goto get_UV_count; // 1 or 2 #endif #if DUNDEF if (Ar.Game == GAME_DunDef && Ar.ArLicenseeVer >= 21) goto get_UV_count; #endif if (Ar.ArVer >= 709) { get_UV_count: Ar << S.NumUVSets; GNumGPUUVSets = S.NumUVSets; } Ar << S.bUseFullPrecisionUVs; if (Ar.ArVer >= 592) Ar << S.bUsePackedPosition << S.MeshExtension << S.MeshOrigin; if (Ar.Platform == PLATFORM_XBOX360 || Ar.Platform == PLATFORM_PS3) AllowPackedPosition = true; #if MOH2010 if (Ar.Game == GAME_MOH2010) AllowPackedPosition = true; #endif #if MKVSDC if (Ar.Game == GAME_MK && Ar.ArVer >= 573) GNumGPUUVSets = S.NumUVSets = 2; // Injustice #endif #if CRIMECRAFT if (Ar.Game == GAME_CrimeCraft && Ar.ArLicenseeVer >= 2) S.NumUVSets = GNumGPUUVSets = 4; #endif #if LOST_PLANET3 if (Ar.Game == GAME_LostPlanet3 && Ar.ArLicenseeVer >= 75) { int NoUV; Ar << NoUV; assert(!NoUV); // when NoUV - special vertex format used: FCompNormal[2] + FVector (or something like this?) } #endif // LOST_PLANET3 // UE3 PC version ignored bUsePackedPosition - forced !bUsePackedPosition in FSkeletalMeshVertexBuffer3 serializer. // Note: in UDK (newer engine) there is no code to serialize GPU vertex with packed position. // Working bUsePackedPosition version was found in all XBox360 games. For PC there is only one game - // MOH2010, which uses bUsePackedPosition. PS3 also has bUsePackedPosition support (at least TRON) DBG_SKEL("... data: packUV:%d packPos:%d%s numUV:%d PackPos:(%g %g %g)+(%g %g %g)\n", !S.bUseFullPrecisionUVs, S.bUsePackedPosition, AllowPackedPosition ? "" : " (disabled)", S.NumUVSets, FVECTOR_ARG(S.MeshOrigin), FVECTOR_ARG(S.MeshExtension)); if (!AllowPackedPosition) S.bUsePackedPosition = false; // not used in games (see comment above) #if PLA if (Ar.Game == GAME_PLA && Ar.ArVer >= 900) { FGuid unk; Ar << unk; } #endif // PLA #if BATMAN if (Ar.Game == GAME_Batman4 && Ar.ArLicenseeVer >= 192) { S.Serialize_Batman4Verts(Ar); goto after_serialize_verts; } #endif // BATMAN serialize_verts: // serialize vertex array if (!S.bUseFullPrecisionUVs) { if (!S.bUsePackedPosition) S.VertsHalf.BulkSerialize(Ar); else S.VertsHalfPacked.BulkSerialize(Ar); } else { if (!S.bUsePackedPosition) S.VertsFloat.BulkSerialize(Ar); else S.VertsFloatPacked.BulkSerialize(Ar); } after_serialize_verts: DBG_SKEL("... verts: Half[%d] HalfPacked[%d] Float[%d] FloatPacked[%d]\n", S.VertsHalf.Num(), S.VertsHalfPacked.Num(), S.VertsFloat.Num(), S.VertsFloatPacked.Num()); #if BATMAN if (Ar.Game == GAME_Batman4 && Ar.ArLicenseeVer >= 190) { TArray<FVector> unk1; int unk2; Ar << unk1 << unk2; } #endif // BATMAN return Ar; unguard; } #if BATMAN void Serialize_Batman4Verts(FArchive &Ar) { guard(Serialize_Batman4Verts); //!! TODO: that'd be great to move this function to UnMeshBatman.cpp, but it requires vertex declatations. //!! Batman4 vertex is derived from FGPUVert3Common. int BatmanPackType; Ar << BatmanPackType; // 0 = FVector // 1 = int16[4] // 2 = int16[4] // 3 = int32 (packed) DBG_SKEL("... bat4 position pack: %d\n", BatmanPackType); if (!bUseFullPrecisionUVs) { // half-precision UVs switch (BatmanPackType) { case 1: case 2: { TArray<FGPUVertBat4_HalfUV_Pos48> Verts; Verts.BulkSerialize(Ar); // copy data VertsHalf.AddUninitialized(Verts.Num()); for (int i = 0; i < Verts.Num(); i++) { const FGPUVertBat4_HalfUV_Pos48& S = Verts[i]; FGPUVert3Half& D = VertsHalf[i]; (FGPUVert3Common&)D = (FGPUVert3Common&)S; memcpy(D.UV, S.UV, sizeof(S.UV)); D.Pos = S.Pos.ToVector(MeshOrigin, MeshExtension); } } return; case 3: { TArray<FGPUVertBat4_HalfUV_Pos32> Verts; Verts.BulkSerialize(Ar); // copy data VertsHalf.AddUninitialized(Verts.Num()); for (int i = 0; i < Verts.Num(); i++) { const FGPUVertBat4_HalfUV_Pos32& S = Verts[i]; FGPUVert3Half& D = VertsHalf[i]; (FGPUVert3Common&)D = (FGPUVert3Common&)S; memcpy(D.UV, S.UV, sizeof(S.UV)); D.Pos = S.Pos.ToVector(MeshOrigin, MeshExtension); } } return; default: VertsHalf.BulkSerialize(Ar); return; } } else { // float-precision UVs switch (BatmanPackType) { case 1: case 2: case 3: appError("Batman4 GPU vertex type %d", BatmanPackType); // VertsFloatPacked.BulkSerialize(Ar); return; default: VertsFloat.BulkSerialize(Ar); return; } } unguard; } #endif // BATMAN #if MKVSDC void Serialize_MK10(FArchive &Ar, int NumVertices) { guard(FSkeletalMeshVertexBuffer3::Serialize_MK10); // MK X vertex data // Position stream int PositionSize, NumPosVerts; Ar << PositionSize << NumPosVerts; assert(PositionSize == 12 && NumPosVerts == NumVertices); TArray<FVector> Positions; Ar << Positions; // Normal stream int NormalSize, NumNormals; Ar << NormalSize << NumNormals; assert(NormalSize == 8 && NumNormals == NumVertices); TArrayOfArray<FPackedNormal, 2> Normals; Ar << Normals; // Influence stream int InfSize, NumInfs; Ar << InfSize << NumInfs; assert(InfSize == 8 && NumInfs == NumVertices); TArray<int64> Infs; Ar << Infs; // UVs int UVSize, NumUVs; Ar << NumUVSets << UVSize << NumUVs; TArray<FMeshUVHalf> UVs; Ar << UVs; assert(NumUVs == NumVertices * NumUVSets); // skip everything else, would fail if number of LODs is > 1 // combine vertex data VertsHalf.AddZeroed(NumVertices); int UVIndex = 0; for (int i = 0; i < NumVertices; i++) { FGPUVert3Half& V = VertsHalf[i]; memset(&V, 0, sizeof(V)); V.Pos = Positions[i]; V.Normal[0] = Normals[i].Data[0]; V.Normal[2] = Normals[i].Data[1]; for (int j = 0; j < NumUVSets; j++) { V.UV[j] = UVs[UVIndex++]; } // unpack influences // MK X allows more than 256 bones per section // stored as 10bit BoneIndices[4] + 8bit Weights[3] // 4th weight is restored in shader taking into account that sum is 255 uint64 data = Infs[i]; int b[4], w[4]; b[0] = data & 0x3FF; b[1] = (data >> 10) & 0x3FF; b[2] = (data >> 20) & 0x3FF; b[3] = (data >> 30) & 0x3FF; w[0] = (data >> 40) & 0xFF; w[1] = (data >> 48) & 0xFF; w[2] = (data >> 56) & 0xFF; w[3] = 255 - w[0] - w[1] - w[2]; for (int j = 0; j < 4; j++) { assert(b[j] < 256); V.BoneIndex[j] = b[j]; V.BoneWeight[j] = w[j]; } } unguard; } #endif // MKVSDC }; // real name: FVertexInfluence struct FVertexInfluence { int Weights; int Boned; friend FArchive& operator<<(FArchive &Ar, FVertexInfluence &S) { return Ar << S.Weights << S.Boned; } }; SIMPLE_TYPE(FVertexInfluence, int) // In UE4.0: TMap<FBoneIndexPair, TArray<uint16> > struct FVertexInfluenceMapOld { // key int f0; int f4; // value TArray<uint16> f8; friend FArchive& operator<<(FArchive &Ar, FVertexInfluenceMapOld &S) { Ar << S.f0 << S.f4 << S.f8; return Ar; } }; // In UE4.0: TMap<FBoneIndexPair, TArray<uint32> > struct FVertexInfluenceMap { // key int f0; int f4; // value TArray<int> f8; friend FArchive& operator<<(FArchive &Ar, FVertexInfluenceMap &S) { Ar << S.f0 << S.f4 << S.f8; return Ar; } }; struct FSkeletalMeshVertexInfluences { TArray<FVertexInfluence> Influences; TArray<FVertexInfluenceMap> VertexInfluenceMapping; TArray<FSkelMeshSection3> Sections; TArray<FSkelMeshChunk3> Chunks; TArray<byte> RequiredBones; byte Usage; // default = 0 friend FArchive& operator<<(FArchive &Ar, FSkeletalMeshVertexInfluences &S) { guard(FSkeletalMeshVertexInfluences<<); DBG_SKEL("Extra vertex influence:\n"); Ar << S.Influences; if (Ar.ArVer >= 609) { if (Ar.ArVer >= 808) { Ar << S.VertexInfluenceMapping; } else { byte unk1; if (Ar.ArVer >= 806) Ar << unk1; TArray<FVertexInfluenceMapOld> VertexInfluenceMappingOld; Ar << VertexInfluenceMappingOld; } } if (Ar.ArVer >= 700) Ar << S.Sections << S.Chunks; if (Ar.ArVer >= 708) { #if BATMAN if (Ar.Game == GAME_Batman4 && Ar.ArLicenseeVer >= 159) { TArray<int> RequiredBones32; Ar << RequiredBones32; } else #endif { Ar << S.RequiredBones; } } if (Ar.ArVer >= 715) Ar << S.Usage; #if DEBUG_SKELMESH for (int i1 = 0; i1 < S.Sections.Num(); i1++) { FSkelMeshSection3 &Sec = S.Sections[i1]; appPrintf("Sec[%d]: M=%d, FirstIdx=%d, NumTris=%d Chunk=%d\n", i1, Sec.MaterialIndex, Sec.FirstIndex, Sec.NumTriangles, Sec.ChunkIndex); } #endif // DEBUG_SKELMESH return Ar; unguard; } }; #if R6VEGAS struct FMesh3R6Unk1 { byte f[6]; friend FArchive& operator<<(FArchive &Ar, FMesh3R6Unk1 &S) { Ar << S.f[0] << S.f[1] << S.f[2] << S.f[3] << S.f[4]; if (Ar.ArLicenseeVer >= 47) Ar << S.f[5]; return Ar; } }; #endif // R6VEGAS #if TRANSFORMERS struct FTRMeshUnkStream { int ItemSize; int NumVerts; TArray<int> Data; // TArray<FPackedNormal> friend FArchive& operator<<(FArchive &Ar, FTRMeshUnkStream &S) { Ar << S.ItemSize << S.NumVerts; if (S.ItemSize && S.NumVerts) S.Data.BulkSerialize(Ar); return Ar; } }; #endif // TRANSFORMERS // Version references: 180..240 - Rainbow 6: Vegas 2 // Other: GOW PC struct FStaticLODModel3 { //!! field names (from UE4 source): f80 = Size, UsedBones = ActiveBoneIndices, f24 = RequiredBones TArray<FSkelMeshSection3> Sections; TArray<FSkelMeshChunk3> Chunks; FSkelIndexBuffer3 IndexBuffer; TArray<int16> UsedBones; // bones, value = [0, NumBones-1] TArray<byte> f24; // count = NumBones, value = [0, NumBones-1]; note: BoneIndex is 'int16', not 'byte' ... TArray<uint16> f68; // indices, value = [0, NumVertices-1] TArray<byte> f74; // count = NumTriangles int f80; int NumVertices; TArray<FEdge3> Edges; // links 2 vertices and 2 faces (triangles) FWordBulkData BulkData; // ElementCount = NumVertices FIntBulkData BulkData2; // used instead of BulkData since version 806, indices? FSkeletalMeshVertexBuffer3 GPUSkin; TArray<FSkeletalMeshVertexInfluences> ExtraVertexInfluences; // GoW2+ engine int NumUVSets; TArray<int> VertexColor; // since version 710 friend FArchive& operator<<(FArchive &Ar, FStaticLODModel3 &Lod) { guard(FStaticLODModel3<<); #if FURY if (Ar.Game == GAME_Fury && Ar.ArLicenseeVer >= 8) { // TLazyArray-like file pointer int EndArPos; Ar << EndArPos; } #endif // FURY #if MKVSDC if (Ar.Game == GAME_MK && Ar.ArVer >= 472 && Ar.Platform == PLATFORM_PS3) //?? remove this code, doesn't work anyway { // this platform has no IndexBuffer Ar << Lod.Sections; goto part1; } if (Ar.Game == GAME_MK && Ar.ArVer >= 677) { // MK X int unk; Ar << unk; // serialized before FStaticLodModel, inside an array serializer function } #endif // MKVSDC Ar << Lod.Sections << Lod.IndexBuffer; part1: #if DEBUG_SKELMESH for (int i1 = 0; i1 < Lod.Sections.Num(); i1++) { FSkelMeshSection3 &S = Lod.Sections[i1]; appPrintf("Sec[%d]: M=%d, FirstIdx=%d, NumTris=%d Chunk=%d\n", i1, S.MaterialIndex, S.FirstIndex, S.NumTriangles, S.ChunkIndex); } appPrintf("Indices: %d (16) / %d (32)\n", Lod.IndexBuffer.Indices16.Num(), Lod.IndexBuffer.Indices32.Num()); #endif // DEBUG_SKELMESH if (Ar.ArVer < 215) { TArray<FRigidVertex3> RigidVerts; TArray<FSoftVertex3> SoftVerts; Ar << SoftVerts << RigidVerts; appNotify("SkeletalMesh: untested code! (ArVer=%d)", Ar.ArVer); } #if ENDWAR || BORDERLANDS if (Ar.Game == GAME_EndWar || (Ar.Game == GAME_Borderlands && Ar.ArLicenseeVer >= 57)) //!! Borderlands version unknown { // refined field set Ar << Lod.UsedBones << Lod.Chunks << Lod.f80 << Lod.NumVertices; goto part2; } #endif // ENDWAR || BORDERLANDS #if TRANSFORMERS if (Ar.Game == GAME_Transformers && Ar.ArVer >= 536) { // Transformers: Dark of the Moon // refined field set + byte bone indices assert(Ar.ArLicenseeVer >= 152); // has mixed version comparisons - ArVer >= 536 and ArLicenseeVer >= 152 TArray<byte> UsedBones2; Ar << UsedBones2; CopyArray(Lod.UsedBones, UsedBones2); // byte -> int Ar << Lod.Chunks << Lod.NumVertices; goto part2; } #endif // TRANSFORMERS if (Ar.ArVer < 686) Ar << Lod.f68; Ar << Lod.UsedBones; if (Ar.ArVer < 686) Ar << Lod.f74; if (Ar.ArVer >= 215) { Ar << Lod.Chunks << Lod.f80 << Lod.NumVertices; } DBG_SKEL("%d chunks, %d bones, %d verts\n", Lod.Chunks.Num(), Lod.UsedBones.Num(), Lod.NumVertices); #if FRONTLINES if (Ar.Game == GAME_Frontlines && Ar.ArLicenseeVer >= 11) { int unk84; Ar << unk84; // default is 1 } #endif if (Ar.ArVer < 686) Ar << Lod.Edges; if (Ar.ArVer < 202) { #if 0 // old version TLazyArray<FVertInfluence> Influences; TLazyArray<FMeshWedge> Wedges; TLazyArray<FMeshFace> Faces; TLazyArray<FVector> Points; Ar << Influences << Wedges << Faces << Points; #else appError("Old UE3 FStaticLodModel"); #endif } #if STRANGLE if (Ar.Game == GAME_Strangle) { // also check MidwayTag == "WOO " and MidwayVer >= 346 // f24 has been moved to the end Lod.BulkData.Serialize(Ar); Ar << Lod.GPUSkin; Ar << Lod.f24; return Ar; } #endif // STRANGLE #if DMC if (Ar.Game == GAME_DmC && Ar.ArLicenseeVer >= 3) goto word_f24; #endif #if BATMAN if (Ar.Game == GAME_Batman4 && Ar.ArLicenseeVer >= 159) { TArray<int> f24_new; Ar << f24_new; goto bulk; } #endif // BATMAN part2: if (Ar.ArVer >= 207) { Ar << Lod.f24; } else { word_f24: TArray<int16> f24_a; Ar << f24_a; } #if APB if (Ar.Game == GAME_APB) { // skip APB bulk; for details check UTexture3::Serialize() Ar.Seek(Ar.Tell() + 8); goto after_bulk; } #endif // APB #if TRANSFORMERS if (Ar.Game == GAME_Transformers && Ar.ArLicenseeVer >= 181) // Transformers: Fall of Cybertron, no version in code goto after_bulk; #endif /*!! PS3 MK: - no Bulk here - int NumSections (equals to Sections.Num()) - int 2 or 4 - 4 x int unknown - int SomeSize - byte[SomeSize] - uint16 SomeSize (same as above) - ... */ bulk: if (Ar.ArVer >= 221) { if (Ar.ArVer < 806) Lod.BulkData.Serialize(Ar); // Bulk of uint16 else Lod.BulkData2.Serialize(Ar); // Bulk of int } after_bulk: #if R6VEGAS if (Ar.Game == GAME_R6Vegas2 && Ar.ArLicenseeVer >= 46) { TArray<FMesh3R6Unk1> unkA0; Ar << unkA0; } #endif // R6VEGAS #if ARMYOF2 if (Ar.Game == GAME_ArmyOf2 && Ar.ArLicenseeVer >= 7) { int unk84; TArray<FMeshUVFloat> extraUV; Ar << unk84; extraUV.BulkSerialize(Ar); } #endif // ARMYOF2 #if BIOSHOCK3 if (Ar.Game == GAME_Bioshock3) { int unkE4; Ar << unkE4; } #endif // BIOSHOCK3 #if REMEMBER_ME if (Ar.Game == GAME_RememberMe && Ar.ArLicenseeVer >= 19) { int unkD4; Ar << unkD4; if (unkD4) appError("RememberMe: new vertex buffer format"); } #endif // REMEMBER_ME #if MKVSDC if (Ar.Game == GAME_MK && Ar.ArVer >= 677) { FByteBulkData UnkBulk; UnkBulk.Skip(Ar); Lod.GPUSkin.Serialize_MK10(Ar, Lod.NumVertices); Lod.NumUVSets = Lod.GPUSkin.NumUVSets; return Ar; } #endif // MKVSDC // UV sets count Lod.NumUVSets = 1; if (Ar.ArVer >= 709) Ar << Lod.NumUVSets; #if DUNDEF if (Ar.Game == GAME_DunDef && Ar.ArLicenseeVer >= 21) Ar << Lod.NumUVSets; #endif DBG_SKEL("NumUVSets=%d\n", Lod.NumUVSets); #if MOH2010 int RealArVer = Ar.ArVer; if (Ar.Game == GAME_MOH2010) { Ar.ArVer = 592; // partially upgraded engine, override version (for easier coding) if (Ar.ArLicenseeVer >= 42) Ar << Lod.ExtraVertexInfluences; // original code: this field is serialized after GPU Skin } #endif // MOH2010 #if FURY if (Ar.Game == GAME_Fury && Ar.ArLicenseeVer >= 34) { int gpuSkinUnk; Ar << gpuSkinUnk; } #endif // FURY if (Ar.ArVer >= 333) Ar << Lod.GPUSkin; #if MKVSDC if (Ar.Game == GAME_MK && Ar.ArVer >= 459) { TArray<FMesh3Unk4_MK> unkA8; Ar << unkA8; return Ar; // no extra fields } #endif // MKVSDC #if MOH2010 if (Ar.Game == GAME_MOH2010) { Ar.ArVer = RealArVer; // restore version if (Ar.ArLicenseeVer >= 42) return Ar; } #endif #if BLOODONSAND if (Ar.Game == GAME_50Cent) return Ar; // new ArVer, but old engine #endif #if MEDGE if (Ar.Game == GAME_MirrorEdge && Ar.ArLicenseeVer >= 15) return Ar; // new ArVer, but old engine #endif // MEDGE #if TRANSFORMERS if (Ar.Game == GAME_Transformers && Ar.ArLicenseeVer >= 73) { FTRMeshUnkStream unkStream; Ar << unkStream; return Ar; } #endif // TRANSFORMERS #if GUILTY if (Ar.Game == GAME_Guilty && Ar.ArLicenseeVer >= 1) goto no_vert_color; #endif if (Ar.ArVer >= 710) { USkeletalMesh3 *LoadingMesh = (USkeletalMesh3*)UObject::GLoadingObj; assert(LoadingMesh); if (LoadingMesh->bHasVertexColors) { #if PLA if (Ar.Game == GAME_PLA && Ar.ArVer >= 900) // this code was guessed, not checked in executable { FGuid unk; Ar << unk; } #endif // PLA Lod.VertexColor.BulkSerialize(Ar); appPrintf("INFO: SkeletalMesh %s has vertex colors\n", LoadingMesh->Name); } } no_vert_color: if (Ar.ArVer >= 534) // post-UT3 code Ar << Lod.ExtraVertexInfluences; if (Ar.ArVer >= 841) // adjacency index buffer { FSkelIndexBuffer3 unk; Ar << unk; } // assert(Lod.IndexBuffer.Indices.Num() == Lod.f68.Num()); -- mostly equals (failed in CH_TwinSouls_Cine.upk) // assert(Lod.BulkData.ElementCount == Lod.NumVertices); -- mostly equals (failed on some GoW packages) #if BATMAN if (Ar.Game == GAME_Batman4 && Ar.ArLicenseeVer >= 107) { TArray<int> unk; Ar << unk; } #endif // BATMAN return Ar; unguard; } }; #if A51 || MKVSDC || STRANGLE || TNA_IMPACT struct FMaterialBone { int Bone; FName Param; friend FArchive& operator<<(FArchive &Ar, FMaterialBone &V) { if (Ar.ArVer >= 573) // Injustice, version unknown { int f1[6], f2[6]; Ar << f1[0] << f1[1] << f1[2] << f1[3] << f1[4] << f1[5]; Ar << V.Param; Ar << f2[0] << f2[1] << f2[2] << f2[3] << f2[4] << f2[5]; return Ar; } return Ar << V.Bone << V.Param; } }; struct FSubSkeleton_MK { FName Name; int BoneSet[8]; // FBoneSet friend FArchive& operator<<(FArchive &Ar, FSubSkeleton_MK &S) { Ar << S.Name; for (int i = 0; i < ARRAY_COUNT(S.BoneSet); i++) Ar << S.BoneSet[i]; return Ar; } }; struct FBoneMirrorInfo_MK { int SourceIndex; byte BoneFlipAxis; // EAxis friend FArchive& operator<<(FArchive &Ar, FBoneMirrorInfo_MK &M) { return Ar << M.SourceIndex << M.BoneFlipAxis; } }; struct FReferenceSkeleton_MK { TArray<VJointPos> RefPose; TArray<int16> Parentage; TArray<FName> BoneNames; TArray<FSubSkeleton_MK> SubSkeletons; TArray<FName> UpperBoneNames; TArray<FBoneMirrorInfo_MK> SkelMirrorTable; byte SkelMirrorAxis; // EAxis byte SkelMirrorFlipAxis; // EAxis friend FArchive& operator<<(FArchive &Ar, FReferenceSkeleton_MK &S) { Ar << S.RefPose << S.Parentage << S.BoneNames; Ar << S.SubSkeletons; // MidwayVer >= 56 Ar << S.UpperBoneNames; // MidwayVer >= 57 Ar << S.SkelMirrorTable << S.SkelMirrorAxis << S.SkelMirrorFlipAxis; return Ar; } }; #endif // MIDWAY ... #if FURY struct FSkeletalMeshLODInfoExtra { int IsForGemini; // bool int IsForTaurus; // bool friend FArchive& operator<<(FArchive &Ar, FSkeletalMeshLODInfoExtra &V) { return Ar << V.IsForGemini << V.IsForTaurus; } }; #endif // FURY #if BATMAN struct FBoneBounds { int BoneIndex; // FSimpleBox FVector Min; FVector Max; friend FArchive& operator<<(FArchive &Ar, FBoneBounds &B) { return Ar << B.BoneIndex << B.Min << B.Max; } }; #endif // BATMAN #if LEGENDARY struct FSPAITag2 { UObject *f0; int f4; friend FArchive& operator<<(FArchive &Ar, FSPAITag2 &S) { Ar << S.f0; if (Ar.ArLicenseeVer < 10) { byte f4; Ar << f4; S.f4 = f4; return Ar; } int f4[9]; // serialize each bit of S.f4 as separate dword Ar << f4[0] << f4[1] << f4[2] << f4[3] << f4[4] << f4[5]; if (Ar.ArLicenseeVer >= 23) Ar << f4[6]; if (Ar.ArLicenseeVer >= 31) Ar << f4[7]; if (Ar.ArLicenseeVer >= 34) Ar << f4[8]; return Ar; } }; #endif // LEGENDARY #if MKVSDC void USkeleton_MK::Serialize(FArchive &Ar) { guard(USkeleton_MK::Serialize); assert(Ar.Game == GAME_MK); Super::Serialize(Ar); Ar << BonePos; Ar << BoneParent; Ar << BoneName; DROP_REMAINING_DATA(Ar); unguard; } #endif // MKVSDC void USkeletalMesh3::Serialize(FArchive &Ar) { guard(USkeletalMesh3::Serialize); #if FRONTLINES if (Ar.Game == GAME_Frontlines && Ar.ArLicenseeVer >= 88) { int unk320; // default 1 Ar << unk320; } #endif // FRONTLINES UObject::Serialize(Ar); // no UPrimitive ... #if MKVSDC if (Ar.Game == GAME_MK && Ar.ArVer >= 677) { Ar << LODModels; // MK X has 1 LODModel and 4 LODInfo if (LODInfo.Num() > LODModels.Num()) LODInfo.RemoveAt(LODModels.Num(), LODInfo.Num() - LODModels.Num()); DROP_REMAINING_DATA(Ar); return; } #endif // MKVSDC #if MEDGE if (Ar.Game == GAME_MirrorEdge && Ar.ArLicenseeVer >= 15) { int unk264; Ar << unk264; } #endif // MEDGE #if FURY if (Ar.Game == GAME_Fury) { int b1, b2, b3, b4; // bools, serialized as ints; LoadForGemini, LoadForTaurus, IsSceneryMesh, IsPlayerMesh TArray<FSkeletalMeshLODInfoExtra> LODInfoExtra; if (Ar.ArLicenseeVer >= 14) Ar << b1 << b2; if (Ar.ArLicenseeVer >= 8) { Ar << b3; Ar << LODInfoExtra; } if (Ar.ArLicenseeVer >= 15) Ar << b4; } #endif // FURY #if DISHONORED if (Ar.Game == GAME_Dishonored && Ar.ArVer >= 759) { // FUserBounds m_UserBounds FName m_BoneName; FVector m_Offset; float m_fRadius; Ar << m_BoneName; if (Ar.ArVer >= 761) Ar << m_Offset; Ar << m_fRadius; } #endif // DISHONORED Ar << Bounds; if (Ar.ArVer < 180) { UObject *unk; Ar << unk; } #if BATMAN if (Ar.Game >= GAME_Batman && Ar.Game <= GAME_Batman4 && Ar.ArLicenseeVer >= 15) { float ConservativeBounds; TArray<FBoneBounds> PerBoneBounds; Ar << ConservativeBounds << PerBoneBounds; } #endif // BATMAN Ar << Materials; #if DEBUG_SKELMESH for (int i1 = 0; i1 < Materials.Num(); i1++) appPrintf("Material[%d] = %s\n", i1, Materials[i1] ? Materials[i1]->Name : "None"); #endif #if BLOODONSAND if (Ar.Game == GAME_50Cent && Ar.ArLicenseeVer >= 65) { TArray<UObject*> OnFireMaterials; // name is not checked Ar << OnFireMaterials; } #endif // BLOODONSAND #if DARKVOID if (Ar.Game == GAME_DarkVoid && Ar.ArLicenseeVer >= 61) { TArray<UObject*> AlternateMaterials; Ar << AlternateMaterials; } #endif // DARKVOID #if ALPHA_PR if (Ar.Game == GAME_AlphaProtocol && Ar.ArLicenseeVer >= 26) { TArray<int> SectionDepthBias; Ar << SectionDepthBias; } #endif // ALPHA_PR #if MKVSDC if (Ar.Game == GAME_MK && Ar.ArVer >= 472) // MK, real version is unknown { FReferenceSkeleton_MK Skel; Ar << Skel << SkeletalDepth; MeshOrigin.Set(0, 0, 0); // not serialized RotOrigin.Set(0, 0, 0); // convert skeleton int NumBones = Skel.RefPose.Num(); assert(NumBones == Skel.Parentage.Num()); assert(NumBones == Skel.BoneNames.Num()); RefSkeleton.AddDefaulted(NumBones); for (int i = 0; i < NumBones; i++) { FMeshBone &B = RefSkeleton[i]; B.Name = Skel.BoneNames[i]; B.BonePos = Skel.RefPose[i]; B.ParentIndex = Skel.Parentage[i]; // appPrintf("BONE: [%d] %s -> %d\n", i, *B.Name, B.ParentIndex); } goto after_skeleton; } #endif // MKVSDC #if ALIENS_CM if (Ar.Game == GAME_AliensCM && Ar.ArVer >= 21) // && Ar.ExtraVer >= 1 { TArray<UObject*> unk; Ar << unk; } #endif // ALIENS_CM Ar << MeshOrigin << RotOrigin; #if DISHONORED if (Ar.Game == GAME_Dishonored && Ar.ArVer >= 775) { TArray<byte> EdgeSkeleton; Ar << EdgeSkeleton; } #endif // DISHONORED #if SOV if (Ar.Game == GAME_SOV && Ar.ArVer >= 850) { FVector unk; Ar << unk; } #endif // SOV Ar << RefSkeleton << SkeletalDepth; after_skeleton: #if DEBUG_SKELMESH appPrintf("RefSkeleton: %d bones, %d depth\n", RefSkeleton.Num(), SkeletalDepth); for (int i1 = 0; i1 < RefSkeleton.Num(); i1++) appPrintf(" [%d] n=%s p=%d\n", i1, *RefSkeleton[i1].Name, RefSkeleton[i1].ParentIndex); #endif // DEBUG_SKELMESH #if A51 || MKVSDC || STRANGLE || TNA_IMPACT //?? check GAME_Wheelman if (Ar.Engine() == GAME_MIDWAY3 && Ar.ArLicenseeVer >= 15) { TArray<FMaterialBone> MaterialBones; Ar << MaterialBones; } #endif // A51 || MKVSDC || STRANGLE #if CRIMECRAFT if (Ar.Game == GAME_CrimeCraft && Ar.ArLicenseeVer >= 5) { byte unk8C; Ar << unk8C; } #endif #if LEGENDARY if (Ar.Game == GAME_Legendary && Ar.ArLicenseeVer >= 9) { TArray<FSPAITag2> OATStags2; Ar << OATStags2; } #endif #if SPECIALFORCE2 if (Ar.Game == GAME_SpecialForce2 && Ar.ArLicenseeVer >= 14) { byte unk108; FName unk10C; Ar << unk108 << unk10C; } #endif Ar << LODModels; #if 0 //!! also: NameIndexMap (ArVer >= 296), PerPolyKDOPs (ArVer >= 435) #else DROP_REMAINING_DATA(Ar); #endif unguard; } void USkeletalMesh3::ConvertMesh() { guard(USkeletalMesh3::ConvertMesh); CSkeletalMesh *Mesh = new CSkeletalMesh(this); ConvertedMesh = Mesh; int ArGame = GetGame(); #if MKVSDC if (ArGame == GAME_MK && Skeleton != NULL && RefSkeleton.Num() == 0) { // convert MK X USkeleton to RefSkeleton int NumBones = Skeleton->BoneName.Num(); assert(Skeleton->BoneParent.Num() == NumBones && Skeleton->BonePos.Num() == NumBones); RefSkeleton.AddDefaulted(NumBones); for (int i = 0; i < NumBones; i++) { FMeshBone& B = RefSkeleton[i]; B.Name = Skeleton->BoneName[i]; B.BonePos = Skeleton->BonePos[i]; B.ParentIndex = Skeleton->BoneParent[i]; } } #endif // MKVSDC if (!RefSkeleton.Num()) { appNotify("SkeletalMesh with no skeleton"); return; } // convert bounds Mesh->BoundingSphere.R = Bounds.SphereRadius / 2; //?? UE3 meshes has radius 2 times larger than mesh VectorSubtract(CVT(Bounds.Origin), CVT(Bounds.BoxExtent), CVT(Mesh->BoundingBox.Min)); VectorAdd (CVT(Bounds.Origin), CVT(Bounds.BoxExtent), CVT(Mesh->BoundingBox.Max)); // MeshScale, MeshOrigin, RotOrigin VectorScale(CVT(MeshOrigin), -1, Mesh->MeshOrigin); Mesh->RotOrigin = RotOrigin; Mesh->MeshScale.Set(1, 1, 1); // missing in UE3 // convert LODs Mesh->Lods.Empty(LODModels.Num()); assert(LODModels.Num() == LODInfo.Num()); for (int lod = 0; lod < LODModels.Num(); lod++) { guard(ConvertLod); const FStaticLODModel3 &SrcLod = LODModels[lod]; if (!SrcLod.Chunks.Num()) continue; int NumTexCoords = max(SrcLod.NumUVSets, SrcLod.GPUSkin.NumUVSets); // number of texture coordinates is serialized differently for some games if (NumTexCoords > MAX_MESH_UV_SETS) appError("SkeletalMesh has %d UV sets", NumTexCoords); CSkelMeshLod *Lod = new (Mesh->Lods) CSkelMeshLod; Lod->NumTexCoords = NumTexCoords; Lod->HasNormals = true; Lod->HasTangents = true; guard(ProcessVerts); // get vertex count and determine vertex source int VertexCount = SrcLod.GPUSkin.GetVertexCount(); bool UseGpuSkinVerts = (VertexCount > 0); if (!VertexCount) { const FSkelMeshChunk3 &C = SrcLod.Chunks[SrcLod.Chunks.Num() - 1]; // last chunk VertexCount = C.FirstVertex + C.NumRigidVerts + C.NumSoftVerts; } // allocate the vertices Lod->AllocateVerts(VertexCount); int chunkIndex = 0; const FSkelMeshChunk3 *C = NULL; int lastChunkVertex = -1; const FSkeletalMeshVertexBuffer3 &S = SrcLod.GPUSkin; CSkelMeshVertex *D = Lod->Verts; int NumReweightedVerts = 0; for (int Vert = 0; Vert < VertexCount; Vert++, D++) { if (Vert >= lastChunkVertex) { // proceed to next chunk C = &SrcLod.Chunks[chunkIndex++]; lastChunkVertex = C->FirstVertex + C->NumRigidVerts + C->NumSoftVerts; } if (UseGpuSkinVerts) { // NOTE: Gears3 has some issues: // - chunk may have FirstVertex set to incorrect value (for recent UE3 versions), which overlaps with the // previous chunk (FirstVertex=0 for a few chunks) // - index count may be greater than sum of all face counts * 3 from all mesh sections -- this is verified in PSK exporter // get vertex from GPU skin const FGPUVert3Common *V; // has normal and influences, but no UV[] and position if (!S.bUseFullPrecisionUVs) { // position const FMeshUVHalf *SUV; if (!S.bUsePackedPosition) { const FGPUVert3Half &V0 = S.VertsHalf[Vert]; D->Position = CVT(V0.Pos); V = &V0; SUV = V0.UV; } else { const FGPUVert3PackedHalf &V0 = S.VertsHalfPacked[Vert]; FVector VPos; VPos = V0.Pos.ToVector(S.MeshOrigin, S.MeshExtension); D->Position = CVT(VPos); V = &V0; SUV = V0.UV; } // UV FMeshUVFloat fUV = SUV[0]; // convert half->float D->UV = CVT(fUV); for (int TexCoordIndex = 1; TexCoordIndex < NumTexCoords; TexCoordIndex++) { Lod->ExtraUV[TexCoordIndex-1][Vert] = CVT(SUV[TexCoordIndex]); } } else { // position const FMeshUVFloat *SUV; if (!S.bUsePackedPosition) { const FGPUVert3Float &V0 = S.VertsFloat[Vert]; V = &V0; D->Position = CVT(V0.Pos); SUV = V0.UV; } else { const FGPUVert3PackedFloat &V0 = S.VertsFloatPacked[Vert]; V = &V0; FVector VPos; VPos = V0.Pos.ToVector(S.MeshOrigin, S.MeshExtension); D->Position = CVT(VPos); SUV = V0.UV; } // UV FMeshUVFloat fUV = SUV[0]; D->UV = CVT(fUV); for (int TexCoordIndex = 1; TexCoordIndex < NumTexCoords; TexCoordIndex++) { Lod->ExtraUV[TexCoordIndex-1][Vert] = CVT(SUV[TexCoordIndex]); } } // convert Normal[3] UnpackNormals(V->Normal, *D); // convert influences int i2 = 0; unsigned PackedWeights = 0; for (int i = 0; i < NUM_INFLUENCES_UE3; i++) { int BoneIndex = V->BoneIndex[i]; byte BoneWeight = V->BoneWeight[i]; if (BoneWeight == 0) continue; // skip this influence (but do not stop the loop!) PackedWeights |= BoneWeight << (i2 * 8); D->Bone[i2] = C->Bones[BoneIndex]; i2++; } D->PackedWeights = PackedWeights; if (i2 < NUM_INFLUENCES_UE3) D->Bone[i2] = INDEX_NONE; // mark end of list } else { // old UE3 version without a GPU skin // get vertex from chunk const FMeshUVFloat *SUV; if (Vert < C->FirstVertex + C->NumRigidVerts) { // rigid vertex const FRigidVertex3 &V0 = C->RigidVerts[Vert - C->FirstVertex]; // position and normal D->Position = CVT(V0.Pos); UnpackNormals(V0.Normal, *D); // single influence D->PackedWeights = 0xFF; D->Bone[0] = C->Bones[V0.BoneIndex]; SUV = V0.UV; } else { // soft vertex const FSoftVertex3 &V0 = C->SoftVerts[Vert - C->FirstVertex - C->NumRigidVerts]; // position and normal D->Position = CVT(V0.Pos); UnpackNormals(V0.Normal, *D); // influences // int TotalWeight = 0; int i2 = 0; unsigned PackedWeights = 0; for (int i = 0; i < NUM_INFLUENCES_UE3; i++) { int BoneIndex = V0.BoneIndex[i]; byte BoneWeight = V0.BoneWeight[i]; if (BoneWeight == 0) continue; PackedWeights |= BoneWeight << (i2 * 8); D->Bone[i2] = C->Bones[BoneIndex]; i2++; // TotalWeight += BoneWeight; } D->PackedWeights = PackedWeights; // assert(TotalWeight == 255); if (i2 < NUM_INFLUENCES_UE3) D->Bone[i2] = INDEX_NONE; // mark end of list SUV = V0.UV; } // UV FMeshUVFloat fUV = SUV[0]; // convert half->float D->UV = CVT(fUV); for (int TexCoordIndex = 1; TexCoordIndex < NumTexCoords; TexCoordIndex++) { Lod->ExtraUV[TexCoordIndex-1][Vert] = CVT(SUV[TexCoordIndex]); } } } if (NumReweightedVerts > 0) appPrintf("LOD %d: adjusted weights for %d vertices\n", lod, NumReweightedVerts); unguard; // ProcessVerts // indices Lod->Indices.Initialize(&SrcLod.IndexBuffer.Indices16, &SrcLod.IndexBuffer.Indices32); // sections guard(ProcessSections); Lod->Sections.Empty(SrcLod.Sections.Num()); const FSkeletalMeshLODInfo &Info = LODInfo[lod]; for (int Sec = 0; Sec < SrcLod.Sections.Num(); Sec++) { const FSkelMeshSection3 &S = SrcLod.Sections[Sec]; CMeshSection *Dst = new (Lod->Sections) CMeshSection; // remap material for LOD int MaterialIndex = S.MaterialIndex; if (MaterialIndex >= 0 && MaterialIndex < Info.LODMaterialMap.Num()) MaterialIndex = Info.LODMaterialMap[MaterialIndex]; Dst->Material = (MaterialIndex < Materials.Num()) ? Materials[MaterialIndex] : NULL; Dst->FirstIndex = S.FirstIndex; Dst->NumFaces = S.NumTriangles; } unguard; // ProcessSections unguardf("lod=%d", lod); // ConvertLod } // copy skeleton guard(ProcessSkeleton); Mesh->RefSkeleton.Empty(RefSkeleton.Num()); for (int i = 0; i < RefSkeleton.Num(); i++) { const FMeshBone &B = RefSkeleton[i]; CSkelMeshBone *Dst = new (Mesh->RefSkeleton) CSkelMeshBone; Dst->Name = B.Name; Dst->ParentIndex = B.ParentIndex; Dst->Position = CVT(B.BonePos.Position); Dst->Orientation = CVT(B.BonePos.Orientation); // fix skeleton; all bones but 0 if (i >= 1) Dst->Orientation.w *= -1; } unguard; // ProcessSkeleton Mesh->FinalizeMesh(); #if BATMAN if (ArGame >= GAME_Batman2 && ArGame <= GAME_Batman4) FixBatman2Skeleton(); #endif unguard; } void USkeletalMesh3::PostLoad() { guard(USkeletalMesh3::PostLoad); // MK X has bones serialized in separate USkeleton object, so perform conversion in PostLoad() ConvertMesh(); assert(ConvertedMesh); int NumSockets = Sockets.Num(); if (NumSockets) { ConvertedMesh->Sockets.Empty(NumSockets); for (int i = 0; i < NumSockets; i++) { USkeletalMeshSocket *S = Sockets[i]; if (!S) continue; CSkelMeshSocket *DS = new (ConvertedMesh->Sockets) CSkelMeshSocket; DS->Name = S->SocketName; DS->Bone = S->BoneName; CCoords &C = DS->Transform; C.origin = CVT(S->RelativeLocation); RotatorToAxis(S->RelativeRotation, C.axis); } } unguard; } /*----------------------------------------------------------------------------- UStaticMesh -----------------------------------------------------------------------------*/ // Implement constructor in cpp to avoid inlining (it's large enough). // It's useful to declare TArray<> structures as forward declarations in header file. UStaticMesh3::UStaticMesh3() : ConvertedMesh(NULL) {} UStaticMesh3::~UStaticMesh3() { delete ConvertedMesh; } #if MOH2010 struct FMOHStaticMeshSectionUnk { TArray<int> f4; TArray<int> f10; TArray<int16> f1C; TArray<int16> f28; TArray<int16> f34; TArray<int16> f40; TArray<int16> f4C; TArray<int16> f58; friend FArchive& operator<<(FArchive &Ar, FMOHStaticMeshSectionUnk &S) { return Ar << S.f4 << S.f10 << S.f1C << S.f28 << S.f34 << S.f40 << S.f4C << S.f58; } }; #endif // MOH2010 struct FPS3StaticMeshData { TArray<int> unk1; TArray<int> unk2; TArray<uint16> unk3; TArray<uint16> unk4; TArray<uint16> unk5; TArray<uint16> unk6; TArray<uint16> unk7; TArray<uint16> unk8; friend FArchive& operator<<(FArchive &Ar, FPS3StaticMeshData &S) { Ar << S.unk1 << S.unk2 << S.unk3 << S.unk4 << S.unk5 << S.unk6 << S.unk7 << S.unk8; #if DUST514 if (Ar.Game == GAME_Dust514) // there's no version check, perhaps that code is standard for UE3? { int16 s1, s2; TArray<FVector> va1, va2; TArray<int16> sa1; Ar << s1 << s2 << va1 << va2; if (Ar.ArLicenseeVer >= 32) Ar << sa1; // appPrintf("s1=%d s2=%d va1=%d va2=%d sa1=%d\n", s1, s2, va1.Num(), va2.Num(), sa1.Num()); } #endif // DUST514 return Ar; } }; struct FStaticMeshSection3 { UMaterialInterface *Mat; int f10; //?? bUseSimple...Collision int f14; //?? ... int bEnableShadowCasting; int FirstIndex; int NumFaces; int f24; //?? first used vertex int f28; //?? last used vertex int Index; //?? index of section TArrayOfArray<int, 2> f30; friend FArchive& operator<<(FArchive &Ar, FStaticMeshSection3 &S) { guard(FStaticMeshSection3<<); #if TUROK if (Ar.Game == GAME_Turok && Ar.ArLicenseeVer >= 57) { // no S.Mat return Ar << S.f10 << S.f14 << S.FirstIndex << S.NumFaces << S.f24 << S.f28; } #endif // TUROK Ar << S.Mat << S.f10 << S.f14; #if MKVSDC if (Ar.Game == GAME_MK) { TArray<FGuid> unk28; // 4x32-bit // no bEnableShadowCasting and Index fields Ar << S.FirstIndex << S.NumFaces << S.f24 << S.f28; if (Ar.ArVer >= 409) Ar << unk28; return Ar; } #endif // MKVSDC if (Ar.ArVer >= 473) Ar << S.bEnableShadowCasting; Ar << S.FirstIndex << S.NumFaces << S.f24 << S.f28; #if MASSEFF if (Ar.Game == GAME_MassEffect && Ar.ArVer >= 485) return Ar << S.Index; //?? other name? #endif // MASSEFF #if HUXLEY if (Ar.Game == GAME_Huxley && Ar.ArVer >= 485) return Ar << S.Index; //?? other name? #endif // HUXLEY if (Ar.ArVer >= 492) Ar << S.Index; // real version is unknown! This field is missing in GOW1_PC (490), but present in UT3 (512) #if ALPHA_PR if (Ar.Game == GAME_AlphaProtocol && Ar.ArLicenseeVer >= 13) { int unk30, unk34; Ar << unk30 << unk34; } #endif // ALPHA_PR #if TRANSFORMERS if (Ar.Game == GAME_Transformers && Ar.ArLicenseeVer >= 49) { Ar << S.f30; return Ar; } #endif // TRANSFORMERS #if FABLE if (Ar.Game == GAME_Fable && Ar.ArLicenseeVer >= 1007) { int unk40; Ar << unk40; } #endif // FABLE if (Ar.ArVer >= 514) Ar << S.f30; #if ALPHA_PR if (Ar.Game == GAME_AlphaProtocol && Ar.ArLicenseeVer >= 39) { int unk38; Ar << unk38; } #endif // ALPHA_PR #if MOH2010 if (Ar.Game == GAME_MOH2010 && Ar.ArVer >= 575) { byte flag; FMOHStaticMeshSectionUnk unk3C; Ar << flag; if (flag) Ar << unk3C; } #endif // MOH2010 #if BATMAN if ((Ar.Game == GAME_Batman2 || Ar.Game == GAME_Batman3) && (Ar.ArLicenseeVer >= 28)) // && (Ar.ArLicenseeVer < 102)) - this will drop Batman3 support { UObject *unk4; Ar << unk4; } #endif // BATMAN #if BIOSHOCK3 if (Ar.Game == GAME_Bioshock3) { FString unk4; Ar << unk4; } #endif // BIOSHOCK3 if (Ar.ArVer >= 618) { byte unk; Ar << unk; if (unk) { FPS3StaticMeshData ps3data; Ar << ps3data; DBG_STAT("PS3 data: %d %d %d %d %d %d %d %d\n", ps3data.unk1.Num(), ps3data.unk2.Num(), ps3data.unk3.Num(), ps3data.unk4.Num(), ps3data.unk5.Num(), ps3data.unk6.Num(), ps3data.unk7.Num(), ps3data.unk8.Num()); } } if (Ar.ArVer >= 869) { // Picked from GRAV executable int32 unk; Ar << unk; } #if XCOM if (Ar.Game == GAME_XcomB) { FString unk; Ar << unk; } if (Ar.Game == GAME_Xcom2 && Ar.ArLicenseeVer >= 83) { int32 unk; Ar << unk; } #endif // XCOM return Ar; unguard; } }; struct FStaticMeshVertexStream3 { int VertexSize; // 0xC int NumVerts; // == Verts.Num() TArray<FVector> Verts; friend FArchive& operator<<(FArchive &Ar, FStaticMeshVertexStream3 &S) { guard(FStaticMeshVertexStream3<<); //!! Borderlands3: //!! (EngineVersion>>16) >= 29 //!! int VertexSize, int NumVerts //!! byte UseCompressedPositions, always 1 (0==float[3], 1=int16[]) //!! byte Use3Components, always 0 (0==int16[4], 0=int16[3]) //!! FVector Mins, Extents #if BATMAN if (Ar.Game >= GAME_Batman && Ar.Game <= GAME_Batman4) { byte VertexType = 0; // appeared in Batman 2; 0 -> FVector, 1 -> half[3], 2 -> half[4] (not checked!) int unk18; // default is 1 if (Ar.ArLicenseeVer >= 41) Ar << VertexType; Ar << S.VertexSize << S.NumVerts; if (Ar.ArLicenseeVer >= 17) Ar << unk18; DBG_STAT("Batman StaticMesh VertexStream: IS:%d NV:%d VT:%d unk:%d\n", S.VertexSize, S.NumVerts, VertexType, unk18); switch (VertexType) { case 0: S.Verts.BulkSerialize(Ar); break; case 4: { TArray<FVectorHalf> PackedVerts; PackedVerts.BulkSerialize(Ar); CopyArray(S.Verts, PackedVerts); } break; default: appError("unsupported vertex type %d", VertexType); } if (Ar.ArLicenseeVer >= 24) { TArray<FMeshUVFloat> unk28; // unknown type, TArray<dword,dword> Ar << unk28; } return Ar; } #endif // BATMAN Ar << S.VertexSize << S.NumVerts; DBG_STAT("StaticMesh Vertex stream: IS:%d NV:%d\n", S.VertexSize, S.NumVerts); #if AVA if (Ar.Game == GAME_AVA && Ar.ArVer >= 442) { int presence; Ar << presence; if (!presence) { appNotify("AVA: StaticMesh without vertex stream"); return Ar; } } #endif // AVA #if MOH2010 if (Ar.Game == GAME_MOH2010 && Ar.ArLicenseeVer >= 58) { int unk28; Ar << unk28; } #endif // MOH2010 #if SHADOWS_DAMNED if (Ar.Game == GAME_ShadowsDamned && Ar.ArLicenseeVer >= 26) { int unk28; Ar << unk28; } #endif // SHADOWS_DAMNED #if MASSEFF if (Ar.Game == GAME_MassEffect3 && Ar.ArLicenseeVer >= 150) { int unk28; Ar << unk28; } #endif // MASSEFF #if PLA if (Ar.Game == GAME_PLA && Ar.ArVer >= 900) { FGuid unk; Ar << unk; } #endif // PLA #if BIOSHOCK3 if (Ar.Game == GAME_Bioshock3) { byte IsPacked, VectorType; // VectorType used only when IsPacked != 0 FVector Mins, Extents; Ar << IsPacked << VectorType << Mins << Extents; DBG_STAT("... Bioshock3: IsPacked=%d VectorType=%d Mins=%g %g %g Extents=%g %g %g\n", IsPacked, VectorType, FVECTOR_ARG(Mins), FVECTOR_ARG(Extents)); if (IsPacked) { if (VectorType) { TArray<FVectorIntervalFixed48Bio> Vecs16x3; Vecs16x3.BulkSerialize(Ar); S.Verts.AddUninitialized(Vecs16x3.Num()); for (int i = 0; i < Vecs16x3.Num(); i++) S.Verts[i] = Vecs16x3[i].ToVector(Mins, Extents); appNotify("type1 - untested"); //?? not found - not used? } else { TArray<FVectorIntervalFixed64> Vecs16x4; Vecs16x4.BulkSerialize(Ar); S.Verts.AddUninitialized(Vecs16x4.Num()); for (int i = 0; i < Vecs16x4.Num(); i++) S.Verts[i] = Vecs16x4[i].ToVector(Mins, Extents); } return Ar; } // else - normal vertex stream } #endif // BIOSHOCK3 #if REMEMBER_ME if (Ar.Game == GAME_RememberMe && Ar.ArLicenseeVer >= 18) { int UsePackedPosition, VertexType; FVector v1, v2; Ar << VertexType << UsePackedPosition; if (Ar.ArLicenseeVer >= 20) Ar << v1 << v2; // appPrintf("VT=%d, PP=%d, V1=%g %g %g, V2=%g %g %g\n", VertexType, UsePackedPosition, FVECTOR_ARG(v1), FVECTOR_ARG(v2)); if (UsePackedPosition && VertexType != 0) { appError("Unsupported vertex type!\n"); } } #endif // REMEMBER_ME #if THIEF4 if (Ar.Game == GAME_Thief4 && Ar.ArLicenseeVer >= 15) { int unk28; Ar << unk28; } #endif // THIEF4 #if DUST514 if (Ar.Game == GAME_Dust514 && Ar.ArLicenseeVer >= 31) { int bUseFullPrecisionPosition; Ar << bUseFullPrecisionPosition; if (!bUseFullPrecisionPosition) { TArray<FVectorHalf> HalfVerts; HalfVerts.BulkSerialize(Ar); CopyArray(S.Verts, HalfVerts); return Ar; } } #endif // DUST514 S.Verts.BulkSerialize(Ar); return Ar; unguard; } }; static int GNumStaticUVSets = 1; static bool GUseStaticFloatUVs = true; static bool GStripStaticNormals = false; struct FStaticMeshUVItem3 { FVector Pos; // old version (< 472) FPackedNormal Normal[3]; int f10; //?? VertexColor? FMeshUVFloat UV[NUM_UV_SETS_UE3]; friend FArchive& operator<<(FArchive &Ar, FStaticMeshUVItem3 &V) { guard(FStaticMeshUVItem3<<); #if MKVSDC if (Ar.Game == GAME_MK) { if (Ar.ArVer >= 472) goto uvs; // normals are stored in FStaticMeshNormalStream_MK int unk; Ar << unk; goto new_ver; } #endif // MKVSDC #if A51 if (Ar.Game == GAME_A51) goto new_ver; #endif #if AVA if (Ar.Game == GAME_AVA) { assert(Ar.ArVer >= 441); Ar << V.Normal[0] << V.Normal[2] << V.f10; goto uvs; } #endif // AVA if (GStripStaticNormals) goto uvs; if (Ar.ArVer < 472) { // old version has position embedded into UVStream (this is not an UVStream, this is a single stream for everything) int unk10; // pad or color ? Ar << V.Pos << unk10; } #if FURY if (Ar.Game == GAME_Fury && Ar.ArLicenseeVer >= 7) { int fC; Ar << fC; // really should be serialized before unk10 above (it's FColor) } #endif // FURY new_ver: if (Ar.ArVer < 477) Ar << V.Normal[0] << V.Normal[1] << V.Normal[2]; else Ar << V.Normal[0] << V.Normal[2]; #if APB if (Ar.Game == GAME_APB && Ar.ArLicenseeVer >= 12) goto uvs; #endif #if MOH2010 if (Ar.Game == GAME_MOH2010 && Ar.ArLicenseeVer >= 58) goto uvs; #endif #if UNDERTOW if (Ar.Game == GAME_Undertow) goto uvs; #endif #if TRANSFORMERS if (Ar.Game == GAME_Transformers && Ar.ArLicenseeVer >= 181) goto uvs; // Transformers: Fall of Cybertron, no version in code #endif if (Ar.ArVer >= 434 && Ar.ArVer < 615) Ar << V.f10; // starting from 615 made as separate stream uvs: if (GUseStaticFloatUVs) { for (int i = 0; i < GNumStaticUVSets; i++) Ar << V.UV[i]; } else { for (int i = 0; i < GNumStaticUVSets; i++) { // read in half format and convert to float FMeshUVHalf UVHalf; Ar << UVHalf; V.UV[i] = UVHalf; // convert } } return Ar; unguard; } }; struct FStaticMeshUVStream3 { int NumTexCoords; int ItemSize; int NumVerts; int bUseFullPrecisionUVs; TArray<FStaticMeshUVItem3> UV; friend FArchive& operator<<(FArchive &Ar, FStaticMeshUVStream3 &S) { guard(FStaticMeshUVStream3<<); Ar << S.NumTexCoords << S.ItemSize << S.NumVerts; S.bUseFullPrecisionUVs = true; #if TUROK if (Ar.Game == GAME_Turok && Ar.ArLicenseeVer >= 59) { int HalfPrecision, unk28; Ar << HalfPrecision << unk28; S.bUseFullPrecisionUVs = !HalfPrecision; assert(S.bUseFullPrecisionUVs); } #endif // TUROK #if AVA if (Ar.Game == GAME_AVA && Ar.ArVer >= 441) goto new_ver; #endif #if MOHA if (Ar.Game == GAME_MOHA && Ar.ArVer >= 421) goto new_ver; #endif #if MKVSDC if (Ar.Game == GAME_MK) goto old_ver; // Injustice has no float/half selection #endif if (Ar.ArVer >= 474) { new_ver: Ar << S.bUseFullPrecisionUVs; } old_ver: #if BATMAN int HasNormals = 1; if (Ar.Game >= GAME_Batman2 && Ar.Game <= GAME_Batman4 && Ar.ArLicenseeVer >= 42) { Ar << HasNormals; if (Ar.ArLicenseeVer >= 194) { int unk; Ar << unk; } } GStripStaticNormals = (HasNormals == 0); #endif // BATMAN #if MASSEFF if (Ar.Game == GAME_MassEffect3 && Ar.ArLicenseeVer >= 150) { int unk30; Ar << unk30; } #endif // MASSEFF DBG_STAT("StaticMesh UV stream: TC:%d IS:%d NV:%d FloatUV:%d\n", S.NumTexCoords, S.ItemSize, S.NumVerts, S.bUseFullPrecisionUVs); #if MKVSDC if (Ar.Game == GAME_MK) S.bUseFullPrecisionUVs = false; #endif #if A51 if (Ar.Game == GAME_A51 && Ar.ArLicenseeVer >= 22) // or MidwayVer ? Ar << S.bUseFullPrecisionUVs; #endif #if MOH2010 if (Ar.Game == GAME_MOH2010 && Ar.ArLicenseeVer >= 58) { int unk30; Ar << unk30; } #endif // MOH2010 #if FURY if (Ar.Game == GAME_Fury && Ar.ArLicenseeVer >= 34) { int unused; // useless stack variable, always 0 Ar << unused; } #endif // FURY #if SHADOWS_DAMNED if (Ar.Game == GAME_ShadowsDamned && Ar.ArLicenseeVer >= 22) { int unk30; Ar << unk30; } #endif // SHADOWS_DAMNED #if PLA if (Ar.Game == GAME_PLA && Ar.ArVer >= 900) { FGuid unk; Ar << unk; } #endif // PLA #if THIEF4 if (Ar.Game == GAME_Thief4 && Ar.ArLicenseeVer >= 15) { int unk30; Ar << unk30; } #endif // prepare for UV serialization if (S.NumTexCoords > MAX_MESH_UV_SETS) appError("StaticMesh has %d UV sets", S.NumTexCoords); GNumStaticUVSets = S.NumTexCoords; GUseStaticFloatUVs = (S.bUseFullPrecisionUVs != 0); S.UV.BulkSerialize(Ar); return Ar; unguard; } }; struct FStaticMeshColorStream3 { int ItemSize; int NumVerts; TArray<int> Colors; friend FArchive& operator<<(FArchive &Ar, FStaticMeshColorStream3 &S) { guard(FStaticMeshColorStream3<<); Ar << S.ItemSize << S.NumVerts; DBG_STAT("StaticMesh ColorStream: IS:%d NV:%d\n", S.ItemSize, S.NumVerts); S.Colors.BulkSerialize(Ar); return Ar; unguard; } }; // new color stream: difference is that data array is not serialized when NumVerts is 0 struct FStaticMeshColorStream3New // ArVer >= 615 { int ItemSize; int NumVerts; TArray<int> Colors; friend FArchive& operator<<(FArchive &Ar, FStaticMeshColorStream3New &S) { guard(FStaticMeshColorStream3New<<); Ar << S.ItemSize << S.NumVerts; DBG_STAT("StaticMesh ColorStreamNew: IS:%d NV:%d\n", S.ItemSize, S.NumVerts); #if THIEF4 if (Ar.Game == GAME_Thief4 && Ar.ArLicenseeVer >= 43) { byte unk; Ar << unk; } #endif if (S.NumVerts) { #if PLA if (Ar.Game == GAME_PLA && Ar.ArVer >= 900) { FGuid unk; Ar << unk; } #endif // PLA S.Colors.BulkSerialize(Ar); } return Ar; unguard; } }; struct FStaticMeshVertex3Old // ArVer < 333 { FVector Pos; FPackedNormal Normal[3]; // packed vector operator FVector() const { return Pos; } friend FArchive& operator<<(FArchive &Ar, FStaticMeshVertex3Old &V) { return Ar << V.Pos << V.Normal[0] << V.Normal[1] << V.Normal[2]; } }; struct FStaticMeshUVStream3Old // ArVer < 364; corresponds to UE2 StaticMesh? { TArray<FMeshUVFloat> Data; friend FArchive& operator<<(FArchive &Ar, FStaticMeshUVStream3Old &S) { guard(FStaticMeshUVStream3Old<<); int unk; // Revision? Ar << S.Data; // used BulkSerialize, but BulkSerialize is newer than this version if (Ar.ArVer < 297) Ar << unk; return Ar; unguard; } }; #if MKVSDC struct FStaticMeshNormal_MK { FPackedNormal Normal[3]; // packed vector friend FArchive& operator<<(FArchive &Ar, FStaticMeshNormal_MK &V) { if (Ar.ArVer >= 573) return Ar << V.Normal[0] << V.Normal[2]; // Injustice return Ar << V.Normal[0] << V.Normal[1] << V.Normal[2]; } }; struct FStaticMeshNormalStream_MK { int ItemSize; int NumVerts; TArray<FStaticMeshNormal_MK> Normals; friend FArchive& operator<<(FArchive &Ar, FStaticMeshNormalStream_MK &S) { Ar << S.ItemSize << S.NumVerts; S.Normals.BulkSerialize(Ar); DBG_STAT("MK NormalStream: ItemSize=%d, Count=%d (%d)\n", S.ItemSize, S.NumVerts, S.Normals.Num()); return Ar; } }; #endif // MKVSDC struct FStaticMeshLODModel3 { FByteBulkData BulkData; // ElementSize = 0xFC for UT3 and 0x170 for UDK ... it's simpler to skip it TArray<FStaticMeshSection3> Sections; FStaticMeshVertexStream3 VertexStream; FStaticMeshUVStream3 UVStream; FStaticMeshColorStream3 ColorStream; //?? FStaticMeshColorStream3New ColorStream2; //?? FIndexBuffer3 Indices; FIndexBuffer3 Indices2; // wireframe int NumVerts; TArray<FEdge3> Edges; TArray<byte> fEC; // flags for faces? removed simultaneously with Edges friend FArchive& operator<<(FArchive &Ar, FStaticMeshLODModel3 &Lod) { guard(FStaticMeshLODModel3<<); DBG_STAT("Serialize UStaticMesh LOD\n"); #if FURY if (Ar.Game == GAME_Fury) { int EndArPos, unkD0; if (Ar.ArLicenseeVer >= 8) Ar << EndArPos; // TLazyArray-like file pointer if (Ar.ArLicenseeVer >= 18) Ar << unkD0; } #endif // FURY #if HUXLEY if (Ar.Game == GAME_Huxley && Ar.ArLicenseeVer >= 14) { // Huxley has different IndirectArray layout: each item // has stored data size before data itself int DataSize; Ar << DataSize; } #endif // HUXLEY #if APB if (Ar.Game == GAME_APB) { // skip bulk; check UTexture3::Serialize() for details Ar.Seek(Ar.Tell() + 8); goto after_bulk; } #endif // APB if (Ar.ArVer >= 218) Lod.BulkData.Skip(Ar); after_bulk: #if TLR if (Ar.Game == GAME_TLR && Ar.ArLicenseeVer >= 2) { FByteBulkData unk128; unk128.Skip(Ar); } #endif // TLR Ar << Lod.Sections; #if DEBUG_STATICMESH appPrintf("%d sections\n", Lod.Sections.Num()); for (int i = 0; i < Lod.Sections.Num(); i++) { FStaticMeshSection3 &S = Lod.Sections[i]; appPrintf("Mat: %s\n", S.Mat ? S.Mat->Name : "?"); appPrintf(" %d %d sh=%d i0=%d NF=%d %d %d idx=%d\n", S.f10, S.f14, S.bEnableShadowCasting, S.FirstIndex, S.NumFaces, S.f24, S.f28, S.Index); } #endif // DEBUG_STATICMESH // serialize vertex and uv streams #if A51 if (Ar.Game == GAME_A51) goto new_ver; #endif #if MKVSDC || AVA if (Ar.Game == GAME_MK || Ar.Game == GAME_AVA) goto ver_3; #endif #if BORDERLANDS if (Ar.Game == GAME_Borderlands && Ar.ArLicenseeVer >= 57 && Ar.ArVer < 832) // Borderlands 1, version unknown; not valid for Borderlands 2 { // refined field set Ar << Lod.VertexStream; Ar << Lod.UVStream; Ar << Lod.NumVerts; Ar << Lod.Indices; // note: no fEC (smoothing groups?) return Ar; } #endif // BORDERLANDS #if TRANSFORMERS if (Ar.Game == GAME_Transformers) { // code is similar to original code (ArVer >= 472) but has different versioning and a few new fields FTRMeshUnkStream unkStream; // normals? int unkD8; // part of Indices2 Ar << Lod.VertexStream << Lod.UVStream; if (Ar.ArVer >= 516) Ar << Lod.ColorStream2; if (Ar.ArLicenseeVer >= 71) Ar << unkStream; if (Ar.ArVer < 536) Ar << Lod.ColorStream; Ar << Lod.NumVerts << Lod.Indices << Lod.Indices2; if (Ar.ArLicenseeVer >= 58) Ar << unkD8; if (Ar.ArLicenseeVer >= 181) // Fall of Cybertron { // pre-Fall of Cybertron has 0 or 1 ints after indices, but Fall of Cybertron has 1 or 2 ints int unkIndexStreamField; Ar << unkIndexStreamField; } if (Ar.ArVer < 536) { Lod.Edges.BulkSerialize(Ar); Ar << Lod.fEC; } return Ar; } #endif // TRANSFORMERS if (Ar.ArVer >= 472) { new_ver: Ar << Lod.VertexStream; Ar << Lod.UVStream; #if MOH2010 if (Ar.Game == GAME_MOH2010 && Ar.ArLicenseeVer >= 55) goto color_stream; #endif #if BLADENSOUL if (Ar.Game == GAME_BladeNSoul && Ar.ArVer >= 572) goto color_stream; #endif // unknown data in UDK if (Ar.ArVer >= 615) { color_stream: Ar << Lod.ColorStream2; } if (Ar.ArVer < 686) Ar << Lod.ColorStream; //?? probably this is not a color stream - the same version is used to remove "edges" Ar << Lod.NumVerts; DBG_STAT("NumVerts: %d\n", Lod.NumVerts); } else if (Ar.ArVer >= 466) { ver_3: #if MKVSDC if (Ar.Game == GAME_MK && Ar.ArVer >= 472) // MK9; real version: MidwayVer >= 36 { FStaticMeshNormalStream_MK NormalStream; Ar << Lod.VertexStream << Lod.ColorStream << NormalStream << Lod.UVStream; if (Ar.ArVer >= 677) { // MK X Ar << Lod.ColorStream2; } Ar << Lod.NumVerts; // copy NormalStream into UVStream assert(Lod.UVStream.UV.Num() == NormalStream.Normals.Num()); for (int i = 0; i < Lod.UVStream.UV.Num(); i++) { FStaticMeshUVItem3 &UV = Lod.UVStream.UV[i]; FStaticMeshNormal_MK &N = NormalStream.Normals[i]; UV.Normal[0] = N.Normal[0]; UV.Normal[1] = N.Normal[1]; UV.Normal[2] = N.Normal[2]; } goto duplicate_verts; } #endif // MKVSDC Ar << Lod.VertexStream; Ar << Lod.UVStream; Ar << Lod.NumVerts; #if MKVSDC || AVA if (Ar.Game == GAME_MK || Ar.Game == GAME_AVA) { duplicate_verts: // note: sometimes UVStream has 2 times more items than VertexStream // we should duplicate vertices int n1 = Lod.VertexStream.Verts.Num(); int n2 = Lod.UVStream.UV.Num(); if (n1 * 2 == n2) { appPrintf("Duplicating MK StaticMesh verts\n"); Lod.VertexStream.Verts.AddUninitialized(n1); for (int i = 0; i < n1; i++) Lod.VertexStream.Verts[i+n1] = Lod.VertexStream.Verts[i]; } } #endif // MKVSDC || AVA } else if (Ar.ArVer >= 364) { // ver_2: Ar << Lod.UVStream; Ar << Lod.NumVerts; // create VertexStream int NumVerts = Lod.UVStream.UV.Num(); Lod.VertexStream.Verts.Empty(NumVerts); // Lod.VertexStream.NumVerts = NumVerts; for (int i = 0; i < NumVerts; i++) Lod.VertexStream.Verts.Add(Lod.UVStream.UV[i].Pos); } else { // ver_1: TArray<FStaticMeshUVStream3Old> UVStream; if (Ar.ArVer >= 333) { appNotify("StaticMesh: untested code! (ArVer=%d)", Ar.ArVer); TArray<FQuat> Verts; TArray<int> Normals; // compressed Ar << Verts << Normals << UVStream; // really used BulkSerialize, but it is too new for this code //!! convert } else { // oldest version TArray<FStaticMeshVertex3Old> Verts; Ar << Verts << UVStream; // convert vertex stream int i; int NumVerts = Verts.Num(); int NumTexCoords = UVStream.Num(); if (NumTexCoords > MAX_MESH_UV_SETS) { appNotify("StaticMesh has %d UV sets", NumTexCoords); NumTexCoords = MAX_MESH_UV_SETS; } Lod.VertexStream.Verts.Empty(NumVerts); Lod.VertexStream.Verts.AddZeroed(NumVerts); Lod.UVStream.UV.Empty(); Lod.UVStream.UV.AddDefaulted(NumVerts); Lod.UVStream.NumVerts = NumVerts; Lod.UVStream.NumTexCoords = NumTexCoords; // resize UV streams for (i = 0; i < NumVerts; i++) { FStaticMeshVertex3Old &V = Verts[i]; FVector &DV = Lod.VertexStream.Verts[i]; FStaticMeshUVItem3 &UV = Lod.UVStream.UV[i]; DV = V.Pos; UV.Normal[2] = V.Normal[2]; for (int j = 0; j < NumTexCoords; j++) UV.UV[j] = UVStream[j].Data[i]; } } } #if DUST514 if (Ar.Game == GAME_Dust514 && Ar.ArLicenseeVer >= 32) { TArray<byte> unk; // compressed index buffer? unk.BulkSerialize(Ar); } #endif // DUST514 DBG_STAT("Serializing indices ...\n"); #if BATMAN if (Ar.Game >= GAME_Batman2 && Ar.Game <= GAME_Batman4 && Ar.ArLicenseeVer >= 45) { int unk34; // variable in IndexBuffer, but in 1st only Ar << unk34; } #endif // BATMAN #if PLA if (Ar.Game == GAME_PLA && Ar.ArVer >= 900) { FGuid unk; Ar << unk; } #endif // PLA Ar << Lod.Indices; #if ENDWAR if (Ar.Game == GAME_EndWar) goto after_indices; // single Indices buffer since version 262 #endif #if APB if (Ar.Game == GAME_APB) { // serialized FIndexBuffer3 guarded by APB bulk seeker (check UTexture3::Serialize() for details) Ar.Seek(Ar.Tell() + 8); goto after_indices; // do not need this data } #endif // APB #if BORDERLANDS if (Ar.Game == GAME_Borderlands && Ar.ArVer >= 832) goto after_indices; // Borderlands 2 #endif #if METRO_CONF if (Ar.Game == GAME_MetroConflict && Ar.ArLicenseeVer >= 8) { int16 unk; Ar << unk; } #endif Ar << Lod.Indices2; DBG_STAT("Indices: %d %d\n", Lod.Indices.Indices.Num(), Lod.Indices2.Indices.Num()); after_indices: if (Ar.ArVer < 686) { Lod.Edges.BulkSerialize(Ar); Ar << Lod.fEC; } #if ALPHA_PR if (Ar.Game == GAME_AlphaProtocol) { assert(Ar.ArLicenseeVer > 8); // ArLicenseeVer = [1..7] has custom code if (Ar.ArLicenseeVer >= 4) { TArray<int> unk128; unk128.BulkSerialize(Ar); } } #endif // ALPHA_PR #if AVA if (Ar.Game == GAME_AVA) { if (Ar.ArLicenseeVer >= 2) { int fFC, f100; Ar << fFC << f100; } if (Ar.ArLicenseeVer >= 4) { FByteBulkData f104, f134, f164, f194, f1C4, f1F4, f224, f254; f104.Skip(Ar); f134.Skip(Ar); f164.Skip(Ar); f194.Skip(Ar); f1C4.Skip(Ar); f1F4.Skip(Ar); f224.Skip(Ar); f254.Skip(Ar); } } #endif // AVA if (Ar.ArVer >= 841) { FIndexBuffer3 Indices3; #if BATMAN if (Ar.Game == GAME_Batman4 && Ar.ArLicenseeVer >= 45) { // the same as for indices above int unk; Ar << unk; } #endif // BATMAN #if PLA if (Ar.Game == GAME_PLA && Ar.ArVer >= 900) { FGuid unk; Ar << unk; } #endif // PLA Ar << Indices3; if (Indices3.Indices.Num()) appPrintf("LOD has extra index buffer (%d items)\n", Indices3.Indices.Num()); } return Ar; unguard; } }; struct FkDOPBounds // bounds for compressed (quantized) kDOP node { FVector v1; FVector v2; friend FArchive& operator<<(FArchive &Ar, FkDOPBounds &V) { #if ENSLAVED if (Ar.Game == GAME_Enslaved) { // compressed structure int16 v1[3], v2[3]; Ar << v1[0] << v1[1] << v1[2] << v2[0] << v2[1] << v2[2]; return Ar; } #endif // ENSLAVED return Ar << V.v1 << V.v2; } }; struct FkDOPNode3 { FkDOPBounds Bounds; int f18; int16 f1C; int16 f1E; friend FArchive& operator<<(FArchive &Ar, FkDOPNode3 &V) { #if ENSLAVED if (Ar.Game == GAME_Enslaved) { // all data compressed byte fC, fD; int16 fE; Ar << V.Bounds; // compressed Ar << fC << fD << fE; return Ar; } #endif // ENSLAVED #if DCU_ONLINE if (Ar.Game == GAME_DCUniverse && (Ar.ArLicenseeVer & 0xFF00) >= 0xA00) return Ar << V.f18 << V.f1C << V.f1E; // no Bounds field - global for all nodes #endif // DCU_ONLINE Ar << V.Bounds << V.f18; #if FRONTLINES if (Ar.Game == GAME_Frontlines && Ar.ArLicenseeVer >= 7) goto new_ver; #endif #if MOHA if (Ar.Game == GAME_MOHA && Ar.ArLicenseeVer >= 8) goto new_ver; #endif #if MKVSDC if (Ar.Game == GAME_MK) goto old_ver; #endif if ((Ar.ArVer < 209) || (Ar.ArVer >= 468)) { new_ver: Ar << V.f1C << V.f1E; // int16 } else { old_ver: // old version assert(Ar.IsLoading); int tmp1C, tmp1E; Ar << tmp1C << tmp1E; V.f1C = tmp1C; V.f1E = tmp1E; } return Ar; } }; struct FkDOPNode3New // starting from version 770 { byte mins[3]; byte maxs[3]; friend FArchive& operator<<(FArchive &Ar, FkDOPNode3New &V) { Ar << V.mins[0] << V.mins[1] << V.mins[2] << V.maxs[0] << V.maxs[1] << V.maxs[2]; return Ar; } }; SIMPLE_TYPE(FkDOPNode3New, byte) struct FkDOPTriangle3 { int16 f0, f2, f4, f6; friend FArchive& operator<<(FArchive &Ar, FkDOPTriangle3 &V) { #if FURY if (Ar.Game == GAME_Fury && Ar.ArLicenseeVer >= 25) goto new_ver; #endif #if FRONTLINES if (Ar.Game == GAME_Frontlines && Ar.ArLicenseeVer >= 7) goto new_ver; #endif #if MOHA if (Ar.Game == GAME_MOHA && Ar.ArLicenseeVer >= 8) goto new_ver; #endif #if MKVSDC if (Ar.Game == GAME_MK) goto old_ver; #endif if ((Ar.ArVer < 209) || (Ar.ArVer >= 468)) { new_ver: Ar << V.f0 << V.f2 << V.f4 << V.f6; } else { old_ver: assert(Ar.IsLoading); int tmp0, tmp2, tmp4, tmp6; Ar << tmp0 << tmp2 << tmp4 << tmp6; V.f0 = tmp0; V.f2 = tmp2; V.f4 = tmp4; V.f6 = tmp6; } #if METRO_CONF if (Ar.Game == GAME_MetroConflict && Ar.ArLicenseeVer >= 2) { int16 unk; Ar << unk; } #endif // METRO_CONF return Ar; } }; #if FURY struct FFuryStaticMeshUnk // in other games this structure serialized after LOD models, in Fury - before { int unk0; int fC, f10, f14; TArray<int16> f18; // old version uses TArray<int>, new - TArray<int16>, but there is no code selection // (array size in old version is always 0?) friend FArchive& operator<<(FArchive &Ar, FFuryStaticMeshUnk &S) { if (Ar.ArVer < 297) Ar << S.unk0; // Version? (like in FIndexBuffer3) if (Ar.ArLicenseeVer >= 4) // Fury-specific Ar << S.fC << S.f10 << S.f14 << S.f18; return Ar; } }; #endif // FURY struct FStaticMeshUnk5 { int f0; byte f4[3]; friend FArchive& operator<<(FArchive &Ar, FStaticMeshUnk5 &S) { return Ar << S.f0 << S.f4[0] << S.f4[1] << S.f4[2]; } }; void UStaticMesh3::Serialize(FArchive &Ar) { guard(UStaticMesh3::Serialize); Super::Serialize(Ar); #if FURY if (Ar.Game == GAME_Fury && Ar.ArLicenseeVer >= 14) { int unk3C, unk40; Ar << unk3C << unk40; } #endif // FURY #if DARKVOID if (Ar.Game == GAME_DarkVoid) { int unk180, unk18C, unk198; if (Ar.ArLicenseeVer >= 5) Ar << unk180 << unk18C; if (Ar.ArLicenseeVer >= 6) Ar << unk198; } #endif // DARKVOID #if TERA if (Ar.Game == GAME_Tera && Ar.ArLicenseeVer >= 3) { FString SourceFileName; Ar << SourceFileName; } #endif // TERA #if TRANSFORMERS if (Ar.Game == GAME_Transformers && Ar.ArLicenseeVer >= 50) { kDOPNodes.BulkSerialize(Ar); kDOPTriangles.BulkSerialize(Ar); Ar << Lods; // note: Bounds is serialized as property (see UStaticMesh in h-file) goto done; } #endif // TRANSFORMERS #if MKVSDC if (Ar.Game == GAME_MK && Ar.ArVer >= 677) { // MK X TArrayOfArray<float, 9> kDOPNodes_MK; Ar << kDOPNodes_MK; goto kdop_tris; } #endif // MKVSDC Ar << Bounds << BodySetup; #if TUROK if (Ar.Game == GAME_Turok && Ar.ArLicenseeVer >= 59) { int unkFC, unk100; Ar << unkFC << unk100; } #endif // TUROK if (Ar.ArVer < 315) { UObject *unk; Ar << unk; } #if ENDWAR if (Ar.Game == GAME_EndWar) goto version; // no kDOP since version 306 #endif // ENDWAR #if SINGULARITY if (Ar.Game == GAME_Singularity) { // serialize kDOP tree assert(Ar.ArLicenseeVer >= 112); // old serialization code kDOPNodes.BulkSerialize(Ar); kDOPTriangles.BulkSerialize(Ar); // new serialization code // bug in Singularity serialization code: serialized the same things twice! goto new_kdop; } #endif // SINGULARITY #if BULLETSTORM if (Ar.Game == GAME_Bulletstorm && Ar.ArVer >= 739) goto new_kdop; #endif #if MASSEFF if (Ar.Game == GAME_MassEffect3 && Ar.ArLicenseeVer >= 153) goto new_kdop; #endif #if DISHONORED if (Ar.Game == GAME_Dishonored) goto old_kdop; #endif #if BIOSHOCK3 if (Ar.Game == GAME_Bioshock3) { FVector v1, v2[2], v3; TArray<int> arr4; Ar << v1 << v2[0] << v2[1] << v3 << arr4; goto version; } #endif #if THIEF4 if (Ar.Game == GAME_Thief4 && Ar.ArVer >= 707) goto new_kdop; #endif // kDOP tree if (Ar.ArVer < 770) { old_kdop: kDOPNodes.BulkSerialize(Ar); } else { new_kdop: FkDOPBounds Bounds; TArray<FkDOPNode3New> Nodes; Ar << Bounds; Nodes.BulkSerialize(Ar); } #if FURY if (Ar.Game == GAME_Fury && Ar.ArLicenseeVer >= 32) { int kDopUnk; Ar << kDopUnk; } #endif // FURY kdop_tris: kDOPTriangles.BulkSerialize(Ar); #if DCU_ONLINE if (Ar.Game == GAME_DCUniverse && (Ar.ArLicenseeVer & 0xFF00) >= 0xA00) { // this game stored kDOP bounds only once FkDOPBounds Bounds; Ar << Bounds; } #endif // DCU_ONLINE #if DOH if (Ar.Game == GAME_DOH && Ar.ArLicenseeVer >= 73) { FVector unk18; // extra computed kDOP field TArray<FVector> unkA0; int unk74; Ar << unk18; Ar << InternalVersion; // has InternalVersion = 0x2000F Ar << unkA0 << unk74 << Lods; goto done; } #endif // DOH #if THIEF4 if (Ar.Game == GAME_Thief4) { if (Ar.ArLicenseeVer >= 7) SkipFixedArray(Ar, sizeof(int) * 7); if (Ar.ArLicenseeVer >= 5) SkipFixedArray(Ar, sizeof(int) * (2+9)); // FName + int[9] if (Ar.ArLicenseeVer >= 3) SkipFixedArray(Ar, sizeof(int) * 7); if (Ar.ArLicenseeVer >= 2) { SkipFixedArray(Ar, sizeof(int) * 7); SkipFixedArray(Ar, sizeof(int) * 10); // complex structure SkipFixedArray(Ar, sizeof(int) * 3); SkipFixedArray(Ar, sizeof(int)); SkipFixedArray(Ar, sizeof(int)); } } #endif // THIEF4 version: Ar << InternalVersion; DBG_STAT("kDOPNodes=%d kDOPTriangles=%d\n", kDOPNodes.Num(), kDOPTriangles.Num()); DBG_STAT("ver: %d\n", InternalVersion); #if FURY if (Ar.Game == GAME_Fury) { int unk1, unk2; TArray<FFuryStaticMeshUnk> unk50; if (Ar.ArLicenseeVer >= 34) Ar << unk1; if (Ar.ArLicenseeVer >= 33) Ar << unk2; if (Ar.ArLicenseeVer >= 8) Ar << unk50; InternalVersion = 16; // uses InternalVersion=18 } #endif // FURY #if TRANSFORMERS if (Ar.Game == GAME_Transformers) goto lods; // The Bourne Conspiracy has InternalVersion=17 #endif if (InternalVersion >= 17 && Ar.ArVer < 593) { TArray<FName> unk; // some text properties; ContentTags ? (switched from binary to properties) Ar << unk; } if (Ar.ArVer >= 823) { guard(SerializeExtraLOD); int unkFlag; FStaticMeshLODModel3 unkLod; Ar << unkFlag; if (unkFlag) { appPrintf("has extra LOD model\n"); Ar << unkLod; } if (Ar.ArVer < 829) { TArray<int> unk; Ar << unk; } else { TArray<FStaticMeshUnk5> f178; Ar << f178; } int f74; Ar << f74; unguard; } #if SHADOWS_DAMNED if (Ar.Game == GAME_ShadowsDamned && Ar.ArLicenseeVer >= 26) { int unk134; Ar << unk134; } #endif // SHADOWS_DAMNED if (Ar.ArVer >= 859) { int unk; Ar << unk; } lods: Ar << Lods; // Ar << f48; done: DROP_REMAINING_DATA(Ar); ConvertMesh(); unguard; } // convert UStaticMesh3 to CStaticMesh void UStaticMesh3::ConvertMesh() { guard(UStaticMesh3::ConvertMesh); CStaticMesh *Mesh = new CStaticMesh(this); ConvertedMesh = Mesh; int ArVer = GetArVer(); int ArGame = GetGame(); // convert bounds Mesh->BoundingSphere.R = Bounds.SphereRadius / 2; //?? UE3 meshes has radius 2 times larger than mesh itself VectorSubtract(CVT(Bounds.Origin), CVT(Bounds.BoxExtent), CVT(Mesh->BoundingBox.Min)); VectorAdd (CVT(Bounds.Origin), CVT(Bounds.BoxExtent), CVT(Mesh->BoundingBox.Max)); // convert lods Mesh->Lods.Empty(Lods.Num()); for (int lod = 0; lod < Lods.Num(); lod++) { guard(ConvertLod); const FStaticMeshLODModel3 &SrcLod = Lods[lod]; if (SrcLod.Sections.Num() == 0) { // skip empty LODs appPrintf("StaticMesh %s.%s lod #%d has no sections\n", GetPackageName(), Name, lod); continue; } CStaticMeshLod *Lod = new (Mesh->Lods) CStaticMeshLod; int NumTexCoords = SrcLod.UVStream.NumTexCoords; int NumVerts = SrcLod.VertexStream.Verts.Num(); Lod->NumTexCoords = NumTexCoords; Lod->HasNormals = true; Lod->HasTangents = (ArVer >= 364); //?? check; FStaticMeshUVStream3 is used since this version #if BATMAN if ((ArGame == GAME_Batman2 || ArGame == GAME_Batman3) && CanStripNormalsAndTangents) Lod->HasNormals = Lod->HasTangents = false; #endif if (NumTexCoords > MAX_MESH_UV_SETS) appError("StaticMesh has %d UV sets", NumTexCoords); // sections Lod->Sections.AddDefaulted(SrcLod.Sections.Num()); for (int i = 0; i < SrcLod.Sections.Num(); i++) { CMeshSection &Dst = Lod->Sections[i]; const FStaticMeshSection3 &Src = SrcLod.Sections[i]; Dst.Material = Src.Mat; Dst.FirstIndex = Src.FirstIndex; Dst.NumFaces = Src.NumFaces; } // vertices Lod->AllocateVerts(NumVerts); for (int i = 0; i < NumVerts; i++) { const FStaticMeshUVItem3 &SUV = SrcLod.UVStream.UV[i]; CStaticMeshVertex &V = Lod->Verts[i]; V.Position = CVT(SrcLod.VertexStream.Verts[i]); UnpackNormals(SUV.Normal, V); // copy UV const FMeshUVFloat* fUV = &SUV.UV[0]; V.UV = *CVT(fUV); for (int TexCoordIndex = 1; TexCoordIndex < NumTexCoords; TexCoordIndex++) { fUV++; Lod->ExtraUV[TexCoordIndex-1][i] = *CVT(fUV); } //!! also has ColorStream } // indices Lod->Indices.Initialize(&SrcLod.Indices.Indices); // 16-bit only if (Lod->Indices.Num() == 0) appNotify("This StaticMesh doesn't have an index buffer"); unguardf("lod=%d", lod); } Mesh->FinalizeMesh(); unguard; } #endif // UNREAL3
710a336e1e217ce7e4c6eed7d91572295938e0a6
fa1ee5240f9585fe12d75547d97629acf65b0632
/engine/system/win/sys_console.cpp
ec640d194f6bb2335438fbf96367d8d1d41e7433
[]
no_license
sthalik/PathOfBuilding-SimpleGraphic
cfdfa0e0ef1419fcab4cf9abcaf9c1d1abf87af7
9bed4798842d03f9970b3b50e55fe01fef2a6468
refs/heads/master
2022-11-22T10:34:28.722002
2020-07-11T18:35:04
2020-07-11T18:35:04
103,319,021
2
10
null
null
null
null
UTF-8
C++
false
false
6,998
cpp
// SimpleGraphic Engine // (c) David Gowor, 2014 // // Module: System Console // Platform: Windows // #include "sys_local.h" // ============= // Configuration // ============= #define SCON_WIDTH 550 #define SCON_HEIGHT 500 #define SCON_STYLE WS_VISIBLE | WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_CLIPCHILDREN // ====================== // sys_IConsole Interface // ====================== class sys_console_c: public sys_IConsole, public conPrintHook_c, public thread_c { public: // Interface void SetVisible(bool show); void SetTitle(const char* title); // Encapsulated sys_console_c(sys_IMain* sysHnd); ~sys_console_c(); sys_main_c* sys; bool shown; // Is currently shown? HWND hwMain; // Main window HWND hwOut; // Output HFONT font; // Font handle HBRUSH bBackground;// Background brush static LRESULT __stdcall WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); volatile bool doRun; volatile bool isRunning; void ThreadProc(); void Print(const char* text); void CopyToClipboard(); void ConPrintHook(const char* text); void ConPrintClear(); }; sys_IConsole* sys_IConsole::GetHandle(sys_IMain* sysHnd) { return new sys_console_c(sysHnd); } void sys_IConsole::FreeHandle(sys_IConsole* hnd) { delete (sys_console_c*)hnd; } sys_console_c::sys_console_c(sys_IMain* sysHnd) : conPrintHook_c(sysHnd->con), sys((sys_main_c*)sysHnd), thread_c(sysHnd) { isRunning = false; doRun = true; ThreadStart(true); while ( !isRunning ) Sleep(15); } void sys_console_c::ThreadProc() { // Get info of the monitor containing the mouse cursor POINT curPos; GetCursorPos(&curPos); HMONITOR hMon = MonitorFromPoint(curPos, MONITOR_DEFAULTTOPRIMARY); MONITORINFO monInfo; monInfo.cbSize = sizeof(monInfo); GetMonitorInfo(hMon, &monInfo); // Find the window position and size RECT wrec; wrec.left = (monInfo.rcMonitor.right + monInfo.rcMonitor.left - SCON_WIDTH) / 2; wrec.top = (monInfo.rcMonitor.bottom + monInfo.rcMonitor.top - SCON_HEIGHT) / 2; wrec.right = wrec.left + SCON_WIDTH; wrec.bottom = wrec.top + SCON_HEIGHT; AdjustWindowRect(&wrec, SCON_STYLE, FALSE); // Register the class WNDCLASS conClass; memset(&conClass, 0, sizeof(WNDCLASS)); conClass.hInstance = sys->hinst; conClass.lpszClassName = CFG_SCON_TITLE " Class"; conClass.lpfnWndProc = WndProc; conClass.hbrBackground = CreateSolidBrush(CFG_SCON_WINBG); conClass.hCursor = LoadCursor(NULL, IDC_ARROW); conClass.hIcon = sys->icon; if (RegisterClass(&conClass) == 0) exit(0); // Create the system console window hwMain = CreateWindowEx( 0, CFG_SCON_TITLE " Class", CFG_SCON_TITLE, SCON_STYLE, wrec.left, wrec.top, wrec.right - wrec.left, wrec.bottom - wrec.top, NULL, NULL, sys->hinst, NULL ); SetWindowLongPtr(hwMain, GWLP_USERDATA, (LONG_PTR)this); // Populate window hwOut = CreateWindowEx( WS_EX_CLIENTEDGE, "EDIT", "", WS_VISIBLE | WS_CHILD | WS_BORDER | WS_VSCROLL | ES_MULTILINE | ES_READONLY, 10, 10, SCON_WIDTH - 20, SCON_HEIGHT - 20, hwMain, NULL, sys->hinst, NULL ); // Create the output window font font = CreateFont( 12, 0, 0, 0, FW_LIGHT, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, FIXED_PITCH|FF_MODERN, "Lucida Console" ); SetWindowFont(hwOut, font, FALSE); Edit_LimitText(hwOut, 0xFFFF); // Create the output window background brush bBackground = CreateSolidBrush(CFG_SCON_TEXTBG); // Flush any messages created sys->RunMessages(NULL, true); shown = true; InstallPrintHook(); isRunning = true; while (doRun) { sys->RunMessages(NULL, false, 100); //sys->Sleep(1); } RemovePrintHook(); // Delete font and brush DeleteObject(bBackground); DeleteObject(font); // Destroy window DestroyWindow(hwMain); UnregisterClass(CFG_SCON_TITLE " Class", sys->hinst); isRunning = false; } sys_console_c::~sys_console_c() { doRun = false; while (isRunning) Sleep(15); } // ======================== // Console Window Procedure // ======================== LRESULT __stdcall sys_console_c::WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { sys_console_c* conWin = (sys_console_c*)GetWindowLongPtr(hwnd, GWLP_USERDATA); switch (msg) { case WM_CTLCOLOREDIT: case WM_CTLCOLORSTATIC: // Set text color of output window SetTextColor((HDC)wParam, CFG_SCON_TEXTCOL); SetBkColor((HDC)wParam, CFG_SCON_TEXTBG); return (LRESULT)conWin->bBackground; case WM_KEYUP: if (wParam != VK_ESCAPE) { break; } case WM_CLOSE: // Quit PostQuitMessage(0); return FALSE; } return DefWindowProc(hwnd, msg, wParam, lParam); } // ============== // System Console // ============== void sys_console_c::SetVisible(bool show) { if (show) { if ( !shown ) { shown = true; // Show the window ShowWindow(hwMain, SW_SHOW); SetForegroundWindow(hwMain); // Select all text and replace with full text Edit_SetText(hwOut, ""); char* buffer = sys->con->BuildBuffer(); Print(buffer); delete buffer; sys->RunMessages(NULL, true); } } else { shown = false; // Hide the window ShowWindow(hwMain, SW_HIDE); } } void sys_console_c::SetTitle(const char* title) { SetWindowText(hwMain, (title && *title)? title : CFG_SCON_TITLE); } void sys_console_c::Print(const char* text) { if ( !shown ) { return; } int escLen; // Find the required buffer length int len = 0; for (int b = 0; text[b]; b++) { if (text[b] == '\n') { // Newline takes 2 characters len+= 2; } else if (escLen = IsColorEscape(&text[b])) { // Skip colour escapes b+= escLen - 1; } else { len++; } } // Parse into the buffer char* winText = AllocStringLen(len); char* p = winText; for (int b = 0; text[b]; b++) { if (text[b] == '\n') { // Append newline *(p++) = '\r'; *(p++) = '\n'; } else if (escLen = IsColorEscape(&text[b])) { // Skip colour escapes b+= escLen - 1; } else { // Add character *(p++) = text[b]; } } // Append to the output Edit_SetSel(hwOut, Edit_GetTextLength(hwOut), -1); Edit_ReplaceSel(hwOut, winText); Edit_Scroll(hwOut, 0xFFFF, 0); sys->RunMessages(NULL, true); delete winText; } void sys_console_c::CopyToClipboard() { int len = GetWindowTextLength(hwOut); if (len) { HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, len + 1); if ( !hg ) return; char* cp = (char*)GlobalLock(hg); GetWindowText(hwOut, cp, len + 1); GlobalUnlock(hg); OpenClipboard(hwMain); EmptyClipboard(); SetClipboardData(CF_TEXT, hg); CloseClipboard(); } } void sys_console_c::ConPrintHook(const char* text) { Print(text); } void sys_console_c::ConPrintClear() { Edit_SetText(hwOut, ""); }
1921d32dfdb8872b7377f46031408b450265aa20
ee0290e802f8db4decd72089439c460da966d861
/algo/contests/3/queries/queries.cpp
76f931029bfb5a186020c0afd2192e11d497d2de
[]
no_license
nunberty/au-fall-2014
d16cecf24a0e791f0c0c009df354a8e28a91f975
60853f9bab1d23c71f167f81ea3cf1323c458d92
refs/heads/master
2021-01-19T03:13:07.857311
2014-12-27T13:28:02
2014-12-27T13:28:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,028
cpp
#include <fstream> #include <algorithm> #include <map> #include <vector> std::map<uint32_t, std::vector<uint32_t>> data; bool contains(uint32_t l, uint32_t r, uint32_t value) { if (data[value].empty()) { return false; } auto low = std::lower_bound(begin(data[value]), end(data[value]), l); auto up = std::upper_bound(begin(data[value]), end(data[value]), r); return (up - low) > 0; } int main() { std::ios_base::sync_with_stdio(false); std::ifstream in("queries.in"); std::ofstream out("queries.out"); uint32_t N; in >> N; for (uint32_t i = 1; i < N + 1; ++i) { uint32_t value; in >> value; data[value].push_back(i); } for (auto &pair : data) { std::sort(begin(pair.second), end(pair.second)); } uint32_t K; in >> K; for (uint32_t i = 0; i < K; ++i) { uint32_t l, r, value; in >> l >> r >> value; out << contains(l , r, value); } out << std::endl; return 0; }
8e8d83d70e59749b97abbd59184a290903a0e4ee
78918391a7809832dc486f68b90455c72e95cdda
/boost_lib/boost/typeof/std/functional.hpp
b4c177d20bd1235611f84be811f3d3ebea87227c
[ "MIT" ]
permissive
kyx0r/FA_Patcher
50681e3e8bb04745bba44a71b5fd04e1004c3845
3f539686955249004b4483001a9e49e63c4856ff
refs/heads/master
2022-03-28T10:03:28.419352
2020-01-02T09:16:30
2020-01-02T09:16:30
141,066,396
2
0
null
null
null
null
UTF-8
C++
false
false
2,505
hpp
// Copyright (C) 2005 Arkadiy Vertleyb, Peder Holt. // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_TYPEOF_STD_functional_hpp_INCLUDED #define BOOST_TYPEOF_STD_functional_hpp_INCLUDED #include <functional> #include <boost/typeof/typeof.hpp> #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP() #ifndef BOOST_NO_CXX98_FUNCTION_BASE BOOST_TYPEOF_REGISTER_TEMPLATE(std::unary_function, 2) BOOST_TYPEOF_REGISTER_TEMPLATE(std::binary_function, 3) #endif//BOOST_NO_CXX98_FUNCTION_BASE BOOST_TYPEOF_REGISTER_TEMPLATE(std::plus, 1) BOOST_TYPEOF_REGISTER_TEMPLATE(std::minus, 1) BOOST_TYPEOF_REGISTER_TEMPLATE(std::multiplies, 1) BOOST_TYPEOF_REGISTER_TEMPLATE(std::divides, 1) BOOST_TYPEOF_REGISTER_TEMPLATE(std::modulus, 1) BOOST_TYPEOF_REGISTER_TEMPLATE(std::negate, 1) BOOST_TYPEOF_REGISTER_TEMPLATE(std::equal_to, 1) BOOST_TYPEOF_REGISTER_TEMPLATE(std::not_equal_to, 1) BOOST_TYPEOF_REGISTER_TEMPLATE(std::greater, 1) BOOST_TYPEOF_REGISTER_TEMPLATE(std::less, 1) BOOST_TYPEOF_REGISTER_TEMPLATE(std::greater_equal, 1) BOOST_TYPEOF_REGISTER_TEMPLATE(std::less_equal, 1) BOOST_TYPEOF_REGISTER_TEMPLATE(std::logical_and, 1) BOOST_TYPEOF_REGISTER_TEMPLATE(std::logical_or, 1) BOOST_TYPEOF_REGISTER_TEMPLATE(std::logical_not, 1) BOOST_TYPEOF_REGISTER_TEMPLATE(std::unary_negate, 1) BOOST_TYPEOF_REGISTER_TEMPLATE(std::binary_negate, 1) #ifndef BOOST_NO_CXX98_BINDERS #if defined(__MWERKS__) && defined(_MSL_EXTENDED_BINDERS) BOOST_TYPEOF_REGISTER_TEMPLATE(std::binder1st, 2) BOOST_TYPEOF_REGISTER_TEMPLATE(std::binder2nd, 2) #else BOOST_TYPEOF_REGISTER_TEMPLATE(std::binder1st, 1) BOOST_TYPEOF_REGISTER_TEMPLATE(std::binder2nd, 1) #endif BOOST_TYPEOF_REGISTER_TEMPLATE(std::pointer_to_unary_function, 2) BOOST_TYPEOF_REGISTER_TEMPLATE(std::pointer_to_binary_function, 3) BOOST_TYPEOF_REGISTER_TEMPLATE(std::mem_fun_t, 2) BOOST_TYPEOF_REGISTER_TEMPLATE(std::mem_fun1_t, 3) BOOST_TYPEOF_REGISTER_TEMPLATE(std::mem_fun_ref_t, 2) BOOST_TYPEOF_REGISTER_TEMPLATE(std::mem_fun1_ref_t, 3) #if !BOOST_WORKAROUND(BOOST_DINKUMWARE_STDLIB, == 1) BOOST_TYPEOF_REGISTER_TEMPLATE(std::const_mem_fun_t, 2) BOOST_TYPEOF_REGISTER_TEMPLATE(std::const_mem_fun1_t, 3) BOOST_TYPEOF_REGISTER_TEMPLATE(std::const_mem_fun_ref_t, 2) BOOST_TYPEOF_REGISTER_TEMPLATE(std::const_mem_fun1_ref_t, 3) #endif//BOOST_WORKAROUND(BOOST_DINKUMWARE_STDLIB, == 1) #endif//BOOST_NO_CXX98_BINDERS #endif//BOOST_TYPEOF_STD_functional_hpp_INCLUDED
73b04cfb8e61d58d5e86f82612173c85c87a33ab
c6c2672f74d8b32d2f7164b6296a33a2a16a28e7
/src/ActionRecognition/Example.cc
f6ef6bf4bd945330b036e48ba0e2d267ba2cd000
[]
no_license
RaduAlexandru/Dense-Trajectories
31b3e3b1a7e67b7b36a932d0f27d23d979fe3372
b2a06f59e2b9fa46e572c0a39e50a98a407daf23
refs/heads/master
2021-01-21T07:13:53.795531
2017-05-24T19:13:37
2017-05-24T19:13:37
91,604,690
1
0
null
null
null
null
UTF-8
C++
false
false
3,268
cc
/* * Example.cc * * Created on: Apr 25, 2017 * Author: richard */ #include "Example.hh" using namespace ActionRecognition; /* parameter definition */ const Core::ParameterString Example::paramSomeFile_( "filename", // parameter name "", // default value "example"); // prefix (set parameter via --example.some-string=your-string) const Core::ParameterInt Example::paramSomeInt_( "some-int", // parameter name 42, // default value "example"); // prefix (set parameter via --example.some-int=11) const Core::ParameterFloat Example::paramSomeFloat_( "some-float", // parameter name 0.123, // default value "example"); // prefix (set parameter via --example.some-float=0.1) /* constructor */ Example::Example() : filename_(Core::Configuration::config(paramSomeFile_)), someInt_(Core::Configuration::config(paramSomeInt_)), someFloat_(Core::Configuration::config(paramSomeFloat_)) { require(!filename_.empty()); // make sure paramter filename contains some string } void Example::logMessages() { // write something to the log (default: std::cout, write log to file by setting parameter --log-file=your-file.log) Core::Log::os("This is an example log. The string ") << filename_ << " has been passed as parameter."; // write something with indentation in xml-style Core::Log::openTag("example"); Core::Log::os("This is an example log in xml style with an opening and closing tag."); Core::Log::closeTag(); // example: abort execution due to some error (e.g. wrong parameter) if (someFloat_ <= 0) Core::Error::msg("Parameter some-float must be positive.") << Core::Error::abort; } void Example::matrixUsage() { Math::Matrix<Float> A(5, 3); // create 5x3 matrix A.setToZero(); A.at(2, 2) = 1.0; A.addConstantElementwise(10.0); Math::Matrix<Float> B(5, 3); B.fill(2.0); B.at(0, 0) = 0.0; A.elementwiseMultiplication(B); A.write("matrix.gz"); // write matrix to file } void Example::fileIO() { /* example: write a gzipped file */ Core::Log::openTag("writing example"); if (!Core::Utils::isGz(filename_)) // if file does not end on .gz filename_.append(".gz"); Core::CompressedStream outStream(filename_, std::ios::out); outStream << "some string followed by a newline" << Core::IOStream::endl; outStream << someFloat_ << " " << someInt_ << Core::IOStream::endl; // write numbers to the file outStream.close(); Core::Log::closeTag(); /* example: read a gzipped file */ Core::Log::openTag("reading example 1"); Core::CompressedStream inStream(filename_, std::ios::in); // read a complete line as a string std::string line; inStream.getline(line); // read the float and int Float f; inStream >> f; u32 i; inStream >> i; Core::Log::os("Read line \"") << line << "\" and int " << i << " and float " << f; inStream.close(); Core::Log::closeTag(); /* example: read all lines of a file */ Core::Log::openTag("reading example 2"); Core::CompressedStream inStream2(filename_, std::ios::in); std::vector<std::string> allLines; while (inStream2.getline(line)) { Core::Log::os("Line by line reading: ") << line; } inStream2.close(); Core::Log::closeTag(); } /* function */ void Example::run() { logMessages(); matrixUsage(); fileIO(); }
38cb2e99d196c94e8ec1a5b28637ab49de3abe35
1a4ce6b9fbec90830ed60796f7cd6fc901e91a05
/算法练习/算法回顾-动态规划/钢条切割典例.cpp
522f6d0e978efd5bec75a75731ce290367a60e3c
[]
no_license
wszhhx/Algorithm-Practice
35271cd8cb564f3c19098bfe5e8e573cab4052d9
5fd3bb0d80bb82c8935ede2bed73670aa912e4c4
refs/heads/master
2020-04-30T01:40:53.214661
2019-03-31T10:14:28
2019-03-31T10:14:28
176,535,592
0
0
null
null
null
null
GB18030
C++
false
false
1,214
cpp
#include<iostream> #include<conio.h> using namespace std; int price[101] = { -1,1,5,8,9,10,17,17,20,24,30 }; int result[101]; int part[101]; int count = 0; int cut_rod_dg(int n) { //原始递归方法 if (n == 0) return 0; int q = -1; int temp; for (int i = 1; i <= n; ++i) { temp = price[i] + cut_rod_dg(n - i); q = q < temp ? temp : q; } return q; } int cut_rod_mem(int n) { //带记忆的自顶向下递归 if (n == 0) return 0; if (result[n] >= 0) return result[n]; int q = -1; int temp; for (int i = 1; i <= n; ++i) { temp = price[i] + cut_rod_mem(n - i); q = q < temp ? temp : q; } result[n] = q; return q; } int cut_rod_bottom_up(int n) { //自底向上的算法 result[0] = 0; int q, temp; for (int i = 1; i <= 100; ++i) { q = -1; for (int j = 1; j <= i; ++j) { //因为是自底向上,所以已经求得的result[i]已经是最优解 temp = price[j] + result[i - j]; q = q < temp ? temp : q; part[i] = j; //记录最优解的第一段长度 } result[i] = q; } return result[n]; } int main() { int n; memset(result, -1, 100 * sizeof(int)); cin >> n; cout << endl; cout << cut_rod_bottom_up(n) << endl; system("pause"); return 0; }
5b1b06385de2cb01eb8d01b9d163ad082f025459
1fb1e2a0932eb0257ca0f94474f483bc1d1433a1
/mxp/sim/lib/vbxapi/convert_vinstr.hpp
2148da4b1fed2e8f1908b50c8f980e841ff8ddf5
[]
no_license
zenggzh/caffepresso
8d4ad93da301f0846ab30c16e87446902ac7679e
72eb027e6a7ae76d671b46a8569c7a6e5ff033ba
refs/heads/master
2020-03-16T17:21:20.041730
2017-10-10T07:06:16
2017-10-10T07:06:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,515
hpp
#ifndef __CONVERT_VINSTR_HPP__ #define __CONVERT_VINSTR_HPP__ #include <assert.h> template<vinstr_t _instr>struct get_arith{ static const vinstr_t instr=_instr;}; template<> struct get_arith<VCMV_LTZ>{static const vinstr_t instr=VSUB;}; template<> struct get_arith<VCMV_GTZ>{static const vinstr_t instr=VSUB;}; template<> struct get_arith<VCMV_LEZ>{static const vinstr_t instr=VSUB;}; template<> struct get_arith<VCMV_GEZ>{static const vinstr_t instr=VSUB;}; template<> struct get_arith<VCMV_Z >{static const vinstr_t instr=VSUB;}; template<> struct get_arith<VCMV_NZ >{static const vinstr_t instr=VSUB;}; template<vinstr_t _instr>struct get_cmv_t{ static const vinstr_t instr=VCMV_NZ;}; template<> struct get_cmv_t<VCMV_LTZ>{static const vinstr_t instr=VCMV_LTZ;}; template<> struct get_cmv_t<VCMV_GTZ>{static const vinstr_t instr=VCMV_GTZ;}; template<> struct get_cmv_t<VCMV_LEZ>{static const vinstr_t instr=VCMV_LEZ;}; template<> struct get_cmv_t<VCMV_GEZ>{static const vinstr_t instr=VCMV_GEZ;}; template<> struct get_cmv_t<VCMV_Z >{static const vinstr_t instr=VCMV_Z ;}; template<> struct get_cmv_t<VCMV_NZ >{static const vinstr_t instr=VCMV_NZ ;}; template<vinstr_t _instr> struct invert_cmv{static const vinstr_t instr=VCMV_Z;}; template<> struct invert_cmv<VCMV_LTZ>{static const vinstr_t instr=VCMV_GEZ;}; template<> struct invert_cmv<VCMV_GTZ>{static const vinstr_t instr=VCMV_LEZ;}; template<> struct invert_cmv<VCMV_LEZ>{static const vinstr_t instr=VCMV_GTZ;}; template<> struct invert_cmv<VCMV_GEZ>{static const vinstr_t instr=VCMV_LTZ;}; template<> struct invert_cmv<VCMV_Z>{static const vinstr_t instr=VCMV_NZ;}; template<> struct invert_cmv<VCMV_NZ>{static const vinstr_t instr=VCMV_Z;}; template<typename T> inline vinstr_t get_cmv(const VBX::Vector<T>& v ){ return v.cmv; } template<typename lhs_t,typename rhs_t,vinstr_t instr,typename btype> inline vinstr_t get_cmv(const bin_op<lhs_t,rhs_t,instr,btype>& ){ return get_cmv_t<instr>::instr; } template<typename lhs_t,typename rhs_t,_internal::log_op_t lop,bool negate> inline vinstr_t get_cmv(const Logical_vop<lhs_t,rhs_t,lop,negate>& lvo ){ return VCMV_NZ; } inline vinstr_t get_inv_cmv(vinstr_t instr ){ switch(instr){ case VCMV_LTZ: return VCMV_GEZ; case VCMV_GTZ: return VCMV_LEZ; case VCMV_LEZ: return VCMV_GTZ; case VCMV_GEZ: return VCMV_LTZ; case VCMV_Z : return VCMV_NZ; case VCMV_NZ : return VCMV_Z; default: assert(0); return instr; } } //resolve //vec a log b // -> #endif //__CONVERT_VINSTR_HPP__
7f8d110ec8c5cc76bf0036481e718499706c2be7
188fb8ded33ad7a2f52f69975006bb38917437ef
/Fluid/processor3/0.25/Uf
0a8bde513cd92af0444001c09d8ddeb6a0b80196
[]
no_license
abarcaortega/Tuto_2
34a4721f14725c20471ff2dc8d22b52638b8a2b3
4a84c22efbb9cd2eaeda92883343b6910e0941e2
refs/heads/master
2020-08-05T16:11:57.674940
2019-10-04T09:56:09
2019-10-04T09:56:09
212,573,883
0
0
null
null
null
null
UTF-8
C++
false
false
30,141
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: dev | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class surfaceVectorField; location "0.25"; object Uf; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 1 -1 0 0 0 0]; internalField nonuniform List<vector> 881 ( (9.91661 2.32849e-24 0.0247533) (9.96431 -1.10858e-20 0.0400171) (9.81644 2.19813e-23 0.0327502) (9.92112 6.68057e-23 0.0494038) (9.69839 -6.00572e-21 0.0393898) (9.84788 -9.09907e-23 0.059836) (9.5609 -5.95456e-21 0.0460881) (9.74638 -1.17286e-20 0.0715825) (9.40418 -9.57192e-23 0.0529232) (9.62357 -1.25079e-20 0.0837888) (9.22858 0 0.059953) (9.482 -1.99867e-22 0.0963839) (9.03406 0 0.0673169) (9.32131 -6.46115e-21 0.109592) (8.82022 3.74294e-21 0.0751493) (9.1407 3.643e-24 0.123638) (8.58642 7.44085e-21 0.0835526) (8.93952 -1.45797e-22 0.138697) (8.3319 1.68314e-21 0.0926002) (8.71711 7.51238e-21 0.154901) (8.0558 7.90109e-23 0.102342) (8.47257 -1.64304e-23 0.172351) (7.75726 2.06225e-21 0.112801) (8.20492 -4.17508e-21 0.191112) (7.43552 6.48636e-22 0.123956) (7.91321 6.76532e-23 0.211184) (7.09001 8.73617e-22 0.135746) (7.59656 -2.28121e-21 0.23249) (6.72048 1.58738e-21 0.148064) (7.25424 1.1866e-21 0.254867) (6.32706 1.2572e-21 0.160765) (6.88584 2.53323e-21 0.278066) (5.91038 0 0.173669) (6.49133 -5.2881e-21 0.301743) (5.47164 0 0.186569) (6.07118 -5.65057e-21 0.325465) (5.01267 0 0.199237) (5.62642 -5.92263e-21 0.348719) (4.53596 1.00939e-20 0.211424) (5.15873 -6.26457e-21 0.370908) (4.67051 9.99406e-21 0.391344) (9.99505 -1.08839e-20 0.0525351) (9.99091 2.59331e-23 0.0424065) (9.95425 -4.87703e-23 0.0722779) (9.97247 4.45427e-23 0.0695476) (9.89049 -5.9729e-21 0.0896007) (9.92772 -2.73613e-22 0.0921769) (9.80568 -1.83031e-20 0.107474) (9.85558 6.36047e-21 0.115765) (9.69997 -1.24585e-20 0.12605) (9.76175 -2.13009e-23 0.140332) (9.57355 -6.73903e-21 0.145411) (9.64884 -1.99867e-22 0.165808) (9.42635 -6.37752e-21 0.165848) (9.51671 2.00951e-22 0.192557) (9.25802 -3.88901e-21 0.18767) (9.36468 1.38222e-20 0.221004) (9.06791 1.47602e-23 0.211133) (9.19216 -4.07223e-21 0.251516) (8.85516 5.71927e-21 0.236438) (8.99852 -3.65728e-21 0.284424) (8.61871 -4.32365e-21 0.263728) (8.78282 2.0976e-21 0.319993) (8.35746 -6.12216e-21 0.293069) (8.54399 -2.5938e-21 0.358394) (8.07032 -2.89367e-21 0.324436) (8.2809 4.82815e-21 0.399696) (7.75625 -1.92952e-21 0.357697) (7.99237 -1.72395e-21 0.443854) (7.41439 2.14e-21 0.392587) (7.67722 3.28426e-21 0.490666) (7.04415 -4.11752e-21 0.428709) (7.33447 -1.23179e-21 0.539747) (6.64534 -1.09446e-20 0.465524) (6.96336 -5.32318e-21 0.590526) (6.21824 -1.1589e-20 0.502363) (6.5635 5.38065e-21 0.642241) (5.76375 -1.21935e-20 0.53842) (6.13497 -1.1546e-20 0.693936) (5.28346 -6.28105e-21 0.572753) (5.67842 -1.82604e-20 0.744463) (5.19519 1.28311e-20 0.792455) (9.98751 1.0971e-20 0.062072) (9.98857 3.33714e-20 0.0483932) (9.94955 -1.8493e-22 0.0925887) (9.96747 2.26009e-20 0.0882464) (9.88903 1.21652e-20 0.121123) (9.92356 5.00875e-25 0.122816) (9.8088 2.45999e-20 0.150626) (9.85428 3.57097e-20 0.157497) (9.70944 1.22496e-20 0.181466) (9.7642 1.24042e-20 0.193404) (9.5911 6.74659e-21 0.21381) (9.65595 0 0.230712) (9.45376 2.0571e-20 0.248065) (9.52966 -6.57386e-21 0.26988) (9.29717 1.34171e-20 0.284695) (9.38478 -1.37473e-20 0.31149) (9.1208 -7.73035e-21 0.324132) (9.22084 -6.79908e-22 0.3561) (8.92389 -7.19956e-21 0.366758) (9.03728 7.96679e-21 0.404226) (8.70546 3.7612e-21 0.412866) (8.83338 -1.54827e-20 0.456321) (8.46437 8.44061e-21 0.462639) (8.60816 1.12523e-20 0.512719) (8.19939 5.91428e-21 0.516134) (8.36051 -6.36684e-21 0.573641) (7.9092 3.54866e-21 0.573251) (8.08917 4.48767e-21 0.639161) (7.59252 -1.33036e-22 0.633688) (7.79286 2.40787e-23 0.709148) (7.24818 -2.50009e-21 0.696914) (7.47027 2.47938e-21 0.783219) (6.87524 1.11131e-20 0.762165) (7.12023 -2.07398e-20 0.860721) (6.47308 5.16448e-21 0.828434) (6.74174 2.72651e-20 0.940714) (6.04155 -1.77478e-20 0.894465) (6.33412 -1.6972e-20 1.02195) (5.58108 1.25631e-21 0.958739) (5.89707 1.21778e-20 1.10288) (5.43083 -1.24994e-20 1.18161) (9.98341 4.48631e-20 0.0750585) (9.98735 1.8105e-22 0.0563446) (9.94554 2.2499e-20 0.117774) (9.96457 -7.47791e-24 0.106902) (9.88603 2.39944e-20 0.158338) (9.92059 1.83113e-22 0.152945) (9.80704 2.32219e-20 0.199416) (9.85253 -1.11079e-21 0.198578) (9.7095 0 0.24186) (9.76422 -8.12607e-24 0.245504) (9.59362 -1.34019e-20 0.286127) (9.65816 7.91331e-22 0.294254) (9.45947 -4.09685e-20 0.332806) (9.5346 -8.46504e-22 0.345402) (9.30687 -2.76707e-20 0.382551) (9.39311 -1.29698e-20 0.399657) (9.13545 1.51247e-20 0.435993) (9.2333 -2.74364e-24 0.457736) (8.94462 -6.05655e-22 0.493711) (9.0547 -1.47829e-20 0.520317) (8.7336 -7.66233e-21 0.556196) (8.85672 -6.25816e-23 0.588013) (8.50142 -3.77074e-21 0.623822) (8.63854 -4.65252e-22 0.661339) (8.24696 -7.65869e-21 0.696821) (8.39914 -2.69815e-21 0.740688) (7.96898 9.07557e-22 0.775234) (8.13737 -3.26491e-21 0.82628) (7.66617 2.66928e-21 0.858854) (7.85199 -4.67548e-21 0.91811) (7.33724 -1.60464e-20 0.947181) (7.54169 2.802e-23 1.01588) (6.98094 -4.00787e-21 1.0394) (7.20516 -5.37282e-21 1.11898) (6.5962 4.57809e-21 1.13436) (6.84115 -5.41037e-21 1.22643) (6.18221 1.33073e-20 1.23053) (6.44853 -1.13332e-20 1.33687) (5.73851 -1.86105e-21 1.32603) (6.02641 3.58937e-20 1.44852) (5.57419 -9.99776e-20 1.55918) (9.98154 -4.46946e-20 0.0888014) (9.98681 -6.5934e-20 0.0651983) (9.94337 -2.23123e-20 0.142287) (9.96325 -6.74509e-20 0.125708) (9.88484 -2.49377e-20 0.193657) (9.91945 0 0.182577) (9.80728 -2.43291e-20 0.245394) (9.8527 -2.46271e-20 0.238914) (9.71164 7.93242e-22 0.298738) (9.76639 -8.1256e-24 0.296588) (9.59821 1.33287e-20 0.354417) (9.6628 7.91286e-22 0.356458) (9.46704 2.70069e-20 0.413159) (9.54221 1.23927e-20 0.419247) (9.31798 1.48608e-20 0.475743) (9.40424 1.45855e-20 0.485781) (9.15071 -3.00938e-20 0.542942) (9.24853 4.49751e-22 0.556917) (8.9647 -1.40595e-20 0.615477) (9.07466 -1.53727e-20 0.63348) (8.75925 7.13051e-21 0.69399) (8.88207 1.57858e-20 0.71624) (8.53347 5.79725e-22 0.779015) (8.66999 -8.36974e-21 0.805876) (8.28635 1.68913e-21 0.870935) (8.43748 9.55669e-21 0.902942) (8.01671 -8.86529e-21 0.969927) (8.18343 -1.20256e-20 1.00781) (7.72332 -7.26225e-21 1.0759) (7.90666 2.26468e-21 1.12063) (7.40485 1.06395e-20 1.18846) (7.60586 -4.93413e-21 1.24122) (7.05997 -6.78269e-21 1.30682) (7.27965 1.53317e-20 1.36908) (6.68739 -2.14236e-20 1.42982) (6.92666 -4.26325e-20 1.50329) (6.2859 1.1814e-20 1.55586) (6.54549 3.30266e-20 1.6425) (5.85446 -6.39554e-20 1.68288) (6.13481 1.55632e-22 1.78489) (5.69342 -2.56592e-20 1.92813) (9.98077 -8.87084e-20 0.102836) (9.98661 4.36416e-20 0.0744209) (9.9426 -4.42858e-20 0.166483) (9.96291 4.46443e-20 0.144513) (9.88527 0 0.228327) (9.9197 -4.57998e-20 0.211605) (9.80958 0 0.290638) (9.85456 0 0.278283) (9.71633 0 0.354813) (9.77064 -4.8606e-20 0.346398) (9.60585 0 0.421764) (9.67002 0 0.417045) (9.4782 0 0.492342) (9.55295 2.59994e-20 0.491112) (9.33325 0 0.567446) (9.4191 0 0.569543) (9.17066 1.49698e-20 0.647984) (9.26814 0 0.653324) (8.98996 1.48511e-20 0.734828) (9.09967 -1.4323e-20 0.743427) (8.79045 -1.16709e-23 0.828781) (8.91313 -3.05452e-20 0.840773) (8.57129 8.27256e-22 0.93054) (8.70778 2.43017e-22 0.946201) (8.33147 -4.42528e-21 1.04065) (8.48269 2.1059e-21 1.06043) (8.06986 -7.19997e-22 1.15945) (8.23677 1.08208e-20 1.18399) (7.78521 4.50749e-21 1.28699) (7.96882 1.78262e-23 1.31718) (7.47616 0 1.42301) (7.67749 0 1.45998) (7.14128 -2.12375e-20 1.56685) (7.36133 0 1.61204) (6.77909 1.27526e-20 1.71744) (7.01882 -1.41903e-22 1.77258) (6.38808 2.09339e-20 1.8732) (6.6483 1.12588e-20 1.94035) (5.96675 3.82155e-20 2.03209) (6.24809 1.12823e-20 2.11365) (5.81643 2.50767e-20 2.29018) (9.98063 1.76997e-19 0.116903) (9.98661 4.38386e-20 0.083713) (9.94289 4.19792e-20 0.190277) (9.96322 4.48418e-20 0.163106) (9.88702 -4.52223e-20 0.262158) (9.92102 -4.62564e-20 0.239898) (9.81355 -4.92128e-20 0.334672) (9.8578 7.31814e-22 0.316496) (9.72314 -4.79977e-20 0.409287) (9.77664 -9.85e-24 0.394689) (9.61615 2.63215e-20 0.487077) (9.67945 0 0.475726) (9.49263 2.56763e-20 0.569034) (9.56647 1.38417e-23 0.560654) (9.35247 0 0.65619) (9.4374 0 0.65054) (9.19536 -2.94687e-20 0.749591) (9.29193 2.68574e-20 0.746498) (9.0208 -5.99193e-20 0.850258) (9.12968 8.606e-22 0.849642) (8.82814 -2.99137e-20 0.959151) (8.95011 -2.9543e-20 0.961046) (8.61654 1.54453e-21 1.07713) (8.75248 -4.7986e-22 1.08171) (8.38499 1.74587e-20 1.2049) (8.53587 5.30511e-22 1.21252) (8.13234 1.14273e-20 1.34296) (8.2992 8.17977e-21 1.35418) (7.85728 -4.49074e-21 1.49154) (8.04121 -1.33816e-20 1.50716) (7.55839 0 1.65054) (7.76051 0 1.67164) (7.23411 2.11107e-20 1.81948) (7.45554 1.22118e-20 1.84745) (6.88274 -1.50914e-21 1.99743) (7.12457 7.96019e-22 2.03399) (6.50246 1.58522e-21 2.183) (6.76571 -2.18618e-20 2.23027) (6.0913 -1.72868e-21 2.37428) (6.37688 2.29054e-20 2.43477) (5.95579 -2.40645e-20 2.64541) (9.98087 -8.82891e-20 0.130792) (9.98674 4.26904e-20 0.0928887) (9.94397 -4.4547e-20 0.213499) (9.964 -4.46338e-20 0.181292) (9.88982 2.75411e-22 0.294959) (9.92315 8.96268e-20 0.267315) (9.81892 4.991e-20 0.377254) (9.86219 1.45907e-21 0.353375) (9.73181 4.79732e-20 0.461899) (9.78415 9.653e-20 0.441225) (9.62881 -2.62982e-20 0.5501) (9.69085 -1.56181e-21 0.532217) (9.51003 -2.5654e-20 0.642988) (9.58251 -7.55462e-20 0.627536) (9.37535 2.71878e-20 0.741718) (9.45884 1.67485e-21 0.728375) (9.22449 5.68555e-20 0.847472) (9.31958 -3.00192e-20 0.835974) (9.05698 3.08435e-20 0.961418) (9.16437 2.81545e-20 0.951585) (8.87217 2.36957e-22 1.08467) (8.9927 3.30003e-20 1.07644) (8.66924 -1.48173e-21 1.21826) (8.80386 -4.8298e-22 1.21169) (8.44718 -8.65509e-21 1.36307) (8.59693 -3.30208e-20 1.35841) (8.20481 -1.68933e-20 1.51977) (8.37083 -6.98928e-21 1.51749) (7.9408 -8.72928e-21 1.6888) (8.12429 1.09306e-21 1.6896) (7.6536 1.23654e-20 1.87026) (7.85585 2.34587e-21 1.87512) (7.34151 -8.25364e-21 2.06389) (7.56383 -2.01888e-21 2.07413) (7.00261 -1.98425e-20 2.26902) (7.24635 4.78647e-21 2.28632) (6.63473 0 2.48453) (6.90123 2.01651e-22 2.51098) (6.23543 0 2.70879) (6.52599 -1.11033e-20 2.74695) (6.11778 2.21994e-20 2.99255) (9.98137 8.52603e-20 0.144338) (9.98696 3.14995e-22 0.101823) (9.94563 9.12212e-20 0.235989) (9.96511 3.45145e-22 0.198906) (9.89351 8.96846e-20 0.326568) (9.92594 -1.55496e-21 0.293706) (9.82551 4.92695e-20 0.41819) (9.86756 1.44969e-21 0.388748) (9.7421 4.5772e-20 0.512412) (9.79299 2.13091e-24 0.485787) (9.64359 -5.17261e-20 0.610549) (9.70401 4.90716e-20 0.586248) (9.53011 -4.72605e-20 0.713854) (9.6008 -1.60503e-21 0.691437) (9.40157 -5.591e-20 0.823608) (9.48314 4.96926e-21 0.802667) (9.25772 -5.79911e-20 0.941123) (9.35077 -3.11222e-20 0.921301) (9.09813 3.03595e-20 1.06771) (9.2034 -2.16606e-23 1.04873) (8.92216 3.18598e-20 1.20465) (9.04054 3.17822e-20 1.18632) (8.72904 -3.24203e-20 1.35314) (8.86152 -1.40326e-21 1.33542) (8.51776 -3.10405e-20 1.51424) (8.66548 -5.66435e-22 1.49726) (8.28716 1.1096e-20 1.68885) (8.45134 1.05932e-21 1.67293) (8.03584 1.21852e-20 1.8776) (8.21784 -5.98609e-21 1.86333) (7.76222 -1.20981e-20 2.08085) (7.96349 1.24279e-21 2.06909) (7.46444 1.1115e-20 2.29863) (7.68654 -1.65919e-20 2.29057) (7.14035 2.48068e-20 2.53061) (7.38496 3.88231e-20 2.52781) (6.78747 -1.10426e-20 2.77605) (7.05632 -1.98453e-20 2.78051) (6.40288 1.15005e-20 3.03378) (6.69778 -3.19416e-20 3.048) (6.30593 3.3349e-20 3.32917) (9.98207 -8.45906e-20 0.157415) (9.98725 -8.633e-20 0.110425) (9.94776 -9.24393e-20 0.257602) (9.96648 -8.64087e-20 0.215812) (9.89796 -8.97365e-20 0.356828) (9.92927 -4.66516e-20 0.318927) (9.83317 -4.78167e-20 0.457289) (9.87377 4.65692e-20 0.422451) (9.75384 3.92785e-21 0.560589) (9.803 -4.94139e-20 0.528169) (9.66028 9.8537e-20 0.668132) (9.71873 3.07234e-21 0.637568) (9.55264 5.06847e-20 0.781285) (9.62115 9.81437e-20 0.752056) (9.43086 2.92955e-20 0.901446) (9.51004 3.29409e-21 0.873058) (9.29474 2.72144e-20 1.03005) (9.38521 7.93882e-20 1.00205) (9.14388 1.7917e-21 1.16856) (9.24641 1.78305e-21 1.14056) (8.97773 -1.8848e-21 1.31841) (9.09322 3.00311e-23 1.29011) (8.79552 3.04464e-20 1.48096) (8.92504 2.7943e-20 1.45219) (8.59632 3.15411e-20 1.65748) (8.74105 3.38928e-20 1.62821) (8.37898 -1.61117e-20 1.84907) (8.54025 -3.51119e-20 1.81949) (8.14212 -1.68465e-20 2.05662) (8.3214 2.13952e-21 2.02714) (7.88412 -3.4608e-21 2.28078) (8.08306 -7.377e-23 2.25209) (7.60303 1.1771e-20 2.52191) (7.82344 1.44181e-20 2.49502) (7.29656 -6.53872e-21 2.7801) (7.54043 1.45217e-20 2.75638) (6.96193 -4.09039e-20 3.05515) (7.23147 -2.0078e-20 3.03637) (6.59579 -9.33729e-21 3.34648) (6.89342 -1.0571e-20 3.33497) (6.52239 2.14545e-20 3.65186) (9.9829 -8.81477e-20 0.169922) (9.98758 -3.342e-22 0.118625) (9.95027 -4.01372e-20 0.278206) (9.96806 3.68568e-22 0.231895) (9.90304 9.08035e-20 0.385589) (9.93304 4.49457e-20 0.342846) (9.84176 4.37637e-20 0.494371) (9.88069 1.42235e-21 0.45433) (9.76686 -4.95957e-20 0.606208) (9.81405 -1.47584e-21 0.568181) (9.67868 3.8802e-21 0.722583) (9.73485 -4.90359e-20 0.685945) (9.57737 4.95813e-20 0.844962) (9.64331 -4.65399e-20 0.809113) (9.46293 5.43213e-20 0.974853) (9.53926 -3.20578e-21 0.939214) (9.3352 5.30027e-20 1.11382) (9.42256 2.12083e-23 1.07784) (9.19386 0 1.26344) (9.29302 0 1.22662) (9.03842 3.01964e-20 1.42531) (9.15031 -5.66919e-20 1.38722) (8.86819 3.14612e-20 1.60097) (8.9939 2.93704e-20 1.5613) (8.68231 -3.35948e-20 1.79187) (8.82307 1.96533e-21 1.75045) (8.47971 -1.64236e-20 1.99933) (8.63692 -3.08763e-21 1.95616) (8.25908 1.88806e-20 2.22452) (8.43431 1.80532e-20 2.17982) (8.0188 1.79849e-20 2.46839) (8.21387 -3.26147e-20 2.42262) (7.75696 1.71679e-20 2.7317) (7.97389 -1.32928e-21 2.68562) (7.47117 5.86011e-22 3.01505) (7.7123 -1.82258e-20 2.96972) (7.1585 1.03875e-20 3.31885) (7.42649 1.16684e-21 3.27572) (6.81529 2.06102e-20 3.64333) (7.1132 1.02765e-20 3.60436) (6.76827 5.46038e-21 3.95632) (9.98386 8.81706e-20 0.181774) (9.98796 8.45829e-20 0.126369) (9.95308 8.59904e-20 0.297688) (9.96981 1.72165e-19 0.24706) (9.90866 -4.49603e-20 0.412715) (9.93719 0 0.365344) (9.85115 -4.38318e-20 0.52927) (9.88823 -4.58176e-20 0.484244) (9.78102 -1.51332e-21 0.649068) (9.82598 1.46149e-21 0.605654) (9.69858 -9.93964e-20 0.773657) (9.75219 -5.22033e-20 0.73117) (9.60405 -9.87599e-20 0.904592) (9.66708 5.18432e-21 0.862358) (9.49746 -5.74317e-20 1.04348) (9.57054 -5.3877e-20 1.00084) (9.37874 -5.29492e-20 1.19199) (9.46249 -1.30278e-21 1.14829) (9.24763 -5.73784e-20 1.35184) (9.34283 5.74245e-20 1.30646) (9.10372 -5.64475e-20 1.52475) (9.21132 -3.52533e-21 1.47715) (8.94646 -4.39032e-22 1.71242) (9.06753 -3.34085e-20 1.66214) (8.77508 3.23891e-20 1.9165) (8.91088 -2.98304e-20 1.86319) (8.58863 3.16207e-20 2.13852) (8.74059 6.66213e-20 2.082) (8.38592 -3.40508e-20 2.37992) (8.5557 -2.02028e-21 2.32017) (8.16547 -5.15528e-20 2.64198) (8.35498 1.979e-21 2.5792) (7.92544 -3.69213e-20 2.92589) (8.1369 -1.8088e-20 2.86049) (7.66354 -1.74272e-20 3.23277) (7.89955 -3.5687e-20 3.16544) (7.37683 1.15406e-21 3.56377) (7.64047 1.16791e-21 3.49548) (7.06159 -4.96324e-21 3.9201) (7.35651 0 3.85221) (7.04353 -3.96969e-23 4.23747) (9.9849 1.69646e-19 0.192904) (9.98838 6.22792e-22 0.133613) (9.95615 8.39988e-20 0.315949) (9.9717 8.43175e-20 0.261228) (9.91473 -1.43715e-21 0.438084) (9.94164 8.56759e-20 0.386317) (9.86125 6.35971e-23 0.561842) (9.89629 8.92728e-20 0.512068) (9.79615 -4.98915e-20 0.688991) (9.83867 1.44961e-21 0.640435) (9.7198 5.30534e-20 0.821139) (9.77057 -5.97569e-21 0.77306) (9.63243 4.93029e-20 0.959916) (9.69223 5.26829e-20 0.91157) (9.53417 2.89038e-21 1.10702) (9.60358 3.1333e-21 1.05766) (9.42498 1.09769e-19 1.2642) (9.50464 5.15782e-20 1.21309) (9.30472 1.10484e-19 1.43331) (9.3954 5.66172e-20 1.37972) (9.1731 1.91296e-20 1.61617) (9.2757 5.65864e-20 1.55942) (9.02967 -6.27353e-20 1.81464) (9.14528 -3.64855e-20 1.75413) (8.87385 5.56142e-21 2.03054) (9.0037 -7.46634e-23 1.96574) (8.70483 3.21592e-20 2.2656) (8.85036 6.40411e-20 2.19613) (8.52163 3.40228e-20 2.52151) (8.6845 -2.01997e-21 2.4471) (8.32297 3.51793e-20 2.79988) (8.50515 3.15393e-20 2.72041) (8.10724 -1.70801e-20 3.1023) (8.31105 4.13068e-21 3.01781) (7.87239 -1.6688e-20 3.43047) (8.10061 -1.57986e-20 3.34115) (7.61575 0 3.78628) (7.87174 3.87477e-20 3.69249) (7.33378 4.9217e-21 4.17199) (7.62169 3.06013e-20 4.07429) (7.34676 4.86927e-21 4.48964) (9.98601 -8.3629e-20 0.203256) (9.98882 -7.75906e-22 0.140321) (9.95942 8.60321e-20 0.332902) (9.9737 -2.17701e-21 0.274332) (9.92118 1.76413e-19 0.461588) (9.94632 -4.71985e-23 0.405678) (9.87192 8.95488e-20 0.591953) (9.90474 -1.92271e-23 0.537695) (9.8121 4.52455e-20 0.725819) (9.85196 0 0.672395) (9.74212 -5.60658e-21 0.864843) (9.78977 8.83881e-20 0.811458) (9.66226 5.9028e-21 1.01072) (9.71846 -9.40952e-20 0.956561) (9.57269 5.24139e-20 1.1652) (9.63803 5.68776e-20 1.10945) (9.47349 -1.44746e-21 1.33015) (9.54857 -4.59846e-21 1.27198) (9.36462 2.76253e-21 1.50748) (9.45017 -5.06171e-20 1.44605) (9.2459 -1.53388e-22 1.69913) (9.34282 9.49528e-23 1.63365) (9.11707 2.65794e-20 1.90709) (9.22638 -5.55314e-20 1.8368) (8.97771 5.9169e-20 2.13331) (9.1006 2.61311e-20 2.05751) (8.82724 2.90964e-20 2.3797) (8.96511 2.81024e-20 2.2978) (8.66492 -4.10395e-21 2.64818) (8.81942 0 2.55964) (8.48981 1.6429e-22 2.94061) (8.66285 3.82182e-21 2.84501) (8.30063 5.13034e-21 3.25899) (8.49455 -1.19621e-20 3.15594) (8.09578 4.02219e-20 3.6055) (8.31338 -2.20423e-20 3.49465) (7.87309 6.92784e-20 3.98277) (8.11783 4.43441e-21 3.86375) (7.62966 3.02673e-20 4.39406) (7.90591 -1.2949e-20 4.26646) (7.67486 2.59635e-20 4.70698) (9.98718 8.06622e-20 0.212788) (9.96283 -8.81699e-20 0.348488) (9.9279 -1.764e-19 0.483145) (9.95122 -6.58676e-21 0.423364) (9.88301 -8.95261e-20 0.619497) (9.91357 -9.10548e-20 0.561047) (9.82865 4.42438e-20 0.75941) (9.86582 0 0.701439) (9.76525 -2.36374e-21 0.904581) (9.80976 -2.35324e-21 0.846248) (9.69315 -4.12502e-20 1.05675) (9.74575 2.38079e-21 0.99719) (9.61258 -8.56458e-22 1.21773) (9.67385 3.17751e-21 1.15606) (9.52373 -5.42686e-20 1.38945) (9.59423 -5.20367e-20 1.32474) (9.42666 -5.26267e-20 1.57388) (9.50709 -4.45746e-20 1.50522) (9.32136 -5.59471e-20 1.77307) (9.41257 4.03245e-20 1.69953) (9.20772 -5.49769e-20 1.98907) (9.31069 -5.18847e-20 1.90976) (9.08556 -4.84545e-21 2.22396) (9.20143 -4.98017e-20 2.13802) (8.95455 -1.26985e-21 2.47978) (9.08466 -1.11086e-19 2.38641) (8.81428 7.96914e-21 2.7586) (8.96018 -7.017e-21 2.65702) (8.66417 -8.47933e-21 3.06252) (8.82772 8.01963e-21 2.95197) (8.50345 -3.93236e-20 3.3938) (8.68688 -1.63821e-20 3.27349) (8.33111 -5.74934e-20 3.75505) (8.53713 1.04506e-19 3.62407) (8.14577 -7.77921e-20 4.14943) (8.37774 -5.77841e-20 4.00667) (7.94555 -1.67535e-20 4.58105) (8.20775 3.19276e-20 4.42503) (8.02582 2.64153e-20 4.88415) (9.93509 8.25304e-20 0.503054) (9.89486 1.30502e-21 0.644885) (9.92303 -8.15955e-20 0.582777) (9.84631 -4.83311e-20 0.790299) (9.88064 2.59942e-21 0.728374) (9.78989 2.53639e-21 0.94102) (9.83112 -4.82839e-20 0.878392) (9.72601 4.8466e-20 1.09882) (9.77487 4.69239e-20 1.03457) (9.65499 -4.95581e-20 1.26556) (9.71202 5.0229e-20 1.19872) (9.5771 -4.20009e-20 1.44319) (9.64285 -5.52815e-20 1.37278) (9.49256 5.13426e-20 1.63376) (9.56768 6.35169e-21 1.55874) (9.40151 4.50948e-20 1.83934) (9.48679 -4.12277e-21 1.7587) (9.30407 -4.65618e-20 2.06206) (9.40042 5.16521e-20 1.97477) (9.20027 -1.59561e-19 2.30407) (9.30875 4.42872e-21 2.20911) (9.09011 -1.17662e-19 2.56748) (9.21195 -5.31154e-20 2.46386) (8.97354 -7.06301e-21 2.85446) (9.11017 -1.39522e-20 2.74115) (8.85045 0 3.16724) (9.00357 0 3.04319) (8.72067 1.3183e-19 3.50825) (8.8923 -1.40266e-20 3.37227) (8.58393 1.05188e-19 3.88031) (8.77653 3.18191e-20 3.73098) (8.43989 5.52682e-20 4.28691) (8.65646 -2.36116e-20 4.12239) (8.28806 7.66539e-20 4.73263) (8.53238 -3.82557e-20 4.55045) (8.40472 -5.67518e-20 5.02034) (9.90724 -8.02111e-20 0.668022) (9.86474 2.61452e-21 0.818312) (9.89604 8.21709e-20 0.752525) (9.81559 -2.77652e-21 0.973889) (9.85328 1.5096e-23 0.907074) (9.76026 4.87299e-20 1.13654) (9.80504 -2.79009e-21 1.06773) (9.69915 4.43125e-20 1.30815) (9.75154 5.6134e-20 1.23633) (9.63265 -5.74899e-21 1.49069) (9.69314 -1.14171e-20 1.4148) (9.56111 -5.03937e-20 1.68622) (9.63029 4.50852e-20 1.60516) (9.48486 2.61132e-21 1.89685) (9.56343 -5.03638e-20 1.80949) (9.40422 1.03745e-19 2.12473) (9.49299 5.17615e-20 2.02993) (9.3195 1.13264e-19 2.37201) (9.41939 4.70288e-20 2.26861) (9.23103 5.30139e-20 2.64083) (9.34311 7.38249e-20 2.52767) (9.13916 -6.71898e-21 2.93338) (9.26466 -6.36743e-20 2.80922) (9.04428 -1.43553e-20 3.25188) (9.18464 5.12753e-20 3.11542) (8.94687 -1.16227e-19 3.59878) (9.10377 -1.43448e-20 3.44849) (8.84752 -9.97769e-20 3.9769) (9.02296 -9.98189e-20 3.81093) (8.747 -1.19081e-19 4.38971) (8.94335 1.34156e-20 4.20566) (8.6464 -1.74346e-19 4.84172) (8.8665 -2.39854e-20 4.63634) (8.79459 -2.17258e-21 5.10776) (9.8839 7.94546e-20 0.843097) (9.84227 0 1.00281) (9.87619 -4.95076e-21 0.931958) (9.79576 4.85367e-21 1.16951) (9.8362 5.0548e-21 1.09629) (9.74487 -9.22546e-22 1.34507) (9.79229 4.53209e-20 1.26842) (9.69008 4.06503e-20 1.53148) (9.74492 -5.65931e-21 1.45028) (9.6319 4.50587e-20 1.73078) (9.69467 7.54261e-21 1.64386) (9.57082 0 1.94506) (9.64213 -5.57176e-21 1.85121) (9.5074 -6.28145e-21 2.17645) (9.58791 -5.71663e-21 2.07444) (9.4422 6.67629e-21 2.42706) (9.53269 -4.65363e-20 2.31561) (9.37589 -4.56109e-20 2.69899) (9.47721 9.10395e-22 2.5768) (9.30922 -4.27889e-21 2.99433) (9.42236 3.32736e-21 2.86002) (9.24311 5.12398e-20 3.31521) (9.36916 2.27845e-21 3.16725) (9.17867 2.18062e-21 3.66389) (9.31888 4.89402e-20 3.50054) (9.11732 1.58514e-20 4.04295) (9.27308 5.36297e-20 3.86208) (9.06091 1.10379e-19 4.45549) (9.23378 1.37047e-20 4.25436) (9.01197 1.51344e-19 4.90542) (9.20361 -4.13393e-21 4.68039) (9.18617 8.2353e-21 5.14394) (9.86969 2.28196e-22 1.02733) (9.83221 4.65314e-20 1.19718) (9.86804 5.17453e-21 1.11987) (9.79174 4.04682e-20 1.37571) (9.83389 -1.18121e-19 1.29458) (9.74889 -3.95052e-20 1.56485) (9.79771 5.10879e-21 1.47874) (9.70427 -4.4246e-20 1.76661) (9.7602 -4.46915e-20 1.6743) (9.65858 -1.14221e-20 1.98304) (9.72209 -5.70208e-21 1.88326) (9.61255 -4.6946e-20 2.21618) (9.68418 -5.84976e-21 2.10762) (9.56702 -5.2417e-20 2.46807) (9.64736 -7.22335e-21 2.34938) (9.52297 5.08886e-20 2.74068) (9.61264 -5.67119e-20 2.61045) (9.48152 1.00519e-20 3.03591) (9.58122 8.57069e-20 2.89266) (9.44406 3.81907e-23 3.35566) (9.5545 -6.28762e-20 3.19777) (9.41227 1.01426e-19 3.70189) (9.53421 1.3775e-20 3.52749) (9.38826 5.12856e-20 4.07669) (9.52245 4.06139e-20 3.88354) (9.37479 -1.02999e-19 4.48249) (9.52191 0 4.26779) (9.37544 -1.4999e-19 4.92219) (9.53598 -1.00232e-19 4.68233) (9.56912 -2.43413e-20 5.12961) (9.86926 -1.63404e-19 1.2192) (9.83932 -1.54183e-19 1.39964) (9.87594 -8.5998e-20 1.31442) (9.80848 -2.26326e-22 1.59032) (9.85098 1.01204e-20 1.49976) (9.77749 -5.20975e-21 1.79319) (9.8262 2.91971e-20 1.69602) (9.74717 0 2.0102) (9.80247 0 1.90513) (9.71847 3.47346e-20 2.2433) (9.78072 0 2.12897) (9.69245 -1.17262e-20 2.49436) (9.76204 3.47077e-20 2.36937) (9.67034 -2.10508e-20 2.76517) (9.74767 -3.35319e-20 2.62807) (9.65361 1.10321e-20 3.05738) (9.73905 1.25709e-20 2.90665) (9.64399 -4.86724e-20 3.37256) (9.73789 -1.19199e-20 3.20657) (9.64363 -4.82143e-20 3.71222) (9.74626 -3.69853e-20 3.52909) (9.65515 -1.18419e-20 4.07783) (9.76663 -1.21174e-20 3.87541) (9.68186 2.54113e-21 4.47096) (9.80209 0 4.24663) (9.72798 2.79388e-20 4.89331) (9.85643 4.92724e-21 4.64383) (9.93444 6.65277e-20 5.06808) (9.88714 8.2196e-20 1.41651) (9.86825 4.02628e-20 1.60752) (9.85075 3.45079e-20 1.81012) (9.89197 -1.28592e-20 1.70869) (9.8356 0 2.02615) (9.88234 0 1.91648) (9.82389 0 2.2574) (9.87638 0 2.13813) (9.81688 1.22652e-20 2.50555) (9.8753 -1.00043e-20 2.37528) (9.816 8.53071e-22 2.77215) (9.88051 6.37956e-20 2.62944) (9.82296 -1.08832e-20 3.05856) (9.89364 -1.11411e-20 2.90191) (9.83976 0 3.36593) (9.9166 0 3.19377) (9.86882 0 3.69525) (9.95165 -4.05882e-20 3.50585) (9.91306 0 4.04733) (10.0015 0 3.83872) (9.97602 2.37923e-21 4.42281) (10.0693 3.99145e-20 4.19273) (10.0621 4.43824e-20 4.82221) (10.1589 6.32995e-20 4.56797) (10.2751 7.01753e-22 4.96428) (9.92324 -4.81351e-20 1.81711) (9.92283 0 2.03061) (9.96082 -9.29147e-21 1.91712) (9.92753 -1.02435e-20 2.25826) (9.97003 0 2.13497) (9.93871 4.27018e-20 2.50152) (9.98573 2.73544e-20 2.36707) (9.95797 5.14527e-20 2.76166) (10.0094 5.26789e-20 2.61467) (9.98715 0 3.0397) (10.0429 -9.62319e-21 2.87876) (10.0284 -4.15427e-20 3.33638) (10.0881 9.80704e-21 3.16003) (10.0842 -4.05359e-20 3.65213) (10.1473 -1.76693e-21 3.45885) (10.1577 4.08446e-20 3.98709) (10.2233 0 3.77522) (10.2522 1.02153e-19 4.34107) (10.3192 1.71704e-21 4.10879) (10.372 1.87033e-20 4.71352) (10.4387 2.58874e-20 4.45879) (10.586 -2.46899e-20 4.82402) (10.0078 -9.28398e-21 2.02351) (10.0281 3.84884e-20 2.2459) (10.0564 3.75552e-20 2.48243) (10.092 1.68099e-21 2.34494) (10.0944 -9.85189e-21 2.73407) (10.1328 -3.59129e-20 2.58415) (10.1439 3.89337e-22 3.0015) (10.1848 -9.84198e-21 2.83787) (10.2072 5.04261e-20 3.28503) (10.25 1.00284e-20 3.10642) (10.2867 3.96418e-20 3.58459) (10.3306 2.2592e-20 3.38973) (10.3854 -3.99651e-20 3.89972) (10.4292 3.5952e-20 3.68729) (10.5064 -7.61506e-20 4.22949) (10.5487 -4.46376e-21 3.99815) (10.6536 -1.83887e-20 4.5725) (10.6924 -2.44972e-21 4.32085) (10.8639 -3.17793e-20 4.65343) (10.1685 -7.3483e-20 2.44872) (10.2235 -3.58773e-20 2.69009) (10.2913 0 2.94503) (10.3178 0 2.78026) (10.3739 -1.84166e-20 3.21346) (10.4005 3.39136e-20 3.03439) (10.4738 1.8753e-20 3.49487) (10.4994 -1.83953e-20 3.3005) (10.5935 7.20943e-20 3.78828) (10.6169 2.15665e-21 3.57767) (10.7359 7.09833e-20 4.0922) (10.7554 3.81309e-21 3.86446) (10.9042 -1.60612e-20 4.40462) (10.9178 5.12537e-20 4.15892) (11.107 2.70818e-20 4.45857) (10.4276 3.47215e-20 2.87167) (10.5268 3.38745e-20 3.12356) (10.5381 -1.496e-20 2.94568) (10.6435 -3.54269e-20 3.3855) (10.6522 -1.58365e-20 3.19346) (10.7801 -6.7749e-20 3.65612) (10.7848 -3.69365e-21 3.44932) (10.939 -1.61934e-20 3.93352) (10.938 -7.41213e-22 3.71148) (11.1227 9.54094e-20 4.21528) (11.1141 -1.39542e-20 3.9777) (11.3152 4.91914e-20 4.24517) (10.6645 -6.58016e-20 3.01747) (10.7948 1.65702e-20 3.25921) (10.9443 6.48053e-20 3.50665) (10.9322 1.71903e-20 3.30527) (11.1151 1.45169e-21 3.75764) (11.096 7.57513e-20 3.54295) (11.3091 -6.12771e-20 4.00955) (11.2812 -1.65881e-20 3.78163) (11.4893 -3.11767e-20 4.01844) (11.0858 2.83639e-20 3.34321) (11.2644 5.72351e-20 3.56853) (11.4641 1.43021e-20 3.79202) (11.4201 -2.46291e-20 3.57478) (11.6309 1.20871e-20 3.78294) (11.5896 -2.68574e-20 3.56675) ) ; boundaryField { inlet { type calculated; value uniform (10 0 0); } outlet { type calculated; value nonuniform 0(); } flap { type calculated; value nonuniform 0(); } upperWall { type calculated; value nonuniform 0(); } lowerWall { type calculated; value uniform (0 0 0); } frontAndBack { type empty; value nonuniform 0(); } procBoundary3to0 { type processor; value nonuniform List<vector> 34 ( (9.98928 1.61918e-19 0.146471) (9.97579 7.9419e-20 0.286328) (9.96649 1.64672e-19 0.362905) (9.95648 1.60063e-19 0.439871) (9.94262 -8.14459e-21 0.521278) (9.93288 -1.63417e-19 0.602343) (9.92014 2.98914e-21 0.688588) (9.91198 1.59027e-19 0.773614) (9.90362 7.25318e-20 0.864287) (9.89964 -5.06833e-21 0.952732) (9.89761 0 1.04713) (9.90029 6.95384e-20 1.13815) (9.90658 1.48608e-19 1.23525) (9.91803 1.47173e-19 1.32765) (9.90419 -4.35375e-21 1.51301) (9.92755 -5.86717e-20 1.61615) (9.95679 -1.30558e-19 1.71207) (9.99415 -9.0694e-20 1.81403) (10.037 2.54152e-20 1.907) (10.0606 0 2.11955) (10.1245 -3.76266e-20 2.22057) (10.1928 -2.90648e-20 2.30932) (10.2492 -4.65258e-20 2.53857) (10.3439 -9.79999e-21 2.63071) (10.4404 1.60006e-20 2.70722) (10.5517 -3.47908e-20 2.78307) (10.6617 -8.24917e-20 2.84219) (10.7879 -1.6716e-20 3.07103) (10.9269 -1.61805e-20 3.11874) (11.0589 -1.32143e-21 3.1485) (11.2297 5.81722e-20 3.36236) (11.3878 -2.56242e-20 3.36982) (11.5321 -7.74314e-20 3.36076) (11.7423 2.47744e-20 3.54256) ) ; } procBoundary3to1 { type processor; value nonuniform List<vector> 9((9.79892 4.84768e-20 5.34671) (10.1767 5.54452e-22 5.2458) (10.5221 -1.98159e-20 5.10344) (10.8312 3.57262e-20 4.9268) (11.1019 -4.95201e-20 4.72293) (11.3339 4.85215e-20 4.49843) (11.528 -1.45075e-20 4.25926) (11.6861 2.76692e-20 4.01059) (11.8108 1.28188e-20 3.75682)); } procBoundary3to4 { type processor; value nonuniform List<vector> 19 ( (4.04475 2.04083e-20 0.222843) (4.77975 -7.02909e-21 0.604264) (5.09275 1.27494e-20 1.01945) (5.26512 -2.50995e-20 1.41854) (5.39229 -1.26603e-19 1.80828) (5.51366 4.84312e-20 2.19142) (5.64721 -2.32672e-20 2.5687) (5.802 -2.41672e-20 2.93954) (5.98318 9.37422e-20 3.30202) (6.19409 -1.12715e-20 3.65309) (6.43696 5.4557e-20 3.98852) (6.71292 5.0803e-21 4.30303) (7.02177 -1.53513e-20 4.59034) (7.36149 -9.33394e-21 4.84361) (7.72783 4.34737e-20 5.05538) (8.1278 0 5.22362) (8.54729 -5.66769e-20 5.33896) (8.97403 2.87827e-20 5.39779) (9.39508 -5.44932e-23 5.39931) ) ; } } // ************************************************************************* //
9dcdaa9047dc724cdad821bc2cec95eef577ed57
c23fd2dff69156dfe255590662ab6101911decc5
/LuminRuntime/UiKit/UiLoadingSpinnersExample/code/src/prefabs/LoadingSpinners.cpp
8858234237f98569b91d4e5f9c7dce199046db4b
[]
no_license
snowymo/MagicLeapSamples
4db6b6a78940c6d23e81b14d1e7d5e166e0672e1
c86a635c29de0103cf0aa6a4aa9a02ebb75ad829
refs/heads/master
2023-01-08T15:30:39.176625
2020-11-04T05:35:18
2020-11-04T05:35:18
309,896,822
3
0
null
null
null
null
UTF-8
C++
false
false
812
cpp
// %BANNER_BEGIN% // --------------------------------------------------------------------- // %COPYRIGHT_BEGIN% // // Copyright (c) 2018 Magic Leap, Inc. All Rights Reserved. // Use of this file is governed by the Creator Agreement, located // here: https://id.magicleap.com/creator-terms // // %COPYRIGHT_END% // --------------------------------------------------------------------- // %BANNER_END% // %SRC_VERSION%: 2 #include <PrefabDescriptor.h> #include <LoadingSpinners.h> namespace prefabs { LoadingSpinners::LoadingSpinners(ExtendedPrefabManager* extendedPrefabManager, lumin::Node* root) : LoadingSpinnersBase(extendedPrefabManager, root) { } LoadingSpinners::~LoadingSpinners() { } // Handler methods are declared in the base class LoadingSpinnersBase and can be implemented here }
6fae10e3f3a17082ec01b1e26e603aa60008dcd7
9f513f7fdd869c049f38b933da5d1f6fe90c276d
/Pixonia/splatter.cpp
8f1b0cc3889036efe588ad22d0a61071722ab36a
[]
no_license
pokitto/Examples
917f0f2992d49e11b830ffee030a8c7b690229e6
e776d310ac633fda39673e180aba1e0246d0a906
refs/heads/master
2021-04-02T13:54:00.357007
2020-04-14T11:40:48
2020-04-14T11:40:48
248,282,517
1
0
null
null
null
null
UTF-8
C++
false
false
267
cpp
/* * BMP image as 4bpp (16 colour index) data */ #include <stdint.h> #include "Pixonia.h" const uint8_t splatter[] = { 8,8, 255,255,255,255,255,239,255,255, 255,255,255,255,255,255,239,255, 255,255,255,255,255,255,255,254, 255,239,255,255,255,255,255,255, };
b2f982cc7596a399e3aa04c72695e5e8f7294caf
07e75d02db3121c191073f6d8220ff1a382708f6
/SRC/Asteroids.cpp
a2a35f3bdb3cf84f93c1dbb590623f527029b158
[]
no_license
AumPatel2208/Asteroids_OpenGL
06e3f3cc46824224d2ac0627276579bbb6017102
3d7dab5fa64508b16ead5f7026e06b52b5a2450e
refs/heads/master
2023-04-09T02:31:28.504558
2021-04-12T20:44:35
2021-04-12T20:44:35
249,833,193
0
0
null
null
null
null
UTF-8
C++
false
false
17,858
cpp
#include "Asteroid.h" #include "Asteroids.h" #include "Animation.h" #include "AnimationManager.h" #include "GameUtil.h" #include "GameWindow.h" #include "GameWorld.h" #include "GameDisplay.h" #include "Spaceship.h" #include "AlienSpaceship.h" #include "BoundingShape.h" #include "BoundingSphere.h" #include "GUILabel.h" #include "Explosion.h" #include "BulletPowerUp.h" #include "CircleBulletPowerUp.h" #include "OnePowerUp.h" // PUBLIC INSTANCE CONSTRUCTORS /////////////////////////////////////////////// /** Constructor. Takes arguments from command line, just in case. */ Asteroids::Asteroids(int argc, char* argv[]) : GameSession(argc, argv) { mLevel = 0; mAsteroidCount = 0; } /** Destructor. */ Asteroids::~Asteroids(void) { } // PUBLIC INSTANCE METHODS //////////////////////////////////////////////////// /** Start an asteroids game. */ void Asteroids::Start() { /* Made global line below*/ // Create a shared pointer for the Asteroids game object - DO NOT REMOVE //shared_ptr<Asteroids> thisPtr = shared_ptr<Asteroids>(this); thisPtr = shared_ptr<Asteroids>(this); // Add this class as a listener of the game world mGameWorld->AddListener(thisPtr.get()); // Add this as a listener to the world and the keyboard mGameWindow->AddKeyboardListener(thisPtr); /*Add code for Start Menu*/ // Add a score keeper to the game world mGameWorld->AddListener(&mScoreKeeper); // Add this class as a listener of the score keeper mScoreKeeper.AddListener(thisPtr); // Create an ambient light to show sprite textures GLfloat ambient_light[] = {1.0f, 1.0f, 1.0f, 1.0f}; GLfloat diffuse_light[] = {1.0f, 1.0f, 1.0f, 1.0f}; glLightfv(GL_LIGHT0, GL_AMBIENT, ambient_light); glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse_light); glEnable(GL_LIGHT0); Animation* explosion_anim = AnimationManager::GetInstance().CreateAnimationFromFile( "explosion", 64, 1024, 64, 64, "explosion_fs.png"); Animation* blue_explosion_anim = AnimationManager::GetInstance().CreateAnimationFromFile( "blueExplosion", 64, 1024, 64, 64, "explosionBlue_fs.png"); Animation* asteroid1_anim = AnimationManager::GetInstance().CreateAnimationFromFile( "asteroid1", 128, 8192, 128, 128, "asteroid1_fs.png"); Animation* spaceship_anim = AnimationManager::GetInstance().CreateAnimationFromFile( "spaceship", 128, 128, 128, 128, "spaceship_fs.png"); Animation* alien_spaceship_anim = AnimationManager::GetInstance().CreateAnimationFromFile( "alienSpaceship", 128, 128, 128, 128, "alien_spaceship_fs.png"); CreateMenu(); // Start the game GameSession::Start(); } /** Stop the current game. */ void Asteroids::Stop() { // Stop the game GameSession::Stop(); } // PUBLIC INSTANCE METHODS IMPLEMENTING IKeyboardListener ///////////////////// void Asteroids::OnKeyPressed(uchar key, int x, int y) { switch (key) { case ' ': if (isGameRunning) mSpaceship->Shoot(); break; case '1': if (!isGameRunning) { // Create a spaceship and add it to the world mGameWorld->AddObject(CreateSpaceship()); // Create an alienspaceship and add it to the world mGameWorld->AddObject(CreateAlienSpaceship()); isAlienAlive=true; SetTimer(500, UPDATE_ALIEN_SHIP); SetTimer(2000, SHOOT_ALIEN_SHIP); // Create some asteroids and add them to the world CreateAsteroids(1); CreateBulletPowerUps(1); CreateOnePowerUps(1); CreateCircleBulletPowerUps(1); //Hiding menu aGameTitle->SetVisible(false); aStartGameOption->SetVisible(false); aExitGameOption->SetVisible(false); aInstructions->SetVisible(false); //Create the GUI CreateGUI(); // Add a player (watcher) to the game world mGameWorld->AddListener(&mPlayer); // Add this class as a listener of the player mPlayer.AddListener(thisPtr); isGameRunning = true; } break; case '2': Stop(); default: break; } } void Asteroids::OnKeyReleased(uchar key, int x, int y) { } void Asteroids::OnSpecialKeyPressed(int key, int x, int y) { switch (key) { // If up arrow key is pressed start applying forward thrust case GLUT_KEY_UP: if (isGameRunning)mSpaceship->Thrust(10); break; // If left arrow key is pressed start rotating anti-clockwise case GLUT_KEY_LEFT: if (isGameRunning) mSpaceship->Rotate(90); break; // If right arrow key is pressed start rotating clockwise case GLUT_KEY_RIGHT: if (isGameRunning) mSpaceship->Rotate(-90); break; // Default case - do nothing default: break; } } void Asteroids::OnSpecialKeyReleased(int key, int x, int y) { switch (key) { // If up arrow key is released stop applying forward thrust case GLUT_KEY_UP: if (isGameRunning)mSpaceship->Thrust(0); break; // If left arrow key is released stop rotating case GLUT_KEY_LEFT: if (isGameRunning) mSpaceship->Rotate(0); break; // If right arrow key is released stop rotating case GLUT_KEY_RIGHT: if (isGameRunning)mSpaceship->Rotate(0); break; // Default case - do nothing default: break; } } // PUBLIC INSTANCE METHODS IMPLEMENTING IGameWorldListener //////////////////// void Asteroids::OnObjectRemoved(GameWorld* world, shared_ptr<GameObject> object) { if (object->GetType() == GameObjectType("Asteroid")) { shared_ptr<GameObject> explosion = CreateExplosion(EXPLOSION_ASTEROID); explosion->SetPosition(object->GetPosition()); explosion->SetRotation(object->GetRotation()); mGameWorld->AddObject(explosion); mAsteroidCount--; if (mAsteroidCount <= 0) { SetTimer(500, START_NEXT_LEVEL); } } else if (object->GetType() == GameObjectType("AlienSpaceship")) { shared_ptr<GameObject> explosion = CreateExplosion(EXPLOSION_SPACESHIP); explosion->SetPosition(object->GetPosition()); explosion->SetRotation(object->GetRotation()); explosion->SetScale(0.5f); mGameWorld->AddObject(explosion); isAlienAlive=false; } else if (object->GetType() == GameObjectType("BulletPowerUp")) { mSpaceship->toggleSuperShot(); bulletPowerTime = 10; SetTimer(10000, RESET_BULLET_POWER_UP); SetTimer(10, INCREASE_POWER_UP_COUNTER); } else if (object->GetType() == GameObjectType("OnePowerUp")) { mPlayer.addLives(1); std::ostringstream msg_stream; msg_stream << "Lives: " << mPlayer.getLives(); // Get the lives left message as a string std::string lives_msg = msg_stream.str(); mLivesLabel->SetText(lives_msg); } else if (object->GetType() == GameObjectType("CircleBulletPowerUp")) { mSpaceship->toggleUltraShoot(); bulletPowerTime = 10; SetTimer(10000, RESET_CIRCLE_BULLET_POWER_UP); SetTimer(10, INCREASE_POWER_UP_COUNTER); } } // PUBLIC INSTANCE METHODS IMPLEMENTING ITimerListener //////////////////////// void Asteroids::OnTimer(int value) { if (value == CREATE_NEW_PLAYER) { mSpaceship->Reset(); mGameWorld->AddObject(mSpaceship); } if (value == START_NEXT_LEVEL) { mLevel++; const int num_asteroids = 1 + 2 * mLevel; CreateOnePowerUps(1); CreateBulletPowerUps(1); if(mLevel%2==0) CreateCircleBulletPowerUps(1); CreateAsteroids(num_asteroids); if(!isAlienAlive){ mAlienSpaceship->SetRandomPosition(); mAlienSpaceship->SetVelocity(GLVector3f(0,0,0)); mGameWorld->AddObject(mAlienSpaceship); isAlienAlive=true;} } if (value == SHOW_GAME_OVER) { mGameOverLabel->SetVisible(true); } if (value == RESET_BULLET_POWER_UP) { mSpaceship->toggleSuperShot(); } if (value == INCREASE_POWER_UP_COUNTER) { bulletPowerTime -= 1; std::ostringstream msg_stream; msg_stream << "Bullet Time: " << bulletPowerTime + 1; std::string bullet_msg = msg_stream.str(); aBulletPowerTime->SetText(bullet_msg); if (bulletPowerTime >= 0) { SetTimer(1000, INCREASE_POWER_UP_COUNTER); } } if (value == RESET_CIRCLE_BULLET_POWER_UP) { mSpaceship->toggleUltraShoot(); } if (value == UPDATE_ALIEN_SHIP) { if (isAlienAlive){ mAlienSpaceship->Thrust(5, mSpaceship->GetPosition()); } SetTimer(100, UPDATE_ALIEN_SHIP); } if (value == SHOOT_ALIEN_SHIP) { if(isAlienAlive){ mAlienSpaceship->Shoot(mSpaceship->GetPosition()); } SetTimer(2500, SHOOT_ALIEN_SHIP); } } // PROTECTED INSTANCE METHODS ///////////////////////////////////////////////// shared_ptr<GameObject> Asteroids::CreateSpaceship() { // Create a raw pointer to a spaceship that can be converted to // shared_ptrs of different types because GameWorld implements IRefCount mSpaceship = make_shared<Spaceship>(); mSpaceship->SetBoundingShape(make_shared<BoundingSphere>(mSpaceship->GetThisPtr(), 4.0f)); shared_ptr<Shape> bullet_shape = make_shared<Shape>("bullet.shape"); mSpaceship->SetBulletShape(bullet_shape); Animation* anim_ptr = AnimationManager::GetInstance().GetAnimationByName("spaceship"); shared_ptr<Sprite> spaceship_sprite = make_shared<Sprite>(anim_ptr->GetWidth(), anim_ptr->GetHeight(), anim_ptr); mSpaceship->SetSprite(spaceship_sprite); mSpaceship->SetScale(0.1f); // Reset spaceship back to centre of the world mSpaceship->Reset(); // Return the spaceship so it can be added to the world return mSpaceship; } shared_ptr<GameObject> Asteroids::CreateAlienSpaceship() { // Create a raw pointer to a spaceship that can be converted to // shared_ptrs of different types because GameWorld implements IRefCount mAlienSpaceship = make_shared<AlienSpaceship>(); mAlienSpaceship->SetBoundingShape(make_shared<BoundingSphere>(mAlienSpaceship->GetThisPtr(), 4.0f)); shared_ptr<Shape> bullet_shape = make_shared<Shape>("bullet_alien.shape"); mAlienSpaceship->SetBulletShape(bullet_shape); Animation* anim_ptr = AnimationManager::GetInstance().GetAnimationByName("alienSpaceship"); shared_ptr<Sprite> spaceship_sprite = make_shared<Sprite>(anim_ptr->GetWidth(), anim_ptr->GetHeight(), anim_ptr); mAlienSpaceship->SetSprite(spaceship_sprite); mAlienSpaceship->SetAngle(180); mAlienSpaceship->SetScale(0.1f); // Return the spaceship so it can be added to the world return mAlienSpaceship; } void Asteroids::CreateAsteroids(const uint num_asteroids) { mAsteroidCount = num_asteroids; for (uint i = 0; i < num_asteroids; i++) { Animation* anim_ptr = AnimationManager::GetInstance().GetAnimationByName("asteroid1"); shared_ptr<Sprite> asteroid_sprite = make_shared<Sprite>(anim_ptr->GetWidth(), anim_ptr->GetHeight(), anim_ptr); asteroid_sprite->SetLoopAnimation(true); shared_ptr<GameObject> asteroid = make_shared<Asteroid>(); asteroid->SetBoundingShape(make_shared<BoundingSphere>(asteroid->GetThisPtr(), 10.0f)); asteroid->SetSprite(asteroid_sprite); asteroid->SetScale(0.2f); mGameWorld->AddObject(asteroid); } } void Asteroids::CreateBulletPowerUps(const uint num_powerUps) { for (uint i = 0; i < num_powerUps; i++) { shared_ptr<GameObject> powerUp = make_shared<BulletPowerUp>(); Animation* anim_ptr = AnimationManager::GetInstance().CreateAnimationFromFile( "bulletPowerUp", 160, 160, 160, 160, "bulletPowerUp.png"); shared_ptr<Sprite> spaceship_sprite = make_shared<Sprite>(anim_ptr->GetWidth(), anim_ptr->GetHeight(), anim_ptr); powerUp->SetSprite(spaceship_sprite); powerUp->SetBoundingShape(make_shared<BoundingSphere>(powerUp->GetThisPtr(), 4.00f)); powerUp->SetScale(0.05f); mGameWorld->AddObject(powerUp); } } void Asteroids::CreateOnePowerUps(const uint num_powerUps) { for (uint i = 0; i < num_powerUps; i++) { shared_ptr<GameObject> powerUp = make_shared<OnePowerUp>(); Animation* anim_ptr = AnimationManager::GetInstance().CreateAnimationFromFile( "onePowerUp", 160, 160, 160, 160, "1-up-powerup (1).png"); shared_ptr<Sprite> spaceship_sprite = make_shared<Sprite>(anim_ptr->GetWidth(), anim_ptr->GetHeight(), anim_ptr); powerUp->SetSprite(spaceship_sprite); powerUp->SetBoundingShape(make_shared<BoundingSphere>(powerUp->GetThisPtr(), 4.00f)); powerUp->SetScale(0.05f); mGameWorld->AddObject(powerUp); } } void Asteroids::CreateCircleBulletPowerUps(const uint num_powerUps) { for (uint i = 0; i < num_powerUps; i++) { shared_ptr<GameObject> powerUp = make_shared<CircleBulletPowerUp>(); Animation* anim_ptr = AnimationManager::GetInstance().CreateAnimationFromFile( "circleBulletPowerUp", 160, 160, 160, 160, "circleShot.png"); shared_ptr<Sprite> spaceship_sprite = make_shared<Sprite>(anim_ptr->GetWidth(), anim_ptr->GetHeight(), anim_ptr); powerUp->SetSprite(spaceship_sprite); powerUp->SetBoundingShape(make_shared<BoundingSphere>(powerUp->GetThisPtr(), 4.00f)); powerUp->SetScale(0.05f); mGameWorld->AddObject(powerUp); } } void Asteroids::CreateMenu() { // Add a (transparent) border around the edge of the game display mGameDisplay->GetContainer()->SetBorder(GLVector2i(10, 10)); aGameTitle = make_shared<GUILabel>("Asteroids by Aum"); aStartGameOption = make_shared<GUILabel>("1) Start Game"); aExitGameOption = make_shared<GUILabel>("2) Exit Game"); aInstructions = make_shared<GUILabel>("Arrow Keys to move, Space to shoot"); aGameTitle->SetVerticalAlignment(GUIComponent::GUI_VALIGN_TOP); aStartGameOption->SetVerticalAlignment(GUIComponent::GUI_VALIGN_TOP); aExitGameOption->SetVerticalAlignment(GUIComponent::GUI_VALIGN_TOP); aInstructions->SetVerticalAlignment(GUIComponent::GUI_VALIGN_BOTTOM); // aInstructions->SetSize(GLVector2i(0.5)); shared_ptr<GUIComponent> a_game_menu_title_component = static_pointer_cast<GUIComponent>(aGameTitle); shared_ptr<GUIComponent> a_game_menu_startGame_component = static_pointer_cast<GUIComponent>(aStartGameOption); shared_ptr<GUIComponent> a_game_menu_exitGame_component = static_pointer_cast<GUIComponent>(aExitGameOption); shared_ptr<GUIComponent> a_game_menu_instructions_component = static_pointer_cast<GUIComponent>(aInstructions); mGameDisplay->GetContainer()->AddComponent(a_game_menu_title_component, GLVector2f(0.3f, 0.7f)); mGameDisplay->GetContainer()->AddComponent(a_game_menu_startGame_component, GLVector2f(0.3f, 0.5f)); mGameDisplay->GetContainer()->AddComponent(a_game_menu_exitGame_component, GLVector2f(0.3f, 0.4f)); mGameDisplay->GetContainer()->AddComponent(a_game_menu_instructions_component, GLVector2f(0.18f, 0.0f)); } void Asteroids::CreateGUI() { aExitGameOption = make_shared<GUILabel>("2) Exit Game"); aExitGameOption->SetVerticalAlignment(GUIComponent::GUI_VALIGN_TOP); shared_ptr<GUIComponent> a_game_menu_exitGame_component = static_pointer_cast<GUIComponent>(aExitGameOption); mGameDisplay->GetContainer()->AddComponent(a_game_menu_exitGame_component, GLVector2f(0.7f, 1.0f)); aBulletPowerTime = make_shared<GUILabel>("Bullet Time: 0"); aBulletPowerTime->SetVerticalAlignment(GUIComponent::GUI_VALIGN_BOTTOM); shared_ptr<GUIComponent> a_bulletPowerTime_component = static_pointer_cast<GUIComponent>(aExitGameOption); mGameDisplay->GetContainer()->AddComponent(aBulletPowerTime, GLVector2f(0.65f, 0.0f)); // Create a new GUILabel and wrap it up in a shared_ptr mScoreLabel = make_shared<GUILabel>("Score: 0"); // Set the vertical alignment of the label to GUI_VALIGN_TOP mScoreLabel->SetVerticalAlignment(GUIComponent::GUI_VALIGN_TOP); // Add the GUILabel to the GUIComponent shared_ptr<GUIComponent> score_component = static_pointer_cast<GUIComponent>(mScoreLabel); mGameDisplay->GetContainer()->AddComponent(score_component, GLVector2f(0.0f, 1.0f)); // Create a new GUILabel and wrap it up in a shared_ptr mLivesLabel = make_shared<GUILabel>("Lives: 3"); // Set the vertical alignment of the label to GUI_VALIGN_BOTTOM mLivesLabel->SetVerticalAlignment(GUIComponent::GUI_VALIGN_BOTTOM); // Add the GUILabel to the GUIComponent shared_ptr<GUIComponent> lives_component = static_pointer_cast<GUIComponent>(mLivesLabel); mGameDisplay->GetContainer()->AddComponent(lives_component, GLVector2f(0.0f, 0.0f)); // Create a new GUILabel and wrap it up in a shared_ptr mGameOverLabel = shared_ptr<GUILabel>(new GUILabel("GAME OVER")); // Set the horizontal alignment of the label to GUI_HALIGN_CENTER mGameOverLabel->SetHorizontalAlignment(GUIComponent::GUI_HALIGN_CENTER); // Set the vertical alignment of the label to GUI_VALIGN_MIDDLE mGameOverLabel->SetVerticalAlignment(GUIComponent::GUI_VALIGN_MIDDLE); // Set the visibility of the label to false (hidden) mGameOverLabel->SetVisible(false); // Add the GUILabel to the GUIContainer shared_ptr<GUIComponent> game_over_component = static_pointer_cast<GUIComponent>(mGameOverLabel); mGameDisplay->GetContainer()->AddComponent(game_over_component, GLVector2f(0.5f, 0.5f)); } void Asteroids::OnScoreChanged(int score) { // Format the score message using an string-based stream std::ostringstream msg_stream; msg_stream << "Score: " << score; // Get the score message as a string std::string score_msg = msg_stream.str(); mScoreLabel->SetText(score_msg); } void Asteroids::OnPlayerKilled(int lives_left) { shared_ptr<GameObject> explosion = CreateExplosion(EXPLOSION_SPACESHIP); explosion->SetPosition(mSpaceship->GetPosition()); explosion->SetRotation(mSpaceship->GetRotation()); explosion->SetScale(0.5f); mGameWorld->AddObject(explosion); // Format the lives left message using an string-based stream std::ostringstream msg_stream; msg_stream << "Lives: " << lives_left; // Get the lives left message as a string std::string lives_msg = msg_stream.str(); mLivesLabel->SetText(lives_msg); if (lives_left > 0) { SetTimer(1000, CREATE_NEW_PLAYER); } else { SetTimer(500, SHOW_GAME_OVER); } } shared_ptr<GameObject> Asteroids::CreateExplosion(const int& type) { Animation* anim_ptr = AnimationManager::GetInstance().GetAnimationByName("explosion"); if (type == EXPLOSION_SPACESHIP) { anim_ptr = AnimationManager::GetInstance().GetAnimationByName("blueExplosion"); } shared_ptr<Sprite> explosion_sprite = make_shared<Sprite>(anim_ptr->GetWidth(), anim_ptr->GetHeight(), anim_ptr); explosion_sprite->SetLoopAnimation(false); shared_ptr<GameObject> explosion = make_shared<Explosion>(); explosion->SetSprite(explosion_sprite); explosion->Reset(); return explosion; }
d965bfcc0bbe2a9aa19c0ce626d8286540bced90
c850e10c3a6bcd63d794e6e386d531ded8687a24
/src/MediaSrv/Service/MediaNetObj.cpp
5dcfa8266406f6c73caf2289a25f0ee44f728d1b
[]
no_license
jjzhang166/Media
c3a42d5ea403260d864efdf341b6497c9da0ca00
00de6b828a397d30f633fa652330425cc170fba4
refs/heads/master
2021-08-12T01:30:55.586365
2014-10-11T06:39:50
2014-10-11T06:39:50
110,660,883
0
2
null
null
null
null
UTF-8
C++
false
false
772
cpp
#include "MediaNetObj.h" #include "CharSetHelper.h" #include "Config.h" CMediaNetObj::CMediaNetObj(Socket_t sHandle, CCrowd* pCrowd, S32 SndBufSize, S32 RcvBufSize) : CNetObj(sHandle, pCrowd, SndBufSize, RcvBufSize) { } CMediaNetObj::CMediaNetObj(S32 SndBufSize, S32 RcvBufSize) : CNetObj(SndBufSize, RcvBufSize) { } CMediaNetObj::~CMediaNetObj(void) { } string CMediaNetObj::GetUrl(string Url) { S8 Ip[20] = { 0 }; S32 Port = 0; S8 URL[256] = { 0 }; sscanf(Url.c_str(), "ip=%[^&]&port=%d&url=%s", Ip, &Port, URL); wstring strMediaPath = CONFIG.GetMediaPath(); string strUrl = W2C(strMediaPath); string strTU = URL; if(strTU.find(strUrl) != string::npos) { return strTU; } else { strUrl += "\\"; strUrl += URL; } return strUrl; }
82be5926545fd5b4d3c115da238a2fb6c5d530ad
bdef29fb02439ff36f40d0d4fe9d3169144db95a
/ZJ-B184 裝貨櫃問題/Demo/ZJ-B184 裝貨櫃問題_hansen033.cpp
215a597ef1107c93c94e9291a2e1ef554b3ecd88
[]
no_license
huangmayor0905/20210930-homework-pro
d138d4adef1ce0e99edc070f564e6d43f81e38ce
539ef13154446bc4d0612904fe793ce41f69de99
refs/heads/master
2023-08-02T01:47:52.525326
2021-09-30T15:56:30
2021-09-30T15:56:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
875
cpp
#include <iostream> using namespace std; struct cargo{ int weight; int value; };//注意這個分號 int main(){ int amount;//儲存貨物數量 while(cin>>amount){ cargo data[amount];//儲存各貨物資訊 for(int t=0; t<amount; t++) cin>>data[t].weight>>data[t].value; //DP的部分 int space[101]={0};//儲存在各個容量下最大的價值 | 用101會比較方便因為會需要0的那格 for(int object=0; object<amount; object++){ for(int t2=100; t2-data[object].weight>=0; t2--){//注意如果是這種直接修改的作法需要由後向前,不然一個東西會被用很多次 //就是這裡會用到容量0價值0的那格 if(space[t2]<space[t2-data[object].weight]+data[object].value) space[t2]=space[t2-data[object].weight]+data[object].value; } } cout<<space[100]<<"\n"; } }
20f3e0d7087790301d444e29f427d1e7fa001abf
64bd2dbc0d2c8f794905e3c0c613d78f0648eefc
/Cpp/SDK/ALK_WieldableObject_ScrubBrush_classes.h
baabd66ca0a736a52b2a1c0f5da9c9957eeca801
[]
no_license
zanzo420/SoT-Insider-SDK
37232fa74866031dd655413837813635e93f3692
874cd4f4f8af0c58667c4f7c871d2a60609983d3
refs/heads/main
2023-06-18T15:48:54.547869
2021-07-19T06:02:00
2021-07-19T06:02:00
387,354,587
1
2
null
null
null
null
UTF-8
C++
false
false
821
h
#pragma once // Name: SoT Insider, Version: 1.103.4306.0 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass ALK_WieldableObject_ScrubBrush.ALK_WieldableObject_ScrubBrush_C // 0x0000 (FullSize[0x0028] - InheritedSize[0x0028]) class UALK_WieldableObject_ScrubBrush_C : public UWieldableItemAnimationStoreId { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass ALK_WieldableObject_ScrubBrush.ALK_WieldableObject_ScrubBrush_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
732a40a0b5ac725c342971919e5902cf32507f46
79d31b4ae847b40a9c27d9895a8de3b71d1a09b1
/FoVProto/Source/FoVProto/Items/Item.cpp
87374864f99f1806e5ec05a43ab8b3505fb3e19b
[]
no_license
Milowan/FoVProto
3e215ff76e7a1a8ddc8be62479c41f111ad1724f
fd29b086b4dfe5848070b0bd15c56d22e1edbf8c
refs/heads/master
2023-01-03T20:31:43.050217
2020-11-01T00:17:05
2020-11-01T00:17:05
276,907,986
1
0
null
null
null
null
UTF-8
C++
false
false
596
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "Item.h" // Sets default values AItem::AItem() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; } // Called when the game starts or when spawned void AItem::BeginPlay() { Super::BeginPlay(); } // Called every frame void AItem::Tick(float DeltaTime) { Super::Tick(DeltaTime); } FString AItem::GetItemName() { return itemName; } void AItem::SetItemName(FString name) { itemName = name; }
00e319519c274a7b7785aa465a8eb5ea49802629
3b39ecf003030018416074939de3ae3f5f3d0aab
/tests/ca_fifo/main.cpp
cbf5c065efdaede384e859d5a7459ce281180391
[]
no_license
liang-aquarius/ca_model
97d8724b0d2c03255a801f175b3eaf07c6d56a14
d6510b9a993c236a096f065cd35bc70d318537d7
refs/heads/master
2020-07-17T09:45:01.576068
2019-09-05T03:39:10
2019-09-05T03:39:10
205,996,724
14
0
null
null
null
null
UTF-8
C++
false
false
2,194
cpp
#include <iostream> #include "ca_fifo/ca_fifo_top.h" #include "driver_monitor.h" ca_fifo_top<0,1024,uint32_t> * u_ca_fifo_top; driver_monitor<0,1024,uint32_t> * u_driver_monitor; using namespace std; void connect_modules() { u_ca_fifo_top->ca_fifo_top_input_i.clk = u_driver_monitor->driver_monitor_output_o.clk; u_ca_fifo_top->ca_fifo_top_input_i.reset_n = u_driver_monitor->driver_monitor_output_o.reset_n; u_ca_fifo_top->ca_fifo_top_input_i.read_en = u_driver_monitor->driver_monitor_output_o.read_en; u_ca_fifo_top->ca_fifo_top_input_i.write_en = u_driver_monitor->driver_monitor_output_o.write_en; u_ca_fifo_top->ca_fifo_top_input_i.data_in = u_driver_monitor->driver_monitor_output_o.data_write; u_driver_monitor->driver_monitor_input_i.full = u_ca_fifo_top->ca_fifo_top_output_o.full_w; u_driver_monitor->driver_monitor_input_i.empty = u_ca_fifo_top->ca_fifo_top_output_o.empty_w; u_driver_monitor->driver_monitor_input_i.data_valid = u_ca_fifo_top->ca_fifo_top_output_o.data_valid_w; u_driver_monitor->driver_monitor_input_i.data_out = u_ca_fifo_top->ca_fifo_top_output_o.data_out_w; u_ca_fifo_top->connect_submod(); u_driver_monitor->connect_submod(); } int main() { ////////////////////vcd file init//////////////////////////////////// begin_init_vcd_file("main_test.vcd", vcd_file); u_ca_fifo_top = new ca_fifo_top<0,1024,uint32_t>(true); u_driver_monitor = new driver_monitor<0,1024,uint32_t>; end_init_vcd_file(vcd_file); int num_cycles = 2048; for(int i=0; i< num_cycles; i++){ //////////////////combinational logic & connect modules///////////////// connect_modules(); /////////////////////////////dump vcd file ///////////////////////// if (u_ca_fifo_top->is_trace()) { u_ca_fifo_top->dump_sigs(vcd_file); time_record = false; } /////////////////////////////update values//////////////////////////// u_ca_fifo_top->update(); u_driver_monitor->update(); /////////////////////////sequential logic///////////////// cycle++; u_ca_fifo_top->run(); u_driver_monitor->run(); } }
083eb688b7ebc58f00047cb46e6a49543ddc8501
35ab160d4c1eb0d8651bb0230595d630d279fbfe
/src/nodal/data/LDAP2PTRTiedEgoCentricNetworkData.h
c37c6a8a1c428dd8fc66204d839b294bfbf0bbd1
[]
no_license
duyvu/EgocentricCitationNetworks
32307f09d69b0b2b692fa9f10da1bdb53a2494a3
0f223db37a122d3bedddfa463d5f31ec7b2005a0
refs/heads/master
2020-07-10T01:09:23.384858
2019-08-24T08:16:14
2019-08-24T08:16:14
204,128,119
0
0
null
null
null
null
UTF-8
C++
false
false
1,667
h
/* * LDAP2PTRTiedEgoCentricNetworkData.h * * Created on: Jan 13, 2011 * Author: duyvu */ #ifndef LDAP2PTRTIEDEGOCENTRICNETWORKDATA_H_ #define LDAP2PTRTIEDEGOCENTRICNETWORKDATA_H_ #include "TiedEgoCentricNetworkData.h" namespace ndip { class LDAP2PTRTiedEgoCentricNetworkData: public ndip::TiedEgoCentricNetworkData { protected: unsigned int windowSizeOfRenewalStatistic; void updateNodalNetworkStatisticsCache(const EdgeEvents& edgeEvents, double nextCitingTime, bool isCached, ListOfEdgeEvents& listOfActiveEvents); DoubleMatrix LDA; public: static const int NUMBER_OF_LDA_TOPICS = 50; static const int NUMBER_OF_NODAL_NETWORK_STATISTICS = 8 + NUMBER_OF_LDA_TOPICS; static const int WINDOW_SIZE_OF_RENEWAL_STATISTIC = 180; LDAP2PTRTiedEgoCentricNetworkData(); LDAP2PTRTiedEgoCentricNetworkData( const ExposureTimeVectorType& _nodeJoiningTimes, const VectorOfEdgeEvents& _vectorOfEdgeEvents, double _observationTimeStart, double _observationTimeEnd, const std::vector<string>& listOfNodalDataFiles); virtual ~LDAP2PTRTiedEgoCentricNetworkData(); void updateNodalNetworkStatistics(const EdgeEvents& edgeEvents) { cout << "This is not supported in LDA data" << endl; } void updateNodalNetworkStatistics(unsigned int indexOfEdgeEvents); int getFirstOrderPopularityIndex(); void setWindowSizeOfRenewalStatistic(unsigned int size) { windowSizeOfRenewalStatistic = size; cout << "Renewal statistic window size is " << windowSizeOfRenewalStatistic << endl; } unsigned int getWindowSizeOfRenewalStatistic() { return windowSizeOfRenewalStatistic; } }; } #endif /* LDAP2PTRTIEDEGOCENTRICNETWORKDATA_H_ */
[ "teo@teo-OptiPlex-990" ]
teo@teo-OptiPlex-990
18bf46a7c447c4cecdddce18b1435b11ee5c78a2
be5f730d4793ada887bc4d26b0125f4865fd74c1
/Basics/Getting _user_input.cpp
4baf934e5309446affb057bc4831ca7813845780
[]
no_license
DataCrusade1999/C--plus---plus
783ecf44bfdc9639700b64f3947963c1c56d37f7
a0202899a56fa6fe5ff0cf08bf251e94f237ab4c
refs/heads/master
2023-03-01T02:55:57.345705
2021-02-09T13:31:01
2021-02-09T13:31:01
309,100,375
0
0
null
2021-02-09T13:16:01
2020-11-01T13:20:18
C++
UTF-8
C++
false
false
173
cpp
#include<iostream> #include<cmath> using namespace std; int main() { int age; cout<<"Enter you age: "; cin>>age; cout<<"Your age is " << age; return 0; }
91d861f730d53474d5efd446612fe970402a1c31
98cd2179bf865fd89d8c965f80bf9346eca2b037
/system/vold/fs/F2fs.cpp
f196c75d9e946075b4bee63fb3a972d4bffffb84
[]
no_license
luyuncsd123/anroidx86-5
471a12928a6b33648273994e45a6400d32f5d476
6276d90b11672fa4b4a2364847d4a63cf1d1c837
refs/heads/master
2022-12-14T11:16:50.261602
2020-08-09T03:10:52
2020-08-09T03:10:52
284,468,694
0
0
null
null
null
null
UTF-8
C++
false
false
3,098
cpp
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "F2fs.h" #include "Utils.h" #include <android-base/logging.h> #include <android-base/stringprintf.h> #include <private/android_filesystem_config.h> #include <vector> #include <string> #include <sys/mount.h> #include <sys/stat.h> using android::base::StringPrintf; namespace android { namespace vold { namespace f2fs { #ifdef MINIVOLD static const char* kMkfsPath = "/sbin/mkfs.f2fs"; static const char* kFsckPath = "/sbin/fsck.f2fs"; #else #ifdef CM_BUILD static const char* kMkfsPath = "/system/bin/mkfs.f2fs"; #else static const char* kMkfsPath = "/system/bin/make_f2fs"; #endif static const char* kFsckPath = "/system/bin/fsck.f2fs"; #endif bool IsSupported() { return access(kMkfsPath, X_OK) == 0 && access(kFsckPath, X_OK) == 0 && IsFilesystemSupported("f2fs"); } status_t Check(const std::string& source, bool trusted) { std::vector<std::string> cmd; cmd.push_back(kFsckPath); cmd.push_back("-a"); cmd.push_back(source); return ForkExecvp(cmd, trusted ? sFsckContext : sFsckUntrustedContext); } status_t Mount(const std::string& source, const std::string& target, const std::string& opts /* = "" */, bool trusted, bool portable) { std::string data(opts); if (portable && is_selinux_enabled() > 0) { if (!data.empty()) { data += ","; } data += "context=u:object_r:sdcard_posix:s0"; } const char* c_source = source.c_str(); const char* c_target = target.c_str(); const char* c_data = data.c_str(); unsigned long flags = MS_NOATIME | MS_NODEV | MS_NOSUID; // Only use MS_DIRSYNC if we're not mounting adopted storage if (!trusted) { flags |= MS_DIRSYNC; } int res = mount(c_source, c_target, "f2fs", flags, c_data); if (portable && res == 0) { chown(c_target, AID_MEDIA_RW, AID_MEDIA_RW); chmod(c_target, 0775); } if (res != 0) { PLOG(ERROR) << "Failed to mount " << source; if (errno == EROFS) { res = mount(c_source, c_target, "f2fs", flags | MS_RDONLY, c_data); if (res != 0) { PLOG(ERROR) << "Failed to mount read-only " << source; } } } return res; } status_t Format(const std::string& source) { std::vector<std::string> cmd; cmd.push_back(kMkfsPath); cmd.push_back(source); return ForkExecvp(cmd); } } // namespace f2fs } // namespace vold } // namespace android
d580a55b0946877b2c3a509223aaa4841b39f568
d2d4dadbbb4f4c4df145ac8cdfed585a9bc5e701
/src/main/cpp/disenum/der_iff_type_5_fop_param6.cpp
4a0013fe23a143c6fb3e2ff4ab80f5e9e02d63ef
[ "BSD-2-Clause" ]
permissive
Updownquark/DISEnumerations
c5e0368d4780a7d1c0de24603f4ab2dbe8c312ae
6b90dd4fb4323d3daf5e1d282078d9c0ffe0545c
refs/heads/master
2021-03-04T22:33:52.529451
2020-03-09T15:26:36
2020-03-09T15:26:36
246,071,613
0
0
NOASSERTION
2020-03-09T15:25:08
2020-03-09T15:25:07
null
UTF-8
C++
false
false
710
cpp
#include <sstream> #include <cstddef> #include <disenum/der_iff_type_5_fop_param6.h> namespace DIS { namespace der_iff_type_5_fop_param6 { bitmask& bitmask::operator=(const unsigned short& i) { (*this) = *( reinterpret_cast<bitmask *> (const_cast<unsigned short*>(&i))) ; return (*this); } bitmask::bitmask(const unsigned short& i) { (*this) = i ; } bitmask::bitmask() { (*this) = (unsigned short) 0; } unsigned short bitmask::getValue(){ unsigned short val = *( reinterpret_cast<unsigned short *> (this)); return val; } void bitmask::setValue(const unsigned short& i){ (*this) = i; } }; /* namespace der_iff_type_5_fop_param6 */ } /* namespace DIS */
2c87e95a29608e8e43afbe3a578ea0c0e2accb6c
f64c38a7b682b511d2f8a9a33a53ddf9d61916f0
/include/D1UserEventInformation.hh
b769cfcd7a4cb1d33f37b31a840d5d82b8cf2a70
[]
no_license
ebode/code
e8c1d479f5fe1dfe32bf0da8ac9f01ae130431ea
ae455db6fa574986b3f4e7971043701b96939e3d
refs/heads/master
2020-03-15T05:21:41.628293
2018-05-03T11:53:04
2018-05-03T11:53:04
131,987,123
0
0
null
null
null
null
UTF-8
C++
false
false
4,443
hh
// // ******************************************************************** // * License and Disclaimer * // * * // * The Geant4 software is copyright of the Copyright Holders of * // * the Geant4 Collaboration. It is provided under the terms and * // * conditions of the Geant4 Software License, included in the file * // * LICENSE and available at http://cern.ch/geant4/license . These * // * include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GEANT4 collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the Geant4 Software license. * // ******************************************************************** // // $Id: LXeUserEventInformation.hh 68752 2013-04-05 10:23:47Z gcosmo $ // /// \file optical/LXe/include/LXeUserEventInformation.hh /// \brief Definition of the LXeUserEventInformation class // #include "G4VUserEventInformation.hh" #include "G4ThreeVector.hh" #include "globals.hh" #ifndef D1UserEventInformation_h #define D1UserEventInformation_h 1 class D1UserEventInformation : public G4VUserEventInformation { public: D1UserEventInformation(); virtual ~D1UserEventInformation(); inline virtual void Print()const{}; void IncPhotonCount_Scint(){fPhotonCount_Scint++;} void IncPhotonCount_Ceren(){fPhotonCount_Ceren++;} void IncEDep(G4double dep){fTotE+=dep;} void IncAbsorption(){fAbsorptionCount++;} void IncBoundaryAbsorption(){fBoundaryAbsorptionCount++;} void IncHitCount(G4int i=1){fHitCount+=i;} void SetEWeightPos(const G4ThreeVector& p){fEWeightPos=p;} void SetReconPos(const G4ThreeVector& p){fReconPos=p;} void SetConvPos(const G4ThreeVector& p){fConvPos=p;fConvPosSet=true;} void SetPosMax(const G4ThreeVector& p,G4double edep){fPosMax=p;fEdepMax=edep;} G4int GetPhotonCount_Scint()const {return fPhotonCount_Scint;} G4int GetPhotonCount_Ceren()const {return fPhotonCount_Ceren;} G4int GetHitCount()const {return fHitCount;} G4double GetEDep()const {return fTotE;} G4int GetAbsorptionCount()const {return fAbsorptionCount;} G4int GetBoundaryAbsorptionCount() const {return fBoundaryAbsorptionCount;} G4ThreeVector GetEWeightPos(){return fEWeightPos;} G4ThreeVector GetReconPos(){return fReconPos;} G4ThreeVector GetConvPos(){return fConvPos;} G4ThreeVector GetPosMax(){return fPosMax;} G4double GetEDepMax(){return fEdepMax;} G4double IsConvPosSet(){return fConvPosSet;} //Gets the total photon count produced G4int GetPhotonCount(){return fPhotonCount_Scint+fPhotonCount_Ceren;} void IncShape1SAboveThreshold(){fShape1sAboveThreshold++;} G4int GetShape1SAboveThreshold(){return fShape1sAboveThreshold;} void IncShape2SAboveThreshold(){fShape2sAboveThreshold++;} G4int GetShape2SAboveThreshold(){return fShape2sAboveThreshold;} private: G4int fHitCount; G4int fPhotonCount_Scint; G4int fPhotonCount_Ceren; G4int fAbsorptionCount; G4int fBoundaryAbsorptionCount; G4double fTotE; //These only have meaning if totE > 0 //If totE = 0 then these wont be set by EndOfEventAction G4ThreeVector fEWeightPos; G4ThreeVector fReconPos; //Also relies on hitCount>0 G4ThreeVector fConvPos;//true (initial) converstion position G4bool fConvPosSet; G4ThreeVector fPosMax; G4double fEdepMax; G4int fShape1sAboveThreshold; G4int fShape2sAboveThreshold; }; #endif
a1dc60121cc94315f4a3dc4485cd38a18ad197f8
a07b19f97463c4105150726a2814b50ee9ac1ad7
/include/point2.h
fcc117ee469db7a344dae0e5b1a1febb2811ac73
[]
no_license
GustavoAC/Raytracer
facb1efbfaf88229f16355fa06cad2e8dfc26ede
8cf3775ee2d7bef05fcdd00f33456222d2e8d5d3
refs/heads/master
2020-05-04T14:01:05.812015
2019-06-24T04:14:46
2019-06-24T04:14:46
179,181,562
1
0
null
null
null
null
UTF-8
C++
false
false
3,075
h
#pragma once #include <math.h> #include <stdlib.h> #include <iostream> using fltType = float; class Point2 { public: Point2() { e[0] = 0; e[1] = 0; } Point2(fltType e0, fltType e1) { e[0] = e0; e[1] = e1; } inline fltType x() const { return e[0]; } inline fltType y() const { return e[1]; } inline const Point2 &operator+() const { return *this; } inline Point2 operator-() const { return Point2(-e[0], -e[1]); } inline fltType operator[](int i) const { return e[i]; } inline fltType &operator[](int i) { return e[i]; } inline Point2 &operator+=(const Point2 &v2); inline Point2 &operator-=(const Point2 &v2); inline Point2 &operator*=(const Point2 &v2); inline Point2 &operator/=(const Point2 &v2); inline Point2 &operator*=(fltType t); inline Point2 &operator/=(fltType t); inline fltType length() const { return sqrt(e[0] * e[0] + e[1] * e[1]); } inline fltType squared_length() const { return e[0] * e[0] + e[1] * e[1]; } inline void make_unit_vector(); fltType e[2]; }; inline std::istream &operator>>(std::istream &is, Point2 &t) { is >> t.e[0] >> t.e[1]; return is; } inline std::ostream &operator<<(std::ostream &os, const Point2 &t) { os << t.e[0] << " " << t.e[1]; return os; } inline Point2 operator+(const Point2 &v1, const Point2 &v2) { return Point2(v1.e[0] + v2.e[0], v1.e[1] + v2.e[1]); } inline Point2 operator-(const Point2 &v1, const Point2 &v2) { return Point2(v1.e[0] - v2.e[0], v1.e[1] - v2.e[1]); } inline Point2 operator*(const Point2 &v1, const Point2 &v2) { return Point2(v1.e[0] * v2.e[0], v1.e[1] * v2.e[1]); } inline Point2 operator/(const Point2 &v1, const Point2 &v2) { return Point2(v1.e[0] / v2.e[0], v1.e[1] / v2.e[1]); } inline Point2 operator*(fltType t, const Point2 &v) { return Point2(v.e[0] * t, v.e[1] * t); } inline Point2 operator*(const Point2 &v, fltType t) { return Point2(v.e[0] * t, v.e[1] * t); } inline Point2 operator/(const Point2 &v, fltType t) { return Point2(v.e[0] / t, v.e[1] / t); } inline fltType dot(const Point2 &v1, const Point2 &v2) { return v1.e[0] * v2.e[0] + v1.e[1] * v2.e[1]; } inline Point2 &Point2::operator+=(const Point2 &v) { e[0] += v.e[0]; e[1] += v.e[1]; return *this; } inline Point2 &Point2::operator-=(const Point2 &v) { e[0] -= v.e[0]; e[1] -= v.e[1]; return *this; } inline Point2 &Point2::operator*=(const Point2 &v) { e[0] *= v.e[0]; e[1] *= v.e[1]; return *this; } inline Point2 &Point2::operator/=(const Point2 &v) { e[0] /= v.e[0]; e[1] /= v.e[1]; return *this; } inline Point2 &Point2::operator*=(fltType t) { e[0] *= t; e[1] *= t; return *this; } inline Point2 &Point2::operator/=(fltType t) { fltType k = 1.0 / t; e[0] *= k; e[1] *= k; return *this; } inline Point2 unit_vector(const Point2 &v) { return v / v.length(); } inline void Point2::make_unit_vector() { fltType unit_scaler = 1.0 / length(); *this *= unit_scaler; }
abda535d355da5f01824c4e9b80e2ed7e0431fc7
6dcb86ae9656831f061df127ed43e5a85fe02593
/src/logging.h
02f35b03935c64a58b1153b89299b39c28d4af21
[ "MIT" ]
permissive
vslotman/SeriousProton
e011fbe748b260b4ac30d49196316ad7c0a588f6
5f298e9e389e2d2a5f0f8a708c3a76354c796e5f
refs/heads/master
2020-04-18T11:41:25.427243
2015-03-08T21:38:00
2015-03-08T21:38:00
31,810,276
0
0
null
2015-03-07T11:42:06
2015-03-07T11:42:06
null
UTF-8
C++
false
false
1,478
h
#ifndef LOGGING_H #define LOGGING_H #include <SFML/System.hpp> #include "stringImproved.h" #define LOG(LEVEL) Logging(LOGLEVEL_ ## LEVEL, __FILE__, __LINE__, __PRETTY_FUNCTION__) enum ELogLevel { LOGLEVEL_DEBUG, LOGLEVEL_INFO, LOGLEVEL_WARNING, LOGLEVEL_ERROR }; class Logging : sf::NonCopyable { static ELogLevel global_level; bool do_logging; public: Logging(ELogLevel level, string file, int line, string function_name); ~Logging(); static void setLogLevel(ELogLevel level); friend const Logging& operator<<(const Logging& log, const char* str); }; const Logging& operator<<(const Logging& log, const char* str); inline const Logging& operator<<(const Logging& log, const std::string& s) { return log << (s.c_str()); } inline const Logging& operator<<(const Logging& log, const int i) { return log << string(i).c_str(); } inline const Logging& operator<<(const Logging& log, const unsigned int i) { return log << string(i).c_str(); } inline const Logging& operator<<(const Logging& log, const long i) { return log << string(int(i)).c_str(); } inline const Logging& operator<<(const Logging& log, const unsigned long i) { return log << string(int(i)).c_str(); } inline const Logging& operator<<(const Logging& log, const float f) { return log << string(f).c_str(); } template<typename T> inline const Logging& operator<<(const Logging& log, const sf::Vector2<T> v) { return log << v.x << "," << v.y; } #endif//LOGGING_H
fcd31ac80f32ed68007cb0f1364536933d4d54a9
8c01eacec149d7b12ed7c084e58c4a266f061f60
/AFPiCS/particles/particle_simple.h
a605ffe6c7652cebdef7cf90bffd5dcae738b01c
[ "Unlicense" ]
permissive
UnknowableCoder/AFFPiCS
937ef4e69e6656a581a46876034a364322554325
553bb1c184262f51eda49fe70502954fea69ef0c
refs/heads/main
2023-03-22T10:53:16.198804
2021-03-18T23:39:59
2021-03-18T23:39:59
347,186,431
1
0
null
null
null
null
UTF-8
C++
false
false
4,136
h
#ifndef AFFPICS_PARTICLES_PARTICLE_SIMPLE #define AFFPICS_PARTICLES_PARTICLE_SIMPLE /*! \file particle_simple.h \brief A class that specifies an instance of a particle with fixed charge and rest mass. \author Nuno Fernandes */ #include "../header.h" #include "particle_base.h" namespace AFFPiCS { namespace Particles { template <indexer num_dims, class derived = void> class particle_simple : public particle_base<num_dims, std::conditional_t<std::is_void_v<derived>, particle_simple<num_dims, derived>, derived>> { private: using deriv_t = std::conditional_t<std::is_void_v<derived>, particle_simple, derived>; protected: vector_type<indexer, num_dims> grid_position; vector_type<FLType, num_dims> position; //In units of cell separation vector_type<FLType, num_dims> mom_over_mass; //In whatever units specified by system_info. public: CUDA_HOS_DEV particle_simple(const vector_type<indexer, num_dims> &cll = vector_type<FLType, num_dims>(0), const vector_type<FLType, num_dims> ps = vector_type<FLType, num_dims>(FLType(0.)), const vector_type<FLType, num_dims> mm = vector_type<FLType, num_dims>(FLType(0.)) ): grid_position(cll), position(ps), mom_over_mass(mm) { } template <class system_info> CUDA_HOS_DEV vector_type<FLType, num_dims> u(const system_info &info) const { return mom_over_mass; } template <class system_info> CUDA_HOS_DEV vector_type<FLType, num_dims> pos(const system_info &info) const { return position; } template <class system_info> CUDA_HOS_DEV vector_type<indexer, num_dims> cell(const system_info &info) const { return grid_position; } template <class system_info> CUDA_HOS_DEV FLType gamma(system_info &info) const { const deriv_t* dhis = static_cast<const deriv_t*>(this); using namespace std; return sqrt(dhis->u(info).square_norm2()/info.units().c()/info.units().c()+FLType(1)); } template <class system_info> CUDA_HOS_DEV void set_u(const vector_type<FLType, num_dims>& new_u, const system_info &info) { mom_over_mass = new_u; } template <class system_info> CUDA_HOS_DEV void set_pos(const vector_type<FLType, num_dims>& new_pos, const system_info &info) { position = new_pos; } template <class system_info> CUDA_HOS_DEV void set_cell(const vector_type<indexer, num_dims>& new_cell, const system_info &info) { grid_position = new_cell; } template<class stream, class str = std::basic_string<typename stream::char_type>> CUDA_ONLY_HOS void textual_output(stream &s, const str& separator = " ") const { g24_lib::textual_output(s, grid_position, separator); s << separator; g24_lib::textual_output(s, position, separator); s << separator; g24_lib::textual_output(s, mom_over_mass, separator); } template<class stream> CUDA_ONLY_HOS void binary_output(stream &s) const { g24_lib::binary_output(s, grid_position); g24_lib::binary_output(s, position); g24_lib::binary_output(s, mom_over_mass); } template<class stream> CUDA_ONLY_HOS void textual_input(stream &s) { g24_lib::textual_input(s, grid_position); g24_lib::textual_input(s, position); g24_lib::textual_input(s, mom_over_mass); } template<class stream> CUDA_ONLY_HOS void binary_input(stream &s) { g24_lib::binary_input(s, grid_position); g24_lib::binary_input(s, position); g24_lib::binary_input(s, mom_over_mass); } }; } } #endif
61e32a17dc8eaa3f31a91b397e9fd621da505d06
e4f85676da4b6a7d8eaa56e7ae8910e24b28b509
/cc/layers/painted_overlay_scrollbar_layer_impl.h
b890e497decb68806a977f5735fde7c4885e1bfd
[ "BSD-3-Clause" ]
permissive
RyoKodama/chromium
ba2b97b20d570b56d5db13fbbfb2003a6490af1f
c421c04308c0c642d3d1568b87e9b4cd38d3ca5d
refs/heads/ozone-wayland-dev
2023-01-16T10:47:58.071549
2017-09-27T07:41:58
2017-09-27T07:41:58
105,863,448
0
0
null
2017-10-05T07:55:32
2017-10-05T07:55:32
null
UTF-8
C++
false
false
2,538
h
// Copyright 2016 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. #ifndef CC_LAYERS_PAINTED_OVERLAY_SCROLLBAR_LAYER_IMPL_H_ #define CC_LAYERS_PAINTED_OVERLAY_SCROLLBAR_LAYER_IMPL_H_ #include "base/macros.h" #include "cc/cc_export.h" #include "cc/input/scrollbar.h" #include "cc/layers/nine_patch_generator.h" #include "cc/layers/scrollbar_layer_impl_base.h" #include "cc/resources/ui_resource_client.h" namespace cc { class LayerTreeImpl; class CC_EXPORT PaintedOverlayScrollbarLayerImpl : public ScrollbarLayerImplBase { public: static std::unique_ptr<PaintedOverlayScrollbarLayerImpl> Create( LayerTreeImpl* tree_impl, int id, ScrollbarOrientation orientation, bool is_left_side_vertical_scrollbar); ~PaintedOverlayScrollbarLayerImpl() override; // LayerImpl implementation. std::unique_ptr<LayerImpl> CreateLayerImpl(LayerTreeImpl* tree_impl) override; void PushPropertiesTo(LayerImpl* layer) override; bool WillDraw(DrawMode draw_mode, ResourceProvider* resource_provider) override; void AppendQuads(viz::RenderPass* render_pass, AppendQuadsData* append_quads_data) override; void SetThumbThickness(int thumb_thickness); void SetThumbLength(int thumb_length); void SetTrackStart(int track_start); void SetTrackLength(int track_length); void SetImageBounds(const gfx::Size& bounds); void SetAperture(const gfx::Rect& aperture); void set_thumb_ui_resource_id(UIResourceId uid) { thumb_ui_resource_id_ = uid; } protected: PaintedOverlayScrollbarLayerImpl(LayerTreeImpl* tree_impl, int id, ScrollbarOrientation orientation, bool is_left_side_vertical_scrollbar); // ScrollbarLayerImplBase implementation. int ThumbThickness() const override; int ThumbLength() const override; float TrackLength() const override; int TrackStart() const override; bool IsThumbResizable() const override; private: const char* LayerTypeAsString() const override; UIResourceId thumb_ui_resource_id_; int thumb_thickness_; int thumb_length_; int track_start_; int track_length_; gfx::Size image_bounds_; gfx::Rect aperture_; NinePatchGenerator quad_generator_; DISALLOW_COPY_AND_ASSIGN(PaintedOverlayScrollbarLayerImpl); }; } // namespace cc #endif // CC_LAYERS_PAINTED_OVERLAY_SCROLLBAR_LAYER_IMPL_H_
93a5e2af419a42a9fb10d0439e8763ad7e533e5c
c9da8015df6b844e20f787f799f06e6a3fbce3ac
/src/engine/renderers/DebugLightRenderer.hpp
130df35489e62d1e7f46b0d9936d0322f95c7711
[ "MIT" ]
permissive
Michael-Lfx/Rendu
6766ad2779558d72581ee99cd2409ad5f77849a8
cb694b67a1fab3e00fda4053bb48a39f7f7e6beb
refs/heads/master
2023-06-23T09:35:17.153547
2021-05-22T10:39:30
2021-05-22T10:39:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,696
hpp
#pragma once #include "scene/Scene.hpp" #include "renderers/LightRenderer.hpp" #include "scene/lights/Light.hpp" #include "scene/lights/PointLight.hpp" #include "scene/lights/DirectionalLight.hpp" #include "scene/lights/SpotLight.hpp" #include "Common.hpp" /** \brief Visualize lights as colored wireframe objects. \ingroup Renderers */ class DebugLightRenderer final : public LightRenderer { public: /** Constructor. \see GLSL::Frag::light_debug for an example. \param fragmentShader the name of the fragment shader to use. */ explicit DebugLightRenderer(const std::string & fragmentShader); /** Set the current user view and projection matrices. \param viewMatrix the camera view matrix \param projMatrix the camera projection matrix */ void updateCameraInfos(const glm::mat4 & viewMatrix, const glm::mat4 & projMatrix); /** Draw a spot light as a colored wireframe cone. \param light the light to draw */ void draw(const SpotLight * light) override; /** Draw a point light as a colored wireframe sphere. \param light the light to draw */ void draw(const PointLight * light) override; /** Draw a directional light as a colored wireframe arrow pointing at the origin. \param light the light to draw */ void draw(const DirectionalLight * light) override; private: const Mesh * _sphere; ///< Point light supporting geometry. const Mesh * _cone; ///< Spot light supporting geometry. const Mesh * _arrow; ///< Spot light supporting geometry. const Program * _program; ///< Light mesh shader. glm::mat4 _view = glm::mat4(1.0f); ///< Cached camera view matrix. glm::mat4 _proj = glm::mat4(1.0f); ///< Cached camera projection matrix. };
fbbeaac43598df9ca213905a2ee3afcbcc58772f
5dcd66a23a1a62681ef50b71e3186dd53cb3e844
/lib/dbgraph.hh
b030e16e2cef360355f071209d19ee61ceaab013
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jasonpell/dbg
ddfb7627dabba927b01bf1cd837aed0e8949c4a1
d50fee4c32d8f1a85b666791ec334ff77e2ba237
refs/heads/master
2021-01-22T02:52:40.466018
2011-07-27T18:13:00
2011-07-27T18:13:00
1,832,562
1
0
null
null
null
null
UTF-8
C++
false
false
1,386
hh
#ifndef DBGRAPH_HH #define DBGRAPH_HH #include "dbg.hh" #include <math.h> #include <string.h> #include <stdlib.h> #include <time.h> #include <vector> namespace dbg { class DBGraph { protected: unsigned int _s; unsigned int _k; HashIntoType _n_bytes; Byte * _counts; public: DBGraph(unsigned int s, unsigned int k) { _s = s; _k = k; _n_bytes = pow(_s, _k) / 8 + 1; _counts = new Byte[_n_bytes]; memset(_counts, 0, _n_bytes); } ~DBGraph() { delete _counts; } void set(HashIntoType h) { HashIntoType byte = h / 8; unsigned char bit = h % 8; _counts[byte] |= (1 << bit); } void unset(HashIntoType h) { HashIntoType byte = h / 8; unsigned char bit = h % 8; _counts[byte] &= (255 ^ (1 << bit)); } unsigned char get(HashIntoType h) { HashIntoType byte = h / 8; unsigned char bit = h % 8; if (!(_counts[byte] & (1 << bit))) { return 0; } return 1; } void clear() { memset(_counts, 0, _n_bytes); } void altfill(float p); void fill(float p); std::vector<HashIntoType>* getNeighbors(HashIntoType h); std::vector<unsigned int>* getComponentLens(); }; }; #endif // DBGRAPH_HH
dfa04b0532371a5237d634bc00da0e18aafd2405
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/third_party/sfntly/src/cpp/src/test/endian_test.cc
0d9da09018bb54e3f3d4106ec499633d19488ae6
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
2,383
cc
/* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "gtest/gtest.h" #include "sfntly/tag.h" #include "sfntly/data/growable_memory_byte_array.h" #include "sfntly/data/writable_font_data.h" #include "sfntly/math/fixed1616.h" #include "sfntly/port/memory_output_stream.h" #include "sfntly/data/font_output_stream.h" namespace sfntly { bool TestEndian() { byte_t test_data[] = { 0x68, 0x65, 0x61, 0x64, // 0: head 0xca, 0xca, 0xca, 0xca, // 4: ubyte, byte, char 0x00, 0x18, 0x80, 0x18, // 8: ushort, short 0x00, 0x00, 0x18, 0x00, // 12: uint24 0x00, 0x00, 0x00, 0x18, // 16: ulong 0xff, 0xff, 0xff, 0x00, // 20: long 0x00, 0x01, 0x00, 0x00 // 24: fixed }; ByteArrayPtr ba1 = new GrowableMemoryByteArray(); for (size_t i = 0; i < sizeof(test_data); ++i) { ba1->Put(i, test_data[i]); } ReadableFontDataPtr rfd = new ReadableFontData(ba1); EXPECT_EQ(rfd->ReadULongAsInt(0), Tag::head); EXPECT_EQ(rfd->ReadUByte(4), 202); EXPECT_EQ(rfd->ReadByte(5), -54); EXPECT_EQ(rfd->ReadChar(6), 202); EXPECT_EQ(rfd->ReadUShort(8), 24); EXPECT_EQ(rfd->ReadShort(10), -32744); EXPECT_EQ(rfd->ReadUInt24(12), 24); EXPECT_EQ(rfd->ReadULong(16), 24); EXPECT_EQ(rfd->ReadLong(20), -256); EXPECT_EQ(rfd->ReadFixed(24), Fixed1616::Fixed(1, 0)); MemoryOutputStream os; FontOutputStream fos(&os); fos.WriteULong(Tag::head); fos.Write(202); fos.Write(202); fos.Write(202); fos.Write(202); fos.WriteUShort(24); fos.WriteShort(-32744); fos.WriteUInt24(24); fos.WriteChar(0); fos.WriteULong(24); fos.WriteLong(-256); fos.WriteFixed(Fixed1616::Fixed(1, 0)); EXPECT_EQ(memcmp(os.Get(), test_data, sizeof(test_data)), 0); return true; } } // namespace sfntly TEST(Endian, All) { ASSERT_TRUE(sfntly::TestEndian()); }
14cf921436e60bcb661e16b54f65f61c6b0b3962
b3755933b72453849cae7f8b18c9313aa79ae819
/src/libs/comguiutils/colorcombobox.h
ee56aeb41572aed43fc592d2657039f15e0f4794
[]
no_license
lpxxn/code
d420b48b4b96d752a5bc1af4b90c700f543def17
ccf172047ae65a4d91545c3ffb3b6fa41819433f
refs/heads/master
2016-09-06T09:50:50.066030
2015-07-21T05:46:10
2015-07-21T05:46:10
32,777,890
0
0
null
null
null
null
UTF-8
C++
false
false
1,314
h
/*! \file * \brief Picture基本界面 * \author 杨永盛 谭立方 * \date 2013 * \version 1.0 * \copyright 2013 PERAGlobal Ltd. All rights reserved. * * 供应用程序中所有其它模块使用的基本通用界面ColorBox */ /**************************************************************************** ** ** Copyright (c) 2013 PERAGlobal Ltd. All rights reserved. ** All rights reserved. ** ****************************************************************************/ #ifndef COLORCOMBOBOX_H #define COLORCOMBOBOX_H #include <QComboBox> #include "comguiutils_global.h" namespace GuiUtils { class COMGUIUTILS_EXPORT ColorComboBox : public QComboBox { Q_OBJECT public: ColorComboBox(QWidget *parent = 0); void setColor(const QColor& c); QColor color() const; static QList<QColor> colorList(); static QStringList colorNames(); static int colorIndex(const QColor& c); static QColor color(int colorIndex); static QColor defaultColor(int colorIndex); static bool isValidColor(const QColor& color); static int numPredefinedColors(); static QStringList defaultColorNames(); static QList<QColor> defaultColors(); protected: void init(); static const int stColorsCount = 24; static const QColor stColors[]; }; } #endif // COLORCOMBOBOX_H
8dae1243ff16d65139875e315c8a73f39066a361
c2fc4673b511b347b47158be96e6bf1f01e3f167
/extras/jbcoin-libpp/extras/jbcoind/src/test/beast/beast_PropertyStream_test.cpp
64475d4866518d5a54ce93f6e1bc33fa9abe924e
[ "MIT-Wu", "MIT", "ISC", "BSL-1.0" ]
permissive
trongnmchainos/validator-keys-tool
037c7d69149cc9581ddfca3dc93892ebc1e031f1
cae131d6ab46051c0f47509b79b6efc47a70eec0
refs/heads/master
2020-04-07T19:42:10.838318
2018-11-22T07:33:26
2018-11-22T07:33:26
158,658,994
2
1
null
null
null
null
UTF-8
C++
false
false
6,734
cpp
//------------------------------------------------------------------------------ /* This file is part of jbcoind: https://github.com/jbcoin/jbcoind Copyright (c) 2012, 2013 Jbcoin Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #include <jbcoin/beast/unit_test.h> #include <jbcoin/beast/utility/PropertyStream.h> namespace beast { class PropertyStream_test : public unit_test::suite { public: using Source = PropertyStream::Source; void test_peel_name(std::string s, std::string const& expected, std::string const& expected_remainder) { try { std::string const peeled_name = Source::peel_name(&s); BEAST_EXPECT(peeled_name == expected); BEAST_EXPECT(s == expected_remainder); } catch (...) { fail("unhandled exception");; } } void test_peel_leading_slash(std::string s, std::string const& expected, bool should_be_found) { try { bool const found(Source::peel_leading_slash(&s)); BEAST_EXPECT(found == should_be_found); BEAST_EXPECT(s == expected); } catch (...) { fail("unhandled exception");; } } void test_peel_trailing_slashstar(std::string s, std::string const& expected_remainder, bool should_be_found) { try { bool const found(Source::peel_trailing_slashstar(&s)); BEAST_EXPECT(found == should_be_found); BEAST_EXPECT(s == expected_remainder); } catch (...) { fail("unhandled exception");; } } void test_find_one(Source& root, Source* expected, std::string const& name) { try { Source* source(root.find_one(name)); BEAST_EXPECT(source == expected); } catch (...) { fail("unhandled exception");; } } void test_find_path(Source& root, std::string const& path, Source* expected) { try { Source* source(root.find_path(path)); BEAST_EXPECT(source == expected); } catch (...) { fail("unhandled exception");; } } void test_find_one_deep(Source& root, std::string const& name, Source* expected) { try { Source* source(root.find_one_deep(name)); BEAST_EXPECT(source == expected); } catch (...) { fail("unhandled exception");; } } void test_find(Source& root, std::string path, Source* expected, bool expected_star) { try { auto const result(root.find(path)); BEAST_EXPECT(result.first == expected); BEAST_EXPECT(result.second == expected_star); } catch (...) { fail("unhandled exception");; } } void run() { Source a("a"); Source b("b"); Source c("c"); Source d("d"); Source e("e"); Source f("f"); Source g("g"); // // a { b { d { f }, e }, c { g } } // a.add(b); a.add(c); c.add(g); b.add(d); b.add(e); d.add(f); testcase("peel_name"); test_peel_name("a", "a", ""); test_peel_name("foo/bar", "foo", "bar"); test_peel_name("foo/goo/bar", "foo", "goo/bar"); test_peel_name("", "", ""); testcase("peel_leading_slash"); test_peel_leading_slash("foo/", "foo/", false); test_peel_leading_slash("foo", "foo", false); test_peel_leading_slash("/foo/", "foo/", true); test_peel_leading_slash("/foo", "foo", true); testcase("peel_trailing_slashstar"); test_peel_trailing_slashstar("/foo/goo/*", "/foo/goo", true); test_peel_trailing_slashstar("foo/goo/*", "foo/goo", true); test_peel_trailing_slashstar("/foo/goo/", "/foo/goo", false); test_peel_trailing_slashstar("foo/goo", "foo/goo", false); test_peel_trailing_slashstar("", "", false); test_peel_trailing_slashstar("/", "", false); test_peel_trailing_slashstar("/*", "", true); test_peel_trailing_slashstar("//", "/", false); test_peel_trailing_slashstar("**", "*", true); test_peel_trailing_slashstar("*/", "*", false); testcase("find_one"); test_find_one(a, &b, "b"); test_find_one(a, nullptr, "d"); test_find_one(b, &e, "e"); test_find_one(d, &f, "f"); testcase("find_path"); test_find_path(a, "a", nullptr); test_find_path(a, "e", nullptr); test_find_path(a, "a/b", nullptr); test_find_path(a, "a/b/e", nullptr); test_find_path(a, "b/e/g", nullptr); test_find_path(a, "b/e/f", nullptr); test_find_path(a, "b", &b); test_find_path(a, "b/e", &e); test_find_path(a, "b/d/f", &f); testcase("find_one_deep"); test_find_one_deep(a, "z", nullptr); test_find_one_deep(a, "g", &g); test_find_one_deep(a, "b", &b); test_find_one_deep(a, "d", &d); test_find_one_deep(a, "f", &f); testcase("find"); test_find(a, "", &a, false); test_find(a, "*", &a, true); test_find(a, "/b", &b, false); test_find(a, "b", &b, false); test_find(a, "d", &d, false); test_find(a, "/b*", &b, true); test_find(a, "b*", &b, true); test_find(a, "d*", &d, true); test_find(a, "/b/*", &b, true); test_find(a, "b/*", &b, true); test_find(a, "d/*", &d, true); test_find(a, "a", nullptr, false); test_find(a, "/d", nullptr, false); test_find(a, "/d*", nullptr, true); test_find(a, "/d/*", nullptr, true); } }; BEAST_DEFINE_TESTSUITE(PropertyStream, utility, beast); }
72768afc935e0f3f05df602f484b17e5b609ad08
3a4051230db32976215d13ccf6ebcb47c88a4268
/ceROBOT/main.cpp
acbee77ce4410ffe9e6d95302b32ce541c170bbd
[]
no_license
joseff01/AED2-P3-TECFS
870bd36aaacbce2c1ec0c659e32f26b52f0c6e84
441120f755ee7edae4d02f90746aaa3c1e79a884
refs/heads/main
2023-06-07T12:48:20.392627
2021-06-26T00:59:56
2021-06-26T00:59:56
376,709,784
0
0
null
null
null
null
UTF-8
C++
false
false
78
cpp
#include <iostream> #include "ceROBOT.h" int main() { ceROBOT ceRobot; }
831f16ac9d8ff085225fd508dab0362d65efbca3
b5a9d42f7ea5e26cd82b3be2b26c324d5da79ba1
/tensorflow/core/ops/debug_ops.cc
3cb55bcae5ddf3b1e13bb11d3fdcaffef92cb5f4
[ "Apache-2.0" ]
permissive
uve/tensorflow
e48cb29f39ed24ee27e81afd1687960682e1fbef
e08079463bf43e5963acc41da1f57e95603f8080
refs/heads/master
2020-11-29T11:30:40.391232
2020-01-11T13:43:10
2020-01-11T13:43:10
230,088,347
0
0
Apache-2.0
2019-12-25T10:49:15
2019-12-25T10:49:14
null
UTF-8
C++
false
false
9,118
cc
/* Copyright 2017 The TensorFlow 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. ==============================================================================*/ // This file registers all TensorFlow Debugger (tfdbg) ops. #include "tensorflow/core/framework/common_shape_fns.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/shape_inference.h" namespace tensorflow { // TensorFlow Debugger-inserted ops. // These ops are used only internally by tfdbg. There is no API for users to // direct create them. Users can create them indirectly by using // RunOptions.debug_options during Session::Run() call. See tfdbg documentation // for more details. REGISTER_OP("Copy") .Input("input: T") .Output("output: T") .Attr("T: type") .Attr("tensor_name: string = ''") .Attr("debug_ops_spec: list(string) = []") .SetAllowsUninitializedInput() .SetShapeFn(shape_inference::UnchangedShape) .Doc(R"doc( Copy Op. Performs CPU-to-CPU or GPU-to-GPU deep-copying of tensor, depending on the device on which the tensor is allocated. N.B.: If the all downstream attached debug ops are disabled given the current gRPC gating status, the output will simply forward the input tensor without deep-copying. See the documentation of Debug* ops for more details. Unlike the CopyHost Op, this op does not have HostMemory constraint on its input or output. input: Input tensor. output: Output tensor, deep-copied from input. tensor_name: The name of the input tensor. debug_ops_spec: A list of debug op spec (op, url, gated_grpc) for attached debug ops. Each element of the list has the format <debug_op>;<grpc_url>;<gated_grpc>, wherein gated_grpc is boolean represented as 0/1. E.g., "DebugIdentity;grpc://foo:3333;1", "DebugIdentity;file:///tmp/tfdbg_1;0". )doc"); REGISTER_OP("CopyHost") .Input("input: T") .Output("output: T") .Attr("T: type") .Attr("tensor_name: string = ''") .Attr("debug_ops_spec: list(string) = []") .SetAllowsUninitializedInput() .SetShapeFn(shape_inference::UnchangedShape) .Doc(R"doc( Copy Host Op. Performs CPU-to-CPU deep-copying of tensor. N.B.: If the all downstream attached debug ops are disabled given the current gRPC gating status, the output will simply forward the input tensor without deep-copying. See the documentation of Debug* ops for more details. Unlike the Copy Op, this op has HostMemory constraint on its input or output. input: Input tensor. output: Output tensor, deep-copied from input. tensor_name: The name of the input tensor. debug_ops_spec: A list of debug op spec (op, url, gated_grpc) for attached debug ops. Each element of the list has the format <debug_op>;<grpc_url>;<gated_grpc>, wherein gated_grpc is boolean represented as 0/1. E.g., "DebugIdentity;grpc://foo:3333;1", "DebugIdentity;file:///tmp/tfdbg_1;0". )doc"); REGISTER_OP("DebugIdentity") .Input("input: T") .Output("output: T") .Attr("T: type") .Attr("device_name: string = ''") .Attr("tensor_name: string = ''") .Attr("debug_urls: list(string) = []") .Attr("gated_grpc: bool = false") .SetAllowsUninitializedInput() .SetShapeFn(shape_inference::UnchangedShape) .Doc(R"doc( Debug Identity Op. Provides an identity mapping of the non-Ref type input tensor for debugging. input: Input tensor, non-Reference type. output: Output tensor that equals the input tensor. tensor_name: Name of the input tensor. debug_urls: List of URLs to debug targets, e.g., file:///foo/tfdbg_dump, grpc:://localhost:11011 gated_grpc: Whether this op will be gated. If any of the debug_urls of this debug node is of the grpc:// scheme, when the value of this attribute is set to True, the data will not actually be sent via the grpc stream unless this debug op has been enabled at the debug_url. If all of the debug_urls of this debug node are of the grpc:// scheme and the debug op is enabled at none of them, the output will be an empty Tensor. )doc"); REGISTER_OP("DebugNanCount") .Input("input: T") .Output("output: int64") // The debug signal (nan count) is int64 .Attr("T: type") .Attr("device_name: string = ''") .Attr("tensor_name: string = ''") .Attr("debug_urls: list(string) = []") .Attr("gated_grpc: bool = false") .SetAllowsUninitializedInput() .SetShapeFn(shape_inference::ScalarShape) .Doc(R"doc( Debug NaN Value Counter Op Counts number of NaNs in the input tensor, for debugging. input: Input tensor, non-Reference type. output: An integer output tensor that is the number of NaNs in the input. tensor_name: Name of the input tensor. debug_urls: List of URLs to debug targets, e.g., file:///foo/tfdbg_dump, grpc:://localhost:11011. gated_grpc: Whether this op will be gated. If any of the debug_urls of this debug node is of the grpc:// scheme, when the value of this attribute is set to True, the data will not actually be sent via the grpc stream unless this debug op has been enabled at the debug_url. If all of the debug_urls of this debug node are of the grpc:// scheme and the debug op is enabled at none of them, the output will be an empty Tensor. )doc"); REGISTER_OP("DebugNumericSummary") .Input("input: T") .Output("output: double") .Attr("T: type") .Attr("device_name: string = ''") .Attr("tensor_name: string = ''") .Attr("debug_urls: list(string) = []") .Attr("lower_bound: float = -inf") .Attr("upper_bound: float = inf") .Attr("mute_if_healthy: bool = false") .Attr("gated_grpc: bool = false") .SetAllowsUninitializedInput() // Note: this could return a more specific shape if needed in future. .SetShapeFn(shape_inference::UnknownShape) .Doc(R"doc( Debug Numeric Summary Op. Provide a basic summary of numeric value types, range and distribution. input: Input tensor, non-Reference type, float or double. output: A double tensor of shape [14 + nDimensions], where nDimensions is the the number of dimensions of the tensor's shape. The elements of output are: [0]: is initialized (1.0) or not (0.0). [1]: total number of elements [2]: NaN element count [3]: generalized -inf count: elements <= lower_bound. lower_bound is -inf by default. [4]: negative element count (excluding -inf), if lower_bound is the default -inf. Otherwise, this is the count of elements > lower_bound and < 0. [5]: zero element count [6]: positive element count (excluding +inf), if upper_bound is the default -inf. Otherwise, this is the count of elements < upper_bound and > 0. [7]: generalized +inf count, elements >= upper_bound. upper_bound is +inf by default. Output elements [1:8] are all zero, if the tensor is uninitialized. [8]: minimum of all non-inf and non-NaN elements. If uninitialized or no such element exists: +inf. [9]: maximum of all non-inf and non-NaN elements. If uninitialized or no such element exists: -inf. [10]: mean of all non-inf and non-NaN elements. If uninitialized or no such element exists: NaN. [11]: variance of all non-inf and non-NaN elements. If uninitialized or no such element exists: NaN. [12]: Data type of the tensor encoded as an enum integer. See the DataType proto for more details. [13]: Number of dimensions of the tensor (ndims). [14+]: Sizes of the dimensions. tensor_name: Name of the input tensor. debug_urls: List of URLs to debug targets, e.g., file:///foo/tfdbg_dump, grpc:://localhost:11011 lower_bound: (float) The lower bound <= which values will be included in the generalized -inf count. Default: -inf. upper_bound: (float) The upper bound >= which values will be included in the generalized +inf count. Default: +inf. mute_if_healthy: (bool) Do not send data to the debug URLs unless at least one of elements [2], [3] and [7] (i.e., the nan count and the generalized -inf and inf counts) is non-zero. gated_grpc: Whether this op will be gated. If any of the debug_urls of this debug node is of the grpc:// scheme, when the value of this attribute is set to True, the data will not actually be sent via the grpc stream unless this debug op has been enabled at the debug_url. If all of the debug_urls of this debug node are of the grpc:// scheme and the debug op is enabled at none of them, the output will be an empty Tensor. )doc"); } // namespace tensorflow
18f7d6363de3c7413f64e5c68167b0affa3133e4
77fd74a63707b9fe0b3df78f1527e8b33d5ec046
/IRcalculator/index.ino
27add6d86ba98bccf3cdc71bcd0997052bc6a079
[]
no_license
Jaagrav/Arduino
d5caf72568354cfed797f4f31f8ae541710bb586
62906b12ccf5ace0744fc4568ea80aeac89ceec7
refs/heads/main
2023-04-03T09:14:37.959280
2021-03-30T14:45:46
2021-03-30T14:45:46
342,885,955
5
0
null
null
null
null
UTF-8
C++
false
false
4,845
ino
/* This is an IR Remote Controlled Calculator. I have tried to get rid of all the bugs that I have seen in other calculators made using an arduino. This calculator can be used like a normal calculator, you can make simultaneous calculations with this, add points, etc. The LCD Display used here is a RG1602A, you may refer to this article to understand how to use the display, https://create.arduino.cc/projecthub/najad/interfacing-lcd1602-with-arduino-764ec4 All you need to do is connect the wires in the corresponding pins written down below and edit the IR Codes: |------#------Arduino Pins------LCD RG1602A--------------------| |----- 1 ---- GND ----- VSS,V0 (With 2K ohm),RW,K -----| |----- 2 ---- 5V ----- VDD, A (With 220 ohm) -----| |----- 3 ---- 12 ----- RS -----| |----- 4 ---- 11 ----- E -----| |----- 5 ---- 5 ----- D4 -----| |----- 6 ---- 4 ----- D5 -----| |----- 7 ---- 3 ----- D6 -----| |----- 8 ---- 2 ----- D7 -----| |--------------------------------------------------------------| |------#------Arduino Pins------IR Transmitter-----------------| |----- 1 ---- 10 ----- Out -----| |----- 2 ---- GND ----- GND -----| |----- 3 ---- 5V ----- Power -----| |--------------------------------------------------------------| Check it out on Github: https://github.com/Jaagrav/IRcalculator/ */ #include <IRremote.h> #include <LiquidCrystal.h> #include <math.h> // Digital Pin Connections to your LCD const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2; LiquidCrystal lcd(rs, en, d4, d5, d6, d7); // Digital Pin Connection to your IR Receiver IRrecv irrecv(10); decode_results results; String number1 = "0", number2 = "0", optr = "=", sixteenString = " "; /* In the below switch-case replace the numbers with the IR codes from your remote. Make sure you write the code that gets printed in your serial monitor from line 142. */ void acceptInput(int character) { Serial.println(character); switch(character) { case 2222: concatNumbers("1"); break; case -31092: concatNumbers("2"); break; case 18888: concatNumbers("3"); break; case 10000: concatNumbers("4"); break; case -22203: concatNumbers("5"); break; case 26666: concatNumbers("6"); break; case 6333: concatNumbers("7"); break; case -25537: concatNumbers("8"); break; case 22222: concatNumbers("9"); break; case 12222: concatNumbers("0"); break; case 28888: concatNumbers("."); break; case 255: number1 = "0"; number2 = "0"; optr = "="; break; case 32222: function("+"); break; case -28870: function("-"); break; case 24444: function("/"); break; case 8444: function("x"); break; case 45555: if(optr != "=") calculate("="); break; case 4333: backSpace(); break; default: Serial.println("Invalid Input"); } } void setup() { Serial.begin(9600); lcd.begin(16, 2); irrecv.enableIRIn(); } void loop() { if (irrecv.decode(&results)) { unsigned int result = results.value; String val = String(result); acceptInput(val.toInt()); irrecv.resume(); } lcd.setCursor(0,0); lcd.print(optr + " " + sixteenString.substring(number1.length() + 3) + number1); lcd.setCursor(0,1); lcd.print(sixteenString.substring(number2.length()) + number2); } void calculate(String op) { double no1 = number1.toDouble(); double no2 = number2.toDouble(); double calcVal = 0.0; if(optr == "+") calcVal = (no1 + no2); else if(optr == "-") calcVal = (no1 - no2); else if(optr == "x") calcVal = (no1 * no2); else if(optr == "/") calcVal = (no1 / no2); number1 = toString(calcVal); number2 = "0"; optr = op; } String toString(double num) { return String(num); } void function(String e) { if(number1 != "0" && number2 != "0") { calculate(e); } else if(number1 == "0") { number1 = number2; number2 = "0"; } optr = e; } void concatNumbers(String num) { if(optr == "=") number1 = "0"; if(num != "."){ if(number2.length() == 1 && number2 == "0") number2 = num; else number2 += num; } else { if(number2.charAt(number2.length()-1) != '.' && number2.indexOf('.') == -1) number2 += num; } } void backSpace() { number2 = number2.substring(0, number2.length() - 1); if(number2 == "") number2 = "0"; }
5dab18e80048757e26a62a4bd23c66aa40d97f8b
171939de0a904c90f9af198b8e5d65f8349429d7
/CQ-00302/palin/palin.cpp
35888575cb7ab61c21f9b90e85045b34895bf59d
[]
no_license
LittleYang0531/CQ-CSP-S-2021
2b1071bbbf0463e65bfc177f86a44b7d3301b6a9
1d9a09f8fb6bf3ba22962969a2bac18383df4722
refs/heads/main
2023-08-26T11:39:42.483746
2021-10-23T14:45:45
2021-10-23T14:45:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
205
cpp
#include<bits/stdc++.h> using namespace std; int main(){ freopen("palin.in", "r", stdin); freopen("palin.out", "w", stdout); int T; scanf("%d", &T); if (T == 2) printf("LRRLLRRRRL\n-1"); return 0; }
3302f2f419de8905a22a16d2188e70875535b0d5
2d26ad5e5359ad6704d0015a395457181e71c072
/Blatt 3/src/Graph.cpp
16e0e79ee44b3deff8cc996b4d1df15b4787519c
[]
no_license
froseb/edm_uebung
88cec3cfb24c3a59b27b6557b6a62e286a8161c0
44be2300cd68f1560b083c54aa1f8b4457dd6038
refs/heads/master
2020-04-02T19:34:25.036815
2019-01-01T22:13:50
2019-01-01T22:13:50
154,738,627
1
0
null
null
null
null
UTF-8
C++
false
false
7,965
cpp
#include <vector> #include <list> #include <string> #include <iostream> #include <fstream> #include "Graph.h" Graph::Edge::Edge(unsigned int a, unsigned int b, unsigned int id, int cost) : a(a), b(b), id(id), cost(cost), active(false) { } unsigned int Graph::Edge::getId() { return id; } unsigned int Graph::Edge::getA() { return a; } unsigned int Graph::Edge::getB() { return b; } bool Graph::Edge::isActive() { return active; } int Graph::Edge::getCost() { return cost; } void Graph::setActive(Edge& e, bool active) { unsigned int oldflow = static_cast<unsigned int>(e.isActive()); e.active = active; Node& a = getNode(e.getA()); Node& b = getNode(e.getB()); a.outFlow -= oldflow; a.outFlow += active; b.inFlow -= oldflow; b.inFlow += active; } Graph::Node::Node(unsigned int id) : id(id) { } unsigned int Graph::Node::getId() { return id; } void Graph::addOutEdge(Graph::Node& n, unsigned int e) { n.outEdges.push_back(e); n.outFlow += static_cast<unsigned int>(getEdge(e).isActive()); } void Graph::addInEdge(Graph::Node& n, unsigned int e) { n.inEdges.push_back(e); n.inFlow += static_cast<unsigned int>(getEdge(e).isActive()); } // Gets the edges going out std::vector<unsigned int>& Graph::Node::getOutEdges() { return outEdges; } // Gets the edges going in std::vector<unsigned int>& Graph::Node::getInEdges() { return inEdges; } // Gets the flow out of the edge unsigned int Graph::Node::getOutFlow() { return outFlow; } // Gets the flow into the edge unsigned int Graph::Node::getInFlow() { return inFlow; } // Constructor, initializes the graph Graph::Graph(unsigned int nc) { nodeCount = nc; // Add node objects to nodes vector nodes.reserve(nc); for (unsigned int i = 0; i < nc; i++) { nodes.push_back(Node(i)); } } // Parses a graph file and constructs the graph Graph::Graph(std::string filename) { std::fstream file(filename, std::ios_base::in); // Check if file is open if (!file.is_open()) { nodeCount = 0; throw(std::runtime_error("File could not be opened.")); return; } // Set Node Count of the Graph unsigned int nc; file >> nc; if (nc%2 != 0) { throw(std::runtime_error("Tried to load an evenly partitioned bipartite graph with odd node count.")); return; } nodeCount = nc + 2; // id of s: getNodeCount-2, id of t: getNodeCount-1 // Add node objects to nodes vector nodes.reserve(nodeCount); for (unsigned int i = 0; i < nodeCount; i++) { nodes.push_back(Node(i)); } // Parses edges from the file unsigned int a, b; int cost; while (file >> a >> b >> cost) { if (a>=nc/2 || b<nc/2) { throw(std::runtime_error("Tried to add an edge between nodes of the wrong partition.")); return; } addEdge(a, b, cost); } // Adds edges from s to all nodes of the left partition and from all nodes of // the right partition to t for (unsigned int i=0; i<(getNodeCount()-2)/2; i++) { addEdge(getNodeCount()-2, i, 0); } for (unsigned int i = (getNodeCount()-2)/2; i<getNodeCount()-2; i++) { addEdge(i, getNodeCount()-1, 0); } } // Adds an edge to the graph void Graph::addEdge(unsigned int a, unsigned int b, int cost) { Edge e(a, b, edges.size(), cost); edges.push_back(e); addOutEdge(getNode(a), e.getId()); addInEdge(getNode(b), e.getId()); } // Gets the node count of the graph unsigned int Graph::getNodeCount() { return nodeCount; } // Gets the edge count of the graph unsigned int Graph::getEdgeCount() { return edges.size(); } // Gets a node in the graph Graph::Node& Graph::getNode(unsigned int a) { if (a > getNodeCount()) { throw(std::runtime_error("Tried to get non-existing node.")); } return nodes[a]; } // Gets an edge in the graph Graph::Edge& Graph::getEdge(unsigned int a) { if (a > getEdgeCount()) { throw(std::runtime_error("Tried to get non-existing edge.")); } return edges[a]; } void Graph::exportMatching(std::ostream& out) { long long int value = 0; for (unsigned int e=0; e<getEdgeCount(); e++) { if (getEdge(e).isActive() && getEdge(e).getA() != getNodeCount()-2 && getEdge(e).getB() != getNodeCount()-1) { value += getEdge(e).getCost(); } } out << value << '\n'; for (unsigned int e=0; e<getEdgeCount(); e++) { if (getEdge(e).isActive() && getEdge(e).getA() != getNodeCount()-2 && getEdge(e).getB() != getNodeCount()-1) { out << getEdge(e).getA() << ' ' << getEdge(e).getB() << '\n'; } } } // Returns the reduced cost long long int redCost(Graph::Edge& e, std::vector<long long int>& potential) { return e.getCost() + potential[e.getA()] - potential[e.getB()]; } // Gets the next active node for dijkstra algorithm unsigned int getNextActive(std::list<unsigned int>& open, std::vector<long long int>& dist) { unsigned int res; // the next element from the open list auto minOpen = open.begin(); for (auto it = open.begin(); it != open.end(); ++it) { if (dist[*it] < dist[*minOpen]) { minOpen = it; } } res = *minOpen; open.erase(minOpen); return res; } // Augments along the shortest path from s to t and updates the potential function void Graph::dijkstra(std::vector<long long int>& potential) { // Stores all the distances from s to any node std::vector<long long int> dist(getNodeCount(), -1); dist[getNodeCount()-2] = 0; // Stores the previous edges std::vector<long long int> prev(getNodeCount(), -1); // Stores open nodes in a list std::list<unsigned int> open; open.push_back(getNodeCount()-2); while (open.size() > 0) { Node& active = getNode(getNextActive(open, dist)); for (unsigned int e : active.getOutEdges()) { if (!getEdge(e).isActive() && (dist[active.getId()] + redCost(getEdge(e), potential) < dist[getEdge(e).getB()] || dist[getEdge(e).getB()] == -1)) { if (dist[getEdge(e).getB()] == -1) { open.push_back(getEdge(e).getB()); } prev[getEdge(e).getB()] = e; dist[getEdge(e).getB()] = dist[active.getId()] + redCost(getEdge(e), potential); } } for (unsigned int e : active.getInEdges()) { if (getEdge(e).isActive() && (dist[active.getId()] - redCost(getEdge(e), potential) < dist[getEdge(e).getA()] || dist[getEdge(e).getA()] == -1)) { if (dist[getEdge(e).getA()] == -1) { open.push_back(getEdge(e).getA()); } prev[getEdge(e).getA()] = e; dist[getEdge(e).getA()] = dist[active.getId()] - redCost(getEdge(e), potential); } } } // Finished pathfinding here // Check if t is reachable if (dist[getNodeCount()-1] == -1) { throw(std::runtime_error("dijkstra: Failed to find s-t-path. Therefore, there is no perfect matching.")); return; } // Augment along the path unsigned int tmp = getNodeCount()-1; while (tmp != getNodeCount()-2) { setActive(getEdge(prev[tmp]), !getEdge(prev[tmp]).isActive()); if (tmp == getEdge(prev[tmp]).getA()) { tmp = getEdge(prev[tmp]).getB(); } else { tmp = getEdge(prev[tmp]).getA(); } } // Update potential for (unsigned int i=0; i<getNodeCount(); i++) { if (dist[i] != -1) { potential[i] += dist[i]; } else { potential[i] += dist[getNodeCount()-1]; } } } void Graph::perfectMatching() { std::vector<long long int> potential(getNodeCount(), 0); // Set up initial potential for (unsigned int e=0; e<getEdgeCount(); e++) { if (getEdge(e).getCost() < potential[getEdge(e).getB()] && getEdge(e).getB() != getNodeCount()-1) { potential[getEdge(e).getB()] = getEdge(e).getCost(); } } for (unsigned int e=0; e<getEdgeCount(); e++) { if (getEdge(e).getB() == getNodeCount()-1 && potential[getEdge(e).getA()] < potential[getNodeCount()-1]) { potential[getNodeCount()-1] = potential[getEdge(e).getA()]; } } while (getNode(getNodeCount()-2).getOutFlow() != (getNodeCount()-2)/2) { dijkstra(potential); } }
0cd40886565f3f30342e900138e2d285c85ed0ed
a9cbc183306f3b4dae5fcfa92d95e346b93e0344
/anabatic/src/PreRouteds.cpp
bc90ead1246d9e34f6a98b487d582e330205385a
[]
no_license
0x01be/coriolis
f4ca0c1eba2a1fd358b5b669178a962bfeaa8ba9
3db5f27aecff1cb858302e3833a46195efd91238
refs/heads/master
2022-12-16T18:34:59.364602
2019-05-28T13:37:10
2019-05-28T13:37:10
282,252,121
0
0
null
null
null
null
UTF-8
C++
false
false
7,277
cpp
// -*- C++ -*- // // This file is part of the Coriolis Software. // Copyright (c) UPMC 2014-2018, All Rights Reserved // // +-----------------------------------------------------------------+ // | C O R I O L I S | // | A n a b a t i c - Global Routing Toolbox | // | | // | Author : Jean-Paul CHAPUT | // | E-mail : [email protected] | // | =============================================================== | // | C++ Module : "./PreRouteds.cpp" | // +-----------------------------------------------------------------+ #include "hurricane/Warning.h" #include "hurricane/BasicLayer.h" #include "hurricane/RegularLayer.h" #include "hurricane/DeepNet.h" #include "hurricane/Pin.h" #include "hurricane/RoutingPad.h" #include "crlcore/AllianceFramework.h" #include "anabatic/AnabaticEngine.h" namespace Anabatic { using std::cerr; using std::cout; using std::endl; using Hurricane::Error; using Hurricane::Warning; using Hurricane::BasicLayer; using Hurricane::RegularLayer; using Hurricane::Component; using Hurricane::Pin; using Hurricane::DeepNet; using Hurricane::Cell; using Hurricane::NetRoutingExtension; using CRL::RoutingGauge; using CRL::RoutingLayerGauge; using CRL::AllianceFramework; void AnabaticEngine::setupSpecialNets () { AllianceFramework* af = AllianceFramework::get(); for ( Net* net : _cell->getNets() ) { const char* excludedType = NULL; if (net->getType() == Net::Type::POWER ) excludedType = "POWER"; if (net->getType() == Net::Type::GROUND) excludedType = "GROUND"; if (excludedType) { cparanoid << Warning( "%s is not a routable net (%s,excluded)." , getString(net).c_str(), excludedType ) << endl; } if (af->isBLOCKAGE(net->getName())) excludedType = "BLOCKAGE"; if (excludedType) { NetData* ndata = getNetData( net, Flags::Create ); NetRoutingState* state = ndata->getNetRoutingState(); state->setFlags( NetRoutingState::Fixed ); ndata->setGlobalRouted( true ); } } } size_t AnabaticEngine::setupPreRouteds () { cmess1 << " o Looking for fixed or manually global routed nets." << endl; openSession(); size_t toBeRouteds = 0; Box ab = getCell()->getAbutmentBox(); ab.inflate( -1 ); for ( Net* net : getCell()->getNets() ) { if (net == _blockageNet) continue; if (net->getType() == Net::Type::POWER ) continue; if (net->getType() == Net::Type::GROUND) continue; // Don't skip the clock. vector<Segment*> segments; vector<Contact*> contacts; bool isPreRouted = false; bool isFixed = false; size_t rpCount = 0; for( Component* component : net->getComponents() ) { if (dynamic_cast<Pin*>(component)) continue; const RegularLayer* layer = dynamic_cast<const RegularLayer*>(component->getLayer()); if (layer and (layer->getBasicLayer()->getMaterial() == BasicLayer::Material::blockage)) continue; Horizontal* horizontal = dynamic_cast<Horizontal*>(component); if (horizontal) { if ( not ab.contains(horizontal->getSourcePosition()) and not ab.contains(horizontal->getTargetPosition()) ) continue; segments.push_back( horizontal ); isPreRouted = true; if (horizontal->getWidth() != Session::getWireWidth(horizontal->getLayer())) isFixed = true; } else { Vertical* vertical = dynamic_cast<Vertical*>(component); if (vertical) { if ( not ab.contains(vertical->getSourcePosition()) and not ab.contains(vertical->getTargetPosition()) ) continue; isPreRouted = true; segments.push_back( vertical ); if (vertical->getWidth() != Session::getWireWidth(vertical->getLayer())) isFixed = true; } else { Contact* contact = dynamic_cast<Contact*>(component); if (contact) { if (not ab.contains(contact->getCenter())) continue; isPreRouted = true; contacts.push_back( contact ); if ( (contact->getWidth () != Session::getViaWidth(contact->getLayer())) or (contact->getHeight() != Session::getViaWidth(contact->getLayer())) or (contact->getLayer () == Session::getContactLayer(0)) ) isFixed = true; } else { RoutingPad* rp = dynamic_cast<RoutingPad*>(component); if (rp) { ++rpCount; } else { // Plug* plug = dynamic_cast<Plug*>(component); // if (plug) { // cerr << "buildPreRouteds(): " << plug << endl; // ++rpCount; // } } } } } } if ((not isFixed and not isPreRouted) and net->isDeepNet()) { Net* rootNet = dynamic_cast<Net*>( dynamic_cast<DeepNet*>(net)->getRootNetOccurrence().getEntity() ); for( Component* component : rootNet->getComponents() ) { if (dynamic_cast<Horizontal*>(component)) { isFixed = true; break; } if (dynamic_cast<Vertical*> (component)) { isFixed = true; break; } if (dynamic_cast<Contact*> (component)) { isFixed = true; break; } } } if (isFixed or isPreRouted or (rpCount < 2)) { NetData* ndata = getNetData( net, Flags::Create ); NetRoutingState* state = ndata->getNetRoutingState(); state->unsetFlags( NetRoutingState::AutomaticGlobalRoute ); state->setFlags ( NetRoutingState::ManualGlobalRoute ); ndata->setGlobalRouted( true ); if (rpCount < 2) state->setFlags ( NetRoutingState::Unconnected ); if (isFixed) { if (rpCount > 1) cmess2 << " - <" << net->getName() << "> is fixed." << endl; state->unsetFlags( NetRoutingState::ManualGlobalRoute ); state->setFlags ( NetRoutingState::Fixed ); } else { if (rpCount > 1) { ++toBeRouteds; cmess2 << " - <" << net->getName() << "> is manually global routed." << endl; for ( auto icontact : contacts ) { AutoContact::createFrom( icontact ); } for ( auto segment : segments ) { AutoContact* source = Session::lookup( dynamic_cast<Contact*>( segment->getSource() )); AutoContact* target = Session::lookup( dynamic_cast<Contact*>( segment->getTarget() )); AutoSegment* autoSegment = AutoSegment::create( source, target, segment ); autoSegment->setFlags( AutoSegment::SegUserDefined|AutoSegment::SegAxisSet ); } } } } else { ++toBeRouteds; } } Session::close(); return toBeRouteds; } } // Anabatic namespace.
234ac95f3f7f52a0ecfc9f519ef43c6eb360f326
55cf527f60d9099b355f87451ba6a5ba5dde674f
/src/Odometrie/compasvisuel.cpp
cc6e6c510f34372f5d0dad5a37dd38679828d88c
[]
no_license
RomMarie/open_rm
94777b6d61f006f60a19c26b0e36b0918b359d8f
2ee092593659634c189f09f7d2073f9dbc2f5a08
refs/heads/master
2021-01-20T17:09:56.644400
2016-10-22T16:17:39
2016-10-22T16:17:39
60,364,383
0
0
null
null
null
null
UTF-8
C++
false
false
4,641
cpp
#include <open_rm/Odometrie/compasvisuel.h> #include <iostream> namespace rm{ namespace Odometrie{ namespace CompasVisuel{ /*! \brief Calcul l'orientation relative entre deux vues panoramique * * Utilise un algorithme de compas visuel par minimisation de l'erreur * quadratique sur l'ensemble de l'image. * \param[in] imgSph Image courante dont l'orientation est à estimer * \param[in] imgRef Image de référence définissant l'orientation 0 * \return angle relatif entre les deux images (en radian, entre -PI et PI) * \note Accepte les images ndg et RGB */ double complet(const cv::Mat &imgSph, const cv::Mat &imgRef) { // On commence par dupliquer l'image de référence (pour éviter les effets de bord) std::vector<cv::Mat> vec; vec.push_back(imgRef); vec.push_back(imgRef); cv::Mat fresque; hconcat( vec, fresque ); int best,bestSom=255*3*imgSph.rows*imgSph.cols; for(int o=0;o<imgSph.cols;o++){ int som=0; for(int i=0;i<imgSph.rows;i++){ for(int j=0;j<imgSph.cols;j++){ switch(imgSph.type()){ case CV_8U: som+=abs((int)imgSph.at<uchar>(i,j)-(int)fresque.at<uchar>(i,j+o)); break; case CV_8UC3: som+=abs((int)imgSph.at<cv::Vec3b>(i,j)[0]-(int)fresque.at<cv::Vec3b>(i,j+o)[0]); som+=abs((int)imgSph.at<cv::Vec3b>(i,j)[1]-(int)fresque.at<cv::Vec3b>(i,j+o)[1]); som+=abs((int)imgSph.at<cv::Vec3b>(i,j)[2]-(int)fresque.at<cv::Vec3b>(i,j+o)[2]); break; } } } if(som<bestSom){ bestSom=som; best=o; } } if(best<imgSph.cols/2){ return best*2*CV_PI/imgSph.cols; } else{ return (best-imgSph.cols)*2*CV_PI/imgSph.cols; } } /*! \brief Calcul l'orientation relative entre deux vues panoramique * * Utilise un algorithme de compas visuel par minimisation de l'erreur * quadratique sur une région d'intérêt de l'image. * \param[in] imgSph Image courante dont l'orientation est à estimer * \param[in] imgRef Image de référence définissant l'orientation 0 * \param[in] ROI Région d'intérêt de l'image (définie par un cv::Rect) * \return angle relatif entre les deux images (en radian, entre -PI et PI) * \note Accepte les images ndg et RGB */ double roi(const cv::Mat &imgSph, const cv::Mat &imgRef, cv::Rect ROI) { // On commence par dupliquer l'image de référence (pour éviter les effets de bord) std::vector<cv::Mat> vec; vec.push_back(imgRef); vec.push_back(imgRef); cv::Mat fresque; hconcat( vec, fresque ); int best,bestSom=255*3*imgSph.rows*imgSph.cols; for(int o=0;o<imgSph.cols;o++){ int som=0; for(int i=ROI.y;i<ROI.y+ROI.width;i++){ for(int j=ROI.x;j<ROI.x+ROI.height;j++){ switch(imgSph.type()){ case CV_8U: som+=abs((int)imgSph.at<uchar>(i,j)-(int)fresque.at<uchar>(i,j+o)); break; case CV_8UC3: som+=abs((int)imgSph.at<cv::Vec3b>(i,j)[0]-(int)fresque.at<cv::Vec3b>(i,j+o)[0]); som+=abs((int)imgSph.at<cv::Vec3b>(i,j)[1]-(int)fresque.at<cv::Vec3b>(i,j+o)[1]); som+=abs((int)imgSph.at<cv::Vec3b>(i,j)[2]-(int)fresque.at<cv::Vec3b>(i,j+o)[2]); break; } } } if(som<bestSom){ bestSom=som; best=o; } } if(best<imgSph.cols/2){ return best*2*CV_PI/imgSph.cols; } else{ return (best-imgSph.cols)*2*CV_PI/imgSph.cols; } } /*! \brief Calcul l'orientation relative entre deux vues panoramique * * Utilise un algorithme de compas visuel par minimisation de l'erreur * quadratique sur une région d'intérêt de l'image. * \param[in] imgSph Image courante dont l'orientation est à estimer * \param[in] imgRef Image de référence définissant l'orientation 0 * \param[in] HOI Anneau d'intéret dans la vue panoramique (définie par ses coordonnées verticales * hautes et basses : cv::Point) * \return angle relatif entre les deux images (en radian, entre -PI et PI) * \note Accepte les images ndg et RGB */ double ring(const cv::Mat &imgSph, const cv::Mat &imgRef, cv::Point HOI) { return rm::Odometrie::CompasVisuel::roi(imgSph,imgRef,cv::Rect(HOI.x,0,HOI.y-HOI.x,imgSph.cols)); } } } }
1a8e5e4cfee6b00f5332167ef381c24b499d8740
21df29f0aca4ea68bf922fadaae52772bea993ad
/src/consensus/merkle.h
d99f0b3f6d252af5a5854ba491ecc4e8a9d1aac5
[ "MIT" ]
permissive
RegulusBit/utabit13
48767b2bdfb9e0872d66d1f530c64c09aaba679b
eb8b301e77fe116a43df87fabe1cb45da358213a
refs/heads/master
2019-07-13T05:22:36.037577
2017-07-26T16:44:41
2017-07-26T16:44:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,315
h
// Copyright (c) 2015 The Utabit Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef UTABIT_MERKLE #define UTABIT_MERKLE #include <stdint.h> #include <vector> #include "primitives/transaction.h" #include "primitives/block.h" #include "uint256.h" uint256 ComputeMerkleRoot(const std::vector<uint256>& leaves, bool* mutated = NULL); std::vector<uint256> ComputeMerkleBranch(const std::vector<uint256>& leaves, uint32_t position); uint256 ComputeMerkleRootFromBranch(const uint256& leaf, const std::vector<uint256>& branch, uint32_t position); /* * Compute the Merkle root of the transactions in a block. * *mutated is set to true if a duplicated subtree was found. */ uint256 BlockMerkleRoot(const CBlock& block, bool* mutated = NULL); /* * Compute the Merkle root of the witness transactions in a block. * *mutated is set to true if a duplicated subtree was found. */ uint256 BlockWitnessMerkleRoot(const CBlock& block, bool* mutated = NULL); /* * Compute the Merkle branch for the tree of transactions in a block, for a * given position. * This can be verified using ComputeMerkleRootFromBranch. */ std::vector<uint256> BlockMerkleBranch(const CBlock& block, uint32_t position); #endif
d98e1795a6a729e0b2e657bdd9c1dd2f8f05ca99
1b53740d0b1a03f39c82999cc2a4a65cb75447e4
/sebon/srm636/solution/sortish.cpp
b80de6ba97d0ac50521556f0d338b16ce37e9947
[]
no_license
litiblue/topcoder
04ad39b6028e790688f245738c82c099182b9d2b
7632a7968b38ac49d0824cdd423a15fa4b0ce5cc
refs/heads/master
2018-11-15T14:52:31.478108
2018-10-01T02:02:13
2018-10-01T02:02:13
22,757,201
0
0
null
null
null
null
UTF-8
C++
false
false
5,349
cpp
#include "stdafx.h" #include <stdio.h> #include <algorithm> #include <iostream> #include <vector> #include <time.h> using namespace::std; int getSortedness(const vector<int> & s) { int r = 0; for (int j = s.size() - 1; j >= 0; j--) { for (int i = 0; i < j; i++) { if (s[i] < s[j]) { r++; } } } return r; } long ways(int sortedness, vector<int> seq) { vector<int> blank , missing; int n = seq.size(); // seq에서 값이 0인 인덱스를 blank vector에 저장한다. for (int i = 0; i < n; i++) { if (seq[i] == 0) { blank.push_back(i); } } // 없는 숫자들을 missing vector에 저장한다. for (int x = 1; x <= n; x++) { if ( count(seq.begin(), seq.end(), x) == 0) { missing.push_back(x); } } // calculate the initial sortedness // 초기에 0이들어간 seq에서의 sorteness를 구한다. int initialSortedness = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if ( (seq[i] < seq[j]) && (seq[i] != 0) && (seq[j] != 0) ) { initialSortedness++; } } } // calculate the sortedness added by choosing a number in each of the blank places // 빈 공간에 들어올수 있는 모든 경우의 배열에서 각자의 sortedness를 계산한다. int m = blank.size(); int **addSort = new int *[m]; for (int i=0; i<m; ++i) { addSort[i] = new int[m]; } //int addSort[m][m]; for (int i = 0; i < m; i++) { for (int j = 0; j < m; j++) { // assign missing[j] to position blank[i] addSort[i][j] = 0; for (int k = 0; k < n; k++) { if (seq[k] != 0) { if ( k < blank[i] ) { if ( seq[k] < missing[j] ) { addSort[i][j]++; } } else if (k > blank[i]) { if ( seq[k] > missing[j] ) { addSort[i][j]++; } } } } } } // we need to precalculate the sortedness of each permutation. // we *could* just use the permutation as a key for an associative array // but the following is a neat trick. We know that next_permutation will // always generate all permuations in the same order, so we can assign // an unique id to each permutation by the order it is visited. int permScore1[5040]; vector<int> per1(m / 2); /* for (int i = 0; i < m / 2; i++) { per1[i] = i; } */ int pid = 0; for (int i = 0; i < m / 2; i++) { per1[i] = i; } do { permScore1[pid++] = getSortedness(per1); for (int i= 0; i<per1.size(); ++i) { printf("%d ", per1[i]); } printf("\n"); } while ( next_permutation(per1.begin(), per1.end()) ); // An issue is that the number of missing elements might be odd, so // the number of small and large elements might be different so we might // need to repeat for large numbers: int permScore2[5040]; vector<int> per2( (m+1) / 2); for (int i = 0; i < (m+1) / 2; i++) { per2[i] = i; } pid = 0; printf("permScore2 start\n"); do { permScore2[pid++] = getSortedness(per2); /* for (int i= 0; i<per2.size(); ++i) { printf("%d ", per2[i]); } printf("\n"); */ } while ( next_permutation(per2.begin(), per2.end()) ); long res = 0; // we can generate all combinations using next_permutation. Okay, this // solution is very next_permutation-specific, I admit. vector<int> comb(m); for (int i = 0; i < m/2; i++) { comb[i] = 0; } for (int j = m/2; j < m; j++) { comb[j] = 1; } do { const int MAX = 1999*7; //The maximum value of s. Roughly you can // imagine that for each of the m/2 small numbers we might add less // than n-1 sortedness. The real limit is smaller but is not needed // to find a tight bound. int combsort = getSortedness(comb); //sortedness by this combination // small : For each small permutation, find s and increment small[s] vector<long> small(MAX + 1); int pid = 0; for (int i = 0; i < m / 2; i++) { per1[i] = i; } do { int s = permScore1[pid++]; // small의 sortness를 더한다. int j = 0; for (int i = 0; i < m; i++) { if (comb[i] == 0) { s += addSort[i][ per1[j++] ]; // } } small[s]++; } while ( next_permutation(per1.begin(), per1.end()) ); // large : For each large permutation, find the required s for a // matching small permutation and add small[s] to res pid = 0; for (int i = 0; i < (m+1) / 2; i++) { per2[i] = i; } do { int s = permScore2[pid++]; int j = 0; for (int i = 0; i < m; i++) { if (comb[i] == 1) { s += addSort[i][ per2[j++] + (m/2) ]; } } int ws = sortedness - initialSortedness - s - combsort; if ( 0 <= ws && ws <= MAX) { res += small[ws]; } } while ( next_permutation(per2.begin(), per2.end()) ); } while (next_permutation(comb.begin(), comb.end())); for (int i=0; i<m; ++i) { delete [] addSort[i]; } delete [] addSort; return res; } int main() { int nSortness = 100; vector<int> seq; int nSeq[] = {0, 13, 0, 0, 12, 0, 0, 0, 2, 0, 0, 10, 5, 0, 0, 0, 0, 0, 0, 7, 15, 16, 20}; /* int nSortness = 5; vector<int> seq; int nSeq[] = {4, 0, 0, 2, 0}; */ seq.assign(nSeq, nSeq+sizeof(nSeq)/sizeof(nSeq[0])); clock_t start_time, end_time; // clock_t start_time = clock(); // Start_Time int ret = ways(nSortness, seq); end_time = clock(); // End_Time printf("Time : %f sec\n", ((double)(end_time-start_time)) / CLOCKS_PER_SEC); printf("ret = %d" , ret); return 0; }
25ca881b5f718a78de5a97cc0918fbb647e80122
de08a8f639b2f42da72bda34ac1236e2413f7cb4
/Components/TextureRenderer.h
283c1362a6e768934a0e3744e07396de54fbdad0
[]
no_license
MartGon/MyEngine
da56754e39efea49d71d86d71aa99043deb209bb
4efd12d4b3f83cdd3c3c824462ce35d34d867d59
refs/heads/master
2020-03-25T17:49:19.287857
2019-07-06T12:56:01
2019-07-06T12:56:01
143,997,815
0
0
null
null
null
null
UTF-8
C++
false
false
1,441
h
#pragma once #include "Component.h" #include "Texture.h" #include <string> #include <deque> #include <optional> struct RenderData { Vector2<float> pos; std::optional<SDL_Point> r_center; double angle; }; class TextureRenderer : public Component { public: TextureRenderer(); TextureRenderer(Texture texture, Uint8 layer = 127); TextureRenderer(const char* path, MapRGB *colorKey = nullptr, Uint8 layer = 127); ~TextureRenderer(); // Attributes Uint8 alpha = 255; Texture texture; std::string tPath; SDL_RendererFlip flip = SDL_FLIP_NONE; SDL_Renderer *renderer = nullptr; // Misc int trail_size = 5; bool hasTrailEffect = false; bool isVanishing = false; int vanish_rate = 1; void setBlink(int framerate, int duration); void unsetBlink(); // Specifications Vector2<float> render_offset; Vector2<float> scale = Vector2<float>(1.f, 1.f); // overridden methods void update() override; void destroy() override; // Own methods void setLayer(Uint8 layer); Uint8 getLayer(); void render(); private: SDL_Point getSDLPointFromVector(Vector2<int> center); // Attributes Uint8 layer = 127; // Misc bool isBlinking = false; int blink_frame_duration = 0; int blink_rate = 2; int blink_frame_count = 0; std::deque<RenderData> trail_pos; // Own methods void vanish(); void blink(); void update_trail(Vector2<float> pos, std::optional<SDL_Point> r_center, double angle); void render_trail(); };
8946097ba33cf4f32dd27838aeb11fa00000755b
02bcaabd21739eadacabaaaf0499f4e679f70779
/src/PositionEnum.hpp
8bef72ade53bc78c7597fa55561ed3690e7a6cb1
[]
no_license
yutkin/UI-MatrixManager
21bcc5f27b4a0f2f17c8cce1bc2e2435ff7e9bb0
09e8c8ca7d4b6209747aeeb6b6f6c6267e08964b
refs/heads/master
2016-09-12T01:17:50.277499
2015-10-08T08:41:18
2015-10-08T08:41:18
43,807,275
0
0
null
null
null
null
UTF-8
C++
false
false
113
hpp
#ifndef POSITIONENUM #define POSITIONENUM enum class Position { Top, Bottom }; #endif // POSITIONENUM
d0e81d040438426e6f05e71186501b2d75bb2407
7a9fb02ada07c5fb03e8b5429c36875abc23dde3
/libraries/ui/src/OffscreenUi.h
d3567bbb5e74e42fcdc6dbc984482920b895b371
[ "Apache-2.0" ]
permissive
KayTHiFi/hifi
130e2f6b874e2ab71446380d44d531004305c153
ffca6a6502c50f82fde48c7c469a39f2e2720608
refs/heads/master
2021-01-21T23:54:07.290870
2015-05-25T23:39:25
2015-05-25T23:39:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,165
h
// // OffscreenUi.h // interface/src/entities // // Created by Bradley Austin Davis on 2015-04-04 // Copyright 2015 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #pragma once #ifndef hifi_OffscreenUi_h #define hifi_OffscreenUi_h #include "OffscreenQmlSurface.h" #include <DependencyManager.h> #define HIFI_QML_DECL \ private: \ static const QString NAME; \ static const QUrl QML; \ public: \ static void registerType(); \ static void show(std::function<void(QQmlContext*, QObject*)> f = [](QQmlContext*, QObject*) {}); \ static void toggle(std::function<void(QQmlContext*, QObject*)> f = [](QQmlContext*, QObject*) {}); \ static void load(std::function<void(QQmlContext*, QObject*)> f = [](QQmlContext*, QObject*) {}); \ private: #define HIFI_QML_DECL_LAMBDA \ protected: \ static const QString NAME; \ static const QUrl QML; \ public: \ static void registerType(); \ static void show(); \ static void toggle(); \ static void load(); \ private: #define HIFI_QML_DEF(x) \ const QUrl x::QML = QUrl(#x ".qml"); \ const QString x::NAME = #x; \ \ void x::registerType() { \ qmlRegisterType<x>("Hifi", 1, 0, NAME.toLocal8Bit().constData()); \ } \ \ void x::show(std::function<void(QQmlContext*, QObject*)> f) { \ auto offscreenUi = DependencyManager::get<OffscreenUi>(); \ offscreenUi->show(QML, NAME, f); \ } \ \ void x::toggle(std::function<void(QQmlContext*, QObject*)> f) { \ auto offscreenUi = DependencyManager::get<OffscreenUi>(); \ offscreenUi->toggle(QML, NAME, f); \ } \ void x::load(std::function<void(QQmlContext*, QObject*)> f) { \ auto offscreenUi = DependencyManager::get<OffscreenUi>(); \ offscreenUi->load(QML, f); \ } #define HIFI_QML_DEF_LAMBDA(x, f) \ const QUrl x::QML = QUrl(#x ".qml"); \ const QString x::NAME = #x; \ \ void x::registerType() { \ qmlRegisterType<x>("Hifi", 1, 0, NAME.toLocal8Bit().constData()); \ } \ void x::show() { \ auto offscreenUi = DependencyManager::get<OffscreenUi>(); \ offscreenUi->show(QML, NAME, f); \ } \ void x::toggle() { \ auto offscreenUi = DependencyManager::get<OffscreenUi>(); \ offscreenUi->toggle(QML, NAME, f); \ } \ void x::load() { \ auto offscreenUi = DependencyManager::get<OffscreenUi>(); \ offscreenUi->load(QML, f); \ } class OffscreenUi : public OffscreenQmlSurface, public Dependency { Q_OBJECT public: OffscreenUi(); virtual ~OffscreenUi(); void show(const QUrl& url, const QString& name, std::function<void(QQmlContext*, QObject*)> f = [](QQmlContext*, QObject*) {}); void toggle(const QUrl& url, const QString& name, std::function<void(QQmlContext*, QObject*)> f = [](QQmlContext*, QObject*) {}); bool shouldSwallowShortcut(QEvent* event); // Messagebox replacement functions using ButtonCallback = std::function<void(QMessageBox::StandardButton)>; static ButtonCallback NO_OP_CALLBACK; static void messageBox(const QString& title, const QString& text, ButtonCallback f, QMessageBox::Icon icon, QMessageBox::StandardButtons buttons); static void information(const QString& title, const QString& text, ButtonCallback callback = NO_OP_CALLBACK, QMessageBox::StandardButtons buttons = QMessageBox::Ok); static void question(const QString& title, const QString& text, ButtonCallback callback = NO_OP_CALLBACK, QMessageBox::StandardButtons buttons = QMessageBox::StandardButtons(QMessageBox::Yes | QMessageBox::No)); static void warning(const QString& title, const QString& text, ButtonCallback callback = NO_OP_CALLBACK, QMessageBox::StandardButtons buttons = QMessageBox::Ok); static void critical(const QString& title, const QString& text, ButtonCallback callback = NO_OP_CALLBACK, QMessageBox::StandardButtons buttons = QMessageBox::Ok); }; #endif
aa550331ccd466d7e8b98f3c519b5c670e9c1b64
e1c6ec3e2357d81addd103efe5ff7f60a2eb4b34
/Code Framework/Components/AND2.h
b2b0f41ac74a94f8ea02a41b130c2643ead66353
[]
no_license
yosefMostafa/logic-C-
aa4be6348e3d151a8773770f50893e179dd2df28
cb301d7b210cf1f3692506d3fc76ba14c4190241
refs/heads/master
2021-07-11T08:49:57.545121
2020-11-29T09:04:46
2020-11-29T09:04:46
224,903,385
0
1
null
null
null
null
UTF-8
C++
false
false
720
h
#ifndef _AND2_H #define _AND2_H /* Class AND2 ----------- represent the 2-input AND gate */ #include "Gate.h" #include<fstream> using namespace std; class AND2:public Gate { public: AND2(GraphicsInfo *r_pGfxInfo, int r_FanOut,bool tf,string s); virtual void Operate(); //Calculates the output of the AND gate virtual void Draw(UI* ); virtual void save(ofstream &data); //Draws 2-input gate virtual int GetOutPinStatus(); //returns status of outputpin if LED, return -1 virtual int GetInputPinStatus(int n); //returns status of Inputpin # n if SWITCH, return -1 virtual int copy(); virtual void setInputPinStatus(int n, STATUS s); //set status of Inputpin # n, to be used by connection class. }; #endif
f134bdb6cff5f5f4b6e1c3c65cb0d001ba478223
2840f3bd7ae7cc6db208475e061a385f7bb63442
/ABC169/f.cpp
ad4041ecf59e1bbb0597c8c0a310d069ccc39df7
[]
no_license
elnath-geek/algorithm
91745c622b51b939cb4e05bcecced092ea4cc0dd
566b3d586e22b56631f96cbbbe543830335a7614
refs/heads/master
2023-02-13T08:37:14.843971
2021-01-09T03:34:39
2021-01-09T03:34:39
284,652,662
0
0
null
null
null
null
UTF-8
C++
false
false
1,770
cpp
#define _USE_MATH_DEFINES #include <iostream> #include <fstream> #include <cstdio> #include <cmath> #include <cstdlib> #include <cstring> #include <cassert> #include <string> #include <vector> #include <utility> #include <complex> #include <set> #include <map> #include <queue> #include <stack> #include <deque> #include <tuple> #include <bitset> #include <limits> #include <algorithm> #include <array> #include <random> #include <complex> #include <regex> #include <iomanip> using namespace std; typedef long double ld; typedef long long ll; typedef vector<int> vint; typedef vector<ll> vll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; #define fcout cout << fixed << setprecision(10) #define rep(i,n) for(int i=0; i<(int)n; i++) #define mp(a,b) make_pair(a,b) #define pb push_back #define all(x) x.begin(), x.end() #define F first #define S second const ll inf = 1e18; const ll mod = 998244353; int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, 1, 0, -1}; // mod. m での a の逆元 a^(-1) を計算する。 ll modinv(ll a, ll m) { ll b = m, u = 1, v = 0; while (b) { ll t = a / b; a -= t * b; swap(a, b); u -= t * v; swap(u, v); } u %= m; if (u < 0) u += m; return u; } ll modpow(ll a, ll n){ ll res = 1; while(n>0){ if(n&1){ res = res * a % mod; } a = a * a % mod; n >>=1; } return res; } int main(){ int n, s; cin >> n >> s; vll a(n); rep(i,n) cin >> a[i]; vector<vll> dp(n+1, vll(s+1, 0)); dp[0][0] = 1; rep(i,n){ rep(j, s+1){ dp[i+1][j] += 2*dp[i][j]; if(j-a[i] >= 0) dp[i+1][j] += dp[i][j-a[i]]; dp[i+1][j] %= mod; } } cout << dp[n][s]%mod << endl; }
d2104dc6c40b8b6d803419e074e0949b794dd168
0bc0903fc444257398798e286d96b3ff3fca2901
/src/common/exceptions/IllegalArgumentException.cpp
eab629de637e9c7dfc924f90f136d5c67fc4f36a
[ "Apache-2.0" ]
permissive
smartdu/kafkaclient-cpp
675bdc7f9ab6a0e7d98511364f85e4932762782b
03d108808a50a13d7a26e63461a1ac27c5bc141c
refs/heads/master
2020-05-18T00:14:17.062934
2019-05-15T03:43:33
2019-05-15T03:43:33
184,055,595
5
1
Apache-2.0
2019-05-13T08:11:57
2019-04-29T11:07:51
C++
UTF-8
C++
false
false
152
cpp
#include "IllegalArgumentException.h" IllegalArgumentException::IllegalArgumentException(std::string message) : ApiException(message.c_str()) { }
9a6d164fc54d0b74513f9acb32ffab85183bf6dd
e8740ea418dd33480cc00660339b787117ac52d1
/cpp/arrays6.cpp
567df37fdc324145ac234d591a93d138ade98a6d
[ "MIT" ]
permissive
lcary/tmp
0361902f1dcf7bd0c2a34dd9a6ad2bfcb11099bd
1ea8e06bc25d13f5be6a0ac578d3302ee2134a77
refs/heads/master
2021-05-15T14:12:02.745296
2017-11-06T23:35:42
2017-11-06T23:35:42
107,182,183
0
0
null
null
null
null
UTF-8
C++
false
false
1,665
cpp
/* attempt to implement a function that resizes a dynamic array. written in a plaintext file. there were multiple compile errors. errors will be notated with ERROR(N) in a comment */ #include <iostream> // ERROR(1): 'newSize' missing type specifier 'int' // ERROR(3): 'int& *arr' was wrong, should be 'int *&arr' void resizeArray(int *&arr, int oldSize, int newSize); // precondition: non-empty array of a given size is passed. // postcondition: array is resized to a new size. int main() { int staticArray[10] = {0, 12, 3, 2, 11, 30, 39, 28, 9, 90}; int *dynamicArray = new int[10]; for (int i = 0; i < 10; i++) { dynamicArray[i] = staticArray[i]; } resizeArray(dynamicArray, 10, 12); dynamicArray[10] = 100; dynamicArray[11] = 0; // does it break for resizing the static array? YES. // arrays6.cpp:25:36: error: cannot bind non-const lvalue reference of type 'int*&' to an rvalue of type 'int*' // resizeArray(staticArray, 10, 12); // ^ // resizeArray(staticArray, 10, 12); return 0; } // ERROR(2): 'newSize' missing type specifier 'int' // ERROR(4): 'int& *arr' was wrong, should be 'int *&arr' void resizeArray(int *&arr, int oldSize, int newSize) { // create a pointer to a temporary array of the new size. // copy all elements from the old array into the new array. // delete the old array on the heap. point its pointer at // the new array. int *temp = new int[newSize]; // ERROR(5) : was originally 'int *temp[newSize];' for (int i = 0; i < oldSize; i++) { temp[i] = arr[i]; } delete [] arr; arr = temp; }
33b28cecaa17a7bcca52d151566bfb300cc870c6
9fbff544471056f0816fa52d1bbf0c4db47c1f24
/leetcode/37.解数独.cpp
dc1d37dcb9307fc57c0f4e1ebc40068f797cff77
[]
no_license
theDreamBear/algorithmn
88d1159fb70e60b5a16bb64673d7383e20dc5fe5
c672d871848a7453ac3ddb8335b1e38d112626ee
refs/heads/master
2023-06-08T15:47:08.368054
2023-06-02T13:00:30
2023-06-02T13:00:30
172,293,806
0
0
null
null
null
null
UTF-8
C++
false
false
3,993
cpp
/* * @lc app=leetcode.cn id=37 lang=cpp * * [37] 解数独 */ #include <iostream> #include <utility> #include <string> #include <string.h> #include <vector> #include <map> #include <set> #include <stack> #include <queue> #include <unordered_map> #include <unordered_set> #include <algorithm> using namespace std; // @lc code=start class Solution { public: /* 这个函数不能写错 */ vector<int> candidateNums(vector<vector<char>> &board, int row, int col) { vector<int> ans; vector<int> used(10); // 行 for (int i = 0; i < board[row].size(); ++i) { if (board[row][i] == '.') { continue; } ++used[board[row][i] - '0']; } // 列 for (int i = 0; i < board.size(); ++i) { if (board[i][col] == '.') { continue; } ++used[board[i][col] - '0']; } // 矩形 int px = row / 3 * 3; int py = col / 3 * 3; for (int i = px; i < 3 + px; ++i) { for (int j = py; j < 3 + py; ++j) { if (board[i][j] == '.') { continue; } ++used[board[i][j] - '0']; } } for (int i = 1; i <= 9; ++i) { if (!used[i]) { ans.push_back(i); } } return ans; } bool solveSudokuHelper(vector<vector<char>> &board, int x, int y, int &leftSpace) { // 出口 if (leftSpace == 0) { return true; } bool found = false; // 找下一个位置 for (int i = y; i < board[x].size(); ++i) { if (board[x][i] == '.') { y = i; found = true; break; } } for (int i = x + 1; i < board.size(); ++i) { if (found) { break; } if (!found) { for (int j = 0; j < board[i].size(); ++j) { if (board[i][j] == '.') { x = i; y = j; found = true; break; } } } } if (!found) { cout << "error"; return false; } // 找后补数字 auto can = candidateNums(board, x, y); // 填错了 if (can.size() == 0) { return false; } // 尝试候补数字 for (int i = 0; i < can.size(); ++i) { board[x][y] = can[i] + '0'; --leftSpace; if (solveSudokuHelper(board, x, y, leftSpace)) { return true; } board[x][y] = '.'; ++leftSpace; } return false; } void solveSudoku(vector<vector<char>> &board) { int leftSpace = 0; for (int i = 0; i < board.size(); ++i) { for (int j = 0; j < board[i].size(); ++j) { if (board[i][j] == '.') { ++leftSpace; } } } solveSudokuHelper(board, 0, 0, leftSpace); } }; // @lc code=end int main() { vector<vector<char>> board = { {'5', '3', '.', '.', '7', '.', '.', '.', '.'}, {'6', '.', '.', '1', '9', '5', '.', '.', '.'}, {'.', '9', '8', '.', '.', '.', '.', '6', '.'}, {'8', '.', '.', '.', '6', '.', '.', '.', '3'}, {'4', '.', '.', '8', '.', '3', '.', '.', '1'}, {'7', '.', '.', '.', '2', '.', '.', '.', '6'}, {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, {'.', '.', '.', '.', '8', '.', '.', '7', '9'}}; Solution{}.solveSudoku(board); for (auto &vec : board) { for (auto &v : vec) { cout << v << "\t"; } cout << endl; } }