text
stringlengths
5
1.04M
#ifndef OPENSTUDIO_RUNAMANAGER_JOBSTATE_HPP #define OPENSTUDIO_RUNAMANAGER_JOBSTATE_HPP #include <QDateTime> #include <boost/optional.hpp> #include "JobErrors.hpp" #include "FileInfo.hpp" #include <utilities/time/DateTime.hpp> namespace openstudio { namespace runmanager { struct JobState { JobState() { } JobState(const boost::optional<DateTime> &t_lastRun, const JobErrors &t_errors, const Files &t_outputFiles, const AdvancedStatus &t_status, const openstudio::path &t_outdir) : lastRun(t_lastRun ? toQDateTime(*t_lastRun) : boost::optional<QDateTime>()), errors(t_errors), outputFiles(t_outputFiles), status(t_status), outdir(t_outdir) { } boost::optional<QDateTime> lastRun; JobErrors errors; Files outputFiles; AdvancedStatus status; openstudio::path outdir; }; } } #endif
#include <testcase.hpp> #include "testcase.pb.h" int main(int c, char *argv[]) { TestInt32::Test msg; msg.set_i(0); write_to_file(msg, "data-zero.pbf"); msg.set_i(1); write_to_file(msg, "data-pos.pbf"); msg.set_i(200); write_to_file(msg, "data-pos200.pbf"); msg.set_i(-1); write_to_file(msg, "data-neg.pbf"); msg.set_i(-200); write_to_file(msg, "data-neg200.pbf"); msg.set_i(std::numeric_limits<int32_t>::max()); write_to_file(msg, "data-max.pbf"); msg.set_i(std::numeric_limits<int32_t>::min()); write_to_file(msg, "data-min.pbf"); }
#using <System.dll> #using <System.Windows.Forms.dll> #using <System.Drawing.dll> using namespace System; using namespace System::Drawing; using namespace System::Windows::Forms; public ref class Form1: public System::Windows::Forms::Form { public: Form1() : Form() { //This call is required by the Windows Form Designer. InitializeComponent(); InitializeRadioButtonsAndGroupBox(); this->RadioButton1->CheckedChanged += gcnew EventHandler( this,&Form1::RadioButton_CheckedChanged ); this->RadioButton2->CheckedChanged += gcnew EventHandler( this,&Form1::RadioButton_CheckedChanged ); this->RadioButton3->CheckedChanged += gcnew EventHandler( this,&Form1::RadioButton_CheckedChanged ); //Add any initialization after the InitializeComponent() call } protected: ~Form1() { if ( components != nullptr ) { delete components; } } private: //Required by the Windows Form Designer System::ComponentModel::IContainer^ components; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System::Diagnostics::DebuggerStepThrough] void InitializeComponent() { //Form1 // this->ClientSize = System::Drawing::Size( 292, 266 ); this->Name = "Form1"; this->Text = "Form1"; this->ResumeLayout( false ); } //<snippet1> //<snippet2> internal: System::Windows::Forms::GroupBox^ GroupBox1; System::Windows::Forms::RadioButton^ RadioButton1; System::Windows::Forms::RadioButton^ RadioButton2; System::Windows::Forms::RadioButton^ RadioButton3; private: void InitializeRadioButtonsAndGroupBox() { // Construct the GroupBox object. this->GroupBox1 = gcnew GroupBox; // Construct the radio buttons. this->RadioButton1 = gcnew System::Windows::Forms::RadioButton; this->RadioButton2 = gcnew System::Windows::Forms::RadioButton; this->RadioButton3 = gcnew System::Windows::Forms::RadioButton; // Set the location, tab and text for each radio button // to a cursor from the Cursors enumeration. this->RadioButton1->Location = System::Drawing::Point( 24, 24 ); this->RadioButton1->TabIndex = 0; this->RadioButton1->Text = "Help"; this->RadioButton1->Tag = Cursors::Help; this->RadioButton1->TextAlign = ContentAlignment::MiddleCenter; this->RadioButton2->Location = System::Drawing::Point( 24, 56 ); this->RadioButton2->TabIndex = 1; this->RadioButton2->Text = "Up Arrow"; this->RadioButton2->Tag = Cursors::UpArrow; this->RadioButton2->TextAlign = ContentAlignment::MiddleCenter; this->RadioButton3->Location = System::Drawing::Point( 24, 80 ); this->RadioButton3->TabIndex = 3; this->RadioButton3->Text = "Cross"; this->RadioButton3->Tag = Cursors::Cross; this->RadioButton3->TextAlign = ContentAlignment::MiddleCenter; // Add the radio buttons to the GroupBox. this->GroupBox1->Controls->Add( this->RadioButton1 ); this->GroupBox1->Controls->Add( this->RadioButton2 ); this->GroupBox1->Controls->Add( this->RadioButton3 ); // Set the location of the GroupBox. this->GroupBox1->Location = System::Drawing::Point( 56, 64 ); this->GroupBox1->Size = System::Drawing::Size( 200, 150 ); // Set the text that will appear on the GroupBox. this->GroupBox1->Text = "Choose a Cursor Style"; // // Add the GroupBox to the form. this->Controls->Add( this->GroupBox1 ); // } // </snippet1> void RadioButton_CheckedChanged( Object^ sender, EventArgs^ /*e*/ ) { // Cast the sender back to a RadioButton object. RadioButton^ selectedRadioButton = dynamic_cast<RadioButton^>(sender); // If the radio button is in a checked state, then // change the cursor. if ( selectedRadioButton->Checked ) { this->Cursor = dynamic_cast<System::Windows::Forms::Cursor^>(selectedRadioButton->Tag); } } //</snippet2> }; int main() { Application::Run( gcnew Form1 ); }
/* * Copyright (C) 2018 Yusuke Suzuki <yusukesuzuki@slowstart.org>. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "PerfLog.h" #if ENABLE(ASSEMBLER) && OS(LINUX) #include <array> #include <elf.h> #include <fcntl.h> #include <mutex> #include <sys/mman.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/types.h> #include <unistd.h> #include <wtf/DataLog.h> #include <wtf/MonotonicTime.h> #include <wtf/PageBlock.h> #include <wtf/ProcessID.h> namespace JSC { namespace PerfLogInternal { static constexpr bool verbose = false; } // namespace PerfLogInternal namespace JITDump { namespace Constants { // Perf jit-dump formats are specified here. // https://raw.githubusercontent.com/torvalds/linux/master/tools/perf/Documentation/jitdump-specification.txt // The latest version 2, but it is too new at that time. static constexpr uint32_t version = 1; #if CPU(LITTLE_ENDIAN) static constexpr uint32_t magic = 0x4a695444; #else static constexpr uint32_t magic = 0x4454694a; #endif #if CPU(X86) static constexpr uint32_t elfMachine = EM_386; #elif CPU(X86_64) static constexpr uint32_t elfMachine = EM_X86_64; #elif CPU(ARM64) static constexpr uint32_t elfMachine = EM_AARCH64; #elif CPU(ARM) static constexpr uint32_t elfMachine = EM_ARM; #elif CPU(MIPS) #if CPU(LITTLE_ENDIAN) static constexpr uint32_t elfMachine = EM_MIPS_RS3_LE; #else static constexpr uint32_t elfMachine = EM_MIPS; #endif #endif } // namespace Constants struct FileHeader { uint32_t magic { Constants::magic }; uint32_t version { Constants::version }; uint32_t totalSize { sizeof(FileHeader) }; uint32_t elfMachine { Constants::elfMachine }; uint32_t padding1 { 0 }; uint32_t pid { 0 }; uint64_t timestamp { 0 }; uint64_t flags { 0 }; }; enum class RecordType : uint32_t { JITCodeLoad = 0, JITCodeMove = 1, JITCodeDebugInfo = 2, JITCodeClose = 3, JITCodeUnwindingInfo = 4, }; struct RecordHeader { RecordType type { RecordType::JITCodeLoad }; uint32_t totalSize { 0 }; uint64_t timestamp { 0 }; }; struct CodeLoadRecord { RecordHeader header { RecordType::JITCodeLoad, 0, 0, }; uint32_t pid { 0 }; uint32_t tid { 0 }; uint64_t vma { 0 }; uint64_t codeAddress { 0 }; uint64_t codeSize { 0 }; uint64_t codeIndex { 0 }; }; } // namespace JITDump PerfLog& PerfLog::singleton() { static PerfLog* logger; static std::once_flag onceKey; std::call_once(onceKey, [] { logger = new PerfLog; }); return *logger; } static inline uint64_t generateTimestamp() { return MonotonicTime::now().secondsSinceEpoch().nanosecondsAs<uint64_t>(); } static inline pid_t getCurrentThreadID() { return static_cast<pid_t>(syscall(__NR_gettid)); } PerfLog::PerfLog() { { std::array<char, 1024> filename; snprintf(filename.data(), filename.size() - 1, "jit-%d.dump", getCurrentProcessID()); filename[filename.size() - 1] = '\0'; m_fd = open(filename.data(), O_CREAT | O_TRUNC | O_RDWR, 0666); RELEASE_ASSERT(m_fd != -1); // Linux perf command records this mmap operation in perf.data as a metadata to the JIT perf annotations. // We do not use this mmap-ed memory region actually. m_marker = mmap(nullptr, pageSize(), PROT_READ | PROT_EXEC, MAP_PRIVATE, m_fd, 0); RELEASE_ASSERT(m_marker != MAP_FAILED); m_file = fdopen(m_fd, "wb"); RELEASE_ASSERT(m_file); } JITDump::FileHeader header; header.timestamp = generateTimestamp(); header.pid = getCurrentProcessID(); auto locker = holdLock(m_lock); write(locker, &header, sizeof(JITDump::FileHeader)); flush(locker); } void PerfLog::write(const AbstractLocker&, const void* data, size_t size) { size_t result = fwrite(data, 1, size, m_file); RELEASE_ASSERT(result == size); } void PerfLog::flush(const AbstractLocker&) { fflush(m_file); } void PerfLog::log(CString&& name, const uint8_t* executableAddress, size_t size) { if (!size) { dataLogLnIf(PerfLogInternal::verbose, "0 size record ", name, " ", RawPointer(executableAddress)); return; } PerfLog& logger = singleton(); auto locker = holdLock(logger.m_lock); JITDump::CodeLoadRecord record; record.header.timestamp = generateTimestamp(); record.header.totalSize = sizeof(JITDump::CodeLoadRecord) + (name.length() + 1) + size; record.pid = getCurrentProcessID(); record.tid = getCurrentThreadID(); record.vma = bitwise_cast<uintptr_t>(executableAddress); record.codeAddress = bitwise_cast<uintptr_t>(executableAddress); record.codeSize = size; record.codeIndex = logger.m_codeIndex++; logger.write(locker, &record, sizeof(JITDump::CodeLoadRecord)); logger.write(locker, name.data(), name.length() + 1); logger.write(locker, executableAddress, size); logger.flush(locker); dataLogLnIf(PerfLogInternal::verbose, name, " [", record.codeIndex, "] ", RawPointer(executableAddress), "-", RawPointer(executableAddress + size), " ", size); } } // namespace JSC #endif // ENABLE(ASSEMBLER) && OS(LINUX)
/** \file * \author Max Mertens <max.mail@dameweb.de> * \section LICENSE * Copyright (c) 2014, Max Mertens. * All rights reserved. * This file is licensed under the "BSD 3-Clause License". * Full license text is under the file "LICENSE" provided with this code. */ #ifndef _VERSION_HPP_ #define _VERSION_HPP_ #ifndef VERSION #define VERSION unknown #endif /*VERSION*/ #define TOSTR2(x) #x #define TOSTR(x) TOSTR2(x) #define VERSION_STR TOSTR(VERSION) #endif /*_VERSION_HPP_*/
/* Copyright 2018 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. ==============================================================================*/ #include <algorithm> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/container/inlined_vector.h" #include "third_party/eigen3/Eigen/Core" #include "tensorflow/compiler/tf2xla/xla_helpers.h" #include "tensorflow/compiler/tf2xla/xla_op_kernel.h" #include "tensorflow/compiler/tf2xla/xla_op_registry.h" #include "tensorflow/compiler/xla/client/lib/constants.h" #include "tensorflow/compiler/xla/client/lib/matrix.h" #include "tensorflow/compiler/xla/client/xla_builder.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/framework/types.pb.h" #include "tensorflow/core/platform/errors.h" #include "tensorflow/core/platform/macros.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { namespace { // Calculates the diagonal length of a diagonal. static inline int ComputeDiagLen(int diag_index, int num_rows, int num_cols) { return std::min(num_rows + std::min(0, diag_index), num_cols - std::max(0, diag_index)); } // Checks if a diagonal is to be aligned left or right. static inline bool IsLeftAligned(int diag_index, bool left_align_superdiagonal, bool left_align_subdiagonal) { return (diag_index >= 0 && left_align_superdiagonal) || (diag_index <= 0 && left_align_subdiagonal); } // Reads the diagonal packing alignment. void ReadAlignment(OpKernelConstruction* context, bool* left_align_superdiagonal, bool* left_align_subdiagonal) { string align; OP_REQUIRES_OK(context, context->GetAttr("align", &align)); *left_align_superdiagonal = align == "LEFT_LEFT" || align == "LEFT_RIGHT"; *left_align_subdiagonal = align == "LEFT_LEFT" || align == "RIGHT_LEFT"; } // Reads or infers lower_diag_index and upper_diag_index from kernel's input // parameter "k". Also validates their values. std::pair<int64, int64> ProcessDiagIndex(XlaOpKernelContext* context) { int64 lower_diag_index = 0; int64 upper_diag_index = 0; TensorShape diag_index_shape = context->InputShape("k"); // Wrapping OP_REQUIRES* macros with a function because they can "return;" // early (without values) which contradicts ProcessDiagIndex's signature. auto validate_diag_indices = [&]() { if (diag_index_shape.dims() == 0) { OP_REQUIRES_OK(context, context->ConstantInputAsIntScalar("k", &lower_diag_index)); upper_diag_index = lower_diag_index; } else { std::vector<int64> diag_index; OP_REQUIRES_OK(context, context->ConstantInputAsIntVector("k", &diag_index)); OP_REQUIRES( context, !diag_index.empty() && diag_index.size() <= 2, errors::InvalidArgument( "diag_index must have only one or two elements, received ", diag_index.size(), " elements.")); lower_diag_index = diag_index[0]; upper_diag_index = (diag_index.size() > 1) ? diag_index[1] : lower_diag_index; } OP_REQUIRES( context, lower_diag_index <= upper_diag_index, errors::InvalidArgument( "lower_diag_index must not be larger than upper_diag_index: ", lower_diag_index, " > ", upper_diag_index)); }; validate_diag_indices(); return {lower_diag_index, upper_diag_index}; } // Makes sure lower_diag_index and upper_diag_index are consistent with the // input matrix size. void ValidateDiagIndexWithOutputMatrixSize(XlaOpKernelContext* context, const int64 lower_diag_index, const int64 upper_diag_index, const int64 num_rows, const int64 num_cols) { // `lower_diag_index == 0` condition is added to handle matrix shape = 0. OP_REQUIRES(context, (-num_rows < lower_diag_index && lower_diag_index < num_cols) || lower_diag_index == 0, errors::InvalidArgument( "lower_diag_index is out of bound: ", lower_diag_index, " It must be between ", -num_rows, " and ", num_cols)); OP_REQUIRES(context, (-num_rows < upper_diag_index && upper_diag_index < num_cols) || upper_diag_index == 0, errors::InvalidArgument( "upper_diag_index is out of bound: ", upper_diag_index, " It must be between ", -num_rows, " and ", num_cols)); OP_REQUIRES(context, lower_diag_index <= upper_diag_index, errors::InvalidArgument( "lower_diag_index must not be larger than upper_diag_index: ", lower_diag_index, " > ", upper_diag_index)); } // Kernel to set matrix diagonals. xla::XlaOp SetMatrixDiag(const xla::XlaOp input, const xla::XlaOp diag, const TensorShape& input_shape, const int64 diag_rank, const int64 num_diags, const int64 lower_diag_index, const int64 upper_diag_index, const int64 max_diag_len, const int64 num_rows, const int64 num_cols, const bool left_align_superdiagonal, const bool left_align_subdiagonal) { // Creates a padding config. const int input_rank = input_shape.dims(); xla::PaddingConfig padding_config; padding_config = xla::MakeNoPaddingConfig(input_rank - 1); // Processes one diagonal at a time: // 1) Extracts a single diagonal (diag_slice). // 2) Broadcasts its contents to fill the whole matrix (diag_broadcast). // 3) Masks diag_broadcast to get the right diagonal shape. // // XLA can fuse multiple Broadcasts and Selects so this shouldn't be slow. // // For example, // diag = [[0, 2, 3], k = (-1, 1), num_cols = 4, and align="RIGHT_LEFT". // [4, 5, 6], // [7, 8, 9]] // The expected output is [[7, 4, 2, 0], // [0, 8, 5, 3], // [0, 0, 9, 6]]. // The 1st diagonal is created by: // 1) Extracting diag_slice = [0, 2, 3] which is right-aligned. // 2) Padding the vector (in the same direction) to be as long as num_cols, // diag_slice = [0, 0, 2, 3], // then broadcasting diag_slice column-wise to a full matrix, // diag_broadcast = [[0, 0, 2, 3], // [0, 0, 2, 3], // [0, 0, 2, 3]]. // The padding value can be anything because it will not appear in the // results after masking. Here, we use zero. // 3) Masking diag_broadcast with a mask of the shape of the 1st diagonal. // mask = [[0, 0, 1, 0], --> output = [[x, x, 2, x], // [0, 0, 0, 1], [x, x, x, 3], // [0, 0, 0, 0]] [x, x, x, x]], // where x denotes the existing input contents. std::vector<int64> broadcast_dimensions(input_rank - 1); absl::c_iota(broadcast_dimensions, 0); auto output = input; for (int64 diag_index = lower_diag_index; diag_index <= upper_diag_index; ++diag_index) { // Extracts a single diagonal. auto diag_slice = diag; if (num_diags > 1) { // The result of SliceInDim has dims: [<batch_dim>, 1, max_diag_len]. // We call Collapse to make the dims: [<batch_dim>, max_diag_len]. const int64 mapped_diag_index = upper_diag_index - diag_index; diag_slice = xla::Collapse( xla::SliceInDim(diag, mapped_diag_index, mapped_diag_index + 1, 1, diag_rank - 2), {diag_rank - 2, diag_rank - 1}); } // Pad if necessary. // - If the diagonal has the longest length, i.e., min(num_rows, num_cols), // no padding is necessary. It is broadcast column-wise if it is a sub- // diagonal, row-wise if superdiagonal. // - Otherwise, pad and keep the old alignment (shorter diagonals in the // input come pre-padded). max_len in the table refers to max_diag_len. // ------------------------------------------------------------------- // | Diag | Align | Broadcast | padding_low | padding_high | // ------------------------------------------------------------------- // | Super | Left | Row-wise | 0 | #rows - max_len | // | | Right | Column-wise | #cols - max_len | 0 | // ------------------------------------------------------------------- // | Sub | Left | Column-wise | 0 | #cols - max_len | // | | Right | Row-wise | #rows - max_len | 0 | // ------------------------------------------------------------------- if (num_cols - num_rows <= diag_index && diag_index <= 0) { broadcast_dimensions.back() = input_rank - 1; // Column-wise. } else if (0 <= diag_index && diag_index <= num_cols - num_rows) { broadcast_dimensions.back() = input_rank - 2; // Row-wise. } else { int length_to_pad_to; if ((diag_index > 0 && left_align_superdiagonal) || (diag_index < 0 && !left_align_subdiagonal)) { length_to_pad_to = num_rows; broadcast_dimensions.back() = input_rank - 2; // Row-wise. } else { length_to_pad_to = num_cols; broadcast_dimensions.back() = input_rank - 1; // Column-wise. } int padding_low = length_to_pad_to - max_diag_len; int padding_high = 0; if (IsLeftAligned(diag_index, left_align_superdiagonal, left_align_subdiagonal)) { std::swap(padding_low, padding_high); } padding_config.mutable_dimensions(input_rank - 2) ->set_edge_padding_low(padding_low); padding_config.mutable_dimensions(input_rank - 2) ->set_edge_padding_high(padding_high); const xla::XlaOp zero = xla::ScalarLike(input, 0); diag_slice = xla::Pad(diag_slice, zero, padding_config); } // Broadcast and mask. xla::XlaOp diag_broadcast = xla::BroadcastInDim( diag_slice, input_shape.dim_sizes(), broadcast_dimensions); const auto mask = xla::GetDiagonalMask(output, diag_index); output = xla::Select(mask, diag_broadcast, output); } return output; } } // namespace class MatrixDiagOp : public XlaOpKernel { public: explicit MatrixDiagOp(OpKernelConstruction* context) : XlaOpKernel(context) { // MatrixDiagV3-specific. if (context->HasAttr("align")) { ReadAlignment(context, &left_align_superdiagonal_, &left_align_subdiagonal_); } } void Compile(XlaOpKernelContext* context) override { OP_REQUIRES( context, context->num_inputs() >= kNumV1Inputs, errors::InvalidArgument("MatrixDiag op must have at least one input")); const TensorShape diag_shape = context->InputShape(0); OP_REQUIRES(context, TensorShapeUtils::IsVectorOrHigher(diag_shape), errors::InvalidArgument("Expected >= 1 dims, got shape ", diag_shape.DebugString())); const DataType dtype = context->expected_output_dtype(0); const xla::XlaOp zero = XlaHelpers::Zero(context->builder(), dtype); // Initializes MatrixDiagV2-specific variables. // Input arguments providing the values of num_rows and num_cols can be // absent (-1) and will be inferred later. int64 lower_diag_index = 0; int64 upper_diag_index = 0; int64 num_rows = -1; int64 num_cols = -1; xla::XlaOp padding_value = zero; // MatrixDiag and MatrixDiagV2 both use this OpKernel. MatrixDiag only has // one input, so we have to check the number of inputs before reading // additional parameters for MatrixDiagV2. if (context->num_inputs() > kNumV1Inputs) { std::tie(lower_diag_index, upper_diag_index) = ProcessDiagIndex(context); OP_REQUIRES_OK(context, context->ConstantInputAsIntScalar(2, &num_rows)); OP_REQUIRES_OK(context, context->ConstantInputAsIntScalar(3, &num_cols)); padding_value = context->Input(4); } // More size validations. const int64 diag_rank = diag_shape.dims(); const int64 max_diag_len = diag_shape.dim_size(diag_rank - 1); const int64 num_diags = upper_diag_index - lower_diag_index + 1; OP_REQUIRES( context, num_diags == 1 || num_diags == diag_shape.dim_size(diag_rank - 2), errors::InvalidArgument( "The number of diagonals provided in the input does not " "match the lower_diag_index and upper_diag_index range.")); const int64 min_num_rows = max_diag_len - std::min(upper_diag_index, int64{0}); const int64 min_num_cols = max_diag_len + std::max(lower_diag_index, int64{0}); OP_REQUIRES(context, num_rows == -1 || num_rows >= min_num_rows, errors::InvalidArgument("The number of rows is too small.")); OP_REQUIRES(context, num_cols == -1 || num_cols >= min_num_cols, errors::InvalidArgument("The number of columns is too small.")); // Infers num_rows and num_cols. If both are unknown, assume that the output // is square. Otherwise, use smallest possible values. if (num_rows == -1 && num_cols == -1) { num_rows = std::max(min_num_rows, min_num_cols); num_cols = num_rows; } else if (num_rows == -1) { num_rows = min_num_rows; } else if (num_cols == -1) { num_cols = min_num_cols; } // At least one of num_rows and num_cols must match its minimum length. // Otherwise, we'll have some incomplete diagonals. OP_REQUIRES(context, num_rows == min_num_rows || num_cols == min_num_cols, errors::InvalidArgument( "The number of rows or columns is not consistent with " "the specified d_lower, d_upper, and diagonal.")); // Actual processing. // Initializes the output tensor with padding_value. TensorShape output_shape = diag_shape; output_shape.RemoveLastDims((num_diags == 1) ? 1 : 2); output_shape.AddDim(num_rows); output_shape.AddDim(num_cols); xla::XlaOp output = xla::Broadcast(padding_value, output_shape.dim_sizes()); xla::XlaOp diag = context->Input(0); context->SetOutput( 0, SetMatrixDiag(output, diag, output_shape, diag_rank, num_diags, lower_diag_index, upper_diag_index, max_diag_len, num_rows, num_cols, left_align_superdiagonal_, left_align_subdiagonal_)); } private: bool left_align_superdiagonal_ = true; bool left_align_subdiagonal_ = true; static constexpr int kNumV1Inputs = 1; }; REGISTER_XLA_OP(Name("MatrixDiag"), MatrixDiagOp); REGISTER_XLA_OP(Name("MatrixDiagV2") .CompileTimeConstantInput("k") .CompileTimeConstantInput("num_rows") .CompileTimeConstantInput("num_cols") .CompileTimeConstantInput("padding_value"), MatrixDiagOp); REGISTER_XLA_OP(Name("MatrixDiagV3") .CompileTimeConstantInput("k") .CompileTimeConstantInput("num_rows") .CompileTimeConstantInput("num_cols") .CompileTimeConstantInput("padding_value"), MatrixDiagOp); class MatrixDiagPartOp : public XlaOpKernel { public: explicit MatrixDiagPartOp(OpKernelConstruction* context) : XlaOpKernel(context), is_gpu_(context->device_type().type_string() == DEVICE_GPU_XLA_JIT) { // MatrixDiagPartV3-specific. if (context->HasAttr("align")) { ReadAlignment(context, &left_align_superdiagonal_, &left_align_subdiagonal_); } } void Compile(XlaOpKernelContext* context) override { const TensorShape input_shape = context->InputShape(0); const int input_rank = input_shape.dims(); OP_REQUIRES(context, TensorShapeUtils::IsMatrixOrHigher(input_shape), errors::InvalidArgument( "input must be at least 2-dim, received shape: ", input_shape.DebugString())); const DataType dtype = context->expected_output_dtype(0); const xla::XlaOp zero = XlaHelpers::Zero(context->builder(), dtype); // Initializes MatrixDiagPartV2-specific variables. int64 lower_diag_index = 0; int64 upper_diag_index = 0; xla::XlaOp padding_value = zero; // MatrixDiagPart and MatrixDiagPartV2 both use this OpKernel. // MatrixDiagPart only has one input, so we have to check the number of // inputs before reading additional parameters in MatrixDiagV2. if (context->num_inputs() > kNumV1Inputs) { std::tie(lower_diag_index, upper_diag_index) = ProcessDiagIndex(context); padding_value = context->Input(2); } // Checks if diag sizes are consistent with input. const int64 num_rows = input_shape.dim_size(input_rank - 2); const int64 num_cols = input_shape.dim_size(input_rank - 1); ValidateDiagIndexWithOutputMatrixSize(context, lower_diag_index, upper_diag_index, num_rows, num_cols); // Creates output shape. TensorShape output_shape = input_shape; output_shape.RemoveLastDims(2); const int num_diags = upper_diag_index - lower_diag_index + 1; if (num_diags > 1) output_shape.AddDim(num_diags); const int32 max_diag_len = std::min(num_rows + std::min(upper_diag_index, int64{0}), num_cols - std::max(lower_diag_index, int64{0})); output_shape.AddDim(max_diag_len); // Computes output. xla::XlaOp input = context->Input(0); std::vector<xla::XlaOp> diag_list; xla::PaddingConfig padding_config = xla::MakeNoPaddingConfig(input_rank - 1); if (num_diags == 1) { context->SetOutput( 0, is_gpu_ ? xla::GetMatrixDiagonalViaGather(input, upper_diag_index) : xla::GetMatrixDiagonal(input, upper_diag_index)); return; } for (int diag_index = upper_diag_index; diag_index >= lower_diag_index; --diag_index) { xla::XlaOp single_diag = is_gpu_ ? xla::GetMatrixDiagonalViaGather(input, diag_index) : xla::GetMatrixDiagonal(input, diag_index); const int64 diag_len = ComputeDiagLen(diag_index, num_rows, num_cols); const int64 padding_len = max_diag_len - diag_len; if (padding_len > 0) { if (IsLeftAligned(diag_index, left_align_superdiagonal_, left_align_subdiagonal_)) { padding_config.mutable_dimensions(input_rank - 2) ->set_edge_padding_low(0); padding_config.mutable_dimensions(input_rank - 2) ->set_edge_padding_high(padding_len); } else { padding_config.mutable_dimensions(input_rank - 2) ->set_edge_padding_low(padding_len); padding_config.mutable_dimensions(input_rank - 2) ->set_edge_padding_high(0); } single_diag = xla::Pad(single_diag, padding_value, padding_config); } diag_list.emplace_back(single_diag); } auto concat = xla::ConcatInDim(context->builder(), diag_list, input_rank - 2); context->SetOutput(0, xla::Reshape(concat, output_shape.dim_sizes())); } private: const bool is_gpu_; bool left_align_superdiagonal_ = true; bool left_align_subdiagonal_ = true; static constexpr int kNumV1Inputs = 1; }; REGISTER_XLA_OP(Name("MatrixDiagPart"), MatrixDiagPartOp); REGISTER_XLA_OP(Name("MatrixDiagPartV2") .CompileTimeConstantInput("k") .CompileTimeConstantInput("padding_value"), MatrixDiagPartOp); REGISTER_XLA_OP(Name("MatrixDiagPartV3") .CompileTimeConstantInput("k") .CompileTimeConstantInput("padding_value"), MatrixDiagPartOp); class MatrixSetDiagOp : public XlaOpKernel { public: explicit MatrixSetDiagOp(OpKernelConstruction* context) : XlaOpKernel(context) { // MatrixSetDiagV3-specific. if (context->HasAttr("align")) { ReadAlignment(context, &left_align_superdiagonal_, &left_align_subdiagonal_); } } void Compile(XlaOpKernelContext* context) override { const TensorShape input_shape = context->InputShape(0); const TensorShape diag_shape = context->InputShape(1); const int input_rank = input_shape.dims(); const int diag_rank = diag_shape.dims(); // Preliminary validation of sizes. OP_REQUIRES(context, TensorShapeUtils::IsMatrixOrHigher(input_shape), errors::InvalidArgument( "input must be at least 2-dim, received shape: ", input_shape.DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsVectorOrHigher(diag_shape), errors::InvalidArgument( "diagonal must be at least 1-dim, received shape: ", diag_shape.DebugString())); // MatrixSetDiag and MatrixSetDiagV2 both use this OpKernel. MatrixSetDiag // only has two inputs, so we have to check the number of inputs before // reading additional parameters in MatrixSetDiagV2. int64 lower_diag_index = 0; int64 upper_diag_index = 0; if (context->num_inputs() > kNumV1Inputs) { std::tie(lower_diag_index, upper_diag_index) = ProcessDiagIndex(context); } // Checks if diag sizes are consistent with input. const int64 num_rows = input_shape.dim_size(input_rank - 2); const int64 num_cols = input_shape.dim_size(input_rank - 1); ValidateDiagIndexWithOutputMatrixSize(context, lower_diag_index, upper_diag_index, num_rows, num_cols); const Eigen::Index num_diags = upper_diag_index - lower_diag_index + 1; OP_REQUIRES( context, lower_diag_index == upper_diag_index || (diag_shape.dim_size(input_rank - 2) == num_diags), errors::InvalidArgument("The number of diagonals provided in `diag` " "is not consistent with `lower_diag_index` and " "`upper_diag_index`")); TensorShape expected_diag_shape = input_shape; expected_diag_shape.RemoveLastDims(2); if (num_diags > 1) expected_diag_shape.AddDim(num_diags); const int32 max_diag_len = std::min(num_rows + std::min(upper_diag_index, int64{0}), num_cols - std::max(lower_diag_index, int64{0})); expected_diag_shape.AddDim(max_diag_len); OP_REQUIRES( context, expected_diag_shape == diag_shape, errors::InvalidArgument( "Either first dimensions of diagonal don't match input.shape[:-2], " "or diagonal.shape[:-1] is not equal to the longests diagonal in " "range [lower_diag_index:upper_diag_index].\nInput shape: ", input_shape.DebugString(), "\nDiagonal shape: ", diag_shape.DebugString(), "\nExpected diagonal shape: ", expected_diag_shape.DebugString())); // Actual processing. xla::XlaOp input = context->Input(0); xla::XlaOp diag = context->Input(1); context->SetOutput( 0, SetMatrixDiag(input, diag, input_shape, diag_rank, num_diags, lower_diag_index, upper_diag_index, max_diag_len, num_rows, num_cols, left_align_superdiagonal_, left_align_subdiagonal_)); } private: bool left_align_superdiagonal_ = true; bool left_align_subdiagonal_ = true; static constexpr int kNumV1Inputs = 2; TF_DISALLOW_COPY_AND_ASSIGN(MatrixSetDiagOp); }; REGISTER_XLA_OP(Name("MatrixSetDiag"), MatrixSetDiagOp); REGISTER_XLA_OP(Name("MatrixSetDiagV2").CompileTimeConstantInput("k"), MatrixSetDiagOp); REGISTER_XLA_OP(Name("MatrixSetDiagV3").CompileTimeConstantInput("k"), MatrixSetDiagOp); } // namespace tensorflow
/**************************************************************************** * * (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include "APMParameterMetaData.h" #include "QGCApplication.h" #include "QGCLoggingCategory.h" #include <QFile> #include <QFileInfo> #include <QDir> #include <QDebug> #include <QStack> static const char* kInvalidConverstion = "Internal Error: No support for string parameters"; QGC_LOGGING_CATEGORY(APMParameterMetaDataLog, "APMParameterMetaDataLog") QGC_LOGGING_CATEGORY(APMParameterMetaDataVerboseLog, "APMParameterMetaDataVerboseLog") APMParameterMetaData::APMParameterMetaData(void) : _parameterMetaDataLoaded(false) { } /// Converts a string to a typed QVariant /// @param string String to convert /// @param type Type for Fact which dictates the QVariant type as well /// @param convertOk Returned: true: conversion success, false: conversion failure /// @return Returns the correctly type QVariant QVariant APMParameterMetaData::_stringToTypedVariant(const QString& string, FactMetaData::ValueType_t type, bool* convertOk) { QVariant var(string); int convertTo = QVariant::Int; // keep compiler warning happy switch (type) { case FactMetaData::valueTypeUint8: case FactMetaData::valueTypeUint16: case FactMetaData::valueTypeUint32: convertTo = QVariant::UInt; break; case FactMetaData::valueTypeInt8: case FactMetaData::valueTypeInt16: case FactMetaData::valueTypeInt32: convertTo = QVariant::Int; break; case FactMetaData::valueTypeFloat: convertTo = QMetaType::Float; break; case FactMetaData::valueTypeElapsedTimeInSeconds: case FactMetaData::valueTypeDouble: convertTo = QVariant::Double; break; case FactMetaData::valueTypeString: qWarning() << kInvalidConverstion; convertTo = QVariant::String; break; case FactMetaData::valueTypeBool: qWarning() << kInvalidConverstion; convertTo = QVariant::Bool; break; case FactMetaData::valueTypeCustom: qWarning() << kInvalidConverstion; convertTo = QVariant::ByteArray; break; } *convertOk = var.convert(convertTo); return var; } QString APMParameterMetaData::mavTypeToString(MAV_TYPE vehicleTypeEnum) { QString vehicleName; switch(vehicleTypeEnum) { case MAV_TYPE_FIXED_WING: case MAV_TYPE_VTOL_DUOROTOR: case MAV_TYPE_VTOL_QUADROTOR: case MAV_TYPE_VTOL_TILTROTOR: case MAV_TYPE_VTOL_RESERVED2: case MAV_TYPE_VTOL_RESERVED3: case MAV_TYPE_VTOL_RESERVED4: case MAV_TYPE_VTOL_RESERVED5: vehicleName = "ArduPlane"; break; case MAV_TYPE_QUADROTOR: case MAV_TYPE_COAXIAL: case MAV_TYPE_HELICOPTER: case MAV_TYPE_HEXAROTOR: case MAV_TYPE_OCTOROTOR: case MAV_TYPE_TRICOPTER: vehicleName = "ArduCopter"; break; case MAV_TYPE_ANTENNA_TRACKER: vehicleName = "Antenna Tracker"; case MAV_TYPE_GENERIC: case MAV_TYPE_GCS: case MAV_TYPE_AIRSHIP: case MAV_TYPE_FREE_BALLOON: case MAV_TYPE_ROCKET: break; case MAV_TYPE_GROUND_ROVER: case MAV_TYPE_SURFACE_BOAT: vehicleName = "APMrover2"; break; case MAV_TYPE_SUBMARINE: vehicleName = "ArduSub"; break; case MAV_TYPE_FLAPPING_WING: case MAV_TYPE_KITE: case MAV_TYPE_ONBOARD_CONTROLLER: case MAV_TYPE_GIMBAL: case MAV_TYPE_ENUM_END: default: break; } return vehicleName; } void APMParameterMetaData::loadParameterFactMetaDataFile(const QString& metaDataFile) { if (_parameterMetaDataLoaded) { return; } _parameterMetaDataLoaded = true; QRegExp parameterCategories = QRegExp("ArduCopter|ArduPlane|APMrover2|ArduSub|AntennaTracker"); QString currentCategory; qCDebug(APMParameterMetaDataLog) << "Loading parameter meta data:" << metaDataFile; QFile xmlFile(metaDataFile); Q_ASSERT(xmlFile.exists()); bool success = xmlFile.open(QIODevice::ReadOnly); Q_UNUSED(success); Q_ASSERT(success); QXmlStreamReader xml(xmlFile.readAll()); xmlFile.close(); if (xml.hasError()) { qCWarning(APMParameterMetaDataLog) << "Badly formed XML, reading failed: " << xml.errorString(); return; } QString errorString; bool badMetaData = true; QStack<int> xmlState; APMFactMetaDataRaw* rawMetaData = NULL; xmlState.push(XmlStateNone); QMap<QString,QStringList> groupMembers; //used to remove groups with single item while (!xml.atEnd()) { if (xml.isStartElement()) { QString elementName = xml.name().toString(); if (elementName.isEmpty()) { // skip empty elements } else if (elementName == "paramfile") { if (xmlState.top() != XmlStateNone) { qCWarning(APMParameterMetaDataLog) << "Badly formed XML, paramfile matched"; } xmlState.push(XmlstateParamFileFound); // we don't really do anything with this element } else if (elementName == "vehicles") { if (xmlState.top() != XmlstateParamFileFound) { qCWarning(APMParameterMetaDataLog) << "Badly formed XML, vehicles matched"; return; } xmlState.push(XmlStateFoundVehicles); } else if (elementName == "libraries") { if (xmlState.top() != XmlstateParamFileFound) { qCWarning(APMParameterMetaDataLog) << "Badly formed XML, libraries matched"; return; } currentCategory = "libraries"; xmlState.push(XmlStateFoundLibraries); } else if (elementName == "parameters") { if (xmlState.top() != XmlStateFoundVehicles && xmlState.top() != XmlStateFoundLibraries) { qCWarning(APMParameterMetaDataLog) << "Badly formed XML, parameters matched" << "but we don't have proper vehicle or libraries yet"; return; } if (xml.attributes().hasAttribute("name")) { // we will handle metadata only for specific MAV_TYPEs and libraries const QString nameValue = xml.attributes().value("name").toString(); if (nameValue.contains(parameterCategories)) { xmlState.push(XmlStateFoundParameters); currentCategory = nameValue; } else if(xmlState.top() == XmlStateFoundLibraries) { // we handle all libraries section under the same category libraries // so not setting currentCategory xmlState.push(XmlStateFoundParameters); } else { qCDebug(APMParameterMetaDataVerboseLog) << "not interested in this block of parameters, skipping:" << nameValue; if (skipXMLBlock(xml, "parameters")) { qCWarning(APMParameterMetaDataLog) << "something wrong with the xml, skip of the xml failed"; return; } xml.readNext(); continue; } } } else if (elementName == "param") { if (xmlState.top() != XmlStateFoundParameters) { qCWarning(APMParameterMetaDataLog) << "Badly formed XML, element param matched" << "while we are not yet in parameters"; return; } xmlState.push(XmlStateFoundParameter); if (!xml.attributes().hasAttribute("name")) { qCWarning(APMParameterMetaDataLog) << "Badly formed XML, parameter attribute name missing"; return; } QString name = xml.attributes().value("name").toString(); if (name.contains(':')) { name = name.split(':').last(); } QString group = name.split('_').first(); group = group.remove(QRegExp("[0-9]*$")); // remove any numbers from the end QString category = xml.attributes().value("user").toString(); if (category.isEmpty()) { category = QStringLiteral("Advanced"); } QString shortDescription = xml.attributes().value("humanName").toString(); QString longDescription = xml.attributes().value("documentation").toString(); qCDebug(APMParameterMetaDataVerboseLog) << "Found parameter name:" << name << "short Desc:" << shortDescription << "longDescription:" << longDescription << "category: " << category << "group: " << group; Q_ASSERT(!rawMetaData); if (_vehicleTypeToParametersMap[currentCategory].contains(name)) { qCDebug(APMParameterMetaDataLog) << "Duplicate parameter found:" << name; rawMetaData = _vehicleTypeToParametersMap[currentCategory][name]; } else { rawMetaData = new APMFactMetaDataRaw(); _vehicleTypeToParametersMap[currentCategory][name] = rawMetaData; groupMembers[group] << name; } qCDebug(APMParameterMetaDataVerboseLog) << "inserting metadata for field" << name; rawMetaData->name = name; rawMetaData->category = category; rawMetaData->group = group; rawMetaData->shortDescription = shortDescription; rawMetaData->longDescription = longDescription; } else { // We should be getting meta data now if (xmlState.top() != XmlStateFoundParameter) { qCWarning(APMParameterMetaDataLog) << "Badly formed XML, while reading parameter fields wrong state"; return; } if (!badMetaData) { if (!parseParameterAttributes(xml, rawMetaData)) { qCDebug(APMParameterMetaDataLog) << "Badly formed XML, failed to read parameter attributes"; return; } continue; } } } else if (xml.isEndElement()) { QString elementName = xml.name().toString(); if (elementName == "param" && xmlState.top() == XmlStateFoundParameter) { // Done loading this parameter // Reset for next parameter qCDebug(APMParameterMetaDataVerboseLog) << "done loading parameter"; rawMetaData = NULL; badMetaData = false; xmlState.pop(); } else if (elementName == "parameters") { qCDebug(APMParameterMetaDataVerboseLog) << "end of parameters for category: " << currentCategory; correctGroupMemberships(_vehicleTypeToParametersMap[currentCategory], groupMembers); groupMembers.clear(); xmlState.pop(); } else if (elementName == "vehicles") { qCDebug(APMParameterMetaDataVerboseLog) << "vehicles end here, libraries will follow"; xmlState.pop(); } } xml.readNext(); } } void APMParameterMetaData::correctGroupMemberships(ParameterNametoFactMetaDataMap& parameterToFactMetaDataMap, QMap<QString,QStringList>& groupMembers) { foreach(const QString& groupName, groupMembers.keys()) { if (groupMembers[groupName].count() == 1) { foreach(const QString& parameter, groupMembers.value(groupName)) { parameterToFactMetaDataMap[parameter]->group = FactMetaData::defaultGroup(); } } } } bool APMParameterMetaData::skipXMLBlock(QXmlStreamReader& xml, const QString& blockName) { QString elementName; do { xml.readNext(); elementName = xml.name().toString(); } while ((elementName != blockName) && (xml.isEndElement())); return !xml.isEndDocument(); } bool APMParameterMetaData::parseParameterAttributes(QXmlStreamReader& xml, APMFactMetaDataRaw* rawMetaData) { QString elementName = xml.name().toString(); QList<QPair<QString,QString> > values; // as long as param doens't end while (!(elementName == "param" && xml.isEndElement())) { if (elementName.isEmpty()) { // skip empty elements. Somehow I am getting lot of these. Don't know what to do with them. } else if (elementName == "field") { QString attributeName = xml.attributes().value("name").toString(); if ( attributeName == "Range") { QString range = xml.readElementText().trimmed(); QStringList rangeList = range.split(' '); if (rangeList.count() != 2) { qCDebug(APMParameterMetaDataVerboseLog) << "space seperator didn't work',trying 'to' separator"; rangeList = range.split("to"); if (rangeList.count() != 2) { qCDebug(APMParameterMetaDataVerboseLog) << " 'to' seperaator didn't work', trying '-' as seperator"; rangeList = range.split('-'); if (rangeList.count() != 2) { qCDebug(APMParameterMetaDataLog) << "something wrong with range, all three separators have failed" << range; } } } // everything should be good. lets collect min and max if (rangeList.count() == 2) { rawMetaData->min = rangeList.first().trimmed(); rawMetaData->max = rangeList.last().trimmed(); // sanitize min and max off any comments that they may have if (rawMetaData->min.contains(' ')) { rawMetaData->min = rawMetaData->min.split(' ').first(); } if(rawMetaData->max.contains(' ')) { rawMetaData->max = rawMetaData->max.split(' ').first(); } qCDebug(APMParameterMetaDataVerboseLog) << "read field parameter " << "min: " << rawMetaData->min << "max: " << rawMetaData->max; } } else if (attributeName == "Increment") { QString increment = xml.readElementText(); qCDebug(APMParameterMetaDataVerboseLog) << "read Increment: " << increment; rawMetaData->incrementSize = increment; } else if (attributeName == "Units") { QString units = xml.readElementText(); qCDebug(APMParameterMetaDataVerboseLog) << "read Units: " << units; rawMetaData->units = units; } else if (attributeName == "Bitmask") { bool parseError = false; QString bitmaskString = xml.readElementText(); qCDebug(APMParameterMetaDataVerboseLog) << "read Bitmask: " << bitmaskString; QStringList bitmaskList = bitmaskString.split(","); if (bitmaskList.count() > 0) { foreach (const QString& bitmask, bitmaskList) { QStringList pair = bitmask.split(":"); if (pair.count() == 2) { rawMetaData->bitmask << QPair<QString, QString>(pair[0], pair[1]); } else { qCDebug(APMParameterMetaDataLog) << "parse error: bitmask:" << bitmaskString << "pair count:" << pair.count(); parseError = true; break; } } } if (parseError) { rawMetaData->bitmask.clear(); } } else if (attributeName == "RebootRequired") { QString strValue = xml.readElementText().trimmed(); if (strValue.compare("true", Qt::CaseInsensitive) == 0) { rawMetaData->rebootRequired = true; } } } else if (elementName == "values") { // doing nothing individual value will follow anyway. May be used for sanity checking. } else if (elementName == "value") { QString valueValue = xml.attributes().value("code").toString(); QString valueName = xml.readElementText(); qCDebug(APMParameterMetaDataVerboseLog) << "read value parameter " << "value desc: " << valueName << "code: " << valueValue; values << QPair<QString,QString>(valueValue, valueName); rawMetaData->values = values; } else { qCWarning(APMParameterMetaDataLog) << "Unknown parameter element in XML: " << elementName; } xml.readNext(); elementName = xml.name().toString(); } return true; } void APMParameterMetaData::addMetaDataToFact(Fact* fact, MAV_TYPE vehicleType) { const QString mavTypeString = mavTypeToString(vehicleType); APMFactMetaDataRaw* rawMetaData = NULL; // check if we have metadata for fact, use generic otherwise if (_vehicleTypeToParametersMap[mavTypeString].contains(fact->name())) { rawMetaData = _vehicleTypeToParametersMap[mavTypeString][fact->name()]; } else if (_vehicleTypeToParametersMap["libraries"].contains(fact->name())) { rawMetaData = _vehicleTypeToParametersMap["libraries"][fact->name()]; } FactMetaData *metaData = new FactMetaData(fact->type(), fact); // we don't have data for this fact if (!rawMetaData) { fact->setMetaData(metaData); qCDebug(APMParameterMetaDataLog) << "No metaData for " << fact->name() << "using generic metadata"; return; } metaData->setName(rawMetaData->name); metaData->setCategory(rawMetaData->category); metaData->setGroup(rawMetaData->group); metaData->setRebootRequired(rawMetaData->rebootRequired); if (!rawMetaData->shortDescription.isEmpty()) { metaData->setShortDescription(rawMetaData->shortDescription); } if (!rawMetaData->longDescription.isEmpty()) { metaData->setLongDescription(rawMetaData->longDescription); } if (!rawMetaData->units.isEmpty()) { metaData->setRawUnits(rawMetaData->units); } if (!rawMetaData->min.isEmpty()) { QVariant varMin; QString errorString; if (metaData->convertAndValidateRaw(rawMetaData->min, false /* validate as well */, varMin, errorString)) { metaData->setRawMin(varMin); } else { qCDebug(APMParameterMetaDataLog) << "Invalid min value, name:" << metaData->name() << " type:" << metaData->type() << " min:" << rawMetaData->min << " error:" << errorString; } } if (!rawMetaData->max.isEmpty()) { QVariant varMax; QString errorString; if (metaData->convertAndValidateRaw(rawMetaData->max, false /* validate as well */, varMax, errorString)) { metaData->setRawMax(varMax); } else { qCDebug(APMParameterMetaDataLog) << "Invalid max value, name:" << metaData->name() << " type:" << metaData->type() << " max:" << rawMetaData->max << " error:" << errorString; } } if (rawMetaData->values.count() > 0) { QStringList enumStrings; QVariantList enumValues; for (int i=0; i<rawMetaData->values.count(); i++) { QVariant enumValue; QString errorString; QPair<QString, QString> enumPair = rawMetaData->values[i]; if (metaData->convertAndValidateRaw(enumPair.first, false /* validate */, enumValue, errorString)) { enumValues << enumValue; enumStrings << enumPair.second; } else { qCDebug(APMParameterMetaDataLog) << "Invalid enum value, name:" << metaData->name() << " type:" << metaData->type() << " value:" << enumPair.first << " error:" << errorString; enumStrings.clear(); enumValues.clear(); break; } } if (enumStrings.count() != 0) { metaData->setEnumInfo(enumStrings, enumValues); } } if (rawMetaData->bitmask.count() > 0) { QStringList bitmaskStrings; QVariantList bitmaskValues; for (int i=0; i<rawMetaData->bitmask.count(); i++) { QVariant bitmaskValue; QString errorString; QPair<QString, QString> bitmaskPair = rawMetaData->bitmask[i]; bool ok = false; unsigned int bitSet = bitmaskPair.first.toUInt(&ok); bitSet = 1 << bitSet; QVariant typedBitSet; switch (fact->type()) { case FactMetaData::valueTypeInt8: typedBitSet = QVariant((signed char)bitSet); break; case FactMetaData::valueTypeInt16: typedBitSet = QVariant((short int)bitSet); break; case FactMetaData::valueTypeInt32: typedBitSet = QVariant((int)bitSet); break; case FactMetaData::valueTypeUint8: case FactMetaData::valueTypeUint16: case FactMetaData::valueTypeUint32: typedBitSet = QVariant(bitSet); break; default: break; } if (typedBitSet.isNull()) { qCDebug(APMParameterMetaDataLog) << "Invalid type for bitmask, name:" << metaData->name() << " type:" << metaData->type(); } if (!ok) { qCDebug(APMParameterMetaDataLog) << "Invalid bitmask value, name:" << metaData->name() << " type:" << metaData->type() << " value:" << bitSet << " error: toUInt failed"; bitmaskStrings.clear(); bitmaskValues.clear(); break; } if (metaData->convertAndValidateRaw(typedBitSet, false /* validate */, bitmaskValue, errorString)) { bitmaskValues << bitmaskValue; bitmaskStrings << bitmaskPair.second; } else { qCDebug(APMParameterMetaDataLog) << "Invalid bitmask value, name:" << metaData->name() << " type:" << metaData->type() << " value:" << typedBitSet << " error:" << errorString; bitmaskStrings.clear(); bitmaskValues.clear(); break; } } if (bitmaskStrings.count() != 0) { metaData->setBitmaskInfo(bitmaskStrings, bitmaskValues); } } if (!rawMetaData->incrementSize.isEmpty()) { double increment; bool ok; increment = rawMetaData->incrementSize.toDouble(&ok); if (ok) { metaData->setIncrement(increment); } else { qCDebug(APMParameterMetaDataLog) << "Invalid value for increment, name:" << metaData->name() << " increment:" << rawMetaData->incrementSize; } } // ArduPilot does not yet support decimal places meta data. So for P/I/D parameters we force to 6 places if ((fact->name().endsWith(QStringLiteral("_P")) || fact->name().endsWith(QStringLiteral("_I")) || fact->name().endsWith(QStringLiteral("_D"))) && (fact->type() == FactMetaData::valueTypeFloat || fact->type() == FactMetaData::valueTypeDouble)) { metaData->setDecimalPlaces(6); } fact->setMetaData(metaData); } void APMParameterMetaData::getParameterMetaDataVersionInfo(const QString& metaDataFile, int& majorVersion, int& minorVersion) { majorVersion = -1; minorVersion = -1; // Meta data version is hacked in for now based on file name QRegExp regExp(".*\\.(\\d)\\.(\\d)\\.xml$"); if (regExp.exactMatch(metaDataFile) && regExp.captureCount() == 2) { majorVersion = regExp.cap(2).toInt(); minorVersion = 0; } }
#include "skse64/PapyrusInput.h" #include "skse64/GameInput.h" #include "Hooks_DirectInput8Create.h" namespace papyrusInput { bool IsKeyPressed(StaticFunctionTag* thisInput, UInt32 dxKeycode) { return DIHookControl::GetSingleton().IsKeyPressed(dxKeycode); } void TapKey(StaticFunctionTag* thisInput, UInt32 dxKeycode) { //DIHookControl::GetSingleton().TapKey(dxKeycode); DIHookControl::GetSingleton().BufferedKeyTap(dxKeycode); } void HoldKey(StaticFunctionTag* thisInput, UInt32 dxKeycode) { //DIHookControl::GetSingleton().SetKeyHeldState(dxKeycode, true); DIHookControl::GetSingleton().BufferedKeyPress(dxKeycode); } void ReleaseKey(StaticFunctionTag* thisInput, UInt32 dxKeycode) { //DIHookControl::GetSingleton().SetKeyHeldState(dxKeycode, false); DIHookControl::GetSingleton().BufferedKeyRelease(dxKeycode); } bool IsKeyHeld(StaticFunctionTag* thisInput, UInt32 dxKeycode) { return DIHookControl::GetSingleton().IsKeyHeld(dxKeycode); } void DisableKey(StaticFunctionTag* thisInput, UInt32 dxKeycode) { DIHookControl::GetSingleton().SetKeyDisableState(dxKeycode, true, 0); } void EnableKey(StaticFunctionTag* thisInput, UInt32 dxKeycode) { DIHookControl::GetSingleton().SetKeyDisableState(dxKeycode, false, 0); } bool IsKeyDisabled(StaticFunctionTag* thisInput, UInt32 dxKeycode) { return DIHookControl::GetSingleton().IsKeyDisabled(dxKeycode); } UInt32 GetNumKeysPressed(StaticFunctionTag* thisInput) { return DIHookControl::GetSingleton().GetNumKeysPressed(); } SInt32 GetNthKeyPressed(StaticFunctionTag* thisInput, UInt32 which) { return DIHookControl::GetSingleton().GetNthKeyPressed(which); } //UInt32 GetNumMouseButtonsPressed(StaticFunctionTag* thisInput); //UInt32 GetMouseButtonPressed(StaticFunctionTag* thisInput, UInt32 which); //void DisableMouse(StaticFunctionTag* thisInput); //void EnableMouse(StaticFunctionTag* thisInput); //bool IsMouseDisabled(StaticFunctionTag* thisInput); SInt32 GetMappedKey(StaticFunctionTag* thisInput, BSFixedString name, UInt32 deviceType) { InputManager * inputManager = InputManager::GetSingleton(); if (!inputManager) return -1; UInt32 key = 0xFF; // Manual device selection if (deviceType != 0xFF) { key = inputManager->GetMappedKey(name, deviceType, InputManager::kContext_Gameplay); } // Auto-selected device else { // Gamepad InputEventDispatcher *inputEventDispatcher = InputEventDispatcher::GetSingleton(); if (inputEventDispatcher && inputEventDispatcher->IsGamepadEnabled()) { deviceType = kDeviceType_Gamepad; key = inputManager->GetMappedKey(name, kDeviceType_Gamepad, InputManager::kContext_Gameplay); } // Mouse + Keyboard else { deviceType = kDeviceType_Keyboard; key = inputManager->GetMappedKey(name, deviceType, InputManager::kContext_Gameplay); if (key == 0xFF) { deviceType = kDeviceType_Mouse; key = inputManager->GetMappedKey(name, deviceType, InputManager::kContext_Gameplay); } } } if (key == 0xFF) return -1; // Map to common value space if (deviceType == kDeviceType_Mouse) { return key + InputMap::kMacro_MouseButtonOffset; } else if (deviceType == kDeviceType_Gamepad) { UInt32 mapped = InputMap::GamepadMaskToKeycode(key); return (mapped != InputMap::kMaxMacros ? mapped : -1); } else { return key; } } BSFixedString GetMappedControl(StaticFunctionTag* thisInput, SInt32 keyCode) { if (keyCode < 0 || keyCode >= InputMap::kMaxMacros) return BSFixedString(); InputManager * inputManager = InputManager::GetSingleton(); if (!inputManager) return BSFixedString(); UInt32 buttonID; UInt32 deviceType; if (keyCode >= InputMap::kMacro_GamepadOffset) { buttonID = InputMap::GamepadKeycodeToMask(keyCode); deviceType = kDeviceType_Gamepad; } else if (keyCode >= InputMap::kMacro_MouseButtonOffset) { buttonID = keyCode - InputMap::kMacro_MouseButtonOffset; deviceType = kDeviceType_Mouse; } else { buttonID = keyCode; deviceType = kDeviceType_Keyboard; } return inputManager->GetMappedControl(buttonID, deviceType, InputManager::kContext_Gameplay); } } #include "PapyrusVM.h" #include "PapyrusNativeFunctions.h" void papyrusInput::RegisterFuncs(VMClassRegistry* registry) { registry->RegisterFunction( new NativeFunction1 <StaticFunctionTag, bool, UInt32> ("IsKeyPressed", "Input", papyrusInput::IsKeyPressed, registry)); registry->RegisterFunction( new NativeFunction1 <StaticFunctionTag, void, UInt32> ("TapKey", "Input", papyrusInput::TapKey, registry)); registry->RegisterFunction( new NativeFunction1 <StaticFunctionTag, void, UInt32> ("HoldKey", "Input", papyrusInput::HoldKey, registry)); registry->RegisterFunction( new NativeFunction1 <StaticFunctionTag, void, UInt32> ("ReleaseKey", "Input", papyrusInput::ReleaseKey, registry)); registry->RegisterFunction( new NativeFunction0 <StaticFunctionTag, UInt32> ("GetNumKeysPressed", "Input", papyrusInput::GetNumKeysPressed, registry)); registry->RegisterFunction( new NativeFunction1 <StaticFunctionTag, SInt32, UInt32> ("GetNthKeyPressed", "Input", papyrusInput::GetNthKeyPressed, registry)); //registry->RegisterFunction( // new NativeFunction1 <StaticFunctionTag, bool, UInt32> ("IsKeyHeld", "Input", papyrusInput::IsKeyHeld, registry)); //registry->RegisterFunction( // new NativeFunction1 <StaticFunctionTag, bool, UInt32> ("IsKeyDisabeld", "Input", papyrusInput::IsKeyDisabled, registry)); //registry->RegisterFunction( // new NativeFunction1 <StaticFunctionTag, void, UInt32> ("DisableKey", "Input", papyrusInput::DisableKey, registry)); //registry->RegisterFunction( // new NativeFunction1 <StaticFunctionTag, void, UInt32> ("EnableKey", "Input", papyrusInput::EnableKey, registry)); registry->RegisterFunction( new NativeFunction2 <StaticFunctionTag, SInt32, BSFixedString, UInt32> ("GetMappedKey", "Input", papyrusInput::GetMappedKey, registry)); registry->RegisterFunction( new NativeFunction1 <StaticFunctionTag, BSFixedString, SInt32> ("GetMappedControl", "Input", papyrusInput::GetMappedControl, registry)); registry->SetFunctionFlags("Input", "IsKeyPressed", VMClassRegistry::kFunctionFlag_NoWait); registry->SetFunctionFlags("Input", "TapKey", VMClassRegistry::kFunctionFlag_NoWait); registry->SetFunctionFlags("Input", "HoldKey", VMClassRegistry::kFunctionFlag_NoWait); registry->SetFunctionFlags("Input", "ReleaseKey", VMClassRegistry::kFunctionFlag_NoWait); registry->SetFunctionFlags("Input", "GetNumKeysPressed", VMClassRegistry::kFunctionFlag_NoWait); registry->SetFunctionFlags("Input", "GetNthKeyPressed", VMClassRegistry::kFunctionFlag_NoWait); registry->SetFunctionFlags("Input", "GetMappedKey", VMClassRegistry::kFunctionFlag_NoWait); registry->SetFunctionFlags("Input", "GetMappedControl", VMClassRegistry::kFunctionFlag_NoWait); }
/* * Copyright (C) 2020 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef IGNITION_PHYSICS_TPE_LIB_SRC_MODEL_HH_ #define IGNITION_PHYSICS_TPE_LIB_SRC_MODEL_HH_ #include <ignition/utils/SuppressWarning.hh> #include "ignition/physics/tpelib/Export.hh" #include "Entity.hh" namespace ignition { namespace physics { namespace tpelib { // forward declaration class ModelPrivate; /// \brief Model class class IGNITION_PHYSICS_TPELIB_VISIBLE Model : public Entity { /// \brief Constructor public: Model(); /// \brief Constructor /// \param[in] _id Model id public: explicit Model(std::size_t _id); /// \brief Destructor public: virtual ~Model(); /// \brief Add a link /// \return Newly created Link public: Entity &AddLink(); /// \brief Get the number of links in the model /// \return Number of links in the model public: std::size_t GetLinkCount() const; /// \brief Add a nested model /// \return Newly created nested model public: Entity &AddModel(); /// \brief Get the number of nested models in the model /// \return Number of nested models in the model public: std::size_t GetModelCount() const; /// \brief Set the canonical link of model public: void SetCanonicalLink( std::size_t linkId = kNullEntityId); /// \brief Get the canonical link of model /// \return Entity the canonical (first) link public: Entity &GetCanonicalLink(); /// \brief Set the linear velocity of model relative to parent /// \param[in] _velocity linear velocity in meters per second public: void SetLinearVelocity(const math::Vector3d &_velocity); /// \brief Get the linear velocity of model relative to parent /// \return linear velocity of model in meters per second public: math::Vector3d GetLinearVelocity() const; /// \brief Set the angular velocity of model relative to parent /// \param[in] _velocity angular velocity from world in radians per second public: void SetAngularVelocity(const math::Vector3d &_velocity); /// \brief Get the angular velocity of model relative to parent /// \return angular velocity in radians per second public: math::Vector3d GetAngularVelocity() const; /// \brief Update the pose of the entity /// \param[in] _timeStep current world timestep in seconds public: virtual void UpdatePose(double _timeStep); /// \brief Removes a child entity (either a link or model) from the /// appropriate child entity containers /// \param[in] _ent Pointer to entity /// \return True if the entity was found and removed public: bool RemoveChildEntityBasedOnType(const Entity *_ent); /// \brief Remove a child entity by id /// \param[in] _id Id of child entity to remove /// \return True if the entity was found and removed public: bool RemoveChildById(std::size_t _id) override; /// \brief Remove a child entity by name /// \param[in] _name Name of child entity to remove /// \return True if child entity was removed, false otherwise public: bool RemoveChildByName(const std::string &_name) override; IGN_UTILS_WARN_IGNORE__DLL_INTERFACE_MISSING /// \brief linear velocity of model protected: math::Vector3d linearVelocity; /// \brief angular velocity of model protected: math::Vector3d angularVelocity; IGN_UTILS_WARN_RESUME__DLL_INTERFACE_MISSING /// \brief Remove a model entity by id /// \param[in] _id Id of model entity to remove private: bool RemoveModelById(std::size_t _id); /// \brief Remove a link entity by id /// \param[in] _id Id of link entity to remove private: bool RemoveLinkById(std::size_t _id); /// \brief Pointer to private data class private: ModelPrivate *dataPtr = nullptr; }; } } } #endif
#include "simpletoken.hpp" #include <cmath> void simpletoken::create( name issuer, asset maximum_supply ) { require_auth( _self ); auto sym = maximum_supply.symbol; eosio_assert( sym.is_valid(), "invalid symbol name" ); eosio_assert( maximum_supply.is_valid(), "invalid supply"); eosio_assert( maximum_supply.amount > 0, "max-supply must be positive"); stats statstable( _self, sym.code().raw() ); auto existing = statstable.find( sym.code().raw() ); eosio_assert( existing == statstable.end(), "token with symbol already exists" ); statstable.emplace( _self, [&]( auto& s ) { s.supply.symbol = maximum_supply.symbol; s.max_supply = maximum_supply; s.issuer = issuer; }); } void simpletoken::issue( name to, asset quantity, string memo ) { auto sym = quantity.symbol; eosio_assert( sym.is_valid(), "invalid symbol name" ); eosio_assert( memo.size() <= 256, "memo has more than 256 bytes" ); stats statstable( _self, sym.code().raw() ); auto existing = statstable.find( sym.code().raw() ); eosio_assert( existing != statstable.end(), "token with symbol does not exist, create token before issue" ); const auto& st = *existing; require_auth( get_self() ); eosio_assert( quantity.is_valid(), "invalid quantity" ); eosio_assert( quantity.amount > 0, "must issue positive quantity" ); eosio_assert( quantity.symbol == st.supply.symbol, "symbol precision mismatch" ); eosio_assert( quantity.amount <= st.max_supply.amount - st.supply.amount, "quantity exceeds available supply"); statstable.modify( st, same_payer, [&]( auto& s ) { s.supply += quantity; }); add_balance( get_self(), quantity, get_self() ); if( to != get_self() ) { SEND_INLINE_ACTION( *this, transfer, { {get_self(), "active"_n} }, { get_self(), to, quantity, memo } ); } } void simpletoken::retire( asset quantity, string memo ) { auto sym = quantity.symbol; eosio_assert( sym.is_valid(), "invalid symbol name" ); eosio_assert( memo.size() <= 256, "memo has more than 256 bytes" ); stats statstable( _self, sym.code().raw() ); auto existing = statstable.find( sym.code().raw() ); eosio_assert( existing != statstable.end(), "token with symbol does not exist" ); const auto& st = *existing; require_auth( st.issuer ); eosio_assert( quantity.is_valid(), "invalid quantity" ); eosio_assert( quantity.amount > 0, "must retire positive quantity" ); eosio_assert( quantity.symbol == st.supply.symbol, "symbol precision mismatch" ); statstable.modify( st, same_payer, [&]( auto& s ) { s.supply -= quantity; }); sub_balance( st.issuer, quantity ); } void simpletoken::transfer( name from, name to, asset quantity, string memo ) { eosio_assert( from != to, "cannot transfer to self" ); require_auth( from ); eosio_assert( is_account( to ), "to account does not exist"); auto sym = quantity.symbol.code(); stats statstable( _self, sym.raw() ); const auto& st = statstable.get( sym.raw() ); require_recipient( from ); require_recipient( to ); eosio_assert( quantity.is_valid(), "invalid quantity" ); eosio_assert( quantity.amount > 0, "must transfer positive quantity" ); eosio_assert( quantity.symbol == st.supply.symbol, "symbol precision mismatch" ); eosio_assert( memo.size() <= 256, "memo has more than 256 bytes" ); name payer = has_auth( to ) ? to : from; sub_balance( from, quantity ); add_balance( to, quantity, payer ); } void simpletoken::sub_balance( name owner, asset value ) { accounts from_acnts( _self, owner.value ); const auto& from = from_acnts.get( value.symbol.code().raw(), "no balance object found" ); eosio_assert( from.balance.amount >= value.amount, "overdrawn balance" ); from_acnts.modify( from, owner, [&]( auto& a ) { a.balance -= value; }); } void simpletoken::add_balance( name owner, asset value, name ram_payer ) { accounts to_acnts( _self, owner.value ); auto to = to_acnts.find( value.symbol.code().raw() ); if( to == to_acnts.end() ) { to_acnts.emplace( ram_payer, [&]( auto& a ){ a.balance = value; }); } else { to_acnts.modify( to, same_payer, [&]( auto& a ) { a.balance += value; }); } } void simpletoken::open( name owner, const symbol& symbol, name ram_payer ) { require_auth( ram_payer ); auto sym_code_raw = symbol.code().raw(); stats statstable( _self, sym_code_raw ); const auto& st = statstable.get( sym_code_raw, "symbol does not exist" ); eosio_assert( st.supply.symbol == symbol, "symbol precision mismatch" ); accounts acnts( _self, owner.value ); auto it = acnts.find( sym_code_raw ); if( it == acnts.end() ) { acnts.emplace( ram_payer, [&]( auto& a ){ a.balance = asset{0, symbol}; }); } } void simpletoken::close( name owner, const symbol& symbol ) { require_auth( owner ); accounts acnts( _self, owner.value ); auto it = acnts.find( symbol.code().raw() ); eosio_assert( it != acnts.end(), "Balance row already deleted or never existed. Action won't have any effect." ); eosio_assert( it->balance.amount == 0, "Cannot close because the balance is not zero." ); acnts.erase( it ); } EOSIO_DISPATCH( simpletoken, (create)(issue)(transfer)(open)(close)(retire) )
// Copyright (c) 2013, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include <algorithm> #include <map> #include <string> #include "db/flush_job.h" #include "db/column_family.h" #include "db/version_set.h" #include "db/writebuffer.h" #include "rocksdb/cache.h" #include "util/file_reader_writer.h" #include "util/string_util.h" #include "util/testharness.h" #include "util/testutil.h" #include "table/mock_table.h" namespace rocksdb { // TODO(icanadi) Mock out everything else: // 1. VersionSet // 2. Memtable class FlushJobTest : public testing::Test { public: FlushJobTest() : env_(Env::Default()), dbname_(test::TmpDir() + "/flush_job_test"), table_cache_(NewLRUCache(50000, 16)), write_buffer_(db_options_.db_write_buffer_size), versions_(new VersionSet(dbname_, &db_options_, env_options_, table_cache_.get(), &write_buffer_, &write_controller_)), shutting_down_(false), mock_table_factory_(new mock::MockTableFactory()) { EXPECT_OK(env_->CreateDirIfMissing(dbname_)); db_options_.db_paths.emplace_back(dbname_, std::numeric_limits<uint64_t>::max()); // TODO(icanadi) Remove this once we mock out VersionSet NewDB(); std::vector<ColumnFamilyDescriptor> column_families; cf_options_.table_factory = mock_table_factory_; column_families.emplace_back(kDefaultColumnFamilyName, cf_options_); EXPECT_OK(versions_->Recover(column_families, false)); } void NewDB() { VersionEdit new_db; new_db.SetLogNumber(0); new_db.SetNextFile(2); new_db.SetLastSequence(0); const std::string manifest = DescriptorFileName(dbname_, 1); unique_ptr<WritableFile> file; Status s = env_->NewWritableFile( manifest, &file, env_->OptimizeForManifestWrite(env_options_)); ASSERT_OK(s); unique_ptr<WritableFileWriter> file_writer( new WritableFileWriter(std::move(file), EnvOptions())); { log::Writer log(std::move(file_writer), 0, false); std::string record; new_db.EncodeTo(&record); s = log.AddRecord(record); } ASSERT_OK(s); // Make "CURRENT" file that points to the new manifest file. s = SetCurrentFile(env_, dbname_, 1, nullptr); } Env* env_; std::string dbname_; EnvOptions env_options_; std::shared_ptr<Cache> table_cache_; WriteController write_controller_; DBOptions db_options_; WriteBuffer write_buffer_; ColumnFamilyOptions cf_options_; std::unique_ptr<VersionSet> versions_; InstrumentedMutex mutex_; std::atomic<bool> shutting_down_; std::shared_ptr<mock::MockTableFactory> mock_table_factory_; }; TEST_F(FlushJobTest, Empty) { JobContext job_context(0); auto cfd = versions_->GetColumnFamilySet()->GetDefault(); EventLogger event_logger(db_options_.info_log.get()); FlushJob flush_job(dbname_, versions_->GetColumnFamilySet()->GetDefault(), db_options_, *cfd->GetLatestMutableCFOptions(), env_options_, versions_.get(), &mutex_, &shutting_down_, {}, kMaxSequenceNumber, &job_context, nullptr, nullptr, nullptr, kNoCompression, nullptr, &event_logger); ASSERT_OK(flush_job.Run()); job_context.Clean(); } TEST_F(FlushJobTest, NonEmpty) { JobContext job_context(0); auto cfd = versions_->GetColumnFamilySet()->GetDefault(); auto new_mem = cfd->ConstructNewMemtable(*cfd->GetLatestMutableCFOptions(), kMaxSequenceNumber); new_mem->Ref(); auto inserted_keys = mock::MakeMockFile(); // Test data: // seqno [ 1, 2 ... 8998, 8999, 9000, 9001, 9002 ... 9999 ] // key [ 1001, 1002 ... 9998, 9999, 0, 1, 2 ... 999 ] // Expected: // smallest_key = "0" // largest_key = "9999" // smallest_seqno = 1 // smallest_seqno = 9999 for (int i = 1; i < 10000; ++i) { std::string key(ToString((i + 1000) % 10000)); std::string value("value" + key); new_mem->Add(SequenceNumber(i), kTypeValue, key, value); InternalKey internal_key(key, SequenceNumber(i), kTypeValue); inserted_keys.insert({internal_key.Encode().ToString(), value}); } autovector<MemTable*> to_delete; cfd->imm()->Add(new_mem, &to_delete); for (auto& m : to_delete) { delete m; } EventLogger event_logger(db_options_.info_log.get()); FlushJob flush_job(dbname_, versions_->GetColumnFamilySet()->GetDefault(), db_options_, *cfd->GetLatestMutableCFOptions(), env_options_, versions_.get(), &mutex_, &shutting_down_, {}, kMaxSequenceNumber, &job_context, nullptr, nullptr, nullptr, kNoCompression, nullptr, &event_logger); FileMetaData fd; mutex_.Lock(); ASSERT_OK(flush_job.Run(&fd)); mutex_.Unlock(); ASSERT_EQ(ToString(0), fd.smallest.user_key().ToString()); ASSERT_EQ(ToString(9999), fd.largest.user_key().ToString()); ASSERT_EQ(1, fd.smallest_seqno); ASSERT_EQ(9999, fd.largest_seqno); mock_table_factory_->AssertSingleFile(inserted_keys); job_context.Clean(); } TEST_F(FlushJobTest, Snapshots) { JobContext job_context(0); auto cfd = versions_->GetColumnFamilySet()->GetDefault(); auto new_mem = cfd->ConstructNewMemtable(*cfd->GetLatestMutableCFOptions(), kMaxSequenceNumber); std::vector<SequenceNumber> snapshots; std::set<SequenceNumber> snapshots_set; int keys = 10000; int max_inserts_per_keys = 8; Random rnd(301); for (int i = 0; i < keys / 2; ++i) { snapshots.push_back(rnd.Uniform(keys * (max_inserts_per_keys / 2)) + 1); snapshots_set.insert(snapshots.back()); } std::sort(snapshots.begin(), snapshots.end()); new_mem->Ref(); SequenceNumber current_seqno = 0; auto inserted_keys = mock::MakeMockFile(); for (int i = 1; i < keys; ++i) { std::string key(ToString(i)); int insertions = rnd.Uniform(max_inserts_per_keys); for (int j = 0; j < insertions; ++j) { std::string value(test::RandomHumanReadableString(&rnd, 10)); auto seqno = ++current_seqno; new_mem->Add(SequenceNumber(seqno), kTypeValue, key, value); // a key is visible only if: // 1. it's the last one written (j == insertions - 1) // 2. there's a snapshot pointing at it bool visible = (j == insertions - 1) || (snapshots_set.find(seqno) != snapshots_set.end()); if (visible) { InternalKey internal_key(key, seqno, kTypeValue); inserted_keys.insert({internal_key.Encode().ToString(), value}); } } } autovector<MemTable*> to_delete; cfd->imm()->Add(new_mem, &to_delete); for (auto& m : to_delete) { delete m; } EventLogger event_logger(db_options_.info_log.get()); FlushJob flush_job(dbname_, versions_->GetColumnFamilySet()->GetDefault(), db_options_, *cfd->GetLatestMutableCFOptions(), env_options_, versions_.get(), &mutex_, &shutting_down_, snapshots, kMaxSequenceNumber, &job_context, nullptr, nullptr, nullptr, kNoCompression, nullptr, &event_logger); mutex_.Lock(); ASSERT_OK(flush_job.Run()); mutex_.Unlock(); mock_table_factory_->AssertSingleFile(inserted_keys); job_context.Clean(); } } // namespace rocksdb int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
/** @defgroup MleDPPBase Magic Lantern Digital Workprint Library API - Base */ /** * @file DppTblMgr.cpp * @ingroup MleDPPBase * * This file implements the table manager used by the Magic Lantern Digital * Playprint Library API. * * @author Mark S. Millard * @date July 17, 2004 */ // COPYRIGHT_BEGIN // // The MIT License (MIT) // // Copyright (c) 2015 Wizzer Works // // 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. // // For information concerning this source file, contact Mark S. Millard, // of Wizzer Works at msm@wizzerworks.com. // // More information concerning Wizzer Works may be found at // // http://www.wizzerworks.com // // COPYRIGHT_END // Include system header files. #include <string.h> // Include Magic Lantern header files. #include "mle/mlUnique.h" #include "mle/mlErrno.h" #include "mle/mlMalloc.h" #include "mle/mlAssert.h" // Include Magic Lantern DPP header files. #include "mle/DppTblMgr.h" // Include Magic Lantern DWP header files. #include "mle/DwpItem.h" #include "mle/DwpActor.h" #include "mle/DwpActorTemplate.h" #include "mle/DwpProperty.h" #include "mle/DwpDatatype.h" #include "mle/DwpActorDef.h" #include "mle/DwpDelegateBinding.h" #include "mle/DwpDelegateDef.h" #include "mle/DwpRoleBinding.h" #include "mle/DwpRoleDef.h" #include "mle/DwpGroup.h" #include "mle/DwpScene.h" #include "mle/DwpForum.h" #include "mle/DwpForumDef.h" #include "mle/DwpSet.h" #include "mle/DwpSetDef.h" #include "mle/DwpMediaRef.h" #include "mle/DwpFinder.h" #include "mle/DwpStrKeyDict.h" #include "mle/DwpHeaderFile.h" #include "mle/DwpPackage.h" // Include Magic Lantern DWP header files. MleDppTblMgr::MleDppTblMgr() :m_discriminator(NULL) { m_actorClassTable.used = m_actorClassTable.allocated = 0; m_actorClassTable.items = NULL; m_roleClassTable.used = m_roleClassTable.allocated = 0; m_roleClassTable.items = NULL; m_setClassTable.used = m_setClassTable.allocated = 0; m_setClassTable.items = NULL; m_actorPropTable.used = m_actorPropTable.allocated = 0; m_actorPropTable.items = NULL; m_setPropTable.used = m_setPropTable.allocated = 0; m_setPropTable.items = NULL; m_groupClassTable.used = m_groupClassTable.allocated = 0; m_groupClassTable.items = NULL; m_groupInstanceTable.used = m_groupInstanceTable.allocated = 0; m_groupInstanceTable.items = NULL; m_sceneClassTable.used = m_sceneClassTable.allocated = 0; m_sceneClassTable.items = NULL; m_setTable.used = m_setTable.allocated = 0; m_setTable.items = NULL; m_mediarefTable.used = m_mediarefTable.allocated = 0; m_mediarefTable.items = NULL; } MleDppTblMgr::~MleDppTblMgr(void) { // Do nothing extra. } #define ALLOC_INC 32 void MleDppTblMgr::saveString( const char *pstr, TblMgrItems *strTable) { if ( strTable->used >= strTable->allocated ) { if ( strTable->allocated == 0 ) { strTable->allocated = ALLOC_INC; strTable->items = (void **)mlMalloc(strTable->allocated*sizeof(char *)); } else { strTable->allocated += ALLOC_INC; strTable->items = (void **)mlRealloc((void *)strTable->items, strTable->allocated*sizeof(char *)); } } strTable->items[strTable->used++] = (void *)pstr; } void MleDppTblMgr::saveActorClass( char *name, int numProperties, char *headerFile, char *package, TblMgrItems *actorTable) { int i; if ( actorTable->used >= actorTable->allocated ) { if ( actorTable->allocated == 0 ) { actorTable->allocated = ALLOC_INC; actorTable->items = (void **)mlMalloc(actorTable->allocated*sizeof(ActorClassTableItem *)); for (i = 0; i < ALLOC_INC; i++) { actorTable->items[i] = (void *)mlMalloc(sizeof(ActorClassTableItem)); } } else { actorTable->allocated += ALLOC_INC; actorTable->items = (void **)mlRealloc((void *)actorTable->items, actorTable->allocated*sizeof(ActorClassTableItem *)); for (i = ALLOC_INC; i > 0; i--) { actorTable->items[actorTable->allocated - i] = (void *)mlMalloc(sizeof(ActorClassTableItem)); } } } ((ActorClassTableItem *)actorTable->items[actorTable->used])->name = name; ((ActorClassTableItem *)actorTable->items[actorTable->used])->numProperties = numProperties; ((ActorClassTableItem *)actorTable->items[actorTable->used])->headerFile = headerFile; ((ActorClassTableItem *)actorTable->items[actorTable->used])->package = package; actorTable->used++; } void MleDppTblMgr::saveRoleClass( char *name, char *headerFile, char *package, TblMgrItems *roleTable) { int i; if ( roleTable->used >= roleTable->allocated ) { if ( roleTable->allocated == 0 ) { roleTable->allocated = ALLOC_INC; roleTable->items = (void **)mlMalloc(roleTable->allocated*sizeof(RoleClassTableItem *)); for (i = 0; i < ALLOC_INC; i++) { roleTable->items[i] = (void *)mlMalloc(sizeof(RoleClassTableItem)); } } else { roleTable->allocated += ALLOC_INC; roleTable->items = (void **)mlRealloc((void *)roleTable->items, roleTable->allocated*sizeof(RoleClassTableItem *)); for (i = ALLOC_INC; i > 0; i--) { roleTable->items[roleTable->allocated - i] = (void *)mlMalloc(sizeof(RoleClassTableItem)); } } } ((RoleClassTableItem *)roleTable->items[roleTable->used])->name = name; ((RoleClassTableItem *)roleTable->items[roleTable->used])->headerFile = headerFile; ((RoleClassTableItem *)roleTable->items[roleTable->used])->package = package; roleTable->used++; } void MleDppTblMgr::saveGroupClass( char *name, char *headerFile, char *package, TblMgrItems *groupTable) { int i; if ( groupTable->used >= groupTable->allocated ) { if ( groupTable->allocated == 0 ) { groupTable->allocated = ALLOC_INC; groupTable->items = (void **)mlMalloc(groupTable->allocated*sizeof(GroupClassTableItem *)); for (i = 0; i < ALLOC_INC; i++) { groupTable->items[i] = (void *)mlMalloc(sizeof(GroupClassTableItem)); } } else { groupTable->allocated += ALLOC_INC; groupTable->items = (void **)mlRealloc((void *)groupTable->items, groupTable->allocated*sizeof(GroupClassTableItem *)); for (i = ALLOC_INC; i > 0; i--) { groupTable->items[groupTable->allocated - i] = (void *)mlMalloc(sizeof(GroupClassTableItem)); } } } ((GroupClassTableItem *)groupTable->items[groupTable->used])->name = name; ((GroupClassTableItem *)groupTable->items[groupTable->used])->headerFile = headerFile; ((GroupClassTableItem *)groupTable->items[groupTable->used])->package = package; groupTable->used++; } void MleDppTblMgr::saveGroupInstance( char *name, TblMgrItems *groupTable) { int i; if ( groupTable->used >= groupTable->allocated ) { if ( groupTable->allocated == 0 ) { groupTable->allocated = ALLOC_INC; groupTable->items = (void **)mlMalloc(groupTable->allocated*sizeof(GroupInstanceTableItem *)); for (i = 0; i < ALLOC_INC; i++) { groupTable->items[i] = (void *)mlMalloc(sizeof(GroupInstanceTableItem)); } } else { groupTable->allocated += ALLOC_INC; groupTable->items = (void **)mlRealloc((void *)groupTable->items, groupTable->allocated*sizeof(GroupInstanceTableItem *)); for (i = ALLOC_INC; i > 0; i--) { groupTable->items[groupTable->allocated - i] = (void *)mlMalloc(sizeof(GroupInstanceTableItem)); } } } ((GroupInstanceTableItem *)groupTable->items[groupTable->used])->name = name; groupTable->used++; } void MleDppTblMgr::saveSceneClass( char *name, char *headerFile, char *package, TblMgrItems *sceneTable) { int i; if ( sceneTable->used >= sceneTable->allocated ) { if ( sceneTable->allocated == 0 ) { sceneTable->allocated = ALLOC_INC; sceneTable->items = (void **)mlMalloc(sceneTable->allocated*sizeof(SceneClassTableItem *)); for (i = 0; i < ALLOC_INC; i++) { sceneTable->items[i] = (void *)mlMalloc(sizeof(SceneClassTableItem)); } } else { sceneTable->allocated += ALLOC_INC; sceneTable->items = (void **)mlRealloc((void *)sceneTable->items, sceneTable->allocated*sizeof(SceneClassTableItem *)); for (i = ALLOC_INC; i > 0; i--) { sceneTable->items[sceneTable->allocated - i] = (void *)mlMalloc(sizeof(SceneClassTableItem)); } } } ((SceneClassTableItem *)sceneTable->items[sceneTable->used])->name = name; ((SceneClassTableItem *)sceneTable->items[sceneTable->used])->headerFile = headerFile; ((SceneClassTableItem *)sceneTable->items[sceneTable->used])->package = package; sceneTable->used++; } void MleDppTblMgr::saveSet( char *name, char *type, TblMgrItems *setTable) { int i; if ( setTable->used >= setTable->allocated ) { if ( setTable->allocated == 0 ) { setTable->allocated = ALLOC_INC; setTable->items = (void **)mlMalloc(setTable->allocated*sizeof(SetTableItem *)); for (i = 0; i < ALLOC_INC; i++) { setTable->items[i] = (void *)mlMalloc(sizeof(SetTableItem)); } } else { setTable->allocated += ALLOC_INC; setTable->items = (void **)mlRealloc((void *)setTable->items, setTable->allocated*sizeof(SetTableItem *)); for (i = ALLOC_INC; i > 0; i--) { setTable->items[setTable->allocated - i] = (void *)mlMalloc(sizeof(SetTableItem)); } } } ((SetTableItem *)setTable->items[setTable->used])->name = name; ((SetTableItem *)setTable->items[setTable->used])->type = type; setTable->used++; } void MleDppTblMgr::saveSetClass( char *name, int numProperties, char *headerFile, char *package, TblMgrItems *setTable) { int i; if ( setTable->used >= setTable->allocated ) { if ( setTable->allocated == 0 ) { setTable->allocated = ALLOC_INC; setTable->items = (void **)mlMalloc(setTable->allocated*sizeof(SetClassTableItem *)); for (i = 0; i < ALLOC_INC; i++) { setTable->items[i] = (void *)mlMalloc(sizeof(SetClassTableItem)); } } else { setTable->allocated += ALLOC_INC; setTable->items = (void **)mlRealloc((void *)setTable->items, setTable->allocated*sizeof(SetClassTableItem *)); for (i = ALLOC_INC; i > 0; i--) { setTable->items[setTable->allocated - i] = (void *)mlMalloc(sizeof(SetClassTableItem)); } } } ((SetClassTableItem *)setTable->items[setTable->used])->name = name; ((SetClassTableItem *)setTable->items[setTable->used])->numProperties = numProperties; ((SetClassTableItem *)setTable->items[setTable->used])->headerFile = headerFile; ((SetClassTableItem *)setTable->items[setTable->used])->package = package; setTable->used++; } void MleDppTblMgr::saveMediaRefClass( char *name, char *headerFile, char *package, TblMgrItems *mrefTable) { int i; if ( mrefTable->used >= mrefTable->allocated ) { if ( mrefTable->allocated == 0 ) { mrefTable->allocated = ALLOC_INC; mrefTable->items = (void **)mlMalloc(mrefTable->allocated*sizeof(MediaRefClassTableItem *)); for (i = 0; i < ALLOC_INC; i++) { mrefTable->items[i] = (void *)mlMalloc(sizeof(MediaRefClassTableItem)); } } else { mrefTable->allocated += ALLOC_INC; mrefTable->items = (void **)mlRealloc((void *)mrefTable->items, mrefTable->allocated*sizeof(MediaRefClassTableItem *)); for (i = ALLOC_INC; i > 0; i--) { mrefTable->items[mrefTable->allocated - i] = (void *)mlMalloc(sizeof(MediaRefClassTableItem)); } } } ((MediaRefClassTableItem *)mrefTable->items[mrefTable->used])->name = name; ((MediaRefClassTableItem *)mrefTable->items[mrefTable->used])->headerFile = headerFile; ((MediaRefClassTableItem *)mrefTable->items[mrefTable->used])->package = package; mrefTable->used++; } static int StrMapCompare( const void *s1, const void *s2 ) { return strcmp(*(char **)s1, *(char **)s2); } static int ActorClassCompare( const void *s1, const void *s2 ) { return strcmp((*(ActorClassTableItem **)s1)->name, (*(ActorClassTableItem **)s2)->name); } static int RoleClassCompare( const void *s1, const void *s2 ) { return strcmp((*(RoleClassTableItem **)s1)->name, (*(RoleClassTableItem **)s2)->name); } static int SetClassCompare( const void *s1, const void *s2 ) { return strcmp((*(SetClassTableItem **)s1)->name, (*(SetClassTableItem **)s2)->name); } static int SetNameCompare( const void *s1, const void *s2 ) { return strcmp((*(SetTableItem **)s1)->name,(*(SetTableItem **)s2)->name); } static int GroupClassCompare( const void *s1, const void *s2 ) { return strcmp((*(GroupClassTableItem **)s1)->name, (*(GroupClassTableItem **)s2)->name); } static int SceneClassCompare( const void *s1, const void *s2 ) { return strcmp((*(SceneClassTableItem **)s1)->name, (*(SceneClassTableItem **)s2)->name); } static int MediaRefClassCompare( const void *s1, const void *s2 ) { return strcmp((*(MediaRefClassTableItem **)s1)->name, (*(MediaRefClassTableItem **)s2)->name); } MlBoolean MleDppTblMgr::buildIndexTables(MleDwpItem *root) { // Declare local variables. MleDwpFinder roleClassFinder; MleDwpFinder mediarefClassFinder; MleDwpRoleBinding **roleClassItems; MleDwpMediaRef **mediarefClassItems; char buf[128]; int numItems,i,j; // PROCESS ACTOR CLASS and PROPERTY TABLES // Find all actors in the workprint. MleDwpFinder actorFinder(MleDwpActor::typeId,NULL,1); actorFinder.find(root); // Create a dictionary of actor classes. // This dictionary is used to hold property dictionaries for each // actor class. That is, the keys to this dictionary are actor // class names, and the value returned is another dictionary that // indexes by property names (to property items). MleDwpStrKeyDict actorClassDict; // Loop over all the actors. // What we are going to do is find all the properties used for each // actor type. We do this by looking at each actor instance and take // the union of all the properties (checking to make sure that types // are consistent). // // The name of the actor type is found by searching for ActorTemplates // until none exist. The properties used in the ActorTemplates must // also be added to the list. // // The set of discriminators should already be set before calling this // method. Do this by calling the setDiscriminators() member function. int nActors = actorFinder.getNumItems(); MleDwpActor **actor = (MleDwpActor **)actorFinder.getItems(); for ( i = 0; i < nActors; i++ ) { // Find the actor class, possibly looking through multiple templates. MleDwpFinder tmplFinder( MleDwpActorTemplate::typeId, actor[i]->getActorClass()); MleDwpActorTemplate *tmpl = NULL; while ( tmplFinder.find(root) ) { tmpl = (MleDwpActorTemplate *)tmplFinder.getItem(); tmplFinder.setName(tmpl->getActorClass()); } // Find the property dictionary to use, based on actor class. MleDwpStrKeyDict *propDict = (MleDwpStrKeyDict *)actorClassDict.find( tmpl ? tmpl->getActorClass() : actor[i]->getActorClass()); // If there isn't one, create it and add it to the dictionary. // XXX These dictionaries are leaked. This is sloppy, but // harmless. Avoiding leaking these objects requires creating // a dictionary subclass that knows how to delete its values. if ( propDict == NULL ) { propDict = new MleDwpStrKeyDict; actorClassDict.set(actor[i]->getActorClass(),propDict); } // Look for properties and traverse to find the real class type // which may be hiding behind one or more templates. MleDwpItem *propCont = actor[i]; const char *actorClassName = actor[i]->getActorClass(); do { // Find all subordinate properties. MleDwpFinder propFinder(MleDwpProperty::typeId,NULL,1); propFinder.find(propCont); // Loop over all the properties. // Add each one to the property dictionary. The dictionary // will only remember the last one entered under a given // name, but that's okay. We'll check to see that the // types are consistent. int nProps = propFinder.getNumItems(); MleDwpProperty **prop = (MleDwpProperty **)propFinder.getItems(); for ( j = 0; j < nProps; j++ ) { // See if the dictionary already has one. MleDwpProperty *currentProp = (MleDwpProperty *)propDict->find(prop[j]->getName()); if ( currentProp ) { // Verify the types match. if ( currentProp->getDatatype() != prop[j]->getDatatype() ) { // Complain. // XXX use real error reporting. fprintf(stderr,"actor class %s property %s inconsistently used as %s and %s.\n", actor[i]->getActorClass(), currentProp->getName(), currentProp->getDatatype()->getName(), prop[j]->getDatatype()->getName()); } } else { // Add the property to the dictionary. propDict->set(prop[j]->getName(),prop[j]); } } // Look for a template. MleDwpFinder tmplFinder(MleDwpActorTemplate::typeId); propCont = (MleDwpItem *)tmplFinder.find(root); } while ( propCont ); } // Iterate through the actor class dictionary. MleDwpDictIter actorClassDictIter(actorClassDict); while ( actorClassDictIter.getKey() ) { MleDwpStrKeyDict *propDict = (MleDwpStrKeyDict *)actorClassDictIter.getValue(); // printf("actor class %s:\n",actorClassDictIter.getKey()); // Iterate through the list of properties. MleDwpDictIter propDictIter(*propDict); int nProps = 0; while ( propDictIter.getKey() ) { nProps++; buf[0] = '\0'; strcat(buf,(char *)actorClassDictIter.getKey()); strcat(buf,"_"); strcat(buf,(char *)propDictIter.getKey()); saveString(strdup(buf),&m_actorPropTable); // printf("\t%s (%s)\n", // propDictIter.getKey(), // ((MleDwpProperty *)propDictIter.getValue())->getDatatype()->getName()); propDictIter.next(); } char *headerFile = NULL; char *package = NULL; // Find the ActorDef item if it exists. MleDwpFinder actorDefFinder( MleDwpActorDef::typeId,(char *)actorClassDictIter.getKey()); MleDwpActorDef *actorDef = (MleDwpActorDef *)actorDefFinder.find(root); if ( actorDef == NULL ) { fprintf(stderr,"warning: ActorDef for %s not found.\n", actorClassDictIter.getKey()); } else { // Find the associated header file for this actor class. MleDwpFinder headerFileFinder(MleDwpHeaderFile::typeId); MleDwpHeaderFile *headerFileItem = (MleDwpHeaderFile *)headerFileFinder.find(actorDef); if (headerFileItem) { if (headerFile != NULL) mlFree(headerFile); headerFile = strdup(headerFileItem->getName()); } else headerFile = NULL; // Find the associated package for this actor class. MleDwpFinder packageFinder(MleDwpPackage::typeId); MleDwpPackage *packageItem = (MleDwpPackage *)packageFinder.find(actorDef); if (packageItem) { if (package != NULL) mlFree(package); package = strdup(packageItem->getName()); } else package = NULL; } saveActorClass(strdup((char *)actorClassDictIter.getKey()),nProps, headerFile,package,&m_actorClassTable); actorClassDictIter.next(); } // RTH shouldn't need to uniquify these any more // MSM however, they still need to be alphabetized in alphanumeric order if (m_actorPropTable.used > 0) { qsort((void *)m_actorClassTable.items,m_actorClassTable.used,sizeof(char *), ActorClassCompare); qsort((void *)m_actorPropTable.items,m_actorPropTable.used, sizeof(char *),StrMapCompare); for ( i = 1, j = 0 ; i<m_actorClassTable.used ; i++ ) { if (strcmp(((ActorClassTableItem *)m_actorClassTable.items[i])->name, ((ActorClassTableItem *)m_actorClassTable.items[j])->name) != 0) { m_actorClassTable.items[++j] = m_actorClassTable.items[i]; } } m_actorClassTable.used = j+1; for ( i = 1, j = 0 ; i < m_actorPropTable.used ; i++ ) { if ( strcmp((char *)m_actorPropTable.items[i], (char *)m_actorPropTable.items[j]) != 0 ) { m_actorPropTable.items[++j] = m_actorPropTable.items[i]; } } m_actorPropTable.used = j+1; } // PROCESS ROLE CLASS TABLE // Retrieve all role classes in the DWP. roleClassFinder.setType(MleDwpRoleBinding::typeId); roleClassFinder.setFindAll(1); roleClassFinder.find(root); roleClassItems = (MleDwpRoleBinding **)roleClassFinder.getItems(); numItems = roleClassFinder.getNumItems(); // // This error checking assumes that a Digital Workprint will // contain at least one role class. // if (roleClassItems == 0) { m_roleClassTable.used = 0; /* mlSetErrno(MLERR_MASTERLIB_NODELEGATECLASS); return FALSE; */ } else { // Iterate over the MleDwpRoleBinding items, extracting class names for (i = 0; i < numItems; i++) { const char *className = roleClassItems[i]->getName(); // Find the DeledageDef item if it exists. MleDwpFinder roleDefFinder( MleDwpRoleDef::typeId,(char *)className); MleDwpRoleDef *roleDef = (MleDwpRoleDef *)roleDefFinder.find(root); char *headerFile = NULL; char *package = NULL; if ( roleDef == NULL ) fprintf(stderr,"warning: RoleDef for %s not found.\n", className); else { // Find the associated header file for this role class. MleDwpFinder headerFileFinder(MleDwpHeaderFile::typeId); MleDwpHeaderFile *headerFileItem = (MleDwpHeaderFile *)headerFileFinder.find(roleDef); if (headerFileItem) headerFile = strdup(headerFileItem->getName()); else headerFile = NULL; // Find the associated package for this role class. MleDwpFinder packageFinder(MleDwpPackage::typeId); MleDwpPackage *packageItem = (MleDwpPackage *)packageFinder.find(roleDef); if (packageItem) package = strdup(packageItem->getName()); else package = NULL; // Skip NULL bindings. // Sometimes a NULL binding may be specified in order to // have MleSet::currentSet available to an actor. In // this case, we need to avoid declaring a creation function. if ( className && strcmp(className,"NULL") != NULL ) saveRoleClass((char *)className,headerFile,package,&m_roleClassTable); } } qsort((void *)m_roleClassTable.items,m_roleClassTable.used, sizeof(char *),RoleClassCompare); for ( i = 1, j = 0 ; i < m_roleClassTable.used ; i++ ) { if ( strcmp(((RoleClassTableItem *)m_roleClassTable.items[i])->name, ((RoleClassTableItem *)m_roleClassTable.items[j])->name) != 0 ) { m_roleClassTable.items[++j] = m_roleClassTable.items[i]; } } m_roleClassTable.used = j+1; } // PROCESS SET TYPE TABLE // Find all sets in the workprint. MleDwpFinder setFinder(MleDwpSet::typeId,NULL,1); setFinder.find(root); // Create a dictionary of set classes. // This dictionary is used to hold property dictionaries for each // set class. That is, the keys to this dictionary are set // class names, and the value returned is another dictionary that // indexes by property names (to property items). MleDwpStrKeyDict setClassDict; // Loop over all the sets. // What we are going to do is find all the properties used for each // set type. We do this by looking at each set instance and // take the union of all the properties (checking to make sure that // types are consistent). int nSets = setFinder.getNumItems(); MleDwpSet **set = (MleDwpSet **)setFinder.getItems(); for (i = 0; i < nSets; i++) { saveSet((char *)set[i]->getName(),(char *)set[i]->getType(), &m_setTable); // Find the property dictionary to use, based on set type. MleDwpStrKeyDict *propDict = (MleDwpStrKeyDict *)setClassDict.find(set[i]->getType()); // If there isn't one, create it and add it to the dictionary. // XXX These dictionaries are leaked. This is sloppy, but // harmless. Avoiding leaking these objects requires creating // a dictionary subclass that knows how to delete its values. if ( propDict == NULL ) { propDict = new MleDwpStrKeyDict; setClassDict.set(set[i]->getType(),propDict); } // Look for properties. MleDwpFinder propFinder(MleDwpProperty::typeId,NULL,1); propFinder.find(set[i]); // Loop over all the properties. // Add each one to the property dictionary. The dictionary // will only remember the last one entered under a given // name, but that's okay. We'll check to see that the // types are consistent. int nProps = propFinder.getNumItems(); MleDwpProperty **prop = (MleDwpProperty **)propFinder.getItems(); for ( j = 0; j < nProps; j++ ) { // See if the dictionary already has one. MleDwpProperty *currentProp = (MleDwpProperty *)propDict->find(prop[j]->getName()); if ( currentProp ) { // Verify the types match. if ( currentProp->getDatatype() != prop[j]->getDatatype() ) { // Complain. // XXX use real error reporting. fprintf(stderr,"set class %s property %s inconsistently used as %s and %s.\n", set[i]->getType(), currentProp->getName(), currentProp->getDatatype()->getName(), prop[j]->getDatatype()->getName()); } } else { // Add the property to the dictionary. propDict->set(prop[j]->getName(),prop[j]); } } } if ( m_setTable.used > 0 ) { m_setTable.used = mlUnique((void *)m_setTable.items, m_setTable.used, sizeof(SetTableItem *), SetNameCompare); #if 0 // Don't sort the set. The order of the set in the DWP is important. qsort((void *)setTable.items,m_setTable.used,sizeof(SetTableItem *), SetNameCompare); for ( i = 1, j = 0 ; i < m_setTable.used ; i++ ) { if ( strcmp(((SetTableItem *)m_setTable.items[i])->name, ((SetTableItem *)m_setTable.items[j])->name) != 0 ) { m_setTable.items[++j] = m_setTable.items[i]; } } m_setTable.used = j+1; #endif /* 0 */ } // Iterate through the set class dictionary. MleDwpDictIter setClassDictIter(setClassDict); while ( setClassDictIter.getKey() ) { // Get the property dictionary. MleDwpStrKeyDict *propDict = (MleDwpStrKeyDict *)setClassDictIter.getValue(); // Iterate through the list of properties. MleDwpDictIter propDictIter(*propDict); int nProps = 0; while ( propDictIter.getKey() ) { nProps++; buf[0] = '\0'; strcat(buf,(char *)setClassDictIter.getKey()); strcat(buf,"_"); strcat(buf,(char *)propDictIter.getKey()); saveString(strdup(buf),&m_setPropTable); propDictIter.next(); } // Find the SetDef item if it exists. MleDwpFinder setDefFinder( MleDwpSetDef::typeId,(char *)setClassDictIter.getKey()); MleDwpSetDef *setDef = (MleDwpSetDef *)setDefFinder.find(root); char *headerFile = NULL; char *package = NULL; if ( setDef == NULL ) fprintf(stderr,"warning: SetDef for %s not found.\n", setClassDictIter.getKey()); else { // Find the associated header file for this set class. MleDwpFinder headerFileFinder(MleDwpHeaderFile::typeId); headerFileFinder.find(setDef); MleDwpHeaderFile *headerFileItem = (MleDwpHeaderFile *) headerFileFinder.getItem(); if (headerFileItem) headerFile = strdup(headerFileItem->getName()); // Find the associated package for this actor class. MleDwpFinder packageFinder(MleDwpPackage::typeId); MleDwpPackage *packageItem = (MleDwpPackage *)packageFinder.find(setDef); if (packageItem) package = strdup(packageItem->getName()); else package = NULL; } saveSetClass(strdup((char *)setClassDictIter.getKey()), nProps, headerFile,package,&m_setClassTable); setClassDictIter.next(); } if (m_setPropTable.used > 0) { qsort((void *)m_setClassTable.items,m_setClassTable.used, sizeof(char *),SetClassCompare); qsort((void *)m_setPropTable.items,m_setPropTable.used, sizeof(char *),StrMapCompare); for ( i = 1, j = 0 ; i<m_setClassTable.used ; i++ ) { if (strcmp(((SetClassTableItem *)m_setClassTable.items[i])->name, ((SetClassTableItem *)m_setClassTable.items[j])->name) != 0) { m_setClassTable.items[++j] = m_setClassTable.items[i]; } } m_setClassTable.used = j+1; for ( i = 1, j = 0 ; i < m_setPropTable.used ; i++ ) { if ( strcmp((char *)m_setPropTable.items[i], (char *)m_setPropTable.items[j]) != 0 ) { m_setPropTable.items[++j] = m_setPropTable.items[i]; } } m_setPropTable.used = j+1; } // PROCESS MEDIAREF CLASS TABLE // Retrieve all mediaref classes in the DWP. mediarefClassFinder.setType(MleDwpMediaRef::typeId); mediarefClassFinder.setFindAll(1); mediarefClassFinder.find(root); mediarefClassItems = (MleDwpMediaRef **)mediarefClassFinder.getItems(); numItems = mediarefClassFinder.getNumItems(); // Iterate over the MleDwpMediaRef items, extracting class names. for (i = 0; i < numItems; i++) { char *headerFile = NULL; char *package = NULL; // Find the associated header file for this role class. MleDwpFinder headerFileFinder(MleDwpHeaderFile::typeId); MleDwpHeaderFile *headerFileItem = (MleDwpHeaderFile *)headerFileFinder.find(mediarefClassItems[i]); if (headerFileItem) headerFile = strdup(headerFileItem->getName()); else headerFile = NULL; // Find the associated package for this role class. MleDwpFinder packageFinder(MleDwpPackage::typeId); MleDwpPackage *packageItem = (MleDwpPackage *)packageFinder.find(mediarefClassItems[i]); if (packageItem) package = strdup(packageItem->getName()); else package = NULL; const char *className = mediarefClassItems[i]->getMediaRefClass(); saveMediaRefClass((char *)className,headerFile,package,&m_mediarefTable); } if (m_mediarefTable.used > 0) { qsort((void *)m_mediarefTable.items,m_mediarefTable.used, sizeof(char *),MediaRefClassCompare); for ( i = 1, j = 0 ; i < m_mediarefTable.used ; i++ ) { if ( strcmp(((MediaRefClassTableItem *)m_mediarefTable.items[i])->name, ((MediaRefClassTableItem *)m_mediarefTable.items[j])->name) != 0 ) { m_mediarefTable.items[++j] = m_mediarefTable.items[i]; } } m_mediarefTable.used = j+1; } // PROCESS GROUP TYPE TABLE // find all groups in the workprint MleDwpFinder groupFinder(MleDwpGroup::typeId,NULL,1); groupFinder.find(root); // Create a dictionary of group classes. // This dictionary is used to hold property dictionaries for each // actor class. That is, the keys to this dictionary are actor // class names, and the value returned is another dictionary that // indexes by property names (to property items). MleDwpStrKeyDict groupClassDict; // Loop over all the groups. // What we are going to do is find all the properties used for each // group type. We do this by looking at each group instance and // take the union of all the properties (checking to make sure that // types are consistent). int nGroups = groupFinder.getNumItems(); MleDwpGroup **group = (MleDwpGroup **)groupFinder.getItems(); for (i = 0; i < nGroups; i++) { char *headerFile = NULL; char *package = NULL; // Find the associated header file for this group class. MleDwpFinder headerFileFinder(MleDwpHeaderFile::typeId); MleDwpHeaderFile *headerFileItem = (MleDwpHeaderFile *)headerFileFinder.find(group[i]); if (headerFileItem) headerFile = strdup(headerFileItem->getName()); else headerFile = NULL; // Find the associated package for this actor class. MleDwpFinder packageFinder(MleDwpPackage::typeId); MleDwpPackage *packageItem = (MleDwpPackage *)packageFinder.find(group[i]); if (packageItem) package = strdup(packageItem->getName()); else package = NULL; // Save the class and the uniquely named instance for this group saveGroupClass((char *)group[i]->getGroupClass(),headerFile,package,&m_groupClassTable); saveGroupInstance((char *)group[i]->getName(),&m_groupInstanceTable); } // Uniqify the class names. The instance names are already expected to // be unique, so don\'t have to sort|unique them. // if (m_groupClassTable.used > 0) { qsort((void *)m_groupClassTable.items,m_groupClassTable.used,sizeof(GroupClassTableItem *), GroupClassCompare); for ( i = 1, j = 0 ; i < m_groupClassTable.used ; i++ ) { if ( strcmp(((GroupClassTableItem *)m_groupClassTable.items[i])->name, ((GroupClassTableItem *)m_groupClassTable.items[j])->name) != 0 ) { m_groupClassTable.items[++j] = m_groupClassTable.items[i]; } } m_groupClassTable.used = j+1; } // PROCESS SCENE TYPE TABLE // Find all scenes in the workprint. MleDwpFinder sceneFinder(MleDwpScene::typeId,NULL,1); sceneFinder.find(root); // Create a dictionary of scene classes. // This dictionary is used to hold property dictionaries for each // actor class. That is, the keys to this dictionary are actor // class names, and the value returned is another dictionary that // indexes by property names (to property items). MleDwpStrKeyDict sceneClassDict; // Loop over all the scenes. // What we are going to do is find all the properties used for each // scene type. We do this by looking at each scene instance and // take the union of all the properties (checking to make sure that // types are consistent). int nScenes = sceneFinder.getNumItems(); MleDwpScene **scene = (MleDwpScene **)sceneFinder.getItems(); for (i = 0; i < nScenes; i++) { char *headerFile = NULL; char *package = NULL; // Find the associated header file for this scene class. MleDwpFinder headerFileFinder(MleDwpHeaderFile::typeId); MleDwpHeaderFile *headerFileItem = (MleDwpHeaderFile *)headerFileFinder.find(scene[i]); if (headerFileItem) headerFile = strdup(headerFileItem->getName()); else headerFile = NULL; // Find the associated package for this actor class. MleDwpFinder packageFinder(MleDwpPackage::typeId); MleDwpPackage *packageItem = (MleDwpPackage *)packageFinder.find(scene[i]); if (packageItem) package = strdup(packageItem->getName()); else package = NULL; saveSceneClass((char *)scene[i]->getSceneClass(),headerFile,package,&m_sceneClassTable); } if (m_sceneClassTable.used > 0) { qsort((void *)m_sceneClassTable.items,m_sceneClassTable.used,sizeof(SceneClassTableItem *), SceneClassCompare); for ( i = 1, j = 0 ; i < m_sceneClassTable.used ; i++ ) { if ( strcmp(((SceneClassTableItem *)m_sceneClassTable.items[i])->name, ((SceneClassTableItem *)m_sceneClassTable.items[j])->name) != 0 ) { m_sceneClassTable.items[++j] = m_sceneClassTable.items[i]; } } m_sceneClassTable.used = j+1; } return TRUE; } /* * This function may be used during the mastering process to retrieve * the mastered index value for a known string. */ int MleDppTblMgr::mapStringToIndex( const char *name, TblMgrItems *strTable) { /* Declare local variables. */ int i; for (i = 0; i < strTable->used; i++) { if (! strcmp((char *)strTable->items[i],name)) return i; } return MLE_DPP_BADTBL_INDEX; } /* * This function may be used during the mastering process to retrieve * the mastered index value for a known actor class. */ int MleDppTblMgr::mapActorClassToIndex( const char *name, TblMgrItems *actorTable) { /* Declare local variables. */ int i; for (i = 0; i < actorTable->used; i++) { if (! strcmp(((ActorClassTableItem *)actorTable->items[i])->name,name)) return i; } return MLE_DPP_BADTBL_INDEX; } /* * This routine is used to access the MleRTActorClass table. */ int MleDppTblMgr::actorClassRuntimeName(const char *actorClass) { /* Declare local variables. */ int index; index = mapActorClassToIndex(actorClass,&m_actorClassTable); if (index == MLE_DPP_BADTBL_INDEX) mlSetErrno(MLE_E_MASTERLIB_BADTBLINDEX); return index; } /* * This function may be used during the mastering process to retrieve * the mastered index value for a known group class. */ int MleDppTblMgr::mapGroupClassToIndex( const char *name, TblMgrItems *groupTable) { /* Declare local variables. */ int i; for (i = 0; i < groupTable->used; i++) { if (! strcmp(((GroupClassTableItem *)groupTable->items[i])->name,name)) return i; } return MLE_DPP_BADTBL_INDEX; } /* * This function may be used during the mastering process to retrieve * the mastered index value for a known group instance. */ int MleDppTblMgr::mapGroupInstanceToIndex( const char *name, TblMgrItems *groupTable) { /* Declare local variables. */ int i; for (i = 0; i < groupTable->used; i++) { if (! strcmp(((GroupInstanceTableItem *)groupTable->items[i])->name,name)) return i; } return MLE_DPP_BADTBL_INDEX; } /* * This routine is used to access the MleRTGroupClass table. */ int MleDppTblMgr::groupClassRuntimeName(const char *groupClass) { /* Declare local variables. */ int index; index = mapGroupClassToIndex(groupClass,&m_groupClassTable); if (index == MLE_DPP_BADTBL_INDEX) mlSetErrno(MLE_E_MASTERLIB_BADTBLINDEX); return index; } /* * This routine is used to access the MleRTGroupInstance table. */ int MleDppTblMgr::groupInstanceRuntimeName(const char *groupInstance) { /* Declare local variables. */ int index; index = mapGroupInstanceToIndex(groupInstance,&m_groupInstanceTable); if (index == MLE_DPP_BADTBL_INDEX) mlSetErrno(MLE_E_MASTERLIB_BADTBLINDEX); return index; } /* * This function may be used during the mastering process to retrieve * the mastered index value for a known scene class. */ int MleDppTblMgr::mapSceneClassToIndex( const char *name, TblMgrItems *sceneTable) { /* Declare local variables. */ int i; for (i = 0; i < sceneTable->used; i++) { if (! strcmp(((SceneClassTableItem *)sceneTable->items[i])->name,name)) return i; } return MLE_DPP_BADTBL_INDEX; } /* * This routine is used to access the MleRTSceneClass table. */ int MleDppTblMgr::sceneClassRuntimeName(const char *sceneClass) { /* Declare local variables. */ int index; index = mapSceneClassToIndex(sceneClass,&m_sceneClassTable); if (index == MLE_DPP_BADTBL_INDEX) mlSetErrno(MLE_E_MASTERLIB_BADTBLINDEX); return index; } /* * This function may be used during the mastering process to retrieve * the mastered index value for a known role class. */ int MleDppTblMgr::mapRoleClassToIndex( const char *name, TblMgrItems *roleTable) { /* Declare local variables. */ int i; for (i = 0; i < roleTable->used; i++) { if (! strcmp(((RoleClassTableItem *)roleTable->items[i])->name,name)) return i; } return MLE_DPP_BADTBL_INDEX; } /* * This routine is used to access the MleRTRoleClass table. */ #if 0 /*** OBSOLETE ***/ int MleDppTblMgr::delegateClassRuntimeName(const char *delegateClass) { /* Declare local variables. */ int index; index = mapDelegateClassToIndex(delegateClass,&m_roleClassTable); if (index == MLE_DPP_BADTBL_INDEX) mlSetErrno(MLE_E_MASTERLIB_BADTBLINDEX); return index; } #endif /* 0 */ int MleDppTblMgr::roleClassRuntimeName(const char *roleClass) { /* Declare local variables. */ int index; index = mapRoleClassToIndex(roleClass,&m_roleClassTable); if (index == MLE_DPP_BADTBL_INDEX) mlSetErrno(MLE_E_MASTERLIB_BADTBLINDEX); return index; } /* * This routine is used to access the MleRTPropertyDesc table. */ int MleDppTblMgr::actorPropRuntimeName( const char *actorClass, const char *propertyName) { /* Declare local variables. */ int index; char *buf; /* Build name. */ buf = (char *)mlMalloc(strlen(actorClass)+1+strlen(propertyName)+1); strcpy(buf,actorClass); strcat(buf,"_"); strcat(buf,propertyName); index = mapStringToIndex(buf,&m_actorPropTable); mlFree(buf); if (index == MLE_DPP_BADTBL_INDEX) mlSetErrno(MLE_E_MASTERLIB_BADTBLINDEX); return index; } /* * This function may be used during the mastering process to retrieve * the mastered index value for a known set. */ int MleDppTblMgr::mapSetToIndex( const char *name, TblMgrItems *setTable) { /* Declare local variables. */ int i; for (i = 0; i < setTable->used; i++) { if (! strcmp(((SetTableItem *)setTable->items[i])->name,name)) return i; } return MLE_DPP_BADTBL_INDEX; } /* * This function may be used during the mastering process to retrieve * the mastered index value for a known set. */ int MleDppTblMgr::mapSetClassToIndex( const char *name, TblMgrItems *setTable) { /* Declare local variables. */ int i; for (i = 0; i < setTable->used; i++) { if (! strcmp(((SetClassTableItem *)setTable->items[i])->name,name)) return i; } return MLE_DPP_BADTBL_INDEX; } /* * This routine is used to access the MleRTSetDesc table. */ #if 0 /*** OBSOLETE ***/ int MleDppTblMgr::forumRuntimeName(const char *forumName) { /* Declare local variables. */ int index; index = mapForumToIndex(forumName,&m_setTable); if (index == MLE_DPP_BADTBL_INDEX) mlSetErrno(MLE_E_MASTERLIB_BADTBLINDEX); return index; } #endif /* 0 */ int MleDppTblMgr::setRuntimeName(const char *setName) { /* Declare local variables. */ int index; index = mapSetToIndex(setName,&m_setTable); if (index == MLE_DPP_BADTBL_INDEX) mlSetErrno(MLE_E_MASTERLIB_BADTBLINDEX); return index; } /* * This routine is used to access the MleRTSetDesc table. */ #if 0 /*** OBSOLETE ***/ int MleDppTblMgr::forumClassRuntimeName(const char *forumName) { /* Declare local variables. */ int index; index = mapForumClassToIndex(forumName,&m_setClassTable); if (index == MLE_DPP_BADTBL_INDEX) mlSetErrno(MLE_E_MASTERLIB_BADTBLINDEX); return index; } #endif /* 0 */ int MleDppTblMgr::setClassRuntimeName(const char *setName) { /* Declare local variables. */ int index; index = mapSetClassToIndex(setName,&m_setClassTable); if (index == MLE_DPP_BADTBL_INDEX) mlSetErrno(MLE_E_MASTERLIB_BADTBLINDEX); return index; } /* * This routine is used to access the MleRTSetProperties table. */ #if 0 /*** OBSOLETE ***/ int MleDppTblMgr::forumPropRuntimeName( const char *forumClass, const char *propertyName) { /* Declare local variables. */ int index; char *buf; /* Build name. */ buf = (char *)mlMalloc(strlen(forumClass)+1+strlen(propertyName)+1); strcpy(buf,forumClass); strcat(buf,"_"); strcat(buf,propertyName); index = mapStringToIndex(buf,&m_setPropTable); mlFree(buf); if (index == MLE_DPP_BADTBL_INDEX) mlSetErrno(MLE_E_MASTERLIB_BADTBLINDEX); return index; } #endif /* 0 */ int MleDppTblMgr::setPropRuntimeName( const char *setClass, const char *propertyName) { /* Declare local variables. */ int index; char *buf; /* Build name. */ buf = (char *)mlMalloc(strlen(setClass)+1+strlen(propertyName)+1); strcpy(buf,setClass); strcat(buf,"_"); strcat(buf,propertyName); index = mapStringToIndex(buf,&m_setPropTable); mlFree(buf); if (index == MLE_DPP_BADTBL_INDEX) mlSetErrno(MLE_E_MASTERLIB_BADTBLINDEX); return index; } /* * This function may be used during the mastering process to retrieve * the mastered index value for a known media reference class. */ int MleDppTblMgr::mapMediaRefClassToIndex( const char *name, TblMgrItems *mrefTable) { /* Declare local variables. */ int i; for (i = 0; i < mrefTable->used; i++) { if (! strcmp(((MediaRefClassTableItem *)mrefTable->items[i])->name,name)) return i; } return MLE_DPP_BADTBL_INDEX; } /* * This routine is used to access the MleRTMediaRef table. */ int MleDppTblMgr::mediarefClassRuntimeName(const char *mediarefClass) { /* Declare local variables */ int index; index = mapMediaRefClassToIndex(mediarefClass,&m_mediarefTable); if (index == MLE_DPP_BADTBL_INDEX) mlSetErrno(MLE_E_MASTERLIB_BADTBLINDEX); return index; } /* * This routine is used to set the Digital Workprint discriminators. * It expects a ':' deliminated string of tags to set multiple * discriminators. For example: * * tags = "brender:win32" */ MlBoolean MleDppTblMgr::setDiscriminators(MleDwpItem *tree, char *tags) { /* Declare local variables. */ char *processTags; char *tag,*nextTag; MleDwpTagAllDiscriminator *newDiscriminator = new MleDwpTagAllDiscriminator; if (! tags) { if (m_discriminator) { tree->setDiscriminator(NULL); delete m_discriminator; } return TRUE; } else { processTags = strdup(tags); } // Remove old discriminator. if (m_discriminator) { tree->setDiscriminator(NULL); delete m_discriminator; } tag = processTags; while (tag) { nextTag = strchr(tag,':'); if (nextTag) *nextTag++ = '\0'; newDiscriminator->addTag(tag); tag = nextTag; } tree->setDiscriminator(newDiscriminator); m_discriminator = newDiscriminator; mlFree(processTags); return TRUE; } void * MleDppTblMgr::operator new(size_t tSize) { void *p = mlMalloc(tSize); return p; } void MleDppTblMgr::operator delete(void *p) { mlFree(p); }
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/interprocess for documentation. // ////////////////////////////////////////////////////////////////////////////// #if defined BOOST_MSVC #pragma warning (pop) #ifdef BOOST_INTERPROCESS_CRT_SECURE_NO_DEPRECATE #undef BOOST_INTERPROCESS_CRT_SECURE_NO_DEPRECATE #undef _CRT_SECURE_NO_DEPRECATE #endif #endif
#ifndef TENSORFLOW_GRAPH_WRAPPER_HPP_ #define TENSORFLOW_GRAPH_WRAPPER_HPP_ #include <tensorflow/c/c_api.h> #include <cstdint> #include <string> #include <vector> #include <unordered_map> class TensorflowGraphWrapper { public: /** * @brief Loads a frozen protobuf graph definition * @details protobuf file should have all variables * as constants. This constructor will not restore any * checkpoints. The protobuf file must also be a binary file and not text * * @param filename name of protobuf file */ TensorflowGraphWrapper(const std::string& filename); ~TensorflowGraphWrapper(); /** * @brief get all the op names in the graph */ std::vector<std::string> get_op_names(); /** * @brief Sets up data about a possible input to the network * @details opname can be entered with or without the tensor index * Example: "layer1/weights" or "layer1/weights:0" * The opname you use here will be the same you use later in run() * * This wrapper can not currently handle variable size inputs. * * @param opname * @param shape shape of the input */ void add_input(const std::string& opname, const std::vector<int64_t>& shape); /** * @brief Sets up data about a possible output from the network * @details opname can be entered with or without the tensor index * Example: "layer1/weights" or "layer1/weights:0" * The opname you use here will be the same you use later in run() * * @param opname */ void add_output(const std::string& opname); /** * @brief Equivalent of sess.run() * @details outputs is the vector of fetched variables * Together (inputs, input_data) is like a feed_dict * NOTE: You will need to delete the output tensors data * using delete_tensors() or else you will have memory leaks * * @param input_data vector of outputs you want to compute from network * @param inputs dict of inputs you want to feed * @returns vector of output tensors. */ std::vector<TF_Tensor*> run(const std::vector<std::string>& outputs, const std::unordered_map<std::string, void*>& inputs); /** * @brief Extracts data from a tensor * @details will return a tuple of <pointer to data, data_type, vector of length of each dim> * the pointer will be need to be cast from void* * the data will in an order such that the last dimension will be contiguous * and then will work its way to the first dimension * For example, for an n by m matrix, the first n elements of the data * will be the first row, the next n elements will be the second row, and so on * Note: this data will be invalidated after running delete_tensors() * * @param tensor tensor to extract data from * @return tuple */ static std::tuple<void*, TF_DataType, std::vector<int64_t>> get_tensor_data(TF_Tensor* tensor); /** * @brief Clean up memory of a vector of tensors * @details this will invalidate any data returned from get_tensor_data() * * @param tensors vector of tensors to delete */ static void delete_tensors(std::vector<TF_Tensor*>& tensors); /** * @brief Prints a 1d or 2d vector * @details currently only prints floats * * @param tensor tensor to print */ static void print_tensor(TF_Tensor* tensor); private: struct InputInfo { TF_Output input; TF_DataType data_type; std::vector<int64_t> shape; size_t num_bytes; }; static TF_Buffer* load_pb_file(const std::string& filename); std::pair<std::string, int> parse_opstring(std::string opstring); TF_Graph* _graph; TF_Status* _status; // used to hold all statuses about TF operations TF_SessionOptions* _sess_opts; TF_Session * _session; std::unordered_map<std::string, TF_Output> _output_map; std::unordered_map<std::string, InputInfo> _input_map; }; #endif /* #define TENSORFLOW_GRAPH_WRAPPER_HPP_ */
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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. ----------------------------------------------------------------------------- PCZCamera.cpp - description ----------------------------------------------------------------------------- begin : Wed Feb 21 2007 author : Eric Cha email : ericc@xenopi.com ----------------------------------------------------------------------------- */ #include "OgreAxisAlignedBox.h" #include "OgrePCZCamera.h" #include "OgrePCZFrustum.h" #include "OgrePortal.h" namespace Ogre { PCZCamera::PCZCamera( const String& name, SceneManager* sm ) : Camera( name, sm ) { mBox.setExtents(-0.1, -0.1, -0.1, 0.1, 0.1, 0.1); mExtraCullingFrustum.setUseOriginPlane(true); } PCZCamera::~PCZCamera() { } const AxisAlignedBox& PCZCamera::getBoundingBox(void) const { return mBox; } // this version checks against extra culling planes bool PCZCamera::isVisible( const AxisAlignedBox &bound, FrustumPlane *culledBy) const { // Null boxes always invisible if ( bound.isNull() ) return false; // Make any pending updates to the calculated frustum planes updateFrustumPlanes(); // check extra culling planes bool extraResults; extraResults = mExtraCullingFrustum.isVisible(bound); if (!extraResults) { return false; } // check "regular" camera frustum bool regcamresults = Camera::isVisible(bound, culledBy); if (!regcamresults) { // culled by regular culling planes return regcamresults; } return true; } /* A 'more detailed' check for visibility of an AAB. This function returns none, partial, or full for visibility of the box. This is useful for stuff like Octree leaf culling */ PCZCamera::Visibility PCZCamera::getVisibility( const AxisAlignedBox &bound ) { // Null boxes always invisible if ( bound.isNull() ) return NONE; // Get centre of the box Vector3 centre = bound.getCenter(); // Get the half-size of the box Vector3 halfSize = bound.getHalfSize(); bool all_inside = true; for ( int plane = 0; plane < 6; ++plane ) { // Skip far plane if infinite view frustum if (plane == FRUSTUM_PLANE_FAR && mFarDist == 0) continue; // This updates frustum planes and deals with cull frustum Plane::Side side = getFrustumPlane(plane).getSide(centre, halfSize); if(side == Plane::NEGATIVE_SIDE) return NONE; // We can't return now as the box could be later on the negative side of a plane. if(side == Plane::BOTH_SIDE) all_inside = false; } switch(mExtraCullingFrustum.getVisibility(bound)) { case PCZFrustum::NONE: return NONE; case PCZFrustum::PARTIAL: return PARTIAL; case PCZFrustum::FULL: break; } if ( all_inside ) return FULL; else return PARTIAL; } /* isVisible() function for portals */ // NOTE: Everything needs to be updated spatially before this function is // called including portal corners, frustum planes, etc. bool PCZCamera::isVisible(PortalBase* portal, FrustumPlane* culledBy) const { // if portal isn't enabled, it's not visible if (!portal->getEnabled()) return false; // check the extra frustum first if (!mExtraCullingFrustum.isVisible(portal)) { return false; } // if portal is of type AABB or Sphere, then use simple bound check against planes if (portal->getType() == PortalBase::PORTAL_TYPE_AABB) { AxisAlignedBox aabb; aabb.setExtents(portal->getDerivedCorner(0), portal->getDerivedCorner(1)); return Camera::isVisible(aabb, culledBy); } else if (portal->getType() == PortalBase::PORTAL_TYPE_SPHERE) { return Camera::isVisible(portal->getDerivedSphere(), culledBy); } // only do this check if it's a portal. (anti portal doesn't care about facing) if (portal->getTypeFlags() == PortalFactory::FACTORY_TYPE_FLAG) { // check if the portal norm is facing the camera Vector3 cameraToPortal = portal->getDerivedCP() - getDerivedPosition(); Vector3 portalDirection = portal->getDerivedDirection(); Real dotProduct = cameraToPortal.dotProduct(portalDirection); if ( dotProduct > 0 ) { // portal is faced away from camera return false; } } // check against regular frustum planes bool visible_flag; if (mCullFrustum) { // For each frustum plane, see if all points are on the negative side // If so, object is not visible // NOTE: We skip the NEAR plane (plane #0) because Portals need to // be visible no matter how close you get to them. for (int plane = 1; plane < 6; ++plane) { // set the visible flag to false visible_flag = false; // Skip far plane if infinite view frustum if (plane == FRUSTUM_PLANE_FAR && mFarDist == 0) continue; // we have to check each corner of the portal for (int corner = 0; corner < 4; corner++) { Plane::Side side = mCullFrustum->getFrustumPlane(plane).getSide(portal->getDerivedCorner(corner)); if (side != Plane::NEGATIVE_SIDE) { visible_flag = true; break; } } // if the visible_flag is still false, then this plane // culled all the portal points if (visible_flag == false) { // ALL corners on negative side therefore out of view if (culledBy) *culledBy = (FrustumPlane)plane; return false; } } } else { // Make any pending updates to the calculated frustum planes Frustum::updateFrustumPlanes(); // For each frustum plane, see if all points are on the negative side // If so, object is not visible // NOTE: We skip the NEAR plane (plane #0) because Portals need to // be visible no matter how close you get to them. // BUGBUG: This can cause a false positive situation when a portal is // behind the camera but close. This could be fixed by having another // culling plane at the camera location with normal same as camera direction. for (int plane = 1; plane < 6; ++plane) { // set the visible flag to false visible_flag = false; // Skip far plane if infinite view frustum if (plane == FRUSTUM_PLANE_FAR && mFarDist == 0) continue; // we have to check each corner of the portal for (int corner = 0; corner < 4; corner++) { Plane::Side side = mFrustumPlanes[plane].getSide(portal->getDerivedCorner(corner)); if (side != Plane::NEGATIVE_SIDE) { visible_flag = true; break; } } // if the visible_flag is still false, then this plane // culled all the portal points if (visible_flag == false) { // ALL corners on negative side therefore out of view if (culledBy) *culledBy = (FrustumPlane)plane; return false; } } } // no plane culled all the portal points and the norm // was facing the camera, so this portal is visible return true; } /// Sets the type of projection to use (orthographic or perspective). void PCZCamera::setProjectionType(ProjectionType pt) { mExtraCullingFrustum.setProjectionType(pt); Camera::setProjectionType(pt); } /* Update function (currently used for making sure the origin stuff for the extra culling frustum is up to date */ void PCZCamera::update(void) { // make sure the extra culling frustum origin stuff is up to date if (mProjType == PT_PERSPECTIVE) //if (!mCustomViewMatrix) { mExtraCullingFrustum.setUseOriginPlane(true); mExtraCullingFrustum.setOrigin(getDerivedPosition()); mExtraCullingFrustum.setOriginPlane(getDerivedDirection(), getDerivedPosition()); } else { // In ortho mode, we don't want to cull things behind camera. // This helps for back casting which is useful for texture shadow projection on directional light. mExtraCullingFrustum.setUseOriginPlane(false); } } // calculate extra culling planes from portal and camera // origin and add to list of extra culling planes // NOTE: returns 0 if portal was completely culled by existing planes // returns > 0 if culling planes are added (# is planes added) int PCZCamera::addPortalCullingPlanes(PortalBase* portal) { // add the extra culling planes from the portal return mExtraCullingFrustum.addPortalCullingPlanes(portal); } // remove extra culling planes created from the given portal // NOTE: This should only be used during visibility traversal (backing out of a recursion) void PCZCamera::removePortalCullingPlanes(PortalBase* portal) { mExtraCullingFrustum.removePortalCullingPlanes(portal); } // remove all extra culling planes void PCZCamera::removeAllExtraCullingPlanes(void) { mExtraCullingFrustum.removeAllCullingPlanes(); } }
#include "sendcoinsentry.h" #include "ui_sendcoinsentry.h" #include "guiutil.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "walletmodel.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include <QApplication> #include <QClipboard> SendCoinsEntry::SendCoinsEntry(QWidget *parent) : QFrame(parent), ui(new Ui::SendCoinsEntry), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC ui->payToLayout->setSpacing(4); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book")); ui->payTo->setPlaceholderText(tr("Enter a COINSDADDY address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)")); #endif setFocusPolicy(Qt::TabFocus); setFocusProxy(ui->payTo); GUIUtil::setupAddressWidget(ui->payTo, this); } SendCoinsEntry::~SendCoinsEntry() { delete ui; } void SendCoinsEntry::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void SendCoinsEntry::on_addressBookButton_clicked() { if(!model) return; AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if(dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->payAmount->setFocus(); } } void SendCoinsEntry::on_payTo_textChanged(const QString &address) { if(!model) return; // Fill in label from address book, if address has an associated label QString associatedLabel = model->getAddressTableModel()->labelForAddress(address); if(!associatedLabel.isEmpty()) ui->addAsLabel->setText(associatedLabel); } void SendCoinsEntry::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel()) connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged())); clear(); } void SendCoinsEntry::setRemoveEnabled(bool enabled) { ui->deleteButton->setEnabled(enabled); } void SendCoinsEntry::clear() { ui->payTo->clear(); ui->addAsLabel->clear(); ui->payAmount->clear(); ui->payTo->setFocus(); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void SendCoinsEntry::on_deleteButton_clicked() { emit removeEntry(this); } bool SendCoinsEntry::validate() { // Check input validity bool retval = true; if(!ui->payAmount->validate()) { retval = false; } else { if(ui->payAmount->value() <= 0) { // Cannot send 0 coins or less ui->payAmount->setValid(false); retval = false; } } if(!ui->payTo->hasAcceptableInput() || (model && !model->validateAddress(ui->payTo->text()))) { ui->payTo->setValid(false); retval = false; } return retval; } SendCoinsRecipient SendCoinsEntry::getValue() { SendCoinsRecipient rv; rv.address = ui->payTo->text(); rv.label = ui->addAsLabel->text(); rv.amount = ui->payAmount->value(); return rv; } QWidget *SendCoinsEntry::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, ui->payTo); QWidget::setTabOrder(ui->payTo, ui->addressBookButton); QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton); QWidget::setTabOrder(ui->pasteButton, ui->deleteButton); QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel); return ui->payAmount->setupTabChain(ui->addAsLabel); } void SendCoinsEntry::setValue(const SendCoinsRecipient &value) { ui->payTo->setText(value.address); ui->addAsLabel->setText(value.label); ui->payAmount->setValue(value.amount); } bool SendCoinsEntry::isClear() { return ui->payTo->text().isEmpty(); } void SendCoinsEntry::setFocus() { ui->payTo->setFocus(); } void SendCoinsEntry::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update payAmount with the current unit ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); } }
// 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. #include "wallet.h" #include "base58.h" #include "coincontrol.h" #include "kernel.h" #include "main.h" #include "net.h" #include "util.h" #include "txdb.h" #include "ui_interface.h" #include "walletdb.h" #include "crypter.h" #include "key.h" #include "spork.h" #include "darksend.h" #include "instantx.h" #include "masternodeman.h" #include "masternode-payments.h" #include "chainparams.h" #include "smessage.h" #include <boost/algorithm/string/replace.hpp> using namespace std; // Settings int64_t nTransactionFee = MIN_TX_FEE; int64_t nReserveBalance = 0; int64_t nMinimumInputValue = 0; //static int64_t stakeCombineThreshold() { return 20 * COIN; } extern int64_t stakeCombineThreshold; static int64_t GetStakeSplitThreshold() { return 2 * stakeCombineThreshold; } ////////////////////////////////////////////////////////////////////////////// // // mapWallet // struct CompareValueOnly { bool operator()(const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t1, const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t2) const { return t1.first < t2.first; } }; const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const { LOCK(cs_wallet); std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash); if (it == mapWallet.end()) return NULL; return &(it->second); } CPubKey CWallet::GenerateNewKey() { AssertLockHeld(cs_wallet); // mapKeyMetadata bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets CKey secret; secret.MakeNewKey(fCompressed); // Compressed public keys were introduced in version 0.6.0 if (fCompressed) SetMinVersion(FEATURE_COMPRPUBKEY); CPubKey pubkey = secret.GetPubKey(); assert(secret.VerifyPubKey(pubkey)); // Create new metadata int64_t nCreationTime = GetTime(); mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime); if (!nTimeFirstKey || nCreationTime < nTimeFirstKey) nTimeFirstKey = nCreationTime; if (!AddKeyPubKey(secret, pubkey)) throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed"); return pubkey; } bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey) { AssertLockHeld(cs_wallet); // mapKeyMetadata if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) return false; // check if we need to remove from watch-only CScript script; script = GetScriptForDestination(pubkey.GetID()); if (HaveWatchOnly(script)) RemoveWatchOnly(script); if (!fFileBacked) return true; if (!IsCrypted()) { return CWalletDB(strWalletFile).WriteKey(pubkey, secret.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]); } return true; } bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret) { if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; if (!fFileBacked) return true; { LOCK(cs_wallet); if (pwalletdbEncryption) return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]); else return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]); } return false; } bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta) { AssertLockHeld(cs_wallet); // mapKeyMetadata if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey)) nTimeFirstKey = meta.nCreateTime; mapKeyMetadata[pubkey.GetID()] = meta; return true; } bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); } bool CWallet::AddCScript(const CScript& redeemScript) { if (!CCryptoKeyStore::AddCScript(redeemScript)) return false; if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript); } // optional setting to unlock wallet for staking only // serves to disable the trivial sendmoney when OS account compromised // provides no real security bool fWalletUnlockStakingOnly = false; bool CWallet::LoadCScript(const CScript& redeemScript) { /* A sanity check was added in pull #3843 to avoid adding redeemScripts * that never can be redeemed. However, old wallets may still contain * these. Do not add them to the wallet and warn. */ if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE) { std::string strAddr = CExclusivecoinAddress(redeemScript.GetID()).ToString(); LogPrintf("%s: Warning: This wallet contains a redeemScript of size %u which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n", __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr); return true; } return CCryptoKeyStore::AddCScript(redeemScript); } bool CWallet::AddWatchOnly(const CScript &dest) { if (!CCryptoKeyStore::AddWatchOnly(dest)) return false; nTimeFirstKey = 1; // No birthday information for watch-only keys. if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteWatchOnly(dest); } bool CWallet::RemoveWatchOnly(const CScript &dest) { AssertLockHeld(cs_wallet); if (!CCryptoKeyStore::RemoveWatchOnly(dest)) return false; if (!HaveWatchOnly()) NotifyWatchonlyChanged(false); if (fFileBacked) if (!CWalletDB(strWalletFile).EraseWatchOnly(dest)) return false; return true; } bool CWallet::LoadWatchOnly(const CScript &dest) { return CCryptoKeyStore::AddWatchOnly(dest); } bool CWallet::Lock() { if (IsLocked()) return true; if (fDebug) printf("Locking wallet.\n"); { LOCK(cs_wallet); CWalletDB wdb(strWalletFile); // -- load encrypted spend_secret of stealth addresses CStealthAddress sxAddrTemp; std::set<CStealthAddress>::iterator it; for (it = stealthAddresses.begin(); it != stealthAddresses.end(); ++it) { if (it->scan_secret.size() < 32) continue; // stealth address is not owned // -- CStealthAddress are only sorted on spend_pubkey CStealthAddress &sxAddr = const_cast<CStealthAddress&>(*it); if (fDebug) printf("Recrypting stealth key %s\n", sxAddr.Encoded().c_str()); sxAddrTemp.scan_pubkey = sxAddr.scan_pubkey; if (!wdb.ReadStealthAddress(sxAddrTemp)) { printf("Error: Failed to read stealth key from db %s\n", sxAddr.Encoded().c_str()); continue; } sxAddr.spend_secret = sxAddrTemp.spend_secret; }; } return LockKeyStore(); }; bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool anonymizeOnly) { SecureString strWalletPassphraseFinal; if(!IsLocked()) { fWalletUnlockAnonymizeOnly = anonymizeOnly; return true; } strWalletPassphraseFinal = strWalletPassphrase; CCrypter crypter; CKeyingMaterial vMasterKey; { LOCK(cs_wallet); BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if(!crypter.SetKeyFromPassphrase(strWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) return false; if (!CCryptoKeyStore::Unlock(vMasterKey)) return false; break; } fWalletUnlockAnonymizeOnly = anonymizeOnly; UnlockStealthAddresses(vMasterKey); SecureMsgWalletUnlocked(); return true; } return false; } bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase) { bool fWasLocked = IsLocked(); SecureString strOldWalletPassphraseFinal; strOldWalletPassphraseFinal = strOldWalletPassphrase; { LOCK(cs_wallet); Lock(); CCrypter crypter; CKeyingMaterial vMasterKey; BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if(!crypter.SetKeyFromPassphrase(strOldWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) return false; if (CCryptoKeyStore::Unlock(vMasterKey) && UnlockStealthAddresses(vMasterKey)) { int64_t nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (pMasterKey.second.nDeriveIterations < 25000) pMasterKey.second.nDeriveIterations = 25000; LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey)) return false; CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second); if (fWasLocked) Lock(); return true; } } } return false; } void CWallet::SetBestChain(const CBlockLocator& loc) { CWalletDB walletdb(strWalletFile); walletdb.WriteBestBlock(loc); } bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit) { LOCK(cs_wallet); // nWalletVersion if (nWalletVersion >= nVersion) return true; // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way if (fExplicit && nVersion > nWalletMaxVersion) nVersion = FEATURE_LATEST; nWalletVersion = nVersion; if (nVersion > nWalletMaxVersion) nWalletMaxVersion = nVersion; if (fFileBacked) { CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile); if (nWalletVersion > 40000) pwalletdb->WriteMinVersion(nWalletVersion); if (!pwalletdbIn) delete pwalletdb; } return true; } bool CWallet::SetMaxVersion(int nVersion) { LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion // cannot downgrade below current version if (nWalletVersion > nVersion) return false; nWalletMaxVersion = nVersion; return true; } set<uint256> CWallet::GetConflicts(const uint256& txid) const { set<uint256> result; AssertLockHeld(cs_wallet); std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid); if (it == mapWallet.end()) return result; const CWalletTx& wtx = it->second; std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range; BOOST_FOREACH(const CTxIn& txin, wtx.vin) { if (mapTxSpends.count(txin.prevout) <= 1) continue; // No conflict if zero or one spends range = mapTxSpends.equal_range(txin.prevout); for (TxSpends::const_iterator it = range.first; it != range.second; ++it) result.insert(it->second); } return result; } void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range) { // We want all the wallet transactions in range to have the same metadata as // the oldest (smallest nOrderPos). // So: find smallest nOrderPos: int nMinOrderPos = std::numeric_limits<int>::max(); const CWalletTx* copyFrom = NULL; for (TxSpends::iterator it = range.first; it != range.second; ++it) { const uint256& hash = it->second; int n = mapWallet[hash].nOrderPos; if (n < nMinOrderPos) { nMinOrderPos = n; copyFrom = &mapWallet[hash]; } } // Now copy data from copyFrom to rest: for (TxSpends::iterator it = range.first; it != range.second; ++it) { const uint256& hash = it->second; CWalletTx* copyTo = &mapWallet[hash]; if (copyFrom == copyTo) continue; copyTo->mapValue = copyFrom->mapValue; copyTo->vOrderForm = copyFrom->vOrderForm; // fTimeReceivedIsTxTime not copied on purpose // nTimeReceived not copied on purpose copyTo->nTimeSmart = copyFrom->nTimeSmart; copyTo->fFromMe = copyFrom->fFromMe; copyTo->strFromAccount = copyFrom->strFromAccount; // nOrderPos not copied on purpose // cached members not copied on purpose } } // Outpoint is spent if any non-conflicted transaction // spends it: bool CWallet::IsSpent(const uint256& hash, unsigned int n) const { const COutPoint outpoint(hash, n); pair<TxSpends::const_iterator, TxSpends::const_iterator> range; range = mapTxSpends.equal_range(outpoint); for (TxSpends::const_iterator it = range.first; it != range.second; ++it) { const uint256& wtxid = it->second; std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid); if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0) return true; // Spent } return false; } void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid) { mapTxSpends.insert(make_pair(outpoint, wtxid)); pair<TxSpends::iterator, TxSpends::iterator> range; range = mapTxSpends.equal_range(outpoint); SyncMetaData(range); } void CWallet::AddToSpends(const uint256& wtxid) { assert(mapWallet.count(wtxid)); CWalletTx& thisTx = mapWallet[wtxid]; if (thisTx.IsCoinBase()) // Coinbases don't spend anything! return; BOOST_FOREACH(const CTxIn& txin, thisTx.vin) AddToSpends(txin.prevout, wtxid); } bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) { if (IsCrypted()) return false; CKeyingMaterial vMasterKey; RandAddSeedPerfmon(); vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE); if (!GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE)) return false; CMasterKey kMasterKey(nDerivationMethodIndex); RandAddSeedPerfmon(); kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE); if (!GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE)) return false; CCrypter crypter; int64_t nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime)); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (kMasterKey.nDeriveIterations < 25000) kMasterKey.nDeriveIterations = 25000; LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey)) return false; { LOCK(cs_wallet); mapMasterKeys[++nMasterKeyMaxID] = kMasterKey; if (fFileBacked) { pwalletdbEncryption = new CWalletDB(strWalletFile); if (!pwalletdbEncryption->TxnBegin()) return false; pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey); } if (!EncryptKeys(vMasterKey)) { if (fFileBacked) pwalletdbEncryption->TxnAbort(); exit(1); //We now probably have half of our keys encrypted in memory, and half not...die and let the user reload their unencrypted wallet. } std::set<CStealthAddress>::iterator it; for (it = stealthAddresses.begin(); it != stealthAddresses.end(); ++it) { if (it->scan_secret.size() < 32) continue; // stealth address is not owned // -- CStealthAddress is only sorted on spend_pubkey CStealthAddress &sxAddr = const_cast<CStealthAddress&>(*it); if (fDebug) printf("Encrypting stealth key %s\n", sxAddr.Encoded().c_str()); std::vector<unsigned char> vchCryptedSecret; CSecret vchSecret; vchSecret.resize(32); memcpy(&vchSecret[0], &sxAddr.spend_secret[0], 32); uint256 iv = Hash(sxAddr.spend_pubkey.begin(), sxAddr.spend_pubkey.end()); if (!EncryptSecret(vMasterKey, vchSecret, iv, vchCryptedSecret)) { printf("Error: Failed encrypting stealth key %s\n", sxAddr.Encoded().c_str()); continue; }; sxAddr.spend_secret = vchCryptedSecret; pwalletdbEncryption->WriteStealthAddress(sxAddr); }; // Encryption was introduced in version 0.4.0 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true); if (fFileBacked) { if (!pwalletdbEncryption->TxnCommit()) exit(1); //We now have keys encrypted in memory, but no on disk...die to avoid confusion and let the user reload their unencrypted wallet. delete pwalletdbEncryption; pwalletdbEncryption = NULL; } Lock(); Unlock(strWalletPassphrase); NewKeyPool(); Lock(); // Need to completely rewrite the wallet file; if we don't, bdb might keep // bits of the unencrypted private key in slack space in the database file. CDB::Rewrite(strWalletFile); } NotifyStatusChanged(this); return true; } int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb) { AssertLockHeld(cs_wallet); // nOrderPosNext int64_t nRet = nOrderPosNext++; if (pwalletdb) { pwalletdb->WriteOrderPosNext(nOrderPosNext); } else { CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext); } return nRet; } void CWallet::MarkDirty() { { LOCK(cs_wallet); BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) item.second.MarkDirty(); } } bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet) { uint256 hash = wtxIn.GetHash(); if (fFromLoadWallet) { mapWallet[hash] = wtxIn; CWalletTx& wtx = mapWallet[hash]; wtx.BindWallet(this); wtxOrdered.insert(make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0))); AddToSpends(hash); } else { LOCK(cs_wallet); // Inserts only if not already there, returns tx inserted or tx found pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn)); CWalletTx& wtx = (*ret.first).second; wtx.BindWallet(this); bool fInsertedNew = ret.second; if (fInsertedNew) { wtx.nTimeReceived = GetAdjustedTime(); wtx.nOrderPos = IncOrderPosNext(); wtxOrdered.insert(make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0))); wtx.nTimeSmart = wtx.nTimeReceived; if (wtxIn.hashBlock != 0) { if (mapBlockIndex.count(wtxIn.hashBlock)) { unsigned int latestNow = wtx.nTimeReceived; unsigned int latestEntry = 0; { // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future int64_t latestTolerated = latestNow + 300; const TxItems & txOrdered = wtxOrdered; for (TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx == &wtx) continue; CAccountingEntry *const pacentry = (*it).second.second; int64_t nSmartTime; if (pwtx) { nSmartTime = pwtx->nTimeSmart; if (!nSmartTime) nSmartTime = pwtx->nTimeReceived; } else nSmartTime = pacentry->nTime; if (nSmartTime <= latestTolerated) { latestEntry = nSmartTime; if (nSmartTime > latestNow) latestNow = nSmartTime; break; } } } unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime; wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow)); } else LogPrintf("AddToWallet() : found %s in block %s not in index\n", wtxIn.GetHash().ToString(), wtxIn.hashBlock.ToString()); } } bool fUpdated = false; if (!fInsertedNew) { // Merge if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock) { wtx.hashBlock = wtxIn.hashBlock; fUpdated = true; } if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex)) { wtx.vMerkleBranch = wtxIn.vMerkleBranch; wtx.nIndex = wtxIn.nIndex; fUpdated = true; } if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe) { wtx.fFromMe = wtxIn.fFromMe; fUpdated = true; } fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent); } //// debug print LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : "")); // Write to disk if (fInsertedNew || fUpdated) if (!wtx.WriteToDisk()) return false; // Break debit/credit balance caches: wtx.MarkDirty(); // Notify UI of new or updated transaction NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED); // notify an external script when a wallet transaction comes in or is updated std::string strCmd = GetArg("-walletnotify", ""); if ( !strCmd.empty()) { boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } } return true; } // Add a transaction to the wallet, or update it. // pblock is optional, but should be provided if the transaction is known to be in a block. // If fUpdate is true, existing transactions will be updated. bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate) { uint256 hash = tx.GetHash(); { LOCK(cs_wallet); bool fExisted = mapWallet.count(hash); if (fExisted && !fUpdate) return false; mapValue_t mapNarr; FindStealthTransactions(tx, mapNarr); if (fExisted || IsMine(tx) || IsFromMe(tx)) { CWalletTx wtx(this,tx); if (!mapNarr.empty()) wtx.mapValue.insert(mapNarr.begin(), mapNarr.end()); // Get merkle branch if transaction was found in a block if (pblock) wtx.SetMerkleBranch(pblock); return AddToWallet(wtx); } } return false; } void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock, bool fConnect) { LOCK2(cs_main, cs_wallet); if (!AddToWalletIfInvolvingMe(tx, pblock, true)) return; // Not one of ours // If a transaction changes 'conflicted' state, that changes the balance // available of the outputs it spends. So force those to be // recomputed, also: BOOST_FOREACH(const CTxIn& txin, tx.vin) { if (mapWallet.count(txin.prevout.hash)) mapWallet[txin.prevout.hash].MarkDirty(); } if (!fConnect) { // wallets need to refund inputs when disconnecting coinstake if (tx.IsCoinStake()) { if (IsFromMe(tx)) DisableTransaction(tx); } return; } AddToWalletIfInvolvingMe(tx, pblock, true); } void CWallet::EraseFromWallet(const uint256 &hash) { if (!fFileBacked) return; { LOCK(cs_wallet); if (mapWallet.erase(hash)) CWalletDB(strWalletFile).EraseTx(hash); } return; } isminetype CWallet::IsMine(const CTxIn &txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) return IsMine(prev.vout[txin.prevout.n]); } } return ISMINE_NO; } CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) if (IsMine(prev.vout[txin.prevout.n]) & filter) return prev.vout[txin.prevout.n].nValue; } } return 0; } // Recursively determine the rounds of a given input (How deep is the Darksend chain for a given input) int CWallet::GetRealInputDarksendRounds(CTxIn in, int rounds) const { static std::map<uint256, CTransaction> mDenomWtxes; if(rounds >= 16) return 15; // 16 rounds max uint256 hash = in.prevout.hash; unsigned int nout = in.prevout.n; const CWalletTx* wtx = GetWalletTx(hash); if(wtx != NULL) { std::map<uint256, CTransaction>::const_iterator mdwi = mDenomWtxes.find(hash); // not known yet, let's add it if(mdwi == mDenomWtxes.end()) { LogPrint("darksend", "GetInputDarksendRounds INSERTING %s\n", hash.ToString()); mDenomWtxes[hash] = CTransaction(*wtx); } // found and it's not an initial value, just return it else if(mDenomWtxes[hash].vout[nout].nRounds != -10) { return mDenomWtxes[hash].vout[nout].nRounds; } // bounds check if(nout >= wtx->vout.size()) { // should never actually hit this LogPrint("darksend", "GetInputDarksendRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, -4); return -4; } if(pwalletMain->IsCollateralAmount(wtx->vout[nout].nValue)) { mDenomWtxes[hash].vout[nout].nRounds = -3; LogPrint("darksend", "GetInputDarksendRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds); return mDenomWtxes[hash].vout[nout].nRounds; } //make sure the final output is non-denominate if(/*rounds == 0 && */!IsDenominatedAmount(wtx->vout[nout].nValue)) //NOT DENOM { mDenomWtxes[hash].vout[nout].nRounds = -2; LogPrint("darksend", "GetInputDarksendRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds); return mDenomWtxes[hash].vout[nout].nRounds; } bool fAllDenoms = true; BOOST_FOREACH(CTxOut out, wtx->vout) { fAllDenoms = fAllDenoms && IsDenominatedAmount(out.nValue); } // this one is denominated but there is another non-denominated output found in the same tx if(!fAllDenoms) { mDenomWtxes[hash].vout[nout].nRounds = 0; LogPrint("darksend", "GetInputDarksendRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds); return mDenomWtxes[hash].vout[nout].nRounds; } int nShortest = -10; // an initial value, should be no way to get this by calculations bool fDenomFound = false; // only denoms here so let's look up BOOST_FOREACH(CTxIn in2, wtx->vin) { if(IsMine(in2)) { int n = GetRealInputDarksendRounds(in2, rounds+1); // denom found, find the shortest chain or initially assign nShortest with the first found value if(n >= 0 && (n < nShortest || nShortest == -10)) { nShortest = n; fDenomFound = true; } } } mDenomWtxes[hash].vout[nout].nRounds = fDenomFound ? (nShortest >= 15 ? 16 : nShortest + 1) // good, we a +1 to the shortest one but only 16 rounds max allowed : 0; // too bad, we are the fist one in that chain LogPrint("darksend", "GetInputDarksendRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds); return mDenomWtxes[hash].vout[nout].nRounds; } return rounds-1; } // respect current settings int CWallet::GetInputDarksendRounds(CTxIn in) const { LOCK(cs_wallet); int realDarksendRounds = GetRealInputDarksendRounds(in, 0); return realDarksendRounds > nDarksendRounds ? nDarksendRounds : realDarksendRounds; } bool CWallet::IsDenominated(const CTxIn &txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) return IsDenominatedAmount(prev.vout[txin.prevout.n].nValue); } } return false; } bool CWallet::IsDenominatedAmount(int64_t nInputAmount) const { BOOST_FOREACH(int64_t d, darkSendDenominations) if(nInputAmount == d) return true; return false; } bool CWallet::IsChange(const CTxOut& txout) const { // TODO: fix handling of 'change' outputs. The assumption is that any // payment to a script that is ours, but is not in the address book // is change. That assumption is likely to break when we implement multisignature // wallets that return change back into a multi-signature-protected address; // a better way of identifying which outputs are 'the send' and which are // 'the change' will need to be implemented (maybe extend CWalletTx to remember // which output, if any, was change). if (::IsMine(*this, txout.scriptPubKey)) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address)) return true; LOCK(cs_wallet); if (!mapAddressBook.count(address)) return true; } return false; } int64_t CWalletTx::GetTxTime() const { int64_t n = nTimeSmart; return n ? n : nTimeReceived; } int CWalletTx::GetRequestCount() const { // Returns -1 if it wasn't being tracked int nRequests = -1; { LOCK(pwallet->cs_wallet); if (IsCoinBase() || IsCoinStake()) { // Generated block if (hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; } } else { // Did anyone request this transaction? map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash()); if (mi != pwallet->mapRequestCount.end()) { nRequests = (*mi).second; // How about the block it's in? if (nRequests == 0 && hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; else nRequests = 1; // If it's in someone else's block it must have got out } } } } return nRequests; } void CWalletTx::GetAmounts(list<pair<CTxDestination, int64_t> >& listReceived, list<pair<CTxDestination, int64_t> >& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const { LOCK(pwallet->cs_wallet); nFee = 0; listReceived.clear(); listSent.clear(); strSentAccount = strFromAccount; // Compute fee: CAmount nDebit = GetDebit(filter); if (nDebit > 0) // debit>0 means we signed/sent this transaction { CAmount nValueOut = GetValueOut(); nFee = nDebit - nValueOut; } // Sent/received. BOOST_FOREACH(const CTxOut& txout, vout) { // Skip special stake out if (txout.scriptPubKey.empty()) continue; isminetype fIsMine = pwallet->IsMine(txout); // Only need to handle txouts if AT LEAST one of these is true: // 1) they debit from us (sent) // 2) the output is to us (received) if (nDebit > 0) { // Don't report 'change' txouts // TXNOTE: CoinControl possible fix related... with HD wallet we need to report change? if (pwallet->IsChange(txout)) continue; } else if (!(fIsMine & filter)) continue; // In either case, we need to get the destination address CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address)) { LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n", this->GetHash().ToString()); address = CNoDestination(); } // If we are debited by the transaction, add the output as a "sent" entry if (nDebit > 0) listSent.push_back(make_pair(address, txout.nValue)); // If we are receiving the output, add it as a "received" entry if (fIsMine & filter) listReceived.push_back(make_pair(address, txout.nValue)); } } void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived, CAmount& nSent, CAmount& nFee, const isminefilter& filter) const { nReceived = nSent = nFee = 0; CAmount allFee; string strSentAccount; list<pair<CTxDestination, int64_t> > listReceived; list<pair<CTxDestination, int64_t> > listSent; GetAmounts(listReceived, listSent, allFee, strSentAccount, filter); if (strAccount == strSentAccount) { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& s, listSent) nSent += s.second; nFee = allFee; } { LOCK(pwallet->cs_wallet); BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived) { if (pwallet->mapAddressBook.count(r.first)) { map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first); if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount) nReceived += r.second; } else if (strAccount.empty()) { nReceived += r.second; } } } } void CWalletTx::AddSupportingTransactions(CTxDB& txdb) { vtxPrev.clear(); const int COPY_DEPTH = 3; if (SetMerkleBranch() < COPY_DEPTH) { vector<uint256> vWorkQueue; BOOST_FOREACH(const CTxIn& txin, vin) vWorkQueue.push_back(txin.prevout.hash); // This critsect is OK because txdb is already open { LOCK(pwallet->cs_wallet); map<uint256, const CMerkleTx*> mapWalletPrev; set<uint256> setAlreadyDone; for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hash = vWorkQueue[i]; if (setAlreadyDone.count(hash)) continue; setAlreadyDone.insert(hash); CMerkleTx tx; map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash); if (mi != pwallet->mapWallet.end()) { tx = (*mi).second; BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev) mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev; } else if (mapWalletPrev.count(hash)) { tx = *mapWalletPrev[hash]; } else if (txdb.ReadDiskTx(hash, tx)) { ; } else { LogPrintf("ERROR: AddSupportingTransactions() : unsupported transaction\n"); continue; } int nDepth = tx.SetMerkleBranch(); vtxPrev.push_back(tx); if (nDepth < COPY_DEPTH) { BOOST_FOREACH(const CTxIn& txin, tx.vin) vWorkQueue.push_back(txin.prevout.hash); } } } } reverse(vtxPrev.begin(), vtxPrev.end()); } bool CWalletTx::WriteToDisk() { return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this); } // Scan the block chain (starting in pindexStart) for transactions // from or to us. If fUpdate is true, found transactions that already // exist in the wallet will be updated. int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) { int ret = 0; CBlockIndex* pindex = pindexStart; { LOCK2(cs_main, cs_wallet); while (pindex) { // no need to read and scan block, if block was created before // our wallet birthday (as adjusted for block time variability) if (nTimeFirstKey && (pindex->nTime < (nTimeFirstKey - 7200))) { pindex = pindex->pnext; continue; } CBlock block; block.ReadFromDisk(pindex, true); BOOST_FOREACH(CTransaction& tx, block.vtx) { if (AddToWalletIfInvolvingMe(tx, &block, fUpdate)) ret++; } pindex = pindex->pnext; } } return ret; } void CWallet::ReacceptWalletTransactions() { CTxDB txdb("r"); bool fRepeat = true; while (fRepeat) { LOCK2(cs_main, cs_wallet); fRepeat = false; vector<CDiskTxPos> vMissingTx; BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) { const uint256& wtxid = item.first; CWalletTx& wtx = item.second; assert(wtx.GetHash() == wtxid); int nDepth = wtx.GetDepthInMainChain(); if (!wtx.IsCoinBase() && nDepth < 0) { // Try to add to memory pool LOCK(mempool.cs); wtx.AcceptToMemoryPool(false); } if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1))) { continue; } CTxIndex txindex; bool fUpdated = false; if (txdb.ReadTxIndex(wtx.GetHash(), txindex)) { // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat if (txindex.vSpent.size() != wtx.vout.size()) { LogPrintf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %u != wtx.vout.size() %u\n", txindex.vSpent.size(), wtx.vout.size()); continue; } for (unsigned int i = 0; i < txindex.vSpent.size(); i++) { if (wtx.IsSpent(i)) continue; if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i])) { wtx.MarkSpent(i); fUpdated = true; vMissingTx.push_back(txindex.vSpent[i]); } } if (fUpdated) { LogPrintf("ReacceptWalletTransactions found spent coin %s EXCL %s\n", FormatMoney(wtx.GetCredit(ISMINE_ALL)), wtx.GetHash().ToString()); wtx.MarkDirty(); wtx.WriteToDisk(); } } else { // Re-accept any txes of ours that aren't already in a block if (!(wtx.IsCoinBase() || wtx.IsCoinStake())) wtx.AcceptWalletTransaction(txdb); } } if (!vMissingTx.empty()) { // TODO: optimize this to scan just part of the block chain? if (ScanForWalletTransactions(pindexGenesisBlock)) fRepeat = true; // Found missing transactions: re-do re-accept. } } } void CWalletTx::RelayWalletTransaction(CTxDB& txdb, std::string strCommand) { if (!(IsCoinBase() || IsCoinStake())) { if (GetDepthInMainChain() == 0) { uint256 hash = GetHash(); if(strCommand == "txlreq"){ LogPrintf("Relaying txlreq %s\n", hash.ToString()); mapTxLockReq.insert(make_pair(hash, ((CTransaction)*this))); CreateNewLock(((CTransaction)*this)); RelayTransactionLockReq((CTransaction)*this, true); } else { LogPrintf("Relaying wtx %s\n", hash.ToString()); RelayTransaction((CTransaction)*this, hash); } } } } void CWalletTx::RelayWalletTransaction(std::string strCommand) { CTxDB txdb("r"); RelayWalletTransaction(txdb, strCommand); } set<uint256> CWalletTx::GetConflicts() const { set<uint256> result; if (pwallet != NULL) { uint256 myHash = GetHash(); result = pwallet->GetConflicts(myHash); result.erase(myHash); } return result; } void CWallet::ResendWalletTransactions(bool fForce) { if (!fForce) { // Do this infrequently and randomly to avoid giving away // that these are our transactions. static int64_t nNextTime; if (GetTime() < nNextTime) return; bool fFirst = (nNextTime == 0); nNextTime = GetTime() + GetRand(30 * 60); if (fFirst) return; // Only do it if there's been a new block since last time static int64_t nLastTime; if (nTimeBestReceived < nLastTime) return; nLastTime = GetTime(); } // Rebroadcast any of our txes that aren't in a block yet LogPrintf("ResendWalletTransactions()\n"); CTxDB txdb("r"); { LOCK(cs_wallet); // Sort them in chronological order multimap<unsigned int, CWalletTx*> mapSorted; BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) { CWalletTx& wtx = item.second; // Don't rebroadcast until it's had plenty of time that // it should have gotten in already by now. if (fForce || nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60) mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx)); } BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted) { CWalletTx& wtx = *item.second; wtx.RelayWalletTransaction(txdb); } } } ////////////////////////////////////////////////////////////////////////////// // // Actions // CAmount CWallet::GetBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } // ppcoin: total coins staked (non-spendable until maturity) CAmount CWallet::GetStake() const { CAmount nTotal = 0; LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0) nTotal += CWallet::GetCredit(*pcoin, ISMINE_ALL); } return nTotal; } CAmount CWallet::GetNewMint() const { CAmount nTotal = 0; LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0) nTotal += CWallet::GetCredit(*pcoin, ISMINE_ALL); } return nTotal; } CAmount CWallet::GetAnonymizableBalance() const { if(fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAnonymizableCredit(); } } return nTotal; } CAmount CWallet::GetAnonymizedBalance() const { if(fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAnonymizedCredit(); } } return nTotal; } // Note: calculated including unconfirmed, // that's ok as long as we use it for informational purposes only double CWallet::GetAverageAnonymizedRounds() const { if(fLiteMode) return 0; double fTotal = 0; double fCount = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; uint256 hash = (*it).first; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { CTxIn vin = CTxIn(hash, i); if(IsSpent(hash, i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE || !IsDenominated(vin)) continue; int rounds = GetInputDarksendRounds(vin); fTotal += (float)rounds; fCount += 1; } } } if(fCount == 0) return 0; return fTotal/fCount; } // Note: calculated including unconfirmed, // that's ok as long as we use it for informational purposes only CAmount CWallet::GetNormalizedAnonymizedBalance() const { if(fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; uint256 hash = (*it).first; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { CTxIn vin = CTxIn(hash, i); if(IsSpent(hash, i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE || !IsDenominated(vin)) continue; if (pcoin->GetDepthInMainChain() < 0) continue; int rounds = GetInputDarksendRounds(vin); nTotal += pcoin->vout[i].nValue * rounds / nDarksendRounds; } } } return nTotal; } CAmount CWallet::GetDenominatedBalance(bool unconfirmed) const { if(fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; nTotal += pcoin->GetDenominatedCredit(unconfirmed); } } return nTotal; } CAmount CWallet::GetUnconfirmedBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0)) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } CAmount CWallet::GetImmatureBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; nTotal += pcoin->GetImmatureCredit(); } } return nTotal; } CAmount CWallet::GetWatchOnlyBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAvailableWatchOnlyCredit(); } } return nTotal; } CAmount CWallet::GetWatchOnlyStake() const { CAmount nTotal = 0; LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0) nTotal += CWallet::GetCredit(*pcoin, ISMINE_WATCH_ONLY); } return nTotal; } CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0)) nTotal += pcoin->GetAvailableWatchOnlyCredit(); } } return nTotal; } CAmount CWallet::GetImmatureWatchOnlyBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; nTotal += pcoin->GetImmatureWatchOnlyCredit(); } } return nTotal; } // populate vCoins with vector of available COutputs. void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, AvailableCoinsType coin_type, bool useIX) const { vCoins.clear(); { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin)) continue; if (fOnlyConfirmed && !pcoin->IsTrusted()) continue; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) continue; if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(false); if (nDepth <= 0) // TXNOTE: coincontrol fix / ignore 0 confirm continue; // do not use IX for inputs that have less then 6 blockchain confirmations if (useIX && nDepth < 10) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { bool found = false; if(coin_type == ONLY_DENOMINATED) { found = IsDenominatedAmount(pcoin->vout[i].nValue); } else if(coin_type == ONLY_NOT10000IFMN) { found = !(fMasterNode && pcoin->vout[i].nValue == GetMNCollateral(pindexBest->nHeight)*COIN); } else if (coin_type == ONLY_NONDENOMINATED_NOT10000IFMN){ if (IsCollateralAmount(pcoin->vout[i].nValue)) continue; // do not use collateral amounts found = !IsDenominatedAmount(pcoin->vout[i].nValue); if(found && fMasterNode) found = pcoin->vout[i].nValue != GetMNCollateral(pindexBest->nHeight)*COIN; // do not use Hot MN funds } else { found = true; } if(!found) continue; isminetype mine = IsMine(pcoin->vout[i]); if (!(pcoin->IsSpent(i)) && mine != ISMINE_NO && !IsLockedCoin((*it).first, i) && pcoin->vout[i].nValue > 0 && (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i))) { vCoins.push_back(COutput(pcoin, i, nDepth, mine & ISMINE_SPENDABLE)); } } } } } void CWallet::AvailableCoinsMN(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, AvailableCoinsType coin_type, bool useIX) const { vCoins.clear(); { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin)) continue; if (fOnlyConfirmed && !pcoin->IsTrusted()) continue; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) continue; if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(); if (nDepth <= 0) // TXNOTE: coincontrol fix / ignore 0 confirm continue; // do not use IX for inputs that have less then 6 blockchain confirmations if (useIX && nDepth < 10) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { bool found = false; if(coin_type == ONLY_DENOMINATED) { found = IsDenominatedAmount(pcoin->vout[i].nValue); } else if(coin_type == ONLY_NOT10000IFMN) { found = !(fMasterNode && pcoin->vout[i].nValue == GetMNCollateral(pindexBest->nHeight)*COIN); } else if (coin_type == ONLY_NONDENOMINATED_NOT10000IFMN){ if (IsCollateralAmount(pcoin->vout[i].nValue)) continue; // do not use collateral amounts found = !IsDenominatedAmount(pcoin->vout[i].nValue); if(found && fMasterNode) found = pcoin->vout[i].nValue != GetMNCollateral(pindexBest->nHeight)*COIN; // do not use Hot MN funds } else { found = true; } if(!found) continue; isminetype mine = IsMine(pcoin->vout[i]); if (!(pcoin->IsSpent(i)) && mine != ISMINE_NO && !IsLockedCoin((*it).first, i) && pcoin->vout[i].nValue > 0 && (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i))) vCoins.push_back(COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO)); } } } } void CWallet::AvailableCoinsForStaking(vector<COutput>& vCoins, unsigned int nSpendTime) const { vCoins.clear(); { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; int nDepth = pcoin->GetDepthInMainChain(); if (nDepth < 1) continue; if (nDepth < nStakeMinConfirmations_2) { continue; } else { // Filtering by tx timestamp instead of block timestamp may give false positives but never false negatives if (pcoin->nTime + nStakeMinAge > nSpendTime) continue; } if (pcoin->GetBlocksToMaturity() > 0) continue; bool found = false; for (unsigned int i = 0; i < pcoin->vout.size(); i++){ if (IsDenominatedAmount(pcoin->vout[i].nValue)){ //LogPrintf("CWallet::AvailableCoinsForStaking - Found denominated amounts.\n"); found = true; break; } if (pcoin->vout[i].nValue == GetMNCollateral(pindexBest->nHeight)*COIN){ //LogPrintf("CWallet::AvailableCoinsForStaking - Found Masternode collateral.\n"); found = true; break; } if (IsCollateralAmount(pcoin->vout[i].nValue)){ //LogPrintf("CWallet::AvailableCoinsForStaking - Found Collateral amount.\n"); found = true; break; } } if(found) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { isminetype mine = IsMine(pcoin->vout[i]); if (!(pcoin->IsSpent(i)) && mine != ISMINE_NO && pcoin->vout[i].nValue >= nMinimumInputValue) vCoins.push_back(COutput(pcoin, i, nDepth, mine & ISMINE_SPENDABLE)); } } } } static void ApproximateBestSubset(vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue, vector<char>& vfBest, int64_t& nBest, int iterations = 1000) { vector<char> vfIncluded; vfBest.assign(vValue.size(), true); nBest = nTotalLower; seed_insecure_rand(); for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++) { vfIncluded.assign(vValue.size(), false); int64_t nTotal = 0; bool fReachedTarget = false; for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) { for (unsigned int i = 0; i < vValue.size(); i++) { //The solver here uses a randomized algorithm, //the randomness serves no real security purpose but is just //needed to prevent degenerate behavior and it is important //that the rng fast. We do not use a constant random sequence, //because there may be some privacy improvement by making //the selection random. if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i]) { nTotal += vValue[i].first; vfIncluded[i] = true; if (nTotal >= nTargetValue) { fReachedTarget = true; if (nTotal < nBest) { nBest = nTotal; vfBest = vfIncluded; } nTotal -= vValue[i].first; vfIncluded[i] = false; } } } } } } // TODO: find appropriate place for this sort function // move denoms down bool less_then_denom (const COutput& out1, const COutput& out2) { const CWalletTx *pcoin1 = out1.tx; const CWalletTx *pcoin2 = out2.tx; bool found1 = false; bool found2 = false; BOOST_FOREACH(int64_t d, darkSendDenominations) // loop through predefined denoms { if(pcoin1->vout[out1.i].nValue == d) found1 = true; if(pcoin2->vout[out2.i].nValue == d) found2 = true; } return (!found1 && found2); } bool CWallet::SelectCoinsMinConf(int64_t nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const { setCoinsRet.clear(); nValueRet = 0; // List of values less than target pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger; coinLowestLarger.first = std::numeric_limits<int64_t>::max(); coinLowestLarger.second.first = NULL; vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > > vValue; int64_t nTotalLower = 0; random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt); // move denoms down on the list sort(vCoins.begin(), vCoins.end(), less_then_denom); // try to find nondenom first to prevent unneeded spending of mixed coins for (unsigned int tryDenom = 0; tryDenom < 2; tryDenom++) { if (fDebug) LogPrint("selectcoins", "tryDenom: %d\n", tryDenom); vValue.clear(); nTotalLower = 0; BOOST_FOREACH(const COutput &output, vCoins) { if (!output.fSpendable) continue; const CWalletTx *pcoin = output.tx; if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs)) continue; int i = output.i; // Follow the timestamp rules if (pcoin->nTime > nSpendTime) continue; int64_t n = pcoin->vout[i].nValue; if (tryDenom == 0 && IsDenominatedAmount(n)) continue; // we don't want denom values on first run pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i)); if (n == nTargetValue) { setCoinsRet.insert(coin.second); nValueRet += coin.first; return true; } else if (n < nTargetValue + CENT) { vValue.push_back(coin); nTotalLower += n; } else if (n < coinLowestLarger.first) { coinLowestLarger = coin; } } if (nTotalLower == nTargetValue) { for (unsigned int i = 0; i < vValue.size(); ++i) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; } return true; } if (nTotalLower < nTargetValue) { if (coinLowestLarger.second.first == NULL) return false; setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; return true; } // Solve subset sum by stochastic approximation sort(vValue.rbegin(), vValue.rend(), CompareValueOnly()); vector<char> vfBest; int64_t nBest; ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000); if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT) ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000); // If we have a bigger coin and (either the stochastic approximation didn't find a good solution, // or the next bigger coin is closer), return the bigger coin if (coinLowestLarger.second.first && ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest)) { setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; } else { for (unsigned int i = 0; i < vValue.size(); i++) if (vfBest[i]) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; } LogPrint("selectcoins", "SelectCoins() best subset: "); for (unsigned int i = 0; i < vValue.size(); i++) if (vfBest[i]) LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first)); LogPrint("selectcoins", "total %s\n", FormatMoney(nBest)); } return true; } return false; } bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX) const { vector<COutput> vCoins; AvailableCoins(vCoins, true, coinControl, coin_type, useIX); // coin control -> return all selected outputs (we want all selected to go into the transaction for sure) if (coinControl && coinControl->HasSelected()) { BOOST_FOREACH(const COutput& out, vCoins) { if(!out.fSpendable) continue; if(coin_type == ONLY_DENOMINATED) { CTxIn vin = CTxIn(out.tx->GetHash(),out.i); int rounds = GetInputDarksendRounds(vin); // make sure it's actually anonymized if(rounds < nDarksendRounds) continue; } nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.insert(make_pair(out.tx, out.i)); } return (nValueRet >= nTargetValue); } //if we're doing only denominated, we need to round up to the nearest .1TX if(coin_type == ONLY_DENOMINATED) { // Make outputs by looping through denominations, from large to small BOOST_FOREACH(int64_t v, darkSendDenominations) { BOOST_FOREACH(const COutput& out, vCoins) { if(out.tx->vout[out.i].nValue == v //make sure it's the denom we're looking for && nValueRet + out.tx->vout[out.i].nValue < nTargetValue + (0.1*COIN)+100 //round the amount up to .1TX over ){ CTxIn vin = CTxIn(out.tx->GetHash(),out.i); int rounds = GetInputDarksendRounds(vin); // make sure it's actually anonymized if(rounds < nDarksendRounds) continue; nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.insert(make_pair(out.tx, out.i)); } } } return (nValueRet >= nTargetValue); } boost::function<bool (const CWallet*, int64_t, unsigned int, int, int, std::vector<COutput>, std::set<std::pair<const CWalletTx*,unsigned int> >&, int64_t&)> f = &CWallet::SelectCoinsMinConf; return (f(this, nTargetValue, nSpendTime, 1, 10, vCoins, setCoinsRet, nValueRet) || f(this, nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) || f(this, nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet)); } // Select some coins without random shuffle or best subset approximation bool CWallet::SelectCoinsForStaking(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const { vector<COutput> vCoins; AvailableCoinsForStaking(vCoins, nSpendTime); setCoinsRet.clear(); nValueRet = 0; BOOST_FOREACH(COutput output, vCoins) { if(!output.fSpendable) continue; const CWalletTx *pcoin = output.tx; int i = output.i; // Stop if we've chosen enough inputs if (nValueRet >= nTargetValue) break; int64_t n = pcoin->vout[i].nValue; pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i)); if (n >= nTargetValue) { // If input value is greater or equal to target then simply insert // it into the current subset and exit setCoinsRet.insert(coin.second); nValueRet += coin.first; break; } else if (n < nTargetValue + CENT) { setCoinsRet.insert(coin.second); nValueRet += coin.first; } } return true; } struct CompareByPriority { bool operator()(const COutput& t1, const COutput& t2) const { return t1.Priority() > t2.Priority(); } }; bool CWallet::SelectCoinsByDenominations(int nDenom, int64_t nValueMin, int64_t nValueMax, std::vector<CTxIn>& vCoinsRet, std::vector<COutput>& vCoinsRet2, int64_t& nValueRet, int nDarksendRoundsMin, int nDarksendRoundsMax) { vCoinsRet.clear(); nValueRet = 0; vCoinsRet2.clear(); vector<COutput> vCoins; AvailableCoins(vCoins, true, NULL, ONLY_DENOMINATED); std::random_shuffle(vCoins.rbegin(), vCoins.rend()); //keep track of each denomination that we have bool fFound1000 = false; bool fFound100 = false; bool fFound10 = false; bool fFound1 = false; bool fFoundDot1 = false; //Check to see if any of the denomination are off, in that case mark them as fulfilled if(!(nDenom & (1 << 0))) fFound1000 = true; if(!(nDenom & (1 << 1))) fFound100 = true; if(!(nDenom & (1 << 2))) fFound10 = true; if(!(nDenom & (1 << 3))) fFound1 = true; if(!(nDenom & (1 << 4))) fFoundDot1 = true; BOOST_FOREACH(const COutput& out, vCoins) { // masternode-like input should not be selected by AvailableCoins now anyway //if(out.tx->vout[out.i].nValue == 1000*COIN) continue; if(nValueRet + out.tx->vout[out.i].nValue <= nValueMax){ bool fAccepted = false; // Function returns as follows: // // bit 0 - 1000TX+1 ( bit on if present ) // bit 1 - 100TX+1 // bit 2 - 10TX+1 // bit 3 - 1TX+1 // bit 4 - .1TX+1 CTxIn vin = CTxIn(out.tx->GetHash(),out.i); int rounds = GetInputDarksendRounds(vin); if(rounds >= nDarksendRoundsMax) continue; if(rounds < nDarksendRoundsMin) continue; if(fFound1000 && fFound100 && fFound10 && fFound1 && fFoundDot1){ //if fulfilled //we can return this for submission if(nValueRet >= nValueMin){ //random reduce the max amount we'll submit for anonymity nValueMax -= (rand() % (nValueMax/5)); //on average use 50% of the inputs or less int r = (rand() % (int)vCoins.size()); if((int)vCoinsRet.size() > r) return true; } //Denomination criterion has been met, we can take any matching denominations if((nDenom & (1 << 0)) && out.tx->vout[out.i].nValue == ((1000*COIN) +1000000)) {fAccepted = true;} else if((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((100*COIN) +100000)) {fAccepted = true;} else if((nDenom & (1 << 2)) && out.tx->vout[out.i].nValue == ((10*COIN) +10000)) {fAccepted = true;} else if((nDenom & (1 << 3)) && out.tx->vout[out.i].nValue == ((1*COIN) +1000)) {fAccepted = true;} else if((nDenom & (1 << 4)) && out.tx->vout[out.i].nValue == ((.1*COIN) +100)) {fAccepted = true;} } else { //Criterion has not been satisfied, we will only take 1 of each until it is. if((nDenom & (1 << 0)) && out.tx->vout[out.i].nValue == ((1000*COIN) +1000000)) {fAccepted = true; fFound1000 = true;} else if((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((100*COIN) +100000)) {fAccepted = true; fFound100 = true;} else if((nDenom & (1 << 2)) && out.tx->vout[out.i].nValue == ((10*COIN) +10000)) {fAccepted = true; fFound10 = true;} else if((nDenom & (1 << 3)) && out.tx->vout[out.i].nValue == ((1*COIN) +1000)) {fAccepted = true; fFound1 = true;} else if((nDenom & (1 << 4)) && out.tx->vout[out.i].nValue == ((.1*COIN) +100)) {fAccepted = true; fFoundDot1 = true;} } if(!fAccepted) continue; vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey nValueRet += out.tx->vout[out.i].nValue; vCoinsRet.push_back(vin); vCoinsRet2.push_back(out); } } return (nValueRet >= nValueMin && fFound1000 && fFound100 && fFound10 && fFound1 && fFoundDot1); } bool CWallet::SelectCoinsDark(CAmount nValueMin, CAmount nValueMax, std::vector<CTxIn>& setCoinsRet, CAmount& nValueRet, int nDarksendRoundsMin, int nDarksendRoundsMax) const { CCoinControl *coinControl=NULL; setCoinsRet.clear(); nValueRet = 0; vector<COutput> vCoins; AvailableCoins(vCoins, true, coinControl, nDarksendRoundsMin < 0 ? ONLY_NONDENOMINATED_NOT10000IFMN : ONLY_DENOMINATED); set<pair<const CWalletTx*,unsigned int> > setCoinsRet2; //order the array so fees are first, then denominated money, then the rest. sort(vCoins.rbegin(), vCoins.rend(), CompareByPriority()); //the first thing we get is a fee input, then we'll use as many denominated as possible. then the rest BOOST_FOREACH(const COutput& out, vCoins) { //do not allow inputs less than 1 CENT if(out.tx->vout[out.i].nValue < CENT) continue; //do not allow collaterals to be selected if(IsCollateralAmount(out.tx->vout[out.i].nValue)) continue; if(fMasterNode && out.tx->vout[out.i].nValue == GetMNCollateral(pindexBest->nHeight)*COIN) continue; //masternode input if(nValueRet + out.tx->vout[out.i].nValue <= nValueMax){ CTxIn vin = CTxIn(out.tx->GetHash(),out.i); int rounds = GetInputDarksendRounds(vin); if(rounds >= nDarksendRoundsMax) continue; if(rounds < nDarksendRoundsMin) continue; vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.push_back(vin); setCoinsRet2.insert(make_pair(out.tx, out.i)); } } // if it's more than min, we're good to return if(nValueRet >= nValueMin) return true; return false; } bool CWallet::SelectCoinsCollateral(std::vector<CTxIn>& setCoinsRet, int64_t& nValueRet) const { vector<COutput> vCoins; //printf(" selecting coins for collateral\n"); AvailableCoins(vCoins); //printf("found coins %d\n", (int)vCoins.size()); set<pair<const CWalletTx*,unsigned int> > setCoinsRet2; BOOST_FOREACH(const COutput& out, vCoins) { // collateral inputs will always be a multiple of DARSEND_COLLATERAL, up to five if(IsCollateralAmount(out.tx->vout[out.i].nValue)) { CTxIn vin = CTxIn(out.tx->GetHash(),out.i); vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.push_back(vin); setCoinsRet2.insert(make_pair(out.tx, out.i)); return true; } } return false; } int CWallet::CountInputsWithAmount(int64_t nInputAmount) { int64_t nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()){ int nDepth = pcoin->GetDepthInMainChain(false); for (unsigned int i = 0; i < pcoin->vout.size(); i++) { bool mine = IsMine(pcoin->vout[i]); COutput out = COutput(pcoin, i, nDepth, mine); CTxIn vin = CTxIn(out.tx->GetHash(), out.i); if(out.tx->vout[out.i].nValue != nInputAmount) continue; if(!IsDenominatedAmount(pcoin->vout[i].nValue)) continue; if(pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]) || !IsDenominated(vin)) continue; nTotal++; } } } } return nTotal; } bool CWallet::HasCollateralInputs(bool fOnlyConfirmed) const { vector<COutput> vCoins; AvailableCoins(vCoins, fOnlyConfirmed); int nFound = 0; BOOST_FOREACH(const COutput& out, vCoins) if(IsCollateralAmount(out.tx->vout[out.i].nValue)) nFound++; return nFound > 0; } bool CWallet::IsCollateralAmount(int64_t nInputAmount) const { return nInputAmount != 0 && nInputAmount % DARKSEND_COLLATERAL == 0 && nInputAmount < DARKSEND_COLLATERAL * 5 && nInputAmount > DARKSEND_COLLATERAL; } bool CWallet::CreateCollateralTransaction(CTransaction& txCollateral, std::string& strReason) { /* To doublespend a collateral transaction, it will require a fee higher than this. So there's still a significant cost. */ CAmount nFeeRet = 0.001*COIN; txCollateral.vin.clear(); txCollateral.vout.clear(); txCollateral.nTime = GetAdjustedTime(); CReserveKey reservekey(this); CAmount nValueIn2 = 0; std::vector<CTxIn> vCoinsCollateral; if (!SelectCoinsCollateral(vCoinsCollateral, nValueIn2)) { strReason = "Error: Darksend requires a collateral transaction and could not locate an acceptable input!"; return false; } // make our change address CScript scriptChange; CPubKey vchPubKey; assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptChange = GetScriptForDestination(vchPubKey.GetID()); reservekey.KeepKey(); BOOST_FOREACH(CTxIn v, vCoinsCollateral) txCollateral.vin.push_back(v); if(nValueIn2 - DARKSEND_COLLATERAL - nFeeRet > 0) { //pay collateral charge in fees CTxOut vout3 = CTxOut(nValueIn2 - DARKSEND_COLLATERAL, scriptChange); txCollateral.vout.push_back(vout3); } int vinNumber = 0; BOOST_FOREACH(CTxIn v, txCollateral.vin) { if(!SignSignature(*this, v.prevPubKey, txCollateral, vinNumber, int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))) { BOOST_FOREACH(CTxIn v, vCoinsCollateral) UnlockCoin(v.prevout); strReason = "CDarksendPool::Sign - Unable to sign collateral transaction! \n"; return false; } vinNumber++; } return true; } bool CWallet::ConvertList(std::vector<CTxIn> vCoins, std::vector<int64_t>& vecAmounts) { BOOST_FOREACH(CTxIn i, vCoins){ if (mapWallet.count(i.prevout.hash)) { CWalletTx& wtx = mapWallet[i.prevout.hash]; if(i.prevout.n < wtx.vout.size()){ vecAmounts.push_back(wtx.vout[i.prevout.n].nValue); } } else { LogPrintf("ConvertList -- Couldn't find transaction\n"); } } return true; } bool CWallet::GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight) { //This is a negative value when there is no weight. But set it to zero //so the user is not confused. Used in reporting in Coin Control. // Descisions based on this function should be used with care. int64_t nTimeWeight = GetWeight(nTime, (int64_t)GetTime()); if (nTimeWeight < 0 ) nTimeWeight=0; CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / (24 * 60 * 60); nWeight = bnCoinDayWeight.getuint64(); return true; } bool CWallet::CreateTransaction(const vector<pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, int32_t& nChangePos, std::string& strFailReason, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX) { int64_t nValue = 0; BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend) { if (nValue < 0) { strFailReason = _("Transaction amounts must be positive"); return false; } nValue += s.second; } if (vecSend.empty() || nValue < 0) { strFailReason = _("Transaction amounts must be positive"); return false; } wtxNew.fTimeReceivedIsTxTime = true; wtxNew.BindWallet(this); { // txdb must be opened before the mapWallet lock CTxDB txdb("r"); LOCK2(cs_main, cs_wallet); { nFeeRet = nTransactionFee; if(useIX) nFeeRet = max(CENT, nFeeRet); while (true) { wtxNew.vin.clear(); wtxNew.vout.clear(); wtxNew.fFromMe = true; int64_t nTotalValue = nValue + nFeeRet; double dPriority = 0; // vouts to the payees BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend) { CTxOut txout(s.second, s.first); bool fOpReturn = false; if(txout.IsNull() || (!txout.IsEmpty() && txout.nValue == 0)) { txnouttype whichType; vector<valtype> vSolutions; if (!Solver(txout.scriptPubKey, whichType, vSolutions)) { strFailReason = _("Invalid scriptPubKey"); return false; } if(whichType == TX_NONSTANDARD) { strFailReason = _("Unknown transaction type"); return false; } if(whichType == TX_NULL_DATA) fOpReturn = true; } if (!fOpReturn && txout.IsDust(MIN_RELAY_TX_FEE)) { strFailReason = _("Transaction amount too small"); return false; } wtxNew.vout.push_back(txout); } // Choose coins to use set<pair<const CWalletTx*,unsigned int> > setCoins; int64_t nValueIn = 0; if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl, coin_type, useIX)) { if(coin_type == ALL_COINS) { strFailReason = _(" Insufficient funds."); } else if (coin_type == ONLY_NOT10000IFMN) { strFailReason = _(" Unable to locate enough Darksend non-denominated funds for this transaction."); } else if (coin_type == ONLY_NONDENOMINATED_NOT10000IFMN ) { strFailReason = _(" Unable to locate enough Darksend non-denominated funds for this transaction that are not equal 1000 TX."); } else { strFailReason = _(" Unable to locate enough Darksend denominated funds for this transaction."); strFailReason += _(" Darksend uses exact denominated amounts to send funds, you might simply need to anonymize some more coins."); } if(useIX){ strFailReason += _(" InstantX requires inputs with at least 10 confirmations, you might need to wait a few minutes and try again."); } return false; } BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { int64_t nCredit = pcoin.first->vout[pcoin.second].nValue; //The coin age after the next block (depth+1) is used instead of the current, //reflecting an assumption the user would accept a bit more delay for //a chance at a free transaction. //But mempool inputs might still be in the mempool, so their age stays 0 int age = pcoin.first->GetDepthInMainChain(); if (age != 0) age += 1; dPriority += (double)nCredit * age; } int64_t nChange = nValueIn - nValue - nFeeRet; //over pay for denominated transactions if(coin_type == ONLY_DENOMINATED) { nFeeRet += nChange; nChange = 0; wtxNew.mapValue["DS"] = "1"; } if (nChange > 0) { // Fill a vout to ourself // TODO: pass in scriptChange instead of reservekey so // change transaction isn't always pay-to-exclusivecoin-address CScript scriptChange; // coin control: send change to custom address if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange)) scriptChange.SetDestination(coinControl->destChange); // no coin control: send change to newly generated address else { // Note: We use a new key here to keep it from being obvious which side is the change. // The drawback is that by not reusing a previous key, the change may be lost if a // backup is restored, if the backup doesn't have the new private key for the change. // If we reused the old key, it would be possible to add code to look for and // rediscover unknown transactions that were written with keys of ours to recover // post-backup change. // Reserve a new key pair from key pool CPubKey vchPubKey; bool ret; ret = reservekey.GetReservedKey(vchPubKey); assert(ret); // should never fail, as we just unlocked scriptChange.SetDestination(vchPubKey.GetID()); } CTxOut newTxOut(nChange, scriptChange); // Never create dust outputs; if we would, just // add the dust to the fee. if (newTxOut.IsDust(MIN_RELAY_TX_FEE)) { nFeeRet += nChange; nChange = 0; reservekey.ReturnKey(); } else { // Insert change txn at random position: vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size()+1); wtxNew.vout.insert(position, newTxOut); } } else reservekey.ReturnKey(); // Fill vin // // Note how the sequence number is set to max()-1 so that the // nLockTime set above actually works. BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second)); // Sign int nIn = 0; BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) if (!SignSignature(*this, *coin.first, wtxNew, nIn++)) { strFailReason = _(" Signing transaction failed"); return false; } // Limit size unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_STANDARD_TX_SIZE) { strFailReason = _(" Transaction too large"); return false; } dPriority = wtxNew.ComputePriority(dPriority, nBytes); // Check that enough fee is included int64_t nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000); bool fAllowFree = AllowFree(dPriority); int64_t nMinFee = GetMinFee(wtxNew, nBytes, fAllowFree, GMF_SEND); if (nFeeRet < max(nPayFee, nMinFee)) { nFeeRet = max(nPayFee, nMinFee); if(useIX) nFeeRet = max(CENT, nFeeRet); continue; } // Fill vtxPrev by copying from previous transactions vtxPrev wtxNew.AddSupportingTransactions(txdb); wtxNew.fTimeReceivedIsTxTime = true; break; } } } return true; } bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, std::string& sNarr, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl) { vector< pair<CScript, int64_t> > vecSend; vecSend.push_back(make_pair(scriptPubKey, nValue)); if (sNarr.length() > 0) { std::vector<uint8_t> vNarr(sNarr.c_str(), sNarr.c_str() + sNarr.length()); std::vector<uint8_t> vNDesc; vNDesc.resize(2); vNDesc[0] = 'n'; vNDesc[1] = 'p'; CScript scriptN = CScript() << OP_RETURN << vNDesc << OP_RETURN << vNarr; vecSend.push_back(make_pair(scriptN, 0)); } // -- CreateTransaction won't place change between value and narr output. // narration output will be for preceding output int nChangePos; std::string strFailReason; bool rv = CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, nChangePos, strFailReason, coinControl); if(!strFailReason.empty()) { LogPrintf("CreateTransaction(): ERROR: %s\n", strFailReason); return false; } // -- narration will be added to mapValue later in FindStealthTransactions From CommitTransaction return rv; } bool CWallet::NewStealthAddress(std::string& sError, std::string& sLabel, CStealthAddress& sxAddr) { ec_secret scan_secret; ec_secret spend_secret; if (GenerateRandomSecret(scan_secret) != 0 || GenerateRandomSecret(spend_secret) != 0) { sError = "GenerateRandomSecret failed."; printf("Error CWallet::NewStealthAddress - %s\n", sError.c_str()); return false; }; ec_point scan_pubkey, spend_pubkey; if (SecretToPublicKey(scan_secret, scan_pubkey) != 0) { sError = "Could not get scan public key."; printf("Error CWallet::NewStealthAddress - %s\n", sError.c_str()); return false; }; if (SecretToPublicKey(spend_secret, spend_pubkey) != 0) { sError = "Could not get spend public key."; printf("Error CWallet::NewStealthAddress - %s\n", sError.c_str()); return false; }; if (fDebug) { printf("getnewstealthaddress: "); printf("scan_pubkey "); for (uint32_t i = 0; i < scan_pubkey.size(); ++i) printf("%02x", scan_pubkey[i]); printf("\n"); printf("spend_pubkey "); for (uint32_t i = 0; i < spend_pubkey.size(); ++i) printf("%02x", spend_pubkey[i]); printf("\n"); }; sxAddr.label = sLabel; sxAddr.scan_pubkey = scan_pubkey; sxAddr.spend_pubkey = spend_pubkey; sxAddr.scan_secret.resize(32); memcpy(&sxAddr.scan_secret[0], &scan_secret.e[0], 32); sxAddr.spend_secret.resize(32); memcpy(&sxAddr.spend_secret[0], &spend_secret.e[0], 32); return true; } bool CWallet::AddStealthAddress(CStealthAddress& sxAddr) { LOCK(cs_wallet); // must add before changing spend_secret stealthAddresses.insert(sxAddr); bool fOwned = sxAddr.scan_secret.size() == ec_secret_size; if (fOwned) { // -- owned addresses can only be added when wallet is unlocked if (IsLocked()) { printf("Error: CWallet::AddStealthAddress wallet must be unlocked.\n"); stealthAddresses.erase(sxAddr); return false; }; if (IsCrypted()) { std::vector<unsigned char> vchCryptedSecret; CSecret vchSecret; vchSecret.resize(32); memcpy(&vchSecret[0], &sxAddr.spend_secret[0], 32); uint256 iv = Hash(sxAddr.spend_pubkey.begin(), sxAddr.spend_pubkey.end()); if (!EncryptSecret(vMasterKey, vchSecret, iv, vchCryptedSecret)) { printf("Error: Failed encrypting stealth key %s\n", sxAddr.Encoded().c_str()); stealthAddresses.erase(sxAddr); return false; }; sxAddr.spend_secret = vchCryptedSecret; }; }; bool rv = CWalletDB(strWalletFile).WriteStealthAddress(sxAddr); if (rv) NotifyAddressBookChanged(this, sxAddr, sxAddr.label, fOwned, CT_NEW); return rv; } bool CWallet::UnlockStealthAddresses(const CKeyingMaterial& vMasterKeyIn) { // -- decrypt spend_secret of stealth addresses std::set<CStealthAddress>::iterator it; for (it = stealthAddresses.begin(); it != stealthAddresses.end(); ++it) { if (it->scan_secret.size() < 32) continue; // stealth address is not owned // -- CStealthAddress are only sorted on spend_pubkey CStealthAddress &sxAddr = const_cast<CStealthAddress&>(*it); if (fDebug) printf("Decrypting stealth key %s\n", sxAddr.Encoded().c_str()); CSecret vchSecret; uint256 iv = Hash(sxAddr.spend_pubkey.begin(), sxAddr.spend_pubkey.end()); if(!DecryptSecret(vMasterKeyIn, sxAddr.spend_secret, iv, vchSecret) || vchSecret.size() != 32) { printf("Error: Failed decrypting stealth key %s\n", sxAddr.Encoded().c_str()); continue; }; ec_secret testSecret; memcpy(&testSecret.e[0], &vchSecret[0], 32); ec_point pkSpendTest; if (SecretToPublicKey(testSecret, pkSpendTest) != 0 || pkSpendTest != sxAddr.spend_pubkey) { printf("Error: Failed decrypting stealth key, public key mismatch %s\n", sxAddr.Encoded().c_str()); continue; }; sxAddr.spend_secret.resize(32); memcpy(&sxAddr.spend_secret[0], &vchSecret[0], 32); }; CryptedKeyMap::iterator mi = mapCryptedKeys.begin(); for (; mi != mapCryptedKeys.end(); ++mi) { CPubKey &pubKey = (*mi).second.first; std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second; if (vchCryptedSecret.size() != 0) continue; CKeyID ckid = pubKey.GetID(); CExclusivecoinAddress addr(ckid); StealthKeyMetaMap::iterator mi = mapStealthKeyMeta.find(ckid); if (mi == mapStealthKeyMeta.end()) { printf("Error: No metadata found to add secret for %s\n", addr.ToString().c_str()); continue; }; CStealthKeyMetadata& sxKeyMeta = mi->second; CStealthAddress sxFind; sxFind.scan_pubkey = sxKeyMeta.pkScan.Raw(); std::set<CStealthAddress>::iterator si = stealthAddresses.find(sxFind); if (si == stealthAddresses.end()) { printf("No stealth key found to add secret for %s\n", addr.ToString().c_str()); continue; }; if (fDebug) printf("Expanding secret for %s\n", addr.ToString().c_str()); ec_secret sSpendR; ec_secret sSpend; ec_secret sScan; if (si->spend_secret.size() != ec_secret_size || si->scan_secret.size() != ec_secret_size) { printf("Stealth address has no secret key for %s\n", addr.ToString().c_str()); continue; } memcpy(&sScan.e[0], &si->scan_secret[0], ec_secret_size); memcpy(&sSpend.e[0], &si->spend_secret[0], ec_secret_size); ec_point pkEphem = sxKeyMeta.pkEphem.Raw(); if (StealthSecretSpend(sScan, pkEphem, sSpend, sSpendR) != 0) { printf("StealthSecretSpend() failed.\n"); continue; }; ec_point pkTestSpendR; if (SecretToPublicKey(sSpendR, pkTestSpendR) != 0) { printf("SecretToPublicKey() failed.\n"); continue; }; CSecret vchSecret; vchSecret.resize(ec_secret_size); memcpy(&vchSecret[0], &sSpendR.e[0], ec_secret_size); CKey ckey; try { ckey.Set(vchSecret.begin(), vchSecret.end(), true); //ckey.SetSecret(vchSecret, true); } catch (std::exception& e) { printf("ckey.SetSecret() threw: %s.\n", e.what()); continue; }; CPubKey cpkT = ckey.GetPubKey(); if (!cpkT.IsValid()) { printf("cpkT is invalid.\n"); continue; }; if (cpkT != pubKey) { printf("Error: Generated secret does not match.\n"); continue; }; if (!ckey.IsValid()) { printf("Reconstructed key is invalid.\n"); continue; }; if (fDebug) { CKeyID keyID = cpkT.GetID(); CExclusivecoinAddress coinAddress(keyID); printf("Adding secret to key %s.\n", coinAddress.ToString().c_str()); }; if (!AddKey(ckey)) { printf("AddKey failed.\n"); continue; }; if (!CWalletDB(strWalletFile).EraseStealthKeyMeta(ckid)) printf("EraseStealthKeyMeta failed for %s\n", addr.ToString().c_str()); }; return true; } bool CWallet::UpdateStealthAddress(std::string &addr, std::string &label, bool addIfNotExist) { if (fDebug) printf("UpdateStealthAddress %s\n", addr.c_str()); CStealthAddress sxAddr; if (!sxAddr.SetEncoded(addr)) return false; std::set<CStealthAddress>::iterator it; it = stealthAddresses.find(sxAddr); ChangeType nMode = CT_UPDATED; CStealthAddress sxFound; if (it == stealthAddresses.end()) { if (addIfNotExist) { sxFound = sxAddr; sxFound.label = label; stealthAddresses.insert(sxFound); nMode = CT_NEW; } else { printf("UpdateStealthAddress %s, not in set\n", addr.c_str()); return false; }; } else { sxFound = const_cast<CStealthAddress&>(*it); if (sxFound.label == label) { // no change return true; }; it->label = label; // update in .stealthAddresses if (sxFound.scan_secret.size() == ec_secret_size) { printf("UpdateStealthAddress: todo - update owned stealth address.\n"); return false; }; }; sxFound.label = label; if (!CWalletDB(strWalletFile).WriteStealthAddress(sxFound)) { printf("UpdateStealthAddress(%s) Write to db failed.\n", addr.c_str()); return false; }; bool fOwned = sxFound.scan_secret.size() == ec_secret_size; NotifyAddressBookChanged(this, sxFound, sxFound.label, fOwned, nMode); return true; } bool CWallet::CreateStealthTransaction(CScript scriptPubKey, int64_t nValue, std::vector<uint8_t>& P, std::vector<uint8_t>& narr, std::string& sNarr, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl) { vector< pair<CScript, int64_t> > vecSend; vecSend.push_back(make_pair(scriptPubKey, nValue)); CScript scriptP = CScript() << OP_RETURN << P; if (narr.size() > 0) scriptP = scriptP << OP_RETURN << narr; vecSend.push_back(make_pair(scriptP, 0)); // -- shuffle inputs, change output won't mix enough as it must be not fully random for plantext narrations std::random_shuffle(vecSend.begin(), vecSend.end()); int nChangePos; std::string strFailReason; bool rv = CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, nChangePos, strFailReason, coinControl); if(!strFailReason.empty()) LogPrintf("CreateStealthTransaction(): %s\n", strFailReason); // -- the change txn is inserted in a random pos, check here to match narr to output if (rv && narr.size() > 0) { for (unsigned int k = 0; k < wtxNew.vout.size(); ++k) { if (wtxNew.vout[k].scriptPubKey != scriptPubKey || wtxNew.vout[k].nValue != nValue) continue; char key[64]; if (snprintf(key, sizeof(key), "n_%u", k) < 1) { printf("CreateStealthTransaction(): Error creating narration key."); break; }; wtxNew.mapValue[key] = sNarr; break; }; }; return rv; } string CWallet::SendStealthMoney(CScript scriptPubKey, int64_t nValue, std::vector<uint8_t>& P, std::vector<uint8_t>& narr, std::string& sNarr, CWalletTx& wtxNew, bool fAskFee) { CReserveKey reservekey(this); int64_t nFeeRequired; if (IsLocked()) { string strError = _("Error: Wallet locked, unable to create transaction "); LogPrintf("SendStealthMoney() : %s\n", strError.c_str()); return strError; } if (fWalletUnlockStakingOnly) { string strError = _("Error: Wallet unlocked for staking only, unable to create transaction."); LogPrintf("SendStealthMoney() : %s\n", strError.c_str()); return strError; } if (!CreateStealthTransaction(scriptPubKey, nValue, P, narr, sNarr, wtxNew, reservekey, nFeeRequired)) { string strError; if (nValue + nFeeRequired > GetBalance()) strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds "), FormatMoney(nFeeRequired).c_str()); else strError = "Failed to Create transaction"; LogPrintf("SendStealthMoney() : %s\n", strError.c_str()); return strError; } if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending..."))) return "ABORTED"; if (!CommitTransaction(wtxNew, reservekey)) return _("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); return ""; } bool CWallet::SendStealthMoneyToDestination(CStealthAddress& sxAddress, int64_t nValue, std::string& sNarr, CWalletTx& wtxNew, std::string& sError, bool fAskFee) { // -- Check amount if (nValue <= 0) { sError = "Invalid amount"; return false; }; if (nValue + nTransactionFee + (1) > GetBalance()) { sError = "Insufficient funds"; return false; }; ec_secret ephem_secret; ec_secret secretShared; ec_point pkSendTo; ec_point ephem_pubkey; if (GenerateRandomSecret(ephem_secret) != 0) { sError = "GenerateRandomSecret failed."; return false; }; if (StealthSecret(ephem_secret, sxAddress.scan_pubkey, sxAddress.spend_pubkey, secretShared, pkSendTo) != 0) { sError = "Could not generate receiving public key."; return false; }; CPubKey cpkTo(pkSendTo); if (!cpkTo.IsValid()) { sError = "Invalid public key generated."; return false; }; CKeyID ckidTo = cpkTo.GetID(); CExclusivecoinAddress addrTo(ckidTo); if (SecretToPublicKey(ephem_secret, ephem_pubkey) != 0) { sError = "Could not generate ephem public key."; return false; }; if (fDebug) { LogPrintf("Stealth send to generated pubkey %" PRIszu": %s\n", pkSendTo.size(), HexStr(pkSendTo).c_str()); LogPrintf("hash %s\n", addrTo.ToString().c_str()); LogPrintf("ephem_pubkey %" PRIszu": %s\n", ephem_pubkey.size(), HexStr(ephem_pubkey).c_str()); }; std::vector<unsigned char> vchNarr; if (sNarr.length() > 0) { SecMsgCrypter crypter; crypter.SetKey(&secretShared.e[0], &ephem_pubkey[0]); if (!crypter.Encrypt((uint8_t*)&sNarr[0], sNarr.length(), vchNarr)) { sError = "Narration encryption failed."; return false; }; if (vchNarr.size() > 48) { sError = "Encrypted narration is too long."; return false; }; }; // -- Parse Bitcoin address CScript scriptPubKey; scriptPubKey.SetDestination(addrTo.Get()); if ((sError = SendStealthMoney(scriptPubKey, nValue, ephem_pubkey, vchNarr, sNarr, wtxNew, fAskFee)) != "") return false; return true; } bool CWallet::FindStealthTransactions(const CTransaction& tx, mapValue_t& mapNarr) { if (fDebug) LogPrintf("FindStealthTransactions() tx: %s\n", tx.GetHash().GetHex().c_str()); mapNarr.clear(); LOCK(cs_wallet); ec_secret sSpendR; ec_secret sSpend; ec_secret sScan; ec_secret sShared; ec_point pkExtracted; std::vector<uint8_t> vchEphemPK; std::vector<uint8_t> vchDataB; std::vector<uint8_t> vchENarr; opcodetype opCode; char cbuf[256]; int32_t nOutputIdOuter = -1; BOOST_FOREACH(const CTxOut& txout, tx.vout) { nOutputIdOuter++; // -- for each OP_RETURN need to check all other valid outputs //printf("txout scriptPubKey %s\n", txout.scriptPubKey.ToString().c_str()); CScript::const_iterator itTxA = txout.scriptPubKey.begin(); if (!txout.scriptPubKey.GetOp(itTxA, opCode, vchEphemPK) || opCode != OP_RETURN) continue; else if (!txout.scriptPubKey.GetOp(itTxA, opCode, vchEphemPK) || vchEphemPK.size() != 33) { // -- look for plaintext narrations if (vchEphemPK.size() > 1 && vchEphemPK[0] == 'n' && vchEphemPK[1] == 'p') { if (txout.scriptPubKey.GetOp(itTxA, opCode, vchENarr) && opCode == OP_RETURN && txout.scriptPubKey.GetOp(itTxA, opCode, vchENarr) && vchENarr.size() > 0) { std::string sNarr = std::string(vchENarr.begin(), vchENarr.end()); snprintf(cbuf, sizeof(cbuf), "n_%d", nOutputIdOuter-1); // plaintext narration always matches preceding value output mapNarr[cbuf] = sNarr; } else { printf("Warning: FindStealthTransactions() tx: %s, Could not extract plaintext narration.\n", tx.GetHash().GetHex().c_str()); }; } continue; } int32_t nOutputId = -1; nStealth++; BOOST_FOREACH(const CTxOut& txoutB, tx.vout) { nOutputId++; if (&txoutB == &txout) continue; bool txnMatch = false; // only 1 txn will match an ephem pk //printf("txoutB scriptPubKey %s\n", txoutB.scriptPubKey.ToString().c_str()); CTxDestination address; if (!ExtractDestination(txoutB.scriptPubKey, address)) continue; if (address.type() != typeid(CKeyID)) continue; CKeyID ckidMatch = boost::get<CKeyID>(address); if (HaveKey(ckidMatch)) // no point checking if already have key continue; std::set<CStealthAddress>::iterator it; for (it = stealthAddresses.begin(); it != stealthAddresses.end(); ++it) { if (it->scan_secret.size() != ec_secret_size) continue; // stealth address is not owned //printf("it->Encodeded() %s\n", it->Encoded().c_str()); memcpy(&sScan.e[0], &it->scan_secret[0], ec_secret_size); if (StealthSecret(sScan, vchEphemPK, it->spend_pubkey, sShared, pkExtracted) != 0) { printf("StealthSecret failed.\n"); continue; }; //printf("pkExtracted %"PRIszu": %s\n", pkExtracted.size(), HexStr(pkExtracted).c_str()); CPubKey cpkE(pkExtracted); if (!cpkE.IsValid()) continue; CKeyID ckidE = cpkE.GetID(); if (ckidMatch != ckidE) continue; if (fDebug) printf("Found stealth txn to address %s\n", it->Encoded().c_str()); if (IsLocked()) { if (fDebug) printf("Wallet is locked, adding key without secret.\n"); // -- add key without secret std::vector<uint8_t> vchEmpty; AddCryptedKey(cpkE, vchEmpty); CKeyID keyId = cpkE.GetID(); CExclusivecoinAddress coinAddress(keyId); std::string sLabel = it->Encoded(); SetAddressBookName(keyId, sLabel); CPubKey cpkEphem(vchEphemPK); CPubKey cpkScan(it->scan_pubkey); CStealthKeyMetadata lockedSkMeta(cpkEphem, cpkScan); if (!CWalletDB(strWalletFile).WriteStealthKeyMeta(keyId, lockedSkMeta)) printf("WriteStealthKeyMeta failed for %s\n", coinAddress.ToString().c_str()); mapStealthKeyMeta[keyId] = lockedSkMeta; nFoundStealth++; } else { if (it->spend_secret.size() != ec_secret_size) continue; memcpy(&sSpend.e[0], &it->spend_secret[0], ec_secret_size); if (StealthSharedToSecretSpend(sShared, sSpend, sSpendR) != 0) { printf("StealthSharedToSecretSpend() failed.\n"); continue; }; ec_point pkTestSpendR; if (SecretToPublicKey(sSpendR, pkTestSpendR) != 0) { printf("SecretToPublicKey() failed.\n"); continue; }; CSecret vchSecret; vchSecret.resize(ec_secret_size); memcpy(&vchSecret[0], &sSpendR.e[0], ec_secret_size); CKey ckey; try { ckey.Set(vchSecret.begin(), vchSecret.end(), true); //ckey.SetSecret(vchSecret, true); } catch (std::exception& e) { printf("ckey.SetSecret() threw: %s.\n", e.what()); continue; }; CPubKey cpkT = ckey.GetPubKey(); if (!cpkT.IsValid()) { printf("cpkT is invalid.\n"); continue; }; if (!ckey.IsValid()) { printf("Reconstructed key is invalid.\n"); continue; }; CKeyID keyID = cpkT.GetID(); if (fDebug) { CExclusivecoinAddress coinAddress(keyID); printf("Adding key %s.\n", coinAddress.ToString().c_str()); }; if (!AddKey(ckey)) { printf("AddKey failed.\n"); continue; }; std::string sLabel = it->Encoded(); SetAddressBookName(keyID, sLabel); nFoundStealth++; }; if (txout.scriptPubKey.GetOp(itTxA, opCode, vchENarr) && opCode == OP_RETURN && txout.scriptPubKey.GetOp(itTxA, opCode, vchENarr) && vchENarr.size() > 0) { SecMsgCrypter crypter; crypter.SetKey(&sShared.e[0], &vchEphemPK[0]); std::vector<uint8_t> vchNarr; if (!crypter.Decrypt(&vchENarr[0], vchENarr.size(), vchNarr)) { printf("Decrypt narration failed.\n"); continue; }; std::string sNarr = std::string(vchNarr.begin(), vchNarr.end()); snprintf(cbuf, sizeof(cbuf), "n_%d", nOutputId); mapNarr[cbuf] = sNarr; }; txnMatch = true; break; }; if (txnMatch) break; }; }; return true; }; uint64_t CWallet::GetStakeWeight() const { // Choose coins to use int64_t nBalance = GetBalance(); if (nBalance <= nReserveBalance) return 0; vector<const CWalletTx*> vwtxPrev; set<pair<const CWalletTx*,unsigned int> > setCoins; int64_t nValueIn = 0; if (!SelectCoinsForStaking(nBalance - nReserveBalance, GetTime(), setCoins, nValueIn)) return 0; if (setCoins.empty()) return 0; uint64_t nWeight = 0; CTxDB txdb("r"); LOCK2(cs_main, cs_wallet); BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { CTxIndex txindex; if (pcoin.first->GetDepthInMainChain() >= nStakeMinConfirmations_2) nWeight += pcoin.first->vout[pcoin.second].nValue; } return nWeight; } bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64_t nSearchInterval, int64_t nFees, CTransaction& txNew, CKey& key) { CBlockIndex* pindexPrev = pindexBest; CBigNum bnTargetPerCoinDay; bnTargetPerCoinDay.SetCompact(nBits); txNew.vin.clear(); txNew.vout.clear(); // Mark coin stake transaction CScript scriptEmpty; scriptEmpty.clear(); txNew.vout.push_back(CTxOut(0, scriptEmpty)); // Choose coins to use int64_t nBalance = GetBalance(); if (nBalance <= nReserveBalance) return false; vector<const CWalletTx*> vwtxPrev; set<pair<const CWalletTx*,unsigned int> > setCoins; int64_t nValueIn = 0; // Select coins with suitable depth if (!SelectCoinsForStaking(nBalance - nReserveBalance, txNew.nTime, setCoins, nValueIn)) return false; if (setCoins.empty()) return false; int64_t nCredit = 0; CScript scriptPubKeyKernel; CTxDB txdb("r"); BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { static int nMaxStakeSearchInterval = 60; bool fKernelFound = false; for (unsigned int n=0; n<min(nSearchInterval,(int64_t)nMaxStakeSearchInterval) && !fKernelFound && pindexPrev == pindexBest; n++) { boost::this_thread::interruption_point(); // Search backward in time from the given txNew timestamp // Search nSearchInterval seconds back up to nMaxStakeSearchInterval COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second); int64_t nBlockTime; if (CheckKernel(pindexPrev, nBits, txNew.nTime - n, prevoutStake, &nBlockTime)) { // Found a kernel LogPrint("coinstake", "CreateCoinStake : kernel found\n"); vector<valtype> vSolutions; txnouttype whichType; CScript scriptPubKeyOut; scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey; if (!Solver(scriptPubKeyKernel, whichType, vSolutions)) { LogPrint("coinstake", "CreateCoinStake : failed to parse kernel\n"); break; } LogPrint("coinstake", "CreateCoinStake : parsed kernel type=%d\n", whichType); if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH) { LogPrint("coinstake", "CreateCoinStake : no support for kernel type=%d\n", whichType); break; // only support pay to public key and pay to address } if (whichType == TX_PUBKEYHASH) // pay to address type { // convert to pay to public key type if (!keystore.GetKey(uint160(vSolutions[0]), key)) { LogPrint("coinstake", "CreateCoinStake : failed to get key for kernel type=%d\n", whichType); break; // unable to find corresponding public key } scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG; } if (whichType == TX_PUBKEY) { valtype& vchPubKey = vSolutions[0]; if (!keystore.GetKey(Hash160(vchPubKey), key)) { LogPrint("coinstake", "CreateCoinStake : failed to get key for kernel type=%d\n", whichType); break; // unable to find corresponding public key } if (key.GetPubKey() != vchPubKey) { LogPrint("coinstake", "CreateCoinStake : invalid key for kernel type=%d\n", whichType); break; // keys mismatch } scriptPubKeyOut = scriptPubKeyKernel; } txNew.nTime -= n; txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second)); nCredit += pcoin.first->vout[pcoin.second].nValue; vwtxPrev.push_back(pcoin.first); txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); if(nCredit > GetStakeSplitThreshold()) txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake LogPrint("coinstake", "CreateCoinStake : added kernel type=%d\n", whichType); fKernelFound = true; break; } } if (fKernelFound) break; // if kernel is found stop searching } if (nCredit == 0 || nCredit > nBalance - nReserveBalance) return false; BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { // Attempt to add more inputs // Only add coins of the same key/address as kernel if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey)) && pcoin.first->GetHash() != txNew.vin[0].prevout.hash) { int64_t nTimeWeight = GetWeight((int64_t)pcoin.first->nTime, (int64_t)txNew.nTime); // Stop adding more inputs if already too many inputs if (txNew.vin.size() >= 100) break; // Stop adding more inputs if value is already pretty significant if (nCredit >= stakeCombineThreshold) break; // Stop adding inputs if reached reserve limit if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance) break; // Do not add additional significant input if (pcoin.first->vout[pcoin.second].nValue >= stakeCombineThreshold) continue; // Do not add input that is still too young if (nTimeWeight < nStakeMinAge) continue; txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second)); nCredit += pcoin.first->vout[pcoin.second].nValue; vwtxPrev.push_back(pcoin.first); } } // Calculate coin age reward int64_t nReward; { uint64_t nCoinAge; CTxDB txdb("r"); if (!txNew.GetCoinAge(txdb, pindexPrev, nCoinAge)) return error("CreateCoinStake : failed to calculate coin age"); nReward = GetProofOfStakeReward(pindexPrev, nCoinAge, nFees); if (nReward <= 0) return false; nCredit += nReward; } // Masternode Payments int payments = 1; // start masternode payments bool bMasterNodePayment = false; // note was false, set true to test if ( Params().NetworkID() == CChainParams::TESTNET ){ if (GetTime() > START_MASTERNODE_PAYMENTS_TESTNET ){ bMasterNodePayment = true; } }else{ if (GetTime() > START_MASTERNODE_PAYMENTS){ bMasterNodePayment = true; } } CScript payee; CTxIn vin; bool hasPayment = true; if(bMasterNodePayment) { //spork if(!masternodePayments.GetBlockPayee(pindexPrev->nHeight+1, payee, vin)){ CMasternode* winningNode = mnodeman.GetCurrentMasterNode(1); if(winningNode){ payee = GetScriptForDestination(winningNode->pubkey.GetID()); } else { return error("CreateCoinStake: Failed to detect masternode to pay\n"); } } } if(hasPayment){ payments = txNew.vout.size() + 1; txNew.vout.resize(payments); txNew.vout[payments-1].scriptPubKey = payee; txNew.vout[payments-1].nValue = 0; CTxDestination address1; ExtractDestination(payee, address1); CExclusivecoinAddress address2(address1); LogPrintf("Masternode payment to %s\n", address2.ToString().c_str()); } int64_t blockValue = nCredit; int64_t masternodePayment = GetMasternodePayment(pindexPrev->nHeight+1, nReward); // Set output amount if (!hasPayment && txNew.vout.size() == 3) // 2 stake outputs, stake was split, no masternode payment { txNew.vout[1].nValue = (blockValue / 2 / CENT) * CENT; txNew.vout[2].nValue = blockValue - txNew.vout[1].nValue; } else if(hasPayment && txNew.vout.size() == 4) // 2 stake outputs, stake was split, plus a masternode payment { txNew.vout[payments-1].nValue = masternodePayment; blockValue -= masternodePayment; txNew.vout[1].nValue = (blockValue / 2 / CENT) * CENT; txNew.vout[2].nValue = blockValue - txNew.vout[1].nValue; } else if(!hasPayment && txNew.vout.size() == 2) // only 1 stake output, was not split, no masternode payment txNew.vout[1].nValue = blockValue; else if(hasPayment && txNew.vout.size() == 3) // only 1 stake output, was not split, plus a masternode payment { txNew.vout[payments-1].nValue = masternodePayment; blockValue -= masternodePayment; txNew.vout[1].nValue = blockValue; } // Sign int nIn = 0; BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev) { if (!SignSignature(*this, *pcoin, txNew, nIn++)) return error("CreateCoinStake : failed to sign coinstake"); } // Limit size unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_BLOCK_SIZE_GEN/5) return error("CreateCoinStake : exceeded coinstake size limit"); // Successfully generated coinstake return true; } // Call after CreateTransaction unless you want to abort bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, std::string strCommand) { mapValue_t mapNarr; FindStealthTransactions(wtxNew, mapNarr); if (!mapNarr.empty()) { BOOST_FOREACH(const PAIRTYPE(string,string)& item, mapNarr) wtxNew.mapValue[item.first] = item.second; }; { LOCK2(cs_main, cs_wallet); LogPrintf("CommitTransaction:\n%s", wtxNew.ToString()); { // This is only to keep the database open to defeat the auto-flush for the // duration of this scope. This is the only place where this optimization // maybe makes sense; please don't do it anywhere else. CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL; // Take key pair from key pool so it won't be used again reservekey.KeepKey(); // Add tx to wallet, because if it has change it's also ours, // otherwise just for transaction history. AddToWallet(wtxNew); // Mark old coins as spent set<CWalletTx*> setCoins; BOOST_FOREACH(const CTxIn& txin, wtxNew.vin) { CWalletTx &coin = mapWallet[txin.prevout.hash]; coin.BindWallet(this); coin.MarkSpent(txin.prevout.n); coin.WriteToDisk(); NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED); } if (fFileBacked) delete pwalletdb; } // Track how many getdata requests our transaction gets mapRequestCount[wtxNew.GetHash()] = 0; // Broadcast if (!wtxNew.AcceptToMemoryPool(false)) { // This must not fail. The transaction has already been signed and recorded. LogPrintf("CommitTransaction() : Error: Transaction not valid\n"); return false; } wtxNew.RelayWalletTransaction(strCommand); } return true; } bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB & pwalletdb) { if (!pwalletdb.WriteAccountingEntry_Backend(acentry)) return false; laccentries.push_back(acentry); CAccountingEntry & entry = laccentries.back(); wtxOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry))); return true; } string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, std::string& sNarr, CWalletTx& wtxNew, bool fAskFee) { CReserveKey reservekey(this); int64_t nFeeRequired; if (IsLocked()) { string strError = _("Error: Wallet locked, unable to create transaction!"); LogPrintf("SendMoney() : %s", strError); return strError; } if (fWalletUnlockStakingOnly) { string strError = _("Error: Wallet unlocked for staking only, unable to create transaction."); LogPrintf("SendMoney() : %s", strError); return strError; } CWalletTx wtx; std::vector<std::pair<CScript, int64_t> > vecSend; vecSend.push_back(make_pair(scriptPubKey, nValue)); string strError = ""; if (!CreateTransaction(scriptPubKey, nValue, sNarr, wtxNew, reservekey, nFeeRequired)) { string strError; if (nValue + nFeeRequired > GetBalance()) strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!"), FormatMoney(nFeeRequired)); else strError = "Failed to Create transaction"; LogPrintf("SendMoney() : %s\n", strError); return strError; } if (!CommitTransaction(wtxNew, reservekey)) return _("Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); return ""; } string CWallet::SendMoneyToDestination(const CTxDestination& address, int64_t nValue, std::string& sNarr, CWalletTx& wtxNew, bool fAskFee) { // Check amount if (nValue <= 0) return _("Invalid amount"); if (nValue + nTransactionFee > GetBalance()) return _("Insufficient funds"); // Parse Bitcoin address CScript scriptPubKey; scriptPubKey.SetDestination(address); return SendMoney(scriptPubKey, nValue, sNarr, wtxNew, fAskFee); } int64_t CWallet::GetTotalValue(std::vector<CTxIn> vCoins) { int64_t nTotalValue = 0; CWalletTx wtx; BOOST_FOREACH(CTxIn i, vCoins){ if (mapWallet.count(i.prevout.hash)) { CWalletTx& wtx = mapWallet[i.prevout.hash]; if(i.prevout.n < wtx.vout.size()){ nTotalValue += wtx.vout[i.prevout.n].nValue; } } else { LogPrintf("GetTotalValue -- Couldn't find transaction\n"); } } return nTotalValue; } string CWallet::PrepareDarksendDenominate(int minRounds, int maxRounds) { if (IsLocked()) return _("Error: Wallet locked, unable to create transaction!"); if(darkSendPool.GetState() != POOL_STATUS_ERROR && darkSendPool.GetState() != POOL_STATUS_SUCCESS) if(darkSendPool.GetEntriesCount() > 0) return _("Error: You already have pending entries in the Darksend pool"); // ** find the coins we'll use std::vector<CTxIn> vCoins; std::vector<CTxIn> vCoinsResult; std::vector<COutput> vCoins2; int64_t nValueIn = 0; CReserveKey reservekey(this); /* Select the coins we'll use if minRounds >= 0 it means only denominated inputs are going in and coming out */ if(minRounds >= 0){ if (!SelectCoinsByDenominations(darkSendPool.sessionDenom, 0.1*COIN, DARKSEND_POOL_MAX, vCoins, vCoins2, nValueIn, minRounds, maxRounds)) return _("Error: Can't select current denominated inputs"); } LogPrintf("PrepareDarksendDenominate - preparing darksend denominate . Got: %d \n", nValueIn); { LOCK(cs_wallet); BOOST_FOREACH(CTxIn v, vCoins) LockCoin(v.prevout); } int64_t nValueLeft = nValueIn; std::vector<CTxOut> vOut; /* TODO: Front load with needed denominations (e.g. .1, 1 ) */ // Make outputs by looping through denominations: try to add every needed denomination, repeat up to 5-10 times. // This way we can be pretty sure that it should have at least one of each needed denomination. // NOTE: No need to randomize order of inputs because they were // initially shuffled in CWallet::SelectCoinsByDenominations already. int nStep = 0; int nStepsMax = 5 + GetRandInt(5); while(nStep < nStepsMax) { BOOST_FOREACH(int64_t v, darkSendDenominations){ // only use the ones that are approved bool fAccepted = false; if((darkSendPool.sessionDenom & (1 << 0)) && v == ((1000*COIN) +1000000)) {fAccepted = true;} else if((darkSendPool.sessionDenom & (1 << 1)) && v == ((100*COIN) +100000)) {fAccepted = true;} else if((darkSendPool.sessionDenom & (1 << 2)) && v == ((10*COIN) +10000)) {fAccepted = true;} else if((darkSendPool.sessionDenom & (1 << 3)) && v == ((1*COIN) +1000)) {fAccepted = true;} else if((darkSendPool.sessionDenom & (1 << 4)) && v == ((.1*COIN) +100)) {fAccepted = true;} if(!fAccepted) continue; // try to add it if(nValueLeft - v >= 0) { // Note: this relies on a fact that both vectors MUST have same size std::vector<CTxIn>::iterator it = vCoins.begin(); std::vector<COutput>::iterator it2 = vCoins2.begin(); while(it2 != vCoins2.end()) { // we have matching inputs if((*it2).tx->vout[(*it2).i].nValue == v) { // add new input in resulting vector vCoinsResult.push_back(*it); // remove corresponting items from initial vectors vCoins.erase(it); vCoins2.erase(it2); CScript scriptChange; CPubKey vchPubKey; // use a unique change address assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptChange = GetScriptForDestination(vchPubKey.GetID()); reservekey.KeepKey(); // add new output CTxOut o(v, scriptChange); vOut.push_back(o); // subtract denomination amount nValueLeft -= v; break; } ++it; ++it2; } } } nStep++; if(nValueLeft == 0) break; } { // unlock unused coins LOCK(cs_wallet); BOOST_FOREACH(CTxIn v, vCoins) UnlockCoin(v.prevout); } if(darkSendPool.GetDenominations(vOut) != darkSendPool.sessionDenom) { // unlock used coins on failure LOCK(cs_wallet); BOOST_FOREACH(CTxIn v, vCoinsResult) UnlockCoin(v.prevout); return "Error: can't make current denominated outputs"; } // randomize the output order std::random_shuffle (vOut.begin(), vOut.end()); // We also do not care about full amount as long as we have right denominations, just pass what we found darkSendPool.SendDarksendDenominate(vCoinsResult, vOut, nValueIn - nValueLeft); return ""; } DBErrors CWallet::LoadWallet(bool& fFirstRunRet) { if (!fFileBacked) return DB_LOAD_OK; fFirstRunRet = false; DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this); if (nLoadWalletRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) { LOCK(cs_wallet); setKeyPool.clear(); // Note: can't top-up keypool here, because wallet is locked. // User will be prompted to unlock wallet the next operation // the requires a new key. } } if (nLoadWalletRet != DB_LOAD_OK) return nLoadWalletRet; fFirstRunRet = !vchDefaultKey.IsValid(); return DB_LOAD_OK; } bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName) { bool fUpdated = false; { LOCK(cs_wallet); // mapAddressBook std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address); fUpdated = mi != mapAddressBook.end(); mapAddressBook[address] = strName; } NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO, (fUpdated ? CT_UPDATED : CT_NEW) ); if (!fFileBacked) return false; return CWalletDB(strWalletFile).WriteName(CExclusivecoinAddress(address).ToString(), strName); } bool CWallet::DelAddressBookName(const CTxDestination& address) { { LOCK(cs_wallet); // mapAddressBook mapAddressBook.erase(address); } NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, CT_DELETED); if (!fFileBacked) return false; CWalletDB(strWalletFile).EraseName(CExclusivecoinAddress(address).ToString()); return CWalletDB(strWalletFile).EraseName(CExclusivecoinAddress(address).ToString()); } bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx) { { LOCK(cs_wallet); map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx); if (mi != mapWallet.end()) { wtx = (*mi).second; return true; } } return false; } bool CWallet::SetDefaultKey(const CPubKey &vchPubKey) { if (fFileBacked) { if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey)) return false; } vchDefaultKey = vchPubKey; return true; } // // Mark old keypool keys as used, // and generate all new keys // bool CWallet::NewKeyPool() { { LOCK(cs_wallet); CWalletDB walletdb(strWalletFile); BOOST_FOREACH(int64_t nIndex, setKeyPool) walletdb.ErasePool(nIndex); setKeyPool.clear(); if (IsLocked()) return false; fLiteMode = GetBoolArg("-litemode", false); int64_t nKeys; if (fLiteMode) nKeys = max(GetArg("-keypool", 100), (int64_t)0); else nKeys = max(GetArg("-keypool", 1000), (int64_t)0); for (int i = 0; i < nKeys; i++) { int64_t nIndex = i+1; walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey())); setKeyPool.insert(nIndex); } LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys); } return true; } bool CWallet::TopUpKeyPool(unsigned int nSize) { { LOCK(cs_wallet); if (IsLocked()) return false; CWalletDB walletdb(strWalletFile); // Top up key pool unsigned int nTargetSize; fLiteMode = GetBoolArg("-litemode", false); if (nSize > 0) nTargetSize = nSize; else if (fLiteMode) nTargetSize = max(GetArg("-keypool", 100), (int64_t)0); else nTargetSize = max(GetArg("-keypool", 1000), (int64_t)0); while (setKeyPool.size() < (nTargetSize + 1)) { int64_t nEnd = 1; if (!setKeyPool.empty()) nEnd = *(--setKeyPool.end()) + 1; if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey()))) throw runtime_error("TopUpKeyPool() : writing generated key failed"); setKeyPool.insert(nEnd); LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size()); double dProgress = 100.f * nEnd / (nTargetSize + 1); std::string strMsg = strprintf(_("Loading wallet... (%3.2f %%)"), dProgress); uiInterface.InitMessage(strMsg); } } return true; } void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool) { nIndex = -1; keypool.vchPubKey = CPubKey(); { LOCK(cs_wallet); if (!IsLocked()) TopUpKeyPool(); // Get the oldest key if(setKeyPool.empty()) return; CWalletDB walletdb(strWalletFile); nIndex = *(setKeyPool.begin()); setKeyPool.erase(setKeyPool.begin()); if (!walletdb.ReadPool(nIndex, keypool)) throw runtime_error("ReserveKeyFromKeyPool() : read failed"); if (!HaveKey(keypool.vchPubKey.GetID())) throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool"); assert(keypool.vchPubKey.IsValid()); LogPrintf("keypool reserve %d\n", nIndex); } } int64_t CWallet::AddReserveKey(const CKeyPool& keypool) { { LOCK2(cs_main, cs_wallet); CWalletDB walletdb(strWalletFile); int64_t nIndex = 1 + *(--setKeyPool.end()); if (!walletdb.WritePool(nIndex, keypool)) throw runtime_error("AddReserveKey() : writing added key failed"); setKeyPool.insert(nIndex); return nIndex; } return -1; } void CWallet::KeepKey(int64_t nIndex) { // Remove from key pool if (fFileBacked) { CWalletDB walletdb(strWalletFile); walletdb.ErasePool(nIndex); } LogPrintf("keypool keep %d\n", nIndex); } void CWallet::ReturnKey(int64_t nIndex) { // Return to key pool { LOCK(cs_wallet); setKeyPool.insert(nIndex); } LogPrintf("keypool return %d\n", nIndex); } bool CWallet::GetKeyFromPool(CPubKey& result) { int64_t nIndex = 0; CKeyPool keypool; { LOCK(cs_wallet); ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) { if (IsLocked()) return false; result = GenerateNewKey(); return true; } KeepKey(nIndex); result = keypool.vchPubKey; } return true; } int64_t CWallet::GetOldestKeyPoolTime() { int64_t nIndex = 0; CKeyPool keypool; ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) return GetTime(); ReturnKey(nIndex); return keypool.nTime; } std::map<CTxDestination, int64_t> CWallet::GetAddressBalances() { map<CTxDestination, int64_t> balances; { LOCK(cs_wallet); BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { CWalletTx *pcoin = &walletEntry.second; if (!IsFinalTx(*pcoin) || !pcoin->IsTrusted()) continue; if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(); if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1)) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { CTxDestination addr; if (!IsMine(pcoin->vout[i])) continue; if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr)) continue; int64_t n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue; if (!balances.count(addr)) balances[addr] = 0; balances[addr] += n; } } } return balances; } set< set<CTxDestination> > CWallet::GetAddressGroupings() { AssertLockHeld(cs_wallet); // mapWallet set< set<CTxDestination> > groupings; set<CTxDestination> grouping; BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { CWalletTx *pcoin = &walletEntry.second; if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0])) { bool any_mine = false; // group all input addresses with each other BOOST_FOREACH(CTxIn txin, pcoin->vin) { CTxDestination address; if(!IsMine(txin)) /* If this input isn't mine, ignore it */ continue; if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address)) continue; grouping.insert(address); any_mine = true; } // group change with input addresses if (any_mine) { BOOST_FOREACH(CTxOut txout, pcoin->vout) { if (IsChange(txout)) { CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash]; CTxDestination txoutAddr; if(!ExtractDestination(txout.scriptPubKey, txoutAddr)) continue; grouping.insert(txoutAddr); } } } if (grouping.size() > 0) { groupings.insert(grouping); grouping.clear(); } } // group lone addrs by themselves for (unsigned int i = 0; i < pcoin->vout.size(); i++) if (IsMine(pcoin->vout[i])) { CTxDestination address; if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address)) continue; grouping.insert(address); groupings.insert(grouping); grouping.clear(); } } set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it BOOST_FOREACH(set<CTxDestination> grouping, groupings) { // make a set of all the groups hit by this new group set< set<CTxDestination>* > hits; map< CTxDestination, set<CTxDestination>* >::iterator it; BOOST_FOREACH(CTxDestination address, grouping) if ((it = setmap.find(address)) != setmap.end()) hits.insert((*it).second); // merge all hit groups into a new single group and delete old groups set<CTxDestination>* merged = new set<CTxDestination>(grouping); BOOST_FOREACH(set<CTxDestination>* hit, hits) { merged->insert(hit->begin(), hit->end()); uniqueGroupings.erase(hit); delete hit; } uniqueGroupings.insert(merged); // update setmap BOOST_FOREACH(CTxDestination element, *merged) setmap[element] = merged; } set< set<CTxDestination> > ret; BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings) { ret.insert(*uniqueGrouping); delete uniqueGrouping; } return ret; } // ppcoin: check 'spent' consistency between wallet and txindex // ppcoin: fix wallet spent state according to txindex void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly) { nMismatchFound = 0; nBalanceInQuestion = 0; LOCK(cs_wallet); vector<CWalletTx*> vCoins; vCoins.reserve(mapWallet.size()); for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) vCoins.push_back(&(*it).second); CTxDB txdb("r"); BOOST_FOREACH(CWalletTx* pcoin, vCoins) { // Find the corresponding transaction index CTxIndex txindex; if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex)) continue; for (unsigned int n=0; n < pcoin->vout.size(); n++) { if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull())) { LogPrintf("FixSpentCoins found lost coin %s EXCL %s[%d], %s\n", FormatMoney(pcoin->vout[n].nValue), pcoin->GetHash().ToString(), n, fCheckOnly? "repair not attempted" : "repairing"); nMismatchFound++; nBalanceInQuestion += pcoin->vout[n].nValue; if (!fCheckOnly) { pcoin->MarkUnspent(n); pcoin->WriteToDisk(); } } else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull())) { LogPrintf("FixSpentCoins found spent coin %s EXCL %s[%d], %s\n", FormatMoney(pcoin->vout[n].nValue), pcoin->GetHash().ToString(), n, fCheckOnly? "repair not attempted" : "repairing"); nMismatchFound++; nBalanceInQuestion += pcoin->vout[n].nValue; if (!fCheckOnly) { pcoin->MarkSpent(n); pcoin->WriteToDisk(); } } } } } // ppcoin: disable transaction (only for coinstake) void CWallet::DisableTransaction(const CTransaction &tx) { if (!tx.IsCoinStake() || !IsFromMe(tx)) return; // only disconnecting coinstake requires marking input unspent LOCK(cs_wallet); BOOST_FOREACH(const CTxIn& txin, tx.vin) { map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n])) { prev.MarkUnspent(txin.prevout.n); prev.WriteToDisk(); } } } } bool CReserveKey::GetReservedKey(CPubKey& pubkey) { if (nIndex == -1) { CKeyPool keypool; pwallet->ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex != -1) vchPubKey = keypool.vchPubKey; else { if (pwallet->vchDefaultKey.IsValid()) { LogPrintf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!"); vchPubKey = pwallet->vchDefaultKey; } else return false; } } assert(vchPubKey.IsValid()); pubkey = vchPubKey; return true; } void CReserveKey::KeepKey() { if (nIndex != -1) pwallet->KeepKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CReserveKey::ReturnKey() { if (nIndex != -1) pwallet->ReturnKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const { setAddress.clear(); CWalletDB walletdb(strWalletFile); LOCK2(cs_main, cs_wallet); BOOST_FOREACH(const int64_t& id, setKeyPool) { CKeyPool keypool; if (!walletdb.ReadPool(id, keypool)) throw runtime_error("GetAllReserveKeyHashes() : read failed"); assert(keypool.vchPubKey.IsValid()); CKeyID keyID = keypool.vchPubKey.GetID(); if (!HaveKey(keyID)) throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool"); setAddress.insert(keyID); } } bool CWallet::UpdatedTransaction(const uint256 &hashTx) { { LOCK(cs_wallet); // Only notify UI if this transaction is in this wallet map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx); if (mi != mapWallet.end()){ NotifyTransactionChanged(this, hashTx, CT_UPDATED); return true; } } return false; } void CWallet::LockCoin(COutPoint& output) { AssertLockHeld(cs_wallet); // setLockedCoins setLockedCoins.insert(output); } void CWallet::UnlockCoin(COutPoint& output) { AssertLockHeld(cs_wallet); // setLockedCoins setLockedCoins.erase(output); } void CWallet::UnlockAllCoins() { AssertLockHeld(cs_wallet); // setLockedCoins setLockedCoins.clear(); } bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const { AssertLockHeld(cs_wallet); // setLockedCoins COutPoint outpt(hash, n); return (setLockedCoins.count(outpt) > 0); } void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) { AssertLockHeld(cs_wallet); // setLockedCoins for (std::set<COutPoint>::iterator it = setLockedCoins.begin(); it != setLockedCoins.end(); it++) { COutPoint outpt = (*it); vOutpts.push_back(outpt); } } void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const { AssertLockHeld(cs_wallet); // mapKeyMetadata mapKeyBirth.clear(); // get birth times for keys with metadata for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++) if (it->second.nCreateTime) mapKeyBirth[it->first] = it->second.nCreateTime; // map in which we'll infer heights of other keys CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock; std::set<CKeyID> setKeys; GetKeys(setKeys); BOOST_FOREACH(const CKeyID &keyid, setKeys) { if (mapKeyBirth.count(keyid) == 0) mapKeyFirstBlock[keyid] = pindexMax; } setKeys.clear(); // if there are no such keys, we're done if (mapKeyFirstBlock.empty()) return; // find first block that affects those keys, if there are any left std::vector<CKeyID> vAffected; for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) { // iterate over all wallet transactions... const CWalletTx &wtx = (*it).second; std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock); if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) { // ... which are already in a block int nHeight = blit->second->nHeight; BOOST_FOREACH(const CTxOut &txout, wtx.vout) { // iterate over all their outputs ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected); BOOST_FOREACH(const CKeyID &keyid, vAffected) { // ... and all their affected keys std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid); if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight) rit->second = blit->second; } vAffected.clear(); } } } // Extract block timestamps for those keys for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++) mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off }
/// \file python_module_order_book.hpp /// /// \brief /// /// \authors maarten /// \date 2020-11-01 /// \copyright Copyright 2017-2020 The Institute for New Economic Thinking, /// Oxford Martin School, University of Oxford /// /// 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. /// /// You may obtain instructions to fulfill the attribution /// requirements in CITATION.cff /// #ifndef ESL_PYTHON_MODULE_ORDER_BOOK_HPP #define ESL_PYTHON_MODULE_ORDER_BOOK_HPP #endif // ESL_PYTHON_MODULE_ORDER_BOOK_HPP
//------------------------------------------------------------------------------ // CustomSensor //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool. // // Copyright (c) 2002 - 2017 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other 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. // // Author: Mike Stark, NASA/GSFC // Created: 2017.04.03 // /** * Implementation of the CustomSensor class */ //------------------------------------------------------------------------------ #include <list> #include <iostream> // for messages, **REPLACE** with appropriate calls ***** #include "CustomSensor.hpp" #include "MessageInterface.hpp" #include "BaseException.hpp" #include "TATCException.hpp" #include "GmatConstants.hpp" #include "RealUtilities.hpp" #include "LinearAlgebra.hpp" //#define DEBUG_CUSTOM_SENSOR //#define DEBUG_CHECK_TARGET using namespace std; using namespace GmatRealConstants; using namespace GmatMathConstants; using namespace GmatMathUtil; //------------------------------------------------------------------------------ // static data //------------------------------------------------------------------------------ // None //------------------------------------------------------------------------------ // public methods //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // CustomSensor(Rvector coneAngleVecIn, clockAngleVecIn) //------------------------------------------------------------------------------ /** * Constructor * * coneAngleVec and clockAngleVec contain pairs of angles that describe the * sensor FOV. coneAngleVec[0] is paired with clockAngleVec[0], * coneAngleVec[1] is paired with clockAngleVec[1] and so on. The last * point in each arrays should be the same as the first point to ensure * FOV closure. * @param coneAngleVec array of cone angles measured from +Z sensor axis (rad) * if xP,yP,zP is a UNIT vector describing a FOV point, then the * cone angle for the point is pi/2 - asin(zP); * @param clockAngleVec array of clock angles (right ascencions) rad * measured clockwise from the + X-axis. if xP,yP,zP is a UNIT vector * describing a FOV point, then the clock angle for the point * is atan2(y,x); */ //------------------------------------------------------------------------------ CustomSensor::CustomSensor (const Rvector &coneAngleVecIn, const Rvector &clockAngleVecIn) : Sensor() { #ifdef DEBUG_CUSTOM_SENSOR MessageInterface::ShowMessage( "DEBUG: Entering CustomSensor constructor\n"); #endif numFOVPoints = coneAngleVecIn.GetSize(); // validate cone & clock angle inputs if (numFOVPoints != clockAngleVecIn.GetSize()) { MessageInterface::ShowMessage( "CustomSensor: Cone & Clock angle vectors must be the same length\n"); throw TATCException( "ERROR: Cone and clock angle vectors must be the same length\n"); } else if (numFOVPoints <= 2) { MessageInterface::ShowMessage( "CustomSensor: must have at least 3 points to form valid FOV\n"); throw TATCException("ERROR: must have 3 points to form valid FOV\n"); } else for (int i = 0; i < numFOVPoints; i++) { // avoid singlularity in stereographic projection //when input is -Z axis of sensor frame if (coneAngleVecIn(i) > PI - 100 * REAL_TOL) { MessageInterface::ShowMessage( "CustomSensor: must have cone angle < Pi to avoid singularity\n"); throw TATCException( "ERROR: must have cone angle < Pi to avoid singularity"); } } // we're good with the input values // set size of arrays for computed stereographic projections xProjectionCoordArray.SetSize(numFOVPoints); yProjectionCoordArray.SetSize(numFOVPoints); // set size of array of line segments connecting points in // stereographic projection segmentArray.SetSize(numFOVPoints,4); // set basic member data items coneAngleVec = coneAngleVecIn; clockAngleVec = clockAngleVecIn; maxExcursionAngle = Max(coneAngleVec); // in superclass Sensor // Perform initial computations //initialize the projection of the FOV arrays ConeClockArraysToStereographic (coneAngleVec, clockAngleVec, xProjectionCoordArray, yProjectionCoordArray); //create bounding box for first test of whether points are in FOV maxXExcursion = Max(xProjectionCoordArray); minXExcursion = Min(xProjectionCoordArray); maxYExcursion = Max(yProjectionCoordArray); minYExcursion = Min(yProjectionCoordArray); // Matlab ComputeLineSegments() only called points to segments, // this is done in constructor instead // compute line segments from stereographic projections segmentArray = PointsToSegments(xProjectionCoordArray, yProjectionCoordArray); // numTestPoints is hardcoded in ComputeExternalPoints() Matlab code, may // want to make it an input parameter to the constructor if this can vary numTestPoints = 3; ComputeExternalPoints(); #ifdef DEBUG_CUSTOM_SENSOR MessageInterface::ShowMessage( "DEBUG: Exiting CustomSensor constructor\n\n"); #endif } // constructor //------------------------------------------------------------------------------ // CustomSensor(const CustomSensor &copy) //------------------------------------------------------------------------------ /** * Copy constructor * * @param copy object to copy */ //------------------------------------------------------------------------------ CustomSensor::CustomSensor(const CustomSensor &copy) : Sensor(copy) { numFOVPoints = copy.numFOVPoints; coneAngleVec = copy.coneAngleVec; clockAngleVec = copy.clockAngleVec; xProjectionCoordArray = copy.xProjectionCoordArray; yProjectionCoordArray = copy.yProjectionCoordArray; segmentArray = copy.segmentArray; numTestPoints = copy.numTestPoints; externalPointArray = copy.externalPointArray; maxXExcursion = copy.maxXExcursion; minXExcursion = copy.minXExcursion; maxYExcursion = copy.maxYExcursion; minYExcursion = copy.minYExcursion; } //------------------------------------------------------------------------------ // CustomSensor& operator= (const CustomSensor &copy) //------------------------------------------------------------------------------ /** * operator= for CustomSensor * * @param copy object to copy * */ //------------------------------------------------------------------------------ CustomSensor& CustomSensor::operator= (const CustomSensor &copy) { Sensor::operator=(copy); if (&copy == this) return *this; numFOVPoints = copy.numFOVPoints; coneAngleVec = copy.coneAngleVec; clockAngleVec = copy.clockAngleVec; xProjectionCoordArray = copy.xProjectionCoordArray; yProjectionCoordArray = copy.yProjectionCoordArray; segmentArray = copy.segmentArray; numTestPoints = copy.numTestPoints; externalPointArray = copy.externalPointArray; maxXExcursion = copy.maxXExcursion; minXExcursion = copy.minXExcursion; maxYExcursion = copy.maxYExcursion; minYExcursion = copy.minYExcursion; return *this; } //------------------------------------------------------------------------------ // ~CustomSensor () //------------------------------------------------------------------------------ // Destructor //------------------------------------------------------------------------------ CustomSensor::~CustomSensor() { } Rvector CustomSensor::GetConeAngleVector(){ return coneAngleVec; } Rvector CustomSensor::GetClockAngleVector(){ return clockAngleVec; } //------------------------------------------------------------------------------ // public methods //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // bool CheckTargetVisibility(Real viewConeAngle, Real viewClockAngle) //------------------------------------------------------------------------------ /* * determines if point represented by a cone angle and a clock angle is in the * sensor's field of view, returns true if this is so * * @param viewConeAngle cone angle for point being tested (rad) * @param viewClockAngle clock angle for point being tested (rad) * @return returns true if point is within sensor field of view * */ //------------------------------------------------------------------------------ bool CustomSensor::CheckTargetVisibility(Real viewConeAngle, Real viewClockAngle) { #ifdef DEBUG_CHECK_TARGET MessageInterface::ShowMessage( "In CustomSensor::CheckTargetVisibility:\n"); MessageInterface::ShowMessage( " viewConeAngle = %12.10f\n", viewConeAngle); MessageInterface::ShowMessage( " viewClockAngle = %12.10f\n", viewClockAngle); #endif // declare data needed for fast checks, and perhaps beyond bool possiblyInView = true; Real xCoord, yCoord; ConeClockToStereographic (viewConeAngle,viewClockAngle,xCoord,yCoord); // first check if in view cone, if so check stereographic box if (!CheckTargetMaxExcursionAngle(viewConeAngle)) possiblyInView = false; else if (!CheckTargetMaxExcursionCoordinates(xCoord,yCoord)) possiblyInView = false; // we've executed the quick tests, if point is possibly in the FOV // then run a line intersection test to determine if it is or not bool inView; if (!possiblyInView) inView = false; else { // outputs of LineSegmentIntersect Rmatrix distanceMatrix(numTestPoints,1); //used in validation std::vector<IntegerArray> adjacency; // used in counting crossings // outputs not used in visibility check Rmatrix huey(numTestPoints,1); Rmatrix dewey(numTestPoints,1); Rmatrix louie(numTestPoints,1); std::vector<IntegerArray> romulus, remus; // vectors of integer arrays have to be loaded to allocate memory // N - vector where each element is an integer array of 1 element IntegerArray row; row.push_back(0); for (int i=0; i<numTestPoints; i++) { adjacency.push_back(row); romulus.push_back(row); remus.push_back(row); } // other declarations Real distance; Real distTol = 1.0e-12; Rmatrix lineSeg(1,4); bool foundValidPoint = false; // valid point test: // See if there is at least 1 valid external point for (int i = 0; i < numTestPoints; i++) { //lineSeg = (xCoord, yCoord, externalPointArray.GetElement(i,0), // externalPointArray.GetElement(i,1)); lineSeg.SetElement(0,0,xCoord); lineSeg.SetElement(0,1,yCoord); lineSeg.SetElement(0,2,externalPointArray.GetElement(i,0)); lineSeg.SetElement(0,3,externalPointArray.GetElement(i,1)); LinearAlgebra::LineSegmentIntersect(segmentArray,lineSeg, adjacency, huey, dewey, louie, distanceMatrix, romulus, remus); // loop exits on finding first valid point or finding none at all // distance matrix computed by LineSegmentIntersect is a // numFOVpoints x 1 matrix for (int j= 0; j < numFOVPoints; j++) { distance = distanceMatrix.GetElement(j,0); if (!(abs(distance)<=distTol || abs(distance-1.0)<=distTol)) { foundValidPoint = true; break; } } if (foundValidPoint) break; } // valid point test // count crossings by iterating across the (numFOVpoints x 1) // adjacency matrix, use result to determine if point is in FOV if (foundValidPoint) { Integer numCrossings = 0; for (int i=0; i < numFOVPoints; i++) if (adjacency[i][0] == 1) numCrossings++; if (numCrossings%2==1) inView = true; else inView = false; } else { MessageInterface::ShowMessage ("Internal Error: No valid external point was found"); inView=false; } } // line intersection test #ifdef DEBUG_CHECK_TARGET MessageInterface::ShowMessage( "LEAVING CustomSensor::CheckTargetVisibility, " "inView = %s\n", (inView? "true" : "false")); #endif return inView; } //------------------------------------------------------------------------------ // bool CheckRegionVisibility(const Rvector &coneAngleVec, // const Rvector &clockAngleVec) //------------------------------------------------------------------------------ /* * returns true if the region enclosed by line segments connecting successive * points represented by the ith and i+1st element of the input vectors is * fully within the sensor FOV * * @param coneAngleVec cone angles for points on region boundary (rad) * @param clockAngVec clock angles for points on region boundary (rad) * @return returns true if region is fully in FOV, false otherwise * */ //------------------------------------------------------------------------------ bool CustomSensor::CheckRegionVisibility(const Rvector &coneAngleVec, const Rvector &clockAngleVec) { #ifdef DEBUG_CUSTOM_SENSOR MessageInterface::ShowMessage( "DEBUG: Entering CheckRegionVisibility()\n"); #endif // linesegArray computed frominput cone and clock angles represents region // object state segmentArray represents sensor FOV Integer size = coneAngleVec.GetSize(); IntegerArray row(size,0); #ifdef DEBUG_CUSTOM_SENSOR MessageInterface::ShowMessage("DEBUG:region defined by %d points\n",size); #endif //unused outputs of line intersection calculations Rmatrix matrixX(numFOVPoints,size); Rmatrix matrixY(numFOVPoints,size); Rmatrix d1To2(numFOVPoints,size); Rmatrix d2To1(numFOVPoints,size); std::vector<IntegerArray> parallel(numFOVPoints,row); std::vector<IntegerArray> coincident(numFOVPoints,row); // adjacency matrix indicating pairs of lines that intersect std::vector<IntegerArray> adjacency(numFOVPoints,row); //compute line segments for region Rvector xCoords(size), yCoords(size); Rmatrix lineSegArray; //MessageInterface::ShowMessage("REGION: to stereographic\n"); ConeClockArraysToStereographic (coneAngleVec,clockAngleVec, xCoords,yCoords); #ifdef DEBUG_CUSTOM_SENSOR MessageInterface::ShowMessage("DEBUG: computed stereographic values:\n"); for (int i = 0; i < size; i++) MessageInterface::ShowMessage("x= %13.10f, y = %13.10f\n", xCoords[i], yCoords[i]); MessageInterface::ShowMessage( "DEBUG: converting points to lineSegArray\n"); #endif lineSegArray = PointsToSegments(xCoords,yCoords); #ifdef DEBUG_CUSTOM_SENSOR MessageInterface::ShowMessage("DEBUG: computed result:\n"); for (int i = 0; i < size; i++) MessageInterface::ShowMessage("(%13.10f %13.10f to %13.10f %13.10f)\n", lineSegArray.GetElement(i,0), lineSegArray.GetElement(i,1), lineSegArray.GetElement(i,2), lineSegArray.GetElement(i,3)); MessageInterface::ShowMessage( "DEBUG: calling intersect routine\n"); #endif // get adjacency matrix for containment test LinearAlgebra::LineSegmentIntersect (segmentArray,lineSegArray, adjacency, matrixX, matrixY, d1To2, d2To1, parallel, coincident); #ifdef DEBUG_CUSTOM_SENSOR MessageInterface::ShowMessage("DEBUG:Returned from intersect routine\n"); MessageInterface::ShowMessage(" Evaluating RegionIsFullyContained()\n"); MessageInterface::ShowMessage(" Then exiting CheckRegionVisibility()\n"); #endif if (RegionIsFullyContained(adjacency) ) return true; else return false; } //------------------------------------------------------------------------------ // protected methods //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // bool CheckTargetMaxExcursionCoordinates(Real xCoord, Real yCoord) //------------------------------------------------------------------------------ /* * returns true if coordinates are in box defined by min and max * excursion each direction, false if point is outside that box. * Provides quick and simple way to reject points. * * @param xCoord x coordinate for point being tested * @param yCoord y coordinate for point being tested */ //------------------------------------------------------------------------------ bool CustomSensor::CheckTargetMaxExcursionCoordinates(Real xCoord, Real yCoord) { // first assume point is in bounding box bool possiblyInView = true; // apply falsifying logic if (xCoord > maxXExcursion) possiblyInView = false; else if (xCoord < minXExcursion) possiblyInView = false; else if (yCoord > maxYExcursion) possiblyInView = false; else if (yCoord < minYExcursion) possiblyInView = false; return possiblyInView; } //------------------------------------------------------------------------------ // Rmatrix PointsToSegments(const Rvector &xCoords, const Rvector &yCoords) //------------------------------------------------------------------------------ /* * Given a vector of N x coordinates and N y coordinates, with [x(i),y(i)] * representing a point, creates an Nx4 matrix with each row representing the * (x,y) pair for two successive points in the vectors and also the line * segment connecting these points. In the current implementation these points * are stereographic projections of vectors on the unit sphere onto a plane. * * @param xCoords vector of x coordinates (N elements) * @param yCoords vector of y coordinates (N elements) * @return returns an Nx4 matrix representing N line segments connecting * successive points to form a closed region. */ //------------------------------------------------------------------------------ Rmatrix CustomSensor::PointsToSegments(const Rvector &xCoords, const Rvector &yCoords) { Integer size = xCoords.GetSize(); Rmatrix lineSegArray(size,4); // convert arrays of points represented by xy stereographic coordinates // to an array of line segments connecting two consecutive points for (int i = 0; i < size - 1; i++) { lineSegArray.SetElement(i,0,xCoords[i]); lineSegArray.SetElement(i,1,yCoords[i]); lineSegArray.SetElement(i,2,xCoords[i+1]); lineSegArray.SetElement(i,3,yCoords[i+1]); } // form last segment by connecting end of xCoords,yCoords // to the beginning int last = size - 1; lineSegArray.SetElement(last,0,xCoords[last]); lineSegArray.SetElement(last,1,yCoords[last]); lineSegArray.SetElement(last,2,xCoords[0]); lineSegArray.SetElement(last,3,yCoords[0]); return lineSegArray; } //------------------------------------------------------------------------------ // void ComputeExternalPoints() //------------------------------------------------------------------------------ /* * Computes points external to FOV to use in visibility tests */ //------------------------------------------------------------------------------ void CustomSensor::ComputeExternalPoints() { #ifdef DEBUG_CUSTOM_SENSOR MessageInterface::ShowMessage( "DEBUG: Entering ComputeExternalPoints()\n"); #endif //setup output array Rvector coneAngles(numFOVPoints); Rvector clockAngles(numFOVPoints); Rvector xCoords(numFOVPoints); Rvector yCoords(numFOVPoints); Rmatrix externalPoints; // check to see if all points in stereographic projection // are inside unit circle, if so create 3 random points outside unit circle Rvector pointDist(numFOVPoints); for (int i=0; i < numFOVPoints; i++) pointDist[i] = sqrt(xProjectionCoordArray[i] * xProjectionCoordArray[i] + yProjectionCoordArray[i] * yProjectionCoordArray[i]); #ifdef DEBUG_CUSTOM_SENSOR MessageInterface::ShowMessage("DEBUG: max distance from center = %f\n", Max(pointDist)); #endif Integer numCandidatePoints = 0; Rvector xCandidatePoints(numFOVPoints); Rvector yCandidatePoints(numFOVPoints); Rvector v1(2), v2(2); Real interiorAngle; Real safetyFactor = 1.1; Rvector candidateConeAngles; // will be set using count of candidates IntegerArray indices; // will also be set using count of candidates // loop over points and compute internal angle at vertex j for (int i = 0; i < numFOVPoints; i++) { Integer j,k; // test for wrap-around of indices if (i <= (numFOVPoints-1)-2) // add -1 so can compare with MATLAB { j = i+1; k = j+1; } else if (i <= (numFOVPoints-1)-1) // add -1 so can compare with MATLAB { j = numFOVPoints-1; // last point in array range k = 0; // wrap around } else //i == numFOVPoints - 1, last point in array wrap around { j = 0; k = 1; } #ifdef DEBUG_CUSTOM_SENSOR MessageInterface::ShowMessage("DEBUG:(i,j,k)= (%d %d %d)\n", i,j,k); #endif // compute internal angles v1[0] = xProjectionCoordArray[j]-xProjectionCoordArray[i]; v1[1] = yProjectionCoordArray[j]-yProjectionCoordArray[i]; v2[0] = xProjectionCoordArray[k]-xProjectionCoordArray[j]; v2[1] = yProjectionCoordArray[k]-yProjectionCoordArray[j]; interiorAngle = Mod (ATan2(v2[1],v2[0]), 2.0*PI) - Mod (ATan2(v1[1],v1[0]), 2.0*PI); interiorAngle = Mod (interiorAngle, 2.0*PI); #ifdef DEBUG_CUSTOM_SENSOR MessageInterface::ShowMessage("DEBUG: interior angle = %f\n", interiorAngle); #endif // see if this is a candidate point if (interiorAngle <= PI) { numCandidatePoints++; xCandidatePoints[numCandidatePoints-1] = xProjectionCoordArray[j]; yCandidatePoints[numCandidatePoints-1] = yProjectionCoordArray[j]; coneAngles[numCandidatePoints-1] = coneAngleVec[j]; } } // for #ifdef DEBUG_CUSTOM_SENSOR MessageInterface::ShowMessage("DEBUG: %d candidate points\n", numCandidatePoints); #endif // sort the candidate points in order of decreasing cone angle // and use three largest cone angles as the test points // check to see how array slices work to see if loop is needed here candidateConeAngles.SetSize(numCandidatePoints); for (int i = 0; i < numCandidatePoints; i++) candidateConeAngles[i] = coneAngles[i]; // false == input defining descending order as not ascending order Sort(candidateConeAngles,indices,false); #ifdef DEBUG_CUSTOM_SENSOR MessageInterface::ShowMessage("DEBUG: Sorted candidate angles\n"); for (int i = 0; i < numCandidatePoints; i++) MessageInterface::ShowMessage("DEBUG: value, index = (%f, %d)\n", candidateConeAngles[i],i); #endif if (numCandidatePoints < numTestPoints) numTestPoints = numCandidatePoints; externalPoints.SetSize(numTestPoints,2); for (int i = 0; i < numTestPoints; i++) { int index = indices[i]; externalPoints.SetElement(i,0,safetyFactor*xCandidatePoints[index]); externalPoints.SetElement(i,1,safetyFactor*yCandidatePoints[index]); } externalPointArray = externalPoints; #ifdef DEBUG_CUSTOM_SENSOR MessageInterface::ShowMessage("DEBUG: Exiting ComputeExternalPoints\n"); #endif } //------------------------------------------------------------------------------ // bool RegionIsFullyContained (std::vector<IntegerArray &adjacency); //------------------------------------------------------------------------------ /* * Determines whether an adajency matrix indicates that a region is * fully contained within the sensor FOV, used by checkRegionVisibility() * * @param adjacency [input] entry (i,j) is 1 if line segments XY1(i,*) * and XY2(j,*)intersect; 0 otherwise * @return returns true if region is completely in FOV, * false otherwise */ //------------------------------------------------------------------------------ bool CustomSensor::RegionIsFullyContained(std::vector<IntegerArray> &adjacency) { //assume no intersecting lines, then look to see if there are any bool isFullyContained = true; Integer nRows = adjacency.size(); Integer nCols; IntegerArray row; #ifdef DEBUG_CUSTOM_SENSOR MessageInterface::ShowMessage("DEBUG: Adjacency being tested\n"); for (int i = 0; i < nRows; i++) { row=adjacency[i]; nCols=row.size(); for (int j = 0; j < nCols; j++) MessageInterface::ShowMessage("%d ",row[j]); MessageInterface::ShowMessage("\n"); } MessageInterface::ShowMessage("\n"); #endif // test to see if there is any line crossing for (int i = 0; i < nRows; i++) { row = adjacency[i]; nCols = row.size(); for (int j = 0; j < nCols; j++) { if (row[j] == 1) { isFullyContained = false; #ifdef DEBUG_CUSTOM_SENSOR MessageInterface::ShowMessage( "found a crossing at index %d,%d\n",i,j); #endif break; // does this exit j-loop ohly or both i & j loops } if (!isFullyContained) break; } } return isFullyContained; } // internal utilities for Rvector and coordinate conversion // Rvector utilities //------------------------------------------------------------------------------ // void Sort(Rvector &v, bool ascending = true) //------------------------------------------------------------------------------ /* * sorts an rVector into ascending or descending order, in place * NOTE: THIS COULD BE MOVED INTO RVECTOR ITSELF AS A MEMBER FUNCTION * * @param v vector to be sorted * @param Ascending indicates ascending sort if true, descending if false * */ //------------------------------------------------------------------------------ void CustomSensor::Sort(Rvector &v, bool ascending) { // load list with Rvector & sort it Integer size = v.GetSize(); std::list<Real> rList; for (int i = 0; i < size; i++) rList.push_back(v[i]); rList.sort(); // move back to Rvector in either ascending or descending order if (ascending) for (int i = 0; i < size; i++) { v[i] = rList.front(); rList.pop_front(); } else // descending for (int i = 0; i < size; i++) { v[i] = rList.back(); rList.pop_back(); } } //------------------------------------------------------------------------------ // void Sort(Rvector &v, IntegerArray &indices, bool ascending = true) //------------------------------------------------------------------------------ /* * sorts an rVector into ascending or descending order, in place * NOTE: THIS COULD BE MOVED INTO RVECTOR ITSELF AS A MEMBER FUNCTION * * @param v vector to be sorted * @param indices array of pre-sort indices of sorted vector * @param Ascending indicates ascending sort if true, descending if false * */ //------------------------------------------------------------------------------ void CustomSensor::Sort(Rvector &v, IntegerArray &indices, bool ascending) { Integer size = v.GetSize(); indices.resize(size); SensorElement e; std::list<SensorElement> eList; eList.clear(); // load list with elements - real value from Rvector and corresponding index for (int i = 0; i<size; i++) { e.value = v[i]; e.index = i; eList.push_back(e); } // sort with std::list sort function; providing necessary compare function eList.sort(CompareSensorElements); // eList now is ascending order, pull data off appropriate end of the list if (ascending) { for (int i = 0; i < size; i++) { e = eList.front(); v[i] = e.value; indices[i] = e.index; eList.pop_front(); } } else // descending, pull highest values off of back to load v { for (int i = 0; i < size; i++) { e = eList.back(); v[i] = e.value; indices[i] = e.index; eList.pop_back(); } } } //------------------------------------------------------------------------------ // Real Max(const Rvector &v) //------------------------------------------------------------------------------ /** * returns maximum value from an Rvector * * @param v vector containing real values to select maximum from * @return maximum value contained in vector */ //------------------------------------------------------------------------------ Real CustomSensor::Max(const Rvector &v) { Real maxval = v[0]; Integer N = v.GetSize(); for (int i = 0; i < N; i++) if (v[i] > maxval) maxval = v[i]; return maxval; } //------------------------------------------------------------------------------ // Real Min(const Rvector &v) //------------------------------------------------------------------------------ /** * returns minimum value from an Rvector * * @param v vector containing real values to select minimum from * @return minimum value contained in vector */ //------------------------------------------------------------------------------ Real CustomSensor::Min(const Rvector &v) { Real minval = v[0]; Integer N = v.GetSize(); for (int i = 0; i < N; i++) if (v[i] < minval) minval = v[i]; return minval; } //------------------------------------------------------------------------------ // bool CompareSensorElements(SensorElement e1, SensorElement e2) //------------------------------------------------------------------------------ /** * compares 2 elements using ordering of values * * @param e1 first element in comparison * @param e2 second element in comparison * @return true if value of e1 is less than value of e2, false otherwise * */ //------------------------------------------------------------------------------ bool CompareSensorElements(const SensorElement &e1, const SensorElement &e2) { return e1.value < e2.value; }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/threadcoin-config.h" #endif #include "util.h" #include "support/allocators/secure.h" #include "chainparamsbase.h" #include "random.h" #include "serialize.h" #include "sync.h" #include "utilstrencodings.h" #include "utiltime.h" #include <stdarg.h> #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)) #include <pthread.h> #include <pthread_np.h> #endif #ifndef WIN32 // for posix_fallocate #ifdef __linux__ #ifdef _POSIX_C_SOURCE #undef _POSIX_C_SOURCE #endif #define _POSIX_C_SOURCE 200112L #endif // __linux__ #include <algorithm> #include <fcntl.h> #include <sys/resource.h> #include <sys/stat.h> #else #ifdef _MSC_VER #pragma warning(disable:4786) #pragma warning(disable:4804) #pragma warning(disable:4805) #pragma warning(disable:4717) #endif #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include <io.h> /* for _commit */ #include <shlobj.h> #endif #ifdef HAVE_SYS_PRCTL_H #include <sys/prctl.h> #endif #include <boost/algorithm/string/case_conv.hpp> // for to_lower() #include <boost/algorithm/string/join.hpp> #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith() #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/classification.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/foreach.hpp> #include <boost/program_options/detail/config_file.hpp> #include <boost/program_options/parsers.hpp> #include <boost/thread.hpp> #include <openssl/crypto.h> #include <openssl/rand.h> #include <openssl/conf.h> // Work around clang compilation problem in Boost 1.46: // /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION namespace boost { namespace program_options { std::string to_internal(const std::string&); } } // namespace boost using namespace std; //Threadcoin only features bool fMasterNode = false; bool fLiteMode = false; /** nWalletBackups: 1..10 - number of automatic backups to keep 0 - disabled by command-line -1 - disabled because of some error during run-time -2 - disabled because wallet was locked and we were not able to replenish keypool */ int nWalletBackups = 10; const char * const BITCOIN_CONF_FILENAME = "threadcoin.conf"; const char * const BITCOIN_PID_FILENAME = "threadcoind.pid"; map<string, string> mapArgs; map<string, vector<string> > mapMultiArgs; bool fDebug = false; bool fPrintToConsole = false; bool fPrintToDebugLog = true; bool fDaemon = false; bool fServer = false; string strMiscWarning; bool fLogTimestamps = DEFAULT_LOGTIMESTAMPS; bool fLogTimeMicros = DEFAULT_LOGTIMEMICROS; bool fLogThreadNames = DEFAULT_LOGTHREADNAMES; bool fLogIPs = DEFAULT_LOGIPS; volatile bool fReopenDebugLog = false; CTranslationInterface translationInterface; /** Init OpenSSL library multithreading support */ static CCriticalSection** ppmutexOpenSSL; void locking_callback(int mode, int i, const char* file, int line) NO_THREAD_SAFETY_ANALYSIS { if (mode & CRYPTO_LOCK) { ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]); } else { LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]); } } // Init class CInit { public: CInit() { // Init OpenSSL library multithreading support ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*)); for (int i = 0; i < CRYPTO_num_locks(); i++) ppmutexOpenSSL[i] = new CCriticalSection(); CRYPTO_set_locking_callback(locking_callback); // OpenSSL can optionally load a config file which lists optional loadable modules and engines. // We don't use them so we don't require the config. However some of our libs may call functions // which attempt to load the config file, possibly resulting in an exit() or crash if it is missing // or corrupt. Explicitly tell OpenSSL not to try to load the file. The result for our libs will be // that the config appears to have been loaded and there are no modules/engines available. OPENSSL_no_config(); #ifdef WIN32 // Seed OpenSSL PRNG with current contents of the screen RAND_screen(); #endif // Seed OpenSSL PRNG with performance counter RandAddSeed(); } ~CInit() { // Securely erase the memory used by the PRNG RAND_cleanup(); // Shutdown OpenSSL library multithreading support CRYPTO_set_locking_callback(NULL); for (int i = 0; i < CRYPTO_num_locks(); i++) delete ppmutexOpenSSL[i]; OPENSSL_free(ppmutexOpenSSL); } } instance_of_cinit; /** * LogPrintf() has been broken a couple of times now * by well-meaning people adding mutexes in the most straightforward way. * It breaks because it may be called by global destructors during shutdown. * Since the order of destruction of static/global objects is undefined, * defining a mutex as a global object doesn't work (the mutex gets * destroyed, and then some later destructor calls OutputDebugStringF, * maybe indirectly, and you get a core dump at shutdown trying to lock * the mutex). */ static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT; /** * We use boost::call_once() to make sure mutexDebugLog and * vMsgsBeforeOpenLog are initialized in a thread-safe manner. * * NOTE: fileout, mutexDebugLog and sometimes vMsgsBeforeOpenLog * are leaked on exit. This is ugly, but will be cleaned up by * the OS/libc. When the shutdown sequence is fully audited and * tested, explicit destruction of these objects can be implemented. */ static FILE* fileout = NULL; static boost::mutex* mutexDebugLog = NULL; static list<string> *vMsgsBeforeOpenLog; static int FileWriteStr(const std::string &str, FILE *fp) { return fwrite(str.data(), 1, str.size(), fp); } static void DebugPrintInit() { assert(mutexDebugLog == NULL); mutexDebugLog = new boost::mutex(); vMsgsBeforeOpenLog = new list<string>; } void OpenDebugLog() { boost::call_once(&DebugPrintInit, debugPrintInitFlag); boost::mutex::scoped_lock scoped_lock(*mutexDebugLog); assert(fileout == NULL); assert(vMsgsBeforeOpenLog); boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; fileout = fopen(pathDebug.string().c_str(), "a"); if (fileout) setbuf(fileout, NULL); // unbuffered // dump buffered messages from before we opened the log while (!vMsgsBeforeOpenLog->empty()) { FileWriteStr(vMsgsBeforeOpenLog->front(), fileout); vMsgsBeforeOpenLog->pop_front(); } delete vMsgsBeforeOpenLog; vMsgsBeforeOpenLog = NULL; } bool LogAcceptCategory(const char* category) { if (category != NULL) { // Give each thread quick access to -debug settings. // This helps prevent issues debugging global destructors, // where mapMultiArgs might be deleted before another // global destructor calls LogPrint() static boost::thread_specific_ptr<set<string> > ptrCategory; if (!fDebug) { if (ptrCategory.get() != NULL) { LogPrintf("debug turned off: thread %s\n", GetThreadName()); ptrCategory.release(); } return false; } if (ptrCategory.get() == NULL) { std::string strThreadName = GetThreadName(); LogPrintf("debug turned on:\n"); for (int i = 0; i < (int)mapMultiArgs["-debug"].size(); ++i) LogPrintf(" thread %s category %s\n", strThreadName, mapMultiArgs["-debug"][i]); const vector<string>& categories = mapMultiArgs["-debug"]; ptrCategory.reset(new set<string>(categories.begin(), categories.end())); // thread_specific_ptr automatically deletes the set when the thread ends. // "threadcoin" is a composite category enabling all Threadcoin-related debug output if(ptrCategory->count(string("threadcoin"))) { ptrCategory->insert(string("privatesend")); ptrCategory->insert(string("instantsend")); ptrCategory->insert(string("masternode")); ptrCategory->insert(string("spork")); ptrCategory->insert(string("keepass")); ptrCategory->insert(string("mnpayments")); ptrCategory->insert(string("gobject")); } } const set<string>& setCategories = *ptrCategory.get(); // if not debugging everything and not debugging specific category, LogPrint does nothing. if (setCategories.count(string("")) == 0 && setCategories.count(string("1")) == 0 && setCategories.count(string(category)) == 0) return false; } return true; } /** * fStartedNewLine is a state variable held by the calling context that will * suppress printing of the timestamp when multiple calls are made that don't * end in a newline. Initialize it to true, and hold/manage it, in the calling context. */ static std::string LogTimestampStr(const std::string &str, bool *fStartedNewLine) { string strStamped; if (!fLogTimestamps) return str; if (*fStartedNewLine) { int64_t nTimeMicros = GetLogTimeMicros(); strStamped = DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nTimeMicros/1000000); if (fLogTimeMicros) strStamped += strprintf(".%06d", nTimeMicros%1000000); strStamped += ' ' + str; } else strStamped = str; return strStamped; } /** * fStartedNewLine is a state variable held by the calling context that will * suppress printing of the thread name when multiple calls are made that don't * end in a newline. Initialize it to true, and hold/manage it, in the calling context. */ static std::string LogThreadNameStr(const std::string &str, bool *fStartedNewLine) { string strThreadLogged; if (!fLogThreadNames) return str; std::string strThreadName = GetThreadName(); if (*fStartedNewLine) strThreadLogged = strprintf("%16s | %s", strThreadName.c_str(), str.c_str()); else strThreadLogged = str; return strThreadLogged; } int LogPrintStr(const std::string &str) { int ret = 0; // Returns total number of characters written static bool fStartedNewLine = true; std::string strThreadLogged = LogThreadNameStr(str, &fStartedNewLine); std::string strTimestamped = LogTimestampStr(strThreadLogged, &fStartedNewLine); if (!str.empty() && str[str.size()-1] == '\n') fStartedNewLine = true; else fStartedNewLine = false; if (fPrintToConsole) { // print to console ret = fwrite(strTimestamped.data(), 1, strTimestamped.size(), stdout); fflush(stdout); } else if (fPrintToDebugLog) { boost::call_once(&DebugPrintInit, debugPrintInitFlag); boost::mutex::scoped_lock scoped_lock(*mutexDebugLog); // buffer if we haven't opened the log yet if (fileout == NULL) { assert(vMsgsBeforeOpenLog); ret = strTimestamped.length(); vMsgsBeforeOpenLog->push_back(strTimestamped); } else { // reopen the log file, if requested if (fReopenDebugLog) { fReopenDebugLog = false; boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL) setbuf(fileout, NULL); // unbuffered } ret = FileWriteStr(strTimestamped, fileout); } } return ret; } /** Interpret string as boolean, for argument parsing */ static bool InterpretBool(const std::string& strValue) { if (strValue.empty()) return true; return (atoi(strValue) != 0); } /** Turn -noX into -X=0 */ static void InterpretNegativeSetting(std::string& strKey, std::string& strValue) { if (strKey.length()>3 && strKey[0]=='-' && strKey[1]=='n' && strKey[2]=='o') { strKey = "-" + strKey.substr(3); strValue = InterpretBool(strValue) ? "0" : "1"; } } void ParseParameters(int argc, const char* const argv[]) { mapArgs.clear(); mapMultiArgs.clear(); for (int i = 1; i < argc; i++) { std::string str(argv[i]); std::string strValue; size_t is_index = str.find('='); if (is_index != std::string::npos) { strValue = str.substr(is_index+1); str = str.substr(0, is_index); } #ifdef WIN32 boost::to_lower(str); if (boost::algorithm::starts_with(str, "/")) str = "-" + str.substr(1); #endif if (str[0] != '-') break; // Interpret --foo as -foo. // If both --foo and -foo are set, the last takes effect. if (str.length() > 1 && str[1] == '-') str = str.substr(1); InterpretNegativeSetting(str, strValue); mapArgs[str] = strValue; mapMultiArgs[str].push_back(strValue); } } std::string GetArg(const std::string& strArg, const std::string& strDefault) { if (mapArgs.count(strArg)) return mapArgs[strArg]; return strDefault; } int64_t GetArg(const std::string& strArg, int64_t nDefault) { if (mapArgs.count(strArg)) return atoi64(mapArgs[strArg]); return nDefault; } bool GetBoolArg(const std::string& strArg, bool fDefault) { if (mapArgs.count(strArg)) return InterpretBool(mapArgs[strArg]); return fDefault; } bool SoftSetArg(const std::string& strArg, const std::string& strValue) { if (mapArgs.count(strArg)) return false; mapArgs[strArg] = strValue; return true; } bool SoftSetBoolArg(const std::string& strArg, bool fValue) { if (fValue) return SoftSetArg(strArg, std::string("1")); else return SoftSetArg(strArg, std::string("0")); } static const int screenWidth = 79; static const int optIndent = 2; static const int msgIndent = 7; std::string HelpMessageGroup(const std::string &message) { return std::string(message) + std::string("\n\n"); } std::string HelpMessageOpt(const std::string &option, const std::string &message) { return std::string(optIndent,' ') + std::string(option) + std::string("\n") + std::string(msgIndent,' ') + FormatParagraph(message, screenWidth - msgIndent, msgIndent) + std::string("\n\n"); } static std::string FormatException(const std::exception* pex, const char* pszThread) { #ifdef WIN32 char pszModule[MAX_PATH] = ""; GetModuleFileNameA(NULL, pszModule, sizeof(pszModule)); #else const char* pszModule = "threadcoin"; #endif if (pex) return strprintf( "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread); else return strprintf( "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread); } void PrintExceptionContinue(const std::exception* pex, const char* pszThread) { std::string message = FormatException(pex, pszThread); LogPrintf("\n\n************************\n%s\n", message); fprintf(stderr, "\n\n************************\n%s\n", message.c_str()); } boost::filesystem::path GetDefaultDataDir() { namespace fs = boost::filesystem; // Windows < Vista: C:\Documents and Settings\Username\Application Data\ThreadcoinCore // Windows >= Vista: C:\Users\Username\AppData\Roaming\ThreadcoinCore // Mac: ~/Library/Application Support/ThreadcoinCore // Unix: ~/.threadcoincore #ifdef WIN32 // Windows return GetSpecialFolderPath(CSIDL_APPDATA) / "ThreadcoinCore"; #else fs::path pathRet; char* pszHome = getenv("HOME"); if (pszHome == NULL || strlen(pszHome) == 0) pathRet = fs::path("/"); else pathRet = fs::path(pszHome); #ifdef MAC_OSX // Mac return pathRet / "Library/Application Support/ThreadcoinCore"; #else // Unix return pathRet / ".threadcoincore"; #endif #endif } static boost::filesystem::path pathCached; static boost::filesystem::path pathCachedNetSpecific; static CCriticalSection csPathCached; const boost::filesystem::path &GetDataDir(bool fNetSpecific) { namespace fs = boost::filesystem; LOCK(csPathCached); fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached; // This can be called during exceptions by LogPrintf(), so we cache the // value so we don't have to do memory allocations after that. if (!path.empty()) return path; if (mapArgs.count("-datadir")) { path = fs::system_complete(mapArgs["-datadir"]); if (!fs::is_directory(path)) { path = ""; return path; } } else { path = GetDefaultDataDir(); } if (fNetSpecific) path /= BaseParams().DataDir(); fs::create_directories(path); return path; } static boost::filesystem::path backupsDirCached; static CCriticalSection csBackupsDirCached; const boost::filesystem::path &GetBackupsDir() { namespace fs = boost::filesystem; LOCK(csBackupsDirCached); fs::path &backupsDir = backupsDirCached; if (!backupsDir.empty()) return backupsDir; if (mapArgs.count("-walletbackupsdir")) { backupsDir = fs::absolute(mapArgs["-walletbackupsdir"]); // Path must exist if (fs::is_directory(backupsDir)) return backupsDir; // Fallback to default path if it doesn't LogPrintf("%s: Warning: incorrect parameter -walletbackupsdir, path must exist! Using default path.\n", __func__); strMiscWarning = _("Warning: incorrect parameter -walletbackupsdir, path must exist! Using default path."); } // Default path backupsDir = GetDataDir() / "backups"; return backupsDir; } void ClearDatadirCache() { pathCached = boost::filesystem::path(); pathCachedNetSpecific = boost::filesystem::path(); } boost::filesystem::path GetConfigFile() { boost::filesystem::path pathConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)); if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile; return pathConfigFile; } boost::filesystem::path GetMasternodeConfigFile() { boost::filesystem::path pathConfigFile(GetArg("-mnconf", "masternode.conf")); if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir() / pathConfigFile; return pathConfigFile; } void ReadConfigFile(map<string, string>& mapSettingsRet, map<string, vector<string> >& mapMultiSettingsRet) { boost::filesystem::ifstream streamConfig(GetConfigFile()); if (!streamConfig.good()){ // Create empty threadcoin.conf if it does not excist FILE* configFile = fopen(GetConfigFile().string().c_str(), "a"); if (configFile != NULL) fclose(configFile); return; // Nothing to read, so just return } set<string> setOptions; setOptions.insert("*"); for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it) { // Don't overwrite existing settings so command line settings override threadcoin.conf string strKey = string("-") + it->string_key; string strValue = it->value[0]; InterpretNegativeSetting(strKey, strValue); if (mapSettingsRet.count(strKey) == 0) mapSettingsRet[strKey] = strValue; mapMultiSettingsRet[strKey].push_back(strValue); } // If datadir is changed in .conf file: ClearDatadirCache(); } #ifndef WIN32 boost::filesystem::path GetPidFile() { boost::filesystem::path pathPidFile(GetArg("-pid", BITCOIN_PID_FILENAME)); if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile; return pathPidFile; } void CreatePidFile(const boost::filesystem::path &path, pid_t pid) { FILE* file = fopen(path.string().c_str(), "w"); if (file) { fprintf(file, "%d\n", pid); fclose(file); } } #endif bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest) { #ifdef WIN32 return MoveFileExA(src.string().c_str(), dest.string().c_str(), MOVEFILE_REPLACE_EXISTING) != 0; #else int rc = std::rename(src.string().c_str(), dest.string().c_str()); return (rc == 0); #endif /* WIN32 */ } /** * Ignores exceptions thrown by Boost's create_directory if the requested directory exists. * Specifically handles case where path p exists, but it wasn't possible for the user to * write to the parent directory. */ bool TryCreateDirectory(const boost::filesystem::path& p) { try { return boost::filesystem::create_directory(p); } catch (const boost::filesystem::filesystem_error&) { if (!boost::filesystem::exists(p) || !boost::filesystem::is_directory(p)) throw; } // create_directory didn't create the directory, it had to have existed already return false; } void FileCommit(FILE *fileout) { fflush(fileout); // harmless if redundantly called #ifdef WIN32 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(fileout)); FlushFileBuffers(hFile); #else #if defined(__linux__) || defined(__NetBSD__) fdatasync(fileno(fileout)); #elif defined(__APPLE__) && defined(F_FULLFSYNC) fcntl(fileno(fileout), F_FULLFSYNC, 0); #else fsync(fileno(fileout)); #endif #endif } bool TruncateFile(FILE *file, unsigned int length) { #if defined(WIN32) return _chsize(_fileno(file), length) == 0; #else return ftruncate(fileno(file), length) == 0; #endif } /** * this function tries to raise the file descriptor limit to the requested number. * It returns the actual file descriptor limit (which may be more or less than nMinFD) */ int RaiseFileDescriptorLimit(int nMinFD) { #if defined(WIN32) return 2048; #else struct rlimit limitFD; if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) { if (limitFD.rlim_cur < (rlim_t)nMinFD) { limitFD.rlim_cur = nMinFD; if (limitFD.rlim_cur > limitFD.rlim_max) limitFD.rlim_cur = limitFD.rlim_max; setrlimit(RLIMIT_NOFILE, &limitFD); getrlimit(RLIMIT_NOFILE, &limitFD); } return limitFD.rlim_cur; } return nMinFD; // getrlimit failed, assume it's fine #endif } /** * this function tries to make a particular range of a file allocated (corresponding to disk space) * it is advisory, and the range specified in the arguments will never contain live data */ void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) { #if defined(WIN32) // Windows-specific version HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file)); LARGE_INTEGER nFileSize; int64_t nEndPos = (int64_t)offset + length; nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF; nFileSize.u.HighPart = nEndPos >> 32; SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN); SetEndOfFile(hFile); #elif defined(MAC_OSX) // OSX specific version fstore_t fst; fst.fst_flags = F_ALLOCATECONTIG; fst.fst_posmode = F_PEOFPOSMODE; fst.fst_offset = 0; fst.fst_length = (off_t)offset + length; fst.fst_bytesalloc = 0; if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) { fst.fst_flags = F_ALLOCATEALL; fcntl(fileno(file), F_PREALLOCATE, &fst); } ftruncate(fileno(file), fst.fst_length); #elif defined(__linux__) // Version using posix_fallocate off_t nEndPos = (off_t)offset + length; posix_fallocate(fileno(file), 0, nEndPos); #else // Fallback version // TODO: just write one byte per block static const char buf[65536] = {}; fseek(file, offset, SEEK_SET); while (length > 0) { unsigned int now = 65536; if (length < now) now = length; fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway length -= now; } #endif } void ShrinkDebugFile() { // Amount of debug.log to save at end when shrinking (must fit in memory) constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000; // Scroll debug.log if it's getting too big boost::filesystem::path pathLog = GetDataDir() / "debug.log"; FILE* file = fopen(pathLog.string().c_str(), "r"); // If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE // trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes if (file && boost::filesystem::file_size(pathLog) > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10)) { // Restart the file with some of the end std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0); fseek(file, -((long)vch.size()), SEEK_END); int nBytes = fread(begin_ptr(vch), 1, vch.size(), file); fclose(file); file = fopen(pathLog.string().c_str(), "w"); if (file) { fwrite(begin_ptr(vch), 1, nBytes, file); fclose(file); } } else if (file != NULL) fclose(file); } #ifdef WIN32 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate) { namespace fs = boost::filesystem; char pszPath[MAX_PATH] = ""; if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate)) { return fs::path(pszPath); } LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n"); return fs::path(""); } #endif boost::filesystem::path GetTempPath() { #if BOOST_FILESYSTEM_VERSION == 3 return boost::filesystem::temp_directory_path(); #else // TODO: remove when we don't support filesystem v2 anymore boost::filesystem::path path; #ifdef WIN32 char pszPath[MAX_PATH] = ""; if (GetTempPathA(MAX_PATH, pszPath)) path = boost::filesystem::path(pszPath); #else path = boost::filesystem::path("/tmp"); #endif if (path.empty() || !boost::filesystem::is_directory(path)) { LogPrintf("GetTempPath(): failed to find temp path\n"); return boost::filesystem::path(""); } return path; #endif } void runCommand(const std::string& strCommand) { int nErr = ::system(strCommand.c_str()); if (nErr) LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr); } void RenameThread(const char* name) { #if defined(PR_SET_NAME) // Only the first 15 characters are used (16 - NUL terminator) ::prctl(PR_SET_NAME, name, 0, 0, 0); #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)) pthread_set_name_np(pthread_self(), name); #elif defined(MAC_OSX) pthread_setname_np(name); #else // Prevent warnings for unused parameters... (void)name; #endif } std::string GetThreadName() { char name[16]; #if defined(PR_GET_NAME) // Only the first 15 characters are used (16 - NUL terminator) ::prctl(PR_GET_NAME, name, 0, 0, 0); #elif defined(MAC_OSX) pthread_getname_np(pthread_self(), name, 16); // #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)) // #else // no get_name here #endif return std::string(name); } void SetupEnvironment() { // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale // may be invalid, in which case the "C" locale is used as fallback. #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__) try { std::locale(""); // Raises a runtime error if current locale is invalid } catch (const std::runtime_error&) { setenv("LC_ALL", "C", 1); } #endif // The path locale is lazy initialized and to avoid deinitialization errors // in multithreading environments, it is set explicitly by the main thread. // A dummy locale is used to extract the internal default locale, used by // boost::filesystem::path, which is then used to explicitly imbue the path. std::locale loc = boost::filesystem::path::imbue(std::locale::classic()); boost::filesystem::path::imbue(loc); } bool SetupNetworking() { #ifdef WIN32 // Initialize Windows Sockets WSADATA wsadata; int ret = WSAStartup(MAKEWORD(2,2), &wsadata); if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2) return false; #endif return true; } void SetThreadPriority(int nPriority) { #ifdef WIN32 SetThreadPriority(GetCurrentThread(), nPriority); #else // WIN32 #ifdef PRIO_THREAD setpriority(PRIO_THREAD, 0, nPriority); #else // PRIO_THREAD setpriority(PRIO_PROCESS, 0, nPriority); #endif // PRIO_THREAD #endif // WIN32 } int GetNumCores() { #if BOOST_VERSION >= 105600 return boost::thread::physical_concurrency(); #else // Must fall back to hardware_concurrency, which unfortunately counts virtual cores return boost::thread::hardware_concurrency(); #endif } uint32_t StringVersionToInt(const std::string& strVersion) { std::vector<std::string> tokens; boost::split(tokens, strVersion, boost::is_any_of(".")); if(tokens.size() != 3) throw std::bad_cast(); uint32_t nVersion = 0; for(unsigned idx = 0; idx < 3; idx++) { if(tokens[idx].length() == 0) throw std::bad_cast(); uint32_t value = boost::lexical_cast<uint32_t>(tokens[idx]); if(value > 255) throw std::bad_cast(); nVersion <<= 8; nVersion |= value; } return nVersion; } std::string IntVersionToString(uint32_t nVersion) { if((nVersion >> 24) > 0) // MSB is always 0 throw std::bad_cast(); if(nVersion == 0) throw std::bad_cast(); std::array<std::string, 3> tokens; for(unsigned idx = 0; idx < 3; idx++) { unsigned shift = (2 - idx) * 8; uint32_t byteValue = (nVersion >> shift) & 0xff; tokens[idx] = boost::lexical_cast<std::string>(byteValue); } return boost::join(tokens, "."); } std::string SafeIntVersionToString(uint32_t nVersion) { try { return IntVersionToString(nVersion); } catch(const std::bad_cast&) { return "invalid_version"; } }
/********************************************************************** Audacity: A Digital Audio Editor ImportQT.cpp Joshua Haberman On OS X, handles import of MPEG-4 audio including AAC and Apple Lossless, import of audio from MPEG-4 video files, and import of AIF(F)/AIFC files (AIF(F) might contain content libsndfile can't handle). Could be modified to support QuickTime import on Windows. **********************************************************************/ #include "../Audacity.h" #include "ImportQT.h" #include "ImportPlugin.h" #define DESC _("QuickTime files") static const wxChar *exts[] = { wxT("aif"), wxT("aifc"), wxT("aiff"), wxT("mov"), wxT("aac"), wxT("m4a"), wxT("mp4") }; #ifndef USE_QUICKTIME void GetQTImportPlugin(ImportPluginList &importPluginList, UnusableImportPluginList &unusableImportPluginList) { unusableImportPluginList.push_back( make_movable<UnusableImportPlugin> (DESC, wxArrayString(WXSIZEOF(exts), exts)) ); } #else /* USE_QUICKTIME */ #include <wx/msgdlg.h> // There's a name collision between our Track and QuickTime's...workaround it #define Track XTrack #if defined(__WXMAC__) // These get used when building under OSX #include <Carbon/Carbon.h> #include <QuickTime/QuickTime.h> #include <wx/osx/core/private.h> #else // These get used when building under Windows #include <ConditionalMacros.h> #include <Movies.h> #include <QuickTimeComponents.h> #include <Sound.h> #include <Folders.h> #include <ToolUtils.h> #include <Gestalt.h> #include <Navigation.h> #endif // There's a name collision between our Track and QuickTime's...workaround it #undef Track #include "../Internat.h" #include "../Tags.h" #include "../WaveTrack.h" #define kQTAudioPropertyID_MaxAudioSampleSize 'mssz' class QTImportPlugin final : public ImportPlugin { public: QTImportPlugin() : ImportPlugin(wxArrayString(WXSIZEOF(exts), exts)), mInitialized(false) { OSErr err = noErr; #if defined(__WXMSW__) err = ::InitializeQTML(0); #endif if (err == noErr) { err = ::EnterMovies(); if (err == noErr) { mInitialized = true; } else { #if defined(__WXMSW__) TerminateQTML(); #endif } } } ~QTImportPlugin() { if (mInitialized) { ExitMovies(); #if defined(__WXMSW__) TerminateQTML(); #endif } mInitialized = false; } wxString GetPluginStringID() { return wxT("quicktime"); } wxString GetPluginFormatDescription(); std::unique_ptr<ImportFileHandle> Open(const wxString & Filename) override; private: bool mInitialized; }; class QTImportFileHandle final : public ImportFileHandle { public: QTImportFileHandle(const wxString & name, Movie movie) : ImportFileHandle(name) { mMovie = movie; } virtual ~QTImportFileHandle() { if (mMovie) { DisposeMovie(mMovie); mMovie = NULL; } } wxString GetFileDescription() override; ByteCount GetFileUncompressedBytes() override; wxInt32 GetStreamCount() override { return 1; } const wxArrayString &GetStreamInfo() override { static wxArrayString empty; return empty; } void SetStreamUsage(wxInt32 StreamID, bool Use) override { } ProgressResult Import(TrackFactory *trackFactory, TrackHolders &outTracks, Tags *tags) override; private: void AddMetadata(Tags *tags); Movie mMovie; }; void GetQTImportPlugin(ImportPluginList &importPluginList, UnusableImportPluginList &unusableImportPluginList) { importPluginList.push_back( make_movable<QTImportPlugin>() ); } wxString QTImportPlugin::GetPluginFormatDescription() { return DESC; } std::unique_ptr<ImportFileHandle> QTImportPlugin::Open(const wxString & Filename) { OSErr err; FSRef inRef; Movie theMovie = NULL; Handle dataRef = NULL; OSType dataRefType = 0; short resID = 0; #if defined(__WXMAC__) err = wxMacPathToFSRef(Filename, &inRef); #else // LLL: This will not work for pathnames with Unicode characters...find // another method. err = FSPathMakeRef((UInt8 *)OSFILENAME(Filename), &inRef, NULL); #endif if (err != noErr) { return nullptr; } err = QTNewDataReferenceFromFSRef(&inRef, 0, &dataRef, &dataRefType); if (err != noErr) { return nullptr; } // instantiate the movie err = NewMovieFromDataRef(&theMovie, newMovieActive | newMovieDontAskUnresolvedDataRefs, &resID, dataRef, dataRefType); DisposeHandle(dataRef); if (err != noErr) { return nullptr; } return std::make_unique<QTImportFileHandle>(Filename, theMovie); } wxString QTImportFileHandle::GetFileDescription() { return DESC; } auto QTImportFileHandle::GetFileUncompressedBytes() -> ByteCount { return 0; } ProgressResult QTImportFileHandle::Import(TrackFactory *trackFactory, TrackHolders &outTracks, Tags *tags) { outTracks.clear(); OSErr err = noErr; MovieAudioExtractionRef maer = NULL; auto updateResult = ProgressResult::Success; auto totSamples = (sampleCount) GetMovieDuration(mMovie); // convert from TimeValue decltype(totSamples) numSamples = 0; Boolean discrete = true; UInt32 quality = kQTAudioRenderQuality_Max; AudioStreamBasicDescription desc; UInt32 maxSampleSize; bool res = false; auto cleanup = finally( [&] { if (maer) { MovieAudioExtractionEnd(maer); } } ); CreateProgress(); do { err = MovieAudioExtractionBegin(mMovie, 0, &maer); if (err != noErr) { wxMessageBox(_("Unable to start QuickTime extraction")); break; } err = MovieAudioExtractionSetProperty(maer, kQTPropertyClass_MovieAudioExtraction_Audio, kQTMovieAudioExtractionAudioPropertyID_RenderQuality, sizeof(quality), &quality); if (err != noErr) { wxMessageBox(_("Unable to set QuickTime render quality")); break; } err = MovieAudioExtractionSetProperty(maer, kQTPropertyClass_MovieAudioExtraction_Movie, kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete, sizeof(discrete), &discrete); if (err != noErr) { wxMessageBox(_("Unable to set QuickTime discrete channels property")); break; } err = MovieAudioExtractionGetProperty(maer, kQTPropertyClass_MovieAudioExtraction_Audio, kQTAudioPropertyID_MaxAudioSampleSize, sizeof(maxSampleSize), &maxSampleSize, NULL); if (err != noErr) { wxMessageBox(_("Unable to get QuickTime sample size property")); break; } err = MovieAudioExtractionGetProperty(maer, kQTPropertyClass_MovieAudioExtraction_Audio, kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription, sizeof(desc), &desc, NULL); if (err != noErr) { wxMessageBox(_("Unable to retrieve stream description")); break; } auto numchan = desc.mChannelsPerFrame; const size_t bufsize = 5 * desc.mSampleRate; // determine sample format sampleFormat format; switch (maxSampleSize) { case 16: format = int16Sample; break; case 24: format = int24Sample; break; default: format = floatSample; break; } // Allocate an array of pointers, whose size is not known statically, // and prefixed with the AudioBufferList structure. MallocPtr< AudioBufferList > abl{ static_cast< AudioBufferList * >( calloc( 1, offsetof( AudioBufferList, mBuffers ) + (sizeof(AudioBuffer) * numchan))) }; abl->mNumberBuffers = numchan; TrackHolders channels{ numchan }; const auto size = sizeof(float) * bufsize; ArraysOf<unsigned char> holders{ numchan, size }; for (size_t c = 0; c < numchan; c++) { auto &buffer = abl->mBuffers[c]; auto &holder = holders[c]; auto &channel = channels[c]; buffer.mNumberChannels = 1; buffer.mDataByteSize = size; buffer.mData = holder.get(); channel = trackFactory->NewWaveTrack( format ); channel->SetRate( desc.mSampleRate ); if (numchan == 2) { if (c == 0) { channel->SetChannel(Track::LeftChannel); channel->SetLinked(true); } else if (c == 1) { channel->SetChannel(Track::RightChannel); } } } do { UInt32 flags = 0; UInt32 numFrames = bufsize; err = MovieAudioExtractionFillBuffer(maer, &numFrames, abl.get(), &flags); if (err != noErr) { wxMessageBox(_("Unable to get fill buffer")); break; } for (size_t c = 0; c < numchan; c++) { channels[c]->Append((char *) abl->mBuffers[c].mData, floatSample, numFrames); } numSamples += numFrames; updateResult = mProgress->Update( numSamples.as_long_long(), totSamples.as_long_long() ); if (numFrames == 0 || flags & kQTMovieAudioExtractionComplete) { break; } } while (updateResult == ProgressResult::Success); res = (updateResult == ProgressResult::Success && err == noErr); if (res) { for (const auto &channel: channels) { channel->Flush(); } outTracks.swap(channels); } // // Extract any metadata // if (res) { AddMetadata(tags); } } while (false); // done: return (res ? ProgressResult::Success : ProgressResult::Failed); } static const struct { const OSType key; const wxChar *name; } names[] = { { kQTMetaDataCommonKeyAuthor, wxT("Author") }, { kQTMetaDataCommonKeyComment, TAG_COMMENTS }, { kQTMetaDataCommonKeyCopyright, TAG_COPYRIGHT }, { kQTMetaDataCommonKeyDirector, wxT("Director") }, { kQTMetaDataCommonKeyDisplayName, wxT("Full Name") }, { kQTMetaDataCommonKeyInformation, wxT("Information") }, { kQTMetaDataCommonKeyKeywords, wxT("Keywords") }, { kQTMetaDataCommonKeyProducer, wxT("Producer") }, { kQTMetaDataCommonKeyAlbum, TAG_ALBUM }, { kQTMetaDataCommonKeyArtist, TAG_ARTIST }, { kQTMetaDataCommonKeyChapterName, wxT("Chapter") }, { kQTMetaDataCommonKeyComposer, wxT("Composer") }, { kQTMetaDataCommonKeyDescription, wxT("Description") }, { kQTMetaDataCommonKeyGenre, TAG_GENRE }, { kQTMetaDataCommonKeyOriginalFormat, wxT("Original Format") }, { kQTMetaDataCommonKeyOriginalSource, wxT("Original Source") }, { kQTMetaDataCommonKeyPerformers, wxT("Performers") }, { kQTMetaDataCommonKeySoftware, TAG_SOFTWARE }, { kQTMetaDataCommonKeyWriter, wxT("Writer") }, }; void QTImportFileHandle::AddMetadata(Tags *tags) { QTMetaDataRef metaDataRef = NULL; auto cleanup = finally( [&] { // we are done so release our metadata object if ( metaDataRef ) QTMetaDataRelease(metaDataRef); } ); OSErr err; err = QTCopyMovieMetaData(mMovie, &metaDataRef); if (err != noErr) { return; } for (int i = 0; i < WXSIZEOF(names); i++) { QTMetaDataItem item = kQTMetaDataItemUninitialized; // OSType key = names[i].key; err = QTMetaDataGetNextItem(metaDataRef, kQTMetaDataStorageFormatWildcard, kQTMetaDataItemUninitialized, kQTMetaDataKeyFormatCommon, (const UInt8 *) &names[i].key, sizeof(names[i].key), &item); if (err != noErr) { continue; } if (item == kQTMetaDataItemUninitialized) { continue; } QTPropertyValueType outPropType; ::ByteCount outPropValueSize; ::ByteCount outPropValueSizeUsed = 0; UInt32 outPropFlags; UInt32 dataType; // Get data type err = QTMetaDataGetItemProperty(metaDataRef, item, kPropertyClass_MetaDataItem, kQTMetaDataItemPropertyID_DataType, sizeof(dataType), &dataType, &outPropValueSizeUsed); if (err != noErr) { continue; } // Get the data length err = QTMetaDataGetItemPropertyInfo(metaDataRef, item, kPropertyClass_MetaDataItem, kQTMetaDataItemPropertyID_Value, &outPropType, &outPropValueSize, &outPropFlags ); if (err != noErr) { continue; } // Alloc memory for it ArrayOf<char> outVals{ outPropValueSize }; // Retrieve the data err = QTMetaDataGetItemProperty(metaDataRef, item, kPropertyClass_MetaDataItem, kQTMetaDataItemPropertyID_Value, outPropValueSize, outVals.get(), &outPropValueSizeUsed); if (err != noErr) continue; wxString v = wxT(""); switch (dataType) { case kQTMetaDataTypeUTF8: v = wxString(outVals.get(), wxConvUTF8); break; case kQTMetaDataTypeUTF16BE: { wxMBConvUTF16BE conv; v = wxString(outVals.get(), conv); } break; } if (!v.IsEmpty()) { tags->SetTag(names[i].name, v); } } return; } #endif
/* * Copyright 2011-present Facebook, 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 <folly/TimeoutQueue.h> #include <algorithm> #include <vector> namespace folly { TimeoutQueue::Id TimeoutQueue::add( int64_t now, int64_t delay, Callback callback) { Id id = nextId_++; timeouts_.insert({id, now + delay, -1, std::move(callback)}); return id; } TimeoutQueue::Id TimeoutQueue::addRepeating( int64_t now, int64_t interval, Callback callback) { Id id = nextId_++; timeouts_.insert({id, now + interval, interval, std::move(callback)}); return id; } int64_t TimeoutQueue::nextExpiration() const { return (timeouts_.empty() ? std::numeric_limits<int64_t>::max() : timeouts_.get<BY_EXPIRATION>().begin()->expiration); } bool TimeoutQueue::erase(Id id) { return timeouts_.get<BY_ID>().erase(id); } int64_t TimeoutQueue::runInternal(int64_t now, bool onceOnly) { auto& byExpiration = timeouts_.get<BY_EXPIRATION>(); int64_t nextExp; do { auto end = byExpiration.upper_bound(now); std::vector<Event> expired; std::move(byExpiration.begin(), end, std::back_inserter(expired)); byExpiration.erase(byExpiration.begin(), end); for (auto& event : expired) { // Reinsert if repeating, do this before executing callbacks // so the callbacks have a chance to call erase if (event.repeatInterval >= 0) { timeouts_.insert({event.id, now + event.repeatInterval, event.repeatInterval, event.callback}); } } // Call callbacks for (auto& event : expired) { event.callback(event.id, now); } nextExp = nextExpiration(); } while (!onceOnly && nextExp <= now); return nextExp; } } // namespace folly
/* * This file is part of the GROMACS molecular simulation package. * * Copyright 2018- The GROMACS Authors * and the project initiators Erik Lindahl, Berk Hess and David van der Spoel. * Consult the AUTHORS/COPYING files and https://www.gromacs.org for details. * * GROMACS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * GROMACS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GROMACS; if not, see * https://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at https://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out https://www.gromacs.org. */ /*! \internal \file * \brief Subroutines to run LINCS on GPU * * Copies data to GPU, runs LINCS and copies the results back. * * \author Artem Zhmurov <zhmurov@gmail.com> * \ingroup module_mdlib */ #include "gmxpre.h" #include "config.h" #include <gtest/gtest.h> #include "constrtestrunners.h" #if GPU_CONSTRAINTS_SUPPORTED # include "gromacs/gpu_utils/devicebuffer.h" #endif #include "gromacs/gpu_utils/gputraits.h" #include "gromacs/mdlib/lincs_gpu.h" #include "gromacs/pbcutil/pbc.h" namespace gmx { namespace test { #if GPU_CONSTRAINTS_SUPPORTED void LincsDeviceConstraintsRunner::applyConstraints(ConstraintsTestData* testData, t_pbc pbc) { const DeviceContext& deviceContext = testDevice_.deviceContext(); const DeviceStream& deviceStream = testDevice_.deviceStream(); setActiveDevice(testDevice_.deviceInfo()); auto lincsGpu = std::make_unique<LincsGpu>( testData->ir_.nLincsIter, testData->ir_.nProjOrder, deviceContext, deviceStream); bool updateVelocities = true; int numAtoms = testData->numAtoms_; Float3* h_x = gmx::asGenericFloat3Pointer(testData->x_); Float3* h_xp = gmx::asGenericFloat3Pointer(testData->xPrime_); Float3* h_v = gmx::asGenericFloat3Pointer(testData->v_); DeviceBuffer<Float3> d_x, d_xp, d_v; lincsGpu->set(*testData->idef_, testData->numAtoms_, testData->invmass_.data()); PbcAiuc pbcAiuc; setPbcAiuc(pbc.ndim_ePBC, pbc.box, &pbcAiuc); allocateDeviceBuffer(&d_x, numAtoms, deviceContext); allocateDeviceBuffer(&d_xp, numAtoms, deviceContext); allocateDeviceBuffer(&d_v, numAtoms, deviceContext); copyToDeviceBuffer(&d_x, h_x, 0, numAtoms, deviceStream, GpuApiCallBehavior::Sync, nullptr); copyToDeviceBuffer(&d_xp, h_xp, 0, numAtoms, deviceStream, GpuApiCallBehavior::Sync, nullptr); if (updateVelocities) { copyToDeviceBuffer(&d_v, h_v, 0, numAtoms, deviceStream, GpuApiCallBehavior::Sync, nullptr); } lincsGpu->apply( d_x, d_xp, updateVelocities, d_v, testData->invdt_, testData->computeVirial_, testData->virialScaled_, pbcAiuc); copyFromDeviceBuffer(h_xp, &d_xp, 0, numAtoms, deviceStream, GpuApiCallBehavior::Sync, nullptr); if (updateVelocities) { copyFromDeviceBuffer(h_v, &d_v, 0, numAtoms, deviceStream, GpuApiCallBehavior::Sync, nullptr); } freeDeviceBuffer(&d_x); freeDeviceBuffer(&d_xp); freeDeviceBuffer(&d_v); } #else // GPU_CONSTRAINTS_SUPPORTED void LincsDeviceConstraintsRunner::applyConstraints(ConstraintsTestData* /* testData */, t_pbc /* pbc */) { GMX_UNUSED_VALUE(testDevice_); FAIL() << "Dummy LINCS GPU function was called instead of the real one."; } #endif // GPU_CONSTRAINTS_SUPPORTED } // namespace test } // namespace gmx
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/apigateway/model/QuotaSettings.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace APIGateway { namespace Model { QuotaSettings::QuotaSettings() : m_limit(0), m_limitHasBeenSet(false), m_offset(0), m_offsetHasBeenSet(false), m_period(QuotaPeriodType::NOT_SET), m_periodHasBeenSet(false) { } QuotaSettings::QuotaSettings(JsonView jsonValue) : m_limit(0), m_limitHasBeenSet(false), m_offset(0), m_offsetHasBeenSet(false), m_period(QuotaPeriodType::NOT_SET), m_periodHasBeenSet(false) { *this = jsonValue; } QuotaSettings& QuotaSettings::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("limit")) { m_limit = jsonValue.GetInteger("limit"); m_limitHasBeenSet = true; } if(jsonValue.ValueExists("offset")) { m_offset = jsonValue.GetInteger("offset"); m_offsetHasBeenSet = true; } if(jsonValue.ValueExists("period")) { m_period = QuotaPeriodTypeMapper::GetQuotaPeriodTypeForName(jsonValue.GetString("period")); m_periodHasBeenSet = true; } return *this; } JsonValue QuotaSettings::Jsonize() const { JsonValue payload; if(m_limitHasBeenSet) { payload.WithInteger("limit", m_limit); } if(m_offsetHasBeenSet) { payload.WithInteger("offset", m_offset); } if(m_periodHasBeenSet) { payload.WithString("period", QuotaPeriodTypeMapper::GetNameForQuotaPeriodType(m_period)); } return payload; } } // namespace Model } // namespace APIGateway } // namespace Aws
#include <iostream> #include <webhelper.hpp> int main(int argc, char const *argv[]) { WebHelper web("www.example.com", WebHelper::HTTP); if( web.GetStatus() != WebHelper::A_OK || web.RequestPage("index.html") != WebHelper::A_OK ) { std::cout << web.GetStatusDescription() << std::endl; } else { std::cout << web.GetResponse() << std::endl; } return 0; }
#include <iostream> #include <string> using namespace std; inline void use_io_optimizations() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } bool is_palindrome(const string& sequence) { for (string::size_type i {0}; i < sequence.size() / 2; ++i) { if (sequence[i] != sequence[sequence.size() - 1 - i]) { return false; } } return true; } int main() { use_io_optimizations(); unsigned int max_palindrome {0}; for (unsigned int i {100}; i <= 999; ++i) { for (unsigned int j {100}; j <= 999; ++j) { if (is_palindrome(to_string(i * j))) { max_palindrome = max(max_palindrome, i * j); } } } cout << max_palindrome << '\n'; return 0; }
/* Copyright (c) 2020 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License. */ #include "graph/context/QueryContext.h" namespace nebula { namespace graph { QueryContext::QueryContext(RequestContextPtr rctx, meta::SchemaManager* sm, meta::IndexManager* im, storage::GraphStorageClient* storage, meta::MetaClient* metaClient, CharsetInfo* charsetInfo) : rctx_(std::move(rctx)), sm_(DCHECK_NOTNULL(sm)), im_(DCHECK_NOTNULL(im)), storageClient_(DCHECK_NOTNULL(storage)), metaClient_(DCHECK_NOTNULL(metaClient)), charsetInfo_(DCHECK_NOTNULL(charsetInfo)) { init(); } QueryContext::QueryContext() { init(); } void QueryContext::init() { objPool_ = std::make_unique<ObjectPool>(); ep_ = std::make_unique<ExecutionPlan>(); ectx_ = std::make_unique<ExecutionContext>(); idGen_ = std::make_unique<IdGenerator>(0); symTable_ = std::make_unique<SymbolTable>(objPool_.get()); vctx_ = std::make_unique<ValidateContext>(std::make_unique<AnonVarGenerator>(symTable_.get())); } } // namespace graph } // namespace nebula
// Copyright (c) 2011-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <qt/addressbookpage.h> #include <qt/forms/ui_addressbookpage.h> #include <qt/addresstablemodel.h> #include <qt/bitcoingui.h> #include <qt/csvmodelwriter.h> #include <qt/editaddressdialog.h> #include <qt/guiutil.h> #include <qt/platformstyle.h> #include <QIcon> #include <QMenu> #include <QMessageBox> #include <QSortFilterProxyModel> AddressBookPage::AddressBookPage(const PlatformStyle *platformStyle, Mode _mode, Tabs _tab, QWidget *parent) : QDialog(parent), ui(new Ui::AddressBookPage), model(0), mode(_mode), tab(_tab) { ui->setupUi(this); if (!platformStyle->getImagesOnButtons()) { ui->newAddress->setIcon(QIcon()); ui->copyAddress->setIcon(QIcon()); ui->deleteAddress->setIcon(QIcon()); ui->exportButton->setIcon(QIcon()); } else { ui->newAddress->setIcon(platformStyle->SingleColorIcon(":/icons/add")); ui->copyAddress->setIcon(platformStyle->SingleColorIcon(":/icons/editcopy")); ui->deleteAddress->setIcon(platformStyle->SingleColorIcon(":/icons/remove")); ui->exportButton->setIcon(platformStyle->SingleColorIcon(":/icons/export")); } switch(mode) { case ForSelection: switch(tab) { case SendingTab: setWindowTitle(tr("Choose the address to send coins to")); break; case ReceivingTab: setWindowTitle(tr("Choose the address to receive coins with")); break; } connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setFocus(); ui->closeButton->setText(tr("C&hoose")); ui->exportButton->hide(); break; case ForEditing: switch(tab) { case SendingTab: setWindowTitle(tr("Sending addresses")); break; case ReceivingTab: setWindowTitle(tr("Receiving addresses")); break; } break; } switch(tab) { case SendingTab: ui->labelExplanation->setText(tr("These are your Looniecoin addresses for sending payments. Always check the amount and the receiving address before sending coins.")); ui->deleteAddress->setVisible(true); break; case ReceivingTab: ui->labelExplanation->setText(tr("These are your Looniecoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.")); ui->deleteAddress->setVisible(false); break; } // Context menu actions QAction *copyAddressAction = new QAction(tr("&Copy Address"), this); QAction *copyLabelAction = new QAction(tr("Copy &Label"), this); QAction *editAction = new QAction(tr("&Edit"), this); deleteAction = new QAction(ui->deleteAddress->text(), this); // Build context menu contextMenu = new QMenu(this); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(editAction); if(tab == SendingTab) contextMenu->addAction(deleteAction); contextMenu->addSeparator(); // Connect signals for context menu actions connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction())); connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(accept())); } AddressBookPage::~AddressBookPage() { delete ui; } void AddressBookPage::setModel(AddressTableModel *_model) { this->model = _model; if(!_model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(_model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); switch(tab) { case ReceivingTab: // Receive filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Receive); break; case SendingTab: // Send filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Send); break; } ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); // Set column widths #if QT_VERSION < 0x050000 ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #else ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #endif connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created address connect(_model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int))); selectionChanged(); } void AddressBookPage::on_copyAddress_clicked() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address); } void AddressBookPage::onCopyLabelAction() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label); } void AddressBookPage::onEditAction() { if(!model) return; if(!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::EditSendingAddress : EditAddressDialog::EditReceivingAddress, this); dlg.setModel(model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void AddressBookPage::on_newAddress_clicked() { if(!model) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::NewSendingAddress : EditAddressDialog::NewReceivingAddress, this); dlg.setModel(model); if(dlg.exec()) { newAddressToSelect = dlg.getAddress(); } } void AddressBookPage::on_deleteAddress_clicked() { QTableView *table = ui->tableView; if(!table->selectionModel()) return; QModelIndexList indexes = table->selectionModel()->selectedRows(); if(!indexes.isEmpty()) { table->model()->removeRow(indexes.at(0).row()); } } void AddressBookPage::selectionChanged() { // Set button states based on selected tab and selection QTableView *table = ui->tableView; if(!table->selectionModel()) return; if(table->selectionModel()->hasSelection()) { switch(tab) { case SendingTab: // In sending tab, allow deletion of selection ui->deleteAddress->setEnabled(true); ui->deleteAddress->setVisible(true); deleteAction->setEnabled(true); break; case ReceivingTab: // Deleting receiving addresses, however, is not allowed ui->deleteAddress->setEnabled(false); ui->deleteAddress->setVisible(false); deleteAction->setEnabled(false); break; } ui->copyAddress->setEnabled(true); } else { ui->deleteAddress->setEnabled(false); ui->copyAddress->setEnabled(false); } } void AddressBookPage::done(int retval) { QTableView *table = ui->tableView; if(!table->selectionModel() || !table->model()) return; // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); for (const QModelIndex& index : indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } if(returnValue.isEmpty()) { // If no address entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void AddressBookPage::on_exportButton_clicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName(this, tr("Export Address List"), QString(), tr("Comma separated file (*.csv)"), nullptr); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole); writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole); if(!writer.write()) { QMessageBox::critical(this, tr("Exporting Failed"), tr("There was an error trying to save the address list to %1. Please try again.").arg(filename)); } } void AddressBookPage::contextualMenu(const QPoint &point) { QModelIndex index = ui->tableView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } } void AddressBookPage::selectNewAddress(const QModelIndex &parent, int begin, int /*end*/) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent)); if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) { // Select row of newly created address, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAddressToSelect.clear(); } }
#include <SFGUI/RadioButton.hpp> #include <SFGUI/RadioButtonGroup.hpp> namespace sfg { RadioButton::Ptr RadioButton::Create( const sf::String& label, RadioButtonGroup::Ptr group ) { auto widget = Ptr( new RadioButton ); widget->SetLabel( label ); if( group ) { widget->SetGroup( group ); } else { widget->SetGroup( RadioButtonGroup::Create() ); } return widget; } RadioButtonGroup::Ptr RadioButton::GetGroup() const { return m_group; } void RadioButton::SetGroup( RadioButtonGroup::Ptr group ) { auto weak_this = std::weak_ptr<RadioButton>( std::static_pointer_cast<RadioButton>( shared_from_this() ) ); if( m_group ) { m_group->GetMembers().erase( weak_this ); } m_group = group; if( m_group ) { m_group->GetMembers().insert( weak_this ); } } void RadioButton::SetActive( bool active ) { if( active && m_group ) { for( auto iter = m_group->GetMembers().begin(); iter != m_group->GetMembers().end(); ++iter ) { std::shared_ptr<RadioButton> radio_button( iter->lock() ); if( radio_button ) { radio_button->SetActive( false ); } else { m_group->GetMembers().erase( iter ); } } } ToggleButton::SetActive( active ); } bool RadioButton::HandleMouseClick( sf::Mouse::Button button, int x, int y ) { if( !IsActive() && ( button == sf::Mouse::Left ) ) { SetActive( true ); } Button::HandleMouseClick( button, x, y ); return true; } const std::string& RadioButton::GetName() const { static const std::string name( "RadioButton" ); return name; } }
//------------------------------------------------------------------------------ /* This file is part of rippled: https://github.com/ripple/rippled Copyright (c) 2012, 2013 Ripple 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 <BeastConfig.h> #include <ripple/app/tx/impl/OfferStream.h> #include <ripple/beast/unit_test.h> namespace ripple { class OfferStream_test : public beast::unit_test::suite { public: void test() { pass(); } void run() { test(); } }; BEAST_DEFINE_TESTSUITE(OfferStream,tx,ripple); }
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ /* * itkTubeSpatialObject test file. * This test file test also the basic functions of the CompositeSpatialObject class, * like Add/RemoveSpatialObject(...), Get/SetChildren(...), etc... */ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkPoint.h" #include "itkAffineTransform.h" #include "itkTubeSpatialObject.h" #include "itkGroupSpatialObject.h" #include "itkMacro.h" #include "vnl/vnl_math.h" int itkTubeSpatialObjectTest(int, char * [] ) { typedef double ScalarType; typedef bool OutputType; typedef itk::Vector< ScalarType, 3> Vector; typedef itk::Vector< OutputType, 3> OutputVector; typedef itk::Point< ScalarType, 3> Point; typedef itk::Matrix< ScalarType, 3, 3> Matrix; typedef itk::TubeSpatialObject<3> TubeType; typedef itk::SmartPointer< TubeType > TubePointer; typedef itk::GroupSpatialObject<3> GroupType; typedef itk::SmartPointer< GroupType > GroupPointer; typedef TubeType::TubePointType TubePointType; typedef TubeType::PointListType TubePointListType; typedef std::list< itk::SpatialObject<3>::Pointer > ChildrenListType; typedef ChildrenListType * ChildrenListPointer; Vector axis, translation; Point in, out; double angle; bool passed = true; //====================================== // testing of a single SpatialObject... //====================================== std::cout<<"=================================="<<std::endl; std::cout<<"Testing SpatialObject:"<<std::endl<<std::endl; TubePointer tube1 = TubeType::New(); tube1->GetProperty()->SetName("Tube 1"); tube1->SetId(1); TubePointListType list; TubeType::TransformType::OffsetType offset; offset.Fill(10); tube1->GetObjectToParentTransform()->SetOffset(offset); tube1->ComputeObjectToWorldTransform(); for( unsigned int i=0; i<10; i++) { TubePointType p; p.SetPosition(i,i,i); p.SetRadius(1); list.push_back(p); } // For coverage TubePointType p; p.SetPosition(1,2,3); p.SetRadius(1); p.Print(std::cout); tube1->SetPoints(list); tube1->ComputeBoundingBox(); in.Fill(15); out.Fill(5); std::cout<<"IsInside()..."; if( !tube1->IsInside(in) || tube1->IsInside(out) ) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; } TubeType::OutputVectorType derivative; std::cout<<"DerivativeAt()..."; try { tube1->DerivativeAt(in,1,derivative); } catch(...) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } TubeType::OutputVectorType expectedDerivative; expectedDerivative.Fill(0); if( expectedDerivative != derivative ) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; } std::cout<<"itkTubeSpatialObjectTest "; if( passed ) { std::cout<<"[PASSED]"<<std::endl; } else { std::cout<<"[FAILED]"<<std::endl; } //============================================== // testing of a single CompositeSpatialObject... //============================================== std::cout<<"=================================="<<std::endl; std::cout<<"Testing GroupSpatialObject:"<<std::endl<<std::endl; ChildrenListType childrenList; ChildrenListPointer returnedList; unsigned int nbChildren; TubePointer tube2 = TubeType::New(); tube2->GetProperty()->SetName("Tube 2"); tube2->SetId(2); tube2->SetPoints(list); tube2->ComputeBoundingBox(); TubePointer tube3 = TubeType::New(); tube3->GetProperty()->SetName("Tube 3"); tube3->SetId(3); tube3->SetPoints(list); tube3->ComputeBoundingBox(); GroupPointer tubeNet1 = GroupType::New(); tubeNet1->GetProperty()->SetName("tube network 1"); tubeNet1->AddSpatialObject( tube1 ); tubeNet1->AddSpatialObject( tube2 ); tubeNet1->AddSpatialObject( tube3 ); // testing the AddSpatialObject() function... nbChildren = tubeNet1->GetNumberOfChildren(); std::cout<<"AddSpatialObject()..."; if( nbChildren != 3 ) { std::cout<<"[FAILED] ["<< nbChildren << "!= 3]" << std::endl; return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; } // testing the RemoveSpatialObject() function... tubeNet1->RemoveSpatialObject( tube1 ); tubeNet1->RemoveSpatialObject( tube2 ); tubeNet1->RemoveSpatialObject( tube3 ); nbChildren = tubeNet1->GetNumberOfChildren(); std::cout<<"RemoveSpatialObject()..."; if( nbChildren != 0 ) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; } tubeNet1->AddSpatialObject( tube1 ); tubeNet1->AddSpatialObject( tube2 ); tubeNet1->AddSpatialObject( tube3 ); // testing the GetChildren() function... childrenList.push_back( tube1.GetPointer() ); childrenList.push_back( tube2.GetPointer() ); childrenList.push_back( tube3.GetPointer() ); returnedList = tubeNet1->GetChildren(); if( childrenList.size() == returnedList->size() ) { ChildrenListType::iterator itTest = returnedList->begin(); ChildrenListType::iterator it = childrenList.begin(); ChildrenListType::iterator end = childrenList.end(); for(unsigned int i=0; it!=end; itTest++,it++,i++ ) { if((*itTest) != (*it)) { passed = false; break; } } } else { passed = false; } std::cout<<"GetChildren()..."; if( !passed ) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; } tubeNet1->RemoveSpatialObject( tube1 ); tubeNet1->RemoveSpatialObject( tube2 ); tubeNet1->RemoveSpatialObject( tube3 ); delete returnedList; // testing the SetChildren() function... std::cout << "Set children ..." << std::endl; tubeNet1->SetChildren(childrenList); returnedList = tubeNet1->GetChildren(); if( childrenList.size() == returnedList->size() ) { ChildrenListType::iterator itTest = returnedList->begin(); ChildrenListType::iterator it = childrenList.begin(); ChildrenListType::iterator end = childrenList.end(); passed = true; for(unsigned int i=0; it!=end; itTest++,it++,i++ ) { if((*itTest) != (*it)) { passed = false; break; } } } else { passed = false; } delete returnedList; std::cout<<"SetChildren()..."; if( !passed ) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; } tubeNet1->ComputeBoundingBox(); std::cout<<"HasParent()..."; if( !tube2->HasParent() ) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; } translation.Fill(10); tubeNet1->GetObjectToParentTransform()->Translate(translation,false); tubeNet1->ComputeObjectToWorldTransform(); axis.Fill(0); axis[1] = 1; angle = vnl_math::pi_over_2; tube2->GetObjectToParentTransform()->Rotate3D(axis,angle); tube2->ComputeObjectToWorldTransform(); angle = -vnl_math::pi_over_2; tube3->GetObjectToParentTransform()->Rotate3D(axis,angle); tube3->ComputeObjectToWorldTransform(); in.Fill(25); out.Fill(15); Point p1,p2; p1.Fill(15); p1[2]=5; p2.Fill(15); p2[0]=5; std::cout<<"IsInside()..."; if( !tubeNet1->IsInside(in,3) || tubeNet1->IsInside(out,3) ) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; } std::cout<<"DerivativeAt()..."; try { tubeNet1->DerivativeAt(in,(unsigned short)1,derivative,true); } catch(...) { std::cout<<"[FAILED]"<<std::endl; } if( derivative == expectedDerivative ) { std::cout<<"[PASSED]"<<std::endl; } else { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } //==================================================== // testing of references behavior for SpatialObject... //==================================================== std::cout<<"=============================================="<<std::endl; std::cout<<"Testing references behavior for SpatialObject:"<<std::endl<<std::endl; TubePointer tube = TubeType::New(); GroupPointer net = GroupType::New(); unsigned int tubeCount, netCount; tubeCount = tube->GetReferenceCount(); netCount = net->GetReferenceCount(); std::cout<<"References test..."; if( tubeCount != 1 ) { std::cout<<"[FAILED]: Problem in Tube initialization of references count" << tubeCount <<std::endl; return EXIT_FAILURE; } else { TubePointer localTube = tube; tubeCount = tube->GetReferenceCount(); if( tubeCount != 2 ) { std::cout<<"[FAILED]: Problem in Tube with incrementation of references count"<<std::endl; return EXIT_FAILURE; } } if( netCount != 1 ) { std::cout<<"[FAILED]: Problem in TubeNetwork initialization of references count"<<std::endl; return EXIT_FAILURE; } else { GroupPointer localNet = net; netCount = net->GetReferenceCount(); if( netCount != 2 ) { std::cout<<"[FAILED]: Problem in TubeNetwork with incrementation of references count"<<std::endl; return EXIT_FAILURE; } } tubeCount = tube->GetReferenceCount(); netCount = net->GetReferenceCount(); if( tubeCount != 1 ) { std::cout<<"[FAILED]: Problem in Tube with decrementation of references count"<<std::endl; return EXIT_FAILURE; } if( netCount != 1 ) { std::cout << "[FAILED]: Problem in TubeNetwork with decrementation of references count"<<std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; // Testing Set/GetParentPoint std::cout << "Set/GetParentPoint: "; tube->SetParentPoint(1); if(tube->GetParentPoint() !=1) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; // Testing ComputeTangentAndNormals(); std::cout << "ComputeTangentAndNormals: "; tube1->ComputeTangentAndNormals(); TubePointType::VectorType t = static_cast<const TubePointType*>(tube1->GetPoint(1))->GetTangent(); TubePointType::CovariantVectorType n1 = static_cast<const TubePointType*>(tube1->GetPoint(1))->GetNormal1(); TubePointType::CovariantVectorType n2 = static_cast<const TubePointType*>(tube1->GetPoint(1))->GetNormal2(); if( (vcl_fabs(t[0]-0.57735)>0.0001) || (vcl_fabs(t[1]-0.57735)>0.0001) || (vcl_fabs(t[2]-0.57735)>0.0001) || (vcl_fabs(n1[0]-0.0)>0.0001) || (vcl_fabs(n1[1]+0.57735)>0.0001) || (vcl_fabs(n1[2]-0.57735)>0.0001) || (vcl_fabs(n2[0]-0.666667)>0.0001) || (vcl_fabs(n2[1]+0.333333)>0.0001) || (vcl_fabs(n2[2]+0.333333)>0.0001) ) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; // Testing IsInside() with m_EndType set to 1 (rounded end-type); std::cout << "IsInside() with m_EndType=1: "; p1.Fill(19.5); if(tube1->IsInside(p1)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } tube1->SetEndType(1); if(!tube1->IsInside(p1)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; // For coverage only std::cout << "Testing PointBasedSO: "; typedef itk::PointBasedSpatialObject<3> PointBasedType; PointBasedType::Pointer pBSO = PointBasedType::New(); pBSO->GetPoint(0); pBSO->ComputeBoundingBox(); std::cout << "[PASSED]" << std::endl; std::cout << "[DONE]" << std::endl; return EXIT_SUCCESS; }
#include <deque> #include <mutex> #include <shared_mutex> #include "REFramework.hpp" #include "RETypeDB.hpp" #include "RETypeDefinition.hpp" namespace sdk { struct RETypeDefinition; sdk::REMethodDefinition* RETypeDefinition::MethodIterator::begin() const { if (m_parent->member_method == 0) { return nullptr; } auto tdb = RETypeDB::get(); return &(*tdb->methods)[m_parent->member_method]; } sdk::REMethodDefinition* RETypeDefinition::MethodIterator::end() const { if (m_parent->member_method == 0) { return nullptr; } auto tdb = RETypeDB::get(); #if TDB_VER >= 69 const auto& impl = (*tdb->typesImpl)[m_parent->impl_index]; const auto num_methods = impl.num_member_methods; #else const auto num_methods = m_parent->num_member_method; #endif return &(*tdb->methods)[m_parent->member_method + num_methods]; } size_t RETypeDefinition::MethodIterator::size() const { return ((uintptr_t)end() - (uintptr_t)begin()) / sizeof(sdk::REMethodDefinition); } sdk::REField* sdk::RETypeDefinition::FieldIterator::REFieldIterator::operator*() const { //#ifndef RE7 if (m_parent->member_field == 0) { return nullptr; } auto tdb = RETypeDB::get(); return &(*tdb->fields)[m_parent->member_field + m_index]; /*#else if (m_parent->member_field_start == 0) { return nullptr; } auto tdb = RETypeDB::get(); const auto field_indices = tdb->get_data<uint32_t>(m_parent->member_field_start); const auto index = field_indices[m_index]; if (index == 0) { return nullptr; } return &(*tdb->fields)[index]; #endif*/ } size_t sdk::RETypeDefinition::FieldIterator::size() const { #if TDB_VER >= 69 auto tdb = sdk::RETypeDB::get(); const auto& impl = (*tdb->typesImpl)[m_parent->impl_index]; const auto num_fields = impl.num_member_fields; #else const auto num_fields = m_parent->num_member_field; #endif return num_fields; } sdk::REProperty* RETypeDefinition::PropertyIterator::begin() const { if (m_parent->member_prop == 0) { return nullptr; } auto tdb = RETypeDB::get(); return &(*tdb->properties)[m_parent->member_prop]; } sdk::REProperty* RETypeDefinition::PropertyIterator::end() const { if (m_parent->member_prop == 0) { return nullptr; } auto tdb = RETypeDB::get(); const auto num_prop = m_parent->num_member_prop; return &(*tdb->properties)[m_parent->member_prop + num_prop]; } size_t RETypeDefinition::PropertyIterator::size() const { return ((uintptr_t)end() - (uintptr_t)begin()) / sizeof(sdk::REProperty); } const char* RETypeDefinition::get_namespace() const { auto tdb = RETypeDB::get(); #if TDB_VER >= 69 auto& impl = (*tdb->typesImpl)[this->impl_index]; const auto name_index = impl.namespace_offset; #else const auto name_index = this->namespace_offset; #endif return tdb->get_string(name_index); } const char* RETypeDefinition::get_name() const { auto tdb = RETypeDB::get(); #if TDB_VER >= 69 auto& impl = (*tdb->typesImpl)[this->impl_index]; const auto name_index = impl.name_offset; #else const auto name_index = this->name_offset; #endif return tdb->get_string(name_index); } // because who knows where this is going to be called from. static std::unordered_map<uint32_t, std::string> g_full_names{}; static std::shared_mutex g_full_name_mtx{}; std::string RETypeDefinition::get_full_name() const { auto tdb = RETypeDB::get(); #ifdef RE7 return tdb->get_string(this->full_name_offset); // uhh thanks? #else { std::shared_lock _{ g_full_name_mtx }; if (auto it = g_full_names.find(this->get_index()); it != g_full_names.end()) { return it->second; } } std::deque<std::string> names{}; std::string full_name{}; if (this->declaring_typeid > 0 && this->declaring_typeid != this->get_index()) { std::unordered_set<const sdk::RETypeDefinition*> seen_classes{}; for (auto owner = this; owner != nullptr; owner = owner->get_declaring_type()) { if (seen_classes.count(owner) > 0) { break; } names.push_front(owner->get_name()); if (owner->get_declaring_type() == nullptr && !std::string{owner->get_namespace()}.empty()) { names.push_front(owner->get_namespace()); } // uh. if (owner->get_declaring_type() == this) { break; } seen_classes.insert(owner); } } else { // namespace if (!std::string{this->get_namespace()}.empty()) { names.push_front(this->get_namespace()); } // actual class name names.push_back(this->get_name()); } for (auto f = 0; f < names.size(); ++f) { if (f > 0) { full_name += "."; } full_name += names[f]; } // Set this here at this point in-case get_full_name runs into it { std::unique_lock _{g_full_name_mtx}; g_full_names[this->get_index()] = full_name; } #ifndef RE7 if (this->generics > 0) { auto generics = tdb->get_data<sdk::GenericListData>(this->generics); if (generics->num > 0) { full_name += "<"; for (uint32_t f = 0; f < generics->num; ++f) { auto gtypeid = generics->types[f]; if (gtypeid > 0 && gtypeid < tdb->numTypes) { auto& generic_type = *tdb->get_type(gtypeid); full_name += generic_type.get_full_name(); } else { full_name += ""; } if (generics->num > 1 && f < generics->num - 1) { full_name += ","; } } full_name += ">"; } } #else //full_name += "<not implemented>"; #endif // For arrays if (full_name.empty()) { struct FakeRuntimeType : public ::REManagedObject { const sdk::RETypeDefinition* t{nullptr}; uint32_t unk{0}; }; FakeRuntimeType fake_type{}; fake_type.t = this; // because using normal find_type will loop back to this function and cause a deadlock static auto system_runtime_type = sdk::RETypeDB::get()->find_type_by_fqn(0x99ff88e6); static auto get_full_name_method = system_runtime_type->get_method("get_FullName"); auto full_name_obj = get_full_name_method->call<::SystemString*>(sdk::get_thread_context(), &fake_type); if (full_name_obj != nullptr) { full_name = utility::re_string::get_string(full_name_obj); // replace all instance of "+" with "." std::replace(full_name.begin(), full_name.end(), '+', '.'); } } { std::unique_lock _{g_full_name_mtx}; g_full_names[this->get_index()] = full_name; } return full_name; #endif } sdk::RETypeDefinition* RETypeDefinition::get_declaring_type() const { auto tdb = RETypeDB::get(); if (this->declaring_typeid == 0 || this->declaring_typeid >= tdb->numTypes) { return nullptr; } return tdb->get_type(this->declaring_typeid); } sdk::RETypeDefinition* RETypeDefinition::get_parent_type() const { auto tdb = RETypeDB::get(); if (this->parent_typeid == 0 || this->parent_typeid >= tdb->numTypes) { return nullptr; } return tdb->get_type(this->parent_typeid); } static std::shared_mutex g_underlying_mtx{}; static std::unordered_map<const sdk::RETypeDefinition*, sdk::RETypeDefinition*> g_underlying_types{}; sdk::RETypeDefinition* RETypeDefinition::get_underlying_type() const { { std::shared_lock _{ g_underlying_mtx }; if (auto it = g_underlying_types.find(this); it != g_underlying_types.end()) { return it->second; } } if (!this->is_enum()) { return nullptr; } #ifndef RE7 // get the underlying type of the enum // and then hash the name of the type instead static auto get_underlying_type_method = this->get_method("GetUnderlyingType"); const auto underlying_type = get_underlying_type_method->call<::REManagedObject*>(sdk::get_thread_context(), this->get_runtime_type()); if (underlying_type != nullptr) { static auto system_runtime_type_type = sdk::RETypeDB::get()->find_type("System.RuntimeType"); static auto get_name_method = system_runtime_type_type->get_method("get_FullName"); const auto full_name = get_name_method->call<::REManagedObject*>(sdk::get_thread_context(), underlying_type); if (full_name != nullptr) { const auto managed_str = (SystemString*)((uintptr_t)utility::re_managed_object::get_field_ptr(full_name) - sizeof(::REManagedObject)); const auto str = utility::narrow(managed_str->data); managed_str->referenceCount = 0; auto type_definition = sdk::RETypeDB::get()->find_type(str); std::unique_lock _{ g_underlying_mtx }; g_underlying_types[this] = type_definition; } } return g_underlying_types[this]; #else const auto value_field = this->get_field("value__"); if (value_field == nullptr) { g_underlying_types[this] = nullptr; return nullptr; } const auto underlying_type = value_field->get_type(); g_underlying_types[this] = underlying_type; return g_underlying_types[this]; #endif } static std::shared_mutex g_field_mtx{}; static std::unordered_map<std::string, sdk::REField*> g_field_map{}; sdk::REField* RETypeDefinition::get_field(std::string_view name) const { auto full_name = std::to_string(this->get_index()) + "." + name.data(); { std::shared_lock _{ g_field_mtx }; if (auto it = g_field_map.find(full_name); it != g_field_map.end()) { return it->second; } } for (auto super = this; super != nullptr; super = super->get_parent_type()) { for (auto f : super->get_fields()) { if (name == f->get_name()) { std::unique_lock _{ g_field_mtx }; g_field_map[full_name] = f; return g_field_map[full_name]; } } } return g_field_map[full_name]; } static std::shared_mutex g_method_mtx{}; static std::unordered_map<std::string, REMethodDefinition*> g_method_map{}; sdk::REMethodDefinition* RETypeDefinition::get_method(std::string_view name) const { // originally this used this->get_full_name() + "." + name.data() // but that doesn't work for generic types if we haven't yet mapped out // how generic (instantiated) types work for the game we're working with // and this is probably faster anyways auto full_name = std::to_string(this->get_index()) + "." + name.data(); { std::shared_lock _{g_method_mtx}; if (auto it = g_method_map.find(full_name); it != g_method_map.end()) { return it->second; } } // first pass, do not use function prototypes for (auto super = this; super != nullptr; super = super->get_parent_type()) { for (auto& m : super->get_methods()) { if (name == m.get_name()) { std::unique_lock _{g_method_mtx}; g_method_map[full_name] = &m; return g_method_map[full_name]; } } } // second pass, build a function prototype for (auto super = this; super != nullptr; super = super->get_parent_type()) { for (auto& m : super->get_methods()) { const auto method_param_types = m.get_param_types(); const auto method_param_names = m.get_param_names(); std::stringstream ss{}; ss << m.get_name() << "("; for (auto i = 0; i < method_param_types.size(); i++) { if (i > 0) { ss << ", "; } ss << method_param_types[i]->get_full_name(); } ss << ")"; const auto method_prototype = ss.str(); if (name == method_prototype) { std::unique_lock _{g_method_mtx}; g_method_map[full_name] = &m; return g_method_map[full_name]; } } } return g_method_map[full_name]; } std::vector<sdk::REMethodDefinition*> RETypeDefinition::get_methods(std::string_view name) const { std::vector<sdk::REMethodDefinition*> out{}; for (auto super = this; super != nullptr; super = super->get_parent_type()) { for (auto& m : super->get_methods()) { if (name == m.get_name()) { out.push_back(&m); } } } return out; } uint32_t RETypeDefinition::get_index() const { #ifndef RE7 return this->index; #else const auto tdb = RETypeDB::get(); return (uint32_t)(((uintptr_t)this - (uintptr_t)tdb->types) / sizeof(sdk::RETypeDefinition)); #endif } int32_t RETypeDefinition::get_fieldptr_offset() const { #ifndef RE7 if (this->managed_vt == nullptr) { return 0; } return *(int32_t*)((uintptr_t)this->managed_vt - sizeof(void*)); #else auto vm = sdk::VM::get(); const auto& vm_type = vm->types[this->get_index()]; return vm_type.fieldptr_offset; #endif } bool RETypeDefinition::has_fieldptr_offset() const { #ifndef RE7 return this->managed_vt != nullptr; #else return true; #endif } bool RETypeDefinition::is_a(sdk::RETypeDefinition* other) const { if (other == nullptr) { return false; } for (auto super = this; super != nullptr; super = super->get_parent_type()) { if (super == other) { return true; } } return false; } bool RETypeDefinition::is_a(std::string_view other) const { return this->is_a(RETypeDB::get()->find_type(other)); } via::clr::VMObjType RETypeDefinition::get_vm_obj_type() const { return (via::clr::VMObjType)this->object_type; } void RETypeDefinition::set_vm_obj_type(via::clr::VMObjType type) { this->object_type = (uint8_t)type; } bool RETypeDefinition::is_value_type() const { return get_vm_obj_type() == via::clr::VMObjType::ValType; } bool RETypeDefinition::is_enum() const { static sdk::RETypeDefinition* enum_type = nullptr; if (enum_type == nullptr) { enum_type = RETypeDB::get()->find_type("System.Enum"); } if (!this->is_value_type()) { return false; } return this->is_a(enum_type); } static std::shared_mutex g_by_ref_mtx{}; static std::unordered_map<const RETypeDefinition*, bool> g_by_ref_map{}; bool RETypeDefinition::is_by_ref() const { { std::shared_lock _{g_by_ref_mtx}; if (auto it = g_by_ref_map.find(this); it != g_by_ref_map.end()) { return it->second; } } std::unique_lock _{g_by_ref_mtx}; auto runtime_type = this->get_runtime_type(); if (runtime_type == nullptr) { g_by_ref_map[this] = true; return true; } auto runtime_typedef = utility::re_managed_object::get_type_definition(runtime_type); if (runtime_typedef == nullptr) { g_by_ref_map[this] = true; return true; } static auto by_ref_method = runtime_typedef->get_method("get_IsByRef"); g_by_ref_map[this] = by_ref_method->call<bool>(sdk::get_thread_context(), runtime_type); return g_by_ref_map[this]; } static std::shared_mutex g_pointer_mtx{}; static std::unordered_map<const RETypeDefinition*, bool> g_pointer_map{}; bool RETypeDefinition::is_pointer() const { { std::shared_lock _{g_pointer_mtx}; if (auto it = g_pointer_map.find(this); it != g_pointer_map.end()) { return it->second; } } std::unique_lock _{g_pointer_mtx}; auto runtime_type = this->get_runtime_type(); if (runtime_type == nullptr) { g_pointer_map[this] = false; return false; } auto runtime_typedef = utility::re_managed_object::get_type_definition(runtime_type); if (runtime_typedef == nullptr) { g_pointer_map[this] = false; return false; } static auto pointer_method = runtime_typedef->get_method("get_IsPointer"); g_pointer_map[this] = pointer_method->call<bool>(sdk::get_thread_context(), runtime_type); return g_pointer_map[this]; } static std::shared_mutex g_primitive_mtx{}; static std::unordered_map<const RETypeDefinition*, bool> g_primitive_map{}; bool RETypeDefinition::is_primitive() const { { std::shared_lock _{g_primitive_mtx}; if (auto it = g_primitive_map.find(this); it != g_primitive_map.end()) { return it->second; } } #ifndef RE7 std::unique_lock _{g_primitive_mtx}; auto runtime_type = this->get_runtime_type(); if (runtime_type == nullptr) { g_primitive_map[this] = false; return false; } auto runtime_typedef = utility::re_managed_object::get_type_definition(runtime_type); if (runtime_typedef == nullptr) { g_primitive_map[this] = false; return false; } static auto primitive_method = runtime_typedef->get_method("get_IsPrimitive"); g_primitive_map[this] = primitive_method->call<bool>(sdk::get_thread_context(), runtime_type); return g_primitive_map[this]; #else // RE7 is missing get_IsPrimitive and System.RuntimeType const auto full_name_hash = utility::hash(this->get_full_name()); switch (full_name_hash) { case "System.Boolean"_fnv:[[fallthrough]]; case "System.Char"_fnv:[[fallthrough]]; case "System.SByte"_fnv:[[fallthrough]]; case "System.Byte"_fnv:[[fallthrough]]; case "System.Int16"_fnv:[[fallthrough]]; case "System.UInt16"_fnv:[[fallthrough]]; case "System.Int32"_fnv:[[fallthrough]]; case "System.UInt32"_fnv:[[fallthrough]]; case "System.Int64"_fnv:[[fallthrough]]; case "System.UInt64"_fnv:[[fallthrough]]; case "System.Single"_fnv:[[fallthrough]]; case "System.Double"_fnv:[[fallthrough]]; case "System.Void"_fnv:[[fallthrough]]; case "System.IntPtr"_fnv:[[fallthrough]]; case "System.UIntPtr"_fnv: g_primitive_map[this] = true; return true; default: g_primitive_map[this] = false; return false; } return false; #endif } uint32_t RETypeDefinition::get_crc_hash() const { #ifndef RE7 const auto t = get_type(); return t != nullptr ? t->typeCRC : this->type_crc; #else const auto t = (regenny::via::typeinfo::TypeInfo*)get_type(); if (t == nullptr) { return 0; } return t->crc; #endif } uint32_t RETypeDefinition::get_fqn_hash() const { return this->fqn_hash; } uint32_t RETypeDefinition::get_size() const { #ifndef RE7 return this->size; #else auto t = (regenny::via::typeinfo::TypeInfo*)get_type(); if (t == nullptr) { return 0; } return t->size; #endif } uint32_t RETypeDefinition::get_valuetype_size() const { #if TDB_VER >= 69 auto tdb = RETypeDB::get(); auto impl_id = this->impl_index; if (impl_id == 0) { return 0; } return (*tdb->typesImpl)[impl_id].field_size; #else return ((REClassInfo*)this)->elementSize; #endif } ::REType* RETypeDefinition::get_type() const { #ifndef RE7 return this->type; #else auto vm = sdk::VM::get(); const auto& vm_type = vm->types[this->get_index()]; return (::REType*)vm_type.reflection_type; #endif } static std::unordered_map<const sdk::RETypeDefinition*, ::REManagedObject*> g_runtime_type_map{}; static std::shared_mutex g_runtime_type_mtx{}; ::REManagedObject* RETypeDefinition::get_runtime_type() const { { std::shared_lock _{g_runtime_type_mtx}; if (auto it = g_runtime_type_map.find(this); it != g_runtime_type_map.end()) { return it->second; } } #ifndef RE7 static auto appdomain_type = sdk::RETypeDB::get()->find_type("System.AppDomain"); static auto assembly_type = sdk::RETypeDB::get()->find_type("System.Reflection.Assembly"); static auto get_current_domain_func = appdomain_type->get_method("get_CurrentDomain"); static auto get_assemblies_func = appdomain_type->get_method("GetAssemblies"); static auto get_assembly_type_func = assembly_type->get_method("GetType(System.String)"); auto context = sdk::get_thread_context(); auto current_domain = get_current_domain_func->call<REManagedObject*>(context, nullptr); if (current_domain == nullptr) { return nullptr; } auto assemblies = get_assemblies_func->call<sdk::SystemArray*>(context, current_domain); if (assemblies == nullptr) { return nullptr; } const auto assembly_count = assemblies->size(); const auto managed_string = sdk::VM::create_managed_string(utility::widen(this->get_full_name())); for (auto i = 0; i < assembly_count; ++i) { auto assembly = (REManagedObject*)assemblies->get_element(i); if (assembly == nullptr) { continue; } if (get_assembly_type_func != nullptr) { auto type = get_assembly_type_func->call<REManagedObject*>(context, assembly, managed_string); if (type != nullptr) { std::unique_lock _{g_runtime_type_mtx}; g_runtime_type_map[this] = type; return type; } } else { // RE7 static auto get_types_method = assembly_type->get_method("GetTypes"); if (get_types_method != nullptr) { auto types = get_types_method->call<sdk::SystemArray*>(context, assembly); if (types != nullptr) { const auto type_count = types->size(); for (auto j = 0; j < type_count; ++j) { auto type = (REManagedObject*)types->get_element(j); if (type == nullptr) { continue; } auto type_t = utility::re_managed_object::get_type_definition(type); if (type_t == nullptr) { continue; } static auto get_namespace_method = type_t->get_method("get_Namespace"); static auto get_name_method = type_t->get_method("get_Name"); auto ns = get_namespace_method->call<SystemString*>(context, type); auto name = get_name_method->call<SystemString*>(context, type); if (ns == nullptr || name == nullptr) { continue; } const auto full_name = utility::narrow(ns->data) + "." + utility::narrow(name->data); if (full_name == this->get_full_name()) { std::unique_lock _{g_runtime_type_mtx}; g_runtime_type_map[this] = type; return type; } } } } } } #else auto vm = sdk::VM::get(); if (vm == nullptr) { return nullptr; } const auto& vm_type = vm->types[this->get_index()]; g_runtime_type_map[this] = (::REManagedObject*)vm_type.runtime_type; return g_runtime_type_map[this]; #endif return g_runtime_type_map[this]; } void* RETypeDefinition::get_instance() const { const auto t = get_type(); if (t == nullptr) { return nullptr; } return utility::re_type::get_singleton_instance(t); } void* RETypeDefinition::create_instance() const { const auto t = get_type(); if (t == nullptr) { return nullptr; } return utility::re_type::create_instance(t); } ::REManagedObject* RETypeDefinition::create_instance_full(bool simplify) { static auto system_activator_type = sdk::RETypeDB::get()->find_type("System.Activator"); static auto create_instance_func = system_activator_type->get_method("CreateInstance(System.Type)"); static auto create_instance_alternative_func = system_activator_type->get_method("createInstance(System.Type)"); const auto typeof = this->get_runtime_type(); if (typeof == nullptr) { return nullptr; } if (simplify) { // forces the game to use a simplified path for creating the object // because in some cases this function could fail const auto old_obj_type = this->get_vm_obj_type(); set_vm_obj_type(via::clr::VMObjType::ValType); auto result = create_instance_alternative_func->call<REManagedObject*>(sdk::get_thread_context(), typeof); set_vm_obj_type(old_obj_type); return result; } else { return create_instance_func->call<REManagedObject*>(sdk::get_thread_context(), typeof); } } bool RETypeDefinition::should_pass_by_pointer() const { return !is_value_type() || (get_valuetype_size() > sizeof(void*) || (!is_primitive() && !is_enum())); } } // namespace sdk
#include "optionsdialog.h" #include "ui_optionsdialog.h" #include "fucoinunits.h" #include "monitoreddatamapper.h" #include "netbase.h" #include "optionsmodel.h" #include <QDir> #include <QIntValidator> #include <QLocale> #include <QMessageBox> #include <QRegExp> #include <QRegExpValidator> OptionsDialog::OptionsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::OptionsDialog), model(0), mapper(0), fRestartWarningDisplayed_Proxy(false), fRestartWarningDisplayed_Lang(false), fProxyIpValid(true) { ui->setupUi(this); /* Network elements init */ #ifndef USE_UPNP ui->mapPortUpnp->setEnabled(false); #endif ui->proxyIp->setEnabled(false); ui->proxyPort->setEnabled(false); ui->proxyPort->setValidator(new QIntValidator(1, 65535, this)); ui->socksVersion->setEnabled(false); ui->socksVersion->addItem("5", 5); ui->socksVersion->addItem("4", 4); ui->socksVersion->setCurrentIndex(0); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy())); ui->proxyIp->installEventFilter(this); /* Window elements init */ #ifdef Q_OS_MAC ui->tabWindow->setVisible(false); #endif /* Display elements init */ QDir translations(":translations"); ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant("")); foreach(const QString &langStr, translations.entryList()) { QLocale locale(langStr); /** check if the locale name consists of 2 parts (language_country) */ if(langStr.contains("_")) { #if QT_VERSION >= 0x040800 /** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } else { #if QT_VERSION >= 0x040800 /** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language (locale name)", e.g. "German (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } } ui->unit->setModel(new BitcoinUnits(this)); /* Widget-to-option mapper */ mapper = new MonitoredDataMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setOrientation(Qt::Vertical); /* enable apply button when data modified */ connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton())); /* disable apply button when new data loaded */ connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton())); /* setup/change UI elements when proxy IP is invalid/valid */ connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool))); } OptionsDialog::~OptionsDialog() { delete ui; } void OptionsDialog::setModel(OptionsModel *model) { this->model = model; if(model) { connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); mapper->setModel(model); setMapper(); mapper->toFirst(); } /* update the display unit, to not use the default ("BTC") */ updateDisplayUnit(); /* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */ connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang())); /* disable apply button after settings are loaded as there is nothing to save */ disableApplyButton(); } void OptionsDialog::setMapper() { /* Main */ mapper->addMapping(ui->transactionFee, OptionsModel::Fee); mapper->addMapping(ui->fucoinAtStartup, OptionsModel::StartAtStartup); mapper->addMapping(ui->detachDatabases, OptionsModel::DetachDatabases); /* Network */ mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP); mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse); mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP); mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort); mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion); /* Window */ #ifndef Q_OS_MAC mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray); mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose); #endif /* Display */ mapper->addMapping(ui->lang, OptionsModel::Language); mapper->addMapping(ui->unit, OptionsModel::DisplayUnit); mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses); } void OptionsDialog::enableApplyButton() { ui->applyButton->setEnabled(true); } void OptionsDialog::disableApplyButton() { ui->applyButton->setEnabled(false); } void OptionsDialog::enableSaveButtons() { /* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */ if(fProxyIpValid) setSaveButtonState(true); } void OptionsDialog::disableSaveButtons() { setSaveButtonState(false); } void OptionsDialog::setSaveButtonState(bool fState) { ui->applyButton->setEnabled(fState); ui->okButton->setEnabled(fState); } void OptionsDialog::on_okButton_clicked() { mapper->submit(); accept(); } void OptionsDialog::on_cancelButton_clicked() { reject(); } void OptionsDialog::on_applyButton_clicked() { mapper->submit(); disableApplyButton(); } void OptionsDialog::showRestartWarning_Proxy() { if(!fRestartWarningDisplayed_Proxy) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting fucoin."), QMessageBox::Ok); fRestartWarningDisplayed_Proxy = true; } } void OptionsDialog::showRestartWarning_Lang() { if(!fRestartWarningDisplayed_Lang) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting fucoin."), QMessageBox::Ok); fRestartWarningDisplayed_Lang = true; } } void OptionsDialog::updateDisplayUnit() { if(model) { /* Update transactionFee with the current unit */ ui->transactionFee->setDisplayUnit(model->getDisplayUnit()); } } void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState) { // this is used in a check before re-enabling the save buttons fProxyIpValid = fState; if(fProxyIpValid) { enableSaveButtons(); ui->statusLabel->clear(); } else { disableSaveButtons(); object->setValid(fProxyIpValid); ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied proxy address is invalid.")); } } bool OptionsDialog::eventFilter(QObject *object, QEvent *event) { if(event->type() == QEvent::FocusOut) { if(object == ui->proxyIp) { CService addr; /* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */ emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr)); } } return QDialog::eventFilter(object, event); }
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. // #include "HotPatcherPrivatePCH.h" #include "CreatePatch/SHotPatcherExportPatch.h" #include "CreatePatch/FExportPatchSettings.h" #include "CreatePatch/PatcherProxy.h" #include "CreatePatch/ScopedSlowTaskContext.h" #include "FlibHotPatcherEditorHelper.h" #include "FlibPatchParserHelper.h" #include "FHotPatcherVersion.h" #include "FLibAssetManageHelperEx.h" #include "FPakFileInfo.h" #include "ThreadUtils/FThreadUtils.hpp" #include "HotPatcherLog.h" #include "HotPatcherEditor.h" // engine header #include "Misc/FileHelper.h" #include "Widgets/Input/SHyperlink.h" #include "Widgets/Layout/SSeparator.h" #include "Widgets/Text/SMultiLineEditableText.h" #include "Kismet/KismetStringLibrary.h" #include "Kismet/KismetSystemLibrary.h" #include "Misc/SecureHash.h" #include "HAL/FileManager.h" #include "PakFileUtilities.h" #include "Kismet/KismetTextLibrary.h" #define LOCTEXT_NAMESPACE "SHotPatcherCreatePatch" void SHotPatcherExportPatch::Construct(const FArguments& InArgs, TSharedPtr<FHotPatcherCreatePatchModel> InCreatePatchModel) { ExportPatchSetting = MakeShareable(new FExportPatchSettings); GPatchSettings = ExportPatchSetting.Get(); CreateExportFilterListView(); mCreatePatchModel = InCreatePatchModel; ChildSlot [ SNew(SVerticalBox) + SVerticalBox::Slot() .AutoHeight() .Padding(FEditorStyle::GetMargin("StandardDialog.ContentPadding")) [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .VAlign(VAlign_Center) [ SettingsView->GetWidget()->AsShared() ] ] + SVerticalBox::Slot() .AutoHeight() .HAlign(HAlign_Right) .Padding(4, 4, 10, 4) [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .HAlign(HAlign_Right) .AutoWidth() .Padding(0, 0, 4, 0) [ SNew(SButton) .Text(LOCTEXT("AddToPreset", "AddToPreset")) .OnClicked(this, &SHotPatcherExportPatch::DoAddToPreset) ] + SHorizontalBox::Slot() .HAlign(HAlign_Right) .AutoWidth() .Padding(0, 0, 4, 0) [ SNew(SButton) .Text(LOCTEXT("PreviewChunk", "PreviewChunk")) .IsEnabled(this, &SHotPatcherExportPatch::CanPreviewChunk) .OnClicked(this, &SHotPatcherExportPatch::DoPreviewChunk) .Visibility(this, &SHotPatcherExportPatch::VisibilityPreviewChunkButtons) ] + SHorizontalBox::Slot() .HAlign(HAlign_Right) .AutoWidth() .Padding(0, 0, 4, 0) [ SNew(SButton) .Text(LOCTEXT("Diff", "Diff")) .IsEnabled(this, &SHotPatcherExportPatch::CanDiff) .OnClicked(this, &SHotPatcherExportPatch::DoDiff) .Visibility(this, &SHotPatcherExportPatch::VisibilityDiffButtons) ] + SHorizontalBox::Slot() .HAlign(HAlign_Right) .AutoWidth() .Padding(0, 0, 4, 0) [ SNew(SButton) .Text(LOCTEXT("ClearDiff", "ClearDiff")) .IsEnabled(this, &SHotPatcherExportPatch::CanDiff) .OnClicked(this, &SHotPatcherExportPatch::DoClearDiff) .Visibility(this, &SHotPatcherExportPatch::VisibilityDiffButtons) ] + SHorizontalBox::Slot() .HAlign(HAlign_Right) .AutoWidth() .Padding(0, 0, 4, 0) [ SNew(SButton) .Text(LOCTEXT("PreviewPatch", "PreviewPatch")) .IsEnabled(this, &SHotPatcherExportPatch::CanPreviewPatch) .OnClicked(this, &SHotPatcherExportPatch::DoPreviewPatch) .ToolTipText(this,&SHotPatcherExportPatch::GetGenerateTooltipText) ] + SHorizontalBox::Slot() .HAlign(HAlign_Right) .AutoWidth() .Padding(0, 0, 4, 0) [ SNew(SButton) .Text(LOCTEXT("GeneratePatch", "GeneratePatch")) .ToolTipText(this,&SHotPatcherExportPatch::GetGenerateTooltipText) .IsEnabled(this, &SHotPatcherExportPatch::CanExportPatch) .OnClicked(this, &SHotPatcherExportPatch::DoExportPatch) ] ] + SVerticalBox::Slot() .AutoHeight() .HAlign(HAlign_Fill) .VAlign(VAlign_Fill) .Padding(4, 4, 10, 4) [ SAssignNew(DiffWidget, SHotPatcherInformations) .Visibility(EVisibility::Collapsed) ] ]; } void SHotPatcherExportPatch::ImportConfig() { UE_LOG(LogHotPatcher, Log, TEXT("Patch Import Config")); TArray<FString> Files = this->OpenFileDialog(); if (!Files.Num()) return; FString LoadFile = Files[0]; FString JsonContent; if (UFLibAssetManageHelperEx::LoadFileToString(LoadFile, JsonContent)) { UFlibPatchParserHelper::TDeserializeJsonStringAsStruct(JsonContent,*ExportPatchSetting); SettingsView->GetDetailsView()->ForceRefresh(); } } void SHotPatcherExportPatch::ExportConfig()const { UE_LOG(LogHotPatcher, Log, TEXT("Patch Export Config")); TArray<FString> Files = this->SaveFileDialog(); if (!Files.Num()) return; FString SaveToFile = Files[0].EndsWith(TEXT(".json")) ? Files[0] : Files[0].Append(TEXT(".json")); if (ExportPatchSetting) { if (ExportPatchSetting->IsSaveConfig()) { FString SerializedJsonStr; UFlibPatchParserHelper::TSerializeStructAsJsonString(*ExportPatchSetting,SerializedJsonStr); if (FFileHelper::SaveStringToFile(SerializedJsonStr, *SaveToFile)) { FText Msg = LOCTEXT("SavedPatchConfigMas", "Successd to Export the Patch Config."); UFlibHotPatcherEditorHelper::CreateSaveFileNotify(Msg, SaveToFile); } } } } void SHotPatcherExportPatch::ResetConfig() { UE_LOG(LogHotPatcher, Log, TEXT("Patch Clear Config")); FString DefaultSettingJson; UFlibPatchParserHelper::TSerializeStructAsJsonString(*FExportPatchSettings::Get(),DefaultSettingJson); UFlibPatchParserHelper::TDeserializeJsonStringAsStruct(DefaultSettingJson,*ExportPatchSetting); SettingsView->GetDetailsView()->ForceRefresh(); } void SHotPatcherExportPatch::DoGenerate() { DoExportPatch(); } bool SHotPatcherExportPatch::InformationContentIsVisibility() const { return DiffWidget->GetVisibility() == EVisibility::Visible; } void SHotPatcherExportPatch::SetInformationContent(const FString& InContent)const { DiffWidget->SetContent(InContent); } void SHotPatcherExportPatch::SetInfomationContentVisibility(EVisibility InVisibility)const { DiffWidget->SetVisibility(InVisibility); } void SHotPatcherExportPatch::ImportProjectConfig() { SHotPatcherPatchableBase::ImportProjectConfig(); bool bUseIoStore = false; bool bAllowBulkDataInIoStore = false; GConfig->GetBool(TEXT("/Script/UnrealEd.ProjectPackagingSettings"),TEXT("bUseIoStore"),bUseIoStore,GGameIni); GConfig->GetBool(TEXT("Core.System"),TEXT("AllowBulkDataInIoStore"),bAllowBulkDataInIoStore,GEngineIni); GetConfigSettings()->IoStoreSettings.bIoStore = bUseIoStore; GetConfigSettings()->IoStoreSettings.bAllowBulkDataInIoStore = bAllowBulkDataInIoStore; #if ENGINE_MAJOR_VERSION > 4 bool bMakeBinaryConfig = false; GConfig->GetBool(TEXT("/Script/UnrealEd.ProjectPackagingSettings"),TEXT("bMakeBinaryConfig"),bMakeBinaryConfig,GEngineIni); GetConfigSettings()->bMakeBinaryConfig = bMakeBinaryConfig; #endif FString PakFileCompressionFormats; GConfig->GetString(TEXT("/Script/UnrealEd.ProjectPackagingSettings"),TEXT("PakFileCompressionFormats"),PakFileCompressionFormats,GGameIni); if(!PakFileCompressionFormats.IsEmpty()) { PakFileCompressionFormats = FString::Printf(TEXT("-compressionformats=%s"),*PakFileCompressionFormats); GetConfigSettings()->DefaultCommandletOptions.AddUnique(PakFileCompressionFormats); } FString PakFileAdditionalCompressionOptions; GConfig->GetString(TEXT("/Script/UnrealEd.ProjectPackagingSettings"),TEXT("PakFileAdditionalCompressionOptions"),PakFileAdditionalCompressionOptions,GGameIni); if(!PakFileAdditionalCompressionOptions.IsEmpty()) GetConfigSettings()->DefaultCommandletOptions.AddUnique(PakFileAdditionalCompressionOptions); } void SHotPatcherExportPatch::ShowMsg(const FString& InMsg)const { auto ErrorMsgShowLambda = [this](const FString& InErrorMsg)->bool { bool bHasError = false; if (!InErrorMsg.IsEmpty()) { this->SetInformationContent(InErrorMsg); this->SetInfomationContentVisibility(EVisibility::Visible); bHasError = true; } else { if (this->InformationContentIsVisibility()) { this->SetInformationContent(TEXT("")); this->SetInfomationContentVisibility(EVisibility::Collapsed); } } return bHasError; }; ErrorMsgShowLambda(InMsg); } bool SHotPatcherExportPatch::CanDiff()const { bool bCanDiff = false; if (ExportPatchSetting) { bool bHasBase = !ExportPatchSetting->GetBaseVersion().IsEmpty() && FPaths::FileExists(ExportPatchSetting->GetBaseVersion()); bool bHasVersionId = !ExportPatchSetting->GetVersionId().IsEmpty(); bool bHasFilter = !!ExportPatchSetting->GetAssetIncludeFiltersPaths().Num(); bool bHasSpecifyAssets = !!ExportPatchSetting->GetIncludeSpecifyAssets().Num(); bCanDiff = bHasBase && bHasVersionId && (bHasFilter || bHasSpecifyAssets); } return bCanDiff; } FReply SHotPatcherExportPatch::DoDiff()const { FString BaseVersionContent; FHotPatcherVersion BaseVersion; bool bDeserializeStatus = false; if (ExportPatchSetting->IsByBaseVersion()) { if (UFLibAssetManageHelperEx::LoadFileToString(ExportPatchSetting->GetBaseVersion(), BaseVersionContent)) { bDeserializeStatus = UFlibPatchParserHelper::TDeserializeJsonStringAsStruct(BaseVersionContent, BaseVersion); } if (!bDeserializeStatus) { UE_LOG(LogHotPatcher, Error, TEXT("Deserialize Base Version Faild!")); return FReply::Handled(); } } ExportPatchSetting->Init(); FHotPatcherVersion CurrentVersion = UFlibPatchParserHelper::ExportReleaseVersionInfo( ExportPatchSetting->GetVersionId(), BaseVersion.VersionId, FDateTime::UtcNow().ToString(), ExportPatchSetting->GetAssetIncludeFiltersPaths(), ExportPatchSetting->GetAssetIgnoreFiltersPaths(), ExportPatchSetting->GetAssetRegistryDependencyTypes(), ExportPatchSetting->GetIncludeSpecifyAssets(), ExportPatchSetting->GetAddExternAssetsToPlatform(), ExportPatchSetting->GetAssetsDependenciesScanedCaches(), ExportPatchSetting->IsIncludeHasRefAssetsOnly() ); FPatchVersionDiff VersionDiffInfo = UFlibPatchParserHelper::DiffPatchVersionWithPatchSetting(*ExportPatchSetting, BaseVersion, CurrentVersion); bool bShowDeleteAsset = false; FString SerializeDiffInfo; UFlibPatchParserHelper::TSerializeStructAsJsonString(VersionDiffInfo,SerializeDiffInfo); SetInformationContent(SerializeDiffInfo); SetInfomationContentVisibility(EVisibility::Visible); return FReply::Handled(); } FReply SHotPatcherExportPatch::DoClearDiff()const { SetInformationContent(TEXT("")); SetInfomationContentVisibility(EVisibility::Collapsed); return FReply::Handled(); } EVisibility SHotPatcherExportPatch::VisibilityDiffButtons() const { bool bHasBase = false; if (ExportPatchSetting && ExportPatchSetting->IsByBaseVersion()) { FString BaseVersionFile = ExportPatchSetting->GetBaseVersion(); bHasBase = !BaseVersionFile.IsEmpty() && FPaths::FileExists(BaseVersionFile); } if (bHasBase && CanExportPatch()) { return EVisibility::Visible; } else { return EVisibility::Collapsed; } } FReply SHotPatcherExportPatch::DoPreviewChunk() const { FHotPatcherVersion BaseVersion; if (ExportPatchSetting->IsByBaseVersion() && !ExportPatchSetting->GetBaseVersionInfo(BaseVersion)) { UE_LOG(LogHotPatcher, Error, TEXT("Deserialize Base Version Faild!")); return FReply::Handled(); } else { // 在不进行外部文件diff的情况下清理掉基础版本的外部文件 if (!ExportPatchSetting->IsEnableExternFilesDiff()) { BaseVersion.PlatformAssets.Empty(); } } ExportPatchSetting->Init(); UFLibAssetManageHelperEx::UpdateAssetMangerDatabase(true); FChunkInfo NewVersionChunk = UFlibHotPatcherEditorHelper::MakeChunkFromPatchSettings(ExportPatchSetting.Get()); FHotPatcherVersion CurrentVersion = UFlibPatchParserHelper::ExportReleaseVersionInfoByChunk( ExportPatchSetting->GetVersionId(), BaseVersion.VersionId, FDateTime::UtcNow().ToString(), NewVersionChunk, ExportPatchSetting->GetAssetsDependenciesScanedCaches(), ExportPatchSetting->IsIncludeHasRefAssetsOnly() ); FString CurrentVersionSavePath = ExportPatchSetting->GetCurrentVersionSavePath(); FPatchVersionDiff VersionDiffInfo = UFlibPatchParserHelper::DiffPatchVersionWithPatchSetting(*ExportPatchSetting, BaseVersion, CurrentVersion); TArray<FChunkInfo> PatchChunks = ExportPatchSetting->GetChunkInfos(); // create default chunk if(ExportPatchSetting->IsCreateDefaultChunk()) { FChunkInfo TotalChunk = UFlibPatchParserHelper::CombineChunkInfos(ExportPatchSetting->GetChunkInfos()); FChunkAssetDescribe ChunkDiffInfo = UFlibPatchParserHelper::DiffChunkWithPatchSetting( *ExportPatchSetting, NewVersionChunk, TotalChunk, ExportPatchSetting->GetAssetsDependenciesScanedCaches() ); if(ChunkDiffInfo.HasValidAssets()) { PatchChunks.Add(ChunkDiffInfo.AsChunkInfo(TEXT("Default"))); } } FString ShowMsg; for (const auto& Chunk : PatchChunks) { FChunkAssetDescribe ChunkAssetsDescrible = UFlibPatchParserHelper::CollectFChunkAssetsDescribeByChunk(VersionDiffInfo, Chunk,ExportPatchSetting->GetPakTargetPlatforms(),ExportPatchSetting->GetAssetsDependenciesScanedCaches()); ShowMsg.Append(FString::Printf(TEXT("Chunk:%s\n"), *Chunk.ChunkName)); auto AppendFilesToMsg = [&ShowMsg](const FString& CategoryName, const TArray<FString>& InFiles) { if (!!InFiles.Num()) { ShowMsg.Append(FString::Printf(TEXT("%s:\n"), *CategoryName)); for (const auto& File : InFiles) { ShowMsg.Append(FString::Printf(TEXT("\t%s\n"), *File)); } } }; AppendFilesToMsg(TEXT("UE Assets"), ChunkAssetsDescrible.GetAssetsStrings()); for(auto Platform:ExportPatchSetting->GetPakTargetPlatforms()) { TArray<FString> PlatformExFiles; FString PlatformName = UFlibPatchParserHelper::GetEnumNameByValue(Platform,false); PlatformExFiles.Append(ChunkAssetsDescrible.GetExFileStrings(Platform)); AppendFilesToMsg(PlatformName, PlatformExFiles); } AppendFilesToMsg(TEXT("Internal Files"), ChunkAssetsDescrible.GetInternalFileStrings()); ShowMsg.Append(TEXT("\n")); } if (!ShowMsg.IsEmpty()) { this->ShowMsg(ShowMsg); } return FReply::Handled(); } bool SHotPatcherExportPatch::CanPreviewChunk() const { return ExportPatchSetting->IsEnableChunk(); } EVisibility SHotPatcherExportPatch::VisibilityPreviewChunkButtons() const { if (CanPreviewChunk()) { return EVisibility::Visible; } else { return EVisibility::Collapsed; } } bool SHotPatcherExportPatch::CanExportPatch()const { bool bCanExport = false; if (ExportPatchSetting) { bool bHasBase = false; if (ExportPatchSetting->IsByBaseVersion()) bHasBase = !ExportPatchSetting->GetBaseVersion().IsEmpty() && FPaths::FileExists(ExportPatchSetting->GetBaseVersion()); else bHasBase = true; bool bHasVersionId = !ExportPatchSetting->GetVersionId().IsEmpty(); bool bHasFilter = !!ExportPatchSetting->GetAssetIncludeFiltersPaths().Num(); bool bHasSpecifyAssets = !!ExportPatchSetting->GetIncludeSpecifyAssets().Num(); // bool bHasExternFiles = !!ExportPatchSetting->GetAddExternFiles().Num(); // bool bHasExDirs = !!ExportPatchSetting->GetAddExternDirectory().Num(); bool bHasExternFiles = !!ExportPatchSetting->GetAllPlatfotmExternFiles().Num(); bool bHasExDirs = !!ExportPatchSetting->GetAddExternAssetsToPlatform().Num(); bool bHasSavePath = !ExportPatchSetting->GetSaveAbsPath().IsEmpty(); bool bHasPakPlatfotm = !!ExportPatchSetting->GetPakTargetPlatforms().Num(); bool bHasAnyPakFiles = ( bHasFilter || bHasSpecifyAssets || bHasExternFiles || bHasExDirs || ExportPatchSetting->IsIncludeEngineIni() || ExportPatchSetting->IsIncludePluginIni() || ExportPatchSetting->IsIncludeProjectIni() ); bCanExport = bHasBase && bHasVersionId && bHasAnyPakFiles && bHasPakPlatfotm && bHasSavePath; } return bCanExport; } FReply SHotPatcherExportPatch::DoExportPatch() { if(!GetConfigSettings()->IsStandaloneMode()) { UPatcherProxy* PatcherProxy = NewObject<UPatcherProxy>(); PatcherProxy->AddToRoot(); PatcherProxy->SetProxySettings(ExportPatchSetting.Get()); PatcherProxy->OnShowMsg.AddRaw(this,&SHotPatcherExportPatch::ShowMsg); PatcherProxy->DoExport(); } else { FString CurrentConfig; UFlibPatchParserHelper::TSerializeStructAsJsonString(*GetConfigSettings(),CurrentConfig); FString SaveConfigTo = FPaths::ConvertRelativePathToFull(FPaths::Combine(FPaths::ProjectSavedDir(),TEXT("HotPatcher"),TEXT("PatchConfig.json"))); FFileHelper::SaveStringToFile(CurrentConfig,*SaveConfigTo); FString MissionCommand = FString::Printf(TEXT("\"%s\" -run=HotPatcher -config=\"%s\" %s"),*UFlibPatchParserHelper::GetProjectFilePath(),*SaveConfigTo,*GetConfigSettings()->GetCombinedAdditionalCommandletArgs()); UE_LOG(LogHotPatcher,Log,TEXT("HotPatcher %s Mission: %s %s"),*GetMissionName(),*UFlibHotPatcherEditorHelper::GetUECmdBinary(),*MissionCommand); FHotPatcherEditorModule::Get().RunProcMission(UFlibHotPatcherEditorHelper::GetUECmdBinary(),MissionCommand,GetMissionName()); } return FReply::Handled(); } FText SHotPatcherExportPatch::GetGenerateTooltipText() const { FString FinalString; if (ExportPatchSetting) { bool bHasBase = false; if (ExportPatchSetting->IsByBaseVersion()) bHasBase = !ExportPatchSetting->GetBaseVersion().IsEmpty() && FPaths::FileExists(ExportPatchSetting->GetBaseVersion()); else bHasBase = true; bool bHasVersionId = !ExportPatchSetting->GetVersionId().IsEmpty(); bool bHasFilter = !!ExportPatchSetting->GetAssetIncludeFiltersPaths().Num(); bool bHasSpecifyAssets = !!ExportPatchSetting->GetIncludeSpecifyAssets().Num(); // bool bHasExternFiles = !!ExportPatchSetting->GetAddExternFiles().Num(); // bool bHasExDirs = !!ExportPatchSetting->GetAddExternDirectory().Num(); bool bHasExternFiles = !!ExportPatchSetting->GetAllPlatfotmExternFiles().Num(); bool bHasExDirs = !!ExportPatchSetting->GetAddExternAssetsToPlatform().Num(); bool bHasSavePath = !ExportPatchSetting->GetSaveAbsPath().IsEmpty(); bool bHasPakPlatfotm = !!ExportPatchSetting->GetPakTargetPlatforms().Num(); bool bHasAnyPakFiles = ( bHasFilter || bHasSpecifyAssets || bHasExternFiles || bHasExDirs || ExportPatchSetting->IsIncludeEngineIni() || ExportPatchSetting->IsIncludePluginIni() || ExportPatchSetting->IsIncludeProjectIni() ); struct FStatus { FStatus(bool InMatch,const FString& InDisplay):bMatch(InMatch) { Display = FString::Printf(TEXT("%s:%s"),*InDisplay,InMatch?TEXT("true"):TEXT("false")); } FString GetDisplay()const{return Display;} bool bMatch; FString Display; }; TArray<FStatus> AllStatus; AllStatus.Emplace(bHasBase,TEXT("BaseVersion")); AllStatus.Emplace(bHasVersionId,TEXT("HasVersionId")); AllStatus.Emplace(bHasAnyPakFiles,TEXT("HasAnyPakFiles")); AllStatus.Emplace(bHasPakPlatfotm,TEXT("HasPakPlatfotm")); AllStatus.Emplace(bHasSavePath,TEXT("HasSavePath")); for(const auto& Status:AllStatus) { FinalString+=FString::Printf(TEXT("%s\n"),*Status.GetDisplay()); } } return UKismetTextLibrary::Conv_StringToText(FinalString); } bool SHotPatcherExportPatch::CanPreviewPatch() const { bool bHasFilter = !!ExportPatchSetting->GetAssetIncludeFiltersPaths().Num(); bool bHasSpecifyAssets = !!ExportPatchSetting->GetIncludeSpecifyAssets().Num(); auto HasExFilesLambda = [this]() { bool result = false; const TMap<ETargetPlatform,FPlatformExternFiles>& ExFiles = ExportPatchSetting->GetAllPlatfotmExternFiles(false); if(!!ExFiles.Num()) { TArray<ETargetPlatform> Platforms; ExFiles.GetKeys(Platforms); for(const auto& Platform:Platforms) { if(!!ExFiles.Find(Platform)->ExternFiles.Num()) { result=true; break; } } } return result; }; bool bHasExternFiles = HasExFilesLambda(); bool bHasAnyPakFiles = ( bHasFilter || bHasSpecifyAssets || bHasExternFiles || ExportPatchSetting->IsIncludeEngineIni() || ExportPatchSetting->IsIncludePluginIni() || ExportPatchSetting->IsIncludeProjectIni() ); return bHasFilter || bHasSpecifyAssets || bHasExternFiles || bHasAnyPakFiles; } FReply SHotPatcherExportPatch::DoPreviewPatch() { ExportPatchSetting->Init(); FChunkInfo DefaultChunk; FHotPatcherVersion BaseVersion; if (ExportPatchSetting->IsByBaseVersion()) { ExportPatchSetting->GetBaseVersionInfo(BaseVersion); DefaultChunk = UFlibHotPatcherEditorHelper::MakeChunkFromPatchVerison(BaseVersion); if (!ExportPatchSetting->IsEnableExternFilesDiff()) { BaseVersion.PlatformAssets.Empty(); } } FChunkInfo NewVersionChunk = UFlibHotPatcherEditorHelper::MakeChunkFromPatchSettings(ExportPatchSetting.Get()); FChunkAssetDescribe ChunkAssetsDescrible = UFlibPatchParserHelper::DiffChunkByBaseVersionWithPatchSetting(*ExportPatchSetting.Get(),NewVersionChunk, DefaultChunk, BaseVersion,ExportPatchSetting->GetAssetsDependenciesScanedCaches()); TArray<FString> AllUnselectedAssets = ChunkAssetsDescrible.GetAssetsStrings(); TArray<FString> UnSelectedInternalFiles = ChunkAssetsDescrible.GetInternalFileStrings(); FString TotalMsg; auto ChunkCheckerMsg = [&TotalMsg](const FString& Category, const TArray<FString>& InAssetList) { if (!!InAssetList.Num()) { TotalMsg.Append(FString::Printf(TEXT("\n%s:\n"), *Category)); for (const auto& Asset : InAssetList) { TotalMsg.Append(FString::Printf(TEXT("\t%s\n"), *Asset)); } } }; ChunkCheckerMsg(TEXT("Unreal Asset"), AllUnselectedAssets); ChunkCheckerMsg(TEXT("External Files"), TArray<FString>{}); for(auto Platform:ExportPatchSetting->GetPakTargetPlatforms()) { TArray<FString> PlatformExFiles; FString PlatformName = UFlibPatchParserHelper::GetEnumNameByValue(Platform,false); PlatformExFiles.Append(ChunkAssetsDescrible.GetExFileStrings(Platform)); PlatformExFiles.Append(ChunkAssetsDescrible.GetExFileStrings(ETargetPlatform::AllPlatforms)); ChunkCheckerMsg(PlatformName, PlatformExFiles); } ChunkCheckerMsg(TEXT("Internal Files"), UnSelectedInternalFiles); if (!TotalMsg.IsEmpty()) { ShowMsg(FString::Printf(TEXT("Patch Assets:\n%s"), *TotalMsg)); return FReply::Handled(); } return FReply::Handled(); } FReply SHotPatcherExportPatch::DoAddToPreset() const { UHotPatcherSettings* Settings = GetMutableDefault<UHotPatcherSettings>(); Settings->PresetConfigs.Add(*const_cast<SHotPatcherExportPatch*>(this)->GetConfigSettings()); Settings->SaveConfig(); return FReply::Handled(); } void SHotPatcherExportPatch::CreateExportFilterListView() { // Create a property view FPropertyEditorModule& EditModule = FModuleManager::Get().GetModuleChecked<FPropertyEditorModule>("PropertyEditor"); FDetailsViewArgs DetailsViewArgs; { DetailsViewArgs.bAllowSearch = true; DetailsViewArgs.bHideSelectionTip = true; DetailsViewArgs.bLockable = false; DetailsViewArgs.bSearchInitialKeyFocus = true; DetailsViewArgs.bUpdatesFromSelection = false; DetailsViewArgs.NotifyHook = nullptr; DetailsViewArgs.bShowOptions = true; DetailsViewArgs.bShowModifiedPropertiesOption = false; DetailsViewArgs.bShowScrollBar = false; DetailsViewArgs.bShowOptions = true; } FStructureDetailsViewArgs StructureViewArgs; { StructureViewArgs.bShowObjects = true; StructureViewArgs.bShowAssets = true; StructureViewArgs.bShowClasses = true; StructureViewArgs.bShowInterfaces = true; } SettingsView = EditModule.CreateStructureDetailView(DetailsViewArgs, StructureViewArgs, nullptr); FStructOnScope* Struct = new FStructOnScope(FExportPatchSettings::StaticStruct(), (uint8*)ExportPatchSetting.Get()); SettingsView->SetStructureData(MakeShareable(Struct)); } #undef LOCTEXT_NAMESPACE
/* * Copyright (c) 2012-2013 ARM Limited * All rights reserved. * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2003-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Erik Hallnor * Ron Dreslinski */ /** * @file * Declaration of a common base class for cache tagstore objects. */ #ifndef __BASE_TAGS_HH__ #define __BASE_TAGS_HH__ #include <string> #include "base/callback.hh" #include "base/statistics.hh" #include "params/BaseTags.hh" #include "sim/clocked_object.hh" class BaseCache; /** * A common base class of Cache tagstore objects. */ class BaseTags : public ClockedObject { protected: /** The block size of the cache. */ const unsigned blkSize; /** The size of the cache. */ const unsigned size; /** The hit latency of the cache. */ const Cycles hitLatency; /** Pointer to the parent cache. */ BaseCache *cache; /** * The number of tags that need to be touched to meet the warmup * percentage. */ int warmupBound; /** Marked true when the cache is warmed up. */ bool warmedUp; /** the number of blocks in the cache */ unsigned numBlocks; // Statistics /** * @addtogroup CacheStatistics * @{ */ /** Number of replacements of valid blocks per thread. */ Stats::Vector replacements; // This is not good approach. But I have not found any other way. #define MAX_NUM_MASTER 56 Stats::Vector replacements_detail[MAX_NUM_MASTER]; Stats::Vector determ_replacements; Stats::Vector determ_blks; Stats::AverageVector avg_determ_blks; /** Per cycle average of the number of tags that hold valid data. */ Stats::Average tagsInUse; /** The total number of references to a block before it is replaced. */ Stats::Scalar totalRefs; /** * The number of reference counts sampled. This is different from * replacements because we sample all the valid blocks when the simulator * exits. */ Stats::Scalar sampledRefs; /** * Average number of references to a block before is was replaced. * @todo This should change to an average stat once we have them. */ Stats::Formula avgRefs; /** The cycle that the warmup percentage was hit. */ Stats::Scalar warmupCycle; /** Average occupancy of each requestor using the cache */ Stats::AverageVector occupancies; /** Average occ % of each requestor using the cache */ Stats::Formula avgOccs; /** Occupancy of each requestor using the cache requested after the stat reset */ Stats::Vector occupanciesReset; /** Occ % of each requestor using the cache requested after the stat reset */ Stats::Formula occsReset; /** Occupancy of each context/cpu using the cache */ Stats::Vector occupanciesTaskId; /** Occupancy of each context/cpu using the cache */ Stats::Vector2d ageTaskId; /** Occ % of each context/cpu using the cache */ Stats::Formula percentOccsTaskId; /** Number of tags consulted over all accesses. */ Stats::Scalar tagAccesses; /** Number of data blocks consulted over all accesses. */ Stats::Scalar dataAccesses; /** * @} */ public: typedef BaseTagsParams Params; BaseTags(const Params *p); /** * Destructor. */ virtual ~BaseTags() {} /** * Set the parent cache back pointer. * @param _cache Pointer to parent cache. */ void setCache(BaseCache *_cache); /** * Register local statistics. */ void regStats(); /** * Average in the reference count for valid blocks when the simulation * exits. */ virtual void cleanupRefs() {} /** * Computes stats just prior to dump event */ virtual void computeStats() {} /** * Limit the allocation for the cache ways. * @param ways The ways available for replacement. */ virtual void setWayAllocation(int lowerNum, int upperNum) { panic("This tag class does not implement way allocation limit!\n"); } /** * Set deterministic associativity. */ virtual void setDmAssoc(bool dmAssocArg) { panic("This tag class does not implement deterministic way allocation limit!\n"); } virtual void clearDM(int lowerWay, int upperWay) { panic("This tag class does not implement deterministic bit clearing!\n"); } /** *iterated through all blocks and clear all locks *Needed to clear all lock tracking at once */ virtual void clearLocks() {} /** * Print all tags used */ virtual std::string print() const = 0; }; class BaseTagsCallback : public Callback { BaseTags *tags; public: BaseTagsCallback(BaseTags *t) : tags(t) {} virtual void process() { tags->cleanupRefs(); }; }; class BaseTagsDumpCallback : public Callback { BaseTags *tags; public: BaseTagsDumpCallback(BaseTags *t) : tags(t) {} virtual void process() { tags->computeStats(); }; }; #endif //__BASE_TAGS_HH__
#include "UnifyDuplicateLets.h" #include "IREquality.h" #include "IRMutator.h" #include <map> namespace Halide { namespace Internal { using std::map; using std::string; class UnifyDuplicateLets : public IRMutator2 { using IRMutator2::visit; map<Expr, string, IRDeepCompare> scope; map<string, string> rewrites; string producing; public: using IRMutator2::mutate; Expr mutate(const Expr &e) override { if (e.defined()) { map<Expr, string, IRDeepCompare>::iterator iter = scope.find(e); if (iter != scope.end()) { return Variable::make(e.type(), iter->second); } else { return IRMutator2::mutate(e); } } else { return Expr(); } } protected: Expr visit(const Variable *op) override { map<string, string>::iterator iter = rewrites.find(op->name); if (iter != rewrites.end()) { return Variable::make(op->type, iter->second); } else { return op; } } // Can't unify lets where the RHS might be not be pure bool is_impure; Expr visit(const Call *op) override { is_impure |= !op->is_pure(); return IRMutator2::visit(op); } Expr visit(const Load *op) override { is_impure |= ((op->name == producing) || starts_with(op->name + ".", producing)); return IRMutator2::visit(op); } Stmt visit(const ProducerConsumer *op) override { if (op->is_producer) { string old_producing = producing; producing = op->name; Stmt stmt = IRMutator2::visit(op); producing = old_producing; return stmt; } else { return IRMutator2::visit(op); } } template<typename LetStmtOrLet> auto visit_let(const LetStmtOrLet *op) -> decltype(op->body) { is_impure = false; Expr value = mutate(op->value); auto body = op->body; bool should_pop = false; bool should_erase = false; if (!is_impure) { map<Expr, string, IRDeepCompare>::iterator iter = scope.find(value); if (iter == scope.end()) { scope[value] = op->name; should_pop = true; } else { value = Variable::make(value.type(), iter->second); rewrites[op->name] = iter->second; should_erase = true; } } body = mutate(op->body); if (should_pop) { scope.erase(value); } if (should_erase) { rewrites.erase(op->name); } if (value.same_as(op->value) && body.same_as(op->body)) { return op; } else { return LetStmtOrLet::make(op->name, value, body); } } Expr visit(const Let *op) override { return visit_let(op); } Stmt visit(const LetStmt *op) override { return visit_let(op); } }; Stmt unify_duplicate_lets(Stmt s) { return UnifyDuplicateLets().mutate(s); } } // namespace Internal } // namespace Halide
/****************************************************************************/ // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo // Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0/ // This Source Code may also be made available under the following Secondary // Licenses when the conditions for such availability set forth in the Eclipse // Public License 2.0 are satisfied: GNU General Public License, version 2 // or later which is available at // https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later /****************************************************************************/ /// @file GUIPolygon.cpp /// @author Daniel Krajzewicz /// @author Jakob Erdmann /// @author Michael Behrisch /// @author Laura Bieker /// @date June 2006 /// // The GUI-version of a polygon /****************************************************************************/ #include <config.h> #include <string> #include <utils/geom/GeomHelper.h> #include <utils/gui/images/GUITexturesHelper.h> #include <utils/gui/globjects/GUIGlObject.h> #include <utils/gui/div/GUIParameterTableWindow.h> #include <utils/gui/globjects/GUIGLObjectPopupMenu.h> #include <utils/gui/settings/GUIVisualizationSettings.h> #include <utils/gui/div/GUIGlobalSelection.h> #include <utils/gui/div/GLHelper.h> #include "GUIPolygon.h" //#define GUIPolygon_DEBUG_DRAW_VERTICES // =========================================================================== // callbacks definitions // =========================================================================== void APIENTRY beginCallback(GLenum which) { glBegin(which); } void APIENTRY errorCallback(GLenum errorCode) { const GLubyte* estring; estring = gluErrorString(errorCode); fprintf(stderr, "Tessellation Error: %s\n", estring); exit(0); } void APIENTRY endCallback(void) { glEnd(); } void APIENTRY vertexCallback(GLvoid* vertex) { glVertex3dv((GLdouble*) vertex); } void APIENTRY combineCallback(GLdouble coords[3], GLdouble* vertex_data[4], GLfloat weight[4], GLdouble** dataOut) { UNUSED_PARAMETER(weight); UNUSED_PARAMETER(*vertex_data); GLdouble* vertex; vertex = (GLdouble*) malloc(7 * sizeof(GLdouble)); vertex[0] = coords[0]; vertex[1] = coords[1]; vertex[2] = coords[2]; *dataOut = vertex; } GLfloat INV_POLY_TEX_DIM = 1.0 / 256.0; GLfloat xPlane[] = {INV_POLY_TEX_DIM, 0.0, 0.0, 0.0}; GLfloat yPlane[] = {0.0, INV_POLY_TEX_DIM, 0.0, 0.0}; // =========================================================================== // method definitions // =========================================================================== GUIPolygon::GUIPolygon(const std::string& id, const std::string& type, const RGBColor& color, const PositionVector& shape, bool geo, bool fill, double lineWidth, double layer, double angle, const std::string& imgFile, bool relativePath): SUMOPolygon(id, type, color, shape, geo, fill, lineWidth, layer, angle, imgFile, relativePath), GUIGlObject_AbstractAdd(GLO_POLYGON, id), myDisplayList(0), myRotatedShape(nullptr) { if (angle != 0.) { setShape(shape); } } GUIPolygon::~GUIPolygon() { delete myRotatedShape; } GUIGLObjectPopupMenu* GUIPolygon::getPopUpMenu(GUIMainWindow& app, GUISUMOAbstractView& parent) { GUIGLObjectPopupMenu* ret = new GUIGLObjectPopupMenu(app, parent, *this); buildPopupHeader(ret, app, false); FXString t(getShapeType().c_str()); new FXMenuCommand(ret, "(" + t + ")", nullptr, nullptr, 0); new FXMenuSeparator(ret); buildCenterPopupEntry(ret); buildNameCopyPopupEntry(ret); buildSelectionPopupEntry(ret); buildShowParamsPopupEntry(ret, false); buildPositionCopyEntry(ret, false); return ret; } GUIParameterTableWindow* GUIPolygon::getParameterWindow(GUIMainWindow& app, GUISUMOAbstractView&) { GUIParameterTableWindow* ret = new GUIParameterTableWindow(app, *this); // add items ret->mkItem("type", false, getShapeType()); ret->mkItem("layer", false, toString(getShapeLayer())); ret->closeBuilding(this); return ret; } Boundary GUIPolygon::getCenteringBoundary() const { const PositionVector& shape = myRotatedShape != nullptr ? *myRotatedShape : myShape; Boundary b; b.add(shape.getBoxBoundary()); b.grow(2); return b; } void GUIPolygon::drawGL(const GUIVisualizationSettings& s) const { // first check if polygon can be drawn if (checkDraw(s)) { FXMutexLock locker(myLock); //if (myDisplayList == 0 || (!getFill() && myLineWidth != s.polySize.getExaggeration(s))) { // storeTesselation(s.polySize.getExaggeration(s)); //} // push name (needed for getGUIGlObjectsUnderCursor(...) glPushName(getGlID()); // draw inner polygon drawInnerPolygon(s, (myRotatedShape != nullptr ? *myRotatedShape : myShape), getShapeLayer(), false); // pop name glPopName(); } } void GUIPolygon::setShape(const PositionVector& shape) { FXMutexLock locker(myLock); SUMOPolygon::setShape(shape); if (getShapeNaviDegree() != 0.) { if (myRotatedShape == nullptr) { myRotatedShape = new PositionVector(); } const Position& centroid = myShape.getCentroid(); *myRotatedShape = myShape; myRotatedShape->sub(centroid); myRotatedShape->rotate2D(-DEG2RAD(getShapeNaviDegree())); myRotatedShape->add(centroid); } else { delete myRotatedShape; myRotatedShape = nullptr; } //storeTesselation(myLineWidth); } void GUIPolygon::performTesselation(const PositionVector& shape, double lineWidth) const { if (getFill()) { // draw the tesselated shape double* points = new double[shape.size() * 3]; GLUtesselator* tobj = gluNewTess(); gluTessCallback(tobj, GLU_TESS_VERTEX, (GLvoid(APIENTRY*)()) &glVertex3dv); gluTessCallback(tobj, GLU_TESS_BEGIN, (GLvoid(APIENTRY*)()) &beginCallback); gluTessCallback(tobj, GLU_TESS_END, (GLvoid(APIENTRY*)()) &endCallback); //gluTessCallback(tobj, GLU_TESS_ERROR, (GLvoid (APIENTRY*) ()) &errorCallback); gluTessCallback(tobj, GLU_TESS_COMBINE, (GLvoid(APIENTRY*)()) &combineCallback); gluTessProperty(tobj, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_ODD); gluTessBeginPolygon(tobj, nullptr); gluTessBeginContour(tobj); for (int i = 0; i != (int)shape.size(); ++i) { points[3 * i] = shape[(int) i].x(); points[3 * i + 1] = shape[(int) i].y(); points[3 * i + 2] = 0; gluTessVertex(tobj, points + 3 * i, points + 3 * i); } gluTessEndContour(tobj); gluTessEndPolygon(tobj); gluDeleteTess(tobj); delete[] points; } else { GLHelper::drawLine(shape); GLHelper::drawBoxLines(shape, lineWidth); } //std::cout << "OpenGL says: '" << gluErrorString(glGetError()) << "'\n"; } void GUIPolygon::storeTesselation(const PositionVector& shape, double lineWidth) const { if (myDisplayList > 0) { glDeleteLists(myDisplayList, 1); } myDisplayList = glGenLists(1); if (myDisplayList == 0) { throw ProcessError("GUIPolygon::storeTesselation() could not create display list"); } glNewList(myDisplayList, GL_COMPILE); performTesselation(shape, lineWidth); glEndList(); } void GUIPolygon::setColor(const GUIVisualizationSettings& s, bool disableSelectionColor) const { const GUIColorer& c = s.polyColorer; const int active = c.getActive(); if (s.netedit && active != 1 && gSelected.isSelected(GLO_POLYGON, getGlID()) && disableSelectionColor) { // override with special selection colors (unless the color scheme is based on selection) GLHelper::setColor(RGBColor(0, 0, 204)); } else if (active == 0) { GLHelper::setColor(getShapeColor()); } else if (active == 1) { GLHelper::setColor(c.getScheme().getColor(gSelected.isSelected(GLO_POLYGON, getGlID()))); } else { GLHelper::setColor(c.getScheme().getColor(0)); } } bool GUIPolygon::checkDraw(const GUIVisualizationSettings& s) const { if (s.polySize.getExaggeration(s, this) == 0) { return false; } Boundary boundary = myShape.getBoxBoundary(); if (s.scale * MAX2(boundary.getWidth(), boundary.getHeight()) < s.polySize.minSize) { return false; } if (getFill()) { if (myShape.size() < 3) { return false; } } else { if (myShape.size() < 2) { return false; } } return true; } void GUIPolygon::drawInnerPolygon(const GUIVisualizationSettings& s, const PositionVector& shape, double layer, bool disableSelectionColor) const { glPushMatrix(); glTranslated(0, 0, layer); setColor(s, disableSelectionColor); int textureID = -1; if (getFill()) { const std::string& file = getShapeImgFile(); if (file != "") { textureID = GUITexturesHelper::getTextureID(file, true); } } // init generation of texture coordinates if (textureID >= 0) { glEnable(GL_TEXTURE_2D); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); // without DEPTH_TEST vehicles may be drawn below roads glDisable(GL_LIGHTING); glDisable(GL_COLOR_MATERIAL); glDisable(GL_ALPHA_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glBindTexture(GL_TEXTURE_2D, textureID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // http://www.gamedev.net/topic/133564-glutesselation-and-texture-mapping/ glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGenfv(GL_S, GL_OBJECT_PLANE, xPlane); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGenfv(GL_T, GL_OBJECT_PLANE, yPlane); } // recall tesselation //glCallList(myDisplayList); performTesselation(shape, myLineWidth * s.polySize.getExaggeration(s, this)); // de-init generation of texture coordinates if (textureID >= 0) { glEnable(GL_DEPTH_TEST); glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_TEXTURE_2D); glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); } #ifdef GUIPolygon_DEBUG_DRAW_VERTICES GLHelper::debugVertices(shape, 80 / s.scale); #endif glPopMatrix(); const Position& namePos = shape.getPolygonCenter(); drawName(namePos, s.scale, s.polyName, s.angle); if (s.polyType.show) { const Position p = namePos + Position(0, -0.6 * s.polyType.size / s.scale); GLHelper::drawTextSettings(s.polyType, getShapeType(), p, s.scale, s.angle); } } /****************************************************************************/
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2021 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Simon Grätzer //////////////////////////////////////////////////////////////////////////////// #include "MutexExecutor.h" #include "Aql/AqlItemBlockManager.h" #include "Aql/ConstFetcher.h" #include "Aql/ExecutionEngine.h" #include "Aql/ExecutionNode.h" #include "Aql/IdExecutor.h" #include "Aql/MutexNode.h" #include "Aql/OutputAqlItemRow.h" #include "Aql/SharedQueryState.h" #include "Aql/Stats.h" #include "Basics/Exceptions.h" #include "Basics/debugging.h" #include "Logger/LogMacros.h" #include <algorithm> #include <utility> using namespace arangodb; using namespace arangodb::aql; MutexExecutorInfos::MutexExecutorInfos( std::vector<std::string> clientIds) : ClientsExecutorInfos(std::move(clientIds)) {} MutexExecutor::MutexExecutor(MutexExecutorInfos const& infos) : _infos(infos), _numClient(0) {} auto MutexExecutor::distributeBlock(SharedAqlItemBlockPtr block, SkipResult skipped, std::unordered_map<std::string, ClientBlockData>& blockMap) -> void { TRI_IF_FAILURE("MutexExecutor::distributeBlock") { THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG); } if (block != nullptr) { std::unordered_map<std::string, std::vector<std::size_t>> choosenMap; choosenMap.reserve(blockMap.size()); for (size_t i = 0; i < block->numRows(); ++i) { if (block->isShadowRow(i)) { // ShadowRows need to be added to all Clients for (auto const& [key, value] : blockMap) { choosenMap[key].emplace_back(i); } } else { auto const& client = getClient(block, i); // We can only have clients we are prepared for TRI_ASSERT(blockMap.find(client) != blockMap.end()); choosenMap[client].emplace_back(i); } } // We cannot have more in choosen than we have blocks TRI_ASSERT(choosenMap.size() <= blockMap.size()); for (auto& [key, target] : blockMap) { auto value = choosenMap.find(key); if (value != choosenMap.end()) { // we have data in this block target.addBlock(skipped, block, std::move(value->second)); } else { // No data, add skipped target.addBlock(skipped, nullptr, {}); } } } else { for (auto& [key, target] : blockMap) { // No data, add skipped target.addBlock(skipped, nullptr, {}); } } } std::string const& MutexExecutor::getClient(SharedAqlItemBlockPtr /*block*/, size_t rowIndex) { TRI_ASSERT(_infos.nrClients() > 0); // round-robin distribution return _infos.clientIds()[(_numClient++) % _infos.nrClients()]; } ExecutionBlockImpl<MutexExecutor>::ExecutionBlockImpl(ExecutionEngine* engine, MutexNode const* node, RegisterInfos registerInfos, MutexExecutorInfos&& executorInfos) : BlocksWithClientsImpl(engine, node, std::move(registerInfos), std::move(executorInfos)) {}
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "nacl_io/kernel_intercept.h" #include <assert.h> #include <errno.h> #include <string.h> #include "nacl_io/kernel_proxy.h" #include "nacl_io/kernel_wrap.h" #include "nacl_io/kernel_wrap_real.h" #include "nacl_io/log.h" #include "nacl_io/osmman.h" #include "nacl_io/ossocket.h" #include "nacl_io/ostime.h" #include "nacl_io/pepper_interface.h" #include "nacl_io/real_pepper_interface.h" using namespace nacl_io; #define ON_NOSYS_RETURN(x) \ if (!ki_is_initialized()) { \ errno = ENOSYS; \ return x; \ } #define TRACE_KP_CALLS 0 #if TRACE_KP_CALLS #define KP_TRACE nacl_io_log #else #define KP_TRACE(...) #endif #define KP_CALL(METHOD, ARGS) \ ON_NOSYS_RETURN(-1); \ int rtn = s_state.kp-> METHOD ARGS; \ KP_TRACE("ki_" #METHOD " -> %d\n", rtn); \ return rtn; struct KernelInterceptState { KernelProxy* kp; PepperInterface* ppapi; bool kp_owned; }; static KernelInterceptState s_state; // The the test code we want to be able to save the previous kernel // proxy when intialising and restore it on uninit. static KernelInterceptState s_saved_state; int ki_push_state_for_testing() { assert(s_saved_state.kp == NULL); if (s_saved_state.kp != NULL) return 1; s_saved_state = s_state; s_state.kp = NULL; s_state.ppapi = NULL; s_state.kp_owned = false; return 0; } static void ki_pop_state() { // Swap out the KernelProxy. This will normally reset the // proxy to NULL, aside from in test code that has called // ki_push_state_for_testing(). s_state = s_saved_state; s_saved_state.kp = NULL; s_saved_state.ppapi = NULL; s_saved_state.kp_owned = false; } int ki_pop_state_for_testing() { ki_pop_state(); return 0; } int ki_init(void* kp) { LOG_TRACE("ki_init: %p", kp); return ki_init_ppapi(kp, 0, NULL); } int ki_init_ppapi(void* kp, PP_Instance instance, PPB_GetInterface get_browser_interface) { assert(!s_state.kp); if (s_state.kp != NULL) return 1; PepperInterface* ppapi = NULL; if (instance && get_browser_interface) { ppapi = new RealPepperInterface(instance, get_browser_interface); s_state.ppapi = ppapi; } int rtn = ki_init_interface(kp, ppapi); return rtn; } int ki_init_interface(void* kp, void* pepper_interface) { LOG_TRACE("ki_init_interface: %p %p", kp, pepper_interface); assert(!s_state.kp); if (s_state.kp != NULL) return 1; PepperInterface* ppapi = static_cast<PepperInterface*>(pepper_interface); kernel_wrap_init(); if (kp == NULL) { s_state.kp = new KernelProxy(); s_state.kp_owned = true; } else { s_state.kp = static_cast<KernelProxy*>(kp); s_state.kp_owned = false; } if (s_state.kp->Init(ppapi) != 0) return 1; return 0; } int ki_is_initialized() { return s_state.kp != NULL; } int ki_uninit() { LOG_TRACE("ki_uninit"); assert(s_state.kp); if (s_state.kp == NULL) return 1; if (s_saved_state.kp == NULL) kernel_wrap_uninit(); // If we are going to delete the KernelProxy don't do it // until we've swapped it out. KernelInterceptState state_to_delete = s_state; ki_pop_state(); if (state_to_delete.kp_owned) delete state_to_delete.kp; delete state_to_delete.ppapi; return 0; } nacl_io::KernelProxy* ki_get_proxy() { return s_state.kp; } void ki_exit(int status) { KP_TRACE("ki_exit\n"); if (ki_is_initialized()) s_state.kp->exit(status); _real_exit(status); } char* ki_getcwd(char* buf, size_t size) { ON_NOSYS_RETURN(NULL); KP_TRACE("ki_getcwd\n"); return s_state.kp->getcwd(buf, size); } char* ki_getwd(char* buf) { ON_NOSYS_RETURN(NULL); KP_TRACE("ki_getwd\n"); return s_state.kp->getwd(buf); } int ki_chdir(const char* path) { KP_CALL(chdir, (path)); } int ki_dup(int oldfd) { KP_CALL(dup, (oldfd)); } int ki_dup2(int oldfd, int newfd) { KP_CALL(dup2, (oldfd, newfd)); } int ki_chmod(const char* path, mode_t mode) { KP_CALL(chmod, (path, mode)); } int ki_fchdir(int fd) { KP_CALL(fchdir, (fd)); } int ki_fchmod(int fd, mode_t mode) { KP_CALL(fchmod, (fd, mode)); } int ki_stat(const char* path, struct stat* buf) { KP_CALL(stat, (path, buf)); } int ki_mkdir(const char* path, mode_t mode) { KP_CALL(mkdir, (path, mode)); } int ki_rmdir(const char* path) { KP_CALL(rmdir, (path)); } int ki_mount(const char* source, const char* target, const char* filesystemtype, unsigned long mountflags, const void* data) { KP_CALL(mount, (source, target, filesystemtype, mountflags, data)); } int ki_umount(const char* path) { KP_CALL(umount, (path)); } int ki_open(const char* path, int oflag, mode_t mode) { KP_CALL(open, (path, oflag, mode)); } int ki_pipe(int pipefds[2]) { KP_CALL(pipe, (pipefds)); } ssize_t ki_read(int fd, void* buf, size_t nbyte) { ON_NOSYS_RETURN(-1); KP_TRACE("ki_read\n"); return s_state.kp->read(fd, buf, nbyte); } ssize_t ki_write(int fd, const void* buf, size_t nbyte) { ON_NOSYS_RETURN(-1); KP_TRACE("ki_write\n"); return s_state.kp->write(fd, buf, nbyte); } int ki_fstat(int fd, struct stat* buf) { KP_CALL(fstat, (fd, buf)); } int ki_getdents(int fd, struct dirent* buf, unsigned int count) { KP_CALL(getdents, (fd, buf, count)); } int ki_ftruncate(int fd, off_t length) { KP_CALL(ftruncate, (fd, length)); } int ki_fsync(int fd) { KP_CALL(fsync, (fd)); } int ki_fdatasync(int fd) { KP_CALL(fdatasync, (fd)); } int ki_isatty(int fd) { ON_NOSYS_RETURN(0); KP_TRACE("ki_isatty\n"); return s_state.kp->isatty(fd); } int ki_close(int fd) { KP_CALL(close, (fd)); } off_t ki_lseek(int fd, off_t offset, int whence) { ON_NOSYS_RETURN(-1); KP_TRACE("ki_lseek\n"); return s_state.kp->lseek(fd, offset, whence); } int ki_remove(const char* path) { KP_CALL(remove, (path)); } int ki_unlink(const char* path) { KP_CALL(unlink, (path)); } int ki_truncate(const char* path, off_t length) { KP_CALL(truncate, (path, length)); } int ki_lstat(const char* path, struct stat* buf) { KP_CALL(lstat, (path, buf)); } int ki_link(const char* oldpath, const char* newpath) { KP_CALL(link, (oldpath, newpath)); } int ki_rename(const char* path, const char* newpath) { KP_CALL(rename, (path, newpath)); } int ki_symlink(const char* oldpath, const char* newpath) { KP_CALL(symlink, (oldpath, newpath)); } int ki_access(const char* path, int amode) { KP_CALL(access, (path, amode)); } int ki_readlink(const char* path, char* buf, size_t count) { KP_CALL(readlink, (path, buf, count)); } int ki_utimes(const char* path, const struct timeval times[2]) { ON_NOSYS_RETURN(-1); KP_TRACE("ki_utimes"); // Implement in terms of utimens. if (!times) { return s_state.kp->utimens(path, NULL); } struct timespec ts[2]; ts[0].tv_sec = times[0].tv_sec; ts[0].tv_nsec = times[0].tv_usec * 1000; ts[1].tv_sec = times[1].tv_sec; ts[1].tv_nsec = times[1].tv_usec * 1000; return s_state.kp->utimens(path, ts); } int ki_futimes(int fd, const struct timeval times[2]) { ON_NOSYS_RETURN(-1); KP_TRACE("ki_futimes"); // Implement in terms of futimens. if (!times) { return s_state.kp->futimens(fd, NULL); } struct timespec ts[2]; ts[0].tv_sec = times[0].tv_sec; ts[0].tv_nsec = times[0].tv_usec * 1000; ts[1].tv_sec = times[1].tv_sec; ts[1].tv_nsec = times[1].tv_usec * 1000; return s_state.kp->futimens(fd, ts); } void* ki_mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset) { ON_NOSYS_RETURN(MAP_FAILED); KP_TRACE("ki_mmap\n"); return s_state.kp->mmap(addr, length, prot, flags, fd, offset); } int ki_munmap(void* addr, size_t length) { ON_NOSYS_RETURN(-1); KP_TRACE("ki_munmap\n"); return s_state.kp->munmap(addr, length); } int ki_open_resource(const char* file) { ON_NOSYS_RETURN(-1); KP_TRACE("ki_open_resource\n"); return s_state.kp->open_resource(file); } int ki_fcntl(int d, int request, va_list args) { KP_CALL(fcntl, (d, request, args)); } int ki_ioctl(int d, int request, va_list args) { KP_CALL(ioctl, (d, request, args)); } int ki_chown(const char* path, uid_t owner, gid_t group) { KP_CALL(chown, (path, owner, group)); } int ki_fchown(int fd, uid_t owner, gid_t group) { KP_CALL(fchown, (fd, owner, group)); } int ki_lchown(const char* path, uid_t owner, gid_t group) { KP_CALL(lchown, (path, owner, group)); } int ki_utime(const char* filename, const struct utimbuf* times) { ON_NOSYS_RETURN(-1); KP_TRACE("ki_utime\n"); // Implement in terms of utimens. if (!times) { return s_state.kp->utimens(filename, NULL); } struct timespec ts[2]; ts[0].tv_sec = times->actime; ts[0].tv_nsec = 0; ts[1].tv_sec = times->modtime; ts[1].tv_nsec = 0; return s_state.kp->utimens(filename, ts); } int ki_futimens(int fd, const struct timespec times[2]) { KP_CALL(futimens, (fd, times)); } mode_t ki_umask(mode_t mask) { ON_NOSYS_RETURN(0); KP_TRACE("ki_umask\n"); return s_state.kp->umask(mask); } int ki_poll(struct pollfd* fds, nfds_t nfds, int timeout) { KP_CALL(poll, (fds, nfds, timeout)); } int ki_select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* exceptfds, struct timeval* timeout) { KP_CALL(select, (nfds, readfds, writefds, exceptfds, timeout)); } int ki_tcflush(int fd, int queue_selector) { KP_CALL(tcflush, (fd, queue_selector)); } int ki_tcgetattr(int fd, struct termios* termios_p) { KP_CALL(tcgetattr, (fd, termios_p)); } int ki_tcsetattr(int fd, int optional_actions, const struct termios* termios_p) { KP_CALL(tcsetattr, (fd, optional_actions, termios_p)); } int ki_kill(pid_t pid, int sig) { KP_CALL(kill, (pid, sig)); } int ki_killpg(pid_t pid, int sig) { errno = ENOSYS; return -1; } int ki_sigaction(int signum, const struct sigaction* action, struct sigaction* oaction) { KP_CALL(sigaction, (signum, action, oaction)); } int ki_sigpause(int sigmask) { errno = ENOSYS; return -1; } int ki_sigpending(sigset_t* set) { errno = ENOSYS; return -1; } int ki_sigsuspend(const sigset_t* set) { errno = ENOSYS; return -1; } sighandler_t ki_signal(int signum, sighandler_t handler) { return ki_sigset(signum, handler); } sighandler_t ki_sigset(int signum, sighandler_t handler) { ON_NOSYS_RETURN(SIG_ERR); KP_TRACE("ki_sigset\n"); // Implement sigset(2) in terms of sigaction(2). struct sigaction action; struct sigaction oaction; memset(&action, 0, sizeof(action)); memset(&oaction, 0, sizeof(oaction)); action.sa_handler = handler; int rtn = s_state.kp->sigaction(signum, &action, &oaction); if (rtn) return SIG_ERR; return oaction.sa_handler; } #ifdef PROVIDES_SOCKET_API // Socket Functions int ki_accept(int fd, struct sockaddr* addr, socklen_t* len) { KP_CALL(accept, (fd, addr, len)); } int ki_bind(int fd, const struct sockaddr* addr, socklen_t len) { KP_CALL(bind, (fd, addr, len)); } int ki_connect(int fd, const struct sockaddr* addr, socklen_t len) { KP_CALL(connect, (fd, addr, len)); } struct hostent* ki_gethostbyname(const char* name) { ON_NOSYS_RETURN(NULL); return s_state.kp->gethostbyname(name); } int ki_getnameinfo(const struct sockaddr *sa, socklen_t salen, char *host, size_t hostlen, char *serv, size_t servlen, unsigned int flags) { ON_NOSYS_RETURN(EAI_SYSTEM); KP_TRACE("ki_getnameinfo\n"); return s_state.kp->getnameinfo(sa, salen, host, hostlen, serv, servlen, flags); } int ki_getaddrinfo(const char* node, const char* service, const struct addrinfo* hints, struct addrinfo** res) { ON_NOSYS_RETURN(EAI_SYSTEM); KP_TRACE("ki_getaddrinfo\n"); return s_state.kp->getaddrinfo(node, service, hints, res); } void ki_freeaddrinfo(struct addrinfo* res) { KP_TRACE("ki_freeaddrinfo\n"); s_state.kp->freeaddrinfo(res); } int ki_getpeername(int fd, struct sockaddr* addr, socklen_t* len) { KP_CALL(getpeername, (fd, addr, len)); } int ki_getsockname(int fd, struct sockaddr* addr, socklen_t* len) { KP_CALL(getsockname, (fd, addr, len)); } int ki_getsockopt(int fd, int lvl, int optname, void* optval, socklen_t* len) { KP_CALL(getsockopt, (fd, lvl, optname, optval, len)); } int ki_listen(int fd, int backlog) { KP_CALL(listen, (fd, backlog)); } ssize_t ki_recv(int fd, void* buf, size_t len, int flags) { ON_NOSYS_RETURN(-1); KP_TRACE("ki_recv\n"); return s_state.kp->recv(fd, buf, len, flags); } ssize_t ki_recvfrom(int fd, void* buf, size_t len, int flags, struct sockaddr* addr, socklen_t* addrlen) { ON_NOSYS_RETURN(-1); KP_TRACE("ki_recvfrom\n"); return s_state.kp->recvfrom(fd, buf, len, flags, addr, addrlen); } ssize_t ki_recvmsg(int fd, struct msghdr* msg, int flags) { ON_NOSYS_RETURN(-1); KP_TRACE("ki_recvmsg\n"); return s_state.kp->recvmsg(fd, msg, flags); } ssize_t ki_send(int fd, const void* buf, size_t len, int flags) { ON_NOSYS_RETURN(-1); KP_TRACE("ki_send\n"); return s_state.kp->send(fd, buf, len, flags); } ssize_t ki_sendto(int fd, const void* buf, size_t len, int flags, const struct sockaddr* addr, socklen_t addrlen) { ON_NOSYS_RETURN(-1); KP_TRACE("ki_sendto\n"); return s_state.kp->sendto(fd, buf, len, flags, addr, addrlen); } ssize_t ki_sendmsg(int fd, const struct msghdr* msg, int flags) { ON_NOSYS_RETURN(-1); KP_TRACE("ki_sendmsg\n"); return s_state.kp->sendmsg(fd, msg, flags); } int ki_setsockopt(int fd, int lvl, int optname, const void* optval, socklen_t len) { KP_CALL(setsockopt, (fd, lvl, optname, optval, len)); } int ki_shutdown(int fd, int how) { KP_CALL(shutdown, (fd, how)); } int ki_socket(int domain, int type, int protocol) { KP_CALL(socket, (domain, type, protocol)); } int ki_socketpair(int domain, int type, int protocol, int* sv) { KP_CALL(socketpair, (domain, type, protocol, sv)); } #endif // PROVIDES_SOCKET_API
/**************************************************************************** * * Copyright (c) 2015-2017 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file camera_trigger.cpp * * External camera-IMU synchronisation and triggering, and support for * camera manipulation using PWM signals over FMU auxillary pins. * * @author Mohammed Kabir <kabir@uasys.io> * @author Kelly Steich <kelly.steich@wingtra.com> * @author Andreas Bircher <andreas@wingtra.com> * @author Lorenz Meier <lorenz@px4.io> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <stdbool.h> #include <poll.h> #include <mathlib/mathlib.h> #include <matrix/math.hpp> #include <px4_platform_common/px4_work_queue/ScheduledWorkItem.hpp> #include <systemlib/err.h> #include <parameters/param.h> #include <uORB/Publication.hpp> #include <uORB/Subscription.hpp> #include <uORB/topics/camera_trigger.h> #include <uORB/topics/vehicle_command.h> #include <uORB/topics/vehicle_command_ack.h> #include <uORB/topics/vehicle_local_position.h> #include <drivers/drv_hrt.h> #include "interfaces/src/camera_interface.h" #include "interfaces/src/gpio.h" #include "interfaces/src/pwm.h" #include "interfaces/src/seagull_map2.h" extern "C" __EXPORT int camera_trigger_main(int argc, char *argv[]); typedef enum : int32_t { CAMERA_INTERFACE_MODE_NONE = 0, CAMERA_INTERFACE_MODE_GPIO, CAMERA_INTERFACE_MODE_SEAGULL_MAP2_PWM, CAMERA_INTERFACE_MODE_MAVLINK, CAMERA_INTERFACE_MODE_GENERIC_PWM } camera_interface_mode_t; typedef enum : int32_t { TRIGGER_MODE_NONE = 0, TRIGGER_MODE_INTERVAL_ON_CMD, TRIGGER_MODE_INTERVAL_ALWAYS_ON, TRIGGER_MODE_DISTANCE_ALWAYS_ON, TRIGGER_MODE_DISTANCE_ON_CMD } trigger_mode_t; #define commandParamToInt(n) static_cast<int>(n >= 0 ? n + 0.5f : n - 0.5f) class CameraTrigger : public px4::ScheduledWorkItem { public: /** * Constructor */ CameraTrigger(); /** * Destructor, also kills task. */ ~CameraTrigger() override; /** * Run intervalometer update */ void update_intervalometer(); /** * Run distance-based trigger update */ void update_distance(); /** * Trigger the camera just once */ void shoot_once(); /** * Toggle keep camera alive functionality */ void enable_keep_alive(bool on); /** * Toggle camera power (on/off) */ void toggle_power(); /** * Start the task. */ bool start(); /** * Stop the task. */ void stop(); /** * Display status. */ void status(); /** * Trigger one image */ void test(); /** * adjusts pose between triggers in CAMPOS mode */ void adjust_roll(); private: struct hrt_call _engagecall; struct hrt_call _disengagecall; struct hrt_call _engage_turn_on_off_call; struct hrt_call _disengage_turn_on_off_call; struct hrt_call _keepalivecall_up; struct hrt_call _keepalivecall_down; float _activation_time; float _interval; float _min_interval; float _distance; uint32_t _trigger_seq; hrt_abstime _last_trigger_timestamp; bool _trigger_enabled; bool _trigger_paused; bool _one_shot; bool _test_shot; bool _turning_on; matrix::Vector2f _last_shoot_position; bool _valid_position; //Camera Auto Mount Pivoting Oblique Survey (CAMPOS) uint32_t _CAMPOS_num_poses; uint32_t _CAMPOS_pose_counter; float _CAMPOS_roll_angle; float _CAMPOS_angle_interval; float _CAMPOS_pitch_angle; bool _CAMPOS_updated_roll_angle; uint32_t _target_system; uint32_t _target_component; uORB::Subscription _command_sub{ORB_ID(vehicle_command)}; uORB::Subscription _lpos_sub{ORB_ID(vehicle_local_position)}; orb_advert_t _trigger_pub; uORB::Publication<vehicle_command_ack_s> _cmd_ack_pub{ORB_ID(vehicle_command_ack)}; param_t _p_mode; param_t _p_activation_time; param_t _p_interval; param_t _p_min_interval; param_t _p_distance; param_t _p_interface; param_t _p_cam_cap_fback; trigger_mode_t _trigger_mode; int32_t _cam_cap_fback; camera_interface_mode_t _camera_interface_mode; CameraInterface *_camera_interface; ///< instance of camera interface /** * Vehicle command handler */ void Run() override; /** * Fires trigger */ static void engage(void *arg); /** * Resets trigger */ static void disengage(void *arg); /** * Fires on/off */ static void engange_turn_on_off(void *arg); /** * Resets on/off */ static void disengage_turn_on_off(void *arg); /** * Enables keep alive signal */ static void keep_alive_up(void *arg); /** * Disables keep alive signal */ static void keep_alive_down(void *arg); }; namespace camera_trigger { CameraTrigger *g_camera_trigger; } CameraTrigger::CameraTrigger() : ScheduledWorkItem(MODULE_NAME, px4::wq_configurations::lp_default), _engagecall {}, _disengagecall {}, _engage_turn_on_off_call {}, _disengage_turn_on_off_call {}, _keepalivecall_up {}, _keepalivecall_down {}, _activation_time(0.5f /* ms */), _interval(100.0f /* ms */), _min_interval(1.0f /* ms */), _distance(25.0f /* m */), _trigger_seq(0), _last_trigger_timestamp(0), _trigger_enabled(false), _trigger_paused(false), _one_shot(false), _test_shot(false), _turning_on(false), _last_shoot_position(0.0f, 0.0f), _valid_position(false), _CAMPOS_num_poses(0), _CAMPOS_pose_counter(0), _CAMPOS_roll_angle(0.0f), _CAMPOS_angle_interval(0.0f), _CAMPOS_pitch_angle(-90), _CAMPOS_updated_roll_angle(false), _target_system(0), _target_component(0), _trigger_pub(nullptr), _trigger_mode(TRIGGER_MODE_NONE), _cam_cap_fback(0), _camera_interface_mode(CAMERA_INTERFACE_MODE_GPIO), _camera_interface(nullptr) { // Initiate camera interface based on camera_interface_mode if (_camera_interface != nullptr) { delete (_camera_interface); // set to zero to ensure parser is not used while not instantiated _camera_interface = nullptr; } // Parameters _p_interval = param_find("TRIG_INTERVAL"); _p_min_interval = param_find("TRIG_MIN_INTERVA"); _p_distance = param_find("TRIG_DISTANCE"); _p_activation_time = param_find("TRIG_ACT_TIME"); _p_mode = param_find("TRIG_MODE"); _p_interface = param_find("TRIG_INTERFACE"); _p_cam_cap_fback = param_find("CAM_CAP_FBACK"); param_get(_p_activation_time, &_activation_time); param_get(_p_interval, &_interval); param_get(_p_min_interval, &_min_interval); param_get(_p_distance, &_distance); param_get(_p_mode, (int32_t *)&_trigger_mode); param_get(_p_interface, (int32_t *)&_camera_interface_mode); param_get(_p_cam_cap_fback, (int32_t *)&_cam_cap_fback); switch (_camera_interface_mode) { #ifdef __PX4_NUTTX case CAMERA_INTERFACE_MODE_GPIO: _camera_interface = new CameraInterfaceGPIO(); break; case CAMERA_INTERFACE_MODE_GENERIC_PWM: _camera_interface = new CameraInterfacePWM(); break; case CAMERA_INTERFACE_MODE_SEAGULL_MAP2_PWM: _camera_interface = new CameraInterfaceSeagull(); break; #endif case CAMERA_INTERFACE_MODE_MAVLINK: // start an interface that does nothing. Instead mavlink will listen to the camera_trigger uORB message _camera_interface = new CameraInterface(); break; default: PX4_ERR("unknown camera interface mode: %i", (int)_camera_interface_mode); break; } // Enforce a lower bound on the activation interval in PWM modes to not miss // engage calls in-between 50Hz PWM pulses. (see PX4 PR #6973) if ((_activation_time < 40.0f) && (_camera_interface_mode == CAMERA_INTERFACE_MODE_GENERIC_PWM || _camera_interface_mode == CAMERA_INTERFACE_MODE_SEAGULL_MAP2_PWM)) { _activation_time = 40.0f; PX4_WARN("Trigger interval too low for PWM interface, setting to 40 ms"); param_set_no_notification(_p_activation_time, &(_activation_time)); } // Advertise critical publishers here, because we cannot advertise in interrupt context struct camera_trigger_s trigger = {}; if (!_cam_cap_fback) { _trigger_pub = orb_advertise(ORB_ID(camera_trigger), &trigger); } else { _trigger_pub = orb_advertise(ORB_ID(camera_trigger_secondary), &trigger); } } CameraTrigger::~CameraTrigger() { if (_camera_interface != nullptr) { delete (_camera_interface); } camera_trigger::g_camera_trigger = nullptr; } void CameraTrigger::update_intervalometer() { // the actual intervalometer runs in interrupt context, so we only need to call // control_intervalometer once on enabling/disabling trigger to schedule the calls. if (_trigger_enabled && !_trigger_paused) { // schedule trigger on and off calls hrt_call_every(&_engagecall, 0, (_interval * 1000), (hrt_callout)&CameraTrigger::engage, this); // schedule trigger on and off calls hrt_call_every(&_disengagecall, 0 + (_activation_time * 1000), (_interval * 1000), (hrt_callout)&CameraTrigger::disengage, this); } } void CameraTrigger::update_distance() { if (_turning_on || !_trigger_enabled || _trigger_paused) { return; } vehicle_local_position_s local{}; _lpos_sub.copy(&local); if (local.xy_valid) { // Initialize position if not done yet matrix::Vector2f current_position(local.x, local.y); if (!_valid_position) { // First time valid position, take first shot _last_shoot_position = current_position; _valid_position = local.xy_valid; if (!_one_shot) { shoot_once(); } } hrt_abstime now = hrt_absolute_time(); if (!_CAMPOS_updated_roll_angle && _CAMPOS_num_poses > 0 && (now - _last_trigger_timestamp > _min_interval * 1000)) { adjust_roll(); _CAMPOS_updated_roll_angle = true; } // Check that distance threshold is exceeded if (matrix::Vector2f(_last_shoot_position - current_position).length() >= _distance) { shoot_once(); _CAMPOS_updated_roll_angle = false; _last_shoot_position = current_position; } } } void CameraTrigger::enable_keep_alive(bool on) { if (on) { // schedule keep-alive up and down calls hrt_call_every(&_keepalivecall_up, 0, (60000 * 1000), (hrt_callout)&CameraTrigger::keep_alive_up, this); hrt_call_every(&_keepalivecall_down, 0 + (30000 * 1000), (60000 * 1000), (hrt_callout)&CameraTrigger::keep_alive_down, this); } else { // cancel all calls hrt_cancel(&_keepalivecall_up); hrt_cancel(&_keepalivecall_down); } } void CameraTrigger::toggle_power() { // schedule power toggle calls hrt_call_after(&_engage_turn_on_off_call, 0, (hrt_callout)&CameraTrigger::engange_turn_on_off, this); hrt_call_after(&_disengage_turn_on_off_call, 0 + (200 * 1000), (hrt_callout)&CameraTrigger::disengage_turn_on_off, this); } void CameraTrigger::shoot_once() { // schedule trigger on and off calls hrt_call_after(&_engagecall, 0, (hrt_callout)&CameraTrigger::engage, this); hrt_call_after(&_disengagecall, 0 + (_activation_time * 1000), (hrt_callout)&CameraTrigger::disengage, this); } bool CameraTrigger::start() { if (_camera_interface == nullptr) { if (camera_trigger::g_camera_trigger != nullptr) { delete (camera_trigger::g_camera_trigger); camera_trigger::g_camera_trigger = nullptr; } return false; } if ((_trigger_mode == TRIGGER_MODE_INTERVAL_ALWAYS_ON || _trigger_mode == TRIGGER_MODE_DISTANCE_ALWAYS_ON) && _camera_interface->has_power_control() && !_camera_interface->is_powered_on()) { // If in always-on mode and the interface supports it, enable power to the camera toggle_power(); enable_keep_alive(true); } else { enable_keep_alive(false); } // enable immediately if configured that way if (_trigger_mode == TRIGGER_MODE_INTERVAL_ALWAYS_ON) { // enable and start triggering _trigger_enabled = true; update_intervalometer(); } else if (_trigger_mode == TRIGGER_MODE_DISTANCE_ALWAYS_ON) { // just enable, but do not fire. actual trigger is based on distance covered _trigger_enabled = true; } // start to monitor at high rate for trigger enable command ScheduleNow(); return true; } void CameraTrigger::stop() { ScheduleClear(); hrt_cancel(&_engagecall); hrt_cancel(&_disengagecall); hrt_cancel(&_engage_turn_on_off_call); hrt_cancel(&_disengage_turn_on_off_call); hrt_cancel(&_keepalivecall_up); hrt_cancel(&_keepalivecall_down); if (camera_trigger::g_camera_trigger != nullptr) { delete (camera_trigger::g_camera_trigger); camera_trigger::g_camera_trigger = nullptr; } } void CameraTrigger::test() { vehicle_command_s vcmd{}; vcmd.timestamp = hrt_absolute_time(); vcmd.param5 = 1.0; vcmd.command = vehicle_command_s::VEHICLE_CMD_DO_DIGICAM_CONTROL; vcmd.target_system = 1; vcmd.target_component = 1; uORB::Publication<vehicle_command_s> vcmd_pub{ORB_ID(vehicle_command)}; vcmd_pub.publish(vcmd); } void CameraTrigger::Run() { // default loop polling interval int poll_interval_usec = 50000; vehicle_command_s cmd{}; unsigned cmd_result = vehicle_command_s::VEHICLE_CMD_RESULT_TEMPORARILY_REJECTED; bool need_ack = false; // this flag is set when the polling loop is slowed down to allow the camera to power on _turning_on = false; // these flags are used to detect state changes in the command loop bool main_state = _trigger_enabled; bool pause_state = _trigger_paused; bool updated = _command_sub.update(&cmd); // Command handling if (updated) { if (cmd.command == vehicle_command_s::VEHICLE_CMD_DO_DIGICAM_CONTROL) { need_ack = true; hrt_abstime now = hrt_absolute_time(); if (now - _last_trigger_timestamp < _min_interval * 1000) { // triggering too fast, abort cmd_result = vehicle_command_s::VEHICLE_CMD_RESULT_TEMPORARILY_REJECTED; } else { if (commandParamToInt(cmd.param7) == 1) { // test shots are not logged or forwarded to GCS for geotagging _test_shot = true; } if (commandParamToInt((float)cmd.param5) == 1) { // Schedule shot _one_shot = true; } cmd_result = vehicle_command_s::VEHICLE_CMD_RESULT_ACCEPTED; } } else if (cmd.command == vehicle_command_s::VEHICLE_CMD_DO_TRIGGER_CONTROL) { need_ack = true; if (commandParamToInt(cmd.param3) == 1) { // pause triggger _trigger_paused = true; } else if (commandParamToInt(cmd.param3) == 0) { _trigger_paused = false; } if (commandParamToInt(cmd.param2) == 1) { // reset trigger sequence _trigger_seq = 0; } if (commandParamToInt(cmd.param1) == 1) { _trigger_enabled = true; } else if (commandParamToInt(cmd.param1) == 0) { _trigger_enabled = false; } cmd_result = vehicle_command_s::VEHICLE_CMD_RESULT_ACCEPTED; } else if (cmd.command == vehicle_command_s::VEHICLE_CMD_DO_SET_CAM_TRIGG_DIST) { need_ack = true; /* * TRANSITIONAL SUPPORT ADDED AS OF 11th MAY 2017 (v1.6 RELEASE) */ if (cmd.param1 > 0.0f) { _distance = cmd.param1; param_set_no_notification(_p_distance, &_distance); _trigger_enabled = true; _trigger_paused = false; _valid_position = false; } else if (commandParamToInt(cmd.param1) == 0) { _trigger_paused = true; } else if (commandParamToInt(cmd.param1) == -1) { _trigger_enabled = false; } // We can only control the shutter integration time of the camera in GPIO mode (for now) if (cmd.param2 > 0.0f) { if (_camera_interface_mode == CAMERA_INTERFACE_MODE_GPIO) { _activation_time = cmd.param2; param_set_no_notification(_p_activation_time, &(_activation_time)); } } // Trigger once immediately if param is set if (cmd.param3 > 0.0f) { // Schedule shot _one_shot = true; } cmd_result = vehicle_command_s::VEHICLE_CMD_RESULT_ACCEPTED; } else if (cmd.command == vehicle_command_s::VEHICLE_CMD_DO_SET_CAM_TRIGG_INTERVAL) { need_ack = true; if (cmd.param1 > 0.0f) { _interval = cmd.param1; param_set_no_notification(_p_interval, &(_interval)); } // We can only control the shutter integration time of the camera in GPIO mode if (cmd.param2 > 0.0f) { if (_camera_interface_mode == CAMERA_INTERFACE_MODE_GPIO) { _activation_time = cmd.param2; param_set_no_notification(_p_activation_time, &_activation_time); } } cmd_result = vehicle_command_s::VEHICLE_CMD_RESULT_ACCEPTED; } else if (cmd.command == vehicle_command_s::VEHICLE_CMD_OBLIQUE_SURVEY) { // Camera Auto Mount Pivoting Oblique Survey (CAMPOS) need_ack = true; if (cmd.param1 > 0.0f) { _distance = cmd.param1; param_set_no_notification(_p_distance, &_distance); _trigger_enabled = true; _trigger_paused = false; _valid_position = false; } else if (commandParamToInt(cmd.param1) == 0) { _trigger_paused = true; } else if (commandParamToInt(cmd.param1) == -1) { _trigger_enabled = false; } // We can only control the shutter integration time of the camera in GPIO mode (for now) if (cmd.param2 > 0.0f) { if (_camera_interface_mode == CAMERA_INTERFACE_MODE_GPIO) { _activation_time = cmd.param2; param_set_no_notification(_p_activation_time, &(_activation_time)); } } // Set Param for minimum camera trigger interval if (cmd.param3 > 0.0f) { _min_interval = cmd.param3; param_set_no_notification(_p_min_interval, &(_min_interval)); } if (cmd.param4 >= 2.0f) { _CAMPOS_num_poses = commandParamToInt(cmd.param4); _CAMPOS_roll_angle = cmd.param5; _CAMPOS_pitch_angle = cmd.param6; _CAMPOS_angle_interval = _CAMPOS_roll_angle * 2 / (_CAMPOS_num_poses - 1); _CAMPOS_pose_counter = 0; _CAMPOS_updated_roll_angle = false; } else { _CAMPOS_num_poses = 0; } cmd_result = vehicle_command_s::VEHICLE_CMD_RESULT_ACCEPTED; } else { goto unknown_cmd; } _target_system = cmd.target_system; _target_component = cmd.target_component; } unknown_cmd: // State change handling if ((main_state != _trigger_enabled) || (pause_state != _trigger_paused) || _one_shot) { if (_trigger_enabled || _one_shot) { // Just got enabled via a command // If camera isn't already powered on, we enable power to it if (!_camera_interface->is_powered_on() && _camera_interface->has_power_control()) { toggle_power(); enable_keep_alive(true); // Give the camera time to turn on before starting to send trigger signals poll_interval_usec = 3000000; _turning_on = true; } } else if (!_trigger_enabled || _trigger_paused) { // Just got disabled/paused via a command // Power off the camera if we are disabled if (_camera_interface->is_powered_on() && _camera_interface->has_power_control() && !_trigger_enabled) { enable_keep_alive(false); toggle_power(); } // cancel all calls for both disabled and paused hrt_cancel(&_engagecall); hrt_cancel(&_disengagecall); // ensure that the pin is off hrt_call_after(&_disengagecall, 0, (hrt_callout)&CameraTrigger::disengage, this); // reset distance counter if needed if (_trigger_mode == TRIGGER_MODE_DISTANCE_ON_CMD || _trigger_mode == TRIGGER_MODE_DISTANCE_ALWAYS_ON) { // this will force distance counter reinit on getting enabled/unpaused _valid_position = false; } } // only run on state changes, not every loop iteration if (_trigger_mode == TRIGGER_MODE_INTERVAL_ON_CMD) { // update intervalometer state and reset calls update_intervalometer(); } } // order matters - one_shot has to be handled LAST // as the other trigger handlers will back off from it // run every loop iteration and trigger if needed if (_trigger_mode == TRIGGER_MODE_DISTANCE_ON_CMD || _trigger_mode == TRIGGER_MODE_DISTANCE_ALWAYS_ON) { // update distance counter and trigger update_distance(); } // One shot command-based capture handling if (_one_shot && !_turning_on) { // One-shot trigger shoot_once(); _one_shot = false; if (_test_shot) { _test_shot = false; } } // Command ACK handling if (updated && need_ack) { vehicle_command_ack_s command_ack{}; command_ack.timestamp = hrt_absolute_time(); command_ack.command = cmd.command; command_ack.result = (uint8_t)cmd_result; command_ack.target_system = cmd.source_system; command_ack.target_component = cmd.source_component; _cmd_ack_pub.publish(command_ack); } ScheduleDelayed(poll_interval_usec); } void CameraTrigger::engage(void *arg) { CameraTrigger *trig = static_cast<CameraTrigger *>(arg); hrt_abstime now = hrt_absolute_time(); if ((trig->_last_trigger_timestamp > 0) && (now - trig->_last_trigger_timestamp < trig->_min_interval * 1000)) { return; } // Trigger the camera trig->_camera_interface->trigger(true); // set last timestamp trig->_last_trigger_timestamp = now; if (trig->_test_shot) { // do not send messages or increment frame count for test shots return; } // Send camera trigger message. This messages indicates that we sent // the camera trigger request. Does not guarantee capture. struct camera_trigger_s trigger = {}; // Set timestamp the instant after the trigger goes off trigger.timestamp = now; timespec tv = {}; px4_clock_gettime(CLOCK_REALTIME, &tv); trigger.timestamp_utc = (uint64_t) tv.tv_sec * 1000000 + tv.tv_nsec / 1000; trigger.seq = trig->_trigger_seq; trigger.feedback = false; if (!trig->_cam_cap_fback) { orb_publish(ORB_ID(camera_trigger), trig->_trigger_pub, &trigger); } else { orb_publish(ORB_ID(camera_trigger_secondary), trig->_trigger_pub, &trigger); } // increment frame count trig->_trigger_seq++; } void CameraTrigger::disengage(void *arg) { CameraTrigger *trig = static_cast<CameraTrigger *>(arg); trig->_camera_interface->trigger(false); } void CameraTrigger::engange_turn_on_off(void *arg) { CameraTrigger *trig = static_cast<CameraTrigger *>(arg); trig->_camera_interface->send_toggle_power(true); } void CameraTrigger::disengage_turn_on_off(void *arg) { CameraTrigger *trig = static_cast<CameraTrigger *>(arg); trig->_camera_interface->send_toggle_power(false); } void CameraTrigger::keep_alive_up(void *arg) { CameraTrigger *trig = static_cast<CameraTrigger *>(arg); trig->_camera_interface->send_keep_alive(true); } void CameraTrigger::keep_alive_down(void *arg) { CameraTrigger *trig = static_cast<CameraTrigger *>(arg); trig->_camera_interface->send_keep_alive(false); } void CameraTrigger::status() { PX4_INFO("main state : %s", _trigger_enabled ? "enabled" : "disabled"); PX4_INFO("pause state : %s", _trigger_paused ? "paused" : "active"); PX4_INFO("mode : %i", _trigger_mode); if (_trigger_mode == TRIGGER_MODE_INTERVAL_ALWAYS_ON || _trigger_mode == TRIGGER_MODE_INTERVAL_ON_CMD) { PX4_INFO("interval : %.2f [ms]", (double)_interval); } else if (_trigger_mode == TRIGGER_MODE_DISTANCE_ALWAYS_ON || _trigger_mode == TRIGGER_MODE_DISTANCE_ON_CMD) { PX4_INFO("distance : %.2f [m]", (double)_distance); } if (_camera_interface->has_power_control()) { PX4_INFO("camera power : %s", _camera_interface->is_powered_on() ? "ON" : "OFF"); } PX4_INFO("activation time : %.2f [ms]", (double)_activation_time); _camera_interface->info(); } static int usage() { PX4_INFO("usage: camera_trigger {start|stop|status|test|test_power}\n"); return 1; } int camera_trigger_main(int argc, char *argv[]) { if (argc < 2) { return usage(); } if (!strcmp(argv[1], "start")) { if (camera_trigger::g_camera_trigger != nullptr) { PX4_WARN("already running"); return 0; } camera_trigger::g_camera_trigger = new CameraTrigger(); if (camera_trigger::g_camera_trigger == nullptr) { PX4_WARN("alloc failed"); return 1; } if (!camera_trigger::g_camera_trigger->start()) { PX4_WARN("failed to start camera trigger"); return 1; } return 0; } if (camera_trigger::g_camera_trigger == nullptr) { PX4_WARN("not running"); return 1; } else if (!strcmp(argv[1], "stop")) { camera_trigger::g_camera_trigger->stop(); } else if (!strcmp(argv[1], "status")) { camera_trigger::g_camera_trigger->status(); } else if (!strcmp(argv[1], "test")) { camera_trigger::g_camera_trigger->test(); } else if (!strcmp(argv[1], "test_power")) { camera_trigger::g_camera_trigger->toggle_power(); } else { return usage(); } return 0; } void CameraTrigger::adjust_roll() { vehicle_command_s vcmd{}; vcmd.timestamp = hrt_absolute_time(); vcmd.command = vehicle_command_s::VEHICLE_CMD_DO_MOUNT_CONTROL; vcmd.target_system = _target_system; vcmd.target_component = _target_component; //param1 of VEHICLE_CMD_DO_MOUNT_CONTROL in VEHICLE_MOUNT_MODE_MAVLINK_TARGETING mode is pitch vcmd.param1 = _CAMPOS_pitch_angle; //param2 of VEHICLE_CMD_DO_MOUNT_CONTROL in VEHICLE_MOUNT_MODE_MAVLINK_TARGETING mode is roll if (++_CAMPOS_pose_counter == _CAMPOS_num_poses) { _CAMPOS_pose_counter = 0; } vcmd.param2 = _CAMPOS_angle_interval * _CAMPOS_pose_counter - _CAMPOS_roll_angle; vcmd.param7 = vehicle_command_s::VEHICLE_MOUNT_MODE_MAVLINK_TARGETING; uORB::Publication<vehicle_command_s> vcmd_pub{ORB_ID(vehicle_command)}; vcmd_pub.publish(vcmd); }
/// \file // Range v3 library // // Copyright Eric Niebler 2019-present // // Use, modification and distribution is subject to the // Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Project home: https://github.com/ericniebler/range-v3 // #ifndef RANGES_V3_ITERATOR_HPP #define RANGES_V3_ITERATOR_HPP #include <range/v3/detail/config.hpp> RANGES_DISABLE_WARNINGS #include <range/v3/utility/any.hpp> #include <range/v3/utility/box.hpp> #include <range/v3/utility/common_tuple.hpp> #include <range/v3/utility/common_type.hpp> #include <range/v3/utility/compressed_pair.hpp> #include <range/v3/utility/copy.hpp> #include <range/v3/utility/get.hpp> #include <range/v3/utility/in_place.hpp> #include <range/v3/utility/memory.hpp> #include <range/v3/utility/move.hpp> #include <range/v3/utility/optional.hpp> #include <range/v3/utility/polymorphic_cast.hpp> #include <range/v3/utility/random.hpp> #include <range/v3/utility/scope_exit.hpp> #include <range/v3/utility/semiregular.hpp> #include <range/v3/utility/static_const.hpp> #include <range/v3/utility/swap.hpp> #include <range/v3/utility/tuple_algorithm.hpp> #include <range/v3/utility/variant.hpp> RANGES_RE_ENABLE_WARNINGS #endif
class Solution { public: int f(int& n, vector<int>& a, vector<int>& b, int sign1, int sign2) { vector<int> v; for( int i = 0 ; i < n ; i++ ) v.push_back(i+sign1*a[i]+sign2*b[i]); int res = 0; int minVal = v[0]; for( int i = 1 ; i < n ; i++ ) { minVal = min(minVal, v[i]); res = max(res, v[i]-minVal); } return res; } int maxAbsValExpr(vector<int>& a, vector<int>& b) { int ans = 0; int n = a.size(); if(n == 0) return 0; ans = max( ans , f(n,a,b,+1,+1) ); ans = max( ans , f(n,a,b,+1,-1) ); ans = max( ans , f(n,a,b,-1,+1) ); ans = max( ans , f(n,a,b,-1,-1) ); return ans; } };
//////////////////////////////////////////////////////////// // // SFML - Simple and Fast Multimedia Library // Copyright (C) 2007-2021 Laurent Gomila (laurent@sfml-dev.org) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // //////////////////////////////////////////////////////////// #ifndef SFML_SLEEPIMPLWIN32_HPP #define SFML_SLEEPIMPLWIN32_HPP //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <SFML/Config.hpp> #include <SFML/System/Time.hpp> namespace sf { namespace priv { //////////////////////////////////////////////////////////// /// \brief Windows implementation of sf::Sleep /// /// \param time Time to sleep /// //////////////////////////////////////////////////////////// void sleepImpl(Time time); } // namespace priv } // namespace sf #endif // SFML_SLEEPIMPLWIN32_HPP
// Copyright 1996-2019 Cyberbotics Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef WB_VERSION_HPP #define WB_VERSION_HPP // // Description: store a generic version structure major.minor.revision // and support Webots specific version R2018a revision 1 // #include <QtCore/QString> class WbVersion { public: WbVersion(int major = 0, int minor = 0, int revision = 0); WbVersion(const WbVersion &other); virtual ~WbVersion() {} void setMajor(int major) { mMajor = major; } void setMinor(int minor) { mMinor = minor; } void setRevision(int revision) { mRevision = revision; } // extract the version from a string using the given prefix and suffix to build the regular expression // e.g. pattern "#VRML_SIM V8.6 utf8" and prefix "^VRML(_...|) " and suffix "( utf8|)$"" bool fromString(const QString &text, const QString &prefix = "", const QString &suffix = "", int expressionCountInPrefix = 0); int majorNumber() const { return mMajor; } int minorNumber() const { return mMinor; } int revisionNumber() const { return mRevision; } // Write version in a verbose way // if revision is false, only major and minor information are included. // In general the string will have the form "8.6.3". // Webots version is a special case and the string will have the form // "R2018a revision 1" or "R2018a" if revision is false, and // "2018.0.1 if digitsOnly is true ('a' = 0) QString toString(bool revision = true, bool digitsOnly = false, bool nightly = false) const; // copy WbVersion &operator=(const WbVersion &other) { mMajor = other.mMajor; mMinor = other.mMinor; mRevision = other.mRevision; mIsWebots = other.mIsWebots; mCommit = other.mCommit; mDate = other.mDate; return *this; } // comparison operators friend bool operator==(const WbVersion &l, const WbVersion &r) { return l.mMajor == r.mMajor && l.mMinor == r.mMinor && l.mRevision == r.mRevision; } friend bool operator!=(const WbVersion &l, const WbVersion &r) { return !(l == r); } friend bool operator<(const WbVersion &l, const WbVersion &r) { // TODO: we can certainly find a cleaner algorithm if (l.mMajor < r.mMajor) return true; else if (l.mMajor > r.mMajor) return false; else { // l.mMajor == r.mMajor if (l.mMinor < r.mMinor) return true; else if (l.mMinor > r.mMinor) return false; else // l.mMinor == r.mMinor return l.mRevision < r.mRevision; } } friend bool operator>(const WbVersion &l, const WbVersion &r) { return r < l; } friend bool operator<=(const WbVersion &l, const WbVersion &r) { return !(r < l); } friend bool operator>=(const WbVersion &l, const WbVersion &r) { return !(l < r); } private: int mMajor; int mMinor; // in case of Webots version 0 corresponds to 'a' int mRevision; QString mCommit; QString mDate; bool mIsWebots; }; #endif
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.ProBuilder.MeshUtility #include "UnityEngine/ProBuilder/MeshUtility.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Func`2<T, TResult> template<typename T, typename TResult> class Func_2; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: Dictionary`2<TKey, TValue> template<typename TKey, typename TValue> class Dictionary_2; // Forward declaring type: IEnumerable`1<T> template<typename T> class IEnumerable_1; } // Forward declaring namespace: UnityEngine::ProBuilder namespace UnityEngine::ProBuilder { // Forward declaring type: Vertex class Vertex; } // Completed forward declares #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::UnityEngine::ProBuilder::MeshUtility::$$c); DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::ProBuilder::MeshUtility::$$c*, "UnityEngine.ProBuilder", "MeshUtility/<>c"); // Type namespace: UnityEngine.ProBuilder namespace UnityEngine::ProBuilder { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: UnityEngine.ProBuilder.MeshUtility/UnityEngine.ProBuilder.<>c // [TokenAttribute] Offset: FFFFFFFF // [CompilerGeneratedAttribute] Offset: FFFFFFFF class MeshUtility::$$c : public ::Il2CppObject { public: // Get static field: static public readonly UnityEngine.ProBuilder.MeshUtility/UnityEngine.ProBuilder.<>c <>9 static ::UnityEngine::ProBuilder::MeshUtility::$$c* _get_$$9(); // Set static field: static public readonly UnityEngine.ProBuilder.MeshUtility/UnityEngine.ProBuilder.<>c <>9 static void _set_$$9(::UnityEngine::ProBuilder::MeshUtility::$$c* value); // Get static field: static public System.Func`2<System.Collections.Generic.Dictionary`2<UnityEngine.ProBuilder.Vertex,System.Int32>,System.Collections.Generic.IEnumerable`1<UnityEngine.ProBuilder.Vertex>> <>9__10_0 static ::System::Func_2<::System::Collections::Generic::Dictionary_2<::UnityEngine::ProBuilder::Vertex*, int>*, ::System::Collections::Generic::IEnumerable_1<::UnityEngine::ProBuilder::Vertex*>*>* _get_$$9__10_0(); // Set static field: static public System.Func`2<System.Collections.Generic.Dictionary`2<UnityEngine.ProBuilder.Vertex,System.Int32>,System.Collections.Generic.IEnumerable`1<UnityEngine.ProBuilder.Vertex>> <>9__10_0 static void _set_$$9__10_0(::System::Func_2<::System::Collections::Generic::Dictionary_2<::UnityEngine::ProBuilder::Vertex*, int>*, ::System::Collections::Generic::IEnumerable_1<::UnityEngine::ProBuilder::Vertex*>*>* value); // static private System.Void .cctor() // Offset: 0x1C144EC static void _cctor(); // System.Collections.Generic.IEnumerable`1<UnityEngine.ProBuilder.Vertex> <CollapseSharedVertices>b__10_0(System.Collections.Generic.Dictionary`2<UnityEngine.ProBuilder.Vertex,System.Int32> x) // Offset: 0x1C14558 ::System::Collections::Generic::IEnumerable_1<::UnityEngine::ProBuilder::Vertex*>* $CollapseSharedVertices$b__10_0(::System::Collections::Generic::Dictionary_2<::UnityEngine::ProBuilder::Vertex*, int>* x); // public System.Void .ctor() // Offset: 0x1C14550 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static MeshUtility::$$c* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::ProBuilder::MeshUtility::$$c::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<MeshUtility::$$c*, creationType>())); } }; // UnityEngine.ProBuilder.MeshUtility/UnityEngine.ProBuilder.<>c #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::ProBuilder::MeshUtility::$$c::_cctor // Il2CppName: .cctor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&UnityEngine::ProBuilder::MeshUtility::$$c::_cctor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::ProBuilder::MeshUtility::$$c*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::ProBuilder::MeshUtility::$$c::$CollapseSharedVertices$b__10_0 // Il2CppName: <CollapseSharedVertices>b__10_0 template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::Generic::IEnumerable_1<::UnityEngine::ProBuilder::Vertex*>* (UnityEngine::ProBuilder::MeshUtility::$$c::*)(::System::Collections::Generic::Dictionary_2<::UnityEngine::ProBuilder::Vertex*, int>*)>(&UnityEngine::ProBuilder::MeshUtility::$$c::$CollapseSharedVertices$b__10_0)> { static const MethodInfo* get() { static auto* x = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "Dictionary`2"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine.ProBuilder", "Vertex"), ::il2cpp_utils::GetClassFromName("System", "Int32")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::ProBuilder::MeshUtility::$$c*), "<CollapseSharedVertices>b__10_0", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{x}); } }; // Writing MetadataGetter for method: UnityEngine::ProBuilder::MeshUtility::$$c::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
// { Driver Code Starts #include <bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution{ public: vector<string> permutation(string S){ // Code Here int len = S.size()-1; vector<string> ans; dfs(S,len,ans); return ans; } void dfs(string s , int len , vector<string> &ans){ if(len == 0){ ans.push_back(s); return ; } dfs(s.substr(0,s.size() - len) + " " + s.substr(s.size()-len),len - 1 ,ans); dfs(s , len - 1 , ans ) ; } }; // { Driver Code Starts. int main(){ int t; cin>>t; while(t--){ string S; cin>>S; vector<string> ans; Solution obj; ans = obj.permutation(S); for(int i=0;i<ans.size();i++){ cout<<"("<<ans[i]<<")"; } cout << endl; } } // } Driver Code Ends
#include "SawWave_samples.h" static const PROGMEM uint32_t sample_0_SawWave_SAW0_48[7680] = { 0x00090000,0x01f700e8,0x03f102f1,0x05de04ea,0x07a806bb,0x0ae5091a,0x0e2d0c7a,0x11520fb9, 0x146012d8,0x174015c5,0x1a1a18a6,0x1ce21b6c,0x1f971e30,0x223920dc,0x24ce237a,0x27592606, 0x29d12881,0x2c352aea,0x2e832d44,0x30b52f88,0x32e031b2,0x34fc33d5,0x370c35e4,0x390a37e8, 0x3af039d9,0x3ccf3bb9,0x3ea43d8a,0x405e3f48,0x420a40fb,0x43a6429b,0x45384420,0x46bc45a3, 0x48294708,0x49974864,0x4af349af,0x4c464ae2,0x4d974bf7,0x4ef04cfa,0x507c4db8,0x53fa4de5, 0xdd8f3674,0xe393e62f,0xe602e684,0xe979e991,0xebf7eb96,0xee89ee7d,0xf156f127,0xf4aaf387, 0xf818f5ab,0xfaf9f7ef,0xfc3afb4c,0xd414ff3b,0x92a589ec,0x91899523,0x960398bc,0x9b3e9c36, 0x9fcf9f61,0xa4fca372,0xa9fba78d,0xad05ab95,0xb158afb4,0xb5c4b46d,0xba06b8ad,0xbe59bcd7, 0xc295c10a,0xc6c1c535,0xcaf5c963,0xcf24cd97,0xd34ad1bd,0xd76bd5e8,0xdb7bd9f8,0xdf86de0b, 0xe383e208,0xe76ce5fc,0xeb25e9cf,0xeecbed7d,0xf25bf11c,0xf5e7f4a8,0xf965f82b,0xfcd2fba9, 0x0037ff09,0x03960275,0x06d105c2,0x0a110902,0x0d330c32,0x10470f51,0x13501265,0x1635155e, 0x1917184a,0x1bf31b29,0x1eb01df9,0x215220b1,0x23dd234e,0x263c25c0,0x288c2821,0x2ac02a6f, 0x2cf32cac,0x2f0b2ed9,0x311230fe,0x330e3306,0x34ee3508,0x36c536f5,0x388738d8,0x3a323aae, 0x3bd03c7b,0x3d553e41,0x3eb54001,0x3ff841d2,0x40d743b0,0x417845e3,0xeca444fb,0xdd9dd10e, 0xdd71d7cc,0xe0bddc12,0xe2f4df57,0xe5cbe2df,0xe8b2e61a,0xebade945,0xeeb8ec74,0xf1c4efa3, 0xf4c8f2d1,0xf7d3f5ed,0xfae8f911,0xfdf2fc39,0x0105ff5d,0x0405028c,0x070c05a0,0x0a2308a0, 0x0d2f0b8e,0x0ffa0e80,0x12891191,0x14e714c4,0x178e1806,0x1aad1acd,0x1e6c1cce,0x21cb1e6d, 0xc84714c3,0xbcd8a974,0xba6bb152,0xbc4cb7d9,0xbf4fbd3d,0xc30ac11f,0xc730c58f,0xcb95c986, 0xcea5cc1e,0xd273cfc2,0xd5e8d3b4,0xd949d747,0xdcb4dacd,0xe01bde3d,0xe37ae199,0xe6d0e4f5, 0xea1de853,0xed66eba4,0xf0a3eef1,0xf3d8f233,0xf705f56e,0xfa29f898,0xfd42fbc1,0x005ffedc, 0x036501ff,0x06580500,0x093f07fa,0x0c1f0ae1,0x0eec0dc3,0x11ad1091,0x1465135a,0x17011611, 0x199a18c0,0x1c1d1b60,0x1e911de8,0x20f12072,0x234222e1,0x2584254f,0x27c527c1,0x29d32a29, 0x2bbc2c82,0x2d652ee0,0x2e893141,0x2ed73405,0x03d73930,0xcde9bb4b,0xcd36c5db,0xd0a7ca3c, 0xd306ce90,0xd654d269,0xd9a0d607,0xdcf3d997,0xe038dd13,0xe38ce087,0xe6dfe3ff,0xea39e765, 0xed94eade,0xf0e9ee45,0xf43cf1a9,0xf798f50d,0xfae3f868,0xfe2ffbbb,0x0178ff06,0x04b40260, 0x07da058d,0x0af208b6,0x0e0a0bd3,0x10fc0eeb,0x13cc11c4,0x16861493,0x193c174c,0x1be319f5, 0x1e851c9c,0x21111f30,0x238321be,0x25ed244e,0x285326c3,0x2ad82922,0x2d482b3f,0x2f922d4c, 0x31732f74,0x32d331f5,0x34223487,0x365736a6,0x389b3707,0xc09d0757,0xcc0bcd2e,0xcf55c9ed, 0xd1feccb3,0xd413d08b,0xd6f2d3d5,0xd9c4d7b0,0xdc5cdb71,0xdf46dd3b,0xe2a7e046,0xe592e348, 0xe869e62e,0xeb3de91d,0xee0aebfa,0xf0dbeecc,0xf3b7f19d,0xf681f465,0xf94cf72f,0xfc08f9ef, 0xfec4fca6,0x0189ff5d,0x04350217,0x06dc04b9,0x09810759,0x0c1609e6,0x0ea20c6d,0x11240ee9, 0x13a3115a,0x161b13c3,0x188b161b,0x1af6186b,0x1d651aa1,0x1fce1cce,0x22441ee3,0x24d420be, 0x27da2247,0x2c672316,0xaffbf505,0xbc0cc216,0xbff0c215,0xc4fec4fa,0xc7f9c7fc,0xcb92cb3f, 0xcf11ce6a,0xd288d1ab,0xd5f7d4fe,0xd968d850,0xdccedba6,0xe02adef2,0xe38ce240,0xe6e9e592, 0xea44e8e5,0xed8dec2b,0xf0d9ef6f,0xf41ff2af,0xf764f5ea,0xfa98f92a,0xfdd1fc56,0x0104ff83, 0x041902a2,0x072805ac,0x0a3208b6,0x0d2c0bb7,0x10170ea4,0x13011184,0x15cb1462,0x18991721, 0x1b4a19e4,0x1dfb1c8b,0x20901f25,0x232121be,0x259d2432,0x281626b0,0x2a74290c,0x2cb22b41, 0x2ecb2d73,0x30af2f92,0x328a318f,0x347d3359,0x369a34da,0x38c6362d,0x3a7837b9,0x3b6c39ac, 0x3bcd3c46,0x2ece3ea4,0xc576e165,0xcc83d863,0xd20bd50a,0xd649d5d7,0xd915d7d3,0xdc83da7e, 0xdf69dd8f,0xe0fde0e4,0xe3dde315,0xe6f2e620,0xe9bae8c1,0xec75eb5e,0xef29ee0d,0xf1cff0b0, 0xf478f364,0xf71ef606,0xf9bff8a2,0xfc60fb43,0xfef4fdd4,0x019c006c,0x042502f7,0x06a1057a, 0x092507fc,0x0b960a70,0x0e030cdc,0x106b0f48,0x12cf119b,0x152113f7,0x176a163f,0x19bd187d, 0x1be91ab9,0x1e0c1ceb,0x203a1f1a,0x12952223,0xb3e1b9f8,0xb9a8bb7d,0xbd18bd08,0xc1bbc0d4, 0xc4d2c3c3,0xc86ec765,0xcbeecac5,0xcf4cce22,0xd2a3d16a,0xd607d4c9,0xd95cd812,0xdcb2db68, 0xdffcdead,0xe34be1f6,0xe68fe53f,0xe9d1e87f,0xed17ebc1,0xf04feefb,0xf37af225,0xf6a8f553, 0xf9c8f87c,0xfce6fb97,0xfffafeaf,0x030301cb,0x060304c5,0x08f807bc,0x0bdb0aa5,0x0eba0d89, 0x118a1061,0x144b1324,0x16fe15e2,0x19a4188e,0x1c431b2c,0x1ecd1dbf,0x214a204e,0x23aa22b5, 0x26172524,0x285f277f,0x2a9e29c7,0x2ccb2bfa,0x2ed62e00,0x30cf2fe9,0x329c31d1,0x343b33c2, 0x35cb35b5,0x37783783,0x399338ff,0x3bc83a10,0x3d9f3b17,0x3deb3cf7,0x0b893e13,0xd4dbc700, 0xd1a9d3d9,0xd449d6c4,0xd7d4d922,0xdad2dae8,0xde5fdd92,0xe1c7e013,0xe357e267,0xe623e50b, 0xe8dbe82b,0xeb7fead2,0xee2ced6b,0xf0cbefff,0xf368f292,0xf602f531,0xf88ef7ca,0xfb17fa61, 0xfda3fcf5,0x0028ff82,0x02a80218,0x051e0492,0x078b070b,0x09f20985,0x0c4c0bfd,0x0ea00e66, 0x10e810d4,0x13261331,0x15471592,0x176117fb,0x19521a6d,0x1add1cf2,0x1bf61fff,0xe46a22ed, 0xbba9a92a,0xbc28b68f,0xbed6ba23,0xc25abf1b,0xc58dc221,0xc8dcc5fc,0xcc39c98d,0xcf94cd0e, 0xd2d3d07b,0xd620d3d6,0xd964d737,0xdca4da89,0xdfeaddd5,0xe323e11b,0xe664e466,0xe998e7ac, 0xecd0eaeb,0xf000ee23,0xf322f14f,0xf649f479,0xf960f79d,0xfc72fabb,0xff7ffdcf,0x028300de, 0x057d03e4,0x086a06d6,0x0b4909c0,0x0e1c0c9d,0x10e90f76,0x13a81238,0x165014ee,0x18f3179f, 0x1b8b1a39,0x1e0d1cc9,0x208a1f50,0x22e421c4,0x2554242c,0x27a42683,0x29df28d9,0x2c052b16, 0x2dfc2d43,0x2ff02f39,0x31e4311b,0x33cc32df,0x357c349e,0x36f63676,0x382b3873,0x398e3a86, 0x3b5a3c2d,0x3dd83d1b,0x40333d6b,0xe0452d76,0xdaf0c8ac,0xd7d7cf91,0xd8a4d4ce,0xda85d8ef, 0xdd11db9c,0xdffedeee,0xe327e1cd,0xe54fe343,0xe83de60a,0xeacbe904,0xed49ebb0,0xefdfee5c, 0xf275f0f1,0xf50af381,0xf798f614,0xfa1cf8ac,0xfca3fb33,0xff1ffdbe,0x01a70048,0x041702c7, 0x0683053e,0x08e407aa,0x0b500a1e,0x0da30c87,0x0ff20eeb,0x12371144,0x1468139c,0x169615ec, 0x18a31844,0x1a721aaa,0x1bee1d59,0xfe702138,0xb623adbc,0xb9d8b7aa,0xbcc2ba0f,0xc0ebbe65, 0xc3fac157,0xc77fc52c,0xcaf0c89f,0xce5bcc16,0xd1b6cf93,0xd50ad2e4,0xd85cd63c,0xdb9ed98c, 0xdee5dcda,0xe223e01e,0xe566e35d,0xe8a1e6a7,0xebd7e9df,0xef09ed18,0xf234f04a,0xf559f370, 0xf877f695,0xfb94f9ae,0xfe96fcc2,0x01a9ffd2,0x04a302d3,0x079605cb,0x0a7608b8,0x0d4c0b96, 0x101e0e6b,0x12e01130,0x159513f4,0x183c169c,0x1ad4193f,0x1d5a1bce,0x1fe41e5a,0x224820cb, 0x24b02336,0x27082593,0x295027e2,0x2b822a18,0x2d912c40,0x2f772e3a,0x314b3038,0x3326321e, 0x350a33e3,0x36ee3576,0x38b736f7,0x3a2b3882,0x3b423a81,0x3c3d3cb2,0x3dde3e8e,0x3db23f03, 0xc79c07fd,0xd565d6eb,0xd857d3c6,0xdac4d64c,0xdc86d99e,0xdf37dc8b,0xe1b7dffb,0xe3d6e356, 0xe679e4da,0xe987e7a2,0xec22ea49,0xeeacecdc,0xf133ef80,0xf3bcf20d,0xf646f4a1,0xf8d6f72b, 0xfb58f9a6,0xfddbfc2c,0x005bfea5,0x02d70127,0x0544039b,0x07b30602,0x0a190861,0x0c7f0ac3, 0x0edd0d1d,0x112c0f67,0x137d11ac,0x15c913e5,0x18051619,0x1a3a183b,0x1c8f1a4c,0x121a1ce9, 0xadb7bd85,0xb711b95d,0xba67ba67,0xbf19bdfd,0xc210c0ff,0xc5c9c483,0xc95bc7f5,0xccdbcb5d, 0xd050cec3,0xd3bbd228,0xd706d577,0xda5fd8c8,0xdda7dc05,0xe0eddf4d,0xe434e288,0xe772e5c9, 0xeab1e907,0xede6ec38,0xf113ef68,0xf43ef28e,0xf75cf5b4,0xfa76f8d1,0xfd89fbdf,0x0096fee3, 0x039801f1,0x068d04ea,0x097207da,0x0c4f0ab7,0x0f220d8f,0x11e81058,0x14a61314,0x175115c0, 0x19ef1861,0x1c771af6,0x1f091d7e,0x21761ffd,0x23e6225d,0x263924c4,0x28812712,0x2abc294d, 0x2cd52b75,0x2ed62d70,0x30c72f57,0x32913132,0x34553318,0x360334f0,0x37c5369f,0x39a5380f, 0x3bac393d,0x3d613a8e,0x3e503c44,0x3e8c3ea6,0x2afc4103,0xcae5dd81,0xd1cbdbfb,0xd6aed92e, 0xdaa3da21,0xdd4ddbf4,0xe093de81,0xe378e153,0xe4d8e454,0xe798e676,0xea79e95f,0xed1febda, 0xefbaee53,0xf249f0db,0xf4cef363,0xf754f5ed,0xf9dcf867,0xfc5efae4,0xfee0fd5d,0x015effc8, 0x03d4023e,0x063e04a0,0x08af06fa,0x0b140955,0x0d7e0bab,0x0fda0df4,0x12331029,0x14981252, 0x16f81473,0x19681669,0x1c4d181a,0x1c29199a,0xa751d5bb,0xb543b8a0,0xb86eb9fb,0xbd5cbcfe, 0xc047c05d,0xc41ac39e,0xc7b4c6f2,0xcb3eca64,0xcec0cdcd,0xd244d132,0xd5a3d49b,0xd8f4d7dd, 0xdc3edb23,0xdf8ede68,0xe2d2e1a5,0xe617e4e2,0xe956e81a,0xec8ceb55,0xefc5ee82,0xf2f4f1aa, 0xf613f4d5,0xf933f7ef,0xfc43fb02,0xff4bfe0d,0x025d0115,0x054f0417,0x083f0708,0x0b2109ed, 0x0df90cc1,0x10bf0f93,0x137c1251,0x162e1506,0x18d517ae,0x1b631a4e,0x1dec1cd2,0x20641f5b, 0x22d421ba,0x25342431,0x2780267b,0x29bd28c5,0x2bd82af8,0x2dcf2d01,0x2fc42ef3,0x31a830cd, 0x33873294,0x35453460,0x36d03638,0x38413807,0x39bf39c6,0x3ba23b47,0x3db93c62,0x3f953d48, 0x402e3eca,0x04f73d54,0xd8eac804,0xd5fdd6d6,0xd87bd9a1,0xdb9ddc22,0xde6cdded,0xe1bee09d, 0xe50ae31f,0xe692e525,0xe94fe7b8,0xebeeeab9,0xee78ed46,0xf107efbf,0xf390f23d,0xf61cf4ba, 0xf894f736,0xfb12f9b0,0xfd8dfc25,0x0001fe9b,0x027b010e,0x04e50373,0x074d05cc,0x09ac0829, 0x0c160a7b,0x0e700cca,0x10c60f07,0x13211130,0x157f1357,0x17ef1553,0x1ac4170d,0x1e2c1868, 0xa826ef5d,0xb4f3b426,0xb771b828,0xbc16baf8,0xbf09beeb,0xc2d7c1f7,0xc656c567,0xc9efc8de, 0xcd6dcc57,0xd0eecfca,0xd466d340,0xd7bcd69b,0xdb0cd9de,0xde55dd25,0xe19ae06a,0xe4e6e3b1, 0xe823e6ed,0xeb5fea2a,0xee93ed60,0xf1c4f08c,0xf4eff3b7,0xf807f6db,0xfb20f9ee,0xfe2afcfe, 0x01360002,0x043a0314,0x0725060b,0x0a0808ed,0x0ce70bcb,0x0fb50ea2,0x12731160,0x152c1423, 0x17d016cc,0x1a691978,0x1cf41c03,0x1f701e88,0x21df20f9,0x24462373,0x269225c9,0x28d7280d, 0x2afd2a49,0x2cf92c59,0x2ee92e54,0x30bb3049,0x32943226,0x346933f1,0x363f35a7,0x37e43745, 0x395538ec,0x3a853abf,0x3bbc3cc1,0x3d533e6f,0x3f9a3f71,0x41eb3f9e,0xdb832847,0xdd3dcdc7, 0xdafdd3f3,0xdc18d889,0xdddddc5e,0xe056def8,0xe314e235,0xe5f2e51b,0xe81ee675,0xeafde922, 0xed75ebf5,0xefe2ee86,0xf25ff113,0xf4dff394,0xf75af60e,0xf9d2f884,0xfc40fafa,0xfeaffd6e, 0x0126ffe1,0x0383024d,0x05df04b0,0x083e070f,0x0a950967,0x0ced0bba,0x0f330e05,0x11781043, 0x13bb127f,0x160114a2,0x185e16a5,0x1bb0188e,0xb21004dc,0xb59dad7c,0xb745b584,0xbb4cb886, 0xbe55bcfb,0xc1f6bffe,0xc56bc392,0xc8e0c71e,0xcc6ccaa6,0xcfe7ce28,0xd364d1af,0xd6ced522, 0xda12d873,0xdd67dbc9,0xe0a8df0f,0xe3f5e257,0xe730e59c,0xea71e8e0,0xeda9ec14,0xf0d2ef4a, 0xf407f27a,0xf727f5a2,0xfa36f8bd,0xfd46fbcd,0x0056fed9,0x035b01f0,0x064f04ea,0x093607d5, 0x0c110ab6,0x0ee80d8f,0x11a7105b,0x1468131b,0x171115ce,0x19ae1874,0x1c3c1b07,0x1ebe1d9a, 0x212a2004,0x23a02282,0x25f124dd,0x2831272a,0x2a682967,0x2c6d2b7d,0x2e652d74,0x304e2f61, 0x321a313d,0x33db331d,0x359d34f5,0x375d36ac,0x39223825,0x3add3986,0x3c653af0,0x3d8a3cb6, 0x3e503eb9,0x3f954094,0x3c774159,0xc8c6010c,0xd7bcdb1e,0xdac5d832,0xdd6cda6c,0xdf44dd54, 0xe1fce00a,0xe478e341,0xe65ae678,0xe8ece808,0xebd5eac3,0xee58ed47,0xf0cbefc2,0xf340f249, 0xf5a8f4c7,0xf81cf73c,0xfa8cf9ab,0xfcf3fc20,0xff58fe87,0x01c200f5,0x0419035a,0x066705b9, 0x08bb0816,0x0afe0a6e,0x0d3f0cc6,0x0f6b0f18,0x11961161,0x13a113b0,0x158515ff,0x17951893, 0xc7f713c2,0xb537a623,0xb753b3e1,0xba9cb6a9,0xbdf2bb84,0xc150be73,0xc4adc23c,0xc81cc5c1, 0xcb95c94b,0xcf12ccdf,0xd291d06c,0xd606d3f1,0xd951d75f,0xdc99daa9,0xdfe1ddfe,0xe320e13b, 0xe660e486,0xe99ce7cb,0xeccceb00,0xeffcee36,0xf328f163,0xf64bf490,0xf95ff7b1,0xfc65fabf, 0xff67fdc5,0x027900d6,0x056e03d5,0x085206c1,0x0b3509a2,0x0e020c80,0x10c40f48,0x137c1202, 0x162c14c1,0x18d11761,0x1b5419f6,0x1de01c88,0x204a1efc,0x22bb2169,0x251323d2,0x275c261d, 0x298c2858,0x2b902a79,0x2d862c76,0x2f712e63,0x3151303f,0x331e3203,0x34e533ca,0x3680359a, 0x380b374f,0x39a438f1,0x3b5d3a60,0x3d473b89,0x3ef13cbc,0x3ff83e30,0x40224053,0x2616424d, 0xcebcdb2a,0xd600de02,0xda04dc19,0xdd98dd79,0xe00edf43,0xe340e1be,0xe615e467,0xe765e727, 0xea13e946,0xecc8ec1c,0xef49ee8a,0xf1caf0e8,0xf438f361,0xf69ef5cb,0xf904f83d,0xfb6cfaae, 0xfdc5fd12,0x0029ff71,0x028501dd,0x04dc043a,0x071b068e,0x095e08ea,0x0b9c0b41,0x0dc80d97, 0x0fe70fe1,0x11e6123a,0x13a914a8,0x1525176c,0xe2041935,0xb13ca599,0xb69cb363,0xb953b5c2, 0xbd1cba78,0xc03bbd6e,0xc3acc13e,0xc712c4bb,0xca83c842,0xce00cbcb,0xd17bcf54,0xd4fbd2db, 0xd85ad656,0xdba1d9b8,0xdeebdcfa,0xe227e047,0xe565e38b,0xe8a3e6cd,0xebd1ea03,0xeeffed39, 0xf226f065,0xf546f38b,0xf865f6b1,0xfb6bf9c9,0xfe6cfccb,0x0178ffd5,0x046e02d7,0x075d05cc, 0x0a3308a8,0x0d080b88,0x0fcb0e59,0x12871111,0x153613ce,0x17d91677,0x1a681911,0x1cf01b9e, 0x1f5b1e1c,0x21d0208e,0x242922f2,0x26722544,0x28a62785,0x2ab629b2,0x2caf2baf,0x2e932da8, 0x30662f85,0x32373162,0x340a3323,0x35d034da,0x37763682,0x38e3382f,0x3a4139e7,0x3b913b90, 0x3d433d1a,0x3f243e43,0x40f53f1a,0x41e9403f,0xff4e3b94,0xdb44ca16,0xd9cbd99a,0xdc00dc01, 0xdec0deb0,0xe14de090,0xe46ae354,0xe77fe5c8,0xe902e79a,0xebb9ea22,0xee31ecfb,0xf096ef70, 0xf30bf1dc,0xf575f440,0xf7d7f6a3,0xfa3cf90b,0xfc9afb6f,0xfef3fdd1,0x01510030,0x03a0028f, 0x05ed04e3,0x082f0732,0x0a6d0980,0x0ca50bca,0x0ed50e18,0x10e0105d,0x12c612ad,0x147e1536, 0xf924187c,0xab21adce,0xb523b2d2,0xb780b559,0xbbc4b98d,0xbebcbc96,0xc246c048,0xc5c3c3b9, 0xc936c730,0xccabcab4,0xd039ce3a,0xd3b5d1bc,0xd72cd541,0xda8ed8b0,0xddd2dbff,0xe114df42, 0xe451e281,0xe792e5c3,0xeac0e900,0xedf2ec2f,0xf118ef60,0xf43ff287,0xf75cf5a9,0xfa69f8c0, 0xfd6bfbc7,0x0073fec7,0x037301d7,0x065604ca,0x093607ad,0x0c0d0a89,0x0ed80d58,0x1193101a, 0x144712d5,0x16ee157f,0x197e181c,0x1c0a1ab0,0x1e7d1d2d,0x20f31fa5,0x2351220d,0x259f2467, 0x27d926ac,0x29ee28dc,0x2beb2ade,0x2de22cd6,0x2fb52eb9,0x31853096,0x33453268,0x34fe3437, 0x36b335e3,0x3866377a,0x3a0138f5,0x3b653a7e,0x3c983c1e,0x3dba3dfd,0x3f103fa3,0x410840c1, 0x429c40f5,0xda152333,0xdec4d09e,0xdd50d7fa,0xdeefdb81,0xe0aedeed,0xe32ae15c,0xe5c0e482, 0xe851e755,0xea6ae8a1,0xed42eb46,0xefa2edef,0xf1f6f05e,0xf45bf2cf,0xf6bbf537,0xf91df795, 0xfb79f9eb,0xfdd0fc46,0x0022fe95,0x028500f4,0x04d30349,0x071d058d,0x096307d0,0x0ba50a0d, 0x0deb0c46,0x101c0e7c,0x123e1096,0x148312b5,0x09c9155f,0xa553bdbd,0xb325b19d,0xb571b511, 0xba1ab882,0xbd03bbca,0xc0babf43,0xc440c2ad,0xc7b6c624,0xcb3ac999,0xcec5cd09,0xd24dd096, 0xd5ccd411,0xd93dd788,0xdc99daef,0xdfd9de39,0xe31de176,0xe65ee4b4,0xe995e7f0,0xecc9eb24, 0xeffbee54,0xf31ff17b,0xf639f499,0xf94ef7b2,0xfc56fac1,0xff56fdb8,0x025b00c3,0x055103be, 0x082d06a4,0x0b0a0981,0x0dd30c53,0x10960f1e,0x135211d5,0x15f01481,0x188a171c,0x1b1f19b3, 0x1d911c34,0x200b1ea3,0x226d211c,0x24c12371,0x270025b9,0x291f27ec,0x2b2029f7,0x2d102beb, 0x2ef32dd5,0x30cf2fa8,0x329d3177,0x3452333c,0x35f234f2,0x379236a8,0x3933383e,0x3ad939b5, 0x3c7b3b03,0x3e023c4f,0x3f243dd3,0x3ffe3fa0,0x40f64173,0x3a134282,0xcb99fc12,0xdb21dc0b, 0xdd47db85,0xe009dd94,0xe1f4e015,0xe4bde29b,0xe73de591,0xe8ede88c,0xeb62ea11,0xee31ecc1, 0xf09aef2f,0xf2f9f183,0xf553f3e3,0xf7aaf63f,0xf9fff893,0xfc5cfadf,0xfea8fd32,0x0113ff7d, 0x035a01ce,0x05ac0412,0x07f6064a,0x0a3a087a,0x0c8a0aa2,0x0ed80cc9,0x11240ecb,0x13c4109e, 0x12b81277,0xa36bd529,0xb19eae53,0xb40cb4e3,0xb8c0b77a,0xbbafbb2b,0xbf6fbe57,0xc2efc1c8, 0xc66fc532,0xc9f0c8a4,0xcd76cc13,0xd104cf8f,0xd48ad31b,0xd7fdd68e,0xdb6cd9f8,0xdebbdd4f, 0xe1fce08e,0xe53be3c9,0xe874e702,0xeba5ea35,0xeed5ed61,0xf1f6f089,0xf518f3a8,0xf82cf6c3, 0xfb36f9cc,0xfe3bfcd1,0x0141ffd1,0x043102cf,0x071505b9,0x09f60896,0x0cc00b6d,0x0f870e2b, 0x123a10eb,0x14e61399,0x177c163d,0x1a1418d0,0x1c901b57,0x1f041dcb,0x21712047,0x23bf229c, 0x260724e4,0x28312724,0x2a34292f,0x2c242b22,0x2e0d2d16,0x2fe42ef2,0x31b730c1,0x337a328a, 0x35283431,0x36d735d7,0x38653784,0x39d9392c,0x3b493ab7,0x3cdc3c1c,0x3e983d4b,0x403b3e65, 0x415e3fa2,0x41a04179,0x2066427a,0xd1fdd977,0xda40df04,0xdd1fde3f,0xe059e00d,0xe2b9e1d4, 0xe5d3e44c,0xe899e6d3,0xe9e7e940,0xec7ceb4a,0xef19ee11,0xf176f061,0xf3dbf2af,0xf635f500, 0xf882f74f,0xfadcf99f,0xfd28fbf0,0xff76fe35,0x01d10086,0x041a02c6,0x066204fe,0x08a4072f, 0x0ae80957,0x0d340b7b,0x0f880d86,0x121e0f58,0x14ba10fb,0xa903ec77,0xb001a928,0xb359b3e9, 0xb78ab5ee,0xba9cba08,0xbe4cbd0b,0xc1c8c08f,0xc541c3f9,0xc8c2c76d,0xcc38cae0,0xcfb8ce5b, 0xd34fd1dd,0xd6c6d55d,0xda3ad8ce,0xdd96dc37,0xe0e0df8a,0xe41ee2bf,0xe753e604,0xea87e933, 0xedb6ec60,0xf0daef85,0xf404f2a9,0xf715f5c7,0xfa21f8d2,0xfd20fbda,0x0020feda,0x031f01de, 0x060704cb,0x08e107a7,0x0bb50a7f,0x0e770d4c,0x1131100b,0x13d812ba,0x167c1564,0x190e17f6, 0x1b911a83,0x1e071cfb,0x20751f77,0x22cc21d7,0x250e2423,0x27452660,0x2949287e,0x2b3f2a7f, 0x2d262c6b,0x2f082e4a,0x30cf3028,0x329331f0,0x344333b3,0x35ef3556,0x37a136f7,0x392c3889, 0x3a9a3a17,0x3be33bab,0x3d183d42,0x3e943ec2,0x40363ff7,0x420540c8,0x4340419f,0xf93e38a1, 0xdcc2ccb3,0xdd23dc32,0xdef5de21,0xe15be0fd,0xe3c6e2f0,0xe6a9e5b5,0xe984e82c,0xeb11e9ca, 0xedbbec33,0xf014eeef,0xf260f148,0xf4b5f39b,0xf704f5ea,0xf955f830,0xfba5fa80,0xfde4fcc7, 0x0030ff0e,0x027d0163,0x04b803a2,0x06f605d4,0x09250808,0x0b650a3a,0x0d990c58,0x0fe70e5b, 0x12ee1051,0xb4ecfe52,0xae9ca48c,0xb311b216,0xb695b417,0xb9d4b88c,0xbd58bb74,0xc0cbbf1b, 0xc441c28d,0xc7bec608,0xcb30c983,0xceaeccff,0xd231d07a,0xd5bcd40b,0xd928d785,0xdc98dafa, 0xdff1de5c,0xe329e1a1,0xe66ce4df,0xe99ae81a,0xeccaeb48,0xefefee74,0xf312f193,0xf62ff4b6, 0xf938f7cf,0xfc3bfad2,0xff3afdda,0x023e00e0,0x052703cd,0x080506b1,0x0adb098a,0x0da20c5b, 0x105b0f1e,0x130811d3,0x15b1147f,0x18461713,0x1ace19a8,0x1d3e1c22,0x1fb61ea5,0x22132105, 0x245e2358,0x2693259d,0x28a327c0,0x2aa129c7,0x2c872bbb,0x2e662d9a,0x303c2f78,0x32013142, 0x33b73307,0x355334b6,0x36f23666,0x38903805,0x3a2a3988,0x3bb33af0,0x3d173c50,0x3e423dc7, 0x3f513f7a,0x406e4117,0x4219424e,0x427c4298,0xd74b1c56,0xdf3dd44f,0xdf01db7d,0xe0e9de1b, 0xe2abe139,0xe518e39a,0xe790e6a4,0xe9d5e96d,0xebeeeab7,0xeea9ed47,0xf0f2efcb,0xf335f224, 0xf57df47e,0xf7c9f6cb,0xfa0cf91a,0xfc56fb5d,0xfe93fda9,0x00e0fff4,0x03170247,0x05480488, 0x077206c8,0x099a0908,0x0baa0b42,0x0dac0d7d,0x0fef0fe5,0xc76c0a6d,0xac0aa167,0xb2b8afeb, 0xb570b246,0xb8fab6df,0xbc3fb9ce,0xbfb5bd7f,0xc321c0fe,0xc697c47c,0xca0cc7fe,0xcd87cb87, 0xd101cf02,0xd486d285,0xd803d614,0xdb74d98b,0xded9dcf9,0xe221e057,0xe55de395,0xe894e6d9, 0xebc2ea02,0xeeebed37,0xf20af05e,0xf528f380,0xf839f698,0xfb3af9a2,0xfe3efca6,0x0147ffad, 0x042d02a5,0x07100587,0x09e60868,0x0cb20b34,0x0f6f0dfd,0x122010b6,0x14c91366,0x175f1601, 0x19ed189a,0x1c5e1b15,0x1edf1d91,0x21351ffc,0x238c2250,0x25bc2497,0x27d826bd,0x29d728c7, 0x2bc72ac3,0x2da72ca9,0x2f7a2e80,0x314e3056,0x33083215,0x34b533c0,0x36543562,0x37e63708, 0x396738a6,0x3ae83a37,0x3c6a3b93,0x3df43cd4,0x3f713dfd,0x40a53f5b,0x417d40e3,0x422d42a8, 0x36e643e9,0xce11f727,0xdd55dd45,0xdf24def6,0xe206e07e,0xe405e2d0,0xe6cfe528,0xe941e7f8, 0xead0eab8,0xed32ec46,0xefdbeef1,0xf227f142,0xf46ef388,0xf6b4f5d1,0xf8e8f814,0xfb26fa5d, 0xfd6dfca4,0xffa4fee6,0x01e50137,0x040b0371,0x062e05b1,0x084c07e7,0x0a530a2d,0x0c2b0c7a, 0x0df50f0a,0xe0041002,0xa671a52d,0xb200ad39,0xb3e6b177,0xb7d7b56d,0xbae5b883,0xbe5cbc2e, 0xc1c9bfa5,0xc53dc31f,0xc8aec6a6,0xcc2dca1f,0xcf9dcda1,0xd319d11b,0xd69bd4a0,0xda0fd820, 0xdd7bdb93,0xe0d7deff,0xe417e24e,0xe74fe58b,0xea7ce8c3,0xeda7ebee,0xf0caef17,0xf3eaf23b, 0xf6fff551,0xfa01f864,0xfd05fb66,0x0007fe69,0x02f90170,0x05db0452,0x08b00734,0x0b870a05, 0x0e430cca,0x10f80f8d,0x13a9123d,0x164014e4,0x18d21775,0x1b4819f7,0x1dc71c72,0x202d1ef0, 0x227f2146,0x24c1238f,0x26d925c0,0x28e027cb,0x2ad529cb,0x2cba2bba,0x2e912d93,0x30602f65, 0x321c3134,0x33cd32e4,0x35783491,0x37183630,0x38a637b7,0x3a28394a,0x3b7f3adb,0x3cd73c51, 0x3e3a3db6,0x3fca3ee0,0x41523fed,0x428a40fd,0x42fa4284,0x1b5b4228,0xd4a6d9bc,0xde20df6e, 0xdfdee092,0xe2d5e270,0xe510e447,0xe805e6ae,0xeabae91c,0xec00eb52,0xee84ed4f,0xf0f5f004, 0xf330f23f,0xf57cf475,0xf7baf6b9,0xf9f0f8ee,0xfc2afb2b,0xfe61fd6b,0x009bffa7,0x02c801eb, 0x04ec041f,0x070b0652,0x09170886,0x0aff0abe,0x0cd00d2b,0xf38a0ffd,0xa272af77,0xb073aac3, 0xb27ab124,0xb6a5b464,0xb997b7b5,0xbd26bb34,0xc090beae,0xc407c220,0xc77fc5a0,0xcaf8c911, 0xce72cc91,0xd1e4d009,0xd563d386,0xd8e0d705,0xdc4dda7e,0xdfb7ddeb,0xe30ce14a,0xe640e493, 0xe96ee7c3,0xec98eaf1,0xefbdee18,0xf2daf13b,0xf5edf454,0xf8f6f768,0xfbf8fa67,0xfef7fd68, 0x01f80066,0x04d40359,0x07b20634,0x0a810907,0x0d430bd3,0x0ffe0e94,0x12a31143,0x154c13ed, 0x17db1686,0x1a57190e,0x1cd71b88,0x1f411e03,0x21962067,0x23df22ae,0x25ff24ec,0x280626fc, 0x2a0528ff,0x2bf02af8,0x2dcb2cd9,0x2f9b2eb1,0x315e3080,0x330c3236,0x34b833e8,0x36533592, 0x37e6372a,0x398038b3,0x3b043a33,0x3c5a3b9d,0x3d9c3d13,0x3eb83e91,0x3ffb4007,0x41724141, 0x4324421d,0x446642be,0xf5693520,0xdd90cfad,0xe083de7b,0xe1d0e038,0xe40ae31d,0xe64de516, 0xe902e7d7,0xebaaea51,0xed32ebcc,0xefd2ee1f,0xf219f0bb,0xf448f2f9,0xf685f539,0xf8bff76c, 0xfafaf9a1,0xfd2ffbd8,0xff68fe10,0x01a40048,0x03cf027e,0x05fe04a7,0x081b06cb,0x0a3308e4, 0x0c560b08,0x01930daf,0x9fedbe8c,0xae01a7f2,0xb0c0b087,0xb4f7b313,0xb7edb69c,0xbb8cb9ec, 0xbf06bd62,0xc282c0d4,0xc5fec44c,0xc97bc7c2,0xccfacb40,0xd072cebe,0xd3f1d22c,0xd76fd5ae, 0xdaf1d92b,0xde5cdc9f,0xe1bee008,0xe50fe363,0xe83ce69f,0xeb6fe9cb,0xee90ecf6,0xf1b5f01a, 0xf4ccf337,0xf7daf649,0xfadff94e,0xfde3fc54,0x00e0ff4d,0x03cc024c,0x06aa052f,0x097a0803, 0x0c440ad3,0x0efe0d95,0x11ad104a,0x144f12ee,0x16e81592,0x196a1823,0x1be71a96,0x1e5a1d12, 0x20b31f79,0x22fd21c7,0x252a2408,0x27302620,0x2931281e,0x2b1f2a1c,0x2d052bff,0x2ed52dd9, 0x30a12fa8,0x32523165,0x34003312,0x35a434bf,0x37313657,0x38b437e8,0x3a3f3978,0x3bb63ae3, 0x3d2b3c36,0x3e7f3d7b,0x3fae3ec7,0x40b7404a,0x41b141c4,0x430f4304,0x41a1438a,0xd9c31833, 0xdfb7d5e1,0xe1b8dfa9,0xe394e111,0xe56ce3e0,0xe7d8e611,0xea3ee8f5,0xec4eeba1,0xee45ece1, 0xf0eeef59,0xf326f1bc,0xf552f3eb,0xf787f627,0xf9b9f854,0xfbecfa86,0xfe27fcb4,0x0059fed8, 0x0295010d,0x04c50328,0x06f3053b,0x09290741,0x0b91092c,0x09e10b2f,0xa294d495,0xaae3a3d5, 0xaffab015,0xb3a4b21f,0xb6c6b5d9,0xba62b8f8,0xbdd8bc6f,0xc14dbfda,0xc4cac343,0xc843c6b5, 0xcbc0ca32,0xcf3acda4,0xd2b4d11e,0xd631d48e,0xd9aad808,0xdd22db84,0xe088deeb,0xe3e2e246, 0xe722e597,0xea46e8c1,0xed71ebed,0xf091ef0a,0xf3a8f227,0xf6b1f53a,0xf9b9f83f,0xfcb9fb43, 0xffb0fe39,0x02a70136,0x0588041d,0x085506f1,0x0b1a09bb,0x0ddc0c7f,0x108d0f30,0x132f11e5, 0x15cb1476,0x184f170f,0x1acb1984,0x1d3e1c02,0x1fa11e6b,0x21ed20be,0x241b22ff,0x262a251b, 0x282a2720,0x2a1c2917,0x2c022b02,0x2ddd2ce2,0x2fa82eb3,0x315b306f,0x33093220,0x34b233c4, 0x36503565,0x37d936ef,0x395a387b,0x3ac83a01,0x3c243b76,0x3d8c3cc6,0x3ef23e01,0x405f3f12, 0x419f4042,0x4278419c,0x43054333,0x332b4453,0xd1b8f4c4,0xdfbadd07,0xe1bce223,0xe460e319, 0xe664e542,0xe91be774,0xeb96ea13,0xed08ec97,0xef47ee1b,0xf1d2f0aa,0xf404f2e3,0xf638f503, 0xf865f731,0xfa90f956,0xfcc3fb85,0xfef2fdac,0x012cffca,0x035b01ee,0x05850402,0x07ba05ff, 0x0a2007d6,0x0c2109a3,0xab0de8aa,0xa781a098,0xaf70ae9a,0xb269b10c,0xb5b0b4c2,0xb930b7d3, 0xbca8bb4b,0xc019beb4,0xc390c221,0xc707c58c,0xca7ec900,0xcdf8cc77,0xd172cfe9,0xd4e9d366, 0xd859d6d5,0xdbd9da45,0xdf3fddbb,0xe2a0e11a,0xe5f4e46f,0xe927e7b9,0xec45ead6,0xef66edf9, 0xf27ef116,0xf589f426,0xf88df72e,0xfb91fa2e,0xfe89fd2f,0x017f001d,0x0466030b,0x073a05ec, 0x09fb08b7,0x0cbc0b78,0x0f710e34,0x121410dc,0x14b2137d,0x173e1614,0x19af188c,0x1c311b0d, 0x1e8b1d76,0x20df1fd3,0x23162218,0x2529243b,0x272a2644,0x291f283f,0x2b0a2a2e,0x2ce72c0f, 0x2eb52de9,0x306d2fa6,0x3220315b,0x33c53307,0x355e34a9,0x36f13641,0x387837c0,0x39f4393c, 0x3b5b3ab2,0x3ca33c1f,0x3dde3d85,0x3f143ed4,0x407d3fff,0x41ee410a,0x432e41f4,0x43d6432b, 0x162d40ca,0xd6a9db08,0xe16fdf8e,0xe28fe304,0xe529e49b,0xe74ce685,0xea12e8e3,0xecb5eb46, 0xedfbed3a,0xf05def1d,0xf2baf1b9,0xf4ddf3e2,0xf70bf603,0xf933f826,0xfb5bfa48,0xfd7ffc72, 0xffa7fe8e,0x01d300bc,0x03f902db,0x061304e1,0x084806d1,0x0b0008c2,0xb8e7f872,0xa4299ef8, 0xaef7abf3,0xb163afdb,0xb4c0b361,0xb826b66a,0xbb99b9f8,0xbefebd61,0xc273c0ca,0xc5dbc43b, 0xc955c7ae,0xcccccb2d,0xd03cce9b,0xd3bbd212,0xd727d589,0xda95d8f4,0xde10dc6b,0xe16fdfd8, 0xe4c7e333,0xe80ae685,0xeb2fe9b8,0xee57ecd6,0xf167eff5,0xf476f307,0xf77df610,0xfa7ef912, 0xfd77fc0f,0x0068ff07,0x035301fa,0x062e04de,0x08ee07a9,0x0bb50a68,0x0e670d29,0x110e0fdd, 0x13b01277,0x163d1512,0x18b51792,0x1b331a10,0x1d971c83,0x1fea1edd,0x222b212b,0x24412355, 0x2644255f,0x283d2767,0x2a2a2950,0x2c0b2b39,0x2dde2d1a,0x2f982ee0,0x314a3095,0x32fc3243, 0x349633ee,0x36223588,0x37a73714,0x391f3898,0x3a9b3a0a,0x3c093b71,0x3d583cc2,0x3e883e19, 0x3f943f6c,0x40b340cc,0x41ef4201,0x437442e8,0x446e4374,0xf3ec3158,0xdcb4d358,0xe362e065, 0xe41ee2e3,0xe638e541,0xe85be74f,0xeae7e9f7,0xed51ec6e,0xeed2edd7,0xf158effe,0xf388f285, 0xf59bf4a9,0xf7bdf6cd,0xf9def8ee,0xfbfffb13,0xfe19fd39,0x0035ff5a,0x024d0187,0x045803ab, 0x064d05bd,0x08a107f5,0xca5c028a,0xa139a064,0xae28a8ae,0xb07daea8,0xb3e0b1e8,0xb719b503, 0xba8ab891,0xbdf0bc02,0xc15abf72,0xc4c8c2e5,0xc835c65b,0xcbafc9cf,0xcf21cd4a,0xd295d0bd, 0xd60ed440,0xd976d7a7,0xdcdedb1b,0xe058de8e,0xe3ace1ee,0xe6ffe549,0xea38e892,0xed50ebbc, 0xf077eed5,0xf37ef1f1,0xf687f4f9,0xf988f800,0xfc81faff,0xff73fdf8,0x026900ec,0x054503ce, 0x080f06a7,0x0acf096c,0x0d840c28,0x10360edd,0x12d01180,0x156c141e,0x17e216a5,0x1a631927, 0x1cce1b9d,0x1f201df8,0x21662047,0x2388227a,0x2590248e,0x278e268e,0x297b2888,0x2b5d2a6d, 0x2d362c51,0x2efb2e1d,0x30b22fd8,0x325f3187,0x34023335,0x359734cb,0x37223659,0x389b37e4, 0x3a0c395c,0x3b733ad7,0x3cd73c33,0x3e293d6c,0x3f793e98,0x409c3fc3,0x41a2411a,0x4283427a, 0x438f43c6,0x3fd14477,0xda7512ba,0xdfb8d7fb,0xe3bae28a,0xe549e397,0xe737e60d,0xe991e824, 0xebe6eadf,0xedbeed73,0xef9feeb6,0xf233f122,0xf44cf36b,0xf668f586,0xf882f7ab,0xfa98f9d1, 0xfcb6fbf5,0xfec7fe19,0x00e0003e,0x02df0276,0x04b304a0,0x069706f8,0xdc370740,0x9eb9a579, 0xac96a56e,0xaf40ad80,0xb2acb079,0xb5cbb3a3,0xb93fb730,0xbca0ba9e,0xc00dbe0b,0xc375c180, 0xc6e7c4f9,0xca5ac868,0xcdcbcbe6,0xd13ccf58,0xd4b6d2ce,0xd823d64a,0xdb90d9b4,0xdf00dd25, 0xe260e092,0xe5bde3f2,0xe906e741,0xec33ea86,0xef47eda8,0xf262f0c0,0xf565f3c6,0xf86af6ce, 0xfb67f9d4,0xfe59fccf,0x0152ffbc,0x042f02ad,0x0702058a,0x09c8084f,0x0c7f0b0f,0x0f330dc6, 0x11ce1073,0x146d130b,0x16e815a2,0x1971181f,0x1bdc1a9b,0x1e3b1cfa,0x20861f53,0x22ac218e, 0x24be23a8,0x26bb25ac,0x28af27a6,0x2a972992,0x2c712b6f,0x2e3f2d4a,0x2ffa2f09,0x319f30b8, 0x33493269,0x34dc3406,0x36703592,0x37f4371f,0x39693893,0x3ad53a02,0x3c2e3b6f,0x3d6c3ccf, 0x3ead3e14,0x3ff23f42,0x414d4040,0x428b414a,0x436f4273,0x43e243e5,0x2de044a7,0xd476efcf, 0xe189de61,0xe3c0e487,0xe626e552,0xe826e750,0xead4e972,0xed3febeb,0xee94ee36,0xf0bbefc3, 0xf327f242,0xf543f46a,0xf761f67e,0xf971f899,0xfb82fab3,0xfd93fcd2,0xffa3feec,0x01a8011f, 0x03870345,0x054f058d,0xec8107f7,0x9d1faf2f,0xaa8ea2a2,0xae2cacd9,0xb18faf7f,0xb499b2b9, 0xb817b629,0xbb78b99a,0xbeddbd01,0xc248c06c,0xc5c0c3e2,0xc92bc755,0xcc99cac7,0xd00bce38, 0xd384d1b1,0xd6fad527,0xda5dd893,0xddc9dbfb,0xe12fdf67,0xe48ce2cd,0xe7dbe620,0xeb19e96b, 0xee3aec9e,0xf148efac,0xf44cf2c0,0xf75af5c3,0xfa51f8c6,0xfd43fbb8,0x0030feaa,0x0317019c, 0x05e70474,0x08af073f,0x0b6d0a03,0x0e160cb2,0x10b70f5d,0x135111f9,0x15d4148b,0x1858170a, 0x1ac81988,0x1d211beb,0x1f751e3f,0x21972087,0x23a82298,0x25b024a8,0x27a2269e,0x298b2890, 0x2b652a76,0x2d382c49,0x2ef82e0f,0x30a92fca,0x324a3174,0x33e43314,0x357434a9,0x36f53635, 0x387037b7,0x39e23926,0x3b473a85,0x3c933bdf,0x3dc73d36,0x3eee3e83,0x3ff83fc1,0x413e40eb, 0x428e41e8,0x43df42ba,0x44ac43a3,0x0df23e33,0xda41d9aa,0xe410e10e,0xe4e4e4cd,0xe738e674, 0xe946e859,0xebe6eab4,0xee64ecfe,0xefaaeeb2,0xf203f099,0xf43cf31e,0xf646f52f,0xf85ff740, 0xfa73f951,0xfc82fb60,0xfe9bfd70,0x00aeff88,0x02a101a2,0x04a103b6,0xf95f064c,0x9d29bd59, 0xa7f9a026,0xad0aac31,0xb051ae96,0xb358b1e2,0xb6d9b527,0xba38b890,0xbd9fbbf1,0xc10dbf5d, 0xc47cc2c0,0xc7eec632,0xcb54c9a1,0xcec9cd0a,0xd23ad07a,0xd5afd3f3,0xd91cd763,0xdc7fdac8, 0xdfe3de2b,0xe348e18d,0xe698e4eb,0xe9dfe835,0xed14eb75,0xf028ee97,0xf331f1a0,0xf636f4ae, 0xf937f7b1,0xfc24faa6,0xff12fd94,0x02080081,0x04db0365,0x079c0632,0x0a6008f5,0x0d100baf, 0x0fb40e55,0x125110fb,0x14d9138b,0x175d160e,0x19d31891,0x1c301af6,0x1e841d4d,0x20b61f98, 0x22c521b2,0x24d023c0,0x26c925c2,0x28b427b2,0x2a99299d,0x2c6a2b77,0x2e292d3e,0x2fe52f02, 0x318e30b4,0x33283250,0x34be33eb,0x36433579,0x37c236fa,0x39283879,0x3a8f39e0,0x3beb3b44, 0x3d4a3c88,0x3e873dc1,0x3fa83ef3,0x40a1402b,0x41a2417f,0x42b142bb,0x441543a5,0x44694415, 0xec6b29e7,0xe017d61e,0xe5d7e2ea,0xe6a1e4dd,0xe88ce737,0xeaabe93b,0xed08ebd7,0xef36ee43, 0xf0bcef7b,0xf33cf19e,0xf557f3fc,0xf760f603,0xf973f814,0xfb80fa1e,0xfd95fc1c,0xffadfe23, 0x01d10027,0x04110206,0x01360424,0x9fb2ce26,0xa4d39da7,0xabc8ab09,0xaed7ad7e,0xb1f3b0d4, 0xb56fb3f8,0xb8d9b75c,0xbc3ebab8,0xbfb1be23,0xc31dc188,0xc691c4f0,0xca02c861,0xcd6dcbc9, 0xd0e2cf37,0xd457d2ab,0xd7c8d620,0xdb2dd984,0xde93dcea,0xe1f1e045,0xe555e3af,0xe8a0e6ff, 0xebdfea49,0xef08ed7a,0xf20ef08c,0xf518f391,0xf81cf696,0xfb0df991,0xfdf8fc7f,0x00e8ff6d, 0x03c60258,0x0690052b,0x095107ed,0x0c070aac,0x0ead0d56,0x11490ffa,0x13d5128c,0x165a1510, 0x18d81796,0x1b3a19fd,0x1d891c5c,0x1fcc1ea7,0x21de20cb,0x23e822da,0x25e324dd,0x27d526d1, 0x29b428b5,0x2b8f2a97,0x2d552c5e,0x2f122e25,0x30c32fd8,0x325b317c,0x33f13315,0x358334a5, 0x36ff362a,0x387b379e,0x39df390b,0x3b323a73,0x3c863bcc,0x3dc73d16,0x3f043e41,0x403f3f4d, 0x416d4052,0x426d4182,0x433142c8,0x43f54413,0x3c2d44ec,0xd90a088d,0xe254dc3c,0xe5b7e53c, 0xe781e5ef,0xe962e81f,0xebbfea25,0xee07ecaf,0xef95ef1e,0xf183f055,0xf3faf2ad,0xf611f4d6, 0xf819f6d5,0xfa25f8dd,0xfc3bfad8,0xfe50fcd3,0x006ffec4,0x02cb00a0,0x04240265,0xa698df99, 0xa1f99be2,0xaaf7a994,0xadbaac92,0xb0dcafe4,0xb452b2f0,0xb7c0b65d,0xbb1cb9b2,0xbe8bbd13, 0xc1f4c077,0xc563c3db,0xc8d4c74a,0xcc3ecab8,0xcfacce1d,0xd31fd18d,0xd693d4fd,0xd9f8d860, 0xdd5ddbd1,0xe0b4df28,0xe415e27e,0xe76ae5df,0xeaaee924,0xede3ec63,0xf0f3ef8c,0xf3f9f28c, 0xf6faf597,0xf9f7f88e,0xfce1fb7c,0xffc6fe66,0x02a80150,0x05790427,0x083506e5,0x0aee09a4, 0x0d930c53,0x102e0ef1,0x12bb1186,0x153c1408,0x17b61687,0x1a1a18fb,0x1c691b53,0x1eab1d99, 0x20bf1fc4,0x22ca21cf,0x24c123d4,0x26b125c4,0x289327ab,0x2a6c2989,0x2c312b55,0x2dee2d10, 0x2f9e2ecf,0x3139307a,0x32cd320a,0x345f339d,0x35dc352a,0x375836a2,0x38c23814,0x3a263974, 0x3b813ac9,0x3cc73c20,0x3deb3d6e,0x3f143ea3,0x40423fc6,0x418f40c4,0x42cc41b9,0x43c242b0, 0x442d43f4,0x258543da,0xd773e896,0xe3fde121,0xe5b0e681,0xe803e75e,0xea0be940,0xecafeb61, 0xef24edbd,0xf056efcf,0xf295f169,0xf4f0f3eb,0xf6fbf604,0xf919f802,0xfb33fa12,0xfd46fc1c, 0xff60fe15,0x01a5fffd,0x044b01da,0xb202eede,0x9faf9b2a,0xaab0a7b6,0xad28abde,0xb060af27, 0xb3bdb229,0xb731b5a6,0xba96b90b,0xbdfbbc6f,0xc168bfd3,0xc4d8c34a,0xc843c6b5,0xcbb2ca16, 0xcf17cd84,0xd28cd0ee,0xd5f8d45e,0xd95ad7c7,0xdcbbdb27,0xe011de88,0xe35ae1cd,0xe6b4e524, 0xe9f1e86c,0xed1feba6,0xf040eecb,0xf337f1d5,0xf62bf4cd,0xf915f7c1,0xfbf4fa9f,0xfecbfd79, 0x01a40053,0x04630317,0x071705d6,0x09bb0882,0x0c580b26,0x0ee30db8,0x11651043,0x13d512b7, 0x164b152f,0x18a3178e,0x1aea19df,0x1d1e1c22,0x1f351e4c,0x212e204e,0x23242244,0x25092433, 0x26f0261c,0x28c227f6,0x2a8829c7,0x2c3c2b7d,0x2df42d38,0x2f992ee7,0x31263082,0x32b63218, 0x3443339d,0x35c03528,0x372c36a0,0x38923812,0x39f93970,0x3b5a3ac9,0x3caa3c1f,0x3dcf3d5c, 0x3ee93e9d,0x3fed3fe4,0x41194124,0x425e4234,0x43bb42f8,0x44cf43a9,0x033439ac,0xdda0d820, 0xe5fce2f5,0xe6b2e627,0xe8d7e81b,0xeaebea0c,0xed88ec8e,0xf004eeef,0xf165f080,0xf3ddf291, 0xf60af517,0xf81df731,0xfa3ff957,0xfc5afb78,0xfe66fd8d,0x006aff96,0x030001c2,0xc19afa63, 0x9de29c66,0xaa8da57b,0xacefab44,0xb034ae6e,0xb378b17e,0xb6eab505,0xba4ab874,0xbda6bbd2, 0xc112bf48,0xc483c2b6,0xc7f1c627,0xcb51c98f,0xceb6ccf7,0xd21fd05e,0xd58ed3ce,0xd8e5d732, 0xdc3dda86,0xdf8adddc,0xe2cae124,0xe60fe465,0xe94fe7ab,0xec72eadd,0xef8dee03,0xf28bf111, 0xf573f405,0xf859f6e7,0xfb22f9c0,0xfdf3fc91,0x00b6ff51,0x0368021c,0x061204c5,0x08ad0767, 0x0b3d09fe,0x0db80c84,0x10300f04,0x12901166,0x14ff13d1,0x174c162e,0x198e1877,0x1bbd1aaf, 0x1dcd1cd2,0x1fc81ed0,0x21b720c9,0x239922b3,0x25702492,0x274a266b,0x2910283a,0x2ac429f6, 0x2c742baa,0x2e1e2d55,0x2fba2f00,0x31473095,0x32d73220,0x345f33ac,0x35da3529,0x3747369d, 0x38ab3815,0x3a0b397d,0x3b6f3ae3,0x3cbe3c2e,0x3e033d5a,0x3f463e90,0x40553fc9,0x41584127, 0x42474279,0x438e438f,0x42ec441b,0xe4bf20b6,0xe1d3d89e,0xe6d9e4c4,0xe7eae654,0xe9e1e8b5, 0xec20ead9,0xee8ced9b,0xf0a1f037,0xf266f186,0xf4faf3e0,0xf726f649,0xf939f876,0xfb57faae, 0xfd53fcde,0xff3dff02,0x015d0163,0xd31600e9,0x9bf0a082,0xa9aaa2c5,0xac48aa86,0xaf9cad77, 0xb2b8b093,0xb635b41a,0xb99cb7a2,0xbcf6bafd,0xc063be6d,0xc3d8c1e5,0xc744c557,0xcaa4c8c7, 0xce08cc2a,0xd16bcf93,0xd4d6d2f9,0xd830d664,0xdb83d9ba,0xded1dd0b,0xe20de059,0xe547e38f, 0xe87ce6c3,0xeba7e9ff,0xeebeed1c,0xf1c5f032,0xf4b1f325,0xf786f602,0xfa52f8db,0xfd0ffb98, 0xffcdfe59,0x027d0115,0x051c03b9,0x07ae0656,0x0a3008df,0x0cae0b61,0x0f1b0dd3,0x11691037, 0x13d21291,0x161a14ec,0x18541722,0x1a841961,0x1c901b7f,0x1e881d7a,0x20731f6e,0x22502158, 0x242e2332,0x2605250f,0x27c326d8,0x297a2896,0x2b2f2a4c,0x2cdb2bfb,0x2e812d9b,0x30142f40, 0x319e30cb,0x332d3255,0x34b533ea,0x3630355f,0x37a736da,0x3913383e,0x3a7639a9,0x3bc83b1b, 0x3d153c76,0x3e5d3dab,0x3fbb3ee0,0x41113ff2,0x42234117,0x42f74252,0x43a543cb,0x37054512, 0xd775fe23,0xe375dedd,0xe686e6dd,0xe89ae780,0xeaa8e9b1,0xed4febe1,0xefd2ee8e,0xf157f11f, 0xf374f29e,0xf60ef52c,0xf840f784,0xfa64f9b1,0xfc6efbef,0xfe4bfe1e,0x003c0082,0xe44c02fa, 0x9a59a92f,0xa80ca01f,0xab87aa14,0xaed3acbb,0xb1e7afed,0xb56ab372,0xb8e2b6f4,0xbc43ba64, 0xbfaebdcb,0xc329c142,0xc699c4b8,0xca03c82a,0xcd65cb96,0xd0c8cef4,0xd42cd25f,0xd786d5c1, 0xdadbd919,0xde1fdc64,0xe15fdfb1,0xe48ee2e0,0xe7b9e60e,0xeae0e935,0xedf3ec5d,0xf0fcef65, 0xf3e8f263,0xf6bef546,0xf97df811,0xfc36facc,0xfee2fd7c,0x018e0024,0x042102c5,0x06a9055a, 0x092407db,0x0b910a48,0x0df50cb4,0x10420f14,0x1297115b,0x14d613a9,0x170815e3,0x192f180e, 0x1b2f1a29,0x1d281c20,0x1f061e0b,0x20e21fe8,0x22b421bd,0x24892390,0x2649255b,0x27fc271a, 0x29aa28c5,0x2b552a76,0x2cec2c13,0x2e8d2db1,0x301b2f4a,0x31a530cf,0x332c325b,0x34ae33e5, 0x36233562,0x379836dd,0x3907383c,0x3a6e39a7,0x3bc93b14,0x3cff3c6a,0x3e373db8,0x3f773f09, 0x40dd4030,0x42374140,0x4369422b,0x44274367,0x1c184213,0xd9cde211,0xe5a8e290,0xe6fde775, 0xe969e8b0,0xeb99eab3,0xee79ed20,0xf12fefa6,0xf277f1b3,0xf4e8f38b,0xf762f64b,0xf995f890, 0xfbbbfac9,0xfdbafce9,0xffc6ff20,0xf22e0229,0x9a57b65a,0xa5fe9e01,0xaae8a9eb,0xae1bac5a, 0xb132af96,0xb4bab2f4,0xb836b672,0xbb97b9e2,0xbf0bbd48,0xc283c0be,0xc5f6c434,0xc95ec7a0, 0xccbfcb03,0xd01ece66,0xd386d1cc,0xd6d6d52d,0xda2fd87a,0xdd6ddbc2,0xe0abdf02,0xe3d3e237, 0xe6f1e559,0xea0be877,0xed28eb95,0xf026ee9f,0xf312f195,0xf5f2f47d,0xf8aef745,0xfb58f9f9, 0xfdfbfca4,0x009bff42,0x032801da,0x05ac0461,0x081c06da,0x0a820948,0x0cd80ba2,0x0f220dfc, 0x116c103f,0x13a2127f,0x15ce14b0,0x17ef16d6,0x19f318ee,0x1bdb1add,0x1dc01cc8,0x1f951ea0, 0x21632072,0x2329223d,0x24f12406,0x26a425c6,0x28522776,0x29fe291e,0x2b982ac4,0x2d392c5b, 0x2ecb2dfc,0x30572f8d,0x31df3115,0x3368329b,0x34ea3428,0x366535a4,0x37d63720,0x393f388b, 0x3ab539f6,0x3c213b5d,0x3d613caa,0x3ea23df7,0x3fba3f64,0x40ee40cd,0x422c4207,0x43b242eb, 0x451a4392,0xf9a8340b,0xe057d7b2,0xe7e5e46f,0xe898e746,0xeabde977,0xed11eba4,0xefd0ee78, 0xf25af10f,0xf3dbf27c,0xf6a2f4cc,0xf8fdf776,0xfb2ef9ad,0xfd4ffbc4,0xff98fdd8,0xfbbd0062, 0x9c18c664,0xa3209b93,0xa9cfa8f9,0xace5ab7b,0xb003aec4,0xb39db207,0xb71fb58a,0xba8ab8fe, 0xbe06bc63,0xc18cbfdc,0xc4fdc356,0xc868c6c3,0xcbd6ca2d,0xcf35cd8f,0xd29bd0f2,0xd5f7d44f, 0xd945d7a2,0xdc8cdaef,0xdfc7de30,0xe2f2e160,0xe60fe483,0xe924e796,0xec38eaa8,0xef39edbb, 0xf227f0ac,0xf50bf396,0xf7d5f671,0xfa75f922,0xfd1afbc0,0xffa4fe58,0x023a00ec,0x04b50374, 0x071d05e3,0x097c0847,0x0bcf0a9d,0x0e160ce9,0x10510f28,0x12851164,0x14a71388,0x16c315a6, 0x18ce17c3,0x1aa819af,0x1c821b87,0x1e581d66,0x20291f31,0x21f02102,0x23a922c0,0x25642475, 0x27172632,0x28be27db,0x2a5d2979,0x2bf42b19,0x2d922cb4,0x2f292e48,0x30ab2fd4,0x3236315e, 0x33c432e6,0x354a3470,0x36c335eb,0x38303766,0x399b38d3,0x3b1f3a53,0x3c843bbe,0x3dd53cf1, 0x3f413e31,0x40813f7a,0x419f40e8,0x42874254,0x43b0439b,0x41264489,0xdfce16ff,0xe3afdb61, 0xe847e6a2,0xe9b9e7d5,0xebd3ea3d,0xee6aec95,0xf0fdef7c,0xf2f1f225,0xf509f380,0xf7dcf613, 0xfa33f888,0xfc5afa8d,0xfed6fc82,0x0020fea8,0xa1a1d7d9,0xa038999b,0xa8fca7b7,0xabddaab2, 0xaf10ae02,0xb2acb134,0xb63eb4c0,0xb9a2b83b,0xbd1cbb91,0xc0adbf15,0xc432c2a4,0xc799c60f, 0xcb02c975,0xce71ccd6,0xd1d5d043,0xd52ad39d,0xd87fd6ef,0xdbc3da3d,0xdf01dd79,0xe229e0a8, 0xe549e3cc,0xe852e6e1,0xeb5ee9ed,0xee5aecec,0xf14cefe4,0xf42cf2cc,0xf703f5a9,0xf9b0f868, 0xfc42fb05,0xfecbfd93,0x01540012,0x03cc029f,0x062f0510,0x0883075d,0x0ad409b5,0x0d0f0bf9, 0x0f400e2e,0x116f1066,0x13891283,0x15961494,0x17a016a4,0x197c1893,0x1b4a1a68,0x1d211c3c, 0x1ee51e02,0x20b01fca,0x225c2187,0x240f2334,0x25bc24e6,0x27692694,0x29052834,0x2aa229d0, 0x2c302b62,0x2dcd2cf8,0x2f5b2e91,0x30dd3011,0x325f3195,0x33f8332a,0x357834a6,0x36ef3624, 0x385e378a,0x39e038ff,0x3b583a8e,0x3c963c01,0x3de93d37,0x3f603e90,0x40e03fb9,0x422f40f1, 0x4316421c,0x43bf439f,0x3096450a,0xd838f4cc,0xe584e17f,0xe81ce8a7,0xea6ee96b,0xecbfeb9e, 0xef9fedfc,0xf23ff09e,0xf3cbf31c,0xf632f4cb,0xf8eff787,0xfb20f9b9,0xfd87fba5,0x00a1fdad, 0xabd7e7cc,0x9da29896,0xa88fa5ec,0xab1ca9fa,0xae63ad35,0xb1ecb05f,0xb579b3ef,0xb8ecb778, 0xbc57bad4,0xbfebbe4e,0xc372c1de,0xc6dbc557,0xca45c8b7,0xcda7cc21,0xd113cf81,0xd46dd2ea, 0xd7b2d62f,0xdafbd97c,0xde3bdcbf,0xe15ddfef,0xe478e30f,0xe784e61d,0xea87e927,0xed7dec25, 0xf06def12,0xf348f1fb,0xf61cf4d0,0xf8d8f79b,0xfb6cfa41,0xfdecfcc6,0x0065ff46,0x02e601c3, 0x0545042b,0x078b0684,0x09d008c8,0x0c0c0b0d,0x0e380d3a,0x10630f68,0x1278118a,0x147d1390, 0x167d159c,0x18591788,0x1a231959,0x1bed1b27,0x1db31ceb,0x1f751eae,0x21342074,0x22d42218, 0x248323c0,0x26342571,0x27c82719,0x296128b1,0x2af42a45,0x2c8a2bdb,0x2e202d72,0x2fa72f01, 0x312b3082,0x32b93207,0x3445339c,0x35bd351f,0x3730369b,0x38ae380b,0x3a3d398a,0x3bb03b09, 0x3cd73c6a,0x3e253dc1,0x3f743f3e,0x40e74095,0x424041b9,0x439c4292,0x44d443ac,0x11e13fd5, 0xdd11ddd6,0xe7c3e496,0xe8d4e8e8,0xeb41ea8a,0xed9eecbf,0xf064ef47,0xf33af1d6,0xf4a4f3d6, 0xf74af5e5,0xf998f89f,0xfbc7fab9,0xfee4fce0,0xb9e5f3c4,0x9b6498d6,0xa81aa36c,0xaa85a904, 0xadc1ac1d,0xb138af41,0xb4c8b2ee,0xb832b679,0xbb98b9da,0xbf1cbd52,0xc2b1c0e6,0xc620c46e, 0xc983c7d2,0xcce2cb38,0xd04ece97,0xd3add203,0xd6ecd554,0xda34d896,0xdd6fdbd2,0xe09adf12, 0xe3afe231,0xe6b3e542,0xe9bfe843,0xecb2eb3f,0xef93ee29,0xf274f108,0xf542f3e9,0xf7fef6b6, 0xfaaaf962,0xfd22fbf5,0xff93fe67,0x021200dd,0x0465034a,0x06b3059d,0x08f307de,0x0b260a1c, 0x0d4b0c45,0x0f730e73,0x117e1088,0x13861292,0x1578148f,0x17571677,0x191f184f,0x1ae41a15, 0x1c9d1bd2,0x1e5b1d8e,0x20131f4d,0x21bc20fc,0x2358229f,0x25022441,0x26a125ec,0x28342783, 0x29c62915,0x2b562aa6,0x2cef2c3c,0x2e7d2dd0,0x2ff72f57,0x317e30cf,0x33123261,0x349533f7, 0x3608356e,0x377936ef,0x38fd3868,0x3a8839f4,0x3bf73b5e,0x3d383ca4,0x3e9e3df6,0x3fd73f7f, 0x41074108,0x42144256,0x43a84355,0x44fe441b,0xf0722cfa,0xe2c6d924,0xe958e67b,0xea44e8df, 0xec60eb4c,0xeea4ed94,0xf169f068,0xf3d9f350,0xf593f4bf,0xf81ff730,0xfa3df9bb,0xfcb1fc21, 0xcaabfafa,0x99769c17,0xa75ea0a9,0xaa0ea841,0xad47ab36,0xb093ae5a,0xb42bb206,0xb7a9b5b0, 0xbb00b90f,0xbe7fbc82,0xc210c013,0xc591c3aa,0xc8ebc710,0xcc51ca7c,0xcfb6cdd6,0xd31ad14b, 0xd65ad49e,0xd99dd7dc,0xdcd7db24,0xdfffde55,0xe31de178,0xe61ae487,0xe91be784,0xec0aea7f, 0xeee3ed65,0xf1b5f03e,0xf48bf316,0xf74af5d7,0xf9f3f88c,0xfc77fb2d,0xfeddfd9e,0x0149fffd, 0x03a20273,0x05e004b9,0x081806f3,0x0a3f091f,0x0c5d0b44,0x0e790d62,0x107e0f75,0x127c1174, 0x1464136b,0x16351548,0x17fd1712,0x19b018d2,0x1b6a1a88,0x1d1d1c3b,0x1ece1df1,0x20721f9a, 0x220d213c,0x23a222d1,0x254f2473,0x26e22610,0x286b27a3,0x29fd292c,0x2b8f2ac5,0x2d1e2c4e, 0x2ea42dde,0x30262f63,0x31b130e8,0x334f327d,0x34c03400,0x36473579,0x37ba36f8,0x39453881, 0x3ac43a13,0x3c233b8a,0x3d8c3cbf,0x3f1f3e1e,0x40843f79,0x41ae40e0,0x42924240,0x43a643cd, 0x3e024538,0xdc470cc8,0xe55fdedb,0xe977e8f2,0xeb3fe9f2,0xed50ec4f,0xf002ee93,0xf2bbf1a3, 0xf482f481,0xf672f5f7,0xf8eff88c,0xfb18fb3e,0xdb9afdc7,0x97c6a346,0xa5d39df8,0xa93aa79f, 0xac83aa63,0xafa3ad94,0xb346b12a,0xb6d5b4d2,0xba27b840,0xbdaebbb4,0xc135bf3c,0xc4bcc2ce, 0xc823c64b,0xcb87c9b4,0xcee6cd12,0xd253d084,0xd58ed3d3,0xd8d7d717,0xdc0bda52,0xdf36dd92, 0xe255e0aa,0xe555e3c6,0xe84fe6b8,0xeb44e9b5,0xee15ec9d,0xf0e4ef6b,0xf3b7f238,0xf66bf4fd, 0xf917f7b3,0xfbaafa59,0xfe16fcd4,0x006eff2e,0x02d30199,0x050803db,0x073b0611,0x0962083e, 0x0b760a5d,0x0d8b0c6d,0x0f8f0e82,0x117f1078,0x1375126e,0x153b144d,0x16fd1608,0x18b117cb, 0x1a5f197c,0x1c0f1b2b,0x1dbb1cd8,0x1f5e1e7f,0x20fe2022,0x229421bd,0x24322356,0x25ca24ef, 0x275f268a,0x28ec2810,0x2a8029a4,0x2c072b34,0x2d962cc6,0x2f262e54,0x30a92fdb,0x323c3161, 0x33cb3305,0x354e347c,0x36db3609,0x385d3789,0x39ef390b,0x3b6d3aa3,0x3cb13c1c,0x3e1e3d77, 0x3fa33ef9,0x41304032,0x429f416c,0x43ca429b,0x44834412,0x295f452f,0xda74ed28,0xe7cee44c, 0xe9f0eab1,0xec42eba0,0xee95eda4,0xf1a2f03b,0xf475f303,0xf5b3f56d,0xf7e5f710,0xfa5ff9f6, 0xea37fd84,0x9653ae8f,0xa2fc9ab7,0xa7b7a681,0xaaf9a91b,0xae28ac6d,0xb1c9afe9,0xb56fb38e, 0xb8c8b70f,0xbc58ba79,0xbfe7be0d,0xc376c19c,0xc6e8c522,0xca58c897,0xcdafcbf3,0xd125cf60, 0xd46fd2c4,0xd7b3d602,0xdaf2d947,0xde28dc82,0xe142dfa7,0xe44ae2bf,0xe746e5bf,0xea3ee8b8, 0xed1deba2,0xefe6ee73,0xf2aef143,0xf577f40b,0xf81ef6c0,0xfabcf965,0xfd34fbf2,0xff90fe59, 0x01ef00ac,0x04250305,0x06570537,0x087d0760,0x0a8d097a,0x0c9d0b84,0x0ea20d9a,0x10910f89, 0x1280117d,0x14491363,0x1600151c,0x17b016d2,0x195f1883,0x1b0e1a2a,0x1cb61bd6,0x1e511d78, 0x1feb1f18,0x218820b3,0x231e2249,0x24b523de,0x264d2578,0x27db2709,0x29662899,0x2af52a2b, 0x2c7d2bad,0x2e172d40,0x2f9b2ed6,0x311c3052,0x32b631df,0x343b3373,0x35c234f4,0x37493689, 0x38c73802,0x3a5b3984,0x3be33b0f,0x3d283c7b,0x3e953de8,0x3fdc3f80,0x414940f5,0x42c34248, 0x444d432c,0x45fa4423,0x088a3c89,0xe0c7dc0c,0xea7fe6bb,0xeb38ea9d,0xed7cec56,0xeffceea5, 0xf2f4f174,0xf5b1f430,0xf6f3f5b1,0xf9adf7bc,0xf492fb4f,0x978bbda7,0xa047985d,0xa6c8a5ce, 0xa9e6a857,0xad2babb6,0xb0d9af27,0xb481b2c6,0xb7e9b653,0xbb6db9b4,0xbf0ebd48,0xc28dc0d8, 0xc5fec44d,0xc975c7c2,0xccd2cb26,0xd03cce89,0xd388d1e8,0xd6ccd528,0xda09d86a,0xdd40dba8, 0xe058deca,0xe367e1db,0xe659e4de,0xe954e7d6,0xec37eac1,0xeefeed98,0xf1c7f058,0xf47ef31e, 0xf737f5d6,0xf9c8f879,0xfc4cfb05,0xfeb5fd76,0x0104ffd7,0x03490225,0x05710456,0x0795067e, 0x09ad089d,0x0bbd0aa5,0x0dc30cb8,0x0fa60eac,0x119a1095,0x1373127d,0x1519143d,0x16c715e4, 0x18761795,0x1a191938,0x1bbe1ae1,0x1d551c78,0x1ee91e14,0x20801fa9,0x221f2148,0x23aa22d3, 0x253d2468,0x26d025f9,0x2860278c,0x29e82914,0x2b6f2aa0,0x2d022c22,0x2e8f2dbd,0x300c2f40, 0x318730ba,0x3323323c,0x34a333ce,0x362a3551,0x379136d2,0x391d3842,0x3aab39da,0x3c393b5b, 0x3d883ca5,0x3f0d3e02,0x40603f7f,0x41b84126,0x42b942a6,0x443d43d1,0x44dd44b7,0xea442534, 0xe5b3dbe8,0xebb3e8fe,0xeca6eab8,0xeefced23,0xf192ef9c,0xf461f2a1,0xf683f542,0xf88df645, 0xfa09f8f8,0x9c52cedc,0x9d61966b,0xa60da4b5,0xa8dea7b8,0xac36ab00,0xaff7ae6b,0xb3a2b20a, 0xb708b598,0xba89b8ea,0xbe1cbc77,0xc1adc00d,0xc508c381,0xc87cc6db,0xcbddca4b,0xcf42cda8, 0xd28ad0fe,0xd5c9d436,0xd907d777,0xdc41dab8,0xdf55dddd,0xe267e0f3,0xe563e3f0,0xe85be6ea, 0xeb43e9dd,0xee0aecb3,0xf0c9ef7a,0xf387f230,0xf62df4e0,0xf8d2f789,0xfb55fa19,0xfdc7fc8f, 0x0020fefb,0x02620141,0x048f037a,0x06b10598,0x08c107bb,0x0ad209c4,0x0cd10bd6,0x0ebf0dcf, 0x10aa0fb4,0x1286119a,0x14371360,0x15d71507,0x178116a7,0x1929184e,0x1acd19f4,0x1c5b1b92, 0x1de91d1c,0x1f7f1eab,0x21172045,0x22a621d8,0x2433235c,0x25c124ed,0x27582686,0x28e02813, 0x2a652995,0x2bec2b16,0x2d822ca8,0x2f052e3b,0x307a2fb0,0x31f9311f,0x339232b2,0x35133439, 0x368c35b9,0x37f63718,0x39813895,0x3b0e3a31,0x3c723bc7,0x3dcd3cf9,0x3f6b3e51,0x41113fb5, 0x42644138,0x43514281,0x4439441f,0x3a084604,0xdc020372,0xe7f8e263,0xeb6aeb4c,0xeda0ec12, 0xf00dee7b,0xf2fcf0f3,0xf5a5f3ac,0xf766f61b,0xfad1f772,0xa4e9df07,0x9aa89519,0xa559a2f3, 0xa803a6e9,0xab4aaa19,0xaf06ad73,0xb2bdb131,0xb623b4c0,0xb98bb805,0xbd2abb92,0xc0b3bf1e, 0xc415c299,0xc771c5f0,0xcad3c94f,0xce45ccb4,0xd187d010,0xd4b2d33e,0xd7f4d678,0xdb37d9ba, 0xde55dced,0xe15fdff8,0xe45be2f9,0xe75be5fb,0xea41e8ed,0xed0bebc2,0xefcdee85,0xf289f149, 0xf52ff3f4,0xf7d6f697,0xfa5bf92f,0xfcd0fba9,0xff3bfe1a,0x01820074,0x03aa02b1,0x05cc04cf, 0x07dd06ef,0x09ef08f7,0x0bf40b06,0x0ddb0cfc,0x0fc40ee8,0x11a210ce,0x13591294,0x14fd1441, 0x169915da,0x1839177b,0x19df191e,0x1b701abf,0x1cf81c48,0x1e8d1dd1,0x20191f67,0x21ab20fb, 0x232f2286,0x24bc2400,0x265a259f,0x27e92732,0x296728b8,0x2ae52a38,0x2c752bbb,0x2e082d4f, 0x2f7f2ed5,0x30e83040,0x327a31b8,0x3408335b,0x357a34d1,0x36ea3647,0x386037a8,0x39fd392c, 0x3b803ac8,0x3cac3c39,0x3e083d80,0x3fa73f23,0x4149409d,0x42c041d4,0x440842cc,0x45354441, 0x208e4459,0xdd77e706,0xea12e6a8,0xebecec49,0xee76edb6,0xf100eff6,0xf3e7f282,0xf6d8f50e, 0xf983f726,0xb182eba8,0x97e294ac,0xa48fa04f,0xa719a5bf,0xaa61a8db,0xadf7ac1b,0xb1bbafe9, 0xb52db395,0xb877b6d0,0xbc0eba4f,0xbfa2bdf4,0xc307c16a,0xc65cc4c5,0xc9b2c816,0xcd24cb73, 0xd07acee4,0xd39cd223,0xd6d9d54c,0xda18d886,0xdd3fdbc5,0xe052ded8,0xe34ae1e1,0xe641e4d7, 0xe937e7d3,0xec01eab7,0xeec0ed74,0xf184f037,0xf427f2ea,0xf6c5f589,0xf958f828,0xfbd0faa7, 0xfe43fd1b,0x0099ff8b,0x02d101d1,0x04f103ef,0x07060613,0x090d081d,0x0b1e0a33,0x0d060c2f, 0x0eef0e0f,0x10cc0ff8,0x128711c5,0x1429136d,0x15c51511,0x175e16a7,0x19051848,0x1a9b19ea, 0x1c1e1b74,0x1da41cf4,0x1f3a1e8a,0x20c22015,0x224a21a7,0x23c82327,0x256024aa,0x26f22648, 0x287027d7,0x29ea294a,0x2b742ac9,0x2cf92c53,0x2e892dec,0x2feb2f63,0x315f30c3,0x32fe3248, 0x347333ec,0x35d93548,0x373e36c3,0x38be382a,0x3a5c39bf,0x3bcd3b43,0x3cf23c7b,0x3e7b3de1, 0x3fd73fa3,0x4136412f,0x427b4292,0x4425437c,0x465e4488,0xfeae379e,0xe3bddc03,0xec6be8ef, 0xed53ec7c,0xefb5eec3,0xf1fcf140,0xf4cef40b,0xf82df70e,0xc170f438,0x95c2969d,0xa3f89d6c, 0xa6a8a4f0,0xa9dea7d9,0xad48ab21,0xb107aeda,0xb496b2a1,0xb7c1b5eb,0xbb49b951,0xbed4bce8, 0xc23ec069,0xc590c3c1,0xc8d7c71b,0xcc3dca61,0xcf9ecdda,0xd2c8d11e,0xd5f3d446,0xd92ed777, 0xdc60dab8,0xdf6dddd4,0xe264e0e0,0xe55ae3d3,0xe848e6c5,0xeb1ce9ab,0xedd8ec71,0xf094ef2a, 0xf33ef1e7,0xf5dcf487,0xf865f71d,0xfaebf9a4,0xfd56fc16,0xffc1fe88,0x020200d9,0x04210310, 0x063b052c,0x08390738,0x0a46093d,0x0c370b42,0x0e170d27,0x0ff70f05,0x11ac10d8,0x13571284, 0x14f41427,0x168b15bf,0x18221756,0x19be18fa,0x1b481a88,0x1cc81c0c,0x1e591d8c,0x1fdd1f25, 0x216820a4,0x22eb222f,0x246c23ad,0x25fd2538,0x278526c9,0x28f72846,0x2a7e29c5,0x2bfb2b46, 0x2d8f2cd1,0x2f032e58,0x306c2fbe,0x31f03136,0x338532ce,0x34e73446,0x365b35a6,0x37b93715, 0x39453895,0x3abf3a28,0x3c163b90,0x3d723cae,0x3f243e34,0x407a3fa7,0x41b7413e,0x42b142b1, 0x442e4437,0x435e45ab,0xe4a21c15,0xe7e4df79,0xed78ebf0,0xeee9ed9d,0xf105f035,0xf371f2ab, 0xf669f60b,0xd2bef935,0x93439c48,0xa2699a30,0xa5d7a415,0xa8f4a6ce,0xac46aa09,0xafdeadbe, 0xb393b17a,0xb6c2b4e4,0xba25b831,0xbdb3bbbb,0xc129bf43,0xc46fc293,0xc7c0c5f5,0xcb13c93a, 0xce7ecca6,0xd1b4cff7,0xd4d5d326,0xd812d651,0xdb3fd98f,0xde57dcb0,0xe158dfc3,0xe449e2b5, 0xe735e5ac,0xea0fe88c,0xecd2eb5e,0xef88ee16,0xf239f0ca,0xf4daf377,0xf764f608,0xf9e6f891, 0xfc5afb19,0xfecbfd83,0x0117ffdf,0x034f0231,0x0560044d,0x076d0660,0x0972085e,0x0b6a0a60, 0x0d4c0c49,0x0f250e2a,0x10e10ff5,0x129211a8,0x142a134a,0x15c414ed,0x17561681,0x18f31817, 0x1a8019ad,0x1c021b34,0x1d881cb8,0x1f1a1e45,0x209d1fc8,0x2221214f,0x239f22d2,0x25232452, 0x26af25dd,0x28302764,0x29a628d7,0x2b252a52,0x2cab2bdb,0x2e292d62,0x2fa12edb,0x3112304d, 0x329931ca,0x341d334f,0x358334c0,0x36f13629,0x385e378b,0x39de390f,0x3b433a8a,0x3c773bf1, 0x3dea3d2c,0x3f873ea8,0x411b3ff7,0x427c414e,0x43a34297,0x44ac4473,0x345d46be,0xdc95fa6a, 0xea63e5ee,0xed97ee31,0xefcdef3b,0xf20cf175,0xf512f436,0xe2a7f8dd,0x9202a74c,0x9fac970d, 0xa4b8a34c,0xa7e1a609,0xab12a933,0xaec1accc,0xb260b073,0xb5a4b3f1,0xb905b736,0xbc7cbaad, 0xbff6be27,0xc342c18c,0xc694c4d6,0xc9e5c824,0xcd46cb85,0xd085ced8,0xd3bbd215,0xd6e9d542, 0xda1ed877,0xdd3adba2,0xe03fdeb4,0xe32be1ae,0xe61ee49c,0xe8f5e77f,0xebbfea53,0xee79ed0d, 0xf123efc6,0xf3ccf26b,0xf65bf508,0xf8dff78f,0xfb61fa13,0xfdd1fc91,0x0027fef4,0x027b0146, 0x04980380,0x069d0591,0x08a70794,0x0a9e0997,0x0c7b0b83,0x0e620d60,0x101b0f37,0x11c810eb, 0x136b128e,0x1504142c,0x169f15c7,0x18311762,0x19c718f2,0x1b511a85,0x1cd71c02,0x1e5c1d92, 0x1fdc1f14,0x215f2095,0x22e02212,0x245b239a,0x25da2510,0x2754268d,0x28d4280e,0x2a452989, 0x2bc82afd,0x2d412c7c,0x2ec72dfc,0x30412f78,0x31b330ef,0x33363268,0x34ac33ee,0x360f3551, 0x377536bf,0x38dc3820,0x3a4d3987,0x3bb63ae4,0x3ce23c52,0x3e263d8f,0x3f983f27,0x411e4085, 0x42af41d9,0x445842f1,0x45f14457,0x1735422b,0xe0ebe2d5,0xecf5e8e5,0xee60ee51,0xf0b7efc3, 0xf368f22e,0xed7cf658,0x93e8b5c1,0x9cf3950e,0xa3b5a23b,0xa700a571,0xaa2ca8b3,0xadd6ac22, 0xb17aafc4,0xb4afb324,0xb81bb668,0xbb8fb9df,0xbeedbd44,0xc23dc096,0xc593c3ee,0xc8ddc733, 0xcc3bca90,0xcf73cddd,0xd2b8d116,0xd5f1d454,0xd915d780,0xdc37daa2,0xdf3fddbc,0xe239e0b5, 0xe526e3ac,0xe7f3e687,0xeab4e94b,0xed78ec0c,0xf01eeec6,0xf2c6f168,0xf555f40f,0xf7dbf68d, 0xfa54f912,0xfcdefb95,0xff32fe01,0x01880050,0x03c102a9,0x05cc04c3,0x07ce06c2,0x09c408c8, 0x0ba20aad,0x0d840c8d,0x0f480e64,0x10ed100c,0x128811b2,0x142a134d,0x15c414eb,0x1759168d, 0x18e3180f,0x1a72199e,0x1bfc1b30,0x1d821cb8,0x1efa1e30,0x207a1fad,0x21f5212a,0x237822b2, 0x24e32420,0x26582593,0x27dd2707,0x294f288b,0x2ac329f9,0x2c3b2b7c,0x2db62ce6,0x2f462e78, 0x30be2ff7,0x3223315e,0x33b032d0,0x35123459,0x368435b7,0x37d03727,0x3922386d,0x3a9539cc, 0x3c0e3b3b,0x3d163c5e,0x3e883d98,0x3fca3f25,0x413a40c1,0x428b424c,0x44414384,0x4676445a, 0xf69730cf,0xe71fdd2b,0xef1deb24,0xf006edfc,0xf2a6f03c,0xf378f36f,0x9732c610,0x9ade93c8, 0xa29fa155,0xa601a473,0xa960a805,0xacefab69,0xb08aaeef,0xb3b0b25e,0xb703b568,0xba7db8e0, 0xbdcebc3e,0xc108bf7d,0xc461c2c1,0xc79fc610,0xcb09c964,0xce3bccb8,0xd174cfe1,0xd4b3d31f, 0xd7f2d668,0xdb02d97b,0xde13dc97,0xe106df8f,0xe3fde280,0xe6c8e568,0xe987e82d,0xec46eae4, 0xeefaeda8,0xf19af04e,0xf439f2f3,0xf6bbf579,0xf93ff7f7,0xfbc4fa84,0xfe33fd04,0x007fff58, 0x02d901ae,0x04fe03e9,0x070105fa,0x090407fd,0x0add09e9,0x0cbb0bc6,0x0e890da4,0x102d0f51, 0x11cd10f3,0x136d1299,0x150a1437,0x16b215d7,0x18361770,0x19c318f4,0x1b5c1a84,0x1ced1c1c, 0x1e661da1,0x1fe21f17,0x215d2090,0x22e12211,0x2452238b,0x25b124f1,0x272b2655,0x28ac27de, 0x2a1d2950,0x2b912ac1,0x2cfa2c33,0x2e922dae,0x301f2f46,0x317e30ba,0x32ef3214,0x347a339e, 0x35dd350e,0x373a3672,0x386f37b0,0x39c038f1,0x3b3e3a65,0x3c653bcc,0x3d8e3cab,0x3f1e3df2, 0x40a33f48,0x421140f4,0x43124280,0x443e43f0,0x40ee4607,0xe1f61227,0xeaaee2c1,0xef96edf8, 0xf1afef0f,0xf588f1a9,0x9dead592,0x97e09161,0xa1e7a07d,0xa45ea34f,0xa820a6d2,0xabd8aa5b, 0xaf5fade7,0xb294b151,0xb5aab447,0xb930b7a4,0xbc8bbb17,0xbfb2be52,0xc2f4c172,0xc641c4cb, 0xc9aac818,0xccf2cb7e,0xd015cea1,0xd35fd1db,0xd6aad52f,0xd9c7d859,0xdcdedb6a,0xdfcade6f, 0xe2c6e165,0xe5a1e452,0xe85ae717,0xeb0ee9c5,0xedcfec87,0xf06eef35,0xf312f1d5,0xf59bf467, 0xf81bf6ef,0xfaacf974,0xfd1ffbf7,0xff81fe64,0x01e100b9,0x041a0316,0x06300537,0x082b073d, 0x0a0d0933,0x0bea0b06,0x0dba0cea,0x0f620ea0,0x10fd1038,0x129f11dd,0x14411375,0x15e5151e, 0x177516b9,0x19001845,0x1a9519d2,0x1c2e1b6e,0x1db11cf8,0x1f241e75,0x20991fe7,0x221a2163, 0x238d22d7,0x24e32448,0x264e259a,0x27cc2710,0x2941288a,0x2aac29fd,0x2c132b60,0x2d9b2cd7, 0x2f3a2e6c,0x30ae2ffc,0x32063154,0x337e32c1,0x350a3446,0x365d35b2,0x378e36fc,0x38be3814, 0x3a34395f,0x3b7e3adb,0x3c643c05,0x3d893cf3,0x3f283e5f,0x40e63fc6,0x426b4135,0x43784240, 0x44fa4405,0x2d384689,0xdeacf267,0xecbee85b,0xefadefa3,0xf40ef0d9,0xa952e387,0x94ff908c, 0xa23d9dce,0xa3d3a33a,0xa72ca5a3,0xab27a967,0xaebdad34,0xb1edb095,0xb4ecb37f,0xb83cb6a6, 0xbbafba23,0xbec9bd65,0xc1edc070,0xc532c3ac,0xc88fc6fd,0xcbe1ca58,0xcf0acd8f,0xd23ed0bb, 0xd592d402,0xd8bed749,0xdbccda63,0xdebbdd5e,0xe1b6e053,0xe497e344,0xe74be60e,0xe9f2e8b4, 0xecaaeb68,0xef5bee21,0xf1f1f0be,0xf47ff34b,0xf704f5d7,0xf990f85e,0xfc0bfaef,0xfe7bfd5b, 0x00d5ffc4,0x03280224,0x05570456,0x075e0679,0x093b0866,0x0b180a45,0x0ceb0c1e,0x0e9b0ddf, 0x10350f7e,0x11d0111a,0x137012bd,0x151c1458,0x16b61608,0x18431794,0x19d61922,0x1b761abc, 0x1cf91c53,0x1e7d1dd7,0x1fe41f4b,0x216b20c3,0x22d42239,0x243b23a7,0x258424f7,0x26f9265c, 0x286e27d3,0x29dc2949,0x2b332aa6,0x2cb42c13,0x2e4d2d9f,0x2fd62f40,0x313730ab,0x32a0320d, 0x3424337b,0x35933516,0x36ba3655,0x37ce377b,0x391f389a,0x3a7439fb,0x3b9a3b28,0x3c5d3c2d, 0x3da63d32,0x3f1e3eea,0x40ba408a,0x41e541d4,0x43e642bb,0x46794470,0x0d5f3f39,0xe453e0f5, 0xef27eb62,0xf1a3f054,0xb86fecdb,0x920c91ee,0xa0f09aa2,0xa446a279,0xa66da4c6,0xaa4da7d0, 0xae10ac01,0xb13caf94,0xb415b27a,0xb742b58a,0xba97b8c5,0xbdcabc26,0xc0c7bf27,0xc3ebc23f, 0xc748c580,0xca99c8ea,0xcdcccc25,0xd0f4cf52,0xd442d289,0xd77ed5e1,0xda9cd907,0xdd85dc0c, 0xe07cdef5,0xe365e1f3,0xe61fe4c3,0xe8c2e76f,0xeb78ea19,0xee17ecc8,0xf0c6ef6e,0xf34cf20b, 0xf5dcf493,0xf86ef726,0xfafaf9b9,0xfd65fc33,0xffd8fea4,0x023a0105,0x04750363,0x069c0595, 0x08840799,0x0a650978,0x0c350b56,0x0deb0d1c,0x0f8b0ec8,0x1127105b,0x12c111fd,0x146b139e, 0x1610154e,0x17b116e7,0x19431884,0x1ae11a19,0x1c741bbf,0x1df91d42,0x1f6f1ec8,0x20e2202e, 0x225621b0,0x23b42310,0x2506246f,0x265e25be,0x27c92725,0x29402896,0x2a932a00,0x2bfe2b5a, 0x2d882cd9,0x2f222e6b,0x308c2ff3,0x31f4315f,0x335232b2,0x34e23437,0x361735a8,0x372636bf, 0x384537d7,0x397b3913,0x3aa13a41,0x3bab3b5c,0x3c8a3c1b,0x3e1e3d5c,0x3f823eff,0x40a5409a, 0x41e64200,0x43fd43c6,0x4622456b,0xeef12988,0xe960e05d,0xf104eeac,0xc93ff13b,0x9036966b, 0x9f529719,0xa347a156,0xa666a4c9,0xa91ba6eb,0xad3aaabc,0xb0a5aeb1,0xb34bb1a6,0xb668b48c, 0xb982b7c1,0xbcb8baee,0xbfbebe10,0xc2c9c118,0xc5ffc42a,0xc965c78e,0xcc87cad4,0xcfbfce01, 0xd2ffd13b,0xd642d486,0xd96bd7bb,0xdc66dad8,0xdf4addb2,0xe23ee0b3,0xe4fee38b,0xe7a6e63a, 0xea51e8df,0xececeb8c,0xef96ee2a,0xf227f0d3,0xf4b1f359,0xf749f5e9,0xf9def884,0xfc50fb0a, 0xfec9fd81,0x0137fff1,0x038a025b,0x05c6049e,0x07ca06c5,0x099f08a6,0x0b820a85,0x0d2e0c4f, 0x0ed90dfc,0x10720f96,0x12131135,0x13b512d4,0x1562147e,0x17011622,0x189f17c1,0x1a3a1968, 0x1bd51aff,0x1d6b1c94,0x1ee11e1e,0x20511f93,0x21c32103,0x23242273,0x247323bf,0x25ca2518, 0x271a2663,0x288927cb,0x29e92933,0x2b442a8c,0x2cc62bfc,0x2e552d8a,0x2fd62f0d,0x314a3094, 0x329f31e9,0x34133357,0x357834ca,0x367c35fc,0x37a53709,0x38b03822,0x39bf392c,0x3ac83a5a, 0x3ba13b59,0x3cd33c27,0x3e873d91,0x3fd53ee8,0x41524037,0x42be4208,0x444c4434,0x3ca74726, 0xe05908ff,0xec94e746,0xd8eff382,0x8ebe9f7c,0x9d159440,0xa232a00c,0xa5dda380,0xa85da730, 0xabd1a9cf,0xafb3adc4,0xb288b10c,0xb56fb3d0,0xb88bb6df,0xbb8cb9f1,0xbe99bcfe,0xc19cc007, 0xc4a8c303,0xc809c646,0xcb3cc999,0xce69ccb6,0xd1b3cff8,0xd4e7d33c,0xd820d670,0xdb33d9a2, 0xde17dc96,0xe106df7f,0xe3cce260,0xe674e514,0xe921e7bb,0xebb7ea5e,0xee51ecf2,0xf0f2ef95, 0xf37ef22b,0xf60ef4b5,0xf8b0f752,0xfb2cf9e5,0xfda6fc60,0x001ffed8,0x028a0149,0x04d7039f, 0x06f805df,0x08df07e3,0x0abf09bf,0x0c770b94,0x0e1c0d3f,0x0fb70ed8,0x11551079,0x12ff121b, 0x14a813c3,0x164d156f,0x17f31716,0x19a618b9,0x1b431a69,0x1cd31bfa,0x1e641d94,0x1fd51f13, 0x21422088,0x22a621ea,0x23f12341,0x254c248f,0x269125ea,0x27f3272e,0x29502899,0x2abd29f7, 0x2c2a2b62,0x2dbb2ce9,0x2f2b2e64,0x30c52feb,0x322a3173,0x339032d1,0x34ec3431,0x3621358c, 0x372f3696,0x384e37c1,0x392c38a2,0x3a4039a0,0x3b3b3aa5,0x3c0e3bac,0x3d543cb2,0x3eb33e43, 0x405a3f5d,0x4256411e,0x441e4285,0x45e644a3,0x25364622,0xe1e9ecdb,0xe4a5ed77,0x8e0cad89, 0x99929154,0xa0249ed9,0xa404a20c,0xa7eea5d4,0xaa7da937,0xae34ac46,0xb156affa,0xb43cb2d4, 0xb74ab5c5,0xba3fb8c9,0xbd22bba4,0xc040beb3,0xc33dc1b6,0xc67cc4d9,0xc9b4c818,0xccf5cb53, 0xd03ece8c,0xd37dd1e2,0xd6abd505,0xd9dbd844,0xdcd5db59,0xdfbdde42,0xe28ce122,0xe53ce3e2, 0xe7e0e680,0xea88e937,0xed1cebc3,0xefafee64,0xf246f0f3,0xf4d9f388,0xf77df622,0xfa0bf8bc, 0xfc89fb44,0xff09fdc7,0x01840037,0x03d902a9,0x061504f9,0x0814070f,0x09fc0902,0x0bbc0ad9, 0x0d600c86,0x0ef40e1f,0x10930fb9,0x123e115d,0x13e3130d,0x158a14b2,0x173b165b,0x18e91804, 0x1a9c19bc,0x1c271b58,0x1dc21ceb,0x1f441e74,0x20ba1ffa,0x220c2156,0x236022b0,0x24ae23f2, 0x25fe254d,0x2743268e,0x289727e2,0x29f92937,0x2b6d2aae,0x2cef2c22,0x2e672da1,0x2ff52f14, 0x317d30b1,0x32e53226,0x34313381,0x357334c1,0x368c35f8,0x37ac3707,0x386e380c,0x395738cf, 0x3a5639c1,0x3b763ac0,0x3c4c3bb1,0x3d9e3cd5,0x3ecf3e30,0x40cf400c,0x428e41ec,0x44cc435c, 0x47d244b2,0x05153a99,0xe611e189,0x925fba90,0x96b08f1c,0x9f139d8e,0xa256a0f1,0xa660a4e4, 0xaa75a8ea,0xad12ab99,0xb066aecf,0xb376b1ff,0xb665b4ff,0xb950b7ed,0xbc0dbaca,0xbf09bd87, 0xc216c09f,0xc541c3ac,0xc85bc6da,0xcb9ec9fc,0xcee2cd45,0xd238d096,0xd556d3c9,0xd88fd6f4, 0xdb9cda14,0xde93dd1d,0xe154dff8,0xe409e2b7,0xe6b0e55b,0xe95be805,0xebe5ea97,0xee74ed2d, 0xf107efb6,0xf3a0f250,0xf643f4ec,0xf8dbf78d,0xfb66fa1d,0xfde9fca2,0x0062ff23,0x02de0198, 0x051d03f8,0x07370627,0x093b0831,0x0b000a1c,0x0ca40bc5,0x0e3b0d66,0x0fd90f01,0x117b10a5, 0x132e124f,0x14ce13f6,0x167a1597,0x183c1750,0x19ed1909,0x1b8d1ab5,0x1d201c4f,0x1eb11dda, 0x20341f67,0x218d20d7,0x22d72223,0x242a236a,0x257024bb,0x26b62602,0x27f22746,0x294c2880, 0x2ac829f5,0x2c412b74,0x2dad2ce1,0x2f2f2e57,0x30bc2fde,0x3247316d,0x339832dd,0x34b53405, 0x35f53531,0x37123669,0x37e5375b,0x389e3819,0x396c38d7,0x3a8639d3,0x3b9d3aec,0x3c783bac, 0x3de13c9a,0x3fbe3e42,0x418d4050,0x4314423d,0x44eb43e7,0x463745d3,0xecc4211f,0x945bc1a6, 0x94f98d6e,0x9e7e9be5,0xa15e9fed,0xa524a369,0xa974a7a7,0xacbbabea,0xaf37ae22,0xb292b10b, 0xb5a7b452,0xb86fb732,0xbb28b9f1,0xbde4bca2,0xc0ebbf82,0xc418c29d,0xc71dc5b7,0xca39c8bc, 0xcd8acbfa,0xd0e1cf4e,0xd415d293,0xd731d5b5,0xda47d8cc,0xdd5fdbec,0xe031dedd,0xe2dbe198, 0xe57fe43a,0xe825e6e4,0xeab8e97f,0xed44ec0e,0xefc7ee8d,0xf260f119,0xf504f3bc,0xf79af659, 0xfa2df8ec,0xfcb8fb84,0xff3efe05,0x01bd007c,0x041502fc,0x063f0535,0x08540757,0x0a38095a, 0x0bda0b16,0x0d790cb4,0x0f140e4a,0x10b40fe6,0x126c1196,0x1407133e,0x15b714da,0x17721695, 0x19321855,0x1ad91a08,0x1c751baf,0x1df91d3f,0x1f961ed3,0x20fa2051,0x224221a1,0x238f22e1, 0x24da2433,0x26202578,0x275c26c3,0x289c27ec,0x2a0d2947,0x2b9d2aca,0x2cf92c43,0x2e742da7, 0x2ff52f34,0x319530b8,0x33083253,0x3425338b,0x354834a0,0x369f35e6,0x37703703,0x384337c7, 0x38ea3870,0x39ef393a,0x3b173a6b,0x3be83b8e,0x3cbe3c0d,0x3edb3d85,0x40e33f58,0x42d94129, 0x442042af,0x45fb44a3,0x3af04814,0x947bede0,0x8f228657,0x9d099ab6,0x9f929e99,0xa325a1a7, 0xa789a559,0xabc6a9ad,0xade8ad75,0xb0a2af47,0xb42db2c0,0xb71db5eb,0xb9c6b8a0,0xbc8bbb4b, 0xbf58be0d,0xc2a4c11e,0xc5afc458,0xc8b1c74c,0xcbf8ca6f,0xcf60cdcd,0xd298d11b,0xd5c6d452, 0xd8cbd763,0xdbf6da7b,0xdef3dd97,0xe19fe06d,0xe441e307,0xe6f8e5ba,0xe993e85c,0xec2aeafe, 0xeea8ed80,0xf13af00d,0xf3e8f2a8,0xf683f557,0xf912f7dc,0xfba1fa74,0xfe2bfcfa,0x009dff7f, 0x031c01f9,0x05480453,0x07720674,0x09720894,0x0b2a0a6b,0x0cc10c0e,0x0e630dac,0x0ffe0f47, 0x11b310e9,0x1352129f,0x14f61435,0x16a115e2,0x1865179b,0x1a0e1954,0x1bb51aff,0x1d371c8e, 0x1ecd1e17,0x204f1fac,0x219b2113,0x22df2251,0x243723a5,0x258024ef,0x26cc2647,0x27ed2776, 0x295528b8,0x2ae02a30,0x2c532bbe,0x2dad2d16,0x2f392e92,0x30bd300e,0x325a31b2,0x338c3318, 0x34a03432,0x35f6355d,0x370d36c1,0x37dc3792,0x38913867,0x39753916,0x3ab63a31,0x3bd43b63, 0x3c373c3d,0x3dce3d20,0x3faa3f40,0x41ab4108,0x432a429e,0x450643b2,0x48ff459f,0xded83e3a, 0x83d98715,0x9c369373,0x9e579e11,0xa185a014,0xa564a373,0xa9d0a79d,0xadb5abca,0xaf45ae35, 0xb2b4b0c4,0xb605b472,0xb8c4b776,0xbb78ba16,0xbe4abcec,0xc16fbfbe,0xc4aec319,0xc794c61d, 0xcab2c91d,0xce21cc64,0xd15dcfd4,0xd495d2fd,0xd79cd621,0xdabbd924,0xddcddc4a,0xe09edf47, 0xe33ae1f1,0xe5f4e49d,0xe899e752,0xeb3ee9f0,0xedbdec8d,0xf044ef07,0xf2e6f197,0xf58af44b, 0xf811f6dc,0xfa9cf960,0xfd25fbed,0xff9cfe6c,0x021100e0,0x0462034f,0x0682057c,0x089507a8, 0x0a710997,0x0c120b4f,0x0dad0cea,0x0f420e8b,0x10f41028,0x129811dd,0x14301370,0x15d7150f, 0x179216c7,0x193a187f,0x1ae21a1e,0x1c6c1bbb,0x1df81d43,0x1f881ed1,0x20e42054,0x222e21a0, 0x238522ed,0x24d52446,0x262c259c,0x276726e3,0x28a82817,0x2a26297c,0x2bac2b0d,0x2d092c77, 0x2e7d2de2,0x2ffa2f5c,0x319930ee,0x32f73275,0x341233ad,0x354e34cb,0x369e3631,0x3783374a, 0x38563823,0x392238f6,0x3a4239ed,0x3b873b35,0x3c523c3e,0x3d503ce5,0x3f2d3e88,0x40ca4084, 0x42294275,0x435243f4,0x46234585,0x1c5c4671,0x99bcd88a,0x952c85bc,0x9eb29a6f,0xa0419e26, 0xa3a4a132,0xa78da530,0xab9ba993,0xae8cad33,0xb0dcaf20,0xb47eb258,0xb794b5e1,0xba3bb8b5, 0xbd15bb7d,0xc011be63,0xc369c193,0xc66cc4ce,0xc974c7c6,0xccbccaec,0xd012ce50,0xd345d195, 0xd663d4be,0xd968d7ca,0xdc8bdae3,0xdf77dded,0xe22be0c3,0xe4dde367,0xe788e629,0xea37e8d2, 0xecc8eb75,0xef4bedf8,0xf1e0f083,0xf488f325,0xf715f5ca,0xf99cf850,0xfc25fad1,0xfe9ffd56, 0x010cffc7,0x0362023a,0x059d047a,0x07b906a5,0x09ab08b0,0x0b660a84,0x0d080c2c,0x0ea40dce, 0x10470f67,0x11f4111a,0x138c12bc,0x152e1452,0x16dd15f9,0x188617b0,0x1a2b1955,0x1bbc1af5, 0x1d511c80,0x1ed01e0c,0x204c1f8e,0x219e20f6,0x22fa2245,0x244a23a4,0x25ac2502,0x26e62649, 0x28362793,0x299a28e9,0x2b1c2a63,0x2c8f2bda,0x2dfc2d43,0x2f732eb3,0x31013040,0x327931c4, 0x33b23323,0x34e83457,0x363335a5,0x375d36d2,0x383c37e6,0x392538bc,0x3a2939b8,0x3b683adf, 0x3c513c1d,0x3d623d00,0x3ecb3e2d,0x40ba3fcf,0x421d4198,0x434f4321,0x448f44e5,0x2aa948c7, 0xe12ff45b,0x900db9b4,0x992690f9,0x9f4d9d34,0xa1bc9f6d,0xa570a304,0xa975a6f3,0xaccdaae3, 0xaf67ae6a,0xb24cb08b,0xb5e8b40d,0xb8d4b73c,0xbba6ba1b,0xbea4bcf6,0xc1d1c021,0xc500c34f, 0xc81ac676,0xcb3ac989,0xce8bcccc,0xd1d4d01a,0xd4efd34f,0xd804d666,0xdb1bd980,0xde20dc85, 0xe0f1df7b,0xe3afe240,0xe663e4f5,0xe916e7aa,0xebb9ea59,0xee45ecef,0xf0d6ef7b,0xf37af21a, 0xf60bf4b0,0xf88ff73f,0xfb11f9cb,0xfd8dfc42,0xfffdfeba,0x026c0128,0x049e036f,0x06d005ab, 0x08d007c3,0x0aa409af,0x0c580b78,0x0df50d1c,0x0f9d0ebc,0x11461066,0x12e01204,0x147913a0, 0x16231540,0x17cf16ed,0x1972188b,0x1b061a31,0x1c991bc0,0x1e1c1d53,0x1f981ecf,0x21022046, 0x226b21a1,0x23b22306,0x251d2457,0x266825ba,0x27bc26fc,0x291d285f,0x2a9129cb,0x2bff2b39, 0x2d7d2caf,0x2edd2e23,0x30742f99,0x31df3123,0x333f3282,0x348c33d6,0x35d2352a,0x36ec364c, 0x3820378e,0x39033886,0x3a263988,0x3b433a9b,0x3c4c3bcb,0x3d763cbc,0x3eb33e42,0x401c3f69, 0x41c8413a,0x43364268,0x44c743f4,0x38954757,0xe4e2ff4a,0xd9bde977,0x8d49a31c,0x9bcb968d, 0x9fa59f90,0xa310a199,0xa6e5a516,0xaa88a8af,0xae57ac2d,0xb084af94,0xb3bdb205,0xb724b593, 0xba27b8ba,0xbd11bb8d,0xc051beb7,0xc358c1cd,0xc6a0c4ff,0xc9c6c82f,0xccfacb61,0xd040ce8f, 0xd36ed1e0,0xd685d4f2,0xd9aad81b,0xdc9edb1a,0xdf93de18,0xe267e0f5,0xe51ee3c5,0xe7dbe670, 0xea8be934,0xed21ebd1,0xefc0ee6a,0xf260f107,0xf4e8f3a0,0xf783f629,0xfa03f8b8,0xfc7bfb37, 0xfef0fdab,0x01520017,0x03970277,0x05d804b3,0x07e506df,0x09ce08d3,0x0b990aad,0x0d440c68, 0x0eed0e0d,0x10930fbb,0x122d1158,0x13d112f6,0x156c1490,0x17171638,0x18af17d2,0x1a461972, 0x1bd81b03,0x1d6e1ca1,0x1edc1e16,0x20491f84,0x21b920fa,0x23152261,0x247623bc,0x25cb251b, 0x2719265e,0x288d27c5,0x29f92938,0x2b4b2a90,0x2cd72bfd,0x2e3d2d7e,0x2fbb2ee8,0x312d306d, 0x327931c5,0x33e2331d,0x35443484,0x364a35b7,0x378a36ce,0x38993809,0x39b63908,0x3add3a3d, 0x3bd43b49,0x3cfb3c21,0x3ea73da7,0x3f963efa,0x410c4035,0x424441a7,0x43ea430a,0x414945b8, 0xe6e90e63,0xee25e529,0xbe1eed28,0x93609137,0x9f7b9afd,0xa1d5a125,0xa557a3ea,0xa891a751, 0xac6eaab0,0xb04eae92,0xb262b125,0xb5ceb3fb,0xb927b792,0xbc1abaac,0xbf58bdaf,0xc25dc0e4, 0xc580c3d9,0xc8d4c730,0xcc00ca6b,0xcf1dcd85,0xd259d0c1,0xd569d3e2,0xd8a0d700,0xdb90da1a, 0xde77dcfc,0xe15fdfe1,0xe433e2ce,0xe6d7e57b,0xe993e835,0xec2eeadb,0xeecfed75,0xf166f016, 0xf3f0f2ac,0xf677f528,0xf907f7bb,0xfb74fa3a,0xfde0fca5,0x0044ff1b,0x02930167,0x04d203a9, 0x06f705e8,0x08df07e2,0x0abd09cb,0x0c830b9b,0x0e290d4f,0x0fd80efa,0x116e1096,0x130e122e, 0x14b013d4,0x164d1574,0x17e2170d,0x1978189f,0x1b0b1a33,0x1ca51bd0,0x1e141d5b,0x1f7d1ebf, 0x2100202c,0x226721a7,0x23d1230a,0x251f2466,0x267725b8,0x27e6271a,0x29662899,0x2aaa29f3, 0x2c202b48,0x2d9f2ccf,0x2f172e42,0x30822fb6,0x31cf3119,0x3332325b,0x34bd33e1,0x35d13533, 0x36f43635,0x38313762,0x396438a6,0x3a9d39d3,0x3b973b00,0x3c843bb9,0x3e4b3d29,0x3faf3ebb, 0x40b13fa6,0x42104097,0x439141e6,0x45bf43ef,0xebca1f8a,0xe9b7e3e3,0xf399f158,0xa040d961, 0x99168fcc,0xa1e29e85,0xa3f5a23b,0xa6cea55b,0xaa1fa858,0xae18ac5d,0xb14cb062,0xb3a7b24e, 0xb757b57e,0xba86b902,0xbdb3bc28,0xc0cfbf56,0xc3c0c257,0xc71ec574,0xca63c8d7,0xcd71cbf6, 0xd098cf0e,0xd3c0d233,0xd6e7d55d,0xd9fbd884,0xdcd4db73,0xdfc2de50,0xe2b7e150,0xe575e420, 0xe82fe6d8,0xead9e988,0xed7fec32,0xf02feede,0xf2bff181,0xf53bf404,0xf7d8f68a,0xfa58f91c, 0xfcc2fb8c,0xff30fdfc,0x01800059,0x03ca02a4,0x05fe04f0,0x07fe0705,0x09e708f4,0x0bc90adb, 0x0d8f0cb3,0x0f430e66,0x10dd1013,0x128011ab,0x14241352,0x15d114fe,0x175e1692,0x18fc182b, 0x1a8819bd,0x1c2b1b5a,0x1db71cf2,0x1f161e66,0x208f1fc4,0x2218214c,0x238322c0,0x24de2432, 0x26392579,0x27a626e6,0x2933285e,0x2a8729d8,0x2be12b15,0x2d5e2c8f,0x2ee72e0d,0x304e2f8f, 0x319830df,0x32e4322a,0x34843396,0x35c93523,0x36da3631,0x37fe3746,0x396b3888,0x3aaa39e7, 0x3bd13b18,0x3c813bd7,0x3e293d00,0x3fb93ec0,0x40dc4016,0x41a6409c,0x43754196,0x474a42ec, 0xf5fc2ea1,0xe6f1e2a6,0xf17def60,0xeb3df44b,0x9082b9de,0x9c78959d,0xa257a188,0xa4a9a386, 0xa7a4a616,0xab97a983,0xaf8bada9,0xb1d0b155,0xb4c2b347,0xb879b6e7,0xbbe0ba59,0xbef7bd96, 0xc204c09d,0xc525c3ac,0xc8a5c70a,0xcbc1ca5d,0xced5cd67,0xd1eed07f,0xd536d3af,0xd858d6e6, 0xdb45d9f7,0xde1ddcca,0xe131dfc0,0xe40ae2be,0xe6cfe590,0xe97de83c,0xec36eaf4,0xeef1eda9, 0xf193f066,0xf410f2e2,0xf6a4f56e,0xf937f802,0xfba4fa8b,0xfe14fcf5,0x0066ff58,0x02be01ac, 0x050003fb,0x070a0619,0x0902081d,0x0aef0a06,0x0cc60bed,0x0e8e0dc1,0x102d0f76,0x11cd110f, 0x137512b1,0x15261460,0x16b51602,0x1845178e,0x19d2191f,0x1b7a1aaf,0x1d021c51,0x1e711dd1, 0x1fd71f32,0x215f20af,0x22db2230,0x244a23a6,0x258d24fe,0x2704265c,0x288a27d4,0x29f6295b, 0x2b3f2aaa,0x2caf2c04,0x2e3d2d7c,0x2fb62f12,0x30f23066,0x323f31a3,0x33c43309,0x353b34a5, 0x365c35de,0x376d36fb,0x38cd3818,0x3a4d39ad,0x3b783af6,0x3c333bf3,0x3d9b3cd0,0x3f3e3e7d, 0x40ab3ffa,0x410f410f,0x422e4187,0x45a5430b,0x03a13b0d,0xe543e3a3,0xf188ec6b,0xf2f2f1e0, 0xd524f3d8,0x91699d7b,0xa0449b35,0xa33ea379,0xa5c0a4c7,0xa95aa7bc,0xad89ab85,0xb15faf68, 0xb343b252,0xb6aeb4e9,0xba73b8b3,0xbdc4bc51,0xc0b8bf4e,0xc3e8c261,0xc73ec58a,0xca92c908, 0xcdb1cc39,0xd0accf3d,0xd3eed24f,0xd71dd5a6,0xda22d8ab,0xdcffdb9d,0xdff6de83,0xe2e9e187, 0xe5cce46e,0xe86ee730,0xeb25e9da,0xedebec9d,0xf098ef56,0xf317f1ed,0xf59ff468,0xf827f6f3, 0xfaa9f981,0xfd12fbf3,0xff63fe4f,0x01be0098,0x03fa02f6,0x060d051d,0x080f0726,0x09fe0917, 0x0be10b0c,0x0dc30ce3,0x0f6b0eba,0x1109104a,0x12ab11f1,0x14591395,0x15f1153f,0x178116d1, 0x1907185a,0x1aa319eb,0x1c361b87,0x1daf1d0d,0x1f171e7b,0x20961fed,0x22192171,0x238f22f8, 0x24ea245f,0x265325b0,0x27e32739,0x294c28c0,0x2aae2a22,0x2c092b80,0x2d862cdf,0x2f1a2e76, 0x306a2ff5,0x319e3125,0x33253286,0x349a3418,0x35e93574,0x370736b4,0x383737c6,0x39d23939, 0x3b303ad8,0x3bea3bd7,0x3d363ccd,0x3eb33e58,0x40333fdd,0x410e4130,0x416c41c1,0x43c142d6, 0x13a742e7,0xe343e77f,0xf05cea7f,0xf25af146,0xf563f229,0xb5eee9da,0x98409138,0xa3549e90, 0xa46ea352,0xa772a59d,0xab0fa922,0xaefdad1a,0xb282b0d6,0xb4adb323,0xb883b63b,0xbc2cba4c, 0xbf2bbd95,0xc247c09c,0xc58dc3d8,0xc8eac724,0xcc32ca7a,0xcf23cd9c,0xd23ed094,0xd58cd3d7, 0xd8a0d70b,0xdb87da02,0xde7adcf0,0xe16edfe7,0xe467e2dc,0xe72be5c9,0xe9d6e877,0xec9deb34, 0xef5cedf8,0xf1f5f0a5,0xf47ef332,0xf702f5bd,0xf98ef841,0xfc05fad0,0xfe58fd32,0x00a4ff77, 0x030801de,0x052c0415,0x07330630,0x0930082e,0x0b1f0a24,0x0d0a0c17,0x0ee00dfd,0x107c0fb0, 0x1223114e,0x13d112fa,0x156f14a7,0x170f1640,0x189317d3,0x1a26195d,0x1bbe1af3,0x1d411c8b, 0x1eb51e03,0x20351f7e,0x21af20f9,0x233f2280,0x249c23f8,0x26012557,0x278e26cc,0x290f2866, 0x2a6429c6,0x2bda2b33,0x2d2f2c8d,0x2ecd2e13,0x303a2f9a,0x316830ec,0x32d23221,0x345433c1, 0x35a9350d,0x36fa3681,0x382037ab,0x398438ec,0x3b273a85,0x3bf93bde,0x3d393ca7,0x3ea23e47, 0x3fef3f9d,0x40e94117,0x418e41f4,0x428a42b3,0x24b745b7,0xe23eee54,0xef55e7a6,0xf164f110, 0xf2bdf208,0xf48ef3f0,0x9c0fd1e5,0x9d29939f,0xa41ba17c,0xa5dca3d3,0xa91ca6e4,0xacb4aa82, 0xb079ae70,0xb363b25a,0xb629b453,0xba43b81c,0xbd91bbd4,0xc0a8beef,0xc3f7c21f,0xc726c57e, 0xca8dc8b7,0xcdafcc16,0xd0aecf08,0xd3edd22c,0xd724d574,0xda0cd880,0xdd17db75,0xdff2de70, 0xe2fde163,0xe5e0e466,0xe89be729,0xeb53e9dc,0xee23ecb2,0xf0c6ef64,0xf361f203,0xf5e7f48f, 0xf86bf71a,0xfaf8f99d,0xfd5cfc20,0xffa1fe68,0x020b00bd,0x04300314,0x0643052b,0x08450734, 0x0a3b0934,0x0c350b23,0x0e1c0d23,0x0fcc0ee9,0x116d108f,0x1323123c,0x14c613ed,0x165e1583, 0x17f31720,0x197b18a4,0x1b121a3d,0x1ca21bcc,0x1e131d50,0x1f9f1ecb,0x21172052,0x22a021cc, 0x240f2352,0x257e24b2,0x26f82631,0x288a27b8,0x29de292a,0x2b572a93,0x2cb72c03,0x2e3a2d6a, 0x2fb02eef,0x30fc3059,0x32513199,0x33dc3319,0x35203475,0x368935d4,0x37c93726,0x39293873, 0x3a9d39da,0x3bcc3b59,0x3cd53c35,0x3e6b3dbd,0x3f993f0a,0x40a24060,0x41624156,0x420f426d, 0x327f4582,0xe232f94d,0xedc8e538,0xf1b0f07f,0xf250f12e,0xf3bef2ef,0xe91af6de,0x92d4b2f0, 0xa0039a32,0xa4aea456,0xa757a5ec,0xaab7a8f8,0xae75ac58,0xb269b034,0xb4a6b3c1,0xb821b63a, 0xbbe4ba28,0xbf27bd91,0xc25fc0b3,0xc5b7c40b,0xc8dcc730,0xcc36ca91,0xcf42cdb8,0xd25dd0ca, 0xd59ad3f7,0xd8a3d721,0xdba9da15,0xde9cdd29,0xe184e006,0xe487e303,0xe755e5e0,0xea09e8a7, 0xecd9eb6a,0xef8cee30,0xf22bf0cd,0xf4bff371,0xf746f5ff,0xf9c9f87b,0xfc43fb03,0xfe90fd5e, 0x00eaffb3,0x032c0214,0x05410433,0x074c0641,0x094f083f,0x0b420a3e,0x0d400c3a,0x0f0d0e1d, 0x10bd0fda,0x12691181,0x1418133e,0x15ab14d6,0x17471674,0x18d71801,0x1a6f199a,0x1bfb1b29, 0x1d771cb1,0x1f021e2e,0x207f1fb8,0x22032131,0x237a22b7,0x24ea2422,0x2670259f,0x27f32725, 0x2956289b,0x2ad029fe,0x2c3f2b7f,0x2db52ce8,0x2f222e5c,0x307c2fc5,0x31e8311a,0x336a3296, 0x34b333fa,0x360e354b,0x376636a3,0x38d7380e,0x3a363974,0x3b703ac9,0x3c983bd7,0x3e263d47, 0x3f643eb0,0x406a3fd3,0x414e409a,0x425d419f,0x3d1a443f,0xe37607fc,0xeae9e3a7,0xf0ecf060, 0xf1d3f178,0xf36ff227,0xf637f41c,0xcf54f55a,0x95bf9b38,0xa3449e5a,0xa5c9a5a4,0xa8a3a78c, 0xabeaaa84,0xafeeae05,0xb3d4b1d9,0xb617b4d1,0xb9b2b7c8,0xbd4bbb93,0xc08dbefa,0xc3dac23d, 0xc70bc578,0xca51c8a1,0xcd94cbf9,0xd0b1cf1f,0xd3c7d23b,0xd6e6d559,0xd9fad872,0xdd0edb82, 0xdfedde79,0xe2d9e15d,0xe5c9e44c,0xe89ee737,0xeb63e9ff,0xee1cecbf,0xf0c9ef70,0xf373f217, 0xf606f4ba,0xf88cf743,0xfb0ef9cd,0xfd74fc3e,0xffcffe98,0x022800fb,0x0449032e,0x065f0549, 0x08680759,0x0a760966,0x0c750b6e,0x0e500d5e,0x10230f36,0x11db10f2,0x139012ab,0x152e1457, 0x16d115fe,0x186d178c,0x1a101934,0x1b9c1ac7,0x1d201c56,0x1eb21dd4,0x20471f73,0x21ca20f3, 0x233b2276,0x24bb23de,0x26432570,0x27d526ff,0x2930286e,0x2aae29d4,0x2c242b55,0x2db22cd6, 0x2f112e54,0x30662f9f,0x31e230fc,0x337c3294,0x34b93400,0x36193550,0x376d3695,0x38fe3811, 0x3a753999,0x3b8d3ae0,0x3cb63bc6,0x3e633d57,0x3fac3ebd,0x40b83ff0,0x41724081,0x42bb4156, 0x440e431f,0xe82f193e,0xe7f9e177,0xf016ef47,0xf0f2f167,0xf20ff275,0xf485f3d0,0xf8aef5c2, 0xaee9e75a,0x9b3c92d5,0xa577a132,0xa6e6a5a6,0xa99ba81c,0xad0cab51,0xb0efaf33,0xb4b6b346, 0xb70fb5a4,0xbae8b8dd,0xbe7cbcb8,0xc1ccc02b,0xc505c365,0xc83bc6b1,0xcb8bc9d1,0xceebcd47, 0xd1fbd06f,0xd50bd383,0xd83ad6a1,0xdb53d9d2,0xde57dcdb,0xe140dfd5,0xe427e2ad,0xe726e5a5, 0xe9fee890,0xecaeeb58,0xef6dee0e,0xf221f0c0,0xf4c8f371,0xf756f609,0xf9e2f89d,0xfc4bfb0e, 0xfec6fd84,0x0114ffee,0x034f0236,0x0565045c,0x0780066b,0x0989087d,0x0ba20a99,0x0d830c8a, 0x0f6a0e6f,0x11311047,0x12ec1210,0x149413b5,0x16341563,0x17d416f8,0x198518a0,0x1b111a42, 0x1c9c1bd1,0x1e2d1d51,0x1fc21eec,0x21522077,0x22ca2208,0x2433236b,0x25cc24ef,0x276b268b, 0x28c32810,0x2a352968,0x2bb52aed,0x2d492c63,0x2ec42dfd,0x30032f48,0x316d3098,0x332e322e, 0x347d33c5,0x35d83502,0x371b365c,0x38b537ad,0x3a4e395f,0x3b813acc,0x3c593b97,0x3e403d03, 0x3f943eaa,0x40c63fc4,0x414e4072,0x427b40f6,0x46274243,0xf1612a06,0xe524e082,0xefe5ed39, 0xf0d8f07c,0xf229f1aa,0xf3a4f342,0xf5cdf581,0xf514f877,0x98d3cad0,0x9f89974f,0xa66aa4bf, 0xa823a6d3,0xab2ca967,0xaeceacd4,0xb2f6b0ea,0xb5bcb51a,0xb894b716,0xbc9abac3,0xc042be95, 0xc36bc1ee,0xc6afc523,0xc9d9c85d,0xcd62cbb4,0xd0a5cf31,0xd3a2d23c,0xd6bed53c,0xda08d87d, 0xdd06db98,0xe009dea1,0xe2d0e180,0xe5cbe45c,0xe8c6e75c,0xeb85ea45,0xee30ece2,0xf0edef9c, 0xf39cf255,0xf636f501,0xf8c8f78e,0xfb2efa10,0xfdaffc78,0x000bfefb,0x02490137,0x04680369, 0x067a057e,0x088b078e,0x0a9f099e,0x0c890ba8,0x0e690d81,0x10440f68,0x121d113d,0x13b212f6, 0x15601499,0x16f7162e,0x18ab17d8,0x1a4e1989,0x1bce1b18,0x1d5a1c95,0x1efd1e39,0x20881fcc, 0x22132159,0x236e22c8,0x24f72435,0x26a925d5,0x280e2768,0x296c28bc,0x2af02a33,0x2c7f2bb2, 0x2e152d51,0x2f5d2ec5,0x30b03000,0x32703183,0x33e83347,0x3536348a,0x368435e0,0x37fc373b, 0x39b538d5,0x3b0d3a74,0x3bb93b5d,0x3d643c66,0x3efe3e41,0x401c3f72,0x40aa4046,0x417340a6, 0x450a418f,0xfdfb36d9,0xe34ae18b,0xef1eeb25,0xf078f00c,0xf1fff0ff,0xf400f29a,0xf5c5f449, 0xf761f6af,0xe42bf9db,0x9468ab70,0xa3509df0,0xa703a75d,0xa963a875,0xaca8ab38,0xb0d2aeac, 0xb4ecb2e2,0xb6dcb626,0xba47b881,0xbe51bc8d,0xc1b4c03b,0xc4e7c365,0xc818c69c,0xcb6dc9c5, 0xcef3cd55,0xd205d09d,0xd501d394,0xd849d6b9,0xdb64d9f6,0xde75dcff,0xe146dffd,0xe41de2c1, 0xe72be5b5,0xea0fe8bc,0xecaaeb75,0xef69ee22,0xf227f0e1,0xf4d1f391,0xf771f63e,0xf9e7f8c8, 0xfc67fb35,0xfef0fdc9,0x01250020,0x0360026a,0x057f0488,0x079906a1,0x09b008b5,0x0bb70ad0, 0x0d9b0cc1,0x0f8a0ea8,0x116a1092,0x13281268,0x14d41412,0x167315bc,0x18341766,0x19e11929, 0x1b791ad1,0x1cfc1c54,0x1eac1df2,0x20481f95,0x21d82135,0x234022a8,0x24bf2418,0x265e25a3, 0x27e52754,0x294728ae,0x2ac12a26,0x2c4a2b9a,0x2de52d42,0x2f552ec4,0x30973011,0x323b317b, 0x33e1334a,0x353d34b8,0x3680360a,0x37ee375c,0x398e38e9,0x3b163a97,0x3bd03bba,0x3d173c90, 0x3eb23e37,0x3ff73fb5,0x4060409d,0x40e5411c,0x433b41df,0x0e03400a,0xe1b9e45b,0xee4ae8a0, 0xefc6ef19,0xf10bf070,0xf322f21a,0xf51cf435,0xf71ef5bf,0xf991f6f3,0xc6c0f48e,0x99b29854, 0xa655a16a,0xa7e9a772,0xaa81a942,0xae08ac47,0xb236b043,0xb5ebb422,0xb7f3b698,0xbbe6b9aa, 0xbfa1bdcf,0xc2eec149,0xc618c475,0xc96ec7b7,0xcce7cb13,0xd04ecea1,0xd345d1c6,0xd678d4d0, 0xd9b0d80c,0xdcc7db42,0xdfbfde42,0xe28de126,0xe580e3fc,0xe88be70e,0xeb48e9ee,0xedf4ec9d, 0xf0b9ef53,0xf377f221,0xf62ef4d1,0xf8b8f77d,0xfb32f9f3,0xfdc0fc7f,0x0022ff00,0x02600150, 0x04860377,0x06af05a5,0x08cf07c0,0x0ad409e3,0x0ccd0bdb,0x0eb80dc5,0x10ac0fb9,0x128111aa, 0x14361368,0x15df1515,0x179e16c1,0x19591889,0x1afd1a39,0x1c8a1bcd,0x1e2f1d68,0x1fce1f0f, 0x217220af,0x22d82238,0x245523a8,0x25e82529,0x277926c6,0x28d7283f,0x2a4f29a6,0x2bbe2b11, 0x2d6c2cb6,0x2ed92e42,0x30382fa8,0x31bd3106,0x336732c0,0x34e63444,0x363135be,0x378936f8, 0x3921388b,0x3ab33a21,0x3b913b82,0x3cba3c51,0x3e203dcb,0x3f7d3f2b,0x3ff94070,0x405540ca, 0x417d41b2,0x1eab4429,0xe067ea8e,0xed9fe61f,0xef69eead,0xf0c4ef5b,0xf292f12b,0xf4b3f3a2, 0xf628f5d1,0xf78bf704,0xfb19f879,0xa92fe1db,0x9faf9624,0xa868a4a5,0xa991a7f5,0xac5aaa53, 0xb001ade1,0xb3b7b1d3,0xb6e5b5aa,0xb985b7b3,0xbd90bb5a,0xc127bf37,0xc44bc2a3,0xc79dc5c5, 0xcaf8c93d,0xce7dcc9a,0xd1b3d00a,0xd4d2d327,0xd7f7d650,0xdb3dd980,0xde32dca7,0xe11bdf93, 0xe3f2e26c,0xe701e564,0xe9d5e859,0xec94eb20,0xef44edd3,0xf20ff098,0xf4cff361,0xf77cf620, 0xf9fcf8ab,0xfc8efb36,0xff09fdbf,0x015e0024,0x038e026a,0x05c004a2,0x07e706c5,0x0a0608eb, 0x0bfc0aef,0x0df30cea,0x0ff00edb,0x11d610e2,0x13a212b3,0x15561479,0x17141623,0x18de17f5, 0x1a9419b5,0x1c331b5d,0x1ddf1cfe,0x1f841eab,0x212a2054,0x22a621ea,0x2426235a,0x25ac24e3, 0x273e2674,0x28a627f3,0x2a202961,0x2b8f2ad6,0x2d382c57,0x2eb02dfa,0x30172f5e,0x319a30d5, 0x3346327f,0x34b83400,0x36393589,0x377c36e3,0x3916384c,0x3a8f39ed,0x3b993b40,0x3cb43c1f, 0x3e0a3d93,0x3f243ec2,0x4003400c,0x403d408b,0x4100413e,0x2dcf44c7,0xdfb6f449,0xebbce37b, 0xef24ee92,0xefc8eecb,0xf208f04a,0xf46bf294,0xf684f502,0xf714f67a,0xf8a2f810,0xf48efb91, 0x9891c33f,0xa3089bd4,0xa8bea7d1,0xaa93a92b,0xade3abf0,0xb173af56,0xb53cb320,0xb7b7b6df, 0xbae1b91d,0xbee2bced,0xc24ec0a3,0xc57dc3c9,0xc8f9c72e,0xcc42ca8f,0xcfb6cdf8,0xd2f5d14c, 0xd60cd47b,0xd946d798,0xdc69dadd,0xdf58ddd3,0xe244e0c6,0xe533e3ab,0xe81ee69b,0xeaf9e97f, 0xedb0ec4b,0xf075ef03,0xf344f1d7,0xf604f4a0,0xf8a0f74b,0xfb3df9e2,0xfdb8fc7b,0x002afeec, 0x02810153,0x04ba038f,0x06ed05c5,0x091207f9,0x0b1a0a0e,0x0d1f0c11,0x0f210e13,0x111a101a, 0x13051204,0x14d113e7,0x1693159f,0x186b1779,0x1a24193a,0x1bd11af2,0x1d901c9e,0x1f381e5b, 0x20ef2004,0x227121a9,0x23f72320,0x258c24b2,0x27102644,0x287827ae,0x29fe2924,0x2b692aa1, 0x2cfb2c22,0x2e872db4,0x2fe52f2b,0x317a3092,0x332c3250,0x348a33c5,0x36163546,0x377936b3, 0x38f43821,0x3a7d39aa,0x3b7e3b09,0x3c963bd0,0x3e123d53,0x3f053e7a,0x3fdf3f77,0x405e4015, 0x40eb40a6,0x39cc4394,0xe077021c,0xe91be112,0xeeafedf2,0xeefdeef1,0xf09aefb3,0xf34cf237, 0xf5dff499,0xf72ef66e,0xf8aef72b,0xfad4f93c,0xdf50fca7,0x97b9a658,0xa64ea12e,0xa92ba97f, 0xabcaaac5,0xaeffad9d,0xb2cab0dc,0xb6c0b4a0,0xb8d8b7d1,0xbc58ba63,0xc02ebe6d,0xc37bc1eb, 0xc6e6c52a,0xca42c898,0xcd8acbd3,0xd110cf51,0xd442d2b4,0xd756d5c1,0xda92d8f2,0xdd93dc15, 0xe08ddf09,0xe37fe206,0xe658e4e9,0xe950e7cb,0xec1feab9,0xeed7ed77,0xf1b3f03e,0xf480f316, 0xf733f5cf,0xf9ebf88c,0xfc6bfb26,0xfee3fda2,0x0159000d,0x03a40280,0x05e404b3,0x082006fe, 0x0a31091e,0x0c400b2b,0x0e540d41,0x10590f52,0x124c1148,0x143b1341,0x16081512,0x17e516ed, 0x19b118c6,0x1b681a85,0x1d2b1c3f,0x1ef01e05,0x20a01fb9,0x223b2168,0x23c022e7,0x25522476, 0x26ed2613,0x283e2783,0x29c028e4,0x2b3c2a70,0x2ccb2bea,0x2e412d75,0x2faf2ee9,0x312f304e, 0x33093208,0x3458339e,0x35d834f7,0x3749366a,0x38d537ee,0x3a4e396f,0x3b6b3ad9,0x3c423b7f, 0x3df13cee,0x3ef03e3d,0x3fb43f16,0x403c3f6d,0x41004006,0x411a41c3,0xe44012c7,0xe5eedf3c, 0xede5ece5,0xeebeeec0,0xefb0ef83,0xf243f143,0xf4d3f429,0xf67cf676,0xf7d2f7b8,0xfa19f90a, 0xfde2fac7,0xbf8cf3f7,0x9df29892,0xa96ea4b9,0xaae0aa0b,0xad4fac11,0xb070aeee,0xb455b28f, 0xb82ab68c,0xba34b8d4,0xbe10bbf7,0xc1a6bfdf,0xc50ec35b,0xc867c6b2,0xcba6ca10,0xcf1fcd48, 0xd29ed0ea,0xd5b3d421,0xd8cfd735,0xdbf2da5b,0xdef0dd75,0xe1f6e068,0xe4c7e367,0xe79ee61f, 0xea98e91d,0xed6eebf8,0xf024eec0,0xf307f192,0xf5bef461,0xf88ef71b,0xfb23f9df,0xfd9cfc5c, 0x000efed0,0x028c014d,0x04c603a1,0x071505e6,0x092c081a,0x0b410a2d,0x0d5a0c41,0x0f6f0e5d, 0x1165105f,0x1363125b,0x15491447,0x17331636,0x1903180a,0x1ac219db,0x1c941b98,0x1e641d70, 0x201a1f2c,0x21c120e7,0x2342226b,0x24e22405,0x268625a6,0x27e3272c,0x29452876,0x2acc29f4, 0x2c5f2b76,0x2ddc2d13,0x2f3a2e6b,0x30b22fd3,0x328b3177,0x33f63336,0x355d347c,0x36c135eb, 0x386d3764,0x39da3905,0x3b0f3a51,0x3bbb3b13,0x3d513c28,0x3e803da7,0x3f473e88,0x3f7c3ec2, 0x406e3f00,0x43a54016,0xec7a235b,0xe32fde6b,0xed4eeb3d,0xee4aee5a,0xefa1ef58,0xf17ef0a5, 0xf468f2f8,0xf63cf599,0xf7b5f72c,0xf91bf8f8,0xfb1bfad8,0xfd78fcf2,0xa4e4dc75,0xa3219a38, 0xab52a875,0xac6eab36,0xaee1ad4b,0xb240b05a,0xb629b44b,0xb8f5b831,0xbb87ba06,0xbf6dbd84, 0xc310c149,0xc650c4bf,0xc997c7f8,0xccc9cb36,0xd070cea7,0xd3b2d232,0xd6c2d54b,0xd9c9d84f, 0xdcf7db6c,0xdff5de7b,0xe2e5e17e,0xe59fe44e,0xe894e724,0xeb90ea22,0xee57ed06,0xf127efc9, 0xf401f2a4,0xf6d6f570,0xf99df84d,0xfc2bfaea,0xfeaafd6f,0x0133fff2,0x039a027e,0x060004d6, 0x08320729,0x0a58094f,0x0c870b70,0x0eaf0d9c,0x10bb0fc4,0x12c411c5,0x14cd13d1,0x16de15dd, 0x18c317d8,0x1a9419af,0x1c6f1b7f,0x1e511d66,0x20241f3d,0x21d7210a,0x236722a2,0x2510243b, 0x26c225e6,0x282c2783,0x299028dd,0x2b052a4a,0x2ca42bc8,0x2e2d2d6f,0x2f7e2ed4,0x30ed3026, 0x32ba31c5,0x344d338b,0x35a934f2,0x36fa3643,0x389237a8,0x3a363957,0x3b563ace,0x3bf33b82, 0x3d583c72,0x3ea33de5,0x3f7e3ee6,0x3f7e3f37,0x40033f31,0x43c33fe4,0xf80b31cc,0xe0d6de58, 0xec80e8d6,0xed95ed49,0xeef7ee51,0xf0c9f012,0xf302f1cc,0xf57ef477,0xf731f5f3,0xf935f7e6, 0xfa98f98f,0xfbe5fb96,0xf1d3ff22,0x98f5bbc3,0xa62d9fe8,0xab00ab03,0xac9cabd4,0xaf83ae11, 0xb353b14d,0xb71ab532,0xb930b8a2,0xbc41baab,0xc04fbe81,0xc3d4c247,0xc704c58d,0xca51c8c3, 0xcdbccc15,0xd156cfa7,0xd484d316,0xd77cd61b,0xdaa1d925,0xddd0dc59,0xe0cedf6d,0xe3a6e255, 0xe685e529,0xe989e81e,0xec81eb23,0xef5dee0d,0xf22df0db,0xf520f3bc,0xf804f6b9,0xfab2f981, 0xfd44fc16,0xffd2fea4,0x02740143,0x04e703c7,0x0731062a,0x096f0865,0x0ba10a9d,0x0de10cd6, 0x100b0f0b,0x121f112c,0x1433133e,0x1661155b,0x185f1781,0x1a41196a,0x1c211b46,0x1e1d1d3a, 0x1ff81f26,0x21ce2105,0x235822af,0x2506244a,0x26c725f8,0x284b27ab,0x29a42905,0x2b182a80, 0x2c9f2beb,0x2e412d9a,0x2fa02f13,0x30f0305f,0x32b431dc,0x345133b7,0x35cc3522,0x370f3692, 0x388037d8,0x3a30397a,0x3b893b1b,0x3bf73bf5,0x3d473cae,0x3e6d3e1c,0x3f6a3f28,0x3f653fc3, 0x3f7e3fa8,0x42184013,0x07293c62,0xdec0e046,0xebc4e640,0xecf5ec77,0xee4ded45,0xf072ef16, 0xf241f153,0xf470f36f,0xf62df581,0xf887f76f,0xfa79f97e,0xfc10fab3,0xfe31fc28,0xd7dafd9f, 0x9b75a200,0xa999a476,0xab67abbb,0xad80aca6,0xb0c4af52,0xb494b2c8,0xb868b678,0xba1ab926, 0xbdc9bbb6,0xc1babfe6,0xc50bc380,0xc83bc698,0xcba8c9fa,0xcf22cd56,0xd2b0d0f6,0xd5abd438, 0xd8b3d731,0xdbf1da51,0xdf07dd98,0xe1f3e085,0xe4cfe370,0xe7bae644,0xead2e950,0xedc3ec5b, 0xf089ef34,0xf37cf207,0xf67cf513,0xf945f7ed,0xfbe1faa8,0xfe7afd3b,0x0124ffd5,0x03be0283, 0x06150506,0x085b0748,0x0a9d098b,0x0cec0bce,0x0f170e18,0x114a103d,0x1357125c,0x158f1485, 0x17b816bf,0x19a718c6,0x1b871aa7,0x1d891ca1,0x1f741e9d,0x21622088,0x22fe224b,0x24ae23e8, 0x2663259e,0x28062760,0x295b28ca,0x2ad52a37,0x2c3e2b9e,0x2dea2d37,0x2f4f2ec6,0x309d3019, 0x32363174,0x33f43351,0x355834c7,0x36c1364a,0x380b3788,0x39aa390e,0x3b203aaf,0x3bad3bcd, 0x3cb33c53,0x3dee3dc5,0x3ec33ebb,0x3ef23f94,0x3ed03f8f,0x3ff73fda,0x182c418e,0xddb8e620, 0xeaffe3b2,0xece1ec45,0xedc2ecca,0xeff4ee6a,0xf25af0eb,0xf403f301,0xf5b3f48a,0xf7dcf6cf, 0xfa03f946,0xfb55fb34,0xfd00fc33,0x00bffd78,0xb86cf020,0xa22e9a41,0xac4aa7d8,0xacfeabf8, 0xaf56ada9,0xb27ab0c9,0xb634b45e,0xb974b81d,0xbb8cb9f7,0xbf95bd50,0xc33cc14e,0xc655c4ae, 0xc9afc7d9,0xccffcb51,0xd0a0ceaa,0xd3e2d245,0xd6dad54e,0xd9f6d846,0xdd38db88,0xe01edea0, 0xe313e18a,0xe5e5e470,0xe8f1e752,0xec01ea72,0xeeebed75,0xf1bef03b,0xf4d3f341,0xf7abf63c, 0xfa74f909,0xfd11fbb5,0xffb9fe5f,0x0273010d,0x04fa03be,0x07480618,0x09a60869,0x0bf60ac3, 0x0e3b0d19,0x10740f4d,0x129f1189,0x14dd13ac,0x171f15ff,0x1935182c,0x1b231a2a,0x1d321c26, 0x1f291e32,0x21262028,0x22e52208,0x248f23b9,0x26532571,0x28032739,0x296928c0,0x2ae82a32, 0x2c542ba3,0x2de72d26,0x2f6c2eb9,0x30b73019,0x323f316e,0x33fc3333,0x356234bf,0x36d03632, 0x382b3790,0x39af38fe,0x3b2e3a90,0x3bf13bd9,0x3ccd3c63,0x3e0a3dac,0x3ecc3eb8,0x3f193f76, 0x3efb3f95,0x3f4e3fdc,0x2831432d,0xdd58ef4a,0xe967e14a,0xeca3ebc5,0xed28ec50,0xef03ed83, 0xf19af00f,0xf3c8f2a1,0xf4cef3e1,0xf769f598,0xf9b9f818,0xfb7cfa69,0xfc36fbd9,0xfd97fd5e, 0xfdd0ffc7,0xa13dd462,0xa5d79d8e,0xac9eaac0,0xadb3ac60,0xb05aae91,0xb3afb194,0xb74ab55b, 0xb9c2b8fa,0xbc99badd,0xc0a4be96,0xc415c25a,0xc756c594,0xcac1c8f4,0xce11cc50,0xd1a5cfd9, 0xd4d2d335,0xd7d1d639,0xdb02d958,0xde28dc8f,0xe115df88,0xe410e289,0xe6f4e56a,0xea18e86c, 0xed25eb98,0xeffeee83,0xf309f16c,0xf608f481,0xf8ddf769,0xfba4fa3d,0xfe56fcef,0x0112ff9e, 0x03d20266,0x063c04f9,0x089c0758,0x0afe09b9,0x0d5c0c23,0x0fa10e68,0x11e510b5,0x142212f1, 0x1678153e,0x18b1178c,0x1abb19aa,0x1cd01baf,0x1ede1dcf,0x20de1fda,0x22b321cb,0x247a238b, 0x26432555,0x28002719,0x297328af,0x2afe2a2f,0x2c6f2baa,0x2e012d27,0x2f752eab,0x30d2301d, 0x324f3177,0x34073323,0x357234b1,0x36e8362f,0x384b3783,0x39d13904,0x3b3e3a7e,0x3c283bd4, 0x3d013c69,0x3e3c3daa,0x3f053ea2,0x3f513f61,0x3f563f60,0x3f7d3fa2,0x356b4294,0xddeefc5c, 0xe729df19,0xec06eb57,0xec87ec1a,0xedfeecef,0xf093ef1d,0xf335f1d6,0xf430f3e8,0xf60cf4ce, 0xf8d8f772,0xfb1bf9b8,0xfc93fb6f,0xfd9efc6b,0xfeeefe07,0xedeb0213,0x9aaab471,0xa8afa312, 0xac72acbe,0xae3fad89,0xb12dafba,0xb4c5b2dc,0xb882b66e,0xba7db9b2,0xbdd3bbfb,0xc1b2bfee, 0xc51fc37f,0xc875c6cd,0xcbe8ca2b,0xcf35cd88,0xd2b5d0ff,0xd5ced451,0xd8f0d75d,0xdc0bda7e, 0xdf29dd9c,0xe226e09e,0xe524e3a5,0xe819e686,0xeb47e9aa,0xee4becc4,0xf149efc2,0xf446f2c0, 0xf73df5c4,0xfa1cf8a3,0xfce5fb83,0xffa1fe3d,0x0270010e,0x050903bb,0x077b063d,0x09ee08a9, 0x0c5f0b24,0x0eb20d7e,0x11000fd4,0x13541214,0x15af147a,0x180516cb,0x1a2f1911,0x1c521b2e, 0x1e731d57,0x20871f6c,0x226e2177,0x24402341,0x26182525,0x27e526f9,0x296928a1,0x2afe2a18, 0x2c732ba5,0x2e0b2d2e,0x2f7c2eb9,0x30d83012,0x3256317d,0x34193323,0x357434b6,0x36fb361c, 0x38543787,0x39f238fa,0x3b593a91,0x3c593bd9,0x3d1a3c66,0x3e843dad,0x3f403eb0,0x3fc03f57, 0x3f9a3f3e,0x3ff93f51,0x3e6e412d,0xe0f80c91,0xe450dd47,0xeb78eac8,0xebcbebf6,0xed16eca8, 0xef65ee74,0xf238f0fd,0xf3eaf368,0xf51af49e,0xf796f677,0xf9eef955,0xfbc6fb57,0xfd1cfccc, 0xfe9efd85,0x019ffef1,0xd00bfd9b,0x9ebb9f4d,0xabaca69a,0xad11ad11,0xaeffae16,0xb20ab0b3, 0xb5b3b3f6,0xb987b7b8,0xbb65ba35,0xbf0fbd02,0xc2d1c0f8,0xc639c499,0xc993c7dd,0xccf2cb56, 0xd058ce8a,0xd3c9d21b,0xd6e9d555,0xd9eed866,0xdd18db76,0xe02adea7,0xe33de1a5,0xe632e4b2, 0xe94ae7ad,0xec68ead1,0xef89edef,0xf281f104,0xf589f3fe,0xf870f6f8,0xfb63f9e4,0xfe2cfcbb, 0x010cff8d,0x03b20255,0x06550506,0x08d10789,0x0b580a13,0x0db70c7d,0x10160ee2,0x12731137, 0x14ec13ab,0x17441609,0x198a1860,0x1bc91a9b,0x1dfb1cd9,0x201b1ef4,0x22192117,0x23f622f2, 0x25e524e2,0x27c326c8,0x294e287e,0x2ae12a00,0x2c702b9b,0x2e042d1d,0x2f842eba,0x30c93010, 0x3244315e,0x3413330f,0x357434b6,0x36da35ff,0x383a376a,0x39d238ce,0x3b5d3a7a,0x3c5d3bce, 0x3cec3c53,0x3e7a3d6d,0x3f4e3ea6,0x3fd43f37,0x3fab3f24,0x3ff93ee5,0x42ac3fc9,0xe83f1e0e, 0xe18adc63,0xeb22e96b,0xeb7debef,0xec9aec55,0xeea4edfc,0xf12ff02f,0xf340f2c0,0xf4fbf449, 0xf6b6f5e0,0xf95bf81b,0xfb28fa89,0xfcc7fc73,0xfd91fde6,0xff71ff09,0x030c0096,0xb109eafe, 0xa44c9b97,0xadc3a9f8,0xae42ad4c,0xb075aef2,0xb36fb1c9,0xb736b56f,0xba56b95b,0xbc8bbb1d, 0xc084be6d,0xc43cc26f,0xc77fc5e0,0xcaeec931,0xce14cc8d,0xd1a2cfd0,0xd4fed35d,0xd7fbd689, 0xdb02d973,0xde40dca8,0xe14adfcb,0xe462e2db,0xe758e5df,0xea78e8e3,0xedb0ec14,0xf0caef4a, 0xf3baf23c,0xf6bbf53e,0xf9b6f83d,0xfca6fb35,0xff84fe18,0x024700f4,0x050303a1,0x07a60659, 0x0a3008ef,0x0cac0b6e,0x0f1e0de4,0x11801043,0x140a12bd,0x1672153e,0x18c81798,0x1b2619f1, 0x1d761c4a,0x1f9a1e82,0x21b920ab,0x2397229f,0x259a248e,0x27952692,0x292f286b,0x2abf29ea, 0x2c572b89,0x2df82d1a,0x2f852ebb,0x30c93023,0x321e3162,0x33ff32f8,0x357134ba,0x36cf3605, 0x38213761,0x39ab38c6,0x3b4e3a65,0x3c763bdf,0x3cd63c6d,0x3e473d49,0x3f4e3ead,0x3fd63f5a, 0x3f953f4a,0x3fac3efc,0x43423f2e,0xf3ae2d96,0xdf86dcbe,0xeab8e791,0xeb7ceb8c,0xec38ebf6, 0xee43ed47,0xf07fef69,0xf290f1be,0xf44cf374,0xf651f58e,0xf836f731,0xfaa4f969,0xfc78fb3e, 0xfddcfd09,0xfed9fe3d,0xffe3fff9,0xfc2702b4,0x9eb1cbd7,0xa7d7a08a,0xadacad02,0xaec0adf5, 0xb135afce,0xb4aeb2b9,0xb87cb696,0xbaa3ba39,0xbd7abbe9,0xc1a0bfb9,0xc529c392,0xc874c6e7, 0xcbbbca35,0xcef8cd75,0xd2a3d0eb,0xd5d5d46d,0xd8bfd762,0xdbf1da68,0xdf2addad,0xe241e0c9, 0xe561e3ec,0xe856e6ed,0xeba2ea06,0xeee6ed5c,0xf1dff07e,0xf4e0f36a,0xf7f2f67d,0xfafcf98a, 0xfdfefc95,0x00d5ff77,0x0398024a,0x06640511,0x091607d4,0x0b930a69,0x0e210ced,0x108e0f6e, 0x132b11ed,0x15ae1485,0x181616fd,0x1a801952,0x1cf11bce,0x1f3a1e2c,0x216a2066,0x235a2275, 0x2561246b,0x27722682,0x2938287f,0x2ac62a05,0x2c682bae,0x2e0d2d40,0x2fa82ef4,0x3102306e, 0x324031af,0x33fc3320,0x359e34fd,0x36ee3655,0x383137ac,0x39b238f5,0x3b483a94,0x3c9e3c1c, 0x3cf03ceb,0x3e243d7f,0x3f493ee2,0x3fe93fb4,0x3f833fe3,0x3f693f73,0x41ee3f70,0x02a7395f, 0xde11df09,0xea61e56d,0xeb44eb0f,0xec13eb89,0xedc9ecae,0xeffaeeca,0xf1e1f0fa,0xf38ef287, 0xf5ebf4ac,0xf795f6f2,0xf968f87c,0xfb8afaad,0xfd57fc70,0xfef0fddb,0x0002fedc,0x01210016, 0xe6da0314,0x9cbfadc1,0xaaf9a5a4,0xadcbae5d,0xaf37aed1,0xb235b0d7,0xb5f1b410,0xb9c3b7e3, 0xbb13ba6f,0xbf19bce7,0xc2abc147,0xc5cdc43a,0xc9aac7df,0xcc61cb3f,0xcfd8cdd7,0xd3d0d22f, 0xd61dd510,0xd9e6d7e6,0xdd3ddbdd,0xe006de97,0xe3e6e204,0xe6e4e59d,0xea13e86b,0xeda7ec08, 0xf092ef3d,0xf3b3f22a,0xf6d7f569,0xf9d0f863,0xfcd5fb63,0xffc6fe62,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, }; static const PROGMEM uint32_t sample_1_SawWave_SAW0_60[5248] = { 0x00210000,0x037701a7,0x067304ea,0x095407d2,0x0d060ac6,0x12410fb1,0x171b14a2,0x1bc9195a, 0x20491df1,0x24952256,0x28bd2690,0x2cb72a94,0x307e2e52,0x341031ce,0x375b3537,0x3a5c3883, 0x3d4e3ba4,0x40503efc,0x434540e0,0x3d2942e6,0xe36ef023,0xeaaceba6,0xef27efd6,0xf395f3c9, 0xf791f80d,0xfd1cfbd0,0x02b1fe71,0xac3ae912,0xb6a3af3e,0xb9f0b529,0xbf12bd17,0xc569c3f5, 0xcb8ac9ba,0xd256cf18,0xd8cdd4ef,0xdec9db2f,0xe489e1ca,0xea41e85d,0xefdcee43,0xf5b2f3ca, 0xfb6af91e,0x00f1fe74,0x062803e1,0x0b370939,0x102c0e6f,0x15041375,0x19ba1838,0x1e271cd8, 0x2235211f,0x26032524,0x29ae2908,0x2d222cc9,0x30583057,0x33d033db,0x35c73787,0x373c3b32, 0xfff53dc2,0xe4f2d597,0xe7f4e0ba,0xebd2e6fc,0xf05eeb90,0xf4c1f083,0xf8fdf5ab,0xfd3efafb, 0x01d80025,0x070d04b4,0x0bd6093d,0x10e10cfd,0x141611c2,0xe239143f,0xcad2b9e0,0xcbfbc8a4, 0xd249cf24,0xd92bd481,0xdebad9dc,0xe3cbdecc,0xe894e496,0xed6aea7e,0xf287f003,0xf7ecf50d, 0xfd4df9d4,0x027efe8f,0x0752037b,0x0bec086f,0x106f0d50,0x14fb11f1,0x196e1655,0x1dcc1a80, 0x21f81e8d,0x25f1227b,0x29db261e,0x2d4f29e5,0x31342c40,0x32042e35,0xcd79ef6c,0xd849dbff, 0xdee3df32,0xe3bfe337,0xe8f1e7d9,0xee1eec7f,0xf343f12b,0xf843f5fc,0xfcfcfafc,0x01a8002f, 0x065f0537,0x0b6609e8,0x10870e1e,0x15791217,0x19ea16bf,0x1d7d1aea,0x20702044,0x157124df, 0xccb0d77b,0xd561d9dd,0xdc6fda9b,0xe1c7ded2,0xe637e451,0xea4ae954,0xef08ee96,0xf431f359, 0xf971f7bf,0xfe83fc20,0x033100bd,0x077d0587,0x0bb60a58,0x0ff80eef,0x1448133c,0x187a1757, 0x1c791b57,0x20c21fa5,0x23dc2351,0x26f72760,0xda19234e,0xd343c7e8,0xd76dd150,0xdbbad7db, 0xe0a9dcf9,0xe5b2e24d,0xead8e798,0xf015ecd1,0xf55df200,0xfa7cf731,0xff79fc65,0x046301ba, 0x093b06f1,0x0e3a0be1,0x13561069,0x184a14bb,0x1cc4191b,0x20a71dac,0x24b2229f,0x27c026cb, 0x2c032a6d,0x2faa2c33,0xd41b0839,0xe1a3defc,0xe533e0e7,0xe8ebe6da,0xed56ec63,0xf19bf0ba, 0xf6aef4a3,0xfb88f894,0x0002fcbc,0x040f0159,0x07f50604,0x0bf10a83,0x10250ea8,0x14ab128d, 0x182816c5,0x1bb11a6b,0x0f5c1e92,0xc1c8c58b,0xc993c895,0xcff7ce1b,0xd572d309,0xdae6d879, 0xe055ddd7,0xe5d2e347,0xeb47e8c0,0xf0c0ee2b,0xf632f393,0xfb92f8e8,0x00e0fe4b,0x060103b0, 0x0b0308f4,0x10080e0e,0x151e12d9,0x1a0d1761,0x1eaf1bdf,0x22a22063,0x260724cc,0x29592903, 0x2d522cc3,0x30c03025,0x34e13296,0x379c3530,0xf5613081,0xec25dc61,0xeb71e7bb,0xef78ed94, 0xf478f1ac,0xf8aef550,0xfcdbf8a4,0x00a7fce1,0x0439015f,0x080305b8,0x0c790a1a,0x10de0ced, 0x15fd0f90,0xb351f765,0xbcd0ba8b,0xc33ac088,0xc87bc681,0xce73cc29,0xd471d1f5,0xda80d7d1, 0xe077ddc4,0xe62ae397,0xebcce945,0xf179eedd,0xf712f47f,0xfc9dfa03,0x0216ff80,0x075f04f3, 0x0c860a48,0x119e0f82,0x16aa1471,0x1b84192a,0x1fdc1d79,0x23d021a3,0x275025d1,0x2aaf29e5, 0x2e2f2daa,0x31d630d5,0x359b338d,0x38be36a4,0x3b34390c,0x3c313ce0,0x23344060,0xea1be7e5, 0xeddff17f,0xf379f2b3,0xf7f9f596,0xfb48f988,0xfe2cfd4c,0x01cc0226,0x04d705ce,0x07e709cd, 0xc4dc0883,0xb6fda7f3,0xbad7b362,0xbfa0baec,0xc4f4c0b6,0xca96c6be,0xd063cca0,0xd643d262, 0xdc19d83c,0xe1d2de16,0xe78ae3f7,0xed0ee9ab,0xf273ef23,0xf7d0f483,0xfd15f9e3,0x0256ff1e, 0x07630455,0x0c580968,0x113b0e50,0x16121309,0x1a8e1786,0x1e981bb9,0x22501fcc,0x25ed23e6, 0x298d27c4,0x2d4a2b34,0x310c2e3c,0x34803117,0x37573400,0x3a0a377b,0x3bdb3a67,0x3e853d87, 0x3e103ed2,0xe3220997,0xf044f1e9,0xf489f107,0xf7b0f531,0xfaf5f9b6,0xfe70fd38,0x02600103, 0x07130348,0x0bb20568,0xa8dfeaaa,0xb2b8b085,0xb874b64f,0xbdaebc89,0xc383c1a1,0xc960c70c, 0xcf2fcc90,0xd4ffd244,0xdad1d81f,0xe091de03,0xe65de3cf,0xebffe980,0xf171eef2,0xf6d0f44c, 0xfc18f9a6,0x0152fee3,0x06720413,0x0b7a0916,0x105c0df4,0x151e12b4,0x196f1766,0x1d641bb7, 0x21431fd3,0x253123aa,0x2922272e,0x2cdb2a81,0x30212dcb,0x32e9314d,0x356d34d6,0x387c3824, 0x3afe3aef,0x3e973cdd,0x41743e1a,0xf24a2fef,0xf43ae75d,0xf39def56,0xf69ef4df,0xfac6f8c4, 0xfec1fbc9,0x02a1ff03,0x06a001b0,0x0a70048c,0xa8ddebc8,0xb228af7c,0xb815b5bd,0xbd8cbb96, 0xc34fc08a,0xc8fec615,0xce95cbcb,0xd44dd19f,0xda25d781,0xdffbdd53,0xe5cbe305,0xeb7ce8c2, 0xf0e9ee46,0xf63ef3a3,0xfb8bf8f8,0x00c9fe39,0x05f00369,0x0af6086e,0x0fc00d60,0x14721238, 0x18d616f0,0x1cfb1b2a,0x210f1f11,0x250e22be,0x28bd2669,0x2c032a1d,0x2f082ddc,0x32083178, 0x35303499,0x38b1371a,0x3b9639d1,0x3e313bc5,0x3f113ee1,0x187140fd,0xeff7e4f6,0xf155f236, 0xf647f495,0xfacdf747,0xfe81faa0,0x016cfe59,0x050101b2,0x08ea04b2,0xa8a5ec4d,0xb1f5ae14, 0xb7ddb487,0xbd10ba6d,0xc285bfaa,0xc804c571,0xcdaecb33,0xd37dd0e9,0xd972d6a8,0xdf50dc66, 0xe512e222,0xeacbe7ed,0xf047ed91,0xf5a1f2ee,0xfaf1f840,0x002ffd81,0x055502b4,0x0a5607c6, 0x0f2d0cbb,0x13f21191,0x18841626,0x1cb91a4e,0x20ba1e3d,0x24732223,0x27f12617,0x2b5829f0, 0x2ec82d6d,0x3266307f,0x35d9332b,0x38da35c7,0x3b8838ff,0x3d503ba1,0x3f2b3ef3,0x38b940fa, 0xe53ffdea,0xf10bf496,0xf5fcf35c,0xf973f6d2,0xfcd5fb18,0xff97ff16,0x03cc01f1,0x084b0438, 0xa8deec1f,0xb186ac8b,0xb6ebb3c3,0xbbd1ba0e,0xc14abf67,0xc6fec507,0xccd5ca8e,0xd2b9d026, 0xd89bd5df,0xde64dbb2,0xe41ce190,0xe9e6e758,0xef7ced05,0xf4ddf26c,0xfa27f7be,0xff6dfd00, 0x0493023e,0x09990753,0x0e860c45,0x135c1109,0x17dc159d,0x1bf519e8,0x1fc91e07,0x23822214, 0x274025f2,0x2b0b2977,0x2eb82ca5,0x32192fb3,0x34fc32dc,0x375f3625,0x3a2b3989,0x3c513c4a, 0x3fbd3e73,0x429b3f3d,0xeae32516,0xf4b1eca3,0xf556f14a,0xf813f68c,0xfc1dfaac,0xff6dfe42, 0x03eb0047,0x08160295,0xa907ebc1,0xb0beab9c,0xb5fdb398,0xbb1ab9c3,0xc0dabeb9,0xc6b1c420, 0xcc6fc9a4,0xd223cf59,0xd7e5d536,0xdda7db19,0xe36ae0eb,0xe93ee6a0,0xeee9ec56,0xf444f1ce, 0xf988f721,0xfec6fc60,0x03fa01a1,0x090206b1,0x0dee0ba0,0x12b71072,0x171a151d,0x1b261981, 0x1f1e1da0,0x23112181,0x26fe251e,0x2ab12894,0x2df62c09,0x30e92f98,0x33a13322,0x366d365b, 0x39be390a,0x3c783b9c,0x3f683d4d,0x40af3fc5,0x0b3a3e42,0xf3c6e48b,0xf370f292,0xf79ef624, 0xfc49f90a,0xff9efca1,0x0354fedf,0x06c501f6,0xa8c3ec79,0xb005aaf1,0xb5afb30f,0xbb0fb8cb, 0xc0b5bda3,0xc648c32d,0xcbd0c8f1,0xd171cec3,0xd741d498,0xdd18da5a,0xe2eae018,0xe8afe5c7, 0xee61eb8c,0xf3c3f116,0xf908f66c,0xfe48fba7,0x037b00e6,0x088505f3,0x0d620aed,0x12250fc6, 0x1695147c,0x1acd18c4,0x1ee91cbf,0x22db208a,0x2690243f,0x29f7280c,0x2d292bc3,0x30552f4b, 0x33a5326d,0x36f13512,0x3a1b376f,0x3cbd3a5e,0x3e8f3ca2,0x3fbd4005,0x3020429e,0xe949f3a7, 0xf224f5d2,0xf74df523,0xfb4df815,0xfe3cfc77,0x0158ff2e,0x05230236,0xa8b7ecdf,0xafd9aa01, 0xb57fb228,0xba99b807,0xbfe1bd31,0xc54cc2f8,0xcae3c8b0,0xd0adce5c,0xd6a1d3fb,0xdc74d9b5, 0xe238df73,0xe7e8e531,0xed9ceaf9,0xf316f091,0xf860f5e9,0xfd99fb20,0x02cf0058,0x07d1056d, 0x0cb10a6a,0x117f0f43,0x160d13e7,0x1a481819,0x1e4a1c25,0x22132017,0x25a42407,0x292727d3, 0x2cb22b5a,0x30402e7a,0x33a93155,0x36a13427,0x3910371a,0x3ba83a66,0x3d693d0b,0x405b3f87, 0x419f405d,0xe6e61826,0xf4aaf15d,0xf6baf31b,0xf9b7f7c3,0xfcf0fc76,0x0079feef,0x04d30128, 0xa92beb92,0xafb6a8f7,0xb4cdb190,0xb9a0b7d2,0xbef1bd18,0xc49bc2a4,0xca67c817,0xd03acd94, 0xd609d33e,0xdbb9d90f,0xe16fdee4,0xe721e4a8,0xecdfea5c,0xf26deffa,0xf7b6f560,0xfcecfa97, 0x0223ffd0,0x072104ef,0x0c0c09e2,0x10e00eb5,0x15651357,0x198417a2,0x1d6c1bcc,0x21381fd4, 0x24f423ae,0x28c12743,0x2c692a8e,0x2fc02dca,0x32b13104,0x35463465,0x37b037a7,0x3abf3a82, 0x3d293cfb,0x40563e9b,0x42644039,0xfe163810,0xf649e723,0xf54ff2eb,0xf8f7f770,0xfd0efb28, 0x00d0fd5e,0x04c0ff6d,0xa91feb05,0xaecaa845,0xb3d4b14d,0xb8f8b758,0xbe96bc3c,0xc45ec17e, 0xca04c6ef,0xcfa0cc9d,0xd548d274,0xdaf6d854,0xe0c0de18,0xe684e3cf,0xec44e978,0xf1dfef26, 0xf72ff49d,0xfc62f9df,0x01a0ff14,0x06a50439,0x0b950929,0x10620e06,0x14e012c3,0x18fc1720, 0x1d081b42,0x20fe1f2e,0x24e722e1,0x289f2677,0x2bfd2a00,0x2f0a2d9c,0x31f83114,0x34f6344a, 0x3807370a,0x3b3f3951,0x3ddb3bf6,0x3feb3de2,0x40ad4109,0x24ee4363,0xee48ec0b,0xf37af64f, 0xf8b4f6ba,0xfcaaf9e8,0x0003fcbc,0x0318ff5c,0xa8a4ec59,0xad76a723,0xb31ab095,0xb87cb61c, 0xbe01baee,0xc379c069,0xc8e8c62c,0xce7ecbfb,0xd445d1bf,0xda21d783,0xdff7dd2c,0xe5bee2e2, 0xeb70e89f,0xf113ee57,0xf676f3e7,0xfbb7f92f,0x00f1fe62,0x0608038e,0x0afa0889,0x0fd20d77, 0x145e123b,0x18961694,0x1cc21aa2,0x20bd1e8c,0x24832261,0x28062630,0x2b5c29ee,0x2eae2d7b, 0x320e30a5,0x356d3373,0x387c360d,0x3b1138a7,0x3d853bc5,0x3f1c3e4b,0x4156410f,0x3eb6425a, 0xe64c0b6a,0xf4c7f4c0,0xf82ef4f0,0xfb0bf970,0xfe65fce9,0x0190ff9b,0xa8f6ecb5,0xad0aa56c, 0xb2b7af56,0xb7b7b50e,0xbce3ba47,0xc238c008,0xc7d3c5c1,0xcd9ecb58,0xd385d0f0,0xd964d6a2, 0xdf24dc67,0xe4dbe235,0xea90e805,0xf041edb9,0xf5c1f355,0xfb02f8a0,0x003bfdda,0x0558030f, 0x0a420811,0x0f210cf7,0x13bb11b3,0x17fa1607,0x1c081a20,0x1fe91e2f,0x239a2222,0x273625f2, 0x2acd298e,0x2e642cd0,0x31c02fd8,0x34c532da,0x375235fe,0x3996391b,0x3c5d3c0a,0x3e773e8a, 0x41a14041,0x440a4149,0xf4c3302c,0xf753ea9b,0xf710f410,0xfa0df92d,0xfe16fc0d,0x01a4fe69, 0xaa66ebe1,0xaccca3a6,0xb206aea9,0xb6c3b4bb,0xbc0eb9f3,0xc1adbf6f,0xc779c4d6,0xcd43ca54, 0xd300cff9,0xd8b1d5d1,0xde63dbaf,0xe421e17f,0xe9dfe73d,0xef96ece5,0xf527f287,0xfa6bf7eb, 0xff9afd28,0x04b80258,0x09ad0761,0x0e900c40,0x132610fb,0x17561562,0x1b581990,0x1f451da8, 0x23182188,0x26e52534,0x2a9128a6,0x2df12c07,0x30fd2f67,0x33be32c5,0x366e3603,0x393838d6, 0x3c563b2c,0x3ed23d9f,0x41313f43,0x420941f1,0x19064283,0xf227e880,0xf54df67e,0xf9c1f890, 0xfe09fa9a,0x015efd4c,0xaa7bebbd,0xab82a327,0xb0f9aea9,0xb613b459,0xbbb5b91e,0xc166be5b, 0xc6ffc3c8,0xcc8cc980,0xd224cf53,0xd7dbd533,0xdda8dafa,0xe379e0ae,0xe943e661,0xeeedec09, 0xf481f1be,0xf9d1f738,0xff06fc74,0x042901a2,0x092606ae,0x0e010b94,0x1297105a,0x16cc14ca, 0x1ae018f0,0x1ef01cf2,0x22d720c0,0x26972470,0x2a0a2813,0x2d432bb1,0x30552f2d,0x3372325b, 0x36a63533,0x39b537a8,0x3c693a02,0x3ecc3cdc,0x40553f13,0x41e3420a,0x38e443e6,0xe870003b, 0xf5a3f71a,0xf96ff753,0xfcd7fa19,0xfff3fd87,0xa9edecd3,0xaa55a2be,0xb075ae1a,0xb5bfb34d, 0xbb27b80e,0xc084bd9a,0xc5dcc34d,0xcb6bc91e,0xd132ced5,0xd70ad484,0xdce1da2c,0xe2a8dfe1, 0xe864e5a3,0xee04eb5e,0xf3a3f117,0xf90ef69d,0xfe40fbdd,0x0367010b,0x0863061d,0x0d430b0a, 0x11de0fd1,0x1623143f,0x1a4a1863,0x1e521c59,0x22252046,0x25bc241d,0x292f27dd,0x2c9d2b71, 0x30042eaf,0x3354319b,0x3667346a,0x390c3739,0x3b3f3a22,0x3dbf3d1b,0x3f843f86,0x427c417d, 0x445a4246,0xee67259c,0xf840ef0e,0xf8abf62c,0xfba7f9f8,0xff46fd4e,0xaaa8ecd7,0xaa3ba113, 0xb05cacbe,0xb527b241,0xba2cb76f,0xbf75bd32,0xc4f8c2cb,0xcac4c856,0xd0a0cddf,0xd66fd385, 0xdc27d949,0xe1d3df19,0xe78ee4ea,0xed39eaab,0xf2e5f050,0xf863f5df,0xfd9bfb35,0x02c30064, 0x07c5057a,0x0ca50a6e,0x11470f3d,0x159813a3,0x19b817ce,0x1daa1be5,0x21751fea,0x252523c4, 0x28c92766,0x2c602aca,0x2fc02dfb,0x32cc311e,0x357f3451,0x37ff377c,0x3a763a5e,0x3d5e3cd0, 0x3fad3f20,0x4258409c,0x439f42aa,0x0c833f05,0xf5c5e82c,0xf715f759,0xfb0ef953,0xff2cfbd2, 0xababebef,0xa9c79fb0,0xaf8aac2b,0xb422b1fb,0xb953b71e,0xbef8bc86,0xc4aac1da,0xca6ec73f, 0xd01cccea,0xd5bed2bd,0xdb62d89c,0xe11dde66,0xe6ebe426,0xeca5e9d5,0xf24def76,0xf7d5f516, 0xfd0dfa80,0x023affaf,0x073b04c5,0x0c2809bb,0x10c50e87,0x151112f6,0x19291733,0x1d271b4e, 0x21101f42,0x24de2301,0x2890268e,0x2bff2a04,0x2f242d78,0x320e30d7,0x34ea340a,0x37dc36ec, 0x3ac3395b,0x3d8e3b83,0x3fe43e18,0x41904009,0x428c4305,0x2ffe4517,0xec07f64a,0xf658f8ce, 0xfa91f823,0xfe32fabd,0xab8dec18,0xa84c9fbe,0xae68ac5e,0xb369b1c0,0xb8f2b669,0xbe99bb98, 0xc420c101,0xc991c6a3,0xcf22cc7e,0xd4cfd24f,0xda9bd813,0xe073ddb7,0xe63be367,0xebebe918, 0xf181eec7,0xf714f46c,0xfc60f9e5,0x018bff13,0x068d042b,0x0b7d0923,0x101d0dee,0x14641267, 0x188c169e,0x1c9c1aab,0x20901e94,0x2450225d,0x27df260c,0x2b2d29af,0x2e612d2f,0x31983066, 0x34c93352,0x37e435f7,0x3a893883,0x3cc33b1b,0x3f133df9,0x40a3404a,0x43134291,0x42c9436c, 0xea97194a,0xf84cf34e,0xf9d7f6d0,0xfcc4fa79,0xab92eca3,0xa76c9f5f,0xae4eabba,0xb357b0bb, 0xb89ab569,0xbdddbaef,0xc328c0a4,0xc8a2c65e,0xce5dcc05,0xd42ad19f,0xd9fed743,0xdfbfdceb, 0xe56ee2aa,0xeb14e871,0xf0acee27,0xf64af3ba,0xfbaef941,0x00d3fe79,0x05d60393,0x0ac70888, 0x0f610d5e,0x13b811d1,0x17e91606,0x1bf11a16,0x1fd01e0b,0x237f21f4,0x270c25b0,0x2a82294e, 0x2df02c98,0x313e2fa5,0x344b329c,0x3705358f,0x3963388a,0x3b8e3b63,0x3e3e3dea,0x404a402d, 0x431741a3,0x44da4305,0x015f38af,0xf7b8ea4b,0xf891f72f,0xfbeffa0c,0xad00ec3d,0xa7759dfb, 0xae65aa61,0xb2e0afcb,0xb7beb4e5,0xbcf9ba9a,0xc276c021,0xc827c592,0xcdf8cafb,0xd3b5d099, 0xd960d65e,0xdf03dc28,0xe4ace1f0,0xea5fe7a8,0xf005ed58,0xf5a1f2dd,0xfb13f86d,0x0041fdbc, 0x053f02db,0x0a3307d0,0x0eda0ca9,0x1330111e,0x1758155a,0x1b581977,0x1f391d7e,0x22fe215f, 0x26ad2509,0x2a45288d,0x2daa2bd3,0x30c62f0b,0x3395324a,0x3642356d,0x38e63859,0x3b993ad9, 0x3e583ce6,0x40a63f45,0x428840f4,0x435243a2,0x259a44e9,0xefd7f080,0xf7bff8f3,0xfbb3f959, 0xada9eb99,0xa6ae9d1b,0xad4baa13,0xb1a5afba,0xb6c0b4af,0xbc5ab9fa,0xc207bf2b,0xc7aac489, 0xcd41ca1a,0xd2cecfe6,0xd874d5c5,0xde29db84,0xe3ece137,0xe9a7e6d7,0xef50ec7e,0xf4dbf213, 0xfa59f7ae,0xff94fd0d,0x049b0233,0x098d0721,0x0e400bfb,0x12931074,0x16bd14bd,0x1ac618df, 0x1eb51cda,0x229520ad,0x26452451,0x29c727e1,0x2d052b5a,0x30092ec0,0x330b31fb,0x361234df, 0x39033778,0x3bbf39d8,0x3e023c1b,0x40403ed3,0x41a940fe,0x43824377,0x3f0344c3,0xea330dfe, 0xf8daf5d0,0xfb1df852,0xad8debc8,0xa5359cf1,0xac2daa36,0xb0fdaf52,0xb662b3d0,0xbbeeb8ea, 0xc159be48,0xc6b4c3ec,0xcc26c9a6,0xd1cbcf6f,0xd79bd51c,0xdd6bdabd,0xe32ce064,0xe8d3e614, 0xee74ebc4,0xf3fdf16a,0xf986f6fd,0xfed4fc68,0x03e50198,0x08d6068d,0x0d8a0b6a,0x11dd0fee, 0x16131432,0x1a2b1856,0x1e201c4f,0x21f3201e,0x258d23e9,0x29002796,0x2c4b2b19,0x2f8d2e67, 0x32c33164,0x35d03430,0x388b36e8,0x3ae539ad,0x3cf03c5f,0x3f633efb,0x41264139,0x43e642c9, 0x45db43b9,0xf81f3066,0xf993ed43,0xfa3cf817,0xadb3ec13,0xa49f9c28,0xac42a956,0xb0feae03, 0xb614b2a7,0xbb37b81a,0xc05fbdc7,0xc5d5c375,0xcb76c90d,0xd143ce91,0xd717d42a,0xdcccd9d2, 0xe274df93,0xe80de556,0xedafeb0f,0xf345f0a8,0xf8d5f634,0xfe33fba7,0x034a00e6,0x083e05e7, 0x0cf40ac2,0x11490f51,0x15841391,0x19a017b4,0x1d8b1bbb,0x214e1fa0,0x24f02373,0x28812717, 0x2bf62a7f,0x2f4f2daa,0x326230bb,0x352c33c3,0x37b136c7,0x3a1b39af,0x3c7a3c3f,0x3f373e59, 0x41604094,0x438641f6,0x4499442e,0x19084374,0xf45aec68,0xf93ef989,0xadbaebbf,0xa4989ae8, 0xac30a855,0xb049ad39,0xb509b243,0xba28b7d6,0xbf9fbd4e,0xc555c2aa,0xcb0ec809,0xd0becd89, 0xd65ed346,0xdbfcd916,0xe19ddee8,0xe750e49b,0xecfcea3c,0xf29befd2,0xf824f557,0xfd8afadb, 0x02b2002c,0x07a80536,0x0c600a16,0x10be0e9e,0x14fc12df,0x190e170b,0x1cfe1b1b,0x20cd1f0c, 0x248b22c4,0x28332658,0x2ba029bf,0x2ed32d0d,0x31c03057,0x348d3380,0x3752366a,0x3a1e3907, 0x3ccb3b41,0x3f3b3d4e,0x41613fd6,0x42bf41ac,0x441d4457,0x381a4683,0xec49010a,0xf972f90b, 0xada9eb19,0xa3b29a2f,0xab23a840,0xaef5ad60,0xb406b22c,0xb994b75c,0xbf37bc75,0xc4dbc1c0, 0xca53c74b,0xcfc9cd03,0xd561d2d4,0xdb15d897,0xe0dfde43,0xe698e3dc,0xec43e97d,0xf1d3ef17, 0xf751f4b1,0xfcc9fa39,0x0204ff91,0x06f904a8,0x0bb30981,0x10170e0b,0x144e1258,0x186a1688, 0x1c6a1a9a,0x20491e7e,0x24052233,0x279825d6,0x2aed2960,0x2e122cce,0x31283014,0x3436330d, 0x372f35c2,0x39f43841,0x3c503abb,0x3e4e3d37,0x40863fe3,0x41fe4202,0x44a043d1,0x456f4508, 0xf0ef2410,0xfa7af15b,0xae31eabb,0xa23499cc,0xaa88a7ff,0xae9aad08,0xb3f6b12a,0xb95db62c, 0xbea9bb7c,0xc3f6c118,0xc959c6dd,0xcee4cc8d,0xd4acd225,0xda7bd7c0,0xe03ddd5b,0xe5dfe307, 0xeb72e8c0,0xf105ee65,0xf68bf3fd,0xfc05f976,0x0153fedb,0x064f0400,0x0b0808e0,0x0f6e0d73, 0x13a711c2,0x17cc15eb,0x1bd019fb,0x1faa1de7,0x235121ab,0x26dd2566,0x2a3c28f4,0x2d8d2c51, 0x30c52f6c,0x33dd324f,0x36a03526,0x391137f4,0x3b453abf,0x3d673d50,0x3ff33f89,0x41e441a3, 0x446d42ed,0x45c74503,0x0c9c3e73,0xf710eb5b,0xaea7ebc8,0xa16f9972,0xaacda6f4,0xaeebac1c, 0xb3bfb02c,0xb8bbb59c,0xbdcfbb31,0xc334c0c9,0xc8d4c652,0xce8acbbf,0xd44cd136,0xd9fbd6dc, 0xdf97dc9b,0xe524e259,0xeabfe80c,0xf05ceda1,0xf5e5f32c,0xfb5af8a1,0x00adfe0e,0x05b70343, 0x0a6a0823,0x0ed40cb0,0x130f1100,0x172c1529,0x1b2d193f,0x1f001d33,0x22ad20ff,0x264924ae, 0x29cc2826,0x2d232b6f,0x30482e8e,0x332831a8,0x35c834b5,0x3855378f,0x3add3a24,0x3d633c61, 0x3fd93e51,0x41eb4098,0x43884233,0x44854530,0x2f5c461b,0xee0ef938,0xb091ec28,0xa0c3990d, 0xaa88a61e,0xae65ac03,0xb2bcb050,0xb7d2b5bd,0xbd30bb01,0xc2d4c03d,0xc880c584,0xce11caff, 0xd38ed095,0xd923d660,0xdeb9dc21,0xe45de1c5,0xea0be759,0xefa4ece0,0xf52bf269,0xfa8af7e3, 0xffe5fd4d,0x05000294,0x09b70778,0x0e1e0c04,0x12601055,0x167f1488,0x1a7c189c,0x1e5b1c8d, 0x22162054,0x25c223f4,0x29382771,0x2c792ad2,0x2f7f2e1b,0x32683146,0x35453438,0x381336de, 0x3ac3393e,0x3d2b3b85,0x3f2f3dc0,0x4148404a,0x42b34247,0x44d744c3,0x42c2452d,0xee2f195e, 0xb241e6a5,0x9fe29893,0xa979a5bc,0xad83ac02,0xb1fcb039,0xb75eb516,0xbce0ba14,0xc25ebf3f, 0xc7bac4c9,0xcd1cca76,0xd291d024,0xd847d5ce,0xde04db6e,0xe3b1e0f9,0xe94fe68e,0xeed5ec22, 0xf451f1b6,0xf9b9f73c,0xff17fc9d,0x045101ef,0x090806e5,0x0d700b6c,0x11b60fc4,0x15d313fb, 0x19db180e,0x1dc51c02,0x21821fc8,0x251f2376,0x2885270f,0x2bc42a80,0x2ee52dc6,0x31fe30d0, 0x34f9339d,0x37ba364b,0x3a2638dd,0x3c4f3b78,0x3e3a3df6,0x4091403c,0x426c424c,0x44f7440b, 0x464f44bb,0x035937c6,0xb108e019,0x9f0298a9,0xa8d8a53f,0xad62ab30,0xb206af48,0xb735b3e2, 0xbc5ab921,0xc184bea0,0xc6d3c447,0xcc58c9e7,0xd1fbcf66,0xd7c5d4d9,0xdd74da77,0xe2ffe014, 0xe889e5c2,0xee10eb61,0xf395f0f1,0xf908f671,0xfe65fbc7,0x03a90124,0x086c062c,0x0cd30abe, 0x111c0f14,0x15491351,0x194b1761,0x1d331b56,0x20ea1f2f,0x248122e7,0x27fa267f,0x2b4f29e3, 0x2e922d17,0x31a73019,0x347f3308,0x371235e9,0x396938ae,0x3bc13b43,0x3e0a3d8a,0x40783f6c, 0x42944190,0x446c4365,0x45154527,0x2500452f,0xaac5e7a0,0x9e4b9863,0xa897a49e,0xad16aa22, 0xb1a4ae94,0xb648b368,0xbb4fb8da,0xc099be50,0xc62ec3af,0xcbdac906,0xd17ace6f,0xd70fd3f4, 0xdca3d9bb,0xe22cdf6d,0xe7bce516,0xed50eaa3,0xf2def026,0xf857f59d,0xfdabfafb,0x02f8005c, 0x07d1057e,0x0c380a16,0x10800e6a,0x14ae12a5,0x18b616c1,0x1c981ab4,0x20561e93,0x23fa224a, 0x278b25d1,0x2aeb2934,0x2e1c2c71,0x311b2f94,0x33d532a5,0x36883591,0x3923382f,0x3bbf3a89, 0x3e1e3ca9,0x40363eaa,0x42534109,0x43aa434c,0x450e4508,0x3e2b4623,0xa81702a1,0x9e1794c4, 0xa835a3fc,0xac12a9ad,0xb0aaae7e,0xb53eb371,0xba99b87f,0xc021bd9a,0xc5b6c2cc,0xcb34c831, 0xd09ecdc8,0xd61ed375,0xdbb8d936,0xe157ded4,0xe6fde45e,0xec93e9da,0xf219ef62,0xf787f4e5, 0xfcd6fa56,0x0231ffac,0x071c04e0,0x0b89097c,0x0fd70dd4,0x140e1217,0x180f1635,0x1bfc1a34, 0x1fc81e11,0x237721c3,0x26fb254d,0x2a5228c6,0x2d702c1c,0x306c2f4c,0x33593251,0x3635350d, 0x38e63792,0x3b6139f7,0x3d7b3c5b,0x3f4c3ead,0x41904105,0x43324376,0x455e446a,0x4668451e, 0xb69823b5,0x9cb58dcc,0xa7bda38b,0xab29a96b,0xb038adf2,0xb511b2cf,0xba6fb76e,0xbfc0bc95, 0xc50dc200,0xca55c7a7,0xcfc6cd4e,0xd55dd2dc,0xdb1cd86c,0xe0c6ddf7,0xe65ae383,0xebdae910, 0xf14feea9,0xf6bff42b,0xfc17f998,0x0173fee1,0x066f0420,0x0adf08d1,0x0f2a0d2b,0x135e1169, 0x1765158c,0x1b531989,0x1f211d62,0x22c5211a,0x264224b4,0x29952836,0x2ccd2b8a,0x2fe72ea1, 0x32e6318d,0x35b7344f,0x383036fe,0x3a7b399e,0x3c973c31,0x3ea23e70,0x4118405d,0x431d42cf, 0x44de4393,0x45b9454b,0xd79b37da,0x96a78fc9,0xa784a312,0xaaffa94f,0xb041acff,0xb51eb214, 0xb9f2b6c5,0xbf05bc35,0xc43ec1bd,0xc9adc73c,0xcf51cca6,0xd4f7d20b,0xda9ad78c,0xe021dd2a, 0xe59de2cd,0xeb17e866,0xf093edee,0xf60cf35d,0xfb67f8c5,0x00b8fe0b,0x05c40356,0x0a3d0816, 0x0e870c6e,0x12ba10ac,0x16ca14d2,0x1ab118cd,0x1e7d1ca8,0x22202068,0x25a02408,0x290e277a, 0x2c562abe,0x2f6e2dd8,0x325430d4,0x350233bc,0x3780368d,0x39eb3924,0x3c593b7e,0x3e9b3d8b, 0x40dd3f5e,0x42fc4201,0x440b432e,0x44fc454d,0xf6823c64,0x90d7a4ce,0xa735a00a,0xaad8a90b, 0xaf82ac58,0xb45ab1dc,0xb8dcb6c2,0xbe1dbbfc,0xc39bc13d,0xc930c673,0xcebecbc2,0xd439d142, 0xd9b6d6e5,0xdf35dc99,0xe4c0e234,0xea4ce7b4,0xefd9ed2c,0xf548f298,0xfaa1f802,0xffe7fd52, 0x0500029e,0x098f0774,0x0ddb0bd3,0x12161013,0x16271440,0x1a17183e,0x1de31c21,0x21951fe8, 0x2522237d,0x289726ee,0x2bd82a42,0x2ee12d76,0x31ba3089,0x3480337c,0x372d362d,0x39ca389d, 0x3c3b3ae4,0x3e583d10,0x40403f36,0x427341f3,0x4381436c,0x456744ee,0x053e3bc1,0x9819c53f, 0xa5e2995e,0xaa64a86d,0xae54abee,0xb386b16e,0xb83cb64d,0xbdadbb07,0xc328c02c,0xc886c57f, 0xcddbcb07,0xd340d0a4,0xd8c6d650,0xde6adbdf,0xe407e167,0xe999e6d8,0xef12ec59,0xf478f1d4, 0xf9d1f746,0xff1dfc9e,0x044401e6,0x08db06c4,0x0d270b2d,0x115c0f66,0x159013a3,0x199317c3, 0x1d6b1bac,0x21051f64,0x247022dd,0x27d92649,0x2b3d29c9,0x2e942d44,0x31bb3090,0x34a5337d, 0x373e360c,0x39ae3876,0x3c1a3b02,0x3e7a3dbe,0x40bb4061,0x42ec42e1,0x438143d9,0x441443ba, 0x05063a13,0xaf07db91,0x9f799472,0xa944a63b,0xae93abb9,0xb4f5b1bb,0xb9cdb718,0xbe54bb5e, 0xc2eec021,0xc7eec544,0xcd71cada,0xd31fd08a,0xd894d5fc,0xdda9db0b,0xe2b2dffe,0xe807e52d, 0xede0eae6,0xf3d9f0f5,0xf970f6d0,0xfe4bfc02,0x0279007f,0x065d0470,0x0aaa087b,0x0fb20d30, 0x1505126f,0x19bc1790,0x1d681bc3,0x203f1ef5,0x22f521a9,0x265624af,0x2a942891,0x2f1b2d03, 0x3308313e,0x35e03489,0x37cd36e6,0x39c538f1,0x3c7f3b7d,0x3ffd3eca,0x43514223,0x454044c5, 0x446144f2,0x41bc42d4,0x00c5379b,0xc8d1dfc8,0x956a9cdc,0xa6cca149,0xaf11aadc,0xb6d9b28f, 0xbbeeb94e,0xbf46bd7f,0xc2efc14d,0xc795c57f,0xcd50ca94,0xd339d03f,0xd87ed5be,0xdce4da8c, 0xe13bdeff,0xe657e3be,0xec84e978,0xf322eff1,0xf904f645,0xfd81fb6f,0x00d1ff4b,0x03ef0258, 0x081f05e9,0x0dd10ade,0x14331112,0x19c6173e,0x1d7c1bec,0x1fa61ec9,0x219f20aa,0x24d12319, 0x29d0272f,0x2f4b2c93,0x341731ce,0x372935f7,0x38a43843,0x3a2939b0,0x3cec3b96,0x41493f00, 0x45b5435b,0x47c04712,0x45ca4729,0x400d436c,0xfe0d34d6,0xd738db7f,0x92d1b4a3,0xa320989f, 0xaebba8cd,0xb7deb36b,0xbdbcbba4,0xc09ebfe3,0xc372c26d,0xc7b7c565,0xcdd0ca67,0xd220cffd, 0xd803d515,0xdc15da69,0xdff9de34,0xe4eae291,0xeb0de7dc,0xf278eed7,0xf85bf5b3,0xfc0bfa79, 0xffb5fe0c,0x01e30103,0x0579037a,0x0b64084f,0x13470f5b,0x19fb1713,0x1d3c1c22,0x1f311e7d, 0x205b1fcb,0x235f21a6,0x2a0d263d,0x2dd52c95,0x342730fd,0x3910378d,0x3a5a3a58,0x3b2f3add, 0x3cdc3bd3,0x415a3ec7,0x46e6444a,0x4a6e49ef,0x47fd4a96,0x3f6d450f,0xfc1c31ee,0xd6e3d7bd, 0xa0eecb1d,0x9d029044,0xad64a59c,0xb8f8b3ec,0xbff2bd3d,0xc2efc1c0,0xc453c377,0xc78ac4f3, 0xce14ca21,0xd1d3d14a,0xd6c4d3a9,0xdb81d9a6,0xdf0cdd40,0xe401e161,0xe9b5e65f,0xf1d3ed84, 0xf7bbf53f,0xfa94f95e,0xfe46fc76,0x0054ffd0,0x02fe0143,0x091205a1,0x12250d8b,0x19fd168c, 0x1d281c65,0x1eab1dec,0x1f1c1ed5,0x225b2057,0x29f02556,0x2c352c1f,0x34172fe1,0x3b1c388c, 0x3c6e3c53,0x3bc43bdc,0x3cf23c7d,0x41263ee1,0x477144e0,0x4d394bb9,0x4ada4d75,0x400c468d, 0xfb233082,0xd1d7d629,0xb870d307,0x941e928e,0xab04a131,0xba1db37e,0xc238be80,0xc569c3b8, 0xc54dc580,0xc6b7c502,0xcd5ec9c7,0xd413d231,0xd4edd35e,0xdaaad7f8,0xde42dc61,0xe32ce056, 0xe888e55e,0xf0d0ec5c,0xf748f4d7,0xf958f860,0xfc71fb17,0xff07fe0f,0x00c8ff66,0x06aa02f7, 0x10f80bd4,0x19ad15c3,0x1d681c6c,0x1ded1d6f,0x1dec1dd9,0x21941ef3,0x29d124d4,0x2a7e2b56, 0x34142e90,0x3ce1393f,0x3e993e7a,0x3bf83d71,0x3d943cfd,0x41663f31,0x482c451c,0x4fd74c60, 0x4ddd5013,0x40f6486d,0xfbb4308a,0xce49d599,0xc93ecfa3,0x8e9da443,0xa76799a5,0xba8eb202, 0xc3eebff8,0xc78bc62b,0xc6acc844,0xc5d3c589,0xcc74c8c9,0xd676d14d,0xd374d601,0xd8d4d567, 0xdd57db6e,0xe20edf7d,0xe775e499,0xef8feb6c,0xf6dcf3fe,0xf811f778,0xfab7f9ff,0xfd41fba2, 0xfecefde7,0x0417009f,0x0fd70a21,0x191514e9,0x1d981c23,0x1d251d89,0x1cb01cca,0x209b1d9e, 0x2a0924c4,0x28892a81,0x33e02d23,0x3e253a16,0x40cd40ac,0x3c9f3f89,0x3e563cd5,0x41f63feb, 0x48ba4565,0x51294ccb,0x505e52ce,0x41f04b01,0xfd713173,0xcc86d5fd,0xcc0dcad3,0x95fcb8eb, 0xa1dd9190,0xb9c8af24,0xc581c114,0xc9e0c864,0xc8f0cadd,0xc5a8c66c,0xcb64c752,0xd690cfb7, 0xd4d7da4e,0xd5fad285,0xdc73d9c6,0xe10fdebb,0xe6d5e3a6,0xeeb2ea97,0xf649f2ab,0xf6f5f6c7, 0xf995f907,0xfa97f92a,0xfd35fc61,0x01aafe96,0x0ec70826,0x1848140a,0x1d501b80,0x1cc71dd8, 0x1b531b7f,0x1f621c38,0x2ab8247c,0x265729d6,0x33442b5c,0x3f263acb,0x42fd4245,0x3e09418b, 0x3e463c87,0x42bf40e6,0x48f945fc,0x51774d66,0x52af54c0,0x43994d7b,0xfffa3274,0xcbd5d787, 0xc819c830,0xa772c3ac,0x9add8fe1,0xb7c9ab47,0xc724c124,0xcc83ca56,0xcbb2cd4d,0xc641c80d, 0xc9dec651,0xd4cace53,0xd9c4dcc0,0xd263d198,0xdb38d719,0xe061de00,0xe65ee27b,0xee2fea09, 0xf516f17d,0xf608f622,0xf8b5f816,0xf757f762,0xfbe6f9f0,0xffaefcd4,0x0d860600,0x177f1352, 0x1ca41aa6,0x1d221dd8,0x19d21a6e,0x1e331ac8,0x2b8823b6,0x245029d7,0x326e2961,0x40633b43, 0x45004371,0x3fda4392,0x3d8d3d1f,0x43f0416d,0x497846e9,0x51fa4df8,0x55045571,0x45db4f95, 0x029c338c,0xcc76da2b,0xc44ec6eb,0xb7d3c371,0x94c5998b,0xb4c5a603,0xc81bbfea,0xcf00cc4b, 0xce2ad008,0xc743ca50,0xc7ffc608,0xd2e8ccb0,0xdf24dc42,0xced6d4e5,0xd8d1d305,0xdfcbdd12, 0xe580e178,0xedd7e9f0,0xf382f0ed,0xf525f501,0xf7d1f738,0xf465f629,0xfa29f642,0xfdedfb77, 0x0c030429,0x16f712c3,0x1bac19bf,0x1d7c1d31,0x180819fb,0x1d141913,0x2c7a2318,0x227c2ad2, 0x30f126cf,0x41a53b49,0x469b44cd,0x41ab45cb,0x3d293e93,0x454340f3,0x4a5a484c,0x52d14e70, 0x565f559a,0x47c851ac,0x04db3537,0xce7add70,0xc256c6c8,0xbe26bf4a,0x95d8aa1e,0xb0ce9f58, 0xc7bbbd88,0xd14ecdff,0xd09cd2fb,0xc924ccda,0xc6e5c6cf,0xd0edca7c,0xe02ed97d,0xcf83db5d, 0xd575ced1,0xdf20db6f,0xe451e0c6,0xed93e97f,0xf248f076,0xf455f321,0xf70ef6a2,0xf2c5f541, 0xf6d8f277,0xfc82fa12,0x0a2902b5,0x166d117d,0x1acb190d,0x1d681c6d,0x174d1aa7,0x1b78176e, 0x2af82187,0x22712a9e,0x300325ca,0x42613b1a,0x4774461d,0x43514727,0x3e1a404d,0x45113fec, 0x4b88497e,0x53d54f68,0x56875665,0x49d65383,0x06df3805,0xcfd6df06,0xc1adc733,0xbd98bd26, 0xa16fb876,0xaa9499df,0xc5dcb9f4,0xd361ce71,0xd394d5a5,0xcc33cf9d,0xc7b3c8f1,0xce8fc8e9, 0xdc58d61f,0xd55ede6c,0xd22ecdc7,0xde32d925,0xe37ee04b,0xed30e853,0xf195efc9,0xf2f8f15a, 0xf65af610,0xf1edf466,0xf2caf030,0xfb49f79f,0x0878014b,0x15630f82,0x1a121879,0x1cc91ba3, 0x17af1b10,0x19a0162f,0x288b1f79,0x22bf28f1,0x2f4525c5,0x42703a8d,0x485046fe,0x44ab47bb, 0x3fb541bd,0x44063ff4,0x4cfd4a14,0x553e50f9,0x57725824,0x4c9554f7,0x09fc3b0d,0xd18de0a0, 0xc200c86f,0xbb64bca5,0xb35dbe0b,0xa3509dca,0xc2efb536,0xd450cd44,0xd5e4d756,0xce5ed1a3, 0xc883cacb,0xcb6cc7d1,0xd74bd276,0xd9f4db90,0xcebad002,0xdbfed588,0xe2c9df4d,0xec93e733, 0xf185efc1,0xf200f11d,0xf6eff62c,0xf299f4f7,0xf144f0ad,0xfb51f5ba,0x08570173,0x14690ea1, 0x194517fc,0x1b1b1a44,0x1714199c,0x16c91493,0x25641c6c,0x219c261d,0x2e4425a5,0x417f3934, 0x489a46ac,0x44e6479d,0x40d14292,0x436a40f8,0x4ea849ee,0x5790532a,0x59fe5a8d,0x4fa6569f, 0x0db73e8d,0xd378e344,0xc334ca64,0xba81bce2,0xc037bd11,0xa040ad16,0xbf08ae87,0xd3cfcada, 0xd77ed86d,0xcfe7d3a7,0xc973cca6,0xc8ccc79e,0xd2d0ce87,0xd9d8d623,0xcdb7d48d,0xd8e6d18f, 0xe20cddcd,0xeb92e686,0xf181efb8,0xf16df153,0xf765f593,0xf33cf59a,0xf135f183,0xfa5ff3d3, 0x085101c5,0x13410e38,0x1897172e,0x196a190f,0x15df17ce,0x146613ae,0x223b196a,0x1f9f2357, 0x2db9252d,0x403137d4,0x487e45e4,0x44c247cc,0x41a24326,0x43c6422c,0x4f49492d,0x59b554fc, 0x5c8d5cb5,0x51c158c3,0x11214234,0xd5a1e6b0,0xc4f7cc92,0xba64bda2,0xc33cbb2f,0xa81fbee8, 0xb9aba7b7,0xd225c78f,0xd8e9d8d1,0xd1d2d5b3,0xcb10ce67,0xc79bc819,0xcec4cae4,0xd5a0d10e, 0xd06cd747,0xd55bcea8,0xe138dba8,0xeae1e61c,0xf1b4ef33,0xf173f16d,0xf734f497,0xf3d0f619, 0xf1eef230,0xf8a3f305,0x08870195,0x12730e12,0x17c815ff,0x17c517ff,0x141615e9,0x12e812b7, 0x1f2a16a8,0x1d7620b1,0x2d7723e4,0x3ed236e4,0x480a44de,0x44f34819,0x428f436e,0x45054341, 0x4f1d4915,0x5ba8564e,0x5ed95ef3,0x53b95b88,0x14be455b,0xd8aaea1d,0xc72eceb8,0xba9bbef8, 0xc10cba5f,0xb97cc886,0xb241a73e,0xcf56c31b,0xd9e9d7e1,0xd3f9d747,0xccdfd005,0xc758c913, 0xcab0c847,0xd026ccbe,0xd451d57e,0xd1eecebc,0xdffdd8e9,0xeaaae5b8,0xf1c0ee90,0xf1a4f1a6, 0xf645f409,0xf442f637,0xf2adf2b5,0xf72ef35c,0x089f0053,0x11fc0df4,0x16ad14be,0x165c170d, 0x1229141b,0x11ed1134,0x1c471490,0x1b7f1e22,0x2cc3220f,0x3d9a3667,0x47414399,0x457347ff, 0x43414393,0x46534442,0x4edf49fa,0x5d3456c8,0x610360fa,0x56505e19,0x186d47ac,0xdc4bed5d, 0xc993d15b,0xbb70c0e4,0xbf1aba29,0xc99ec8e6,0xac52b2ad,0xcb99bce5,0xd9fcd5d0,0xd5e2d8ad, 0xce6cd208,0xc783ca9f,0xc706c6e0,0xcb40c88f,0xd54cd086,0xcff0d1b8,0xde04d5c2,0xea81e519, 0xf14bee46,0xf1aff1f1,0xf533f3ed,0xf481f5a4,0xf33df326,0xf6eff43a,0x081cfeae,0x11c30e1c, 0x155013fd,0x151815f4,0x10301268,0x10a10f44,0x19ab132c,0x198d1ba1,0x2b38202b,0x3cb535e1, 0x46184233,0x45b54770,0x438043f4,0x474e4526,0x4f364b3e,0x5e0656a0,0x63086287,0x5918603c, 0x1b564a0c,0xdfaff0d3,0xcc0bd4df,0xbce2c34f,0xbe49ba64,0xcff0c617,0xaf44c523,0xc6adb541, 0xd8e7d2c5,0xd783d9a7,0xd023d444,0xc85ecc4a,0xc499c639,0xc708c481,0xd23dcb33,0xd0f7d4a4, 0xdb8ed313,0xea53e407,0xf0f3ee60,0xf1eff1fa,0xf4a9f3d2,0xf44ff487,0xf3b7f376,0xf7a2f504, 0x06bffdb2,0x11b40e17,0x141d1391,0x13d8148a,0x0e4510e2,0x0ebf0d2f,0x17a811ee,0x17a81944, 0x29501e69,0x3c2a34c8,0x44c44111,0x45a046a8,0x43df4493,0x486345db,0x50714c85,0x5e5456cc, 0x64d263b7,0x5b97626b,0x1dc04d1c,0xe318f43e,0xcf31d8b9,0xbef6c5d9,0xbdd7bb33,0xce4ac425, 0xbdebd2af,0xbfabb115,0xd69ece9b,0xd8d2d97c,0xd22fd5fc,0xc9a8cda5,0xc333c5f3,0xc2e0c122, 0xcd14c69e,0xd406d431,0xd8f7d239,0xe9f1e253,0xf110ee79,0xf238f1b7,0xf461f3b0,0xf377f388, 0xf40cf37e,0xf88cf599,0x0543fdc0,0x11b50d3e,0x134c1332,0x125212ee,0x0c700f5e,0x0cae0b23, 0x163d1053,0x15f61758,0x278f1cc8,0x3b7b3319,0x43834054,0x4541459c,0x448e44ea,0x49644645, 0x51d74d99,0x5e6b579a,0x661d6451,0x5dd16466,0x208a5023,0xe6cff6e4,0xd32ddc55,0xc17fc8a0, 0xbde0bcad,0xcb25c315,0xd023d5b8,0xb831b7c0,0xd354c902,0xd98bd82f,0xd423d770,0xcad0cf48, 0xc235c64b,0xbee1bef3,0xc803c26e,0xd5d0d043,0xd709d401,0xe8f5e026,0xf14eee74,0xf21ff1b1, 0xf407f3bf,0xf256f305,0xf43cf314,0xf958f61b,0x04a0fe82,0x11660bd4,0x12bc130a,0x109311a8, 0x0ac60ddb,0x0a840927,0x14b40e49,0x146a15eb,0x25dc1b2f,0x3a143129,0x42673fa6,0x44874451, 0x452244c8,0x49fa46be,0x52f84e9c,0x5ece58d3,0x66db6484,0x5feb65e0,0x23bd52ab,0xea2af93c, 0xd738e016,0xc424cc3c,0xbe8fbedc,0xc944c266,0xda8bd2bf,0xb6bfc8f7,0xcf04c184,0xd93dd5e2, 0xd5b4d8b8,0xcbe1d149,0xc1b7c702,0xbbdbbd91,0xc3b8be4f,0xd433cb32,0xd726d6d5,0xe76cde14, 0xf183ee2c,0xf1edf20f,0xf3c0f3bb,0xf182f2a2,0xf423f227,0xfa04f67f,0x04eeff5b,0x10600aaa, 0x124d12ea,0x0ede10c3,0x092d0c2f,0x086c075a,0x12d00c2d,0x134214d1,0x243c19c2,0x383f2f64, 0x419c3eac,0x4397432e,0x456d447d,0x4a7d478e,0x541b4f98,0x5fcd5a2a,0x675a64ef,0x61d266ea, 0x26bd5519,0xecdafc2b,0xdb15e417,0xc733d07b,0xbfe8c162,0xc7eec228,0xdabccf8f,0xc143d9c9, 0xc8eabaf0,0xd7c3d279,0xd6f8d929,0xcd48d2e9,0xc1d4c768,0xb9e2bc70,0xbfa9ba90,0xd000c697, 0xd972d7b1,0xe5b0dd0b,0xf1afed63,0xf22cf283,0xf3aaf36e,0xf105f225,0xf38cf11e,0xfa85f6a3, 0x0593fff8,0x0efb0a47,0x11ef1241,0x0d6a0fee,0x076b0a3c,0x065d0590,0x109c09f3,0x128d1370, 0x22c918a0,0x36642db6,0x40cb3d1d,0x42914242,0x456b43ec,0x4b404830,0x5550504e,0x610e5b56, 0x67df65b7,0x6322678d,0x29515768,0xef8fff47,0xdf42e793,0xcb2bd49d,0xc203c417,0xc6fec2a5, 0xd6f8cd9c,0xd3d5e0af,0xc143bcd5,0xd53dcddb,0xd7e9d88b,0xcecbd414,0xc1fdc7ce,0xb854bbd1, 0xbb94b7cc,0xcb40c286,0xdbb8d556,0xe429ddea,0xf179ec11,0xf29ef2d4,0xf358f329,0xf07cf1cb, 0xf29cf06b,0xfae4f677,0x063a007b,0x0e1b0aad,0x11921116,0x0c4f0f4d,0x058d087a,0x047503cf, 0x0e5a07ca,0x11d811ba,0x217f17ca,0x34a42c19,0x3f803b37,0x419b4163,0x451d4305,0x4c04485a, 0x563950de,0x621c5c64,0x689166b1,0x63d96819,0x2bbc5931,0xf2af01df,0xe371ea6c,0xcf86d8b5, 0xc472c76c,0xc6a7c3f4,0xd3fecc22,0xe255dec6,0xbca4caf6,0xd1b7c766,0xd815d6ec,0xcfe0d52b, 0xc1fac8ae,0xb724bbe0,0xb831b5fa,0xc727bea1,0xdba3d13d,0xe3dbe045,0xf0c5eab4,0xf310f321, 0xf2dff35d,0xeff5f192,0xf1c0eff0,0xfb03f5ec,0x06ac00da,0x0dff0b40,0x10b60feb,0x0b570ecf, 0x03a4071b,0x029b0203,0x0c1605c6,0x10d60fe3,0x206f1728,0x32f22aa5,0x3dc73965,0x40dc406d, 0x449a4232,0x4c944861,0x570651c3,0x63245d97,0x699467d0,0x647d6912,0x2e0a5a69,0xf5c00438, 0xe70bed9b,0xd3b7dd2f,0xc72acba8,0xc70ac5f3,0xd1f8cb04,0xe5d1dab8,0xc274dda0,0xccacc00a, 0xd717d41c,0xd08dd5b8,0xc212c95b,0xb695bbc9,0xb5d3b45b,0xc37ebae0,0xd8f2cd26,0xe549e1e2, 0xefbce9d5,0xf375f30b,0xf2a6f3ad,0xef97f11b,0xf12def5b,0xfad2f529,0x06fa0100,0x0e570baf, 0x0f7a0f44,0x0a6f0e15,0x01da05d7,0x00a1fffc,0x09c903bc,0x0f970deb,0x1fa41667,0x3178297b, 0x3bfc37cc,0x40283f1c,0x43e84185,0x4cc3482d,0x57cf528c,0x642e5e88,0x6aa168c6,0x658b6a4e, 0x2fc75b3c,0xf84f068b,0xea4df10f,0xd805e17d,0xca9bcff8,0xc84fc833,0xd04cca8a,0xe267d7e8, 0xd37ae8f1,0xc5bbbe22,0xd515d036,0xd10ed55f,0xc279c972,0xb66fbb78,0xb3fdb312,0xbfd5b7e1, 0xd51fc9a4,0xe75de100,0xeebbea1d,0xf3b8f274,0xf2c2f3de,0xef40f099,0xf0adeed6,0xfa60f495, 0x072100e7,0x0ec70bf7,0x0e720f43,0x09a60cf3,0x007004bb,0xfeaffe11,0x07aa01bd,0x0e4e0bf7, 0x1ed41565,0x30292872,0x3a3f3633,0x3f283d69,0x432a40d2,0x4cad4793,0x589f52d0,0x650d5f24, 0x6b796986,0x67016b61,0x30da5c3c,0xfaa80886,0xedebf427,0xdcafe52d,0xcec9d425,0xca37cadd, 0xcf1ccaf1,0xde80d5de,0xe54de98f,0xbf6fc839,0xd1f8cabb,0xd105d40a,0xc27bc946,0xb613bb83, 0xb251b291,0xbc8fb5df,0xd1b6c67f,0xe837de32,0xee5debc2,0xf39cf1af,0xf2dbf40f,0xeebbf07d, 0xf01aee85,0xf9e3f437,0x07000092,0x0f010c0f,0x0e050f84,0x08a60bc6,0xff3103d0,0xfcabfc72, 0x0584ffba,0x0ceb0a0e,0x1dcc144c,0x2f0f277f,0x38a434cd,0x3ddf3bba,0x42984018,0x4c7046f2, 0x594d52f2,0x65d86002,0x6c546a7e,0x68ab6c78,0x31dd5e1d,0xfcf109df,0xf18cf6c1,0xe0eee8be, 0xd2d3d894,0xcc50ce53,0xce94cc35,0xdbd9d413,0xed42e54e,0xc0efdb2b,0xcda5c393,0xd009d199, 0xc1edc8e6,0xb5a5bba7,0xb11eb241,0xba23b411,0xcecbc353,0xe6d4dadf,0xef23ed72,0xf322f12c, 0xf2e2f427,0xee5ff097,0xefaaee23,0xf991f3ca,0x06a40018,0x0f0f0bed,0x0df20fb6,0x07550ae0, 0xfdfa02d0,0xfab3faf7,0x0341fd9c,0x0b70081d,0x1c9b131c,0x2e032656,0x372b33a7,0x3c753a39, 0x41ff3f2a,0x4bf74670,0x59a352fc,0x668d60ea,0x6d2f6b65,0x6a016d67,0x33976078,0xfeb90aa9, 0xf49ef939,0xe4a9ec9f,0xd6dadd36,0xcf02d23f,0xcf09ce06,0xd9b6d2d5,0xeba4e1a5,0xced4eaee, 0xc784bee2,0xce10ce0c,0xc12ec7d4,0xb594bb31,0xb091b199,0xb852b251,0xcbf4c09c,0xe400d7f2, 0xf0a3ed81,0xf28ff13d,0xf2e6f3c9,0xee58f087,0xef57eda2,0xf954f354,0x0633ffb3,0x0efd0b97, 0x0e1d0fcc,0x06320a7b,0xfcf901ab,0xf910f9a9,0x010cfb91,0x0a080621,0x1b6c11d2,0x2ccc24fb, 0x35de329a,0x3b0938b9,0x41293df3,0x4b5b45d1,0x59b652a0,0x67426157,0x6e006bfb,0x6b006e2a, 0x364b6272,0xffa70ba8,0xf738fb68,0xe874f02d,0xdb45e159,0xd28bd607,0xd072d02b,0xd7edd26d, 0xe753df27,0xe26fefae,0xc085c44f,0xcb0dc93a,0xc036c5f0,0xb572ba53,0xb014b12f,0xb691b151, 0xc94cbed5,0xe127d57d,0xf1b9ebd0,0xf25cf239,0xf2c3f332,0xee62f072,0xeeeeed70,0xf901f30b, 0x05bbff69,0x0eac0b1a,0x0e2f0fbb,0x05720a60,0xfbec007c,0xf799f87d,0xfedcf9b3,0x088f0416, 0x1a2c1085,0x2b5523a5,0x34d53175,0x39c9376d,0x40363cb8,0x4ad64516,0x59bf5213,0x67e9618a, 0x6ecf6ca5,0x6bf96f11,0x39636408,0x00520e05,0xf9c8fd02,0xec6bf329,0xdfb7e529,0xd644d9f0, 0xd23fd2fe,0xd6b5d30f,0xe416dced,0xef38ec91,0xbe21d533,0xc6cec275,0xbe73c2f1,0xb49ab954, 0xaf52b10c,0xb504b0d6,0xc747bd5b,0xdec5d312,0xf142e940,0xf2bff384,0xf245f2b8,0xee40f070, 0xee92ed89,0xf8b6f2d7,0x0552ff14,0x0e180a97,0x0e0a0f6a,0x04ea0a46,0xfab3ff7f,0xf626f75e, 0xfcadf7fd,0x06ed0207,0x18cd0f34,0x29cf225d,0x33d73008,0x38b33673,0x3f3d3baf,0x4a45444f, 0x597251a7,0x681f61ab,0x6f6d6d52,0x6ce87004,0x3bd56553,0x01df1184,0xfbf6fdcc,0xefd6f5d3, 0xe39ae91d,0xd9d2de3c,0xd47ad682,0xd674d491,0xe1c0db19,0xf0e4e87f,0xc765e7ef,0xc112bbee, 0xbbcebece,0xb372b7f3,0xaee0b07f,0xb43ab023,0xc5eabbb8,0xdc9bd0d5,0xef61e6d0,0xf3a2f3fa, 0xf19bf294,0xee2af02e,0xee91ed87,0xf899f28e,0x04eafea3,0x0d7f0a23,0x0dbe0ed5,0x04970a14, 0xf9aefed6,0xf4e5f63d,0xfabcf66b,0x0542000d,0x17680dc0,0x286420f2,0x327e2e4d,0x37be3599, 0x3e343aae,0x4960435b,0x58e2510c,0x6807617d,0x6ff86d92,0x6dd970bd,0x3d986678,0x051414d5, 0xfd41fe9a,0xf29df853,0xe755ece8,0xddace254,0xd77dda05,0xd762d679,0xdfb3da09,0xed0ce5d5, 0xda4af158,0xb9babc9a,0xb820b982,0xb243b5de,0xae9faf5b,0xb3d0af6a,0xc49eba8f,0xda83cf61, 0xed19e4d9,0xf470f322,0xf135f2d9,0xee23efa5,0xeeb9ed67,0xf888f280,0x046bfe57,0x0d0609b8, 0x0d380e1e,0x044609bb,0xf8fdfe5a,0xf3c5f539,0xf8fff506,0x03bdfe3c,0x16040c34,0x270a1f78, 0x30b92cb2,0x371e3495,0x3d5539d7,0x48724267,0x58615033,0x67ee6104,0x707f6d74,0x6eeb716e, 0x3f4067ba,0x094c174a,0xfdf00103,0xf537fa4a,0xeb24f003,0xe1cee5ee,0xdaf0dd70,0xd903d8d9, 0xde0fda08,0xe96ee3b1,0xeaebf081,0xb440c977,0xb32eb279,0xb090b2d3,0xadb3adfd,0xb315af0b, 0xc332ba2c,0xd8d5ce62,0xeb29e312,0xf46cf167,0xf11bf355,0xeddfef24,0xeeaeed67,0xf875f2c0, 0x03d4fe29,0x0c96092a,0x0c5e0d7a,0x03c40922,0xf85afddd,0xf297f469,0xf743f3ab,0x0236fc7e, 0x145d0a9f,0x257f1df2,0x2ed32b48,0x3695330d,0x3ca73950,0x47a941a8,0x57dc4f4e,0x67b4609e, 0x709a6d69,0x6fd3721c,0x40e4691d,0x0cd11919,0xff460560,0xf795fb4b,0xee8ef29d,0xe59be981, 0xde46e14b,0xdb06dc0b,0xdd4fdb35,0xe712e1d2,0xf0a5ec4a,0xb820dce0,0xaceeaa51,0xae17ae9c, 0xac30ac81,0xb26bae81,0xc260b9d0,0xd7cbcd16,0xe985e14e,0xf351ef78,0xf119f36c,0xed5ceeda, 0xee89ed5b,0xf8adf2f6,0x036bfe02,0x0c1a087d,0x0b940d15,0x03210852,0xf7d4fd67,0xf1b4f3e4, 0xf5b2f270,0x00d8fae2,0x12a10934,0x23e31c4d,0x2d2829d5,0x358e3107,0x3c0a38ff,0x46cf40ed, 0x56d24e4f,0x6709600d,0x704e6d22,0x708f7272,0x42816a5b,0x0f0c1ab6,0x02b70a14,0xf91efbe0, 0xf12ff50b,0xe90eed0d,0xe1c0e552,0xddb1df78,0xddcddd02,0xe51ce087,0xedfbe92c,0xc7d3ea82, 0xa506a648,0xaac1a94d,0xaabbaa95,0xb227ad4c,0xc24ab942,0xd6eecbe2,0xe801e020,0xf1b9edf6, 0xf105f2d1,0xed0aeeb8,0xee95ed18,0xf924f2ea,0x031afdf5,0x0b6f07d1,0x0b0d0cb0,0x02500752, 0xf75dfcd0,0xf132f35f,0xf443f164,0xff92f957,0x110107df,0x22411a6a,0x2bbd2839,0x33e42f1e, 0x3bd03891,0x461f405d,0x55c44d7f,0x66665f35,0x70136c93,0x713d7255,0x44586b88,0x10de1c88, 0x08240da2,0xf9bafdf3,0xf375f717,0xec89efe8,0xe5a8e8e6,0xe102e2b8,0xdf58df31,0xe35ce036, 0xe9bde6f5,0xda44ecc3,0x9cedad2e,0xa62fa27e,0xa90ea7db,0xb16faba8,0xc208b8ec,0xd5a6cb79, 0xe6a9df74,0xf030ecb2,0xf089f184,0xece7ee6f,0xee93ecbb,0xf965f2ec,0x02d4fe46,0x0aa30750, 0x0abc0c20,0x012c067b,0xf6c1fc00,0xf0a9f2c3,0xf2d7f0a5,0xfe41f7d2,0x0f83069a,0x206b187f, 0x2a41269d,0x31ef2da6,0x3bd13787,0x459c4018,0x54eb4cd2,0x65bc5e13,0x6fd46be7,0x71ac7234, 0x464b6cc6,0x12b71e7f,0x0d480fe5,0xfa7902b3,0xf584f81d,0xefabf203,0xe985ec43,0xe45ee64b, 0xe16be21c,0xe25ae142,0xe6e3e4fd,0xe3ffe8c8,0x9b27be20,0xa0639a10,0xa6d3a41d,0xaff0aa0e, 0xc19ab8bb,0xd4a2cb79,0xe5dede84,0xeef5eb6e,0xef7befe7,0xec9cedd3,0xee51ec9b,0xf967f31a, 0x02c5fea2,0x09ea06e3,0x0a580b54,0x00060613,0xf60dfaff,0xf00af234,0xf1c6f03b,0xfcfff66e, 0x0e200559,0x1e5416c5,0x289c24e3,0x30452c53,0x3b5835b1,0x45214011,0x54194c24,0x64725cd8, 0x6f126b16,0x718971ff,0x48006dab,0x149c2092,0x10a211c3,0xfd7408e7,0xf6eef845,0xf1f4f3d0, 0xecf7ef8b,0xe7aeea3e,0xe405e586,0xe297e34c,0xe4c2e377,0xe33fe4cf,0xa54acdfb,0x99219318, 0xa3e09f38,0xae52a845,0xc193b7ec,0xd485cb3f,0xe558dd43,0xedeeea81,0xee0eee82,0xebf1ecf0, 0xee27ec8a,0xf99bf333,0x030dfeb5,0x095c0693,0x09af0a7b,0xff4305d5,0xf535f9c4,0xef68f19d, 0xf140efbf,0xfbe0f545,0x0cd20424,0x1c5c153d,0x26f322e3,0x2f182ad5,0x3a0533cb,0x44fe4019, 0x53664b98,0x62e45be2,0x6e3669fe,0x71707194,0x49ac6e20,0x16c222ad,0x12d613c6,0x03740e08, 0xf733f967,0xf399f558,0xf045f239,0xeb65edf9,0xe74be8cd,0xe426e5c1,0xe2c3e2c2,0xde68e21a, 0xb699d341,0x9099948e,0x9fc79906,0xacb5a5dd,0xc167b66f,0xd498cb0a,0xe45bdc98,0xecfcea23, 0xec92ed73,0xeaf9ebc9,0xee3aec0d,0xf9f6f31f,0x032efe9d,0x08da068c,0x08c409b7,0xfeea0550, 0xf407f89e,0xeec8f0d8,0xf0d5ef02,0xfacef48e,0x0b6b02ec,0x1a9613ba,0x251620ad,0x2df7293b, 0x3810326e,0x45373f7b,0x52e34b4f,0x61a45b2f,0x6d686874,0x717f70f2,0x4b356e6a,0x193624de, 0x150b1616,0x0a3c1142,0xf70ffdaf,0xf504f603,0xf355f404,0xef60f161,0xead5ec36,0xe67fe8c5, 0xe13fe366,0xda6edfc6,0xc304cf83,0x8b60a19c,0x9a779132,0xaacea2a2,0xc06bb4ee,0xd459cb25, 0xe326dcab,0xec6ae99d,0xeb49ec6e,0xe9d7ea65,0xee08eaf1,0xfa19f32a,0x02e4febd,0x088006ab, 0x07dc0915,0xfea40482,0xf2cbf81d,0xee0eefe2,0xf01bee42,0xfa0df44d,0x0a0a01d1,0x18fc1236, 0x22e01eab,0x2c98278f,0x3640317d,0x45213dc0,0x526c4b4d,0x609e5a81,0x6c0266b1,0x71177020, 0x4c066ea9,0x1b6b26bb,0x1730186d,0x0f00135d,0xf8c304b0,0xf5fbf575,0xf594f54c,0xf30ff4aa, 0xee42f01a,0xe957ec75,0xe0e8e56c,0xd7abddc8,0xc465c9e8,0x907db279,0x93e5891c,0xa8549e42, 0xbefeb376,0xd45acae0,0xe2d1dcbe,0xec43e88e,0xea48eb9c,0xe8b3e914,0xed22e9ac,0xfa38f35c, 0x02acff01,0x088d068c,0x072a089f,0xfe0d0393,0xf1eaf807,0xed30eeb2,0xef25ed83,0xf9e6f3ed, 0x08b000d3,0x176710a4,0x20a71cf7,0x2b3825a2,0x352c3080,0x44183ba0,0x52394b87,0x5fc959f4, 0x6a1f6555,0x70736f27,0x4ccc6ee6,0x1d9b283a,0x19971aef,0x11bb1590,0xfe4a0b80,0xf5def52b, 0xf6fcf65f,0xf679f778,0xf1eef410,0xecc0f022,0xe1f9e804,0xd50fdc5f,0xbedac589,0x9fc1bb6b, 0x8bbb866f,0xa4d998a2,0xbd9cb193,0xd473c9b0,0xe2ffdc89,0xebace794,0xe95deb43,0xe782e80a, 0xebace88f,0xfa97f305,0x02c0ff1f,0x089e0617,0x0694086d,0xfd1c02b2,0xf1b2f7c3,0xec0ced75, 0xee22ec98,0xf9f8f309,0x0763004a,0x15ba0f06,0x1eb61b5a,0x29b72367,0x34722f5b,0x420c3a0c, 0x52744b3f,0x5f20599f,0x686c6461,0x6fe96dab,0x4de86ee2,0x1fb52974,0x1c531d85,0x13e31805, 0x06120fc5,0xf4bbf7e2,0xf7fdf6c3,0xf9b1f949,0xf60df7b3,0xf0a4f3c7,0xe438eb1d,0xd2c9dc45, 0xb8e4c1fc,0xaef1b9b6,0x84888f04,0xa02a9199,0xbc27af04,0xd3d7c837,0xe2eedc9e,0xea73e778, 0xe8a7eafa,0xe666e725,0xea44e78e,0xfad2f1c0,0x02d1ff47,0x083505c4,0x0629087d,0xfc1b01ff, 0xf1cdf71c,0xeab9ece0,0xed24eb8c,0xf9b2f1fb,0x065e0061,0x13fb0d7b,0x1d0e19b6,0x27d42142, 0x33862e20,0x3fcb3927,0x529249a2,0x5e6f5977,0x6710636b,0x6eda6b9e,0x4eba6e8e,0x21312aa7, 0x1f091fdf,0x16231a9a,0x0c651213,0xf4b1fe9d,0xf8aaf5cf,0xfc2afa56,0xfa1cfb21,0xf475f7dc, 0xe70feee1,0xd171ddc1,0xb45fbea0,0xb444b374,0x84f89f69,0x9a4e896d,0xba57ab7a,0xd285c6f6, 0xe2d4dca3,0xe9c1e7b6,0xe869ea09,0xe595e660,0xe948e697,0xfa33f012,0x02cdffaf,0x079e05c6, 0x061b0861,0xfb3c0170,0xf19ff62f,0xe9b2ed10,0xec18ea52,0xf8f5f105,0x06090096,0x12430c0f, 0x1b7617f4,0x25bd1f7d,0x32782cb3,0x3e593876,0x51c84720,0x5df159a1,0x6602628f,0x6d1a69ee, 0x4f396e30,0x22782c1a,0x21ba21ef,0x189c1d77,0x0fc7141b,0xf8b7069a,0xf868f44c,0xfda0fb1d, 0xfdd4fe2c,0xf85bfc3c,0xea62f2de,0xd188e02c,0xb042bba9,0xb049adc8,0x9092abef,0x92ef83d9, 0xb7bea6a6,0xd127c591,0xe30cdbcc,0xe9eee7aa,0xe7f0e8be,0xe4e6e5f6,0xe877e5c2,0xf895eec3, 0x02f5ffa4,0x074c05b1,0x062b07c5,0xfa7f011f,0xf0ebf53b,0xe96ced4a,0xeac6e8e9,0xf800efea, 0x062c001b,0x10880b05,0x19b71611,0x23dd1def,0x315f2ada,0x3daa3793,0x4fb444f4,0x5ded599e, 0x652a61f3,0x6b4668e0,0x4fc86d5d,0x24202d69,0x245f239d,0x1b74207b,0x11b7167d,0x00a80c22, 0xf6c2f51d,0xfe6afb5c,0x015b0040,0xfcbd0069,0xee49f6ba,0xd319e314,0xac4fb9cc,0xa9c5a94c, 0xa0a7adb5,0x8b088790,0xb3f9a08e,0xcfe4c3a7,0xe2d3da57,0xea18e7b0,0xe69be82a,0xe44ae5c0, 0xe7a1e51b,0xf6ceedf1,0x032afe66,0x07360594,0x05e00723,0xfa00012f,0xf014f47a,0xe9dded18, 0xe957e820,0xf729eec6,0x0620ff37,0x0efb0ac4,0x17c7142f,0x22511c48,0x2fdc28db,0x3ce43686, 0x4ced43ab,0x5e015843,0x644f6173,0x69d867eb,0x4ff56bab,0x25b52e41,0x265e250b,0x1e5f233c, 0x139618f3,0x087d0e95,0xf54ffac6,0xfef3fa6c,0x04400159,0x014c0458,0xf24afae2,0xd58fe6a2, 0xa908b9a3,0xa48ea524,0xa9f0a83f,0x87c49579,0xaf0b9915,0xce84c0f8,0xe1c6d91f,0xea1ee7fe, 0xe555e866,0xe423e507,0xe6ffe496,0xf5aced4d,0x0289fc44,0x070005ab,0x052306d7,0xf9db0137, 0xef5bf3ec,0xea37ec84,0xe7eae840,0xf629ed5d,0x0551fe3c,0x0e1c0ae6,0x15e11272,0x21051a8f, 0x2e08274e,0x3bef3564,0x4ac742ed,0x5d6a5581,0x63936153,0x68f1670b,0x4f726a1b,0x27092f2e, 0x280526e8,0x215f25d3,0x15cc1bcf,0x0cf71018,0xf78003a3,0xfec8f849,0x060901fa,0x059707f2, 0xf626ff7f,0xd868ea84,0xa707babf,0xa02fa129,0xa8aaa1f1,0x8ee0a436,0xa8c19222,0xcc90bd04, 0xe057d7ec,0xea58e78f,0xe4f5e86c,0xe3ede384,0xe686e440,0xf525ecb3,0x0099fa6c,0x06ed05a4, 0x049606c0,0xf9fe00c4,0xeebef39b,0xe9e6ebc2,0xe73ae8c7,0xf4efebb2,0x0416fd34,0x0e010a6c, 0x13f910fa,0x1f9818ac,0x2c48261f,0x3ae833d8,0x49b24212,0x5b525295,0x6336613d,0x6846665a, 0x4e83694d,0x284f2fdb,0x29f328df,0x245427fb,0x18511ee8,0x0eb811df,0xfef00af2,0xfd24f763, 0x06e30230,0x098f0a94,0xfa700401,0xdbe2ee5b,0xa6b8bc88,0x9bf99e06,0xa2549d0c,0x9df7a9e8, 0xa14991be,0xc997b7d5,0xdf21d673,0xea7be641,0xe505e84d,0xe2d6e255,0xe61de437,0xf4b5ec40, 0xfe0ef970,0x0707045f,0x046b0690,0xf9ed0002,0xee5ff3b1,0xe942eb29,0xe78de8f7,0xf37dea5a, 0x02defc0c,0x0df70933,0x12331058,0x1df616c4,0x2afb24fe,0x399f31f5,0x48d440f2,0x57ee5088, 0x63095ff3,0x678665ad,0x4dd268c8,0x29712f90,0x2c182a54,0x26d229c0,0x1b1521e3,0x0fec13dc, 0x08420e45,0xfabcfb5b,0x075c016b,0x0d0d0c1a,0xff220852,0xdfa1f250,0xa79ebee3,0x982d9c7f, 0x9c7198c9,0xaa70a655,0x9be39bfc,0xc56fb15e,0xddfed467,0xe9c9e4ed,0xe4e2e88b,0xe141e229, 0xe600e3dc,0xf457ebef,0xfc33f906,0x069e01d3,0x04510692,0xf952ff97,0xee59f3f5,0xe8aaeac8, 0xe821e89b,0xf1fcea18,0x01a9fac2,0x0d2207bf,0x10f51065,0x1c3614e4,0x2a0223ae,0x37de305d, 0x47bf3fc7,0x54cf4f6f,0x628b5cfe,0x66e6655a,0x4de2685c,0x2a022f06,0x2e162bc7,0x28ce2be6, 0x1e0324b2,0x1183162c,0x0e9f0f68,0xfaf8046a,0x075bff27,0x0f7a0ce8,0x03b70c63,0xe34ef6c6, 0xa912c1cc,0x95669c88,0x97c49495,0xacb09fb5,0x9eafab3a,0xc010aa36,0xdc87d13e,0xe874e3e0, 0xe4cde873,0xe05ee22c,0xe60ae282,0xf41aebba,0xfb56f8a5,0x04b7ff13,0x043306a0,0xf896ff83, 0xeeaef3ca,0xe82cea9e,0xe811e7f0,0xf0f9ea9d,0x0039f91f,0x0b8b0642,0x10921018,0x1a64132e, 0x28f6221f,0x36002f41,0x46973e4e,0x52fe4e7d,0x60b3594d,0x66966557,0x4e576815,0x29dd2f44, 0x2fe22d2e,0x2add2e6b,0x20fb272b,0x137018e7,0x10f71089,0x01160dc4,0x05fcfce6,0x10b30d42, 0x07ee0f98,0xe71bfb58,0xaaf4c4a1,0x94579d84,0x936390eb,0xa7649a2c,0xab34b4a6,0xb953a6c5, 0xda46ccd0,0xe73be2bf,0xe4ebe761,0xe049e1e7,0xe551e0ef,0xf3e6ebbe,0xfadef843,0x01a6fd55, 0x045705bf,0xf857ff79,0xef07f326,0xe7efeae4,0xe781e764,0xf12beb13,0xfea2f79c,0x09df04c3, 0x10a40ee1,0x18a41235,0x27a42070,0x347d2e52,0x453b3c4e,0x51cb4d31,0x5d115638,0x66776475, 0x4ead67cb,0x29a03003,0x31822d9c,0x2d393073,0x2394290b,0x15aa1ba3,0x11c1120a,0x0b7012ef, 0x033afecb,0x115a0ce4,0x0bd4119a,0xeb85ffcf,0xad58c78e,0x94d69f14,0x8f408eae,0xa0f595b1, 0xb981b405,0xb2edacc6,0xd6eec744,0xe656e14d,0xe47ce602,0xe030e1ec,0xe3b0e04f,0xf3d6eba6, 0xfa67f806,0xfef0fc97,0x04500340,0xf864ff8a,0xeeddf2ab,0xe807eb7c,0xe6d0e706,0xf1faead4, 0xfccef6f5,0x083f0318,0x101d0d1e,0x1741122e,0x261d1ec6,0x33742d3b,0x43643a56,0x507c4bc4, 0x59155464,0x665d61d9,0x4f2f67ca,0x2a4e310e,0x32df2d78,0x2fc0325a,0x25b52b33,0x183e1e57, 0x12dc13de,0x1444146d,0x01b8071e,0x11850af1,0x0ea3128b,0xeff003f5,0xafabcadd,0x961ea131, 0x8bfb8e46,0x9be1915f,0xbfafade8,0xb1f9baaf,0xd254c083,0xe54bdee9,0xe32ce4ea,0xdff6e1f5, 0xe241e049,0xf3f4ea8c,0xf9f1f7ca,0xfd79fc12,0x02eafff7,0xf877ffd7,0xee59f2b6,0xe890ebe3, 0xe63fe6e8,0xf24aea1b,0xfb3df764,0x06790124,0x0e8f0b4d,0x16bf1238,0x24841d2f,0x32832bdf, 0x413d38f4,0x4eff4a36,0x56525323,0x652e5ddb,0x4fe06825,0x2b9c322d,0x335a2dcc,0x31f73450, 0x27a12de4,0x1aee20c2,0x14621626,0x1836151e,0x05d4123f,0x10a50801,0x102a12f7,0xf41b0774, 0xb1fdce82,0x97cda36c,0x8a258f02,0x976a8d49,0xbc9fa7d7,0xbab4c6dc,0xcc78bb34,0xe3b6db46, 0xe1c0e3fa,0xe003e127,0xe1d3e00e,0xf39ee8b7,0xf997f7c5,0xfcdbfb85,0xfff1fd83,0xf8b7ff94, 0xee25f2e9,0xe93deba6,0xe5d9e727,0xf1d9e956,0xfacdf822,0x048cff1d,0x0cae098b,0x170b115f, 0x22ea1c29,0x314d2a4c,0x3f4b37e7,0x4d5c480c,0x549c5188,0x61f359f4,0x50b86806,0x2cdc3346, 0x33512ede,0x33f9358b,0x29de305a,0x1d62228a,0x162c189a,0x190a163a,0x103c1a01,0x0e1807d9, 0x10de12d8,0xf80609d4,0xb4ecd233,0x9a15a5aa,0x8a29907e,0x93148a55,0xb634a31d,0xc8d9c9bf, 0xc5f3bd08,0xe12fd689,0xe0c5e2f0,0xdfe4dfb9,0xe1c1dfe8,0xf22de787,0xf956f7cf,0xfc60fb12, 0xfcb6fc70,0xf915fdb3,0xee72f32a,0xe987eb4e,0xe5d0e7d8,0xf12be8ca,0xfb6ff840,0x026bfdb6, 0x0add07aa,0x170e0fa4,0x21851c21,0x2fcc28ae,0x3de636cd,0x4b6145b1,0x531d4fc7,0x5db05770, 0x51c56658,0x2e333498,0x3404305f,0x35df35da,0x2c83327b,0x1f6c2452,0x18691b19,0x19bb17b4, 0x1b871cb0,0x0b720e95,0x1120116a,0xfb290b03,0xb821d5b4,0x9c6fa82d,0x8b379282,0x8f388922, 0xb0a69ebf,0xd245c504,0xc25cc7fc,0xdd6ed096,0xdfe5e142,0xded5de76,0xe16fdfff,0xf059e73b, 0xf940f70b,0xfbd6faaa,0xfab9fc03,0xf87bfa6f,0xeed5f3ab,0xe93eeb64,0xe624e87a,0xf06ce860, 0xfbebf792,0x004dfd83,0x08f7058a,0x15eb0dad,0x20d41c95,0x2e252713,0x3ccf3563,0x48fb43cd, 0x516c4dfc,0x5a4355f7,0x522e62de,0x2fc33650,0x35a531ff,0x37133643,0x2f0134bf,0x211a26c6, 0x1ae51d6f,0x1af5199b,0x21f21d32,0x0d3b1ab1,0x10870e4b,0xfcdd0b5d,0xbb17d8ab,0x9e9bab0e, 0x8cb794c2,0x8c908964,0xac0d9a5f,0xd21cbe92,0xc6f0d535,0xd880ca96,0xdec0de76,0xdd5add91, 0xe150df91,0xef58e6f6,0xf8ebf521,0xfb54fa50,0xfa05fb85,0xf61ef77d,0xef5bf40b,0xe915ebf0, 0xe6dee89e,0xefece864,0xfba3f6c9,0xff1ffe1d,0x06f3033e,0x14130bce,0x211b1c58,0x2c6b25cb, 0x3b7933ab,0x467c4266,0x4f864ba7,0x58275457,0x50875ebc,0x315937da,0x3748337e,0x374a3762, 0x311d368d,0x22f5295a,0x1d4f1f40,0x1c791be1,0x238d1df0,0x168d2568,0x0e4f0c4f,0xfd8c0b43, 0xbdeedaa9,0xa154ae2d,0x8ee2971d,0x8be08aa5,0xa7b996d1,0xcc57b979,0xd352db8f,0xd2a1c936, 0xdcedda97,0xdc44dcc5,0xe141de44,0xef05e685,0xf786f344,0xfae7fa19,0xf9c7fb0d,0xf2dbf61e, 0xf029f31f,0xe97eec91,0xe75ce853,0xef99e8d0,0xfac0f60b,0xff3ffe4c,0x04cb014d,0x123f09ec, 0x21981b0c,0x2ac82571,0x39c631d3,0x448d4115,0x4d7048e6,0x56bb5278,0x4d485bd2,0x334c3848, 0x38fb3533,0x37ee3939,0x33493763,0x25732b9a,0x1f7520d0,0x1e791e54,0x23f01f34,0x23b22a53, 0x0aea1091,0xfd9a0a1b,0xc025db53,0xa477b11f,0x9143998c,0x8c8f8c6c,0xa38f94d2,0xc645b50f, 0xded2d8ff,0xcdb5d072,0xd9efd593,0xdb81db9a,0xe076dcda,0xee8de659,0xf540f260,0xfa96f95d, 0xf976faa5,0xf07bf5e7,0xf07ef077,0xea31ed63,0xe733e850,0xefa2e962,0xf9bdf565,0xffbafd94, 0x027d007b,0x107407dd,0x21121938,0x29a625ea,0x37d02ff1,0x430e3f73,0x4adc4661,0x5526508f, 0x4a345a56,0x350636c5,0x3ae1373d,0x399e3b36,0x350137cd,0x28052dd2,0x212c22ed,0x20dd20ba, 0x24df20dd,0x2d492b35,0x0a3d1c4d,0xfcfd0711,0xc103daf3,0xa77ab3ac,0x93709c5c,0x8dd18e93, 0xa04e9484,0xc165b0a4,0xe1f0d2ac,0xceb6dd1f,0xd5d4cfcd,0xdab1d98b,0xdeefdbe1,0xee05e5fe, 0xf35ff1de,0xfa2df760,0xf918fa3e,0xefbaf5d4,0xef2fed72,0xeafbee60,0xe6dce8e3,0xf00fe98e, 0xf8dbf50f,0xff8cfc76,0x00d800dc,0x0e9c05a8,0x1f8b177d,0x29842629,0x35b62e36,0x416b3d66, 0x47e84462,0x53414e3f,0x487d590d,0x351033e8,0x3cc63953,0x3ba13d15,0x359038cb,0x2a212fe2, 0x22c42576,0x234222ad,0x262f22ec,0x30a92b9d,0x114529a0,0xfb0e03b8,0xc0adda18,0xaa66b573, 0x95fb9f92,0x8fb890df,0x9ede956b,0xbd0aaca8,0xdda5cd0e,0xd81de63b,0xd0c2cc61,0xd979d66b, 0xdda6db3c,0xedc6e4d2,0xf27bf12a,0xf8fdf4e2,0xf8c8f9f4,0xefdcf5ac,0xec67ebc9,0xec13ee7e, 0xe70ce9b9,0xf08fe935,0xf831f52f,0xfe98fb60,0x008c0141,0x0c9b0388,0x1dc215c5,0x29ff253e, 0x33a02d32,0x3f6c3b27,0x456342af,0x51464b64,0x47e9577c,0x331d31c9,0x3eef3abe,0x3d9f3f12, 0x36033ab0,0x2c473129,0x250927d9,0x2590243d,0x27f02555,0x31122cb5,0x1efc3198,0xf7640518, 0xbf8fd87b,0xaceab5e4,0x9906a2b0,0x91f59321,0x9f0a96ea,0xb8b2a9ee,0xd75fc87f,0xe446e68d, 0xcb7ecff3,0xd739d236,0xdcc9da6d,0xed11e32a,0xf1b3f090,0xf693f321,0xf883f967,0xf001f582, 0xe9e0eba7,0xed10eccc,0xe7b6eaa1,0xf06ae8d3,0xf7caf58b,0xfd52fa5b,0x011400bb,0x0a660241, 0x1c0713e6,0x29cf2378,0x31da2d30,0x3d2138d9,0x438240d1,0x4ef0488d,0x477055da,0x309e3153, 0x412f3a5f,0x3fc84154,0x37813cee,0x2e5031a8,0x27bb2a0d,0x277a261e,0x2a2d27cc,0x31a72e25, 0x2baf339a,0xf49c0eff,0xbdc7d525,0xae3bb50d,0x9c0ea579,0x940195a8,0x9ff898c7,0xb4daa8e3, 0xd222c409,0xea8ce121,0xc9dddab3,0xd3eecd23,0xdc13d901,0xeb73e1d9,0xf0aef009,0xf406f21b, 0xf846f7b8,0xf010f55f,0xe902ec23,0xecd4ea19,0xe88cebdf,0xefdbe914,0xf7d9f5bc,0xfc23f999, 0x0148ff96,0x08840261,0x1a4711e3,0x2868219c,0x30ea2d61,0x3a993689,0x41a73e7e,0x4c064628, 0x468a53eb,0x2f243184,0x42223810,0x41d64398,0x398f3ef3,0x2f403251,0x2a0e2c3e,0x291428a6, 0x2c992a04,0x32d13000,0x31b233bb,0xf8871dd8,0xbb0bd079,0xae42b398,0x9f12a7c0,0x963e98bb, 0xa1949af0,0xb2a6a95b,0xcdc6bfd0,0xe8a2db34,0xcfd7e57e,0xcfb3c8c8,0xdb2cd697,0xe9afe0fd, 0xefeceed8,0xf26cf103,0xf781f513,0xf02ef552,0xe982ec89,0xead7e840,0xe995ecb8,0xef87e9ba, 0xf810f547,0xfb1df935,0x0097fe54,0x07d5030f,0x18760fd9,0x26741fe4,0x30e12ca8,0x380834b8, 0x3f7f3be1,0x494c4443,0x4590517e,0x2f343191,0x411435ca,0x441c459b,0x3bb54111,0x2f9e3407, 0x2c492e04,0x2b382b56,0x2f0d2bd5,0x34543250,0x329f3475,0x0525292a,0xb675ce88,0xad49b180, 0xa1d9a8cb,0x98fd9bd2,0xa3959cfd,0xb21faa78,0xc968bc66,0xe2c7d66d,0xdb21e8fe,0xcac5c940, 0xd97ed31c,0xe856e01d,0xef0cecdd,0xf14fefda,0xf585f2bb,0xf053f531,0xea4fece7,0xe866e82a, 0xeacdec01,0xefc5ea78,0xf7d4f482,0xfa4bf924,0xff62fd1c,0x08540305,0x16700e51,0x24861e0f, 0x30a52aca,0x359533d9,0x3cf23922,0x47334252,0x445f4eca,0x2fcc3176,0x3ec73519,0x46934632, 0x3de8435e,0x30be364f,0x2ea42ed6,0x2e162dc2,0x31432dad,0x365934d2,0x32b735ac,0x143b2d38, 0xb139d4e2,0xab91adff,0xa3aea86b,0x9be89ea2,0xa5849f2d,0xb2a8ac0b,0xc539ba96,0xdd3ed212, 0xe3c4e553,0xc792d11c,0xd6d2cec7,0xe767defc,0xed56eb1a,0xeff5eee2,0xf2d3f145,0xf079f431, 0xeaf5ed42,0xe746e91e,0xeb46e9c5,0xf04beb7c,0xf704f42b,0xf9e7f917,0xfe2efc17,0x08f6022d, 0x14800e26,0x229a1c1d,0x2f30288a,0x33b4338a,0x3a163646,0x455c3feb,0x42914c60,0x300d3136, 0x3d003597,0x484744ae,0x400e45ad,0x32ab3867,0x30252f4c,0x30bc3012,0x32fc301b,0x38a4372c, 0x337f372f,0x1d912d54,0xb0cfe32a,0xa928a8b1,0xa448a745,0x9edda136,0xa77da1f7,0xb3dbae04, 0xc24eba74,0xd8dbcdcb,0xe4b9df87,0xca43dc11,0xd336ca40,0xe65fdcff,0xeb23e9c5,0xeeb1ed95, 0xf0cbf00b,0xf065f205,0xeba7edb4,0xe7e8ea37,0xea20e7ca,0xf106ec93,0xf632f471,0xf9d4f88e, 0xfd18fb65,0x08be0107,0x136f0ef0,0x20b11a17,0x2ce5267c,0x32da32b8,0x371f33b4,0x43453d26, 0x40974a82,0x301e3089,0x3cca362c,0x482c4261,0x424c47f1,0x34dc3a86,0x30bd30af,0x33273251, 0x35083317,0x3b283949,0x34cc394d,0x1ff22d94,0xb9eff12f,0xa518a41f,0xa3a3a571,0xa196a2ab, 0xa9c9a4d1,0xb58cafdd,0xc118bb2c,0xd4abc9fc,0xe00bda9b,0xd365e24c,0xcec7c87e,0xe4d4d9f0, 0xe940e8a1,0xed88eb6e,0xef77ee91,0xef3cef90,0xec4bee14,0xe92beb1a,0xe7d1e75b,0xf1f0ec7e, 0xf5dcf4d4,0xf985f778,0xfc2afb0a,0x07c4ffdf,0x13a90f62,0x1ea0184e,0x2a7e246b,0x325030b8, 0x343b31fc,0x40d13a36,0x3f2748ce,0x30202f6c,0x3d953689,0x46684144,0x44c4494c,0x37113cd3, 0x31a032f7,0x35bf33bb,0x37e535dd,0x3d913b25,0x36773bb3,0x1fb82e7c,0xc924f7cf,0x9f5da665, 0xa214a281,0xa39ca2a5,0xac5ba761,0xb73eb19b,0xc120bc51,0xd079c780,0xda85d67b,0xdd2be10b, 0xcad6cd29,0xe272d616,0xe7efe770,0xebe5e92c,0xee3aed5d,0xed04edea,0xecf5edea,0xea62ebfc, 0xe64ee86d,0xf2a5eacd,0xf607f572,0xf8a6f69b,0xfb98fadf,0x06a2fedb,0x14790ee9,0x1c871797, 0x28342249,0x30e42e0a,0x31b43118,0x3df43722,0x3e1246a5,0x2f7e2e41,0x3e1436a1,0x4450417f, 0x46c84889,0x39373f16,0x33683522,0x37ec3455,0x3af3386c,0x3f963d77,0x38a13e2e,0x201a2fc9, 0xd529f84d,0x9c39b284,0x9fe79dbe,0xa482a198,0xaefaa9d2,0xb8efb3f1,0xc200be0b,0xcd29c6d6, 0xd62fd283,0xe0e2dbf0,0xcabdd6d6,0xdf0cd19e,0xe6aae599,0xe98be75c,0xecddec1f,0xeb04ece1, 0xed86eca6,0xeb80ece5,0xe684e9e0,0xf1e9e884,0xf64df63a,0xf778f652,0xfb6bfa65,0x059ffe21, 0x14bc0df7,0x1af61827,0x25e72014,0x2e552b6d,0x3014301c,0x3af03429,0x3cef4419,0x2e8d2db2, 0x3e613695,0x43b24253,0x477a467a,0x3b6f4165,0x35b43744,0x391a358b,0x3db23b1e,0x41934090, 0x3b104084,0x2123318e,0xd90ef790,0xa1eac23e,0x9c73982f,0xa4179fd9,0xb169ab77,0xbac3b678, 0xc359bfb0,0xcb62c72e,0xd25eceb2,0xddffd6f1,0xd0e9debc,0xdac6ce53,0xe51ae2b9,0xe736e5da, 0xebb0ea1d,0xe9d9eba2,0xed4aea99,0xec9aedcf,0xe7e0eb2d,0xefb3e776,0xf6c5f65e,0xf6a0f653, 0xfb36f949,0x04b2fdb7,0x14100ce8,0x1a9718d4,0x23811dec,0x2b6328da,0x2f122e0b,0x37dc31c2, 0x3b69414b,0x2df22d80,0x3ead3613,0x446d42f9,0x466044f1,0x3dd14336,0x3801398d,0x3a0437c9, 0x40813d47,0x444d43b2,0x3d93428b,0x227d33c7,0xd80ef7a7,0xb0aacc10,0x96f29737,0xa2949d2c, 0xb364abab,0xbcf8b8bf,0xc4eac121,0xcb05c808,0xce7ecbe0,0xd8c2d2f6,0xda31dff9,0xd655cfc4, 0xe2e8df07,0xe57ee473,0xea55e7b3,0xe90aea80,0xebfbe924,0xedb1ee6e,0xe95fec65,0xed87e812, 0xf74af4f6,0xf65ef679,0xfa94f81b,0x0419fd9f,0x13170bf8,0x1b3318bd,0x210f1c84,0x288b2640, 0x2d942b05,0x34f0302f,0x396a3e3f,0x2dca2cf5,0x3e8c3544,0x45424352,0x445744cf,0x3ff1434f, 0x3a223bbe,0x3ba23a1a,0x43373e5a,0x478b466d,0x3fd744b9,0x24643636,0xd6e5f849,0xbfefcdd4, 0x91f2a080,0xa06e98f7,0xb472aab6,0xbf49bae9,0xc66cc2fe,0xcb96c980,0xcb21cac7,0xd454cf61, 0xdfe9dc03,0xd3fbd6e5,0xdfc6daa8,0xe402e2b3,0xe83ae59c,0xe808e982,0xea4de86c,0xeebfee1c, 0xeac1eda4,0xecf2e98a,0xf6edf28b,0xf65cf6eb,0xf979f775,0x03d7fd63,0x121c0b2e,0x1b9b17ea, 0x1edc1c61,0x25c7239b,0x2af527e1,0x32b72ef5,0x372a3b31,0x2dc42c00,0x3df034e5,0x45c84394, 0x433e45a8,0x413941ca,0x3c5b3df8,0x3e073c4c,0x45213f85,0x4a9d4955,0x41ef47c1,0x26bc38be, 0xd6b2f963,0xc76dcc51,0x93f0b12f,0x9d46930d,0xb423a8db,0xc165bc8e,0xc7efc539,0xccaecb17, 0xc908caef,0xd0b2cbc4,0xdefed6f7,0xd6b4def0,0xdbbed66f,0xe260e015,0xe5d7e3e8,0xe718e800, 0xe943e7b2,0xef44ecb9,0xec04eeca,0xedc3eaec,0xf4fbf0aa,0xf67cf721,0xf873f73d,0x03b0fc97, 0x11270aa4,0x1b1516d7,0x1d9d1cd3,0x22fa20f6,0x27ba24ea,0x31512d08,0x34cf3882,0x2d702aba, 0x3d65350a,0x464f4384,0x43b74688,0x40ec402b,0x3ea83fff,0x407d3e98,0x465141b1,0x4d874c0e, 0x44804b29,0x294f3b0b,0xd6e0fb03,0xc791cb4c,0xa08bbf03,0x981d8f3f,0xb28aa618,0xc326bce1, 0xc9c0c733,0xce2acc68,0xc87ccbaa,0xcd2fc8d4,0xda4ed2e6,0xddebe217,0xd748d52d,0xe061dca4, 0xe406e26f,0xe657e5f9,0xe8efe6f9,0xeed3eb7b,0xed5befe5,0xef13ec3a,0xf283f072,0xf6d6f62f, 0xf806f735,0x0348fb7e,0x106b0a6c,0x1a0a15cc,0x1d7b1cc0,0x20251ebe,0x247f21f2,0x2fd829fe, 0x32693681,0x2c912922,0x3d3334f2,0x467f42df,0x449f46fb,0x3f483fa4,0x40c940ca,0x42b540d4, 0x47dc4441,0x50814dbc,0x47d24e2a,0x2be23d3e,0xd793fd0d,0xc5f5cb1d,0xb1f3c3ff,0x91fe9497, 0xb034a229,0xc44fbbff,0xcbe3c916,0xcfb9cdf8,0xc905cd13,0xc9e0c770,0xd593cf7f,0xe41ddf63, 0xd3a3d914,0xdd8ed87d,0xe290e0cc,0xe4f9e3fa,0xe87ae673,0xeda2eb01,0xee9df049,0xf03eed77, 0xf10ff15d,0xf6bef3ec,0xf7f9f765,0x0262fabf,0x10020a3f,0x18ec14e5,0x1d9b1be3,0x1d6f1da4, 0x216e1efd,0x2d78269a,0x307c351d,0x2b6c2770,0x3d55347b,0x463d4278,0x455c4768,0x3dff4064, 0x42724005,0x44ff4308,0x4a4d46ac,0x530d4efa,0x4b375127,0x2e3f4025,0xd8d4ff58,0xc551cb57, 0xbda3c323,0x904fa42b,0xacfc9c3d,0xc423ba08,0xcdbfca9c,0xd110cfee,0xca18cec7,0xc77ec76b, 0xd1cccc11,0xe4abda43,0xd388dfca,0xd9d5d408,0xe116de8f,0xe31de273,0xe7f9e5be,0xecc1eace, 0xef8cef9b,0xf141eea2,0xf122f272,0xf550f194,0xf805f7a2,0x014dfa80,0x0fc309a3,0x17ca142a, 0x1cfc1a9c,0x1b561d61,0x1e591c07,0x2a372355,0x2f4e3360,0x2a1a25ed,0x3d3d33ad,0x45ce429a, 0x45fa47a6,0x3e2b4181,0x42e83e9f,0x475d4527,0x4d024914,0x54ac50fa,0x4e575446,0x30cd43c0, 0xda7c01a3,0xc543cc14,0xc038c1b2,0x9938b51a,0xa81b9659,0xc2a0b722,0xcf4acb22,0xd2a1d1c5, 0xcba5d039,0xc69ac81a,0xce62c8f8,0xe080d5ae,0xd82ce3e0,0xd59dd122,0xdf75db8f,0xe1a0e141, 0xe7c0e47e,0xecaaea8d,0xefbaee9a,0xf242efc3,0xf207f35c,0xf2e4f091,0xf857f72f,0x00b8fa8e, 0x0f7408a1,0x16d213c0,0x1bb31952,0x1a4f1cfe,0x1b45194b,0x26c52023,0x2e63309c,0x28a224df, 0x3ca33282,0x459b42b9,0x466a474d,0x3f224235,0x41e53dd6,0x49734665,0x4f544b63,0x561b538c, 0x51815699,0x342a4727,0xdc6903cb,0xc5a2cd5c,0xbea5c158,0xaababe03,0xa16d9753,0xc032b345, 0xd079ca68,0xd4a0d36e,0xcd8cd1c3,0xc70cc985,0xcb21c73a,0xdb25d209,0xdddde259,0xd152d219, 0xdd09d7a4,0xe092dfe6,0xe75de31e,0xecf9eaa4,0xef4bee7d,0xf34ef0ad,0xf2c7f427,0xf08ff0a3, 0xf82ef507,0x006efa73,0x0edf07ae,0x169713ce,0x1abe18a8,0x1a301c4f,0x18231771,0x22f71c9b, 0x2c2d2c89,0x26fc23df,0x3bc330f1,0x466142d0,0x475b47a5,0x40be439c,0x40c13ebb,0x4aab4619, 0x50b94cd0,0x5797551f,0x54685796,0x38944a8d,0xdf64074e,0xc7a4d036,0xbdeec244,0xb9b7be9c, 0x9b82a2e9,0xbbb1ac51,0xcff3c786,0xd6b4d4ae,0xd035d464,0xc93ecc9d,0xc927c7f1,0xd670ced6, 0xdecadcb4,0xce06d5b2,0xd90ed247,0xdfc9dde5,0xe776e2ca,0xeec7ec3a,0xf068f096,0xf557f21f, 0xf3ecf5c0,0xefeef191,0xf786f29d,0x014bfb40,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000, }; static const PROGMEM uint32_t sample_2_SawWave_SAW0_72[5120] = { 0x00be0000,0x06fd0295,0x0d1c08f1,0x12d50eea,0x1bbd14e0,0x25f11f91,0x2fe02941,0x38f731ea, 0x40b73968,0x49c74022,0xdd9c2095,0xee9ef125,0xfa8ef77f,0x0679ff17,0x11170776,0xc52a04f3, 0xc76bb09d,0xcf40c28e,0xda3bd26c,0xe6a3e04e,0xf2eeec93,0xff9bf7c2,0x0aed0371,0x15870e4b, 0x1fc21938,0x299c2336,0x32f32ad7,0x3b08318a,0xd1b4f871,0xe21de59d,0xedbaedc4,0xf969f78b, 0x0580015b,0x114c0aa4,0x1bf613f7,0x24521df0,0xec3c2497,0xd85fc353,0xdd77d7a6,0xe74fe500, 0xf328f048,0xfe66fae5,0x094a04df,0x13260fca,0x1b7919b6,0x248123af,0xd7ec25e2,0xd7ccc94a, 0xe15ad7bc,0xec1be3fb,0xf747f048,0x02e3fc20,0x0edb075b,0x1aa811b5,0x257c1ba0,0x2e3c25b3, 0x34252fbe,0x0f8d38ef,0xe21bd481,0xe807e74c,0xf28cf10e,0xfe06f9a5,0x088802a9,0x12250a67, 0x1ce51358,0xb41af99d,0xc6a1c790,0xd3fcd130,0xe062dc1c,0xec58e7bf,0xf7fef3ae,0x03d1ff9b, 0x0fa80aed,0x1b2d1550,0x25b51f3c,0x2e3c2893,0x350d3213,0x3a4d3bbb,0x280244a8,0xe1e3e822, 0xeb63f365,0xf67df996,0x006d0088,0x0945099d,0xc1a90d21,0xbdd8ae5e,0xc790bf10,0xd3f2cc16, 0xe0e5d8f3,0xecffe5a5,0xf8eef21f,0x04bdfe9e,0x10580a78,0x1bd4157a,0x25cf1f75,0x2ea628c3, 0x360c3249,0x3c2c3ba0,0x41e14438,0x3d304b24,0xe332fe68,0xf0e6fa20,0xfb3dfd2a,0xe376054d, 0xaf4a9dfd,0xb8bbb023,0xc4e7bd84,0xd1bbca67,0xdf32d713,0xec87e3fb,0xf8daf125,0x04b6fdc3, 0x106809f8,0x1b451527,0x25811eda,0x2e99284d,0x36773187,0x3d513aa2,0x43ca430c,0x4a8b49a5, 0x4dd94dc8,0xe9441416,0xf692f928,0x9796ad32,0xa842a60a,0xb4cdb0a0,0xc10abcbc,0xceeac9be, 0xdc58d67f,0xea07e338,0xf71af064,0x0359fd93,0x0ea609e9,0x196014bd,0x23a21eba,0x2d00280b, 0x353c313e,0x3c8c3a09,0x43334256,0x49f0494b,0x51274d85,0x59284f7a,0x84a70b70,0x9e4d996a, 0xa93ca00d,0xb424ac29,0xc05dba36,0xccabc790,0xdac9d4b1,0xe823e1cb,0xf538ee85,0x01acfbe4, 0x0cb30877,0x1737138b,0x215f1dbd,0x2ace273f,0x3339304b,0x3a683960,0x40f541c9,0x469e48f2, 0x4cbb4f16,0x069d4ee6,0xfdfee8ba,0xa329df65,0xae37991d,0xb631a738,0xc04bb620,0xccdcc49b, 0xd987d23a,0xe754ded0,0xf430ebfc,0xffdaf86a,0x0b1704df,0x15d410ae,0x1fd81b0a,0x29522486, 0x31f92dac,0x39773655,0x3f8f3ea1,0x454d4607,0x2c6b4da5,0xf47ee41d,0xfcc4f127,0x04c9f90b, 0xbd36f83e,0xb9eda07b,0xc05fb3b5,0xcb12c2ea,0xd819d0a8,0xe51bdd79,0xf1eee942,0xfd8df568, 0x089b0117,0x137a0cc8,0x1e05179c,0x27cd2119,0x30e5299b,0x38ca31d8,0x404738db,0x42e33fa1, 0xe098f9e0,0xf05bf00d,0xfb57f5df,0x0519fd95,0x0cce0710,0xda0c0e32,0xc21bad2f,0xc89dc372, 0xd45cd12b,0xe198dd40,0xedc2e86b,0xf997f2fc,0x04b7fedc,0x0f1809ec,0x19b514af,0x23e21e88, 0x2cf4273f,0x35382e8c,0x3e1c359e,0xd7361e0a,0xe720e5aa,0xf1d0edbb,0xfca1f643,0x06efffa8, 0x0f840984,0x168f1474,0xf87e1f10,0xc822be8a,0xd0f9d317,0xdd09dd58,0xe9cfe702,0xf570f18f, 0x0022fbd0,0x0a7a0766,0x13fe11f9,0x1dd51bfc,0x2674250c,0x2e152dcc,0xea5d31a3,0xe1a4d06a, 0xe996e089,0xf3c1eb88,0xfe94f5f9,0x0902002b,0x12920ab2,0x1ac115b8,0x21ef20d4,0x151f2b47, 0xccc8d484,0xd987df0e,0xe66ce5b5,0xf27cee27,0xfd26f859,0x06ae0293,0x10720d6b,0x18d8171c, 0x21862021,0x0bfe2a3d,0xd45cc54f,0xddcad5de,0xe82ae12b,0xf353ec4b,0xfeb7f70e,0x09cf019f, 0x13ef0c5f,0x1cfd1771,0x25332275,0x2cc92c8e,0x2b893445,0xd1eeed67,0xe34ee74f,0xefebeb5d, 0xfadef346,0x04b7fd2f,0x0d4c06c9,0x17390fbf,0x1c5f17e2,0xbc85d58a,0xce1bcdc2,0xda30d73a, 0xe5e2e232,0xf1abed9f,0xfd72f8b8,0x092603c5,0x13a30eb6,0x1cbb1933,0x24f323aa,0x2c542ce9, 0x34613497,0x39cd39f7,0xd6c0069f,0xea26ea14,0xf4c0ed98,0xfd9af5f3,0x060a0030,0x0de70907, 0x17b811e3,0xbb66065c,0xc822bf01,0xd2afcb69,0xdd4dd752,0xe844e2d1,0xf36eedfd,0xfe9ef8b2, 0x095f0383,0x131a0e64,0x1c31191b,0x24e7236e,0x2d402c0d,0x363732cc,0x3e8e3796,0xdcb018c9, 0xedd9e395,0xf5adea5a,0xfd3ff47c,0x059cff32,0x0dbf0801,0x17e6105c,0xb9bc02c0,0xc747be45, 0xd1d2cad6,0xdca9d6cc,0xe7d8e235,0xf32ded3c,0xfe4df803,0x08ce030d,0x12950e2b,0x1c0c18ca, 0x257b229a,0x2e922a88,0x37a730e3,0x3fad3634,0xe89328c4,0xf049dcb7,0xf50ae8ea,0xfc06f444, 0x04bdfebb,0x0d610735,0x17ac0f00,0xb7f9ff7c,0xc622bdf1,0xd0cfca81,0xdc0ad64d,0xe77ae189, 0xf2d2ec77,0xfde3f760,0x085102a1,0x12610dbd,0x1c6b1802,0x266e214f,0x2fbf28d2,0x38342f80, 0x3ea1362b,0xf96d350c,0xef85d80f,0xf2b2e9d9,0xfa34f52a,0x03a2fea6,0x0ccc06a0,0x16e10e16, 0xb5dcfcff,0xc4d1bda4,0xcfc2ca29,0xdb65d5b9,0xe703e0dc,0xf252ebc9,0xfd4bf6e0,0x07e00237, 0x125d0d20,0x1cda170e,0x270d2004,0x2ff527b4,0x37662f33,0x3c833744,0x0c503ceb,0xeb1dd8b0, 0xef61ecdb,0xf862f650,0x029bfe6a,0x0c1605f7,0x15cf0d54,0xb3c7fa5e,0xc36bbd85,0xcecec9d1, 0xdab3d510,0xe665e037,0xf199eb4e,0xfc99f685,0x076701e2,0x12440c7f,0x1cf3163b,0x26e31f4a, 0x2f16279c,0x35ac300c,0x3a7a38dc,0x1e9a40eb,0xe460dfbe,0xecc4f01f,0xf777f68e,0x01fafd90, 0x0b7f0524,0x14b80cb5,0xb1bef80a,0xc26abd22,0xce06c935,0xda1ed454,0xe5b6dfa3,0xf0cdeaf5, 0xfbe0f648,0x06f60181,0x11fc0bf5,0x1c9215c0,0x25f21f30,0x2d902832,0x33e93134,0x396839ef, 0x2e154177,0xddfbec7d,0xec0cf1bb,0xf79df565,0x01cbfc0d,0x0afd0403,0x13d00bef,0xb032f516, 0xc1aabce8,0xcd83c879,0xd98dd3ac,0xe4fedf40,0xf006eabb,0xfb3df606,0x067f0119,0x11780b77, 0x1bb31587,0x248b1f78,0x2bf328f1,0x32b23206,0x398539f5,0x39863fec,0xda5afdc9,0xed91f037, 0xf8a5f2df,0x01c4fa2e,0x0a8e02ce,0x13020b16,0xaf19f16a,0xc161bc70,0xcd1ac7b7,0xd8f5d2f6, 0xe44ddedd,0xef60ea6e,0xfac1f59d,0x06110097,0x10cf0b0c,0x1aad157c,0x23451fcb,0x2ae6294d, 0x327b31ee,0x3a8c38e6,0x40693db0,0xdc371095,0xf0b7eb4a,0xf9a7efc7,0x016ff889,0x09fe01cd, 0x127d0a26,0xae0bedc4,0xc100bbc2,0xcc95c6e5,0xd83ad264,0xe3a8de82,0xeedfe9fe,0xfa60f503, 0x05a7fff6,0x10200a9f,0x19ce155c,0x22901fc3,0x2ac028ed,0x333030d8,0x3bd1371b,0x438a3bc5, 0xe4692234,0xf3a5e488,0xf9b6ed88,0x0083f7c7,0x09340121,0x11c80955,0xad3ee9d9,0xc09bbb26, 0xcbdbc654,0xd771d1fa,0xe319de1c,0xee80e96e,0xfa17f457,0x053eff56,0x0f880a34,0x194b150a, 0x22711f3d,0x2b4727df,0x34302f37,0x3ca03555,0x43b93ac9,0xf20530ce,0xf4a8de80,0xf846ed41, 0xfefef80b,0x084800df,0x1123089f,0xabf0e625,0xbfc3bb1d,0xcaecc61a,0xd69cd1ca,0xe29addb8, 0xee27e8e7,0xf9aff3be,0x04c0fed9,0x0f0109d4,0x190c1493,0x22a11e65,0x2be72695,0x34cc2dc3, 0x3c72344c,0x42223afe,0x02de3b5a,0xf29fdbd9,0xf5bfef02,0xfd4af8fa,0x073a00b2,0x101c080b, 0xaab9e25b,0xbeafbb3b,0xc9d7c61b,0xd5d0d193,0xe21add48,0xedbbe85a,0xf938f33c,0x042bfe72, 0x0e84097e,0x18f41403,0x22db1d7d,0x2c1f2579,0x34902cef,0x3b4d3446,0x3ff23c0b,0x150d41bc, 0xed9dde3c,0xf2f5f1fe,0xfbd4f9c5,0x06620045,0x0f23074a,0xa93edee1,0xbd93bb9e,0xc8d8c626, 0xd51dd145,0xe18edcbc,0xed30e7e4,0xf880f2dd,0x037efe2e,0x0e090930,0x18c21370,0x22b51ccf, 0x2bb024ec,0x337b2cf0,0x399e351c,0x3e3f3d5f,0x260f44b2,0xe6dae6a8,0xf0d0f4a7,0xfb1bf9b0, 0x05c7ff5e,0x0e230682,0xa7c6dbc8,0xbc65bb57,0xc7e4c5c2,0xd46bd089,0xe0ecdbfa,0xec74e757, 0xf7b6f290,0x02cafdf8,0x0d9308de,0x186d12fa,0x22351c7b,0x2ab22507,0x31f92dae,0x38103653, 0x3d863e6b,0x3452450f,0xe107f46f,0xf0acf553,0xfb66f82e,0x0588fdd6,0x0cf40583,0xa6b9d87d, 0xbbabbacd,0xc754c4ff,0xd3f4cfa4,0xe051db27,0xebb8e6d6,0xf6f4f241,0x0231fd9d,0x0d23086e, 0x17e9128f,0x21501c5a,0x2963255e,0x308f2e6c,0x372c36fd,0x3df33e42,0x3ee74383,0xde8605ea, 0xf298f2d6,0xfc42f586,0x0552fc24,0x0bf60491,0xa5d9d55f,0xbb3eb9c1,0xc707c406,0xd379ce95, 0xdfaada63,0xeaffe65e,0xf652f1df,0x01bafd1f,0x0cbe07e5,0x17441229,0x20681c59,0x285725ab, 0x2fe22eb4,0x375236c0,0x3f233d1f,0x451d417c,0xe17d18cd,0xf597ed47,0xfcd3f2d1,0x04a9fadf, 0x0a8203ef,0xa536d265,0xbaffb880,0xc6a9c2ed,0xd2e5cd98,0xdee0d9b1,0xea57e5e1,0xf5d5f152, 0x015efc77,0x0c520744,0x169c11c0,0x1fad1c38,0x27cb258e,0x2ff82e39,0x382735af,0x40523b87, 0x47723ffb,0xeb0f2a20,0xf7e6e63f,0xfc4df133,0x0370fa7e,0x08f60380,0xa4adcf4e,0xba88b763, 0xc623c20b,0xd212cce1,0xde03d927,0xe9bce55c,0xf570f0ac,0x00fafbb9,0x0bdc06ab,0x1607115b, 0x1f391bdf,0x27d12505,0x30902d2d,0x3917343b,0x40f13a20,0x47363f8f,0xf9d937f2,0xf794e0e5, 0xfa6af1ab,0x01c5fb08,0x074e0373,0xa40bcc79,0xb9d6b66d,0xc54ac170,0xd117cc70,0xdd2dd8c2, 0xe93be4cb,0xf511f006,0x008afb19,0x0b600628,0x15881100,0x1f0c1b62,0x280e243a,0x31152c07, 0x397c330a,0x4087397b,0x459b401d,0x0b574176,0xf451dfb6,0xf7adf3d2,0x0002fbed,0x0557034f, 0xa3a0c989,0xb8edb5f3,0xc461c120,0xd014cc37,0xdc70d860,0xe8b8e431,0xf499ef6d,0xfff7fa91, 0x0aba05c5,0x151010a3,0x1ee01ac9,0x2823235a,0x31172b1c,0x38f6327e,0x3f3039b4,0x4394413b, 0x1d6b4715,0xee63e407,0xf51df6c0,0xfec7fc75,0x03aa02f2,0xa331c65b,0xb807b575,0xc36cc0e5, 0xcf39cbf9,0xdbd2d7da,0xe83ee386,0xf40beee2,0xff43fa2b,0x0a100577,0x14911043,0x1e9c1a31, 0x27e022b1,0x30692aad,0x37b432a5,0x3d743a90,0x420a4254,0x2df44927,0xe7adee44,0xf3d2f8a0, 0xfe53fbd9,0x021601df,0xa2c2c355,0xb726b4ff,0xc2aac070,0xcea2cb79,0xdb57d70f,0xe7b6e2c1, 0xf362ee5b,0xfe87f9cd,0x09680524,0x141e0fd3,0x1e28199e,0x272c2247,0x2f3d2ab1,0x362c332a, 0x3c0b3b5d,0x419a42be,0x3b2048a3,0xe2a5fd6c,0xf45df7fb,0xfe8dfa26,0x00a80096,0xa29cbfee, 0xb67bb47b,0xc234bfc4,0xce4ecaae,0xdaefd622,0xe728e1f5,0xf2b9eddf,0xfdd8f972,0x08e404be, 0x13b40f57,0x1d9b192e,0x26502229,0x2e122afc,0x350433b5,0x3b7d3bb3,0x4229425a,0x43ee471b, 0xe1f70f24,0xf664f471,0xff25f7bb,0xff12ff45,0xa23cbc69,0xb5e3b3e1,0xc1d6beb7,0xce05c9af, 0xda7dd522,0xe682e13d,0xf213ed65,0xfd4df907,0x08830435,0x13510eca,0x1cfd18cc,0x257b2214, 0x2d372b28,0x348033ca,0x3bb93b4a,0x43454132,0x48f24568,0xe6e020fa,0xf8d7eea5,0xff30f59a, 0xfce3fe76,0xa21bb8fc,0xb573b339,0xc194bda0,0xcdb9c8aa,0xd9eed449,0xe5cfe095,0xf182eceb, 0xfce4f881,0x0832038c,0x12f50e33,0x1c6d1862,0x24e421ed,0x2cd92afa,0x34c0333e,0x3c953a34, 0x444f3fb7,0x4ac84438,0xf15830e5,0xfa4ce87f,0xfe52f4b8,0xfa51fe75,0xa1a1b613,0xb514b2a0, 0xc11bbc92,0xcd31c7da,0xd922d39f,0xe506e015,0xf0f8ec66,0xfc8bf7d8,0x07da02d9,0x12860d9e, 0x1be21802,0x24862192,0x2cdd2a5e,0x354a3238,0x3d5b38e2,0x44ab3e88,0x4a4743f4,0x002e3db0, 0xf94ce414,0xfc3ef589,0xf735ff1a,0xa130b396,0xb484b202,0xc06cbbac,0xcc63c740,0xd836d332, 0xe438dfa1,0xf07bebcf,0xfc24f735,0x076c023a,0x12060d25,0x1b6417a2,0x2459210e,0x2d1b299c, 0x35bf311e,0x3da437d9,0x44253e1d,0x488b44a3,0x119a4674,0xf56ae3bf,0xf988f7e1,0xf3d00018, 0xa0deb0d6,0xb40ab165,0xbf8cbb08,0xcb7cc6d3,0xd73fd2dc,0xe37edf28,0xf000eb29,0xfbb3f694, 0x06e101b0,0x11710cc2,0x1af6173e,0x24422078,0x2d3a28cf,0x35b83054,0x3d183772,0x42e53e76, 0x46c545d9,0x234a4b6a,0xef4be8fe,0xf70ffa91,0xf1190088,0xa0aaade9,0xb36eb0a1,0xbe8aba6d, 0xca84c671,0xd668d27c,0xe2ebde8a,0xef83ea69,0xfb24f601,0x063b014a,0x10d40c74,0x1a8f16e9, 0x24091fef,0x2cf42840,0x35133009,0x3be837c4,0x41563f63,0x457d46f4,0x32e24d3b,0xe8e7f3f0, 0xf5e7fc24,0xeebbfffb,0xa0f5aa94,0xb303afb3,0xbdaab9d5,0xc9cfc5e0,0xd5d9d1e2,0xe278ddb0, 0xef05e99d,0xfa86f577,0x058e00ec,0x10410c22,0x1a271678,0x23a21f68,0x2c5327ef,0x34053022, 0x3a89385c,0x40154031,0x45394755,0x3f5c4cd3,0xe4990301,0xf687fb44,0xed4efe42,0xa14fa704, 0xb292aea8,0xbcfeb927,0xc95ac515,0xd586d0fe,0xe213dcad,0xee75e8cf,0xf9e3f4ee,0x04ea007e, 0x0fc10bab,0x19bf15e9,0x23121ee8,0x2b7427c4,0x32da305b,0x397038c7,0x3f9a406b,0x45d746b9, 0x47f44afd,0xe44f14f7,0xf8b4f753,0xebdbfbe4,0xa16ca446,0xb243ad9a,0xbc8ab87d,0xc921c414, 0xd552cffc,0xe1aadbac,0xedd3e80a,0xf942f467,0x0462fffd,0x0f580b04,0x19481538,0x22611e6a, 0x2a8f2792,0x31ed304d,0x38f5388a,0x3fe43fa1,0x46db4537,0x4c524918,0xea65279f,0xfb2af096, 0xea5ff9e8,0xa0cea2ba,0xb1e9ace3,0xbc40b7db,0xc8ecc307,0xd508cf0c,0xe10cdad8,0xed1ae76f, 0xf8b0f3dc,0x03f7ff57,0x0ef80a42,0x18ce1483,0x21b11de3,0x29e62732,0x318f2fdd,0x391e37ae, 0x409d3e3f,0x47934397,0x4d5a47f9,0xf6e9378a,0xfbafea07,0xe7d1f9af,0x9fa5a250,0xb15bac5a, 0xbbeeb74b,0xc87fc218,0xd480ce5b,0xe045da48,0xec58e6f2,0xf82bf347,0x0399fe9e,0x0e89097f, 0x184613d9,0x21161d62,0x297b26a6,0x318e2f0c,0x39883672,0x41133ccd,0x477d4275,0x4c5a47da, 0x079a435b,0xf911e6c7,0xe3f5faf9,0x9e67a25b,0xb0cfabf9,0xbb80b6c3,0xc7c5c165,0xd3b6cde3, 0xdf5cd9e6,0xeb95e674,0xf7abf29d,0x0323fddd,0x0e0108cb,0x17a21347,0x20881cde,0x293925f9, 0x319e2e19,0x39a53552,0x40ec3be1,0x469d4225,0x4a93488a,0x197c4ad8,0xf3dde8b1,0xe010fd3b, 0x9d64a1ba,0xb04aab58,0xbb09b630,0xc6eac0d3,0xd2decd85,0xde7ed993,0xeaf3e5e8,0xf734f1ee, 0x029ffd3d,0x0d620848,0x170412d8,0x20131c6b,0x28ff2551,0x31752d4d,0x394c3496,0x40163b92, 0x45314281,0x48e2495c,0x2a854e6a,0xed7af052,0xdc87febb,0x9d43a086,0xb00aaa91,0xba9ab588, 0xc617c065,0xd220cd24,0xdddbd92b,0xea6fe53d,0xf6b8f129,0x0207fca9,0x0cb507d9,0x1660126f, 0x1f901be8,0x289d24a4,0x30f82cae,0x38683448,0x3ec93bb9,0x43c3430f,0x47ec49e9,0x38ee4f20, 0xe7e5fd3f,0xda7ffe7a,0x9dda9e63,0xafeea973,0xba43b4d2,0xc55cbffe,0xd199cc97,0xdd6bd88c, 0xea07e468,0xf62ef065,0x0170fc27,0x0c09076f,0x15cb1200,0x1f1f1b5c,0x2818240c,0x30332c52, 0x37503444,0x3d833c0b,0x42cc435e,0x47e649b5,0x438c4e24,0xe5c80dcc,0xd9a3fb51,0x9e9f9bde, 0xafd9a82f,0xb9ddb40f,0xc4d2bf7b,0xd141cbd0,0xdd24d7b4,0xe999e37b,0xf591efa4,0x00c5fb9b, 0x0b6d06f0,0x154d1166,0x1ea81abc,0x276f237e,0x2f4d2c08,0x3646343e,0x3cb23c11,0x4289431a, 0x487c48ca,0x4a394c83,0xe88c1f24,0xd917f610,0x9f539919,0xaf85a732,0xb96bb357,0xc462bede, 0xd0f6cad7,0xdcdcd6c5,0xe917e296,0xf4f3eef4,0x0031fb0e,0x0af80667,0x14eb10c1,0x1e411a19, 0x26dd2307,0x2ea02bcb,0x35ac340f,0x3c803bb4,0x42f24250,0x494d4779,0x4d854b1a,0xf0d32fcb, 0xd830f012,0x9f379755,0xaedfa6a7,0xb8d7b2cb,0xc40dbe47,0xd09bc9e3,0xdc72d5f8,0xe86ee1e5, 0xf440ee5f,0xffabfa82,0x0a8e05c7,0x14891007,0x1dcb1973,0x263f2292,0x2e182b64,0x356e338d, 0x3cb23ad1,0x4380410d,0x49b6462f,0x4dfe4a57,0xfe103dc1,0xd52beadc,0x9e7d970a,0xade1a6b3, 0xb837b26f,0xc3aabdbd,0xd016c906,0xdbdfd559,0xe7a6e15e,0xf385eddc,0xff2af9e3,0x0a2e051d, 0x141b0f50,0x1d4718dc,0x25bf2213,0x2dc72adb,0x357132ce,0x3cfd39c0,0x43c33fe4,0x497a4563, 0x4cf44a70,0x0ec247d0,0xcf82e953,0x9d1297ac,0xace6a710,0xb793b21d,0xc33fbd31,0xcf57c85f, 0xdb22d4e0,0xe6cfe0fd,0xf2d5ed59,0xfeaff939,0x09c2046d,0x13920eb1,0x1cb71852,0x25432193, 0x2d902a31,0x357831ef,0x3d0438c7,0x437a3f23,0x4892452b,0x4b6e4afe,0x20294df2,0xc806eccf, 0x9bbb98ad,0xac15a740,0xb6ffb18f,0xc2b8bc99,0xce77c7e0,0xda4ad47a,0xe605e096,0xf238ecc2, 0xfe33f882,0x093d03c8,0x12f70e29,0x1c2217e2,0x24d6211b,0x2d552990,0x354b3137,0x3ca03833, 0x42b33ef5,0x4755458f,0x4a384bb6,0x300a50c5,0xbfe4f57e,0x9b2c98ca,0xabbaa6ca,0xb689b0b1, 0xc22bbbe8,0xcd8fc763,0xd98ed3fc,0xe55be013,0xf1adec01,0xfdacf7ba,0x08a00338,0x124c0db5, 0x1b901775,0x2468209d,0x2cf928f6,0x34d030b4,0x3bce37fc,0x41993f29,0x46394612,0x49a54c0c, 0x3d6d5137,0xb9a802c5,0x9bac96ec,0xabd3a5a0,0xb635af8b,0xc1a6bb1f,0xcccfc6d9,0xd8f7d353, 0xe4e4df5d,0xf135eb22,0xfd13f6f5,0x080202a6,0x11b00d3d,0x1b0916f6,0x23fd200f,0x2c832868, 0x341f3061,0x3ae237fa,0x409f3f61,0x459f4643,0x49de4bb6,0x47025013,0xb70e12d2,0x9d209306, 0xac2ba418,0xb5dbae74,0xc121ba61,0xcc32c64f,0xd88ad27a,0xe48fde8a,0xf0b7ea3d,0xfc7bf63e, 0x07690226,0x11230cc0,0x1a971663,0x23981f7d,0x2bee27ea,0x33623025,0x3a1237f2,0x40073f52, 0x459645df,0x4a954ac5,0x4ce84e96,0xb936235b,0x9e778d33,0xac4fa2c7,0xb54ead90,0xc08fb9b2, 0xcbb4c5b1,0xd829d186,0xe42adda5,0xf021e966,0xfbcaf594,0x06d30198,0x10a80c29,0x1a3615be, 0x232b1ed9,0x2b5c2770,0x32c62fd5,0x399937ac,0x3ff23ed6,0x46024501,0x4b534980,0x4f7d4d62, 0xc0b83219,0x9ecf876c,0xabcfa21d,0xb47cad27,0xbfe9b931,0xcb42c511,0xd7b6d099,0xe3addcdb, 0xef6fe8bd,0xfb13f4fd,0x065200fa,0x10400b82,0x19d31508,0x22b61e36,0x2ace26f7,0x325b2f69, 0x39763722,0x40363dfb,0x468543d6,0x4ba84855,0x4ff54cc4,0xcc7e3e14,0x9d2083d9,0xaabfa293, 0xb36ead3d,0xbf30b8d9,0xcac3c486,0xd718cfce,0xe301dc49,0xee99e836,0xfa58f47a,0x05cd005c, 0x0fd70ad3,0x1962145a,0x22371da5,0x2a4f267b,0x32132edf,0x397c3664,0x40783cf8,0x46b442dd, 0x4b5847b7,0x4ef04cef,0xdb0f4667,0x995283e9,0xa95fa3b5,0xb25cad6a,0xbe88b865,0xca41c3f5, 0xd646cf27,0xe23adbcf,0xedc3e7ce,0xf9aef3eb,0x0553ffac,0x0f5f0a2d,0x18dd13c3,0x21ab1d2c, 0x29e02608,0x31de2e3a,0x397635a0,0x406c3c24,0x46614243,0x4a8747a2,0x4db24d6e,0xea0f4ac2, 0x93f68948,0xa838a4a2,0xb192ad7f,0xbde7b7c9,0xc9b0c35e,0xd55fcea8,0xe167db60,0xecfee75f, 0xf910f34a,0x04cffef4,0x0ed3098e,0x1839133c,0x21141cb4,0x29722584,0x31962d95,0x393a34ef, 0x3fed3b96,0x458b4215,0x497947e6,0x4ccc4df2,0xf7174c04,0x8f2a93a6,0xa7c4a490,0xb145ad06, 0xbd74b6f3,0xc91dc2b4,0xd480ce33,0xe0b5dae2,0xec5de6d6,0xf885f28c,0x0437fe2b,0x0e3508f6, 0x178912c8,0x207c1c3b,0x28fd24fd,0x312b2cf5,0x38a6346a,0x3f183b5b,0x44784228,0x487a4828, 0x4c7b4ded,0x01544b33,0x8c91a232,0xa827a271,0xb167ac0f,0xbd1ab5f8,0xc895c20c,0xd3cdcdbc, 0xe029da37,0xebe9e62c,0xf804f1b0,0x03a2fd6c,0x0d8b0867,0x16e7124a,0x1ff01bb1,0x288c2465, 0x309f2c61,0x37ef340d,0x3e2f3b39,0x43924239,0x47fa4813,0x4cd14d5f,0x07ba48d9,0x8e09b2d5, 0xa91f9e90,0xb19faacd,0xbcb0b50c,0xc811c164,0xd336cd34,0xdfbcd965,0xeb89e55a,0xf77ef0d5, 0x02f7fcb7,0x0cef07e1,0x166111ca,0x1f7f1b1d,0x281c23cd,0x300e2be1,0x373c33cb,0x3d773b18, 0x4329420c,0x48224798,0x4d904c4e,0x0a974677,0x9431c338,0xa9a9997b,0xb192a9ce,0xbc0cb458, 0xc77ac0ce,0xd2bdcca5,0xdf4bd878,0xeb18e48a,0xf6dff011,0x0246fc1a,0x0c5d0751,0x15ed1136, 0x1f1c1a78,0x27b52334,0x2f822b6f,0x36b1337c,0x3d1a3ac8,0x4329417a,0x489846a8,0x4e3a4b22, 0x0a8f442c,0x9f43d1fb,0xa8d594e4,0xb0f6a967,0xbb1cb406,0xc6bcc043,0xd238cc05,0xdeb7d792, 0xea8be3cc,0xf618ef6f,0x0183fb78,0x0bd206b5,0x157b108c,0x1eb519c8,0x273c229d,0x2efc2afa, 0x3654330b,0x3d063a3a,0x436440a3,0x4911459f,0x4e8f4a2c,0x08b242bb,0xaddedd77,0xa63b92de, 0xafeda9a9,0xba08b40b,0xc5f7bfd2,0xd1b7cb6d,0xddffd6d0,0xe9d2e330,0xf546eeec,0x00cdfaef, 0x0b520618,0x15120fee,0x1e3f192b,0x26c22216,0x2e892a8a,0x36143284,0x3d103988,0x439b3fc2, 0x493544bc,0x4e5a49a4,0x05e1417c,0xbde2e57b,0xa22594d9,0xae95aa59,0xb903b434,0xc53cbf56, 0xd123cad8,0xdd2ad63b,0xe8ffe2ba,0xf475ee84,0x001bfa67,0x0acf056f,0x149b0f51,0x1db718a4, 0x263a21a6,0x2e222a21,0x35eb31f4,0x3d0d38db,0x43893f0a,0x48e34440,0x4d8e4998,0x027a409d, 0xce2bea4e,0x9d4b9b73,0xad85aac3,0xb84bb41e,0xc49fbeb5,0xd089ca3d,0xdc3fd5ba,0xe839e248, 0xf3bfee13,0xff80f9cb,0x0a5004bf,0x14110ec0,0x1d24182c,0x25b1213a,0x2dc629ac,0x35b03165, 0x3cd33849,0x431a3e99,0x4836442f,0x4cc349e5,0xffac3fac,0xdc99ec34,0x98eba68f,0xad0aaa02, 0xb7edb398,0xc413bdd1,0xcfeac993,0xdb67d547,0xe77ce1ba,0xf31ded81,0xfeebf905,0x09b80402, 0x13740e34,0x1c7d17bb,0x252a20cb,0x2d5c292d,0x354e30d9,0x3c5637db,0x42573e6f,0x47514447, 0x4bfb4a1d,0xfd873df5,0xe80fec5f,0x96edb558,0xad47a793,0xb7edb298,0xc399bcce,0xcf53c8d7, 0xda9fd4c0,0xe6e6e105,0xf29deccc,0xfe60f837,0x091a0341,0x12d40dae,0x1be9174b,0x24a9204c, 0x2ce9289e,0x34c5304f,0x3ba63786,0x417f3e5c,0x4699444d,0x4bad49f4,0xfc313bd4,0xefc2eb74, 0x9963c63f,0xade1a347,0xb825b17b,0xc316bbf1,0xcec1c83a,0xda0dd43b,0xe66ce034,0xf22bec00, 0xfdc3f75f,0x0863028d,0x122c0d1c,0x1b5716bc,0x24241fac,0x2c6827ff,0x34202fc4,0x3ae93731, 0x40c23e1d,0x462c43f5,0x4ba94950,0xfbaf3931,0xf404ea74,0xa0f6d6aa,0xadee9e5f,0xb806b0aa, 0xc272bb62,0xce2bc7ac,0xd993d3b1,0xe5f8df56,0xf1b3eb3b,0xfd11f69c,0x07a701ee,0x11910c88, 0x1ad11619,0x23af1efd,0x2be32756,0x337f2f45,0x3a4d36cb,0x40583da5,0x46264341,0x4bf54840, 0xfb04367a,0xf5a5e9f2,0xad00e4e9,0xaca19aa3,0xb782b069,0xc186bb35,0xcd7cc735,0xd914d329, 0xe563de85,0xf119ea8e,0xfc46f607,0x06e6015b,0x10fd0be4,0x1a531576,0x232d1e4a,0x2b5a26b7, 0x32e32ebe,0x39d83641,0x40203cfa,0x4639424d,0x4c2c471f,0xf9da3402,0xf560e9d7,0xbc32efe8, 0xa9a299e9,0xb6acb0c9,0xc0a1bb6a,0xccdbc6dc,0xd89ed2b3,0xe4adddde,0xf05eea08,0xfb62f592, 0x061f00bd,0x10610b36,0x19c614c1,0x228e1d9a,0x2aaf2614,0x32422e2a,0x39623593,0x3fe23c14, 0x46154140,0x4bbf461e,0xf88931f7,0xf446ea75,0xcd1cf73a,0xa53d9db2,0xb5c5b120,0xbfe0bbbd, 0xcc3bc676,0xd824d239,0xe3d8dd5b,0xef95e999,0xfa91f525,0x05690022,0x0fc30a7e,0x1928140c, 0x21da1cf7,0x29f62588,0x31a82d92,0x38fd34d1,0x3f8f3b41,0x45b4406a,0x4b034589,0xf6b0302d, 0xf329eb21,0xdd04fb22,0xa0cea67f,0xb50db0c8,0xbf73bbd7,0xcbbdc5ed,0xd79bd1b2,0xe2fadcf7, 0xeecce926,0xf9d1f4aa,0x04bdff6c,0x0f2309bf,0x187e136d,0x21211c67,0x294824f8,0x31122cf4, 0x38783415,0x3efd3a90,0x44ef3fdd,0x49cb4546,0xf4eb2eb7,0xf27eeb99,0xea56fc8a,0x9e16b38d, 0xb4b0af00,0xbf5fbb7b,0xcb4cc52c,0xd710d11d,0xe235dc8d,0xee29e895,0xf938f417,0x0421fea0, 0x0e7e0905,0x17d212dd,0x20731bef,0x28b32477,0x308e2c6a,0x37fb3386,0x3e673a23,0x44203fad, 0x48d34550,0xf3232cf4,0xf280ebc8,0xf428fc80,0x9e50c279,0xb492abee,0xbf5cba92,0xcabec438, 0xd670d070,0xe17cdc08,0xed8ce7d6,0xf8b1f35d,0x0384fdcd,0x0dd5084c,0x172c1255,0x1fd61b76, 0x282c23f5,0x301c2be0,0x3774330c,0x3dbd39d7,0x43673f97,0x4800454f,0xf1da2aff,0xf2daeb58, 0xfaa9fb9c,0xa2a6d27b,0xb444a7aa,0xbf72b986,0xca1dc368,0xd5d0cfc5,0xe0e0db71,0xed06e704, 0xf833f293,0x02ddfcfd,0x0d2307ab,0x169211d1,0x1f511af1,0x27b92363,0x2fa52b5a,0x36df329e, 0x3d1d3993,0x42d23f66,0x477444ff,0xf10a2877,0xf364eab1,0xfe0efaaf,0xab80e18b,0xb34ca3a9, 0xbf3bb89e,0xc958c2e5,0xd526cf23,0xe059dade,0xec79e628,0xf7a9f1d0,0x0227fc4c,0x0c68070a, 0x15fa1143,0x1ed21a5c,0x274522ce,0x2f2a2ace,0x36503237,0x3c9d393f,0x42913f0b,0x473a4474, 0xf06425d5,0xf3c8e9ef,0xff36fa4b,0xb847ee27,0xb106a15f,0xbeacb803,0xc875c2c4,0xd477ce99, 0xdfd6da48,0xebd1e55b,0xf703f125,0x0159fbba,0x0baf0677,0x156e10a9,0x1e5c19cb,0x26cc2230, 0x2ea82a46,0x35d431cd,0x3c3b38cf,0x42683e7d,0x470543bb,0xefe0234a,0xf3abe971,0xfef0fa49, 0xc754f78f,0xadaca26f,0xbda9b7ab,0xc77fc2d7,0xd3b7ce18,0xdf42d9b3,0xeb0de4ac,0xf642f098, 0x0081fb38,0x0af505e4,0x14e31006,0x1de21933,0x2648219e,0x2e1929d0,0x3551315d,0x3be9384c, 0x424a3dde,0x4698430b,0xeee7209c,0xf33ce94b,0xfe09fab5,0xd6a7fdb1,0xa9f0a767,0xbc97b762, 0xc6c3c2f1,0xd311cd8b,0xdeb3d929,0xea36e427,0xf579f020,0xffb9fac7,0x0a44054f,0x14520f5e, 0x1d50189b,0x25aa211b,0x2d7c2958,0x34d030e1,0x3b8c37b0,0x42063d38,0x45d24273,0xed641e2f, 0xf289e991,0xfd0cfb39,0xe54800ff,0xa663b0a7,0xbbc0b66b,0xc651c2e0,0xd277cce6,0xde24d897, 0xe95ae3b1,0xf4b5ef9c,0xff05fa45,0x099a049a,0x13b30ea2,0x1caf1803,0x24fb209b,0x2cdb28e2, 0x3449305b,0x3b0d3717,0x41773cab,0x449d421a,0xebcf1be2,0xf1f7ea0f,0xfc90fba5,0xf18e01fd, 0xa4a7bdc2,0xbb25b44c,0xc642c26b,0xd1facc23,0xdd92d7f8,0xe893e344,0xf40fef05,0xfe62f9ad, 0x090403dd,0x130f0df3,0x1c041777,0x24512025,0x2c432862,0x33ca2fd8,0x3a8b3691,0x40db3c4e, 0x435a41fc,0xea3c19cb,0xf19dea70,0xfc98fbab,0xfa8701b4,0xa642ccf6,0xbac9b110,0xc65fc18e, 0xd179cb53,0xdd05d753,0xe7ece2cb,0xf376ee43,0xfddbf8f8,0x0863030e,0x12550d3c,0x1b5816e6, 0x23a21f9e,0x2ba527ca,0x33312f40,0x39d035ff,0x3ff23be9,0x41d041ce,0xe95f17ed,0xf15cea35, 0xfcf5fb24,0x004f00e1,0xac43dcc3,0xba19ad44,0xc682c087,0xd0e8cab2,0xdc6cd6b2,0xe75fe23c, 0xf2e6ed73,0xfd55f82c,0x07b10243,0x118f0c8a,0x1aa6164a,0x23081efd,0x2b0d2723,0x32932e98, 0x390f3573,0x3f2d3b7f,0x40904174,0xe8cc15d5,0xf192e9ba,0xfd6dfa5f,0x0341000b,0xb675eb0e, 0xb8b9aa43,0xc66abfa7,0xd03dca6a,0xdbd7d628,0xe6e8e1b5,0xf253eca2,0xfcc4f773,0x06ed018f, 0x10ca0be4,0x19fc15a8,0x22711e56,0x2a782670,0x31f42df4,0x385934eb,0x3e7c3b0c,0x3f8f40fd, 0xe89d13bf,0xf1c5e8f1,0xfdb1f99f,0x0414ffa0,0xc3f5f6c4,0xb64ba971,0xc5e4bef4,0xcf79ca71, 0xdb2ed5ac,0xe669e12b,0xf1a6ebe2,0xfc19f6cf,0x061900fa,0x10070b44,0x195e14fd,0x21dd1dad, 0x29db25c5,0x31482d56,0x37ab3464,0x3df33a81,0x3e744063,0xe87a114e,0xf1f3e84e,0xfd9ef929, 0x03b9ffb7,0xd2e4ff2b,0xb306abce,0xc4ffbe43,0xceb6ca97,0xda82d52c,0xe5e1e09a,0xf0e1eb43, 0xfb59f63d,0x0551007d,0x0f580aad,0x18cd145c,0x21601d1d,0x2955253d,0x30bf2cde,0x372a33ff, 0x3d923a0b,0x3d963fde,0xe7b00e79,0xf1dce7d3,0xfd16f908,0x02e70002,0xe1c8045f,0xaf9bb22e, 0xc3d5bd61,0xce1acaa9,0xd9dad49e,0xe552e00a,0xf010eabc,0xfa8ff5b8,0x04930005,0x0ea60a0b, 0x183913b5,0x20ca1c85,0x28b024bb,0x301c2c70,0x369c3382,0x3d25397f,0x3c533f64,0xe6dc0bf4, 0xf17ce7af,0xfc44f920,0x02150055,0xef3e0708,0xad1ebc51,0xc2d0bbe8,0xcdcdca74,0xd947d3f2, 0xe4c6df6f,0xef3bea47,0xf9dbf533,0x03e4ff7e,0x0e070964,0x179d1305,0x20321bfd,0x28082448, 0x2f822c00,0x3621330f,0x3cac3907,0x3ae63ef3,0xe5d9099c,0xf0f0e7c8,0xfb8af95d,0x01a8007d, 0xfa6307c1,0xacc0c971,0xc1fab99e,0xcdc0c9d2,0xd8c6d338,0xe437decf,0xee83e9cc,0xf935f48d, 0x0355fed9,0x0d6e08a7,0x16ff1259,0x1f8d1b76,0x276c23d5,0x2ef32b89,0x359d3293,0x3c1e388e, 0x39703eb6,0xe4ba07a5,0xf056e7cb,0xfb10f968,0x01b70042,0x0263073d,0xaf93d849,0xc13cb67b, 0xcde4c8e9,0xd844d283,0xe3aade2d,0xede1e953,0xf8abf3d5,0x02d9fe2c,0x0cd707ed,0x165911b1, 0x1ef41af9,0x26d62357,0x2e6b2b07,0x350f320e,0x3b77382b,0x37a03e75,0xe3cf05a2,0xf001e7d4, 0xfaf0f927,0x020effb4,0x07490663,0xb661e714,0xc03ab343,0xcdf4c7c5,0xd7b5d1f8,0xe314dd8c, 0xed5fe8ca,0xf823f305,0x0257fd70,0x0c300737,0x15a31109,0x1e571a6f,0x264522d1,0x2de12a75, 0x34853186,0x3ad137c0,0x35ee3e47,0xe2f5035e,0xefefe775,0xfb08f892,0x0264fedf,0x09b005a6, 0xc0f1f42f,0xbe91b117,0xcdb7c6a3,0xd70cd1b3,0xe276dcf9,0xecdce837,0xf792f239,0x01c9fcba, 0x0b7c0694,0x14ec1079,0x1dc819d8,0x25c92243,0x2d5f29e4,0x33fa3100,0x3a2b375c,0x34263dde, 0xe25600f9,0xf028e70b,0xfb3af7d6,0x0289fe26,0x0a4a0540,0xce0cfeb7,0xbc54b133,0xcd0dc5bd, 0xd65cd1ad,0xe1d8dc7c,0xec64e7ad,0xf6ecf187,0x0124fc1c,0x0aba060d,0x143e0fec,0x1d3a1941, 0x254a21af,0x2cde294f,0x33663086,0x399236f6,0x326f3d85,0xe1eafe50,0xf071e68a,0xfb46f72d, 0x0255fda2,0x09d90546,0xdc730645,0xb966b45f,0xcc0ec4f5,0xd5aad1c8,0xe133dc00,0xebe6e722, 0xf632f0f0,0x0076fb9a,0x09f7059a,0x13950f5d,0x1cb218a9,0x24c6211d,0x2c5328cc,0x32d4300d, 0x39133699,0x30bb3d0c,0xe17afbd1,0xf083e60f,0xfb01f6b1,0x01cdfd79,0x09000592,0xeac90af1, 0xb672bb26,0xcaedc40a,0xd52bd1cd,0xe099db76,0xeb5ee691,0xf567f06d,0xffb5fb13,0x09440524, 0x12f00ebb,0x1c1f1803,0x2439208e,0x2bb02853,0x32332f96,0x387d362b,0x2ece3c81,0xe103f943, 0xf061e5cd,0xfa7af67a,0x0116fd88,0x084e05ea,0xf7930d2a,0xb467c584,0xc9dcc270,0xd4e7d18f, 0xe006dad3,0xeacde5f5,0xf4a0eff6,0xff00fa84,0x08a10499,0x124e0e0b,0x1b891752,0x23a02003, 0x2b0627de,0x319b2f27,0x37fb35bb,0x2cf63c0d,0xe05bf707,0xf00ae5b2,0xf9baf66f,0x006cfdac, 0x080105ff,0x01e30db1,0xb494d295,0xc8fec020,0xd4dcd0d9,0xdf89da19,0xea35e54a,0xf3e4ef77, 0xfe59f9dc,0x081103ee,0x11b80d4a,0x1ae816a4,0x22fb1f72,0x2a582762,0x30f82ea0,0x3766353b, 0x2ae43b81,0xdfe1f512,0xefafe5e3,0xf939f693,0x0022fdcd,0x083805e3,0x09790d5c,0xb7d7e0df, 0xc834bd22,0xd4edcfc5,0xdf03d95c,0xe99be498,0xf33ceee6,0xfdc4f90f,0x078b0330,0x111b0c84, 0x1a3815f2,0x22551eea,0x29cd26e0,0x306d2e19,0x36df34b8,0x28923b11,0xdf4bf304,0xef7ae617, 0xf8edf689,0x0037fd9a,0x08ae0570,0x0e2e0c8e,0xbec0ef32,0xc736ba2d,0xd4e4cea2,0xde69d8c6, 0xe8ffe3ea,0xf2b1ee50,0xfd30f83d,0x06fb0261,0x105f0bb9,0x19751535,0x21a91e44,0x2924263c, 0x2fce2d65,0x36303418,0x26523a68,0xdee5f138,0xef6ce640,0xf8f2f653,0x008dfd37,0x093604db, 0x10700c01,0xc953fc15,0xc5a0b825,0xd496cd8b,0xddacd873,0xe850e349,0xf224eda1,0xfc82f759, 0x065b0197,0x0f930afc,0x18a4147e,0x20fb1d92,0x288c258a,0x2f2c2cad,0x3583336f,0x23cf39c8, 0xdeb8ef55,0xefa7e64e,0xf91ef5ec,0x00fcfca1,0x097f0458,0x11010bd5,0xd6a30652,0xc33db860, 0xd3e7cca5,0xdce8d865,0xe79ae2b3,0xf195ed00,0xfbcaf690,0x059f00e2,0x0ebb0a5b,0x17da13d0, 0x20571cd7,0x27ef24d6,0x2e872bf8,0x34d232d5,0x218c391f,0xde99ed72,0xefede62a,0xf95af569, 0x012dfc23,0x09710414,0x10af0c0c,0xe5240da4,0xc041bbea,0xd2cdcbcb,0xdc36d872,0xe6e3e21e, 0xf0f5ec55,0xfaf5f5dd,0x04cb0032,0x0ddd09bf,0x17181322,0x1fad1c15,0x27542426,0x2ddf2b52, 0x34323242,0x1f12386a,0xde8beb9b,0xf024e5f4,0xf968f4f5,0x010efbd0,0x0900041c,0x0ff40c7d, 0xf3561220,0xbd50c300,0xd1a1cabe,0xdb9ed859,0xe63be17e,0xf06aebbf,0xfa21f554,0x0418ffab, 0x0d2b0946,0x167a127d,0x1f231b6e,0x26c82397,0x2d432ad3,0x339f31dd,0x1cc737d5,0xde41e9b1, 0xf014e5a2,0xf904f484,0x0085fb9d,0x0847043a,0x0f4c0cc6,0xfff41428,0xbb71cd9c,0xd0a6c929, 0xdb69d809,0xe5afe0cc,0xefdceb1b,0xf960f4d6,0x0369ff15,0x0c9108bd,0x15df11c7,0x1e8b1abb, 0x262f2306,0x2c9f2a54,0x330a315d,0x1a95371f,0xdddee7f8,0xefbee551,0xf86df439,0xffd5fb93, 0x07a30460,0x0f020ccb,0x09fc146d,0xbbc4dade,0xcfd3c6b8,0xdb69d754,0xe52fe013,0xef4fea6d, 0xf8adf45a,0x02ccfe6a,0x0c070815,0x154e110a,0x1ded1a09,0x25992279,0x2c0829db,0x328430e1, 0x18073645,0xdd79e646,0xef5ae53a,0xf7c8f417,0xff38fb91,0x0742045c,0x0f220c84,0x110513e7, 0xbf7de94c,0xcf09c3a4,0xdb8fd645,0xe4b1df64,0xeec2e9c6,0xf81df3d1,0x0244fda1,0x0b91075b, 0x14bb104f,0x1d4e195a,0x24fd21ed,0x2b7c2956,0x3204304f,0x1598357c,0xdd05e498,0xeef6e52b, 0xf740f3f3,0xfed8fb6d,0x07460417,0x0f900bf6,0x155d1316,0xc6e2f766,0xcdfdc0b1,0xdb84d51d, 0xe41dded1,0xee2ae91a,0xf796f338,0x01bcfccc,0x0b100690,0x14170f8c,0x1ca218b4,0x246a2151, 0x2afc28bb,0x319b2fb5,0x13003484,0xdc9de314,0xeea5e524,0xf6e1f3ac,0xfecdfb0d,0x0783038a, 0x0ff70b40,0x176a127a,0xd19a03d8,0xcc53bee4,0xdb1ed409,0xe365de83,0xed83e87f,0xf71bf29e, 0x0121fbf4,0x0a8105dc,0x13670eea,0x1bfc181c,0x23e620c2,0x2a8a281f,0x312d2f1a,0x107633ac, 0xdc42e193,0xee66e4fe,0xf6bcf341,0xfee0fa7d,0x07c002e0,0x100e0aa3,0x17b8123b,0xdef00dcf, 0xc9d1bf41,0xda5cd31f,0xe295de6c,0xecd4e7e9,0xf697f1f7,0x006ffb39,0x09d80534,0x12a80e58, 0x1b4b1775,0x235a2017,0x2a172782,0x30bb2e79,0x0dcb329c,0xdbe2e029,0xee3be4bb,0xf69ff2b6, 0xfeeef9d4,0x07d00244,0x0fd80a54,0x172f1263,0xed7e14ac,0xc6bfc31c,0xd94cd247,0xe1e6de78, 0xec2be759,0xf60af15e,0xffaafa95,0x091e04a0,0x11e20dd4,0x1a9d16d5,0x22cd1f68,0x298726cf, 0x302c2ddc,0x0b21318f,0xdba9dedd,0xee22e486,0xf690f22f,0xfedbf94f,0x078e01e9,0x0f510a4a, 0x166012c6,0xfb9b18bb,0xc3d9cabe,0xd826d126,0xe168de69,0xeb8ae6b8,0xf577f0c1,0xfed2fa08, 0x08620409,0x11270d45,0x19f8161c,0x22361ea5,0x28fd262a,0x2f952d44,0x08b3308b,0xdb64ddb4, 0xedfee443,0xf654f1b5,0xfe8af8f9,0x070501d3,0x0e9d0a75,0x15d01314,0x07da1a85,0xc25dd5dc, 0xd723cf7c,0xe136de05,0xeb04e60c,0xf4e9f01b,0xfe10f984,0x07ac0370,0x10860ca6,0x19581550, 0x21931ddd,0x2857257a,0x2eeb2ca2,0x06142f38,0xdb47dcad,0xedbce414,0xf5f3f15d,0xfdfef8da, 0x066201e0,0x0e070aa4,0x1596131d,0x11821ac1,0xc333e342,0xd657cd08,0xe141dd41,0xea83e54d, 0xf458ef6c,0xfd55f900,0x070702ae,0x0ffa0be5,0x18b9147a,0x20e11d13,0x27af24cf,0x2e542bfb, 0x037a2dfb,0xdafedb89,0xed70e3ec,0xf570f124,0xfd66f8c1,0x05ca01ec,0x0db30a9e,0x15bb12c5, 0x183c1a11,0xc762f1b9,0xd593ca09,0xe15cdc34,0xea00e4a0,0xf3caeebb,0xfcbdf86c,0x067c01e1, 0x0f710b1e,0x180c13a4,0x20301c4e,0x270b241f,0x2dc02b4d,0x00f92c7c,0xdacada77,0xed09e3ce, 0xf4ecf0e9,0xfce6f8ad,0x057301c7,0x0db50a4e,0x16181233,0x1c1f1942,0xcf2fffa6,0xd46cc731, 0xe159db14,0xe968e427,0xf32dee14,0xfc38f7d5,0x05ec00ff,0x0ef20a53,0x176312e1,0x1f7e1b96, 0x26812373,0x2d422aa5,0xfe5d2afc,0xda9cd970,0xecace3ba,0xf47ef0ae,0xfc9cf873,0x05620171, 0x0de909c2,0x166f1187,0x1db918b7,0xda6e0bad,0xd2b2c5bf,0xe0ebd9fe,0xe8bde3e9,0xf28fed88, 0xfbbaf73c,0x055c0032,0x0e5f099a,0x16b31238,0x1ecc1aec,0x25f622c5,0x2ce729f3,0xfbf32987, 0xda51d867,0xec4ee39e,0xf427f05b,0xfc77f819,0x057900e2,0x0e1a0917,0x168010ee,0x1dea1886, 0xe7db14ef,0xd033c6c7,0xe025d91c,0xe80ae3e6,0xf1e8ecff,0xfb3cf6a5,0x04a9ff74,0x0db008f6, 0x15f111a0,0x1e161a40,0x25652207,0x2c63292b,0xf98a27dc,0xda16d797,0xebf2e375,0xf3e4eff2, 0xfc65f798,0x05800048,0x0e150886,0x162e10a1,0x1d4d18a5,0xf6161b4d,0xcd57cb2a,0xdf15d84b, 0xe75de3ee,0xf13dec6b,0xfaaef605,0x03d7fecd,0x0cec085d,0x152b1110,0x1d6b1992,0x24e12146, 0x2bff2877,0xf6e62631,0xd9cbd6b6,0xeba1e360,0xf3a5ef7e,0xfc47f71d,0x055affc8,0x0dc60839, 0x159610a2,0x1c7a18fb,0x03b41f00,0xcaa2d310,0xddf3d72a,0xe6e5e3df,0xf09eebca,0xfa1df567, 0x0312fe44,0x0c3407cb,0x1476107f,0x1cca18d6,0x245d207f,0x2b6d27c6,0xf46e2490,0xd971d5e7, 0xeb42e32f,0xf35def04,0xfc07f6b3,0x04f6ff76,0x0d380825,0x14ec10dc,0x1bee194d,0x0f7d2086, 0xc92dde2c,0xdcdad54c,0xe6a9e363,0xf00aeb0f,0xf98af4b8,0x024bfdba,0x0b860728,0x13e20fe6, 0x1c3c1816,0x23d51fc0,0x2aff2724,0xf1dd22e7,0xd91ed52c,0xeaeee301,0xf2fbee9b,0xfba7f667, 0x0466ff5f,0x0c950842,0x14661110,0x1bd91965,0x18a020b7,0xca3deb99,0xdbedd2a3,0xe6ade285, 0xef82ea51,0xf8f0f405,0x0199fd30,0x0aed0677,0x13660f38,0x1baa1754,0x23441f05,0x2a7d2692, 0xef702134,0xd8c6d45c,0xea85e2b9,0xf286ee2e,0xfb21f628,0x03cdff50,0x0c0c084a,0x141d110c, 0x1c071911,0x1ee12018,0xcec2f9c7,0xdafacf93,0xe6aae155,0xeeefe993,0xf858f34a,0x00fdfc98, 0x0a6105a4,0x12e60e6e,0x1b151686,0x22a71e48,0x29ee25e2,0xed121f4b,0xd878d3a7,0xea25e273, 0xf201edd4,0xfa97f5f1,0x034dff35,0x0bbf0823,0x142310c0,0x1c65187a,0x228e1f5f,0xd6d0074e, 0xd9b4cce9,0xe684e01b,0xee4be917,0xf7baf29f,0x0078fbfc,0x09d604d2,0x126a0daa,0x1a7015cc, 0x220b1da1,0x29722548,0xeada1d7a,0xd833d2d3,0xe9b6e230,0xf182ed78,0xfa26f5b5,0x02fdfef5, 0x0bad07c2,0x145f1030,0x1cb717db,0x23fd1ed4,0xe21a130e,0xd7d4cb9c,0xe608df10,0xed91e8dc, 0xf714f208,0xfff5fb5e,0x09390401,0x11d50cf8,0x19be1528,0x21651cfb,0x28ef249b,0xe8cd1b87, 0xd7ddd21b,0xe942e1df,0xf108ed1e,0xf9cef561,0x02d2fe96,0x0bc10735,0x148a0f90,0x1cbc1758, 0x240b1ec0,0xefb71c0f,0xd52acce2,0xe52cde1b,0xecd5e8d9,0xf65ff17b,0xff74fac7,0x088c0350, 0x112f0c58,0x1909149b,0x20c91c57,0x287123eb,0xe6a01958,0xd7a0d16e,0xe8cee1ad,0xf09decc2, 0xf990f500,0x02c3fe19,0x0bc106a7,0x14840f0d,0x1c73171d,0x236c1efe,0xfdfb2212,0xd216d1b2, 0xe3ffdd17,0xec26e8d6,0xf5aff0e5,0xfedbfa25,0x07bf02b2,0x10740bc3,0x18471412,0x20291bae, 0x27e7232b,0xe4711746,0xd72dd0b6,0xe84ee167,0xf030ec5a,0xf954f485,0x029cfd96,0x0b950634, 0x14230ec1,0x1bd61726,0x22b31f63,0x0b5e2581,0xcf8eda1e,0xe2b2dbc3,0xeba6e8a5,0xf502f041, 0xfe39f981,0x06ee0224,0x0fb80b2e,0x179a138c,0x1f8c1afa,0x2746226d,0xe25014f9,0xd6ccd02f, 0xe7cde139,0xefc7ebf3,0xf905f41e,0x024ffd27,0x0b2c05e9,0x13900ebd,0x1b2d1766,0x22291fa9, 0x16bd26d7,0xce7be58e,0xe19cd9da,0xeb67e81d,0xf46aef7f,0xfd9ff8cc,0x061f019d,0x0f050a82, 0x16f112e0,0x1ef81a2c,0x269f21a7,0xe02e12cb,0xd688cfc4,0xe75ee115,0xef70eb9b,0xf8b5f3be, 0x01e4fce9,0x0a9c05d3,0x12ef0ed7,0x1aa4178f,0x22051fab,0x1f6826ce,0xd005f303,0xe0bfd757, 0xeb6ee741,0xf3e5eec1,0xfd09f823,0x05710111,0x0e6709c7,0x166a1226,0x1e5e1957,0x25d520e1, 0xde19105c,0xd63fcf54,0xe6f6e0e7,0xef0ceb38,0xf84af366,0x0164fcbc,0x0a0605ce,0x12680ede, 0x1a611781,0x22391f53,0x25332620,0xd4e80119,0xdfd5d45d,0xeb7be62b,0xf350ee25,0xfc6af778, 0x04d60082,0x0dce08f4,0x15dd115c,0x1db91884,0x24fe201f,0xdc030df7,0xd615ceeb,0xe68de0af, 0xeea5eaca,0xf7d0f317,0x00dafc88,0x098105ac,0x12120eae,0x1a5b171f,0x22861eb1,0x285f2560, 0xdd6b0e4e,0xde8bd1e5,0xeb50e4f2,0xf2b0edb3,0xfbc8f6cf,0x044dffda,0x0d3d081f,0x15511093, 0x1d0817c7,0x242b1f67,0xda250ba5,0xd5e0ce6e,0xe630e063,0xee40ea56,0xf75ff2cf,0x006dfc4c, 0x09360570,0x12030e4d,0x1a88168a,0x22c01e04,0x29a424e1,0xe8e41979,0xdc94d0fa,0xeac6e3e9, 0xf1f3ed87,0xfb17f63c,0x03c2ff47,0x0c950758,0x14a70fdf,0x1c46171b,0x23211ebf,0xd86f0918, 0xd5c3ce03,0xe5c7e010,0xedd4e9e9,0xf6eff27a,0x0012fbf5,0x090b0505,0x120a0db3,0x1a9815dc, 0x229d1d6e,0x297824ad,0xf6762205,0xda16d2d1,0xe9e9e31a,0xf13ded90,0xfa6bf5bb,0x033ffeae, 0x0bda06aa,0x13ee0f3f,0x1b771688,0x223f1e14,0xd6c2069c,0xd587cd86,0xe560dfc8,0xed60e98f, 0xf692f22a,0xffd2fb94,0x08f20484,0x11f90d1e,0x1a731558,0x22281d2c,0x28a124e0,0x048427a1, 0xd738d7f9,0xe8d3e240,0xf0a3eda8,0xf9bcf536,0x02aafe18,0x0b060616,0x13200eab,0x1aa91600, 0x21251d71,0xd5360402,0xd557cd1d,0xe4e8df83,0xece8e92e,0xf62df1d1,0xff93fb1f,0x08ba0402, 0x11ac0c99,0x1a001505,0x21751d28,0x27cc251b,0x119f2a93,0xd4dce0d4,0xe7a4e0f8,0xf040ed86, 0xf921f49e,0x0207fd77,0x0a2c0592,0x12560e14,0x19ec156c,0x201b1caa,0xd3a40158,0xd51eccd6, 0xe466df48,0xec75e8de,0xf5cdf178,0xff40fab2,0x086b0399,0x11340c4f,0x194e14ef,0x20b51d48, 0x2741254c,0x1c762ba7,0xd427ec7d,0xe696deff,0xf015ed01,0xf88cf3eb,0x016afccf,0x095b0512, 0x11940d6b,0x194214c7,0x1f341bf7,0xd223feda,0xd4c9cc69,0xe3e2df04,0xec08e87d,0xf57ff125, 0xfee8fa53,0x08070359,0x10a60c3e,0x18b6150f,0x20381d75,0x27212545,0x24a52b90,0xd609f9e7, 0xe597dc6a,0xf001ebfd,0xf7f3f328,0x00b7fc18,0x089c0480,0x10e20caa,0x18a2140a,0x1e031b28, 0xd0b5fc33,0xd495cc26,0xe371dec7,0xeba9e822,0xf529f0c4,0xfe7efa03,0x0785032b,0x10190c3b, 0x18401512,0x20041d6f,0x275c24e8,0x2a1e2ae8,0xdb2a07a5,0xe499d980,0xefeeeace,0xf74ff27d, 0x0008fb5f,0x07fd03e7,0x104a0bd7,0x1812134b,0x1cef1a6c,0xcf26f973,0xd453cbc4,0xe304de89, 0xeb51e7af,0xf4d7f069,0xfe18f9bb,0x07170305,0x0fab0c24,0x180414e8,0x20181d19,0x27b02452, 0x2cfe2a27,0xe3d41484,0xe338d718,0xefa2e9a0,0xf69cf201,0xff50fab2,0x07610346,0x0f990afa, 0x176e1283,0x1b9a19b6,0xcdb3f6e0,0xd41acb5d,0xe29ede2a,0xeaf3e734,0xf476effc,0xfdabf96a, 0x06b402ca,0x0f6f0be0,0x17fb1484,0x204a1c86,0x27e423b5,0x2e0a29bd,0xef6f1f51,0xe10dd64d, 0xeefee880,0xf5d0f1cc,0xfe8efa19,0x06ca02a1,0x0edf0a2e,0x16b011d6,0x1a3f1929,0xcc53f432, 0xd3f1cb0b,0xe243ddcb,0xea92e6b7,0xf41cef9b,0xfd45f920,0x06710276,0x0f510b7f,0x180a13f7, 0x20691be5,0x27d5233b,0x2de029b1,0xfcda2756,0xde57d85f,0xee00e78c,0xf506f1d0,0xfdcaf98a, 0x06330205,0x0e110983,0x15f11141,0x18c618b9,0xcaeef1a0,0xd3b1ca8a,0xe1d9dd5b,0xea24e634, 0xf3a4ef33,0xfcdff8c4,0x062f0207,0x0f360af7,0x17ff1363,0x20421b68,0x275f2301,0x2d2329ec, 0x0aa32cbb,0xdb81dde7,0xecd5e69c,0xf472f1d9,0xfd1ff90c,0x05a0017a,0x0d430902,0x152310c9, 0x174c1848,0xc9b2eefd,0xd366ca12,0xe164dce0,0xe9a5e5be,0xf331eed0,0xfc75f85c,0x05f4018f, 0x0f090a7e,0x17bb12ef,0x1fd01b2e,0x26b12312,0x2c602a3a,0x17722f82,0xd952e6da,0xebb8e554, 0xf40df1ad,0xfc85f873,0x050900e4,0x0c6d088b,0x1469104f,0x15f017e6,0xc86fec6a,0xd316c977, 0xe0d8dc6d,0xe91ce546,0xf2aeee61,0xfc15f7ee,0x05990113,0x0eb10a11,0x173612a4,0x1f2f1b1f, 0x25fe233b,0x2be22a5e,0x221f3066,0xd8caf2c9,0xeaaae34c,0xf3f2f126,0xfbf4f7c6,0x046e0040, 0x0ba10814,0x13ad0fbb,0x1486175c,0xc75ce9d7,0xd2b2c8ed,0xe043dbf1,0xe88ee4d9,0xf236edf5, 0xfbb2f780,0x053600a3,0x0e3d09c0,0x169d1288,0x1e841b2a,0x257d2355,0x2bc42a45,0x29e33025, 0xdb170062,0xe9b6e09a,0xf3ebf033,0xfb62f719,0x03ccff9a,0x0ae10793,0x13010f05,0x130116c2, 0xc662e71c,0xd270c883,0xdfcedb98,0xe820e474,0xf1dbed91,0xfb5df71a,0x04c90042,0x0db80982, 0x160a1273,0x1e0a1b1c,0x2541232b,0x2bf529cf,0x2ee42f6d,0xe0e10e0e,0xe8a4ddd0,0xf3e3eefc, 0xfaccf684,0x0326feeb,0x0a430703,0x12530e44,0x118c1608,0xc560e48e,0xd212c813,0xdf57db2d, 0xe7b9e404,0xf17ced1d,0xfafbf6aa,0x0459fff0,0x0d3c0948,0x15941242,0x1dc91ada,0x254c22b6, 0x2c39291e,0x317d2eae,0xea011a8d,0xe740dbce,0xf39bedd2,0xfa1df624,0x0276fe55,0x09ab066d, 0x11a80d79,0x0fde1563,0xc470e200,0xd1c3c7b8,0xdeeadabf,0xe75fe384,0xf127eca2,0xfa9cf635, 0x03eaff96,0x0cd40900,0x155311ec,0x1db61a5b,0x256d2211,0x2c53286e,0x32542e2f,0xf5ca24e5, 0xe525db76,0xf2f0eccb,0xf95df5ff,0x01bafdc2,0x091305d5,0x10e70cc2,0x0e3314c6,0xc367dfa5, 0xd165c75a,0xde7cda45,0xe70ae305,0xf0c8ec23,0xfa34f5ca,0x037fff38,0x0c8b08a0,0x1531117b, 0x1dbd19cb,0x257c216f,0x2c3227f9,0x32012e27,0x03352c95,0xe262ddd8,0xf1f1ebd1,0xf898f5fe, 0x00f7fd31,0x0877053f,0x100a0c1f,0x0c29143c,0xc26cdd43,0xd107c6f0,0xde0ad9c0,0xe6a6e27c, 0xf062ebaa,0xf9c9f560,0x0321fedb,0x0c4e0832,0x151e10fb,0x1dad1936,0x254920ef,0x2bb727c8, 0x31352e5b,0x10d43166,0xdf93e3c1,0xf0b8eac4,0xf7fdf5ff,0x003ffca9,0x07ce04a6,0x0f2b0b9c, 0x0a3613b9,0xc17edafa,0xd0c5c69f,0xdd9cd941,0xe644e200,0xeff1eb46,0xf964f502,0x02cffe79, 0x0c0e07bc,0x14f1107d,0x1d6618c7,0x24cb20b0,0x2b0e27cc,0x307e2ea8,0x1d2433d1,0xdd97ed26, 0xef84e955,0xf79af5bb,0xff95fc06,0x072b0409,0x0e440b24,0x08491332,0xc0bcd8e3,0xd077c62d, 0xdd27d8ad,0xe5d4e186,0xef7beaeb,0xf8f5f4a5,0x0278fe17,0x0bc70750,0x149b1018,0x1ced1883, 0x242520a1,0x2a5427ee,0x300a2ec1,0x2724348b,0xdd80f90e,0xee74e74d,0xf76cf513,0xfef8fb4f, 0x067a0358,0x0d660aa5,0x061b1282,0xc018d691,0xd03dc5c9,0xdcabd81a,0xe564e10f,0xef04ea86, 0xf888f43e,0x0218fda9,0x0b6206e7,0x14200fcd,0x1c501861,0x237a20a3,0x29d627f1,0x2fee2e8f, 0x2e74342b,0xe029065a,0xed89e4a6,0xf769f414,0xfe62fa9a,0x05d202ac,0x0caf0a24,0x042a11d2, 0xbf79d437,0xcff8c547,0xdc31d78a,0xe4eee09a,0xee99ea25,0xf82af3cf,0x01c1fd3e,0x0af70682, 0x139a0f8a,0x1bb41843,0x22ff2083,0x29a627bd,0x30202e12,0x331a3361,0xe62113bf,0xec7ce1f1, 0xf75af2e2,0xfdc6fa08,0x053301fe,0x0c120997,0x020c1104,0xbeddd1df,0xcfa5c4cf,0xdb8fd6fa, 0xe477e015,0xee36e9ac,0xf7cbf350,0x0163fcc8,0x0a860625,0x13310f50,0x1b55181c,0x22cc2046, 0x29be274a,0x307a2d72,0x357932b2,0xef6b1fe1,0xeaf5dfee,0xf708f1b4,0xfd11f9ae,0x04800165, 0x0b82090c,0xfff0102b,0xbe3fcf89,0xcf3fc463,0xdb01d666,0xe405df88,0xedd9e92f,0xf776f2cc, 0x0107fc4e,0x0a2105d0,0x12d50f01,0x1b2417cc,0x22d81fcc,0x29ef26b7,0x30a42cd5,0x36393267, 0xfb6229cd,0xe8c5dfd9,0xf653f0a0,0xfc58f98b,0x03cc00d2,0x0aef087a,0xfddc0f77,0xbd82cd76, 0xcebdc3f3,0xda60d5dc,0xe393def0,0xed76e8a0,0xf713f244,0x00a0fbdc,0x09be0573,0x128f0e9f, 0x1b0e1752,0x22de1f37,0x2a082614,0x307f2c60,0x35f33264,0x08a4310f,0xe60be2a2,0xf544efa7, 0xfb99f98e,0x030c003e,0x0a5207e9,0xfb5b0ea8,0xbcd0cb74,0xce39c3b2,0xd9cad54b,0xe323de59, 0xed11e817,0xf6acf1c8,0x002efb75,0x09630515,0x125a0e32,0x1b0016d3,0x22d11eac,0x29de25ae, 0x300e2c44,0x353132a8,0x160e35c2,0xe357e8c5,0xf40bee94,0xfaf9f975,0x0258ffa6,0x09b60753, 0xf8e40e19,0xbbfec971,0xcdc2c35c,0xd939d4b3,0xe2b1ddb3,0xeca9e795,0xf636f159,0xffc4fb10, 0x090c04b5,0x12270dbe,0x1ad11660,0x22821e44,0x29682579,0x2f682c5b,0x348632f9,0x22373800, 0xe168f239,0xf2e0ed0a,0xfa9ef926,0x01b5fef7,0x090f06b1,0xf6550d59,0xbb62c79f,0xcd61c31d, 0xd8bad414,0xe23cdd1f,0xec36e71c,0xf5b8f0f5,0xff57faaf,0x08b7044c,0x11d60d4a,0x1a7715f7, 0x22051e00,0x28bd2568,0x2ec02c7a,0x3420330b,0x2bfa387b,0xe18bfe75,0xf1d3ead8,0xfa7ef874, 0x011dfe3e,0x08720602,0xf3db0cb7,0xbae8c5ce,0xcd1bc2ce,0xd845d377,0xe1c9dc87,0xebbde6ad, 0xf544f096,0xfeeafa4a,0x085903dc,0x11710cdc,0x19fc15a3,0x21651dd7,0x281b255f,0x2e472c72, 0x341d32cc,0x32f4380d,0xe4a00bda,0xf0c7e80c,0xfa7cf758,0x0080fd7c,0x07cb0548,0xf1700bdc, 0xba61c3f3,0xcccdc255,0xd7cad2cb,0xe14cdbf1,0xeb48e641,0xf4d2f027,0xfe8af9d5,0x0803036b, 0x10fe0c77,0x1979155e,0x20d21db4,0x27a02536,0x2e122c2a,0x34443237,0x37403737,0xeb1b1906, 0xefbbe578,0xfa5ff61c,0xffebfce2,0x07230499,0xeeff0af5,0xba17c226,0xcca9c1fa,0xd756d23f, 0xe0d1db6d,0xeae0e5d3,0xf474efb9,0xfe2bf960,0x07a002f4,0x108b0c14,0x18f61518,0x205d1d67, 0x275f24cf,0x2e1a2b92,0x34773174,0x39483666,0xf4c124ce,0xee23e3b6,0xfa0af4e8,0xff39fc86, 0x068503fa,0xecdb0a1d,0xb9aec081,0xcc6ec1a0,0xd6ced1b9,0xe04adaf4,0xea77e560,0xf41cef47, 0xfdd1f8e2,0x073f027a,0x10190bb1,0x188f14bd,0x20181d01,0x27492439,0x2e2f2adb,0x347530ba, 0x39a235ec,0x00dc2e3a,0xebfbe400,0xf954f3e3,0xfe78fc60,0x05d1035d,0xea9b0916,0xb95bbf10, 0xcc0fc15c,0xd63ed151,0xdfccda84,0xea1ce4e7,0xf3c8eeca,0xfd71f865,0x06d8020d,0x0fae0b4a, 0x1843144a,0x1ff51c6f,0x273c238f,0x2e1a2a28,0x342d3036,0x392735d8,0x0e2334e5,0xe945e731, 0xf844f2d9,0xfdcafc56,0x052a02c0,0xe8220810,0xb8c8bd92,0xcba6c127,0xd5a9d0f7,0xdf42da05, 0xe9a8e45b,0xf364ee4a,0xfd09f7eb,0x066801a1,0x0f4e0aeb,0x180413d3,0x1fcd1be8,0x272322ff, 0x2dde29b9,0x33b0300c,0x386e3618,0x1b263910,0xe6a3edc8,0xf701f1a3,0xfd3efc30,0x047c0220, 0xe5ae06fc,0xb80dbc17,0xcb09c0d5,0xd4f9d078,0xdeb3d96d,0xe935e3c6,0xf2f5edca,0xfc90f784, 0x05f7013b,0x0eff0a87,0x17c7135c,0x1f9a1b75,0x26da229a,0x2d6e298a,0x3312302a,0x37d8365f, 0x26d63b26,0xe514f776,0xf5d0effa,0xfcedfbc1,0x03f7015c,0xe31205d6,0xb764bab8,0xca87c08b, 0xd461cff8,0xde33d8cc,0xe8b8e32c,0xf281ed53,0xfc14f71d,0x059100dc,0x0ead0a24,0x177e12f1, 0x1f481b14,0x265f2265,0x2cd1298c,0x32803054,0x37883677,0x30463b91,0xe585039b,0xf4c5edb5, 0xfcd6faf8,0x0375009b,0xe09c049a,0xb6c3b965,0xca04c01b,0xd3e4cf5e,0xddb0d824,0xe832e291, 0xf202ecdc,0xfb9af6bd,0x052d0071,0x0e5509bd,0x17251291,0x1eda1ad1,0x25d4224c,0x2c4b2991, 0x322a3057,0x37ab3640,0x36f63b23,0xe8ed10f2,0xf3c6eaec,0xfcddf9d4,0x02f5ffd7,0xddf10334, 0xb648b81a,0xc999bf9d,0xd36dceb8,0xdd2cd771,0xe7aae1fc,0xf180ec62,0xfb28f64f,0x04c6fffc, 0x0dff094c,0x16b51233,0x1e5b1a92,0x254d222a,0x2be6296e,0x32143011,0x37f735c2,0x3af53a68, 0xefdd1dfb,0xf28be850,0xfccdf881,0x026dff3f,0xdb6d01e9,0xb5d8b6c9,0xc92dbf1c,0xd2f3cdfd, 0xdc9fd6ce,0xe710e168,0xf107ebe0,0xfac1f5db,0x0467ff7e,0x0da008d5,0x164611d5,0x1de61a4f, 0x24f621f2,0x2bc6291b,0x32332f91,0x38423517,0x3ce939d2,0xf9d0295f,0xf0e6e6e3,0xfc5ef732, 0x01cefedc,0xd8fd009f,0xb57bb5a0,0xc8a9be8c,0xd26fcd59,0xdbffd634,0xe675e0dd,0xf08eeb5d, 0xfa64f55b,0x040aff00,0x0d3e0860,0x15dd1174,0x1d8f19f5,0x24c7218b,0x2bc82893,0x325f2eee, 0x3854347a,0x3d4c3978,0x06053272,0xeeb8e788,0xfba9f61b,0x012efeb2,0xd649ff30,0xb52cb47d, 0xc82abe36,0xd1d8cccc,0xdb64d5c3,0xe5e2e060,0xf01eead9,0xfa02f4d9,0x03a3fe7d,0x0cd407f3, 0x1579111e,0x1d48198b,0x24a92109,0x2bbf27f2,0x325c2e4e,0x380e340e,0x3cc43976,0x133138ca, 0xec23eb19,0xfaa0f51f,0x0091fe9f,0xd3d3fdd9,0xb4d0b36f,0xc799bde9,0xd148cc5f,0xdac5d568, 0xe55bdfea,0xefb8ea56,0xf99af464,0x0335fe0a,0x0c64078c,0x151710b7,0x1d061910,0x247f207d, 0x2b9c2762,0x32122ddf,0x378733ee,0x3bf939a9,0x1ffd3c90,0xe98df1e8,0xf968f3cc,0x001afe64, 0xd14bfc30,0xb477b27a,0xc6fabdc4,0xd09fcbec,0xda31d504,0xe4d8df69,0xef40e9ca,0xf92ef3e7, 0x02b8fd9d,0x0bed072a,0x14ae104e,0x1cb4188b,0x24341ff6,0x2b2b26ec,0x316c2d95,0x36bf33e1, 0x3b4539c7,0x2b423e2f,0xe839fbfb,0xf838f20d,0xffe4fde7,0xcf02faa9,0xb42eb194,0xc673bda4, 0xd01bcb8a,0xd9bbd4a4,0xe462dee6,0xeecee943,0xf8b7f377,0x023bfd39,0x0b7406c8,0x144d0fde, 0x1c4f180d,0x23bd1f87,0x2a91269e,0x30ad2d75,0x360433e0,0x3ae439b0,0x34153e61,0xe9210818, 0xf733efb6,0xffd8fcfd,0xcccaf8c0,0xb3e6b0c0,0xc5f3bd81,0xcf9fcb10,0xd95bd42f,0xe3f2de56, 0xee51e8bc,0xf839f30a,0x01bdfcd7,0x0b05065b,0x13e60f6e,0x1bd81796,0x23351f2e,0x29e32667, 0x30082d56,0x359733bb,0x3ad83943,0x3a523db8,0xecf5152f,0xf646ed12,0xffdafbce,0xca94f707, 0xb3adafee,0xc591bd66,0xcf37ca82,0xd909d3ae,0xe37cddc5,0xedd2e839,0xf7bff2ab,0x0146fc6d, 0x0a9e05ec,0x137a0ef6,0x1b61172d,0x22a81ee2,0x2952263c,0x2f982d20,0x3570335e,0x3b0838a7, 0x3df73cdb,0xf40c21e3,0xf518ea92,0xffcbfa80,0xc873f579,0xb341af14,0xc523bd20,0xcebcc9cc, 0xd898d30f,0xe2f2dd33,0xed3ce7b3,0xf743f22c,0x00d6fbfd,0x0a39056b,0x13150e82,0x1ae416ca, 0x222f1e98,0x28ee25f5,0x2f6c2cbc,0x358632cc,0x3b3f37f6,0x3f8f3c3b,0xfe4e2cf6,0xf378e952, 0xff65f93d,0xc621f3eb,0xb2dcae58,0xc4babcd7,0xce31c91c,0xd81ed27a,0xe256dcb0,0xeca4e72e, 0xf6c9f1ac,0x0071fb79,0x09d504e9,0x12a80e07,0x1a72166c,0x21cc1e38,0x28bb2584,0x2f652c2a, 0x35a33224,0x3b45375c,0x3fcf3bf1,0x0a99358a,0xf145ea66,0xfebbf822,0xc3baf2a6,0xb255ad8a, 0xc450bc91,0xcd91c885,0xd789d1f7,0xe1acdc40,0xec0fe6b7,0xf65af127,0x0009faff,0x096d046c, 0x123d0d9d,0x1a061607,0x21841dc9,0x289b2504,0x2f5c2b8f,0x358d3187,0x3af536f8,0x3f443bf3, 0x17a43b81,0xeecfee60,0xfd9af726,0xc17bf13a,0xb1ebacd7,0xc3d7bc47,0xccdac802,0xd6efd188, 0xe108dbdc,0xeb7ee635,0xf5e5f09e,0xff9dfa80,0x08f903fc,0x11c80d36,0x19a215a9,0x21421d56, 0x2870247f,0x2f332b00,0x35433125,0x3a6536d8,0x3e853c28,0x24253f06,0xec93f596,0xfc71f5e9, 0xbf67efb0,0xb187ac2c,0xc35cbbf9,0xcc20c799,0xd648d11c,0xe069db79,0xeaefe5ac,0xf56af011, 0xff21fa08,0x0879038f,0x114f0cd7,0x1942153c,0x20f61ce0,0x282a2405,0x2ec42aa0,0x34b130f5, 0x39b536ec,0x3de63c51,0x2f044072,0xeb8bffb1,0xfb61f43d,0xbdb1edee,0xb118ab5a,0xc2d7bb98, 0xcb61c72c,0xd5a9d099,0xdfdedb03,0xea6ae518,0xf4e3ef81,0xfe9ff996,0x07f3032f,0x10d50c6f, 0x18df14d5,0x20941c6e,0x27bc23a7,0x2e362a6c,0x340730ec,0x39223702,0x3da93c52,0x377340a0, 0xecb00bdd,0xfa43f1d8,0xbc47eb9d,0xb0d6aab4,0xc250bb2c,0xcac5c6be,0xd51cd008,0xdf6eda78, 0xe9e8e47b,0xf45ceeec,0xfe19f924,0x077402cb,0x10600c06,0x187e1461,0x20261c03,0x2738235b, 0x2d992a45,0x337030e1,0x38c936e6,0x3dbc3bfe,0x3d424008,0xf0ea18cd,0xf954ef49,0xbac6e8ef, 0xb083a9f2,0xc1d1bad3,0xca3fc64c,0xd4a8cf6c,0xdf01d9e2,0xe962e3dd,0xf3d0ee60,0xfd93f8b6, 0x07010262,0x0ffa0b99,0x181613ee,0x1fae1ba3,0x26b4231e,0x2d162a1c,0x331230ae,0x38b43690, 0x3dfc3b64,0x40b93f46,0xf8512518,0xf802ed08,0xb94ae626,0xb033a97a,0xc13eba72,0xc9c7c5d4, 0xd432cec7,0xde92d949,0xe8dbe350,0xf33eede1,0xfd1bf841,0x069701f3,0x0f970b1b,0x17ab1375, 0x1f3b1b46,0x264322d1,0x2cb529d4,0x32eb3043,0x38c83603,0x3e283ab1,0x42213eaa,0x02932fd6, 0xf646ec04,0xb773e354,0xafc5a93d,0xc0b5ba2a,0xc950c552,0xd3a8ce1d,0xde13d8ba,0xe83de2d0, 0xf2a1ed62,0xfca4f7c5,0x062e0173,0x0f2a0a9b,0x173e1301,0x1ec21ae4,0x25e02274,0x2c7d2967, 0x32df2fad,0x38d6355a,0x3e193a1d,0x422a3e65,0x0ed7381d,0xf3d1ed50,0xb560e0ab,0xaf53a929, 0xc017b9dd,0xc8d8c4d6,0xd313cd8f,0xdd7fd840,0xe798e262,0xf209ece9,0xfc2bf746,0x05ca00f2, 0x0ebc0a1b,0x16c81298,0x1e531a82,0x25932208,0x2c5828e7,0x32cf2f11,0x38b734c2,0x3dc339cd, 0x41853e74,0x1bd23db3,0xf10bf1a0,0xb30edde1,0xaef5a93f,0xbf82b991,0xc858c457,0xd26acd1c, 0xdcdbd7cd,0xe6f2e1fd,0xf17bec71,0xfbb8f6c0,0x0561007b,0x0e3e09ae,0x164f122d,0x1df01a1f, 0x254e2190,0x2c262861,0x32922e90,0x385a3466,0x3d2b39b3,0x40c63eb1,0x27eb40e4,0xee8af911, 0xb0bbdae0,0xaed4a926,0xbf00b948,0xc7ddc3e0,0xd1c6ccc5,0xdc45d76e,0xe666e1a7,0xf0faebf5, 0xfb3ff634,0x04ec0009,0x0dc7094f,0x15dc11d6,0x1d9419c3,0x25062128,0x2be127f8,0x322f2e3f, 0x37c5344e,0x3c7839cd,0x402e3ede,0x32594237,0xed46034e,0xaebad77b,0xaedfa8cf,0xbe82b8dd, 0xc764c361,0xd121cc67,0xdbb9d6f9,0xe5eae136,0xf07ceb64,0xfac0f5ab,0x0468ff94,0x0d3908f2, 0x155b116c,0x1d221954,0x249320a6,0x2b61278f,0x31842dfa,0x370b3437,0x3bc539d1,0x3fd43eb6, 0x3a5c422c,0xee2c0f65,0xacd3d32b,0xaf34a829,0xbe26b884,0xc6f9c2e0,0xd0a0cc15,0xdb44d67d, 0xe581e0b5,0xf001eacd,0xfa3bf51b,0x03e6ff2d,0x0cba088f,0x14e710fe,0x1cb718d9,0x24162038, 0x2ace2741,0x30d82dca,0x36683417,0x3b5f39a4,0x3fcd3e47,0x3fc44172,0xf2181c3a,0xaaf1cec2, 0xaf88a741,0xbdc7b832,0xc68bc26b,0xd033cbba,0xdaddd5eb,0xe525e030,0xef86ea3c,0xf9b0f49f, 0x0365febb,0x0c3a0824,0x14721084,0x1c461862,0x238e1fcd,0x2a3526f1,0x30412d92,0x35f233cd, 0x3b353934,0x3fec3d97,0x42aa40a5,0xf9542867,0xa8e0caae,0xafc8a63d,0xbd61b817,0xc615c1f4, 0xcfd9cb51,0xda74d548,0xe4c3dfa3,0xeefce9b5,0xf924f41f,0x02ecfe48,0x0bd307b0,0x1411100a, 0x1be017f0,0x23121f71,0x29c426a4,0x2fec2d4d,0x35cd336a,0x3b4438a7,0x40123cfc,0x43da402b, 0x035f32b5,0xa63dc82c,0xaf88a534,0xbccab80b,0xc586c17b,0xcf72cadf,0xd9f1d4aa,0xe44adf1a, 0xee65e93d,0xf890f3a1,0x0270fdc6,0x0b6a0734,0x13a20f84,0x1b681777,0x22971f12,0x2959263e, 0x2fa62ccc,0x35ac32c7,0x3b3c37f2,0x3fe23c5b,0x43b93fe9,0x0efa3a89,0xa349c7fe,0xaef6a45f, 0xbc3fb83b,0xc4fec115,0xcf10ca69,0xd95ed427,0xe3c0de9d,0xedbde8d2,0xf7fff32b,0x01fffd45, 0x0af706ae,0x13270f02,0x1aeb1700,0x22221e9f,0x290225c7,0x2f6f2c40,0x35863226,0x3b05375c, 0x3f633c01,0x43003ff0,0x1b223fcb,0xa021caf0,0xae36a394,0xbbc3b875,0xc47ac0aa,0xcea8ca02, 0xd8bfd3bf,0xe328de34,0xed23e877,0xf76df2ac,0x018bfcba,0x0a810634,0x12a40e90,0x1a71169f, 0x21b21e3d,0x28a9254e,0x2f312bb7,0x353531a2,0x3a9036fc,0x3eb63be9,0x42154028,0x267c42b8, 0x9d91d10f,0xad48a279,0xbb7ab876,0xc3fbc033,0xce3bc98b,0xd81ad35f,0xe292ddd3,0xec95e816, 0xf6e3f21e,0x010bfc2b,0x0a0505bf,0x12200e26,0x19f11637,0x21491dd2,0x285224cf,0x2ed72b46, 0x34bc314b,0x39f036dd,0x3df83c05,0x4186405a,0x2fd043dc,0x9c71d9bf,0xac78a0cf,0xbb61b81a, 0xc385bfa3,0xcdc0c8ff,0xd775d2fb,0xe200dd4f,0xec19e79c,0xf666f18d,0x0085fb9c,0x0982054a, 0x119e0dc7,0x197415d6,0x20e41d6b,0x27ea2461,0x2e5f2af0,0x34253119,0x394236d8,0x3d5f3c10, 0x414f4047,0x36ce43e6,0x9da3e428,0xaba49e8d,0xbb6bb74d,0xc319bf0a,0xcd46c86d,0xd6ead28c, 0xe181dcbc,0xebabe70a,0xf5e4f0ed,0xfff3fb07,0x08fb04d6,0x11180d5b,0x18ff1563,0x207b1cf5, 0x277223f6,0x2dd22aa5,0x338130f0,0x38b136c6,0x3d003bed,0x41503fdd,0x3b174354,0xa212ef19, 0xaad99c37,0xbb6fb646,0xc2a2be7c,0xccc5c7dc,0xd66ed219,0xe10adc11,0xeb3de66e,0xf562f04c, 0xff64fa79,0x08770467,0x10a10cea,0x189214eb,0x20101c82,0x26f9239c,0x2d442a65,0x32fd30c1, 0x38533688,0x3ce93b87,0x41753f49,0x3d1f429c,0xa9a5f933,0xa9c69a81,0xbb49b528,0xc224be28, 0xcc43c752,0xd609d1a6,0xe098db69,0xeacfe5d6,0xf4cfefc0,0xfecdf9f4,0x07fd03ec,0x10340c74, 0x182f146e,0x1fa61c0f,0x267c233e,0x2cd72a17,0x32a73076,0x382e3621,0x3cfc3afa,0x41923eb8, 0x3d564242,0xb3c9018e,0xa81d9a11,0xbad4b417,0xc197be08,0xcbb3c6d5,0xd59dd124,0xe012daca, 0xea58e549,0xf436ef45,0xfe39f978,0x07840369,0x0fd10bfa,0x17c813ed,0x1f321ba2,0x260822dc, 0x2c7729af,0x326c3002,0x3814358c,0x3ce03a57,0x414f3e30,0x3c164213,0xbfde0755,0xa6309c6e, 0xba0bb33e,0xc11abe1c,0xcb35c679,0xd53cd0b3,0xdf7cda43,0xe9c5e4cf,0xf39feed9,0xfda5f900, 0x070b02e0,0x0f600b73,0x17491369,0x1eb01b2e,0x2591226c,0x2c1b2936,0x322c2f74,0x37e734ef, 0x3c9c39ca,0x40c43ddd,0x3a63423c,0xcc170a76,0xa41fa1ba,0xb8f8b247,0xc0adbe23,0xcab2c618, 0xd4d5d039,0xdee0d9d5,0xe930e462,0xf2feee75,0xfd14f882,0x068d024b,0x0ee70ae9,0x16c912f5, 0x1e341abc,0x251a2201,0x2bc628b4,0x31e72ee6,0x37903462,0x3c16396a,0x3fff3dd2,0x38724261, 0xd76b0b7e,0xa2beaa20,0xb7e3b128,0xc06fbdfa,0xca3fc5a3,0xd46ccfc6,0xde42d976,0xe89fe3f5, 0xf270ee09,0xfc91f7f2,0x060e01b7,0x0e6a0a70,0x16431288,0x1db21a52,0x24b02195,0x2b612839, 0x31802e6e,0x3700340a,0x3b653945,0x3f303dee,0x36c2428e,0xe0fa0abd,0xa2c9b50b,0xb6e3af70, 0xc061bd7b,0xc9d2c514,0xd3f3cf39,0xddabd914,0xe813e373,0xf1f5ed8e,0xfc0df758,0x058d0121, 0x0de709f9,0x15bf1227,0x1d3d19eb,0x244e2129,0x2b0027c8,0x31062e1b,0x366533e3,0x3ab83941, 0x3eaa3e00,0x356a4277,0xe8140907,0xa529c169,0xb5eead28,0xc071bc94,0xc969c480,0xd37ccea3, 0xdd1ed8a6,0xe794e2d9,0xf189ed00,0xfb8ef6b6,0x0501008b,0x0d5f0983,0x153a11b8,0x1cca197a, 0x23e720ba,0x2a84275d,0x307a2dcf,0x35c733bd,0x3a1f3927,0x3e4a3ddd,0x343c420d,0xecca06df, 0xaaa3ce24,0xb4e1aabf,0xc07dbb6f,0xc8f8c407,0xd2fdce0d,0xdca8d82e,0xe71fe22d,0xf121ec5b, 0xfb07f615,0x046efff5,0x0cdf0905,0x14c6113e,0x1c5e18fc,0x237d2039,0x2a0426f9,0x2fef2d81, 0x35463386,0x39cb38e6,0x3e363d74,0x33444170,0xef4204cd,0xb33bd9d7,0xb38da91c,0xc04dba3c, 0xc879c3b5,0xd27ccd8c,0xdc43d7ad,0xe6afe182,0xf0afebb9,0xfa78f581,0x03d6ff6a,0x0c600886, 0x145710c0,0x1bf51878,0x23081fbe,0x298c269a,0x2f762d2f,0x34e93329,0x399d3864,0x3e2f3cd8, 0x320d40b6,0xf036031b,0xbe34e3ba,0xb1bfa909,0xbfd2b923,0xc7f1c39e,0xd1f3cd10,0xdbded732, 0xe62ce0e0,0xf030eb2c,0xf9dbf504,0x033cfedc,0x0be607fd,0x13f51046,0x1b9d17f9,0x22ae1f5b, 0x293b2652,0x2f4b2cf4,0x34f132ee,0x39d73814,0x3e8c3c93,0x30cf40a4,0xefb5014d,0xca91eb4f, 0xaf09aab0,0xbe5eb7bc,0xc6d7c31d,0xd0eecc25,0xdb13d64d,0xe545dffa,0xef6dea77,0xf921f474, 0x02adfe57,0x0b910785,0x13c00feb,0x1b6d17bf,0x22951f3c,0x29392653,0x2f812cf5,0x355732ec, 0x3a4f3810,0x3ef13cb2,0x2f9240fd,0xee95ffcd,0xd75bf04d,0xabb8af44,0xbc85b62a,0xc5bac274, 0xcfdbcb1f,0xda31d552,0xe44cdf24,0xee97e9bd,0xf867f3e4,0x0213fdba,0x0b2c06f8,0x13770f87, 0x1b2d177d,0x226d1f21,0x29392648,0x2fac2ce4,0x359a32e6,0x3a883823,0x3f013d06,0x2ddd419c, 0xed9dfe6a,0xe359f2fd,0xa8f5b780,0xbac2b441,0xc4d1c183,0xcedcc9f6,0xd94dd451,0xe34cde5a, 0xedc4e900,0xf7baf347,0x018bfd16,0x0ac20667,0x13220f2c,0x1ae2174c,0x22401f03,0x293a2637, 0x2fc52cda,0x35ba32f8,0x3a883868,0x3eec3d9e,0x2c394254,0xece5fcf2,0xed50f3e1,0xa7edc28a, 0xb950b1a6,0xc429c034,0xcde8c8c2,0xd86ed340,0xe259dd95,0xed06e82c,0xf725f292,0x00fffc55, 0x0a4505d1,0x12bd0ecc,0x1a961710,0x22121edb,0x29312616,0x2fc32cce,0x35a93318,0x3a6138c5, 0x3ebf3e2d,0x2aa842d5,0xecb5fb52,0xf4b1f3a3,0xa9d6cf95,0xb81bae35,0xc3a7be92,0xccfcc785, 0xd78ad234,0xe181dcc3,0xec58e73f,0xf6a1f1c4,0x0078fb91,0x09c40537,0x12580e69,0x1a4d16cd, 0x21ef1e9e,0x292425eb,0x2fae2cc1,0x358f3346,0x3a41391d,0x3ed63e9d,0x29704312,0xeccdf95a, 0xf953f2fd,0xaf7cdcdc,0xb6caaa82,0xc311bce5,0xcc01c673,0xd6a0d131,0xe0bedbe8,0xebabe63c, 0xf617f0eb,0xffd6fad2,0x093504a1,0x11f40dfe,0x1a081677,0x21c61e4e,0x290725b6,0x2f8a2cb2, 0x3576335c,0x3a493949,0x3f193ebb,0x287f42e2,0xecf7f768,0xfb82f267,0xb8fde8e5,0xb4bea79f, 0xc22fbb5c,0xcae1c5a1,0xd5a8d036,0xe003db03,0xeaf4e53b,0xf574f019,0xff23fa27,0x089f0413, 0x11960d88,0x19d01613,0x21a11dfa,0x28ef2583,0x2f732ca7,0x3584336f,0x3a8d3958,0x3fa73eae, 0x274e4299,0xecf9f560,0xfc20f258,0xc52af280,0xb1d2a6e7,0xc0d3ba16,0xc99cc500,0xd49ccf3e, 0xdf3dda13,0xea1ce446,0xf4bcef54,0xfe5ff98f,0x08060386,0x11380d0c,0x199c15ad,0x21751daa, 0x28cf2558,0x2f6c2ca2,0x35ab336b,0x3af3394c,0x40383e99,0x26164268,0xec84f3b4,0xfbaaf28f, 0xd302f954,0xadeda98b,0xbf30b8e3,0xc859c474,0xd38cce39,0xde62d91f,0xe928e36a,0xf3e6eea3, 0xfd96f900,0x077402ef,0x10dc0c82,0x195b1548,0x213b1d68,0x28a82539,0x2f6b2c96,0x35de335a, 0x3b4f3935,0x40963e91,0x245b425e,0xebe2f292,0xfaf8f322,0xe0d0fd64,0xa9fab030,0xbd86b758, 0xc746c3b5,0xd283cd19,0xdd7fd81e,0xe81ee299,0xf30aedeb,0xfcdaf867,0x06e30244,0x10750be7, 0x190414df,0x20f61d29,0x287e2518,0x2f6f2c83,0x36073344,0x3b863933,0x40b43ec7,0x227542a5, 0xeb19f1aa,0xfa82f39a,0xed06ff12,0xa724bacf,0xbc0db4d6,0xc67ec2a7,0xd184cbd0,0xdc97d712, 0xe716e1cb,0xf235ed1c,0xfc32f7b3,0x06570183,0x0fff0b48,0x18a9147e,0x20a41cf2,0x285124f1, 0x2f702c68,0x36193338,0x3b8f394c,0x40a33f1f,0x208c430a,0xea6df0ef,0xfa6ef3a9,0xf68bff25, 0xa711c83a,0xbad6b153,0xc5f0c122,0xd08eca6e,0xdba8d5f4,0xe623e0f1,0xf17bec31,0xfb9df6e6, 0x05ce00b1,0x0f810aa8,0x18491420,0x20581cb8,0x282f24c4,0x2f6a2c43,0x3615332d,0x3b7c3978, 0x40873f8e,0x1e724345,0xea13efdc,0xfac2f362,0xfd01fe66,0xaaaed69b,0xb9c7ad47,0xc573bf71, 0xcf92c930,0xdac1d4e6,0xe557e017,0xf0d7eb30,0xfb19f606,0x0543ffe6,0x0ef90a0b,0x17e313ba, 0x20181c68,0x280e247c,0x2f5a2c0d,0x35f7331f,0x3b5d39a0,0x407b3fe0,0x1c87433d,0xea1dee42, 0xfb3df2c6,0x00aafd6b,0xb291e4c4,0xb844a946,0xc4d1bde3,0xce81c832,0xd9d6d3e3,0xe49adf38, 0xf02aea1f,0xfa87f525,0x0498ff2a,0x0e5c0973,0x177e1345,0x1fde1c07,0x27ef241f,0x2f3e2bd0, 0x35d5330c,0x3b5039a8,0x40a63fec,0x1abd42c3,0xea6aec83,0xfbaaf22e,0x01effcd1,0xbe87f103, 0xb5b5a6c1,0xc3d0bc93,0xcd49c78b,0xd8d7d2f5,0xe3e4de52,0xef68e91e,0xf9ddf45c,0x03dffe7b, 0x0dc708ea,0x172012c9,0x1fa91b9a,0x27c623c4,0x2f212b97,0x35c53301,0x3b7339ab,0x41103fe6, 0x191b4238,0xeaa6eab3,0xfbb3f1c1,0x01bffcb8,0xcd14fa36,0xb1faa763,0xc25cbb8c,0xcbfbc715, 0xd7ced205,0xe322dd6e,0xee7be836,0xf913f39f,0x0312fde8,0x0d280857,0x16bd1236,0x1f671b27, 0x27862363,0x2ef32b5b,0x35ac32dd,0x3b923977,0x41753f96,0x17ad4166,0xea4ae986,0xfb2af169, 0x00e8fcfc,0xdcb6003c,0xad85ac7f,0xc0b5ba46,0xcad3c6a7,0xd6c6d101,0xe248dc7b,0xed78e767, 0xf82ef2e8,0x0243fd55,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, }; static const PROGMEM uint32_t sample_3_SawWave_SSTR186A[4864] = { 0x0f2301e0,0x111b15c7,0xcdcdec69,0xec81cff7,0x14b20751,0x19801759,0x22e0205c,0xf36311fe, 0xe596e443,0x0786f356,0x16831131,0xe0400836,0xd5dbca8d,0x0a4cf412,0x17ee154d,0x22621bfe, 0x0ab92159,0xe3f2edf1,0xf9e4e894,0x13b00ca4,0xfcc915bd,0xc9a1d5aa,0xf9cadc8c,0x16810c70, 0x1eda19ed,0x1e0923d3,0xe95b02b0,0xec55e3ea,0x116c0118,0x129c16da,0xccf1efc1,0xe33fca9e, 0x0e8ffde6,0x1ced18b0,0x24752193,0xfa821902,0xe429e58b,0x0883f130,0x1a0f163a,0xe1ec0c30, 0xcd98c65b,0x00ece9ac,0x1bc21131,0x23b02041,0x126d23f7,0xe292f2cc,0xf755e535,0x1b370fdd, 0x01c51bca,0xc294d45d,0xef6fd2ce,0x1484035a,0x23261f6e,0x220524cd,0xec220ab8,0xe7ade0b1, 0x16fefeb7,0x1a312008,0xc8a9f3a8,0xd9c4c25f,0x05b8f3e5,0x23441893,0x24d624e2,0x028b1e7b, 0xe029e6e3,0x06feebe5,0x23de1dbe,0xe37d13d9,0xc5bec082,0xf6d7e109,0x1d5808ac,0x252f2692, 0x19692404,0xe310fa96,0xf1e9e10e,0x24140faa,0x085e258d,0xbccbd3d8,0xe72dcb80,0x0cd6f8e0, 0x28942275,0x227a246d,0xf346130f,0xe39ae06e,0x1857f97f,0x238229f2,0xc74ef8b0,0xd207bd01, 0xfb2aebb0,0x270c1268,0x234128f1,0x0bd0200e,0xdf11ecad,0x0241e829,0x2e9b2101,0xe72e1c35, 0xbfa0bf50,0xeef3d861,0x18c7fec6,0x27f82a28,0x1c852202,0xe6d50418,0xeec1dfa9,0x297b0bd0, 0x0f52305a,0xbb7fd708,0xde52c375,0x0416f1bb,0x2b641ebb,0x209c264e,0xfc2217df,0xe2dae252, 0x15e5f6e0,0x2d6630eb,0xca95fe90,0xc855ba51,0xf4dbe3a8,0x233f0a8c,0x24792b1b,0x12381eca, 0xe030f42a,0xfffae85e,0x36191ffe,0xecf72511,0xbab0c21c,0xe819ce5c,0x110ef8f1,0x29fa2629, 0x1c5522a1,0xece10b82,0xef4fe105,0x297309c2,0x181b3814,0xbc64dd18,0xd4f6bcad,0xfe0aebc6, 0x27ee16d4,0x20a3286d,0x03b21905,0xe464e76b,0x13f8f724,0x363431cf,0xcfe30827,0xc0a8b86e, 0xef4adb1a,0x1bc703b5,0x267d28f0,0x148d1e58,0xe4a9fb5a,0xffe0e977,0x38c21e35,0xf7032fdf, 0xb659c514,0xe03ec64a,0x0984f329,0x29272002,0x1bae2417,0xf3b50ec5,0xefd1e4ba,0x282b0961, 0x24d93d70,0xbc69e628,0xccaab6c0,0xf78be493,0x23530f36,0x214a2860,0x08061891,0xe73aee11, 0x133df754,0x3e65318a,0xd6ac15c6,0xb9c3b62d,0xe88bd300,0x1474fc5e,0x2695255c,0x14e41e45, 0xeb280130,0xffd0ebae,0x39a41cff,0x04263a62,0xb2ccc969,0xd8e5bee7,0x016aec7e,0x25f818cb, 0x1b2b23f9,0xfb4610a1,0xf1aaeb05,0x265908e3,0x31153f71,0xbeeef1d4,0xc564b25e,0xf09dde33, 0x1be80655,0x20ca2545,0x0c0117f6,0xed46f71b,0x1222f8dd,0x41dc2f02,0xe0842323,0xb4acb76b, 0xe2f6cc71,0x0ab9f4e3,0x23751db8,0x149e1d40,0xf528079b,0x00f8f16c,0x369e1b1e,0x11de3feb, 0xb2d7d166,0xd36eb959,0xf921e753,0x1e3c0e4c,0x198520bd,0x0435115c,0xf710f575,0x2380098a, 0x38f13c87,0xc520fef7,0xbff2b133,0xeb60d9f0,0x10d4fd0b,0x1d571d7c,0x0eb315db,0xf7c1025f, 0x1206fdce,0x3fb32b0c,0xec402cf1,0xb292bc0c,0xdfa8c7d8,0x004bef0c,0x1ba21226,0x12ac198d, 0x023f0d39,0x0529fbaf,0x317319f2,0x1cdb3f15,0xb650db75,0xd02ab6e3,0xf220e454,0x123e029d, 0x15b51900,0x0d3a1091,0x00cd03a7,0x20ec0c96,0x3a073639,0xcdd80a80,0xbdc3b3eb,0xe7bfd7de, 0x03daf44f,0x15f91146,0x10301242,0x06540ea0,0x137e0699,0x38e226ac,0xf8083093,0xb4cec3ed, 0xde13c64f,0xf577e9ce,0x0f980400,0x0fe912d9,0x111f11ee,0x0c6d09f3,0x2b24195d,0x237338ea, 0xbdaee73b,0xcf5bb8c0,0xea99e238,0x0338f59d,0x0ff90d8f,0x15b30f8e,0x0e071456,0x1dfe11a9, 0x35da2e66,0xd94213d3,0xbf44bad3,0xe431d7ac,0xf4ceea70,0x0b6501db,0x11cb0e03,0x17c71af5, 0x15ea11f0,0x30722184,0x03292f58,0xbaf5cec4,0xde1ec7a9,0xe980e45a,0x003bf341,0x0dd2096c, 0x20ea169a,0x153d1acb,0x243a1916,0x254e310f,0xc7d0f34c,0xd0f6bdc5,0xe343e1e5,0xf15de7c2, 0x0857fe89,0x1d830fe5,0x1ce22696,0x1b2417de,0x2f842693,0xe5f71864,0xc33ec3e4,0xe2ded9b5, 0xe54de138,0xfd25ef6d,0x144608dc,0x2af525d5,0x19af1e2e,0x28cc1c4d,0x0a582ac1,0xc2a3dbe1, 0xe059cb21,0xde44e16e,0xeda6e273,0x0b35fcc7,0x2e871ae2,0x1f282d86,0x1d631a4c,0x22562a2a, 0xd49ffd38,0xd44bc44a,0xde1de3d9,0xdf89da98,0xfdf8ec7f,0x23930f5e,0x2e9b364e,0x19b51fb9, 0x290d1f3c,0xf21d1756,0xc911cfc0,0xe3f0dcf0,0xd691d988,0xeca8dd09,0x157c00d0,0x3c312da3, 0x1f392eb7,0x217818d8,0x0ba52458,0xcd7ce914,0xe34fd066,0xd458e105,0xdbadd2a1,0x0547ee85, 0x37ca1d9d,0x2dbe3fd3,0x18c51d5d,0x1c6122a2,0xe20a00cf,0xd8d4ce4c,0xdbffe64d,0xcf67cf1e, 0xf20ddc1b,0x27410b6e,0x411640cb,0x1ac02b4a,0x216019a3,0xf7a81288,0xd22ddd45,0xe5bbe089, 0xca49d5de,0xde7ccd9c,0x1331f717,0x47cf317d,0x27723fdd,0x1acf1841,0x08551d30,0xdb2df08e, 0xe601d847,0xcf65e227,0xcdb7c649,0xfd8ae289,0x3b7b1c1c,0x3c644c4b,0x168122d7,0x164b1b6a, 0xebacff06,0xdf33dbd4,0xdc5de861,0xc38bc919,0xe7eecfbe,0x25a7052d,0x4dff44a7,0x1e303754, 0x1a9015d3,0xf77a0d6c,0xded0e900,0xe762e57c,0xc361d51f,0xd37fc265,0x0db9ee79,0x4c7b2f7b, 0x31684d03,0x16211a28,0x03ae1766,0xe86ff23b,0xe9e1e36c,0xcd2be319,0xc310bea8,0xf602d8ba, 0x395c16ea,0x49a75260,0x17522b38,0x117716ab,0xef84fa78,0xe8bbe9ce,0xdc07eb4c,0xbb5ec554, 0xdf2dc5a7,0x2093fe66,0x55c442e2,0x2565445a,0x163715e7,0xf32f090f,0xecd1ef4b,0xe910ed7b, 0xbe66d332,0xca18b9f0,0x0789e695,0x4b6a2a7a,0x3dd1563d,0x15872080,0xff5a138f,0xf139eee3, 0xf040f0d2,0xc9e9e346,0xbaa8b8fb,0xeecbd00c,0x34491144,0x53e65236,0x1cd536f6,0x0e1b1555, 0xedf6f604,0xf4c0f4a5,0xdad8eff6,0xb576c153,0xd713bd87,0x1b51f7ca,0x56b73d9b,0x30814f6d, 0x14411a51,0xeeb40620,0xf8a3f010,0xec45f77f,0xba29d10f,0xc243b401,0x0188deeb,0x46012559, 0x49b658cb,0x189c2acb,0xfca5115d,0xf441ea92,0xf844fc51,0xc726e582,0xb4a2b4c2,0xe77fc87c, 0x2ef60bd9,0x58ae4d24,0x25ea436d,0x0c20172e,0xea05f333,0xff18f956,0xdc55f698,0xb13cbe1b, 0xcfd9b751,0x1655f0ca,0x52d037c1,0x3cf756ac,0x156d21e9,0xeb7f0496,0xfe4aec9e,0xf21a00a2, 0xb6acd1ad,0xbc08afa9,0xfac7d7ff,0x3f8b2056,0x531556d3,0x1edc369e,0xfb8212a0,0xf141e6e1, 0x00800283,0xc6c7ea8b,0xb034b13f,0xe0b8c28a,0x2948053a,0x58f54667,0x309a4e4a,0x0e041cc4, 0xe5d3f24f,0x05cbf6b5,0xe041fde9,0xadecbce8,0xca42b313,0x0f92ea0e,0x4c573120,0x48a45933, 0x1b382b46,0xeab8070d,0xfc35e7c0,0xf81b07ce,0xb4ead467,0xb80cacb7,0xf406d2a0,0x38551933, 0x57ef5128,0x27324248,0xfe0a18f5,0xeb8ae601,0x07dd0195,0xc889ef18,0xad92af14,0xdb6abe6a, 0x220ffe41,0x54dc3f3c,0x3b84557b,0x1444248c,0xe45bf46d,0x06bef05d,0xe3d1053a,0xab56bde2, 0xc573b01d,0x0846e490,0x45d02a89,0x51b457c6,0x2264352a,0xec0b0c49,0xf60de510,0xff990b3b, 0xb513d798,0xb3cba96d,0xeddfccd9,0x32d611fd,0x59ef4c08,0x300e4c7f,0x01d91ef0,0xe767e60f, 0x0e39fcb1,0xcb95f71a,0xa8faae37,0xd498b84c,0x1b95f73a,0x51f93adb,0x46595abe,0x18d82c23, 0xe2b2f6c2,0x0425eb24,0xec330ea9,0xa918c092,0xbda4a9cc,0x00c2dcc5,0x42782519,0x59925769, 0x28774023,0xecbc0ff7,0xf061e1c8,0x0b730bb5,0xb6f1dfae,0xabf7a583,0xe581c3fa,0x2e560aa1, 0x5bbe49a2,0x3a6d565d,0x050c23e6,0xe303e50b,0x11fef73f,0xd2a10403,0xa383aec8,0xcb5eafa5, 0x14bceedf,0x50443717,0x518d5e70,0x1d8e354a,0xe051f969,0xff7de60a,0xf8c71539,0xa826c611, 0xb4dda35c,0xf8c4d3b6,0x3f421ed2,0x5f34563e,0x30734bbe,0xee991508,0xeaa9de66,0x140d083a, 0xbaaeeb03,0xa538a345,0xdccabb68,0x28a702f1,0x5b6546db,0x45955deb,0x0a992b4d,0xdea6e5d5, 0x100bf0ea,0xdc340e05,0xa079b0e2,0xc2f3a8ff,0x0d3de659,0x4de73225,0x5aa75f6c,0x25183fa0, 0xdf96ff0b,0xf8c6e09a,0x03971544,0xa905cd9a,0xae549ff8,0xf040cb39,0x3b3917a0,0x61e75458, 0x3a1e55cd,0xf35d1d1b,0xe456dbe1,0x165c01a8,0xc030f5d0,0xa1a6a377,0xd415b4c7,0x221ffa7e, 0x5a0243bd,0x50106283,0x12d234cb,0xdaa9e8b3,0x0a24ea1c,0xe62d1260,0xa065b4d2,0xbc0da51a, 0x051ddd7b,0x4b6f2c9a,0x61275eb4,0x2ec74a3e,0xe0430664,0xf1cadbe1,0x0969102f,0xac23d666, 0xa9e39f9c,0xe768c3fb,0x36b01020,0x62405216,0x44de5e14,0xf90226df,0xdf6adad6,0x11eafa68, 0xc80ffcbc,0xa0a9a640,0xcc7cafc1,0x1b5ef1ed,0x57ad3fdc,0x59e56475,0x1c533fd3,0xd875ec71, 0x0226e51d,0xee510e85,0xa2c8bc1a,0xb68da33e,0xfd1dd598,0x47b1266b,0x65265c5a,0x3a42556d, 0xe2230f4c,0xec90d8cf,0x06bf06e4,0xb2b0dff7,0xa745a142,0xdf8ebe1e,0x30b308d7,0x60394e23, 0x51566463,0x00d132cf,0xdbc8dabe,0x0736f483,0xd2adfc5a,0xa177aba3,0xc667aca2,0x1490ea9d, 0x537539c7,0x62bb6339,0x28414d7f,0xd67af26d,0xfadfe150,0xf10c032b,0xa6dcc6d9,0xb315a358, 0xf693cfa2,0x41961f97,0x655b57f1,0x48a960f8,0xe5c41a57,0xe88ed587,0xfc23fd9c,0xbcd1e5d8, 0xa6b7a451,0xda03ba68,0x297e02a9,0x5bc64839,0x5f5066f9,0x0a4c4118,0xd7dbdc38,0xfbdaef90, 0xdb41f3dd,0xa3c9b4f7,0xc2a6ab5e,0x0e09e55c,0x4dc13242,0x68875f50,0x35cd5cf2,0xd681fa59, 0xf3f8dcb2,0xebbef650,0xaf62d198,0xb131a4f3,0xf10bcbe4,0x39ed1848,0x6314526c,0x587369f2, 0xec9d273f,0xe273d47a,0xeeddf425,0xc903e485,0xa7a8abe0,0xd606b82f,0x2168fc63,0x56e34084, 0x6a7e673d,0x170750bb,0xd548e241,0xeff8e71a,0xde1de7ad,0xaa4ac18d,0xc037abf0,0x06f6e0ba, 0x464f298b,0x6b495bdd,0x457e694b,0xdb45070a,0xe8dcd7ca,0xe21ee8f6,0xbb71d7fd,0xb1aaaaaf, 0xeb98c903,0x30dd1099,0x61714bf9,0x65ae6e6d,0xf8b1373d,0xdabcd710,0xe18de6bf,0xd1ecde19, 0xad19b721,0xd25fb85c,0x1955f62a,0x522837a3,0x704a66e5,0x27155f2a,0xd521ec9d,0xe13ddc8a, 0xdaa6dba4,0xb4eccc6a,0xbf80b139,0x000bdc37,0x3e4b2164,0x6b5d58e8,0x554870ef,0xe2fb166d, 0xdb7ad4fd,0xd77dda48,0xc81ed750,0xb65ab4d9,0xe659c70d,0x2903092a,0x5f67454e,0x70096ed6, 0x068147f3,0xd548dc09,0xd40ad6e2,0xd49ad448,0xb6a5c528,0xcf77bbcc,0x11d4f051,0x4cc03070, 0x720a64b2,0x37e56c51,0xd7d2f84a,0xd021d3cb,0xd1b2cf4d,0xc356d2ff,0xc189b9c6,0xf9d6d8f3, 0x37e51a63,0x68d553fa,0x6468750e,0xec982685,0xcf1bd534,0xcba0c98a,0xd22bd073,0xbd92c2a3, 0xe30bc828,0x22fa030a,0x5a2b3f68,0x76906cc5,0x15645813,0xd1f4e3c9,0xc45ac806,0xd115c8db, 0xc316d17b,0xd00dc1c0,0x0c4eed13,0x46972b80,0x71065f48,0x485a74d4,0xdd0f05e1,0xc094cc6e, 0xc7bcc079,0xd0d0d320,0xc67cc482,0xf6c1d8ee,0x33a615d8,0x63f74d12,0x6eef74f9,0xf8c836cd, 0xc4d1d69f,0xbdd5ba1d,0xd5a0c8e8,0xc697d06f,0xe234cc09,0x1f860051,0x52f33b0b,0x778c6897, 0x250564d5,0xcef0edd2,0xb511bc60,0xcc19bcff,0xd076d7fe,0xd275c92c,0x0a2feb90,0x41a728e1, 0x6d0f587a,0x56e677cc,0xe3b41462,0xb454c5a2,0xbe70b1ca,0xda0bd07f,0xcc56d0c2,0xf526d9ac, 0x316c147a,0x5da247c3,0x74b67132,0x05824625,0xbb64d8e7,0xb0dfad92,0xd55bc1f0,0xd13bdb99, 0xe1b0d04c,0x1eddff53,0x4d8738f6,0x749d6251,0x34426d57,0xcca1f7da,0xa8ecb161,0xc6d0b28c, 0xdc6cda26,0xd53cd216,0x0a2deaab,0x3f9c28bf,0x669752cb,0x61a6765f,0xea0922d0,0xa8d5bf4c, 0xb667a713,0xde5acc62,0xd3a9dc8d,0xf4d2db5e,0x31aa1563,0x57494578,0x754b6a7e,0x124052c3, 0xb238dae2,0xa844a2be,0xd225bba2,0xdc65e183,0xe2ffd63a,0x205b0012,0x4a7c395b,0x6de85ae2, 0x422b70aa,0xca4201a8,0x9fcba6f0,0xc179ac25,0xe390d7a3,0xda0edc7a,0x0beaec64,0x3fb62a73, 0x5ddf4e89,0x68687099,0xef9130a6,0x9eb2b94c,0xb1e4a037,0xdc8fc76f,0xdd2de4ea,0xf753df98, 0x3313178b,0x519d44c6,0x7213610a,0x1dc85cc4,0xa9f0db40,0xa3b79a1e,0xcd3cb88f,0xe61ae0e5, 0xe737dedd,0x221802f0,0x48c039dc,0x653c5437,0x4de0715a,0xc5b80872,0x99349e10,0xbf59a987, 0xe4f8d2ca,0xe219e783,0x0e10f0ac,0x3edd2ae4,0x575c4c0b,0x6d246a6d,0xf0213b73,0x9692b19c, 0xb0969b8c,0xd829c5c7,0xe963e927,0xfaeee765,0x319f17dd,0x4f3042ac,0x6f2a5c05,0x24d16459, 0xa18ed647,0xa086935d,0xcbb2b7de,0xed8edd91,0xeeaeec0d,0x200d04ca,0x46193688,0x623a52d4, 0x560f714d,0xbe1409f0,0x940796a9,0xbec5a732,0xe346d11b,0xefedf20d,0x0da8f727,0x3a6c26b1, 0x578249b6,0x6ef968c2,0xecb44164,0x90afaa53,0xae869813,0xd632c526,0xf691e980,0xffd8f524, 0x2c1a156a,0x4dd73e1e,0x6de25d47,0x265066a5,0x9be8d08e,0x9e858f32,0xcaf8b5db,0xf042db64, 0xfb65fb41,0x1c100814,0x420830d2,0x637452c6,0x56c27019,0xb86b06f1,0x91bc928a,0xbcf8a61e, 0xe147d041,0x0048f77a,0x0f6e0225,0x354021cc,0x58784671,0x6dad6927,0xe7373e9d,0x8e09a57d, 0xae019743,0xd552c393,0xff18e840,0x08de0596,0x26ff15a7,0x4bbd3982,0x6da35e44,0x1ffd6403, 0x97fecac4,0x9e758e26,0xc96fb5aa,0xf068dabc,0x0aea06e5,0x1afa0f17,0x3e042bd4,0x639a51c8, 0x50e46f59,0xb384ff25,0x91e7902c,0xbc8aa668,0xe0efcece,0x0e65f9be,0x1481100d,0x304a1fd4, 0x578e438a,0x6ae16893,0xe07c351e,0x8dcaa220,0xae6897fd,0xd45dc25d,0x03f8e842,0x14c21514, 0x2453190d,0x49ea34ff,0x6c745c87,0x15195cbe,0x96bec67e,0x9f638f98,0xc7bfb59c,0xf11bdaa2, 0x1ab60e68,0x1cce1890,0x3acb288b,0x61894fcd,0x44e76c1e,0xb1c4f5f5,0x93ff90ea,0xbbbba72e, 0xe1f1cdc3,0x183efba4,0x1aff1f0f,0x2d1b1fea,0x5497414f,0x63a46702,0xda8d2772,0x8f6ca24c, 0xae6b99c7,0xd4f5c195,0x075dea96,0x21a620dc,0x22d61c21,0x47053285,0x6aab59a5,0x095651be, 0x97fac38c,0xa00390e1,0xc864b4e4,0xf4a5dd31,0x27c0134c,0x1cb92239,0x381c2624,0x60474b9d, 0x38a3684c,0xb129ed8d,0x94209264,0xbb86a612,0xe62ad08f,0x1e83ff9c,0x21692c75,0x29d41da5, 0x50f03cd4,0x5cb066e1,0xd55b1bfb,0x90aea3d8,0xac299849,0xd99bc361,0x0aa9ef91,0x2ef62864, 0x1f272054,0x413a2d43,0x68e15899,0xff3847a8,0x9b9fc1cb,0x9cee919c,0xcc8bb33d,0xf8fce2e2, 0x309b1540,0x1fa22fd8,0x305620c4,0x60de476c,0x2c0561c6,0xb39ce563,0x9405978d,0xbbeda273, 0xebfbd638,0x1f4e0210,0x2fbc3723,0x221e1f1e,0x50503469,0x506964d3,0xd0e10e61,0x962eaa6a, 0xa9999774,0xdfa8c5b1,0x0ad9f49d,0x3c1428e7,0x1e5e2ebc,0x3b5223ca,0x600d593d,0xf35137a2, 0xa4c6c276,0x9c479684,0xcf7ab271,0xfca0e88d,0x320513b7,0x2ca23f60,0x27541d8e,0x5d3544ea, 0x1c2e51f3,0xb913ddbb,0x9874a15d,0xbc10a2ec,0xf0c7d8be,0x1cf20437,0x40b33a6e,0x1da32990, 0x4dda2e08,0x3d8658c8,0xce4f0214,0x9fd5b2e9,0xab0c9c50,0xe18fc587,0x0bdef835,0x41b82682, 0x265c3fbb,0x372e1ff7,0x4c76516d,0xebb3267e,0xaec3c41e,0xa1fca07e,0xceaab3be,0xfef8e9e7, 0x30341404,0x3cba4735,0x254b2465,0x4ce73f68,0x0f643b72,0xbda3da39,0xa367ac8f,0xbc60a8c4, 0xf169d7aa,0x1cc405a0,0x4a2339aa,0x24f138f3,0x42512c93,0x28c74143,0xcdf0f9e0,0xaca8b9ba, 0xafe6a7ed,0xe044c4f1,0x0cc7f802,0x4225260e,0x36404a83,0x32a9282c,0x31f53d4a,0xe7801607, 0xb810c641,0xad1eaee8,0xcd78b71b,0xfe40e7e2,0x2fa8149d,0x49bb48b4,0x2cb535b6,0x316a3387, 0x03fd2233,0xc24dd96d,0xb26fb8a6,0xbe85b266,0xee82d587,0x1d2d04b6,0x4d5638e2,0x36ee497a, 0x2cca2fa8,0x13532290,0xcfdaf3a8,0xbaf0c183,0xb7bab64a,0xdca4c621,0x0b99f4c5,0x40da2667, 0x4a0a516c,0x2d653892,0x14421fce,0xe5e90596,0xc346ca9b,0xb9f9bdf5,0xcd6fbd69,0xfb10e302, 0x2f99132d,0x55f647d8,0x38544a9d,0x10a523cd,0xf94b07d8,0xc98fdb2d,0xc0fbc662,0xc39dbd73, 0xe946d3d7,0x1baf015e,0x4f5f37e6,0x4a7c5a34,0x147932e7,0xfd9a02a3,0xd406ee8f,0xc9a3cbeb, 0xc12dc3b2,0xd978c9d8,0x0800ef99,0x3fd1248c,0x5d1557e0,0x26494819,0xf714037d,0xe535f5af, 0xcff0d12b,0xc609cc83,0xcf59c59f,0xf5bcdef8,0x2d120f5d,0x5ff448da,0x40415e50,0xf3f7143d, 0xef7ceea4,0xd241ddcb,0xced7d414,0xca7fc87b,0xe49ed409,0x1742fbce,0x530935f7,0x5c5f667f, 0x00d430f6,0xe9bce745,0xd977e9e4,0xd7bed5a9,0xcbabd08c,0xd881cef5,0x022cea2e,0x405b1fab, 0x6b3c5cda,0x1c2653d7,0xde6bef12,0xe4d9e77d,0xd9edd870,0xd224daaf,0xd2a3cf75,0xef8cdd13, 0x2984091b,0x65904bb4,0x42c96c5a,0xe03e060f,0xe657da13,0xd9bfe12e,0xdccede6d,0xd2f5d464, 0xe183d5d6,0x113df4f4,0x567d354d,0x66316d1b,0xf1db2b6c,0xd9bfd540,0xdf22e576,0xe2c5dc7e, 0xd748de92,0xd8ded598,0xfb0be599,0x41d71b70,0x7193604a,0x126c569d,0xcf07e0d0,0xe48edc30, 0xe047de4b,0xe097e6a4,0xd78dda0a,0xe9b9dbaa,0x279802c8,0x69194d9d,0x3f876f0f,0xd39ffb93, 0xdfe1ce1c,0xde83e324,0xea10e4ab,0xdc35e2cf,0xde4fd92b,0x0ce0eee6,0x584c344f,0x62e56ee5, 0xe88b25ac,0xd217cb58,0xe114e2f4,0xe935dfe0,0xe4c2ed2a,0xda88dde4,0xf632e18a,0x405318e7, 0x6db661ba,0x0d5f4e7c,0xc922d9e9,0xe3c1d916,0xe22cdf05,0xefbdedc6,0xdf0ee656,0xe65cdc04, 0x25820010,0x67b14b72,0x368362ff,0xd082f8d0,0xe006ccfe,0xddc4e1ea,0xf276e52a,0xe7a4f18b, 0xde91df81,0x0bfced63,0x55663178,0x50976653,0xe8d91f7c,0xd4fbcd2a,0xde88e41c,0xe91add93, 0xf2aff713,0xdfb2e851,0xf6a6e2fb,0x3c851893,0x5b985beb,0x0ba73b7a,0xcf86de46,0xe42fddf0, 0xde74db23,0xfb1aee7d,0xe7f4f34d,0xe953e0d9,0x247301a6,0x5b314679,0x27df49f1,0xd96efc0a, 0xe4ded5d8,0xd8aee0ea,0xf547e0d3,0xf327fe10,0xe3d3e718,0x0d4af151,0x4d632f39,0x36845140, 0xf17a1782,0xddf8d95b,0xdbfde7d5,0xe565d791,0xffabfc8b,0xe6f7f22c,0xfa9de899,0x38de1867, 0x40634db1,0x0b1a2550,0xdc89ebee,0xe659e5c3,0xd833d71a,0x0308ec54,0xf0f4ffe1,0xeee4e853, 0x22ae0474,0x45333fcf,0x17ec2d8c,0xea0a033c,0xeb1ae1ee,0xd36ce166,0xf4d5db18,0xff1107dd, 0xeb3df055,0x0dfef660,0x40af2c23,0x1ce735a4,0xff850ef3,0xe886ea69,0xdad9ec66,0xe06fd1af, 0x0ad2fda7,0xf0bafde9,0xfe52ef97,0x33361728,0x239f391c,0x0aae107b,0xec9bfe5a,0xe97aee97, 0xd257d488,0x05c9e7c5,0xfd060c2b,0xf51af230,0x2009060e,0x2a763476,0x09091380,0xfe450a64, 0xf240f060,0xcfd8e371,0xf064d569,0x0c650cb6,0xf4b8fcaf,0x0dbdfb15,0x2d622704,0x079d1938, 0x0c5306ac,0xf4d6fec7,0xdbe6f26a,0xda83cda8,0x1217f9d0,0xfcee0c04,0x00fff823,0x289215a7, 0x09d61f49,0x088f00b6,0xffdd0ec2,0xeedbf8c5,0xce1fd49e,0x0388e157,0x0b6515ce,0xfbeefdbf, 0x1c370731,0x0e9c2219,0xfec5feb3,0x10c40d0b,0xfb02017b,0xcf37e814,0xe9eed0c7,0x18150cc6, 0xff180a9f,0x0e09ffc3,0x14bd1ddc,0xf87cffc8,0x127000f2,0x03911211,0xdf93fa58,0xd554cc75, 0x14d8f414,0x09c61929,0x041400aa,0x17d41409,0xf53904ad,0x05cef6f9,0x12db179e,0xf60d05a6, 0xcc27d764,0xff00dbf8,0x190b1b84,0x024f08fd,0x15a0096f,0xf6430ae3,0xf925efb8,0x1be60c05, 0x069213a2,0xd0f7ee9b,0xe4bfce23,0x209e09e5,0x083617b7,0x0e94049d,0xfaff0fc3,0xeeeaec29, 0x12bcfd94,0x14bb1efe,0xe57004f0,0xd2a5cce7,0x144fef24,0x155623a5,0x0852078f,0x02c00ff5, 0xe739ecc3,0x0339f1a0,0x2128193f,0xfff615c5,0xcbb8dc10,0xfa92d9b6,0x241b1da5,0x07e0123e, 0x0a190c54,0xe322f290,0xf669e6f3,0x1ef90985,0x15972301,0xd407f7ac,0xe2d4cde0,0x24d30694, 0x0f332211,0x0cfd09f9,0xe43bfced,0xea23deb7,0x1004fc20,0x24d323d4,0xed1f12bf,0xd327cef2, 0x1251ed6f,0x1e4728db,0x0c9b0d7d,0xec8706a1,0xdeb0dacd,0x020cef6c,0x28391662,0x0c5225ff, 0xcdd6e259,0xf915dabb,0x29a21c5f,0x0ddc19fe,0xf9460c07,0xd691de23,0xf587e1ea,0x1c9107d8, 0x253b2c63,0xd9bc02a1,0xe3f6d081,0x239704e2,0x169627e0,0x04cf0ee4,0xd49fe923,0xe73ad68d, 0x0d8afb8c,0x2fe422b1,0xf74b216b,0xd60bd4e8,0x0f7dee71,0x248827e0,0x0cfd14cf,0xdb18f74f, 0xd9bbd014,0x013bed70,0x28a9134d,0x1a4331f1,0xd416ec7b,0xf958ddb5,0x29b01801,0x13b320a8, 0xe786051a,0xcf9fd172,0xf3c3def9,0x193606bd,0x31dc2e2d,0xe4051059,0xe6e7d694,0x1e900364, 0x1d59295e,0xf7901077,0xcc14d99e,0xe51ad242,0x0c3dfa0f,0x33151f38,0x04ec2f26,0xdb7edec6, 0x0be2f0a9,0x278d2389,0x08611abf,0xcf56e7c2,0xd6c6ca36,0x0052eb8e,0x255511e0,0x295a3754, 0xdca5f994,0xf9cae205,0x26ec130e,0x16fd2581,0xd942fb20,0xcb19c888,0xf249dc27,0x17ca0682, 0x3a722bc0,0xefc52066,0xe95add0e,0x195b01a9,0x23cc28fc,0xeb1c0f48,0xc4b5cdc3,0xe21fcdec, 0x0cb8f933,0x32af1e0b,0x15033b3b,0xdf72e860,0x0878f0be,0x2a801eed,0x026020da,0xc563db8c, 0xd217c399,0x0019e8d0,0x24991325,0x385739d5,0xe3af08af,0xf7cbe369,0x23e30ead,0x19cf2b99, 0xce7df1dd,0xc4efbff5,0xf024d76e,0x19a40701,0x40082b86,0xfd123144,0xe897e1a4,0x1488fe70, 0x2ac02886,0xe0e40d2d,0xbd77c492,0xddecc837,0x0e01f7d1,0x32ef1fce,0x26c543ac,0xe201f360, 0x04b4ee96,0x2cb01a2c,0xfc4b257f,0xbdd4d20b,0xccf0bdb8,0xffafe565,0x259714d3,0x43853a93, 0xec341a55,0xf4ffe461,0x1fe70a7d,0x1a762f12,0xc673ea33,0xc015ba3a,0xed9dd2ca,0x1afe0799, 0x41a62b7b,0x0d6f3f2d,0xe84fe7bf,0x0fd1fb64,0x2d6c25e3,0xd9980a71,0xb971be59,0xd9b6c3d8, 0x0f39f65f,0x3202206a,0x36e0470a,0xe5f90161,0x014ced59,0x2b321547,0xf7d225d2,0xb99dcbf7, 0xc8b7bac6,0xff69e1c5,0x2587161d,0x49943939,0xf7692b5d,0xf2fee6a7,0x1b7f069f,0x17f62d79, 0xc1ece553,0xbd8ab7d1,0xeae1cec7,0x1c1b0845,0x408c2aec,0x1e054842,0xe94af07c,0x0bd5f8c3, 0x2a072201,0xd53405ad,0xb831bb91,0xd626c15f,0x1072f4bb,0x30e62176,0x42a046f8,0xecc010c3, 0xfe4fed3d,0x26bd1199,0xf2391fb3,0xb874c8da,0xc634b9da,0xfecedebf,0x269817b5,0x4b53376a, 0x05453926,0xf1e6eb81,0x17ff0397,0x101326ef,0xc0a3e0c0,0xbc35b787,0xe864cc12,0x1e37087f, 0x3e502bc0,0x2d2c4c86,0xebe1fc22,0x091ef6a9,0x210b1dd8,0xd2fefea3,0xb78cbbdb,0xd312bf37, 0x1166f2c7,0x311a2437,0x49ca454c,0xf502203c,0xfb2aed45,0x20b80fac,0xee7d1623,0xb913c911, 0xc32eb7f7,0xfd57db75,0x29a31973,0x4b6f3730,0x136c4307,0xef18ef8f,0x16cd0023,0x09221e8d, 0xc215e0df,0xb928b704,0xe547c883,0x20a2075a,0x3eb02e6d,0x38f04f04,0xeba60769,0x06fbf138, 0x17961beb,0xd598fc7d,0xb574bce8,0xcfa0bbc1,0x1061eff9,0x336026a4,0x4e6d4731,0xfcbc2cd9, 0xf4c5e91b,0x1c150f70,0xf0d80e31,0xb8cecc45,0xc020b504,0xfa81d895,0x2b5d183e,0x4eba39cc, 0x201d4950,0xe835f3aa,0x1679fb3c,0x04a016c7,0xc4d8e5ec,0xb655b59c,0xe2d2c651,0x1edd040e, 0x42182fa5,0x40bf52ee,0xec641390,0x0419ea1f,0x0e3a188a,0xdbe2fb9f,0xb37ebf33,0xce21b99a, 0x0c51ed62,0x34ef246f,0x529f4b09,0x07713622,0xefc5e7ae,0x14800c4a,0xf2fc0531,0xbaced365, 0xbea5b2d2,0xf751d733,0x29a51361,0x528c3c16,0x2a464e03,0xe6d5fc54,0x1038f830,0xfd420c26, 0xccb3ead5,0xb419b723,0xe107c53c,0x19a8fff0,0x44bf2f44,0x45d956bd,0xf3b61daf,0x007aea67, 0x027b0e38,0xe3a0f6c8,0xb484c72c,0xcd2fb7b3,0x070beac8,0x35c11fa2,0x56584d83,0x11853aec, 0xf136ef44,0x073b056d,0xf1a9fa04,0xc246dd68,0xbd8db404,0xf370d621,0x259f0d0f,0x54603d24, 0x2e7550d9,0xef7d0793,0x052bf8a0,0xf406fdf7,0xd7baed95,0xb661be88,0xdf1fc51a,0x12aefa77, 0x44fc2be4,0x46cf5758,0x012d2248,0xfdbdf330,0xf557000f,0xea00f0a0,0xbcfad28a,0xcd47bb42, 0x003ae705,0x32d5189a,0x55354c41,0x182a39fa,0xf817fe4f,0xf83efe9e,0xef39ef3f,0xce82e685, 0xc165bdf6,0xed57d4c2,0x1f6b05b1,0x51993a9f,0x2cc14e01,0xfde110e0,0xfb07fbc7,0xec32f04e, 0xe344ef03,0xc0b5cc5d,0xdaadc750,0x0bccf299,0x42d62773,0x42f253c9,0x0c162144,0xfc75fe8e, 0xea13f445,0xef6aebc7,0xcc10e0c2,0xcc0cc3f8,0xf7c1df2b,0x30721314,0x51f34a82,0x18ab3607, 0xff220916,0xec53f95f,0xed4ee63d,0xdf50f020,0xc6eacce0,0xe315cf8b,0x1b71fd94,0x50693996, 0x29814bdb,0x07641318,0xf2e6fe73,0xe4bbe4fa,0xf0f6f019,0xce1adec6,0xd25dc965,0x0453e74d, 0x41f62436,0x42315356,0x101a1f48,0xfb5c0687,0xdf57ea63,0xf398e531,0xdebef1c4,0xcb99cf80, 0xec4dd52c,0x2c960bc7,0x526548fe,0x186936a5,0x058c0f01,0xe19ff538,0xe756dbc3,0xf25af75a, 0xd116deff,0xd871cd99,0x1376f21f,0x4e50342b,0x2b7d4d4e,0x0ef314d8,0xec710308,0xda29da16, 0xfb05eaff,0xdf9af2a4,0xcf6dd2a8,0xf888dc60,0x3b1d1ae7,0x44ce5153,0x13a722b0,0xfdb70f01, 0xd470e26f,0xeff9da74,0xf2cefe48,0xd3bfe095,0xe0ebd14f,0x21daff3c,0x512c41b1,0x1cfd3ac4, 0x0e1513ca,0xd8d5f539,0xdcbbd0a4,0x0101f5d5,0xe19ff320,0xd390d430,0x05e2e5d8,0x4797286f, 0x316e4d6d,0x14ad19db,0xea660ae6,0xce9dd0a3,0xfc0de0f9,0xf3c10341,0xd449e23b,0xeafdd63b, 0x2efe0c29,0x46e34bc9,0x18862a24,0x046515c1,0xca27deca,0xe6e0ce8c,0x051c0241,0xe21cf48d, 0xd92ad474,0x1201f040,0x4d3735b5,0x25013f39,0x15bc18ae,0xd3cffa7e,0xd0a5c583,0x082bee06, 0xf529068f,0xd4e0e13e,0xf58bdc57,0x3c3017c5,0x37e34b9c,0x19f7219d,0xee4212f8,0xc305ca66, 0xf612d4dc,0x07830d5f,0xdfcbf524,0xdfedd5a5,0x1df9fad1,0x47824197,0x1fa93188,0x0c981b61, 0xc324e16a,0xdae4c2e0,0x1163fe85,0xf42507e4,0xd6f7de18,0x002ce405,0x451124cf,0x2c4241bc, 0x1ba11ee6,0xd58b0305,0xc4f6be54,0x06bae24e,0x07a013ef,0xdca1f214,0xe894d8f5,0x2c0b05d6, 0x3b1545f9,0x1eff2807,0xf78119c3,0xbbe3cbac,0xeaabc8db,0x151b0e0a,0xef2e06ab,0xdb95dbcb, 0x0c0ded7e,0x43fd330d,0x24db344e,0x154c1f91,0xc414eb66,0xce1ebb7e,0x1406f3ba,0x04e91552, 0xdba1ebdd,0xf2a8debe,0x38d9131b,0x2e2c3f4e,0x1ffc22d9,0xdfbd0e18,0xbcc5be95,0xfd4fd49b, 0x14fe1881,0xe88a0225,0xe269dc05,0x1b14f813,0x38e03c47,0x22092943,0x04711f44,0xbaead522, 0xdc91bf81,0x1b900705,0xfe35142a,0xdcf9e589,0xfdece67c,0x3c932385,0x25be3217,0x1c512224, 0xcbe8f92b,0xc3b1b8fc,0x1020e63a,0x12681d73,0xe331f94e,0xeab3de9f,0x2b60048e,0x2c0b39e1, 0x22812382,0xed6c1692,0xb8e2c436,0xf155c96b,0x1e6017ce,0xf4210f2e,0xe0ffe1c4,0x0c4beec8, 0x351d315a,0x2287271c,0x0e63221e,0xbe52e227,0xd0b7ba90,0x1da7fd10,0x0a5d1e44,0xe162ef7f, 0xf2e1e3c8,0x3460150d,0x23592f5b,0x1feb22c6,0xd7d704c5,0xbdaaba99,0x0857d99b,0x1cbf21d3, 0xebe90480,0xe672e20d,0x1df0f7c2,0x2979340b,0x23a32118,0xfab91b57,0xb92dcecc,0xe402c1c5, 0x249b125a,0xfe7d1966,0xe38be97a,0xfe51e8be,0x30cb255c,0x20ca2440,0x14a723c4,0xc782f0be, 0xc6f7b990,0x1ad0ef90,0x144a25eb,0xe826f910,0xeb32e555,0x29c506a0,0x20992bb7,0x21cf222a, 0xe7210cad,0xbb03c25b,0xfb88cdc9,0x255021c0,0xf48a0e09,0xe6dee7cb,0x0f7ceee1,0x26492a8f, 0x23ed1f42,0x04391d4b,0xbf2ede4b,0xd68ebd3f,0x27240729,0x07782286,0xe811f0fb,0xf483e822, 0x28511708,0x203721ef,0x16c2246f,0xd6a2fbf0,0xc089bd69,0x11f6e101,0x1dbe2ac8,0xee58013c, 0xe9b6e88a,0x1bcafbc2,0x1fa7247f,0x22a0228c,0xf4390f51,0xbc88d033,0xec86c543,0x2c5c1bbe, 0xfbbc1783,0xe8faec7d,0x0368ec4b,0x20c41d50,0x24e61fa0,0x081d1e60,0xcac5ed18,0xcbabbc55, 0x246bf893,0x108a2b90,0xeb41f722,0xf03de96a,0x1c4509f9,0x215e1e5a,0x18652607,0xe64801d3, 0xbcf3c613,0x04d6d3e3,0x28362ba3,0xf36c0992,0xea19ea77,0x0e51f570,0x1dbf1a05,0x251f240d, 0xfc6911d5,0xc1f4df7f,0xdde9bee8,0x309e110a,0x032f2286,0xe9f3f084,0xfb36eb8c,0x17f71010, 0x26ab1edc,0x0bba2206,0xd89ff75e,0xc2e5be8d,0x1c9ce978,0x1b373278,0xee48fdc2,0xee3de9b6, 0x0fae0073,0x21311718,0x1d46283b,0xf22106a2,0xbc6cd1ba,0xf608c956,0x30b6269e,0xf96d1362, 0xea10ec96,0x0412f22a,0x17cd0e38,0x281c23fb,0x028117d9,0xcb1aec3b,0xd21fbc49,0x2e0f02d8, 0x0c282baa,0xeb6ff609,0xf6a4eb56,0x0ce7057c,0x268519e1,0x12b4264d,0xe579fec6,0xbeacc53f, 0x0f38dc9f,0x24753229,0xf3520637,0xed9ceaf0,0x04dcfaa2,0x1cd90cb1,0x233f2868,0xfa9b0e4b, 0xc0ccde06,0xe810c3ac,0x32981aa0,0x01881c8a,0xeb24f124,0xfd1bf0ba,0x0e07031a,0x29692043, 0x0a671f86,0xd65af579,0xcad3be68,0x246cf400,0x15142f88,0xef82fdb6,0xf43dec1d,0x0186fd6e, 0x23cf10d2,0x1b9a2952,0xef690684,0xbe7ecf10,0x004bd368,0x29c22b95,0xfa780ea9,0xee01ee80, 0xfbccf73a,0x14a8012f,0x2820271a,0x024117c9,0xc8c3e8bf,0xdcebc10a,0x2f0c0c9b,0x09632290, 0xee3df7d2,0xf8a2f0c6,0x0272f92a,0x29c9192f,0x14082620,0xe1b4fd82,0xc5aac406,0x17fae741, 0x1b452e80,0xf5e50528,0xf3ddeedf,0xf6a8f7c2,0x1e4f053e,0x23a12ba4,0xf8360ff6,0xc163da71, 0xf284cbec,0x2a99211c,0x01df14b2,0xf080f4b4,0xf4aff641,0x09aef545,0x2c6d23f0,0x0b28207f, 0xd374f255,0xd3a8c141,0x26c8fe7c,0x0f252464,0xf432ff6a,0xf6d8f30e,0xf5f6f06a,0x29560fdf, 0x1c582bb1,0xec180598,0xc3d4cdb2,0x0a17dcdf,0x1d0f2819,0xfd930ac2,0xf603f48a,0xeccaf51e, 0x1712f93b,0x29322d28,0xffdc173e,0xca44e623,0xe70ec8e8,0x25031357,0x078a1602,0xf5f0fc4b, 0xf1d2f85f,0xfe4beb7b,0x2e771d91,0x11fe2590,0xe149fac8,0xcf8ec9c3,0x1855f0b2,0x109a1f18, 0xfbcc055c,0xf965f81e,0xec82ee82,0x220d0335,0x221f2dd4,0xf6ed0d7e,0xcba1de0c,0xf804d60a, 0x19151905,0x042d0d56,0xfa5afc23,0xec04f91e,0x06a7ee20,0x2d0224f4,0x0a0b1fcf,0xdc24f431, 0xdabfce37,0x1795fca2,0x0bce14ee,0xfcd103fc,0xf7b1fc34,0xeec3e999,0x27ff0968,0x1e532d47, 0xf1dd073d,0xcfc2da88,0x0029ddaa,0x12aa164c,0x044e0b7a,0xfd93fd64,0xe64ef48a,0x0da6eeee, 0x2e502c59,0x045e1c87,0xd81aeee8,0xe0bfcfe1,0x15840471,0x0bd51161,0xfe1e0450,0xef00fde3, 0xf0bbe2b6,0x317014be,0x197a2eb6,0xea9000d5,0xd004d4bb,0x0945e633,0x10881440,0x03ca0c29, 0xfc08ff72,0xe0a2e7ce,0x1e00f5b3,0x2d5a35a9,0xfc5b1513,0xd170e4f3,0xee2dd226,0x121d0cbb, 0x0be20ffe,0x010c0367,0xe0f5f76b,0xfdabe14e,0x37eb2781,0x0fd22a25,0xdf0af702,0xd715cf81, 0x0d82f693,0x0f9b0fd5,0x03e20b1e,0xf0ab01ea,0xe48cdc21,0x2fbb076b,0x259f382b,0xf1310a49, 0xcf73d9e4,0xfd02ddfa,0x0e3d0c28,0x0a6b0f47,0x01060552,0xd9b4e900,0x11f9e9a1,0x36d73634, 0x04c7205c,0xd5f4eb56,0xe565d10b,0x0a340088,0x0f1a0d94,0x07380a2e,0xe180fdb9,0xf058d954, 0x3af61cd8,0x1abb3422,0xe5b3ff47,0xd411d319,0x0193ec2e,0x0db408d1,0x0a890f19,0xf7d208bc, 0xdac6db1a,0x2797f8f9,0x2ffc3de6,0xf98e14f9,0xd143e06d,0xf170d889,0x0861012c,0x0f170e5f, 0x08c50b94,0xd689effc,0x0393de35,0x3ea43180,0x0f3c2a96,0xdbaaf387,0xde1ed0c6,0x006bf488, 0x0f5508c8,0x0d3b0f04,0xe7870665,0xe3ead417,0x39c10f8a,0x24993cf3,0xed5b0972,0xd21ad78f, 0xf588e3aa,0x09e0001e,0x0f2b1049,0x015d0eeb,0xd3c3dfba,0x1bd9ebfa,0x39213fb4,0x036a1ec3, 0xd463e740,0xe7ded53e,0x00a5f550,0x10fe0b8e,0x0f9d0ffc,0xd945fa31,0xf615d5ab,0x42ff278c, 0x19573402,0xe15cfce8,0xd991d296,0xf4f3ea10,0x0d94021c,0x118d1174,0xf1d10e48,0xda14d48b, 0x31ee018e,0x2e7e439b,0xf5c213fa,0xd2aadbe8,0xea6addff,0x0463f543,0x11fe0f86,0x0a72134e, 0xd1fae94e,0x0d99e109,0x41d73a78,0x0e002927,0xd771ee13,0xe160d4cd,0xf6a9e9a2,0x11200729, 0x144b12f9,0xe1a00469,0xea25d1f1,0x40bf1980,0x24153e57,0xe64706de,0xd880d4b2,0xe8b5e2ce, 0x0a14f926,0x146f1276,0xfd0e13a7,0xd48fdb73,0x24a6f4b8,0x39f34489,0xfe631ee8,0xd43bdf0a, 0xe209dc8b,0xfc80e897,0x13cb0cf2,0x110215fb,0xd714f559,0x0006d9be,0x45fb2e8d,0x18ec3565, 0xd937f4c6,0xdf68d619,0xe9fcdfa7,0x0fb50066,0x16f8154d,0xedfc0c87,0xe14ad4b3,0x36df0b58, 0x30ea4594,0xeabe1151,0xd995d5a3,0xdcfbdfdb,0x0483ed20,0x16fd1257,0x06c216cb,0xd4a6e754, 0x1610eab9,0x43ec3d82,0x079e2c12,0xd4c3e17f,0xdd8bdd46,0xf19fdb99,0x14dd0887,0x151a18b6, 0xe1a0005a,0xf529d753,0x42811fe2,0x25e64175,0xda53fc41,0xdf7fd64c,0xdc94d952,0x0c50f6a8, 0x1a2d175d,0xf9e611e4,0xdcc2dd3d,0x28e4ff92,0x3e3e45ee,0xf0931d7d,0xd943d5f3,0xd4fbdf00, 0xfb83dfec,0x1a000fec,0x0d831aef,0xdaaef3be,0x0957e456,0x47d8313c,0x12b239d3,0xd44ce639, 0xdb95dc44,0xe4afd262,0x13780006,0x1a671cd5,0xee030896,0xed0dda69,0x38ce1294,0x336d4853, 0xde350664,0xdde8d4cb,0xd278d64b,0x0472e9c8,0x1f851718,0x03b6184c,0xdcaee8ca,0x1badf60a, 0x47503f3b,0xfa092a6e,0xd6bad8b0,0xd0f9dd20,0xeecbd4e6,0x1af50900,0x1500214b,0xe474ff07, 0xfef8e152,0x443724b7,0x1ee84466,0xd56aeee0,0xd9afd932,0xd8aacd40,0x0dc0f3ec,0x21711efc, 0xfa3e115e,0xe7b2e1c9,0x2d4a07ee,0x3edb47b9,0xe58211cc,0xdaf7d448,0xcbc6d45e,0xf96cdd0a, 0x22ac12b5,0x0df31ffb,0xe16ef548,0x10f4ef11,0x499834e9,0x04813620,0xd522de31,0xce94dacb, 0xe1e4cc42,0x17d8ff37,0x1dad2555,0xf0ad0aae,0xf6efe35d,0x3b6819b2,0x2a87492e,0xd940f84c, 0xd814d73b,0xce30c9a0,0x050be73f,0x269d1d02,0x073e1b56,0xe714ed27,0x21b5fefe,0x45aa40c2, 0xee021d49,0xd925d6e8,0xc63ed32e,0xecfad12b,0x21e10add,0x195026ba,0xeb280391,0x06e2ebfe, 0x44ab28d0,0x0fea3ec1,0xd6d2e60f,0xcd1ed978,0xd4f9c49e,0x10d4f2ee,0x2624261d,0xffd51780, 0xf1a4eac7,0x2f230e4b,0x34e54696,0xe07a0396,0xd76cd811,0xc48fc711,0xf929d97d,0x29651710, 0x15a22549,0xebdbfc69,0x1512f7a2,0x45e234ce,0xf8ea28f4,0xd988dd1e,0xc1efd307,0xdec1c5cb, 0x1d5dffc1,0x24792b87,0xf9be138c,0xfdc1ee20,0x39b31b42,0x1bf241e7,0xdbd0f029,0xccf1da21, 0xc833be4b,0x06a8e4c4,0x2c912333,0x115823e4,0xf15ff824,0x20f103da,0x3a483d26,0xe9940f02, 0xd8ffdc43,0xbc61c637,0xeb4fcbbe,0x27fc0d9c,0x23982ce6,0xf7b80f4c,0x09b4f573,0x3e12261b, 0x034f2f6a,0xddc5e55d,0xbff7d5a9,0xd054bc34,0x1450f217,0x2d0e2b73,0x0da8238b,0xfa22f868, 0x2a7c0f0b,0x22af3b76,0xe37bf9af,0xd02ddf39,0xbd8cbb12,0xf8f3d5d4,0x2dba1a8d,0x23a62d7a, 0xf9fa0c89,0x13bafeff,0x35132d8f,0xf24e15ed,0xdf34e3bb,0xb7f2c92f,0xdc23c03c,0x202fffed, 0x2e682f35,0x0bc023d2,0x0387fc25,0x2e8417e0,0x0a782bc4,0xe586ed25,0xc1dedc5b,0xc43bb692, 0x071ce31e,0x30732501,0x23e02fe7,0xfea10b0c,0x1b93076a,0x21262c8a,0xea9800b4,0xd64ce75b, 0xb6bfbb74,0xeaa1c987,0x28ed0e59,0x31d9320d,0x0a662378,0x0ad30109,0x27781e51,0xf8da16af, 0xe70feae1,0xb69ece17,0xcff0b867,0x1533f28d,0x34682c3d,0x226133e2,0x030409ed,0x1ef50e20, 0x0d232034,0xece5f395,0xc570e33f,0xbb9fb375,0xfab4d73e,0x2f751b4f,0x357d3776,0x097820b2, 0x113204b4,0x18291cb1,0xf16704d7,0xdc2fee5a,0xb20ebd92,0xdf5ac084,0x20b002bf,0x3ad232e5, 0x1e893649,0x06b408ca,0x17d21328,0xfe301063,0xed35f1b5,0xb714d315,0xc72db2c5,0x0a54e82e, 0x36772583,0x36123e16,0x08271bcf,0x1303095e,0x09551170,0xf2e9f986,0xc930e887,0xb607b27c, 0xf156cf83,0x29dc1123,0x41043a14,0x188f348f,0x0c440855,0x0aab103d,0xf704032f,0xe062f33c, 0xb070bfaf,0xd90cbbe8,0x1705fa26,0x3df22de3,0x31834348,0x09e11555,0x0ae70e20,0xfe5c0461, 0xf118f687,0xb7ccd5a4,0xc3e5b14d,0x01fbe2de,0x321b1c28,0x443b4251,0x12f82d09,0x0d440c60, 0xff5e03bb,0xf750fb9d,0xc9ebeb72,0xb4e9b279,0xec02ccff,0x213408b4,0x46e3373c,0x27c04328, 0x0e2e11ef,0xfc41087c,0xfb93fc85,0xe243f7cb,0xb01bbf1a,0xd61abaa5,0x0edaf3fc,0x3d7d2708, 0x3fc84a99,0x11cd227f,0x00200d09,0xfc94f674,0xf60bfdd9,0xb6b3d6b3,0xc1c5b099,0xfb19de6e, 0x2e2b154b,0x4c4c4412,0x1dec3a79,0x07681129,0xf404f658,0x00bcff97,0xca9bf0cd,0xb3a7b185, 0xe5dec993,0x1c9f0227,0x497e3640,0x33f14b88,0x0e2a1a2e,0xee0afdbe,0x0471f5a8,0xe8090212, 0xafb7bfcc,0xd174b8eb,0x09c3ecef,0x3e0e24e1,0x48934cb7,0x16cd2cf7,0xf2580781,0xfacee992, 0x00580940,0xb7a0dcb1,0xbfd5b106,0xf458d906,0x2da31200,0x4ddc4420,0x265443cb,0xfd3b1299, 0xe9e2e842,0x0c7801c4,0xd038fb08,0xb4e4b2df,0xe04ec791,0x1ab0fc78,0x47e43604,0x3d734d93, 0x0bd92095,0xe1faf103,0x08abee56,0xf2130d75,0xb1b1c466,0xcf51ba7f,0x0541e7aa,0x3cfc23a4, 0x4bf049ec,0x1b2c3649,0xe5c70154,0xf53ee077,0x0bd80e82,0xbb2de5de,0xc10ab380,0xef99d6b7, 0x2c730e7f,0x4b0341f9,0x2f6a488f,0xf3e913f6,0xe2ffde57,0x1314fcfd,0xd7e406b9,0xb74db5df, 0xddeec810,0x17e6f85f,0x4510346a,0x43b64b3e,0x08c228e1,0xdbaee6eb,0x04bee810,0xfd3d15e6, 0xb472cac6,0xcf5cbc68,0x01d7e572,0x3ac4211f,0x4a4546aa,0x20a93e5f,0xdde3fa0c,0xee86dcc8, 0x15ac0c20,0xc0eaf003,0xc2b6b5dd,0xedadd6c2,0x29bd0b8e,0x47273f08,0x3897483b,0xeb61145b, 0xe033d9e5,0x12a0f5c2,0xe17a1118,0xb94cbb1a,0xde2bc9fc,0x152df699,0x414e3128,0x45ba46de, 0x04253069,0xd9bce06f,0xfd5ce516,0x08141771,0xb8b4d45d,0xd18bbe7b,0xfff6e5b9,0x36c91e7e, 0x46554238,0x23714262,0xda53f334,0xeaebdbf7,0x19980542,0xca18fc04,0xc4f5b8f9,0xedabd8c0, 0x2705099f,0x42973a8d,0x3c2445f5,0xe51511a5,0xdfc1d814,0x0d8bf15a,0xeecb183c,0xbb7cc2d7, 0xdfa0cbd0,0x135af63c,0x3cf12e17,0x45214317,0xfdef30b4,0xd877db6d,0xf8b8e47a,0x12fa15a5, 0xbe75e1dd,0xd25fbfac,0xff73e6ba,0x33661c7d,0x43fb3ea0,0x1fdb41e9,0xd60bec1a,0xe9d6daa6, 0x1c0d0188,0xd6490a13,0xc4b9bcd2,0xee89d8c4,0x244108e5,0x400f3735,0x3a2844b2,0xdea40bff, 0xde1ed401,0x0b80f01c,0xfe6d1f0c,0xbd7eccfb,0xdf8fca2e,0x11d0f70b,0x39f52a5f,0x43b84165, 0xf89d2d13,0xd469d61a,0xf79ae2b3,0x1d9f1561,0xc683f184,0xd033bfd2,0xffcce70e,0x2f171993, 0x425f3bf6,0x1bd03f26,0xd1bae876,0xe863d6c8,0x1db50036,0xe4f917d3,0xc374c2d0,0xef15d70f, 0x200c0832,0x3d6532cd,0x35914229,0xdcb508f3,0xdae3d08b,0x098eeeff,0x0e732360,0xc175da12, 0xdeabc86f,0x0fcff746,0x35a1257e,0x3f303e64,0xf7582714,0xd1e3d543,0xf64fe051,0x258c132c, 0xd18d02ae,0xcecec22a,0xff4de6a3,0x2a171675,0x3ea6379d,0x15c537af,0xd19ee90e,0xe68dd534, 0x1c6cfe3b,0xf6072385,0xc4e2cbbb,0xeea3d63e,0x1c2b06d0,0x39052dad,0x2b323cbe,0xdee604da, 0xd9d1d130,0x06cced38,0x1d1a2431,0xc896ea26,0xde29c98e,0x0d79f68a,0x302820fd,0x368c39db, 0xf6db1bb2,0xd330d8c8,0xf433df23,0x28fb0fff,0xe04c1340,0xcfbfc7ef,0xfe10e62b,0x24d9131e, 0x38e931ef,0x0c982b25,0xd622ec7b,0xe4e0d69e,0x1979fbb4,0x07ce29b1,0xc97cd8dc,0xee14d6be, 0x17f104b8,0x337c27df,0x1c5133eb,0xe5320058,0xda94d615,0x0440eb17,0x264f2253,0xd3a9fc6f, 0xddf4ccb9,0x0a47f586,0x2aa81c47,0x29673402,0xf7300dae,0xd764e065,0xf22fdece,0x29540e3c, 0xf2021fb7,0xd10cd071,0xfbece501,0x206b0f20,0x31092dd4,0x02131aa5,0xdd93f03a,0xe3ccd8f4, 0x1971fa9a,0x170f2d47,0xcf05e8dc,0xeb75d604,0x13d00131,0x308324d1,0x0b5f282d,0xeafcfa0f, 0xdacbdbd0,0x04aeea2a,0x2d5624b5,0xe12e0d59,0xdb42cf57,0x05f7f0fe,0x29c61897,0x19e32f9b, 0xf4ecff2c,0xda50e732,0xf1fede03,0x2dff1085,0x036a2969,0xd151db46,0xf5fce05b,0x1dcb0abb, 0x27f62df5,0xf77f09e3,0xe40ff1fc,0xe349d996,0x1d6bfb47,0x224b3331,0xd779fa05,0xe532d494, 0x0f96fb16,0x2dd4239f,0xfc8019c9,0xf05df412,0xdae3e0f6,0x0653ea42,0x333a2983,0xf1d31968, 0xd888d5e3,0x0052ea2f,0x288214ea,0x09262633,0xf3dff413,0xde8deece,0xf28ede97,0x32621304, 0x10522e9a,0xd641eb4f,0xef86dcd7,0x1b050578,0x17ae28b6,0xf0ccfae7,0xeca7f569,0xe40cdde0, 0x2007fc5f,0x270b365f,0xe6a7083c,0xe162d81e,0x0aebf4e1,0x2123203a,0xf1c006bd,0xf71ff1ad, 0xdf1eea6b,0x07a9ead2,0x35392b56,0x01a81eae,0xdaf7e3e2,0xfa1ae5ff,0x20bd10ee,0xf8611292, 0xf52fedfe,0xe8d5f823,0xf2f5e1f2,0x3340139b,0x17302fec,0xe2e1fc98,0xea96de3c,0x15deff97, 0x01971975,0xeeb6ef48,0xf874f9c4,0xe652e817,0x1f1cfc37,0x283c36bb,0xf8f3116c,0xe1a0e330, 0x0558ef56,0x0b10162d,0xeb96f359,0xfe4af29f,0xe848f849,0x05f8ec4c,0x356f2930,0x0d892033, 0xe43af68a,0xf46fe53a,0x0ee609bf,0xea9bfa12,0xf86eec44,0xf7b30239,0xf35ee9cc,0x30a90fd6, 0x19a13008,0xf4f50b48,0xe920e5d2,0x0995f98c,0xebc6008d,0xf035e759,0x0566ff10,0xecdcf6e3, 0x199bfab8,0x285d343d,0x0a13158d,0xe805f3ee,0xfd35ed28,0xef82020c,0xe861e301,0x05eef66a, 0xf6540797,0x0213f0f8,0x3377229e,0x140320b9,0xf38e092f,0xf103ea8d,0xf390fc84,0xdfa9e105, 0xfe0becab,0x088e0ca9,0xf553f66a,0x29be09c1,0x1ad62f29,0x083a143a,0xed0af3e4,0xf4c0f38f, 0xd7e8e25f,0xf37ee0a2,0x129c068a,0xf6fa084d,0x11f5f9be,0x28d62e11,0x1517177b,0xf4880754, 0xf214ef45,0xd3a0e633,0xe545d436,0x0f5dfc26,0x06f616ec,0xfecaf7bd,0x2f261a5a,0x168f2216, 0x06ad15e2,0xf039f50a,0xd4dde9bf,0xd535ca27,0x05e8ed1b,0x18f217a8,0xf8fe04b1,0x2223050c, 0x1c692ce9,0x169f1747,0xf53505fd,0xdaa4ed37,0xc646c5b3,0xf74eda85,0x1e640ff7,0x020d1867, 0x0ca1fb6f,0x27fd2810,0x18f018cb,0x04bf1793,0xe353f422,0xbb9dc891,0xe38cc79c,0x195802d2, 0x158522ba,0xff6a002f,0x2ac21512,0x174621ed,0x18361b92,0xef4802b1,0xb889d27b,0xcdccb74b, 0x0e98ef29,0x244a20fb,0x00151157,0x1d5304d6,0x1c6029a3,0x1f4117a3,0xff4a1771,0xbe8ae39b, 0xb8a5adb7,0xfc3fd7eb,0x26471959,0x0d7b233b,0x0b9601c6,0x255b23c5,0x1a231858,0x14d322e0, 0xd0a9f85d,0xa8e2ace0,0xe4a7bf47,0x21d009d3,0x20532944,0x04ca0b2d,0x26c71369,0x16961f6b, 0x24cd1ea0,0xeac61031,0xa0e5ba55,0xca33a9c7,0x1676f2fa,0x2a4c2782,0x0a9b1cd8,0x1b350925, 0x19ab258e,0x239817b6,0x07b3247b,0xa65ed5e5,0xaff99b26,0x01ecd812,0x2ae22083,0x19fa29c4, 0x0f2c0b7a,0x20c520f9,0x1b1d15fd,0x21a5276a,0xbdb2f867,0x9b14986a,0xe7a7bad1,0x273d0fd4, 0x28662c8e,0x0dea1859,0x22f61657,0x15571a88,0x29ac1ef0,0xe1fb1a1f,0x9116a7fd,0xc93ea072, 0x1ae7f773,0x2d0b2afd,0x1817272e,0x1cfc122a,0x155d210c,0x21d416cd,0x0aef29b9,0x9867c887, 0xab078ff3,0x057cd9a4,0x2c912267,0x26cb2d34,0x17c41939,0x1cb92181,0x186b1295,0x24df23c1, 0xb1abf40c,0x94e68fa5,0xe9cbb9bf,0x26d8104f,0x2e1b2d02,0x1b922742,0x23601d99,0x11a517df, 0x243d1913,0xd9c717f7,0x8d6ba0da,0xca5d9f7a,0x17eff790,0x2db8293f,0x28343023,0x22cf1e9a, 0x139822e2,0x18e61121,0x030b20d5,0x96c6c1eb,0xade39179,0x0211da3c,0x2ac21d60,0x32c32fe5, 0x21d82934,0x2051271a,0x10011014,0x16a217b2,0xb005ea79,0x9ad79319,0xe78fbd69,0x21940a00, 0x33a92c9e,0x29e9352d,0x29f0257e,0x0cdd1c13,0x13ae0dfb,0xd3f8058f,0x9573a4a7,0xcbdda73d, 0x1096f20c,0x2fd22510,0x36d03829,0x29ef2a6a,0x16d32a57,0x0ad8091a,0xf1780a7d,0x9f69c2b9, 0xb4369c94,0xfa9cd855,0x287a1665,0x3c773482,0x2ba43750,0x27dc2e85,0x046210d5,0xfbfb055b, 0xb6fcdf43,0xa6039ff3,0xe2e2c097,0x1b5d0254,0x3a012cb8,0x36cd3ff7,0x318c2e99,0x09b422eb, 0xfb8dfec0,0xd158eb7e,0xa4d0b09b,0xcc2eafaf,0x0986ec25,0x32391fd2,0x42363f83,0x32e73659, 0x1bcf31aa,0xf74a018c,0xdd45ed3f,0xaf9dc7e0,0xb935ab35,0xf4e0d6e5,0x24b60fd5,0x448e3892, 0x3732432a,0x2e7136ce,0xf8e21298,0xdd89ec0a,0xc317d379,0xb142b262,0xe0cfc2e5,0x1548fd44, 0x3f0b2aba,0x438c48d1,0x38993960,0x081a27ba,0xdcb4eec9,0xce7fd09b,0xb5f2c2d7,0xccafb72a, 0x04ccea56,0x31ad1aac,0x4c54452b,0x3bcc4418,0x1de3372e,0xe12dfd0c,0xc900cc52,0xc4f2ce4f, 0xbdc0b8c0,0xf37ad682,0x20d70b50,0x4ae338f0,0x44b94f58,0x31e23d4a,0xf04b1225,0xbf29cfef, 0xd1acc775,0xbb64c69b,0xe06ac54a,0x117ffbaf,0x400a27f2,0x51c15076,0x3ce144e6,0x053f28d6, 0xbe33dfe1,0xcb6db806,0xc6f4d5cb,0xcdc4bed5,0x02dee9fe,0x2f8f1830,0x560446f3,0x446d52d4, 0x1d0e39a8,0xcc03f61b,0xb7b4b02a,0xd854d2d8,0xc376c6e4,0xf29ad6f4,0x1f9109c5,0x4df63742, 0x520e5aee,0x332e434a,0xe3170f1b,0xa896b7ee,0xdac6bd40,0xc761d8e7,0xe029c95b,0x1110fa53, 0x3efb274d,0x5df3551c,0x41284fe0,0xfe1f2988,0xa7f7cc92,0xc672a805,0xd85ce114,0xd058c8e3, 0x01ece8c4,0x2f3d18c1,0x5ba146d3,0x4d4c5e49,0x1c6b3d50,0xb5dee8c5,0xad309f1a,0xe51ed0ae, 0xcbabd78e,0xf0e2d7e1,0x20af09e8,0x4e8f3781,0x5c74604a,0x36b24ae2,0xcfa00a92,0x9dc5a3b5, 0xda0cb5dd,0xd711e73a,0xdf82cfba,0x123ef917,0x3ff5290d,0x62825560,0x481a59cf,0xf2e62bb0, 0x995cb66a,0xbfe3a229,0xe808e1c8,0xd4c4d744,0x01b3e740,0x31fa1ae5,0x5a8f47db,0x573062e0, 0x1a534368,0xa239d6d2,0xa9c596df,0xe7eec9e4,0xd84ee7ff,0xef78da8a,0x24040ab0,0x4e533adf, 0x62525e3a,0x3aa8543f,0xbaf501be,0x99f59612,0xd36cb2b2,0xe766eca2,0xe12dda3b,0x140df858, 0x42a72d71,0x610a5331,0x4fe860f8,0xe4002b86,0x918aa49b,0xbc08a02d,0xefbbdc4b,0xdd40e690, 0x01d1e8f3,0x36641dda,0x572448a8,0x5e536329,0x14a448a1,0x9662c60d,0xa819926b,0xe406c56f, 0xe600f133,0xf1d3e1c5,0x27c50bda,0x4d2f3dfb,0x63e55ae3,0x3c225a1e,0xad29f732,0x96e68f93, 0xce79b106,0xf196ea13,0xe812e661,0x1669fb6d,0x43fe30f3,0x5e5a5112,0x53f762b0,0xd77227fe, 0x8e209bf7,0xba489e05,0xee9fd699,0xe858f1b5,0x0576efdf,0x38a320f6,0x54e548e2,0x5fe860d2, 0x0bcb4a14,0x91e7bae1,0xa6dc9096,0xdda5c331,0xf22ff278,0xf87eec41,0x2a790fcc,0x4d213ed2, 0x61d758b4,0x395d5bf7,0xa514eae8,0x96388d16,0xcb70b042,0xf640e419,0xf1f3f36a,0x19f6016d, 0x43f5322c,0x5c2850f6,0x558361b5,0xcb21200f,0x8c679647,0xb96e9e12,0xea98d314,0xf5bff9f8, 0x0a83f8d7,0x383e231a,0x54904859,0x60c15ed8,0x0052493b,0x8d16b0f5,0xa6e68f95,0xda46c240, 0xfd6cf15e,0x005df95c,0x2aaf1380,0x4c223d4c,0x60b05804,0x346e5dd5,0x9d7edf5d,0x95f988db, 0xca9daffb,0xf824e12b,0xfe1e00ba,0x1bda083f,0x41a730e8,0x5b134fb0,0x55f361cc,0xc1d017ee, 0x8994901d,0xb9119e4c,0xe7f8d224,0x0441fea3,0x102c03bf,0x3626232b,0x534a4584,0x61695d95, 0xf7c04657,0x8889a9c9,0xa76a8e80,0xd8afc1bf,0x04e8eedd,0x0a03082e,0x296917a5,0x494e3a84, 0x5fa356bc,0x2ef65d3c,0x97e3d845,0x960d868e,0xc982b093,0xf61ede86,0x0c840b21,0x1e3f108e, 0x3e3c2ea1,0x59ce4d45,0x52d360b4,0xbc691286,0x89248c63,0xb92b9ed4,0xe426d032,0x1135fe0f, 0x16d7113e,0x32db23e8,0x512a41db,0x5ee05c84,0xf4714195,0x86fda5e4,0xa7df8ed1,0xd5efc0de, 0x06c1ea30,0x163416f1,0x28a81c7e,0x45b3366e,0x5e5254bb,0x2aff5801,0x95b0d769,0x966f8690, 0xc7a2b091,0xf162dafb,0x1c510fbf,0x216e1b16,0x39fa2c8e,0x58014989,0x4b675d89,0xbd891144, 0x89bd8bd1,0xb88d9f2b,0xdff6cd7b,0x187bfa13,0x1f9b2161,0x2fdb2596,0x4d313dbc,0x58595a88, 0xf6683a3c,0x8746a873,0xa8388f6d,0xd286bfad,0x03f8e5d7,0x260420b6,0x28ca238c,0x417832fe, 0x5ad050d6,0x264c4e75,0x98ecdc41,0x96c1869f,0xc5e9b0d3,0xed64d75d,0x285b0e8a,0x269629e3, 0x362e2b0e,0x54364518,0x41555730,0xc49210fc,0x88a88e8c,0xb87b9ed3,0xdd05cb7f,0x195ff6c8, 0x2c942f0c,0x2cc4286c,0x48db3970,0x4f5755f9,0xfb2e32da,0x8846b08b,0xa6bd8c9e,0xd111bf29, 0x01a9e467,0x341d23fd,0x291c2dd1,0x3cde2e7d,0x545d4c9d,0x240844a4,0xa091e588,0x91e3852f, 0xc546adfc,0xedc9d77e,0x2d9e0d64,0x2dbc36ff,0x30c42938,0x4f39408e,0x391f4e8f,0xd0bc14c1, 0x84b39489,0xb48c97ec,0xdf6dcb7f,0x1923f8ac,0x37b93561,0x29922ce0,0x441633d1,0x45644f11, 0x04682e39,0x8c28bda8,0x9e4a8664,0xd27fbada,0x041fe8db,0x3ab9241a,0x2bf236fb,0x37482ace, 0x4b184680,0x24143af2,0xad3cf2ad,0x89dc86f1,0xc178a4d0,0xf321da8f,0x2dad0f48,0x35a73dd4, 0x2ced2b81,0x46ae3a62,0x316a4398,0xe02e19ad,0x844ea002,0xab828eba,0xe371c8da,0x19b5fd77, 0x3f5c35ae,0x2bc63454,0x3c5f2f51,0x3a3743cd,0x0dde29d0,0x95d4ce24,0x94a583d9,0xd11fb28d, 0x0779ec98,0x3c56234d,0x33413fdc,0x31432c7a,0x3dbd3ca9,0x23a83130,0xbd890039,0x85608e44, 0xba319b40,0xf59fda01,0x2c2c1132,0x3f7641fc,0x2cf33285,0x3a8c3278,0x2a203575,0xf0f61db3, 0x8923aed5,0xa24d88aa,0xe2efc2a8,0x1aadfea0,0x468e349b,0x31ea3e4a,0x32c32cb6,0x2cd7356f, 0x16bb2571,0xa28be075,0x8d5e865d,0xcbcaa9cb,0x0801eb6e,0x3ce523cf,0x3cc0498b,0x2bf930bd, 0x2dbc315f,0x229b25d0,0xcf8d0d98,0x85ad993a,0xb1d5932f,0xf39ad4f6,0x2c9511e4,0x4ab544d6, 0x2e6f3b07,0x2d272b2e,0x2162253e,0x016a2073,0x92cebfea,0x99e586d0,0xdd79ba52,0x1bdafc20, 0x4bb3353c,0x38814a7a,0x29d82b8b,0x1e1325fd,0x1d381f84,0xb314f283,0x89d28e7a,0xc2e3a13b, 0x0583e54d,0x3dd7255a,0x492f50e5,0x293b349a,0x1d6d2676,0x1f761963,0xe2b81723,0x8bc9a917, 0xa8e48ea5,0xed26cb2a,0x2e390f8d,0x5469460b,0x30174664,0x201a2778,0x174f1594,0x0d931fe8, 0xa0ead3ea,0x94c38b1b,0xd324b0c1,0x1990f5c0,0x4d6a3691,0x41c7564a,0x24842c80,0x0fbb178a, 0x1f3117ae,0xc69c0166,0x8cbf9a1c,0xb8cc9b82,0xff40db29,0x3e6e2310,0x561d53c8,0x2a053c37, 0x0e931e9d,0x1a100c6b,0xf3f71bf4,0x9550ba79,0xa2989035,0xe3a5c0ed,0x2bf2093f,0x58fc45c1, 0x3724539c,0x15ac26ef,0x0c1c06dd,0x15a31d49,0xafaee620,0x94a99309,0xc90fa9f9,0x1352ecd6, 0x4c813446,0x4f4d5ca0,0x213832f2,0x01aa0b35,0x1f8e0efc,0xd8700c68,0x92eda6f3,0xb18899a6, 0xf6bbd152,0x3c091d45,0x5e57529f,0x2e8c4a1e,0x01501832,0x1450ffe2,0x00dd1f1c,0xa0aecb8f, 0x9f1d9437,0xda0db927,0x26fa0131,0x57fe431e,0x44985e06,0x0cd52859,0x01def9d8,0x1adc1a61, 0xc023f402,0x96699ca5,0xc0dba522,0x0c08e39b,0x49783039,0x5bd75c66,0x1f4c3e9a,0xf5f0011f, 0x1f03073c,0xe70012c6,0x9a58b67f,0xab9f9972,0xee26c8e7,0x38b516e5,0x5f804f23,0x37625826, 0xf7391379,0x0ed2f5e7,0x07eb2042,0xaea1dad4,0x9d5d9977,0xd1bbb264,0x2158f976,0x54194049, 0x53466110,0x063c2de0,0xf97cf0a0,0x1d1616d3,0xcfeffc04,0x99e6a86f,0xb977a1fc,0x04f0dbaf, 0x46e72b18,0x61305837,0x217b4cf1,0xede1f9c4,0x1d130010,0xf09a15d4,0xa3efc638,0xa70e9b74, 0xe6a2c139,0x34171006,0x5b7c4c78,0x443a6008,0xf01d12d6,0x089deecd,0x0c071fa0,0xbd86e653, 0x9dc4a120,0xca19aca8,0x1a85f20b,0x51003c34,0x5d405e1a,0x03db3840,0xf2f5ea54,0x1d9b117e, 0xdcf30192,0x9fb4b5e9,0xb335a0a7,0xfd64d41f,0x43352466,0x601b54c8,0x291f57f1,0xe85ef6d8, 0x18aef9c6,0xf7c11795,0xaf89d403,0xa4589f42,0xdef0bb0a,0x2d800860,0x582a4912,0x4f256118, 0xed57184a,0x0258e99e,0x0f301c7c,0xcb4beef4,0x9fa7aa67,0xc41aa941,0x12c6ea1a,0x4e0a35a2, 0x604f5b3e,0x07eb4291,0xed7be7ae,0x1c450b54,0xe6dc062c,0xa67fc2d8,0xaf96a118,0xf530ce0e, 0x3cd31c5b,0x5dce5250,0x32e35cdc,0xe55bf9fb,0x1333f388,0xfd9d1884,0xbaebdeeb,0xa3dea3e5, 0xd877b738,0x250dffdd,0x55dd4341,0x56035f82,0xef8b21a0,0xfb5ee5ba,0x123d18ac,0xd6c5f5b9, 0xa2c3b3e6,0xbfd2a81c,0x09eae303,0x48f32d07,0x5fe158a1,0x10b04b6a,0xe87ce8c6,0x1adc044c, 0xee440a75,0xae2bce6e,0xadb8a333,0xed7fc90c,0x347b134d,0x5ab04db8,0x3d695e2a,0xe54d01d8, 0x0d2bed9f,0x020e1957,0xc636e701,0xa52caa03,0xd2adb46a,0x1c12f7c0,0x516a3b6c,0x59705c26, 0xf6442d39,0xf4fbe4ab,0x14561467,0xdfc8f9db,0xa798be84,0xbbf9a880,0x0196dc8f,0x4198244f, 0x5cbd542f,0x1cbe5117,0xe686ee5a,0x187bfded,0xf26e0cc5,0xb7cfd874,0xad00a6ea,0xe679c446, 0x2c000ae6,0x565346c0,0x45635bb2,0xe9d20de0,0x073beab2,0x03fd1874,0xd0faebd3,0xa7dbb28b, 0xcd2db29e,0x13aff032,0x4ae132f4,0x582157e7,0x01e13785,0xf10be815,0x14410f53,0xe5affb4f, 0xaefcc99e,0xb94eaa3d,0xf9a4d66d,0x39081bf5,0x588e4e37,0x29145194,0xe8a6f90f,0x148af935, 0xf3a80cc0,0xc2dedf91,0xadecad1a,0xdfcec0cf,0x23b302d6,0x51003e51,0x482f57ae,0xf3051b6e, 0x0249eb5f,0x03aa159b,0xd961ed69,0xaca3bd29,0xc8adb2a2,0x0bc3e936,0x431a2b01,0x54965353, 0x0f6b3c9e,0xf04bef2f,0x124a0ab3,0xe860fb09,0xb88dd36c,0xb7d0ad54,0xf28ad0a0,0x32161473, 0x54e447af,0x2ff04ec3,0xed3d0552,0x1084f74c,0xf4330bd4,0xcdffe428,0xaee1b4d6,0xd8babcec, 0x1d28fbae,0x4c2a3902,0x462754eb,0xfd0d2364,0xff89ed72,0x043f1266,0xe087ef47,0xb1eec901, 0xc1ffb0e0,0x04b1e12d,0x3f99260b,0x525f5034,0x17ed3b83,0xf060f68c,0x10550760,0xebb4fd16, 0xc421dd52,0xb30aafe0,0xea10c7b6,0x2ed90de4,0x52ee4595,0x30254cac,0xf23b0df5,0x0d09f61e, 0xf6de0b4f,0xda19e8fe,0xaea1bf3f,0xcecfb5af,0x176df362,0x4aa736f9,0x442e5346,0x05902542, 0xfdbbf0e2,0x04990f4c,0xe6dff19f,0xba7dd659,0xb99bae28,0xfd14d777,0x3dfa20fc,0x50924e73, 0x1b8239fe,0xf302fefa,0x0de20570,0xed6dfd50,0xd1b0e507,0xaeb7b611,0xe14cbf6e,0x2a0706fa, 0x508343b7,0x2f4d4ad6,0xfab61323,0x0b53f849,0xf6550956,0xe2feea67,0xb254cc0c,0xc73cb0c5, 0x10cdebb0,0x4838321d,0x42955072,0x0c5a2515,0xff7cf959,0x02b50df9,0xe886f05a,0xc5b2e029, 0xb4b9afc5,0xf61cd097,0x39051a41,0x4de84b74,0x1c1d388f,0xfb17077e,0x0cd306c9,0xebccfb35, 0xdc10e768,0xaef0bf4e,0xdadcbab5,0x230e003f,0x4d423ea6,0x2dc448a9,0x04e1150a,0x0c59ff77, 0xf3e8082c,0xe66be8c5,0xb9bed6a5,0xc28ab032,0x09fae570,0x43032ae3,0x40d14d49,0x10492369, 0x056e049e,0x00fe0eb6,0xe711ed9b,0xd054e4e2,0xb39fb5c4,0xefdfcbc5,0x3183131f,0x4b23462f, 0x1aba36fe,0x06910df0,0x0d220b91,0xe8aff89e,0xe252e648,0xb3d1c9da,0xd5d4b91b,0x1b6bf9de, 0x481d36d9,0x2c4e4685,0x0dc914a9,0x10400a66,0xf04c07b7,0xe5e9e52d,0xc3fede8e,0xc068b41a, 0x0337e02a,0x3afa2297,0x3f764881,0x11b02224,0x0f7b0f95,0xff5b11ed,0xe2ebe8f2,0xd9c5e569, 0xb6c0bf7c,0xea4ec92c,0x28750bb7,0x46ea3de8,0x19e8366c,0x130e11c9,0x0f88149a,0xe309f569, 0xe45de1ab,0xbd08d480,0xd2e7bbca,0x1325f3de,0x3f772ce5,0x2c5d42f2,0x149614bb,0x182317b3, 0xeb6608e0,0xe127deb7,0xcfa1e296,0xc2f9bd31,0xfc84dcf5,0x2fce1946,0x3c913f67,0x134a22ac, 0x1c9c1957,0xfec5187f,0xdbdbe2a1,0xe042e12b,0xc017cc21,0xe694cbb6,0x1dd70405,0x3d92312e, 0x1af13442,0x1eff158b,0x14a820b6,0xdbe5f2d7,0xe199da35,0xcaaaddd9,0xd51fc560,0x0a38ef2e, 0x313c2099,0x2b0b39f1,0x1a9b168f,0x22f12498,0xe7160c70,0xd997d751,0xdbd1e272,0xcc5bcb67, 0xf687de42,0x21980eda,0x34a23055,0x162e2261,0x299a2112,0x00a0222b,0xd465dd30,0xe3aada0f, 0xce33da6d,0xe68bd429,0x11a4fc80,0x2eb7214f,0x1bda2e05,0x27b8196a,0x1d3a2dad,0xd5edf2fa, 0xdbf1d294,0xd9f8e4f8,0xdc06d2b2,0x00d5edb4,0x206512a5,0x26d92c61,0x1f0218b0,0x2ff72e14, 0xe5b81380,0xd1edd0f2,0xe60cdf4e,0xd850dada,0xf367e386,0x124c035b,0x29361f53,0x193f2044, 0x342c259a,0x05d32ec6,0xcd7cda91,0xe38fd30f,0xdd38e708,0xea43de89,0x043ff734,0x1e56111b, 0x1b9d2530,0x2c821ceb,0x287a3982,0xd1ecf674,0xd653cb67,0xe864e7f8,0xe4f5e0d7,0xf90aef93, 0x0f9203d7,0x20a91d6b,0x227d19f5,0x3c7533b4,0xe7b91cf1,0xcb39cb71,0xec3fdb4b,0xe562ea5b, 0xf2ddeafb,0x026cf941,0x1c520e4b,0x1b8a1c95,0x3afb28f6,0x0dc83b04,0xc703dae8,0xe150cd48, 0xece6f065,0xefb8ea79,0xf839f419,0x0dbe006b,0x1a2c1adc,0x2fee1fac,0x3421413e,0xd05cfd2a, 0xd169c4ea,0xf457e807,0xef68f003,0xf398f287,0xfe8ff62d,0x19480e04,0x254e1a3b,0x44c23740, 0xecc32824,0xc54bc84c,0xef29d74f,0xf394f804,0xf34af341,0xf38df1aa,0x0ee8fd98,0x1cbc1835, 0x3e802ba3,0x184b43fd,0xc2fbddc8,0xdec1c80b,0xfb86f650,0xf550f710,0xeea8f22d,0xfdf4f111, 0x1832102b,0x3244211d,0x3e0e44cb,0xd1290646,0xcd04c081,0xfd1ae76b,0xf99efed3,0xef7ff558, 0xef76eb24,0x119bffb7,0x26a31994,0x48e438fc,0xf3f632e7,0xc0dbc787,0xf0c5d404,0x0182033e, 0xf385fa8b,0xe7d3ebbd,0x0295ef3c,0x1c771322,0x3f892ca7,0x2360496e,0xc123e30e,0xdcafc3fb, 0x086afa41,0xf99b02f4,0xe785f045,0xf098e550,0x14e8061b,0x32b120b4,0x454c456d,0xd4c0110e, 0xc9acbe12,0x035de688,0x02b50c26,0xec23f70c,0xe3fce36d,0x09caf381,0x25dc173f,0x49cb388b, 0xfddc3c01,0xbe50c9b6,0xf112d17a,0x0df50b8d,0xf35700b9,0xdfe8e79c,0xf7b1e419,0x1a680d52, 0x3e292b5b,0x2df44b73,0xc245eba2,0xdad4c1ad,0x1226fbe1,0xfd480d8f,0xe319eeec,0xe5d5dd4f, 0x109afcb9,0x30bb1e67,0x492f4363,0xdbe41c6c,0xc7bfbe8e,0x0674e534,0x0afd166e,0xea2cf8c8, 0xdbf5def8,0x0206e942,0x22fd13c1,0x47b635c7,0x09544225,0xbe7bcfa4,0xf038cfed,0x17d1100f, 0xf3a30696,0xdb8fe575,0xee2ddc20,0x16fa070d,0x3a8b27c4,0x364c4a2a,0xc749f6c7,0xd98cc1c3, 0x17c3fb8b,0x00e7162c,0xe11eee4c,0xddf8d920,0x0b73f426,0x2c681a79,0x49853f1c,0xe667269a, 0xc7e8c2d2,0x06bde3ff,0x11df1ca7,0xe935fa94,0xd7ccdd61,0xfa87e17f,0x1e5a0f1b,0x434830d6, 0x14c144be,0xc217d926,0xeee5d01f,0x1e34111e,0xf43a0bab,0xda45e4ab,0xe699d7a8,0x123b0092, 0x353022a5,0x3b734659,0xcf6c029b,0xd97fc4cb,0x19cbfa17,0x046e1c73,0xe0b5ee5a,0xd8dfd7bb, 0x059becf4,0x273e1562,0x4735399e,0xf1bb2e1f,0xca46c96d,0x056de35d,0x17ec1fd9,0xe92ffcf0, 0xd5d2dd2c,0xf3dedbb0,0x192b0962,0x3e172bde,0x1df844a6,0xc735e349,0xedacd18c,0x22a51061, 0xf5c01169,0xda01e4a8,0xe045d4ca,0x0c6cfa5a,0x30541dae,0x3dca422d,0xd8220ca6,0xd9cec864, 0x19d9f8af,0x09b72211,0xe0afef28,0xd501d75c,0xffa5e668,0x223f0fa5,0x44c834e1,0xfbf33281, 0xcc2fd0c6,0x042be2ff,0x1e8f2097,0xe94b0172,0xd563dd61,0xed63d6ed,0x136603be,0x3a092624, 0x23b1443a,0xcd28ed7c,0xed74d1f6,0x24080ee4,0xf91118c3,0xdad3e457,0xdae3d43a,0x073bf444, 0x29b2170b,0x3eee3f9b,0xe24f1334,0xd9b5ccce,0x175ff8c3,0x1135247a,0xe073f120,0xd438d8e1, 0xfa59e0c7,0x19d90a65,0x43fe2e49,0x03423470,0xcf65dab4,0x036de36f,0x22861d1e,0xea3c086f, 0xd760dd78,0xe7f2d5ed,0x0ce1ff3d,0x34c81c4e,0x260244b2,0xd681f59c,0xee33d4de,0x20aa0c08, 0xff451e68,0xdb0ce4aa,0xd9c9d694,0x0290ef51,0x20050e79,0x3fe23c26,0xeb281603,0xdccfd596, 0x1263f860,0x18392290,0xe02cf699,0xd729d920,0xf5a2dfb0,0x0ff50423,0x41b62627,0x06eb358d, 0xd7d2e436,0x00d2e616,0x22a8172f,0xeeec1062,0xd82ddc72,0xe6b9d9b9,0x047bf9cd,0x2e1812bf, 0x276942cb,0xe0b9fa93,0xef5ddca2,0x1aec0776,0x07a82080,0xd9a0e845,0xde33d8d1,0xfb86ed5d, 0x17b804f7,0x3e2535d2,0xf1e31817,0xe30de028,0x0ccdf7c8,0x1c131d92,0xe2a1fed5,0xdb20d82c, 0xf22fe3aa,0x0708fbb3,0x3b181ea1,0x0a2b345a,0xe183ec9d,0xff0dea23,0x1efc115d,0xf68f15ea, 0xd84fde26,0xe8cbde71,0xfbf6f4ad,0x267b0b4d,0x27723c7d,0xe981ff2a,0xf13ee3e5,0x159c0548, 0x0ecc1f23,0xdaf2ef3b,0xe1d6d9a3,0xf574eca1,0x1188fda8,0x39ab2e28,0xf6f919cd,0xe6f5e73d, 0x0addf818,0x1e0519d0,0xe8e8075f,0xdb8ad8ea,0xeefbe4c7,0x012ff5b1,0x3499191b,0x0d01331b, 0xe55ff096,0xfea8eae4,0x1dce103d,0xffe71b76,0xd7f1e368,0xe749ddba,0xf64cf02a,0x21600651, 0x297538c6,0xeb3d01b2,0xeffde48d,0x159004f9,0x172c20e1,0xdebff85c,0xe04fd839,0xf07fe98f, 0x0c9ef7cf,0x3984299b,0xf83e1d79,0xe5cfe6f9,0x0b15f61b,0x22261a76,0xf0f310f1,0xda09db5c, 0xeb85e346,0xfab6f03b,0x30f71393,0x109035ab,0xe47bf0cd,0xfccae98a,0x1e4f10d1,0x091620f3, 0xd9d6ea48,0xe661dd2d,0xf00cecb3,0x1ad5ff30,0x2cf2363e,0xeb2c0489,0xef1de492,0x15bc03af, 0x1d1720af,0xe5040095,0xe0e1da58,0xecbbe93e,0x04d1f11c,0x37cb225c,0xfa6020b4,0xe764e75b, 0x0a79f59e,0x21771967,0xf88d1706,0xdc56e184,0xeb4ee48c,0xf41cec10,0x29ca0b2b,0x13353454, 0xe5f1f203,0xfc9cec2c,0x1bc91074,0x0faa209e,0xdfcaf1b1,0xe7f9df0a,0xebebec0a,0x124af8b2, 0x2c062f99,0xeb930630,0xf1f3e752,0x14e003c4,0x1e281d31,0xec6d07f0,0xe208df87,0xeb8eead0, 0xfe31ed46,0x31dd1a16,0xfa8e2066,0xeaf7e7c3,0x0a6af833,0x1dd91793,0x00b21a3d,0xe035e8ec, 0xec7de513,0xf04ceac7,0x21a10465,0x13362f9a,0xe6dcf0ec,0xfebaefec,0x19040fe1,0x15541dd1, 0xe6cefa93,0xe7bde142,0xeae2ecdc,0x0b73f4cd,0x28e0279e,0xe9a505a2,0xf5b0e87b,0x13f60559, 0x1d2819d8,0xf57d1002,0xe23de53f,0xec93e9a6,0xfaccecb6,0x2aa7137f,0xf84f1dd9,0xec6be4f5, 0x0bcefc42,0x1a9016c7,0x0a481bfa,0xe3aef0b5,0xeaf2e311,0xf0beeca0,0x1bfe0296,0x0ebe28af, 0xe3b4ec24,0x0383f2de,0x188b1196,0x19e21b7e,0xebdb036f,0xe42fe23a,0xedf3ec18,0x0c40f734, 0x1f8422ac,0xe31bfd13,0xfb87e72d,0x15f60ac7,0x1c711991,0xfb5015b8,0xe17de795,0xed80e61a, 0xffe4f151,0x23a21685,0xec5e0f1a,0xef90dfb2,0x10ee04fc,0x1a46186f,0x0ece1c61,0xe4d3f347, 0xe8f0e213,0xf715efb3,0x1e3f09ba,0xfb1e1bf0,0xe30fe0c7,0x0d41fafc,0x191414f1,0x1a061a96, 0xed34062a,0xe3d9e3ba,0xf310ec1f,0x12d3fe5e,0x0d402075,0xdc17e96c,0x063beb44,0x170b131b, 0x1add1929,0xfe531645,0xe330e952,0xef46e5d5,0x05e9f799,0x1bf0195b,0xdd90fbc6,0xf5aedd74, 0x165f0f3a,0x191117b3,0x11e21aad,0xe6fbf815,0xe840e2fc,0xfd36f303,0x1c270ca0,0xebbc11dc, 0xe29fd7e0,0x1529fffa,0x179d1792,0x1a431907,0xf31a0d72,0xe31be55a,0xf785eb63,0x11e3031d, 0x04bc1b49,0xd69bdf6b,0x08c7e9a4,0x17a5184f,0x1981178a,0x08a619fa,0xe3deeecc,0xef39e3c7, 0x08a8fc6e,0x173215d4,0xd6f6f69f,0xf1acd810,0x198a0f9e,0x1802177b,0x19521ada,0xeaf602f9, 0xe55de258,0x017df375,0x188a0db1,0xe8cc0fba,0xdbcad1d2,0x146cfa52,0x179019c8,0x1cc6193d, 0xfca11747,0xe123e789,0xf7fce817,0x122406c7,0x049f1945,0xcfb6dc98,0x02c0e1f8,0x1993176c, 0x1b1717fa,0x13581e67,0xe482f64f,0xebd8e105,0x0bf1fd2a,0x16c815ad,0xd35df6e0,0xea50d093, 0x190a09d3,0x18c518fd,0x1f0c1d33,0xf08d0dd4,0xe281e227,0x0308f06f,0x17fd1005,0xe8d71036, 0xd472cdab,0x0eebf38d,0x1824198e,0x1f521a05,0x075b1e58,0xe110eb9e,0xf5d3e560,0x129e0898, 0x05e7189a,0xcb52dccf,0xfc0ddb26,0x190f1224,0x1bcb178e,0x1c082149,0xe7ce0078,0xe931e185, 0x0ca5fbd8,0x168e145b,0xd3c8f95b,0xe3b8cc2c,0x13e702b8,0x17eb1802,0x22ab1dff,0xf9aa17e3, 0xe334e565,0x01eeedd0,0x15c50f2d,0xec5b110d,0xcffccdca,0x0753ec85,0x175914b3,0x2052197c, 0x11fa22d6,0xe449f364,0xf360e59f,0x11350790,0x082f1681,0xca8ce03b,0xf413d5dc,0x154d0a4c, 0x1bfb17ed,0x2155225d,0xedf20ab8,0xe897e3f6,0x0ca5f9e7,0x15be13b0,0xd5aafcca,0xdc8cc9a0, 0x0c6ff9c9,0x19ed1680,0x23d31eda,0x02b01e09,0xe3eae95b,0x0116ec54,0x16da116a,0xefc3129e, 0xca9eccf2,0xfde6e33f,0x18b00e8f,0x21941ced,0x19032476,0xe58bfa82,0xf12fe428,0x163a0882, 0x0c301a0f,0xc65be1ec,0xe9accd98,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, }; static const PROGMEM uint32_t sample_4_SawWave_SBRS296[1280] = { 0x00060000,0x00180010,0x002d001f,0x007b004d,0x00a60095,0x00d200bf,0x00f200e0,0x010d00ff, 0x013a011b,0x01800167,0x01b2019a,0x01bc01b9,0x01c601c8,0x01bf01c5,0x01fd01cf,0x021f020f, 0x021f0221,0x0206021e,0x01d401f3,0x01b801aa,0x01f801e7,0x01ff0206,0x01e401f7,0x01a401cb, 0x013d0176,0x018d014c,0x01d701b3,0x01e401de,0x01c001d5,0x0168019e,0x0141011f,0x01f001ab, 0x0248022a,0x0258025b,0x0215023e,0x016501ce,0x022201a1,0x02d80289,0x031902fd,0x02f2030b, 0x024002a0,0x01e001ac,0x02f9028a,0x0392035e,0x039603a8,0x02f20364,0x019a025d,0x02a501db, 0x03bb0339,0x042003fc,0x03bd03fe,0x0269032f,0x01b6016a,0x037902b9,0x0478041a,0x048304a8, 0x03640422,0x0134026b,0x02d2018f,0x049803c4,0x05470513,0x049f0518,0x026d03b5,0x015a00e4, 0x041602e0,0x05ba0518,0x05ba05fe,0x03ec051a,0x006f0256,0x02ed010d,0x05be046e,0x06c30672, 0x05aa0672,0x023d0435,0x00b0ffe9,0x04cd0302,0x074f0661,0x074607ad,0x04690639,0xff1a01e3, 0x0285ffe2,0x06bc04c7,0x088c07fc,0x06fc0825,0x022604ee,0xfffcff28,0x04f502ab,0x081306e0, 0x081a088b,0x04c906d9,0xfef301f6,0x02aaffe9,0x06f204fc,0x08940820,0x06de081d,0x01e204bf, 0xffdcfee4,0x04ff02a7,0x082106fa,0x080d088c,0x049306b2,0xfea5019e,0x0297ffb0,0x073a0519, 0x08f20892,0x069d084f,0x000b03e1,0xfdf1fc56,0x05be0214,0x0a8008bf,0x09f30aee,0x046107af, 0xfc40000c,0x0298fe3e,0x08c60616,0x0a310a20,0x069608f2,0xfefd0341,0xfdb7fb6d,0x06210247, 0x0ab00915,0x09870ad6,0x02cd06c8,0xf97ffda2,0x02bcfca4,0x0bd707ec,0x0ddc0de3,0x07cf0bce, 0xfb52024c,0xfa5cf626,0x09090226,0x10bd0e22,0x0d8d1077,0x00ea0816,0xf219f81e,0x020cf7de, 0x11860b09,0x13b9148c,0x08260f7a,0xf3fdfee0,0xf540ed46,0x0df9026c,0x194715f3,0x11781781, 0xfbfc07a7,0xe7e8eee3,0x038af2c3,0x1b5511e9,0x1b461e8b,0x061a12ca,0xe886f7d0,0xf066e1c1, 0x173a058f,0x249121e3,0x13781f00,0xf26a0361,0xdb59e122,0x0928eef4,0x29a61e15,0x22412ae5, 0xff2512ee,0xd8a4eb73,0xee72d4cf,0x26a50e61,0x315c3265,0x110924ad,0xe37df95c,0xcf08cfbb, 0x158aefa7,0x3b92309d,0x258c370f,0xf1f00d3d,0xc66bda4f,0xf2b5c9f2,0x3c151ed0,0x3c264527, 0x07c024ee,0xd0b1e91a,0xc6a6bda3,0x2a0af81b,0x4e224860,0x22333f6e,0xdf73006c,0xb579c705, 0xff8ac4de,0x553336d7,0x412e5651,0xf7d51dae,0xbdd2d523,0xc51bae8a,0x448208e3,0x5cb76161, 0x17264090,0xcb19ee11,0xa9abb5b5,0x129ec777,0x6a475068,0x3ea3601c,0xe78911b3,0xb208c569, 0xc9c0a86a,0x549216d1,0x61326d29,0x109a3e54,0xc40be622,0xa70db078,0x17fbca2d,0x6df055ee, 0x3db8615a,0xe48d0f68,0xaf0dc267,0xcb7ea634,0x58101a47,0x615b6f2f,0x0ddb3cbd,0xc0e9e2d9, 0xa543ad8d,0x1cdbccf7,0x70cf5aa8,0x3bf361bf,0xe0f60c66,0xabf8bf11,0xce6ba452,0x5cef1f55, 0x61db721e,0x0af03b1a,0xbda6df63,0xa379aa89,0x21abcfe8,0x734e5f2c,0x3a0361e5,0xdd5e0941, 0xa8debbc8,0xd1d6a2d0,0x61b82476,0x620474c0,0x07db3923,0xba67dbd5,0xa22ba781,0x2702d392, 0x761f6432,0x381e6237,0xd9d70645,0xa5ddb8a1,0xd501a165,0x660b2929,0x620b7700,0x04dc371f, 0xb76fd863,0xa127a483,0x2c2fd774,0x783e68b5,0x35c361ee,0xd6380300,0xa2ccb591,0xd90da086, 0x6aa02e65,0x61bf791f,0x018c34b0,0xb431d4aa,0xa010a193,0x30cddb02,0x7a1a6cd0,0x33816194, 0xd2da0002,0xa004b2be,0xddb3a056,0x6ee033c0,0x60c17aa4,0xfe3331e6,0xb1a6d139,0xa05f9f13, 0x35cadfca,0x7afa706c,0x30916043,0xcfbcfcc8,0x9dfeb095,0xe26ea122,0x71fb3843,0x5f477b27, 0xfb172eed,0xaf85ce31,0xa16d9d1f,0x3a99e4eb,0x7b5e73ad,0x2d625e88,0xcc9af97d,0x9bf2ae61, 0xe71aa217,0x74ac3c85,0x5d887b3a,0xf8132bf9,0xad96cb6d,0xa2969b3b,0x3dede908,0x7b3d7586, 0x2b325d16,0xca97f758,0x9a74acf5,0xea1da2e5,0x76183ecc,0x5d297b79,0xf7682b33,0xad30cad9, 0xa2149acc,0x3d7be87c,0x7b8e757a,0x2c015dc3,0xcb66f81a,0x9aefad67,0xe6e8a17d,0x74883c0d, 0x5e387b8f,0xf9002cdd,0xade3cc28,0xa0d89b54,0x3b0ce5ad,0x7bdf7426,0x2dd25ef0,0xccd4f9d5, 0x9b8dae34,0xe448a082,0x735239d5,0x5f3b7bbb,0xfa6d2e6e,0xae82cd63,0x9f729bb8,0x3855e260, 0x7bf772ab,0x2f82600f,0xce25fb66,0x9bf4aee7,0xe0d69ef6,0x71d136f0,0x60977bed,0xfc32305d, 0xaf67cefc,0x9e449c79,0x357fdf31,0x7c267113,0x31586143,0xcfaffd2c,0x9c8cafbc,0xddfb9ded, 0x7049345d,0x61887bf8,0xfdd03200,0xb027d05b,0x9d799d11,0x3323dc88,0x7c276fa6,0x32e86237, 0xd0f8fe9d,0x9d07b066,0xdabd9cca,0x6ea4318a,0x62b07c00,0xff9d33de,0xb11fd1ed,0x9c589db3, 0x301ad943,0x7bfa6dd1,0x34846327,0xd2560026,0x9d95b127,0xd7909bb5,0x6cdd2e92,0x63b77bf4, 0x01453599,0xb1ebd36e,0x9bcc9e43,0x2daed685,0x7c1f6c6c,0x36626454,0xd3f101fb,0x9e54b216, 0xd5029b34,0x6b602c26,0x64ae7bed,0x02f03747,0xb2d1d4ec,0x9af89ee9,0x2abfd36a,0x7bea6a91, 0x37f66530,0xd54e0391,0x9ed5b2e1,0xd1b89a2c,0x696528f3,0x65967ba8,0x048d38de,0xb3a4d66c, 0x9a359f93,0x27cbd065,0x7bb068b9,0x398d660e,0xd6e80544,0x9fc0b3f2,0xcf8499fd,0x67ff26d4, 0x665a7b8d,0x06083a48,0xb4b6d7d3,0x99f6a085,0x248acd74,0x7afe665a,0x3b5766ba,0xd8ed0743, 0xa0f7b55b,0xcb7c99a4,0x6499222f,0x671a7a6e,0x08983c7c,0xb65eda3a,0x99e2a1cf,0x2058c9f8, 0x79f66339,0x3d8d678a,0xdb7809d7,0xa267b73b,0xc7eb9996,0x614b1dee,0x67c1792a,0x0b1b3e82, 0xb829dcbe,0x99ada32d,0x1b75c5ed,0x78915f69,0x3fd66849,0xde240ca7,0xa3e0b938,0xc4b799d3, 0x5de019a9,0x687877eb,0x0dc740ad,0xba2edf52,0x99eea4ac,0x1725c2a0,0x771b5c06,0x41cd68cc, 0xe0c00f38,0xa558bb2f,0xc0f799f2,0x59f914c3,0x68e1761c,0x106f42af,0xbc24e1f5,0x9a42a618, 0x12ddbf90,0x75af5889,0x43cb6953,0xe35711d5,0xa6e9bd4e,0xbe089a7e,0x569e1090,0x695874a6, 0x1318449f,0xbe4ce49e,0x9ac3a7ae,0x0dfdbc3e,0x738d5476,0x45866960,0xe5e91462,0xa853bf4e, 0xbb129ae5,0x52e90c2c,0x699372dc,0x15a04671,0xc07ae73e,0x9b6ea93f,0x09e3b98a,0x71fe510a, 0x477869cb,0xe8ac1711,0xa9fec196,0xb84c9bb7,0x4f1707be,0x699b70d1,0x17f947f4,0xc275e9b1, 0x9c19aaa3,0x0629b74b,0x706e4e00,0x48b269e6,0xea8818e3,0xab10c31f,0xb5f59c45,0x4c7d0449, 0x6a066fbb,0x19f9496c,0xc438eba8,0x9cecabfe,0x018cb47f,0x6e844a40,0x4a726a12,0xed341b7d, 0xacc6c57b,0xb3349d4d,0x4876ff7d,0x6a006d79,0x1c8c4b0b,0xc69dee67,0x9e13adb8,0xfce3b1fb, 0x6c3e463e,0x4bec69fc,0xefd81dfa,0xae7cc7db,0xb0b29e78,0x445efabd,0x69ff6b38,0x1f3c4ca5, 0xc930f136,0x9f64af8d,0xf83fafa6,0x69cb422f,0x4d3d69b3,0xf26b2062,0xb02bca43,0xae729fbe, 0x402ef5fe,0x69b668a0,0x21c44e1d,0xcbcaf3f0,0xa0deb164,0xf3aaadb1,0x676f3e2c,0x4ec66994, 0xf5342302,0xb222ccf1,0xac9ba154,0x3c18f173,0x696c661b,0x24524f75,0xce6af6ac,0xa25bb338, 0xef0aabe7,0x64b439f9,0x4fe3690e,0xf7d72560,0xb3eccf7d,0xaafca2d7,0x37eeecef,0x68e46362, 0x26c6509e,0xd105f959,0xa3ecb516,0xea86aa69,0x61e535bc,0x51356892,0xfabc2802,0xb602d255, 0xa9b1a497,0x339fe873,0x683b606d,0x293051b7,0xd3b8fc0d,0xa592b70d,0xe614a933,0x5eee3170, 0x522967d4,0xfd592a4c,0xb7efd4fb,0xa89da642,0x2f69e41c,0x67765d82,0x2b6752a0,0xd634fe92, 0xa714b8c1,0xe1eea827,0x5c462d79,0x530f673a,0xff972c5f,0xb982d741,0xa7bca7b1,0x2beee04f, 0x66fc5b22,0x2d575383,0xd88500b6,0xa8bfba77,0xdd9ba768,0x59372935,0x5415668a,0x02702ec9, 0xbbafda2c,0xa726a9b8,0x26c9db60,0x65cd5768,0x301d547f,0xdbe2040b,0xaadfbd03,0xd914a709, 0x5574243d,0x54dd651f,0x0591314e,0xbe35dd78,0xa6e8abf3,0x217bd69c,0x643b534a,0x327d551d, 0xdf060715,0xacf2bf71,0xd447a6cb,0x51561ed5,0x5591638a,0x08da33e5,0xc0ece0f0,0xa6fdae3d, 0x1c1cd203,0x62744f0d,0x34e955a5,0xe27b0a4b,0xaf56c23a,0xcff9a73f,0x4cfc1983,0x55de6188, 0x0be8360d,0xc395e432,0xa76fb061,0x171cce19,0x608e4af6,0x371655f9,0xe5d10d61,0xb19ec500, 0xcbf1a7da,0x48c11444,0x56445f91,0x0f0a3852,0xc664e78a,0xa82bb2b4,0x11d2ca27,0x5e4f4696, 0x3916561c,0xe91e1062,0xb3e8c7cb,0xc8a2a8dd,0x449a0f6e,0x562d5d48,0x11d53a11,0xc932eab7, 0xa938b4f3,0x0c73c688,0x5bd7420f,0x3b0f5610,0xec801383,0xb63bcad2,0xc50fa9f6,0x3ffd09fe, 0x561c5ac0,0x15073c04,0xcc4cee2b,0xaa98b76e,0x072cc355,0x59143d6d,0x3c9d55b3,0xefb5164d, 0xb8a2cdc9,0xc21aab7c,0x3b6d04ce,0x55c35803,0x17e13d98,0xcf57f169,0xac14b9c1,0x0262c0ac, 0x56863933,0x3e445578,0xf303193f,0xbb0ed0ed,0xbf6ead1f,0x36c5ffad,0x553254fa,0x1a983ef3, 0xd242f47f,0xada8bbf1,0xfd41be23,0x53aa34a5,0x3fa654fa,0xf6101bf7,0xbd48d3e1,0xbd29aec4, 0x3290fae6,0x54bd5255,0x1d00402b,0xd4eff730,0xaf45be01,0xf8e1bc04,0x516730f5,0x40d754c9, 0xf8941e38,0xbf06d64b,0xbb4bb033,0x2f3cf6e3,0x548f5055,0x1f224151,0xd736f980,0xb0d1bfaf, 0xf47dba1f,0x4f072d3e,0x41e15466,0xfad9205a,0xc0c5d89d,0xb99fb1cb,0x2b95f299,0x54494df7, 0x2176427d,0xd9e0fc19,0xb292c1a4,0xf09bb8f2,0x4c9f29c4,0x42b753de,0xfd0c2249,0xc27adaf3, 0xb835b370,0x27a4ee2a,0x53bf4b55,0x239d436a,0xdc4afe7c,0xb435c367,0xec38b795,0x4a0f25e7, 0x43c35372,0xff8c2486,0xc45ddd87,0xb71cb52e,0x23c3e9ea,0x5306489d,0x2591442b,0xdebd00bd, 0xb5f6c537,0xe806b6b1,0x474c2203,0x448252a7,0x01e3268d,0xc637e000,0xb67cb6ed,0x2035e629, 0x5276461b,0x27994508,0xe1470317,0xb7d1c720,0xe407b629,0x44851e24,0x454a51f0,0x043f2893, 0xc808e275,0xb5f4b8a4,0x1c24e20f,0x5185431f,0x29a145ad,0xe3d80581,0xb9a5c91c,0xe02bb5e7, 0x419e1a39,0x45cc50ee,0x067f2a63,0xc9f9e4f7,0xb5e1ba7d,0x1842de46,0x50974041,0x2b8b464b, 0xe65907e1,0xbb5fcb0b,0xdcacb5f3,0x3ecc1684,0x464c4fde,0x088d2c0e,0xcbcee73e,0xb60abc3a, 0x1454dab9,0x4f4a3d38,0x2d04468b,0xe88309c9,0xbd1cccd8,0xd93bb640,0x3bd212a5,0x46b34ebe, 0x0ae32dca,0xcddce9ab,0xb69fbe0c,0x10dfd7c3,0x4e413a87,0x2eb14707,0xead60bfb,0xbee5cec9, 0xd5fab6da,0x38c10ead,0x46f74d59,0x0cdf2f46,0xcfafebde,0xb73dbfad,0x0cedd4a1,0x4cc2376d, 0x2fff471e,0xecd40dd7,0xc015d070,0xd476b750,0x36a30c5a,0x46964bf4,0x0e092fd4,0xd0d2ed2c, 0xb758c036,0x0c88d4d2,0x4bb5367d,0x2fc7466f,0xed440e1c,0xc01cd0d4,0xd4ebb734,0x360e0c4c, 0x46064b2d,0x0e322f9f,0xd105ed72,0xb73bc024,0x0c9ad564,0x4b16361a,0x2f9245ee,0xed790e39, 0xbff1d102,0xd54eb6f1,0x35b40c68,0x459a4a93,0x0e6d2f79,0xd15eedd3,0xb70dc01b,0x0c77d5bb, 0x4a24356a,0x2f2a4524,0xedaa0e3f,0xbfddd13b,0xd5c2b6da,0x35210c5d,0x450149c3,0x0e9c2f45, 0xd1a3ee15,0xb711c019,0x0cbad65f,0x49c3354c,0x2f2a44dd,0xee0b0e8d,0xbfdad19e,0xd645b6bf, 0x34cb0c75,0x4488492c,0x0ebb2f09,0xd1e6ee5b,0xb6d8bff3,0x0cdcd6d0,0x492a3511,0x2ea6444b, 0xedbf0e3d,0xbf47d13c,0xd6e8b656,0x35670d3b,0x44644969,0x0e152e89,0xd128ed96,0xb67abf26, 0x0dc4d79a,0x497e35c2,0x2e894467,0xeda10e23,0xbefbd125,0xd790b62d,0x35540d9b,0x43f248f6, 0x0e152e45,0xd150edb2,0xb640befa,0x0da1d7e9,0x48a53529,0x2e3f43bf,0xeddc0e39,0xbeeed16c, 0xd80cb64a,0x34d40d8d,0x4373483d,0x0e5a2e23,0xd1b1ee0f,0xb66bbefb,0x0d96d875,0x47e434a5, 0x2df0432a,0xee1d0e4e,0xbeedd1c0,0xd892b64c,0x34590d91,0x42cf4779,0x0e492dbe,0xd1e5ee26, 0xb664beec,0x0d83d8e1,0x4723342c,0x2db7429a,0xee680e7b,0xbeecd218,0xd8eab661,0x33c30d5f, 0x423646a8,0x0e892d87,0xd250ee90,0xb6adbf02,0x0d7dd96c,0x465833a0,0x2d5c41f0,0xeea30e8c, 0xbf02d27d,0xd996b6a4,0x33590d73,0x419a45ed,0x0e832d23,0xd292eeb3,0xb6c6bf01,0x0d62d9e4, 0x45a03329,0x2d21416d,0xeef60eb7,0xbf08d2d3,0xd9e4b6cd,0x32890d18,0x40d344e5,0x0e952cc2, 0xd2efeef4,0xb714bf0e,0x0d44da6e,0x44b93267,0x2caf40ad,0xef370ec2,0xbf25d335,0xda9cb728, 0x324e0d44,0x40614460,0x0eb92c7e,0xd358ef48,0xb767bf2c,0x0d44dafe,0x440b3208,0x2c764034, 0xef7c0ee7,0xbf2dd394,0xdb49b77b,0x31d20d48,0x3fba438f,0x0eb92c18,0xd380ef65,0xb792bf0d, 0x0d83db94,0x43ab31ff,0x2bf93fc1,0xef140e85,0xbea4d330,0xdbd7b745,0x32850e09,0x3fc943f5, 0x0e342bd2,0xd2deeeb5,0xb753be36,0x0e9cdc68,0x443d32ef,0x2bc43fef,0xee720e15,0xbdd3d29b, 0xdc80b726,0x33000ea4,0x3fb24410,0x0dd92b75,0xd267ee3b,0xb712bd97,0x0f06dcd9,0x443b3341, 0x2b5d3fb4,0xeddd0da1,0xbd14d201,0xdd12b6ed,0x33810f48,0x3fa44436,0x0d832b3f,0xd1f9edc6, 0xb70dbcfa,0x0f87dd6e,0x443c3398,0x2aec3f86,0xed500d2f,0xbc4fd17f,0xdda2b6b4,0x33ee0fd3, 0x3f87444f,0x0d322af0,0xd187ed54,0xb707bc64,0x1030de23,0x44673418,0x2abb3f7f,0xecf80cf4, 0xbbcfd11f,0xde1eb69a,0x345c1062,0x3f774475,0x0cd82aac,0xd113ecde,0xb6eebbb6,0x10d2dec5, 0x446d347c,0x2a4e3f4c,0xec640c75,0xbb29d09b,0xdeb9b69d,0x34ad10e7,0x3f4c4472,0x0c782a4f, 0xd09bec62,0xb6c8bb0e,0x1151df41,0x449734e0,0x2a2c3f55,0xec1d0c4b,0xbab3d059,0xdf84b6c8, 0x351c1191,0x3f0f447b,0x0bfb29e4,0xd00debce,0xb6bbba68,0x11bedfad,0x44a83538,0x29e63f31, 0xebb70bf5,0xba15cff4,0xe024b6d3,0x35a6123b,0x3f1344ad,0x0bb629aa,0xcfb5eb69,0xb6dfb9e6, 0x1242e05f,0x446f3589,0x29833efb,0xeb2e0b92,0xb978cf77,0xe09cb6bc,0x35ea12a9,0x3ede44a1, 0x0b512952,0xcf43eaf6,0xb701b943,0x12f2e11a,0x44a13618,0x294a3ef9,0xeadd0b48,0xb8e8cf19, 0xe132b6e0,0x36471324,0x3ed644be,0x0b182917,0xcee6ea9f,0xb704b8ba,0x136ce1a4,0x449f365b, 0x28e63ec4,0xea5f0ae6,0xb859ceab,0xe1cab6fd,0x369313a3,0x3ea044b6,0x0ab728bb,0xce7aea2e, 0xb711b81c,0x13dfe21d,0x44b536ba,0x28b83eb8,0xea0a0aa9,0xb7ddce4e,0xe28eb745,0x36fa143d, 0x3e6944b7,0x0a2a284a,0xcdd7e994,0xb715b761,0x145fe2a7,0x44ad370c,0x283e3e79,0xe94e0a16, 0xb714cd98,0xe385b76b,0x37d9154f,0x3e884535,0x09c92813,0xcd49e907,0xb772b6da,0x152ae388, 0x44e73799,0x281a3e70,0xe91709e3,0xb6c5cd64,0xe39eb78d,0x37881534,0x3e1644bd,0x09a127bf, 0xcd46e8f3,0xb7c3b69f,0x154fe3fc,0x448f377e,0x27c23e13,0xe8f309b0,0xb683cd3b,0xe452b7fd, 0x379f1594,0x3de4449c,0x09a127a0,0xcd48e8f4,0xb839b691,0x156ae46e,0x44183742,0x27623da0, 0xe8c1096d,0xb643cd1e,0xe462b82f,0x37461564,0x3d834424,0x098e2763,0xcd51e8fb,0xb8beb66b, 0x15a6e4fb,0x43dc373f,0x271c3d59,0xe8ab094a,0xb616ccf9,0xe526b8c0,0x378a15eb,0x3d38440e, 0x090726ed,0xccb8e860,0xb8d8b5e0,0x1625e576,0x43eb3797,0x26c23d2d,0xe82f08da,0xb59fcc80, 0xe561b8d6,0x37621600,0x3d0643c9,0x092426e3,0xcd01e8a3,0xb984b613,0x1601e5d9,0x434e3710, 0x26b73c9b,0xe8bd092b,0xb61ecd22,0xe5ceb9bd,0x36a515b5,0x3c6542ed,0x094e269c,0xcd7ce90f, 0xba1eb676,0x155fe5d9,0x4252361c,0x26773bee,0xe9250955,0xb67fcd9d,0xe5e7ba59,0x35e2154a, 0x3bbc4215,0x09702659,0xcde6e96c,0xbae8b6d4,0x1519e634,0x41673559,0x26203b38,0xe987096d, 0xb6edce0b,0xe63cbb36,0x34f514da,0x3afa410d,0x097525f6,0xce51e9c6,0xbb93b72f,0x14b3e668, 0x40ae34a8,0x25fc3ab4,0xea0109a0,0xb74bce85,0xe64ebbbe,0x34411473,0x3a704057,0x09af25d4, 0xced1ea38,0xbc5ab7a8,0x143de69a,0x3fa633b5,0x259439eb,0xea5209a7,0xb7e4cf01,0xe6a5bcb8, 0x3355140c,0x39ad3f4a,0x09b22571,0xcf4ceaa3,0xbd1db81b,0x13e7e6da,0x3ee93307,0x25753962, 0xeade09dd,0xb85bcf8e,0xe6d5bd5d,0x32b213b8,0x39293ea1,0x09d4254e,0xcf9ceaee,0xbd9fb871, 0x13afe6fb,0x3e7f329e,0x25543918,0xeaef09de,0xb86dcfa2,0xe6d9bd74,0x000013b8,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, }; static const PROGMEM AudioSynthWavetable::sample_data SawWave_samples[5] = { { (int16_t*)sample_0_SawWave_SAW0_48, // sample true, // LOOP 14, // LENGTH_BITS (1 << (32 - 14)) * WAVETABLE_CENTS_SHIFT(0) * 22050.0 / WAVETABLE_NOTE_TO_FREQUENCY(48) / AUDIO_SAMPLE_RATE_EXACT + 0.5, // PER_HERTZ_PHASE_INCREMENT ((uint32_t)15244 - 1) << (32 - 14), // MAX_PHASE ((uint32_t)15243 - 1) << (32 - 14), // LOOP_PHASE_END (((uint32_t)15243 - 1) << (32 - 14)) - (((uint32_t)5111 - 1) << (32 - 14)), // LOOP_PHASE_LENGTH uint16_t(UINT16_MAX * WAVETABLE_DECIBEL_SHIFT(0)), // INITIAL_ATTENUATION_SCALAR uint32_t(0.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // DELAY_COUNT uint32_t(1.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // ATTACK_COUNT uint32_t(0.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // HOLD_COUNT uint32_t(1760.31 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // DECAY_COUNT uint32_t(25.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // RELEASE_COUNT int32_t((1.0 - WAVETABLE_DECIBEL_SHIFT(-0.3)) * AudioSynthWavetable::UNITY_GAIN), // SUSTAIN_MULT uint32_t(0.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / (2 * AudioSynthWavetable::LFO_PERIOD)), // VIBRATO_DELAY uint32_t(8.2 * AudioSynthWavetable::LFO_PERIOD * (UINT32_MAX / AUDIO_SAMPLE_RATE_EXACT)), // VIBRATO_INCREMENT (WAVETABLE_CENTS_SHIFT(0) - 1.0) * 4, // VIBRATO_PITCH_COEFFICIENT_INITIAL (1.0 - WAVETABLE_CENTS_SHIFT(0)) * 4, // VIBRATO_COEFFICIENT_SECONDARY uint32_t(100.02 * AudioSynthWavetable::SAMPLES_PER_MSEC / (2 * AudioSynthWavetable::LFO_PERIOD)), // MODULATION_DELAY uint32_t(6.0 * AudioSynthWavetable::LFO_PERIOD * (UINT32_MAX / AUDIO_SAMPLE_RATE_EXACT)), // MODULATION_INCREMENT (WAVETABLE_CENTS_SHIFT(0) - 1.0) * 4, // MODULATION_PITCH_COEFFICIENT_INITIAL (1.0 - WAVETABLE_CENTS_SHIFT(0)) * 4, // MODULATION_PITCH_COEFFICIENT_SECOND int32_t(UINT16_MAX * (WAVETABLE_DECIBEL_SHIFT(0) - 1.0)) * 4, // MODULATION_AMPLITUDE_INITIAL_GAIN int32_t(UINT16_MAX * (1.0 - WAVETABLE_DECIBEL_SHIFT(0))) * 4, // MODULATION_AMPLITUDE_FINAL_GAIN }, { (int16_t*)sample_1_SawWave_SAW0_60, // sample true, // LOOP 14, // LENGTH_BITS (1 << (32 - 14)) * WAVETABLE_CENTS_SHIFT(0) * 22050.0 / WAVETABLE_NOTE_TO_FREQUENCY(60) / AUDIO_SAMPLE_RATE_EXACT + 0.5, // PER_HERTZ_PHASE_INCREMENT ((uint32_t)10312 - 1) << (32 - 14), // MAX_PHASE ((uint32_t)10311 - 1) << (32 - 14), // LOOP_PHASE_END (((uint32_t)10311 - 1) << (32 - 14)) - (((uint32_t)4408 - 1) << (32 - 14)), // LOOP_PHASE_LENGTH uint16_t(UINT16_MAX * WAVETABLE_DECIBEL_SHIFT(0)), // INITIAL_ATTENUATION_SCALAR uint32_t(0.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // DELAY_COUNT uint32_t(1.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // ATTACK_COUNT uint32_t(0.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // HOLD_COUNT uint32_t(1760.31 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // DECAY_COUNT uint32_t(25.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // RELEASE_COUNT int32_t((1.0 - WAVETABLE_DECIBEL_SHIFT(-0.3)) * AudioSynthWavetable::UNITY_GAIN), // SUSTAIN_MULT uint32_t(0.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / (2 * AudioSynthWavetable::LFO_PERIOD)), // VIBRATO_DELAY uint32_t(8.2 * AudioSynthWavetable::LFO_PERIOD * (UINT32_MAX / AUDIO_SAMPLE_RATE_EXACT)), // VIBRATO_INCREMENT (WAVETABLE_CENTS_SHIFT(0) - 1.0) * 4, // VIBRATO_PITCH_COEFFICIENT_INITIAL (1.0 - WAVETABLE_CENTS_SHIFT(0)) * 4, // VIBRATO_COEFFICIENT_SECONDARY uint32_t(100.02 * AudioSynthWavetable::SAMPLES_PER_MSEC / (2 * AudioSynthWavetable::LFO_PERIOD)), // MODULATION_DELAY uint32_t(6.0 * AudioSynthWavetable::LFO_PERIOD * (UINT32_MAX / AUDIO_SAMPLE_RATE_EXACT)), // MODULATION_INCREMENT (WAVETABLE_CENTS_SHIFT(0) - 1.0) * 4, // MODULATION_PITCH_COEFFICIENT_INITIAL (1.0 - WAVETABLE_CENTS_SHIFT(0)) * 4, // MODULATION_PITCH_COEFFICIENT_SECOND int32_t(UINT16_MAX * (WAVETABLE_DECIBEL_SHIFT(0) - 1.0)) * 4, // MODULATION_AMPLITUDE_INITIAL_GAIN int32_t(UINT16_MAX * (1.0 - WAVETABLE_DECIBEL_SHIFT(0))) * 4, // MODULATION_AMPLITUDE_FINAL_GAIN }, { (int16_t*)sample_2_SawWave_SAW0_72, // sample true, // LOOP 14, // LENGTH_BITS (1 << (32 - 14)) * WAVETABLE_CENTS_SHIFT(0) * 22050.0 / WAVETABLE_NOTE_TO_FREQUENCY(72) / AUDIO_SAMPLE_RATE_EXACT + 0.5, // PER_HERTZ_PHASE_INCREMENT ((uint32_t)10020 - 1) << (32 - 14), // MAX_PHASE ((uint32_t)10019 - 1) << (32 - 14), // LOOP_PHASE_END (((uint32_t)10019 - 1) << (32 - 14)) - (((uint32_t)3892 - 1) << (32 - 14)), // LOOP_PHASE_LENGTH uint16_t(UINT16_MAX * WAVETABLE_DECIBEL_SHIFT(0)), // INITIAL_ATTENUATION_SCALAR uint32_t(0.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // DELAY_COUNT uint32_t(1.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // ATTACK_COUNT uint32_t(0.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // HOLD_COUNT uint32_t(1760.31 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // DECAY_COUNT uint32_t(25.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // RELEASE_COUNT int32_t((1.0 - WAVETABLE_DECIBEL_SHIFT(-0.3)) * AudioSynthWavetable::UNITY_GAIN), // SUSTAIN_MULT uint32_t(0.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / (2 * AudioSynthWavetable::LFO_PERIOD)), // VIBRATO_DELAY uint32_t(8.2 * AudioSynthWavetable::LFO_PERIOD * (UINT32_MAX / AUDIO_SAMPLE_RATE_EXACT)), // VIBRATO_INCREMENT (WAVETABLE_CENTS_SHIFT(0) - 1.0) * 4, // VIBRATO_PITCH_COEFFICIENT_INITIAL (1.0 - WAVETABLE_CENTS_SHIFT(0)) * 4, // VIBRATO_COEFFICIENT_SECONDARY uint32_t(100.02 * AudioSynthWavetable::SAMPLES_PER_MSEC / (2 * AudioSynthWavetable::LFO_PERIOD)), // MODULATION_DELAY uint32_t(6.0 * AudioSynthWavetable::LFO_PERIOD * (UINT32_MAX / AUDIO_SAMPLE_RATE_EXACT)), // MODULATION_INCREMENT (WAVETABLE_CENTS_SHIFT(0) - 1.0) * 4, // MODULATION_PITCH_COEFFICIENT_INITIAL (1.0 - WAVETABLE_CENTS_SHIFT(0)) * 4, // MODULATION_PITCH_COEFFICIENT_SECOND int32_t(UINT16_MAX * (WAVETABLE_DECIBEL_SHIFT(0) - 1.0)) * 4, // MODULATION_AMPLITUDE_INITIAL_GAIN int32_t(UINT16_MAX * (1.0 - WAVETABLE_DECIBEL_SHIFT(0))) * 4, // MODULATION_AMPLITUDE_FINAL_GAIN }, { (int16_t*)sample_3_SawWave_SSTR186A, // sample true, // LOOP 14, // LENGTH_BITS (1 << (32 - 14)) * WAVETABLE_CENTS_SHIFT(0) * 22050.0 / WAVETABLE_NOTE_TO_FREQUENCY(86) / AUDIO_SAMPLE_RATE_EXACT + 0.5, // PER_HERTZ_PHASE_INCREMENT ((uint32_t)9590 - 1) << (32 - 14), // MAX_PHASE ((uint32_t)9589 - 1) << (32 - 14), // LOOP_PHASE_END (((uint32_t)9589 - 1) << (32 - 14)) - (((uint32_t)82 - 1) << (32 - 14)), // LOOP_PHASE_LENGTH uint16_t(UINT16_MAX * WAVETABLE_DECIBEL_SHIFT(0)), // INITIAL_ATTENUATION_SCALAR uint32_t(0.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // DELAY_COUNT uint32_t(1.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // ATTACK_COUNT uint32_t(0.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // HOLD_COUNT uint32_t(1760.31 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // DECAY_COUNT uint32_t(25.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // RELEASE_COUNT int32_t((1.0 - WAVETABLE_DECIBEL_SHIFT(-0.3)) * AudioSynthWavetable::UNITY_GAIN), // SUSTAIN_MULT uint32_t(0.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / (2 * AudioSynthWavetable::LFO_PERIOD)), // VIBRATO_DELAY uint32_t(8.2 * AudioSynthWavetable::LFO_PERIOD * (UINT32_MAX / AUDIO_SAMPLE_RATE_EXACT)), // VIBRATO_INCREMENT (WAVETABLE_CENTS_SHIFT(0) - 1.0) * 4, // VIBRATO_PITCH_COEFFICIENT_INITIAL (1.0 - WAVETABLE_CENTS_SHIFT(0)) * 4, // VIBRATO_COEFFICIENT_SECONDARY uint32_t(100.02 * AudioSynthWavetable::SAMPLES_PER_MSEC / (2 * AudioSynthWavetable::LFO_PERIOD)), // MODULATION_DELAY uint32_t(6.0 * AudioSynthWavetable::LFO_PERIOD * (UINT32_MAX / AUDIO_SAMPLE_RATE_EXACT)), // MODULATION_INCREMENT (WAVETABLE_CENTS_SHIFT(0) - 1.0) * 4, // MODULATION_PITCH_COEFFICIENT_INITIAL (1.0 - WAVETABLE_CENTS_SHIFT(0)) * 4, // MODULATION_PITCH_COEFFICIENT_SECOND int32_t(UINT16_MAX * (WAVETABLE_DECIBEL_SHIFT(0) - 1.0)) * 4, // MODULATION_AMPLITUDE_INITIAL_GAIN int32_t(UINT16_MAX * (1.0 - WAVETABLE_DECIBEL_SHIFT(0))) * 4, // MODULATION_AMPLITUDE_FINAL_GAIN }, { (int16_t*)sample_4_SawWave_SBRS296, // sample true, // LOOP 12, // LENGTH_BITS (1 << (32 - 12)) * WAVETABLE_CENTS_SHIFT(0) * 22050.0 / WAVETABLE_NOTE_TO_FREQUENCY(95) / AUDIO_SAMPLE_RATE_EXACT + 0.5, // PER_HERTZ_PHASE_INCREMENT ((uint32_t)2429 - 1) << (32 - 12), // MAX_PHASE ((uint32_t)2428 - 1) << (32 - 12), // LOOP_PHASE_END (((uint32_t)2428 - 1) << (32 - 12)) - (((uint32_t)2406 - 1) << (32 - 12)), // LOOP_PHASE_LENGTH uint16_t(UINT16_MAX * WAVETABLE_DECIBEL_SHIFT(0)), // INITIAL_ATTENUATION_SCALAR uint32_t(0.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // DELAY_COUNT uint32_t(1.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // ATTACK_COUNT uint32_t(0.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // HOLD_COUNT uint32_t(1760.31 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // DECAY_COUNT uint32_t(25.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / AudioSynthWavetable::ENVELOPE_PERIOD + 0.5), // RELEASE_COUNT int32_t((1.0 - WAVETABLE_DECIBEL_SHIFT(-0.3)) * AudioSynthWavetable::UNITY_GAIN), // SUSTAIN_MULT uint32_t(0.00 * AudioSynthWavetable::SAMPLES_PER_MSEC / (2 * AudioSynthWavetable::LFO_PERIOD)), // VIBRATO_DELAY uint32_t(8.2 * AudioSynthWavetable::LFO_PERIOD * (UINT32_MAX / AUDIO_SAMPLE_RATE_EXACT)), // VIBRATO_INCREMENT (WAVETABLE_CENTS_SHIFT(0) - 1.0) * 4, // VIBRATO_PITCH_COEFFICIENT_INITIAL (1.0 - WAVETABLE_CENTS_SHIFT(0)) * 4, // VIBRATO_COEFFICIENT_SECONDARY uint32_t(100.02 * AudioSynthWavetable::SAMPLES_PER_MSEC / (2 * AudioSynthWavetable::LFO_PERIOD)), // MODULATION_DELAY uint32_t(6.0 * AudioSynthWavetable::LFO_PERIOD * (UINT32_MAX / AUDIO_SAMPLE_RATE_EXACT)), // MODULATION_INCREMENT (WAVETABLE_CENTS_SHIFT(0) - 1.0) * 4, // MODULATION_PITCH_COEFFICIENT_INITIAL (1.0 - WAVETABLE_CENTS_SHIFT(0)) * 4, // MODULATION_PITCH_COEFFICIENT_SECOND int32_t(UINT16_MAX * (WAVETABLE_DECIBEL_SHIFT(0) - 1.0)) * 4, // MODULATION_AMPLITUDE_INITIAL_GAIN int32_t(UINT16_MAX * (1.0 - WAVETABLE_DECIBEL_SHIFT(0))) * 4, // MODULATION_AMPLITUDE_FINAL_GAIN }, }; static const PROGMEM uint8_t SawWave_ranges[] = {55, 67, 85, 107, 127, }; const PROGMEM AudioSynthWavetable::instrument_data SawWave = {5, SawWave_ranges, SawWave_samples };
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <algorithm> #include <string> #include <unordered_map> #include <vector> #include "paddle/fluid/framework/ir/fuse_optimizer_ops_pass/fuse_optimizer_op_pass.h" #include "paddle/fluid/framework/op_registry.h" namespace paddle { namespace framework { namespace ir { class FuseMomentumOpPass : public FuseOptimizerOpPass { private: virtual const std::string GetOpType() const { return "momentum"; } virtual const std::vector<std::string> GetAuxiliaryVarNames() const { return {"Velocity"}; } // Fuse Momentum Ops virtual ir::Node *FuseOptimizerOps( const std::unordered_map<std::string, std::vector<std::string>> &vars_set, const std::unordered_map<std::string, std::string> &fused_vars_name, const std::vector<ir::Node *> &momentum_ops, ir::Graph *graph) const { PADDLE_ENFORCE_GT(momentum_ops.size(), static_cast<size_t>(0)); // Check attributions // NOTE: If new attribution is added, the following code maybe need change. int op_role = BOOST_GET_CONST(int, momentum_ops[0]->Op()->GetAttr( OpProtoAndCheckerMaker::OpRoleAttrName())); float mu = BOOST_GET_CONST(float, momentum_ops[0]->Op()->GetAttr("mu")); bool use_nesterov = BOOST_GET_CONST(bool, momentum_ops[0]->Op()->GetAttr("use_nesterov")); for (auto &momentum_op : momentum_ops) { PADDLE_ENFORCE_EQ( mu, BOOST_GET_CONST(float, momentum_op->Op()->GetAttr("mu"))); PADDLE_ENFORCE_EQ( use_nesterov, BOOST_GET_CONST(bool, momentum_op->Op()->GetAttr("use_nesterov"))); PADDLE_ENFORCE_EQ( op_role, BOOST_GET_CONST(int, momentum_op->Op()->GetAttr( OpProtoAndCheckerMaker::OpRoleAttrName()))); } // NOTE: fused_var is only exist in scope, so the graph doesn't have // fused_var node. VLOG(6) << "Insert momentum to graph "; OpDesc momentum_desc(momentum_ops[0]->Op()->Block()); momentum_desc.SetType("momentum"); momentum_desc.SetInput(kParam, {fused_vars_name.at(kParam)}); momentum_desc.SetInput(kGrad, {fused_vars_name.at(kGrad)}); momentum_desc.SetInput("Velocity", {fused_vars_name.at("Velocity")}); // TODO(zcd): The LearningRate should be equal. momentum_desc.SetInput(kLearningRate, momentum_ops[0]->Op()->Input(kLearningRate)); momentum_desc.SetOutput("ParamOut", {fused_vars_name.at(kParam)}); momentum_desc.SetOutput("VelocityOut", {fused_vars_name.at("Velocity")}); momentum_desc.SetAttr("mu", mu); momentum_desc.SetAttr("use_nesterov", use_nesterov); momentum_desc.SetAttr(OpProtoAndCheckerMaker::OpRoleAttrName(), op_role); return graph->CreateOpNode(&momentum_desc); } }; } // namespace ir } // namespace framework } // namespace paddle REGISTER_PASS(fuse_momentum_op_pass, paddle::framework::ir::FuseMomentumOpPass);
/* * SpatialPolygon_test.cpp * * Created on: May 21, 2020 * Author: mrilee * * Copyright (C) 2020 Rilee Systems Technologies LLC */ #include "SpatialPolygon.h" using namespace std; #include "Test.h" #include "SpatialIndex.h" #define hexOut1(a,b) cout << a << " 0x" << hex << setfill('0') << setw(16) << b << dec << endl << flush; void SpatialPolygon_test() { // cout << "nodes" << endl << flush; Vertices nodes; // CCW nodes.push_back(SpatialVector(1,0,0)); nodes.push_back(SpatialVector(0,1,0)); nodes.push_back(SpatialVector(0,0,1)); nodes.push_back(SpatialVector(1,0,0)); // cout << "x and normalize" << endl << flush; SpatialVector x(0,1,1); x.normalize(); // cout << "make polygon" << endl << flush; SpatialPolygon p(nodes); // cout << "execute intersection" << endl << flush; // cout << x << " x & p intersection: " << p.intersection(x) << endl << flush; ASSERT_EQUALM("011 in xyz",0,p.intersection(x)); x = SpatialVector(0,-1,-1); x.normalize(); // cout << x << " x & p intersection: " << p.intersection(x) << endl << flush; ASSERT_EQUALM("-011 in xyz",0,p.intersection(x)); x = SpatialVector(0.5,0.5,0.5); x.normalize(); // cout << x << " x & p intersection: " << p.intersection(x) << endl << flush; ASSERT_EQUALM("111 in xyz",1,p.intersection(x)); x = SpatialVector(0.5,0.5,0.5); x.normalize(); x = -1.0*x; // cout << x << " x & p intersection: " << p.intersection(x) << endl << flush; ASSERT_EQUALM("-111 in xyz",0,p.intersection(x)); SpatialVector tr0 = SpatialVector(1,0,0); tr0.normalize(); SpatialVector tr1 = SpatialVector(0,1,0); tr1.normalize(); SpatialVector tr2 = SpatialVector(0,0,1); tr2.normalize(); SpatialVector trc = tr0+tr1+tr2; trc.normalize(); Triangle tr; tr.centroid = trc; // Not correct tr.vertices.clear(); tr.vertices.push_back(tr0); tr.vertices.push_back(tr1); tr.vertices.push_back(tr2); ASSERT_EQUALM("tr0",1,p.intersection(tr0)); ASSERT_EQUALM("tr1",1,p.intersection(tr1)); ASSERT_EQUALM("tr2",1,p.intersection(tr2)); ASSERT_EQUALM("trc",1,p.intersection(trc)); SpatialVector a; a = tr0+tr1; a.normalize(); ASSERT_EQUALM("tr01",1,p.intersection(a)); a = tr1+tr2; a.normalize(); ASSERT_EQUALM("tr12",1,p.intersection(a)); a = tr2+tr0; a.normalize(); ASSERT_EQUALM("tr20",1,p.intersection(a)); // cout << "tr intersection " << p.intersect_triangle(tr) << endl << flush; ASSERT_EQUALM("identical",7,p.intersect_triangle(tr)); // BELWO ARE REGRESSIONS VIZ WHEN ABLE, PLEASE. tr0 = SpatialVector(-1,1,1); tr0.normalize(); tr.vertices[0] = tr0; // cout << "tr intersection " << p.intersect_triangle(tr) << endl << flush; ASSERT_EQUALM("-x",4,p.intersect_triangle(tr)); tr0 = SpatialVector(1-0.1,0,0); tr0.normalize(); tr1 = SpatialVector(0,1-0.1,0); tr1.normalize(); tr.vertices[0] = tr0; tr.vertices[1] = tr1; // cout << "tr intersection " << p.intersect_triangle(tr) << endl << flush; ASSERT_EQUALM("tuck 2",7,p.intersect_triangle(tr)); tr0 = SpatialVector(1-0.1,0,0); tr0.normalize(); tr1 = SpatialVector(0,1-0.1,0); tr1.normalize(); tr2 = SpatialVector(0,0,-1); tr2.normalize(); tr.vertices[0] = tr0; tr.vertices[1] = tr1; tr.vertices[2] = tr2; // cout << "tr intersection " << p.intersect_triangle(tr) << endl << flush; ASSERT_EQUALM("-z",4,p.intersect_triangle(tr)); // cout << "ccw" << endl << flush; // CCW nodes.clear(); nodes.push_back(SpatialVector(1,0,0)); nodes.push_back(SpatialVector(0,1,0)); nodes.push_back(SpatialVector(0,0,1)); nodes.push_back(SpatialVector(1,0,0)); SpatialPolygon p0(nodes); ASSERT_EQUAL(true,p0.ccw_orientation); // cout << "cw" << endl << flush; // CW nodes.clear(); nodes.push_back(SpatialVector(1,0,0)); nodes.push_back(SpatialVector(0,0,1)); nodes.push_back(SpatialVector(0,1,0)); nodes.push_back(SpatialVector(1,0,0)); SpatialPolygon p1(nodes); ASSERT_EQUAL(false,p1.ccw_orientation); }
// Copyright (c) 2014-2020 The Dash Core developers #include <cachemultimap.h> #include <test/util/setup_common.h> #include <algorithm> #include <iostream> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(cachemultimap_tests, BasicTestingSetup) static bool Compare(const CacheMultiMap<int,int>& cmmap1, const CacheMultiMap<int,int>& cmmap2) { if(cmmap1.GetMaxSize() != cmmap2.GetMaxSize()) { std::cout << "Compare returning false: max size mismatch" << std::endl; return false; } if(cmmap1.GetSize() != cmmap2.GetSize()) { std::cout << "Compare returning false: size mismatch" << std::endl; return false; } const CacheMultiMap<int,int>::list_t& items1 = cmmap1.GetItemList(); const CacheMultiMap<int,int>::list_t& items2 = cmmap2.GetItemList(); CacheMultiMap<int,int>::list_cit it2 = items2.begin(); for(CacheMultiMap<int,int>::list_cit it1 = items1.begin(); it1 != items1.end(); ++it1) { const CacheItem<int,int>& item1 = *it1; const CacheItem<int,int>& item2 = *it2; if(item1.key != item2.key) { return false; } if(item1.value != item2.value) { return false; } ++it2; } return true; } static bool CheckExpected(const CacheMultiMap<int,int>& cmmap, int* expected, CacheMultiMap<int,int>::size_type nSize) { if(cmmap.GetSize() != nSize) { return false; } for(CacheMultiMap<int,int>::size_type i = 0; i < nSize; ++i) { int nVal = 0; int eVal = expected[i]; if(!cmmap.Get(eVal, nVal)) { return false; } if(nVal != eVal) { return false; } } return true; } BOOST_AUTO_TEST_CASE(cachemultimap_test) { // create a CacheMultiMap limited to 10 items CacheMultiMap<int,int> cmmapTest1(10); // check that the max size is 10 BOOST_CHECK(cmmapTest1.GetMaxSize() == 10); // check that the size is 0 BOOST_CHECK(cmmapTest1.GetSize() == 0); // insert (-1, -1) cmmapTest1.Insert(-1, -1); // make sure that the size is updated BOOST_CHECK(cmmapTest1.GetSize() == 1); // make sure the map contains the key BOOST_CHECK(cmmapTest1.HasKey(-1) == true); // add 10 items for(int i = 0; i < 10; ++i) { cmmapTest1.Insert(i, i); } // check that the size is 10 BOOST_CHECK(cmmapTest1.GetSize() == 10); // check that the map contains the expected items for(int i = 0; i < 10; ++i) { int nVal = 0; BOOST_CHECK(cmmapTest1.Get(i, nVal) == true); BOOST_CHECK(nVal == i); } // check that the map no longer contains the first item BOOST_CHECK(cmmapTest1.HasKey(-1) == false); // erase an item cmmapTest1.Erase(5); // check the size BOOST_CHECK(cmmapTest1.GetSize() == 9); // check that the map no longer contains the item BOOST_CHECK(cmmapTest1.HasKey(5) == false); // check that the map contains the expected items int expected[] = { 0, 1, 2, 3, 4, 6, 7, 8, 9 }; BOOST_CHECK(CheckExpected(cmmapTest1, expected, 9 ) == true); // add multiple items for the same key cmmapTest1.Insert(5, 2); cmmapTest1.Insert(5, 1); cmmapTest1.Insert(5, 4); // check the size BOOST_CHECK(cmmapTest1.GetSize() == 10); // check that 2 keys have been removed BOOST_CHECK(cmmapTest1.HasKey(0) == false); BOOST_CHECK(cmmapTest1.HasKey(1) == false); BOOST_CHECK(cmmapTest1.HasKey(2) == true); // check multiple values std::vector<int> vecVals; BOOST_CHECK(cmmapTest1.GetAll(5, vecVals) == true); BOOST_CHECK(vecVals.size() == 3); BOOST_CHECK(vecVals[0] == 1); BOOST_CHECK(vecVals[1] == 2); BOOST_CHECK(vecVals[2] == 4); // std::cout << "cmmapTest1 dump:" << std::endl; // DumpMap(cmmapTest1); // test serialization CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << cmmapTest1; CacheMultiMap<int,int> cmmapTest2; ss >> cmmapTest2; // std::cout << "cmmapTest2 dump:" << std::endl; // DumpMap(cmmapTest2); // check multiple values std::vector<int> vecVals2; BOOST_CHECK(cmmapTest2.GetAll(5, vecVals2) == true); BOOST_CHECK(vecVals2.size() == 3); BOOST_CHECK(vecVals2[0] == 1); BOOST_CHECK(vecVals2[1] == 2); BOOST_CHECK(vecVals2[2] == 4); BOOST_CHECK(Compare(cmmapTest1, cmmapTest2)); // test copy constructor CacheMultiMap<int,int> cmmapTest3(cmmapTest1); BOOST_CHECK(Compare(cmmapTest1, cmmapTest3)); // test assignment operator CacheMultiMap<int,int> mapTest4; mapTest4 = cmmapTest1; BOOST_CHECK(Compare(cmmapTest1, mapTest4)); } BOOST_AUTO_TEST_SUITE_END()
#include "platform/i_platform.h" #include "kill_score_system.h" #include "core/player_controller_component.h" #include "core/team_component.h" #include "show_text_event.h" namespace engine { KillScoreSystem::KillScoreSystem() : mScene( Scene::Get() ) , mProgramState( core::ProgramState::Get() ) , mScoreModel( "score", &RootModel::Get() ) , mKill( 0 ) , mDeath( 0 ) , mScore( 0 ) { } void KillScoreSystem::Init() { mOnKillScore = EventServer<engine::KillScoreEvent>::Get().Subscribe( boost::bind( &KillScoreSystem::OnKillScore, this, _1 ) ); mScoreModels.clear(); mScoreModels.push_back( new ModelValue( GetIntFunc( this, &KillScoreSystem::GetKill ), "kill", &mScoreModel ) ); mScoreModels.push_back( new ModelValue( GetIntFunc( this, &KillScoreSystem::GetDeath ), "death", &mScoreModel ) ); mScoreModels.push_back( new ModelValue( GetIntFunc( this, &KillScoreSystem::GetScore ), "score", &mScoreModel ) ); } void KillScoreSystem::Update( double DeltaTime ) { Opt<core::ClientData> clientData( mProgramState.FindClientDataByClientId( mProgramState.mClientId ) ); if( clientData.IsValid() ) { mKill = clientData->mKill; mDeath = clientData->mDeath; mScore = clientData->mScore; } } void KillScoreSystem::OnKillScore( engine::KillScoreEvent const& Evt ) { Opt<Actor> dead = mScene.GetActor( Evt.mDeadGUID ); if ( !dead.IsValid() ) { L1( "cannot find dead actor with GUID: (%s) %d \n", __FUNCTION__, Evt.mDeadGUID ); return; } Opt<PlayerControllerComponent> deadPCC = dead->Get<IControllerComponent>(); Opt<core::ClientData> deadClientData; if ( deadPCC.IsValid() ) { deadClientData = mProgramState.FindClientDataByClientId( deadPCC->mControllerId ); } if ( deadClientData.IsValid() ) { ++deadClientData->mDeath; //he is dead that's for sure } Opt<Actor> killer = mScene.GetActor( Evt.mKillerGUID ); if ( !killer.IsValid() ) { L1( "cannot find killer actor with GUID: (%s) %d \n", __FUNCTION__, Evt.mKillerGUID ); return; } Opt<PlayerControllerComponent> killerPCC = killer->Get<IControllerComponent>(); Opt<core::ClientData> killerClientData; if ( killerPCC.IsValid() ) { killerClientData = mProgramState.FindClientDataByClientId( killerPCC->mControllerId ); } if ( killerClientData.IsValid() ) { auto killerTeamC = killer->Get<ITeamComponent>(); auto deadTeamC = dead->Get<ITeamComponent>(); if ( killerTeamC.IsValid() && deadTeamC.IsValid() ) { if ( killerTeamC->GetTeam() == deadTeamC->GetTeam() ) { --killerClientData->mKill; //you got one less kill, that's a punishment for TK --killerClientData->mScore; //your score is decreased too. naughty naughty! } else { ++killerClientData->mKill; ++killerClientData->mScore; } } else if ( deadPCC.IsValid() ) { ++killerClientData->mKill; ++killerClientData->mScore; } } if ( killerClientData.IsValid() && deadClientData.IsValid() ) { EventServer<engine::ShowTextEvent>::Get().SendEvent( engine::ShowTextEvent( 2.5, killerClientData->mClientName + " reaped " + deadClientData->mClientName + "!" ) ); } } int32_t const& KillScoreSystem::GetKill() { return mKill; } int32_t const& KillScoreSystem::GetDeath() { return mDeath; } int32_t const& KillScoreSystem::GetScore() { return mScore; } } // namespace engine
/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <sstream> #include <osquery/core.h> #include <osquery/logger.h> #include <osquery/registry.h> #include <osquery/sql.h> #include <osquery/tables.h> #include "osquery/core/conversions.h" namespace osquery { FLAG(int32, value_max, 512, "Maximum returned row value size"); CREATE_LAZY_REGISTRY(SQLPlugin, "sql"); SQL::SQL(const std::string& q) { TableColumns table_columns; q_ = q; status_ = getQueryColumns(q_, table_columns); if (status_.ok()) { for (auto c : table_columns) { columns_.push_back(std::get<0>(c)); } status_ = query(q_, results_); } } const QueryData& SQL::rows() const { return results_; } const ColumnNames& SQL::columns() { return columns_; } bool SQL::ok() { return status_.ok(); } const Status& SQL::getStatus() const { return status_; } std::string SQL::getMessageString() { return status_.toString(); } static inline void escapeNonPrintableBytes(std::string& data) { std::string escaped; // clang-format off char const hex_chars[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', }; // clang-format on bool needs_replacement = false; for (size_t i = 0; i < data.length(); i++) { if (((unsigned char)data[i]) < 0x20 || ((unsigned char)data[i]) >= 0x80) { needs_replacement = true; escaped += "\\x"; escaped += hex_chars[(((unsigned char)data[i])) >> 4]; escaped += hex_chars[((unsigned char)data[i] & 0x0F) >> 0]; } else { escaped += data[i]; } } // Only replace if any escapes were made. if (needs_replacement) { data = std::move(escaped); } } void escapeNonPrintableBytesEx(std::string& data) { return escapeNonPrintableBytes(data); } void SQL::escapeResults() { for (auto& row : results_) { for (auto& column : row) { escapeNonPrintableBytes(column.second); } } } QueryData SQL::selectAllFrom(const std::string& table) { PluginResponse response; Registry::call("table", table, {{"action", "generate"}}, response); return response; } QueryData SQL::selectAllFrom(const std::string& table, const std::string& column, ConstraintOperator op, const std::string& expr) { PluginRequest request = {{"action", "generate"}}; { // Create a fake content, there will be no caching. QueryContext ctx; ctx.constraints[column].add(Constraint(op, expr)); TablePlugin::setRequestFromContext(ctx, request); } PluginResponse response; Registry::call("table", table, request, response); return response; } Status SQLPlugin::call(const PluginRequest& request, PluginResponse& response) { response.clear(); if (request.count("action") == 0) { return Status(1, "SQL plugin must include a request action"); } if (request.at("action") == "query") { return this->query(request.at("query"), response); } else if (request.at("action") == "columns") { TableColumns columns; auto status = this->getQueryColumns(request.at("query"), columns); // Convert columns to response for (const auto& column : columns) { response.push_back( {{"n", std::get<0>(column)}, {"t", columnTypeName(std::get<1>(column))}, {"o", INTEGER(static_cast<size_t>(std::get<2>(column)))}}); } return status; } else if (request.at("action") == "attach") { // Attach a virtual table name using an optional included definition. return this->attach(request.at("table")); } else if (request.at("action") == "detach") { this->detach(request.at("table")); return Status(0, "OK"); } else if (request.at("action") == "tables") { std::vector<std::string> tables; auto status = this->getQueryTables(request.at("query"), tables); if (status.ok()) { for (const auto& table : tables) { response.push_back({{"t", table}}); } } return status; } return Status(1, "Unknown action"); } Status query(const std::string& q, QueryData& results) { return Registry::call( "sql", "sql", {{"action", "query"}, {"query", q}}, results); } Status getQueryColumns(const std::string& q, TableColumns& columns) { PluginResponse response; auto status = Registry::call( "sql", "sql", {{"action", "columns"}, {"query", q}}, response); // Convert response to columns for (const auto& item : response) { columns.push_back(make_tuple( item.at("n"), columnTypeName(item.at("t")), ColumnOptions::DEFAULT)); } return status; } Status mockGetQueryTables(std::string copy_q, std::vector<std::string>& tables) { std::transform(copy_q.begin(), copy_q.end(), copy_q.begin(), ::tolower); auto offset_from = copy_q.find("from "); if (offset_from == std::string::npos) { return Status(1); } auto simple_tables = osquery::split(copy_q.substr(offset_from + 5), ","); for (const auto& table : simple_tables) { tables.push_back(table); } return Status(0); } Status getQueryTables(const std::string& q, std::vector<std::string>& tables) { if (!Registry::get().exists("sql", "sql") && kToolType == ToolType::TEST) { // We 'mock' this functionality for internal tests. return mockGetQueryTables(q, tables); } PluginResponse response; auto status = Registry::call( "sql", "sql", {{"action", "tables"}, {"query", q}}, response); for (const auto& table : response) { tables.push_back(table.at("t")); } return status; } }
#include <Imath/ImathFrustum.h> void frustum_example() { float near = 1.7f; float far = 567.0f; float left = -3.5f; float right = 2.0f; float top = 0.9f; float bottom = -1.3f; Imath::Frustumf frustum (near, far, left, right, top, bottom, false); Imath::M44f m = frustum.projectionMatrix(); Imath::V3f p (1.0f, 1.0f, 1.0f); Imath::V2f s = frustum.projectPointToScreen (p); assert (s.equalWithAbsError (Imath::V2f (-0.345455f, -1.36364f), 0.0001f)); }
/*========================================================================= Program: MIMX Meshing Toolkit Module: $RCSfile: vtkMimxCylindricalMesh.cxx,v $ Language: C++ Date: $Date: 2012/12/07 19:08:59 $ Version: $Revision: 1.1.1.1 $ Musculoskeletal Imaging, Modelling and Experimentation (MIMX) Center for Computer Aided Design The University of Iowa Iowa City, IA 52242 http://www.ccad.uiowa.edu/mimx/ Copyright (c) The University of Iowa. All rights reserved. See MIMXCopyright.txt or http://www.ccad.uiowa.edu/mimx/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "vtkMimxCylindricalMesh.h" #include "vtkCell.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkCellLocator.h" #include "vtkDataSetAttributes.h" #include "vtkDataSetCollection.h" #include "vtkMimxEdgeToPlanarStructuredGrid.h" #include "vtkExecutive.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkMath.h" #include "vtkMergeCells.h" #include "vtkObjectFactory.h" #include "vtkPlane.h" #include "vtkPointData.h" #include "vtkPointLocator.h" #include "vtkPolyDataWriter.h" #include "vtkPlaneWidget.h" #include "vtkStructuredGrid.h" #include "vtkUnstructuredGrid.h" #include "vtkMimxSubdivideCurve.h" #include "vtkStructuredGridWriter.h" #include "vtkStructuredGridReader.h" #include "vtkMimxStructuredPlanarToStructuredSolidGrid.h" #include "vtkUnstructuredGrid.h" #include "vtkUnstructuredGridWriter.h" vtkCxxRevisionMacro(vtkMimxCylindricalMesh, "$Revision: 1.1.1.1 $"); vtkStandardNewMacro(vtkMimxCylindricalMesh); //---------------------------------------------------------------------------- vtkMimxCylindricalMesh::vtkMimxCylindricalMesh() { this->SetNumberOfInputPorts(6); for(int i=0; i < 9; i++) { this->StructuredSolidGrid[i] = vtkStructuredGrid::New(); } for(int i=0; i < 40; i++) { this->StructuredPlanarGrid[i] = vtkStructuredGrid::New(); } for(int i=0; i<60; i++) { this->EdgePolyData[i] = vtkPolyData::New(); } //this->SuperiorDividingPoints = vtkPoints::New(); //this->InferiorDividingPoints = vtkPoints::New(); } //---------------------------------------------------------------------------- vtkMimxCylindricalMesh::~vtkMimxCylindricalMesh() { for(int i=0; i < 9; i++) { this->StructuredSolidGrid[i]->Delete(); } for(int i=0; i < 40; i++) { this->StructuredPlanarGrid[i]->Delete(); } for(int i=0; i<60; i++) { this->EdgePolyData[i]->Delete(); } //this->SuperiorDividingPoints->Delete(); //this->InferiorDividingPoints->Delete(); } //---------------------------------------------------------------------------- // Append data sets into single unstructured grid int vtkMimxCylindricalMesh::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { // get the output info object // vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the ouptut //vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); vtkPolyData *source = vtkPolyData::SafeDownCast(inputVector[4]-> GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); vtkCellLocator *locator = vtkCellLocator::New(); vtkUnstructuredGrid *bbox = vtkUnstructuredGrid::SafeDownCast(inputVector[5]-> GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); double dim[3]; bbox->GetCellData()->GetVectors()->GetTuple(0,dim); this->MeshSeed[0] = static_cast<int>(dim[2])-1; this->MeshSeed[1] = static_cast<int>(dim[0])-1; this->MeshSeed[2] = static_cast<int>(dim[1])-1; bbox->GetCellData()->GetVectors()->GetTuple(1,dim); this->MeshSeed[3] = static_cast<int>(dim[0])-1; bbox->GetCellData()->GetVectors()->GetTuple(4,dim); this->MeshSeed[4] = static_cast<int>(dim[2])-1; locator->SetDataSet(source); locator->BuildLocator(); // temporary input vtkInformation *inInfo = NULL; inInfo = inputVector[0]->GetInformationObject(0); // this->EdgePolyData[0] = vtkPolyData::New(); // this->EdgePolyData[1] = vtkPolyData::SafeDownCast( // inputVector[3]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); // this->EdgePolyData[2] = vtkPolyData::New(); // this->EdgePolyData[3] = vtkPolyData::SafeDownCast( // inputVector[2]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); // this->EdgePolyData[4] = vtkPolyData::New(); // this->EdgePolyData[5] = vtkPolyData::SafeDownCast( // inputVector[1]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); // this->EdgePolyData[6] = vtkPolyData::New(); // this->EdgePolyData[7] = vtkPolyData::SafeDownCast( // inputVector[0]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); // for(int i=8; i < 12; i++) // this->EdgePolyData[i] = vtkPolyData::New(); /* vtkPolyData::SafeDownCast( inputVector[0]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()))->GetCenter(SupCenter); vtkPolyData::SafeDownCast( inputVector[2]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()))->GetCenter(InfCenter);*/ double bottomcenter[3], topcenter[3]; this->CalculateCenter(vtkPolyData::SafeDownCast( inputVector[0]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()))); for (int i=0; i <3; i++) { this->SupCenter[i] = this->Center[i]; topcenter[i] = this->Center[i]; } this->CalculateCenter(vtkPolyData::SafeDownCast( inputVector[2]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()))); for (int i=0; i <3; i++) { bottomcenter[i] = this->Center[i]; this->InfCenter[i] = this->Center[i]; } for(int i=0; i < 4; i++) { //if(i==0 || i ==2) //{ // this->CalculateCenter(vtkPolyData::SafeDownCast( // inputVector[i]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()))); //} this->DivideCurve(i,vtkPolyData::SafeDownCast( inputVector[i]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())), bbox); } // block 0 // subdivide the known edges if needed project // curve 1 this->EdgeSubdivideProject(1,this->MeshSeed[1],locator); this->SetEdgeScalars(1,0); // curve 3 this->EdgeSubdivideProject(3,this->MeshSeed[1],locator); this->SetEdgeScalars(3,0); // curve 5 this->EdgeSubdivideProject(5,this->MeshSeed[1],locator); this->SetEdgeScalars(5,0); // curve 7 this->EdgeSubdivideProject(7,this->MeshSeed[1],locator); this->SetEdgeScalars(7,0); // generate curves for by connecting the known curves subdivide and // if needed project // curve 0 this->GenerateUnknownEdge(0, 3, 1, 0); this->EdgeSubdivideProject(0, this->MeshSeed[0],locator); this->SetEdgeScalars(0,1); // curve 2 this->GenerateUnknownEdge(2, 3, 1, 1); this->EdgeSubdivideProject(2, this->MeshSeed[0],locator); this->SetEdgeScalars(2,1); // curve 4 this->GenerateUnknownEdge(4, 7, 5, 0); this->EdgeSubdivideProject(4, this->MeshSeed[0],locator); this->SetEdgeScalars(4,1); // curve 6 this->GenerateUnknownEdge(6, 7, 5, 1); this->EdgeSubdivideProject(6, this->MeshSeed[0],locator); this->SetEdgeScalars(6,1); // curve 8 this->GenerateUnknownEdge(8, 3, 7, 0); this->EdgeSubdivideProject(8, this->MeshSeed[2],NULL); this->SetEdgeScalars(8,1); // curve 9 this->GenerateUnknownEdge(9, 1, 5, 0); this->EdgeSubdivideProject(9, this->MeshSeed[2],locator); this->SetEdgeScalars(9,1); // curve 10 this->GenerateUnknownEdge(10, 3, 7, 1); this->EdgeSubdivideProject(10, this->MeshSeed[2],NULL); this->SetEdgeScalars(10,1); // curve 11 this->GenerateUnknownEdge(11, 1, 5, 1); this->EdgeSubdivideProject(11, this->MeshSeed[2],locator); this->SetEdgeScalars(11,1); // generate face from 4 curves // face 0 through 5 this->GenerateFaceProject(0,3,10,7,8,NULL); this->GenerateFaceProject(1,1,11,5,9,locator); this->GenerateFaceProject(2,0,9,4,8,NULL); this->GenerateFaceProject(3,2,11,6,10,NULL); this->GenerateFaceProject(4,0,1,2,3,locator); this->SetFaceScalars(4,0); this->GenerateFaceProject(5,4,5,6,7,locator); this->SetFaceScalars(5,0); // generate the solid mesh for first bounding box int FaceArray[6]; for(int i=0; i<6; i++) FaceArray[i] = i; this->GenerateSolidMesh(0,FaceArray); //************************************************************** // block 1 // subdivide the known edges if needed project // curve 12 this->EdgeSubdivideProject(12,this->MeshSeed[3],locator); this->SetEdgeScalars(12,0); // curve 14 this->EdgeSubdivideProject(14,this->MeshSeed[3],locator); this->SetEdgeScalars(14,0); // curve 15 this->EdgeSubdivideProject(15,this->MeshSeed[3],locator); this->SetEdgeScalars(15,0); // curve 17 this->EdgeSubdivideProject(17,this->MeshSeed[3],locator); this->SetEdgeScalars(17,0); // generate curves for by connecting the known curves subdivide and // if needed project // curve 13 this->GenerateUnknownEdge(13, 14, 12, 1); this->EdgeSubdivideProject(13, this->MeshSeed[0],locator); this->SetEdgeScalars(13,1); // curve 16 this->GenerateUnknownEdge(16, 17, 15, 1); this->EdgeSubdivideProject(16, this->MeshSeed[0],locator); this->SetEdgeScalars(16,1); // curve 18 this->GenerateUnknownEdge(18, 14, 17, 1); this->EdgeSubdivideProject(18, this->MeshSeed[2],NULL); this->SetEdgeScalars(18,1); // curve 19 this->GenerateUnknownEdge(19, 12, 15, 1); this->EdgeSubdivideProject(19, this->MeshSeed[2],locator); this->SetEdgeScalars(19,1); // generate face from 4 curves // face 0 through 5 this->GenerateFaceProject(6,14,18,17,10,NULL); this->GenerateFaceProject(7,12,19,15,11,locator); this->GenerateFaceProject(8,13,19,16,18,NULL); this->GenerateFaceProject(9,2,12,13,14,locator); this->SetFaceScalars(9,0); this->GenerateFaceProject(10,6,15,16,17,locator); this->SetFaceScalars(10,0); // generate the solid mesh for first bounding box FaceArray[0] = 6; FaceArray[1] = 7; FaceArray[2] = 3; FaceArray[3] = 8; FaceArray[4] = 9; FaceArray[5] = 10; this->GenerateSolidMesh(1,FaceArray); //************************************************************** // block 2 // subdivide the known edges if needed project // curve 12 this->EdgeSubdivideProject(20,this->MeshSeed[1],locator); this->SetEdgeScalars(20,0); // curve 14 this->EdgeSubdivideProject(22,this->MeshSeed[1],locator); this->SetEdgeScalars(22,0); // curve 15 this->EdgeSubdivideProject(23,this->MeshSeed[1],locator); this->SetEdgeScalars(23,0); // curve 17 this->EdgeSubdivideProject(25,this->MeshSeed[1],locator); this->SetEdgeScalars(25,0); // generate curves for by connecting the known curves subdivide and // if needed project // curve 2 this->GenerateUnknownEdge(21, 22, 20, 1); this->EdgeSubdivideProject(21, this->MeshSeed[0],locator); this->SetEdgeScalars(21,1); // curve 6 this->GenerateUnknownEdge(24, 25, 23, 1); this->EdgeSubdivideProject(24, this->MeshSeed[0],locator); this->SetEdgeScalars(24,1); // curve 18 this->GenerateUnknownEdge(26, 22, 25, 1); this->EdgeSubdivideProject(26, this->MeshSeed[2],NULL); this->SetEdgeScalars(26,1); // curve 19 this->GenerateUnknownEdge(27, 20, 23, 1); this->EdgeSubdivideProject(27, this->MeshSeed[2],locator); this->SetEdgeScalars(27,1); // generate face from 4 curves // face 0 through 5 this->GenerateFaceProject(11,22,26,25,18,NULL); this->GenerateFaceProject(12,20,27,23,19,locator); this->GenerateFaceProject(13,21,27,24,26,NULL); this->GenerateFaceProject(14,13,20,21,22,locator); this->SetFaceScalars(14,0); this->GenerateFaceProject(15,16,23,24,25,locator); this->SetFaceScalars(15,0); // generate the solid mesh for first bounding box FaceArray[0] = 11; FaceArray[1] = 12; FaceArray[2] = 8; FaceArray[3] = 13; FaceArray[4] = 14; FaceArray[5] = 15; this->GenerateSolidMesh(2,FaceArray); //************************************************************** // block 3 // subdivide the known edges if needed project // curve 12 this->EdgeSubdivideProject(28,this->MeshSeed[3],locator); this->SetEdgeScalars(28,0); // curve 14 this->EdgeSubdivideProject(29,this->MeshSeed[3],locator); this->SetEdgeScalars(29,0); // curve 15 this->EdgeSubdivideProject(30,this->MeshSeed[3],locator); this->SetEdgeScalars(30,0); // curve 17 this->EdgeSubdivideProject(31,this->MeshSeed[3],locator); this->SetEdgeScalars(31,0); // generate face from 4 curves // face 0 through 5 this->GenerateFaceProject(16,29,8,31,26,NULL); this->GenerateFaceProject(17,28,9,30,27,locator); this->GenerateFaceProject(18,21,28,0,29,NULL); this->SetFaceScalars(18,0); this->GenerateFaceProject(19,24,30,4,31,locator); this->SetFaceScalars(19,0); // generate the solid mesh for first bounding box FaceArray[0] = 16; FaceArray[1] = 17; FaceArray[2] = 13; FaceArray[3] = 2; FaceArray[4] = 18; FaceArray[5] = 19; this->GenerateSolidMesh(3,FaceArray); ////************************************************************** //// block 4 //// reverse the edges direction 14,17,22,25 //this->ReverseEdgeDirection(14); this->ReverseEdgeDirection(17); //this->ReverseEdgeDirection(22); this->ReverseEdgeDirection(25); //// generate 4 new faces required //this->GenerateFaceProject(20,22,18,25,26,NULL); //this->GenerateFaceProject(21,14,10,17,18,NULL); //this->GenerateFaceProject(22,29,3,14,22,locator); //this->GenerateFaceProject(23,31,7,17,25,locator); //// generate the solid mesh for the center //FaceArray[0] = 20; FaceArray[1] = 0; FaceArray[2] = 16; //FaceArray[3] = 21; FaceArray[4] = 22; FaceArray[5] = 23; //this->GenerateSolidMesh(4,FaceArray); //***************************************************************** // generating inner blocks // calculate the the inner 8 points vtkPoints *innerpoints = vtkPoints::New(); innerpoints->SetNumberOfPoints(8); // calculation of the centers of the traces //vtkPolyData::SafeDownCast(inputVector[0]->GetInformationObject(0)-> // Get(vtkDataObject::DATA_OBJECT()))->GetCenter(topcenter); //vtkPolyData::SafeDownCast(inputVector[2]->GetInformationObject(0)-> // Get(vtkDataObject::DATA_OBJECT()))->GetCenter(bottomcenter); // the four points are placed half way between the center and the // point connecting outer mesh //double x[3]; //double ratio = 0.75; //int m; //this->EdgePolyData[0]->GetPoint(0, outerpoint); //for(m =0; m <3; m++) x[m] = outerpoint[m] + (bottomcenter[m] - outerpoint[m])*ratio; //innerpoints->SetPoint(0, x); //this->EdgePolyData[2]->GetPoint(0, outerpoint); //for(m =0; m <3; m++) x[m] = outerpoint[m] + (bottomcenter[m] - outerpoint[m])*ratio; //innerpoints->SetPoint(1, x); // //this->EdgePolyData[13]->GetPoint(0, outerpoint); //for(m =0; m <3; m++) x[m] = outerpoint[m] + (bottomcenter[m] - outerpoint[m])*ratio; //innerpoints->SetPoint(2, x); // //this->EdgePolyData[21]->GetPoint(0, outerpoint); //for(m =0; m <3; m++) x[m] = outerpoint[m] + (bottomcenter[m] - outerpoint[m])*ratio; //innerpoints->SetPoint(3, x); //this->EdgePolyData[4]->GetPoint(0, outerpoint); //for(m =0; m <3; m++) x[m] = outerpoint[m] + (topcenter[m] - outerpoint[m])*ratio; //innerpoints->SetPoint(4, x); //this->EdgePolyData[6]->GetPoint(0, outerpoint); //for(m =0; m <3; m++) x[m] = outerpoint[m] + (topcenter[m] - outerpoint[m])*ratio; //innerpoints->SetPoint(5, x); //this->EdgePolyData[16]->GetPoint(0, outerpoint); //for(m =0; m <3; m++) x[m] = outerpoint[m] + (topcenter[m] - outerpoint[m])*ratio; //innerpoints->SetPoint(6, x); //this->EdgePolyData[24]->GetPoint(0, outerpoint); //for(m =0; m <3; m++) x[m] = outerpoint[m] + (topcenter[m] - outerpoint[m])*ratio; //innerpoints->SetPoint(7, x); int startingnodenum = 8; for (int i=startingnodenum; i <startingnodenum+4; i++) { innerpoints->SetPoint(i-startingnodenum, bbox->GetPoint(i)); } startingnodenum = 20; int startnum = 4; for (int i=startingnodenum; i <startingnodenum+4; i++) { innerpoints->SetPoint(startnum, bbox->GetPoint(i)); startnum++; } // block 4 // edge 32 this->GenerateUnknownEdgeFromPoints(32, innerpoints->GetPoint(0), this->EdgePolyData[0]->GetPoint(0)); this->EdgeSubdivideProject(32, this->MeshSeed[4],locator); this->SetEdgeScalars(32, 1); // edge 33 this->GenerateUnknownEdgeFromPoints(33, innerpoints->GetPoint(1), this->EdgePolyData[2]->GetPoint(0)); this->EdgeSubdivideProject(33, this->MeshSeed[4],locator); this->SetEdgeScalars(33, 1); // edge 34 this->GenerateUnknownEdge(34, 32, 33, 0); this->EdgeSubdivideProject(34, this->MeshSeed[1],locator); this->SetEdgeScalars(34, 1); // edge 35 this->GenerateUnknownEdgeFromPoints(35, innerpoints->GetPoint(4), this->EdgePolyData[4]->GetPoint(0)); this->EdgeSubdivideProject(35, this->MeshSeed[4],locator); this->SetEdgeScalars(35, 1); // edge 36 this->GenerateUnknownEdgeFromPoints(36, innerpoints->GetPoint(5), this->EdgePolyData[6]->GetPoint(0)); this->EdgeSubdivideProject(36, this->MeshSeed[4],locator); this->SetEdgeScalars(36, 1); // edge 37 this->GenerateUnknownEdge(37, 35, 36, 0); this->EdgeSubdivideProject(37, this->MeshSeed[1],locator); this->SetEdgeScalars(37, 1); // edge 38 this->GenerateUnknownEdge(38, 32, 35, 0); this->EdgeSubdivideProject(38, this->MeshSeed[2],NULL); this->SetEdgeScalars(38, 1); // edge 39 this->GenerateUnknownEdge(39, 33, 36, 0); this->EdgeSubdivideProject(39, this->MeshSeed[2],NULL); this->SetEdgeScalars(39, 1); // this->GenerateFaceProject(20,34,39,37,38,NULL); this->GenerateFaceProject(21,32,8,35,38,NULL); this->GenerateFaceProject(22,33,10,36,39,NULL); this->GenerateFaceProject(23,32,3,33,34,locator); // this->SetFaceScalars(23,0); this->GenerateFaceProject(24,35,7,36,37,locator); // this->SetFaceScalars(24,0); // generate the solid mesh for first bounding box FaceArray[0] = 20; FaceArray[1] = 0; FaceArray[2] = 21; FaceArray[3] = 22; FaceArray[4] = 23; FaceArray[5] = 24; this->GenerateSolidMesh(4,FaceArray); // block 5 // edge 40 this->GenerateUnknownEdgeFromPoints(40, innerpoints->GetPoint(2), this->EdgePolyData[13]->GetPoint(0)); this->EdgeSubdivideProject(40, this->MeshSeed[4],locator); this->SetEdgeScalars(40, 1); // edge 41 this->GenerateUnknownEdge(41, 33, 40, 0); this->EdgeSubdivideProject(41, this->MeshSeed[3],locator); this->SetEdgeScalars(41, 1); // edge 42 this->GenerateUnknownEdgeFromPoints(42, innerpoints->GetPoint(6), this->EdgePolyData[16]->GetPoint(0)); this->EdgeSubdivideProject(42, this->MeshSeed[4],locator); this->SetEdgeScalars(42, 1); // edge 43 this->GenerateUnknownEdge(43, 36, 42, 0); this->EdgeSubdivideProject(43, this->MeshSeed[3],locator); this->SetEdgeScalars(43, 1); // edge 44 this->GenerateUnknownEdge(44, 40, 42, 0); this->EdgeSubdivideProject(44, this->MeshSeed[2],NULL); this->SetEdgeScalars(44, 1); // face this->GenerateFaceProject(25,41,44,43,39,NULL); this->GenerateFaceProject(26,40,18,42,44,NULL); this->GenerateFaceProject(27,33,14,40,41,locator); // this->SetFaceScalars(27,0); this->GenerateFaceProject(28,36,17,42,43,locator); // this->SetFaceScalars(28,0); // generate the solid mesh for first bounding box FaceArray[0] = 25; FaceArray[1] = 6; FaceArray[2] = 22; FaceArray[3] = 26; FaceArray[4] = 27; FaceArray[5] = 28; this->GenerateSolidMesh(5,FaceArray); // block 6 // edge 45 this->GenerateUnknownEdgeFromPoints(45, innerpoints->GetPoint(3), this->EdgePolyData[21]->GetPoint(0)); this->EdgeSubdivideProject(45, this->MeshSeed[4],locator); this->SetEdgeScalars(45, 1); // edge 46 this->GenerateUnknownEdge(46, 40, 45, 0); this->EdgeSubdivideProject(46, this->MeshSeed[1],locator); this->SetEdgeScalars(46, 1); // edge 47 this->GenerateUnknownEdgeFromPoints(47, innerpoints->GetPoint(7), this->EdgePolyData[24]->GetPoint(0)); this->EdgeSubdivideProject(47, this->MeshSeed[4],locator); this->SetEdgeScalars(47, 1); // edge 48 this->GenerateUnknownEdge(48, 42, 47, 0); this->EdgeSubdivideProject(48, this->MeshSeed[1],locator); this->SetEdgeScalars(48, 1); // edge 49 this->GenerateUnknownEdge(49, 45, 47, 0); this->EdgeSubdivideProject(49, this->MeshSeed[2],NULL); this->SetEdgeScalars(49, 1); // face this->GenerateFaceProject(29,46,49,48,44,NULL); this->GenerateFaceProject(30,45,26,47,49,NULL); this->GenerateFaceProject(31,40,22,45,46,locator); // this->SetFaceScalars(31,0); this->GenerateFaceProject(32,42,25,47,48,locator); // this->SetFaceScalars(32,0); // generate the solid mesh for first bounding box FaceArray[0] = 29; FaceArray[1] = 11; FaceArray[2] = 26; FaceArray[3] = 30; FaceArray[4] = 31; FaceArray[5] = 32; this->GenerateSolidMesh(6,FaceArray); // block 7 // edge 50 this->GenerateUnknownEdge(50, 45, 32, 0); this->EdgeSubdivideProject(50, this->MeshSeed[3],locator); this->SetEdgeScalars(50, 1); // edge 51 this->GenerateUnknownEdge(51, 47, 35, 0); this->EdgeSubdivideProject(51, this->MeshSeed[3],locator); this->SetEdgeScalars(51, 1); // face this->GenerateFaceProject(33,50,38,51,49,NULL); this->GenerateFaceProject(34,45,29,32,50,locator); // this->SetFaceScalars(34,0); this->GenerateFaceProject(35,47,31,35,51,locator); // this->SetFaceScalars(35,0); // generate the solid mesh for first bounding box FaceArray[0] = 33; FaceArray[1] = 16; FaceArray[2] = 30; FaceArray[3] = 21; FaceArray[4] = 34; FaceArray[5] = 35; this->GenerateSolidMesh(7,FaceArray); // block 8 // reverse the edges direction 14,17,22,25 this->ReverseEdgeDirection(41); this->ReverseEdgeDirection(43); this->ReverseEdgeDirection(46); this->ReverseEdgeDirection(48); // generate 4 new faces required this->GenerateFaceProject(36,46,44,48,49,NULL); this->GenerateFaceProject(37,41,39,43,44,NULL); this->GenerateFaceProject(38,50,34,41,46,locator); // this->SetFaceScalars(38,0); this->GenerateFaceProject(39,51,37,43,48,locator); // this->SetFaceScalars(39,0); // generate the solid mesh for the center FaceArray[0] = 36; FaceArray[1] = 20; FaceArray[2] = 33; FaceArray[3] = 37; FaceArray[4] = 38; FaceArray[5] = 39; this->GenerateSolidMesh(8,FaceArray); // final unstructured grid this->MergeSGridToUGrid(source); innerpoints->Delete(); return 1; } //---------------------------------------------------------------------------- int vtkMimxCylindricalMesh::FillInputPortInformation(int port, vtkInformation *info) { if(port < 5) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkPolyData"); } else info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkUnstructuredGrid"); return 1; } //---------------------------------------------------------------------------- //int vtkCylindricalMesh::SetSuperiorDividingPoints(vtkPoints *Points) //{ // if(Points->GetNumberOfPoints() != 4) // { // return 0; // } // this->SuperiorDividingPoints->SetNumberOfPoints(4); // this->SuperiorDividingPoints->DeepCopy(Points); // double x[3]; // this->Center[0] = 0; this->Center[1] = 0; this->Center[2] = 0; // for(int i=0; i <4; i++) // { // this->SuperiorDividingPoints->GetPoint(i,x); // for(int j=0; j<3; j++) // { // this->Center[j] = this->Center[j] + x[j]; // } // // } // for(int j=0; j<3; j++) // { // this->Center[j] = this->Center[j]/4; // } // return 1; //} ////---------------------------------------------------------------------------- //int vtkCylindricalMesh::SetInferiorDividingPoints(vtkPoints *Points) //{ // if(Points->GetNumberOfPoints() != 4) // { // return 0; // } // this->InferiorDividingPoints->SetNumberOfPoints(4); // this->InferiorDividingPoints->DeepCopy(Points); // double x[3]; // this->Center[0] = 0; this->Center[1] = 0; this->Center[2] = 0; // for(int i=0; i <4; i++) // { // this->InferiorDividingPoints->GetPoint(i,x); // for(int j=0; j<3; j++) // { // this->Center[j] = this->Center[j] + x[j]; // } // // } // for(int j=0; j<3; j++) // { // this->Center[j] = this->Center[j]/4; // } // return 1; //} //----------------------------------------------------------------------- //int vtkCylindricalMesh::SetMeshSeed(int MSeed[5]) //{ // for(int i=0; i<5; i++) // { // this->MeshSeed[i] = MSeed[i]; // } // return 1; //} void vtkMimxCylindricalMesh::SetCenter(double X[3]) { for(int i=0; i<3; i++) this->Center[i] = X[i]; } //---------------------------------------------------------------------------- void vtkMimxCylindricalMesh::EdgeSubdivideProject(int EdgeNum, int NumDiv, vtkCellLocator *Locator) { vtkCellArray *cellarray = vtkCellArray::New(); for (int i=0; i < this->EdgePolyData[EdgeNum]->GetNumberOfPoints()-1; i++) { cellarray->InsertNextCell(2); cellarray->InsertCellPoint(i); cellarray->InsertCellPoint(i+1); } this->EdgePolyData[EdgeNum]->SetLines(cellarray); cellarray->Delete(); //vtkPolyDataWriter *writer1 = vtkPolyDataWriter::New(); //writer1->SetInput(this->EdgePolyData[EdgeNum]); //writer1->SetFileName("Edge1.vtk"); //writer1->Write(); //writer1->Delete(); vtkMimxSubdivideCurve *subdividecurve = vtkMimxSubdivideCurve::New(); subdividecurve->SetInput(this->EdgePolyData[EdgeNum]); subdividecurve->SetNumberOfDivisions(NumDiv); subdividecurve->Update(); this->EdgePolyData[EdgeNum]->GetPoints()->Initialize(); this->EdgePolyData[EdgeNum]->GetPoints()->DeepCopy(subdividecurve->GetOutput()->GetPoints()); this->EdgePolyData[EdgeNum]->DeepCopy(subdividecurve->GetOutput()); subdividecurve->Delete(); //vtkPolyDataWriter *writer = vtkPolyDataWriter::New(); //writer->SetInput(this->EdgePolyData[EdgeNum]); //writer->SetFileName("Edge.vtk"); //writer->Write(); //writer->Delete(); if(Locator) { this->ClosestPointProjection(this->EdgePolyData[EdgeNum]->GetPoints(),Locator); } } //---------------------------------------------------------------------------- void vtkMimxCylindricalMesh::GenerateUnknownEdge(int EdgeNum, int FirstEdge, int SecondEdge, int BeginOrEnd) { vtkPoints *points = vtkPoints::New(); points->SetNumberOfPoints(2); if(!BeginOrEnd) { double x[3], y[3]; this->EdgePolyData[FirstEdge]->GetPoint(0,x); this->EdgePolyData[SecondEdge]->GetPoint(0,y); points->SetPoint(0,this->EdgePolyData[FirstEdge]->GetPoint(0)); points->SetPoint(1,this->EdgePolyData[SecondEdge]->GetPoint(0)); } else { points->SetPoint(0,this->EdgePolyData[FirstEdge]->GetPoint (this->EdgePolyData[FirstEdge]->GetNumberOfPoints()-1)); points->SetPoint(1,this->EdgePolyData[SecondEdge]->GetPoint (this->EdgePolyData[SecondEdge]->GetNumberOfPoints()-1)); } this->EdgePolyData[EdgeNum]->SetPoints(points); points->Delete(); } //---------------------------------------------------------------------------- void vtkMimxCylindricalMesh::GenerateFaceProject(int FaceNum,int Edge0, int Edge1, int Edge2, int Edge3, vtkCellLocator* Locator) { vtkMimxEdgeToPlanarStructuredGrid *edgetostructgrid = vtkMimxEdgeToPlanarStructuredGrid::New(); int dim[2]; dim[0] = this->EdgePolyData[Edge0]->GetNumberOfPoints(); dim[1] = this->EdgePolyData[Edge1]->GetNumberOfPoints(); //int dim0 = this->EdgePolyData[Edge2]->GetNumberOfPoints(); //int dim1 = this->EdgePolyData[Edge3]->GetNumberOfPoints(); edgetostructgrid->SetDimensions(dim); edgetostructgrid->SetEdge(0,this->EdgePolyData[Edge0]); edgetostructgrid->SetEdge(1,this->EdgePolyData[Edge1]); edgetostructgrid->SetEdge(2,this->EdgePolyData[Edge2]); edgetostructgrid->SetEdge(3,this->EdgePolyData[Edge3]); // edgetostructgrid->SetOutput(this->StructuredPlanarGrid[FaceNum]); edgetostructgrid->Update(); if(Locator) { this->ClosestPointProjection(edgetostructgrid->GetOutput()->GetPoints(),Locator); } vtkPoints *points = vtkPoints::New(); points->SetNumberOfPoints(edgetostructgrid->GetOutput()->GetNumberOfPoints()); double x[3]; for(int i=0; i<edgetostructgrid->GetOutput()->GetNumberOfPoints(); i++) { edgetostructgrid->GetOutput()->GetPoint(i,x); points->SetPoint(i,x); } this->StructuredPlanarGrid[FaceNum]->SetDimensions (edgetostructgrid->GetOutput()->GetDimensions()); this->StructuredPlanarGrid[FaceNum]->SetPoints(points); this->StructuredPlanarGrid[FaceNum]->GetPointData()->SetScalars( edgetostructgrid->GetOutput()->GetPointData()->GetScalars()); //vtkStructuredGridWriter* writer = vtkStructuredGridWriter::New(); //writer->SetInput(this->StructuredPlanarGrid[FaceNum]); //writer->SetFileName("sgrid.vtk"); //writer->Write(); points->Delete(); edgetostructgrid->Delete(); } //---------------------------------------------------------------------------------- void vtkMimxCylindricalMesh::SetSource(vtkPolyData* Polydata) { this->SetInput(4, Polydata); } //----------------------------------------------------------------------------------- void vtkMimxCylindricalMesh::SetCurve(int CurveNum, vtkPolyData* Polydata) { this->SetInput(CurveNum, Polydata); } //----------------------------------------------------------------------------------- void vtkMimxCylindricalMesh::SetBoundingBox(vtkUnstructuredGrid *BoundingBox) { this->SetInput(5, BoundingBox); } //------------------------------------------------------------------------------------ void vtkMimxCylindricalMesh::ClosestPointProjection(vtkPoints *Points, vtkCellLocator *Locator) { double dist,ClosestPoint[3],x[3]; vtkIdType CellId; int SubId; for(int i=0; i<Points->GetNumberOfPoints(); i++) { Points->GetPoint(i,x); Locator->FindClosestPoint(x,ClosestPoint,CellId,SubId,dist); Points->SetPoint(i,ClosestPoint); }} //---------------------------------------------------------------------------- void vtkMimxCylindricalMesh::GenerateSolidMesh(int BoxNum, int FaceArray[6]) { vtkMimxStructuredPlanarToStructuredSolidGrid *sgrid = vtkMimxStructuredPlanarToStructuredSolidGrid::New(); sgrid->SetOutput(this->StructuredSolidGrid[BoxNum]); for(int i=0; i<6; i++) { sgrid->SetInput(i,this->StructuredPlanarGrid[FaceArray[i]]); } sgrid->Update(); vtkPoints *points = vtkPoints::New(); double x[3]; points->SetNumberOfPoints(sgrid->GetOutput()->GetNumberOfPoints()); for(int i=0; i<sgrid->GetOutput()->GetNumberOfPoints(); i++) { sgrid->GetOutput()->GetPoint(i,x); points->SetPoint(i,x); } this->StructuredSolidGrid[BoxNum]->SetDimensions( sgrid->GetOutput()->GetDimensions()); this->StructuredSolidGrid[BoxNum]->SetPoints(points); points->Delete(); //vtkStructuredGridWriter* writer = vtkStructuredGridWriter::New(); //writer->SetInput(this->StructuredSolidGrid[BoxNum]); //writer->SetFileName("sgrid.vtk"); //writer->Write(); sgrid->Delete(); } //------------------------------------------------------------------------------ //void vtkCylindricalMesh::DivideCurve(int CurveNum, vtkPolyData *PolyData) //{ // find 4 points of intersection of the plane with the input curves // vtkPoints *pointsstore = vtkPoints::New(); // pointsstore->SetNumberOfPoints(5); // vtkIntArray *lineid = vtkIntArray::New(); // lineid->SetNumberOfValues(5); // to store the curve numbers for the final mesh // vtkIntArray *curveid = vtkIntArray::New(); // curveid->SetNumberOfValues(4); // vtkPoints *pdatapoints[4]; // // for(int i=0; i<4; i++) // { // pdatapoints[i] = vtkPoints::New(); // pdatapoints[i]->SetNumberOfPoints(0); // } // // for(int i=0; i < 4; i++) // { // cutting plane definition // double x[3], t; // this->SuperiorDividingPoints->GetPoint(i,x); // double normal[3]; // normal[1] = 0.0; // calculate normal of the plane // double theta; // if(x[0] <= this->Center[0] && x[2] <= this->Center[2]) // { // theta = acos(fabs(this->Center[2] - x[2])/sqrt( // pow(x[0]-Center[0],2.0)+pow(x[2]-Center[2],2.0))); // theta += 3.1416; // } // else // { // if(x[0] <= this->Center[0] && x[2] >= this->Center[2]) // { // theta = acos((x[2] - this->Center[2])/sqrt( // pow(x[0]-Center[0],2.0)+pow(x[2]-Center[2],2.0))); // theta = 2.0*3.1416 - theta; // } // else // { // theta = acos((x[2] - this->Center[2])/sqrt( // pow(x[0]-Center[0],2.0)+pow(x[2]-Center[2],2.0))); // } // } // determine to which quadrant plane belongs // quadrant 2 ///* if(x[0] >= this->Center[0] && x[2] <=this->Center[2]) // { // // }*/ // theta = theta + 3.1416/2.0; // normal[2] = cos(theta); // normal[0] = sin(theta); // to store two possible intersection points and the line id on which // the point lies // vtkIdType lineid1, lineid2; // double intpoint1[3], intpoint2[3]; // check which line segment intersects // first intersection point // for(int j=0; j < PolyData->GetNumberOfPoints(); j++) // { // double pt1[3], pt2[3]; // PolyData->GetPoint(j,pt1); // PolyData->GetPoint(j+1,pt2); // if(vtkPlane::IntersectWithLine(pt1,pt2,normal,this->Center,t,intpoint1)) // { // lineid1 = j; // break; // } // } // second intersection point // for(int j= lineid1+1; j < PolyData->GetNumberOfPoints(); j++) // { // if(j == PolyData->GetNumberOfPoints()-1) // { // double pt1[3], pt2[3]; // PolyData->GetPoint(j,pt1); // PolyData->GetPoint(0,pt2); // if(vtkPlane::IntersectWithLine(pt1,pt2,normal,this->Center,t,intpoint2)) // { // lineid2 = j; // break; // } // } // else // { // double pt1[3], pt2[3]; // PolyData->GetPoint(j,pt1); // PolyData->GetPoint(j+1,pt2); // if(vtkPlane::IntersectWithLine(pt1,pt2,normal,this->Center,t,intpoint2)) // { // lineid2 = j; // break; // } // } // } // closest point is the actual point of intersection // double distance1 = sqrt(pow(x[0] - intpoint1[0],2.0) + // pow(x[2] - intpoint1[2],2.0)); // double distance2 = sqrt(pow(x[0] - intpoint2[0],2.0) + // pow(x[2] - intpoint2[2],2.0)); // // if(distance1 > distance2) // { // pointsstore->SetPoint(i,intpoint2); // lineid->SetValue(i,lineid2); // } // else // { // pointsstore->SetPoint(i,intpoint1); // lineid->SetValue(i,lineid1); // } // } // // pointsstore->InsertPoint(4,pointsstore->GetPoint(0)); // lineid->SetValue(4,lineid->GetValue(0)); // if(CurveNum == 0) // {curveid->SetValue(0,7); curveid->SetValue(1,17); // curveid->SetValue(2,25); curveid->SetValue(3,31);} // if(CurveNum == 1) // {curveid->SetValue(0,5); curveid->SetValue(1,15); // curveid->SetValue(2,23); curveid->SetValue(3,30);} // if(CurveNum == 2) // {curveid->SetValue(0,3); curveid->SetValue(1,14); // curveid->SetValue(2,22); curveid->SetValue(3,29);} // if(CurveNum == 3) // {curveid->SetValue(0,1); curveid->SetValue(1,12); // curveid->SetValue(2,20); curveid->SetValue(3,28);} // // for(int i=0; i<4; i++) // { // // line could contain a part of end of original trace // int pt1 = lineid->GetValue(i); int pt2 = lineid->GetValue(i+1); // if(lineid->GetValue(i) > lineid->GetValue(i+1)) // { // pdatapoints[i] = vtkPoints::New(); // pdatapoints[i]->SetNumberOfPoints(1); // pdatapoints[i]->SetPoint(0,pointsstore->GetPoint(i)); // for(int j = lineid->GetValue(i)+1; // j < PolyData->GetNumberOfPoints(); j++) // { // pdatapoints[i]->InsertPoint( // pdatapoints[i]->GetNumberOfPoints(),PolyData->GetPoint(j)); // } // for(int j=0; j <= lineid->GetValue(i+1); j++) // { // pdatapoints[i]->InsertPoint( // pdatapoints[i]->GetNumberOfPoints(),PolyData->GetPoint(j)); // } // pdatapoints[i]->InsertPoint(pdatapoints[i]->GetNumberOfPoints(), // pointsstore->GetPoint(i+1)); // } // else // { // pdatapoints[i]->SetPoint(0,pointsstore->GetPoint(i)); // for(int j = lineid->GetValue(i)+1; j<= lineid->GetValue(i+1); j++) // { // pdatapoints[i]->InsertPoint( // pdatapoints[i]->GetNumberOfPoints(),PolyData->GetPoint(j)); // } // pdatapoints[i]->InsertPoint(pdatapoints[i]->GetNumberOfPoints(), // pointsstore->GetPoint(i+1)); // } // //// //cout <<" Curve "<<i<<endl; // //for(int j=0; j<pdatapoints[i]->GetNumberOfPoints(); j++) // //{ // // double x[3]; // // pdatapoints[i]->GetPoint(j,x); // // // //cout<<j<<" "<<x[0]<<" "<<x[1]<<" "<<x[2]<<endl; // //} // } ///**********/ // double length = this->MeasureCurveLength(PolyData, 1); // // divide the length to four parts // length = length/4.0; // // calculate the dividing points // double startingpoint[3], currentlength; // int startingpointnum; // for (int i=0; i < 4; i++) { // if(i =0) // { // PolyData->GetPoint(0, startingpoint); // startingpointnum = 1; // } // currentlength = 0.0; // while (currentlength < length) { // pdatapoints[i]->InsertNextPoint(startingpoint); // if(pdatapoints[i]->GetNumberOfPoints() >1) // { // currentlength = MeasureCurveLength(pdatapoints[i], 0) // + sqrt(vtkMath::Distance2BetweenPoints( // pdatapoints->GetPoint(pdatapoints[i]->GetNumberOfPoints()-1), // PolyData->GetPoint(startingpointnum))); // // if the length of the curve being constructed is less than the // // prescribed length // if(currentlength < length) // { // pdatapoints[i]->InsertNextPoint(PolyData->GetPoint(startingpointnum)); // startingpointnum ++; // } // else{// interpolate the line and divide // double nextpoint[3], prevpoint[3]; // PolyData->GetPoint(startingpointnum, nextpoint); // pdatapoints[i]->GetPoint( // pdatapoints[i]->GetNumberOfPoints()-1,prevpoint); // for (int k=0; k <3; k++) { // startingpoint[k] = prevpoint[k] + // } // } // } // } // } // vtkPolyData *polydatastore = vtkPolyData::New(); // polydatastore->DeepCopy(PolyData); // polydatastore->GetPoints()->InsertNextPoint(polydatastore->GetPoint(0)); // vtkSubdivideCurve *subdivide = vtkSubdivideCurve::New(); // subdivide->SetInput(polydatastore); // subdivide->SetNumberOfDivisions(2*(this->MeshSeed[1] + this->MeshSeed[3])); // subdivide->Update(); // int dim[4]; // dim[0] = this->MeshSeed[1]; dim[2] = this->MeshSeed[1]; // dim[1] = this->MeshSeed[3]; dim[3] = this->MeshSeed[3]; // // set the divided line to the four curves // int pointnum = 1; // for (int i=0; i <4; i++) { // pointnum --; // for (int j=0; j<=dim[i]; j++) { // pdatapoints[i]->InsertPoint(pdatapoints[i]->GetNumberOfPoints(), // subdivide->GetOutput()->GetPoint(pointnum)); // pointnum++; // } // } // polydatastore->Delete(); // subdivide->Delete(); ///**********/ // // for(int j = 0; j < 4; j++) // { // this->EdgePolyData[curveid->GetValue(j)]->SetPoints(pdatapoints[j]); // pdatapoints[j]->Delete(); // } // pointsstore->Delete(); // lineid->Delete(); // curveid->Delete(); //} void vtkMimxCylindricalMesh::DivideCurve(int CurveNum, vtkPolyData *PolyData, vtkUnstructuredGrid *UGrid) { // find 4 points of intersection of the plane with the input curves vtkPoints *pointsstore = vtkPoints::New(); pointsstore->SetNumberOfPoints(5); vtkIntArray *lineid = vtkIntArray::New(); lineid->SetNumberOfValues(5); // to store the curve numbers for the final mesh vtkIntArray *curveid = vtkIntArray::New(); curveid->SetNumberOfValues(4); vtkPoints *pdatapoints[4]; for(int i=0; i<4; i++) { pdatapoints[i] = vtkPoints::New(); pdatapoints[i]->SetNumberOfPoints(1); } vtkCellLocator *locator = vtkCellLocator::New(); locator->SetDataSet(PolyData); locator->BuildLocator(); int startnodenum; if(CurveNum == 0) startnodenum = 16; if(CurveNum == 1) startnodenum = 12; if(CurveNum == 2) startnodenum = 4; if(CurveNum == 3) startnodenum = 0; for(int i=startnodenum; i < startnodenum+4; i++) { // cutting plane definition //double x[3], t; //if (CurveNum < 2) { // this->SuperiorDividingPoints->GetPoint(i,x); //} //else //{ // this->InferiorDividingPoints->GetPoint(i,x); //} /* double normal[3]; switch (i) { case 0: this->Plane1->GetCenter(x); this->Plane1->GetNormal(normal); break; case 1: this->Plane2->GetCenter(x); this->Plane2->GetNormal(normal); break; case 2: this->Plane3->GetCenter(x); this->Plane3->GetNormal(normal); break; case 3: this->Plane4->GetCenter(x); this->Plane4->GetNormal(normal); break; }*/ /* if(CurveNum == 2 || CurveNum == 3) { for (int k=0; k<3; k++) { x[k] = x[k] + InfCenter[k] - SupCenter[k]; } } */ //normal[1] = 0.0; //// calculate normal of the plane //double theta; //if(x[0] <= this->Center[0] && x[2] <= this->Center[2]) //{ // theta = acos(fabs(this->Center[2] - x[2])/sqrt( // pow(x[0]-Center[0],2.0)+pow(x[2]-Center[2],2.0))); // theta += 3.1416; //} //else //{ // if(x[0] <= this->Center[0] && x[2] >= this->Center[2]) // { // theta = acos((x[2] - this->Center[2])/sqrt( // pow(x[0]-Center[0],2.0)+pow(x[2]-Center[2],2.0))); // theta = 2.0*3.1416 - theta; // } // else // { // theta = acos((x[2] - this->Center[2])/sqrt( // pow(x[0]-Center[0],2.0)+pow(x[2]-Center[2],2.0))); // } //} //// determine to which quadrant plane belongs //// quadrant 2 ///* if(x[0] >= this->Center[0] && x[2] <=this->Center[2]) //{ //}*/ //theta = theta + 3.1416/2.0; //normal[2] = cos(theta); //normal[0] = sin(theta); // to store two possible intersection points and the line id on which // the point lies vtkIdType cellid; int subid; double closestpoint[3], distance; locator->FindClosestPoint(UGrid->GetPoint(i),closestpoint, cellid, subid, distance); // check which line segment intersects // first intersection point //for(int j=0; j < PolyData->GetNumberOfPoints(); j++) //{ // double pt1[3], pt2[3]; // PolyData->GetPoint(j,pt1); // PolyData->GetPoint(j+1,pt2); // if(vtkPlane::IntersectWithLine(pt1,pt2,normal,x,t,intpoint1)) // { // lineid1 = j; // break; // } //} // second intersection point /* for(int j= lineid1+1; j < PolyData->GetNumberOfPoints(); j++) { if(j == PolyData->GetNumberOfPoints()-1) { double pt1[3], pt2[3]; PolyData->GetPoint(j,pt1); PolyData->GetPoint(0,pt2); if(vtkPlane::IntersectWithLine(pt1,pt2,normal,x,t,intpoint2)) { lineid2 = j; break; } } else { double pt1[3], pt2[3]; PolyData->GetPoint(j,pt1); PolyData->GetPoint(j+1,pt2); if(vtkPlane::IntersectWithLine(pt1,pt2,normal,x,t,intpoint2)) { lineid2 = j; break; } } } */ // closest point is the actual point of intersection //double distance1 = sqrt(pow(x[0] - intpoint1[0],2.0) + // pow(x[2] - intpoint1[2],2.0)); //double distance2 = sqrt(pow(x[0] - intpoint2[0],2.0) + // pow(x[2] - intpoint2[2],2.0)); //if(distance1 > distance2) //{ // pointsstore->SetPoint(i,intpoint2); // lineid->SetValue(i,lineid2); //} //else //{ // pointsstore->SetPoint(i,intpoint1); // lineid->SetValue(i,lineid1); //} pointsstore->SetPoint(i-startnodenum, closestpoint); lineid->SetValue(i-startnodenum, cellid); } locator->Delete(); pointsstore->InsertPoint(4,pointsstore->GetPoint(0)); lineid->SetValue(4,lineid->GetValue(0)); if(CurveNum == 0) {curveid->SetValue(0,7); curveid->SetValue(1,17); curveid->SetValue(2,25); curveid->SetValue(3,31);} if(CurveNum == 1) {curveid->SetValue(0,5); curveid->SetValue(1,15); curveid->SetValue(2,23); curveid->SetValue(3,30);} if(CurveNum == 2) {curveid->SetValue(0,3); curveid->SetValue(1,14); curveid->SetValue(2,22); curveid->SetValue(3,29);} if(CurveNum == 3) {curveid->SetValue(0,1); curveid->SetValue(1,12); curveid->SetValue(2,20); curveid->SetValue(3,28);} for(int i=0; i<4; i++) { vtkPointLocator *pointlocator = vtkPointLocator::New(); // line could contain a part of end of original trace //int pt1 = lineid->GetValue(i); int pt2 = lineid->GetValue(i+1); vtkIdType pointid; pdatapoints[i] = vtkPoints::New(); pdatapoints[i]->Allocate(100); pointlocator->InitPointInsertion(pdatapoints[i],PolyData->GetPoints()->GetBounds()); if(lineid->GetValue(i) > lineid->GetValue(i+1)) { pointlocator->InsertUniquePoint(pointsstore->GetPoint(i),pointid); // pdatapoints[i]->SetPoint(0,pointsstore->GetPoint(i)); for(int j = lineid->GetValue(i)+1; j < PolyData->GetNumberOfPoints(); j++) { pointlocator->InsertUniquePoint(PolyData->GetPoint(j),pointid); // pdatapoints[i]->InsertPoint( // pdatapoints[i]->GetNumberOfPoints(),PolyData->GetPoint(j)); } for(int j=0; j <= lineid->GetValue(i+1); j++) { pointlocator->InsertUniquePoint(PolyData->GetPoint(j),pointid); // pdatapoints[i]->InsertPoint( // pdatapoints[i]->GetNumberOfPoints(),PolyData->GetPoint(j)); } pointlocator->InsertUniquePoint(pointsstore->GetPoint(i+1),pointid); // pdatapoints[i]->InsertPoint(pdatapoints[i]->GetNumberOfPoints(), // pointsstore->GetPoint(i+1)); } else { pointlocator->InsertUniquePoint(pointsstore->GetPoint(i),pointid); // pdatapoints[i]->SetPoint(0,pointsstore->GetPoint(i)); for(int j = lineid->GetValue(i)+1; j<= lineid->GetValue(i+1); j++) { pointlocator->InsertUniquePoint(PolyData->GetPoint(j),pointid); // pdatapoints[i]->InsertPoint( // pdatapoints[i]->GetNumberOfPoints(),PolyData->GetPoint(j)); } pointlocator->InsertUniquePoint(pointsstore->GetPoint(i+1),pointid); // pdatapoints[i]->InsertPoint(pdatapoints[i]->GetNumberOfPoints(), // pointsstore->GetPoint(i+1)); } cout <<" Curve "<<i<<endl; for(int j=0; j<pdatapoints[i]->GetNumberOfPoints(); j++) { double x[3]; pdatapoints[i]->GetPoint(j,x); cout<<j<<" "<<x[0]<<" "<<x[1]<<" "<<x[2]<<endl; } pointlocator->Delete(); } for(int j = 0; j < 4; j++) { this->EdgePolyData[curveid->GetValue(j)]->SetPoints(pdatapoints[j]); pdatapoints[j]->Delete(); } pointsstore->Delete(); lineid->Delete(); curveid->Delete(); } //------------------------------------------------------------------------------ void vtkMimxCylindricalMesh::ReverseEdgeDirection(int EdgeNum) { vtkPoints *points = vtkPoints::New(); points->SetNumberOfPoints(this->EdgePolyData[EdgeNum] ->GetNumberOfPoints()); for(int i=1; i<=this->EdgePolyData[EdgeNum]->GetNumberOfPoints(); i++) { points->SetPoint(i-1, this->EdgePolyData[EdgeNum]->GetPoint( this->EdgePolyData[EdgeNum]->GetNumberOfPoints()-i)); } this->EdgePolyData[EdgeNum]->SetPoints(points); points->Delete(); } //------------------------------------------------------------------------------ void vtkMimxCylindricalMesh::MergeSGridToUGrid(vtkPolyData *source) { vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast(this->GetOutputDataObject(0)); //int numele = 0; //int numnodes = 0; //int dim[3]; //vtkCell* cell; //// calculate number of nodes and elements //for(int i=0; i < 9; i++) //{ // this->StructuredSolidGrid[i]->GetDimensions(dim); // numnodes = numnodes + dim[0]*dim[1]*dim[2]; // numele = numele + (dim[0]-1)*(dim[1]-1)*(dim[2]-1); //} //vtkMergeCells* mergecells = vtkMergeCells::New(); //mergecells->SetUnstructuredGrid(output); //mergecells->MergeDuplicatePointsOn(); //mergecells->SetTotalNumberOfDataSets(9); //mergecells->SetTotalNumberOfCells(numele); //mergecells->SetTotalNumberOfPoints(numnodes); //for(int i = 0; i < 9; i++) //{ // mergecells->MergeDataSet(this->StructuredSolidGrid[i]); //} //vtkIdType max_val = 0; //for(int i=0; i < output->GetNumberOfCells(); i++) //{ // cell = output->GetCell(i); // vtkIdList* idlist = cell->GetPointIds(); // for(int j=0; j <8; j++) // { // vtkIdType val = idlist->GetId(j); // if(val > max_val) max_val = val; // } //} //output->GetPoints()->Squeeze(); //output->GetPoints()->SetNumberOfPoints(max_val+1); int dim[3], m; int numele = 0; int numnode = 0; int i, j, k; for(i=0; i <9; i++) { this->StructuredSolidGrid[i]->GetDimensions(dim); numele = numele + (dim[0]-1)*(dim[1]-1)*(dim[2]-1); numnode = numnode + dim[0]*dim[1]*dim[2]; } // start with the other bounding boxes // check if a dataset contains coincident points vtkPointLocator *globallocator = vtkPointLocator::New(); vtkPoints *globalpoints = vtkPoints::New(); globalpoints->Allocate(numnode); output->Allocate(numele); globallocator->InitPointInsertion(globalpoints, source->GetBounds()); vtkIntArray *intarray = vtkIntArray::New(); intarray->SetNumberOfComponents(1); int startnodenum; for(m=0; m < 9; m++) { vtkPoints* sgridpoints = this->StructuredSolidGrid[m]->GetPoints(); this->StructuredSolidGrid[m]->GetDimensions(dim); // create the global point id list for the individual points in the data set // and insert unique points belonging to different data sets vtkIdList *poirenum = vtkIdList::New(); startnodenum = globalpoints->GetNumberOfPoints(); for (i=0; i < sgridpoints->GetNumberOfPoints(); i++) { // if point does not exist if(globallocator->IsInsertedPoint(sgridpoints->GetPoint(i)) == -1) { poirenum->InsertNextId(globalpoints->GetNumberOfPoints()); globallocator->InsertNextPoint(sgridpoints->GetPoint(i)); double status[1]; this->StructuredSolidGrid[m]->GetPointData()->GetScalars()->GetTuple(i,status); intarray->InsertNextTuple1(status[0]); } else { // if the point belongs to different data set if(globallocator->IsInsertedPoint(sgridpoints->GetPoint(i)) < startnodenum) { poirenum->InsertNextId(globallocator->IsInsertedPoint(sgridpoints->GetPoint(i))); } else{ poirenum->InsertNextId(globalpoints->GetNumberOfPoints()); globallocator->InsertNextPoint(sgridpoints->GetPoint(i)); double status[1]; this->StructuredSolidGrid[m]->GetPointData()->GetScalars()->GetTuple(i,status); intarray->InsertNextTuple1(status[0]); } } } // insert the element connectivity based on global point ids vtkIdList *ptids = vtkIdList::New(); for (k=0; k<dim[2]-1; k++) { for (j=0; j<dim[1]-1; j++) { for (i=0; i<dim[0]-1; i++) { ptids->Initialize(); ptids->SetNumberOfIds(8); ptids->SetId(0, poirenum->GetId(k*dim[1]*dim[0]+j*dim[0]+i)); ptids->SetId(1, poirenum->GetId(k*dim[1]*dim[0]+j*dim[0]+i+1)); ptids->SetId(2, poirenum->GetId(k*dim[1]*dim[0]+j*dim[0]+i + dim[0]+1)); ptids->SetId(3, poirenum->GetId(k*dim[1]*dim[0]+j*dim[0]+i + dim[0])); ptids->SetId(4, poirenum->GetId(k*dim[1]*dim[0]+j*dim[0]+i + dim[0]*dim[1])); ptids->SetId(5, poirenum->GetId(k*dim[1]*dim[0]+j*dim[0]+i+1 + dim[0]*dim[1])); ptids->SetId(6, poirenum->GetId(k*dim[1]*dim[0]+j*dim[0]+i + dim[0]+1 + dim[0]*dim[1])); ptids->SetId(7, poirenum->GetId(k*dim[1]*dim[0]+j*dim[0]+i + dim[0] + dim[0]*dim[1])); output->InsertNextCell(12, ptids); } } } ptids->Delete(); poirenum->Delete(); } output->GetPointData()->SetScalars(intarray); intarray->Delete(); output->SetPoints(globalpoints); output->Squeeze(); globalpoints->Delete(); globallocator->Delete(); } //------------------------------------------------------------------------------ double vtkMimxCylindricalMesh::MeasureCurveLength(vtkPolyData *PolyData, int CalculateClosedCurve) { double length = 0.0; for (int i=0; i < PolyData->GetNumberOfPoints()-1; i++) { length = length + sqrt(vtkMath::Distance2BetweenPoints(PolyData->GetPoint(i), PolyData->GetPoint(i+1))); } if(CalculateClosedCurve) { length = length + sqrt(vtkMath::Distance2BetweenPoints(PolyData->GetPoint(0), PolyData->GetPoint(PolyData->GetNumberOfPoints()-1))); } return length; } //------------------------------------------------------------------------------ void vtkMimxCylindricalMesh::SetEdgeScalars(int EdgeNum, int ScalarValue) { vtkIntArray *intarray = vtkIntArray::New(); intarray->SetNumberOfValues(this->EdgePolyData[EdgeNum]->GetNumberOfPoints()); for (int i=0; i < this->EdgePolyData[EdgeNum]->GetNumberOfPoints(); i++) { intarray->SetValue(i, ScalarValue); } this->EdgePolyData[EdgeNum]->GetPointData()->SetScalars(intarray); intarray->Delete(); } //------------------------------------------------------------------------------ void vtkMimxCylindricalMesh::GenerateUnknownEdgeFromPoints(int EdgeNum, double *FirstPoint, double *SecondPoint) { vtkPoints *points = vtkPoints::New(); points->SetNumberOfPoints(2); points->SetPoint(0,FirstPoint); points->SetPoint(1,SecondPoint); this->EdgePolyData[EdgeNum]->SetPoints(points); points->Delete(); } //------------------------------------------------------------------------------ void vtkMimxCylindricalMesh::SetFaceScalars(int FaceNum, int ScalarValue) { //vtkIntArray *intarray = vtkIntArray::New(); //intarray->SetNumberOfValues(this->EdgePolyData[EdgeNum]->GetNumberOfPoints()); for (int i=0; i < this->StructuredPlanarGrid[FaceNum]->GetNumberOfPoints(); i++) { double status[1]; this->StructuredPlanarGrid[FaceNum]->GetPointData()->GetScalars()-> GetTuple(i,status); if(status[0]) { status[0] = ScalarValue; this->StructuredPlanarGrid[FaceNum]->GetPointData()->GetScalars()-> SetTuple(i,status); } } //this->EdgePolyData[EdgeNum]->GetPointData()->SetScalars(intarray); //intarray->Delete(); } //------------------------------------------------------------------------------ void vtkMimxCylindricalMesh::CalculateCenter(vtkPolyData *curve) { this->Center[0] = 0.0; this->Center[1] = 0.0; this->Center[2] = 0.0; for (int i=0; i<curve->GetNumberOfPoints(); i++) { double x[3]; curve->GetPoint(i,x); for (int j=0; j<3; j++) { this->Center[j] = this->Center[j] + x[j]; } } for (int i=0; i<3; i++) { this->Center[i] = this->Center[i]/curve->GetNumberOfPoints(); } } //------------------------------------------------------------------------------ void vtkMimxCylindricalMesh::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); }
//hdu1242 /* BFS+优先队列写法 存入所有可走的点,最先弹出时间花费最少的点进行计算 */ #include<iostream> #include<cstring> #include<queue> using namespace std; char graph[205][205]; int visit[205][205]; int dir[4][2] = { { -1,0 },{ 1,0 },{ 0,-1 },{ 0,1 } }; int n, m; struct node { int x, y; int time; friend bool operator < (const node &a, const node &b) //时间小的先出队 { return a.time>b.time; } }; int Turn(int x, int y)//判断该点是否可走 { if (0 <= x && x<n && 0 <= y && y<m&&graph[x][y] != '#') return 1; return 0; } int bfs(int x, int y)//输入起始坐标 { int i; node cnt, next; priority_queue<node> que; //定义一个优先队列 memset(visit, 0, sizeof(visit)); cnt.x = x; cnt.y = y; cnt.time = 0; visit[cnt.x][cnt.y] = 1;//标记该点 que.push(cnt);//放入该点到优先队列 while (!que.empty())//队列不空 { cnt = que.top(); que.pop();//取出首个元素 if (graph[cnt.x][cnt.y] == 'r')//碰到了天使朋友 return cnt.time;//最短时间确定 for (i = 0; i<4; i++)//没碰到则移动 { next.x = cnt.x + dir[i][0]; next.y = cnt.y + dir[i][1]; if (Turn(next.x, next.y) && !visit[next.x][next.y]) {//判断该点是否可走,当前没有走过 visit[next.x][next.y] = 1;//标记为走过 if (graph[next.x][next.y] == 'x')//碰到守卫 next.time = cnt.time + 2; else next.time = cnt.time + 1; que.push(next);//放入该点 } } } return -1; } int main() { ios::sync_with_stdio(false); int i, j; int x, y, ans; while (cin>>n>>m) { for (i = 0; i<n; i++) cin>>graph[i]; for (i = 0; i<n; i++) for (j = 0; j<m; j++) if (graph[i][j] == 'a') { x = i; y = j;//保持天使所在位置 break; } ans = bfs(x, y); if (ans == -1)//出不来 cout<<"Poor ANGEL has to stay in the prison all his life."<<endl; else cout<<ans<<endl; } return 0; }
//////////////////////////////////////////////////////////////////////////////// // Pac-Man clone // // Copyright (c) 2021 Kwena Mashamaite (kwena.mashamaite1@gmail.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //////////////////////////////////////////////////////////////////////////////// #include "LoadingSceneView.h" #include <IME/ui/widgets/Label.h> #include <IME/ui/widgets/ProgressBar.h> #include <IME/ui/widgets/Picture.h> #include <IME/ui/widgets/Panel.h> namespace pm { /////////////////////////////////////////////////////////////// void LoadingSceneView::init(ime::ui::GuiContainer& gui) { using namespace ime::ui; auto pnlContainer = gui.addWidget<Panel>(Panel::create(), "pnlContainer"); pnlContainer->getRenderer()->setBackgroundColour(ime::Colour::Transparent); auto picLEngineLogo = pnlContainer->addWidget(Picture::create("IME_logo.png"), "picEngineLogo"); picLEngineLogo->setOrigin(0.5f, 0.0f); picLEngineLogo->setPosition("50%", "50%"); auto lblPoweredBy = Label::create("Powered by"); lblPoweredBy->getRenderer()->setTextStyle(ime::TextStyle::Italic); lblPoweredBy->setOrigin(0.5f, 1.0f); lblPoweredBy->setPosition("50%", ime::bindTop(picLEngineLogo)); pnlContainer->addWidget(std::move(lblPoweredBy), "lblPoweredBy"); auto pbrAssetLoading = pnlContainer->addWidget<ProgressBar>(ProgressBar::create("loading fonts..."), "pbrAssetLoading");; pbrAssetLoading->getRenderer()->setBorderColour({0, 230, 64, 135}); pbrAssetLoading->getRenderer()->setFillColour(ime::Colour("#4d05e8")); pbrAssetLoading->setOrigin(0.5f, 0.0f); pbrAssetLoading->setSize("80%", std::to_string(pbrAssetLoading->getSize().y)); pbrAssetLoading->setPosition("50%", "90%"); auto lblLoading = Label::create("Loading resources, please wait..."); lblLoading->setOrigin(0.5f, 1.0f); lblLoading->setPosition("50%", ime::bindTop(pbrAssetLoading)); pnlContainer->addWidget(std::move(lblLoading), "lblLoading"); } } // namespace pm
#ifndef _JH_HEADER_TOKEN_ #define _JH_HEADER_TOKEN_ namespace jh{ class Token{ public: enum class Type{ Literal_null = 1, //null Literal_bool_true, //true Literal_bool_false, //false Literal_int, //0, 1, 2, 54987, -45632 Literal_real, //2.5, 2., .2 /* vJass */ Literal_super, //super Literal_this, //this /* Jass */ Keyword_function, //function Keyword_endfunction, //endfunction Keyword_globals, //globals Keyword_endglobals, //endglobals Keyword_array, Keyword_takes, //takes Keyword_returns, //returns Keyword_local, //local Keyword_set, //set Keyword_call, //call Keyword_if, //if x Keyword_then, //then Keyword_else, //else Keyword_elseif, //elseif X Keyword_endif, //endif Keyword_loop, //loop Keyword_exitwhen, //exitwhen COND Keyword_endloop, //endloop Keyword_constant, //constant Keyword_return, //return Keyword_or, //or Keyword_and, //and Keyword_not, //not Keyword_extends, //extends Keyword_native, //native Keyword_type, //type /* vJass */ Keyword_debug, //debug Keyword_library, //library Keyword_endlibrary, //endlibrary Keyword_uses, //uses Keyword_requires, //requires Keyword_needs, //needs Keyword_initializer, //initializer Keyword_optional, //optional Keyword_scope, //scope Keyword_endscope, //endscope Keyword_struct, //struct Keyword_class, //class Keyword_endstruct, //endstruct Keyword_endclass, //endclass Keyword_method, //method Keyword_endmethod, //endmethod Keyword_operator, //method operator Keyword_static, //static Keyword_private, //private Keyword_public, //public Keyword_readonly, //readonly Keyword_temporary, //temporary Keyword_template, //template Keyword_alias, //alias Keyword_inline, //inline Keyword_deprecated, //deprecated Keyword_textmacro, //textmacro Keyword_runtextmacro, //runtextmacro Keyword_endtextmacro, //endtextmacro Keyword_module, //module Keyword_endmodule, //endmodule Keyword_external, //external Keyword_endexternal, //endexternal Keyword_externalblock, //externalblock Keyword_endexternalblock, //endexternalblock Keyword_interface, //interface Keyword_endinterface, //endinterface Keyword_defaults, //defaults Keyword_stub, //stub Keyword_sizeof, //sizeof(not implemented) Keyword_static_assert, //static_assert Keyword_compiletime, //compiletime Keyword_while, //while Keyword_endwhile, //endwhile Keyword_break, //break Keyword_for, //for Keyword_endfor, //endfor Keyword_implement, //implement Keyword_catch, //catch Keyword_thistype, //thistype Keyword_final, //final Keyword_hashif, //#if Keyword_hashelseif, //#elseif Keyword_hashelse, //#else Keyword_hashendif, //#endif Keyword_auto, //auto Keyword_override, //override Keyword_mutable, //mutable Keyword_endblock, //endblock Keyword_allocator, //allocator Keyword_endallocator, //endallocator Keyword_using, //using Keyword_hook, //hook Keyword_before, //before Keyword_after, //after Keyword_constructor, //constructor Keyword_endconstructor, //endconstructor Keyword_construct, //construct Keyword_destructor, //destructor Keyword_enddestructor, //enddestructor Keyword_import, //import Keyword_encrypted, //encrypted Keyword_priority, //priority Keyword_extendor, //extendor Keyword_endextendor, //endextendor Keyword_concept, //concept Keyword_endconcept, //endconcept /* Jass */ Operator_newline, //\n, \r\n, \r Operator_plus, //+ Operator_minus, //- Operator_multiply, //* Operator_divide, // / Operator_LPar, //( Operator_RPar, //) Operator_LBPar, //[ Operator_RBPar, //] Operator_assign, //= Operator_equal, //== Operator_notequal, //!= Operator_less, //< Operator_bigger, //> Operator_biggerequal, //>= Operator_lessequal, //<= Operator_rawcode, //' Operator_string, //" Operator_comma, //, /* vJass */ Operator_modulo, //% Operator_rshift, //>> Operator_lshift, //<< Operator_eqplus, //+= Operator_eqminus, //-= Operator_eqmultiply, //*= Operator_eqdivide, ///= Operator_eqmodulo, //%= Operator_eqrshift, //>>= Operator_eqlshift, //<<= Operator_increment, //++ Operator_decrement, //-- Operator_dComment, ///* block block block */ Operator_preprocessor, // //! Operator_LCPar, //{ Operator_RCPar, //} Operator_semi, //; Operator_dot, //. Operator_textmacroarg, //$ARG$ /* UNIVERSAL */ Id //any identifier that did not fit other type /* Tokens with 'length' set: Operator_preprocessor - up until next line Operator_rawcode - up until ending, the ending operator is not included Operator_string - up until ending, the ending operator is not included Id - the identifier's lenght in given string Operator_dComment - stores the length of the block. Operator_textmacroarg - stores the length of argument(text between 2 $) In all cases 'line' stores the line that opening of the token lies in. */ }type; //first position of token in the file, the last position //can be calculated as (position + raw.size() - 1) int position; //the length of raw value int length; //line given token is declared at //for Operator_newline, this is always the line that the '\n' is placed at int line; Token(Token::Type t, int pos, int lin, int len = 0) : type(t), length(len), position(pos), line(lin) { } }; } #endif //_JH_HEADER_TOKEN_
#include "Timer.hpp" #include <Windows.h> namespace gengine { namespace platform { Timer::Timer() { LARGE_INTEGER fq, start; QueryPerformanceFrequency(&fq); frequency = 1.0 / fq.QuadPart; QueryPerformanceCounter(&start); this->start = start.QuadPart; } void Timer::reset() { LARGE_INTEGER start; QueryPerformanceCounter(&start); this->start = start.QuadPart; } float Timer::elapsed() { LARGE_INTEGER current; QueryPerformanceCounter(&current); uint64_t cycles = current.QuadPart - this->start; return (float)(cycles * frequency); } }; }
// Copyright (c) 2017-2018 WEYCOIN developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/weycoin-config.h" #endif #include "utilitydialog.h" #include "ui_helpmessagedialog.h" #include "weycoingui.h" #include "clientmodel.h" #include "guiconstants.h" #include "intro.h" #include "paymentrequestplus.h" #include "guiutil.h" #include "clientversion.h" #include "init.h" #include "util.h" #include <stdio.h> #include <QCloseEvent> #include <QLabel> #include <QRegExp> #include <QTextTable> #include <QTextCursor> #include <QVBoxLayout> /** "Help message" or "About" dialog box */ HelpMessageDialog::HelpMessageDialog(QWidget *parent, bool about) : QDialog(parent), ui(new Ui::HelpMessageDialog) { ui->setupUi(this); QString version = tr(PACKAGE_NAME) + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()); /* On x86 add a bit specifier to the version so that users can distinguish between * 32 and 64 bit builds. On other architectures, 32/64 bit may be more ambiguous. */ #if defined(__x86_64__) version += " " + tr("(%1-bit)").arg(64); #elif defined(__i386__ ) version += " " + tr("(%1-bit)").arg(32); #endif if (about) { setWindowTitle(tr("About %1").arg(tr(PACKAGE_NAME))); /// HTML-format the license message from the core QString licenseInfo = QString::fromStdString(LicenseInfo()); QString licenseInfoHTML = licenseInfo; // Make URLs clickable QRegExp uri("<(.*)>", Qt::CaseSensitive, QRegExp::RegExp2); uri.setMinimal(true); // use non-greedy matching licenseInfoHTML.replace(uri, "<a href=\"\\1\">\\1</a>"); // Replace newlines with HTML breaks licenseInfoHTML.replace("\n", "<br>"); ui->aboutMessage->setTextFormat(Qt::RichText); ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); text = version + "\n" + licenseInfo; ui->aboutMessage->setText(version + "<br><br>" + licenseInfoHTML); ui->aboutMessage->setWordWrap(true); ui->helpMessage->setVisible(false); } else { setWindowTitle(tr("Command-line options")); QString header = tr("Usage:") + "\n" + " weycoin-qt [" + tr("command-line options") + "] " + "\n"; QTextCursor cursor(ui->helpMessage->document()); cursor.insertText(version); cursor.insertBlock(); cursor.insertText(header); cursor.insertBlock(); std::string strUsage = HelpMessage(HMM_WEYCOIN_QT); const bool showDebug = GetBoolArg("-help-debug", false); strUsage += HelpMessageGroup(tr("UI Options:").toStdString()); if (showDebug) { strUsage += HelpMessageOpt("-allowselfsignedrootcertificates", strprintf("Allow self signed root certificates (default: %u)", DEFAULT_SELFSIGNED_ROOTCERTS)); } strUsage += HelpMessageOpt("-choosedatadir", strprintf(tr("Choose data directory on startup (default: %u)").toStdString(), DEFAULT_CHOOSE_DATADIR)); strUsage += HelpMessageOpt("-lang=<lang>", tr("Set language, for example \"de_DE\" (default: system locale)").toStdString()); strUsage += HelpMessageOpt("-min", tr("Start minimized").toStdString()); strUsage += HelpMessageOpt("-rootcertificates=<file>", tr("Set SSL root certificates for payment request (default: -system-)").toStdString()); strUsage += HelpMessageOpt("-splash", strprintf(tr("Show splash screen on startup (default: %u)").toStdString(), DEFAULT_SPLASHSCREEN)); strUsage += HelpMessageOpt("-resetguisettings", tr("Reset all settings changed in the GUI").toStdString()); if (showDebug) { strUsage += HelpMessageOpt("-uiplatform", strprintf("Select platform to customize UI for (one of windows, macosx, other; default: %s)", WeyCoinGUI::DEFAULT_UIPLATFORM)); } QString coreOptions = QString::fromStdString(strUsage); text = version + "\n" + header + "\n" + coreOptions; QTextTableFormat tf; tf.setBorderStyle(QTextFrameFormat::BorderStyle_None); tf.setCellPadding(2); QVector<QTextLength> widths; widths << QTextLength(QTextLength::PercentageLength, 35); widths << QTextLength(QTextLength::PercentageLength, 65); tf.setColumnWidthConstraints(widths); QTextCharFormat bold; bold.setFontWeight(QFont::Bold); Q_FOREACH (const QString &line, coreOptions.split("\n")) { if (line.startsWith(" -")) { cursor.currentTable()->appendRows(1); cursor.movePosition(QTextCursor::PreviousCell); cursor.movePosition(QTextCursor::NextRow); cursor.insertText(line.trimmed()); cursor.movePosition(QTextCursor::NextCell); } else if (line.startsWith(" ")) { cursor.insertText(line.trimmed()+' '); } else if (line.size() > 0) { //Title of a group if (cursor.currentTable()) cursor.currentTable()->appendRows(1); cursor.movePosition(QTextCursor::Down); cursor.insertText(line.trimmed(), bold); cursor.insertTable(1, 2, tf); } } ui->helpMessage->moveCursor(QTextCursor::Start); ui->scrollArea->setVisible(false); ui->aboutLogo->setVisible(false); } } HelpMessageDialog::~HelpMessageDialog() { delete ui; } void HelpMessageDialog::printToConsole() { // On other operating systems, the expected action is to print the message to the console. fprintf(stdout, "%s\n", qPrintable(text)); } void HelpMessageDialog::showOrPrint() { #if defined(WIN32) // On Windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } void HelpMessageDialog::on_okButton_accepted() { close(); } /** "Shutdown" window */ ShutdownWindow::ShutdownWindow(QWidget *parent, Qt::WindowFlags f): QWidget(parent, f) { QVBoxLayout *layout = new QVBoxLayout(); layout->addWidget(new QLabel( tr("%1 is shutting down...").arg(tr(PACKAGE_NAME)) + "<br /><br />" + tr("Do not shut down the computer until this window disappears."))); setLayout(layout); } QWidget *ShutdownWindow::showShutdownWindow(WeyCoinGUI *window) { if (!window) return nullptr; // Show a simple window indicating shutdown status QWidget *shutdownWindow = new ShutdownWindow(); shutdownWindow->setWindowTitle(window->windowTitle()); // Center shutdown window at where main window was const QPoint global = window->mapToGlobal(window->rect().center()); shutdownWindow->move(global.x() - shutdownWindow->width() / 2, global.y() - shutdownWindow->height() / 2); shutdownWindow->show(); return shutdownWindow; } void ShutdownWindow::closeEvent(QCloseEvent *event) { event->ignore(); }
/* * ----------------- BEGIN LICENSE BLOCK --------------------------------- * * Copyright (C) 2018-2019 Intel Corporation * * SPDX-License-Identifier: MIT * * ----------------- END LICENSE BLOCK ----------------------------------- */ #include <gtest/gtest.h> #include <spdlog/spdlog.h> #include "spdlog/sinks/null_sink.h" int main(int argc, char **argv) { auto logger = spdlog::create<spdlog::sinks::null_sink_st>("null_logger"); spdlog::set_default_logger(logger); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
/* Problem 5: Write a recursive solution to evaluate the previous polynomial for any given x and n. Like, when x=2 and n=5, we have 1 + x + x^2 + ................. + x^n-1 = 31 Input: 2 5 Output: 31 */ #include <bits/stdc++.h> using namespace std; int func(int &x, int n) { if (n == 0) { return 1; } return func(x, n-1) + pow(x, n); } int main() { int x, n; cin >> x >> n; cout << func(x, n-1) << endl; }
//===- AArch64TargetStreamer.cpp - AArch64TargetStreamer class ------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements the AArch64TargetStreamer class. // //===----------------------------------------------------------------------===// #include "AArch64TargetStreamer.h" #include "llvm/MC/ConstantPools.h" #include "llvm/MC/MCSection.h" #include "llvm/MC/MCSubtargetInfo.h" using namespace llvm; // // AArch64TargetStreamer Implemenation // AArch64TargetStreamer::AArch64TargetStreamer(MCStreamer &S) : MCTargetStreamer(S), ConstantPools(new AssemblerConstantPools()) {} AArch64TargetStreamer::~AArch64TargetStreamer() = default; // The constant pool handling is shared by all AArch64TargetStreamer // implementations. const MCExpr *AArch64TargetStreamer::addConstantPoolEntry(const MCExpr *Expr, unsigned Size, SMLoc Loc) { return ConstantPools->addEntry(Streamer, Expr, Size, Loc); } void AArch64TargetStreamer::emitCurrentConstantPool() { ConstantPools->emitForCurrentSection(Streamer); } // finish() - write out any non-empty assembler constant pools. void AArch64TargetStreamer::finish() { ConstantPools->emitAll(Streamer); } void AArch64TargetStreamer::emitInst(uint32_t Inst) { char Buffer[4]; // We can't just use EmitIntValue here, as that will swap the // endianness on big-endian systems (instructions are always // little-endian). for (unsigned I = 0; I < 4; ++I) { Buffer[I] = uint8_t(Inst); Inst >>= 8; } getStreamer().EmitBytes(StringRef(Buffer, 4)); } namespace llvm { MCTargetStreamer * createAArch64ObjectTargetStreamer(MCStreamer &S, const MCSubtargetInfo &STI) { const Triple &TT = STI.getTargetTriple(); if (TT.isOSBinFormatELF()) return new AArch64TargetELFStreamer(S); if (TT.isOSBinFormatCOFF()) return new AArch64TargetWinCOFFStreamer(S); return nullptr; } } // end namespace llvm
/* This file is part of Kismet Kismet is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kismet 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 Kismet; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "dot11_ie_45_ht_cap.h" void dot11_ie_45_ht_cap::parse(std::shared_ptr<kaitai::kstream> p_io) { m_ht_capabilities = p_io->read_u2le(); m_ampdu = p_io->read_u1(); m_mcs.reset(new dot11_ie_45_rx_mcs()); m_mcs->parse(p_io); m_ht_extended_caps = p_io->read_u2be(); m_txbf_caps = p_io->read_u4be(); m_asel_caps = p_io->read_u1(); } void dot11_ie_45_ht_cap::dot11_ie_45_rx_mcs::parse(std::shared_ptr<kaitai::kstream> p_io) { m_rx_mcs = p_io->read_bytes(10); m_supported_data_rate = p_io->read_u2le(); m_txflags = p_io->read_u4be(); }
#include <iostream> #include <queue> #include <cstring> using namespace std; bool viable[30][30][30]; int bfsIndex[30][30][30]; int l, r, c; int x1, y1, z1; int x2, y2, z2; struct Triple { Triple(int x, int y, int z) : a(x), b(y), c(z) {}; int a, b, c; }; int bfs() { bfsIndex[x1][y1][z1] = 0; queue<Triple> q; Triple each(x1, y1, z1); q.push(each); while(bfsIndex[x2][y2][z2] == -1 && !q.empty()) { Triple next = q.front(); q.pop(); int x = next.a; int y = next.b; int z = next.c; if(x-1 >= 0 && bfsIndex[x-1][y][z] == -1 && viable[x-1][y][z]) { bfsIndex[x-1][y][z] = bfsIndex[x][y][z] + 1; Triple next(x-1, y, z); q.push(next); } if(x+1 < l && bfsIndex[x+1][y][z] == -1 && viable[x+1][y][z]) { bfsIndex[x+1][y][z] = bfsIndex[x][y][z] + 1; Triple next(x+1, y, z); q.push(next); } if(y-1 >= 0 && bfsIndex[x][y-1][z] == -1 && viable[x][y-1][z]) { bfsIndex[x][y-1][z] = bfsIndex[x][y][z] + 1; Triple next(x, y-1, z); q.push(next); } if(y+1 < r && bfsIndex[x][y+1][z] == -1 && viable[x][y+1][z]) { bfsIndex[x][y+1][z] = bfsIndex[x][y][z] + 1; Triple next(x, y+1, z); q.push(next); } if(z-1 >= 0 && bfsIndex[x][y][z-1] == -1 && viable[x][y][z-1]) { bfsIndex[x][y][z-1] = bfsIndex[x][y][z] + 1; Triple next(x, y, z-1); q.push(next); } if(z+1 < c && bfsIndex[x][y][z+1] == -1 && viable[x][y][z+1]) { bfsIndex[x][y][z+1] = bfsIndex[x][y][z] + 1; Triple next(x, y, z+1); q.push(next); } } return bfsIndex[x2][y2][z2]; } int main() { string line; while(cin >> l >> r >> c && (l || r || c)) { getline(cin, line); memset(viable, false, sizeof viable); memset(bfsIndex, -1, sizeof bfsIndex); for(int i= 0; i < l; i++) { for(int j= 0; j < r; j++) { getline(cin, line); for(int k =0; k < c; k++) { if(line[k] == 'S') { x1 = i; y1 = j; z1 = k; viable[i][j][k] = true; } else if (line[k] == '.') { viable[i][j][k] = true; } else if (line[k] == 'E') { x2 = i; y2 = j; z2 = k; viable[i][j][k] = true; } else if (line[k] == '#') { viable[i][j][k] = false; } } } getline(cin, line); } int result = bfs(); if(result == -1) cout << "Trapped!" << endl; else cout << "Escaped in " << result << " minute(s)." << endl; } return 0; }
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // #ifndef SIM_CLASSIFICATION_CLASSIFICATION_SYSTEM_OWNER_ZONE_TYPE_CLASSIFICATION_HXX #define SIM_CLASSIFICATION_CLASSIFICATION_SYSTEM_OWNER_ZONE_TYPE_CLASSIFICATION_HXX #ifndef XSD_USE_CHAR #define XSD_USE_CHAR #endif #ifndef XSD_CXX_TREE_USE_CHAR #define XSD_CXX_TREE_USE_CHAR #endif // Begin prologue. // // // End prologue. #include <xsd/cxx/config.hxx> #if (XSD_INT_VERSION != 4000000L) #error XSD runtime version mismatch #endif #include <xsd/cxx/pre.hxx> #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/types.hxx> #include <xsd/cxx/xml/error-handler.hxx> #include <xsd/cxx/xml/dom/auto-ptr.hxx> #include <xsd/cxx/tree/parsing.hxx> #include <xsd/cxx/tree/parsing/byte.hxx> #include <xsd/cxx/tree/parsing/unsigned-byte.hxx> #include <xsd/cxx/tree/parsing/short.hxx> #include <xsd/cxx/tree/parsing/unsigned-short.hxx> #include <xsd/cxx/tree/parsing/int.hxx> #include <xsd/cxx/tree/parsing/unsigned-int.hxx> #include <xsd/cxx/tree/parsing/long.hxx> #include <xsd/cxx/tree/parsing/unsigned-long.hxx> #include <xsd/cxx/tree/parsing/boolean.hxx> #include <xsd/cxx/tree/parsing/float.hxx> #include <xsd/cxx/tree/parsing/double.hxx> #include <xsd/cxx/tree/parsing/decimal.hxx> namespace xml_schema { // anyType and anySimpleType. // typedef ::xsd::cxx::tree::type type; typedef ::xsd::cxx::tree::simple_type< char, type > simple_type; typedef ::xsd::cxx::tree::type container; // 8-bit // typedef signed char byte; typedef unsigned char unsigned_byte; // 16-bit // typedef short short_; typedef unsigned short unsigned_short; // 32-bit // typedef int int_; typedef unsigned int unsigned_int; // 64-bit // typedef long long long_; typedef unsigned long long unsigned_long; // Supposed to be arbitrary-length integral types. // typedef long long integer; typedef long long non_positive_integer; typedef unsigned long long non_negative_integer; typedef unsigned long long positive_integer; typedef long long negative_integer; // Boolean. // typedef bool boolean; // Floating-point types. // typedef float float_; typedef double double_; typedef double decimal; // String types. // typedef ::xsd::cxx::tree::string< char, simple_type > string; typedef ::xsd::cxx::tree::normalized_string< char, string > normalized_string; typedef ::xsd::cxx::tree::token< char, normalized_string > token; typedef ::xsd::cxx::tree::name< char, token > name; typedef ::xsd::cxx::tree::nmtoken< char, token > nmtoken; typedef ::xsd::cxx::tree::nmtokens< char, simple_type, nmtoken > nmtokens; typedef ::xsd::cxx::tree::ncname< char, name > ncname; typedef ::xsd::cxx::tree::language< char, token > language; // ID/IDREF. // typedef ::xsd::cxx::tree::id< char, ncname > id; typedef ::xsd::cxx::tree::idref< char, ncname, type > idref; typedef ::xsd::cxx::tree::idrefs< char, simple_type, idref > idrefs; // URI. // typedef ::xsd::cxx::tree::uri< char, simple_type > uri; // Qualified name. // typedef ::xsd::cxx::tree::qname< char, simple_type, uri, ncname > qname; // Binary. // typedef ::xsd::cxx::tree::buffer< char > buffer; typedef ::xsd::cxx::tree::base64_binary< char, simple_type > base64_binary; typedef ::xsd::cxx::tree::hex_binary< char, simple_type > hex_binary; // Date/time. // typedef ::xsd::cxx::tree::time_zone time_zone; typedef ::xsd::cxx::tree::date< char, simple_type > date; typedef ::xsd::cxx::tree::date_time< char, simple_type > date_time; typedef ::xsd::cxx::tree::duration< char, simple_type > duration; typedef ::xsd::cxx::tree::gday< char, simple_type > gday; typedef ::xsd::cxx::tree::gmonth< char, simple_type > gmonth; typedef ::xsd::cxx::tree::gmonth_day< char, simple_type > gmonth_day; typedef ::xsd::cxx::tree::gyear< char, simple_type > gyear; typedef ::xsd::cxx::tree::gyear_month< char, simple_type > gyear_month; typedef ::xsd::cxx::tree::time< char, simple_type > time; // Entity. // typedef ::xsd::cxx::tree::entity< char, ncname > entity; typedef ::xsd::cxx::tree::entities< char, simple_type, entity > entities; typedef ::xsd::cxx::tree::content_order content_order; // Flags and properties. // typedef ::xsd::cxx::tree::flags flags; typedef ::xsd::cxx::tree::properties< char > properties; // Parsing/serialization diagnostics. // typedef ::xsd::cxx::tree::severity severity; typedef ::xsd::cxx::tree::error< char > error; typedef ::xsd::cxx::tree::diagnostics< char > diagnostics; // Exceptions. // typedef ::xsd::cxx::tree::exception< char > exception; typedef ::xsd::cxx::tree::bounds< char > bounds; typedef ::xsd::cxx::tree::duplicate_id< char > duplicate_id; typedef ::xsd::cxx::tree::parsing< char > parsing; typedef ::xsd::cxx::tree::expected_element< char > expected_element; typedef ::xsd::cxx::tree::unexpected_element< char > unexpected_element; typedef ::xsd::cxx::tree::expected_attribute< char > expected_attribute; typedef ::xsd::cxx::tree::unexpected_enumerator< char > unexpected_enumerator; typedef ::xsd::cxx::tree::expected_text_content< char > expected_text_content; typedef ::xsd::cxx::tree::no_prefix_mapping< char > no_prefix_mapping; typedef ::xsd::cxx::tree::no_type_info< char > no_type_info; typedef ::xsd::cxx::tree::not_derived< char > not_derived; // Error handler callback interface. // typedef ::xsd::cxx::xml::error_handler< char > error_handler; // DOM interaction. // namespace dom { // Automatic pointer for DOMDocument. // using ::xsd::cxx::xml::dom::auto_ptr; #ifndef XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA #define XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA // DOM user data key for back pointers to tree nodes. // const XMLCh* const tree_node_key = ::xsd::cxx::tree::user_data_keys::node; #endif } } // Forward declarations. // namespace schema { namespace simxml { namespace ResourcesGeneral { class SimClassification_ClassificationSystem_OwnerZoneTypeClassification; } } } #include <memory> // ::std::auto_ptr #include <limits> // std::numeric_limits #include <algorithm> // std::binary_search #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/containers.hxx> #include <xsd/cxx/tree/list.hxx> #include <xsd/cxx/xml/dom/parsing-header.hxx> #include "simclassification_classificationsystem.hxx" namespace schema { namespace simxml { namespace ResourcesGeneral { class SimClassification_ClassificationSystem_OwnerZoneTypeClassification: public ::schema::simxml::ResourcesGeneral::SimClassification_ClassificationSystem { public: // Constructors. // SimClassification_ClassificationSystem_OwnerZoneTypeClassification (); SimClassification_ClassificationSystem_OwnerZoneTypeClassification (const RefId_type&); SimClassification_ClassificationSystem_OwnerZoneTypeClassification (const ::xercesc::DOMElement& e, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); SimClassification_ClassificationSystem_OwnerZoneTypeClassification (const SimClassification_ClassificationSystem_OwnerZoneTypeClassification& x, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); virtual SimClassification_ClassificationSystem_OwnerZoneTypeClassification* _clone (::xml_schema::flags f = 0, ::xml_schema::container* c = 0) const; virtual ~SimClassification_ClassificationSystem_OwnerZoneTypeClassification (); }; } } } #include <iosfwd> #include <xercesc/sax/InputSource.hpp> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMErrorHandler.hpp> namespace schema { namespace simxml { namespace ResourcesGeneral { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue. #endif // SIM_CLASSIFICATION_CLASSIFICATION_SYSTEM_OWNER_ZONE_TYPE_CLASSIFICATION_HXX
// Copyright (c) 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. #include "rpcserver.h" #include "base58.h" #include "init.h" #include "util.h" #include "sync.h" #include "base58.h" #include "db.h" #include "ui_interface.h" #include "wallet.h" #include <boost/algorithm/string.hpp> #include <boost/asio.hpp> #include <boost/asio/ip/v6_only.hpp> #include <boost/asio/ssl.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/shared_ptr.hpp> #include <list> using namespace json_spirit; namespace ba = boost::asio; static std::string strRPCUserColonPass; // These are created by StartRPCThreads, destroyed in StopRPCThreads static ba::io_service* rpc_io_service = NULL; static std::map<std::string, boost::shared_ptr<ba::deadline_timer> > deadlineTimers; static ba::ssl::context* rpc_ssl_context = NULL; static boost::thread_group* rpc_worker_group = NULL; void RPCTypeCheck(const Array& params, const std::list<Value_type>& typesExpected, bool fAllowNull) { unsigned int i = 0; BOOST_FOREACH(Value_type t, typesExpected) { if (params.size() <= i) break; const Value& v = params[i]; if (!((v.type() == t) || (fAllowNull && (v.type() == null_type)))) { std::string err = strprintf("Expected type %s, got %s", Value_type_name[t], Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } i++; } } void RPCTypeCheck(const Object& o, const std::map<std::string, Value_type>& typesExpected, bool fAllowNull) { BOOST_FOREACH(const PAIRTYPE(std::string, Value_type)& t, typesExpected) { const Value& v = find_value(o, t.first); if (!fAllowNull && v.type() == null_type) throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first)); if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type)))) { std::string err = strprintf("Expected type %s for %s, got %s", Value_type_name[t.second], t.first, Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } } } int64_t AmountFromValue(const Value& value) { double dAmount = value.get_real(); if (dAmount <= 0.0 || dAmount > MAX_MONEY) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); int64_t nAmount = roundint64(dAmount * COIN); if (!MoneyRange(nAmount)) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); return nAmount; } Value ValueFromAmount(int64_t amount) { return (double)amount / (double)COIN; } std::string HexBits(unsigned int nBits) { union { int32_t nBits; char cBits[4]; } uBits; uBits.nBits = htonl((int32_t)nBits); return HexStr(BEGIN(uBits.cBits), END(uBits.cBits)); } bool IsStringBoolPositive(std::string& value) { return (value == "+" || value == "on" || value == "true" || value == "1" || value == "yes"); }; bool IsStringBoolNegative(std::string& value) { return (value == "-" || value == "off" || value == "false" || value == "0" || value == "no" || value == "n"); }; // // Utilities: convert hex-encoded Values // (throws error if not hex). // uint256 ParseHashV(const Value& v, std::string strName) { std::string strHex; if (v.type() == str_type) strHex = v.get_str(); if (!IsHex(strHex)) // Note: IsHex("") is false throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal std::string (not '"+strHex+"')"); uint256 result; result.SetHex(strHex); return result; } uint256 ParseHashO(const Object& o, std::string strKey) { return ParseHashV(find_value(o, strKey), strKey); } std::vector<unsigned char> ParseHexV(const Value& v, std::string strName) { std::string strHex; if (v.type() == str_type) strHex = v.get_str(); if (!IsHex(strHex)) throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal std::string (not '"+strHex+"')"); return ParseHex(strHex); } std::vector<unsigned char> ParseHexO(const Object& o, std::string strKey) { return ParseHexV(find_value(o, strKey), strKey); } /// /// Note: This interface may still be subject to change. /// std::string CRPCTable::help(std::string strCommand) const { bool fAllAnon = strCommand == "anon" ? true : false; std::string strRet; std::set<rpcfn_type> setDone; for (std::map<std::string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) { const CRPCCommand *pcmd = mi->second; std::string strMethod = mi->first; // We already filter duplicates, but these deprecated screw up the sort order if (strMethod.find("label") != std::string::npos) continue; if (fAllAnon) { if (strMethod != "sendsdctoanon" && strMethod != "sendanontoanon" && strMethod != "sendanontosdc" && strMethod != "estimateanonfee" && strMethod != "anonoutputs" && strMethod != "anoninfo" && strMethod != "reloadanondata") continue; } else if (strCommand != "" && strMethod != strCommand) continue; if (pcmd->reqWallet && !pwalletMain) continue; try { Array params; rpcfn_type pfn = pcmd->actor; if (setDone.insert(pfn).second) (*pfn)(params, true); } catch (std::exception& e) { // Help text is returned in an exception std::string strHelp = std::string(e.what()); if (strCommand == "") if (strHelp.find('\n') != std::string::npos) strHelp = strHelp.substr(0, strHelp.find('\n')); strRet += strHelp + "\n"; }; }; if (strRet == "") strRet = strprintf("help: unknown command: %s\n", strCommand); strRet = strRet.substr(0,strRet.size()-1); return strRet; } Value help(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw std::runtime_error( "help [command]\n" "List commands, or get help for a command."); std::string strCommand; if (params.size() > 0) strCommand = params[0].get_str(); return tableRPC.help(strCommand); } Value stop(const Array& params, bool fHelp) { // Accept the deprecated and ignored 'detach' boolean argument if (fHelp || params.size() > 1) throw std::runtime_error( "stop\n" "Stop StealthCash server."); // Shutdown will take long enough that the response should get back StartShutdown(); return "StealthCash server stopping"; } // // Call Table // static const CRPCCommand vRPCCommands[] = { // name actor (function) okSafeMode threadSafe reqWallet // ------------------------ ----------------------- ---------- ---------- --------- { "help", &help, true, true, false }, { "stop", &stop, true, true, false }, { "getbestblockhash", &getbestblockhash, true, false, false }, { "getblockcount", &getblockcount, true, false, false }, { "getconnectioncount", &getconnectioncount, true, false, false }, { "getpeerinfo", &getpeerinfo, true, false, false }, { "addnode", &addnode, true, true, false }, { "getaddednodeinfo", &getaddednodeinfo, true, true, false }, { "getdifficulty", &getdifficulty, true, false, false }, { "getinfo", &getinfo, true, false, false }, { "getsubsidy", &getsubsidy, true, false, false }, { "getmininginfo", &getmininginfo, true, false, false }, { "getstakinginfo", &getstakinginfo, true, false, false }, { "getnewaddress", &getnewaddress, true, false, false }, { "getnewpubkey", &getnewpubkey, true, false, false }, { "getaccountaddress", &getaccountaddress, true, false, false }, { "setaccount", &setaccount, true, false, false }, { "getaccount", &getaccount, false, false, false }, { "getaddressesbyaccount", &getaddressesbyaccount, true, false, false }, { "sendtoaddress", &sendtoaddress, false, false, false }, { "getreceivedbyaddress", &getreceivedbyaddress, false, false, false }, { "getreceivedbyaccount", &getreceivedbyaccount, false, false, false }, { "listreceivedbyaddress", &listreceivedbyaddress, false, false, false }, { "listreceivedbyaccount", &listreceivedbyaccount, false, false, false }, { "backupwallet", &backupwallet, true, false, false }, { "keypoolrefill", &keypoolrefill, true, false, false }, { "walletpassphrase", &walletpassphrase, true, false, false }, { "walletpassphrasechange", &walletpassphrasechange, false, false, false }, { "walletlock", &walletlock, true, false, false }, { "encryptwallet", &encryptwallet, false, false, false }, { "validateaddress", &validateaddress, true, false, false }, { "validatepubkey", &validatepubkey, true, false, false }, { "getbalance", &getbalance, false, false, false }, { "move", &movecmd, false, false, false }, { "sendfrom", &sendfrom, false, false, false }, { "sendmany", &sendmany, false, false, false }, { "addmultisigaddress", &addmultisigaddress, false, false, false }, { "addredeemscript", &addredeemscript, false, false, false }, { "getrawmempool", &getrawmempool, true, false, false }, { "getblock", &getblock, false, false, false }, { "getblockbynumber", &getblockbynumber, false, false, false }, { "setbestblockbyheight", &setbestblockbyheight, false, false, false }, { "rewindchain", &rewindchain, false, false, false }, { "nextorphan", &nextorphan, false, false, false }, { "getblockhash", &getblockhash, false, false, false }, { "gettransaction", &gettransaction, false, false, false }, { "listtransactions", &listtransactions, false, false, false }, { "listaddressgroupings", &listaddressgroupings, false, false, false }, { "signmessage", &signmessage, false, false, false }, { "verifymessage", &verifymessage, false, false, false }, { "getwork", &getwork, true, false, false }, { "getworkex", &getworkex, true, false, false }, { "listaccounts", &listaccounts, false, false, false }, { "settxfee", &settxfee, false, false, false }, { "getblocktemplate", &getblocktemplate, true, false, false }, { "submitblock", &submitblock, false, false, false }, { "listsinceblock", &listsinceblock, false, false, false }, { "dumpprivkey", &dumpprivkey, false, false, false }, { "dumpwallet", &dumpwallet, true, false, false }, { "importwallet", &importwallet, false, false, false }, { "importprivkey", &importprivkey, false, false, false }, { "listunspent", &listunspent, false, false, false }, { "getrawtransaction", &getrawtransaction, false, false, false }, { "createrawtransaction", &createrawtransaction, false, false, false }, { "decoderawtransaction", &decoderawtransaction, false, false, false }, { "decodescript", &decodescript, false, false, false }, { "signrawtransaction", &signrawtransaction, false, false, false }, { "sendrawtransaction", &sendrawtransaction, false, false, false }, { "getcheckpoint", &getcheckpoint, true, false, false }, { "reservebalance", &reservebalance, false, true, false }, { "checkwallet", &checkwallet, false, true, false }, { "repairwallet", &repairwallet, false, true, false }, { "resendtx", &resendtx, false, true, false }, { "makekeypair", &makekeypair, false, true, false }, { "sendalert", &sendalert, false, false, false }, { "getnetworkinfo", &getnetworkinfo, false, false, false }, { "getnewstealthaddress", &getnewstealthaddress, false, false, false }, { "liststealthaddresses", &liststealthaddresses, false, false, false }, { "importstealthaddress", &importstealthaddress, false, false, false }, { "sendtostealthaddress", &sendtostealthaddress, false, false, false }, { "clearwallettransactions",&clearwallettransactions,false, false, false }, { "scanforalltxns", &scanforalltxns, false, false, false }, { "scanforstealthtxns", &scanforstealthtxns, false, false, false }, { "sendsdctoanon", &sendsdctoanon, false, false, false }, { "sendanontoanon", &sendanontoanon, false, false, false }, { "sendanontosdc", &sendanontosdc, false, false, false }, { "estimateanonfee", &estimateanonfee, false, false, false }, { "anonoutputs", &anonoutputs, false, false, false }, { "anoninfo", &anoninfo, false, false, false }, { "reloadanondata", &reloadanondata, false, false, false }, { "txnreport", &txnreport, false, false, false }, { "smsgenable", &smsgenable, false, false, false }, { "smsgdisable", &smsgdisable, false, false, false }, { "smsglocalkeys", &smsglocalkeys, false, false, false }, { "smsgoptions", &smsgoptions, false, false, false }, { "smsgscanchain", &smsgscanchain, false, false, false }, { "smsgscanbuckets", &smsgscanbuckets, false, false, false }, { "smsgaddkey", &smsgaddkey, false, false, false }, { "smsggetpubkey", &smsggetpubkey, false, false, false }, { "smsgsend", &smsgsend, false, false, false }, { "smsgsendanon", &smsgsendanon, false, false, false }, { "smsginbox", &smsginbox, false, false, false }, { "smsgoutbox", &smsgoutbox, false, false, false }, { "smsgbuckets", &smsgbuckets, false, false, false }, { "thinscanmerkleblocks", &thinscanmerkleblocks, false, false, false }, { "thinforcestate", &thinforcestate, false, false, false }, }; CRPCTable::CRPCTable() { unsigned int vcidx; for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++) { const CRPCCommand *pcmd; pcmd = &vRPCCommands[vcidx]; mapCommands[pcmd->name] = pcmd; } } const CRPCCommand *CRPCTable::operator[](std::string name) const { std::map<std::string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); if (it == mapCommands.end()) return NULL; return (*it).second; } bool HTTPAuthorized(std::map<std::string, std::string>& mapHeaders) { std::string strAuth = mapHeaders["authorization"]; if (strAuth.substr(0,6) != "Basic ") return false; std::string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64); std::string strUserPass = DecodeBase64(strUserPass64); return TimingResistantEqual(strUserPass, strRPCUserColonPass); } void ErrorReply(std::ostream& stream, const Object& objError, const Value& id) { // Send error reply from json-rpc error object int nStatus = HTTP_INTERNAL_SERVER_ERROR; int code = find_value(objError, "code").get_int(); if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST; else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND; std::string strReply = JSONRPCReply(Value::null, objError, id); stream << HTTPReply(nStatus, strReply, false) << std::flush; } bool ClientAllowed(const ba::ip::address& address) { // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses if (address.is_v6() && (address.to_v6().is_v4_compatible() || address.to_v6().is_v4_mapped())) return ClientAllowed(address.to_v6().to_v4()); if (address == ba::ip::address_v4::loopback() || address == ba::ip::address_v6::loopback() || (address.is_v4() // Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet) && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000)) return true; const std::string strAddress = address.to_string(); const std::vector<std::string>& vAllow = mapMultiArgs["-rpcallowip"]; BOOST_FOREACH(std::string strAllow, vAllow) if (WildcardMatch(strAddress, strAllow)) return true; return false; } class AcceptedConnection { public: virtual ~AcceptedConnection() {} virtual std::iostream& stream() = 0; virtual std::string peer_address_to_string() const = 0; virtual void close() = 0; }; template <typename Protocol> class AcceptedConnectionImpl : public AcceptedConnection { public: AcceptedConnectionImpl( ba::io_service& io_service, ba::ssl::context &context, bool fUseSSL) : sslStream(io_service, context), _d(sslStream, fUseSSL), _stream(_d) { } virtual std::iostream& stream() { return _stream; } virtual std::string peer_address_to_string() const { return peer.address().to_string(); } virtual void close() { _stream.close(); } typename Protocol::endpoint peer; ba::ssl::stream<typename Protocol::socket> sslStream; private: SSLIOStreamDevice<Protocol> _d; boost::iostreams::stream< SSLIOStreamDevice<Protocol> > _stream; }; void ServiceConnection(AcceptedConnection *conn); // Forward declaration required for RPCListen template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr<ba::basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ba::ssl::context& context, bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error); /** * Sets up I/O resources to accept and handle a new connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCListen(boost::shared_ptr<ba::basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ba::ssl::context& context, const bool fUseSSL) { // Accept connection AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL); acceptor->async_accept( conn->sslStream.lowest_layer(), conn->peer, boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>, acceptor, boost::ref(context), fUseSSL, conn, ba::placeholders::error)); } /** * Accept and handle incoming connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr<ba::basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ba::ssl::context& context, const bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error) { // Immediately start accepting new connections, except when we're cancelled or our socket is closed. if (error != ba::error::operation_aborted && acceptor->is_open()) RPCListen(acceptor, context, fUseSSL); AcceptedConnectionImpl<ba::ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ba::ip::tcp>* >(conn); // TODO: Actually handle errors if (error) { delete conn; } // Restrict callers by IP. It is important to // do this before starting client thread, to filter out // certain DoS and misbehaving clients. else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address())) { // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake. if (!fUseSSL) conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush; delete conn; } else { ServiceConnection(conn); conn->close(); delete conn; } } void StartRPCThreads() { strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; if (((mapArgs["-rpcpassword"] == "") || (mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) && Params().RequireRPCPassword()) { unsigned char rand_pwd[32]; RAND_bytes(rand_pwd, 32); std::string strWhatAmI = "To use StealthCashd"; if (mapArgs.count("-server")) strWhatAmI = strprintf(_("To use the %s option"), "\"-server\""); else if (mapArgs.count("-daemon")) strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\""); uiInterface.ThreadSafeMessageBox(strprintf( _("%s, you must set a rpcpassword in the configuration file:\n" "%s\n" "It is recommended you use the following random password:\n" "rpcuser=StealthCashrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"StealthCash Alert\" admin@foo.com\n"), strWhatAmI, GetConfigFile().string(), EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32)), "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } assert(rpc_io_service == NULL); rpc_io_service = new ba::io_service(); rpc_ssl_context = new ba::ssl::context(*rpc_io_service, ba::ssl::context::sslv23); const bool fUseSSL = GetBoolArg("-rpcssl", false); if (fUseSSL) { rpc_ssl_context->set_options(ba::ssl::context::no_sslv2); boost::filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert")); if (!pathCertFile.is_complete()) pathCertFile = boost::filesystem::path(GetDataDir()) / pathCertFile; if (boost::filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string()); else LogPrintf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string()); boost::filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem")); if (!pathPKFile.is_complete()) pathPKFile = boost::filesystem::path(GetDataDir()) / pathPKFile; if (boost::filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ba::ssl::context::pem); else LogPrintf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string()); std::string strCiphers = GetArg("-rpcsslciphers", "TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH"); SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str()); } // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets const bool loopback = !mapArgs.count("-rpcallowip"); ba::ip::address bindAddress = loopback ? ba::ip::address_v6::loopback() : ba::ip::address_v6::any(); ba::ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", Params().RPCPort())); boost::system::error_code v6_only_error; boost::shared_ptr<ba::ip::tcp::acceptor> acceptor(new ba::ip::tcp::acceptor(*rpc_io_service)); bool fListening = false; std::string strerr; try { acceptor->open(endpoint.protocol()); acceptor->set_option(ba::ip::tcp::acceptor::reuse_address(true)); // Try making the socket dual IPv6/IPv4 (if listening on the "any" address) acceptor->set_option(ba::ip::v6_only(loopback), v6_only_error); acceptor->bind(endpoint); acceptor->listen(ba::socket_base::max_connections); RPCListen(acceptor, *rpc_ssl_context, fUseSSL); fListening = true; } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what()); } try { // If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately if (!fListening || loopback || v6_only_error) { bindAddress = loopback ? ba::ip::address_v4::loopback() : ba::ip::address_v4::any(); endpoint.address(bindAddress); acceptor.reset(new ba::ip::tcp::acceptor(*rpc_io_service)); acceptor->open(endpoint.protocol()); acceptor->set_option(ba::ip::tcp::acceptor::reuse_address(true)); acceptor->bind(endpoint); acceptor->listen(ba::socket_base::max_connections); RPCListen(acceptor, *rpc_ssl_context, fUseSSL); fListening = true; } } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what()); } if (!fListening) { uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } rpc_worker_group = new boost::thread_group(); for (int i = 0; i < GetArg("-rpcthreads", 4); i++) rpc_worker_group->create_thread(boost::bind(&ba::io_service::run, rpc_io_service)); } void StopRPCThreads() { if (rpc_io_service == NULL) return; deadlineTimers.clear(); rpc_io_service->stop(); if (rpc_worker_group != NULL) rpc_worker_group->join_all(); delete rpc_worker_group; rpc_worker_group = NULL; delete rpc_ssl_context; rpc_ssl_context = NULL; delete rpc_io_service; rpc_io_service = NULL; } void RPCRunHandler(const boost::system::error_code& err, boost::function<void(void)> func) { if (!err) func(); } void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64_t nSeconds) { assert(rpc_io_service != NULL); if (deadlineTimers.count(name) == 0) { deadlineTimers.insert(make_pair(name, boost::shared_ptr<ba::deadline_timer>(new ba::deadline_timer(*rpc_io_service)))); } deadlineTimers[name]->expires_from_now(boost::posix_time::seconds(nSeconds)); deadlineTimers[name]->async_wait(boost::bind(RPCRunHandler, _1, func)); } CNetAddr BoostAsioToCNetAddr(boost::asio::ip::address address) { CNetAddr netaddr; // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses if (address.is_v6() && (address.to_v6().is_v4_compatible() || address.to_v6().is_v4_mapped())) address = address.to_v6().to_v4(); if (address.is_v4()) { boost::asio::ip::address_v4::bytes_type bytes = address.to_v4().to_bytes(); netaddr.SetRaw(NET_IPV4, &bytes[0]); } else { boost::asio::ip::address_v6::bytes_type bytes = address.to_v6().to_bytes(); netaddr.SetRaw(NET_IPV6, &bytes[0]); }; return netaddr; } class JSONRequest { public: Value id; std::string strMethod; Array params; JSONRequest() { id = Value::null; } void parse(const Value& valRequest); }; void JSONRequest::parse(const Value& valRequest) { // Parse request if (valRequest.type() != obj_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object"); const Object& request = valRequest.get_obj(); // Parse id now so errors from here on will have the id id = find_value(request, "id"); // Parse method Value valMethod = find_value(request, "method"); if (valMethod.type() == null_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method"); if (valMethod.type() != str_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a std::string"); strMethod = valMethod.get_str(); if (strMethod != "getwork" && strMethod != "getblocktemplate") LogPrint("rpc", "ThreadRPCServer method=%s\n", strMethod); // Parse params Value valParams = find_value(request, "params"); if (valParams.type() == array_type) params = valParams.get_array(); else if (valParams.type() == null_type) params = Array(); else throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array"); } static Object JSONRPCExecOne(const Value& req) { Object rpc_result; JSONRequest jreq; try { jreq.parse(req); Value result = tableRPC.execute(jreq.strMethod, jreq.params); rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id); } catch (Object& objError) { rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id); } catch (std::exception& e) { rpc_result = JSONRPCReplyObj(Value::null, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); } return rpc_result; } static std::string JSONRPCExecBatch(const Array& vReq) { Array ret; for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++) ret.push_back(JSONRPCExecOne(vReq[reqIdx])); return write_string(Value(ret), false) + "\n"; } void ServiceConnection(AcceptedConnection *conn) { bool fRun = true; while (fRun) { int nProto = 0; std::map<std::string, std::string> mapHeaders; std::string strRequest, strMethod, strURI; // Read HTTP request line if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI)) break; // Read HTTP message headers and body ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto); if (strURI != "/") { conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush; break; } // Check authorization if (mapHeaders.count("authorization") == 0) { conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (!HTTPAuthorized(mapHeaders)) { LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string()); /* Deter brute-forcing short passwords. If this results in a DoS the user really shouldn't have their RPC port exposed. */ if (mapArgs["-rpcpassword"].size() < 20) MilliSleep(250); conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (mapHeaders["connection"] == "close") fRun = false; JSONRequest jreq; try { // Parse request Value valRequest; if (!read_string(strRequest, valRequest)) throw JSONRPCError(RPC_PARSE_ERROR, "Parse error"); std::string strReply; // singleton request if (valRequest.type() == obj_type) { jreq.parse(valRequest); Value result = tableRPC.execute(jreq.strMethod, jreq.params); // Send reply strReply = JSONRPCReply(result, Value::null, jreq.id); // array of requests } else if (valRequest.type() == array_type) strReply = JSONRPCExecBatch(valRequest.get_array()); else throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error"); conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush; } catch (Object& objError) { ErrorReply(conn->stream(), objError, jreq.id); break; } catch (std::exception& e) { ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); break; } } } json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array &params) const { // Find method const CRPCCommand *pcmd = tableRPC[strMethod]; if (!pcmd) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found"); if (pcmd->reqWallet && !pwalletMain) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)"); // Observe safe mode std::string strWarning = GetWarnings("rpc"); if (strWarning != "" && !GetBoolArg("-disablesafemode", false) && !pcmd->okSafeMode) throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, std::string("Safe mode: ") + strWarning); try { // Execute Value result; { if (pcmd->threadSafe) { result = pcmd->actor(params, false); } else if (!pwalletMain) { LOCK(cs_main); result = pcmd->actor(params, false); } else { LOCK2(cs_main, pwalletMain->cs_wallet); result = pcmd->actor(params, false); }; } return result; } catch (std::exception& e) { throw JSONRPCError(RPC_MISC_ERROR, e.what()); } } const CRPCTable tableRPC;
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2010, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" #include "IECore/MatrixMultiplyOp.h" #include "IECorePython/RunTimeTypedBinding.h" using namespace boost; using namespace boost::python; using namespace IECore; namespace IECorePython { void bindMatrixMultiplyOp() { RunTimeTypedClass<MatrixMultiplyOp>() .def( init<>() ) ; } } // namespace IECorePython
/** * Copyright (C) 2016-2019 Xilinx, Inc * * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ /** * Copyright (C) 2015 Xilinx, Inc */ #include "shim.h" #include "system_swemu.h" #include <errno.h> #include <unistd.h> namespace xclcpuemhal2 { std::map<unsigned int, CpuemShim*> devices; unsigned int CpuemShim::mBufferCount = 0; std::map<int, std::tuple<std::string,int,void*> > CpuemShim::mFdToFileNameMap; bool CpuemShim::mFirstBinary = true; const unsigned CpuemShim::TAG = 0X586C0C6C; // XL OpenCL X->58(ASCII), L->6C(ASCII), O->0 C->C L->6C(ASCII); const unsigned CpuemShim::CONTROL_AP_START = 1; const unsigned CpuemShim::CONTROL_AP_DONE = 2; const unsigned CpuemShim::CONTROL_AP_IDLE = 4; const unsigned CpuemShim::CONTROL_AP_CONTINUE = 0x10; std::map<std::string, std::string> CpuemShim::mEnvironmentNameValueMap(xclemulation::getEnvironmentByReadingIni()); #define PRINTENDFUNC if (mLogStream.is_open()) mLogStream << __func__ << " ended " << std::endl; CpuemShim::CpuemShim(unsigned int deviceIndex, xclDeviceInfo2 &info, std::list<xclemulation::DDRBank>& DDRBankList, bool _unified, bool _xpr, FeatureRomHeader& fRomHeader) :mTag(TAG) ,mRAMSize(info.mDDRSize) ,mCoalesceThreshold(4) ,mDSAMajorVersion(DSA_MAJOR_VERSION) ,mDSAMinorVersion(DSA_MINOR_VERSION) ,mDeviceIndex(deviceIndex) { binaryCounter = 0; mReqCounter = 0; sock = NULL; ci_msg.set_size(0); ci_msg.set_xcl_api(0); mCore = nullptr; mSWSch = nullptr; ci_buf = malloc(ci_msg.ByteSize()); ri_msg.set_size(0); ri_buf = malloc(ri_msg.ByteSize()); buf = NULL; buf_size = 0; deviceName = "device"+std::to_string(deviceIndex); deviceDirectory = xclemulation::getRunDirectory() + "/"+std::to_string(getpid())+"/sw_emu/"+deviceName; simulator_started = false; mVerbosity = XCL_INFO; std::memset(&mDeviceInfo, 0, sizeof(xclDeviceInfo2)); fillDeviceInfo(&mDeviceInfo,&info); initMemoryManager(DDRBankList); std::memset(&mFeatureRom, 0, sizeof(FeatureRomHeader)); std::memcpy(&mFeatureRom, &fRomHeader, sizeof(FeatureRomHeader)); char* pack_size = getenv("SW_EMU_PACKET_SIZE"); if(pack_size) { unsigned int messageSize = strtoll(pack_size,NULL,0); message_size = messageSize; } else { message_size = 0x800000; } mCloseAll = false; bUnified = _unified; bXPR = _xpr; mIsKdsSwEmu = (xclemulation::is_sw_emulation()) ? xrt_core::config::get_flag_kds_sw_emu() : false; } size_t CpuemShim::alloc_void(size_t new_size) { if (buf_size == 0) { buf = malloc(new_size); return new_size; } if (buf_size < new_size) { buf = (void*) realloc(buf,new_size); return new_size; } return buf_size; } void CpuemShim::initMemoryManager(std::list<xclemulation::DDRBank>& DDRBankList) { std::list<xclemulation::DDRBank>::iterator start = DDRBankList.begin(); std::list<xclemulation::DDRBank>::iterator end = DDRBankList.end(); uint64_t base = 0; for(;start != end; start++) { const uint64_t bankSize = (*start).ddrSize; mDdrBanks.push_back(*start); //CR 966701: alignment to 4k (instead of mDeviceInfo.mDataAlignment) mDDRMemoryManager.push_back(new xclemulation::MemoryManager(bankSize, base , getpagesize())); base += bankSize; } } //private bool CpuemShim::isGood() const { // TODO: Add sanity check for card state return true; } CpuemShim *CpuemShim::handleCheck(void *handle) { // Sanity checks if (!handle) return 0; if (*(unsigned *)handle != TAG) return 0; if (!((CpuemShim *)handle)->isGood()) { return 0; } return (CpuemShim *)handle; } static void saveDeviceProcessOutputs() { std::map<unsigned int, CpuemShim*>::iterator start = devices.begin(); std::map<unsigned int, CpuemShim*>::iterator end = devices.end(); for(; start != end; start++) { CpuemShim* handle = (*start).second; if(!handle) continue; handle->saveDeviceProcessOutput(); } } static void sigHandler(int sn, siginfo_t *si, void *sc) { switch(sn) { case SIGSEGV: { saveDeviceProcessOutputs(); kill(0,SIGSEGV); exit(1); break; } case SIGFPE : { saveDeviceProcessOutputs(); kill(0,SIGTERM); exit(1); break; } case SIGABRT: { saveDeviceProcessOutputs(); kill(0,SIGABRT); exit(1); break; } case SIGUSR1: { // One of the spawned processes died for some reason, // kill all of the others and exit the host code saveDeviceProcessOutputs() ; std::cerr << "Software emulation of compute unit(s) exited unexpectedly" << std::endl ; kill(0, SIGTERM) ; exit(1) ; break ; } default: { break; } } } int CpuemShim::dumpXML(const xclBin* header, std::string& fileLocation) { if (!header) return 0 ; // We didn't dump it, but this isn't an error char* xclbininmemory = reinterpret_cast<char*>(const_cast<xclBin*>(header)) ; char* xmlfile = nullptr ; int xmllength = 0 ; if (memcmp(xclbininmemory, "xclbin0", 8) == 0) { if (mLogStream.is_open()) { mLogStream << __func__ << " unsupported Legacy XCLBIN header " << std::endl; } return -1; //xmlfile = xclbininmemory + (header->m_metadataOffset) ; //xmllength = (int)(header->m_metadataLength); } else if (memcmp(xclbininmemory,"xclbin2",7) == 0) { auto top = reinterpret_cast<const axlf*>(header); if (auto sec = xclbin::get_axlf_section(top,EMBEDDED_METADATA)) { xmlfile = xclbininmemory + sec->m_sectionOffset; xmllength = sec->m_sectionSize; } } else { // This was not a valid xclbin file if (mLogStream.is_open()) { mLogStream << __func__ << " invalid XCLBIN header " << std::endl; } return -1 ; } if (xmlfile == nullptr || xmllength == 0) { // This xclbin file did not contain any XML meta-data if (mLogStream.is_open()) { mLogStream << __func__ << " XCLBIN did not contain meta-data" << std::endl ; } return -1 ; } // First, create the device directory if it doesn't exist systemUtil::makeSystemCall(deviceDirectory, systemUtil::systemOperation::CREATE) ; // Second, create the binary directory if it doesn't exist std::stringstream binaryDirectory ; binaryDirectory << deviceDirectory << "/binary_" << binaryCounter ; std::string binDir = binaryDirectory.str() ; systemUtil::makeSystemCall(binDir, systemUtil::systemOperation::CREATE) ; systemUtil::makeSystemCall(binDir, systemUtil::systemOperation::PERMISSIONS, "777") ; // The XML file will exist in this binary directory fileLocation = binDir + "/xmltmp" ; // Keep appending underscore to the file name until we find // a file that does not exist. bool foundName = false ; while (!foundName) { FILE* fp = fopen(fileLocation.c_str(), "rb") ; if (fp == NULL) { // The file does not exist, so we can use this file location foundName = true ; } else { // The name we've chosen already exists, so append an underscore // and try again fclose(fp) ; fileLocation += "_" ; } } // The file name we've chosen does not exist, so attempt to // open it for writing FILE* fp = fopen(fileLocation.c_str(), "wb") ; if(fp==NULL) { if (mLogStream.is_open()) { mLogStream << __func__ << " failed to create temporary xml file " << std::endl; } return -1; } fwrite(xmlfile,xmllength,1,fp); fflush(fp); fclose(fp); return 0 ; } bool CpuemShim::parseIni(unsigned int& debugPort) { debugPort = xclemulation::config::getInstance()->getServerPort() ; if (debugPort == 0) { return false ; } return true ; } void CpuemShim::launchDeviceProcess(bool debuggable, std::string& binaryDirectory) { std::lock_guard<std::mutex> lk(mProcessLaunchMtx); systemUtil::makeSystemCall(deviceDirectory, systemUtil::systemOperation::CREATE); std::stringstream ss1; ss1<<deviceDirectory<<"/binary_"<<binaryCounter; binaryDirectory = ss1.str(); systemUtil::makeSystemCall(binaryDirectory, systemUtil::systemOperation::CREATE); systemUtil::makeSystemCall(binaryDirectory, systemUtil::systemOperation::PERMISSIONS, "777"); binaryCounter++; if(sock) { return; } struct sigaction s; memset(&s, 0, sizeof(s)); s.sa_flags = SA_SIGINFO; s.sa_sigaction = sigHandler; if (sigaction(SIGSEGV, &s, (struct sigaction *)0) || sigaction(SIGFPE , &s, (struct sigaction *)0) || sigaction(SIGABRT, &s, (struct sigaction *)0) || sigaction(SIGUSR1, &s, (struct sigaction *)0)) { //debug_print("unable to support all signals"); } // We also need to check the .ini file in order to determine // if the dynamic port on the sdx_server the child process // must connect to was specified unsigned int debugPort = 0 ; bool passPort = parseIni(debugPort) ; std::stringstream portStream ; portStream << debugPort ; // If debuggable, the child process also requires the PID of the parent (us) pid_t parentPid = getpid() ; std::stringstream pidStream ; pidStream << parentPid ; // Spawn off the process to run the stub bool simDontRun = xclemulation::config::getInstance()->isDontRun(); if(!simDontRun) { std::stringstream socket_id; socket_id << deviceName << "_" << binaryCounter << "_" << getpid(); setenv("EMULATION_SOCKETID",socket_id.str().c_str(),true); pid_t pid = fork(); assert(pid >= 0); if (pid == 0) { std::string childProcessPath(""); std::string xilinxInstall(""); //Added the latest ENV to get the install path char *vitisInstallEnvvar = getenv("XILINX_VITIS"); if (vitisInstallEnvvar != NULL) { xilinxInstall = std::string(vitisInstallEnvvar); } char *scoutInstallEnvvar = getenv("XILINX_SCOUT"); if(scoutInstallEnvvar != NULL && xilinxInstall.empty() ){ xilinxInstall = std::string(scoutInstallEnvvar); } char *installEnvvar = getenv("XILINX_SDX"); if (installEnvvar != NULL && xilinxInstall.empty()) { xilinxInstall = std::string(installEnvvar); } else { installEnvvar = getenv("XILINX_OPENCL"); if (installEnvvar != NULL) { xilinxInstall = std::string(installEnvvar); } } char *xilinxVivadoEnvvar = getenv("XILINX_VIVADO"); if(xilinxVivadoEnvvar) { std::string sHlsBinDir = xilinxVivadoEnvvar; std::string sLdLibs(""); std::string DS("/"); std::string sPlatform("lnx64"); char* sLdLib = getenv("LD_LIBRARY_PATH"); if (sLdLib) sLdLibs = std::string(sLdLib) + ":"; sLdLibs += sHlsBinDir + DS + sPlatform + DS + "tools" + DS + "fft_v9_1" + ":"; sLdLibs += sHlsBinDir + DS + sPlatform + DS + "tools" + DS + "fir_v7_0" + ":"; sLdLibs += sHlsBinDir + DS + sPlatform + DS + "tools" + DS + "fpo_v7_0" + ":"; sLdLibs += sHlsBinDir + DS + sPlatform + DS + "tools" + DS + "dds_v6_0" + ":"; sLdLibs += sHlsBinDir + DS + sPlatform + DS + "tools" + DS + "opencv" + ":"; sLdLibs += sHlsBinDir + DS + sPlatform + DS + "lib" + DS + "csim" + ":"; sLdLibs += sHlsBinDir + DS + "lib" + DS + "lnx64.o" + DS + "Default" + DS; setenv("LD_LIBRARY_PATH",sLdLibs.c_str(),true); } if (xilinxInstall.empty()) { std::cerr << "ERROR : [SW-EM 10] Please make sure that the XILINX_VITIS environment variable is set correctly" << std::endl; exit(1); } std::string modelDirectory(""); #if defined(RDIPF_aarch64) modelDirectory= xilinxInstall + "/data/emulation/unified/cpu_em/zynqu/model/genericpciemodel"; #elif defined(RDIPF_arm64) modelDirectory= xilinxInstall + "/data/emulation/unified/cpu_em/zynq/model/genericpciemodel"; #else modelDirectory= xilinxInstall + "/data/emulation/unified/cpu_em/generic_pcie/model/genericpciemodel"; #endif FILE *filep; if ((filep = fopen(modelDirectory.c_str(), "r")) != NULL) { // file exists fclose(filep); } else { //File not found, no memory leak since 'file' == NULL std::cerr << "ERROR : [SW-EM 11] Unable to launch Device process, Please make sure that the XILINX_VITIS environment variable is set correctly" << std::endl; exit(1); } const char* childArgv[6] = { NULL, NULL, NULL, NULL, NULL, NULL } ; childArgv[0] = modelDirectory.c_str() ; // If we determined this should be debuggable, pass the proper // arguments to the process if (debuggable) { childArgv[1] = "-debug" ; childArgv[2] = "-ppid" ; childArgv[3] = pidStream.str().c_str() ; if (passPort) { childArgv[4] = "-port" ; childArgv[5] = portStream.str().c_str() ; } } int r = execl(modelDirectory.c_str(), childArgv[0], childArgv[1], childArgv[2], childArgv[3], childArgv[4], childArgv[5], NULL) ; //fclose (stdout); if(r == -1){std::cerr << "FATAL ERROR : child process did not launch" << std::endl; exit(1);} exit(0); } } sock = new unix_socket; } int CpuemShim::xclLoadXclBin(const xclBin *header) { if(mLogStream.is_open()) mLogStream << __func__ << " begin " << std::endl; std::string xmlFile = "" ; int result = dumpXML(header, xmlFile) ; if (result != 0) return result ; // Before we spawn off the child process, we must determine // if the process will be debuggable or not. We get that // by checking to see if there is a DEBUG_DATA section in // the xclbin file. Note, this only works with xclbin2 // files. Also, the GUI can overwrite this by setting an // environment variable bool debuggable = false ; if (getenv("ENABLE_KERNEL_DEBUG") != NULL && strcmp("true", getenv("ENABLE_KERNEL_DEBUG")) == 0) { char* xclbininmemory = reinterpret_cast<char*>(const_cast<xclBin*>(header)) ; if (!memcmp(xclbininmemory, "xclbin2", 7)) { auto top = reinterpret_cast<const axlf*>(header) ; auto sec = xclbin::get_axlf_section(top, DEBUG_DATA) ; if (sec) { debuggable = true ; } } } std::string binaryDirectory(""); launchDeviceProcess(debuggable,binaryDirectory); if(header) { resetProgram(); if( mFirstBinary ) { mFirstBinary = false; } char *xclbininmemory = reinterpret_cast<char*> (const_cast<xclBin*> (header)); //parse header char *sharedlib = nullptr; int sharedliblength = 0; char* memTopology = nullptr; ssize_t memTopologySize = 0; //check header if (!memcmp(xclbininmemory, "xclbin0", 8)) { if (mLogStream.is_open()) { mLogStream << __func__ << " invalid XCLBIN header " << std::endl; } return -1; } else if (!memcmp(xclbininmemory,"xclbin2",7)) { auto top = reinterpret_cast<const axlf*>(header); if (auto sec = xclbin::get_axlf_section(top,BITSTREAM)) { sharedlib = xclbininmemory + sec->m_sectionOffset; sharedliblength = sec->m_sectionSize; } if (auto sec = xclbin::get_axlf_section(top,MEM_TOPOLOGY)) { memTopologySize = sec->m_sectionSize; memTopology = new char[memTopologySize]; memcpy(memTopology, xclbininmemory + sec->m_sectionOffset, memTopologySize); } } else { if (mLogStream.is_open()) { mLogStream << __func__ << " invalid XCLBIN header " << std::endl; mLogStream << __func__ << " header " << xclbininmemory[0] << xclbininmemory[1] << xclbininmemory[2] << xclbininmemory[3] << xclbininmemory[4] << xclbininmemory[5] << std::endl; } return -1; } //write out shared library to file for consumption with dlopen std::string tempdlopenfilename = binaryDirectory+"/dltmp"; { bool tempfilecreated = false; unsigned int counter = 0; while( !tempfilecreated ) { FILE *fp = fopen(tempdlopenfilename.c_str(),"rb"); if(fp==NULL) { tempfilecreated = true; } else { fclose(fp); std::stringstream ss; ss << std::hex << counter; tempdlopenfilename+=ss.str(); counter = counter+1; } } FILE *fp = fopen(tempdlopenfilename.c_str(),"wb"); if( !fp ) { if(mLogStream.is_open()) mLogStream << __func__ << " failed to create temporary dlopen file" << std::endl; if(memTopology) { delete []memTopology; memTopology = NULL; } return -1; } fwrite(sharedlib,sharedliblength,1,fp); fflush(fp); fclose(fp); } if(memTopology) { const mem_topology* m_mem = (reinterpret_cast<const ::mem_topology*>(memTopology)); if(m_mem) { uint64_t argNum = 0; uint64_t prev_instanceBaseAddr = ULLONG_MAX; std::map<uint64_t, std::pair<uint64_t,std::string> > argFlowIdMap; for (int32_t i=0; i<m_mem->m_count; ++i) { uint64_t flow_id =m_mem->m_mem_data[i].flow_id;//base address + flow_id combo uint64_t instanceBaseAddr = 0xFFFF0000 & flow_id; if(prev_instanceBaseAddr != ULLONG_MAX && instanceBaseAddr != prev_instanceBaseAddr) { //RPC CALL bool success = false; xclSetupInstance_RPC_CALL(xclSetupInstance, prev_instanceBaseAddr , argFlowIdMap); if(mLogStream.is_open()) mLogStream << __func__ << " setup instance: " << prev_instanceBaseAddr <<" success "<< success << std::endl; argFlowIdMap.clear(); argNum = 0; } if(m_mem->m_mem_data[i].m_type == MEM_TYPE::MEM_STREAMING) { std::string m_tag (reinterpret_cast<const char*>(m_mem->m_mem_data[i].m_tag)); std::pair<uint64_t,std::string> mPair; mPair.first = flow_id; mPair.second = m_tag; argFlowIdMap[argNum] = mPair; } argNum++; prev_instanceBaseAddr = instanceBaseAddr; } bool success = false; xclSetupInstance_RPC_CALL(xclSetupInstance, prev_instanceBaseAddr, argFlowIdMap); if(mLogStream.is_open()) mLogStream << __func__ << " setup instance: " << prev_instanceBaseAddr <<" success "<< success << std::endl; } delete []memTopology; memTopology = NULL; } //check xclbin version with vivado tool version xclemulation::checkXclibinVersionWithTool(header); if (mIsKdsSwEmu) { mCore = new exec_core; mSWSch = new SWScheduler(this); mSWSch->init_scheduler_thread(); } bool ack = true; bool verbose = false; if(mLogStream.is_open()) verbose = true; xclLoadBitstream_RPC_CALL(xclLoadBitstream,xmlFile,tempdlopenfilename,deviceDirectory,binaryDirectory,verbose); if(!ack) return -1; } return 0; } int CpuemShim::xclGetDeviceInfo2(xclDeviceInfo2 *info) { std::memset(info, 0, sizeof(xclDeviceInfo2)); fillDeviceInfo(info,&mDeviceInfo); for (auto i : mDDRMemoryManager) { info->mDDRFreeSize += i->freeSize(); } return 0; } void CpuemShim::launchTempProcess() { std::string binaryDirectory(""); launchDeviceProcess(false,binaryDirectory); std::string xmlFile(""); std::string tempdlopenfilename(""); SHIM_UNUSED bool ack = true; bool verbose = false; if(mLogStream.is_open()) verbose = true; xclLoadBitstream_RPC_CALL(xclLoadBitstream,xmlFile,tempdlopenfilename,deviceDirectory,binaryDirectory,verbose); } uint64_t CpuemShim::xclAllocDeviceBuffer(size_t size) { size_t requestedSize = size; if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << size << std::endl; } if(!sock) { launchTempProcess(); } if (size == 0) size = DDR_BUFFER_ALIGNMENT; uint64_t result = xclemulation::MemoryManager::mNull; for (auto i : mDDRMemoryManager) { result = i->alloc(size); if (result != xclemulation::MemoryManager::mNull) break; } bool ack = false; // Memory Manager Has allocated aligned address, // size contains alignement + original size requested. // We are passing original size to device process for exact stats. bool noHostMemory = false; std::string sFileName(""); xclAllocDeviceBuffer_RPC_CALL(xclAllocDeviceBuffer,result,requestedSize,noHostMemory); if(!ack) { PRINTENDFUNC; return 0; } PRINTENDFUNC; return result; } uint64_t CpuemShim::xclAllocDeviceBuffer2(size_t& size, xclMemoryDomains domain, unsigned flags,bool noHostMemory,std::string &sFileName) { if (mLogStream.is_open()) { mLogStream << __func__ <<" , "<<std::this_thread::get_id() << ", " << size <<", "<<domain<<", "<< flags <<std::endl; } if(!sock) { launchTempProcess(); } //flags = flags % 32; if (domain != XCL_MEM_DEVICE_RAM) { return xclemulation::MemoryManager::mNull; } if (size == 0) size = DDR_BUFFER_ALIGNMENT; if (flags >= mDDRMemoryManager.size()) { return xclemulation::MemoryManager::mNull; } uint64_t result = mDDRMemoryManager[flags]->alloc(size); if (result == xclemulation::MemoryManager::mNull) { auto ddrSize = mDDRMemoryManager[flags]->size(); std::string ddrSizeStr = std::to_string(ddrSize); std::string initMsg = "ERROR: [SW-EM 12] OutOfMemoryError : Requested Global memory size exceeds DDR limit " + ddrSizeStr + " Bytes"; std::cout << initMsg << std::endl; return result; } bool ack = false; // Memory Manager Has allocated aligned address, // size contains alignement + original size requested. // We are passing original size to device process for exact stats. xclAllocDeviceBuffer_RPC_CALL(xclAllocDeviceBuffer,result,size,noHostMemory); if(!ack) { PRINTENDFUNC; return 0; } PRINTENDFUNC; return result; } void CpuemShim::xclFreeDeviceBuffer(uint64_t offset) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << offset << std::endl; } for (auto i : mDDRMemoryManager) { if (offset < i->start() + i->size()) { i->free(offset); } } bool ack = true; if(sock) { xclFreeDeviceBuffer_RPC_CALL(xclFreeDeviceBuffer,offset); } if(!ack) { PRINTENDFUNC; return; } PRINTENDFUNC; return; } size_t CpuemShim::xclWrite(xclAddressSpace space, uint64_t offset, const void *hostBuf, size_t size) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << offset<<", "<<hostBuf<<", "<< size<<std::endl; } if(!sock) return size; if(space != XCL_ADDR_KERNEL_CTRL) { if (mLogStream.is_open()) mLogStream << "xclWrite called with xclAddressSpace != XCL_ADDR_KERNEL_CTRL " << std::endl; return -1; } if(size%4) { if (mLogStream.is_open()) mLogStream << "xclWrite only supports 32-bit writes" << std::endl; return -1; } fflush(stdout); xclWriteAddrKernelCtrl_RPC_CALL(xclWriteAddrKernelCtrl,space,offset,hostBuf,size,kernelArgsInfo); PRINTENDFUNC; return size; } size_t CpuemShim::xclRead(xclAddressSpace space, uint64_t offset, void *hostBuf, size_t size) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << space << ", " << offset << ", " << hostBuf << ", " << size << std::endl; } if(!sock) { PRINTENDFUNC; return size; } if(space != XCL_ADDR_KERNEL_CTRL) { if (mLogStream.is_open()) mLogStream << "xclRead called with xclAddressSpace != XCL_ADDR_KERNEL_CTRL " << std::endl; PRINTENDFUNC; return -1; } if(size!=4) { if (mLogStream.is_open()) mLogStream << "xclRead called with size != 4 " << std::endl; PRINTENDFUNC; return -1; } xclReadAddrKernelCtrl_RPC_CALL(xclReadAddrKernelCtrl,space,offset,hostBuf,size); PRINTENDFUNC; return size; } size_t CpuemShim::xclCopyBufferHost2Device(uint64_t dest, const void *src, size_t size, size_t seek) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << dest << ", " << src << ", " << size << ", " << seek << std::endl; } if(!sock) { launchTempProcess(); } src = (unsigned char*)src + seek; dest += seek; void *handle = this; unsigned int messageSize = get_messagesize(); unsigned int c_size = messageSize; unsigned int processed_bytes = 0; while(processed_bytes < size){ if((size - processed_bytes) < messageSize){ c_size = size - processed_bytes; }else{ c_size = messageSize; } void* c_src = (((unsigned char*)(src)) + processed_bytes); uint64_t c_dest = dest + processed_bytes; #ifndef _WINDOWS uint32_t space =0; xclCopyBufferHost2Device_RPC_CALL(xclCopyBufferHost2Device,handle,c_dest,c_src,c_size,seek,space); #endif processed_bytes += c_size; } return size; } size_t CpuemShim::xclCopyBufferDevice2Host(void *dest, uint64_t src, size_t size, size_t skip) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << dest << ", " << src << ", " << size << ", " << skip << std::endl; } dest = ((unsigned char*)dest) + skip; if(!sock) { launchTempProcess(); } src += skip; void *handle = this; unsigned int messageSize = get_messagesize(); unsigned int c_size = messageSize; unsigned int processed_bytes = 0; while(processed_bytes < size){ if((size - processed_bytes) < messageSize){ c_size = size - processed_bytes; }else{ c_size = messageSize; } void* c_dest = (((unsigned char*)(dest)) + processed_bytes); uint64_t c_src = src + processed_bytes; #ifndef _WINDOWS uint32_t space =0; xclCopyBufferDevice2Host_RPC_CALL(xclCopyBufferDevice2Host,handle,c_dest,c_src,c_size,skip,space); #endif processed_bytes += c_size; } return size; } void CpuemShim::xclOpen(const char* logfileName) { xclemulation::config::getInstance()->populateEnvironmentSetup(mEnvironmentNameValueMap); if( logfileName && (logfileName[0] != '\0')) { mLogStream.open(logfileName); mLogStream << "FUNCTION, THREAD ID, ARG..." << std::endl; mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } // Shim object creation doesn't follow xclOpen/xclClose. // The core device must correspond to open and close, so // create here rather than in constructor mCoreDevice = xrt_core::swemu::get_userpf_device(this, mDeviceIndex); } void CpuemShim::fillDeviceInfo(xclDeviceInfo2* dest, xclDeviceInfo2* src) { std::strcpy(dest->mName, src->mName); dest->mMagic = src->mMagic ; dest->mHALMajorVersion = src->mHALMajorVersion; dest->mHALMinorVersion = src->mHALMinorVersion; dest->mVendorId = src->mVendorId; dest->mDeviceId = src->mDeviceId; dest->mSubsystemVendorId = src->mSubsystemVendorId; dest->mDeviceVersion = src->mDeviceVersion; dest->mDDRSize = src->mDDRSize; dest->mDataAlignment = src->mDataAlignment; dest->mDDRBankCount = src->mDDRBankCount; for(unsigned int i = 0; i < 4 ;i++) dest->mOCLFrequency[i] = src->mOCLFrequency[i]; } void CpuemShim::saveDeviceProcessOutput() { if(!sock) return; for(int i = binaryCounter-1; i >= 0; i--) { std::stringstream sw_emu_folder; sw_emu_folder <<deviceDirectory<<"/binary_"<<i; char path[FILENAME_MAX]; size_t size = PATH_MAX; char* pPath = GetCurrentDir(path,size); if(pPath) { std::string debugFilePath = sw_emu_folder.str()+"/genericpcieoutput"; std::string destPath = std::string(path) + "/genericpcieoutput_device"+ std::to_string(mDeviceIndex) + "_"+std::to_string(i); systemUtil::makeSystemCall(debugFilePath, systemUtil::systemOperation::COPY,destPath); } } } void CpuemShim::resetProgram(bool callingFromClose) { for (auto& it: mFdToFileNameMap) { int fd=it.first; int sSize = std::get<1>(it.second); void* addr = std::get<2>(it.second); munmap(addr,sSize); close(fd); } mFdToFileNameMap.clear(); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } if (!sock) { PRINTENDFUNC if (mIsKdsSwEmu && mSWSch && mCore) { mSWSch->fini_scheduler_thread(); delete mCore; mCore = nullptr; delete mSWSch; mSWSch = nullptr; } return; } std::string socketName = sock->get_name(); if(socketName.empty() == false)// device is active if socketName is non-empty { #ifndef _WINDOWS xclClose_RPC_CALL(xclClose,this); #endif } saveDeviceProcessOutput(); } void CpuemShim::xclClose() { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } // Shim object is not deleted as part of closing device. // The core device must correspond to open and close, so // reset here rather than in destructor mCoreDevice.reset(); if(!sock) { if( xclemulation::config::getInstance()->isKeepRunDirEnabled() == false) systemUtil::makeSystemCall(deviceDirectory, systemUtil::systemOperation::REMOVE); if (mIsKdsSwEmu && mSWSch && mCore) { mSWSch->fini_scheduler_thread(); delete mCore; mCore = nullptr; delete mSWSch; mSWSch = nullptr; } return; } for (auto& it: mFdToFileNameMap) { int fd=it.first; int sSize = std::get<1>(it.second); void* addr = std::get<2>(it.second); munmap(addr,sSize); close(fd); } mFdToFileNameMap.clear(); mCloseAll = true; std::string socketName = sock->get_name(); if(socketName.empty() == false)// device is active if socketName is non-empty { #ifndef _WINDOWS xclClose_RPC_CALL(xclClose,this); #endif } mCloseAll = false; int status = 0; bool simDontRun = xclemulation::config::getInstance()->isDontRun(); if(!simDontRun) while (-1 == waitpid(0, &status, 0)); systemUtil::makeSystemCall(socketName, systemUtil::systemOperation::REMOVE); delete sock; sock = nullptr; PRINTENDFUNC; if (mIsKdsSwEmu && mSWSch && mCore) { mSWSch->fini_scheduler_thread(); delete mCore; mCore = nullptr; delete mSWSch; mSWSch = nullptr; } //clean up directories which are created inside the driver if( xclemulation::config::getInstance()->isKeepRunDirEnabled() == false) { //TODO sleeping for some time sothat gdb releases the process and its contents sleep(5); systemUtil::makeSystemCall(deviceDirectory, systemUtil::systemOperation::REMOVE); } google::protobuf::ShutdownProtobufLibrary(); } CpuemShim::~CpuemShim() { if (mIsKdsSwEmu && mSWSch && mCore) { mSWSch->fini_scheduler_thread(); delete mCore; mCore = nullptr; delete mSWSch; mSWSch = nullptr; } if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } free(ci_buf); free(ri_buf); free(buf); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; mLogStream.close(); } if (mLogStream.is_open()) { mLogStream.close(); } } /**********************************************HAL2 API's START HERE **********************************************/ /*********************************** Utility ******************************************/ xclemulation::drm_xocl_bo* CpuemShim::xclGetBoByHandle(unsigned int boHandle) { auto it = mXoclObjMap.find(boHandle); if(it == mXoclObjMap.end()) return nullptr; xclemulation::drm_xocl_bo* bo = (*it).second; return bo; } inline unsigned short CpuemShim::xocl_ddr_channel_count() { return mDeviceInfo.mDDRBankCount; } inline unsigned long long CpuemShim::xocl_ddr_channel_size() { return 0; } int CpuemShim::xclGetBOProperties(unsigned int boHandle, xclBOProperties *properties) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boHandle << std::endl; } xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(boHandle); if (!bo) { PRINTENDFUNC; return -1; } properties->handle = bo->handle; properties->flags = bo->flags; properties->size = bo->size; properties->paddr = bo->base; PRINTENDFUNC; return 0; } /*****************************************************************************************/ /******************************** xclAllocBO *********************************************/ uint64_t CpuemShim::xoclCreateBo(xclemulation::xocl_create_bo* info) { size_t size = info->size; unsigned ddr = xclemulation::xocl_bo_ddr_idx(info->flags); if (!size) return -1; // system linker doesnt run in sw_emu. if ddr idx morethan ddr_count, then create it in 0 by considering all plrams in zero'th ddr const unsigned ddr_count = xocl_ddr_channel_count(); if(ddr_count <= ddr) { ddr = 0; } //struct xclemulation::drm_xocl_bo *xobj = new xclemulation::drm_xocl_bo; auto xobj = std::make_unique<xclemulation::drm_xocl_bo>(); xobj->flags=info->flags; /* check whether buffer is p2p or not*/ bool noHostMemory = xclemulation::no_host_memory(xobj.get()); std::string sFileName(""); xobj->base = xclAllocDeviceBuffer2(size,XCL_MEM_DEVICE_RAM,ddr,noHostMemory,sFileName); xobj->filename = sFileName; xobj->size = size; xobj->userptr = NULL; xobj->buf = NULL; xobj->fd = -1; if (xobj->base == xclemulation::MemoryManager::mNull) { return xclemulation::MemoryManager::mNull; } info->handle = mBufferCount; mXoclObjMap[mBufferCount++] = xobj.release(); return 0; } unsigned int CpuemShim::xclAllocBO(size_t size, int unused, unsigned flags) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << size << std::dec << " , "<< unused <<" , "<< flags << std::endl; } xclemulation::xocl_create_bo info = {size, mNullBO, flags}; uint64_t result = xoclCreateBo(&info); PRINTENDFUNC; return result ? mNullBO : info.handle; } /***************************************************************************************/ /******************************** xclAllocUserPtrBO ************************************/ unsigned int CpuemShim::xclAllocUserPtrBO(void *userptr, size_t size, unsigned flags) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << userptr <<", " << std::hex << size << std::dec <<" , "<< flags << std::endl; } xclemulation::xocl_create_bo info = {size, mNullBO, flags}; uint64_t result = xoclCreateBo(&info); xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(info.handle); if (bo) { bo->userptr = userptr; } PRINTENDFUNC; return result ? mNullBO : info.handle; } /***************************************************************************************/ /******************************** xclExportBO *******************************************/ int CpuemShim::xclExportBO(unsigned int boHandle) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boHandle << std::endl; } xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(boHandle); if(!bo) return -1; std::string sFileName = bo->filename; if(sFileName.empty()) { std::cout<<"Exported Buffer is not P2P "<<std::endl; PRINTENDFUNC; return -1; } uint64_t size = bo->size; int fd = open(sFileName.c_str(), (O_CREAT | O_RDWR), 0666); if (fd == -1) { printf("Error opening exported BO file.\n"); PRINTENDFUNC; return -1; }; char* data = (char*) mmap(0, bo->size , PROT_READ |PROT_WRITE |PROT_EXEC , MAP_SHARED, fd, 0); if(!data) { PRINTENDFUNC; return -1; } int fR = ftruncate(fd, bo->size); if(fR == -1) { close(fd); munmap(data,bo->size); return -1; } mFdToFileNameMap [fd] = std::make_tuple(sFileName,size,(void*)data); PRINTENDFUNC; return fd; } /***************************************************************************************/ /******************************** xclImportBO *******************************************/ unsigned int CpuemShim::xclImportBO(int boGlobalHandle, unsigned flags) { //TODO if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boGlobalHandle << std::endl; } auto itr = mFdToFileNameMap.find(boGlobalHandle); if(itr != mFdToFileNameMap.end()) { const std::string& fileName = std::get<0>((*itr).second); int size = std::get<1>((*itr).second); unsigned int importedBo = xclAllocBO(size, 0,flags); xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(importedBo); if(!bo) { std::cout<<"ERROR HERE in importBO "<<std::endl; return -1; } mImportedBOs.insert(importedBo); bo->fd = boGlobalHandle; bool ack; xclImportBO_RPC_CALL(xclImportBO,fileName,bo->base,size); if(!ack) return -1; PRINTENDFUNC; return importedBo; } return -1; } /***************************************************************************************/ /******************************** xclCopyBO *******************************************/ int CpuemShim::xclCopyBO(unsigned int dst_boHandle, unsigned int src_boHandle, size_t size, size_t dst_offset, size_t src_offset) { std::lock_guard<std::mutex> lk(mApiMtx); //TODO if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << dst_boHandle <<" , "<< src_boHandle << " , "<< size <<"," << dst_offset << "," <<src_offset<< std::endl; } xclemulation::drm_xocl_bo* sBO = xclGetBoByHandle(src_boHandle); if(!sBO) { PRINTENDFUNC; return -1; } xclemulation::drm_xocl_bo* dBO = xclGetBoByHandle(dst_boHandle); if(!dBO) { PRINTENDFUNC; return -1; } if(dBO->fd < 0) { std::cout<<"bo is not exported for copying"<<std::endl; return -1; } int ack = false; auto fItr = mFdToFileNameMap.find(dBO->fd); if(fItr != mFdToFileNameMap.end()) { const std::string& sFileName = std::get<0>((*fItr).second); xclCopyBO_RPC_CALL(xclCopyBO,sBO->base,sFileName,size,src_offset,dst_offset); } if(!ack) return -1; PRINTENDFUNC; return 0; } /***************************************************************************************/ /******************************** xclMapBO *********************************************/ void *CpuemShim::xclMapBO(unsigned int boHandle, bool write) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boHandle << " , " << write << std::endl; } xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(boHandle); if (!bo) { PRINTENDFUNC; return nullptr; } std::string sFileName = bo->filename; if(!sFileName.empty() ) { int fd = open(sFileName.c_str(), (O_CREAT | O_RDWR), 0666); if (fd == -1) { printf("Error opening exported BO file.\n"); return nullptr; }; char* data = (char*) mmap(0, bo->size , PROT_READ |PROT_WRITE |PROT_EXEC , MAP_SHARED, fd, 0); if(!data) return nullptr; int fR = ftruncate(fd, bo->size); if(fR == -1) { close(fd); munmap(data,bo->size); return nullptr; } mFdToFileNameMap [fd] = std::make_tuple(sFileName,bo->size,(void*)data); bo->buf = data; PRINTENDFUNC; return data; } void *pBuf=nullptr; if (posix_memalign(&pBuf, getpagesize(), bo->size)) { if (mLogStream.is_open()) mLogStream << "posix_memalign failed" << std::endl; pBuf=nullptr; } bo->buf = pBuf; PRINTENDFUNC; return pBuf; } int CpuemShim::xclUnmapBO(unsigned int boHandle, void* addr) { std::lock_guard<std::mutex> lk(mApiMtx); auto bo = xclGetBoByHandle(boHandle); return bo ? munmap(addr,bo->size) : -1; } /**************************************************************************************/ /******************************** xclSyncBO *******************************************/ int CpuemShim::xclSyncBO(unsigned int boHandle, xclBOSyncDirection dir, size_t size, size_t offset) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boHandle << " , " << std::endl; } xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(boHandle); if(!bo) { PRINTENDFUNC; return -1; } int returnVal = 0; if(dir == XCL_BO_SYNC_BO_TO_DEVICE) { void* buffer = bo->userptr ? bo->userptr : bo->buf; if (xclCopyBufferHost2Device(bo->base,buffer, size, offset) != size) { returnVal = EIO; } } else { void* buffer = bo->userptr ? bo->userptr : bo->buf; if (xclCopyBufferDevice2Host(buffer, bo->base, size, offset) != size) { returnVal = EIO; } } PRINTENDFUNC; return returnVal; } /***************************************************************************************/ /******************************** xclFreeBO *******************************************/ void CpuemShim::xclFreeBO(unsigned int boHandle) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boHandle << std::endl; } auto it = mXoclObjMap.find(boHandle); if(it == mXoclObjMap.end()) { PRINTENDFUNC; return; } xclemulation::drm_xocl_bo* bo = (*it).second;; if(bo) { xclFreeDeviceBuffer(bo->base); mXoclObjMap.erase(it); } PRINTENDFUNC; } /***************************************************************************************/ /******************************** xclWriteBO *******************************************/ size_t CpuemShim::xclWriteBO(unsigned int boHandle, const void *src, size_t size, size_t seek) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boHandle << " , "<< src <<" , "<< size << ", " << seek << std::endl; } xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(boHandle); if(!bo) { PRINTENDFUNC; return -1; } size_t returnVal = 0; if (xclCopyBufferHost2Device(bo->base, src, size, seek) != size) { returnVal = EIO; } PRINTENDFUNC; return returnVal; } /***************************************************************************************/ /******************************** xclReadBO *******************************************/ size_t CpuemShim::xclReadBO(unsigned int boHandle, void *dst, size_t size, size_t skip) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boHandle << " , "<< dst <<" , "<< size << ", " << skip << std::endl; } xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(boHandle); if(!bo) { PRINTENDFUNC; return -1; } size_t returnVal = 0; if (xclCopyBufferDevice2Host(dst, bo->base, size, skip) != size) { returnVal = EIO; } PRINTENDFUNC; return returnVal; } /***************************************************************************************/ /********************************************** QDMA APIs IMPLEMENTATION START **********************************************/ /* * xclCreateWriteQueue() */ int CpuemShim::xclCreateWriteQueue(xclQueueContext *q_ctx, uint64_t *q_hdl) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; uint64_t q_handle = 0; xclCreateQueue_RPC_CALL(xclCreateQueue,q_ctx,true); if(q_handle <= 0) { if (mLogStream.is_open()) mLogStream << " unable to create write queue "<<std::endl; PRINTENDFUNC; return -1; } *q_hdl = q_handle; PRINTENDFUNC; return 0; } /* * xclCreateReadQueue() */ int CpuemShim::xclCreateReadQueue(xclQueueContext *q_ctx, uint64_t *q_hdl) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } uint64_t q_handle = 0; xclCreateQueue_RPC_CALL(xclCreateQueue,q_ctx,false); if(q_handle <= 0) { if (mLogStream.is_open()) mLogStream << " unable to create read queue "<<std::endl; PRINTENDFUNC; return -1; } *q_hdl = q_handle; PRINTENDFUNC; return 0; } /* * xclDestroyQueue() */ int CpuemShim::xclDestroyQueue(uint64_t q_hdl) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } uint64_t q_handle = q_hdl; bool success = false; xclDestroyQueue_RPC_CALL(xclDestroyQueue, q_handle); if(!success) { if (mLogStream.is_open()) mLogStream <<" unable to destroy the queue"<<std::endl; PRINTENDFUNC; return -1; } PRINTENDFUNC; return 0; } /* * xclWriteQueue() */ ssize_t CpuemShim::xclWriteQueue(uint64_t q_hdl, xclQueueRequest *wr) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } bool eot = false; if(wr->flag & XCL_QUEUE_REQ_EOT) eot = true; bool nonBlocking = false; if (wr->flag & XCL_QUEUE_REQ_NONBLOCKING) { std::map<uint64_t,uint64_t> vaLenMap; for (unsigned i = 0; i < wr->buf_num; i++) { vaLenMap[wr->bufs[i].va] = wr->bufs[i].len; } mReqList.push_back(std::make_tuple(mReqCounter, wr->priv_data, vaLenMap)); nonBlocking = true; } uint64_t fullSize = 0; for (unsigned i = 0; i < wr->buf_num; i++) { xclWriteQueue_RPC_CALL(xclWriteQueue,q_hdl, wr->bufs[i].va, wr->bufs[i].len); fullSize += written_size; } PRINTENDFUNC; mReqCounter++; return fullSize; } /* * xclReadQueue() */ ssize_t CpuemShim::xclReadQueue(uint64_t q_hdl, xclQueueRequest *rd) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } bool eot = false; if(rd->flag & XCL_QUEUE_REQ_EOT) eot = true; bool nonBlocking = false; if (rd->flag & XCL_QUEUE_REQ_NONBLOCKING) { nonBlocking = true; std::map<uint64_t,uint64_t> vaLenMap; for (unsigned i = 0; i < rd->buf_num; i++) { vaLenMap[rd->bufs[i].va] = rd->bufs[i].len; } mReqList.push_back(std::make_tuple(mReqCounter,rd->priv_data, vaLenMap)); } void *dest; uint64_t fullSize = 0; for (unsigned i = 0; i < rd->buf_num; i++) { dest = (void *)rd->bufs[i].va; uint64_t read_size = 0; do { xclReadQueue_RPC_CALL(xclReadQueue,q_hdl, dest , rd->bufs[i].len); } while (read_size == 0 && !nonBlocking); fullSize += read_size; } mReqCounter++; PRINTENDFUNC; return fullSize; } /* * xclPollCompletion */ int CpuemShim::xclPollCompletion(int min_compl, int max_compl, xclReqCompletion *comps, int* actual, int timeout) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << " , "<< max_compl <<", "<<min_compl<<" ," << *actual <<" ," << timeout << std::endl; } // struct timespec time, *ptime = NULL; // // if (timeout > 0) // { // memset(&time, 0, sizeof(time)); // time.tv_sec = timeout / 1000; // time.tv_nsec = (timeout % 1000) * 1000000; // ptime = &time; // } *actual = 0; while(*actual < min_compl) { std::list<std::tuple<uint64_t ,void*, std::map<uint64_t,uint64_t> > >::iterator it = mReqList.begin(); while ( it != mReqList.end() ) { unsigned numBytesProcessed = 0; uint64_t reqCounter = std::get<0>(*it); void* priv_data = std::get<1>(*it); std::map<uint64_t,uint64_t>vaLenMap = std::get<2>(*it); xclPollCompletion_RPC_CALL(xclPollCompletion,reqCounter,vaLenMap); if(numBytesProcessed > 0) { comps[*actual].priv_data = priv_data; comps[*actual].nbytes = numBytesProcessed; (*actual)++; mReqList.erase(it++); } else { it++; } } } PRINTENDFUNC; return (*actual); } /* * xclAllocQDMABuf() */ void * CpuemShim::xclAllocQDMABuf(size_t size, uint64_t *buf_hdl) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } void *pBuf=nullptr; if (posix_memalign(&pBuf, sizeof(double)*16, size)) { if (mLogStream.is_open()) mLogStream << "posix_memalign failed" << std::endl; pBuf=nullptr; return pBuf; } memset(pBuf, 0, size); PRINTENDFUNC; return pBuf; } /* * xclFreeQDMABuf() */ int CpuemShim::xclFreeQDMABuf(uint64_t buf_hdl) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } PRINTENDFUNC; return 0;//TODO } /* * xclLogMsg() */ int CpuemShim::xclLogMsg(xclDeviceHandle handle, xrtLogMsgLevel level, const char* tag, const char* format, va_list args1) { int len = std::vsnprintf(nullptr, 0, format, args1); if (len < 0) { //illegal arguments std::string err_str = "ERROR: Illegal arguments in log format string. "; err_str.append(std::string(format)); xrt_core::message::send((xrt_core::message::severity_level)level, tag, err_str.c_str()); return len; } len++; //To include null terminator std::vector<char> buf(len); len = std::vsnprintf(buf.data(), len, format, args1); if (len < 0) { //error processing arguments std::string err_str = "ERROR: When processing arguments in log format string. "; err_str.append(std::string(format)); xrt_core::message::send((xrt_core::message::severity_level)level, tag, err_str.c_str()); return len; } xrt_core::message::send((xrt_core::message::severity_level)level, tag, buf.data()); return 0; } /* * xclOpenContext */ int CpuemShim::xclOpenContext(const uuid_t xclbinId, unsigned int ipIndex, bool shared) const { return 0; } /* * xclExecWait */ int CpuemShim::xclExecWait(int timeoutMilliSec) { //unsigned int tSec = 0; //static bool bConfig = true; //tSec = timeoutMilliSec / 1000; //if (bConfig) //{ // tSec = timeoutMilliSec / 1000; // bConfig = false; //} //sleep(tSec); //PRINTENDFUNC; return 1; } /* * xclExecBuf */ int CpuemShim::xclExecBuf(unsigned int cmdBO) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << cmdBO << std::endl; } if (!mIsKdsSwEmu) return 0; xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(cmdBO); if (!mSWSch || !bo) { PRINTENDFUNC; return -1; } int ret = mSWSch->add_exec_buffer(mCore, bo); PRINTENDFUNC; return ret; } /* * xclCloseContext */ int CpuemShim::xclCloseContext(const uuid_t xclbinId, unsigned int ipIndex) const { return 0; } /********************************************** QDMA APIs IMPLEMENTATION END**********************************************/ /**********************************************HAL2 API's END HERE **********************************************/ }
#include <iostream> #include <vector> #include <string> using namespace std; bool is_before(string first, string second){ if(first[0] != second[0]) return first[0] < second[0]; else{ if(first.size() > 1 && second.size() > 1) return is_before(first.substr(1), second.substr(1)); if(first.size() == 1) return true; else return false; } } int main(){ ios_base::sync_with_stdio (false); vector<string> names; vector<int> attack; vector<int> defense; int cases, c, i, j, atta, defe; string name; cin >> cases; for(c = 1; c <= cases; c++){ cout << "Case " << c << ":\n"; names.clear(); attack.clear(); defense.clear(); for(i = 0; i < 10; i++){ cin >> name >> atta >> defe; names.push_back(name); attack.push_back(atta); defense.push_back(defe); } for(i = 1; i < 10; i++){ j = i-1; name = names[i]; atta = attack[i]; defe = defense[i]; while(j >= 0 && !is_before(name, names[j])){ names[j+1] = names[j]; attack[j+1] = attack[j]; defense[j+1] = defense[j]; j--; } names[j+1] = name; attack[j+1] = atta; defense[j+1] = defe; } for(i = 1; i < 10; i++){ j = i-1; name = names[i]; atta = attack[i]; defe = defense[i]; while(j >= 0 && defense[j] < defe){ names[j+1] = names[j]; attack[j+1] = attack[j]; defense[j+1] = defense[j]; j--; } names[j+1] = name; attack[j+1] = atta; defense[j+1] = defe; } for(i = 1; i < 10; i++){ j = i-1; name = names[i]; atta = attack[i]; while(j >= 0 && attack[j] > atta){ names[j+1] = names[j]; attack[j+1] = attack[j]; j--; } names[j+1] = name; attack[j+1] = atta; } for(i = 1; i < 5; i++){ j = i-1; name = names[i]; while(j >= 0 && is_before(name, names[j])){ names[j+1] = names[j]; j--; } names[j+1] = name; } for(i = 5; i < 10; i++){ j = i-1; name = names[i]; while(j >= 5 && is_before(name, names[j])){ names[j+1] = names[j]; j--; } names[j+1] = name; } cout << "(" << names[5] << ", " << names[6] << ", " << names[7] << ", " << names[8] << ", " << names[9] << ")\n"; cout << "(" << names[0] << ", " << names[1] << ", " << names[2] << ", " << names[3] << ", " << names[4] << ")\n"; } return 0; }
#include<bits/stdc++.h> using namespace std; ifstream fin("fact.in"); ofstream fout("fact.out"); int main() { int n,k; fin>>n>>k; long double lg=.0L; for(int i=1;i<=n;i++) lg+=log10((long double)i); int len=floor(lg); fout.precision(k); fout<<pow(10.0L,lg-len)<<"e+"<<len<<endl; return 0; }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "pow.h" #include "chain.h" #include "chainparams.h" #include "primitives/block.h" #include "uint256.h" #include "util.h" unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock) { unsigned int nProofOfWorkLimit = Params().ProofOfWorkLimit().GetCompact(); // Genesis block if (pindexLast == NULL) return nProofOfWorkLimit; // Only change once per interval if ((pindexLast->nHeight+1) % Params().Interval() != 0) { if (Params().AllowMinDifficultyBlocks()) { // Special difficulty rule for testnet: // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + Params().TargetSpacing()*2) return nProofOfWorkLimit; else { // Return the last non-special-min-difficulty-rules-block const CBlockIndex* pindex = pindexLast; while (pindex->pprev && pindex->nHeight % Params().Interval() != 0 && pindex->nBits == nProofOfWorkLimit) pindex = pindex->pprev; return pindex->nBits; } } return pindexLast->nBits; } // Merelcoin: This fixes an issue where a 51% attack can change difficulty at will. // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz int blockstogoback = Params().Interval()-1; if ((pindexLast->nHeight+1) != Params().Interval()) blockstogoback = Params().Interval(); // Go back by what we want to be 14 days worth of blocks const CBlockIndex* pindexFirst = pindexLast; for (int i = 0; pindexFirst && i < blockstogoback; i++) pindexFirst = pindexFirst->pprev; assert(pindexFirst); // Limit adjustment step int64_t nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime(); LogPrintf(" nActualTimespan = %d before bounds\n", nActualTimespan); if (nActualTimespan < Params().TargetTimespan()/4) nActualTimespan = Params().TargetTimespan()/4; if (nActualTimespan > Params().TargetTimespan()*4) nActualTimespan = Params().TargetTimespan()*4; // Retarget uint256 bnNew; uint256 bnOld; bnNew.SetCompact(pindexLast->nBits); bnOld = bnNew; // Merelcoin: intermediate uint256 can overflow by 1 bit bool fShift = bnNew.bits() > 235; if (fShift) bnNew >>= 1; bnNew *= nActualTimespan; bnNew /= Params().TargetTimespan(); if (fShift) bnNew <<= 1; if (bnNew > Params().ProofOfWorkLimit()) bnNew = Params().ProofOfWorkLimit(); /// debug print LogPrintf("GetNextWorkRequired RETARGET\n"); LogPrintf("Params().TargetTimespan() = %d nActualTimespan = %d\n", Params().TargetTimespan(), nActualTimespan); LogPrintf("Before: %08x %s\n", pindexLast->nBits, bnOld.ToString()); LogPrintf("After: %08x %s\n", bnNew.GetCompact(), bnNew.ToString()); return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, unsigned int nBits) { bool fNegative; bool fOverflow; uint256 bnTarget; if (Params().SkipProofOfWorkCheck()) return true; bnTarget.SetCompact(nBits, &fNegative, &fOverflow); // Check range if (fNegative || bnTarget == 0 || fOverflow || bnTarget > Params().ProofOfWorkLimit()) return error("CheckProofOfWork() : nBits below minimum work"); // Check proof of work matches claimed amount if (hash > bnTarget) return error("CheckProofOfWork() : hash doesn't match nBits"); return true; } uint256 GetBlockProof(const CBlockIndex& block) { uint256 bnTarget; bool fNegative; bool fOverflow; bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow); if (fNegative || fOverflow || bnTarget == 0) return 0; // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256 // as it's too large for a uint256. However, as 2**256 is at least as large // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1, // or ~bnTarget / (nTarget+1) + 1. return (~bnTarget / (bnTarget + 1)) + 1; }
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2005-2008. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/container for documentation. // ////////////////////////////////////////////////////////////////////////////// // // This code comes from N1953 document by Howard E. Hinnant // ////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_CONTAINERS_DETAIL_VERSION_TYPE_HPP #define BOOST_CONTAINERS_DETAIL_VERSION_TYPE_HPP #include <boost/interprocess/containers/container/detail/mpl.hpp> #include <boost/interprocess/containers/container/detail/type_traits.hpp> namespace boost{ namespace interprocess_container { namespace containers_detail { //using namespace boost; template <class T, unsigned V> struct version_type : public containers_detail::integral_constant<unsigned, V> { typedef T type; version_type(const version_type<T, 0>&); }; namespace impl{ template <class T, bool = containers_detail::is_convertible<version_type<T, 0>, typename T::version>::value> struct extract_version { static const unsigned value = 1; }; template <class T> struct extract_version<T, true> { static const unsigned value = T::version::value; }; template <class T> struct has_version { private: struct two {char _[2];}; template <class U> static two test(...); template <class U> static char test(const typename U::version*); public: static const bool value = sizeof(test<T>(0)) == 1; void dummy(){} }; template <class T, bool = has_version<T>::value> struct version { static const unsigned value = 1; }; template <class T> struct version<T, true> { static const unsigned value = extract_version<T>::value; }; } //namespace impl template <class T> struct version : public containers_detail::integral_constant<unsigned, impl::version<T>::value> { }; } //namespace containers_detail { } //namespace interprocess_container { } //namespace boost{ #endif //#define BOOST_CONTAINERS_DETAIL_VERSION_TYPE_HPP
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ /*! \class QGraphicsItem \brief The QGraphicsItem class is the base class for all graphical items in a QGraphicsScene. \since 4.2 \ingroup graphicsview-api It provides a light-weight foundation for writing your own custom items. This includes defining the item's geometry, collision detection, its painting implementation and item interaction through its event handlers. QGraphicsItem is part of the \l{Graphics View Framework} \image graphicsview-items.png For convenience, Qt provides a set of standard graphics items for the most common shapes. These are: \list \o QGraphicsEllipseItem provides an ellipse item \o QGraphicsLineItem provides a line item \o QGraphicsPathItem provides an arbitrary path item \o QGraphicsPixmapItem provides a pixmap item \o QGraphicsPolygonItem provides a polygon item \o QGraphicsRectItem provides a rectangular item \o QGraphicsSimpleTextItem provides a simple text label item \o QGraphicsTextItem provides an advanced text browser item \endlist All of an item's geometric information is based on its local coordinate system. The item's position, pos(), is the only function that does not operate in local coordinates, as it returns a position in parent coordinates. \l {The Graphics View Coordinate System} describes the coordinate system in detail. You can set whether an item should be visible (i.e., drawn, and accepting events), by calling setVisible(). Hiding an item will also hide its children. Similarly, you can enable or disable an item by calling setEnabled(). If you disable an item, all its children will also be disabled. By default, items are both visible and enabled. To toggle whether an item is selected or not, first enable selection by setting the ItemIsSelectable flag, and then call setSelected(). Normally, selection is toggled by the scene, as a result of user interaction. To write your own graphics item, you first create a subclass of QGraphicsItem, and then start by implementing its two pure virtual public functions: boundingRect(), which returns an estimate of the area painted by the item, and paint(), which implements the actual painting. For example: \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 0 The boundingRect() function has many different purposes. QGraphicsScene bases its item index on boundingRect(), and QGraphicsView uses it both for culling invisible items, and for determining the area that needs to be recomposed when drawing overlapping items. In addition, QGraphicsItem's collision detection mechanisms use boundingRect() to provide an efficient cut-off. The fine grained collision algorithm in collidesWithItem() is based on calling shape(), which returns an accurate outline of the item's shape as a QPainterPath. QGraphicsScene expects all items boundingRect() and shape() to remain unchanged unless it is notified. If you want to change an item's geometry in any way, you must first call prepareGeometryChange() to allow QGraphicsScene to update its bookkeeping. Collision detection can be done in two ways: \list 1 \o Reimplement shape() to return an accurate shape for your item, and rely on the default implementation of collidesWithItem() to do shape-shape intersection. This can be rather expensive if the shapes are complex. \o Reimplement collidesWithItem() to provide your own custom item and shape collision algorithm. \endlist The contains() function can be called to determine whether the item \e contains a point or not. This function can also be reimplemented by the item. The default behavior of contains() is based on calling shape(). Items can contain other items, and also be contained by other items. All items can have a parent item and a list of children. Unless the item has no parent, its position is in \e parent coordinates (i.e., the parent's local coordinates). Parent items propagate both their position and their transformation to all children. \img graphicsview-parentchild.png \target Transformations \section1 Transformations QGraphicsItem supports projective transformations in addition to its base position, pos(). There are several ways to change an item's transformation. For simple transformations, you can call either of the convenience functions setRotation() or setScale(), or you can pass any transformation matrix to setTransform(). For advanced transformation control you also have the option of setting several combined transformations by calling setTransformations(). Item transformations accumulate from parent to child, so if both a parent and child item are rotated 90 degrees, the child's total transformation will be 180 degrees. Similarly, if the item's parent is scaled to 2x its original size, its children will also be twice as large. An item's transformation does not affect its own local geometry; all geometry functions (e.g., contains(), update(), and all the mapping functions) still operate in local coordinates. For convenience, QGraphicsItem provides the functions sceneTransform(), which returns the item's total transformation matrix (including its position and all parents' positions and transformations), and scenePos(), which returns its position in scene coordinates. To reset an item's matrix, call resetTransform(). Certain transformation operations produce a different outcome depending on the order in which they are applied. For example, if you scale an transform, and then rotate it, you may get a different result than if the transform was rotated first. However, the order you set the transformation properties on QGraphicsItem does not affect the resulting transformation; QGraphicsItem always applies the properties in a fixed, defined order: \list \o The item's base transform is applied (transform()) \o The item's transformations list is applied in order (transformations()) \o The item is rotated relative to its transform origin point (rotation(), transformOriginPoint()) \o The item is scaled relative to its transform origin point (scale(), transformOriginPoint()) \endlist \section1 Painting The paint() function is called by QGraphicsView to paint the item's contents. The item has no background or default fill of its own; whatever is behind the item will shine through all areas that are not explicitly painted in this function. You can call update() to schedule a repaint, optionally passing the rectangle that needs a repaint. Depending on whether or not the item is visible in a view, the item may or may not be repainted; there is no equivalent to QWidget::repaint() in QGraphicsItem. Items are painted by the view, starting with the parent items and then drawing children, in ascending stacking order. You can set an item's stacking order by calling setZValue(), and test it by calling zValue(), where items with low z-values are painted before items with high z-values. Stacking order applies to sibling items; parents are always drawn before their children. \section1 Sorting All items are drawn in a defined, stable order, and this same order decides which items will receive mouse input first when you click on the scene. Normally you don't have to worry about sorting, as the items follow a "natural order", following the logical structure of the scene. An item's children are stacked on top of the parent, and sibling items are stacked by insertion order (i.e., in the same order that they were either added to the scene, or added to the same parent). If you add item A, and then B, then B will be on top of A. If you then add C, the items' stacking order will be A, then B, then C. \image graphicsview-zorder.png This example shows the stacking order of all limbs of the robot from the \l{graphicsview/dragdroprobot}{Drag and Drop Robot} example. The torso is the root item (all other items are children or descendants of the torso), so it is drawn first. Next, the head is drawn, as it is the first item in the torso's list of children. Then the upper left arm is drawn. As the lower arm is a child of the upper arm, the lower arm is then drawn, followed by the upper arm's next sibling, which is the upper right arm, and so on. For advanced users, there are ways to alter how your items are sorted: \list \o You can call setZValue() on an item to explicitly stack it on top of, or under, other sibling items. The default Z value for an item is 0. Items with the same Z value are stacked by insertion order. \o You can call stackBefore() to reorder the list of children. This will directly modify the insertion order. \o You can set the ItemStacksBehindParent flag to stack a child item behind its parent. \endlist The stacking order of two sibling items also counts for each item's children and descendant items. So if one item is on top of another, then all its children will also be on top of all the other item's children as well. \section1 Events QGraphicsItem receives events from QGraphicsScene through the virtual function sceneEvent(). This function distributes the most common events to a set of convenience event handlers: \list \o contextMenuEvent() handles context menu events \o focusInEvent() and focusOutEvent() handle focus in and out events \o hoverEnterEvent(), hoverMoveEvent(), and hoverLeaveEvent() handles hover enter, move and leave events \o inputMethodEvent() handles input events, for accessibility support \o keyPressEvent() and keyReleaseEvent() handle key press and release events \o mousePressEvent(), mouseMoveEvent(), mouseReleaseEvent(), and mouseDoubleClickEvent() handles mouse press, move, release, click and doubleclick events \endlist You can filter events for any other item by installing event filters. This functionality is separate from Qt's regular event filters (see QObject::installEventFilter()), which only work on subclasses of QObject. After installing your item as an event filter for another item by calling installSceneEventFilter(), the filtered events will be received by the virtual function sceneEventFilter(). You can remove item event filters by calling removeSceneEventFilter(). \section1 Custom Data Sometimes it's useful to register custom data with an item, be it a custom item, or a standard item. You can call setData() on any item to store data in it using a key-value pair (the key being an integer, and the value is a QVariant). To get custom data from an item, call data(). This functionality is completely untouched by Qt itself; it is provided for the user's convenience. \sa QGraphicsScene, QGraphicsView, {Graphics View Framework} */ /*! \variable QGraphicsItem::Type The type value returned by the virtual type() function in standard graphics item classes in Qt. All such standard graphics item classes in Qt are associated with a unique value for Type, e.g. the value returned by QGraphicsPathItem::type() is 2. \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 18 */ /*! \variable QGraphicsItem::UserType The lowest permitted type value for custom items (subclasses of QGraphicsItem or any of the standard items). This value is used in conjunction with a reimplementation of QGraphicsItem::type() and declaring a Type enum value. Example: \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 1 \note UserType = 65536 */ /*! \enum QGraphicsItem::GraphicsItemFlag This enum describes different flags that you can set on an item to toggle different features in the item's behavior. All flags are disabled by default. \value ItemIsMovable The item supports interactive movement using the mouse. By clicking on the item and then dragging, the item will move together with the mouse cursor. If the item has children, all children are also moved. If the item is part of a selection, all selected items are also moved. This feature is provided as a convenience through the base implementation of QGraphicsItem's mouse event handlers. \value ItemIsSelectable The item supports selection. Enabling this feature will enable setSelected() to toggle selection for the item. It will also let the item be selected automatically as a result of calling QGraphicsScene::setSelectionArea(), by clicking on an item, or by using rubber band selection in QGraphicsView. \value ItemIsFocusable The item supports keyboard input focus (i.e., it is an input item). Enabling this flag will allow the item to accept focus, which again allows the delivery of key events to QGraphicsItem::keyPressEvent() and QGraphicsItem::keyReleaseEvent(). \value ItemClipsToShape The item clips to its own shape. The item cannot draw or receive mouse, tablet, drag and drop or hover events outside its shape. It is disabled by default. This behavior is enforced by QGraphicsView::drawItems() or QGraphicsScene::drawItems(). This flag was introduced in Qt 4.3. \value ItemClipsChildrenToShape The item clips the painting of all its descendants to its own shape. Items that are either direct or indirect children of this item cannot draw outside this item's shape. By default, this flag is disabled; children can draw anywhere. This behavior is enforced by QGraphicsView::drawItems() or QGraphicsScene::drawItems(). This flag was introduced in Qt 4.3. \value ItemIgnoresTransformations The item ignores inherited transformations (i.e., its position is still anchored to its parent, but the parent or view rotation, zoom or shear transformations are ignored). This flag is useful for keeping text label items horizontal and unscaled, so they will still be readable if the view is transformed. When set, the item's view geometry and scene geometry will be maintained separately. You must call deviceTransform() to map coordinates and detect collisions in the view. By default, this flag is disabled. This flag was introduced in Qt 4.3. \note With this flag set you can still scale the item itself, and that scale transformation will influence the item's children. \value ItemIgnoresParentOpacity The item ignores its parent's opacity. The item's effective opacity is the same as its own; it does not combine with the parent's opacity. This flags allows your item to keep its absolute opacity even if the parent is semitransparent. This flag was introduced in Qt 4.5. \value ItemDoesntPropagateOpacityToChildren The item doesn't propagate its opacity to its children. This flag allows you to create a semitransparent item that does not affect the opacity of its children. This flag was introduced in Qt 4.5. \value ItemStacksBehindParent The item is stacked behind its parent. By default, child items are stacked on top of the parent item. But setting this flag, the child will be stacked behind it. This flag is useful for drop shadow effects and for decoration objects that follow the parent item's geometry without drawing on top of it. This flag was introduced in Qt 4.5. \value ItemUsesExtendedStyleOption The item makes use of either \l{QStyleOptionGraphicsItem::} {exposedRect} or \l{QStyleOptionGraphicsItem::} {matrix} in QStyleOptionGraphicsItem. By default, the \l{QStyleOptionGraphicsItem::} {exposedRect} is initialized to the item's boundingRect() and the \l{QStyleOptionGraphicsItem::}{matrix} is untransformed. You can enable this flag for the style options to be set up with more fine-grained values. Note that QStyleOptionGraphicsItem::levelOfDetail is unaffected by this flag and always initialized to 1. Use QStyleOptionGraphicsItem::levelOfDetailFromTransform() if you need a higher value. This flag was introduced in Qt 4.6. \value ItemHasNoContents The item does not paint anything (i.e., calling paint() on the item has no effect). You should set this flag on items that do not need to be painted to ensure that Graphics View avoids unnecessary painting preparations. This flag was introduced in Qt 4.6. \value ItemSendsGeometryChanges The item enables itemChange() notifications for ItemPositionChange, ItemPositionHasChanged, ItemMatrixChange, ItemTransformChange, ItemTransformHasChanged, ItemRotationChange, ItemRotationHasChanged, ItemScaleChange, ItemScaleHasChanged, ItemTransformOriginPointChange, and ItemTransformOriginPointHasChanged. For performance reasons, these notifications are disabled by default. You must enable this flag to receive notifications for position and transform changes. This flag was introduced in Qt 4.6. \value ItemAcceptsInputMethod The item supports input methods typically used for Asian languages. This flag was introduced in Qt 4.6. \value ItemNegativeZStacksBehindParent The item automatically stacks behind it's parent if it's z-value is negative. This flag enables setZValue() to toggle ItemStacksBehindParent. This flag was introduced in Qt 4.6. \value ItemIsPanel The item is a panel. A panel provides activation and contained focus handling. Only one panel can be active at a time (see QGraphicsItem::isActive()). When no panel is active, QGraphicsScene activates all non-panel items. Window items (i.e., QGraphicsItem::isWindow() returns true) are panels. This flag was introduced in Qt 4.6. \omitvalue ItemIsFocusScope \omit Internal only (for now). \endomit \value ItemSendsScenePositionChanges The item enables itemChange() notifications for ItemScenePositionHasChanged. For performance reasons, these notifications are disabled by default. You must enable this flag to receive notifications for scene position changes. This flag was introduced in Qt 4.6. \omitvalue ItemStopsClickFocusPropagation \omit The item stops propagating click focus to items underneath when being clicked on. This flag allows you create a non-focusable item that can be clicked on without changing the focus. \endomit \omitvalue ItemStopsFocusHandling \omit Same as ItemStopsClickFocusPropagation, but also suppresses focus-out. This flag allows you to completely take over focus handling. This flag was introduced in Qt 4.7. \endomit */ /*! \enum QGraphicsItem::GraphicsItemChange This enum describes the state changes that are notified by QGraphicsItem::itemChange(). The notifications are sent as the state changes, and in some cases, adjustments can be made (see the documentation for each change for details). Note: Be careful with calling functions on the QGraphicsItem itself inside itemChange(), as certain function calls can lead to unwanted recursion. For example, you cannot call setPos() in itemChange() on an ItemPositionChange notification, as the setPos() function will again call itemChange(ItemPositionChange). Instead, you can return the new, adjusted position from itemChange(). \value ItemEnabledChange The item's enabled state changes. If the item is presently enabled, it will become disabled, and vice verca. The value argument is the new enabled state (i.e., true or false). Do not call setEnabled() in itemChange() as this notification is delivered. Instead, you can return the new state from itemChange(). \value ItemEnabledHasChanged The item's enabled state has changed. The value argument is the new enabled state (i.e., true or false). Do not call setEnabled() in itemChange() as this notification is delivered. The return value is ignored. \value ItemMatrixChange The item's affine transformation matrix is changing. This value is obsolete; you can use ItemTransformChange instead. \value ItemPositionChange The item's position changes. This notification is sent if the ItemSendsGeometryChanges flag is enabled, and when the item's local position changes, relative to its parent (i.e., as a result of calling setPos() or moveBy()). The value argument is the new position (i.e., a QPointF). You can call pos() to get the original position. Do not call setPos() or moveBy() in itemChange() as this notification is delivered; instead, you can return the new, adjusted position from itemChange(). After this notification, QGraphicsItem immediately sends the ItemPositionHasChanged notification if the position changed. \value ItemPositionHasChanged The item's position has changed. This notification is sent if the ItemSendsGeometryChanges flag is enabled, and after the item's local position, relative to its parent, has changed. The value argument is the new position (the same as pos()), and QGraphicsItem ignores the return value for this notification (i.e., a read-only notification). \value ItemTransformChange The item's transformation matrix changes. This notification is send if the ItemSendsGeometryChanges flag is enabled, and when the item's local transformation matrix changes (i.e., as a result of calling setTransform(). The value argument is the new matrix (i.e., a QTransform); to get the old matrix, call transform(). Do not call setTransform() or set any of the transformation properties in itemChange() as this notification is delivered; instead, you can return the new matrix from itemChange(). This notification is not sent if you change the transformation properties. \value ItemTransformHasChanged The item's transformation matrix has changed either because setTransform is called, or one of the transformation properties is changed. This notification is sent if the ItemSendsGeometryChanges flag is enabled, and after the item's local transformation matrix has changed. The value argument is the new matrix (same as transform()), and QGraphicsItem ignores the return value for this notification (i.e., a read-only notification). \value ItemRotationChange The item's rotation property changes. This notification is sent if the ItemSendsGeometryChanges flag is enabled, and when the item's rotation property changes (i.e., as a result of calling setRotation()). The value argument is the new rotation (i.e., a double); to get the old rotation, call rotation(). Do not call setRotation() in itemChange() as this notification is delivered; instead, you can return the new rotation from itemChange(). \value ItemRotationHasChanged The item's rotation property has changed. This notification is sent if the ItemSendsGeometryChanges flag is enabled, and after the item's rotation property has changed. The value argument is the new rotation (i.e., a double), and QGraphicsItem ignores the return value for this notification (i.e., a read-only notification). Do not call setRotation() in itemChange() as this notification is delivered. \value ItemScaleChange The item's scale property changes. This notification is sent if the ItemSendsGeometryChanges flag is enabled, and when the item's scale property changes (i.e., as a result of calling setScale()). The value argument is the new scale (i.e., a double); to get the old scale, call scale(). Do not call setScale() in itemChange() as this notification is delivered; instead, you can return the new scale from itemChange(). \value ItemScaleHasChanged The item's scale property has changed. This notification is sent if the ItemSendsGeometryChanges flag is enabled, and after the item's scale property has changed. The value argument is the new scale (i.e., a double), and QGraphicsItem ignores the return value for this notification (i.e., a read-only notification). Do not call setScale() in itemChange() as this notification is delivered. \value ItemTransformOriginPointChange The item's transform origin point property changes. This notification is sent if the ItemSendsGeometryChanges flag is enabled, and when the item's transform origin point property changes (i.e., as a result of calling setTransformOriginPoint()). The value argument is the new origin point (i.e., a QPointF); to get the old origin point, call transformOriginPoint(). Do not call setTransformOriginPoint() in itemChange() as this notification is delivered; instead, you can return the new transform origin point from itemChange(). \value ItemTransformOriginPointHasChanged The item's transform origin point property has changed. This notification is sent if the ItemSendsGeometryChanges flag is enabled, and after the item's transform origin point property has changed. The value argument is the new origin point (i.e., a QPointF), and QGraphicsItem ignores the return value for this notification (i.e., a read-only notification). Do not call setTransformOriginPoint() in itemChange() as this notification is delivered. \value ItemSelectedChange The item's selected state changes. If the item is presently selected, it will become unselected, and vice verca. The value argument is the new selected state (i.e., true or false). Do not call setSelected() in itemChange() as this notification is delivered; instead, you can return the new selected state from itemChange(). \value ItemSelectedHasChanged The item's selected state has changed. The value argument is the new selected state (i.e., true or false). Do not call setSelected() in itemChange() as this notification is delivered. The return value is ignored. \value ItemVisibleChange The item's visible state changes. If the item is presently visible, it will become invisible, and vice verca. The value argument is the new visible state (i.e., true or false). Do not call setVisible() in itemChange() as this notification is delivered; instead, you can return the new visible state from itemChange(). \value ItemVisibleHasChanged The item's visible state has changed. The value argument is the new visible state (i.e., true or false). Do not call setVisible() in itemChange() as this notification is delivered. The return value is ignored. \value ItemParentChange The item's parent changes. The value argument is the new parent item (i.e., a QGraphicsItem pointer). Do not call setParentItem() in itemChange() as this notification is delivered; instead, you can return the new parent from itemChange(). \value ItemParentHasChanged The item's parent has changed. The value argument is the new parent (i.e., a pointer to a QGraphicsItem). Do not call setParentItem() in itemChange() as this notification is delivered. The return value is ignored. \value ItemChildAddedChange A child is added to this item. The value argument is the new child item (i.e., a QGraphicsItem pointer). Do not pass this item to any item's setParentItem() function as this notification is delivered. The return value is unused; you cannot adjust anything in this notification. Note that the new child might not be fully constructed when this notification is sent; calling pure virtual functions on the child can lead to a crash. \value ItemChildRemovedChange A child is removed from this item. The value argument is the child item that is about to be removed (i.e., a QGraphicsItem pointer). The return value is unused; you cannot adjust anything in this notification. \value ItemSceneChange The item is moved to a new scene. This notification is also sent when the item is added to its initial scene, and when it is removed. The item's scene() is the old scene (or 0 if the item has not been added to a scene yet). The value argument is the new scene (i.e., a QGraphicsScene pointer), or a null pointer if the item is removed from a scene. Do not override this change by passing this item to QGraphicsScene::addItem() as this notification is delivered; instead, you can return the new scene from itemChange(). Use this feature with caution; objecting to a scene change can quickly lead to unwanted recursion. \value ItemSceneHasChanged The item's scene has changed. The item's scene() is the new scene. This notification is also sent when the item is added to its initial scene, and when it is removed.The value argument is the new scene (i.e., a pointer to a QGraphicsScene). Do not call setScene() in itemChange() as this notification is delivered. The return value is ignored. \value ItemCursorChange The item's cursor changes. The value argument is the new cursor (i.e., a QCursor). Do not call setCursor() in itemChange() as this notification is delivered. Instead, you can return a new cursor from itemChange(). \value ItemCursorHasChanged The item's cursor has changed. The value argument is the new cursor (i.e., a QCursor). Do not call setCursor() as this notification is delivered. The return value is ignored. \value ItemToolTipChange The item's tooltip changes. The value argument is the new tooltip (i.e., a QToolTip). Do not call setToolTip() in itemChange() as this notification is delivered. Instead, you can return a new tooltip from itemChange(). \value ItemToolTipHasChanged The item's tooltip has changed. The value argument is the new tooltip (i.e., a QToolTip). Do not call setToolTip() as this notification is delivered. The return value is ignored. \value ItemFlagsChange The item's flags change. The value argument is the new flags (i.e., a quint32). Do not call setFlags() in itemChange() as this notification is delivered. Instead, you can return the new flags from itemChange(). \value ItemFlagsHaveChanged The item's flags have changed. The value argument is the new flags (i.e., a quint32). Do not call setFlags() in itemChange() as this notification is delivered. The return value is ignored. \value ItemZValueChange The item's Z-value changes. The value argument is the new Z-value (i.e., a double). Do not call setZValue() in itemChange() as this notification is delivered. Instead, you can return a new Z-value from itemChange(). \value ItemZValueHasChanged The item's Z-value has changed. The value argument is the new Z-value (i.e., a double). Do not call setZValue() as this notification is delivered. The return value is ignored. \value ItemOpacityChange The item's opacity changes. The value argument is the new opacity (i.e., a double). Do not call setOpacity() in itemChange() as this notification is delivered. Instead, you can return a new opacity from itemChange(). \value ItemOpacityHasChanged The item's opacity has changed. The value argument is the new opacity (i.e., a double). Do not call setOpacity() as this notification is delivered. The return value is ignored. \value ItemScenePositionHasChanged The item's scene position has changed. This notification is sent if the ItemSendsScenePositionChanges flag is enabled, and after the item's scene position has changed (i.e., the position or transformation of the item itself or the position or transformation of any ancestor has changed). The value argument is the new scene position (the same as scenePos()), and QGraphicsItem ignores the return value for this notification (i.e., a read-only notification). */ /*! \enum QGraphicsItem::CacheMode \since 4.4 This enum describes QGraphicsItem's cache modes. Caching is used to speed up rendering by allocating and rendering to an off-screen pixel buffer, which can be reused when the item requires redrawing. For some paint devices, the cache is stored directly in graphics memory, which makes rendering very quick. \value NoCache The default; all item caching is disabled. QGraphicsItem::paint() is called every time the item needs redrawing. \value ItemCoordinateCache Caching is enabled for the item's logical (local) coordinate system. QGraphicsItem creates an off-screen pixel buffer with a configurable size / resolution that you can pass to QGraphicsItem::setCacheMode(). Rendering quality will typically degrade, depending on the resolution of the cache and the item transformation. The first time the item is redrawn, it will render itself into the cache, and the cache is then reused for every subsequent expose. The cache is also reused as the item is transformed. To adjust the resolution of the cache, you can call setCacheMode() again. \value DeviceCoordinateCache Caching is enabled at the paint device level, in device coordinates. This mode is for items that can move, but are not rotated, scaled or sheared. If the item is transformed directly or indirectly, the cache will be regenerated automatically. Unlike ItemCoordinateCacheMode, DeviceCoordinateCache always renders at maximum quality. \sa QGraphicsItem::setCacheMode() */ /*! \enum QGraphicsItem::Extension \internal Note: This is provided as a hook to avoid future problems related to adding virtual functions. See also extension(), supportsExtension() and setExtension(). */ /*! \enum QGraphicsItem::PanelModality \since 4.6 This enum specifies the behavior of a modal panel. A modal panel is one that blocks input to other panels. Note that items that are children of a modal panel are not blocked. The values are: \value NonModal The panel is not modal and does not block input to other panels. This is the default value for panels. \value PanelModal The panel is modal to a single item hierarchy and blocks input to its parent pane, all grandparent panels, and all siblings of its parent and grandparent panels. \value SceneModal The window is modal to the entire scene and blocks input to all panels. \sa QGraphicsItem::setPanelModality(), QGraphicsItem::panelModality(), QGraphicsItem::ItemIsPanel */ #include "qgraphicsitem.h" #ifndef QT_NO_GRAPHICSVIEW #include "qgraphicsscene.h" #include "qgraphicsscene_p.h" #include "qgraphicssceneevent.h" #include "qgraphicsview.h" #include "qgraphicswidget.h" #include "qgraphicsproxywidget.h" #include "qgraphicsscenebsptreeindex_p.h" #include <QtCore/qbitarray.h> #include <QtCore/qdebug.h> #include <QtCore/qpoint.h> #include <QtCore/qstack.h> #include <QtCore/qtimer.h> #include <QtCore/qvariant.h> #include <QtCore/qvarlengtharray.h> #include <QtCore/qnumeric.h> #include <QtGui/qapplication.h> #include <QtGui/qbitmap.h> #include <QtGui/qpainter.h> #include <QtGui/qpainterpath.h> #include <QtGui/qpixmapcache.h> #include <QtGui/qstyleoption.h> #include <QtGui/qevent.h> #include <QtGui/qinputcontext.h> #include <QtGui/qgraphicseffect.h> #ifndef QT_NO_ACCESSIBILITY # include "qaccessible.h" #endif #include <private/qgraphicsitem_p.h> #include <private/qgraphicswidget_p.h> #include <private/qtextcontrol_p.h> #include <private/qtextdocumentlayout_p.h> #include <private/qtextengine_p.h> #include <private/qwidget_p.h> #include <private/qapplication_p.h> #ifdef Q_WS_X11 #include <private/qt_x11_p.h> #include <private/qpixmap_x11_p.h> #endif #include <private/qgesturemanager_p.h> #include <math.h> QT_BEGIN_NAMESPACE static inline void _q_adjustRect(QRect *rect) { Q_ASSERT(rect); if (!rect->width()) rect->adjust(0, 0, 1, 0); if (!rect->height()) rect->adjust(0, 0, 0, 1); } /* ### Move this into QGraphicsItemPrivate */ class QGraphicsItemCustomDataStore { public: QMap<const QGraphicsItem *, QMap<int, QVariant> > data; }; Q_GLOBAL_STATIC(QGraphicsItemCustomDataStore, qt_dataStore) /*! \internal Returns a QPainterPath of \a path when stroked with the \a pen. Ignoring dash pattern. */ static QPainterPath qt_graphicsItem_shapeFromPath(const QPainterPath &path, const QPen &pen) { // We unfortunately need this hack as QPainterPathStroker will set a width of 1.0 // if we pass a value of 0.0 to QPainterPathStroker::setWidth() const qreal penWidthZero = qreal(0.00000001); if (path == QPainterPath()) return path; QPainterPathStroker ps; ps.setCapStyle(pen.capStyle()); if (pen.widthF() <= 0.0) ps.setWidth(penWidthZero); else ps.setWidth(pen.widthF()); ps.setJoinStyle(pen.joinStyle()); ps.setMiterLimit(pen.miterLimit()); QPainterPath p = ps.createStroke(path); p.addPath(path); return p; } /*! \internal Propagates the ancestor flag \a flag with value \a enabled to all this item's children. If \a root is false, the flag is also set on this item (default is true). */ void QGraphicsItemPrivate::updateAncestorFlag(QGraphicsItem::GraphicsItemFlag childFlag, AncestorFlag flag, bool enabled, bool root) { Q_Q(QGraphicsItem); if (root) { // For root items only. This is the item that has either enabled or // disabled \a childFlag, or has been reparented. switch (int(childFlag)) { case -2: flag = AncestorFiltersChildEvents; enabled = q->filtersChildEvents(); break; case -1: flag = AncestorHandlesChildEvents; enabled = q->handlesChildEvents(); break; case QGraphicsItem::ItemClipsChildrenToShape: flag = AncestorClipsChildren; enabled = flags & QGraphicsItem::ItemClipsChildrenToShape; break; case QGraphicsItem::ItemIgnoresTransformations: flag = AncestorIgnoresTransformations; enabled = flags & QGraphicsItem::ItemIgnoresTransformations; break; default: return; } if (parent) { // Inherit the enabled-state from our parents. if ((parent->d_ptr->ancestorFlags & flag) || (int(parent->d_ptr->flags & childFlag) == childFlag) || (childFlag == -1 && parent->d_ptr->handlesChildEvents) || (childFlag == -2 && parent->d_ptr->filtersDescendantEvents)) { enabled = true; ancestorFlags |= flag; } else { ancestorFlags &= ~flag; } } else { // Top-level root items don't have any ancestors, so there are no // ancestor flags either. ancestorFlags = 0; } } else { // Don't set or propagate the ancestor flag if it's already correct. if (((ancestorFlags & flag) && enabled) || (!(ancestorFlags & flag) && !enabled)) return; // Set the flag. if (enabled) ancestorFlags |= flag; else ancestorFlags &= ~flag; // Don't process children if the item has the main flag set on itself. if ((childFlag != -1 && int(flags & childFlag) == childFlag) || (int(childFlag) == -1 && handlesChildEvents) || (int(childFlag) == -2 && filtersDescendantEvents)) return; } for (int i = 0; i < children.size(); ++i) children.at(i)->d_ptr->updateAncestorFlag(childFlag, flag, enabled, false); } void QGraphicsItemPrivate::updateAncestorFlags() { int flags = 0; if (parent) { // Inherit the parent's ancestor flags. QGraphicsItemPrivate *pd = parent->d_ptr.data(); flags = pd->ancestorFlags; // Add in flags from the parent. if (pd->filtersDescendantEvents) flags |= AncestorFiltersChildEvents; if (pd->handlesChildEvents) flags |= AncestorHandlesChildEvents; if (pd->flags & QGraphicsItem::ItemClipsChildrenToShape) flags |= AncestorClipsChildren; if (pd->flags & QGraphicsItem::ItemIgnoresTransformations) flags |= AncestorIgnoresTransformations; } if (ancestorFlags == flags) return; // No change; stop propagation. ancestorFlags = flags; // Propagate to children recursively. for (int i = 0; i < children.size(); ++i) children.at(i)->d_ptr->updateAncestorFlags(); } /*! \internal Propagates item group membership. */ void QGraphicsItemPrivate::setIsMemberOfGroup(bool enabled) { Q_Q(QGraphicsItem); isMemberOfGroup = enabled; if (!qgraphicsitem_cast<QGraphicsItemGroup *>(q)) { foreach (QGraphicsItem *child, children) child->d_func()->setIsMemberOfGroup(enabled); } } /*! \internal Maps any item pos properties of \a event to \a item's coordinate system. */ void QGraphicsItemPrivate::remapItemPos(QEvent *event, QGraphicsItem *item) { Q_Q(QGraphicsItem); switch (event->type()) { case QEvent::GraphicsSceneMouseMove: case QEvent::GraphicsSceneMousePress: case QEvent::GraphicsSceneMouseRelease: case QEvent::GraphicsSceneMouseDoubleClick: { QGraphicsSceneMouseEvent *mouseEvent = static_cast<QGraphicsSceneMouseEvent *>(event); mouseEvent->setPos(item->mapFromItem(q, mouseEvent->pos())); mouseEvent->setLastPos(item->mapFromItem(q, mouseEvent->pos())); for (int i = 0x1; i <= 0x10; i <<= 1) { if (mouseEvent->buttons() & i) { Qt::MouseButton button = Qt::MouseButton(i); mouseEvent->setButtonDownPos(button, item->mapFromItem(q, mouseEvent->buttonDownPos(button))); } } break; } case QEvent::GraphicsSceneWheel: { QGraphicsSceneWheelEvent *wheelEvent = static_cast<QGraphicsSceneWheelEvent *>(event); wheelEvent->setPos(item->mapFromItem(q, wheelEvent->pos())); break; } case QEvent::GraphicsSceneContextMenu: { QGraphicsSceneContextMenuEvent *contextEvent = static_cast<QGraphicsSceneContextMenuEvent *>(event); contextEvent->setPos(item->mapFromItem(q, contextEvent->pos())); break; } case QEvent::GraphicsSceneHoverMove: { QGraphicsSceneHoverEvent *hoverEvent = static_cast<QGraphicsSceneHoverEvent *>(event); hoverEvent->setPos(item->mapFromItem(q, hoverEvent->pos())); break; } default: break; } } /*! \internal Maps the point \a pos from scene to item coordinates. If \a view is passed and the item is untransformable, this function will correctly map \a pos from the scene using the view's transformation. */ QPointF QGraphicsItemPrivate::genericMapFromScene(const QPointF &pos, const QWidget *viewport) const { Q_Q(const QGraphicsItem); if (!itemIsUntransformable()) return q->mapFromScene(pos); QGraphicsView *view = 0; if (viewport) view = qobject_cast<QGraphicsView *>(viewport->parentWidget()); if (!view) return q->mapFromScene(pos); // ### More ping pong than needed. return q->deviceTransform(view->viewportTransform()).inverted().map(view->mapFromScene(pos)); } /*! \internal Combines this item's position and transform onto \a transform. If you need to change this function (e.g., adding more transformation modes / options), make sure to change all places marked with COMBINE. */ void QGraphicsItemPrivate::combineTransformToParent(QTransform *x, const QTransform *viewTransform) const { // COMBINE if (viewTransform && itemIsUntransformable()) { *x = q_ptr->deviceTransform(*viewTransform); } else { if (transformData) *x *= transformData->computedFullTransform(); if (!pos.isNull()) *x *= QTransform::fromTranslate(pos.x(), pos.y()); } } /*! \internal Combines this item's position and transform onto \a transform. If you need to change this function (e.g., adding more transformation modes / options), make sure to change QGraphicsItem::deviceTransform() as well. */ void QGraphicsItemPrivate::combineTransformFromParent(QTransform *x, const QTransform *viewTransform) const { // COMBINE if (viewTransform && itemIsUntransformable()) { *x = q_ptr->deviceTransform(*viewTransform); } else { x->translate(pos.x(), pos.y()); if (transformData) *x = transformData->computedFullTransform(x); } } void QGraphicsItemPrivate::updateSceneTransformFromParent() { if (parent) { Q_ASSERT(!parent->d_ptr->dirtySceneTransform); if (parent->d_ptr->sceneTransformTranslateOnly) { sceneTransform = QTransform::fromTranslate(parent->d_ptr->sceneTransform.dx() + pos.x(), parent->d_ptr->sceneTransform.dy() + pos.y()); } else { sceneTransform = parent->d_ptr->sceneTransform; sceneTransform.translate(pos.x(), pos.y()); } if (transformData) { sceneTransform = transformData->computedFullTransform(&sceneTransform); sceneTransformTranslateOnly = (sceneTransform.type() <= QTransform::TxTranslate); } else { sceneTransformTranslateOnly = parent->d_ptr->sceneTransformTranslateOnly; } } else if (!transformData) { sceneTransform = QTransform::fromTranslate(pos.x(), pos.y()); sceneTransformTranslateOnly = 1; } else if (transformData->onlyTransform) { sceneTransform = transformData->transform; if (!pos.isNull()) sceneTransform *= QTransform::fromTranslate(pos.x(), pos.y()); sceneTransformTranslateOnly = (sceneTransform.type() <= QTransform::TxTranslate); } else if (pos.isNull()) { sceneTransform = transformData->computedFullTransform(); sceneTransformTranslateOnly = (sceneTransform.type() <= QTransform::TxTranslate); } else { sceneTransform = QTransform::fromTranslate(pos.x(), pos.y()); sceneTransform = transformData->computedFullTransform(&sceneTransform); sceneTransformTranslateOnly = (sceneTransform.type() <= QTransform::TxTranslate); } dirtySceneTransform = 0; } /*! \internal This helper function helped us add input method query support in Qt 4.4.1 without having to reimplement the inputMethodQuery() function in QGraphicsProxyWidget. ### Qt 5: Remove. We cannot remove it in 4.5+ even if we do reimplement the function properly, because apps compiled with 4.4 will not be able to call the reimplementation. */ QVariant QGraphicsItemPrivate::inputMethodQueryHelper(Qt::InputMethodQuery query) const { Q_UNUSED(query); return QVariant(); } /*! \internal Make sure not to trigger any pure virtual function calls (e.g., prepareGeometryChange) if the item is in its destructor, i.e. inDestructor is 1. */ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, const QVariant *newParentVariant, const QVariant *thisPointerVariant) { Q_Q(QGraphicsItem); if (newParent == parent) return; if (isWidget) static_cast<QGraphicsWidgetPrivate *>(this)->fixFocusChainBeforeReparenting((newParent && newParent->isWidget()) ? static_cast<QGraphicsWidget *>(newParent) : 0, scene); if (scene) { // Deliver the change to the index if (scene->d_func()->indexMethod != QGraphicsScene::NoIndex) scene->d_func()->index->itemChange(q, QGraphicsItem::ItemParentChange, newParent); // Disable scene pos notifications for old ancestors if (scenePosDescendants || (flags & QGraphicsItem::ItemSendsScenePositionChanges)) scene->d_func()->setScenePosItemEnabled(q, false); } if (subFocusItem && parent) { // Make sure none of the old parents point to this guy. subFocusItem->d_ptr->clearSubFocus(parent); } // We anticipate geometry changes. If the item is deleted, it will be // removed from the index at a later stage, and the whole scene will be // updated. if (!inDestructor) q_ptr->prepareGeometryChange(); if (parent) { // Remove from current parent parent->d_ptr->removeChild(q); if (thisPointerVariant) parent->itemChange(QGraphicsItem::ItemChildRemovedChange, *thisPointerVariant); } // Update toplevelitem list. If this item is being deleted, its parent // will be 0 but we don't want to register/unregister it in the TLI list. if (scene && !inDestructor) { if (parent && !newParent) { scene->d_func()->registerTopLevelItem(q); } else if (!parent && newParent) { scene->d_func()->unregisterTopLevelItem(q); } } // Ensure any last parent focus scope does not point to this item or any of // its descendents. QGraphicsItem *p = parent; QGraphicsItem *parentFocusScopeItem = 0; while (p) { if (p->d_ptr->flags & QGraphicsItem::ItemIsFocusScope) { // If this item's focus scope's focus scope item points // to this item or a descendent, then clear it. QGraphicsItem *fsi = p->d_ptr->focusScopeItem; if (q_ptr == fsi || q_ptr->isAncestorOf(fsi)) { parentFocusScopeItem = fsi; p->d_ptr->focusScopeItem = 0; } break; } p = p->d_ptr->parent; } // Update graphics effect optimization flag if (newParent && (graphicsEffect || mayHaveChildWithGraphicsEffect)) newParent->d_ptr->updateChildWithGraphicsEffectFlagRecursively(); // Update focus scope item ptr in new scope. QGraphicsItem *newFocusScopeItem = subFocusItem ? subFocusItem : parentFocusScopeItem; if (newFocusScopeItem && newParent) { QGraphicsItem *p = newParent; while (p) { if (p->d_ptr->flags & QGraphicsItem::ItemIsFocusScope) { if (subFocusItem && subFocusItem != q_ptr) { // Find the subFocusItem's topmost focus scope within the new parent's focusscope QGraphicsItem *ancestorScope = 0; QGraphicsItem *p2 = subFocusItem->d_ptr->parent; while (p2 && p2 != p) { if (p2->d_ptr->flags & QGraphicsItem::ItemIsFocusScope) ancestorScope = p2; if (p2->d_ptr->flags & QGraphicsItem::ItemIsPanel) break; if (p2 == q_ptr) break; p2 = p2->d_ptr->parent; } if (ancestorScope) newFocusScopeItem = ancestorScope; } p->d_ptr->focusScopeItem = newFocusScopeItem; newFocusScopeItem->d_ptr->focusScopeItemChange(true); // Ensure the new item is no longer the subFocusItem. The // only way to set focus on a child of a focus scope is // by setting focus on the scope itself. if (subFocusItem && !p->focusItem()) subFocusItem->d_ptr->clearSubFocus(); break; } p = p->d_ptr->parent; } } // Resolve depth. invalidateDepthRecursively(); if ((parent = newParent)) { if (parent->d_func()->scene && parent->d_func()->scene != scene) { // Move this item to its new parent's scene parent->d_func()->scene->addItem(q); } else if (!parent->d_func()->scene && scene) { // Remove this item from its former scene scene->removeItem(q); } parent->d_ptr->addChild(q); if (thisPointerVariant) parent->itemChange(QGraphicsItem::ItemChildAddedChange, *thisPointerVariant); if (scene) { // Re-enable scene pos notifications for new ancestors if (scenePosDescendants || (flags & QGraphicsItem::ItemSendsScenePositionChanges)) scene->d_func()->setScenePosItemEnabled(q, true); } // Propagate dirty flags to the new parent markParentDirty(/*updateBoundingRect=*/true); // Inherit ancestor flags from the new parent. updateAncestorFlags(); // Update item visible / enabled. if (parent->d_ptr->visible != visible) { if (!parent->d_ptr->visible || !explicitlyHidden) setVisibleHelper(parent->d_ptr->visible, /* explicit = */ false, /* update = */ false); } if (parent->isEnabled() != enabled) { if (!parent->d_ptr->enabled || !explicitlyDisabled) setEnabledHelper(parent->d_ptr->enabled, /* explicit = */ false, /* update = */ false); } // Auto-activate if visible and the parent is active. if (visible && parent->isActive()) q->setActive(true); } else { // Inherit ancestor flags from the new parent. updateAncestorFlags(); if (!inDestructor) { // Update item visible / enabled. if (!visible && !explicitlyHidden) setVisibleHelper(true, /* explicit = */ false); if (!enabled && !explicitlyDisabled) setEnabledHelper(true, /* explicit = */ false); } } dirtySceneTransform = 1; if (!inDestructor && (transformData || (newParent && newParent->d_ptr->transformData))) transformChanged(); // Reparenting is finished, now safe to notify the previous focusScopeItem about changes if (parentFocusScopeItem) parentFocusScopeItem->d_ptr->focusScopeItemChange(false); // Restore the sub focus chain. if (subFocusItem) { subFocusItem->d_ptr->setSubFocus(newParent); if (parent && parent->isActive()) subFocusItem->setFocus(); } // Deliver post-change notification if (newParentVariant) q->itemChange(QGraphicsItem::ItemParentHasChanged, *newParentVariant); if (isObject) emit static_cast<QGraphicsObject *>(q)->parentChanged(); } /*! \internal Returns the bounding rect of this item's children (excluding itself). */ void QGraphicsItemPrivate::childrenBoundingRectHelper(QTransform *x, QRectF *rect, QGraphicsItem *topMostEffectItem) { Q_Q(QGraphicsItem); QRectF childrenRect; QRectF *result = rect; rect = &childrenRect; const bool setTopMostEffectItem = !topMostEffectItem; for (int i = 0; i < children.size(); ++i) { QGraphicsItem *child = children.at(i); QGraphicsItemPrivate *childd = child->d_ptr.data(); if (setTopMostEffectItem) topMostEffectItem = child; bool hasPos = !childd->pos.isNull(); if (hasPos || childd->transformData) { // COMBINE QTransform matrix = childd->transformToParent(); if (x) matrix *= *x; *rect |= matrix.mapRect(child->d_ptr->effectiveBoundingRect(topMostEffectItem)); if (!childd->children.isEmpty()) childd->childrenBoundingRectHelper(&matrix, rect, topMostEffectItem); } else { if (x) *rect |= x->mapRect(child->d_ptr->effectiveBoundingRect(topMostEffectItem)); else *rect |= child->d_ptr->effectiveBoundingRect(topMostEffectItem); if (!childd->children.isEmpty()) childd->childrenBoundingRectHelper(x, rect, topMostEffectItem); } } if (flags & QGraphicsItem::ItemClipsChildrenToShape){ if (x) *rect &= x->mapRect(q->boundingRect()); else *rect &= q->boundingRect(); } *result |= *rect; } void QGraphicsItemPrivate::initStyleOption(QStyleOptionGraphicsItem *option, const QTransform &worldTransform, const QRegion &exposedRegion, bool allItems) const { Q_ASSERT(option); Q_Q(const QGraphicsItem); // Initialize standard QStyleOption values. const QRectF brect = q->boundingRect(); option->state = QStyle::State_None; option->rect = brect.toRect(); option->levelOfDetail = 1; option->exposedRect = brect; if (selected) option->state |= QStyle::State_Selected; if (enabled) option->state |= QStyle::State_Enabled; if (q->hasFocus()) option->state |= QStyle::State_HasFocus; if (scene) { if (scene->d_func()->hoverItems.contains(q_ptr)) option->state |= QStyle::State_MouseOver; if (q == scene->mouseGrabberItem()) option->state |= QStyle::State_Sunken; } if (!(flags & QGraphicsItem::ItemUsesExtendedStyleOption)) return; // Initialize QStyleOptionGraphicsItem specific values (matrix, exposedRect). option->matrix = worldTransform.toAffine(); //### discards perspective if (!allItems) { // Determine the item's exposed area option->exposedRect = QRectF(); const QTransform reverseMap = worldTransform.inverted(); const QVector<QRect> exposedRects(exposedRegion.rects()); for (int i = 0; i < exposedRects.size(); ++i) { option->exposedRect |= reverseMap.mapRect(QRectF(exposedRects.at(i))); if (option->exposedRect.contains(brect)) break; } option->exposedRect &= brect; } } /*! \internal Empty all cached pixmaps from the pixmap cache. */ void QGraphicsItemCache::purge() { QPixmapCache::remove(key); key = QPixmapCache::Key(); QMutableMapIterator<QPaintDevice *, DeviceData> it(deviceData); while (it.hasNext()) { DeviceData &data = it.next().value(); QPixmapCache::remove(data.key); data.cacheIndent = QPoint(); } deviceData.clear(); allExposed = true; exposed.clear(); } /*! Constructs a QGraphicsItem with the given \a parent item. It does not modify the parent object returned by QObject::parent(). If \a parent is 0, you can add the item to a scene by calling QGraphicsScene::addItem(). The item will then become a top-level item. \sa QGraphicsScene::addItem(), setParentItem() */ QGraphicsItem::QGraphicsItem(QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : d_ptr(new QGraphicsItemPrivate) { d_ptr->q_ptr = this; setParentItem(parent); if (scene && parent && parent->scene() != scene) { qWarning("QGraphicsItem::QGraphicsItem: ignoring scene (%p), which is" " different from parent's scene (%p)", scene, parent->scene()); return; } if (scene && !parent) scene->addItem(this); } /*! \internal */ QGraphicsItem::QGraphicsItem(QGraphicsItemPrivate &dd, QGraphicsItem *parent, QGraphicsScene *scene) : d_ptr(&dd) { d_ptr->q_ptr = this; setParentItem(parent); if (scene && parent && parent->scene() != scene) { qWarning("QGraphicsItem::QGraphicsItem: ignoring scene (%p), which is" " different from parent's scene (%p)", scene, parent->scene()); return; } if (scene && !parent) scene->addItem(this); } /*! Destroys the QGraphicsItem and all its children. If this item is currently associated with a scene, the item will be removed from the scene before it is deleted. \note It is more efficient to remove the item from the QGraphicsScene before destroying the item. */ QGraphicsItem::~QGraphicsItem() { if (d_ptr->isObject) { QGraphicsObject *o = static_cast<QGraphicsObject *>(this); QObjectPrivate *p = QObjectPrivate::get(o); p->wasDeleted = true; if (p->declarativeData) { QAbstractDeclarativeData::destroyed(p->declarativeData, o); p->declarativeData = 0; } } d_ptr->inDestructor = 1; d_ptr->removeExtraItemCache(); #ifndef QT_NO_GESTURES if (d_ptr->isObject && !d_ptr->gestureContext.isEmpty()) { QGraphicsObject *o = static_cast<QGraphicsObject *>(this); if (QGestureManager *manager = QGestureManager::instance()) { foreach (Qt::GestureType type, d_ptr->gestureContext.keys()) manager->cleanupCachedGestures(o, type); } } #endif clearFocus(); // Update focus scope item ptr. QGraphicsItem *p = d_ptr->parent; while (p) { if (p->flags() & ItemIsFocusScope) { if (p->d_ptr->focusScopeItem == this) p->d_ptr->focusScopeItem = 0; break; } p = p->d_ptr->parent; } if (!d_ptr->children.isEmpty()) { while (!d_ptr->children.isEmpty()) delete d_ptr->children.first(); Q_ASSERT(d_ptr->children.isEmpty()); } if (d_ptr->scene) { d_ptr->scene->d_func()->removeItemHelper(this); } else { d_ptr->resetFocusProxy(); setParentItem(0); } #ifndef QT_NO_GRAPHICSEFFECT delete d_ptr->graphicsEffect; #endif //QT_NO_GRAPHICSEFFECT if (d_ptr->transformData) { for(int i = 0; i < d_ptr->transformData->graphicsTransforms.size(); ++i) { QGraphicsTransform *t = d_ptr->transformData->graphicsTransforms.at(i); static_cast<QGraphicsTransformPrivate *>(t->d_ptr.data())->item = 0; delete t; } } delete d_ptr->transformData; if (QGraphicsItemCustomDataStore *dataStore = qt_dataStore()) dataStore->data.remove(this); } /*! Returns the current scene for the item, or 0 if the item is not stored in a scene. To add or move an item to a scene, call QGraphicsScene::addItem(). */ QGraphicsScene *QGraphicsItem::scene() const { return d_ptr->scene; } /*! Returns a pointer to this item's item group, or 0 if this item is not member of a group. \sa QGraphicsItemGroup, QGraphicsScene::createItemGroup() */ QGraphicsItemGroup *QGraphicsItem::group() const { if (!d_ptr->isMemberOfGroup) return 0; QGraphicsItem *parent = const_cast<QGraphicsItem *>(this); while ((parent = parent->d_ptr->parent)) { if (QGraphicsItemGroup *group = qgraphicsitem_cast<QGraphicsItemGroup *>(parent)) return group; } // Unreachable; if d_ptr->isMemberOfGroup is != 0, then one parent of this // item is a group item. return 0; } /*! Adds this item to the item group \a group. If \a group is 0, this item is removed from any current group and added as a child of the previous group's parent. \sa group(), QGraphicsScene::createItemGroup() */ void QGraphicsItem::setGroup(QGraphicsItemGroup *group) { if (!group) { if (QGraphicsItemGroup *group = this->group()) group->removeFromGroup(this); } else { group->addToGroup(this); } } /*! Returns a pointer to this item's parent item. If this item does not have a parent, 0 is returned. \sa setParentItem(), childItems() */ QGraphicsItem *QGraphicsItem::parentItem() const { return d_ptr->parent; } /*! Returns this item's top-level item. The top-level item is the item's topmost ancestor item whose parent is 0. If an item has no parent, its own pointer is returned (i.e., a top-level item is its own top-level item). \sa parentItem() */ QGraphicsItem *QGraphicsItem::topLevelItem() const { QGraphicsItem *parent = const_cast<QGraphicsItem *>(this); while (QGraphicsItem *grandPa = parent->parentItem()) parent = grandPa; return parent; } /*! \since 4.6 Returns a pointer to the item's parent, cast to a QGraphicsObject. returns 0 if the parent item is not a QGraphicsObject. \sa parentItem(), childItems() */ QGraphicsObject *QGraphicsItem::parentObject() const { QGraphicsItem *p = d_ptr->parent; return (p && p->d_ptr->isObject) ? static_cast<QGraphicsObject *>(p) : 0; } /*! \since 4.4 Returns a pointer to the item's parent widget. The item's parent widget is the closest parent item that is a widget. \sa parentItem(), childItems() */ QGraphicsWidget *QGraphicsItem::parentWidget() const { QGraphicsItem *p = parentItem(); while (p && !p->isWidget()) p = p->parentItem(); return (p && p->isWidget()) ? static_cast<QGraphicsWidget *>(p) : 0; } /*! \since 4.4 Returns a pointer to the item's top level widget (i.e., the item's ancestor whose parent is 0, or whose parent is not a widget), or 0 if this item does not have a top level widget. If the item is its own top level widget, this function returns a pointer to the item itself. */ QGraphicsWidget *QGraphicsItem::topLevelWidget() const { if (const QGraphicsWidget *p = parentWidget()) return p->topLevelWidget(); return isWidget() ? static_cast<QGraphicsWidget *>(const_cast<QGraphicsItem *>(this)) : 0; } /*! \since 4.4 Returns the item's window, or 0 if this item does not have a window. If the item is a window, it will return itself. Otherwise it will return the closest ancestor that is a window. \sa QGraphicsWidget::isWindow() */ QGraphicsWidget *QGraphicsItem::window() const { QGraphicsItem *p = panel(); if (p && p->isWindow()) return static_cast<QGraphicsWidget *>(p); return 0; } /*! \since 4.6 Returns the item's panel, or 0 if this item does not have a panel. If the item is a panel, it will return itself. Otherwise it will return the closest ancestor that is a panel. \sa isPanel(), ItemIsPanel */ QGraphicsItem *QGraphicsItem::panel() const { if (d_ptr->flags & ItemIsPanel) return const_cast<QGraphicsItem *>(this); return d_ptr->parent ? d_ptr->parent->panel() : 0; } /*! \since 4.6 Return the graphics item cast to a QGraphicsObject, if the class is actually a graphics object, 0 otherwise. */ QGraphicsObject *QGraphicsItem::toGraphicsObject() { return d_ptr->isObject ? static_cast<QGraphicsObject *>(this) : 0; } /*! \since 4.6 Return the graphics item cast to a QGraphicsObject, if the class is actually a graphics object, 0 otherwise. */ const QGraphicsObject *QGraphicsItem::toGraphicsObject() const { return d_ptr->isObject ? static_cast<const QGraphicsObject *>(this) : 0; } /*! Sets this item's parent item to \a newParent. If this item already has a parent, it is first removed from the previous parent. If \a newParent is 0, this item will become a top-level item. Note that this implicitly adds this graphics item to the scene of the parent. You should not \l{QGraphicsScene::addItem()}{add} the item to the scene yourself. Calling this function on an item that is an ancestor of \a newParent have undefined behaviour. \sa parentItem(), childItems() */ void QGraphicsItem::setParentItem(QGraphicsItem *newParent) { if (newParent == this) { qWarning("QGraphicsItem::setParentItem: cannot assign %p as a parent of itself", this); return; } if (newParent == d_ptr->parent) return; const QVariant newParentVariant(itemChange(QGraphicsItem::ItemParentChange, QVariant::fromValue<QGraphicsItem *>(newParent))); newParent = qvariant_cast<QGraphicsItem *>(newParentVariant); if (newParent == d_ptr->parent) return; const QVariant thisPointerVariant(QVariant::fromValue<QGraphicsItem *>(this)); d_ptr->setParentItemHelper(newParent, &newParentVariant, &thisPointerVariant); } /*! \obsolete Use childItems() instead. \sa setParentItem() */ QList<QGraphicsItem *> QGraphicsItem::children() const { return childItems(); } /*! \since 4.4 Returns a list of this item's children. The items are sorted by stacking order. This takes into account both the items' insertion order and their Z-values. \sa setParentItem(), zValue(), {QGraphicsItem#Sorting}{Sorting} */ QList<QGraphicsItem *> QGraphicsItem::childItems() const { const_cast<QGraphicsItem *>(this)->d_ptr->ensureSortedChildren(); return d_ptr->children; } /*! \since 4.4 Returns true if this item is a widget (i.e., QGraphicsWidget); otherwise, returns false. */ bool QGraphicsItem::isWidget() const { return d_ptr->isWidget; } /*! \since 4.4 Returns true if the item is a QGraphicsWidget window, otherwise returns false. \sa QGraphicsWidget::windowFlags() */ bool QGraphicsItem::isWindow() const { return d_ptr->isWidget && (static_cast<const QGraphicsWidget *>(this)->windowType() & Qt::Window); } /*! \since 4.6 Returns true if the item is a panel; otherwise returns false. \sa QGraphicsItem::panel(), ItemIsPanel */ bool QGraphicsItem::isPanel() const { return d_ptr->flags & ItemIsPanel; } /*! Returns this item's flags. The flags describe what configurable features of the item are enabled and not. For example, if the flags include ItemIsFocusable, the item can accept input focus. By default, no flags are enabled. \sa setFlags(), setFlag() */ QGraphicsItem::GraphicsItemFlags QGraphicsItem::flags() const { return GraphicsItemFlags(d_ptr->flags); } /*! If \a enabled is true, the item flag \a flag is enabled; otherwise, it is disabled. \sa flags(), setFlags() */ void QGraphicsItem::setFlag(GraphicsItemFlag flag, bool enabled) { if (enabled) setFlags(GraphicsItemFlags(d_ptr->flags) | flag); else setFlags(GraphicsItemFlags(d_ptr->flags) & ~flag); } /*! \internal Sets the flag \a flag on \a item and all its children, to \a enabled. */ static void _q_qgraphicsItemSetFlag(QGraphicsItem *item, QGraphicsItem::GraphicsItemFlag flag, bool enabled) { if (item->flags() & flag) { // If this item already has the correct flag set, we don't have to // propagate it. return; } item->setFlag(flag, enabled); foreach (QGraphicsItem *child, item->children()) _q_qgraphicsItemSetFlag(child, flag, enabled); } /*! Sets the item flags to \a flags. All flags in \a flags are enabled; all flags not in \a flags are disabled. If the item had focus and \a flags does not enable ItemIsFocusable, the item loses focus as a result of calling this function. Similarly, if the item was selected, and \a flags does not enabled ItemIsSelectable, the item is automatically unselected. By default, no flags are enabled. (QGraphicsWidget enables the ItemSendsGeometryChanges flag by default in order to track position changes.) \sa flags(), setFlag() */ void QGraphicsItem::setFlags(GraphicsItemFlags flags) { // Notify change and check for adjustment. if (quint32(d_ptr->flags) == quint32(flags)) return; flags = GraphicsItemFlags(itemChange(ItemFlagsChange, quint32(flags)).toUInt()); if (quint32(d_ptr->flags) == quint32(flags)) return; if (d_ptr->scene && d_ptr->scene->d_func()->indexMethod != QGraphicsScene::NoIndex) d_ptr->scene->d_func()->index->itemChange(this, ItemFlagsChange, &flags); // Flags that alter the geometry of the item (or its children). const quint32 geomChangeFlagsMask = (ItemClipsChildrenToShape | ItemClipsToShape | ItemIgnoresTransformations | ItemIsSelectable); bool fullUpdate = (quint32(flags) & geomChangeFlagsMask) != (d_ptr->flags & geomChangeFlagsMask); if (fullUpdate) d_ptr->updatePaintedViewBoundingRects(/*children=*/true); // Keep the old flags to compare the diff. GraphicsItemFlags oldFlags = GraphicsItemFlags(d_ptr->flags); // Update flags. d_ptr->flags = flags; if (!(d_ptr->flags & ItemIsFocusable) && hasFocus()) { // Clear focus on the item if it has focus when the focusable flag // is unset. clearFocus(); } if (!(d_ptr->flags & ItemIsSelectable) && isSelected()) { // Unselect the item if it is selected when the selectable flag is // unset. setSelected(false); } if ((flags & ItemClipsChildrenToShape) != (oldFlags & ItemClipsChildrenToShape)) { // Item children clipping changes. Propagate the ancestor flag to // all children. d_ptr->updateAncestorFlag(ItemClipsChildrenToShape); // The childrenBoundingRect is clipped to the boundingRect in case of ItemClipsChildrenToShape, // which means we have to invalidate the cached childrenBoundingRect whenever this flag changes. d_ptr->dirtyChildrenBoundingRect = 1; d_ptr->markParentDirty(true); } if ((flags & ItemIgnoresTransformations) != (oldFlags & ItemIgnoresTransformations)) { // Item children clipping changes. Propagate the ancestor flag to // all children. d_ptr->updateAncestorFlag(ItemIgnoresTransformations); } if ((flags & ItemNegativeZStacksBehindParent) != (oldFlags & ItemNegativeZStacksBehindParent)) { // NB! We change the flags directly here, so we must also update d_ptr->flags. // Note that this has do be done before the ItemStacksBehindParent check // below; otherwise we will loose the change. // Update stack-behind. if (d_ptr->z < qreal(0.0)) flags |= ItemStacksBehindParent; else flags &= ~ItemStacksBehindParent; d_ptr->flags = flags; } if ((flags & ItemStacksBehindParent) != (oldFlags & ItemStacksBehindParent)) { // NB! This check has to come after the ItemNegativeZStacksBehindParent // check above. Be careful. // Ensure child item sorting is up to date when toggling this flag. if (d_ptr->parent) d_ptr->parent->d_ptr->needSortChildren = 1; else if (d_ptr->scene) d_ptr->scene->d_func()->needSortTopLevelItems = 1; } if ((flags & ItemAcceptsInputMethod) != (oldFlags & ItemAcceptsInputMethod)) { // Update input method sensitivity in any views. if (d_ptr->scene) d_ptr->scene->d_func()->updateInputMethodSensitivityInViews(); } if ((d_ptr->panelModality != NonModal) && d_ptr->scene && (flags & ItemIsPanel) != (oldFlags & ItemIsPanel)) { // update the panel's modal state if (flags & ItemIsPanel) d_ptr->scene->d_func()->enterModal(this); else d_ptr->scene->d_func()->leaveModal(this); } if (d_ptr->scene) { if ((flags & ItemSendsScenePositionChanges) != (oldFlags & ItemSendsScenePositionChanges)) { if (flags & ItemSendsScenePositionChanges) d_ptr->scene->d_func()->registerScenePosItem(this); else d_ptr->scene->d_func()->unregisterScenePosItem(this); } d_ptr->scene->d_func()->markDirty(this, QRectF(), /*invalidateChildren=*/true); } // Notify change. itemChange(ItemFlagsHaveChanged, quint32(flags)); } /*! \since 4.4 Returns the cache mode for this item. The default mode is NoCache (i.e., cache is disabled and all painting is immediate). \sa setCacheMode() */ QGraphicsItem::CacheMode QGraphicsItem::cacheMode() const { return QGraphicsItem::CacheMode(d_ptr->cacheMode); } /*! \since 4.4 Sets the item's cache mode to \a mode. The optional \a logicalCacheSize argument is used only by ItemCoordinateCache mode, and describes the resolution of the cache buffer; if \a logicalCacheSize is (100, 100), QGraphicsItem will fit the item into 100x100 pixels in graphics memory, regardless of the logical size of the item itself. By default QGraphicsItem uses the size of boundingRect(). For all other cache modes than ItemCoordinateCache, \a logicalCacheSize is ignored. Caching can speed up rendering if your item spends a significant time redrawing itself. In some cases the cache can also slow down rendering, in particular when the item spends less time redrawing than QGraphicsItem spends redrawing from the cache. When enabled, the item's paint() function will be called only once for each call to update(); for any subsequent repaint requests, the Graphics View framework will redraw from the cache. This approach works particularly well with QGLWidget, which stores all the cache as OpenGL textures. Be aware that QPixmapCache's cache limit may need to be changed to obtain optimal performance. You can read more about the different cache modes in the CacheMode documentation. \sa CacheMode, QPixmapCache::setCacheLimit() */ void QGraphicsItem::setCacheMode(CacheMode mode, const QSize &logicalCacheSize) { CacheMode lastMode = CacheMode(d_ptr->cacheMode); d_ptr->cacheMode = mode; bool noVisualChange = (mode == NoCache && lastMode == NoCache) || (mode == NoCache && lastMode == DeviceCoordinateCache) || (mode == DeviceCoordinateCache && lastMode == NoCache) || (mode == DeviceCoordinateCache && lastMode == DeviceCoordinateCache); if (mode == NoCache) { d_ptr->removeExtraItemCache(); } else { QGraphicsItemCache *cache = d_ptr->extraItemCache(); // Reset old cache cache->purge(); if (mode == ItemCoordinateCache) { if (lastMode == mode && cache->fixedSize == logicalCacheSize) noVisualChange = true; cache->fixedSize = logicalCacheSize; } } if (!noVisualChange) update(); } /*! \since 4.6 Returns the modality for this item. */ QGraphicsItem::PanelModality QGraphicsItem::panelModality() const { return d_ptr->panelModality; } /*! \since 4.6 Sets the modality for this item to \a panelModality. Changing the modality of a visible item takes effect immediately. */ void QGraphicsItem::setPanelModality(PanelModality panelModality) { if (d_ptr->panelModality == panelModality) return; PanelModality previousModality = d_ptr->panelModality; bool enterLeaveModal = (isPanel() && d_ptr->scene && isVisible()); if (enterLeaveModal && panelModality == NonModal) d_ptr->scene->d_func()->leaveModal(this); d_ptr->panelModality = panelModality; if (enterLeaveModal && d_ptr->panelModality != NonModal) d_ptr->scene->d_func()->enterModal(this, previousModality); } /*! \since 4.6 Returns true if this item is blocked by a modal panel, false otherwise. If \a blockingPanel is non-zero, \a blockingPanel will be set to the modal panel that is blocking this item. If this item is not blocked, \a blockingPanel will not be set by this function. This function always returns false for items not in a scene. \sa panelModality() setPanelModality() PanelModality */ bool QGraphicsItem::isBlockedByModalPanel(QGraphicsItem **blockingPanel) const { if (!d_ptr->scene) return false; QGraphicsItem *dummy = 0; if (!blockingPanel) blockingPanel = &dummy; QGraphicsScenePrivate *scene_d = d_ptr->scene->d_func(); if (scene_d->modalPanels.isEmpty()) return false; // ### if (!scene_d->popupWidgets.isEmpty() && scene_d->popupWidgets.first() == this) return false; for (int i = 0; i < scene_d->modalPanels.count(); ++i) { QGraphicsItem *modalPanel = scene_d->modalPanels.at(i); if (modalPanel->panelModality() == QGraphicsItem::SceneModal) { // Scene modal panels block all non-descendents. if (modalPanel != this && !modalPanel->isAncestorOf(this)) { *blockingPanel = modalPanel; return true; } } else { // Window modal panels block ancestors and siblings/cousins. if (modalPanel != this && !modalPanel->isAncestorOf(this) && commonAncestorItem(modalPanel)) { *blockingPanel = modalPanel; return true; } } } return false; } #ifndef QT_NO_TOOLTIP /*! Returns the item's tool tip, or an empty QString if no tool tip has been set. \sa setToolTip(), QToolTip */ QString QGraphicsItem::toolTip() const { return d_ptr->extra(QGraphicsItemPrivate::ExtraToolTip).toString(); } /*! Sets the item's tool tip to \a toolTip. If \a toolTip is empty, the item's tool tip is cleared. \sa toolTip(), QToolTip */ void QGraphicsItem::setToolTip(const QString &toolTip) { const QVariant toolTipVariant(itemChange(ItemToolTipChange, toolTip)); d_ptr->setExtra(QGraphicsItemPrivate::ExtraToolTip, toolTipVariant.toString()); itemChange(ItemToolTipHasChanged, toolTipVariant); } #endif // QT_NO_TOOLTIP #ifndef QT_NO_CURSOR /*! Returns the current cursor shape for the item. The mouse cursor will assume this shape when it's over this item. See the \link Qt::CursorShape list of predefined cursor objects\endlink for a range of useful shapes. An editor item might want to use an I-beam cursor: \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 2 If no cursor has been set, the cursor of the item beneath is used. \sa setCursor(), hasCursor(), unsetCursor(), QWidget::cursor, QApplication::overrideCursor() */ QCursor QGraphicsItem::cursor() const { return qvariant_cast<QCursor>(d_ptr->extra(QGraphicsItemPrivate::ExtraCursor)); } /*! Sets the current cursor shape for the item to \a cursor. The mouse cursor will assume this shape when it's over this item. See the \link Qt::CursorShape list of predefined cursor objects\endlink for a range of useful shapes. An editor item might want to use an I-beam cursor: \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 3 If no cursor has been set, the cursor of the item beneath is used. \sa cursor(), hasCursor(), unsetCursor(), QWidget::cursor, QApplication::overrideCursor() */ void QGraphicsItem::setCursor(const QCursor &cursor) { const QVariant cursorVariant(itemChange(ItemCursorChange, QVariant::fromValue<QCursor>(cursor))); d_ptr->setExtra(QGraphicsItemPrivate::ExtraCursor, qvariant_cast<QCursor>(cursorVariant)); d_ptr->hasCursor = 1; if (d_ptr->scene) { d_ptr->scene->d_func()->allItemsUseDefaultCursor = false; foreach (QGraphicsView *view, d_ptr->scene->views()) { view->viewport()->setMouseTracking(true); // Note: Some of this logic is duplicated in QGraphicsView's mouse events. if (view->underMouse()) { foreach (QGraphicsItem *itemUnderCursor, view->items(view->mapFromGlobal(QCursor::pos()))) { if (itemUnderCursor->hasCursor()) { QMetaObject::invokeMethod(view, "_q_setViewportCursor", Q_ARG(QCursor, itemUnderCursor->cursor())); break; } } break; } } } itemChange(ItemCursorHasChanged, cursorVariant); } /*! Returns true if this item has a cursor set; otherwise, false is returned. By default, items don't have any cursor set. cursor() will return a standard pointing arrow cursor. \sa unsetCursor() */ bool QGraphicsItem::hasCursor() const { return d_ptr->hasCursor; } /*! Clears the cursor from this item. \sa hasCursor(), setCursor() */ void QGraphicsItem::unsetCursor() { d_ptr->unsetExtra(QGraphicsItemPrivate::ExtraCursor); d_ptr->hasCursor = 0; if (d_ptr->scene) { foreach (QGraphicsView *view, d_ptr->scene->views()) { if (view->underMouse() && view->itemAt(view->mapFromGlobal(QCursor::pos())) == this) { QMetaObject::invokeMethod(view, "_q_unsetViewportCursor"); break; } } } } #endif // QT_NO_CURSOR /*! Returns true if the item is visible; otherwise, false is returned. Note that the item's general visibility is unrelated to whether or not it is actually being visualized by a QGraphicsView. \sa setVisible() */ bool QGraphicsItem::isVisible() const { return d_ptr->visible; } /*! \since 4.4 Returns true if the item is visible to \a parent; otherwise, false is returned. \a parent can be 0, in which case this function will return whether the item is visible to the scene or not. An item may not be visible to its ancestors even if isVisible() is true. It may also be visible to its ancestors even if isVisible() is false. If any ancestor is hidden, the item itself will be implicitly hidden, in which case this function will return false. \sa isVisible(), setVisible() */ bool QGraphicsItem::isVisibleTo(const QGraphicsItem *parent) const { const QGraphicsItem *p = this; if (d_ptr->explicitlyHidden) return false; do { if (p == parent) return true; if (p->d_ptr->explicitlyHidden) return false; } while ((p = p->d_ptr->parent)); return parent == 0; } /*! \internal Sets this item's visibility to \a newVisible. If \a explicitly is true, this item will be "explicitly" \a newVisible; otherwise, it.. will not be. */ void QGraphicsItemPrivate::setVisibleHelper(bool newVisible, bool explicitly, bool update) { Q_Q(QGraphicsItem); // Update explicit bit. if (explicitly) explicitlyHidden = newVisible ? 0 : 1; // Check if there's nothing to do. if (visible == quint32(newVisible)) return; // Don't show child if parent is not visible if (parent && newVisible && !parent->d_ptr->visible) return; // Modify the property. const QVariant newVisibleVariant(q_ptr->itemChange(QGraphicsItem::ItemVisibleChange, quint32(newVisible))); newVisible = newVisibleVariant.toBool(); if (visible == quint32(newVisible)) return; visible = newVisible; // Schedule redrawing if (update) { QGraphicsItemCache *c = (QGraphicsItemCache *)qvariant_cast<void *>(extra(ExtraCacheData)); if (c) c->purge(); if (scene) { #ifndef QT_NO_GRAPHICSEFFECT invalidateParentGraphicsEffectsRecursively(); #endif //QT_NO_GRAPHICSEFFECT scene->d_func()->markDirty(q_ptr, QRectF(), /*invalidateChildren=*/false, /*force=*/true); } } // Certain properties are dropped as an item becomes invisible. bool hasFocus = q_ptr->hasFocus(); if (!newVisible) { if (scene) { if (scene->d_func()->mouseGrabberItems.contains(q)) q->ungrabMouse(); if (scene->d_func()->keyboardGrabberItems.contains(q)) q->ungrabKeyboard(); if (q->isPanel() && panelModality != QGraphicsItem::NonModal) scene->d_func()->leaveModal(q_ptr); } if (hasFocus && scene) { // Hiding the closest non-panel ancestor of the focus item QGraphicsItem *focusItem = scene->focusItem(); if (isWidget && !focusItem->isPanel()) { do { if (focusItem == q_ptr) { static_cast<QGraphicsWidget *>(q_ptr)->focusNextPrevChild(true); break; } } while ((focusItem = focusItem->parentWidget()) && !focusItem->isPanel()); } // Clear focus if previous steps didn't move it to another widget if (q_ptr->hasFocus()) clearFocusHelper(/* giveFocusToParent = */ false); } if (q_ptr->isSelected()) q_ptr->setSelected(false); } else { geometryChanged = 1; paintedViewBoundingRectsNeedRepaint = 1; if (scene) { if (isWidget) { QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(q_ptr); if (widget->windowType() == Qt::Popup) scene->d_func()->addPopup(widget); } if (q->isPanel() && panelModality != QGraphicsItem::NonModal) { scene->d_func()->enterModal(q_ptr); } } } // Update children with explicitly = false. const bool updateChildren = update && !((flags & QGraphicsItem::ItemClipsChildrenToShape) && !(flags & QGraphicsItem::ItemHasNoContents)); foreach (QGraphicsItem *child, children) { if (!newVisible || !child->d_ptr->explicitlyHidden) child->d_ptr->setVisibleHelper(newVisible, false, updateChildren); } // Update activation if (scene && q->isPanel()) { if (newVisible) { if (parent && parent->isActive()) q->setActive(true); } else { if (q->isActive()) scene->setActivePanel(parent); } } // Enable subfocus if (scene) { if (newVisible) { // Item is shown QGraphicsItem *p = parent; bool done = false; while (p) { if (p->flags() & QGraphicsItem::ItemIsFocusScope) { QGraphicsItem *fsi = p->d_ptr->focusScopeItem; if (q_ptr == fsi || q_ptr->isAncestorOf(fsi)) { done = true; while (fsi->d_ptr->focusScopeItem && fsi->d_ptr->focusScopeItem->isVisible()) fsi = fsi->d_ptr->focusScopeItem; fsi->d_ptr->setFocusHelper(Qt::OtherFocusReason, /* climb = */ true, /* focusFromHide = */ false); } break; } p = p->d_ptr->parent; } if (!done) { QGraphicsItem *fi = subFocusItem; if (fi && fi != scene->focusItem()) { scene->setFocusItem(fi); } else if (flags & QGraphicsItem::ItemIsFocusScope && !scene->focusItem() && q->isAncestorOf(scene->d_func()->lastFocusItem)) { q_ptr->setFocus(); } } } else { // Item is hidden if (hasFocus) { QGraphicsItem *p = parent; while (p) { if (p->flags() & QGraphicsItem::ItemIsFocusScope) { if (p->d_ptr->visible) { p->d_ptr->setFocusHelper(Qt::OtherFocusReason, /* climb = */ true, /* focusFromHide = */ true); } break; } p = p->d_ptr->parent; } } } } // Deliver post-change notification. q_ptr->itemChange(QGraphicsItem::ItemVisibleHasChanged, newVisibleVariant); if (isObject) emit static_cast<QGraphicsObject *>(q_ptr)->visibleChanged(); } /*! If \a visible is true, the item is made visible. Otherwise, the item is made invisible. Invisible items are not painted, nor do they receive any events. In particular, mouse events pass right through invisible items, and are delivered to any item that may be behind. Invisible items are also unselectable, they cannot take input focus, and are not detected by QGraphicsScene's item location functions. If an item becomes invisible while grabbing the mouse, (i.e., while it is receiving mouse events,) it will automatically lose the mouse grab, and the grab is not regained by making the item visible again; it must receive a new mouse press to regain the mouse grab. Similarly, an invisible item cannot have focus, so if the item has focus when it becomes invisible, it will lose focus, and the focus is not regained by simply making the item visible again. If you hide a parent item, all its children will also be hidden. If you show a parent item, all children will be shown, unless they have been explicitly hidden (i.e., if you call setVisible(false) on a child, it will not be reshown even if its parent is hidden, and then shown again). Items are visible by default; it is unnecessary to call setVisible() on a new item. \sa isVisible(), show(), hide() */ void QGraphicsItem::setVisible(bool visible) { d_ptr->setVisibleHelper(visible, /* explicit = */ true); } /*! \fn void QGraphicsItem::hide() Hides the item. (Items are visible by default.) This convenience function is equivalent to calling \c setVisible(false). \sa show(), setVisible() */ /*! \fn void QGraphicsItem::show() Shows the item. (Items are visible by default.) This convenience function is equivalent to calling \c setVisible(true). \sa hide(), setVisible() */ /*! Returns true if the item is enabled; otherwise, false is returned. \sa setEnabled() */ bool QGraphicsItem::isEnabled() const { return d_ptr->enabled; } /*! \internal Sets this item's visibility to \a newEnabled. If \a explicitly is true, this item will be "explicitly" \a newEnabled; otherwise, it.. will not be. */ void QGraphicsItemPrivate::setEnabledHelper(bool newEnabled, bool explicitly, bool update) { // Update explicit bit. if (explicitly) explicitlyDisabled = newEnabled ? 0 : 1; // Check if there's nothing to do. if (enabled == quint32(newEnabled)) return; // Certain properties are dropped when an item is disabled. if (!newEnabled) { if (scene && scene->mouseGrabberItem() == q_ptr) q_ptr->ungrabMouse(); if (q_ptr->hasFocus()) { // Disabling the closest non-panel ancestor of the focus item // causes focus to pop to the next item, otherwise it's cleared. QGraphicsItem *focusItem = scene->focusItem(); if (isWidget && !focusItem->isPanel() && q_ptr->isAncestorOf(focusItem)) { do { if (focusItem == q_ptr) { static_cast<QGraphicsWidget *>(q_ptr)->focusNextPrevChild(true); break; } } while ((focusItem = focusItem->parentWidget()) && !focusItem->isPanel()); } // Clear focus if previous steps didn't move it to another widget if (q_ptr->hasFocus()) q_ptr->clearFocus(); } if (q_ptr->isSelected()) q_ptr->setSelected(false); } // Modify the property. const QVariant newEnabledVariant(q_ptr->itemChange(QGraphicsItem::ItemEnabledChange, quint32(newEnabled))); enabled = newEnabledVariant.toBool(); // Schedule redraw. if (update) q_ptr->update(); foreach (QGraphicsItem *child, children) { if (!newEnabled || !child->d_ptr->explicitlyDisabled) child->d_ptr->setEnabledHelper(newEnabled, /* explicitly = */ false); } // Deliver post-change notification. q_ptr->itemChange(QGraphicsItem::ItemEnabledHasChanged, newEnabledVariant); if (isObject) emit static_cast<QGraphicsObject *>(q_ptr)->enabledChanged(); } /*! If \a enabled is true, the item is enabled; otherwise, it is disabled. Disabled items are visible, but they do not receive any events, and cannot take focus nor be selected. Mouse events are discarded; they are not propagated unless the item is also invisible, or if it does not accept mouse events (see acceptedMouseButtons()). A disabled item cannot become the mouse grabber, and as a result of this, an item loses the grab if it becomes disabled when grabbing the mouse, just like it loses focus if it had focus when it was disabled. Disabled items are traditionally drawn using grayed-out colors (see \l QPalette::Disabled). If you disable a parent item, all its children will also be disabled. If you enable a parent item, all children will be enabled, unless they have been explicitly disabled (i.e., if you call setEnabled(false) on a child, it will not be reenabled if its parent is disabled, and then enabled again). Items are enabled by default. \note If you install an event filter, you can still intercept events before they are delivered to items; this mechanism disregards the item's enabled state. \sa isEnabled() */ void QGraphicsItem::setEnabled(bool enabled) { d_ptr->setEnabledHelper(enabled, /* explicitly = */ true); } /*! Returns true if this item is selected; otherwise, false is returned. Items that are in a group inherit the group's selected state. Items are not selected by default. \sa setSelected(), QGraphicsScene::setSelectionArea() */ bool QGraphicsItem::isSelected() const { if (QGraphicsItemGroup *group = this->group()) return group->isSelected(); return d_ptr->selected; } /*! If \a selected is true and this item is selectable, this item is selected; otherwise, it is unselected. If the item is in a group, the whole group's selected state is toggled by this function. If the group is selected, all items in the group are also selected, and if the group is not selected, no item in the group is selected. Only visible, enabled, selectable items can be selected. If \a selected is true and this item is either invisible or disabled or unselectable, this function does nothing. By default, items cannot be selected. To enable selection, set the ItemIsSelectable flag. This function is provided for convenience, allowing individual toggling of the selected state of an item. However, a more common way of selecting items is to call QGraphicsScene::setSelectionArea(), which will call this function for all visible, enabled, and selectable items within a specified area on the scene. \sa isSelected(), QGraphicsScene::selectedItems() */ void QGraphicsItem::setSelected(bool selected) { if (QGraphicsItemGroup *group = this->group()) { group->setSelected(selected); return; } if (!(d_ptr->flags & ItemIsSelectable) || !d_ptr->enabled || !d_ptr->visible) selected = false; if (d_ptr->selected == selected) return; const QVariant newSelectedVariant(itemChange(ItemSelectedChange, quint32(selected))); bool newSelected = newSelectedVariant.toBool(); if (d_ptr->selected == newSelected) return; d_ptr->selected = newSelected; update(); if (d_ptr->scene) { QGraphicsScenePrivate *sceneD = d_ptr->scene->d_func(); if (selected) { sceneD->selectedItems << this; } else { // QGraphicsScene::selectedItems() lazily pulls out all items that are // no longer selected. } if (!sceneD->selectionChanging) emit d_ptr->scene->selectionChanged(); } // Deliver post-change notification. itemChange(QGraphicsItem::ItemSelectedHasChanged, newSelectedVariant); } /*! \since 4.5 Returns this item's local opacity, which is between 0.0 (transparent) and 1.0 (opaque). This value is combined with parent and ancestor values into the effectiveOpacity(). The effective opacity decides how the item is rendered. The opacity property decides the state of the painter passed to the paint() function. If the item is cached, i.e., ItemCoordinateCache or DeviceCoordinateCache, the effective property will be applied to the item's cache as it is rendered. The default opacity is 1.0; fully opaque. \sa setOpacity(), paint(), ItemIgnoresParentOpacity, ItemDoesntPropagateOpacityToChildren */ qreal QGraphicsItem::opacity() const { return d_ptr->opacity; } /*! \since 4.5 Returns this item's \e effective opacity, which is between 0.0 (transparent) and 1.0 (opaque). This value is a combination of this item's local opacity, and its parent and ancestors' opacities. The effective opacity decides how the item is rendered. \sa opacity(), setOpacity(), paint(), ItemIgnoresParentOpacity, ItemDoesntPropagateOpacityToChildren */ qreal QGraphicsItem::effectiveOpacity() const { return d_ptr->effectiveOpacity(); } /*! \since 4.5 Sets this item's local \a opacity, between 0.0 (transparent) and 1.0 (opaque). The item's local opacity is combined with parent and ancestor opacities into the effectiveOpacity(). By default, opacity propagates from parent to child, so if a parent's opacity is 0.5 and the child is also 0.5, the child's effective opacity will be 0.25. The opacity property decides the state of the painter passed to the paint() function. If the item is cached, i.e., ItemCoordinateCache or DeviceCoordinateCache, the effective property will be applied to the item's cache as it is rendered. There are two item flags that affect how the item's opacity is combined with the parent: ItemIgnoresParentOpacity and ItemDoesntPropagateOpacityToChildren. \sa opacity(), effectiveOpacity() */ void QGraphicsItem::setOpacity(qreal opacity) { // Notify change. const QVariant newOpacityVariant(itemChange(ItemOpacityChange, opacity)); // Normalized opacity qreal newOpacity = qBound(qreal(0), newOpacityVariant.toReal(), qreal(1)); // No change? Done. if (newOpacity == d_ptr->opacity) return; bool wasFullyTransparent = d_ptr->isOpacityNull(); d_ptr->opacity = newOpacity; // Notify change. itemChange(ItemOpacityHasChanged, newOpacityVariant); // Update. if (d_ptr->scene) { #ifndef QT_NO_GRAPHICSEFFECT d_ptr->invalidateParentGraphicsEffectsRecursively(); if (!(d_ptr->flags & ItemDoesntPropagateOpacityToChildren)) d_ptr->invalidateChildGraphicsEffectsRecursively(QGraphicsItemPrivate::OpacityChanged); #endif //QT_NO_GRAPHICSEFFECT d_ptr->scene->d_func()->markDirty(this, QRectF(), /*invalidateChildren=*/true, /*force=*/false, /*ignoreOpacity=*/d_ptr->isOpacityNull()); if (wasFullyTransparent) d_ptr->paintedViewBoundingRectsNeedRepaint = 1; } if (d_ptr->isObject) emit static_cast<QGraphicsObject *>(this)->opacityChanged(); } /*! Returns a pointer to this item's effect if it has one; otherwise 0. \since 4.6 */ #ifndef QT_NO_GRAPHICSEFFECT QGraphicsEffect *QGraphicsItem::graphicsEffect() const { return d_ptr->graphicsEffect; } /*! Sets \a effect as the item's effect. If there already is an effect installed on this item, QGraphicsItem will delete the existing effect before installing the new \a effect. If \a effect is the installed on a different item, setGraphicsEffect() will remove the effect from the item and install it on this item. QGraphicsItem takes ownership of \a effect. \note This function will apply the effect on itself and all its children. \since 4.6 */ void QGraphicsItem::setGraphicsEffect(QGraphicsEffect *effect) { if (d_ptr->graphicsEffect == effect) return; if (d_ptr->graphicsEffect) { delete d_ptr->graphicsEffect; d_ptr->graphicsEffect = 0; } else if (d_ptr->parent) { d_ptr->parent->d_ptr->updateChildWithGraphicsEffectFlagRecursively(); } if (effect) { // Set new effect. QGraphicsEffectSourcePrivate *sourced = new QGraphicsItemEffectSourcePrivate(this); QGraphicsEffectSource *source = new QGraphicsEffectSource(*sourced); d_ptr->graphicsEffect = effect; effect->d_func()->setGraphicsEffectSource(source); prepareGeometryChange(); } } #endif //QT_NO_GRAPHICSEFFECT void QGraphicsItemPrivate::updateChildWithGraphicsEffectFlagRecursively() { #ifndef QT_NO_GRAPHICSEFFECT QGraphicsItemPrivate *itemPrivate = this; do { // parent chain already notified? if (itemPrivate->mayHaveChildWithGraphicsEffect) return; itemPrivate->mayHaveChildWithGraphicsEffect = 1; } while ((itemPrivate = itemPrivate->parent ? itemPrivate->parent->d_ptr.data() : 0)); #endif } /*! \internal \since 4.6 Returns the effective bounding rect of the given item space rect. If the item has no effect, the rect is returned unmodified. If the item has an effect, the effective rect can be extend beyond the item's bounding rect, depending on the effect. \sa boundingRect() */ QRectF QGraphicsItemPrivate::effectiveBoundingRect(const QRectF &rect) const { #ifndef QT_NO_GRAPHICSEFFECT Q_Q(const QGraphicsItem); QGraphicsEffect *effect = graphicsEffect; if (scene && effect && effect->isEnabled()) { if (scene->d_func()->views.isEmpty()) return effect->boundingRectFor(rect); QRectF sceneRect = q->mapRectToScene(rect); QRectF sceneEffectRect; foreach (QGraphicsView *view, scene->views()) { QRectF deviceRect = view->d_func()->mapRectFromScene(sceneRect); QRect deviceEffectRect = effect->boundingRectFor(deviceRect).toAlignedRect(); sceneEffectRect |= view->d_func()->mapRectToScene(deviceEffectRect); } return q->mapRectFromScene(sceneEffectRect); } #endif //QT_NO_GRAPHICSEFFECT return rect; } /*! \internal \since 4.6 Returns the effective bounding rect of the item. If the item has no effect, this is the same as the item's bounding rect. If the item has an effect, the effective rect can be larger than the item's bouding rect, depending on the effect. \sa boundingRect() */ QRectF QGraphicsItemPrivate::effectiveBoundingRect(QGraphicsItem *topMostEffectItem) const { #ifndef QT_NO_GRAPHICSEFFECT Q_Q(const QGraphicsItem); QRectF brect = effectiveBoundingRect(q_ptr->boundingRect()); if (ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren || topMostEffectItem == q) return brect; const QGraphicsItem *effectParent = parent; while (effectParent) { QGraphicsEffect *effect = effectParent->d_ptr->graphicsEffect; if (scene && effect && effect->isEnabled()) { const QRectF brectInParentSpace = q->mapRectToItem(effectParent, brect); const QRectF effectRectInParentSpace = effectParent->d_ptr->effectiveBoundingRect(brectInParentSpace); brect = effectParent->mapRectToItem(q, effectRectInParentSpace); } if (effectParent->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren || topMostEffectItem == effectParent) { return brect; } effectParent = effectParent->d_ptr->parent; } return brect; #else //QT_NO_GRAPHICSEFFECT return q_ptr->boundingRect(); #endif //QT_NO_GRAPHICSEFFECT } /*! \internal \since 4.6 Returns the effective bounding rect of this item in scene coordinates, by combining sceneTransform() with boundingRect(), taking into account the effect that the item might have. If the item has no effect, this is the same as sceneBoundingRect(). \sa effectiveBoundingRect(), sceneBoundingRect() */ QRectF QGraphicsItemPrivate::sceneEffectiveBoundingRect() const { // Find translate-only offset // COMBINE QPointF offset; const QGraphicsItem *parentItem = q_ptr; const QGraphicsItemPrivate *itemd; do { itemd = parentItem->d_ptr.data(); if (itemd->transformData) break; offset += itemd->pos; } while ((parentItem = itemd->parent)); QRectF br = effectiveBoundingRect(); br.translate(offset); return !parentItem ? br : parentItem->sceneTransform().mapRect(br); } /*! Returns true if this item can accept drag and drop events; otherwise, returns false. By default, items do not accept drag and drop events; items are transparent to drag and drop. \sa setAcceptDrops() */ bool QGraphicsItem::acceptDrops() const { return d_ptr->acceptDrops; } /*! If \a on is true, this item will accept drag and drop events; otherwise, it is transparent for drag and drop events. By default, items do not accept drag and drop events. \sa acceptDrops() */ void QGraphicsItem::setAcceptDrops(bool on) { d_ptr->acceptDrops = on; } /*! Returns the mouse buttons that this item accepts mouse events for. By default, all mouse buttons are accepted. If an item accepts a mouse button, it will become the mouse grabber item when a mouse press event is delivered for that mouse button. However, if the item does not accept the button, QGraphicsScene will forward the mouse events to the first item beneath it that does. \sa setAcceptedMouseButtons(), mousePressEvent() */ Qt::MouseButtons QGraphicsItem::acceptedMouseButtons() const { return Qt::MouseButtons(d_ptr->acceptedMouseButtons); } /*! Sets the mouse \a buttons that this item accepts mouse events for. By default, all mouse buttons are accepted. If an item accepts a mouse button, it will become the mouse grabber item when a mouse press event is delivered for that button. However, if the item does not accept the mouse button, QGraphicsScene will forward the mouse events to the first item beneath it that does. To disable mouse events for an item (i.e., make it transparent for mouse events), call setAcceptedMouseButtons(0). \sa acceptedMouseButtons(), mousePressEvent() */ void QGraphicsItem::setAcceptedMouseButtons(Qt::MouseButtons buttons) { if (Qt::MouseButtons(d_ptr->acceptedMouseButtons) != buttons) { if (buttons == 0 && d_ptr->scene && d_ptr->scene->mouseGrabberItem() == this && d_ptr->scene->d_func()->lastMouseGrabberItemHasImplicitMouseGrab) { ungrabMouse(); } d_ptr->acceptedMouseButtons = quint32(buttons); } } /*! \since 4.4 Returns true if an item accepts hover events (QGraphicsSceneHoverEvent); otherwise, returns false. By default, items do not accept hover events. \sa setAcceptedMouseButtons() */ bool QGraphicsItem::acceptHoverEvents() const { return d_ptr->acceptsHover; } /*! \obsolete Call acceptHoverEvents() instead. */ bool QGraphicsItem::acceptsHoverEvents() const { return d_ptr->acceptsHover; } /*! \since 4.4 If \a enabled is true, this item will accept hover events; otherwise, it will ignore them. By default, items do not accept hover events. Hover events are delivered when there is no current mouse grabber item. They are sent when the mouse cursor enters an item, when it moves around inside the item, and when the cursor leaves an item. Hover events are commonly used to highlight an item when it's entered, and for tracking the mouse cursor as it hovers over the item (equivalent to QWidget::mouseTracking). Parent items receive hover enter events before their children, and leave events after their children. The parent does not receive a hover leave event if the cursor enters a child, though; the parent stays "hovered" until the cursor leaves its area, including its children's areas. If a parent item handles child events, it will receive hover move, drag move, and drop events as the cursor passes through its children, but it does not receive hover enter and hover leave, nor drag enter and drag leave events on behalf of its children. A QGraphicsWidget with window decorations will accept hover events regardless of the value of acceptHoverEvents(). \sa acceptHoverEvents(), hoverEnterEvent(), hoverMoveEvent(), hoverLeaveEvent() */ void QGraphicsItem::setAcceptHoverEvents(bool enabled) { if (d_ptr->acceptsHover == quint32(enabled)) return; d_ptr->acceptsHover = quint32(enabled); if (d_ptr->acceptsHover && d_ptr->scene && d_ptr->scene->d_func()->allItemsIgnoreHoverEvents) { d_ptr->scene->d_func()->allItemsIgnoreHoverEvents = false; d_ptr->scene->d_func()->enableMouseTrackingOnViews(); } } /*! \obsolete Use setAcceptHoverEvents(\a enabled) instead. */ void QGraphicsItem::setAcceptsHoverEvents(bool enabled) { setAcceptHoverEvents(enabled); } /*! \since 4.6 Returns true if an item accepts \l{QTouchEvent}{touch events}; otherwise, returns false. By default, items do not accept touch events. \sa setAcceptTouchEvents() */ bool QGraphicsItem::acceptTouchEvents() const { return d_ptr->acceptTouchEvents; } /*! \since 4.6 If \a enabled is true, this item will accept \l{QTouchEvent}{touch events}; otherwise, it will ignore them. By default, items do not accept touch events. */ void QGraphicsItem::setAcceptTouchEvents(bool enabled) { if (d_ptr->acceptTouchEvents == quint32(enabled)) return; d_ptr->acceptTouchEvents = quint32(enabled); if (d_ptr->acceptTouchEvents && d_ptr->scene && d_ptr->scene->d_func()->allItemsIgnoreTouchEvents) { d_ptr->scene->d_func()->allItemsIgnoreTouchEvents = false; d_ptr->scene->d_func()->enableTouchEventsOnViews(); } } /*! \since 4.6 Returns true if this item filters child events (i.e., all events intended for any of its children are instead sent to this item); otherwise, false is returned. The default value is false; child events are not filtered. \sa setFiltersChildEvents() */ bool QGraphicsItem::filtersChildEvents() const { return d_ptr->filtersDescendantEvents; } /*! \since 4.6 If \a enabled is true, this item is set to filter all events for all its children (i.e., all events intented for any of its children are instead sent to this item); otherwise, if \a enabled is false, this item will only handle its own events. The default value is false. \sa filtersChildEvents() */ void QGraphicsItem::setFiltersChildEvents(bool enabled) { if (d_ptr->filtersDescendantEvents == enabled) return; d_ptr->filtersDescendantEvents = enabled; d_ptr->updateAncestorFlag(QGraphicsItem::GraphicsItemFlag(-2)); } /*! \obsolete Returns true if this item handles child events (i.e., all events intended for any of its children are instead sent to this item); otherwise, false is returned. This property is useful for item groups; it allows one item to handle events on behalf of its children, as opposed to its children handling their events individually. The default is to return false; children handle their own events. The exception for this is if the item is a QGraphicsItemGroup, then it defaults to return true. \sa setHandlesChildEvents() */ bool QGraphicsItem::handlesChildEvents() const { return d_ptr->handlesChildEvents; } /*! \obsolete If \a enabled is true, this item is set to handle all events for all its children (i.e., all events intented for any of its children are instead sent to this item); otherwise, if \a enabled is false, this item will only handle its own events. The default value is false. This property is useful for item groups; it allows one item to handle events on behalf of its children, as opposed to its children handling their events individually. If a child item accepts hover events, its parent will receive hover move events as the cursor passes through the child, but it does not receive hover enter and hover leave events on behalf of its child. \sa handlesChildEvents() */ void QGraphicsItem::setHandlesChildEvents(bool enabled) { if (d_ptr->handlesChildEvents == enabled) return; d_ptr->handlesChildEvents = enabled; d_ptr->updateAncestorFlag(QGraphicsItem::GraphicsItemFlag(-1)); } /*! \since 4.6 Returns true if this item is active; otherwise returns false. An item can only be active if the scene is active. An item is active if it is, or is a descendent of, an active panel. Items in non-active panels are not active. Items that are not part of a panel follow scene activation when the scene has no active panel. Only active items can gain input focus. \sa QGraphicsScene::isActive(), QGraphicsScene::activePanel(), panel(), isPanel() */ bool QGraphicsItem::isActive() const { if (!d_ptr->scene || !d_ptr->scene->isActive()) return false; return panel() == d_ptr->scene->activePanel(); } /*! \since 4.6 If \a active is true, and the scene is active, this item's panel will be activated. Otherwise, the panel is deactivated. If the item is not part of an active scene, \a active will decide what happens to the panel when the scene becomes active or the item is added to the scene. If true, the item's panel will be activated when the item is either added to the scene or the scene is activated. Otherwise, the item will stay inactive independent of the scene's activated state. \sa isPanel(), QGraphicsScene::setActivePanel(), QGraphicsScene::isActive() */ void QGraphicsItem::setActive(bool active) { d_ptr->explicitActivate = 1; d_ptr->wantsActive = active; if (d_ptr->scene) { if (active) { // Activate this item. d_ptr->scene->setActivePanel(this); } else { // Deactivate this item, and reactivate the last active item // (if any). QGraphicsItem *lastActive = d_ptr->scene->d_func()->lastActivePanel; d_ptr->scene->setActivePanel(lastActive != this ? lastActive : 0); } } } /*! Returns true if this item is active, and it or its \l{focusProxy()}{focus proxy} has keyboard input focus; otherwise, returns false. \sa focusItem(), setFocus(), QGraphicsScene::setFocusItem(), isActive() */ bool QGraphicsItem::hasFocus() const { if (!d_ptr->scene || !d_ptr->scene->isActive()) return false; if (d_ptr->focusProxy) return d_ptr->focusProxy->hasFocus(); if (d_ptr->scene->d_func()->focusItem != this) return false; return panel() == d_ptr->scene->d_func()->activePanel; } /*! Gives keyboard input focus to this item. The \a focusReason argument will be passed into any \l{QFocusEvent}{focus event} generated by this function; it is used to give an explanation of what caused the item to get focus. Only enabled items that set the ItemIsFocusable flag can accept keyboard focus. If this item is not visible, not active, or not associated with a scene, it will not gain immediate input focus. However, it will be registered as the preferred focus item for its subtree of items, should it later become visible. As a result of calling this function, this item will receive a \l{focusInEvent()}{focus in event} with \a focusReason. If another item already has focus, that item will first receive a \l{focusOutEvent()} {focus out event} indicating that it has lost input focus. \sa clearFocus(), hasFocus(), focusItem(), focusProxy() */ void QGraphicsItem::setFocus(Qt::FocusReason focusReason) { d_ptr->setFocusHelper(focusReason, /* climb = */ true, /* focusFromHide = */ false); } /*! \internal */ void QGraphicsItemPrivate::setFocusHelper(Qt::FocusReason focusReason, bool climb, bool focusFromHide) { // Disabled / unfocusable items cannot accept focus. if (!q_ptr->isEnabled() || !(flags & QGraphicsItem::ItemIsFocusable)) return; // Find focus proxy. QGraphicsItem *f = q_ptr; while (f->d_ptr->focusProxy) f = f->d_ptr->focusProxy; // Return if it already has focus. if (scene && scene->focusItem() == f) return; // Update focus scope item ptr. QGraphicsItem *p = parent; while (p) { if (p->flags() & QGraphicsItem::ItemIsFocusScope) { QGraphicsItem *oldFocusScopeItem = p->d_ptr->focusScopeItem; p->d_ptr->focusScopeItem = q_ptr; if (!p->focusItem() && !focusFromHide) { if (oldFocusScopeItem) oldFocusScopeItem->d_ptr->focusScopeItemChange(false); focusScopeItemChange(true); // If you call setFocus on a child of a focus scope that // doesn't currently have a focus item, then stop. return; } break; } p = p->d_ptr->parent; } if (climb) { while (f->d_ptr->focusScopeItem && f->d_ptr->focusScopeItem->isVisible()) f = f->d_ptr->focusScopeItem; } // Update the child focus chain. QGraphicsItem *commonAncestor = 0; if (scene && scene->focusItem()) { commonAncestor = scene->focusItem()->commonAncestorItem(f); scene->focusItem()->d_ptr->clearSubFocus(scene->focusItem(), commonAncestor); } f->d_ptr->setSubFocus(f, commonAncestor); // Update the scene's focus item. if (scene) { QGraphicsItem *p = q_ptr->panel(); if ((!p && scene->isActive()) || (p && p->isActive())) { // Visible items immediately gain focus from scene. scene->d_func()->setFocusItemHelper(f, focusReason); } } } /*! Takes keyboard input focus from the item. If it has focus, a \l{focusOutEvent()}{focus out event} is sent to this item to tell it that it is about to lose the focus. Only items that set the ItemIsFocusable flag, or widgets that set an appropriate focus policy, can accept keyboard focus. \sa setFocus(), hasFocus(), QGraphicsWidget::focusPolicy */ void QGraphicsItem::clearFocus() { d_ptr->clearFocusHelper(/* giveFocusToParent = */ true); } /*! \internal */ void QGraphicsItemPrivate::clearFocusHelper(bool giveFocusToParent) { if (giveFocusToParent) { // Pass focus to the closest parent focus scope if (!inDestructor) { QGraphicsItem *p = parent; while (p) { if (p->flags() & QGraphicsItem::ItemIsFocusScope) { if (p->d_ptr->focusScopeItem == q_ptr) { p->d_ptr->focusScopeItem = 0; if (!q_ptr->hasFocus()) //if it has focus, focusScopeItemChange is called elsewhere focusScopeItemChange(false); } if (q_ptr->hasFocus()) p->d_ptr->setFocusHelper(Qt::OtherFocusReason, /* climb = */ false, /* focusFromHide = */ false); return; } p = p->d_ptr->parent; } } } if (q_ptr->hasFocus()) { // Invisible items with focus must explicitly clear subfocus. clearSubFocus(q_ptr); // If this item has the scene's input focus, clear it. scene->setFocusItem(0); } } /*! \since 4.6 Returns this item's focus proxy, or 0 if this item has no focus proxy. \sa setFocusProxy(), setFocus(), hasFocus() */ QGraphicsItem *QGraphicsItem::focusProxy() const { return d_ptr->focusProxy; } /*! \since 4.6 Sets the item's focus proxy to \a item. If an item has a focus proxy, the focus proxy will receive input focus when the item gains input focus. The item itself will still have focus (i.e., hasFocus() will return true), but only the focus proxy will receive the keyboard input. A focus proxy can itself have a focus proxy, and so on. In such case, keyboard input will be handled by the outermost focus proxy. The focus proxy \a item must belong to the same scene as this item. \sa focusProxy(), setFocus(), hasFocus() */ void QGraphicsItem::setFocusProxy(QGraphicsItem *item) { if (item == d_ptr->focusProxy) return; if (item == this) { qWarning("QGraphicsItem::setFocusProxy: cannot assign self as focus proxy"); return; } if (item) { if (item->d_ptr->scene != d_ptr->scene) { qWarning("QGraphicsItem::setFocusProxy: focus proxy must be in same scene"); return; } for (QGraphicsItem *f = item->focusProxy(); f != 0; f = f->focusProxy()) { if (f == this) { qWarning("QGraphicsItem::setFocusProxy: %p is already in the focus proxy chain", item); return; } } } QGraphicsItem *lastFocusProxy = d_ptr->focusProxy; if (lastFocusProxy) lastFocusProxy->d_ptr->focusProxyRefs.removeOne(&d_ptr->focusProxy); d_ptr->focusProxy = item; if (item) item->d_ptr->focusProxyRefs << &d_ptr->focusProxy; } /*! \since 4.6 If this item, a child or descendant of this item currently has input focus, this function will return a pointer to that item. If no descendant has input focus, 0 is returned. \sa hasFocus(), setFocus(), QWidget::focusWidget() */ QGraphicsItem *QGraphicsItem::focusItem() const { return d_ptr->subFocusItem; } /*! \internal Returns this item's focus scope item. */ QGraphicsItem *QGraphicsItem::focusScopeItem() const { return d_ptr->focusScopeItem; } /*! \since 4.4 Grabs the mouse input. This item will receive all mouse events for the scene until any of the following events occurs: \list \o The item becomes invisible \o The item is removed from the scene \o The item is deleted \o The item call ungrabMouse() \o Another item calls grabMouse(); the item will regain the mouse grab when the other item calls ungrabMouse(). \endlist When an item gains the mouse grab, it receives a QEvent::GrabMouse event. When it loses the mouse grab, it receives a QEvent::UngrabMouse event. These events can be used to detect when your item gains or loses the mouse grab through other means than receiving mouse button events. It is almost never necessary to explicitly grab the mouse in Qt, as Qt grabs and releases it sensibly. In particular, Qt grabs the mouse when you press a mouse button, and keeps the mouse grabbed until you release the last mouse button. Also, Qt::Popup widgets implicitly call grabMouse() when shown, and ungrabMouse() when hidden. Note that only visible items can grab mouse input. Calling grabMouse() on an invisible item has no effect. Keyboard events are not affected. \sa QGraphicsScene::mouseGrabberItem(), ungrabMouse(), grabKeyboard() */ void QGraphicsItem::grabMouse() { if (!d_ptr->scene) { qWarning("QGraphicsItem::grabMouse: cannot grab mouse without scene"); return; } if (!d_ptr->visible) { qWarning("QGraphicsItem::grabMouse: cannot grab mouse while invisible"); return; } d_ptr->scene->d_func()->grabMouse(this); } /*! \since 4.4 Releases the mouse grab. \sa grabMouse(), ungrabKeyboard() */ void QGraphicsItem::ungrabMouse() { if (!d_ptr->scene) { qWarning("QGraphicsItem::ungrabMouse: cannot ungrab mouse without scene"); return; } d_ptr->scene->d_func()->ungrabMouse(this); } /*! \since 4.4 Grabs the keyboard input. The item will receive all keyboard input to the scene until one of the following events occur: \list \o The item becomes invisible \o The item is removed from the scene \o The item is deleted \o The item calls ungrabKeyboard() \o Another item calls grabKeyboard(); the item will regain the keyboard grab when the other item calls ungrabKeyboard(). \endlist When an item gains the keyboard grab, it receives a QEvent::GrabKeyboard event. When it loses the keyboard grab, it receives a QEvent::UngrabKeyboard event. These events can be used to detect when your item gains or loses the keyboard grab through other means than gaining input focus. It is almost never necessary to explicitly grab the keyboard in Qt, as Qt grabs and releases it sensibly. In particular, Qt grabs the keyboard when your item gains input focus, and releases it when your item loses input focus, or when the item is hidden. Note that only visible items can grab keyboard input. Calling grabKeyboard() on an invisible item has no effect. Keyboard events are not affected. \sa ungrabKeyboard(), grabMouse(), setFocus() */ void QGraphicsItem::grabKeyboard() { if (!d_ptr->scene) { qWarning("QGraphicsItem::grabKeyboard: cannot grab keyboard without scene"); return; } if (!d_ptr->visible) { qWarning("QGraphicsItem::grabKeyboard: cannot grab keyboard while invisible"); return; } d_ptr->scene->d_func()->grabKeyboard(this); } /*! \since 4.4 Releases the keyboard grab. \sa grabKeyboard(), ungrabMouse() */ void QGraphicsItem::ungrabKeyboard() { if (!d_ptr->scene) { qWarning("QGraphicsItem::ungrabKeyboard: cannot ungrab keyboard without scene"); return; } d_ptr->scene->d_func()->ungrabKeyboard(this); } /*! Returns the position of the item in parent coordinates. If the item has no parent, its position is given in scene coordinates. The position of the item describes its origin (local coordinate (0, 0)) in parent coordinates; this function returns the same as mapToParent(0, 0). For convenience, you can also call scenePos() to determine the item's position in scene coordinates, regardless of its parent. \sa x(), y(), setPos(), transform(), {The Graphics View Coordinate System} */ QPointF QGraphicsItem::pos() const { return d_ptr->pos; } /*! \fn QGraphicsItem::x() const This convenience function is equivalent to calling pos().x(). \sa y() */ /*! \since 4.6 Set's the \a x coordinate of the item's position. Equivalent to calling setPos(x, y()). \sa x(), setPos() */ void QGraphicsItem::setX(qreal x) { if (d_ptr->inDestructor) return; if (qIsNaN(x)) return; setPos(QPointF(x, d_ptr->pos.y())); } /*! \fn QGraphicsItem::y() const This convenience function is equivalent to calling pos().y(). \sa x() */ /*! \since 4.6 Set's the \a y coordinate of the item's position. Equivalent to calling setPos(x(), y). \sa x(), setPos() */ void QGraphicsItem::setY(qreal y) { if (d_ptr->inDestructor) return; if (qIsNaN(y)) return; setPos(QPointF(d_ptr->pos.x(), y)); } /*! Returns the item's position in scene coordinates. This is equivalent to calling \c mapToScene(0, 0). \sa pos(), sceneTransform(), {The Graphics View Coordinate System} */ QPointF QGraphicsItem::scenePos() const { return mapToScene(0, 0); } /*! \internal Sets the position \a pos. */ void QGraphicsItemPrivate::setPosHelper(const QPointF &pos) { Q_Q(QGraphicsItem); inSetPosHelper = 1; if (scene) q->prepareGeometryChange(); QPointF oldPos = this->pos; this->pos = pos; dirtySceneTransform = 1; inSetPosHelper = 0; if (isObject) { if (pos.x() != oldPos.x()) emit static_cast<QGraphicsObject *>(q_ptr)->xChanged(); if (pos.y() != oldPos.y()) emit static_cast<QGraphicsObject *>(q_ptr)->yChanged(); } } /*! \internal Sets the transform \a transform. */ void QGraphicsItemPrivate::setTransformHelper(const QTransform &transform) { q_ptr->prepareGeometryChange(); transformData->transform = transform; dirtySceneTransform = 1; transformChanged(); } /*! Sets the position of the item to \a pos, which is in parent coordinates. For items with no parent, \a pos is in scene coordinates. The position of the item describes its origin (local coordinate (0, 0)) in parent coordinates. \sa pos(), scenePos(), {The Graphics View Coordinate System} */ void QGraphicsItem::setPos(const QPointF &pos) { if (d_ptr->pos == pos) return; if (d_ptr->inDestructor) return; // Update and repositition. if (!(d_ptr->flags & (ItemSendsGeometryChanges | ItemSendsScenePositionChanges))) { d_ptr->setPosHelper(pos); if (d_ptr->isWidget) static_cast<QGraphicsWidget *>(this)->d_func()->setGeometryFromSetPos(); if (d_ptr->scenePosDescendants) d_ptr->sendScenePosChange(); return; } // Notify the item that the position is changing. const QVariant newPosVariant(itemChange(ItemPositionChange, QVariant::fromValue<QPointF>(pos))); QPointF newPos = newPosVariant.toPointF(); if (newPos == d_ptr->pos) return; // Update and repositition. d_ptr->setPosHelper(newPos); // Send post-notification. itemChange(QGraphicsItem::ItemPositionHasChanged, newPosVariant); d_ptr->sendScenePosChange(); } /*! \fn void QGraphicsItem::setPos(qreal x, qreal y) \overload This convenience function is equivalent to calling setPos(QPointF(\a x, \a y)). */ /*! \fn void QGraphicsItem::moveBy(qreal dx, qreal dy) Moves the item by \a dx points horizontally, and \a dy point vertically. This function is equivalent to calling setPos(pos() + QPointF(\a dx, \a dy)). */ /*! If this item is part of a scene that is viewed by a QGraphicsView, this convenience function will attempt to scroll the view to ensure that \a rect is visible inside the view's viewport. If \a rect is a null rect (the default), QGraphicsItem will default to the item's bounding rect. \a xmargin and \a ymargin are the number of pixels the view should use for margins. If the specified rect cannot be reached, the contents are scrolled to the nearest valid position. If this item is not viewed by a QGraphicsView, this function does nothing. \sa QGraphicsView::ensureVisible() */ void QGraphicsItem::ensureVisible(const QRectF &rect, int xmargin, int ymargin) { if (d_ptr->scene) { QRectF sceneRect; if (!rect.isNull()) sceneRect = sceneTransform().mapRect(rect); else sceneRect = sceneBoundingRect(); foreach (QGraphicsView *view, d_ptr->scene->d_func()->views) view->ensureVisible(sceneRect, xmargin, ymargin); } } /*! \fn void QGraphicsItem::ensureVisible(qreal x, qreal y, qreal w, qreal h, int xmargin = 50, int ymargin = 50) This convenience function is equivalent to calling ensureVisible(QRectF(\a x, \a y, \a w, \a h), \a xmargin, \a ymargin): */ /*! \obsolete Returns the item's affine transformation matrix. This is a subset or the item's full transformation matrix, and might not represent the item's full transformation. Use transform() instead. \sa setTransform(), sceneTransform() */ QMatrix QGraphicsItem::matrix() const { return transform().toAffine(); } /*! \since 4.3 Returns this item's transformation matrix. The transformation matrix is combined with the item's rotation(), scale() and transformations() into a combined transformations for the item. The default transformation matrix is an identity matrix. \sa setTransform(), sceneTransform() */ QTransform QGraphicsItem::transform() const { if (!d_ptr->transformData) return QTransform(); return d_ptr->transformData->transform; } /*! \since 4.6 Returns the clockwise rotation, in degrees, around the Z axis. The default value is 0 (i.e., the item is not rotated). The rotation is combined with the item's scale(), transform() and transformations() to map the item's coordinate system to the parent item. \sa setRotation(), transformOriginPoint(), {Transformations} */ qreal QGraphicsItem::rotation() const { if (!d_ptr->transformData) return 0; return d_ptr->transformData->rotation; } /*! \since 4.6 Sets the clockwise rotation \a angle, in degrees, around the Z axis. The default value is 0 (i.e., the item is not rotated). Assigning a negative value will rotate the item counter-clockwise. Normally the rotation angle is in the range (-360, 360), but it's also possible to assign values outside of this range (e.g., a rotation of 370 degrees is the same as a rotation of 10 degrees). The item is rotated around its transform origin point, which by default is (0, 0). You can select a different transformation origin by calling setTransformOriginPoint(). The rotation is combined with the item's scale(), transform() and transformations() to map the item's coordinate system to the parent item. \sa rotation(), setTransformOriginPoint(), {Transformations} */ void QGraphicsItem::setRotation(qreal angle) { prepareGeometryChange(); qreal newRotation = angle; if (d_ptr->flags & ItemSendsGeometryChanges) { // Notify the item that the rotation is changing. const QVariant newRotationVariant(itemChange(ItemRotationChange, angle)); newRotation = newRotationVariant.toReal(); } if (!d_ptr->transformData) d_ptr->transformData = new QGraphicsItemPrivate::TransformData; if (d_ptr->transformData->rotation == newRotation) return; d_ptr->transformData->rotation = newRotation; d_ptr->transformData->onlyTransform = false; d_ptr->dirtySceneTransform = 1; // Send post-notification. if (d_ptr->flags & ItemSendsGeometryChanges) itemChange(ItemRotationHasChanged, newRotation); if (d_ptr->isObject) emit static_cast<QGraphicsObject *>(this)->rotationChanged(); d_ptr->transformChanged(); } /*! \since 4.6 Returns the scale factor of the item. The default scale factor is 1.0 (i.e., the item is not scaled). The scale is combined with the item's rotation(), transform() and transformations() to map the item's coordinate system to the parent item. \sa setScale(), rotation(), {Transformations} */ qreal QGraphicsItem::scale() const { if (!d_ptr->transformData) return 1.; return d_ptr->transformData->scale; } /*! \since 4.6 Sets the scale \a factor of the item. The default scale factor is 1.0 (i.e., the item is not scaled). A scale factor of 0.0 will collapse the item to a single point. If you provide a negative scale factor, the item will be flipped and mirrored (i.e., rotated 180 degrees). The item is scaled around its transform origin point, which by default is (0, 0). You can select a different transformation origin by calling setTransformOriginPoint(). The scale is combined with the item's rotation(), transform() and transformations() to map the item's coordinate system to the parent item. \sa scale(), setTransformOriginPoint(), {Transformations Example} */ void QGraphicsItem::setScale(qreal factor) { prepareGeometryChange(); qreal newScale = factor; if (d_ptr->flags & ItemSendsGeometryChanges) { // Notify the item that the scale is changing. const QVariant newScaleVariant(itemChange(ItemScaleChange, factor)); newScale = newScaleVariant.toReal(); } if (!d_ptr->transformData) d_ptr->transformData = new QGraphicsItemPrivate::TransformData; if (d_ptr->transformData->scale == newScale) return; d_ptr->transformData->scale = newScale; d_ptr->transformData->onlyTransform = false; d_ptr->dirtySceneTransform = 1; // Send post-notification. if (d_ptr->flags & ItemSendsGeometryChanges) itemChange(ItemScaleHasChanged, newScale); if (d_ptr->isObject) emit static_cast<QGraphicsObject *>(this)->scaleChanged(); d_ptr->transformChanged(); } /*! \since 4.6 Returns a list of graphics transforms that currently apply to this item. QGraphicsTransform is for applying and controlling a chain of individual transformation operations on an item. It's particularly useful in animations, where each transform operation needs to be interpolated independently, or differently. The transformations are combined with the item's rotation(), scale() and transform() to map the item's coordinate system to the parent item. \sa scale(), rotation(), transformOriginPoint(), {Transformations} */ QList<QGraphicsTransform *> QGraphicsItem::transformations() const { if (!d_ptr->transformData) return QList<QGraphicsTransform *>(); return d_ptr->transformData->graphicsTransforms; } /*! \since 4.6 Sets a list of graphics \a transformations (QGraphicsTransform) that currently apply to this item. If all you want is to rotate or scale an item, you should call setRotation() or setScale() instead. If you want to set an arbitrary transformation on an item, you can call setTransform(). QGraphicsTransform is for applying and controlling a chain of individual transformation operations on an item. It's particularly useful in animations, where each transform operation needs to be interpolated independently, or differently. The transformations are combined with the item's rotation(), scale() and transform() to map the item's coordinate system to the parent item. \sa scale(), setTransformOriginPoint(), {Transformations} */ void QGraphicsItem::setTransformations(const QList<QGraphicsTransform *> &transformations) { prepareGeometryChange(); if (!d_ptr->transformData) d_ptr->transformData = new QGraphicsItemPrivate::TransformData; d_ptr->transformData->graphicsTransforms = transformations; for (int i = 0; i < transformations.size(); ++i) transformations.at(i)->d_func()->setItem(this); d_ptr->transformData->onlyTransform = false; d_ptr->dirtySceneTransform = 1; d_ptr->transformChanged(); } /*! \internal */ void QGraphicsItemPrivate::prependGraphicsTransform(QGraphicsTransform *t) { if (!transformData) transformData = new QGraphicsItemPrivate::TransformData; if (!transformData->graphicsTransforms.contains(t)) transformData->graphicsTransforms.prepend(t); Q_Q(QGraphicsItem); t->d_func()->setItem(q); transformData->onlyTransform = false; dirtySceneTransform = 1; transformChanged(); } /*! \internal */ void QGraphicsItemPrivate::appendGraphicsTransform(QGraphicsTransform *t) { if (!transformData) transformData = new QGraphicsItemPrivate::TransformData; if (!transformData->graphicsTransforms.contains(t)) transformData->graphicsTransforms.append(t); Q_Q(QGraphicsItem); t->d_func()->setItem(q); transformData->onlyTransform = false; dirtySceneTransform = 1; transformChanged(); } /*! \since 4.6 Returns the origin point for the transformation in item coordinates. The default is QPointF(0,0). \sa setTransformOriginPoint(), {Transformations} */ QPointF QGraphicsItem::transformOriginPoint() const { if (!d_ptr->transformData) return QPointF(0,0); return QPointF(d_ptr->transformData->xOrigin, d_ptr->transformData->yOrigin); } /*! \since 4.6 Sets the \a origin point for the transformation in item coordinates. \sa transformOriginPoint(), {Transformations} */ void QGraphicsItem::setTransformOriginPoint(const QPointF &origin) { prepareGeometryChange(); QPointF newOrigin = origin; if (d_ptr->flags & ItemSendsGeometryChanges) { // Notify the item that the origin point is changing. const QVariant newOriginVariant(itemChange(ItemTransformOriginPointChange, QVariant::fromValue<QPointF>(origin))); newOrigin = newOriginVariant.toPointF(); } if (!d_ptr->transformData) d_ptr->transformData = new QGraphicsItemPrivate::TransformData; if (d_ptr->transformData->xOrigin == newOrigin.x() && d_ptr->transformData->yOrigin == newOrigin.y()) { return; } d_ptr->transformData->xOrigin = newOrigin.x(); d_ptr->transformData->yOrigin = newOrigin.y(); d_ptr->transformData->onlyTransform = false; d_ptr->dirtySceneTransform = 1; // Send post-notification. if (d_ptr->flags & ItemSendsGeometryChanges) itemChange(ItemTransformOriginPointHasChanged, QVariant::fromValue<QPointF>(newOrigin)); } /*! \fn void QGraphicsItem::setTransformOriginPoint(qreal x, qreal y) \since 4.6 \overload Sets the origin point for the transformation in item coordinates. This is equivalent to calling setTransformOriginPoint(QPointF(\a x, \a y)). \sa setTransformOriginPoint(), {Transformations} */ /*! \obsolete Use sceneTransform() instead. \sa transform(), setTransform(), scenePos(), {The Graphics View Coordinate System} */ QMatrix QGraphicsItem::sceneMatrix() const { d_ptr->ensureSceneTransform(); return d_ptr->sceneTransform.toAffine(); } /*! \since 4.3 Returns this item's scene transformation matrix. This matrix can be used to map coordinates and geometrical shapes from this item's local coordinate system to the scene's coordinate system. To map coordinates from the scene, you must first invert the returned matrix. Example: \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 4 Unlike transform(), which returns only an item's local transformation, this function includes the item's (and any parents') position, and all the transfomation properties. \sa transform(), setTransform(), scenePos(), {The Graphics View Coordinate System}, {Transformations} */ QTransform QGraphicsItem::sceneTransform() const { d_ptr->ensureSceneTransform(); return d_ptr->sceneTransform; } /*! \since 4.3 Returns this item's device transformation matrix, using \a viewportTransform to map from scene to device coordinates. This matrix can be used to map coordinates and geometrical shapes from this item's local coordinate system to the viewport's (or any device's) coordinate system. To map coordinates from the viewport, you must first invert the returned matrix. Example: \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 5 This function is the same as combining this item's scene transform with the view's viewport transform, but it also understands the ItemIgnoresTransformations flag. The device transform can be used to do accurate coordinate mapping (and collision detection) for untransformable items. \sa transform(), setTransform(), scenePos(), {The Graphics View Coordinate System}, itemTransform() */ QTransform QGraphicsItem::deviceTransform(const QTransform &viewportTransform) const { // Ensure we return the standard transform if we're not untransformable. if (!d_ptr->itemIsUntransformable()) { d_ptr->ensureSceneTransform(); return d_ptr->sceneTransform * viewportTransform; } // Find the topmost item that ignores view transformations. const QGraphicsItem *untransformedAncestor = this; QList<const QGraphicsItem *> parents; while (untransformedAncestor && ((untransformedAncestor->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorIgnoresTransformations))) { parents.prepend(untransformedAncestor); untransformedAncestor = untransformedAncestor->parentItem(); } if (!untransformedAncestor) { // Assert in debug mode, continue in release. Q_ASSERT_X(untransformedAncestor, "QGraphicsItem::deviceTransform", "Invalid object structure!"); return QTransform(); } // First translate the base untransformable item. untransformedAncestor->d_ptr->ensureSceneTransform(); QPointF mappedPoint = (untransformedAncestor->d_ptr->sceneTransform * viewportTransform).map(QPointF(0, 0)); // COMBINE QTransform matrix = QTransform::fromTranslate(mappedPoint.x(), mappedPoint.y()); if (untransformedAncestor->d_ptr->transformData) matrix = untransformedAncestor->d_ptr->transformData->computedFullTransform(&matrix); // Then transform and translate all children. for (int i = 0; i < parents.size(); ++i) { const QGraphicsItem *parent = parents.at(i); parent->d_ptr->combineTransformFromParent(&matrix); } return matrix; } /*! \since 4.5 Returns a QTransform that maps coordinates from this item to \a other. If \a ok is not null, and if there is no such transform, the boolean pointed to by \a ok will be set to false; otherwise it will be set to true. This transform provides an alternative to the mapToItem() or mapFromItem() functions, by returning the appropriate transform so that you can map shapes and coordinates yourself. It also helps you write more efficient code when repeatedly mapping between the same two items. \note In rare circumstances, there is no transform that maps between two items. \sa mapToItem(), mapFromItem(), deviceTransform() */ QTransform QGraphicsItem::itemTransform(const QGraphicsItem *other, bool *ok) const { // Catch simple cases first. if (other == 0) { qWarning("QGraphicsItem::itemTransform: null pointer passed"); return QTransform(); } if (other == this) { if (ok) *ok = true; return QTransform(); } QGraphicsItem *parent = d_ptr->parent; const QGraphicsItem *otherParent = other->d_ptr->parent; // This is other's child if (parent == other) { if (ok) *ok = true; QTransform x; d_ptr->combineTransformFromParent(&x); return x; } // This is other's parent if (otherParent == this) { const QPointF &otherPos = other->d_ptr->pos; if (other->d_ptr->transformData) { QTransform otherToParent; other->d_ptr->combineTransformFromParent(&otherToParent); return otherToParent.inverted(ok); } if (ok) *ok = true; return QTransform::fromTranslate(-otherPos.x(), -otherPos.y()); } // Siblings if (parent == otherParent) { // COMBINE const QPointF &itemPos = d_ptr->pos; const QPointF &otherPos = other->d_ptr->pos; if (!d_ptr->transformData && !other->d_ptr->transformData) { QPointF delta = itemPos - otherPos; if (ok) *ok = true; return QTransform::fromTranslate(delta.x(), delta.y()); } QTransform itemToParent; d_ptr->combineTransformFromParent(&itemToParent); QTransform otherToParent; other->d_ptr->combineTransformFromParent(&otherToParent); return itemToParent * otherToParent.inverted(ok); } // Find the closest common ancestor. If the two items don't share an // ancestor, then the only way is to combine their scene transforms. const QGraphicsItem *commonAncestor = commonAncestorItem(other); if (!commonAncestor) { d_ptr->ensureSceneTransform(); other->d_ptr->ensureSceneTransform(); return d_ptr->sceneTransform * other->d_ptr->sceneTransform.inverted(ok); } // If the two items are cousins (in sibling branches), map both to the // common ancestor, and combine the two transforms. bool cousins = other != commonAncestor && this != commonAncestor; if (cousins) { bool good = false; QTransform thisToScene = itemTransform(commonAncestor, &good); QTransform otherToScene(Qt::Uninitialized); if (good) otherToScene = other->itemTransform(commonAncestor, &good); if (!good) { if (ok) *ok = false; return QTransform(); } return thisToScene * otherToScene.inverted(ok); } // One is an ancestor of the other; walk the chain. bool parentOfOther = isAncestorOf(other); const QGraphicsItem *child = parentOfOther ? other : this; const QGraphicsItem *root = parentOfOther ? this : other; QTransform x; const QGraphicsItem *p = child; do { p->d_ptr.data()->combineTransformToParent(&x); } while ((p = p->d_ptr->parent) && p != root); if (parentOfOther) return x.inverted(ok); if (ok) *ok = true; return x; } /*! \obsolete Sets the item's affine transformation matrix. This is a subset or the item's full transformation matrix, and might not represent the item's full transformation. Use setTransform() instead. \sa transform(), {The Graphics View Coordinate System} */ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) { if (!d_ptr->transformData) d_ptr->transformData = new QGraphicsItemPrivate::TransformData; QTransform newTransform(combine ? QTransform(matrix) * d_ptr->transformData->transform : QTransform(matrix)); if (d_ptr->transformData->transform == newTransform) return; // Update and set the new transformation. if (!(d_ptr->flags & ItemSendsGeometryChanges)) { d_ptr->setTransformHelper(newTransform); return; } // Notify the item that the transformation matrix is changing. const QVariant newMatrixVariant = QVariant::fromValue<QMatrix>(newTransform.toAffine()); newTransform = QTransform(qvariant_cast<QMatrix>(itemChange(ItemMatrixChange, newMatrixVariant))); if (d_ptr->transformData->transform == newTransform) return; // Update and set the new transformation. d_ptr->setTransformHelper(newTransform); // Send post-notification. itemChange(ItemTransformHasChanged, QVariant::fromValue<QTransform>(newTransform)); } /*! \since 4.3 Sets the item's current transformation matrix to \a matrix. If \a combine is true, then \a matrix is combined with the current matrix; otherwise, \a matrix \e replaces the current matrix. \a combine is false by default. To simplify interation with items using a transformed view, QGraphicsItem provides mapTo... and mapFrom... functions that can translate between items' and the scene's coordinates. For example, you can call mapToScene() to map an item coordiate to a scene coordinate, or mapFromScene() to map from scene coordinates to item coordinates. The transformation matrix is combined with the item's rotation(), scale() and transformations() into a combined transformation that maps the item's coordinate system to its parent. \sa transform(), setRotation(), setScale(), setTransformOriginPoint(), {The Graphics View Coordinate System}, {Transformations} */ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) { if (!d_ptr->transformData) d_ptr->transformData = new QGraphicsItemPrivate::TransformData; QTransform newTransform(combine ? matrix * d_ptr->transformData->transform : matrix); if (d_ptr->transformData->transform == newTransform) return; // Update and set the new transformation. if (!(d_ptr->flags & (ItemSendsGeometryChanges | ItemSendsScenePositionChanges))) { d_ptr->setTransformHelper(newTransform); if (d_ptr->scenePosDescendants) d_ptr->sendScenePosChange(); return; } // Notify the item that the transformation matrix is changing. const QVariant newTransformVariant(itemChange(ItemTransformChange, QVariant::fromValue<QTransform>(newTransform))); newTransform = qvariant_cast<QTransform>(newTransformVariant); if (d_ptr->transformData->transform == newTransform) return; // Update and set the new transformation. d_ptr->setTransformHelper(newTransform); // Send post-notification. itemChange(ItemTransformHasChanged, newTransformVariant); d_ptr->sendScenePosChange(); } /*! \obsolete Use resetTransform() instead. */ void QGraphicsItem::resetMatrix() { resetTransform(); } /*! \since 4.3 Resets this item's transformation matrix to the identity matrix or all the transformation properties to their default values. This is equivalent to calling \c setTransform(QTransform()). \sa setTransform(), transform() */ void QGraphicsItem::resetTransform() { setTransform(QTransform(), false); } /*! \obsolete Use \code setRotation(rotation() + angle); \endcode instead. Rotates the current item transformation \a angle degrees clockwise around its origin. To translate around an arbitrary point (x, y), you need to combine translation and rotation with setTransform(). Example: \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 6 \sa setTransform(), transform(), scale(), shear(), translate() */ void QGraphicsItem::rotate(qreal angle) { setTransform(QTransform().rotate(angle), true); } /*! \obsolete Use \code setTransform(QTransform::fromScale(sx, sy), true); \endcode instead. Scales the current item transformation by (\a sx, \a sy) around its origin. To scale from an arbitrary point (x, y), you need to combine translation and scaling with setTransform(). Example: \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 7 \sa setTransform(), transform() */ void QGraphicsItem::scale(qreal sx, qreal sy) { setTransform(QTransform::fromScale(sx, sy), true); } /*! \obsolete Use \code setTransform(QTransform().shear(sh, sv), true); \endcode instead. Shears the current item transformation by (\a sh, \a sv). \sa setTransform(), transform() */ void QGraphicsItem::shear(qreal sh, qreal sv) { setTransform(QTransform().shear(sh, sv), true); } /*! \obsolete Use setPos() or setTransformOriginPoint() instead. For identical behavior, use \code setTransform(QTransform::fromTranslate(dx, dy), true); \endcode Translates the current item transformation by (\a dx, \a dy). If all you want is to move an item, you should call moveBy() or setPos() instead; this function changes the item's translation, which is conceptually separate from its position. \sa setTransform(), transform() */ void QGraphicsItem::translate(qreal dx, qreal dy) { setTransform(QTransform::fromTranslate(dx, dy), true); } /*! This virtual function is called twice for all items by the QGraphicsScene::advance() slot. In the first phase, all items are called with \a phase == 0, indicating that items on the scene are about to advance, and then all items are called with \a phase == 1. Reimplement this function to update your item if you need simple scene-controlled animation. The default implementation does nothing. For individual item animation, an alternative to this function is to either use QGraphicsItemAnimation, or to multiple-inherit from QObject and QGraphicsItem, and animate your item using QObject::startTimer() and QObject::timerEvent(). \sa QGraphicsItemAnimation, QTimeLine */ void QGraphicsItem::advance(int phase) { Q_UNUSED(phase); } /*! Returns the Z-value of the item. The Z-value affects the stacking order of sibling (neighboring) items. The default Z-value is 0. \sa setZValue(), {QGraphicsItem#Sorting}{Sorting}, stackBefore(), ItemStacksBehindParent */ qreal QGraphicsItem::zValue() const { return d_ptr->z; } /*! Sets the Z-value of the item to \a z. The Z value decides the stacking order of sibling (neighboring) items. A sibling item of high Z value will always be drawn on top of another sibling item with a lower Z value. If you restore the Z value, the item's insertion order will decide its stacking order. The Z-value does not affect the item's size in any way. The default Z-value is 0. \sa zValue(), {QGraphicsItem#Sorting}{Sorting}, stackBefore(), ItemStacksBehindParent */ void QGraphicsItem::setZValue(qreal z) { const QVariant newZVariant(itemChange(ItemZValueChange, z)); qreal newZ = newZVariant.toReal(); if (newZ == d_ptr->z) return; if (d_ptr->scene && d_ptr->scene->d_func()->indexMethod != QGraphicsScene::NoIndex) { // Z Value has changed, we have to notify the index. d_ptr->scene->d_func()->index->itemChange(this, ItemZValueChange, &newZ); } d_ptr->z = newZ; if (d_ptr->parent) d_ptr->parent->d_ptr->needSortChildren = 1; else if (d_ptr->scene) d_ptr->scene->d_func()->needSortTopLevelItems = 1; if (d_ptr->scene) d_ptr->scene->d_func()->markDirty(this, QRectF(), /*invalidateChildren=*/true); itemChange(ItemZValueHasChanged, newZVariant); if (d_ptr->flags & ItemNegativeZStacksBehindParent) setFlag(QGraphicsItem::ItemStacksBehindParent, z < qreal(0.0)); if (d_ptr->isObject) emit static_cast<QGraphicsObject *>(this)->zChanged(); } /*! \internal Ensures that the list of children is sorted by insertion order, and that the siblingIndexes are packed (no gaps), and start at 0. ### This function is almost identical to QGraphicsScenePrivate::ensureSequentialTopLevelSiblingIndexes(). */ void QGraphicsItemPrivate::ensureSequentialSiblingIndex() { if (!sequentialOrdering) { qSort(children.begin(), children.end(), insertionOrder); sequentialOrdering = 1; needSortChildren = 1; } if (holesInSiblingIndex) { holesInSiblingIndex = 0; for (int i = 0; i < children.size(); ++i) children[i]->d_ptr->siblingIndex = i; } } /*! \internal */ inline void QGraphicsItemPrivate::sendScenePosChange() { Q_Q(QGraphicsItem); if (scene) { if (flags & QGraphicsItem::ItemSendsScenePositionChanges) q->itemChange(QGraphicsItem::ItemScenePositionHasChanged, q->scenePos()); if (scenePosDescendants) { foreach (QGraphicsItem *item, scene->d_func()->scenePosItems) { if (q->isAncestorOf(item)) item->itemChange(QGraphicsItem::ItemScenePositionHasChanged, item->scenePos()); } } } } /*! \since 4.6 Stacks this item before \a sibling, which must be a sibling item (i.e., the two items must share the same parent item, or must both be toplevel items). The \a sibling must have the same Z value as this item, otherwise calling this function will have no effect. By default, all sibling items are stacked by insertion order (i.e., the first item you add is drawn before the next item you add). If two items' Z values are different, then the item with the highest Z value is drawn on top. When the Z values are the same, the insertion order will decide the stacking order. \sa setZValue(), ItemStacksBehindParent, {QGraphicsItem#Sorting}{Sorting} */ void QGraphicsItem::stackBefore(const QGraphicsItem *sibling) { if (sibling == this) return; if (!sibling || d_ptr->parent != sibling->parentItem()) { qWarning("QGraphicsItem::stackUnder: cannot stack under %p, which must be a sibling", sibling); return; } QList<QGraphicsItem *> *siblings = d_ptr->parent ? &d_ptr->parent->d_ptr->children : (d_ptr->scene ? &d_ptr->scene->d_func()->topLevelItems : 0); if (!siblings) { qWarning("QGraphicsItem::stackUnder: cannot stack under %p, which must be a sibling", sibling); return; } // First, make sure that the sibling indexes have no holes. This also // marks the children list for sorting. if (d_ptr->parent) d_ptr->parent->d_ptr->ensureSequentialSiblingIndex(); else d_ptr->scene->d_func()->ensureSequentialTopLevelSiblingIndexes(); // Only move items with the same Z value, and that need moving. int siblingIndex = sibling->d_ptr->siblingIndex; int myIndex = d_ptr->siblingIndex; if (myIndex >= siblingIndex) { siblings->move(myIndex, siblingIndex); // Fixup the insertion ordering. for (int i = 0; i < siblings->size(); ++i) { int &index = siblings->at(i)->d_ptr->siblingIndex; if (i != siblingIndex && index >= siblingIndex && index <= myIndex) ++index; } d_ptr->siblingIndex = siblingIndex; for (int i = 0; i < siblings->size(); ++i) { int &index = siblings->at(i)->d_ptr->siblingIndex; if (i != siblingIndex && index >= siblingIndex && index <= myIndex) siblings->at(i)->d_ptr->siblingOrderChange(); } d_ptr->siblingOrderChange(); } } /*! Returns the bounding rect of this item's descendants (i.e., its children, their children, etc.) in local coordinates. The rectangle will contain all descendants after they have been mapped to local coordinates. If the item has no children, this function returns an empty QRectF. This does not include this item's own bounding rect; it only returns its descendants' accumulated bounding rect. If you need to include this item's bounding rect, you can add boundingRect() to childrenBoundingRect() using QRectF::operator|(). This function is linear in complexity; it determines the size of the returned bounding rect by iterating through all descendants. \sa boundingRect(), sceneBoundingRect() */ QRectF QGraphicsItem::childrenBoundingRect() const { if (!d_ptr->dirtyChildrenBoundingRect) return d_ptr->childrenBoundingRect; d_ptr->childrenBoundingRect = QRectF(); d_ptr->childrenBoundingRectHelper(0, &d_ptr->childrenBoundingRect, 0); d_ptr->dirtyChildrenBoundingRect = 0; return d_ptr->childrenBoundingRect; } /*! \fn virtual QRectF QGraphicsItem::boundingRect() const = 0 This pure virtual function defines the outer bounds of the item as a rectangle; all painting must be restricted to inside an item's bounding rect. QGraphicsView uses this to determine whether the item requires redrawing. Although the item's shape can be arbitrary, the bounding rect is always rectangular, and it is unaffected by the items' transformation. If you want to change the item's bounding rectangle, you must first call prepareGeometryChange(). This notifies the scene of the imminent change, so that its can update its item geometry index; otherwise, the scene will be unaware of the item's new geometry, and the results are undefined (typically, rendering artifacts are left around in the view). Reimplement this function to let QGraphicsView determine what parts of the widget, if any, need to be redrawn. Note: For shapes that paint an outline / stroke, it is important to include half the pen width in the bounding rect. It is not necessary to compensate for antialiasing, though. Example: \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 8 \sa boundingRegion(), shape(), contains(), {The Graphics View Coordinate System}, prepareGeometryChange() */ /*! Returns the bounding rect of this item in scene coordinates, by combining sceneTransform() with boundingRect(). \sa boundingRect(), {The Graphics View Coordinate System} */ QRectF QGraphicsItem::sceneBoundingRect() const { // Find translate-only offset // COMBINE QPointF offset; const QGraphicsItem *parentItem = this; const QGraphicsItemPrivate *itemd; do { itemd = parentItem->d_ptr.data(); if (itemd->transformData) break; offset += itemd->pos; } while ((parentItem = itemd->parent)); QRectF br = boundingRect(); br.translate(offset); if (!parentItem) return br; if (parentItem->d_ptr->hasTranslateOnlySceneTransform()) { br.translate(parentItem->d_ptr->sceneTransform.dx(), parentItem->d_ptr->sceneTransform.dy()); return br; } return parentItem->d_ptr->sceneTransform.mapRect(br); } /*! Returns the shape of this item as a QPainterPath in local coordinates. The shape is used for many things, including collision detection, hit tests, and for the QGraphicsScene::items() functions. The default implementation calls boundingRect() to return a simple rectangular shape, but subclasses can reimplement this function to return a more accurate shape for non-rectangular items. For example, a round item may choose to return an elliptic shape for better collision detection. For example: \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 9 The outline of a shape can vary depending on the width and style of the pen used when drawing. If you want to include this outline in the item's shape, you can create a shape from the stroke using QPainterPathStroker. This function is called by the default implementations of contains() and collidesWithPath(). \sa boundingRect(), contains(), prepareGeometryChange(), QPainterPathStroker */ QPainterPath QGraphicsItem::shape() const { QPainterPath path; path.addRect(boundingRect()); return path; } /*! Returns true if this item is clipped. An item is clipped if it has either set the \l ItemClipsToShape flag, or if it or any of its ancestors has set the \l ItemClipsChildrenToShape flag. Clipping affects the item's appearance (i.e., painting), as well as mouse and hover event delivery. \sa clipPath(), shape(), setFlags() */ bool QGraphicsItem::isClipped() const { Q_D(const QGraphicsItem); return (d->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren) || (d->flags & QGraphicsItem::ItemClipsToShape); } /*! \since 4.5 Returns this item's clip path, or an empty QPainterPath if this item is not clipped. The clip path constrains the item's appearance and interaction (i.e., restricts the area the item can draw, and it also restricts the area that the item receives events). You can enable clipping by setting the ItemClipsToShape or ItemClipsChildrenToShape flags. The item's clip path is calculated by intersecting all clipping ancestors' shapes. If the item sets ItemClipsToShape, the final clip is intersected with the item's own shape. \note Clipping introduces a performance penalty for all items involved; you should generally avoid using clipping if you can (e.g., if your items always draw inside boundingRect() or shape() boundaries, clipping is not necessary). \sa isClipped(), shape(), setFlags() */ QPainterPath QGraphicsItem::clipPath() const { Q_D(const QGraphicsItem); if (!isClipped()) return QPainterPath(); const QRectF thisBoundingRect(boundingRect()); if (thisBoundingRect.isEmpty()) return QPainterPath(); QPainterPath clip; // Start with the item's bounding rect. clip.addRect(thisBoundingRect); if (d->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren) { const QGraphicsItem *parent = this; const QGraphicsItem *lastParent = this; // Intersect any in-between clips starting at the top and moving downwards. while ((parent = parent->d_ptr->parent)) { if (parent->d_ptr->flags & ItemClipsChildrenToShape) { // Map clip to the current parent and intersect with its shape/clipPath clip = lastParent->itemTransform(parent).map(clip); clip = clip.intersected(parent->shape()); if (clip.isEmpty()) return clip; lastParent = parent; } if (!(parent->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)) break; } if (lastParent != this) { // Map clip back to the item's transform. // ### what if itemtransform fails clip = lastParent->itemTransform(this).map(clip); } } if (d->flags & ItemClipsToShape) clip = clip.intersected(shape()); return clip; } /*! Returns true if this item contains \a point, which is in local coordinates; otherwise, false is returned. It is most often called from QGraphicsView to determine what item is under the cursor, and for that reason, the implementation of this function should be as light-weight as possible. By default, this function calls shape(), but you can reimplement it in a subclass to provide a (perhaps more efficient) implementation. \sa shape(), boundingRect(), collidesWithPath() */ bool QGraphicsItem::contains(const QPointF &point) const { return isClipped() ? clipPath().contains(point) : shape().contains(point); } /*! Returns true if this item collides with \a other; otherwise returns false. The \a mode is applied to \a other, and the resulting shape or bounding rectangle is then compared to this item's shape. The default value for \a mode is Qt::IntersectsItemShape; \a other collides with this item if it either intersects, contains, or is contained by this item's shape (see Qt::ItemSelectionMode for details). The default implementation is based on shape intersection, and it calls shape() on both items. Because the complexity of arbitrary shape-shape intersection grows with an order of magnitude when the shapes are complex, this operation can be noticably time consuming. You have the option of reimplementing this function in a subclass of QGraphicsItem to provide a custom algorithm. This allows you to make use of natural constraints in the shapes of your own items, in order to improve the performance of the collision detection. For instance, two untransformed perfectly circular items' collision can be determined very efficiently by comparing their positions and radii. Keep in mind that when reimplementing this function and calling shape() or boundingRect() on \a other, the returned coordinates must be mapped to this item's coordinate system before any intersection can take place. \sa contains(), shape() */ bool QGraphicsItem::collidesWithItem(const QGraphicsItem *other, Qt::ItemSelectionMode mode) const { if (other == this) return true; if (!other) return false; // The items share the same clip if their closest clipper is the same, or // if one clips the other. bool clips = (d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren); bool otherClips = (other->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren); if (clips || otherClips) { const QGraphicsItem *closestClipper = isAncestorOf(other) ? this : parentItem(); while (closestClipper && !(closestClipper->flags() & ItemClipsChildrenToShape)) closestClipper = closestClipper->parentItem(); const QGraphicsItem *otherClosestClipper = other->isAncestorOf(this) ? other : other->parentItem(); while (otherClosestClipper && !(otherClosestClipper->flags() & ItemClipsChildrenToShape)) otherClosestClipper = otherClosestClipper->parentItem(); if (closestClipper == otherClosestClipper) { d_ptr->localCollisionHack = 1; bool res = collidesWithPath(mapFromItem(other, other->shape()), mode); d_ptr->localCollisionHack = 0; return res; } } QPainterPath otherShape = other->isClipped() ? other->clipPath() : other->shape(); return collidesWithPath(mapFromItem(other, otherShape), mode); } /*! Returns true if this item collides with \a path. The collision is determined by \a mode. The default value for \a mode is Qt::IntersectsItemShape; \a path collides with this item if it either intersects, contains, or is contained by this item's shape. Note that this function checks whether the item's shape or bounding rectangle (depending on \a mode) is contained within \a path, and not whether \a path is contained within the items shape or bounding rectangle. \sa collidesWithItem(), contains(), shape() */ bool QGraphicsItem::collidesWithPath(const QPainterPath &path, Qt::ItemSelectionMode mode) const { if (path.isEmpty()) { // No collision with empty paths. return false; } QRectF rectA(boundingRect()); _q_adjustRect(&rectA); QRectF rectB(path.controlPointRect()); _q_adjustRect(&rectB); if (!rectA.intersects(rectB)) { // This we can determine efficiently. If the two rects neither // intersect nor contain eachother, then the two items do not collide. return false; } // For further testing, we need this item's shape or bounding rect. QPainterPath thisShape; if (mode == Qt::IntersectsItemShape || mode == Qt::ContainsItemShape) thisShape = (isClipped() && !d_ptr->localCollisionHack) ? clipPath() : shape(); else thisShape.addRect(rectA); if (thisShape == QPainterPath()) { // Empty shape? No collision. return false; } // Use QPainterPath boolean operations to determine the collision, O(N*logN). if (mode == Qt::IntersectsItemShape || mode == Qt::IntersectsItemBoundingRect) return path.intersects(thisShape); return path.contains(thisShape); } /*! Returns a list of all items that collide with this item. The way collisions are detected is determined by applying \a mode to items that are compared to this item, i.e., each item's shape or bounding rectangle is checked against this item's shape. The default value for \a mode is Qt::IntersectsItemShape. \sa collidesWithItem() */ QList<QGraphicsItem *> QGraphicsItem::collidingItems(Qt::ItemSelectionMode mode) const { if (d_ptr->scene) return d_ptr->scene->collidingItems(this, mode); return QList<QGraphicsItem *>(); } /*! Returns true if this item's bounding rect is completely obscured by the opaque shape of any of colliding items above it (i.e., with a higher Z value than this item). Its implementation is based on calling isObscuredBy(), which you can reimplement to provide a custom obscurity algorithm. \sa opaqueArea() */ bool QGraphicsItem::isObscured() const { return isObscured(QRectF()); } /*! \internal Item obscurity helper function. Returns true if the subrect \a rect of \a item's bounding rect is obscured by \a other (i.e., \a other's opaque area covers \a item's \a rect completely. \a other is assumed to already be "on top of" \a item wrt. stacking order. */ static bool qt_QGraphicsItem_isObscured(const QGraphicsItem *item, const QGraphicsItem *other, const QRectF &rect) { return other->mapToItem(item, other->opaqueArea()).contains(rect); } /*! \overload \since 4.3 Returns true if \a rect is completely obscured by the opaque shape of any of colliding items above it (i.e., with a higher Z value than this item). Unlike the default isObscured() function, this function does not call isObscuredBy(). \sa opaqueArea() */ bool QGraphicsItem::isObscured(const QRectF &rect) const { Q_D(const QGraphicsItem); if (!d->scene) return false; QRectF br = boundingRect(); QRectF testRect = rect.isNull() ? br : rect; foreach (QGraphicsItem *item, d->scene->items(mapToScene(br), Qt::IntersectsItemBoundingRect)) { if (item == this) break; if (qt_QGraphicsItem_isObscured(this, item, testRect)) return true; } return false; } /*! \fn bool QGraphicsItem::isObscured(qreal x, qreal y, qreal w, qreal h) const \since 4.3 This convenience function is equivalent to calling isObscured(QRectF(\a x, \a y, \a w, \a h)). */ /*! Returns true if this item's bounding rect is completely obscured by the opaque shape of \a item. The base implementation maps \a item's opaqueArea() to this item's coordinate system, and then checks if this item's boundingRect() is fully contained within the mapped shape. You can reimplement this function to provide a custom algorithm for determining whether this item is obscured by \a item. \sa opaqueArea(), isObscured() */ bool QGraphicsItem::isObscuredBy(const QGraphicsItem *item) const { if (!item) return false; return qt_closestItemFirst(item, this) && qt_QGraphicsItem_isObscured(this, item, boundingRect()); } /*! This virtual function returns a shape representing the area where this item is opaque. An area is opaque if it is filled using an opaque brush or color (i.e., not transparent). This function is used by isObscuredBy(), which is called by underlying items to determine if they are obscured by this item. The default implementation returns an empty QPainterPath, indicating that this item is completely transparent and does not obscure any other items. \sa isObscuredBy(), isObscured(), shape() */ QPainterPath QGraphicsItem::opaqueArea() const { return QPainterPath(); } /*! \since 4.4 Returns the bounding region for this item. The coordinate space of the returned region depends on \a itemToDeviceTransform. If you pass an identity QTransform as a parameter, this function will return a local coordinate region. The bounding region describes a coarse outline of the item's visual contents. Although it's expensive to calculate, it's also more precise than boundingRect(), and it can help to avoid unnecessary repainting when an item is updated. This is particularly efficient for thin items (e.g., lines or simple polygons). You can tune the granularity for the bounding region by calling setBoundingRegionGranularity(). The default granularity is 0; in which the item's bounding region is the same as its bounding rect. \a itemToDeviceTransform is the transformation from item coordinates to device coordinates. If you want this function to return a QRegion in scene coordinates, you can pass sceneTransform() as an argument. \sa boundingRegionGranularity() */ QRegion QGraphicsItem::boundingRegion(const QTransform &itemToDeviceTransform) const { // ### Ideally we would have a better way to generate this region, // preferably something in the lines of QPainterPath::toRegion(QTransform) // coupled with a way to generate a painter path from a set of painter // operations (e.g., QPicture::toPainterPath() or so). The current // approach generates a bitmap with the size of the item's bounding rect // in device coordinates, scaled by b.r.granularity, then paints the item // into the bitmap, converts the result to a QRegion and scales the region // back to device space with inverse granularity. qreal granularity = boundingRegionGranularity(); QRect deviceRect = itemToDeviceTransform.mapRect(boundingRect()).toRect(); _q_adjustRect(&deviceRect); if (granularity == 0.0) return QRegion(deviceRect); int pad = 1; QSize bitmapSize(qMax(1, int(deviceRect.width() * granularity) + pad * 2), qMax(1, int(deviceRect.height() * granularity) + pad * 2)); QImage mask(bitmapSize, QImage::Format_ARGB32_Premultiplied); mask.fill(0); QPainter p(&mask); p.setRenderHints(QPainter::Antialiasing); // Transform painter (### this code is from QGraphicsScene::drawItemHelper // and doesn't work properly with perspective transformations). QPointF viewOrigo = itemToDeviceTransform.map(QPointF(0, 0)); QPointF offset = viewOrigo - deviceRect.topLeft(); p.scale(granularity, granularity); p.translate(offset); p.translate(pad, pad); p.setWorldTransform(itemToDeviceTransform, true); p.translate(itemToDeviceTransform.inverted().map(QPointF(0, 0))); // Render QStyleOptionGraphicsItem option; const_cast<QGraphicsItem *>(this)->paint(&p, &option, 0); p.end(); // Transform QRegion back to device space QTransform unscale = QTransform::fromScale(1 / granularity, 1 / granularity); QRegion r; QBitmap colorMask = QBitmap::fromImage(mask.createMaskFromColor(0)); foreach (const QRect &rect, QRegion( colorMask ).rects()) { QRect xrect = unscale.mapRect(rect).translated(deviceRect.topLeft() - QPoint(pad, pad)); r += xrect.adjusted(-1, -1, 1, 1) & deviceRect; } return r; } /*! \since 4.4 Returns the item's bounding region granularity; a value between and including 0 and 1. The default value is 0 (i.e., the lowest granularity, where the bounding region corresponds to the item's bounding rectangle). \omit ### NOTE \endomit \sa setBoundingRegionGranularity() */ qreal QGraphicsItem::boundingRegionGranularity() const { return d_ptr->hasBoundingRegionGranularity ? qvariant_cast<qreal>(d_ptr->extra(QGraphicsItemPrivate::ExtraBoundingRegionGranularity)) : 0; } /*! \since 4.4 Sets the bounding region granularity to \a granularity; a value between and including 0 and 1. The default value is 0 (i.e., the lowest granularity, where the bounding region corresponds to the item's bounding rectangle). The granularity is used by boundingRegion() to calculate how fine the bounding region of the item should be. The highest achievable granularity is 1, where boundingRegion() will return the finest outline possible for the respective device (e.g., for a QGraphicsView viewport, this gives you a pixel-perfect bounding region). The lowest possible granularity is 0. The value of \a granularity describes the ratio between device resolution and the resolution of the bounding region (e.g., a value of 0.25 will provide a region where each chunk corresponds to 4x4 device units / pixels). \sa boundingRegionGranularity() */ void QGraphicsItem::setBoundingRegionGranularity(qreal granularity) { if (granularity < 0.0 || granularity > 1.0) { qWarning("QGraphicsItem::setBoundingRegionGranularity: invalid granularity %g", granularity); return; } if (granularity == 0.0) { d_ptr->unsetExtra(QGraphicsItemPrivate::ExtraBoundingRegionGranularity); d_ptr->hasBoundingRegionGranularity = 0; return; } d_ptr->hasBoundingRegionGranularity = 1; d_ptr->setExtra(QGraphicsItemPrivate::ExtraBoundingRegionGranularity, QVariant::fromValue<qreal>(granularity)); } /*! \fn virtual void QGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0) = 0 This function, which is usually called by QGraphicsView, paints the contents of an item in local coordinates. Reimplement this function in a QGraphicsItem subclass to provide the item's painting implementation, using \a painter. The \a option parameter provides style options for the item, such as its state, exposed area and its level-of-detail hints. The \a widget argument is optional. If provided, it points to the widget that is being painted on; otherwise, it is 0. For cached painting, \a widget is always 0. \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 10 The painter's pen is 0-width by default, and its pen is initialized to the QPalette::Text brush from the paint device's palette. The brush is initialized to QPalette::Window. Make sure to constrain all painting inside the boundaries of boundingRect() to avoid rendering artifacts (as QGraphicsView does not clip the painter for you). In particular, when QPainter renders the outline of a shape using an assigned QPen, half of the outline will be drawn outside, and half inside, the shape you're rendering (e.g., with a pen width of 2 units, you must draw outlines 1 unit inside boundingRect()). QGraphicsItem does not support use of cosmetic pens with a non-zero width. All painting is done in local coordinates. \sa setCacheMode(), QPen::width(), {Item Coordinates}, ItemUsesExtendedStyleOption */ /*! \internal Returns true if we can discard an update request; otherwise false. */ bool QGraphicsItemPrivate::discardUpdateRequest(bool ignoreVisibleBit, bool ignoreDirtyBit, bool ignoreOpacity) const { // No scene, or if the scene is updating everything, means we have nothing // to do. The only exception is if the scene tracks the growing scene rect. return !scene || (!visible && !ignoreVisibleBit && !this->ignoreVisible) || (!ignoreDirtyBit && fullUpdatePending) || (!ignoreOpacity && !this->ignoreOpacity && childrenCombineOpacity() && isFullyTransparent()); } /*! \internal */ int QGraphicsItemPrivate::depth() const { if (itemDepth == -1) const_cast<QGraphicsItemPrivate *>(this)->resolveDepth(); return itemDepth; } /*! \internal */ #ifndef QT_NO_GRAPHICSEFFECT void QGraphicsItemPrivate::invalidateParentGraphicsEffectsRecursively() { QGraphicsItemPrivate *itemPrivate = this; do { if (itemPrivate->graphicsEffect && !itemPrivate->updateDueToGraphicsEffect) { itemPrivate->notifyInvalidated = 1; static_cast<QGraphicsItemEffectSourcePrivate *>(itemPrivate->graphicsEffect->d_func()->source->d_func())->invalidateCache(); } } while ((itemPrivate = itemPrivate->parent ? itemPrivate->parent->d_ptr.data() : 0)); } void QGraphicsItemPrivate::invalidateChildGraphicsEffectsRecursively(QGraphicsItemPrivate::InvalidateReason reason) { if (!mayHaveChildWithGraphicsEffect) return; for (int i = 0; i < children.size(); ++i) { QGraphicsItemPrivate *childPrivate = children.at(i)->d_ptr.data(); if (reason == OpacityChanged && (childPrivate->flags & QGraphicsItem::ItemIgnoresParentOpacity)) continue; if (childPrivate->graphicsEffect) { childPrivate->notifyInvalidated = 1; static_cast<QGraphicsItemEffectSourcePrivate *>(childPrivate->graphicsEffect->d_func()->source->d_func())->invalidateCache(); } childPrivate->invalidateChildGraphicsEffectsRecursively(reason); } } #endif //QT_NO_GRAPHICSEFFECT /*! \internal */ void QGraphicsItemPrivate::invalidateDepthRecursively() { if (itemDepth == -1) return; itemDepth = -1; for (int i = 0; i < children.size(); ++i) children.at(i)->d_ptr->invalidateDepthRecursively(); } /*! \internal Resolves the stacking depth of this object and all its ancestors. */ void QGraphicsItemPrivate::resolveDepth() { if (!parent) itemDepth = 0; else { if (parent->d_ptr->itemDepth == -1) parent->d_ptr->resolveDepth(); itemDepth = parent->d_ptr->itemDepth + 1; } } /*! \internal ### This function is almost identical to QGraphicsScenePrivate::registerTopLevelItem(). */ void QGraphicsItemPrivate::addChild(QGraphicsItem *child) { // Remove all holes from the sibling index list. Now the max index // number is equal to the size of the children list. ensureSequentialSiblingIndex(); needSortChildren = 1; // ### maybe 0 child->d_ptr->siblingIndex = children.size(); children.append(child); if (isObject) emit static_cast<QGraphicsObject *>(q_ptr)->childrenChanged(); } /*! \internal ### This function is almost identical to QGraphicsScenePrivate::unregisterTopLevelItem(). */ void QGraphicsItemPrivate::removeChild(QGraphicsItem *child) { // When removing elements in the middle of the children list, // there will be a "gap" in the list of sibling indexes (0,1,3,4). if (!holesInSiblingIndex) holesInSiblingIndex = child->d_ptr->siblingIndex != children.size() - 1; if (sequentialOrdering && !holesInSiblingIndex) children.removeAt(child->d_ptr->siblingIndex); else children.removeOne(child); // NB! Do not use children.removeAt(child->d_ptr->siblingIndex) because // the child is not guaranteed to be at the index after the list is sorted. // (see ensureSortedChildren()). child->d_ptr->siblingIndex = -1; if (isObject) emit static_cast<QGraphicsObject *>(q_ptr)->childrenChanged(); } /*! \internal */ QGraphicsItemCache *QGraphicsItemPrivate::maybeExtraItemCache() const { return (QGraphicsItemCache *)qvariant_cast<void *>(extra(ExtraCacheData)); } /*! \internal */ QGraphicsItemCache *QGraphicsItemPrivate::extraItemCache() const { QGraphicsItemCache *c = (QGraphicsItemCache *)qvariant_cast<void *>(extra(ExtraCacheData)); if (!c) { QGraphicsItemPrivate *that = const_cast<QGraphicsItemPrivate *>(this); c = new QGraphicsItemCache; that->setExtra(ExtraCacheData, QVariant::fromValue<void *>(c)); } return c; } /*! \internal */ void QGraphicsItemPrivate::removeExtraItemCache() { QGraphicsItemCache *c = (QGraphicsItemCache *)qvariant_cast<void *>(extra(ExtraCacheData)); if (c) { c->purge(); delete c; } unsetExtra(ExtraCacheData); } void QGraphicsItemPrivate::updatePaintedViewBoundingRects(bool updateChildren) { if (!scene) return; for (int i = 0; i < scene->d_func()->views.size(); ++i) { QGraphicsViewPrivate *viewPrivate = scene->d_func()->views.at(i)->d_func(); QRect rect = paintedViewBoundingRects.value(viewPrivate->viewport); rect.translate(viewPrivate->dirtyScrollOffset); viewPrivate->updateRect(rect); } if (updateChildren) { for (int i = 0; i < children.size(); ++i) children.at(i)->d_ptr->updatePaintedViewBoundingRects(true); } } // Traverses all the ancestors up to the top-level and updates the pointer to // always point to the top-most item that has a dirty scene transform. // It then backtracks to the top-most dirty item and start calculating the // scene transform by combining the item's transform (+pos) with the parent's // cached scene transform (which we at this point know for sure is valid). void QGraphicsItemPrivate::ensureSceneTransformRecursive(QGraphicsItem **topMostDirtyItem) { Q_ASSERT(topMostDirtyItem); if (dirtySceneTransform) *topMostDirtyItem = q_ptr; if (parent) parent->d_ptr->ensureSceneTransformRecursive(topMostDirtyItem); if (*topMostDirtyItem == q_ptr) { if (!dirtySceneTransform) return; // OK, neither my ancestors nor I have dirty scene transforms. *topMostDirtyItem = 0; } else if (*topMostDirtyItem) { return; // Continue backtrack. } // This item and all its descendants have dirty scene transforms. // We're about to validate this item's scene transform, so we have to // invalidate all the children; otherwise there's no way for the descendants // to detect that the ancestor has changed. invalidateChildrenSceneTransform(); // COMBINE my transform with the parent's scene transform. updateSceneTransformFromParent(); Q_ASSERT(!dirtySceneTransform); } /*! \internal */ void QGraphicsItemPrivate::setSubFocus(QGraphicsItem *rootItem, QGraphicsItem *stopItem) { // Update focus child chain. Stop at panels, or if this item // is hidden, stop at the first item with a visible parent. QGraphicsItem *parent = rootItem ? rootItem : q_ptr; if (parent->panel() != q_ptr->panel()) return; do { // Clear any existing ancestor's subFocusItem. if (parent != q_ptr && parent->d_ptr->subFocusItem) { if (parent->d_ptr->subFocusItem == q_ptr) break; parent->d_ptr->subFocusItem->d_ptr->clearSubFocus(0, stopItem); } parent->d_ptr->subFocusItem = q_ptr; parent->d_ptr->subFocusItemChange(); } while (!parent->isPanel() && (parent = parent->d_ptr->parent) && (visible || !parent->d_ptr->visible)); if (scene && !scene->isActive()) { scene->d_func()->passiveFocusItem = subFocusItem; scene->d_func()->lastFocusItem = subFocusItem; } } /*! \internal */ void QGraphicsItemPrivate::clearSubFocus(QGraphicsItem *rootItem, QGraphicsItem *stopItem) { // Reset sub focus chain. QGraphicsItem *parent = rootItem ? rootItem : q_ptr; do { if (parent->d_ptr->subFocusItem != q_ptr) break; parent->d_ptr->subFocusItem = 0; if (parent != stopItem && !parent->isAncestorOf(stopItem)) parent->d_ptr->subFocusItemChange(); } while (!parent->isPanel() && (parent = parent->d_ptr->parent)); } /*! \internal Sets the focusProxy pointer to 0 for all items that have this item as their focusProxy. ### Qt 5: Use QPointer instead. */ void QGraphicsItemPrivate::resetFocusProxy() { for (int i = 0; i < focusProxyRefs.size(); ++i) *focusProxyRefs.at(i) = 0; focusProxyRefs.clear(); } /*! \internal Subclasses can reimplement this function to be notified when subFocusItem changes. */ void QGraphicsItemPrivate::subFocusItemChange() { } /*! \internal Subclasses can reimplement this function to be notified when an item becomes a focusScopeItem (or is no longer a focusScopeItem). */ void QGraphicsItemPrivate::focusScopeItemChange(bool isSubFocusItem) { Q_UNUSED(isSubFocusItem); } /*! \internal Subclasses can reimplement this function to be notified when its siblingIndex order is changed. */ void QGraphicsItemPrivate::siblingOrderChange() { } /*! \internal Tells us if it is a proxy widget */ bool QGraphicsItemPrivate::isProxyWidget() const { return false; } /*! Schedules a redraw of the area covered by \a rect in this item. You can call this function whenever your item needs to be redrawn, such as if it changes appearance or size. This function does not cause an immediate paint; instead it schedules a paint request that is processed by QGraphicsView after control reaches the event loop. The item will only be redrawn if it is visible in any associated view. As a side effect of the item being repainted, other items that overlap the area \a rect may also be repainted. If the item is invisible (i.e., isVisible() returns false), this function does nothing. \sa paint(), boundingRect() */ void QGraphicsItem::update(const QRectF &rect) { if (rect.isEmpty() && !rect.isNull()) return; // Make sure we notify effects about invalidated source. #ifndef QT_NO_GRAPHICSEFFECT d_ptr->invalidateParentGraphicsEffectsRecursively(); #endif //QT_NO_GRAPHICSEFFECT #ifndef QT_NO_GRAPHICSEFFECT if (!d_ptr->updateDueToGraphicsEffect) { #endif if (CacheMode(d_ptr->cacheMode) != NoCache) { // Invalidate cache. QGraphicsItemCache *cache = d_ptr->extraItemCache(); if (!cache->allExposed) { if (rect.isNull()) { cache->allExposed = true; cache->exposed.clear(); } else { cache->exposed.append(rect); } } // Only invalidate cache; item is already dirty. if (d_ptr->fullUpdatePending) return; } #ifndef QT_NO_GRAPHICSEFFECT } #endif if (d_ptr->scene) d_ptr->scene->d_func()->markDirty(this, rect); } /*! \since 4.4 Scrolls the contents of \a rect by \a dx, \a dy. If \a rect is a null rect (the default), the item's bounding rect is scrolled. Scrolling provides a fast alternative to simply redrawing when the contents of the item (or parts of the item) are shifted vertically or horizontally. Depending on the current transformation and the capabilities of the paint device (i.e., the viewport), this operation may consist of simply moving pixels from one location to another using memmove(). In most cases this is faster than rerendering the entire area. After scrolling, the item will issue an update for the newly exposed areas. If scrolling is not supported (e.g., you are rendering to an OpenGL viewport, which does not benefit from scroll optimizations), this function is equivalent to calling update(\a rect). \bold{Note:} Scrolling is only supported when QGraphicsItem::ItemCoordinateCache is enabled; in all other cases calling this function is equivalent to calling update(\a rect). If you for sure know that the item is opaque and not overlapped by other items, you can map the \a rect to viewport coordinates and scroll the viewport. \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 19 \sa boundingRect() */ void QGraphicsItem::scroll(qreal dx, qreal dy, const QRectF &rect) { Q_D(QGraphicsItem); if (dx == 0.0 && dy == 0.0) return; if (!d->scene) return; // Accelerated scrolling means moving pixels from one location to another // and only redraw the newly exposed area. The following requirements must // be fulfilled in order to do that: // // 1) Item is opaque. // 2) Item is not overlapped by other items. // // There's (yet) no way to detect whether an item is opaque or not, which means // we cannot do accelerated scrolling unless the cache is enabled. In case of using // DeviceCoordinate cache we also have to take the device transform into account in // order to determine whether we can do accelerated scrolling or not. That's left out // for simplicity here, but it is definitely something we can consider in the future // as a performance improvement. if (d->cacheMode != QGraphicsItem::ItemCoordinateCache || !qFuzzyIsNull(dx - int(dx)) || !qFuzzyIsNull(dy - int(dy))) { update(rect); return; } QGraphicsItemCache *cache = d->extraItemCache(); if (cache->allExposed || cache->fixedSize.isValid()) { // Cache is either invalidated or item is scaled (see QGraphicsItem::setCacheMode). update(rect); return; } // Find pixmap in cache. QPixmap cachedPixmap; if (!QPixmapCache::find(cache->key, &cachedPixmap)) { update(rect); return; } QRect scrollRect = (rect.isNull() ? boundingRect() : rect).toAlignedRect(); if (!scrollRect.intersects(cache->boundingRect)) return; // Nothing to scroll. // Remove from cache to avoid deep copy when modifying. QPixmapCache::remove(cache->key); QRegion exposed; cachedPixmap.scroll(dx, dy, scrollRect.translated(-cache->boundingRect.topLeft()), &exposed); // Reinsert into cache. cache->key = QPixmapCache::insert(cachedPixmap); // Translate the existing expose. for (int i = 0; i < cache->exposed.size(); ++i) { QRectF &e = cache->exposed[i]; if (!rect.isNull() && !e.intersects(rect)) continue; e.translate(dx, dy); } // Append newly exposed areas. Note that the exposed region is currently // in pixmap coordinates, so we have to translate it to item coordinates. exposed.translate(cache->boundingRect.topLeft()); const QVector<QRect> exposedRects = exposed.rects(); for (int i = 0; i < exposedRects.size(); ++i) cache->exposed += exposedRects.at(i); // Trigger update. This will redraw the newly exposed area and make sure // the pixmap is re-blitted in case there are overlapping items. d->scene->d_func()->markDirty(this, rect); } /*! \fn void QGraphicsItem::update(qreal x, qreal y, qreal width, qreal height) \overload This convenience function is equivalent to calling update(QRectF(\a x, \a y, \a width, \a height)). */ /*! Maps the point \a point, which is in this item's coordinate system, to \a item's coordinate system, and returns the mapped coordinate. If \a item is 0, this function returns the same as mapToScene(). \sa itemTransform(), mapToParent(), mapToScene(), transform(), mapFromItem(), {The Graphics View Coordinate System} */ QPointF QGraphicsItem::mapToItem(const QGraphicsItem *item, const QPointF &point) const { if (item) return itemTransform(item).map(point); return mapToScene(point); } /*! \fn QPointF QGraphicsItem::mapToItem(const QGraphicsItem *item, qreal x, qreal y) const \overload This convenience function is equivalent to calling mapToItem(\a item, QPointF(\a x, \a y)). */ /*! Maps the point \a point, which is in this item's coordinate system, to its parent's coordinate system, and returns the mapped coordinate. If the item has no parent, \a point will be mapped to the scene's coordinate system. \sa mapToItem(), mapToScene(), transform(), mapFromParent(), {The Graphics View Coordinate System} */ QPointF QGraphicsItem::mapToParent(const QPointF &point) const { // COMBINE if (!d_ptr->transformData) return point + d_ptr->pos; return d_ptr->transformToParent().map(point); } /*! \fn QPointF QGraphicsItem::mapToParent(qreal x, qreal y) const \overload This convenience function is equivalent to calling mapToParent(QPointF(\a x, \a y)). */ /*! Maps the point \a point, which is in this item's coordinate system, to the scene's coordinate system, and returns the mapped coordinate. \sa mapToItem(), mapToParent(), transform(), mapFromScene(), {The Graphics View Coordinate System} */ QPointF QGraphicsItem::mapToScene(const QPointF &point) const { if (d_ptr->hasTranslateOnlySceneTransform()) return QPointF(point.x() + d_ptr->sceneTransform.dx(), point.y() + d_ptr->sceneTransform.dy()); return d_ptr->sceneTransform.map(point); } /*! \fn QPointF QGraphicsItem::mapToScene(qreal x, qreal y) const \overload This convenience function is equivalent to calling mapToScene(QPointF(\a x, \a y)). */ /*! Maps the rectangle \a rect, which is in this item's coordinate system, to \a item's coordinate system, and returns the mapped rectangle as a polygon. If \a item is 0, this function returns the same as mapToScene(). \sa itemTransform(), mapToParent(), mapToScene(), mapFromItem(), {The Graphics View Coordinate System} */ QPolygonF QGraphicsItem::mapToItem(const QGraphicsItem *item, const QRectF &rect) const { if (item) return itemTransform(item).map(rect); return mapToScene(rect); } /*! \fn QPolygonF QGraphicsItem::mapToItem(const QGraphicsItem *item, qreal x, qreal y, qreal w, qreal h) const \since 4.3 This convenience function is equivalent to calling mapToItem(item, QRectF(\a x, \a y, \a w, \a h)). */ /*! Maps the rectangle \a rect, which is in this item's coordinate system, to its parent's coordinate system, and returns the mapped rectangle as a polygon. If the item has no parent, \a rect will be mapped to the scene's coordinate system. \sa mapToScene(), mapToItem(), mapFromParent(), {The Graphics View Coordinate System} */ QPolygonF QGraphicsItem::mapToParent(const QRectF &rect) const { // COMBINE if (!d_ptr->transformData) return rect.translated(d_ptr->pos); return d_ptr->transformToParent().map(rect); } /*! \fn QPolygonF QGraphicsItem::mapToParent(qreal x, qreal y, qreal w, qreal h) const \since 4.3 This convenience function is equivalent to calling mapToParent(QRectF(\a x, \a y, \a w, \a h)). */ /*! Maps the rectangle \a rect, which is in this item's coordinate system, to the scene's coordinate system, and returns the mapped rectangle as a polygon. \sa mapToParent(), mapToItem(), mapFromScene(), {The Graphics View Coordinate System} */ QPolygonF QGraphicsItem::mapToScene(const QRectF &rect) const { if (d_ptr->hasTranslateOnlySceneTransform()) return rect.translated(d_ptr->sceneTransform.dx(), d_ptr->sceneTransform.dy()); return d_ptr->sceneTransform.map(rect); } /*! \fn QPolygonF QGraphicsItem::mapToScene(qreal x, qreal y, qreal w, qreal h) const \since 4.3 This convenience function is equivalent to calling mapToScene(QRectF(\a x, \a y, \a w, \a h)). */ /*! \since 4.5 Maps the rectangle \a rect, which is in this item's coordinate system, to \a item's coordinate system, and returns the mapped rectangle as a new rectangle (i.e., the bounding rectangle of the resulting polygon). If \a item is 0, this function returns the same as mapRectToScene(). \sa itemTransform(), mapToParent(), mapToScene(), mapFromItem(), {The Graphics View Coordinate System} */ QRectF QGraphicsItem::mapRectToItem(const QGraphicsItem *item, const QRectF &rect) const { if (item) return itemTransform(item).mapRect(rect); return mapRectToScene(rect); } /*! \fn QRectF QGraphicsItem::mapRectToItem(const QGraphicsItem *item, qreal x, qreal y, qreal w, qreal h) const \since 4.5 This convenience function is equivalent to calling mapRectToItem(item, QRectF(\a x, \a y, \a w, \a h)). */ /*! \since 4.5 Maps the rectangle \a rect, which is in this item's coordinate system, to its parent's coordinate system, and returns the mapped rectangle as a new rectangle (i.e., the bounding rectangle of the resulting polygon). \sa itemTransform(), mapToParent(), mapToScene(), mapFromItem(), {The Graphics View Coordinate System} */ QRectF QGraphicsItem::mapRectToParent(const QRectF &rect) const { // COMBINE if (!d_ptr->transformData) return rect.translated(d_ptr->pos); return d_ptr->transformToParent().mapRect(rect); } /*! \fn QRectF QGraphicsItem::mapRectToParent(qreal x, qreal y, qreal w, qreal h) const \since 4.5 This convenience function is equivalent to calling mapRectToParent(QRectF(\a x, \a y, \a w, \a h)). */ /*! \since 4.5 Maps the rectangle \a rect, which is in this item's coordinate system, to the scene coordinate system, and returns the mapped rectangle as a new rectangle (i.e., the bounding rectangle of the resulting polygon). \sa itemTransform(), mapToParent(), mapToScene(), mapFromItem(), {The Graphics View Coordinate System} */ QRectF QGraphicsItem::mapRectToScene(const QRectF &rect) const { if (d_ptr->hasTranslateOnlySceneTransform()) return rect.translated(d_ptr->sceneTransform.dx(), d_ptr->sceneTransform.dy()); return d_ptr->sceneTransform.mapRect(rect); } /*! \fn QRectF QGraphicsItem::mapRectToScene(qreal x, qreal y, qreal w, qreal h) const \since 4.5 This convenience function is equivalent to calling mapRectToScene(QRectF(\a x, \a y, \a w, \a h)). */ /*! \since 4.5 Maps the rectangle \a rect, which is in \a item's coordinate system, to this item's coordinate system, and returns the mapped rectangle as a new rectangle (i.e., the bounding rectangle of the resulting polygon). If \a item is 0, this function returns the same as mapRectFromScene(). \sa itemTransform(), mapToParent(), mapToScene(), mapFromItem(), {The Graphics View Coordinate System} */ QRectF QGraphicsItem::mapRectFromItem(const QGraphicsItem *item, const QRectF &rect) const { if (item) return item->itemTransform(this).mapRect(rect); return mapRectFromScene(rect); } /*! \fn QRectF QGraphicsItem::mapRectFromItem(const QGraphicsItem *item, qreal x, qreal y, qreal w, qreal h) const \since 4.5 This convenience function is equivalent to calling mapRectFromItem(item, QRectF(\a x, \a y, \a w, \a h)). */ /*! \since 4.5 Maps the rectangle \a rect, which is in this item's parent's coordinate system, to this item's coordinate system, and returns the mapped rectangle as a new rectangle (i.e., the bounding rectangle of the resulting polygon). \sa itemTransform(), mapToParent(), mapToScene(), mapFromItem(), {The Graphics View Coordinate System} */ QRectF QGraphicsItem::mapRectFromParent(const QRectF &rect) const { // COMBINE if (!d_ptr->transformData) return rect.translated(-d_ptr->pos); return d_ptr->transformToParent().inverted().mapRect(rect); } /*! \fn QRectF QGraphicsItem::mapRectFromParent(qreal x, qreal y, qreal w, qreal h) const \since 4.5 This convenience function is equivalent to calling mapRectFromParent(QRectF(\a x, \a y, \a w, \a h)). */ /*! \since 4.5 Maps the rectangle \a rect, which is in scene coordinates, to this item's coordinate system, and returns the mapped rectangle as a new rectangle (i.e., the bounding rectangle of the resulting polygon). \sa itemTransform(), mapToParent(), mapToScene(), mapFromItem(), {The Graphics View Coordinate System} */ QRectF QGraphicsItem::mapRectFromScene(const QRectF &rect) const { if (d_ptr->hasTranslateOnlySceneTransform()) return rect.translated(-d_ptr->sceneTransform.dx(), -d_ptr->sceneTransform.dy()); return d_ptr->sceneTransform.inverted().mapRect(rect); } /*! \fn QRectF QGraphicsItem::mapRectFromScene(qreal x, qreal y, qreal w, qreal h) const \since 4.5 This convenience function is equivalent to calling mapRectFromScene(QRectF(\a x, \a y, \a w, \a h)). */ /*! Maps the polygon \a polygon, which is in this item's coordinate system, to \a item's coordinate system, and returns the mapped polygon. If \a item is 0, this function returns the same as mapToScene(). \sa itemTransform(), mapToParent(), mapToScene(), mapFromItem(), {The Graphics View Coordinate System} */ QPolygonF QGraphicsItem::mapToItem(const QGraphicsItem *item, const QPolygonF &polygon) const { if (item) return itemTransform(item).map(polygon); return mapToScene(polygon); } /*! Maps the polygon \a polygon, which is in this item's coordinate system, to its parent's coordinate system, and returns the mapped polygon. If the item has no parent, \a polygon will be mapped to the scene's coordinate system. \sa mapToScene(), mapToItem(), mapFromParent(), {The Graphics View Coordinate System} */ QPolygonF QGraphicsItem::mapToParent(const QPolygonF &polygon) const { // COMBINE if (!d_ptr->transformData) return polygon.translated(d_ptr->pos); return d_ptr->transformToParent().map(polygon); } /*! Maps the polygon \a polygon, which is in this item's coordinate system, to the scene's coordinate system, and returns the mapped polygon. \sa mapToParent(), mapToItem(), mapFromScene(), {The Graphics View Coordinate System} */ QPolygonF QGraphicsItem::mapToScene(const QPolygonF &polygon) const { if (d_ptr->hasTranslateOnlySceneTransform()) return polygon.translated(d_ptr->sceneTransform.dx(), d_ptr->sceneTransform.dy()); return d_ptr->sceneTransform.map(polygon); } /*! Maps the path \a path, which is in this item's coordinate system, to \a item's coordinate system, and returns the mapped path. If \a item is 0, this function returns the same as mapToScene(). \sa itemTransform(), mapToParent(), mapToScene(), mapFromItem(), {The Graphics View Coordinate System} */ QPainterPath QGraphicsItem::mapToItem(const QGraphicsItem *item, const QPainterPath &path) const { if (item) return itemTransform(item).map(path); return mapToScene(path); } /*! Maps the path \a path, which is in this item's coordinate system, to its parent's coordinate system, and returns the mapped path. If the item has no parent, \a path will be mapped to the scene's coordinate system. \sa mapToScene(), mapToItem(), mapFromParent(), {The Graphics View Coordinate System} */ QPainterPath QGraphicsItem::mapToParent(const QPainterPath &path) const { // COMBINE if (!d_ptr->transformData) return path.translated(d_ptr->pos); return d_ptr->transformToParent().map(path); } /*! Maps the path \a path, which is in this item's coordinate system, to the scene's coordinate system, and returns the mapped path. \sa mapToParent(), mapToItem(), mapFromScene(), {The Graphics View Coordinate System} */ QPainterPath QGraphicsItem::mapToScene(const QPainterPath &path) const { if (d_ptr->hasTranslateOnlySceneTransform()) return path.translated(d_ptr->sceneTransform.dx(), d_ptr->sceneTransform.dy()); return d_ptr->sceneTransform.map(path); } /*! Maps the point \a point, which is in \a item's coordinate system, to this item's coordinate system, and returns the mapped coordinate. If \a item is 0, this function returns the same as mapFromScene(). \sa itemTransform(), mapFromParent(), mapFromScene(), transform(), mapToItem(), {The Graphics View Coordinate System} */ QPointF QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QPointF &point) const { if (item) return item->itemTransform(this).map(point); return mapFromScene(point); } /*! \fn QPointF QGraphicsItem::mapFromItem(const QGraphicsItem *item, qreal x, qreal y) const \overload This convenience function is equivalent to calling mapFromItem(\a item, QPointF(\a x, \a y)). */ /*! Maps the point \a point, which is in this item's parent's coordinate system, to this item's coordinate system, and returns the mapped coordinate. \sa mapFromItem(), mapFromScene(), transform(), mapToParent(), {The Graphics View Coordinate System} */ QPointF QGraphicsItem::mapFromParent(const QPointF &point) const { // COMBINE if (d_ptr->transformData) return d_ptr->transformToParent().inverted().map(point); return point - d_ptr->pos; } /*! \fn QPointF QGraphicsItem::mapFromParent(qreal x, qreal y) const \overload This convenience function is equivalent to calling mapFromParent(QPointF(\a x, \a y)). */ /*! Maps the point \a point, which is in this item's scene's coordinate system, to this item's coordinate system, and returns the mapped coordinate. \sa mapFromItem(), mapFromParent(), transform(), mapToScene(), {The Graphics View Coordinate System} */ QPointF QGraphicsItem::mapFromScene(const QPointF &point) const { if (d_ptr->hasTranslateOnlySceneTransform()) return QPointF(point.x() - d_ptr->sceneTransform.dx(), point.y() - d_ptr->sceneTransform.dy()); return d_ptr->sceneTransform.inverted().map(point); } /*! \fn QPointF QGraphicsItem::mapFromScene(qreal x, qreal y) const \overload This convenience function is equivalent to calling mapFromScene(QPointF(\a x, \a y)). */ /*! Maps the rectangle \a rect, which is in \a item's coordinate system, to this item's coordinate system, and returns the mapped rectangle as a polygon. If \a item is 0, this function returns the same as mapFromScene() \sa itemTransform(), mapToItem(), mapFromParent(), transform(), {The Graphics View Coordinate System} */ QPolygonF QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QRectF &rect) const { if (item) return item->itemTransform(this).map(rect); return mapFromScene(rect); } /*! \fn QPolygonF QGraphicsItem::mapFromItem(const QGraphicsItem *item, qreal x, qreal y, qreal w, qreal h) const \since 4.3 This convenience function is equivalent to calling mapFromItem(item, QRectF(\a x, \a y, \a w, \a h)). */ /*! Maps the rectangle \a rect, which is in this item's parent's coordinate system, to this item's coordinate system, and returns the mapped rectangle as a polygon. \sa mapToParent(), mapFromItem(), transform(), {The Graphics View Coordinate System} */ QPolygonF QGraphicsItem::mapFromParent(const QRectF &rect) const { // COMBINE if (!d_ptr->transformData) return rect.translated(-d_ptr->pos); return d_ptr->transformToParent().inverted().map(rect); } /*! \fn QPolygonF QGraphicsItem::mapFromParent(qreal x, qreal y, qreal w, qreal h) const \since 4.3 This convenience function is equivalent to calling mapFromItem(QRectF(\a x, \a y, \a w, \a h)). */ /*! Maps the rectangle \a rect, which is in this item's scene's coordinate system, to this item's coordinate system, and returns the mapped rectangle as a polygon. \sa mapToScene(), mapFromItem(), transform(), {The Graphics View Coordinate System} */ QPolygonF QGraphicsItem::mapFromScene(const QRectF &rect) const { if (d_ptr->hasTranslateOnlySceneTransform()) return rect.translated(-d_ptr->sceneTransform.dx(), -d_ptr->sceneTransform.dy()); return d_ptr->sceneTransform.inverted().map(rect); } /*! \fn QPolygonF QGraphicsItem::mapFromScene(qreal x, qreal y, qreal w, qreal h) const \since 4.3 This convenience function is equivalent to calling mapFromScene(QRectF(\a x, \a y, \a w, \a h)). */ /*! Maps the polygon \a polygon, which is in \a item's coordinate system, to this item's coordinate system, and returns the mapped polygon. If \a item is 0, this function returns the same as mapFromScene(). \sa itemTransform(), mapToItem(), mapFromParent(), transform(), {The Graphics View Coordinate System} */ QPolygonF QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QPolygonF &polygon) const { if (item) return item->itemTransform(this).map(polygon); return mapFromScene(polygon); } /*! Maps the polygon \a polygon, which is in this item's parent's coordinate system, to this item's coordinate system, and returns the mapped polygon. \sa mapToParent(), mapToItem(), transform(), {The Graphics View Coordinate System} */ QPolygonF QGraphicsItem::mapFromParent(const QPolygonF &polygon) const { // COMBINE if (!d_ptr->transformData) return polygon.translated(-d_ptr->pos); return d_ptr->transformToParent().inverted().map(polygon); } /*! Maps the polygon \a polygon, which is in this item's scene's coordinate system, to this item's coordinate system, and returns the mapped polygon. \sa mapToScene(), mapFromParent(), transform(), {The Graphics View Coordinate System} */ QPolygonF QGraphicsItem::mapFromScene(const QPolygonF &polygon) const { if (d_ptr->hasTranslateOnlySceneTransform()) return polygon.translated(-d_ptr->sceneTransform.dx(), -d_ptr->sceneTransform.dy()); return d_ptr->sceneTransform.inverted().map(polygon); } /*! Maps the path \a path, which is in \a item's coordinate system, to this item's coordinate system, and returns the mapped path. If \a item is 0, this function returns the same as mapFromScene(). \sa itemTransform(), mapFromParent(), mapFromScene(), mapToItem(), {The Graphics View Coordinate System} */ QPainterPath QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QPainterPath &path) const { if (item) return item->itemTransform(this).map(path); return mapFromScene(path); } /*! Maps the path \a path, which is in this item's parent's coordinate system, to this item's coordinate system, and returns the mapped path. \sa mapFromScene(), mapFromItem(), mapToParent(), {The Graphics View Coordinate System} */ QPainterPath QGraphicsItem::mapFromParent(const QPainterPath &path) const { // COMBINE if (!d_ptr->transformData) return path.translated(-d_ptr->pos); return d_ptr->transformToParent().inverted().map(path); } /*! Maps the path \a path, which is in this item's scene's coordinate system, to this item's coordinate system, and returns the mapped path. \sa mapFromParent(), mapFromItem(), mapToScene(), {The Graphics View Coordinate System} */ QPainterPath QGraphicsItem::mapFromScene(const QPainterPath &path) const { if (d_ptr->hasTranslateOnlySceneTransform()) return path.translated(-d_ptr->sceneTransform.dx(), -d_ptr->sceneTransform.dy()); return d_ptr->sceneTransform.inverted().map(path); } /*! Returns true if this item is an ancestor of \a child (i.e., if this item is \a child's parent, or one of \a child's parent's ancestors). \sa parentItem() */ bool QGraphicsItem::isAncestorOf(const QGraphicsItem *child) const { if (!child || child == this) return false; if (child->d_ptr->depth() < d_ptr->depth()) return false; const QGraphicsItem *ancestor = child; while ((ancestor = ancestor->d_ptr->parent)) { if (ancestor == this) return true; } return false; } /*! \since 4.4 Returns the closest common ancestor item of this item and \a other, or 0 if either \a other is 0, or there is no common ancestor. \sa isAncestorOf() */ QGraphicsItem *QGraphicsItem::commonAncestorItem(const QGraphicsItem *other) const { if (!other) return 0; if (other == this) return const_cast<QGraphicsItem *>(this); const QGraphicsItem *thisw = this; const QGraphicsItem *otherw = other; int thisDepth = d_ptr->depth(); int otherDepth = other->d_ptr->depth(); while (thisDepth > otherDepth) { thisw = thisw->d_ptr->parent; --thisDepth; } while (otherDepth > thisDepth) { otherw = otherw->d_ptr->parent; --otherDepth; } while (thisw && thisw != otherw) { thisw = thisw->d_ptr->parent; otherw = otherw->d_ptr->parent; } return const_cast<QGraphicsItem *>(thisw); } /*! \since 4,4 Returns true if this item is currently under the mouse cursor in one of the views; otherwise, false is returned. \sa QGraphicsScene::views(), QCursor::pos() */ bool QGraphicsItem::isUnderMouse() const { Q_D(const QGraphicsItem); if (!d->scene) return false; QPoint cursorPos = QCursor::pos(); foreach (QGraphicsView *view, d->scene->views()) { if (contains(mapFromScene(view->mapToScene(view->mapFromGlobal(cursorPos))))) return true; } return false; } /*! Returns this item's custom data for the key \a key as a QVariant. Custom item data is useful for storing arbitrary properties in any item. Example: \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 11 Qt does not use this feature for storing data; it is provided solely for the convenience of the user. \sa setData() */ QVariant QGraphicsItem::data(int key) const { QGraphicsItemCustomDataStore *store = qt_dataStore(); if (!store->data.contains(this)) return QVariant(); return store->data.value(this).value(key); } /*! Sets this item's custom data for the key \a key to \a value. Custom item data is useful for storing arbitrary properties for any item. Qt does not use this feature for storing data; it is provided solely for the convenience of the user. \sa data() */ void QGraphicsItem::setData(int key, const QVariant &value) { qt_dataStore()->data[this][key] = value; } /*! \fn T qgraphicsitem_cast(QGraphicsItem *item) \relates QGraphicsItem \since 4.2 Returns the given \a item cast to type T if \a item is of type T; otherwise, 0 is returned. \note To make this function work correctly with custom items, reimplement the \l{QGraphicsItem::}{type()} function for each custom QGraphicsItem subclass. \sa QGraphicsItem::type(), QGraphicsItem::UserType */ /*! Returns the type of an item as an int. All standard graphicsitem classes are associated with a unique value; see QGraphicsItem::Type. This type information is used by qgraphicsitem_cast() to distinguish between types. The default implementation (in QGraphicsItem) returns UserType. To enable use of qgraphicsitem_cast() with a custom item, reimplement this function and declare a Type enum value equal to your custom item's type. Custom items must return a value larger than or equal to UserType (65536). For example: \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp QGraphicsItem type \sa UserType */ int QGraphicsItem::type() const { return (int)UserType; } /*! Installs an event filter for this item on \a filterItem, causing all events for this item to first pass through \a filterItem's sceneEventFilter() function. To filter another item's events, install this item as an event filter for the other item. Example: \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 12 An item can only filter events for other items in the same scene. Also, an item cannot filter its own events; instead, you can reimplement sceneEvent() directly. Items must belong to a scene for scene event filters to be installed and used. \sa removeSceneEventFilter(), sceneEventFilter(), sceneEvent() */ void QGraphicsItem::installSceneEventFilter(QGraphicsItem *filterItem) { if (!d_ptr->scene) { qWarning("QGraphicsItem::installSceneEventFilter: event filters can only be installed" " on items in a scene."); return; } if (d_ptr->scene != filterItem->scene()) { qWarning("QGraphicsItem::installSceneEventFilter: event filters can only be installed" " on items in the same scene."); return; } d_ptr->scene->d_func()->installSceneEventFilter(this, filterItem); } /*! Removes an event filter on this item from \a filterItem. \sa installSceneEventFilter() */ void QGraphicsItem::removeSceneEventFilter(QGraphicsItem *filterItem) { if (!d_ptr->scene || d_ptr->scene != filterItem->scene()) return; d_ptr->scene->d_func()->removeSceneEventFilter(this, filterItem); } /*! Filters events for the item \a watched. \a event is the filtered event. Reimplementing this function in a subclass makes it possible for the item to be used as an event filter for other items, intercepting all the events send to those items before they are able to respond. Reimplementations must return true to prevent further processing of a given event, ensuring that it will not be delivered to the watched item, or return false to indicate that the event should be propagated further by the event system. \sa installSceneEventFilter() */ bool QGraphicsItem::sceneEventFilter(QGraphicsItem *watched, QEvent *event) { Q_UNUSED(watched); Q_UNUSED(event); return false; } /*! This virtual function receives events to this item. Reimplement this function to intercept events before they are dispatched to the specialized event handlers contextMenuEvent(), focusInEvent(), focusOutEvent(), hoverEnterEvent(), hoverMoveEvent(), hoverLeaveEvent(), keyPressEvent(), keyReleaseEvent(), mousePressEvent(), mouseReleaseEvent(), mouseMoveEvent(), and mouseDoubleClickEvent(). Returns true if the event was recognized and handled; otherwise, (e.g., if the event type was not recognized,) false is returned. \a event is the intercepted event. */ bool QGraphicsItem::sceneEvent(QEvent *event) { if (d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorHandlesChildEvents) { if (event->type() == QEvent::HoverEnter || event->type() == QEvent::HoverLeave || event->type() == QEvent::DragEnter || event->type() == QEvent::DragLeave) { // Hover enter and hover leave events for children are ignored; // hover move events are forwarded. return true; } QGraphicsItem *handler = this; do { handler = handler->d_ptr->parent; Q_ASSERT(handler); } while (handler->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorHandlesChildEvents); // Forward the event to the closest parent that handles child // events, mapping existing item-local coordinates to its // coordinate system. d_ptr->remapItemPos(event, handler); handler->sceneEvent(event); return true; } if (event->type() == QEvent::FocusOut) { focusOutEvent(static_cast<QFocusEvent *>(event)); return true; } if (!d_ptr->visible) { // Eaten return true; } switch (event->type()) { case QEvent::FocusIn: focusInEvent(static_cast<QFocusEvent *>(event)); break; case QEvent::GraphicsSceneContextMenu: contextMenuEvent(static_cast<QGraphicsSceneContextMenuEvent *>(event)); break; case QEvent::GraphicsSceneDragEnter: dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent *>(event)); break; case QEvent::GraphicsSceneDragMove: dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent *>(event)); break; case QEvent::GraphicsSceneDragLeave: dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent *>(event)); break; case QEvent::GraphicsSceneDrop: dropEvent(static_cast<QGraphicsSceneDragDropEvent *>(event)); break; case QEvent::GraphicsSceneHoverEnter: hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent *>(event)); break; case QEvent::GraphicsSceneHoverMove: hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent *>(event)); break; case QEvent::GraphicsSceneHoverLeave: hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent *>(event)); break; case QEvent::GraphicsSceneMouseMove: mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent *>(event)); break; case QEvent::GraphicsSceneMousePress: mousePressEvent(static_cast<QGraphicsSceneMouseEvent *>(event)); break; case QEvent::GraphicsSceneMouseRelease: mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent *>(event)); break; case QEvent::GraphicsSceneMouseDoubleClick: mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent *>(event)); break; case QEvent::GraphicsSceneWheel: wheelEvent(static_cast<QGraphicsSceneWheelEvent *>(event)); break; case QEvent::KeyPress: { QKeyEvent *k = static_cast<QKeyEvent *>(event); if (k->key() == Qt::Key_Tab || k->key() == Qt::Key_Backtab) { if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier? bool res = false; if (k->key() == Qt::Key_Backtab || (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier))) { if (d_ptr->isWidget) { res = static_cast<QGraphicsWidget *>(this)->focusNextPrevChild(false); } else if (d_ptr->scene) { res = d_ptr->scene->focusNextPrevChild(false); } } else if (k->key() == Qt::Key_Tab) { if (d_ptr->isWidget) { res = static_cast<QGraphicsWidget *>(this)->focusNextPrevChild(true); } else if (d_ptr->scene) { res = d_ptr->scene->focusNextPrevChild(true); } } if (!res) event->ignore(); return true; } } keyPressEvent(static_cast<QKeyEvent *>(event)); break; } case QEvent::KeyRelease: keyReleaseEvent(static_cast<QKeyEvent *>(event)); break; case QEvent::InputMethod: inputMethodEvent(static_cast<QInputMethodEvent *>(event)); break; case QEvent::WindowActivate: case QEvent::WindowDeactivate: // Propagate panel activation. if (d_ptr->scene) { for (int i = 0; i < d_ptr->children.size(); ++i) { QGraphicsItem *child = d_ptr->children.at(i); if (child->isVisible() && !child->isPanel()) { if (!(child->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorHandlesChildEvents)) d_ptr->scene->sendEvent(child, event); } } } break; default: return false; } return true; } /*! This event handler can be reimplemented in a subclass to process context menu events. The \a event parameter contains details about the event to be handled. If you ignore the event, (i.e., by calling QEvent::ignore(),) \a event will propagate to any item beneath this item. If no items accept the event, it will be ignored by the scene, and propagate to the view. It's common to open a QMenu in response to receiving a context menu event. Example: \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 13 The default implementation ignores the event. \sa sceneEvent() */ void QGraphicsItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) { event->ignore(); } /*! This event handler, for event \a event, can be reimplemented to receive drag enter events for this item. Drag enter events are generated as the cursor enters the item's area. By accepting the event, (i.e., by calling QEvent::accept(),) the item will accept drop events, in addition to receiving drag move and drag leave. Otherwise, the event will be ignored and propagate to the item beneath. If the event is accepted, the item will receive a drag move event before control goes back to the event loop. A common implementation of dragEnterEvent accepts or ignores \a event depending on the associated mime data in \a event. Example: \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 14 Items do not receive drag and drop events by default; to enable this feature, call \c setAcceptDrops(true). The default implementation does nothing. \sa dropEvent(), dragMoveEvent(), dragLeaveEvent() */ void QGraphicsItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event) { Q_D(QGraphicsItem); // binary compatibility workaround between 4.4 and 4.5 if (d->isProxyWidget()) static_cast<QGraphicsProxyWidget*>(this)->dragEnterEvent(event); } /*! This event handler, for event \a event, can be reimplemented to receive drag leave events for this item. Drag leave events are generated as the cursor leaves the item's area. Most often you will not need to reimplement this function, but it can be useful for resetting state in your item (e.g., highlighting). Calling QEvent::ignore() or QEvent::accept() on \a event has no effect. Items do not receive drag and drop events by default; to enable this feature, call \c setAcceptDrops(true). The default implementation does nothing. \sa dragEnterEvent(), dropEvent(), dragMoveEvent() */ void QGraphicsItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event) { Q_D(QGraphicsItem); // binary compatibility workaround between 4.4 and 4.5 if (d->isProxyWidget()) static_cast<QGraphicsProxyWidget*>(this)->dragLeaveEvent(event); } /*! This event handler, for event \a event, can be reimplemented to receive drag move events for this item. Drag move events are generated as the cursor moves around inside the item's area. Most often you will not need to reimplement this function; it is used to indicate that only parts of the item can accept drops. Calling QEvent::ignore() or QEvent::accept() on \a event toggles whether or not the item will accept drops at the position from the event. By default, \a event is accepted, indicating that the item allows drops at the specified position. Items do not receive drag and drop events by default; to enable this feature, call \c setAcceptDrops(true). The default implementation does nothing. \sa dropEvent(), dragEnterEvent(), dragLeaveEvent() */ void QGraphicsItem::dragMoveEvent(QGraphicsSceneDragDropEvent *event) { Q_D(QGraphicsItem); // binary compatibility workaround between 4.4 and 4.5 if (d->isProxyWidget()) static_cast<QGraphicsProxyWidget*>(this)->dragMoveEvent(event); } /*! This event handler, for event \a event, can be reimplemented to receive drop events for this item. Items can only receive drop events if the last drag move event was accepted. Calling QEvent::ignore() or QEvent::accept() on \a event has no effect. Items do not receive drag and drop events by default; to enable this feature, call \c setAcceptDrops(true). The default implementation does nothing. \sa dragEnterEvent(), dragMoveEvent(), dragLeaveEvent() */ void QGraphicsItem::dropEvent(QGraphicsSceneDragDropEvent *event) { Q_D(QGraphicsItem); // binary compatibility workaround between 4.4 and 4.5 if (d->isProxyWidget()) static_cast<QGraphicsProxyWidget*>(this)->dropEvent(event); } /*! This event handler, for event \a event, can be reimplemented to receive focus in events for this item. The default implementation calls ensureVisible(). \sa focusOutEvent(), sceneEvent(), setFocus() */ void QGraphicsItem::focusInEvent(QFocusEvent *event) { Q_UNUSED(event); update(); } /*! This event handler, for event \a event, can be reimplemented to receive focus out events for this item. The default implementation does nothing. \sa focusInEvent(), sceneEvent(), setFocus() */ void QGraphicsItem::focusOutEvent(QFocusEvent *event) { Q_UNUSED(event); update(); } /*! This event handler, for event \a event, can be reimplemented to receive hover enter events for this item. The default implementation calls update(); otherwise it does nothing. Calling QEvent::ignore() or QEvent::accept() on \a event has no effect. \sa hoverMoveEvent(), hoverLeaveEvent(), sceneEvent(), setAcceptHoverEvents() */ void QGraphicsItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { Q_UNUSED(event); update(); } /*! This event handler, for event \a event, can be reimplemented to receive hover move events for this item. The default implementation does nothing. Calling QEvent::ignore() or QEvent::accept() on \a event has no effect. \sa hoverEnterEvent(), hoverLeaveEvent(), sceneEvent(), setAcceptHoverEvents() */ void QGraphicsItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) { Q_UNUSED(event); } /*! This event handler, for event \a event, can be reimplemented to receive hover leave events for this item. The default implementation calls update(); otherwise it does nothing. Calling QEvent::ignore() or QEvent::accept() on \a event has no effect. \sa hoverEnterEvent(), hoverMoveEvent(), sceneEvent(), setAcceptHoverEvents() */ void QGraphicsItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { Q_UNUSED(event); update(); } /*! This event handler, for event \a event, can be reimplemented to receive key press events for this item. The default implementation ignores the event. If you reimplement this handler, the event will by default be accepted. Note that key events are only received for items that set the ItemIsFocusable flag, and that have keyboard input focus. \sa keyReleaseEvent(), setFocus(), QGraphicsScene::setFocusItem(), sceneEvent() */ void QGraphicsItem::keyPressEvent(QKeyEvent *event) { event->ignore(); } /*! This event handler, for event \a event, can be reimplemented to receive key release events for this item. The default implementation ignores the event. If you reimplement this handler, the event will by default be accepted. Note that key events are only received for items that set the ItemIsFocusable flag, and that have keyboard input focus. \sa keyPressEvent(), setFocus(), QGraphicsScene::setFocusItem(), sceneEvent() */ void QGraphicsItem::keyReleaseEvent(QKeyEvent *event) { event->ignore(); } /*! This event handler, for event \a event, can be reimplemented to receive mouse press events for this item. Mouse press events are only delivered to items that accept the mouse button that is pressed. By default, an item accepts all mouse buttons, but you can change this by calling setAcceptedMouseButtons(). The mouse press event decides which item should become the mouse grabber (see QGraphicsScene::mouseGrabberItem()). If you do not reimplement this function, the press event will propagate to any topmost item beneath this item, and no other mouse events will be delivered to this item. If you do reimplement this function, \a event will by default be accepted (see QEvent::accept()), and this item is then the mouse grabber. This allows the item to receive future move, release and doubleclick events. If you call QEvent::ignore() on \a event, this item will lose the mouse grab, and \a event will propagate to any topmost item beneath. No further mouse events will be delivered to this item unless a new mouse press event is received. The default implementation handles basic item interaction, such as selection and moving. If you want to keep the base implementation when reimplementing this function, call QGraphicsItem::mousePressEvent() in your reimplementation. The event is \l{QEvent::ignore()}d for items that are neither \l{QGraphicsItem::ItemIsMovable}{movable} nor \l{QGraphicsItem::ItemIsSelectable}{selectable}. \sa mouseMoveEvent(), mouseReleaseEvent(), mouseDoubleClickEvent(), sceneEvent() */ void QGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { if (event->button() == Qt::LeftButton && (flags() & ItemIsSelectable)) { bool multiSelect = (event->modifiers() & Qt::ControlModifier) != 0; if (!multiSelect) { if (!d_ptr->selected) { if (QGraphicsScene *scene = d_ptr->scene) { ++scene->d_func()->selectionChanging; scene->clearSelection(); --scene->d_func()->selectionChanging; } setSelected(true); } } } else if (!(flags() & ItemIsMovable)) { event->ignore(); } if (d_ptr->isWidget) { // Qt::Popup closes when you click outside. QGraphicsWidget *w = static_cast<QGraphicsWidget *>(this); if ((w->windowFlags() & Qt::Popup) == Qt::Popup) { event->accept(); if (!w->rect().contains(event->pos())) w->close(); } } } /*! obsolete */ bool _qt_movableAncestorIsSelected(const QGraphicsItem *item) { const QGraphicsItem *parent = item->parentItem(); return parent && (((parent->flags() & QGraphicsItem::ItemIsMovable) && parent->isSelected()) || _qt_movableAncestorIsSelected(parent)); } bool QGraphicsItemPrivate::movableAncestorIsSelected(const QGraphicsItem *item) { const QGraphicsItem *parent = item->d_ptr->parent; return parent && (((parent->flags() & QGraphicsItem::ItemIsMovable) && parent->isSelected()) || _qt_movableAncestorIsSelected(parent)); } /*! This event handler, for event \a event, can be reimplemented to receive mouse move events for this item. If you do receive this event, you can be certain that this item also received a mouse press event, and that this item is the current mouse grabber. Calling QEvent::ignore() or QEvent::accept() on \a event has no effect. The default implementation handles basic item interaction, such as selection and moving. If you want to keep the base implementation when reimplementing this function, call QGraphicsItem::mouseMoveEvent() in your reimplementation. Please note that mousePressEvent() decides which graphics item it is that receives mouse events. See the mousePressEvent() description for details. \sa mousePressEvent(), mouseReleaseEvent(), mouseDoubleClickEvent(), sceneEvent() */ void QGraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { if ((event->buttons() & Qt::LeftButton) && (flags() & ItemIsMovable)) { // Determine the list of items that need to be moved. QList<QGraphicsItem *> selectedItems; QMap<QGraphicsItem *, QPointF> initialPositions; if (d_ptr->scene) { selectedItems = d_ptr->scene->selectedItems(); initialPositions = d_ptr->scene->d_func()->movingItemsInitialPositions; if (initialPositions.isEmpty()) { foreach (QGraphicsItem *item, selectedItems) initialPositions[item] = item->pos(); initialPositions[this] = pos(); } d_ptr->scene->d_func()->movingItemsInitialPositions = initialPositions; } // Find the active view. QGraphicsView *view = 0; if (event->widget()) view = qobject_cast<QGraphicsView *>(event->widget()->parentWidget()); // Move all selected items int i = 0; bool movedMe = false; while (i <= selectedItems.size()) { QGraphicsItem *item = 0; if (i < selectedItems.size()) item = selectedItems.at(i); else item = this; if (item == this) { // Slightly clumsy-looking way to ensure that "this" is part // of the list of items to move, this is to avoid allocations // (appending this item to the list of selected items causes a // detach). if (movedMe) break; movedMe = true; } if ((item->flags() & ItemIsMovable) && !QGraphicsItemPrivate::movableAncestorIsSelected(item)) { QPointF currentParentPos; QPointF buttonDownParentPos; if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorIgnoresTransformations) { // Items whose ancestors ignore transformations need to // map screen coordinates to local coordinates, then map // those to the parent. QTransform viewToItemTransform = (item->deviceTransform(view->viewportTransform())).inverted(); currentParentPos = mapToParent(viewToItemTransform.map(QPointF(view->mapFromGlobal(event->screenPos())))); buttonDownParentPos = mapToParent(viewToItemTransform.map(QPointF(view->mapFromGlobal(event->buttonDownScreenPos(Qt::LeftButton))))); } else if (item->flags() & ItemIgnoresTransformations) { // Root items that ignore transformations need to // calculate their diff by mapping viewport coordinates // directly to parent coordinates. // COMBINE QTransform itemTransform; if (item->d_ptr->transformData) itemTransform = item->d_ptr->transformData->computedFullTransform(); itemTransform.translate(item->d_ptr->pos.x(), item->d_ptr->pos.y()); QTransform viewToParentTransform = itemTransform * (item->sceneTransform() * view->viewportTransform()).inverted(); currentParentPos = viewToParentTransform.map(QPointF(view->mapFromGlobal(event->screenPos()))); buttonDownParentPos = viewToParentTransform.map(QPointF(view->mapFromGlobal(event->buttonDownScreenPos(Qt::LeftButton)))); } else { // All other items simply map from the scene. currentParentPos = item->mapToParent(item->mapFromScene(event->scenePos())); buttonDownParentPos = item->mapToParent(item->mapFromScene(event->buttonDownScenePos(Qt::LeftButton))); } item->setPos(initialPositions.value(item) + currentParentPos - buttonDownParentPos); if (item->flags() & ItemIsSelectable) item->setSelected(true); } ++i; } } else { event->ignore(); } } /*! This event handler, for event \a event, can be reimplemented to receive mouse release events for this item. Calling QEvent::ignore() or QEvent::accept() on \a event has no effect. The default implementation handles basic item interaction, such as selection and moving. If you want to keep the base implementation when reimplementing this function, call QGraphicsItem::mouseReleaseEvent() in your reimplementation. Please note that mousePressEvent() decides which graphics item it is that receives mouse events. See the mousePressEvent() description for details. \sa mousePressEvent(), mouseMoveEvent(), mouseDoubleClickEvent(), sceneEvent() */ void QGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { if (flags() & ItemIsSelectable) { bool multiSelect = (event->modifiers() & Qt::ControlModifier) != 0; if (event->scenePos() == event->buttonDownScenePos(Qt::LeftButton)) { // The item didn't move if (multiSelect) { setSelected(!isSelected()); } else { bool selectionChanged = false; if (QGraphicsScene *scene = d_ptr->scene) { ++scene->d_func()->selectionChanging; // Clear everything but this item. Bypass // QGraphicsScene::clearSelection()'s default behavior by // temporarily removing this item from the selection list. if (d_ptr->selected) { scene->d_func()->selectedItems.remove(this); foreach (QGraphicsItem *item, scene->d_func()->selectedItems) { if (item->isSelected()) { selectionChanged = true; break; } } } scene->clearSelection(); if (d_ptr->selected) scene->d_func()->selectedItems.insert(this); --scene->d_func()->selectionChanging; if (selectionChanged) emit d_ptr->scene->selectionChanged(); } setSelected(true); } } } if (d_ptr->scene && !event->buttons()) d_ptr->scene->d_func()->movingItemsInitialPositions.clear(); } /*! This event handler, for event \a event, can be reimplemented to receive mouse doubleclick events for this item. When doubleclicking an item, the item will first receive a mouse press event, followed by a release event (i.e., a click), then a doubleclick event, and finally a release event. Calling QEvent::ignore() or QEvent::accept() on \a event has no effect. The default implementation calls mousePressEvent(). If you want to keep the base implementation when reimplementing this function, call QGraphicsItem::mouseDoubleClickEvent() in your reimplementation. Note that an item will not receive double click events if it is neither \l {QGraphicsItem::ItemIsSelectable}{selectable} nor \l{QGraphicsItem::ItemIsMovable}{movable} (single mouse clicks are ignored in this case, and that stops the generation of double clicks). \sa mousePressEvent(), mouseMoveEvent(), mouseReleaseEvent(), sceneEvent() */ void QGraphicsItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) { mousePressEvent(event); } /*! This event handler, for event \a event, can be reimplemented to receive wheel events for this item. If you reimplement this function, \a event will be accepted by default. If you ignore the event, (i.e., by calling QEvent::ignore(),) it will propagate to any item beneath this item. If no items accept the event, it will be ignored by the scene, and propagate to the view (e.g., the view's vertical scroll bar). The default implementation ignores the event. \sa sceneEvent() */ void QGraphicsItem::wheelEvent(QGraphicsSceneWheelEvent *event) { event->ignore(); } /*! This event handler, for event \a event, can be reimplemented to receive input method events for this item. The default implementation ignores the event. \sa inputMethodQuery(), sceneEvent() */ void QGraphicsItem::inputMethodEvent(QInputMethodEvent *event) { event->ignore(); } /*! This method is only relevant for input items. It is used by the input method to query a set of properties of the item to be able to support complex input method operations, such as support for surrounding text and reconversions. \a query specifies which property is queried. \sa inputMethodEvent(), QInputMethodEvent, QInputContext */ QVariant QGraphicsItem::inputMethodQuery(Qt::InputMethodQuery query) const { if (isWidget()) { // ### Qt 5: Remove. The reimplementation in // QGraphicsProxyWidget solves this problem (but requires a // recompile to take effect). return d_ptr->inputMethodQueryHelper(query); } Q_UNUSED(query); return QVariant(); } /*! Returns the current input method hints of this item. Input method hints are only relevant for input items. The hints are used by the input method to indicate how it should operate. For example, if the Qt::ImhNumbersOnly flag is set, the input method may change its visual components to reflect that only numbers can be entered. The effect may vary between input method implementations. \since 4.6 \sa setInputMethodHints(), inputMethodQuery(), QInputContext */ Qt::InputMethodHints QGraphicsItem::inputMethodHints() const { Q_D(const QGraphicsItem); return d->imHints; } /*! Sets the current input method hints of this item to \a hints. \since 4.6 \sa inputMethodHints(), inputMethodQuery(), QInputContext */ void QGraphicsItem::setInputMethodHints(Qt::InputMethodHints hints) { Q_D(QGraphicsItem); d->imHints = hints; if (!hasFocus()) return; d->scene->d_func()->updateInputMethodSensitivityInViews(); #if !defined(QT_NO_IM) && (defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN)) QWidget *fw = QApplication::focusWidget(); if (!fw) return; for (int i = 0 ; i < scene()->views().count() ; ++i) if (scene()->views().at(i) == fw) if (QInputContext *inputContext = fw->inputContext()) inputContext->update(); #endif } /*! Updates the item's micro focus. \since 4.7 \sa QInputContext */ void QGraphicsItem::updateMicroFocus() { #if !defined(QT_NO_IM) && (defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN)) if (QWidget *fw = QApplication::focusWidget()) { if (scene()) { for (int i = 0 ; i < scene()->views().count() ; ++i) { if (scene()->views().at(i) == fw) { if (QInputContext *inputContext = fw->inputContext()) { inputContext->update(); #ifndef QT_NO_ACCESSIBILITY // ##### is this correct if (toGraphicsObject()) QAccessible::updateAccessibility(toGraphicsObject(), 0, QAccessible::StateChanged); #endif break; } } } } } #endif } /*! This virtual function is called by QGraphicsItem to notify custom items that some part of the item's state changes. By reimplementing this function, your can react to a change, and in some cases, (depending on \a change,) adjustments can be made. \a change is the parameter of the item that is changing. \a value is the new value; the type of the value depends on \a change. Example: \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 15 The default implementation does nothing, and returns \a value. Note: Certain QGraphicsItem functions cannot be called in a reimplementation of this function; see the GraphicsItemChange documentation for details. \sa GraphicsItemChange */ QVariant QGraphicsItem::itemChange(GraphicsItemChange change, const QVariant &value) { Q_UNUSED(change); return value; } /*! \internal Note: This is provided as a hook to avoid future problems related to adding virtual functions. */ bool QGraphicsItem::supportsExtension(Extension extension) const { Q_UNUSED(extension); return false; } /*! \internal Note: This is provided as a hook to avoid future problems related to adding virtual functions. */ void QGraphicsItem::setExtension(Extension extension, const QVariant &variant) { Q_UNUSED(extension); Q_UNUSED(variant); } /*! \internal Note: This is provided as a hook to avoid future problems related to adding virtual functions. */ QVariant QGraphicsItem::extension(const QVariant &variant) const { Q_UNUSED(variant); return QVariant(); } /*! \internal Adds this item to the scene's index. Called in conjunction with removeFromIndex() to ensure the index bookkeeping is correct when the item's position, transformation or shape changes. */ void QGraphicsItem::addToIndex() { if (d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren) { // ### add to child index only if applicable return; } if (d_ptr->scene) d_ptr->scene->d_func()->index->addItem(this); } /*! \internal Removes this item from the scene's index. Called in conjunction with addToIndex() to ensure the index bookkeeping is correct when the item's position, transformation or shape changes. */ void QGraphicsItem::removeFromIndex() { if (d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren) { // ### remove from child index only if applicable return; } if (d_ptr->scene) d_ptr->scene->d_func()->index->removeItem(this); } /*! Prepares the item for a geometry change. Call this function before changing the bounding rect of an item to keep QGraphicsScene's index up to date. prepareGeometryChange() will call update() if this is necessary. Example: \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 16 \sa boundingRect() */ void QGraphicsItem::prepareGeometryChange() { if (d_ptr->inDestructor) return; if (d_ptr->scene) { d_ptr->scene->d_func()->dirtyGrowingItemsBoundingRect = true; d_ptr->geometryChanged = 1; d_ptr->paintedViewBoundingRectsNeedRepaint = 1; d_ptr->notifyBoundingRectChanged = !d_ptr->inSetPosHelper; QGraphicsScenePrivate *scenePrivate = d_ptr->scene->d_func(); scenePrivate->index->prepareBoundingRectChange(this); scenePrivate->markDirty(this, QRectF(), /*invalidateChildren=*/true, /*force=*/false, /*ignoreOpacity=*/ false, /*removingItemFromScene=*/ false, /*updateBoundingRect=*/true); // For compatibility reasons, we have to update the item's old geometry // if someone is connected to the changed signal or the scene has no views. // Note that this has to be done *after* markDirty to ensure that // _q_processDirtyItems is called before _q_emitUpdated. if (scenePrivate->isSignalConnected(scenePrivate->changedSignalIndex) || scenePrivate->views.isEmpty()) { if (d_ptr->hasTranslateOnlySceneTransform()) { d_ptr->scene->update(boundingRect().translated(d_ptr->sceneTransform.dx(), d_ptr->sceneTransform.dy())); } else { d_ptr->scene->update(d_ptr->sceneTransform.mapRect(boundingRect())); } } } d_ptr->markParentDirty(/*updateBoundingRect=*/true); } /*! \internal Highlights \a item as selected. NOTE: This function is a duplicate of qt_graphicsItem_highlightSelected() in qgraphicssvgitem.cpp! */ static void qt_graphicsItem_highlightSelected( QGraphicsItem *item, QPainter *painter, const QStyleOptionGraphicsItem *option) { const QRectF murect = painter->transform().mapRect(QRectF(0, 0, 1, 1)); if (qFuzzyIsNull(qMax(murect.width(), murect.height()))) return; const QRectF mbrect = painter->transform().mapRect(item->boundingRect()); if (qMin(mbrect.width(), mbrect.height()) < qreal(1.0)) return; qreal itemPenWidth; switch (item->type()) { case QGraphicsEllipseItem::Type: itemPenWidth = static_cast<QGraphicsEllipseItem *>(item)->pen().widthF(); break; case QGraphicsPathItem::Type: itemPenWidth = static_cast<QGraphicsPathItem *>(item)->pen().widthF(); break; case QGraphicsPolygonItem::Type: itemPenWidth = static_cast<QGraphicsPolygonItem *>(item)->pen().widthF(); break; case QGraphicsRectItem::Type: itemPenWidth = static_cast<QGraphicsRectItem *>(item)->pen().widthF(); break; case QGraphicsSimpleTextItem::Type: itemPenWidth = static_cast<QGraphicsSimpleTextItem *>(item)->pen().widthF(); break; case QGraphicsLineItem::Type: itemPenWidth = static_cast<QGraphicsLineItem *>(item)->pen().widthF(); break; default: itemPenWidth = 1.0; } const qreal pad = itemPenWidth / 2; const qreal penWidth = 0; // cosmetic pen const QColor fgcolor = option->palette.windowText().color(); const QColor bgcolor( // ensure good contrast against fgcolor fgcolor.red() > 127 ? 0 : 255, fgcolor.green() > 127 ? 0 : 255, fgcolor.blue() > 127 ? 0 : 255); painter->setPen(QPen(bgcolor, penWidth, Qt::SolidLine)); painter->setBrush(Qt::NoBrush); painter->drawRect(item->boundingRect().adjusted(pad, pad, -pad, -pad)); painter->setPen(QPen(option->palette.windowText(), 0, Qt::DashLine)); painter->setBrush(Qt::NoBrush); painter->drawRect(item->boundingRect().adjusted(pad, pad, -pad, -pad)); } /*! \class QGraphicsObject \brief The QGraphicsObject class provides a base class for all graphics items that require signals, slots and properties. \since 4.6 \ingroup graphicsview-api The class extends a QGraphicsItem with QObject's signal/slot and property mechanisms. It maps many of QGraphicsItem's basic setters and getters to properties and adds notification signals for many of them. \section1 Parents and Children Each graphics object can be constructed with a parent item. This ensures that the item will be destroyed when its parent item is destroyed. Although QGraphicsObject inherits from both QObject and QGraphicsItem, you should use the functions provided by QGraphicsItem, \e not QObject, to manage the relationships between parent and child items. The relationships between items can be explored using the parentItem() and childItems() functions. In the hierarchy of items in a scene, the parentObject() and parentWidget() functions are the equivalent of the QWidget::parent() and QWidget::parentWidget() functions for QWidget subclasses. \sa QGraphicsWidget */ /*! Constructs a QGraphicsObject with \a parent. */ QGraphicsObject::QGraphicsObject(QGraphicsItem *parent) : QGraphicsItem(parent) { QGraphicsItem::d_ptr->isObject = true; } /*! \internal */ QGraphicsObject::QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent, QGraphicsScene *scene) : QGraphicsItem(dd, parent, scene) { QGraphicsItem::d_ptr->isObject = true; } #ifndef QT_NO_GESTURES /*! Subscribes the graphics object to the given \a gesture with specific \a flags. \sa ungrabGesture(), QGestureEvent */ void QGraphicsObject::grabGesture(Qt::GestureType gesture, Qt::GestureFlags flags) { bool contains = QGraphicsItem::d_ptr->gestureContext.contains(gesture); QGraphicsItem::d_ptr->gestureContext.insert(gesture, flags); if (!contains && QGraphicsItem::d_ptr->scene) QGraphicsItem::d_ptr->scene->d_func()->grabGesture(this, gesture); } /*! Unsubscribes the graphics object from the given \a gesture. \sa grabGesture(), QGestureEvent */ void QGraphicsObject::ungrabGesture(Qt::GestureType gesture) { if (QGraphicsItem::d_ptr->gestureContext.remove(gesture) && QGraphicsItem::d_ptr->scene) QGraphicsItem::d_ptr->scene->d_func()->ungrabGesture(this, gesture); } #endif // QT_NO_GESTURES /*! Updates the item's micro focus. This is slot for convenience. \since 4.7 \sa QInputContext */ void QGraphicsObject::updateMicroFocus() { QGraphicsItem::updateMicroFocus(); } void QGraphicsItemPrivate::children_append(QDeclarativeListProperty<QGraphicsObject> *list, QGraphicsObject *item) { if (item) { QGraphicsObject *graphicsObject = static_cast<QGraphicsObject *>(list->object); if (QGraphicsItemPrivate::get(graphicsObject)->sendParentChangeNotification) { item->setParentItem(graphicsObject); } else { QGraphicsItemPrivate::get(item)->setParentItemHelper(graphicsObject, 0, 0); } } } int QGraphicsItemPrivate::children_count(QDeclarativeListProperty<QGraphicsObject> *list) { QGraphicsItemPrivate *d = QGraphicsItemPrivate::get(static_cast<QGraphicsObject *>(list->object)); return d->children.count(); } QGraphicsObject *QGraphicsItemPrivate::children_at(QDeclarativeListProperty<QGraphicsObject> *list, int index) { QGraphicsItemPrivate *d = QGraphicsItemPrivate::get(static_cast<QGraphicsObject *>(list->object)); if (index >= 0 && index < d->children.count()) return d->children.at(index)->toGraphicsObject(); else return 0; } void QGraphicsItemPrivate::children_clear(QDeclarativeListProperty<QGraphicsObject> *list) { QGraphicsItemPrivate *d = QGraphicsItemPrivate::get(static_cast<QGraphicsObject *>(list->object)); int childCount = d->children.count(); if (d->sendParentChangeNotification) { for (int index = 0; index < childCount; index++) d->children.at(0)->setParentItem(0); } else { for (int index = 0; index < childCount; index++) QGraphicsItemPrivate::get(d->children.at(0))->setParentItemHelper(0, 0, 0); } } /*! Returns a list of this item's children. The items are sorted by stacking order. This takes into account both the items' insertion order and their Z-values. */ QDeclarativeListProperty<QGraphicsObject> QGraphicsItemPrivate::childrenList() { Q_Q(QGraphicsItem); if (isObject) { QGraphicsObject *that = static_cast<QGraphicsObject *>(q); return QDeclarativeListProperty<QGraphicsObject>(that, &children, children_append, children_count, children_at, children_clear); } else { //QGraphicsItem is not supported for this property return QDeclarativeListProperty<QGraphicsObject>(); } } /*! \internal Returns the width of the item Reimplemented by QGraphicsWidget */ qreal QGraphicsItemPrivate::width() const { return 0; } /*! \internal Set the width of the item Reimplemented by QGraphicsWidget */ void QGraphicsItemPrivate::setWidth(qreal w) { Q_UNUSED(w); } /*! \internal Reset the width of the item Reimplemented by QGraphicsWidget */ void QGraphicsItemPrivate::resetWidth() { } /*! \internal Returns the height of the item Reimplemented by QGraphicsWidget */ qreal QGraphicsItemPrivate::height() const { return 0; } /*! \internal Set the height of the item Reimplemented by QGraphicsWidget */ void QGraphicsItemPrivate::setHeight(qreal h) { Q_UNUSED(h); } /*! \internal Reset the height of the item Reimplemented by QGraphicsWidget */ void QGraphicsItemPrivate::resetHeight() { } /*! \property QGraphicsObject::children \since 4.7 \internal */ /*! \property QGraphicsObject::width \since 4.7 \internal */ /*! \property QGraphicsObject::height \since 4.7 \internal */ /*! \property QGraphicsObject::parent \brief the parent of the item \note The item's parent is set independently of the parent object returned by QObject::parent(). \sa QGraphicsItem::setParentItem(), QGraphicsItem::parentObject() */ /*! \property QGraphicsObject::opacity \brief the opacity of the item \sa QGraphicsItem::setOpacity(), QGraphicsItem::opacity() */ /*! \fn QGraphicsObject::opacityChanged() This signal gets emitted whenever the opacity of the item changes \sa QGraphicsItem::opacity() */ /*! \fn QGraphicsObject::parentChanged() This signal gets emitted whenever the parent of the item changes */ /*! \property QGraphicsObject::pos \brief the position of the item Describes the items position. \sa QGraphicsItem::setPos(), QGraphicsItem::pos() */ /*! \property QGraphicsObject::x \brief the x position of the item Describes the items x position. \sa QGraphicsItem::setX(), setPos(), xChanged() */ /*! \fn QGraphicsObject::xChanged() This signal gets emitted whenever the x position of the item changes \sa pos() */ /*! \property QGraphicsObject::y \brief the y position of the item Describes the items y position. \sa QGraphicsItem::setY(), setPos(), yChanged() */ /*! \fn QGraphicsObject::yChanged() This signal gets emitted whenever the y position of the item changes. \sa pos() */ /*! \property QGraphicsObject::z \brief the z value of the item Describes the items z value. \sa QGraphicsItem::setZValue(), zValue(), zChanged() */ /*! \fn QGraphicsObject::zChanged() This signal gets emitted whenever the z value of the item changes. \sa pos() */ /*! \property QGraphicsObject::rotation This property holds the rotation of the item in degrees. This specifies how many degrees to rotate the item around its transformOrigin. The default rotation is 0 degrees (i.e. not rotated at all). */ /*! \fn QGraphicsObject::rotationChanged() This signal gets emitted whenever the roation of the item changes. */ /*! \property QGraphicsObject::scale This property holds the scale of the item. A scale of less than 1 means the item will be displayed smaller than normal, and a scale of greater than 1 means the item will be displayed larger than normal. A negative scale means the item will be mirrored. By default, items are displayed at a scale of 1 (i.e. at their normal size). Scaling is from the item's transformOrigin. */ /*! \fn void QGraphicsObject::scaleChanged() This signal is emitted when the scale of the item changes. */ /*! \property QGraphicsObject::enabled \brief whether the item is enabled or not This property is declared in QGraphicsItem. By default, this property is true. \sa QGraphicsItem::isEnabled(), QGraphicsItem::setEnabled() \sa QGraphicsObject::enabledChanged() */ /*! \fn void QGraphicsObject::enabledChanged() This signal gets emitted whenever the item get's enabled or disabled. \sa isEnabled() */ /*! \property QGraphicsObject::visible \brief whether the item is visible or not This property is declared in QGraphicsItem. By default, this property is true. \sa QGraphicsItem::isVisible(), QGraphicsItem::setVisible(), visibleChanged() */ /*! \fn QGraphicsObject::visibleChanged() This signal gets emitted whenever the visibility of the item changes \sa visible */ /*! \fn const QObjectList &QGraphicsObject::children() const \internal This function returns the same value as QObject::children(). It's provided to differentiate between the obsolete member QGraphicsItem::children() and QObject::children(). QGraphicsItem now provides childItems() instead. */ /*! \property QGraphicsObject::transformOriginPoint \brief the transformation origin This property sets a specific point in the items coordiante system as the origin for scale and rotation. \sa scale, rotation, QGraphicsItem::transformOriginPoint() */ /*! \fn void QGraphicsObject::widthChanged() \internal */ /*! \fn void QGraphicsObject::heightChanged() \internal */ /*! \fn QGraphicsObject::childrenChanged() This signal gets emitted whenever the children list changes \internal */ /*! \property QGraphicsObject::effect \since 4.7 \brief the effect attached to this item \sa QGraphicsItem::setGraphicsEffect(), QGraphicsItem::graphicsEffect() */ /*! \class QAbstractGraphicsShapeItem \brief The QAbstractGraphicsShapeItem class provides a common base for all path items. \since 4.2 \ingroup graphicsview-api This class does not fully implement an item by itself; in particular, it does not implement boundingRect() and paint(), which are inherited by QGraphicsItem. You can subclass this item to provide a simple base implementation of accessors for the item's pen and brush. \sa QGraphicsRectItem, QGraphicsEllipseItem, QGraphicsPathItem, QGraphicsPolygonItem, QGraphicsTextItem, QGraphicsLineItem, QGraphicsPixmapItem, {Graphics View Framework} */ class QAbstractGraphicsShapeItemPrivate : public QGraphicsItemPrivate { Q_DECLARE_PUBLIC(QAbstractGraphicsShapeItem) public: QBrush brush; QPen pen; // Cached bounding rectangle mutable QRectF boundingRect; }; /*! Constructs a QAbstractGraphicsShapeItem. \a parent is passed to QGraphicsItem's constructor. */ QAbstractGraphicsShapeItem::QAbstractGraphicsShapeItem(QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : QGraphicsItem(*new QAbstractGraphicsShapeItemPrivate, parent, scene) { } /*! \internal */ QAbstractGraphicsShapeItem::QAbstractGraphicsShapeItem(QAbstractGraphicsShapeItemPrivate &dd, QGraphicsItem *parent, QGraphicsScene *scene) : QGraphicsItem(dd, parent, scene) { } /*! Destroys a QAbstractGraphicsShapeItem. */ QAbstractGraphicsShapeItem::~QAbstractGraphicsShapeItem() { } /*! Returns the item's pen. If no pen has been set, this function returns QPen(), a default black solid line pen with 0 width. */ QPen QAbstractGraphicsShapeItem::pen() const { Q_D(const QAbstractGraphicsShapeItem); return d->pen; } /*! Sets the pen for this item to \a pen. The pen is used to draw the item's outline. \sa pen() */ void QAbstractGraphicsShapeItem::setPen(const QPen &pen) { Q_D(QAbstractGraphicsShapeItem); if (d->pen == pen) return; prepareGeometryChange(); d->pen = pen; d->boundingRect = QRectF(); update(); } /*! Returns the item's brush, or an empty brush if no brush has been set. \sa setBrush() */ QBrush QAbstractGraphicsShapeItem::brush() const { Q_D(const QAbstractGraphicsShapeItem); return d->brush; } /*! Sets the item's brush to \a brush. The item's brush is used to fill the item. If you use a brush with a QGradient, the gradient is relative to the item's coordinate system. \sa brush() */ void QAbstractGraphicsShapeItem::setBrush(const QBrush &brush) { Q_D(QAbstractGraphicsShapeItem); if (d->brush == brush) return; d->brush = brush; update(); } /*! \reimp */ bool QAbstractGraphicsShapeItem::isObscuredBy(const QGraphicsItem *item) const { return QGraphicsItem::isObscuredBy(item); } /*! \reimp */ QPainterPath QAbstractGraphicsShapeItem::opaqueArea() const { Q_D(const QAbstractGraphicsShapeItem); if (d->brush.isOpaque()) return isClipped() ? clipPath() : shape(); return QGraphicsItem::opaqueArea(); } /*! \class QGraphicsPathItem \brief The QGraphicsPathItem class provides a path item that you can add to a QGraphicsScene. \since 4.2 \ingroup graphicsview-api To set the item's path, pass a QPainterPath to QGraphicsPathItem's constructor, or call the setPath() function. The path() function returns the current path. \image graphicsview-pathitem.png QGraphicsPathItem uses the path to provide a reasonable implementation of boundingRect(), shape(), and contains(). The paint() function draws the path using the item's associated pen and brush, which you can set by calling the setPen() and setBrush() functions. \sa QGraphicsRectItem, QGraphicsEllipseItem, QGraphicsPolygonItem, QGraphicsTextItem, QGraphicsLineItem, QGraphicsPixmapItem, {Graphics View Framework} */ class QGraphicsPathItemPrivate : public QAbstractGraphicsShapeItemPrivate { Q_DECLARE_PUBLIC(QGraphicsPathItem) public: QPainterPath path; }; /*! Constructs a QGraphicsPath item using \a path as the default path. \a parent is passed to QAbstractGraphicsShapeItem's constructor. \sa QGraphicsScene::addItem() */ QGraphicsPathItem::QGraphicsPathItem(const QPainterPath &path, QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : QAbstractGraphicsShapeItem(*new QGraphicsPathItemPrivate, parent, scene) { if (!path.isEmpty()) setPath(path); } /*! Constructs a QGraphicsPath. \a parent is passed to QAbstractGraphicsShapeItem's constructor. \sa QGraphicsScene::addItem() */ QGraphicsPathItem::QGraphicsPathItem(QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : QAbstractGraphicsShapeItem(*new QGraphicsPathItemPrivate, parent, scene) { } /*! Destroys the QGraphicsPathItem. */ QGraphicsPathItem::~QGraphicsPathItem() { } /*! Returns the item's path as a QPainterPath. If no item has been set, an empty QPainterPath is returned. \sa setPath() */ QPainterPath QGraphicsPathItem::path() const { Q_D(const QGraphicsPathItem); return d->path; } /*! Sets the item's path to be the given \a path. \sa path() */ void QGraphicsPathItem::setPath(const QPainterPath &path) { Q_D(QGraphicsPathItem); if (d->path == path) return; prepareGeometryChange(); d->path = path; d->boundingRect = QRectF(); update(); } /*! \reimp */ QRectF QGraphicsPathItem::boundingRect() const { Q_D(const QGraphicsPathItem); if (d->boundingRect.isNull()) { qreal pw = pen().widthF(); if (pw == 0.0) d->boundingRect = d->path.controlPointRect(); else { d->boundingRect = shape().controlPointRect(); } } return d->boundingRect; } /*! \reimp */ QPainterPath QGraphicsPathItem::shape() const { Q_D(const QGraphicsPathItem); return qt_graphicsItem_shapeFromPath(d->path, d->pen); } /*! \reimp */ bool QGraphicsPathItem::contains(const QPointF &point) const { return QAbstractGraphicsShapeItem::contains(point); } /*! \reimp */ void QGraphicsPathItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_D(QGraphicsPathItem); Q_UNUSED(widget); painter->setPen(d->pen); painter->setBrush(d->brush); painter->drawPath(d->path); if (option->state & QStyle::State_Selected) qt_graphicsItem_highlightSelected(this, painter, option); } /*! \reimp */ bool QGraphicsPathItem::isObscuredBy(const QGraphicsItem *item) const { return QAbstractGraphicsShapeItem::isObscuredBy(item); } /*! \reimp */ QPainterPath QGraphicsPathItem::opaqueArea() const { return QAbstractGraphicsShapeItem::opaqueArea(); } /*! \reimp */ int QGraphicsPathItem::type() const { return Type; } /*! \internal */ bool QGraphicsPathItem::supportsExtension(Extension extension) const { Q_UNUSED(extension); return false; } /*! \internal */ void QGraphicsPathItem::setExtension(Extension extension, const QVariant &variant) { Q_UNUSED(extension); Q_UNUSED(variant); } /*! \internal */ QVariant QGraphicsPathItem::extension(const QVariant &variant) const { Q_UNUSED(variant); return QVariant(); } /*! \class QGraphicsRectItem \brief The QGraphicsRectItem class provides a rectangle item that you can add to a QGraphicsScene. \since 4.2 \ingroup graphicsview-api To set the item's rectangle, pass a QRectF to QGraphicsRectItem's constructor, or call the setRect() function. The rect() function returns the current rectangle. \image graphicsview-rectitem.png QGraphicsRectItem uses the rectangle and the pen width to provide a reasonable implementation of boundingRect(), shape(), and contains(). The paint() function draws the rectangle using the item's associated pen and brush, which you can set by calling the setPen() and setBrush() functions. \note The rendering of invalid rectangles, such as those with negative widths or heights, is undefined. If you cannot be sure that you are using valid rectangles (for example, if you are creating rectangles using data from an unreliable source) then you should use QRectF::normalized() to create normalized rectangles, and use those instead. \sa QGraphicsPathItem, QGraphicsEllipseItem, QGraphicsPolygonItem, QGraphicsTextItem, QGraphicsLineItem, QGraphicsPixmapItem, {Graphics View Framework} */ class QGraphicsRectItemPrivate : public QAbstractGraphicsShapeItemPrivate { Q_DECLARE_PUBLIC(QGraphicsRectItem) public: QRectF rect; }; /*! Constructs a QGraphicsRectItem, using \a rect as the default rectangle. \a parent is passed to QAbstractGraphicsShapeItem's constructor. \sa QGraphicsScene::addItem() */ QGraphicsRectItem::QGraphicsRectItem(const QRectF &rect, QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : QAbstractGraphicsShapeItem(*new QGraphicsRectItemPrivate, parent, scene) { setRect(rect); } /*! \fn QGraphicsRectItem::QGraphicsRectItem(qreal x, qreal y, qreal width, qreal height, QGraphicsItem *parent) Constructs a QGraphicsRectItem with a default rectangle defined by (\a x, \a y) and the given \a width and \a height. \a parent is passed to QAbstractGraphicsShapeItem's constructor. \sa QGraphicsScene::addItem() */ QGraphicsRectItem::QGraphicsRectItem(qreal x, qreal y, qreal w, qreal h, QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : QAbstractGraphicsShapeItem(*new QGraphicsRectItemPrivate, parent, scene) { setRect(QRectF(x, y, w, h)); } /*! Constructs a QGraphicsRectItem. \a parent is passed to QAbstractGraphicsShapeItem's constructor. \sa QGraphicsScene::addItem() */ QGraphicsRectItem::QGraphicsRectItem(QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : QAbstractGraphicsShapeItem(*new QGraphicsRectItemPrivate, parent, scene) { } /*! Destroys the QGraphicsRectItem. */ QGraphicsRectItem::~QGraphicsRectItem() { } /*! Returns the item's rectangle. \sa setRect() */ QRectF QGraphicsRectItem::rect() const { Q_D(const QGraphicsRectItem); return d->rect; } /*! \fn void QGraphicsRectItem::setRect(const QRectF &rectangle) Sets the item's rectangle to be the given \a rectangle. \sa rect() */ void QGraphicsRectItem::setRect(const QRectF &rect) { Q_D(QGraphicsRectItem); if (d->rect == rect) return; prepareGeometryChange(); d->rect = rect; d->boundingRect = QRectF(); update(); } /*! \fn void QGraphicsRectItem::setRect(qreal x, qreal y, qreal width, qreal height) \fn void QGraphicsEllipseItem::setRect(qreal x, qreal y, qreal width, qreal height) Sets the item's rectangle to the rectangle defined by (\a x, \a y) and the given \a width and \a height. This convenience function is equivalent to calling \c {setRect(QRectF(x, y, width, height))} \sa rect() */ /*! \reimp */ QRectF QGraphicsRectItem::boundingRect() const { Q_D(const QGraphicsRectItem); if (d->boundingRect.isNull()) { qreal halfpw = pen().widthF() / 2; d->boundingRect = d->rect; if (halfpw > 0.0) d->boundingRect.adjust(-halfpw, -halfpw, halfpw, halfpw); } return d->boundingRect; } /*! \reimp */ QPainterPath QGraphicsRectItem::shape() const { Q_D(const QGraphicsRectItem); QPainterPath path; path.addRect(d->rect); return qt_graphicsItem_shapeFromPath(path, d->pen); } /*! \reimp */ bool QGraphicsRectItem::contains(const QPointF &point) const { return QAbstractGraphicsShapeItem::contains(point); } /*! \reimp */ void QGraphicsRectItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_D(QGraphicsRectItem); Q_UNUSED(widget); painter->setPen(d->pen); painter->setBrush(d->brush); painter->drawRect(d->rect); if (option->state & QStyle::State_Selected) qt_graphicsItem_highlightSelected(this, painter, option); } /*! \reimp */ bool QGraphicsRectItem::isObscuredBy(const QGraphicsItem *item) const { return QAbstractGraphicsShapeItem::isObscuredBy(item); } /*! \reimp */ QPainterPath QGraphicsRectItem::opaqueArea() const { return QAbstractGraphicsShapeItem::opaqueArea(); } /*! \reimp */ int QGraphicsRectItem::type() const { return Type; } /*! \internal */ bool QGraphicsRectItem::supportsExtension(Extension extension) const { Q_UNUSED(extension); return false; } /*! \internal */ void QGraphicsRectItem::setExtension(Extension extension, const QVariant &variant) { Q_UNUSED(extension); Q_UNUSED(variant); } /*! \internal */ QVariant QGraphicsRectItem::extension(const QVariant &variant) const { Q_UNUSED(variant); return QVariant(); } /*! \class QGraphicsEllipseItem \brief The QGraphicsEllipseItem class provides an ellipse item that you can add to a QGraphicsScene. \since 4.2 \ingroup graphicsview-api QGraphicsEllipseItem respresents an ellipse with a fill and an outline, and you can also use it for ellipse segments (see startAngle(), spanAngle()). \table \row \o \inlineimage graphicsview-ellipseitem.png \o \inlineimage graphicsview-ellipseitem-pie.png \endtable To set the item's ellipse, pass a QRectF to QGraphicsEllipseItem's constructor, or call setRect(). The rect() function returns the current ellipse geometry. QGraphicsEllipseItem uses the rect and the pen width to provide a reasonable implementation of boundingRect(), shape(), and contains(). The paint() function draws the ellipse using the item's associated pen and brush, which you can set by calling setPen() and setBrush(). \sa QGraphicsPathItem, QGraphicsRectItem, QGraphicsPolygonItem, QGraphicsTextItem, QGraphicsLineItem, QGraphicsPixmapItem, {Graphics View Framework} */ class QGraphicsEllipseItemPrivate : public QAbstractGraphicsShapeItemPrivate { Q_DECLARE_PUBLIC(QGraphicsEllipseItem) public: inline QGraphicsEllipseItemPrivate() : startAngle(0), spanAngle(360 * 16) { } QRectF rect; int startAngle; int spanAngle; }; /*! Constructs a QGraphicsEllipseItem using \a rect as the default rectangle. \a parent is passed to QAbstractGraphicsShapeItem's constructor. \sa QGraphicsScene::addItem() */ QGraphicsEllipseItem::QGraphicsEllipseItem(const QRectF &rect, QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : QAbstractGraphicsShapeItem(*new QGraphicsEllipseItemPrivate, parent, scene) { setRect(rect); } /*! \fn QGraphicsEllipseItem::QGraphicsEllipseItem(qreal x, qreal y, qreal width, qreal height, QGraphicsItem *parent) \since 4.3 Constructs a QGraphicsEllipseItem using the rectangle defined by (\a x, \a y) and the given \a width and \a height, as the default rectangle. \a parent is passed to QAbstractGraphicsShapeItem's constructor. \sa QGraphicsScene::addItem() */ QGraphicsEllipseItem::QGraphicsEllipseItem(qreal x, qreal y, qreal w, qreal h, QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : QAbstractGraphicsShapeItem(*new QGraphicsEllipseItemPrivate, parent, scene) { setRect(x,y,w,h); } /*! Constructs a QGraphicsEllipseItem. \a parent is passed to QAbstractGraphicsShapeItem's constructor. \sa QGraphicsScene::addItem() */ QGraphicsEllipseItem::QGraphicsEllipseItem(QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : QAbstractGraphicsShapeItem(*new QGraphicsEllipseItemPrivate, parent, scene) { } /*! Destroys the QGraphicsEllipseItem. */ QGraphicsEllipseItem::~QGraphicsEllipseItem() { } /*! Returns the item's ellipse geometry as a QRectF. \sa setRect(), QPainter::drawEllipse() */ QRectF QGraphicsEllipseItem::rect() const { Q_D(const QGraphicsEllipseItem); return d->rect; } /*! Sets the item's ellipse geometry to \a rect. The rectangle's left edge defines the left edge of the ellipse, and the rectangle's top edge describes the top of the ellipse. The height and width of the rectangle describe the height and width of the ellipse. \sa rect(), QPainter::drawEllipse() */ void QGraphicsEllipseItem::setRect(const QRectF &rect) { Q_D(QGraphicsEllipseItem); if (d->rect == rect) return; prepareGeometryChange(); d->rect = rect; d->boundingRect = QRectF(); update(); } /*! Returns the start angle for an ellipse segment in 16ths of a degree. This angle is used together with spanAngle() for representing an ellipse segment (a pie). By default, the start angle is 0. \sa setStartAngle(), spanAngle() */ int QGraphicsEllipseItem::startAngle() const { Q_D(const QGraphicsEllipseItem); return d->startAngle; } /*! Sets the start angle for an ellipse segment to \a angle, which is in 16ths of a degree. This angle is used together with spanAngle() for representing an ellipse segment (a pie). By default, the start angle is 0. \sa startAngle(), setSpanAngle(), QPainter::drawPie() */ void QGraphicsEllipseItem::setStartAngle(int angle) { Q_D(QGraphicsEllipseItem); if (angle != d->startAngle) { prepareGeometryChange(); d->boundingRect = QRectF(); d->startAngle = angle; update(); } } /*! Returns the span angle of an ellipse segment in 16ths of a degree. This angle is used together with startAngle() for representing an ellipse segment (a pie). By default, this function returns 5760 (360 * 16, a full ellipse). \sa setSpanAngle(), startAngle() */ int QGraphicsEllipseItem::spanAngle() const { Q_D(const QGraphicsEllipseItem); return d->spanAngle; } /*! Sets the span angle for an ellipse segment to \a angle, which is in 16ths of a degree. This angle is used together with startAngle() to represent an ellipse segment (a pie). By default, the span angle is 5760 (360 * 16, a full ellipse). \sa spanAngle(), setStartAngle(), QPainter::drawPie() */ void QGraphicsEllipseItem::setSpanAngle(int angle) { Q_D(QGraphicsEllipseItem); if (angle != d->spanAngle) { prepareGeometryChange(); d->boundingRect = QRectF(); d->spanAngle = angle; update(); } } /*! \reimp */ QRectF QGraphicsEllipseItem::boundingRect() const { Q_D(const QGraphicsEllipseItem); if (d->boundingRect.isNull()) { qreal pw = pen().widthF(); if (pw == 0.0 && d->spanAngle == 360 * 16) d->boundingRect = d->rect; else d->boundingRect = shape().controlPointRect(); } return d->boundingRect; } /*! \reimp */ QPainterPath QGraphicsEllipseItem::shape() const { Q_D(const QGraphicsEllipseItem); QPainterPath path; if (d->rect.isNull()) return path; if (d->spanAngle != 360 * 16) { path.moveTo(d->rect.center()); path.arcTo(d->rect, d->startAngle / qreal(16.0), d->spanAngle / qreal(16.0)); } else { path.addEllipse(d->rect); } return qt_graphicsItem_shapeFromPath(path, d->pen); } /*! \reimp */ bool QGraphicsEllipseItem::contains(const QPointF &point) const { return QAbstractGraphicsShapeItem::contains(point); } /*! \reimp */ void QGraphicsEllipseItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_D(QGraphicsEllipseItem); Q_UNUSED(widget); painter->setPen(d->pen); painter->setBrush(d->brush); if ((d->spanAngle != 0) && (qAbs(d->spanAngle) % (360 * 16) == 0)) painter->drawEllipse(d->rect); else painter->drawPie(d->rect, d->startAngle, d->spanAngle); if (option->state & QStyle::State_Selected) qt_graphicsItem_highlightSelected(this, painter, option); } /*! \reimp */ bool QGraphicsEllipseItem::isObscuredBy(const QGraphicsItem *item) const { return QAbstractGraphicsShapeItem::isObscuredBy(item); } /*! \reimp */ QPainterPath QGraphicsEllipseItem::opaqueArea() const { return QAbstractGraphicsShapeItem::opaqueArea(); } /*! \reimp */ int QGraphicsEllipseItem::type() const { return Type; } /*! \internal */ bool QGraphicsEllipseItem::supportsExtension(Extension extension) const { Q_UNUSED(extension); return false; } /*! \internal */ void QGraphicsEllipseItem::setExtension(Extension extension, const QVariant &variant) { Q_UNUSED(extension); Q_UNUSED(variant); } /*! \internal */ QVariant QGraphicsEllipseItem::extension(const QVariant &variant) const { Q_UNUSED(variant); return QVariant(); } /*! \class QGraphicsPolygonItem \brief The QGraphicsPolygonItem class provides a polygon item that you can add to a QGraphicsScene. \since 4.2 \ingroup graphicsview-api To set the item's polygon, pass a QPolygonF to QGraphicsPolygonItem's constructor, or call the setPolygon() function. The polygon() function returns the current polygon. \image graphicsview-polygonitem.png QGraphicsPolygonItem uses the polygon and the pen width to provide a reasonable implementation of boundingRect(), shape(), and contains(). The paint() function draws the polygon using the item's associated pen and brush, which you can set by calling the setPen() and setBrush() functions. \sa QGraphicsPathItem, QGraphicsRectItem, QGraphicsEllipseItem, QGraphicsTextItem, QGraphicsLineItem, QGraphicsPixmapItem, {Graphics View Framework} */ class QGraphicsPolygonItemPrivate : public QAbstractGraphicsShapeItemPrivate { Q_DECLARE_PUBLIC(QGraphicsPolygonItem) public: inline QGraphicsPolygonItemPrivate() : fillRule(Qt::OddEvenFill) { } QPolygonF polygon; Qt::FillRule fillRule; }; /*! Constructs a QGraphicsPolygonItem with \a polygon as the default polygon. \a parent is passed to QAbstractGraphicsShapeItem's constructor. \sa QGraphicsScene::addItem() */ QGraphicsPolygonItem::QGraphicsPolygonItem(const QPolygonF &polygon, QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : QAbstractGraphicsShapeItem(*new QGraphicsPolygonItemPrivate, parent, scene) { setPolygon(polygon); } /*! Constructs a QGraphicsPolygonItem. \a parent is passed to QAbstractGraphicsShapeItem's constructor. \sa QGraphicsScene::addItem() */ QGraphicsPolygonItem::QGraphicsPolygonItem(QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : QAbstractGraphicsShapeItem(*new QGraphicsPolygonItemPrivate, parent, scene) { } /*! Destroys the QGraphicsPolygonItem. */ QGraphicsPolygonItem::~QGraphicsPolygonItem() { } /*! Returns the item's polygon, or an empty polygon if no polygon has been set. \sa setPolygon() */ QPolygonF QGraphicsPolygonItem::polygon() const { Q_D(const QGraphicsPolygonItem); return d->polygon; } /*! Sets the item's polygon to be the given \a polygon. \sa polygon() */ void QGraphicsPolygonItem::setPolygon(const QPolygonF &polygon) { Q_D(QGraphicsPolygonItem); if (d->polygon == polygon) return; prepareGeometryChange(); d->polygon = polygon; d->boundingRect = QRectF(); update(); } /*! Returns the fill rule of the polygon. The default fill rule is Qt::OddEvenFill. \sa setFillRule(), QPainterPath::fillRule(), QPainter::drawPolygon() */ Qt::FillRule QGraphicsPolygonItem::fillRule() const { Q_D(const QGraphicsPolygonItem); return d->fillRule; } /*! Sets the fill rule of the polygon to \a rule. The default fill rule is Qt::OddEvenFill. \sa fillRule(), QPainterPath::fillRule(), QPainter::drawPolygon() */ void QGraphicsPolygonItem::setFillRule(Qt::FillRule rule) { Q_D(QGraphicsPolygonItem); if (rule != d->fillRule) { d->fillRule = rule; update(); } } /*! \reimp */ QRectF QGraphicsPolygonItem::boundingRect() const { Q_D(const QGraphicsPolygonItem); if (d->boundingRect.isNull()) { qreal pw = pen().widthF(); if (pw == 0.0) d->boundingRect = d->polygon.boundingRect(); else d->boundingRect = shape().controlPointRect(); } return d->boundingRect; } /*! \reimp */ QPainterPath QGraphicsPolygonItem::shape() const { Q_D(const QGraphicsPolygonItem); QPainterPath path; path.addPolygon(d->polygon); return qt_graphicsItem_shapeFromPath(path, d->pen); } /*! \reimp */ bool QGraphicsPolygonItem::contains(const QPointF &point) const { return QAbstractGraphicsShapeItem::contains(point); } /*! \reimp */ void QGraphicsPolygonItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_D(QGraphicsPolygonItem); Q_UNUSED(widget); painter->setPen(d->pen); painter->setBrush(d->brush); painter->drawPolygon(d->polygon, d->fillRule); if (option->state & QStyle::State_Selected) qt_graphicsItem_highlightSelected(this, painter, option); } /*! \reimp */ bool QGraphicsPolygonItem::isObscuredBy(const QGraphicsItem *item) const { return QAbstractGraphicsShapeItem::isObscuredBy(item); } /*! \reimp */ QPainterPath QGraphicsPolygonItem::opaqueArea() const { return QAbstractGraphicsShapeItem::opaqueArea(); } /*! \reimp */ int QGraphicsPolygonItem::type() const { return Type; } /*! \internal */ bool QGraphicsPolygonItem::supportsExtension(Extension extension) const { Q_UNUSED(extension); return false; } /*! \internal */ void QGraphicsPolygonItem::setExtension(Extension extension, const QVariant &variant) { Q_UNUSED(extension); Q_UNUSED(variant); } /*! \internal */ QVariant QGraphicsPolygonItem::extension(const QVariant &variant) const { Q_UNUSED(variant); return QVariant(); } /*! \class QGraphicsLineItem \brief The QGraphicsLineItem class provides a line item that you can add to a QGraphicsScene. \since 4.2 \ingroup graphicsview-api To set the item's line, pass a QLineF to QGraphicsLineItem's constructor, or call the setLine() function. The line() function returns the current line. By default the line is black with a width of 0, but you can change this by calling setPen(). \img graphicsview-lineitem.png QGraphicsLineItem uses the line and the pen width to provide a reasonable implementation of boundingRect(), shape(), and contains(). The paint() function draws the line using the item's associated pen. \sa QGraphicsPathItem, QGraphicsRectItem, QGraphicsEllipseItem, QGraphicsTextItem, QGraphicsPolygonItem, QGraphicsPixmapItem, {Graphics View Framework} */ class QGraphicsLineItemPrivate : public QGraphicsItemPrivate { Q_DECLARE_PUBLIC(QGraphicsLineItem) public: QLineF line; QPen pen; }; /*! Constructs a QGraphicsLineItem, using \a line as the default line. \a parent is passed to QGraphicsItem's constructor. \sa QGraphicsScene::addItem() */ QGraphicsLineItem::QGraphicsLineItem(const QLineF &line, QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : QGraphicsItem(*new QGraphicsLineItemPrivate, parent, scene) { setLine(line); } /*! Constructs a QGraphicsLineItem, using the line between (\a x1, \a y1) and (\a x2, \a y2) as the default line. \a parent is passed to QGraphicsItem's constructor. \sa QGraphicsScene::addItem() */ QGraphicsLineItem::QGraphicsLineItem(qreal x1, qreal y1, qreal x2, qreal y2, QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : QGraphicsItem(*new QGraphicsLineItemPrivate, parent, scene) { setLine(x1, y1, x2, y2); } /*! Constructs a QGraphicsLineItem. \a parent is passed to QGraphicsItem's constructor. \sa QGraphicsScene::addItem() */ QGraphicsLineItem::QGraphicsLineItem(QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : QGraphicsItem(*new QGraphicsLineItemPrivate, parent, scene) { } /*! Destroys the QGraphicsLineItem. */ QGraphicsLineItem::~QGraphicsLineItem() { } /*! Returns the item's pen, or a black solid 0-width pen if no pen has been set. \sa setPen() */ QPen QGraphicsLineItem::pen() const { Q_D(const QGraphicsLineItem); return d->pen; } /*! Sets the item's pen to \a pen. If no pen is set, the line will be painted using a black solid 0-width pen. \sa pen() */ void QGraphicsLineItem::setPen(const QPen &pen) { Q_D(QGraphicsLineItem); if (d->pen == pen) return; prepareGeometryChange(); d->pen = pen; update(); } /*! Returns the item's line, or a null line if no line has been set. \sa setLine() */ QLineF QGraphicsLineItem::line() const { Q_D(const QGraphicsLineItem); return d->line; } /*! Sets the item's line to be the given \a line. \sa line() */ void QGraphicsLineItem::setLine(const QLineF &line) { Q_D(QGraphicsLineItem); if (d->line == line) return; prepareGeometryChange(); d->line = line; update(); } /*! \fn void QGraphicsLineItem::setLine(qreal x1, qreal y1, qreal x2, qreal y2) \overload Sets the item's line to be the line between (\a x1, \a y1) and (\a x2, \a y2). This is the same as calling \c {setLine(QLineF(x1, y1, x2, y2))}. */ /*! \reimp */ QRectF QGraphicsLineItem::boundingRect() const { Q_D(const QGraphicsLineItem); if (d->pen.widthF() == 0.0) { const qreal x1 = d->line.p1().x(); const qreal x2 = d->line.p2().x(); const qreal y1 = d->line.p1().y(); const qreal y2 = d->line.p2().y(); qreal lx = qMin(x1, x2); qreal rx = qMax(x1, x2); qreal ty = qMin(y1, y2); qreal by = qMax(y1, y2); return QRectF(lx, ty, rx - lx, by - ty); } return shape().controlPointRect(); } /*! \reimp */ QPainterPath QGraphicsLineItem::shape() const { Q_D(const QGraphicsLineItem); QPainterPath path; if (d->line == QLineF()) return path; path.moveTo(d->line.p1()); path.lineTo(d->line.p2()); return qt_graphicsItem_shapeFromPath(path, d->pen); } /*! \reimp */ bool QGraphicsLineItem::contains(const QPointF &point) const { return QGraphicsItem::contains(point); } /*! \reimp */ void QGraphicsLineItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_D(QGraphicsLineItem); Q_UNUSED(widget); painter->setPen(d->pen); painter->drawLine(d->line); if (option->state & QStyle::State_Selected) qt_graphicsItem_highlightSelected(this, painter, option); } /*! \reimp */ bool QGraphicsLineItem::isObscuredBy(const QGraphicsItem *item) const { return QGraphicsItem::isObscuredBy(item); } /*! \reimp */ QPainterPath QGraphicsLineItem::opaqueArea() const { return QGraphicsItem::opaqueArea(); } /*! \reimp */ int QGraphicsLineItem::type() const { return Type; } /*! \internal */ bool QGraphicsLineItem::supportsExtension(Extension extension) const { Q_UNUSED(extension); return false; } /*! \internal */ void QGraphicsLineItem::setExtension(Extension extension, const QVariant &variant) { Q_UNUSED(extension); Q_UNUSED(variant); } /*! \internal */ QVariant QGraphicsLineItem::extension(const QVariant &variant) const { Q_UNUSED(variant); return QVariant(); } /*! \class QGraphicsPixmapItem \brief The QGraphicsPixmapItem class provides a pixmap item that you can add to a QGraphicsScene. \since 4.2 \ingroup graphicsview-api To set the item's pixmap, pass a QPixmap to QGraphicsPixmapItem's constructor, or call the setPixmap() function. The pixmap() function returns the current pixmap. QGraphicsPixmapItem uses pixmap's optional alpha mask to provide a reasonable implementation of boundingRect(), shape(), and contains(). \image graphicsview-pixmapitem.png The pixmap is drawn at the item's (0, 0) coordinate, as returned by offset(). You can change the drawing offset by calling setOffset(). You can set the pixmap's transformation mode by calling setTransformationMode(). By default, Qt::FastTransformation is used, which provides fast, non-smooth scaling. Qt::SmoothTransformation enables QPainter::SmoothPixmapTransform on the painter, and the quality depends on the platform and viewport. The result is usually not as good as calling QPixmap::scale() directly. Call transformationMode() to get the current transformation mode for the item. \sa QGraphicsPathItem, QGraphicsRectItem, QGraphicsEllipseItem, QGraphicsTextItem, QGraphicsPolygonItem, QGraphicsLineItem, {Graphics View Framework} */ /*! \enum QGraphicsPixmapItem::ShapeMode This enum describes how QGraphicsPixmapItem calculates its shape and opaque area. The default value is MaskShape. \value MaskShape The shape is determined by calling QPixmap::mask(). This shape includes only the opaque pixels of the pixmap. Because the shape is more complex, however, it can be slower than the other modes, and uses more memory. \value BoundingRectShape The shape is determined by tracing the outline of the pixmap. This is the fastest shape mode, but it does not take into account any transparent areas on the pixmap. \value HeuristicMaskShape The shape is determine by calling QPixmap::createHeuristicMask(). The performance and memory consumption is similar to MaskShape. */ extern Q_AUTOTEST_EXPORT QPainterPath qt_regionToPath(const QRegion &region); class QGraphicsPixmapItemPrivate : public QGraphicsItemPrivate { Q_DECLARE_PUBLIC(QGraphicsPixmapItem) public: QGraphicsPixmapItemPrivate() : transformationMode(Qt::FastTransformation), shapeMode(QGraphicsPixmapItem::MaskShape), hasShape(false) {} QPixmap pixmap; Qt::TransformationMode transformationMode; QPointF offset; QGraphicsPixmapItem::ShapeMode shapeMode; QPainterPath shape; bool hasShape; void updateShape() { shape = QPainterPath(); switch (shapeMode) { case QGraphicsPixmapItem::MaskShape: { QBitmap mask = pixmap.mask(); if (!mask.isNull()) { shape = qt_regionToPath(QRegion(mask).translated(offset.toPoint())); break; } // FALL THROUGH } case QGraphicsPixmapItem::BoundingRectShape: shape.addRect(QRectF(offset.x(), offset.y(), pixmap.width(), pixmap.height())); break; case QGraphicsPixmapItem::HeuristicMaskShape: #ifndef QT_NO_IMAGE_HEURISTIC_MASK shape = qt_regionToPath(QRegion(pixmap.createHeuristicMask()).translated(offset.toPoint())); #else shape.addRect(QRectF(offset.x(), offset.y(), pixmap.width(), pixmap.height())); #endif break; } } }; /*! Constructs a QGraphicsPixmapItem, using \a pixmap as the default pixmap. \a parent is passed to QGraphicsItem's constructor. \sa QGraphicsScene::addItem() */ QGraphicsPixmapItem::QGraphicsPixmapItem(const QPixmap &pixmap, QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : QGraphicsItem(*new QGraphicsPixmapItemPrivate, parent, scene) { setPixmap(pixmap); } /*! Constructs a QGraphicsPixmapItem. \a parent is passed to QGraphicsItem's constructor. \sa QGraphicsScene::addItem() */ QGraphicsPixmapItem::QGraphicsPixmapItem(QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : QGraphicsItem(*new QGraphicsPixmapItemPrivate, parent, scene) { } /*! Destroys the QGraphicsPixmapItem. */ QGraphicsPixmapItem::~QGraphicsPixmapItem() { } /*! Sets the item's pixmap to \a pixmap. \sa pixmap() */ void QGraphicsPixmapItem::setPixmap(const QPixmap &pixmap) { Q_D(QGraphicsPixmapItem); prepareGeometryChange(); d->pixmap = pixmap; d->hasShape = false; update(); } /*! Returns the item's pixmap, or an invalid QPixmap if no pixmap has been set. \sa setPixmap() */ QPixmap QGraphicsPixmapItem::pixmap() const { Q_D(const QGraphicsPixmapItem); return d->pixmap; } /*! Returns the transformation mode of the pixmap. The default mode is Qt::FastTransformation, which provides quick transformation with no smoothing. \sa setTransformationMode() */ Qt::TransformationMode QGraphicsPixmapItem::transformationMode() const { Q_D(const QGraphicsPixmapItem); return d->transformationMode; } /*! Sets the pixmap item's transformation mode to \a mode, and toggles an update of the item. The default mode is Qt::FastTransformation, which provides quick transformation with no smoothing. Qt::SmoothTransformation enables QPainter::SmoothPixmapTransform on the painter, and the quality depends on the platform and viewport. The result is usually not as good as calling QPixmap::scale() directly. \sa transformationMode() */ void QGraphicsPixmapItem::setTransformationMode(Qt::TransformationMode mode) { Q_D(QGraphicsPixmapItem); if (mode != d->transformationMode) { d->transformationMode = mode; update(); } } /*! Returns the pixmap item's \e offset, which defines the point of the top-left corner of the pixmap, in local coordinates. \sa setOffset() */ QPointF QGraphicsPixmapItem::offset() const { Q_D(const QGraphicsPixmapItem); return d->offset; } /*! Sets the pixmap item's offset to \a offset. QGraphicsPixmapItem will draw its pixmap using \a offset for its top-left corner. \sa offset() */ void QGraphicsPixmapItem::setOffset(const QPointF &offset) { Q_D(QGraphicsPixmapItem); if (d->offset == offset) return; prepareGeometryChange(); d->offset = offset; d->hasShape = false; update(); } /*! \fn void QGraphicsPixmapItem::setOffset(qreal x, qreal y) \since 4.3 This convenience function is equivalent to calling setOffset(QPointF(\a x, \a y)). */ /*! \reimp */ QRectF QGraphicsPixmapItem::boundingRect() const { Q_D(const QGraphicsPixmapItem); if (d->pixmap.isNull()) return QRectF(); if (d->flags & ItemIsSelectable) { qreal pw = 1.0; return QRectF(d->offset, d->pixmap.size()).adjusted(-pw/2, -pw/2, pw/2, pw/2); } else { return QRectF(d->offset, d->pixmap.size()); } } /*! \reimp */ QPainterPath QGraphicsPixmapItem::shape() const { Q_D(const QGraphicsPixmapItem); if (!d->hasShape) { QGraphicsPixmapItemPrivate *thatD = const_cast<QGraphicsPixmapItemPrivate *>(d); thatD->updateShape(); thatD->hasShape = true; } return d_func()->shape; } /*! \reimp */ bool QGraphicsPixmapItem::contains(const QPointF &point) const { return QGraphicsItem::contains(point); } /*! \reimp */ void QGraphicsPixmapItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_D(QGraphicsPixmapItem); Q_UNUSED(widget); painter->setRenderHint(QPainter::SmoothPixmapTransform, (d->transformationMode == Qt::SmoothTransformation)); painter->drawPixmap(d->offset, d->pixmap); if (option->state & QStyle::State_Selected) qt_graphicsItem_highlightSelected(this, painter, option); } /*! \reimp */ bool QGraphicsPixmapItem::isObscuredBy(const QGraphicsItem *item) const { return QGraphicsItem::isObscuredBy(item); } /*! \reimp */ QPainterPath QGraphicsPixmapItem::opaqueArea() const { return shape(); } /*! \reimp */ int QGraphicsPixmapItem::type() const { return Type; } /*! Returns the item's shape mode. The shape mode describes how QGraphicsPixmapItem calculates its shape. The default mode is MaskShape. \sa setShapeMode(), ShapeMode */ QGraphicsPixmapItem::ShapeMode QGraphicsPixmapItem::shapeMode() const { return d_func()->shapeMode; } /*! Sets the item's shape mode to \a mode. The shape mode describes how QGraphicsPixmapItem calculates its shape. The default mode is MaskShape. \sa shapeMode(), ShapeMode */ void QGraphicsPixmapItem::setShapeMode(ShapeMode mode) { Q_D(QGraphicsPixmapItem); if (d->shapeMode == mode) return; d->shapeMode = mode; d->hasShape = false; } /*! \internal */ bool QGraphicsPixmapItem::supportsExtension(Extension extension) const { Q_UNUSED(extension); return false; } /*! \internal */ void QGraphicsPixmapItem::setExtension(Extension extension, const QVariant &variant) { Q_UNUSED(extension); Q_UNUSED(variant); } /*! \internal */ QVariant QGraphicsPixmapItem::extension(const QVariant &variant) const { Q_UNUSED(variant); return QVariant(); } /*! \class QGraphicsTextItem \brief The QGraphicsTextItem class provides a text item that you can add to a QGraphicsScene to display formatted text. \since 4.2 \ingroup graphicsview-api If you only need to show plain text in an item, consider using QGraphicsSimpleTextItem instead. To set the item's text, pass a QString to QGraphicsTextItem's constructor, or call setHtml()/setPlainText(). QGraphicsTextItem uses the text's formatted size and the associated font to provide a reasonable implementation of boundingRect(), shape(), and contains(). You can set the font by calling setFont(). It is possible to make the item editable by setting the Qt::TextEditorInteraction flag using setTextInteractionFlags(). The item's preferred text width can be set using setTextWidth() and obtained using textWidth(). \note In order to align HTML text in the center, the item's text width must be set. \img graphicsview-textitem.png \note QGraphicsTextItem accepts \l{QGraphicsItem::acceptHoverEvents()}{hover events} by default. You can change this with \l{QGraphicsItem::}{setAcceptHoverEvents()}. \sa QGraphicsSimpleTextItem, QGraphicsPathItem, QGraphicsRectItem, QGraphicsEllipseItem, QGraphicsPixmapItem, QGraphicsPolygonItem, QGraphicsLineItem, {Graphics View Framework} */ class QGraphicsTextItemPrivate { public: QGraphicsTextItemPrivate() : control(0), pageNumber(0), useDefaultImpl(false), tabChangesFocus(false), clickCausedFocus(0) { } mutable QTextControl *control; QTextControl *textControl() const; inline QPointF controlOffset() const { return QPointF(0., pageNumber * control->document()->pageSize().height()); } inline void sendControlEvent(QEvent *e) { if (control) control->processEvent(e, controlOffset()); } void _q_updateBoundingRect(const QSizeF &); void _q_update(QRectF); void _q_ensureVisible(QRectF); bool _q_mouseOnEdge(QGraphicsSceneMouseEvent *); QRectF boundingRect; int pageNumber; bool useDefaultImpl; bool tabChangesFocus; uint clickCausedFocus : 1; QGraphicsTextItem *qq; }; /*! Constructs a QGraphicsTextItem, using \a text as the default plain text. \a parent is passed to QGraphicsItem's constructor. \sa QGraphicsScene::addItem() */ QGraphicsTextItem::QGraphicsTextItem(const QString &text, QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : QGraphicsObject(*new QGraphicsItemPrivate, parent, scene), dd(new QGraphicsTextItemPrivate) { dd->qq = this; if (!text.isEmpty()) setPlainText(text); setAcceptDrops(true); setAcceptHoverEvents(true); setFlags(ItemUsesExtendedStyleOption); } /*! Constructs a QGraphicsTextItem. \a parent is passed to QGraphicsItem's constructor. \sa QGraphicsScene::addItem() */ QGraphicsTextItem::QGraphicsTextItem(QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : QGraphicsObject(*new QGraphicsItemPrivate, parent, scene), dd(new QGraphicsTextItemPrivate) { dd->qq = this; setAcceptDrops(true); setAcceptHoverEvents(true); setFlag(ItemUsesExtendedStyleOption); } /*! Destroys the QGraphicsTextItem. */ QGraphicsTextItem::~QGraphicsTextItem() { delete dd; } /*! Returns the item's text converted to HTML, or an empty QString if no text has been set. \sa setHtml() */ QString QGraphicsTextItem::toHtml() const { #ifndef QT_NO_TEXTHTMLPARSER if (dd->control) return dd->control->toHtml(); #endif return QString(); } /*! Sets the item's text to \a text, assuming that text is HTML formatted. If the item has keyboard input focus, this function will also call ensureVisible() to ensure that the text is visible in all viewports. \sa toHtml(), hasFocus(), QGraphicsSimpleTextItem */ void QGraphicsTextItem::setHtml(const QString &text) { dd->textControl()->setHtml(text); } /*! Returns the item's text converted to plain text, or an empty QString if no text has been set. \sa setPlainText() */ QString QGraphicsTextItem::toPlainText() const { if (dd->control) return dd->control->toPlainText(); return QString(); } /*! Sets the item's text to \a text. If the item has keyboard input focus, this function will also call ensureVisible() to ensure that the text is visible in all viewports. \sa toHtml(), hasFocus() */ void QGraphicsTextItem::setPlainText(const QString &text) { dd->textControl()->setPlainText(text); } /*! Returns the item's font, which is used to render the text. \sa setFont() */ QFont QGraphicsTextItem::font() const { if (!dd->control) return QFont(); return dd->control->document()->defaultFont(); } /*! Sets the font used to render the text item to \a font. \sa font() */ void QGraphicsTextItem::setFont(const QFont &font) { dd->textControl()->document()->setDefaultFont(font); } /*! Sets the color for unformatted text to \a col. */ void QGraphicsTextItem::setDefaultTextColor(const QColor &col) { QTextControl *c = dd->textControl(); QPalette pal = c->palette(); QColor old = pal.color(QPalette::Text); pal.setColor(QPalette::Text, col); c->setPalette(pal); if (old != col) update(); } /*! Returns the default text color that is used to for unformatted text. */ QColor QGraphicsTextItem::defaultTextColor() const { return dd->textControl()->palette().color(QPalette::Text); } /*! \reimp */ QRectF QGraphicsTextItem::boundingRect() const { return dd->boundingRect; } /*! \reimp */ QPainterPath QGraphicsTextItem::shape() const { if (!dd->control) return QPainterPath(); QPainterPath path; path.addRect(dd->boundingRect); return path; } /*! \reimp */ bool QGraphicsTextItem::contains(const QPointF &point) const { return dd->boundingRect.contains(point); } /*! \reimp */ void QGraphicsTextItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(widget); if (dd->control) { painter->save(); QRectF r = option->exposedRect; painter->translate(-dd->controlOffset()); r.translate(dd->controlOffset()); QTextDocument *doc = dd->control->document(); QTextDocumentLayout *layout = qobject_cast<QTextDocumentLayout *>(doc->documentLayout()); // the layout might need to expand the root frame to // the viewport if NoWrap is set if (layout) layout->setViewport(dd->boundingRect); dd->control->drawContents(painter, r); if (layout) layout->setViewport(QRect()); painter->restore(); } if (option->state & (QStyle::State_Selected | QStyle::State_HasFocus)) qt_graphicsItem_highlightSelected(this, painter, option); } /*! \reimp */ bool QGraphicsTextItem::isObscuredBy(const QGraphicsItem *item) const { return QGraphicsItem::isObscuredBy(item); } /*! \reimp */ QPainterPath QGraphicsTextItem::opaqueArea() const { return QGraphicsItem::opaqueArea(); } /*! \reimp */ int QGraphicsTextItem::type() const { return Type; } /*! Sets the preferred width for the item's text. If the actual text is wider than the specified width then it will be broken into multiple lines. If \a width is set to -1 then the text will not be broken into multiple lines unless it is enforced through an explicit line break or a new paragraph. The default value is -1. Note that QGraphicsTextItem keeps a QTextDocument internally, which is used to calculate the text width. \sa textWidth(), QTextDocument::setTextWidth() */ void QGraphicsTextItem::setTextWidth(qreal width) { dd->textControl()->setTextWidth(width); } /*! Returns the text width. The width is calculated with the QTextDocument that QGraphicsTextItem keeps internally. \sa setTextWidth(), QTextDocument::textWidth() */ qreal QGraphicsTextItem::textWidth() const { if (!dd->control) return -1; return dd->control->textWidth(); } /*! Adjusts the text item to a reasonable size. */ void QGraphicsTextItem::adjustSize() { if (dd->control) dd->control->adjustSize(); } /*! Sets the text document \a document on the item. */ void QGraphicsTextItem::setDocument(QTextDocument *document) { dd->textControl()->setDocument(document); dd->_q_updateBoundingRect(dd->control->size()); } /*! Returns the item's text document. */ QTextDocument *QGraphicsTextItem::document() const { return dd->textControl()->document(); } /*! \reimp */ bool QGraphicsTextItem::sceneEvent(QEvent *event) { QEvent::Type t = event->type(); if (!dd->tabChangesFocus && (t == QEvent::KeyPress || t == QEvent::KeyRelease)) { int k = ((QKeyEvent *)event)->key(); if (k == Qt::Key_Tab || k == Qt::Key_Backtab) { dd->sendControlEvent(event); return true; } } bool result = QGraphicsItem::sceneEvent(event); // Ensure input context is updated. switch (event->type()) { case QEvent::ContextMenu: case QEvent::FocusIn: case QEvent::FocusOut: case QEvent::GraphicsSceneDragEnter: case QEvent::GraphicsSceneDragLeave: case QEvent::GraphicsSceneDragMove: case QEvent::GraphicsSceneDrop: case QEvent::GraphicsSceneHoverEnter: case QEvent::GraphicsSceneHoverLeave: case QEvent::GraphicsSceneHoverMove: case QEvent::GraphicsSceneMouseDoubleClick: case QEvent::GraphicsSceneMousePress: case QEvent::GraphicsSceneMouseMove: case QEvent::GraphicsSceneMouseRelease: case QEvent::KeyPress: case QEvent::KeyRelease: // Reset the focus widget's input context, regardless // of how this item gained or lost focus. if (QWidget *fw = qApp->focusWidget()) { #ifndef QT_NO_IM if (QInputContext *qic = fw->inputContext()) { if (event->type() == QEvent::FocusIn || event->type() == QEvent::FocusOut) qic->reset(); else qic->update(); } #endif //QT_NO_IM } break; case QEvent::ShortcutOverride: dd->sendControlEvent(event); return true; default: break; } return result; } /*! \reimp */ void QGraphicsTextItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { if ((QGraphicsItem::d_ptr->flags & (ItemIsSelectable | ItemIsMovable)) && (event->buttons() & Qt::LeftButton) && dd->_q_mouseOnEdge(event)) { // User left-pressed on edge of selectable/movable item, use // base impl. dd->useDefaultImpl = true; } else if (event->buttons() == event->button() && dd->control->textInteractionFlags() == Qt::NoTextInteraction) { // User pressed first button on non-interactive item. dd->useDefaultImpl = true; } if (dd->useDefaultImpl) { QGraphicsItem::mousePressEvent(event); if (!event->isAccepted()) dd->useDefaultImpl = false; return; } dd->sendControlEvent(event); } /*! \reimp */ void QGraphicsTextItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { if (dd->useDefaultImpl) { QGraphicsItem::mouseMoveEvent(event); return; } dd->sendControlEvent(event); } /*! \reimp */ void QGraphicsTextItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { if (dd->useDefaultImpl) { QGraphicsItem::mouseReleaseEvent(event); if (dd->control->textInteractionFlags() == Qt::NoTextInteraction && !event->buttons()) { // User released last button on non-interactive item. dd->useDefaultImpl = false; } else if ((event->buttons() & Qt::LeftButton) == 0) { // User released the left button on an interactive item. dd->useDefaultImpl = false; } return; } QWidget *widget = event->widget(); if (widget && (dd->control->textInteractionFlags() & Qt::TextEditable) && boundingRect().contains(event->pos())) { qt_widget_private(widget)->handleSoftwareInputPanel(event->button(), dd->clickCausedFocus); } dd->clickCausedFocus = 0; dd->sendControlEvent(event); } /*! \reimp */ void QGraphicsTextItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) { if (dd->useDefaultImpl) { QGraphicsItem::mouseDoubleClickEvent(event); return; } if (!hasFocus()) { QGraphicsItem::mouseDoubleClickEvent(event); return; } dd->sendControlEvent(event); } /*! \reimp */ void QGraphicsTextItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) { dd->sendControlEvent(event); } /*! \reimp */ void QGraphicsTextItem::keyPressEvent(QKeyEvent *event) { dd->sendControlEvent(event); } /*! \reimp */ void QGraphicsTextItem::keyReleaseEvent(QKeyEvent *event) { dd->sendControlEvent(event); } /*! \reimp */ void QGraphicsTextItem::focusInEvent(QFocusEvent *event) { dd->sendControlEvent(event); if (event->reason() == Qt::MouseFocusReason) { dd->clickCausedFocus = 1; } update(); } /*! \reimp */ void QGraphicsTextItem::focusOutEvent(QFocusEvent *event) { dd->sendControlEvent(event); update(); } /*! \reimp */ void QGraphicsTextItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event) { dd->sendControlEvent(event); } /*! \reimp */ void QGraphicsTextItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event) { dd->sendControlEvent(event); } /*! \reimp */ void QGraphicsTextItem::dragMoveEvent(QGraphicsSceneDragDropEvent *event) { dd->sendControlEvent(event); } /*! \reimp */ void QGraphicsTextItem::dropEvent(QGraphicsSceneDragDropEvent *event) { dd->sendControlEvent(event); } /*! \reimp */ void QGraphicsTextItem::inputMethodEvent(QInputMethodEvent *event) { dd->sendControlEvent(event); } /*! \reimp */ void QGraphicsTextItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { dd->sendControlEvent(event); } /*! \reimp */ void QGraphicsTextItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) { dd->sendControlEvent(event); } /*! \reimp */ void QGraphicsTextItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { dd->sendControlEvent(event); } /*! \reimp */ QVariant QGraphicsTextItem::inputMethodQuery(Qt::InputMethodQuery query) const { QVariant v; if (dd->control) v = dd->control->inputMethodQuery(query); if (v.type() == QVariant::RectF) v = v.toRectF().translated(-dd->controlOffset()); else if (v.type() == QVariant::PointF) v = v.toPointF() - dd->controlOffset(); else if (v.type() == QVariant::Rect) v = v.toRect().translated(-dd->controlOffset().toPoint()); else if (v.type() == QVariant::Point) v = v.toPoint() - dd->controlOffset().toPoint(); return v; } /*! \internal */ bool QGraphicsTextItem::supportsExtension(Extension extension) const { Q_UNUSED(extension); return false; } /*! \internal */ void QGraphicsTextItem::setExtension(Extension extension, const QVariant &variant) { Q_UNUSED(extension); Q_UNUSED(variant); } /*! \internal */ QVariant QGraphicsTextItem::extension(const QVariant &variant) const { Q_UNUSED(variant); return QVariant(); } /*! \internal */ void QGraphicsTextItemPrivate::_q_update(QRectF rect) { if (rect.isValid()) { rect.translate(-controlOffset()); } else { rect = boundingRect; } if (rect.intersects(boundingRect)) qq->update(rect); } /*! \internal */ void QGraphicsTextItemPrivate::_q_updateBoundingRect(const QSizeF &size) { if (!control) return; // can't happen const QSizeF pageSize = control->document()->pageSize(); // paged items have a constant (page) size if (size == boundingRect.size() || pageSize.height() != -1) return; qq->prepareGeometryChange(); boundingRect.setSize(size); qq->update(); } /*! \internal */ void QGraphicsTextItemPrivate::_q_ensureVisible(QRectF rect) { if (qq->hasFocus()) { rect.translate(-controlOffset()); qq->ensureVisible(rect, /*xmargin=*/0, /*ymargin=*/0); } } QTextControl *QGraphicsTextItemPrivate::textControl() const { if (!control) { QGraphicsTextItem *that = const_cast<QGraphicsTextItem *>(qq); control = new QTextControl(that); control->setTextInteractionFlags(Qt::NoTextInteraction); QObject::connect(control, SIGNAL(updateRequest(QRectF)), qq, SLOT(_q_update(QRectF))); QObject::connect(control, SIGNAL(documentSizeChanged(QSizeF)), qq, SLOT(_q_updateBoundingRect(QSizeF))); QObject::connect(control, SIGNAL(visibilityRequest(QRectF)), qq, SLOT(_q_ensureVisible(QRectF))); QObject::connect(control, SIGNAL(linkActivated(QString)), qq, SIGNAL(linkActivated(QString))); QObject::connect(control, SIGNAL(linkHovered(QString)), qq, SIGNAL(linkHovered(QString))); const QSizeF pgSize = control->document()->pageSize(); if (pgSize.height() != -1) { qq->prepareGeometryChange(); that->dd->boundingRect.setSize(pgSize); qq->update(); } else { that->dd->_q_updateBoundingRect(control->size()); } } return control; } /*! \internal */ bool QGraphicsTextItemPrivate::_q_mouseOnEdge(QGraphicsSceneMouseEvent *event) { QPainterPath path; path.addRect(qq->boundingRect()); QPainterPath docPath; const QTextFrameFormat format = control->document()->rootFrame()->frameFormat(); docPath.addRect( qq->boundingRect().adjusted( format.leftMargin(), format.topMargin(), -format.rightMargin(), -format.bottomMargin())); return path.subtracted(docPath).contains(event->pos()); } /*! \fn QGraphicsTextItem::linkActivated(const QString &link) This signal is emitted when the user clicks on a link on a text item that enables Qt::LinksAccessibleByMouse or Qt::LinksAccessibleByKeyboard. \a link is the link that was clicked. \sa setTextInteractionFlags() */ /*! \fn QGraphicsTextItem::linkHovered(const QString &link) This signal is emitted when the user hovers over a link on a text item that enables Qt::LinksAccessibleByMouse. \a link is the link that was hovered over. \sa setTextInteractionFlags() */ /*! Sets the flags \a flags to specify how the text item should react to user input. The default for a QGraphicsTextItem is Qt::NoTextInteraction. This function also affects the ItemIsFocusable QGraphicsItem flag by setting it if \a flags is different from Qt::NoTextInteraction and clearing it otherwise. By default, the text is read-only. To transform the item into an editor, set the Qt::TextEditable flag. */ void QGraphicsTextItem::setTextInteractionFlags(Qt::TextInteractionFlags flags) { if (flags == Qt::NoTextInteraction) setFlags(this->flags() & ~(QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemAcceptsInputMethod)); else setFlags(this->flags() | QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemAcceptsInputMethod); dd->textControl()->setTextInteractionFlags(flags); } /*! Returns the current text interaction flags. \sa setTextInteractionFlags() */ Qt::TextInteractionFlags QGraphicsTextItem::textInteractionFlags() const { if (!dd->control) return Qt::NoTextInteraction; return dd->control->textInteractionFlags(); } /*! \since 4.5 If \a b is true, the \gui Tab key will cause the widget to change focus; otherwise, the tab key will insert a tab into the document. In some occasions text edits should not allow the user to input tabulators or change indentation using the \gui Tab key, as this breaks the focus chain. The default is false. \sa tabChangesFocus(), ItemIsFocusable, textInteractionFlags() */ void QGraphicsTextItem::setTabChangesFocus(bool b) { dd->tabChangesFocus = b; } /*! \since 4.5 Returns true if the \gui Tab key will cause the widget to change focus; otherwise, false is returned. By default, this behavior is disabled, and this function will return false. \sa setTabChangesFocus() */ bool QGraphicsTextItem::tabChangesFocus() const { return dd->tabChangesFocus; } /*! \property QGraphicsTextItem::openExternalLinks Specifies whether QGraphicsTextItem should automatically open links using QDesktopServices::openUrl() instead of emitting the linkActivated signal. The default value is false. */ void QGraphicsTextItem::setOpenExternalLinks(bool open) { dd->textControl()->setOpenExternalLinks(open); } bool QGraphicsTextItem::openExternalLinks() const { if (!dd->control) return false; return dd->control->openExternalLinks(); } /*! \property QGraphicsTextItem::textCursor This property represents the visible text cursor in an editable text item. By default, if the item's text has not been set, this property contains a null text cursor; otherwise it contains a text cursor placed at the start of the item's document. */ void QGraphicsTextItem::setTextCursor(const QTextCursor &cursor) { dd->textControl()->setTextCursor(cursor); } QTextCursor QGraphicsTextItem::textCursor() const { if (!dd->control) return QTextCursor(); return dd->control->textCursor(); } class QGraphicsSimpleTextItemPrivate : public QAbstractGraphicsShapeItemPrivate { Q_DECLARE_PUBLIC(QGraphicsSimpleTextItem) public: inline QGraphicsSimpleTextItemPrivate() { pen.setStyle(Qt::NoPen); brush.setStyle(Qt::SolidPattern); } QString text; QFont font; QRectF boundingRect; void updateBoundingRect(); }; static QRectF setupTextLayout(QTextLayout *layout) { layout->setCacheEnabled(true); layout->beginLayout(); while (layout->createLine().isValid()) ; layout->endLayout(); qreal maxWidth = 0; qreal y = 0; for (int i = 0; i < layout->lineCount(); ++i) { QTextLine line = layout->lineAt(i); maxWidth = qMax(maxWidth, line.naturalTextWidth()); line.setPosition(QPointF(0, y)); y += line.height(); } return QRectF(0, 0, maxWidth, y); } void QGraphicsSimpleTextItemPrivate::updateBoundingRect() { Q_Q(QGraphicsSimpleTextItem); QRectF br; if (text.isEmpty()) { br = QRectF(); } else { QString tmp = text; tmp.replace(QLatin1Char('\n'), QChar::LineSeparator); QStackTextEngine engine(tmp, font); QTextLayout layout(&engine); br = setupTextLayout(&layout); } if (br != boundingRect) { q->prepareGeometryChange(); boundingRect = br; q->update(); } } /*! \class QGraphicsSimpleTextItem \brief The QGraphicsSimpleTextItem class provides a simple text path item that you can add to a QGraphicsScene. \since 4.2 \ingroup graphicsview-api To set the item's text, you can either pass a QString to QGraphicsSimpleTextItem's constructor, or call setText() to change the text later. To set the text fill color, call setBrush(). The simple text item can have both a fill and an outline; setBrush() will set the text fill (i.e., text color), and setPen() sets the pen that will be used to draw the text outline. (The latter can be slow, especially for complex pens, and items with long text content.) If all you want is to draw a simple line of text, you should call setBrush() only, and leave the pen unset; QGraphicsSimpleTextItem's pen is by default Qt::NoPen. QGraphicsSimpleTextItem uses the text's formatted size and the associated font to provide a reasonable implementation of boundingRect(), shape(), and contains(). You can set the font by calling setFont(). QGraphicsSimpleText does not display rich text; instead, you can use QGraphicsTextItem, which provides full text control capabilities. \img graphicsview-simpletextitem.png \sa QGraphicsTextItem, QGraphicsPathItem, QGraphicsRectItem, QGraphicsEllipseItem, QGraphicsPixmapItem, QGraphicsPolygonItem, QGraphicsLineItem, {Graphics View Framework} */ /*! Constructs a QGraphicsSimpleTextItem. \a parent is passed to QGraphicsItem's constructor. \sa QGraphicsScene::addItem() */ QGraphicsSimpleTextItem::QGraphicsSimpleTextItem(QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : QAbstractGraphicsShapeItem(*new QGraphicsSimpleTextItemPrivate, parent, scene) { } /*! Constructs a QGraphicsSimpleTextItem, using \a text as the default plain text. \a parent is passed to QGraphicsItem's constructor. \sa QGraphicsScene::addItem() */ QGraphicsSimpleTextItem::QGraphicsSimpleTextItem(const QString &text, QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : QAbstractGraphicsShapeItem(*new QGraphicsSimpleTextItemPrivate, parent, scene) { setText(text); } /*! Destroys the QGraphicsSimpleTextItem. */ QGraphicsSimpleTextItem::~QGraphicsSimpleTextItem() { } /*! Sets the item's text to \a text. The text will be displayed as plain text. Newline characters ('\n') as well as characters of type QChar::LineSeparator will cause item to break the text into multiple lines. */ void QGraphicsSimpleTextItem::setText(const QString &text) { Q_D(QGraphicsSimpleTextItem); if (d->text == text) return; d->text = text; d->updateBoundingRect(); update(); } /*! Returns the item's text. */ QString QGraphicsSimpleTextItem::text() const { Q_D(const QGraphicsSimpleTextItem); return d->text; } /*! Sets the font that is used to draw the item's text to \a font. */ void QGraphicsSimpleTextItem::setFont(const QFont &font) { Q_D(QGraphicsSimpleTextItem); d->font = font; d->updateBoundingRect(); } /*! Returns the font that is used to draw the item's text. */ QFont QGraphicsSimpleTextItem::font() const { Q_D(const QGraphicsSimpleTextItem); return d->font; } /*! \reimp */ QRectF QGraphicsSimpleTextItem::boundingRect() const { Q_D(const QGraphicsSimpleTextItem); return d->boundingRect; } /*! \reimp */ QPainterPath QGraphicsSimpleTextItem::shape() const { Q_D(const QGraphicsSimpleTextItem); QPainterPath path; path.addRect(d->boundingRect); return path; } /*! \reimp */ bool QGraphicsSimpleTextItem::contains(const QPointF &point) const { Q_D(const QGraphicsSimpleTextItem); return d->boundingRect.contains(point); } /*! \reimp */ void QGraphicsSimpleTextItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(widget); Q_D(QGraphicsSimpleTextItem); painter->setFont(d->font); QString tmp = d->text; tmp.replace(QLatin1Char('\n'), QChar::LineSeparator); QStackTextEngine engine(tmp, d->font); QTextLayout layout(&engine); setupTextLayout(&layout); QPen p; p.setBrush(d->brush); painter->setPen(p); if (d->pen.style() == Qt::NoPen && d->brush.style() == Qt::SolidPattern) { painter->setBrush(Qt::NoBrush); } else { QTextLayout::FormatRange range; range.start = 0; range.length = layout.text().length(); range.format.setTextOutline(d->pen); QList<QTextLayout::FormatRange> formats; formats.append(range); layout.setAdditionalFormats(formats); } layout.draw(painter, QPointF(0, 0)); if (option->state & (QStyle::State_Selected | QStyle::State_HasFocus)) qt_graphicsItem_highlightSelected(this, painter, option); } /*! \reimp */ bool QGraphicsSimpleTextItem::isObscuredBy(const QGraphicsItem *item) const { return QAbstractGraphicsShapeItem::isObscuredBy(item); } /*! \reimp */ QPainterPath QGraphicsSimpleTextItem::opaqueArea() const { return QAbstractGraphicsShapeItem::opaqueArea(); } /*! \reimp */ int QGraphicsSimpleTextItem::type() const { return Type; } /*! \internal */ bool QGraphicsSimpleTextItem::supportsExtension(Extension extension) const { Q_UNUSED(extension); return false; } /*! \internal */ void QGraphicsSimpleTextItem::setExtension(Extension extension, const QVariant &variant) { Q_UNUSED(extension); Q_UNUSED(variant); } /*! \internal */ QVariant QGraphicsSimpleTextItem::extension(const QVariant &variant) const { Q_UNUSED(variant); return QVariant(); } /*! \class QGraphicsItemGroup \brief The QGraphicsItemGroup class provides a container that treats a group of items as a single item. \since 4.2 \ingroup graphicsview-api A QGraphicsItemGroup is a special type of compound item that treats itself and all its children as one item (i.e., all events and geometries for all children are merged together). It's common to use item groups in presentation tools, when the user wants to group several smaller items into one big item in order to simplify moving and copying of items. If all you want is to store items inside other items, you can use any QGraphicsItem directly by passing a suitable parent to setParentItem(). The boundingRect() function of QGraphicsItemGroup returns the bounding rectangle of all items in the item group. QGraphicsItemGroup ignores the ItemIgnoresTransformations flag on its children (i.e., with respect to the geometry of the group item, the children are treated as if they were transformable). There are two ways to construct an item group. The easiest and most common approach is to pass a list of items (e.g., all selected items) to QGraphicsScene::createItemGroup(), which returns a new QGraphicsItemGroup item. The other approach is to manually construct a QGraphicsItemGroup item, add it to the scene calling QGraphicsScene::addItem(), and then add items to the group manually, one at a time by calling addToGroup(). To dismantle ("ungroup") an item group, you can either call QGraphicsScene::destroyItemGroup(), or you can manually remove all items from the group by calling removeFromGroup(). \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 17 The operation of adding and removing items preserves the items' scene-relative position and transformation, as opposed to calling setParentItem(), where only the child item's parent-relative position and transformation are kept. The addtoGroup() function reparents the target item to this item group, keeping the item's position and transformation intact relative to the scene. Visually, this means that items added via addToGroup() will remain completely unchanged as a result of this operation, regardless of the item or the group's current position or transformation; although the item's position and matrix are likely to change. The removeFromGroup() function has similar semantics to setParentItem(); it reparents the item to the parent item of the item group. As with addToGroup(), the item's scene-relative position and transformation remain intact. \sa QGraphicsItem, {Graphics View Framework} */ class QGraphicsItemGroupPrivate : public QGraphicsItemPrivate { public: QRectF itemsBoundingRect; }; /*! Constructs a QGraphicsItemGroup. \a parent is passed to QGraphicsItem's constructor. \sa QGraphicsScene::addItem() */ QGraphicsItemGroup::QGraphicsItemGroup(QGraphicsItem *parent #ifndef Q_QDOC // obsolete argument , QGraphicsScene *scene #endif ) : QGraphicsItem(*new QGraphicsItemGroupPrivate, parent, scene) { setHandlesChildEvents(true); } /*! Destroys the QGraphicsItemGroup. */ QGraphicsItemGroup::~QGraphicsItemGroup() { } /*! Adds the given \a item and item's child items to this item group. The item and child items will be reparented to this group, but its position and transformation relative to the scene will stay intact. \sa removeFromGroup(), QGraphicsScene::createItemGroup() */ void QGraphicsItemGroup::addToGroup(QGraphicsItem *item) { Q_D(QGraphicsItemGroup); if (!item) { qWarning("QGraphicsItemGroup::addToGroup: cannot add null item"); return; } if (item == this) { qWarning("QGraphicsItemGroup::addToGroup: cannot add a group to itself"); return; } // COMBINE bool ok; QTransform itemTransform = item->itemTransform(this, &ok); if (!ok) { qWarning("QGraphicsItemGroup::addToGroup: could not find a valid transformation from item to group coordinates"); return; } QTransform newItemTransform(itemTransform); item->setPos(mapFromItem(item, 0, 0)); item->setParentItem(this); // removing position from translation component of the new transform if (!item->pos().isNull()) newItemTransform *= QTransform::fromTranslate(-item->x(), -item->y()); // removing additional transformations properties applied with itemTransform() QPointF origin = item->transformOriginPoint(); QMatrix4x4 m; QList<QGraphicsTransform*> transformList = item->transformations(); for (int i = 0; i < transformList.size(); ++i) transformList.at(i)->applyTo(&m); newItemTransform *= m.toTransform().inverted(); newItemTransform.translate(origin.x(), origin.y()); newItemTransform.rotate(-item->rotation()); newItemTransform.scale(1/item->scale(), 1/item->scale()); newItemTransform.translate(-origin.x(), -origin.y()); // ### Expensive, we could maybe use dirtySceneTransform bit for optimization item->setTransform(newItemTransform); item->d_func()->setIsMemberOfGroup(true); prepareGeometryChange(); d->itemsBoundingRect |= itemTransform.mapRect(item->boundingRect() | item->childrenBoundingRect()); update(); } /*! Removes the specified \a item from this group. The item will be reparented to this group's parent item, or to 0 if this group has no parent. Its position and transformation relative to the scene will stay intact. \sa addToGroup(), QGraphicsScene::destroyItemGroup() */ void QGraphicsItemGroup::removeFromGroup(QGraphicsItem *item) { Q_D(QGraphicsItemGroup); if (!item) { qWarning("QGraphicsItemGroup::removeFromGroup: cannot remove null item"); return; } QGraphicsItem *newParent = d_ptr->parent; // COMBINE bool ok; QTransform itemTransform; if (newParent) itemTransform = item->itemTransform(newParent, &ok); else itemTransform = item->sceneTransform(); QPointF oldPos = item->mapToItem(newParent, 0, 0); item->setParentItem(newParent); item->setPos(oldPos); // removing position from translation component of the new transform if (!item->pos().isNull()) itemTransform *= QTransform::fromTranslate(-item->x(), -item->y()); // removing additional transformations properties applied // with itemTransform() or sceneTransform() QPointF origin = item->transformOriginPoint(); QMatrix4x4 m; QList<QGraphicsTransform*> transformList = item->transformations(); for (int i = 0; i < transformList.size(); ++i) transformList.at(i)->applyTo(&m); itemTransform *= m.toTransform().inverted(); itemTransform.translate(origin.x(), origin.y()); itemTransform.rotate(-item->rotation()); itemTransform.scale(1 / item->scale(), 1 / item->scale()); itemTransform.translate(-origin.x(), -origin.y()); // ### Expensive, we could maybe use dirtySceneTransform bit for optimization item->setTransform(itemTransform); item->d_func()->setIsMemberOfGroup(item->group() != 0); // ### Quite expensive. But removeFromGroup() isn't called very often. prepareGeometryChange(); d->itemsBoundingRect = childrenBoundingRect(); } /*! \reimp Returns the bounding rect of this group item, and all its children. */ QRectF QGraphicsItemGroup::boundingRect() const { Q_D(const QGraphicsItemGroup); return d->itemsBoundingRect; } /*! \reimp */ void QGraphicsItemGroup::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(widget); if (option->state & QStyle::State_Selected) { Q_D(QGraphicsItemGroup); painter->setBrush(Qt::NoBrush); painter->drawRect(d->itemsBoundingRect); } } /*! \reimp */ bool QGraphicsItemGroup::isObscuredBy(const QGraphicsItem *item) const { return QGraphicsItem::isObscuredBy(item); } /*! \reimp */ QPainterPath QGraphicsItemGroup::opaqueArea() const { return QGraphicsItem::opaqueArea(); } /*! \reimp */ int QGraphicsItemGroup::type() const { return Type; } #ifndef QT_NO_GRAPHICSEFFECT QRectF QGraphicsItemEffectSourcePrivate::boundingRect(Qt::CoordinateSystem system) const { const bool deviceCoordinates = (system == Qt::DeviceCoordinates); if (!info && deviceCoordinates) { // Device coordinates without info not yet supported. qWarning("QGraphicsEffectSource::boundingRect: Not yet implemented, lacking device context"); return QRectF(); } QRectF rect = item->boundingRect(); if (!item->d_ptr->children.isEmpty()) rect |= item->childrenBoundingRect(); if (deviceCoordinates) { Q_ASSERT(info->painter); rect = info->painter->worldTransform().mapRect(rect); } return rect; } void QGraphicsItemEffectSourcePrivate::draw(QPainter *painter) { if (!info) { qWarning("QGraphicsEffectSource::draw: Can only begin as a result of QGraphicsEffect::draw"); return; } Q_ASSERT(item->d_ptr->scene); QGraphicsScenePrivate *scened = item->d_ptr->scene->d_func(); if (painter == info->painter) { scened->draw(item, painter, info->viewTransform, info->transformPtr, info->exposedRegion, info->widget, info->opacity, info->effectTransform, info->wasDirtySceneTransform, info->drawItem); } else { QTransform effectTransform = info->painter->worldTransform().inverted(); effectTransform *= painter->worldTransform(); scened->draw(item, painter, info->viewTransform, info->transformPtr, info->exposedRegion, info->widget, info->opacity, &effectTransform, info->wasDirtySceneTransform, info->drawItem); } } // sourceRect must be in the given coordinate system QRect QGraphicsItemEffectSourcePrivate::paddedEffectRect(Qt::CoordinateSystem system, QGraphicsEffect::PixmapPadMode mode, const QRectF &sourceRect, bool *unpadded) const { QRectF effectRectF; if (unpadded) *unpadded = false; if (mode == QGraphicsEffect::PadToEffectiveBoundingRect) { if (info) { QRectF deviceRect = system == Qt::DeviceCoordinates ? sourceRect : info->painter->worldTransform().mapRect(sourceRect); effectRectF = item->graphicsEffect()->boundingRectFor(deviceRect); if (unpadded) *unpadded = (effectRectF.size() == sourceRect.size()); if (info && system == Qt::LogicalCoordinates) effectRectF = info->painter->worldTransform().inverted().mapRect(effectRectF); } else { // no choice but to send a logical coordinate bounding rect to boundingRectFor effectRectF = item->graphicsEffect()->boundingRectFor(sourceRect); } } else if (mode == QGraphicsEffect::PadToTransparentBorder) { // adjust by 1.5 to account for cosmetic pens effectRectF = sourceRect.adjusted(-1.5, -1.5, 1.5, 1.5); } else { effectRectF = sourceRect; if (unpadded) *unpadded = true; } return effectRectF.toAlignedRect(); } QPixmap QGraphicsItemEffectSourcePrivate::pixmap(Qt::CoordinateSystem system, QPoint *offset, QGraphicsEffect::PixmapPadMode mode) const { const bool deviceCoordinates = (system == Qt::DeviceCoordinates); if (!info && deviceCoordinates) { // Device coordinates without info not yet supported. qWarning("QGraphicsEffectSource::pixmap: Not yet implemented, lacking device context"); return QPixmap(); } if (!item->d_ptr->scene) return QPixmap(); QGraphicsScenePrivate *scened = item->d_ptr->scene->d_func(); bool unpadded; const QRectF sourceRect = boundingRect(system); QRect effectRect = paddedEffectRect(system, mode, sourceRect, &unpadded); if (offset) *offset = effectRect.topLeft(); bool untransformed = !deviceCoordinates || info->painter->worldTransform().type() <= QTransform::TxTranslate; if (untransformed && unpadded && isPixmap()) { if (offset) *offset = boundingRect(system).topLeft().toPoint(); return static_cast<QGraphicsPixmapItem *>(item)->pixmap(); } if (effectRect.isEmpty()) return QPixmap(); QPixmap pixmap(effectRect.size()); pixmap.fill(Qt::transparent); QPainter pixmapPainter(&pixmap); pixmapPainter.setRenderHints(info ? info->painter->renderHints() : QPainter::TextAntialiasing); QTransform effectTransform = QTransform::fromTranslate(-effectRect.x(), -effectRect.y()); if (deviceCoordinates && info->effectTransform) effectTransform *= *info->effectTransform; if (!info) { // Logical coordinates without info. QTransform sceneTransform = item->sceneTransform(); QTransform newEffectTransform = sceneTransform.inverted(); newEffectTransform *= effectTransform; scened->draw(item, &pixmapPainter, 0, &sceneTransform, 0, 0, qreal(1.0), &newEffectTransform, false, true); } else if (deviceCoordinates) { // Device coordinates with info. scened->draw(item, &pixmapPainter, info->viewTransform, info->transformPtr, 0, info->widget, info->opacity, &effectTransform, info->wasDirtySceneTransform, info->drawItem); } else { // Item coordinates with info. QTransform newEffectTransform = info->transformPtr->inverted(); newEffectTransform *= effectTransform; scened->draw(item, &pixmapPainter, info->viewTransform, info->transformPtr, 0, info->widget, info->opacity, &newEffectTransform, info->wasDirtySceneTransform, info->drawItem); } pixmapPainter.end(); return pixmap; } #endif //QT_NO_GRAPHICSEFFECT #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug debug, QGraphicsItem *item) { if (!item) { debug << "QGraphicsItem(0)"; return debug; } if (QGraphicsObject *o = item->toGraphicsObject()) debug << o->metaObject()->className(); else debug << "QGraphicsItem"; debug << "(this =" << (void*)item << ", parent =" << (void*)item->parentItem() << ", pos =" << item->pos() << ", z =" << item->zValue() << ", flags = " << item->flags() << ")"; return debug; } QDebug operator<<(QDebug debug, QGraphicsObject *item) { if (!item) { debug << "QGraphicsObject(0)"; return debug; } debug.nospace() << item->metaObject()->className() << '(' << (void*)item; if (!item->objectName().isEmpty()) debug << ", name = " << item->objectName(); debug.nospace() << ", parent = " << ((void*)item->parentItem()) << ", pos = " << item->pos() << ", z = " << item->zValue() << ", flags = " << item->flags() << ')'; return debug.space(); } QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemChange change) { const char *str = "UnknownChange"; switch (change) { case QGraphicsItem::ItemChildAddedChange: str = "ItemChildAddedChange"; break; case QGraphicsItem::ItemChildRemovedChange: str = "ItemChildRemovedChange"; break; case QGraphicsItem::ItemCursorChange: str = "ItemCursorChange"; break; case QGraphicsItem::ItemCursorHasChanged: str = "ItemCursorHasChanged"; break; case QGraphicsItem::ItemEnabledChange: str = "ItemEnabledChange"; break; case QGraphicsItem::ItemEnabledHasChanged: str = "ItemEnabledHasChanged"; break; case QGraphicsItem::ItemFlagsChange: str = "ItemFlagsChange"; break; case QGraphicsItem::ItemFlagsHaveChanged: str = "ItemFlagsHaveChanged"; break; case QGraphicsItem::ItemMatrixChange: str = "ItemMatrixChange"; break; case QGraphicsItem::ItemParentChange: str = "ItemParentChange"; break; case QGraphicsItem::ItemParentHasChanged: str = "ItemParentHasChanged"; break; case QGraphicsItem::ItemPositionChange: str = "ItemPositionChange"; break; case QGraphicsItem::ItemPositionHasChanged: str = "ItemPositionHasChanged"; break; case QGraphicsItem::ItemSceneChange: str = "ItemSceneChange"; break; case QGraphicsItem::ItemSceneHasChanged: str = "ItemSceneHasChanged"; break; case QGraphicsItem::ItemSelectedChange: str = "ItemSelectedChange"; break; case QGraphicsItem::ItemSelectedHasChanged: str = "ItemSelectedHasChanged"; break; case QGraphicsItem::ItemToolTipChange: str = "ItemToolTipChange"; break; case QGraphicsItem::ItemToolTipHasChanged: str = "ItemToolTipHasChanged"; break; case QGraphicsItem::ItemTransformChange: str = "ItemTransformChange"; break; case QGraphicsItem::ItemTransformHasChanged: str = "ItemTransformHasChanged"; break; case QGraphicsItem::ItemVisibleChange: str = "ItemVisibleChange"; break; case QGraphicsItem::ItemVisibleHasChanged: str = "ItemVisibleHasChanged"; break; case QGraphicsItem::ItemZValueChange: str = "ItemZValueChange"; break; case QGraphicsItem::ItemZValueHasChanged: str = "ItemZValueHasChanged"; break; case QGraphicsItem::ItemOpacityChange: str = "ItemOpacityChange"; break; case QGraphicsItem::ItemOpacityHasChanged: str = "ItemOpacityHasChanged"; break; case QGraphicsItem::ItemScenePositionHasChanged: str = "ItemScenePositionHasChanged"; break; case QGraphicsItem::ItemRotationChange: str = "ItemRotationChange"; break; case QGraphicsItem::ItemRotationHasChanged: str = "ItemRotationHasChanged"; break; case QGraphicsItem::ItemScaleChange: str = "ItemScaleChange"; break; case QGraphicsItem::ItemScaleHasChanged: str = "ItemScaleHasChanged"; break; case QGraphicsItem::ItemTransformOriginPointChange: str = "ItemTransformOriginPointChange"; break; case QGraphicsItem::ItemTransformOriginPointHasChanged: str = "ItemTransformOriginPointHasChanged"; break; } debug << str; return debug; } QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemFlag flag) { const char *str = "UnknownFlag"; switch (flag) { case QGraphicsItem::ItemIsMovable: str = "ItemIsMovable"; break; case QGraphicsItem::ItemIsSelectable: str = "ItemIsSelectable"; break; case QGraphicsItem::ItemIsFocusable: str = "ItemIsFocusable"; break; case QGraphicsItem::ItemClipsToShape: str = "ItemClipsToShape"; break; case QGraphicsItem::ItemClipsChildrenToShape: str = "ItemClipsChildrenToShape"; break; case QGraphicsItem::ItemIgnoresTransformations: str = "ItemIgnoresTransformations"; break; case QGraphicsItem::ItemIgnoresParentOpacity: str = "ItemIgnoresParentOpacity"; break; case QGraphicsItem::ItemDoesntPropagateOpacityToChildren: str = "ItemDoesntPropagateOpacityToChildren"; break; case QGraphicsItem::ItemStacksBehindParent: str = "ItemStacksBehindParent"; break; case QGraphicsItem::ItemUsesExtendedStyleOption: str = "ItemUsesExtendedStyleOption"; break; case QGraphicsItem::ItemHasNoContents: str = "ItemHasNoContents"; break; case QGraphicsItem::ItemSendsGeometryChanges: str = "ItemSendsGeometryChanges"; break; case QGraphicsItem::ItemAcceptsInputMethod: str = "ItemAcceptsInputMethod"; break; case QGraphicsItem::ItemNegativeZStacksBehindParent: str = "ItemNegativeZStacksBehindParent"; break; case QGraphicsItem::ItemIsPanel: str = "ItemIsPanel"; break; case QGraphicsItem::ItemIsFocusScope: str = "ItemIsFocusScope"; break; case QGraphicsItem::ItemSendsScenePositionChanges: str = "ItemSendsScenePositionChanges"; break; case QGraphicsItem::ItemStopsClickFocusPropagation: str = "ItemStopsClickFocusPropagation"; break; case QGraphicsItem::ItemStopsFocusHandling: str = "ItemStopsFocusHandling"; break; } debug << str; return debug; } QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemFlags flags) { debug << '('; bool f = false; for (int i = 0; i < 17; ++i) { if (flags & (1 << i)) { if (f) debug << '|'; f = true; debug << QGraphicsItem::GraphicsItemFlag(int(flags & (1 << i))); } } debug << ')'; return debug; } #endif QT_END_NAMESPACE #include "moc_qgraphicsitem.cpp" #endif // QT_NO_GRAPHICSVIEW
#include <omp.h> #include <cstdlib> #include <cstdio> #include <cmath> #include <iostream> #include <vector> #include <cassert> using namespace std; #include "randomMT.h" float force(const float x) { return -2. * atan(x) / (x * x + 1.); } int main(void) { const int n = 64; vector<float> x(n); /* Generate random points on the unit interval */ #pragma omp parallel { const long tid = omp_get_thread_num(); randMT r(4357U + unsigned(tid)); /* Thread safe generation of random numbers */ #pragma omp for for (int i = 0; i < n; ++i) x[i] = r.rand(); } /* Compute interaction forces between particles. Atomic is used. */ vector<float> f(n); #pragma omp parallel for for (int i = 0; i < n; ++i) f[i] = 0.; #pragma omp parallel for for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) { const float x_ = x[i] - x[j]; const float f_ = force(x_); #pragma omp atomic f[i] += f_; #pragma omp atomic f[j] -= f_; } // Test { vector<float> f0(n, 0.); for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) { const float x_ = x[i] - x[j]; const float f_ = force(x_); f0[i] += f_; f0[j] -= f_; } for (int i = 0; i < n; ++i) assert(fabs(f0[i] - f[i]) < 1e-4); float max = 0; for (int i = 0; i < n; ++i) max = max < fabs(f0[i] - f[i]) ? fabs(f0[i] - f[i]) : max; printf("largest error %g\n", max); cout << "PASS\n"; } return 0; }
/******************************************************************************* * Copyright 2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef CPU_JIT_AVX512_CORE_U8S8S32X_WINO_CONVOLUTION_HPP #define CPU_JIT_AVX512_CORE_U8S8S32X_WINO_CONVOLUTION_HPP #include <assert.h> #include "c_types_map.hpp" #include "mkldnn_thread.hpp" #include "type_helpers.hpp" #include "utils.hpp" #include "cpu_convolution_pd.hpp" #include "cpu_primitive.hpp" #include "jit_primitive_conf.hpp" #include "jit_generator.hpp" namespace mkldnn { namespace impl { namespace cpu { struct jit_avx512_core_u8s8s32x_wino_conv_fwd_ker_t; struct jit_avx512_core_u8s8s32x_wino_conv_src_trans_t; struct jit_avx512_core_u8s8s32x_wino_conv_dst_trans_t; template <data_type_t dst_data_type> struct jit_avx512_core_u8s8s32x_wino_convolution_fwd_t : public cpu_primitive_t { struct pd_t : public cpu_convolution_fwd_pd_t { pd_t(engine_t *engine, const convolution_desc_t *adesc, const primitive_attr_t *attr, const typename pd_t::base_class *hint_fwd_pd) : cpu_convolution_fwd_pd_t(engine, adesc, attr, hint_fwd_pd) , jcp_() {} DECLARE_COMMON_PD_T( JIT_IMPL_NAME_HELPER("jit_int8_wino:", ((jcp_.ver == ver_vnni) ? avx512_core_vnni : avx512_core), ""), jit_avx512_core_u8s8s32x_wino_convolution_fwd_t<dst_data_type>); status_t init() { bool ok = true && is_fwd() && utils::one_of(desc()->alg_kind, alg_kind::convolution_auto, alg_kind::convolution_winograd) && expect_data_types(data_type::u8, data_type::s8, data_type::undef, dst_data_type, data_type::s32) && IMPLICATION(with_bias(), utils::one_of( desc()->bias_desc.data_type, data_type::f32, data_type::s32, data_type::s8, data_type::u8)) && !has_zero_dim_memory() && set_default_formats(); if (!ok) return status::unimplemented; status_t status = jit_conf(); if (status != status::success) return status; set_default_alg_kind(alg_kind::convolution_winograd); init_scratchpad(); return status; } jit_conv_conf_2x3_wino_t jcp_; protected: status_t jit_conf(); void init_scratchpad(); bool set_default_formats() { using namespace format_tag; return set_default_formats_common(nhwc, any, nhwc); } }; typedef typename prec_traits<data_type::u8>::type src_data_t; typedef typename prec_traits<data_type::s8>::type wei_data_t; typedef typename prec_traits<data_type::s32>::type acc_data_t; typedef typename prec_traits<dst_data_type>::type dst_data_t; jit_avx512_core_u8s8s32x_wino_convolution_fwd_t(const pd_t *apd); ~jit_avx512_core_u8s8s32x_wino_convolution_fwd_t(); virtual status_t execute(const exec_ctx_t &ctx) const override { execute_forward(ctx); return status::success; } private: const float *adjust_oscales(const memory_tracking::grantor_t &scratchpad) const; void execute_forward(const exec_ctx_t &ctx) const; void execute_forward_small_mb(const src_data_t *src, const wei_data_t *wei, const char *bia, dst_data_t *dst, const memory_tracking::grantor_t &scratchpad) const; void execute_forward_mbN(const src_data_t *src, const wei_data_t *wei, const char *bia, dst_data_t *dst, const memory_tracking::grantor_t &scratchpad) const; const pd_t *pd() const { return (const pd_t *)primitive_t::pd(); } jit_avx512_core_u8s8s32x_wino_conv_fwd_ker_t *kernel_; jit_avx512_core_u8s8s32x_wino_conv_src_trans_t *src_trans_; jit_avx512_core_u8s8s32x_wino_conv_dst_trans_t *dst_trans_; }; } } } #endif // vim: et ts=4 sw=4 cindent cino^=l0,\:0,N-s
/// Pimpact /// \author huppd /// \date 2018 #include <cmath> #include "Pimpact_Operator.hpp" #include "Pimpact_MultiGrid.hpp" #include "Pimpact_CoarsenStrategyGlobal.hpp" using S = double; using O = int; const int sd = 2; const int d = 3; const int dNC= 4; using GridT = Pimpact::Grid<S, O, sd, d, dNC>; using FGridT = GridT; using CGridT = Pimpact::Grid<S, O, sd, d, 2>; using CS = Pimpact::CoarsenStrategyGlobal<FGridT, CGridT>; template<class T1, class T2> using TransVF = Pimpact::VectorFieldOpWrap<Pimpact::TransferOp<T1, T2> >; template<class T> using RestrVF = Pimpact::VectorFieldOpWrap<Pimpact::RestrictionVFOp<T> >; template<class T> using InterVF = Pimpact::VectorFieldOpWrap<Pimpact::InterpolationOp<T> >; template<class T> using MOP = Pimpact::InverseOp<T>; int main(int argi, char** argv) { // intialize MPI MPI_Init(&argi, &argv); auto pl = Teuchos::parameterList(); pl->set("npy", 2); pl->set("npx", 2); int nwinds = 64; S pi = 4. * std::atan(1.) ; pl->set<S>("Re", 1000); pl->set<O>("nx", 129); pl->set<O>("ny", 129); auto grid = Pimpact::create<GridT>(pl); auto mgGrids = Pimpact::createMGGrids<CS>(grid, 5); Pimpact::VectorField<GridT> wind(grid); Pimpact::VectorField<GridT> y (grid); Pimpact::VectorField<GridT> z (grid); Pimpact::VectorField<GridT> z2 (grid); auto op = Pimpact::create<ConvDiffOpT>(grid); { short int dirx=1; short int diry=1; { auto pls = Teuchos::parameterList(); pls->sublist("Smoother").set("omega", 1.); pls->sublist("Smoother").set("numIters", ((dirx==3)?1:4)*1); pls->sublist("Smoother").set<int>("Ordering", (dirx==3)?1:0); pls->sublist("Smoother").set<short int>("dir X", dirx); pls->sublist("Smoother").set<short int>("dir Y", diry); pls->sublist("Smoother").set<short int>("dir Z", 1); auto smoother = Pimpact::createMultiGrid< Pimpact::VectorField, TransVF, RestrVF, InterVF, ConvDiffOpT, ConvDiffOpT, ConvDiffSORT, MOP > (mgGrids, op, pls); std::ofstream phifile; if(grid()->rankST()==0) { std::string fname = "phin.txt"; if(3==dirx) fname.insert(4, std::to_string((long long)8)); else fname.insert(4, std::to_string((long long)dirx+diry*2+3)); phifile.open(fname, std::ofstream::out); } for(int phii=0; phii<nwinds; ++phii) { S phi = 2.*pi*phii/(nwinds); if(grid()->rankST()==0) phifile << phi << "\t"; // init solution y(Pimpact::F::U).initField(Pimpact::Grad2D_inX); y(Pimpact::F::V).initField(Pimpact::Grad2D_inY); auto sol = y.clone(Pimpact::ECopy::Deep); //sol->write(3333); wind(Pimpact::F::U).init(std::cos(phi)); wind(Pimpact::F::V).init(std::sin(phi)); op->assignField(wind); smoother->assignField(wind); z.init(); // constructing rhs op->apply(y, z); y.init(); std::ofstream ofs; std::string filename = "GS.txt"; filename.insert(2, std::to_string((long long)phii)); if(grid()->rankST()==0) ofs.open(filename, std::ofstream::out); S error; int iter=0; do { smoother->apply(z, y); z2.add(-1., *sol, 1., y); error = z2.norm()/sol->norm(); if(grid()->rankST()==0) ofs << error << "\n"; if(grid()->rankST()==0) std::cout << "iter: " << iter << " " << error << "\n"; iter++; if(iter>1000) error=-1; } while(error>1.e-6); if(grid()->rankST()==0) // phifile << error << "\n"; phifile << iter << "\n"; if(grid()->rankST()==0) ofs.close(); } if(grid()->rankST()==0) phifile.close(); } } MPI_Finalize(); return 0; }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache 2.0 License. #include "ccf/historical_queries_adapter.h" #include "ccf/rpc_context.h" #include "ccf/service/tables/service.h" #include "kv/kv_types.h" #include "node/rpc/network_identity_subsystem.h" #include "node/tx_receipt_impl.h" namespace ccf { static std::map<crypto::Pem, std::vector<crypto::Pem>> service_endorsement_cache; nlohmann::json describe_receipt_v1(const TxReceiptImpl& receipt) { // Legacy JSON format, retained for compatibility nlohmann::json out = nlohmann::json::object(); out["signature"] = crypto::b64_from_raw(receipt.signature); auto proof = nlohmann::json::array(); if (receipt.path != nullptr) { for (const auto& node : *receipt.path) { auto n = nlohmann::json::object(); if (node.direction == ccf::HistoryTree::Path::Direction::PATH_LEFT) { n["left"] = node.hash.to_string(); } else { n["right"] = node.hash.to_string(); } proof.emplace_back(std::move(n)); } } out["proof"] = proof; out["node_id"] = receipt.node_id; if (receipt.node_cert.has_value()) { out["cert"] = receipt.node_cert->str(); } if (receipt.path == nullptr) { // Signature transaction out["leaf"] = receipt.root.to_string(); } else if (!receipt.commit_evidence.has_value()) { out["leaf"] = receipt.write_set_digest->hex_str(); } else { auto leaf_components = nlohmann::json::object(); if (receipt.write_set_digest.has_value()) { leaf_components["write_set_digest"] = receipt.write_set_digest->hex_str(); } if (receipt.commit_evidence.has_value()) { leaf_components["commit_evidence"] = receipt.commit_evidence.value(); } if (!receipt.claims_digest.empty()) { leaf_components["claims_digest"] = receipt.claims_digest.value().hex_str(); } out["leaf_components"] = leaf_components; } if (receipt.service_endorsements.has_value()) { out["service_endorsements"] = receipt.service_endorsements; } return out; } ccf::ReceiptPtr describe_receipt_v2(const TxReceiptImpl& in) { ccf::ReceiptPtr receipt = nullptr; if (in.path != nullptr && in.commit_evidence.has_value()) { auto proof_receipt = std::make_shared<ProofReceipt>(); proof_receipt->proof.reserve(in.path->size()); for (const auto& node : *in.path) { const auto direction = node.direction == ccf::HistoryTree::Path::Direction::PATH_LEFT ? ccf::ProofReceipt::ProofStep::Left : ccf::ProofReceipt::ProofStep::Right; const auto hash = crypto::Sha256Hash::from_span( {node.hash.bytes, sizeof(node.hash.bytes)}); proof_receipt->proof.push_back({direction, hash}); } if (in.write_set_digest.has_value()) { proof_receipt->leaf_components.write_set_digest = in.write_set_digest.value(); } if (in.commit_evidence.has_value()) { proof_receipt->leaf_components.commit_evidence = in.commit_evidence.value(); } if (!in.claims_digest.empty()) { proof_receipt->leaf_components.claims_digest = in.claims_digest; } receipt = proof_receipt; } else { // Signature transaction auto sig_receipt = std::make_shared<SignatureReceipt>(); sig_receipt->signed_root = crypto::Sha256Hash::from_span({in.root.bytes, sizeof(in.root.bytes)}); receipt = sig_receipt; } auto& out = *receipt; out.signature = in.signature; out.node_id = in.node_id; if (in.node_cert.has_value()) { out.cert = in.node_cert.value(); } if (in.service_endorsements.has_value()) { out.service_endorsements = in.service_endorsements.value(); } return receipt; } } namespace ccf::historical { std::optional<ccf::TxID> txid_from_header(endpoints::EndpointContext& args) { const auto tx_id_header = args.rpc_ctx->get_request_header(http::headers::CCF_TX_ID); if (!tx_id_header.has_value()) { args.rpc_ctx->set_error( HTTP_STATUS_BAD_REQUEST, ccf::errors::MissingRequiredHeader, fmt::format( "Historical query is missing '{}' header.", http::headers::CCF_TX_ID)); return std::nullopt; } const auto tx_id_opt = ccf::TxID::from_str(tx_id_header.value()); if (!tx_id_opt.has_value()) { args.rpc_ctx->set_error( HTTP_STATUS_BAD_REQUEST, ccf::errors::InvalidHeaderValue, fmt::format( "The value '{}' in header '{}' could not be converted to a valid " "Tx ID.", tx_id_header.value(), http::headers::CCF_TX_ID)); return std::nullopt; } return tx_id_opt; } bool is_tx_committed_v1( kv::Consensus* consensus, ccf::View view, ccf::SeqNo seqno, std::string& error_reason) { if (consensus == nullptr) { error_reason = "Node is not fully configured"; return false; } const auto tx_view = consensus->get_view(seqno); const auto committed_seqno = consensus->get_committed_seqno(); const auto committed_view = consensus->get_view(committed_seqno); const auto tx_status = ccf::evaluate_tx_status( view, seqno, tx_view, committed_view, committed_seqno); if (tx_status != ccf::TxStatus::Committed) { error_reason = fmt::format( "Only committed transactions can be queried. Transaction {}.{} " "is " "{}", view, seqno, ccf::tx_status_to_str(tx_status)); return false; } return true; } HistoricalTxStatus is_tx_committed_v2( kv::Consensus* consensus, ccf::View view, ccf::SeqNo seqno, std::string& error_reason) { if (consensus == nullptr) { error_reason = "Node is not fully configured"; return HistoricalTxStatus::Error; } const auto tx_view = consensus->get_view(seqno); const auto committed_seqno = consensus->get_committed_seqno(); const auto committed_view = consensus->get_view(committed_seqno); const auto tx_status = ccf::evaluate_tx_status( view, seqno, tx_view, committed_view, committed_seqno); switch (tx_status) { case ccf::TxStatus::Unknown: case ccf::TxStatus::Pending: error_reason = fmt::format( "Only committed transactions can be queried. Transaction {}.{} " "is " "{}", view, seqno, ccf::tx_status_to_str(tx_status)); return HistoricalTxStatus::PendingOrUnknown; case ccf::TxStatus::Invalid: error_reason = fmt::format( "Only committed transactions can be queried. Transaction {}.{} " "is " "{}", view, seqno, ccf::tx_status_to_str(tx_status)); return HistoricalTxStatus::Invalid; case ccf::TxStatus::Committed:; } return HistoricalTxStatus::Valid; } std::optional<ServiceInfo> find_previous_service_identity( auto& ctx, ccf::historical::StatePtr& state, AbstractStateCache& state_cache) { SeqNo target_seqno = state->transaction_id.seqno; // We start at the previous write to the latest (current) service info. auto service = ctx.tx.template ro<Service>(Tables::SERVICE); // Iterate until we find the most recent write to the service info that // precedes the target seqno. std::optional<ServiceInfo> hservice_info = service->get(); SeqNo i = -1; do { if (!hservice_info->previous_service_identity_version) { // Pre 2.0 we did not record the versions of previous identities in the // service table. throw std::runtime_error( "The service identity that signed the receipt cannot be found " "because it is in a pre-2.0 part of the ledger."); } i = hservice_info->previous_service_identity_version.value_or(i - 1); LOG_TRACE_FMT("historical service identity search at: {}", i); auto hstate = state_cache.get_state_at(i, i); if (!hstate) { return std::nullopt; // Not available yet - retry later. } auto htx = hstate->store->create_read_only_tx(); auto hservice = htx.ro<Service>(Tables::SERVICE); hservice_info = hservice->get(); } while (i > target_seqno || (i > 1 && !hservice_info)); if (!hservice_info) { throw std::runtime_error("Failed to locate previous service identity"); } return hservice_info; } bool get_service_endorsements( auto& ctx, ccf::historical::StatePtr& state, AbstractStateCache& state_cache, std::shared_ptr<NetworkIdentitySubsystem> network_identity_subsystem) { try { if (!network_identity_subsystem) { throw std::runtime_error( "The service identity endorsement for this receipt cannot be created " "because the current network identity is not available."); } const auto& network_identity = network_identity_subsystem->get(); if (state && state->receipt && state->receipt->node_cert) { auto& receipt = *state->receipt; if (receipt.node_cert->empty()) { // Pre 2.0 receipts did not contain node certs. throw std::runtime_error( "Node certificate in receipt is empty, likely because the " "transaction is in a pre-2.0 part of the ledger."); } auto v = crypto::make_unique_verifier(*receipt.node_cert); if (!v->verify_certificate( {&network_identity->cert}, {}, /* ignore_time */ true)) { // The current service identity does not endorse the node certificate // in the receipt, so we search for the the most recent write to the // service info table before the historical transaction ID to get the // historical service identity. auto opt_psi = find_previous_service_identity(ctx, state, state_cache); if (!opt_psi) { return false; } auto hpubkey = crypto::public_key_pem_from_cert( crypto::cert_pem_to_der(opt_psi->cert)); auto eit = service_endorsement_cache.find(hpubkey); if (eit != service_endorsement_cache.end()) { // Note: validity period of service certificate may have changed // since we created the cached endorsements. receipt.service_endorsements = eit->second; } else { auto ncv = crypto::make_unique_verifier(network_identity->cert); auto endorsement = create_endorsed_cert( hpubkey, ReplicatedNetworkIdentity::subject_name, {}, ncv->validity_period(), network_identity->priv_key, network_identity->cert, true); service_endorsement_cache[hpubkey] = {endorsement}; receipt.service_endorsements = {endorsement}; } } } } catch (std::exception& ex) { LOG_DEBUG_FMT( "Exception while extracting previous service identities: {}", ex.what()); // (We keep the incomplete receipt, no further error reporting) } return true; } ccf::endpoints::EndpointFunction adapter_v3( const HandleHistoricalQuery& f, ccfapp::AbstractNodeContext& node_context, const CheckHistoricalTxStatus& available, const TxIDExtractor& extractor) { auto& state_cache = node_context.get_historical_state(); std::shared_ptr<NetworkIdentitySubsystem> network_identity_subsystem = node_context.get_subsystem<NetworkIdentitySubsystem>(); return [f, &state_cache, network_identity_subsystem, available, extractor]( endpoints::EndpointContext& args) { // Extract the requested transaction ID ccf::TxID target_tx_id; { const auto tx_id_opt = extractor(args); if (tx_id_opt.has_value()) { target_tx_id = tx_id_opt.value(); } else { return; } } // Check that the requested transaction ID is available { auto error_reason = fmt::format( "Transaction {} is not available.", target_tx_id.to_str()); auto is_available = available(target_tx_id.view, target_tx_id.seqno, error_reason); switch (is_available) { case HistoricalTxStatus::Error: { args.rpc_ctx->set_error( HTTP_STATUS_INTERNAL_SERVER_ERROR, ccf::errors::TransactionPendingOrUnknown, std::move(error_reason)); return; } case HistoricalTxStatus::PendingOrUnknown: { // Set header No-Cache args.rpc_ctx->set_response_header( http::headers::CACHE_CONTROL, "no-cache"); args.rpc_ctx->set_error( HTTP_STATUS_NOT_FOUND, ccf::errors::TransactionPendingOrUnknown, std::move(error_reason)); return; } case HistoricalTxStatus::Invalid: { args.rpc_ctx->set_error( HTTP_STATUS_NOT_FOUND, ccf::errors::TransactionInvalid, std::move(error_reason)); return; } case HistoricalTxStatus::Valid: { } } } // We need a handle to determine whether this request is the 'same' as a // previous one. For simplicity we use target_tx_id.seqno. This means we // keep a lot of state around for old requests! It should be cleaned up // manually const auto historic_request_handle = target_tx_id.seqno; // Get a state at the target version from the cache, if it is present auto historical_state = state_cache.get_state_at(historic_request_handle, target_tx_id.seqno); if ( historical_state == nullptr || (!get_service_endorsements( args, historical_state, state_cache, network_identity_subsystem))) { args.rpc_ctx->set_response_status(HTTP_STATUS_ACCEPTED); constexpr size_t retry_after_seconds = 3; args.rpc_ctx->set_response_header( http::headers::RETRY_AFTER, retry_after_seconds); args.rpc_ctx->set_response_header( http::headers::CONTENT_TYPE, http::headervalues::contenttype::TEXT); args.rpc_ctx->set_response_body(fmt::format( "Historical transaction {} is not currently available.", target_tx_id.to_str())); return; } // Call the provided handler f(args, historical_state); }; } ccf::endpoints::EndpointFunction adapter_v2( const HandleHistoricalQuery& f, AbstractStateCache& state_cache, const CheckHistoricalTxStatus& available, const TxIDExtractor& extractor) { return [f, &state_cache, available, extractor]( endpoints::EndpointContext& args) { // Extract the requested transaction ID ccf::TxID target_tx_id; { const auto tx_id_opt = extractor(args); if (tx_id_opt.has_value()) { target_tx_id = tx_id_opt.value(); } else { return; } } // Check that the requested transaction ID is available { auto error_reason = fmt::format( "Transaction {} is not available.", target_tx_id.to_str()); auto is_available = available(target_tx_id.view, target_tx_id.seqno, error_reason); switch (is_available) { case HistoricalTxStatus::Error: { args.rpc_ctx->set_error( HTTP_STATUS_INTERNAL_SERVER_ERROR, ccf::errors::TransactionPendingOrUnknown, std::move(error_reason)); return; } case HistoricalTxStatus::PendingOrUnknown: { // Set header No-Cache args.rpc_ctx->set_response_header( http::headers::CACHE_CONTROL, "no-cache"); args.rpc_ctx->set_error( HTTP_STATUS_NOT_FOUND, ccf::errors::TransactionPendingOrUnknown, std::move(error_reason)); return; } case HistoricalTxStatus::Invalid: { args.rpc_ctx->set_error( HTTP_STATUS_NOT_FOUND, ccf::errors::TransactionInvalid, std::move(error_reason)); return; } case HistoricalTxStatus::Valid: { } } } // We need a handle to determine whether this request is the 'same' as a // previous one. For simplicity we use target_tx_id.seqno. This means we // keep a lot of state around for old requests! It should be cleaned up // manually const auto historic_request_handle = target_tx_id.seqno; // Get a state at the target version from the cache, if it is present auto historical_state = state_cache.get_state_at(historic_request_handle, target_tx_id.seqno); if (historical_state == nullptr) { args.rpc_ctx->set_response_status(HTTP_STATUS_ACCEPTED); constexpr size_t retry_after_seconds = 3; args.rpc_ctx->set_response_header( http::headers::RETRY_AFTER, retry_after_seconds); args.rpc_ctx->set_response_header( http::headers::CONTENT_TYPE, http::headervalues::contenttype::TEXT); args.rpc_ctx->set_response_body(fmt::format( "Historical transaction {} is not currently available.", target_tx_id.to_str())); return; } // Call the provided handler f(args, historical_state); }; } ccf::endpoints::EndpointFunction adapter_v1( const HandleHistoricalQuery& f, AbstractStateCache& state_cache, const CheckAvailability& available, const TxIDExtractor& extractor) { return [f, &state_cache, available, extractor]( endpoints::EndpointContext& args) { // Extract the requested transaction ID ccf::TxID target_tx_id; { const auto tx_id_opt = extractor(args); if (tx_id_opt.has_value()) { target_tx_id = tx_id_opt.value(); } else { return; } } // Check that the requested transaction ID is available { auto error_reason = fmt::format( "Transaction {} is not available.", target_tx_id.to_str()); if (!available(target_tx_id.view, target_tx_id.seqno, error_reason)) { args.rpc_ctx->set_error( HTTP_STATUS_BAD_REQUEST, ccf::errors::TransactionNotFound, std::move(error_reason)); return; } } // We need a handle to determine whether this request is the 'same' as a // previous one. For simplicity we use target_tx_id.seqno. This means we // keep a lot of state around for old requests! It should be cleaned up // manually const auto historic_request_handle = target_tx_id.seqno; // Get a state at the target version from the cache, if it is present auto historical_state = state_cache.get_state_at(historic_request_handle, target_tx_id.seqno); if (historical_state == nullptr) { args.rpc_ctx->set_response_status(HTTP_STATUS_ACCEPTED); constexpr size_t retry_after_seconds = 3; args.rpc_ctx->set_response_header( http::headers::RETRY_AFTER, retry_after_seconds); args.rpc_ctx->set_response_header( http::headers::CONTENT_TYPE, http::headervalues::contenttype::TEXT); args.rpc_ctx->set_response_body(fmt::format( "Historical transaction {} is not currently available.", target_tx_id.to_str())); return; } // Call the provided handler f(args, historical_state); }; } ccf::endpoints::EndpointFunction adapter( const HandleHistoricalQuery& f, AbstractStateCache& state_cache, const CheckAvailability& available, const TxIDExtractor& extractor) { return adapter_v1(f, state_cache, available, extractor); } bool is_tx_committed( kv::Consensus* consensus, ccf::View view, ccf::SeqNo seqno, std::string& error_reason) { return is_tx_committed_v1(consensus, view, seqno, error_reason); } }
// Copyright 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Lovell Fuller and contributors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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 <numeric> #include <vector> #include <napi.h> #include <vips/vips8> #include "common.h" #include "metadata.h" class MetadataWorker : public Napi::AsyncWorker { public: MetadataWorker(Napi::Function callback, MetadataBaton *baton, Napi::Function debuglog) : Napi::AsyncWorker(callback), baton(baton), debuglog(Napi::Persistent(debuglog)) {} ~MetadataWorker() {} void Execute() { // Decrement queued task counter g_atomic_int_dec_and_test(&sharp::counterQueue); vips::VImage image; sharp::ImageType imageType = sharp::ImageType::UNKNOWN; try { std::tie(image, imageType) = OpenInput(baton->input); } catch (vips::VError const &err) { (baton->err).append(err.what()); } if (imageType != sharp::ImageType::UNKNOWN) { // Image type baton->format = sharp::ImageTypeId(imageType); // VipsImage attributes baton->width = image.width(); baton->height = image.height(); baton->space = vips_enum_nick(VIPS_TYPE_INTERPRETATION, image.interpretation()); baton->channels = image.bands(); baton->depth = vips_enum_nick(VIPS_TYPE_BAND_FORMAT, image.format()); if (sharp::HasDensity(image)) { baton->density = sharp::GetDensity(image); } if (image.get_typeof("jpeg-chroma-subsample") == VIPS_TYPE_REF_STRING) { baton->chromaSubsampling = image.get_string("jpeg-chroma-subsample"); } if (image.get_typeof("interlaced") == G_TYPE_INT) { baton->isProgressive = image.get_int("interlaced") == 1; } if (image.get_typeof("palette-bit-depth") == G_TYPE_INT) { baton->paletteBitDepth = image.get_int("palette-bit-depth"); } if (image.get_typeof(VIPS_META_N_PAGES) == G_TYPE_INT) { baton->pages = image.get_int(VIPS_META_N_PAGES); } if (image.get_typeof(VIPS_META_PAGE_HEIGHT) == G_TYPE_INT) { baton->pageHeight = image.get_int(VIPS_META_PAGE_HEIGHT); } if (image.get_typeof("loop") == G_TYPE_INT) { baton->loop = image.get_int("loop"); } if (image.get_typeof("delay") == VIPS_TYPE_ARRAY_INT) { baton->delay = image.get_array_int("delay"); } if (image.get_typeof("heif-primary") == G_TYPE_INT) { baton->pagePrimary = image.get_int("heif-primary"); } baton->hasProfile = sharp::HasProfile(image); // Derived attributes baton->hasAlpha = sharp::HasAlpha(image); baton->orientation = sharp::ExifOrientation(image); // EXIF if (image.get_typeof(VIPS_META_EXIF_NAME) == VIPS_TYPE_BLOB) { size_t exifLength; void const *exif = image.get_blob(VIPS_META_EXIF_NAME, &exifLength); baton->exif = static_cast<char*>(g_malloc(exifLength)); memcpy(baton->exif, exif, exifLength); baton->exifLength = exifLength; } // ICC profile if (image.get_typeof(VIPS_META_ICC_NAME) == VIPS_TYPE_BLOB) { size_t iccLength; void const *icc = image.get_blob(VIPS_META_ICC_NAME, &iccLength); baton->icc = static_cast<char*>(g_malloc(iccLength)); memcpy(baton->icc, icc, iccLength); baton->iccLength = iccLength; } // IPTC if (image.get_typeof(VIPS_META_IPTC_NAME) == VIPS_TYPE_BLOB) { size_t iptcLength; void const *iptc = image.get_blob(VIPS_META_IPTC_NAME, &iptcLength); baton->iptc = static_cast<char *>(g_malloc(iptcLength)); memcpy(baton->iptc, iptc, iptcLength); baton->iptcLength = iptcLength; } // XMP if (image.get_typeof(VIPS_META_XMP_NAME) == VIPS_TYPE_BLOB) { size_t xmpLength; void const *xmp = image.get_blob(VIPS_META_XMP_NAME, &xmpLength); baton->xmp = static_cast<char *>(g_malloc(xmpLength)); memcpy(baton->xmp, xmp, xmpLength); baton->xmpLength = xmpLength; } // TIFFTAG_PHOTOSHOP if (image.get_typeof(VIPS_META_PHOTOSHOP_NAME) == VIPS_TYPE_BLOB) { size_t tifftagPhotoshopLength; void const *tifftagPhotoshop = image.get_blob(VIPS_META_PHOTOSHOP_NAME, &tifftagPhotoshopLength); baton->tifftagPhotoshop = static_cast<char *>(g_malloc(tifftagPhotoshopLength)); memcpy(baton->tifftagPhotoshop, tifftagPhotoshop, tifftagPhotoshopLength); baton->tifftagPhotoshopLength = tifftagPhotoshopLength; } } // Clean up vips_error_clear(); vips_thread_shutdown(); } void OnOK() { Napi::Env env = Env(); Napi::HandleScope scope(env); // Handle warnings std::string warning = sharp::VipsWarningPop(); while (!warning.empty()) { debuglog.Call({ Napi::String::New(env, warning) }); warning = sharp::VipsWarningPop(); } if (baton->err.empty()) { Napi::Object info = Napi::Object::New(env); info.Set("format", baton->format); if (baton->input->bufferLength > 0) { info.Set("size", baton->input->bufferLength); } info.Set("width", baton->width); info.Set("height", baton->height); info.Set("space", baton->space); info.Set("channels", baton->channels); info.Set("depth", baton->depth); if (baton->density > 0) { info.Set("density", baton->density); } if (!baton->chromaSubsampling.empty()) { info.Set("chromaSubsampling", baton->chromaSubsampling); } info.Set("isProgressive", baton->isProgressive); if (baton->paletteBitDepth > 0) { info.Set("paletteBitDepth", baton->paletteBitDepth); } if (baton->pages > 0) { info.Set("pages", baton->pages); } if (baton->pageHeight > 0) { info.Set("pageHeight", baton->pageHeight); } if (baton->loop >= 0) { info.Set("loop", baton->loop); } if (!baton->delay.empty()) { int i = 0; Napi::Array delay = Napi::Array::New(env, static_cast<size_t>(baton->delay.size())); for (int const d : baton->delay) { delay.Set(i++, d); } info.Set("delay", delay); } if (baton->pagePrimary > -1) { info.Set("pagePrimary", baton->pagePrimary); } info.Set("hasProfile", baton->hasProfile); info.Set("hasAlpha", baton->hasAlpha); if (baton->orientation > 0) { info.Set("orientation", baton->orientation); } if (baton->exifLength > 0) { info.Set("exif", Napi::Buffer<char>::New(env, baton->exif, baton->exifLength, sharp::FreeCallback)); } if (baton->iccLength > 0) { info.Set("icc", Napi::Buffer<char>::New(env, baton->icc, baton->iccLength, sharp::FreeCallback)); } if (baton->iptcLength > 0) { info.Set("iptc", Napi::Buffer<char>::New(env, baton->iptc, baton->iptcLength, sharp::FreeCallback)); } if (baton->xmpLength > 0) { info.Set("xmp", Napi::Buffer<char>::New(env, baton->xmp, baton->xmpLength, sharp::FreeCallback)); } if (baton->tifftagPhotoshopLength > 0) { info.Set("tifftagPhotoshop", Napi::Buffer<char>::New(env, baton->tifftagPhotoshop, baton->tifftagPhotoshopLength, sharp::FreeCallback)); } Callback().MakeCallback(Receiver().Value(), { env.Null(), info }); } else { Callback().MakeCallback(Receiver().Value(), { Napi::Error::New(env, baton->err).Value() }); } delete baton->input; delete baton; } private: MetadataBaton* baton; Napi::FunctionReference debuglog; }; /* metadata(options, callback) */ Napi::Value metadata(const Napi::CallbackInfo& info) { // V8 objects are converted to non-V8 types held in the baton struct MetadataBaton *baton = new MetadataBaton; Napi::Object options = info[0].As<Napi::Object>(); // Input baton->input = sharp::CreateInputDescriptor(options.Get("input").As<Napi::Object>()); // Function to notify of libvips warnings Napi::Function debuglog = options.Get("debuglog").As<Napi::Function>(); // Join queue for worker thread Napi::Function callback = info[1].As<Napi::Function>(); MetadataWorker *worker = new MetadataWorker(callback, baton, debuglog); worker->Queue(); // Increment queued task counter g_atomic_int_inc(&sharp::counterQueue); return info.Env().Undefined(); }
/**************************************************************************** ** Meta object code from reading C++ file 'rthpis.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.10.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../rtProcessing/rthpis.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #include <QtCore/QSharedPointer> #include <QtCore/QVector> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'rthpis.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.10.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_REALTIMELIB__RtHPISWorker_t { QByteArrayData data[5]; char stringdata0[76]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_REALTIMELIB__RtHPISWorker_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_REALTIMELIB__RtHPISWorker_t qt_meta_stringdata_REALTIMELIB__RtHPISWorker = { { QT_MOC_LITERAL(0, 0, 25), // "REALTIMELIB::RtHPISWorker" QT_MOC_LITERAL(1, 26, 11), // "resultReady" QT_MOC_LITERAL(2, 38, 0), // "" QT_MOC_LITERAL(3, 39, 26), // "REALTIMELIB::FittingResult" QT_MOC_LITERAL(4, 66, 9) // "fitResult" }, "REALTIMELIB::RtHPISWorker\0resultReady\0" "\0REALTIMELIB::FittingResult\0fitResult" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_REALTIMELIB__RtHPISWorker[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: name, argc, parameters, tag, flags 1, 1, 19, 2, 0x06 /* Public */, // signals: parameters QMetaType::Void, 0x80000000 | 3, 4, 0 // eod }; void REALTIMELIB::RtHPISWorker::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { RtHPISWorker *_t = static_cast<RtHPISWorker *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->resultReady((*reinterpret_cast< const REALTIMELIB::FittingResult(*)>(_a[1]))); break; default: ; } } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { switch (_id) { default: *reinterpret_cast<int*>(_a[0]) = -1; break; case 0: switch (*reinterpret_cast<int*>(_a[1])) { default: *reinterpret_cast<int*>(_a[0]) = -1; break; case 0: *reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< REALTIMELIB::FittingResult >(); break; } break; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); { typedef void (RtHPISWorker::*_t)(const REALTIMELIB::FittingResult & ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&RtHPISWorker::resultReady)) { *result = 0; return; } } } } const QMetaObject REALTIMELIB::RtHPISWorker::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_REALTIMELIB__RtHPISWorker.data, qt_meta_data_REALTIMELIB__RtHPISWorker, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *REALTIMELIB::RtHPISWorker::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *REALTIMELIB::RtHPISWorker::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_REALTIMELIB__RtHPISWorker.stringdata0)) return static_cast<void*>(this); return QObject::qt_metacast(_clname); } int REALTIMELIB::RtHPISWorker::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 1) qt_static_metacall(this, _c, _id, _a); _id -= 1; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 1) qt_static_metacall(this, _c, _id, _a); _id -= 1; } return _id; } // SIGNAL 0 void REALTIMELIB::RtHPISWorker::resultReady(const REALTIMELIB::FittingResult & _t1) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } struct qt_meta_stringdata_REALTIMELIB__RtHPIS_t { QByteArrayData data[13]; char stringdata0[194]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_REALTIMELIB__RtHPIS_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_REALTIMELIB__RtHPIS_t qt_meta_stringdata_REALTIMELIB__RtHPIS = { { QT_MOC_LITERAL(0, 0, 19), // "REALTIMELIB::RtHPIS" QT_MOC_LITERAL(1, 20, 25), // "newFittingResultAvailable" QT_MOC_LITERAL(2, 46, 0), // "" QT_MOC_LITERAL(3, 47, 26), // "REALTIMELIB::FittingResult" QT_MOC_LITERAL(4, 74, 9), // "fitResult" QT_MOC_LITERAL(5, 84, 7), // "operate" QT_MOC_LITERAL(6, 92, 15), // "Eigen::MatrixXd" QT_MOC_LITERAL(7, 108, 7), // "matData" QT_MOC_LITERAL(8, 116, 13), // "matProjectors" QT_MOC_LITERAL(9, 130, 12), // "QVector<int>" QT_MOC_LITERAL(10, 143, 6), // "vFreqs" QT_MOC_LITERAL(11, 150, 33), // "QSharedPointer<FIFFLIB::FiffI..." QT_MOC_LITERAL(12, 184, 9) // "pFiffInfo" }, "REALTIMELIB::RtHPIS\0newFittingResultAvailable\0" "\0REALTIMELIB::FittingResult\0fitResult\0" "operate\0Eigen::MatrixXd\0matData\0" "matProjectors\0QVector<int>\0vFreqs\0" "QSharedPointer<FIFFLIB::FiffInfo>\0" "pFiffInfo" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_REALTIMELIB__RtHPIS[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 2, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 2, // signalCount // signals: name, argc, parameters, tag, flags 1, 1, 24, 2, 0x06 /* Public */, 5, 4, 27, 2, 0x06 /* Public */, // signals: parameters QMetaType::Void, 0x80000000 | 3, 4, QMetaType::Void, 0x80000000 | 6, 0x80000000 | 6, 0x80000000 | 9, 0x80000000 | 11, 7, 8, 10, 12, 0 // eod }; void REALTIMELIB::RtHPIS::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { RtHPIS *_t = static_cast<RtHPIS *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->newFittingResultAvailable((*reinterpret_cast< const REALTIMELIB::FittingResult(*)>(_a[1]))); break; case 1: _t->operate((*reinterpret_cast< const Eigen::MatrixXd(*)>(_a[1])),(*reinterpret_cast< const Eigen::MatrixXd(*)>(_a[2])),(*reinterpret_cast< const QVector<int>(*)>(_a[3])),(*reinterpret_cast< QSharedPointer<FIFFLIB::FiffInfo>(*)>(_a[4]))); break; default: ; } } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { switch (_id) { default: *reinterpret_cast<int*>(_a[0]) = -1; break; case 0: switch (*reinterpret_cast<int*>(_a[1])) { default: *reinterpret_cast<int*>(_a[0]) = -1; break; case 0: *reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< REALTIMELIB::FittingResult >(); break; } break; case 1: switch (*reinterpret_cast<int*>(_a[1])) { default: *reinterpret_cast<int*>(_a[0]) = -1; break; case 2: *reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< QVector<int> >(); break; } break; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); { typedef void (RtHPIS::*_t)(const REALTIMELIB::FittingResult & ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&RtHPIS::newFittingResultAvailable)) { *result = 0; return; } } { typedef void (RtHPIS::*_t)(const Eigen::MatrixXd & , const Eigen::MatrixXd & , const QVector<int> & , QSharedPointer<FIFFLIB::FiffInfo> ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&RtHPIS::operate)) { *result = 1; return; } } } } const QMetaObject REALTIMELIB::RtHPIS::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_REALTIMELIB__RtHPIS.data, qt_meta_data_REALTIMELIB__RtHPIS, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *REALTIMELIB::RtHPIS::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *REALTIMELIB::RtHPIS::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_REALTIMELIB__RtHPIS.stringdata0)) return static_cast<void*>(this); return QObject::qt_metacast(_clname); } int REALTIMELIB::RtHPIS::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 2) qt_static_metacall(this, _c, _id, _a); _id -= 2; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 2) qt_static_metacall(this, _c, _id, _a); _id -= 2; } return _id; } // SIGNAL 0 void REALTIMELIB::RtHPIS::newFittingResultAvailable(const REALTIMELIB::FittingResult & _t1) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void REALTIMELIB::RtHPIS::operate(const Eigen::MatrixXd & _t1, const Eigen::MatrixXd & _t2, const QVector<int> & _t3, QSharedPointer<FIFFLIB::FiffInfo> _t4) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)), const_cast<void*>(reinterpret_cast<const void*>(&_t4)) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); } QT_WARNING_POP QT_END_MOC_NAMESPACE
/* Copyright (c) 2007-2008 FastMQ Inc. This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __ZMQ_POLL_THREAD_HPP_INCLUDED__ #define __ZMQ_POLL_THREAD_HPP_INCLUDED__ #include <stddef.h> #include <assert.h> #include <pthread.h> #include <poll.h> #include "i_context.hpp" #include "i_pollable.hpp" #include "dispatcher.hpp" #include "ysocketpair.hpp" namespace zmq { // Poll thread is a I/O thread that waits for events from engines // using POSIX poll function and schedules handling of the signals // by individual engines. Engine compatible with poll thread should // expose i_pollable interface. class poll_thread_t : public i_context { public: // Create a poll thread. static poll_thread_t *create (dispatcher_t *dispatcher_); // Destroy the poll thread. ~poll_thread_t (); // Registers the engine with the poll thread. void register_engine (i_pollable *engine_); // Unregisters the engine from the thread. void unregister_engine (i_pollable* engine_); // i_context implementation int get_thread_id (); void send_command (i_context *destination_, const command_t &command_); private: poll_thread_t (dispatcher_t *dispatcher_); // Main worker thread routine. static void *worker_routine (void *arg_); // Main routine (non-static) - called from worker_routine. void loop (); // Processes commands from other threads. Returns false if the thread // should terminate. bool process_commands (uint32_t signals_); // Pointer to dispatcher. dispatcher_t *dispatcher; // Thread ID allocated for the poll thread by dispatcher. int thread_id; // Poll thread gets notifications about incoming commands using // this socketpair. ysocketpair_t signaler; // Handle of the physical thread doing the I/O work. pthread_t worker; // Pollset to pass to the poll function. typedef std::vector <pollfd> pollset_t; pollset_t pollset; // List of engines handled by this poll thread. typedef std::vector <i_pollable*> engines_t; engines_t engines; }; } #endif
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "Projection.h" #include "paddle/legacy/utils/Stat.h" namespace paddle { /** * IdentityProjection performs addition: * \f[ * out.row[i] += in.row[i] * \f] * * The config file api is identity_projection. */ class IdentityProjection : public Projection { public: IdentityProjection(const ProjectionConfig& config, const ParameterPtr& parameter, bool useGpu); virtual void forward(); virtual void backward(const UpdateCallback& callback); }; REGISTER_PROJECTION(identity, IdentityProjection); /** * Constructed function. * @note IdentityProjection should not have any parameter. */ IdentityProjection::IdentityProjection(const ProjectionConfig& config, const ParameterPtr& parameter, bool useGpu) : Projection(config, parameter, useGpu) { CHECK(!parameter) << "'identity' projection should not have any parameter"; } void IdentityProjection::forward() { out_->value->add(*in_->value); } void IdentityProjection::backward(const UpdateCallback& callback) { if (in_->grad) { in_->grad->add(*out_->grad); } } /** * IdentityOffsetProjection likes IdentityProjection, but layer size may be * smaller * than input size. It selects dimensions [offset, offset+layer_size) from input * to * perform addition: * \f[ * out.row[i] += in.row[i + \textrm{offset}] * \f] * * The config file api is identity_projection. */ class IdentityOffsetProjection : public Projection { public: IdentityOffsetProjection(const ProjectionConfig& config, const ParameterPtr& parameter, bool useGpu); virtual void forward(); virtual void backward(const UpdateCallback& callback); }; REGISTER_PROJECTION(identity_offset, IdentityOffsetProjection); /** * Constructed function. * @note IdentityOffsetProjection should not have any parameter. */ IdentityOffsetProjection::IdentityOffsetProjection( const ProjectionConfig& config, const ParameterPtr& parameter, bool useGpu) : Projection(config, parameter, useGpu) { CHECK(!parameter) << "'identity_offset' projection " "should not have any parameter"; CHECK_LE(config.output_size() + config.offset(), config.input_size()); } void IdentityOffsetProjection::forward() { out_->value->addAtOffset(*in_->value, config_.offset()); } void IdentityOffsetProjection::backward(const UpdateCallback& callback) { if (in_->grad) { in_->grad->addAtOffset(*out_->grad, config_.offset()); } } } // namespace paddle
#include "bottools.hpp" #include <stdlib.h> #include <unistd.h> #include <sstream> void error_exit(std::string const &s1) { std::cerr << s1 << std::endl; exit(1); } void ioerror(int sock, std::string const &msg) { close(sock); error_exit(msg); } int ft_stoi(std::string const &str) { std::istringstream iss(str); int val = 0; if (!(iss >> val)) return (0); return (val); } std::string ft_tostring(int val) { std::ostringstream oss; oss << val; return (oss.str()); } std::string ft_strtoupper(std::string const &str) { std::string res = str; for (int i = 0; res[i] != '\0'; i++) { if (res[i] >= 'a' && res[i] <= 'z') res[i] = std::toupper(res[i]); } return (res); } std::string ft_strtolower(std::string const &str) { std::string res = str; for (int i = 0; res[i] != '\0'; i++) { if (res[i] >= 'A' && res[i] <= 'Z') res[i] = std::tolower(res[i]); } return (res); } t_strvect ft_splitcmdbyspace(std::string msg) { t_strvect split; size_t pos = 0; std::string tmp; if ((pos = msg.find_last_not_of(" \t\f\v\n\r")) != std::string::npos) msg.erase(pos + 1); else return (split); if ((pos = msg.find_first_not_of(" \t\f\v\n\r")) != std::string::npos) msg = msg.substr(pos); else return (split); while ((pos = msg.find_first_of(" \t\f\v\n\r")) != std::string::npos) { tmp = msg.substr(0, pos); if (!tmp.empty()) split.push_back(tmp); msg.erase(0, pos + 1); if (!msg.empty() && msg[0] == ':') break ; } if (!msg.empty()) split.push_back(msg); if (split.back().size() > 0 && split.back()[0] == ':') split.back() = split.back().substr(1); return (split); } t_strvect ft_splitstringbyany(std::string msg, std::string const &delim) { t_strvect split; size_t pos = 0; std::string tmp; while ((pos = msg.find_first_of(delim)) != std::string::npos) { tmp = msg.substr(0, pos); if (!tmp.empty()) split.push_back(tmp); msg.erase(0, pos + 1); } if (!msg.empty()) split.push_back(msg); return (split); }
#include "steerable.h" #include "behaviors.h" using namespace glm; using namespace atk; float omegan = 8.0; float eta = 1.0; float ASteerable::kVelKv = 10.0; float ASteerable::kOriKv = 2.0 * omegan * eta; float ASteerable::kOriKp = omegan * omegan; // Given a desired velocity, veld, and dt, compute a transform holding // the new orientation and change in position // // rotation control: tau = I * (-Kv1 * thetaDot + Kp1 * (thetaD - theta)) // translation control: f = m * Kv0 * (vd - v) void ASteerable::senseControlAct(const vec3& veld, float dt) { // Compute _vd and _thetad _vd = length(veld); _thetad = atan2(veld.x, veld.z); // compute _force and _torque _force = _mass * kVelKv * (_vd - length(_state[VEL])) ; _torque = _inertia * (kOriKp*(_thetad - _state[ORI]) - kOriKv*_state[AVEL]); //_torque = 0.0; // find derivative _derivative[POS] = _state[VEL]; _derivative[ORI] = _state[AVEL]; _derivative[AVEL] = _torque/_inertia; _derivative[VEL] = _force/_mass; // update state _state[0]=_state[0] + dt* _derivative[0]; _state[1]=_state[1] + dt* _derivative[1]; _state[2]=_state[2] + dt* _derivative[2]; _state[3]=_state[3] + dt* _derivative[3]; // compute global position and orientation and update _characterRoot quat rot = glm::angleAxis(_state[ORI], vec3(0,1,0)); vec3 localPos(0,0,_state[POS]); _characterRoot.setT(rot * localPos + _characterRoot.t()); _characterRoot.setR(rot); std::cout << _thetad << " " << _vd << " " << _state[POS]<<std::endl; } // randomize the colors, characters, and animation times here void ASteerable::randomizeAppearance() { // to randomize the walking animations, compute different initial values // for _time _time = float(rand()%10)+3; // to randomize color, call _drawer.setColor _drawer.color = agl::randomUnitVector(); // to randomize shape, compute random values for _drawer.setJointRadius _drawer.jointRadius=float(rand()%10)+10; //_drawer.setJointRadius(agl::randomUnitVector()*10); // or randomly assign different drawers to have a mix of characters }
#include <UECS/World.h> #include <iostream> using namespace Ubpa::UECS; struct A {}; struct B {}; struct C {}; class PrintASystem : public System { public: using System::System; virtual void OnUpdate(Schedule& schedule) override { schedule.RegisterEntityJob([](A*) { std::cout << "A" << std::endl; }, "Parallel Print A"); auto spilt = schedule.RegisterJob([]() { std::cout << "vvvvvvvvvv" << std::endl; }, "Spilt"); schedule.RegisterEntityJob([](const A*) { std::cout << "A" << std::endl; }, "Serial Print A", false); schedule.Order("Parallel Print A", "Spilt"); schedule.Order("Spilt", "Serial Print A"); } }; int main() { World w; w.systemMngr.Register<PrintASystem>(); w.entityMngr.Create<A>(); w.entityMngr.Create<A, B>(); w.entityMngr.Create<A, C>(); w.entityMngr.Create<A, B, C>(); w.cmptTraits.Register <A, B, C>(); for (size_t i = 0; i < 5; i++) { w.Update(); std::cout << "^^^^^^^^^^" << std::endl; } for (size_t i = 0; i < 100; i++) w.entityMngr.Create(); w.RunEntityJob([](Entity e) { std::cout << e.Idx() << std::endl; }, false); std::cout << w.DumpUpdateJobGraph() << std::endl; std::cout << w.GenUpdateFrameGraph().Dump() << std::endl; }
/************************************************************************* * * REALM CONFIDENTIAL * __________________ * * [2011] - [2015] Realm Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Realm Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Realm Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Realm Incorporated. * **************************************************************************/ /* Searching: The main finding function is: template<class cond, Action action, size_t bitwidth, class Callback> void find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState *state, Callback callback) const cond: One of Equal, NotEqual, Greater, etc. classes Action: One of act_ReturnFirst, act_FindAll, act_Max, act_CallbackIdx, etc, constants Callback: Optional function to call for each search result. Will be called if action == act_CallbackIdx find() will call find_action_pattern() or find_action() that again calls match() for each search result which optionally calls callback(): find() -> find_action() -------> bool match() -> bool callback() | ^ +-> find_action_pattern()----+ If callback() returns false, find() will exit, otherwise it will keep searching remaining items in array. */ #ifndef REALM_ARRAY_HPP #define REALM_ARRAY_HPP #include <cmath> #include <cstdlib> // size_t #include <algorithm> #include <utility> #include <vector> #include <ostream> #include <stdint.h> // unint8_t etc #include <realm/util/meta.hpp> #include <realm/util/assert.hpp> #include <realm/util/file_mapper.hpp> #include <realm/utilities.hpp> #include <realm/alloc.hpp> #include <realm/string_data.hpp> #include <realm/query_conditions.hpp> #include <realm/column_fwd.hpp> /* MMX: mmintrin.h SSE: xmmintrin.h SSE2: emmintrin.h SSE3: pmmintrin.h SSSE3: tmmintrin.h SSE4A: ammintrin.h SSE4.1: smmintrin.h SSE4.2: nmmintrin.h */ #ifdef REALM_COMPILER_SSE # include <emmintrin.h> // SSE2 # include <realm/realm_nmmintrin.h> // SSE42 #endif namespace realm { enum Action {act_ReturnFirst, act_Sum, act_Max, act_Min, act_Count, act_FindAll, act_CallIdx, act_CallbackIdx, act_CallbackVal, act_CallbackNone, act_CallbackBoth, act_Average}; template<class T> inline T no0(T v) { return v == 0 ? 1 : v; } /// Special index value. It has various meanings depending on /// context. It is returned by some search functions to indicate 'not /// found'. It is similar in function to std::string::npos. const size_t npos = size_t(-1); // Maximum number of bytes that the payload of an array can be const size_t max_array_payload = 0x00ffffffL; /// Alias for realm::npos. const size_t not_found = npos; /* wid == 16/32 likely when accessing offsets in B tree */ #define REALM_TEMPEX(fun, wid, arg) \ if (wid == 16) {fun<16> arg;} \ else if (wid == 32) {fun<32> arg;} \ else if (wid == 0) {fun<0> arg;} \ else if (wid == 1) {fun<1> arg;} \ else if (wid == 2) {fun<2> arg;} \ else if (wid == 4) {fun<4> arg;} \ else if (wid == 8) {fun<8> arg;} \ else if (wid == 64) {fun<64> arg;} \ else {REALM_ASSERT_DEBUG(false); fun<0> arg;} #define REALM_TEMPEX2(fun, targ, wid, arg) \ if (wid == 16) {fun<targ, 16> arg;} \ else if (wid == 32) {fun<targ, 32> arg;} \ else if (wid == 0) {fun<targ, 0> arg;} \ else if (wid == 1) {fun<targ, 1> arg;} \ else if (wid == 2) {fun<targ, 2> arg;} \ else if (wid == 4) {fun<targ, 4> arg;} \ else if (wid == 8) {fun<targ, 8> arg;} \ else if (wid == 64) {fun<targ, 64> arg;} \ else {REALM_ASSERT_DEBUG(false); fun<targ, 0> arg;} #define REALM_TEMPEX3(fun, targ1, targ2, wid, arg) \ if (wid == 16) {fun<targ1, targ2, 16> arg;} \ else if (wid == 32) {fun<targ1, targ2, 32> arg;} \ else if (wid == 0) {fun<targ1, targ2, 0> arg;} \ else if (wid == 1) {fun<targ1, targ2, 1> arg;} \ else if (wid == 2) {fun<targ1, targ2, 2> arg;} \ else if (wid == 4) {fun<targ1, targ2, 4> arg;} \ else if (wid == 8) {fun<targ1, targ2, 8> arg;} \ else if (wid == 64) {fun<targ1, targ2, 64> arg;} \ else {REALM_ASSERT_DEBUG(false); fun<targ1, targ2, 0> arg;} #define REALM_TEMPEX4(fun, targ1, targ2, wid, targ3, arg) \ if (wid == 16) {fun<targ1, targ2, 16, targ3> arg;} \ else if (wid == 32) {fun<targ1, targ2, 32, targ3> arg;} \ else if (wid == 0) {fun<targ1, targ2, 0, targ3> arg;} \ else if (wid == 1) {fun<targ1, targ2, 1, targ3> arg;} \ else if (wid == 2) {fun<targ1, targ2, 2, targ3> arg;} \ else if (wid == 4) {fun<targ1, targ2, 4, targ3> arg;} \ else if (wid == 8) {fun<targ1, targ2, 8, targ3> arg;} \ else if (wid == 64) {fun<targ1, targ2, 64, targ3> arg;} \ else {REALM_ASSERT_DEBUG(false); fun<targ1, targ2, 0, targ3> arg;} #define REALM_TEMPEX5(fun, targ1, targ2, targ3, targ4, wid, arg) \ if (wid == 16) {fun<targ1, targ2, targ3, targ4, 16> arg;} \ else if (wid == 32) {fun<targ1, targ2, targ3, targ4, 32> arg;} \ else if (wid == 0) {fun<targ1, targ2, targ3, targ4, 0> arg;} \ else if (wid == 1) {fun<targ1, targ2, targ3, targ4, 1> arg;} \ else if (wid == 2) {fun<targ1, targ2, targ3, targ4, 2> arg;} \ else if (wid == 4) {fun<targ1, targ2, targ3, targ4, 4> arg;} \ else if (wid == 8) {fun<targ1, targ2, targ3, targ4, 8> arg;} \ else if (wid == 64) {fun<targ1, targ2, targ3, targ4, 64> arg;} \ else {REALM_ASSERT_DEBUG(false); fun<targ1, targ2, targ3, targ4, 0> arg;} // Pre-definitions class Array; class StringColumn; class GroupWriter; template<class T> class QueryState; namespace _impl { class ArrayWriterBase; } #ifdef REALM_DEBUG class MemStats { public: MemStats(): allocated(0), used(0), array_count(0) { } size_t allocated; size_t used; size_t array_count; }; #endif class ArrayParent { public: virtual ~ArrayParent() noexcept {} protected: virtual void update_child_ref(size_t child_ndx, ref_type new_ref) = 0; virtual ref_type get_child_ref(size_t child_ndx) const noexcept = 0; #ifdef REALM_DEBUG // Used only by Array::to_dot(). virtual std::pair<ref_type, size_t> get_to_dot_parent(size_t ndx_in_parent) const = 0; #endif friend class Array; }; /// Provides access to individual array nodes of the database. /// /// This class serves purely as an accessor, it assumes no ownership of the /// referenced memory. /// /// An array accessor can be in one of two states: attached or unattached. It is /// in the attached state if, and only if is_attached() returns true. Most /// non-static member functions of this class have undefined behaviour if the /// accessor is in the unattached state. The exceptions are: is_attached(), /// detach(), create(), init_from_ref(), init_from_mem(), init_from_parent(), /// has_parent(), get_parent(), set_parent(), get_ndx_in_parent(), /// set_ndx_in_parent(), adjust_ndx_in_parent(), and get_ref_from_parent(). /// /// An array accessor contains information about the parent of the referenced /// array node. This 'reverse' reference is not explicitely present in the /// underlying node hierarchy, but it is needed when modifying an array. A /// modification may lead to relocation of the underlying array node, and the /// parent must be updated accordingly. Since this applies recursivly all the /// way to the root node, it is essential that the entire chain of parent /// accessors is constructed and propperly maintained when a particular array is /// modified. /// /// The parent reference (`pointer to parent`, `index in parent`) is updated /// independently from the state of attachment to an underlying node. In /// particular, the parent reference remains valid and is unannfected by changes /// in attachment. These two aspects of the state of the accessor is updated /// independently, and it is entirely the responsibility of the caller to update /// them such that they are consistent with the underlying node hierarchy before /// calling any method that modifies the underlying array node. /// /// FIXME: This class currently has fragments of ownership, in particular the /// constructors that allocate underlying memory. On the other hand, the /// destructor never frees the memory. This is a disastrous situation, because /// it so easily becomes an obscure source of leaks. There are three options for /// a fix of which the third is most attractive but hardest to implement: (1) /// Remove all traces of ownership semantics, that is, remove the constructors /// that allocate memory, but keep the trivial copy constructor. For this to /// work, it is important that the constness of the accessor has nothing to do /// with the constness of the underlying memory, otherwise constness can be /// violated simply by copying the accessor. (2) Disallov copying but associate /// the constness of the accessor with the constness of the underlying /// memory. (3) Provide full ownership semantics like is done for Table /// accessors, and provide a proper copy constructor that really produces a copy /// of the array. For this to work, the class should assume ownership if, and /// only if there is no parent. A copy produced by a copy constructor will not /// have a parent. Even if the original was part of a database, the copy will be /// free-standing, that is, not be part of any database. For intra, or inter /// database copying, one would have to also specify the target allocator. class Array: public ArrayParent { public: // void state_init(int action, QueryState *state); // bool match(int action, size_t index, int64_t value, QueryState *state); /// Create an array accessor in the unattached state. explicit Array(Allocator&) noexcept; // Fastest way to instantiate an array, if you just want to utilize its // methods struct no_prealloc_tag {}; explicit Array(no_prealloc_tag) noexcept; ~Array() noexcept override {} enum Type { type_Normal, /// This array is the main array of an innner node of a B+-tree as used /// in table columns. type_InnerBptreeNode, /// This array may contain refs to subarrays. An element whose least /// significant bit is zero, is a ref pointing to a subarray. An element /// whose least significant bit is one, is just a value. It is the /// responsibility of the application to ensure that non-ref values have /// their least significant bit set. This will generally be done by /// shifting the desired vlue to the left by one bit position, and then /// setting the vacated bit to one. type_HasRefs }; /// Create a new integer array of the specified type and size, and filled /// with the specified value, and attach this accessor to it. This does not /// modify the parent reference information of this accessor. /// /// Note that the caller assumes ownership of the allocated underlying /// node. It is not owned by the accessor. void create(Type, bool context_flag = false, size_t size = 0, int_fast64_t value = 0); /// Reinitialize this array accessor to point to the specified new /// underlying memory. This does not modify the parent reference information /// of this accessor. void init_from_ref(ref_type) noexcept; /// Same as init_from_ref(ref_type) but avoid the mapping of 'ref' to memory /// pointer. void init_from_mem(MemRef) noexcept; /// Same as `init_from_ref(get_ref_from_parent())`. void init_from_parent() noexcept; /// Update the parents reference to this child. This requires, of course, /// that the parent information stored in this child is up to date. If the /// parent pointer is set to null, this function has no effect. void update_parent(); /// Called in the context of Group::commit() to ensure that attached /// accessors stay valid across a commit. Please note that this works only /// for non-transactional commits. Accessors obtained during a transaction /// are always detached when the transaction ends. /// /// Returns true if, and only if the array has changed. If the array has not /// changed, then its children are guaranteed to also not have changed. bool update_from_parent(size_t old_baseline) noexcept; /// Change the type of an already attached array node. /// /// The effect of calling this function on an unattached accessor is /// undefined. void set_type(Type); /// Construct a complete copy of this array (including its subarrays) using /// the specified target allocator and return just the reference to the /// underlying memory. MemRef clone_deep(Allocator& target_alloc) const; void move_assign(Array&) noexcept; // Move semantics for assignment /// Construct an empty integer array of the specified type, and return just /// the reference to the underlying memory. static MemRef create_empty_array(Type, bool context_flag, Allocator&); /// Construct an integer array of the specified type and size, and return /// just the reference to the underlying memory. All elements will be /// initialized to the specified value. static MemRef create_array(Type, bool context_flag, size_t size, int_fast64_t value, Allocator&); /// Construct a shallow copy of the specified slice of this array using the /// specified target allocator. Subarrays will **not** be cloned. See /// slice_and_clone_children() for an alternative. MemRef slice(size_t offset, size_t size, Allocator& target_alloc) const; /// Construct a deep copy of the specified slice of this array using the /// specified target allocator. Subarrays will be cloned. MemRef slice_and_clone_children(size_t offset, size_t size, Allocator& target_alloc) const; // Parent tracking bool has_parent() const noexcept; ArrayParent* get_parent() const noexcept; /// Setting a new parent affects ownership of the attached array node, if /// any. If a non-null parent is specified, and there was no parent /// originally, then the caller passes ownership to the parent, and vice /// versa. This assumes, of course, that the change in parentship reflects a /// corresponding change in the list of children in the affected parents. void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept; size_t get_ndx_in_parent() const noexcept; void set_ndx_in_parent(size_t) noexcept; void adjust_ndx_in_parent(int diff) noexcept; /// Get the ref of this array as known to the parent. The caller must ensure /// that the parent information ('pointer to parent' and 'index in parent') /// is correct before calling this function. ref_type get_ref_from_parent() const noexcept; bool is_attached() const noexcept; /// Detach from the underlying array node. This method has no effect if the /// accessor is currently unattached (idempotency). void detach() noexcept; size_t size() const noexcept; bool is_empty() const noexcept; Type get_type() const noexcept; static void add_to_column(IntegerColumn* column, int64_t value); void insert(size_t ndx, int_fast64_t value); void add(int_fast64_t value); /// This function is guaranteed to not throw if the current width is /// sufficient for the specified value (e.g. if you have called /// ensure_minimum_width(value)) and get_alloc().is_read_only(get_ref()) /// returns false (noexcept:array-set). Note that for a value of zero, the /// first criterion is trivially satisfied. void set(size_t ndx, int64_t value); void set_as_ref(size_t ndx, ref_type ref); template<size_t w> void set(size_t ndx, int64_t value); int64_t get(size_t ndx) const noexcept; template<size_t w> int64_t get(size_t ndx) const noexcept; void get_chunk(size_t ndx, int64_t res[8]) const noexcept; template<size_t w> void get_chunk(size_t ndx, int64_t res[8]) const noexcept; ref_type get_as_ref(size_t ndx) const noexcept; int64_t front() const noexcept; int64_t back() const noexcept; /// Remove the element at the specified index, and move elements at higher /// indexes to the next lower index. /// /// This function does **not** destroy removed subarrays. That is, if the /// erased element is a 'ref' pointing to a subarray, then that subarray /// will not be destroyed automatically. /// /// This function guarantees that no exceptions will be thrown if /// get_alloc().is_read_only(get_ref()) would return false before the /// call. This is automatically guaranteed if the array is used in a /// non-transactional context, or if the array has already been successfully /// modified within the current write transaction. void erase(size_t ndx); /// Same as erase(size_t), but remove all elements in the specified /// range. /// /// Please note that this function does **not** destroy removed subarrays. /// /// This function guarantees that no exceptions will be thrown if /// get_alloc().is_read_only(get_ref()) would return false before the call. void erase(size_t begin, size_t end); /// Reduce the size of this array to the specified number of elements. It is /// an error to specify a size that is greater than the current size of this /// array. The effect of doing so is undefined. This is just a shorthand for /// calling the ranged erase() function with appropriate arguments. /// /// Please note that this function does **not** destroy removed /// subarrays. See clear_and_destroy_children() for an alternative. /// /// This function guarantees that no exceptions will be thrown if /// get_alloc().is_read_only(get_ref()) would return false before the call. void truncate(size_t size); /// Reduce the size of this array to the specified number of elements. It is /// an error to specify a size that is greater than the current size of this /// array. The effect of doing so is undefined. Subarrays will be destroyed /// recursively, as if by a call to `destroy_deep(subarray_ref, alloc)`. /// /// This function is guaranteed not to throw if /// get_alloc().is_read_only(get_ref()) returns false. void truncate_and_destroy_children(size_t size); /// Remove every element from this array. This is just a shorthand for /// calling truncate(0). /// /// Please note that this function does **not** destroy removed /// subarrays. See clear_and_destroy_children() for an alternative. /// /// This function guarantees that no exceptions will be thrown if /// get_alloc().is_read_only(get_ref()) would return false before the call. void clear(); /// Remove every element in this array. Subarrays will be destroyed /// recursively, as if by a call to `destroy_deep(subarray_ref, /// alloc)`. This is just a shorthand for calling /// truncate_and_destroy_children(0). /// /// This function guarantees that no exceptions will be thrown if /// get_alloc().is_read_only(get_ref()) would return false before the call. void clear_and_destroy_children(); /// If neccessary, expand the representation so that it can store the /// specified value. void ensure_minimum_width(int_fast64_t value); typedef StringData (*StringGetter)(void*, size_t, char*); // Pre-declare getter function from string index size_t index_string_find_first(StringData value, ColumnBase* column) const; void index_string_find_all(IntegerColumn& result, StringData value, ColumnBase* column) const; size_t index_string_count(StringData value, ColumnBase* column) const; FindRes index_string_find_all_no_copy(StringData value, size_t& res_ref, ColumnBase* column) const; /// This one may change the represenation of the array, so be carefull if /// you call it after ensure_minimum_width(). void set_all_to_zero(); /// Add \a diff to the element at the specified index. void adjust(size_t ndx, int_fast64_t diff); /// Add \a diff to all the elements in the specified index range. void adjust(size_t begin, size_t end, int_fast64_t diff); /// Add signed \a diff to all elements that are greater than, or equal to \a /// limit. void adjust_ge(int_fast64_t limit, int_fast64_t diff); //@{ /// These are similar in spirit to std::move() and std::move_backward from /// <algorithm>. \a dest_begin must not be in the range [`begin`,`end`), and /// \a dest_end must not be in the range (`begin`,`end`]. /// /// These functions are guaranteed to not throw if /// `get_alloc().is_read_only(get_ref())` returns false. void move(size_t begin, size_t end, size_t dest_begin); void move_backward(size_t begin, size_t end, size_t dest_end); //@} /// move_rotate moves one element from \a from to be located at index \a to, /// shifting all elements inbetween by one. /// /// If \a from is larger than \a to, the elements inbetween are shifted down. /// If \a to is larger than \a from, the elements inbetween are shifted up. /// /// This function is guaranteed to not throw if /// `get_alloc().is_read_only(get_ref())` returns false. void move_rotate(size_t from, size_t to, size_t num_elems = 1); //@{ /// Find the lower/upper bound of the specified value in a sequence of /// integers which must already be sorted ascendingly. /// /// For an integer value '`v`', lower_bound_int(v) returns the index '`l`' /// of the first element such that `get(l) &ge; v`, and upper_bound_int(v) /// returns the index '`u`' of the first element such that `get(u) &gt; /// v`. In both cases, if no such element is found, the returned value is /// the number of elements in the array. /// /// 3 3 3 4 4 4 5 6 7 9 9 9 /// ^ ^ ^ ^ ^ /// | | | | | /// | | | | -- Lower and upper bound of 15 /// | | | | /// | | | -- Lower and upper bound of 8 /// | | | /// | | -- Upper bound of 4 /// | | /// | -- Lower bound of 4 /// | /// -- Lower and upper bound of 1 /// /// These functions are similar to std::lower_bound() and /// std::upper_bound(). /// /// We currently use binary search. See for example /// http://www.tbray.org/ongoing/When/200x/2003/03/22/Binary. /// /// FIXME: It may be worth considering if overall efficiency can be improved /// by doing a linear search for short sequences. size_t lower_bound_int(int64_t value) const noexcept; size_t upper_bound_int(int64_t value) const noexcept; //@} /// \brief Search the \c Array for a value greater or equal than \a target, /// starting the search at the \a start index. If \a indirection is /// provided, use it as a look-up table to iterate over the \c Array. /// /// If \a indirection is not provided, then the \c Array must be sorted in /// ascending order. If \a indirection is provided, then its values should /// point to indices in this \c Array in such a way that iteration happens /// in ascending order. /// /// Behaviour is undefined if: /// - a value in \a indirection is out of bounds for this \c Array; /// - \a indirection does not contain at least as many elements as this \c /// Array; /// - sorting conditions are not respected; /// - \a start is greater than the number of elements in this \c Array or /// \a indirection (if provided). /// /// \param target the smallest value to search for /// \param start the offset at which to start searching in the array /// \param indirection an \c Array containing valid indices of values in /// this \c Array, sorted in ascending order /// \return the index of the value if found, or realm::not_found otherwise size_t find_gte(const int64_t target, size_t start, Array const* indirection) const; void preset(int64_t min, int64_t max, size_t count); void preset(size_t bitwidth, size_t count); int64_t sum(size_t start = 0, size_t end = size_t(-1)) const; size_t count(int64_t value) const noexcept; bool maximum(int64_t& result, size_t start = 0, size_t end = size_t(-1), size_t* return_ndx = nullptr) const; bool minimum(int64_t& result, size_t start = 0, size_t end = size_t(-1), size_t* return_ndx = nullptr) const; /// This information is guaranteed to be cached in the array accessor. bool is_inner_bptree_node() const noexcept; /// Returns true if type is either type_HasRefs or type_InnerColumnNode. /// /// This information is guaranteed to be cached in the array accessor. bool has_refs() const noexcept; /// This information is guaranteed to be cached in the array accessor. /// /// Columns and indexes can use the context bit to differentiate leaf types. bool get_context_flag() const noexcept; void set_context_flag(bool) noexcept; ref_type get_ref() const noexcept; MemRef get_mem() const noexcept; /// Destroy only the array that this accessor is attached to, not the /// children of that array. See non-static destroy_deep() for an /// alternative. If this accessor is already in the detached state, this /// function has no effect (idempotency). void destroy() noexcept; /// Recursively destroy children (as if calling /// clear_and_destroy_children()), then put this accessor into the detached /// state (as if calling detach()), then free the allocated memory. If this /// accessor is already in the detached state, this function has no effect /// (idempotency). void destroy_deep() noexcept; /// Shorthand for `destroy(MemRef(ref, alloc), alloc)`. static void destroy(ref_type ref, Allocator& alloc) noexcept; /// Destroy only the specified array node, not its children. See also /// destroy_deep(MemRef, Allocator&). static void destroy(MemRef, Allocator&) noexcept; /// Shorthand for `destroy_deep(MemRef(ref, alloc), alloc)`. static void destroy_deep(ref_type ref, Allocator& alloc) noexcept; /// Destroy the specified array node and all of its children, recursively. /// /// This is done by freeing the specified array node after calling /// destroy_deep() for every contained 'ref' element. static void destroy_deep(MemRef, Allocator&) noexcept; Allocator& get_alloc() const noexcept { return m_alloc; } // Serialization /// Returns the ref (position in the target stream) of the written copy of /// this array, or the ref of the original array if \a only_if_modified is /// true, and this array is unmodified (Alloc::is_read_only()). /// /// The number of bytes that will be written by a non-recursive invocation /// of this function is exactly the number returned by get_byte_size(). /// /// \param deep If true, recursively write out subarrays, but still subject /// to \a only_if_modified. ref_type write(_impl::ArrayWriterBase&, bool deep, bool only_if_modified) const; /// Same as non-static write() with `deep` set to true. This is for the /// cases where you do not already have an array accessor available. static ref_type write(ref_type, Allocator&, _impl::ArrayWriterBase&, bool only_if_modified); // Main finding function - used for find_first, find_all, sum, max, min, etc. bool find(int cond, Action action, int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, bool nullable_array = false, bool find_null = false) const; // Templated find function to avoid conversion to and from integer represenation of condition template <class cond> bool find(Action action, int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t> *state, bool nullable_array = false, bool find_null = false) const { if (action == act_ReturnFirst) { REALM_TEMPEX3(return find, cond, act_ReturnFirst, m_width, (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null)) } else if (action == act_Sum) { REALM_TEMPEX3(return find, cond, act_Sum, m_width, (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null)) } else if (action == act_Min) { REALM_TEMPEX3(return find, cond, act_Min, m_width, (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null)) } else if (action == act_Max) { REALM_TEMPEX3(return find, cond, act_Max, m_width, (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null)) } else if (action == act_Count) { REALM_TEMPEX3(return find, cond, act_Count, m_width, (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null)) } else if (action == act_FindAll) { REALM_TEMPEX3(return find, cond, act_FindAll, m_width, (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null)) } else if (action == act_CallbackIdx) { REALM_TEMPEX3(return find, cond, act_CallbackIdx, m_width, (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null)) } REALM_ASSERT_DEBUG(false); return false; } /* bool find(int cond, Action action, null, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state) const; */ template<class cond, Action action, size_t bitwidth, class Callback> bool find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback, bool nullable_array = false, bool find_null = false) const; // This is the one installed into the m_vtable->finder slots. template<class cond, Action action, size_t bitwidth> bool find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state) const; template<class cond, Action action, class Callback> bool find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback, bool nullable_array = false, bool find_null = false) const; /* template<class cond, Action action, class Callback> bool find(null, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback) const; */ // Optimized implementation for release mode template<class cond, Action action, size_t bitwidth, class Callback> bool find_optimized(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback, bool nullable_array = false, bool find_null = false) const; // Called for each search result template<Action action, class Callback> bool find_action(size_t index, util::Optional<int64_t> value, QueryState<int64_t>* state, Callback callback) const; template<Action action, class Callback> bool find_action_pattern(size_t index, uint64_t pattern, QueryState<int64_t>* state, Callback callback) const; // Wrappers for backwards compatibility and for simple use without // setting up state initialization etc template<class cond> size_t find_first(int64_t value, size_t start = 0, size_t end = size_t(-1)) const; void find_all(IntegerColumn* result, int64_t value, size_t col_offset = 0, size_t begin = 0, size_t end = size_t(-1)) const; size_t find_first(int64_t value, size_t begin = 0, size_t end = size_t(-1)) const; // Non-SSE find for the four functions Equal/NotEqual/Less/Greater template<class cond, Action action, size_t bitwidth, class Callback> bool compare(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback) const; // Non-SSE find for Equal/NotEqual template<bool eq, Action action, size_t width, class Callback> inline bool compare_equality(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback) const; // Non-SSE find for Less/Greater template<bool gt, Action action, size_t bitwidth, class Callback> bool compare_relation(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback) const; template<class cond, Action action, size_t foreign_width, class Callback, size_t width> bool compare_leafs_4(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback) const; template<class cond, Action action, class Callback, size_t bitwidth, size_t foreign_bitwidth> bool compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback) const; template<class cond, Action action, class Callback> bool compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback) const; template<class cond, Action action, size_t width, class Callback> bool compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback) const; // SSE find for the four functions Equal/NotEqual/Less/Greater #ifdef REALM_COMPILER_SSE template<class cond, Action action, size_t width, class Callback> bool find_sse(int64_t value, __m128i *data, size_t items, QueryState<int64_t>* state, size_t baseindex, Callback callback) const; template<class cond, Action action, size_t width, class Callback> REALM_FORCEINLINE bool find_sse_intern(__m128i* action_data, __m128i* data, size_t items, QueryState<int64_t>* state, size_t baseindex, Callback callback) const; #endif template<size_t width> inline bool test_zero(uint64_t value) const; // Tests value for 0-elements template<bool eq, size_t width> size_t find_zero(uint64_t v) const; // Finds position of 0/non-zero element template<size_t width, bool zero> uint64_t cascade(uint64_t a) const; // Sets lowermost bits of zero or non-zero elements template<bool gt, size_t width> int64_t find_gtlt_magic(int64_t v) const; // Compute magic constant needed for searching for value 'v' using bit hacks template<size_t width> inline int64_t lower_bits() const; // Return chunk with lower bit set in each element size_t first_set_bit(unsigned int v) const; size_t first_set_bit64(int64_t v) const; template<size_t w> int64_t get_universal(const char* const data, const size_t ndx) const; // Find value greater/less in 64-bit chunk - only works for positive values template<bool gt, Action action, size_t width, class Callback> bool find_gtlt_fast(uint64_t chunk, uint64_t magic, QueryState<int64_t>* state, size_t baseindex, Callback callback) const; // Find value greater/less in 64-bit chunk - no constraints template<bool gt, Action action, size_t width, class Callback> bool find_gtlt(int64_t v, uint64_t chunk, QueryState<int64_t>* state, size_t baseindex, Callback callback) const; /// Get the number of elements in the B+-tree rooted at this array /// node. The root must not be a leaf. /// /// Please avoid using this function (consider it deprecated). It /// will have to be removed if we choose to get rid of the last /// element of the main array of an inner B+-tree node that stores /// the total number of elements in the subtree. The motivation /// for removing it, is that it will significantly improve the /// efficiency when inserting after, and erasing the last element. size_t get_bptree_size() const noexcept; /// The root must not be a leaf. static size_t get_bptree_size_from_header(const char* root_header) noexcept; /// Find the leaf node corresponding to the specified element /// index index. The specified element index must refer to an /// element that exists in the tree. This function must be called /// on an inner B+-tree node, never a leaf. Note that according to /// invar:bptree-nonempty-inner and invar:bptree-nonempty-leaf, an /// inner B+-tree node can never be empty. /// /// This function is not obliged to instantiate intermediate array /// accessors. For this reason, this function cannot be used for /// operations that modify the tree, as that requires an unbroken /// chain of parent array accessors between the root and the /// leaf. Thus, despite the fact that the returned MemRef object /// appears to allow modification of the referenced memory, the /// caller must handle the memory reference as if it was /// const-qualified. /// /// \return (`leaf_header`, `ndx_in_leaf`) where `leaf_header` /// points to the the header of the located leaf, and /// `ndx_in_leaf` is the local index within that leaf /// corresponding to the specified element index. std::pair<MemRef, size_t> get_bptree_leaf(size_t elem_ndx) const noexcept; class NodeInfo; class VisitHandler; /// Visit leaves of the B+-tree rooted at this inner node, /// starting with the leaf that contains the element at the /// specified element index start offset, and ending when the /// handler returns false. The specified element index offset must /// refer to an element that exists in the tree. This function /// must be called on an inner B+-tree node, never a leaf. Note /// that according to invar:bptree-nonempty-inner and /// invar:bptree-nonempty-leaf, an inner B+-tree node can never be /// empty. /// /// \param elems_in_tree The total number of element in the tree. /// /// \return True if, and only if the handler has returned true for /// all visited leafs. bool visit_bptree_leaves(size_t elem_ndx_offset, size_t elems_in_tree, VisitHandler&); class UpdateHandler; /// Call the handler for every leaf. This function must be called /// on an inner B+-tree node, never a leaf. void update_bptree_leaves(UpdateHandler&); /// Call the handler for the leaf that contains the element at the /// specified index. This function must be called on an inner /// B+-tree node, never a leaf. void update_bptree_elem(size_t elem_ndx, UpdateHandler&); class EraseHandler; /// Erase the element at the specified index in the B+-tree with /// the specified root. When erasing the last element, you must /// pass npos in place of the index. This function must be called /// with a root that is an inner B+-tree node, never a leaf. /// /// This function is guaranteed to succeed (not throw) if the /// specified element was inserted during the current transaction, /// and no other modifying operation has been carried out since /// then (noexcept:bptree-erase-alt). /// /// FIXME: ExceptionSafety: The exception guarantee explained /// above is not as powerfull as we would like it to be. Here is /// what we would like: This function is guaranteed to succeed /// (not throw) if the specified element was inserted during the /// current transaction (noexcept:bptree-erase). This must be true /// even if the element is modified after insertion, and/or if /// other elements are inserted or erased around it. There are two /// aspects of the current design that stand in the way of this /// guarantee: (A) The fact that the node accessor, that is cached /// in the column accessor, has to be reallocated/reinstantiated /// when the root switches between being a leaf and an inner /// node. This problem would go away if we always cached the last /// used leaf accessor in the column accessor instead. (B) The /// fact that replacing one child ref with another can fail, /// because it may require reallocation of memory to expand the /// bit-width. This can be fixed in two ways: Either have the /// inner B+-tree nodes always have a bit-width of 64, or allow /// the root node to be discarded and the column ref to be set to /// zero in Table::m_columns. static void erase_bptree_elem(Array* root, size_t elem_ndx, EraseHandler&); struct TreeInsertBase { size_t m_split_offset; size_t m_split_size; }; template<class TreeTraits> struct TreeInsert: TreeInsertBase { typename TreeTraits::value_type m_value; bool m_nullable; }; /// Same as bptree_insert() but insert after the last element. template<class TreeTraits> ref_type bptree_append(TreeInsert<TreeTraits>& state); /// Insert an element into the B+-subtree rooted at this array /// node. The element is inserted before the specified element /// index. This function must be called on an inner B+-tree node, /// never a leaf. If this inner node had to be split, this /// function returns the `ref` of the new sibling. template<class TreeTraits> ref_type bptree_insert(size_t elem_ndx, TreeInsert<TreeTraits>& state); ref_type bptree_leaf_insert(size_t ndx, int64_t, TreeInsertBase& state); /// Get the specified element without the cost of constructing an /// array instance. If an array instance is already available, or /// you need to get multiple values, then this method will be /// slower. static int_fast64_t get(const char* header, size_t ndx) noexcept; /// Like get(const char*, size_t) but gets two consecutive /// elements. static std::pair<int64_t, int64_t> get_two(const char* header, size_t ndx) noexcept; static void get_three(const char* data, size_t ndx, ref_type& v0, ref_type& v1, ref_type& v2) noexcept; /// The meaning of 'width' depends on the context in which this /// array is used. size_t get_width() const noexcept { return m_width; } static char* get_data_from_header(char*) noexcept; static char* get_header_from_data(char*) noexcept; static const char* get_data_from_header(const char*) noexcept; enum WidthType { wtype_Bits = 0, wtype_Multiply = 1, wtype_Ignore = 2 }; static bool get_is_inner_bptree_node_from_header(const char*) noexcept; static bool get_hasrefs_from_header(const char*) noexcept; static bool get_context_flag_from_header(const char*) noexcept; static WidthType get_wtype_from_header(const char*) noexcept; static size_t get_width_from_header(const char*) noexcept; static size_t get_size_from_header(const char*) noexcept; static Type get_type_from_header(const char*) noexcept; /// Get the number of bytes currently in use by this array. This /// includes the array header, but it does not include allocated /// bytes corresponding to excess capacity. The result is /// guaranteed to be a multiple of 8 (i.e., 64-bit aligned). /// /// This number is exactly the number of bytes that will be /// written by a non-recursive invocation of write(). size_t get_byte_size() const noexcept; /// Get the maximum number of bytes that can be written by a /// non-recursive invocation of write() on an array with the /// specified number of elements, that is, the maximum value that /// can be returned by get_byte_size(). static size_t get_max_byte_size(size_t num_elems) noexcept; /// FIXME: Belongs in IntegerArray static size_t calc_aligned_byte_size(size_t size, int width); #ifdef REALM_DEBUG void print() const; void verify() const; typedef size_t (*LeafVerifier)(MemRef, Allocator&); void verify_bptree(LeafVerifier) const; class MemUsageHandler { public: virtual void handle(ref_type ref, size_t allocated, size_t used) = 0; }; void report_memory_usage(MemUsageHandler&) const; void stats(MemStats& stats) const; typedef void (*LeafDumper)(MemRef, Allocator&, std::ostream&, int level); void dump_bptree_structure(std::ostream&, int level, LeafDumper) const; void to_dot(std::ostream&, StringData title = StringData()) const; class ToDotHandler { public: virtual void to_dot(MemRef leaf_mem, ArrayParent*, size_t ndx_in_parent, std::ostream&) = 0; ~ToDotHandler() {} }; void bptree_to_dot(std::ostream&, ToDotHandler&) const; void to_dot_parent_edge(std::ostream&) const; #endif static const int header_size = 8; // Number of bytes used by header // The encryption layer relies on headers always fitting within a single page. static_assert(header_size == 8, "Header must always fit in entirely on a page"); private: Array& operator=(const Array&); // not allowed protected: typedef bool(*CallbackDummy)(int64_t); /// Insert a new child after original. If the parent has to be /// split, this function returns the `ref` of the new parent node. ref_type insert_bptree_child(Array& offsets, size_t orig_child_ndx, ref_type new_sibling_ref, TreeInsertBase& state); void ensure_bptree_offsets(Array& offsets); void create_bptree_offsets(Array& offsets, int_fast64_t first_value); bool do_erase_bptree_elem(size_t elem_ndx, EraseHandler&); template<IndexMethod method, class T> size_t index_string(StringData value, IntegerColumn& result, ref_type& result_ref, ColumnBase* column) const; protected: // void add_positive_local(int64_t value); // Includes array header. Not necessarily 8-byte aligned. virtual size_t calc_byte_len(size_t size, size_t width) const; virtual size_t calc_item_count(size_t bytes, size_t width) const noexcept; virtual WidthType GetWidthType() const { return wtype_Bits; } bool get_is_inner_bptree_node_from_header() const noexcept; bool get_hasrefs_from_header() const noexcept; bool get_context_flag_from_header() const noexcept; WidthType get_wtype_from_header() const noexcept; size_t get_width_from_header() const noexcept; size_t get_size_from_header() const noexcept; // Undefined behavior if m_alloc.is_read_only(m_ref) returns true size_t get_capacity_from_header() const noexcept; void set_header_is_inner_bptree_node(bool value) noexcept; void set_header_hasrefs(bool value) noexcept; void set_header_context_flag(bool value) noexcept; void set_header_wtype(WidthType value) noexcept; void set_header_width(int value) noexcept; void set_header_size(size_t value) noexcept; void set_header_capacity(size_t value) noexcept; static void set_header_is_inner_bptree_node(bool value, char* header) noexcept; static void set_header_hasrefs(bool value, char* header) noexcept; static void set_header_context_flag(bool value, char* header) noexcept; static void set_header_wtype(WidthType value, char* header) noexcept; static void set_header_width(int value, char* header) noexcept; static void set_header_size(size_t value, char* header) noexcept; static void set_header_capacity(size_t value, char* header) noexcept; static void init_header(char* header, bool is_inner_bptree_node, bool has_refs, bool context_flag, WidthType width_type, int width, size_t size, size_t capacity) noexcept; // This returns the minimum value ("lower bound") of the representable values // for the given bit width. Valid widths are 0, 1, 2, 4, 8, 16, 32, and 64. template<size_t width> static int_fast64_t lbound_for_width() noexcept; static int_fast64_t lbound_for_width(size_t width) noexcept; // This returns the maximum value ("inclusive upper bound") of the representable values // for the given bit width. Valid widths are 0, 1, 2, 4, 8, 16, 32, and 64. template<size_t width> static int_fast64_t ubound_for_width() noexcept; static int_fast64_t ubound_for_width(size_t width) noexcept; template<size_t width> void set_width() noexcept; void set_width(size_t) noexcept; void alloc(size_t count, size_t width); void copy_on_write(); private: template<size_t w> int64_t sum(size_t start, size_t end) const; template<bool max, size_t w> bool minmax(int64_t& result, size_t start, size_t end, size_t* return_ndx) const; template<size_t w> size_t find_gte(const int64_t target, size_t start, Array const* indirection) const; protected: /// The total size in bytes (including the header) of a new empty /// array. Must be a multiple of 8 (i.e., 64-bit aligned). static const size_t initial_capacity = 128; /// It is an error to specify a non-zero value unless the width /// type is wtype_Bits. It is also an error to specify a non-zero /// size if the width type is wtype_Ignore. static MemRef create(Type, bool context_flag, WidthType, size_t size, int_fast64_t value, Allocator&); static MemRef clone(MemRef header, Allocator& alloc, Allocator& target_alloc); /// Get the address of the header of this array. char* get_header() noexcept; /// Same as get_byte_size(). static size_t get_byte_size_from_header(const char*) noexcept; // Undefined behavior if array is in immutable memory static size_t get_capacity_from_header(const char*) noexcept; // Overriding method in ArrayParent void update_child_ref(size_t, ref_type) override; // Overriding method in ArrayParent ref_type get_child_ref(size_t) const noexcept override; void destroy_children(size_t offset = 0) noexcept; #ifdef REALM_DEBUG std::pair<ref_type, size_t> get_to_dot_parent(size_t ndx_in_parent) const override; #endif protected: // Getters and Setters for adaptive-packed arrays typedef int64_t (Array::*Getter)(size_t) const; // Note: getters must not throw typedef void (Array::*Setter)(size_t, int64_t); typedef bool (Array::*Finder)(int64_t, size_t, size_t, size_t, QueryState<int64_t>*) const; typedef void (Array::*ChunkGetter)(size_t, int64_t res[8]) const; // Note: getters must not throw struct VTable { Getter getter; ChunkGetter chunk_getter; Setter setter; Finder finder[cond_VTABLE_FINDER_COUNT]; // one for each active function pointer }; template<size_t w> struct VTableForWidth; protected: /// Takes a 64-bit value and returns the minimum number of bits needed /// to fit the value. For alignment this is rounded up to nearest /// log2. Posssible results {0, 1, 2, 4, 8, 16, 32, 64} static size_t bit_width(int64_t value); #ifdef REALM_DEBUG void report_memory_usage_2(MemUsageHandler&) const; #endif private: Getter m_getter = nullptr; // cached to avoid indirection const VTable* m_vtable = nullptr; public: // FIXME: Should not be public char* m_data = nullptr; // Points to first byte after header protected: int64_t m_lbound; // min number that can be stored with current m_width int64_t m_ubound; // max number that can be stored with current m_width size_t m_size = 0; // Number of elements currently stored. size_t m_capacity = 0; // Number of elements that fit inside the allocated memory. Allocator& m_alloc; private: size_t m_ref; ArrayParent* m_parent = nullptr; size_t m_ndx_in_parent = 0; // Ignored if m_parent is null. protected: uint_least8_t m_width = 0; // Size of an element (meaning depend on type of array). bool m_is_inner_bptree_node; // This array is an inner node of B+-tree. bool m_has_refs; // Elements whose first bit is zero are refs to subarrays. bool m_context_flag; // Meaning depends on context. private: ref_type do_write_shallow(_impl::ArrayWriterBase&) const; ref_type do_write_deep(_impl::ArrayWriterBase&, bool only_if_modified) const; friend class SlabAlloc; friend class GroupWriter; friend class StringColumn; }; class Array::NodeInfo { public: MemRef m_mem; Array* m_parent; size_t m_ndx_in_parent; size_t m_offset, m_size; }; class Array::VisitHandler { public: virtual bool visit(const NodeInfo& leaf_info) = 0; virtual ~VisitHandler() noexcept {} }; class Array::UpdateHandler { public: virtual void update(MemRef, ArrayParent*, size_t leaf_ndx_in_parent, size_t elem_ndx_in_leaf) = 0; virtual ~UpdateHandler() noexcept {} }; class Array::EraseHandler { public: /// If the specified leaf has more than one element, this function /// must erase the specified element from the leaf and return /// false. Otherwise, when the leaf has a single element, this /// function must return true without modifying the leaf. If \a /// elem_ndx_in_leaf is `npos`, it refers to the last element in /// the leaf. The implementation of this function must be /// exception safe. This function is guaranteed to be called at /// most once during each execution of Array::erase_bptree_elem(), /// and *exactly* once during each *successful* execution of /// Array::erase_bptree_elem(). virtual bool erase_leaf_elem(MemRef, ArrayParent*, size_t leaf_ndx_in_parent, size_t elem_ndx_in_leaf) = 0; virtual void destroy_leaf(MemRef leaf_mem) noexcept = 0; /// Must replace the current root with the specified leaf. The /// implementation of this function must not destroy the /// underlying root node, or any of its children, as that will be /// done by Array::erase_bptree_elem(). The implementation of this /// function must be exception safe. virtual void replace_root_by_leaf(MemRef leaf_mem) = 0; /// Same as replace_root_by_leaf(), but must replace the root with /// an empty leaf. Also, if this function is called during an /// execution of Array::erase_bptree_elem(), it is guaranteed that /// it will be preceeded by a call to erase_leaf_elem(). virtual void replace_root_by_empty_leaf() = 0; virtual ~EraseHandler() noexcept {} }; // Implementation: class QueryStateBase { virtual void dyncast(){} }; template<> class QueryState<int64_t>: public QueryStateBase { public: int64_t m_state; size_t m_match_count; size_t m_limit; size_t m_minmax_index; // used only for min/max, to save index of current min/max value template<Action action> bool uses_val() { if (action == act_Max || action == act_Min || action == act_Sum) return true; else return false; } void init(Action action, IntegerColumn* akku, size_t limit) { m_match_count = 0; m_limit = limit; m_minmax_index = not_found; if (action == act_Max) m_state = -0x7fffffffffffffffLL - 1LL; else if (action == act_Min) m_state = 0x7fffffffffffffffLL; else if (action == act_ReturnFirst) m_state = not_found; else if (action == act_Sum) m_state = 0; else if (action == act_Count) m_state = 0; else if (action == act_FindAll) m_state = reinterpret_cast<int64_t>(akku); else if (action == act_CallbackIdx) { } else { REALM_ASSERT_DEBUG(false); } } template<Action action, bool pattern> inline bool match(size_t index, uint64_t indexpattern, int64_t value) { if (pattern) { if (action == act_Count) { // If we are close to 'limit' argument in query, we cannot count-up a complete chunk. Count up single // elements instead if (m_match_count + 64 >= m_limit) return false; m_state += fast_popcount64(indexpattern); m_match_count = size_t(m_state); return true; } // Other aggregates cannot (yet) use bit pattern for anything. Make Array-finder call with pattern = false instead return false; } ++m_match_count; if (action == act_Max) { if (value > m_state) { m_state = value; m_minmax_index = index; } } else if (action == act_Min) { if (value < m_state) { m_state = value; m_minmax_index = index; } } else if (action == act_Sum) m_state += value; else if (action == act_Count) { m_state++; m_match_count = size_t(m_state); } else if (action == act_FindAll) { Array::add_to_column(reinterpret_cast<IntegerColumn*>(m_state), index); } else if (action == act_ReturnFirst) { m_state = index; return false; } else { REALM_ASSERT_DEBUG(false); } return (m_limit > m_match_count); } template<Action action, bool pattern> inline bool match(size_t index, uint64_t indexpattern, util::Optional<int64_t> value) { // FIXME: This is a temporary hack for nullable integers. if (value) { return match<action, pattern>(index, indexpattern, *value); } // If value is null, the only sensible actions are count, find_all, and return first. // Max, min, and sum should all have no effect. if (action == act_Count) { m_state++; m_match_count = size_t(m_state); } else if (action == act_FindAll) { Array::add_to_column(reinterpret_cast<IntegerColumn*>(m_state), index); } else if (action == act_ReturnFirst) { m_match_count++; m_state = index; return false; } return m_limit > m_match_count; } }; // Used only for Basic-types: currently float and double template<class R> class QueryState : public QueryStateBase { public: R m_state; size_t m_match_count; size_t m_limit; size_t m_minmax_index; // used only for min/max, to save index of current min/max value template<Action action> bool uses_val() { return (action == act_Max || action == act_Min || action == act_Sum || action == act_Count); } void init(Action action, Array*, size_t limit) { REALM_ASSERT((std::is_same<R, float>::value || std::is_same<R, double>::value)); m_match_count = 0; m_limit = limit; m_minmax_index = not_found; if (action == act_Max) m_state = -std::numeric_limits<R>::infinity(); else if (action == act_Min) m_state = std::numeric_limits<R>::infinity(); else if (action == act_Sum) m_state = 0.0; else { REALM_ASSERT_DEBUG(false); } } template<Action action, bool pattern, typename resulttype> inline bool match(size_t index, uint64_t /*indexpattern*/, resulttype value) { if (pattern) return false; static_assert(action == act_Sum || action == act_Max || action == act_Min || action == act_Count, "Search action not supported"); if (action == act_Count) { ++m_match_count; } else if (!null::is_null_float(value)) { ++m_match_count; if (action == act_Max) { if (value > m_state) { m_state = value; m_minmax_index = index; } } else if (action == act_Min) { if (value < m_state) { m_state = value; m_minmax_index = index; } } else if (action == act_Sum) m_state += value; else { REALM_ASSERT_DEBUG(false); } } return (m_limit > m_match_count); } }; inline Array::Array(Allocator& alloc) noexcept: m_alloc(alloc) { } // Fastest way to instantiate an Array. For use with GetDirect() that only fills out m_width, m_data // and a few other basic things needed for read-only access. Or for use if you just want a way to call // some methods written in Array.* inline Array::Array(no_prealloc_tag) noexcept: m_alloc(*static_cast<Allocator*>(0)) { } inline void Array::create(Type type, bool context_flag, size_t size, int_fast64_t value) { MemRef mem = create_array(type, context_flag, size, value, m_alloc); // Throws init_from_mem(mem); } inline void Array::init_from_ref(ref_type ref) noexcept { REALM_ASSERT_DEBUG(ref); char* header = m_alloc.translate(ref); init_from_mem(MemRef(header, ref)); } inline void Array::init_from_parent() noexcept { ref_type ref = get_ref_from_parent(); init_from_ref(ref); } inline Array::Type Array::get_type() const noexcept { if (m_is_inner_bptree_node) { REALM_ASSERT_DEBUG(m_has_refs); return type_InnerBptreeNode; } if (m_has_refs) return type_HasRefs; return type_Normal; } inline void Array::get_chunk(size_t ndx, int64_t res[8]) const noexcept { REALM_ASSERT_DEBUG(ndx < m_size); (this->*(m_vtable->chunk_getter))(ndx, res); } inline int64_t Array::get(size_t ndx) const noexcept { REALM_ASSERT_DEBUG(is_attached()); REALM_ASSERT_DEBUG(ndx < m_size); return (this->*m_getter)(ndx); // Two ideas that are not efficient but may be worth looking into again: /* // Assume correct width is found early in REALM_TEMPEX, which is the case for B tree offsets that // are probably either 2^16 long. Turns out to be 25% faster if found immediately, but 50-300% slower // if found later REALM_TEMPEX(return get, (ndx)); */ /* // Slightly slower in both of the if-cases. Also needs an matchcount m_size check too, to avoid // reading beyond array. if (m_width >= 8 && m_size > ndx + 7) return get<64>(ndx >> m_shift) & m_widthmask; else return (this->*(m_vtable->getter))(ndx); */ } inline int64_t Array::front() const noexcept { return get(0); } inline int64_t Array::back() const noexcept { return get(m_size - 1); } inline ref_type Array::get_as_ref(size_t ndx) const noexcept { REALM_ASSERT_DEBUG(is_attached()); REALM_ASSERT_DEBUG(m_has_refs); int64_t v = get(ndx); return to_ref(v); } inline bool Array::is_inner_bptree_node() const noexcept { return m_is_inner_bptree_node; } inline bool Array::has_refs() const noexcept { return m_has_refs; } inline bool Array::get_context_flag() const noexcept { return m_context_flag; } inline void Array::set_context_flag(bool value) noexcept { m_context_flag = value; set_header_context_flag(value); } inline ref_type Array::get_ref() const noexcept { return m_ref; } inline MemRef Array::get_mem() const noexcept { return MemRef(get_header_from_data(m_data), m_ref); } inline void Array::destroy() noexcept { if (!is_attached()) return; char* header = get_header_from_data(m_data); m_alloc.free_(m_ref, header); m_data = nullptr; } inline void Array::destroy_deep() noexcept { if (!is_attached()) return; if (m_has_refs) destroy_children(); char* header = get_header_from_data(m_data); m_alloc.free_(m_ref, header); m_data = nullptr; } inline ref_type Array::write(_impl::ArrayWriterBase& out, bool deep, bool only_if_modified) const { REALM_ASSERT(is_attached()); if (only_if_modified && m_alloc.is_read_only(m_ref)) return m_ref; if (!deep || !m_has_refs) return do_write_shallow(out); // Throws return do_write_deep(out, only_if_modified); // Throws } inline ref_type Array::write(ref_type ref, Allocator& alloc, _impl::ArrayWriterBase& out, bool only_if_modified) { if (only_if_modified && alloc.is_read_only(ref)) return ref; Array array(alloc); array.init_from_ref(ref); if (!array.m_has_refs) return array.do_write_shallow(out); // Throws return array.do_write_deep(out, only_if_modified); // Throws } inline void Array::add(int_fast64_t value) { insert(m_size, value); } inline void Array::erase(size_t ndx) { // This can throw, but only if array is currently in read-only // memory. move(ndx+1, size(), ndx); // Update size (also in header) --m_size; set_header_size(m_size); } inline void Array::erase(size_t begin, size_t end) { if (begin != end) { // This can throw, but only if array is currently in read-only memory. move(end, size(), begin); // Throws // Update size (also in header) m_size -= end - begin; set_header_size(m_size); } } inline void Array::clear() { truncate(0); // Throws } inline void Array::clear_and_destroy_children() { truncate_and_destroy_children(0); } inline void Array::destroy(ref_type ref, Allocator& alloc) noexcept { destroy(MemRef(ref, alloc), alloc); } inline void Array::destroy(MemRef mem, Allocator& alloc) noexcept { alloc.free_(mem); } inline void Array::destroy_deep(ref_type ref, Allocator& alloc) noexcept { destroy_deep(MemRef(ref, alloc), alloc); } inline void Array::destroy_deep(MemRef mem, Allocator& alloc) noexcept { if (!get_hasrefs_from_header(mem.m_addr)) { alloc.free_(mem); return; } Array array(alloc); array.init_from_mem(mem); array.destroy_deep(); } inline void Array::adjust(size_t ndx, int_fast64_t diff) { // FIXME: Should be optimized REALM_ASSERT_3(ndx, <=, m_size); int_fast64_t v = get(ndx); set(ndx, int64_t(v + diff)); // Throws } inline void Array::adjust(size_t begin, size_t end, int_fast64_t diff) { // FIXME: Should be optimized for (size_t i = begin; i != end; ++i) adjust(i, diff); // Throws } inline void Array::adjust_ge(int_fast64_t limit, int_fast64_t diff) { size_t n = size(); for (size_t i = 0; i != n; ++i) { int_fast64_t v = get(i); if (v >= limit) set(i, int64_t(v + diff)); // Throws } } //------------------------------------------------- inline bool Array::get_is_inner_bptree_node_from_header(const char* header) noexcept { typedef unsigned char uchar; const uchar* h = reinterpret_cast<const uchar*>(header); return (int(h[4]) & 0x80) != 0; } inline bool Array::get_hasrefs_from_header(const char* header) noexcept { typedef unsigned char uchar; const uchar* h = reinterpret_cast<const uchar*>(header); return (int(h[4]) & 0x40) != 0; } inline bool Array::get_context_flag_from_header(const char* header) noexcept { typedef unsigned char uchar; const uchar* h = reinterpret_cast<const uchar*>(header); return (int(h[4]) & 0x20) != 0; } inline Array::WidthType Array::get_wtype_from_header(const char* header) noexcept { typedef unsigned char uchar; const uchar* h = reinterpret_cast<const uchar*>(header); return WidthType((int(h[4]) & 0x18) >> 3); } inline size_t Array::get_width_from_header(const char* header) noexcept { typedef unsigned char uchar; const uchar* h = reinterpret_cast<const uchar*>(header); return size_t((1 << (int(h[4]) & 0x07)) >> 1); } inline size_t Array::get_size_from_header(const char* header) noexcept { typedef unsigned char uchar; const uchar* h = reinterpret_cast<const uchar*>(header); return (size_t(h[5]) << 16) + (size_t(h[6]) << 8) + h[7]; } inline size_t Array::get_capacity_from_header(const char* header) noexcept { typedef unsigned char uchar; const uchar* h = reinterpret_cast<const uchar*>(header); return (size_t(h[0]) << 16) + (size_t(h[1]) << 8) + h[2]; } inline char* Array::get_data_from_header(char* header) noexcept { return header + header_size; } inline char* Array::get_header_from_data(char* data) noexcept { return data - header_size; } inline const char* Array::get_data_from_header(const char* header) noexcept { return get_data_from_header(const_cast<char*>(header)); } inline bool Array::get_is_inner_bptree_node_from_header() const noexcept { return get_is_inner_bptree_node_from_header(get_header_from_data(m_data)); } inline bool Array::get_hasrefs_from_header() const noexcept { return get_hasrefs_from_header(get_header_from_data(m_data)); } inline bool Array::get_context_flag_from_header() const noexcept { return get_context_flag_from_header(get_header_from_data(m_data)); } inline Array::WidthType Array::get_wtype_from_header() const noexcept { return get_wtype_from_header(get_header_from_data(m_data)); } inline size_t Array::get_width_from_header() const noexcept { return get_width_from_header(get_header_from_data(m_data)); } inline size_t Array::get_size_from_header() const noexcept { return get_size_from_header(get_header_from_data(m_data)); } inline size_t Array::get_capacity_from_header() const noexcept { return get_capacity_from_header(get_header_from_data(m_data)); } inline void Array::set_header_is_inner_bptree_node(bool value, char* header) noexcept { typedef unsigned char uchar; uchar* h = reinterpret_cast<uchar*>(header); h[4] = uchar((int(h[4]) & ~0x80) | int(value) << 7); } inline void Array::set_header_hasrefs(bool value, char* header) noexcept { typedef unsigned char uchar; uchar* h = reinterpret_cast<uchar*>(header); h[4] = uchar((int(h[4]) & ~0x40) | int(value) << 6); } inline void Array::set_header_context_flag(bool value, char* header) noexcept { typedef unsigned char uchar; uchar* h = reinterpret_cast<uchar*>(header); h[4] = uchar((int(h[4]) & ~0x20) | int(value) << 5); } inline void Array::set_header_wtype(WidthType value, char* header) noexcept { // Indicates how to calculate size in bytes based on width // 0: bits (width/8) * size // 1: multiply width * size // 2: ignore 1 * size typedef unsigned char uchar; uchar* h = reinterpret_cast<uchar*>(header); h[4] = uchar((int(h[4]) & ~0x18) | int(value) << 3); } inline void Array::set_header_width(int value, char* header) noexcept { // Pack width in 3 bits (log2) int w = 0; while (value) { ++w; value >>= 1; } REALM_ASSERT_3(w, <, 8); typedef unsigned char uchar; uchar* h = reinterpret_cast<uchar*>(header); h[4] = uchar((int(h[4]) & ~0x7) | w); } inline void Array::set_header_size(size_t value, char* header) noexcept { REALM_ASSERT_3(value, <=, max_array_payload); typedef unsigned char uchar; uchar* h = reinterpret_cast<uchar*>(header); h[5] = uchar((value >> 16) & 0x000000FF); h[6] = uchar((value >> 8) & 0x000000FF); h[7] = uchar( value & 0x000000FF); } // Note: There is a copy of this function is test_alloc.cpp inline void Array::set_header_capacity(size_t value, char* header) noexcept { REALM_ASSERT_3(value, <=, max_array_payload); typedef unsigned char uchar; uchar* h = reinterpret_cast<uchar*>(header); h[0] = uchar((value >> 16) & 0x000000FF); h[1] = uchar((value >> 8) & 0x000000FF); h[2] = uchar( value & 0x000000FF); } inline void Array::set_header_is_inner_bptree_node(bool value) noexcept { set_header_is_inner_bptree_node(value, get_header_from_data(m_data)); } inline void Array::set_header_hasrefs(bool value) noexcept { set_header_hasrefs(value, get_header_from_data(m_data)); } inline void Array::set_header_context_flag(bool value) noexcept { set_header_context_flag(value, get_header_from_data(m_data)); } inline void Array::set_header_wtype(WidthType value) noexcept { set_header_wtype(value, get_header_from_data(m_data)); } inline void Array::set_header_width(int value) noexcept { set_header_width(value, get_header_from_data(m_data)); } inline void Array::set_header_size(size_t value) noexcept { set_header_size(value, get_header_from_data(m_data)); } inline void Array::set_header_capacity(size_t value) noexcept { set_header_capacity(value, get_header_from_data(m_data)); } inline Array::Type Array::get_type_from_header(const char* header) noexcept { if (get_is_inner_bptree_node_from_header(header)) return type_InnerBptreeNode; if (get_hasrefs_from_header(header)) return type_HasRefs; return type_Normal; } inline char* Array::get_header() noexcept { return get_header_from_data(m_data); } inline size_t Array::get_byte_size() const noexcept { size_t num_bytes = 0; const char* header = get_header_from_data(m_data); switch (get_wtype_from_header(header)) { case wtype_Bits: { // FIXME: The following arithmetic could overflow, that // is, even though both the total number of elements and // the total number of bytes can be represented in // uint_fast64_t, the total number of bits may not // fit. Note that "num_bytes = width < 8 ? size / (8 / // width) : size * (width / 8)" would be guaranteed to // never overflow, but it potentially involves two slow // divisions. uint_fast64_t num_bits = uint_fast64_t(m_size) * m_width; num_bytes = size_t(num_bits / 8); if (num_bits & 0x7) ++num_bytes; goto found; } case wtype_Multiply: { num_bytes = m_size * m_width; goto found; } case wtype_Ignore: num_bytes = m_size; goto found; } REALM_ASSERT_DEBUG(false); found: // Ensure 8-byte alignment size_t rest = (~num_bytes & 0x7) + 1; if (rest < 8) num_bytes += rest; num_bytes += header_size; REALM_ASSERT_7(m_alloc.is_read_only(m_ref), ==, true, ||, num_bytes, <=, get_capacity_from_header(header)); return num_bytes; } inline size_t Array::get_byte_size_from_header(const char* header) noexcept { size_t num_bytes = 0; size_t size = get_size_from_header(header); switch (get_wtype_from_header(header)) { case wtype_Bits: { size_t width = get_width_from_header(header); size_t num_bits = (size * width); // FIXME: Prone to overflow num_bytes = num_bits / 8; if (num_bits & 0x7) ++num_bytes; goto found; } case wtype_Multiply: { size_t width = get_width_from_header(header); num_bytes = size * width; goto found; } case wtype_Ignore: num_bytes = size; goto found; } REALM_ASSERT_DEBUG(false); found: // Ensure 8-byte alignment size_t rest = (~num_bytes & 0x7) + 1; if (rest < 8) num_bytes += rest; num_bytes += header_size; return num_bytes; } inline void Array::init_header(char* header, bool is_inner_bptree_node, bool has_refs, bool context_flag, WidthType width_type, int width, size_t size, size_t capacity) noexcept { // Note: Since the header layout contains unallocated bit and/or // bytes, it is important that we put the entire header into a // well defined state initially. std::fill(header, header + header_size, 0); set_header_is_inner_bptree_node(is_inner_bptree_node, header); set_header_hasrefs(has_refs, header); set_header_context_flag(context_flag, header); set_header_wtype(width_type, header); set_header_width(width, header); set_header_size(size, header); set_header_capacity(capacity, header); } //------------------------------------------------- inline MemRef Array::clone_deep(Allocator& target_alloc) const { char* header = get_header_from_data(m_data); return clone(MemRef(header, m_ref), m_alloc, target_alloc); // Throws } inline void Array::move_assign(Array& a) noexcept { REALM_ASSERT_3(&get_alloc(), ==, &a.get_alloc()); // FIXME: Be carefull with the old parent info here. Should it be // copied? // FIXME: It will likely be a lot better for the optimizer if we // did a member-wise copy, rather than recreating the state from // the referenced data. This is important because TableView efficiency, for // example, relies on long chains of moves to be optimized away // completely. This change should be a 'no-brainer'. destroy_deep(); init_from_ref(a.get_ref()); a.detach(); } inline MemRef Array::create_empty_array(Type type, bool context_flag, Allocator& alloc) { size_t size = 0; int_fast64_t value = 0; return create_array(type, context_flag, size, value, alloc); // Throws } inline MemRef Array::create_array(Type type, bool context_flag, size_t size, int_fast64_t value, Allocator& alloc) { return create(type, context_flag, wtype_Bits, size, value, alloc); // Throws } inline bool Array::has_parent() const noexcept { return m_parent != nullptr; } inline ArrayParent* Array::get_parent() const noexcept { return m_parent; } inline void Array::set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept { m_parent = parent; m_ndx_in_parent = ndx_in_parent; } inline size_t Array::get_ndx_in_parent() const noexcept { return m_ndx_in_parent; } inline void Array::set_ndx_in_parent(size_t ndx) noexcept { m_ndx_in_parent = ndx; } inline void Array::adjust_ndx_in_parent(int diff) noexcept { // Note that `diff` is promoted to an unsigned type, and that // C++03 still guarantees the expected result regardless of the // sizes of `int` and `decltype(m_ndx_in_parent)`. m_ndx_in_parent += diff; } inline ref_type Array::get_ref_from_parent() const noexcept { ref_type ref = m_parent->get_child_ref(m_ndx_in_parent); return ref; } inline bool Array::is_attached() const noexcept { return m_data != nullptr; } inline void Array::detach() noexcept { m_data = nullptr; } inline size_t Array::size() const noexcept { REALM_ASSERT_DEBUG(is_attached()); return m_size; } inline bool Array::is_empty() const noexcept { return size() == 0; } inline size_t Array::get_max_byte_size(size_t num_elems) noexcept { int max_bytes_per_elem = 8; return header_size + num_elems * max_bytes_per_elem; // FIXME: Prone to overflow } inline void Array::update_parent() { if (m_parent) m_parent->update_child_ref(m_ndx_in_parent, m_ref); } inline void Array::update_child_ref(size_t child_ndx, ref_type new_ref) { set(child_ndx, new_ref); } inline ref_type Array::get_child_ref(size_t child_ndx) const noexcept { return get_as_ref(child_ndx); } inline size_t Array::get_bptree_size() const noexcept { REALM_ASSERT_DEBUG(is_inner_bptree_node()); int_fast64_t v = back(); return size_t(v / 2); // v = 1 + 2*total_elems_in_tree } inline size_t Array::get_bptree_size_from_header(const char* root_header) noexcept { REALM_ASSERT_DEBUG(get_is_inner_bptree_node_from_header(root_header)); size_t root_size = get_size_from_header(root_header); int_fast64_t v = get(root_header, root_size-1); return size_t(v / 2); // v = 1 + 2*total_elems_in_tree } inline void Array::ensure_bptree_offsets(Array& offsets) { int_fast64_t first_value = get(0); if (first_value % 2 == 0) { offsets.init_from_ref(to_ref(first_value)); } else { create_bptree_offsets(offsets, first_value); // Throws } offsets.set_parent(this, 0); } template<class TreeTraits> ref_type Array::bptree_append(TreeInsert<TreeTraits>& state) { // FIXME: Consider exception safety. Especially, how can the split // be carried out in an exception safe manner? // // Can split be done as a separate preparation step, such that if // the actual insert fails, the split will still have occured. // // Unfortunately, it requires a rather significant rearrangement // of the insertion flow. Instead of returning the sibling ref // from insert functions, the leaf-insert functions must instead // call the special bptree_insert() function on the parent, which // will then cascade the split towards the root as required. // // At each level where a split is required (starting at the leaf): // // 1. Create the new sibling. // // 2. Copy relevant entries over such that new sibling is in // its final state. // // 3. Call Array::bptree_insert() on parent with sibling ref. // // 4. Rearrange entries in original sibling and truncate as // required (must not throw). // // What about the 'offsets' array? It will always be // present. Consider this carefully. REALM_ASSERT_DEBUG(size() >= 1 + 1 + 1); // At least one child ArrayParent& childs_parent = *this; size_t child_ref_ndx = size() - 2; ref_type child_ref = get_as_ref(child_ref_ndx), new_sibling_ref; char* child_header = static_cast<char*>(m_alloc.translate(child_ref)); bool child_is_leaf = !get_is_inner_bptree_node_from_header(child_header); if (child_is_leaf) { size_t elem_ndx_in_child = npos; // Append new_sibling_ref = TreeTraits::leaf_insert(MemRef(child_header, child_ref), childs_parent, child_ref_ndx, m_alloc, elem_ndx_in_child, state); // Throws } else { Array child(m_alloc); child.init_from_mem(MemRef(child_header, child_ref)); child.set_parent(&childs_parent, child_ref_ndx); new_sibling_ref = child.bptree_append(state); // Throws } if (REALM_LIKELY(!new_sibling_ref)) { // +2 because stored value is 1 + 2*total_elems_in_subtree adjust(size()-1, +2); // Throws return 0; // Child was not split, so parent was not split either } Array offsets(m_alloc); int_fast64_t first_value = get(0); if (first_value % 2 == 0) { // Offsets array is present (general form) offsets.init_from_ref(to_ref(first_value)); offsets.set_parent(this, 0); } size_t child_ndx = child_ref_ndx - 1; return insert_bptree_child(offsets, child_ndx, new_sibling_ref, state); // Throws } template<class TreeTraits> ref_type Array::bptree_insert(size_t elem_ndx, TreeInsert<TreeTraits>& state) { REALM_ASSERT_3(size(), >=, 1 + 1 + 1); // At least one child // Conversion to general form if in compact form. Since this // conversion will occur from root to leaf, it will maintain // invar:bptree-node-form. Array offsets(m_alloc); ensure_bptree_offsets(offsets); // Throws size_t child_ndx, elem_ndx_in_child; if (elem_ndx == 0) { // Optimization for prepend child_ndx = 0; elem_ndx_in_child = 0; } else { // There is a choice to be made when the element is to be // inserted between two subtrees. It can either be appended to // the first subtree, or it can be prepended to the second // one. We currently always append to the first subtree. It is // essentially a matter of using the lower vs. the upper bound // when searching through the offsets array. child_ndx = offsets.lower_bound_int(elem_ndx); REALM_ASSERT_3(child_ndx, <, size() - 2); size_t elem_ndx_offset = child_ndx == 0 ? 0 : to_size_t(offsets.get(child_ndx-1)); elem_ndx_in_child = elem_ndx - elem_ndx_offset; } ArrayParent& childs_parent = *this; size_t child_ref_ndx = child_ndx + 1; ref_type child_ref = get_as_ref(child_ref_ndx), new_sibling_ref; char* child_header = static_cast<char*>(m_alloc.translate(child_ref)); bool child_is_leaf = !get_is_inner_bptree_node_from_header(child_header); if (child_is_leaf) { REALM_ASSERT_3(elem_ndx_in_child, <=, REALM_MAX_BPNODE_SIZE); new_sibling_ref = TreeTraits::leaf_insert(MemRef(child_header, child_ref), childs_parent, child_ref_ndx, m_alloc, elem_ndx_in_child, state); // Throws } else { Array child(m_alloc); child.init_from_mem(MemRef(child_header, child_ref)); child.set_parent(&childs_parent, child_ref_ndx); new_sibling_ref = child.bptree_insert(elem_ndx_in_child, state); // Throws } if (REALM_LIKELY(!new_sibling_ref)) { // +2 because stored value is 1 + 2*total_elems_in_subtree adjust(size()-1, +2); // Throws offsets.adjust(child_ndx, offsets.size(), +1); return 0; // Child was not split, so parent was not split either } return insert_bptree_child(offsets, child_ndx, new_sibling_ref, state); // Throws } //************************************************************************************* // Finding code * //************************************************************************************* template<size_t w> int64_t Array::get(size_t ndx) const noexcept { return get_universal<w>(m_data, ndx); } template<size_t w> int64_t Array::get_universal(const char* data, size_t ndx) const { if (w == 0) { return 0; } else if (w == 1) { size_t offset = ndx >> 3; return (data[offset] >> (ndx & 7)) & 0x01; } else if (w == 2) { size_t offset = ndx >> 2; return (data[offset] >> ((ndx & 3) << 1)) & 0x03; } else if (w == 4) { size_t offset = ndx >> 1; return (data[offset] >> ((ndx & 1) << 2)) & 0x0F; } else if (w == 8) { return *reinterpret_cast<const signed char*>(data + ndx); } else if (w == 16) { size_t offset = ndx * 2; return *reinterpret_cast<const int16_t*>(data + offset); } else if (w == 32) { size_t offset = ndx * 4; return *reinterpret_cast<const int32_t*>(data + offset); } else if (w == 64) { size_t offset = ndx * 8; return *reinterpret_cast<const int64_t*>(data + offset); } else { REALM_ASSERT_DEBUG(false); return int64_t(-1); } } /* find() (calls find_optimized()) will call match() for each search result. If pattern == true: 'indexpattern' contains a 64-bit chunk of elements, each of 'width' bits in size where each element indicates a match if its lower bit is set, otherwise it indicates a non-match. 'index' tells the database row index of the first element. You must return true if you chose to 'consume' the chunk or false if not. If not, then Array-finder will afterwards call match() successive times with pattern == false. If pattern == false: 'index' tells the row index of a single match and 'value' tells its value. Return false to make Array-finder break its search or return true to let it continue until 'end' or 'limit'. Array-finder decides itself if - and when - it wants to pass you an indexpattern. It depends on array bit width, match frequency, and wether the arithemetic and computations for the given search criteria makes it feasible to construct such a pattern. */ // These wrapper functions only exist to enable a possibility to make the compiler see that 'value' and/or 'index' are unused, such that caller's // computation of these values will not be made. Only works if find_action() and find_action_pattern() rewritten as macros. Note: This problem has been fixed in // next upcoming array.hpp version template<Action action, class Callback> bool Array::find_action(size_t index, util::Optional<int64_t> value, QueryState<int64_t>* state, Callback callback) const { if (action == act_CallbackIdx) return callback(index); else return state->match<action, false>(index, 0, value); } template<Action action, class Callback> bool Array::find_action_pattern(size_t index, uint64_t pattern, QueryState<int64_t>* state, Callback callback) const { static_cast<void>(callback); if (action == act_CallbackIdx) { // Possible future optimization: call callback(index) like in above find_action(), in a loop for each bit set in 'pattern' return false; } return state->match<action, true>(index, pattern, 0); } template<size_t width, bool zero> uint64_t Array::cascade(uint64_t a) const { // Takes a chunk of values as argument and sets the least significant bit for each // element which is zero or non-zero, depending on the template parameter. // Example for zero=true: // width == 4 and a = 0x5fd07a107610f610 // will return: 0x0001000100010001 // static values needed for fast population count const uint64_t m1 = 0x5555555555555555ULL; if (width == 1) { return zero ? ~a : a; } else if (width == 2) { // Masks to avoid spillover between segments in cascades const uint64_t c1 = ~0ULL/0x3 * 0x1; a |= (a >> 1) & c1; // cascade ones in non-zeroed segments a &= m1; // isolate single bit in each segment if (zero) a ^= m1; // reverse isolated bits if checking for zeroed segments return a; } else if (width == 4) { const uint64_t m = ~0ULL/0xF * 0x1; // Masks to avoid spillover between segments in cascades const uint64_t c1 = ~0ULL/0xF * 0x7; const uint64_t c2 = ~0ULL/0xF * 0x3; a |= (a >> 1) & c1; // cascade ones in non-zeroed segments a |= (a >> 2) & c2; a &= m; // isolate single bit in each segment if (zero) a ^= m; // reverse isolated bits if checking for zeroed segments return a; } else if (width == 8) { const uint64_t m = ~0ULL/0xFF * 0x1; // Masks to avoid spillover between segments in cascades const uint64_t c1 = ~0ULL/0xFF * 0x7F; const uint64_t c2 = ~0ULL/0xFF * 0x3F; const uint64_t c3 = ~0ULL/0xFF * 0x0F; a |= (a >> 1) & c1; // cascade ones in non-zeroed segments a |= (a >> 2) & c2; a |= (a >> 4) & c3; a &= m; // isolate single bit in each segment if (zero) a ^= m; // reverse isolated bits if checking for zeroed segments return a; } else if (width == 16) { const uint64_t m = ~0ULL/0xFFFF * 0x1; // Masks to avoid spillover between segments in cascades const uint64_t c1 = ~0ULL/0xFFFF * 0x7FFF; const uint64_t c2 = ~0ULL/0xFFFF * 0x3FFF; const uint64_t c3 = ~0ULL/0xFFFF * 0x0FFF; const uint64_t c4 = ~0ULL/0xFFFF * 0x00FF; a |= (a >> 1) & c1; // cascade ones in non-zeroed segments a |= (a >> 2) & c2; a |= (a >> 4) & c3; a |= (a >> 8) & c4; a &= m; // isolate single bit in each segment if (zero) a ^= m; // reverse isolated bits if checking for zeroed segments return a; } else if (width == 32) { const uint64_t m = ~0ULL/0xFFFFFFFF * 0x1; // Masks to avoid spillover between segments in cascades const uint64_t c1 = ~0ULL/0xFFFFFFFF * 0x7FFFFFFF; const uint64_t c2 = ~0ULL/0xFFFFFFFF * 0x3FFFFFFF; const uint64_t c3 = ~0ULL/0xFFFFFFFF * 0x0FFFFFFF; const uint64_t c4 = ~0ULL/0xFFFFFFFF * 0x00FFFFFF; const uint64_t c5 = ~0ULL/0xFFFFFFFF * 0x0000FFFF; a |= (a >> 1) & c1; // cascade ones in non-zeroed segments a |= (a >> 2) & c2; a |= (a >> 4) & c3; a |= (a >> 8) & c4; a |= (a >> 16) & c5; a &= m; // isolate single bit in each segment if (zero) a ^= m; // reverse isolated bits if checking for zeroed segments return a; } else if (width == 64) { return (a == 0) == zero; } else { REALM_ASSERT_DEBUG(false); return uint64_t(-1); } } // This is the main finding function for Array. Other finding functions are just wrappers around this one. // Search for 'value' using condition cond (Equal, NotEqual, Less, etc) and call find_action() or find_action_pattern() // for each match. Break and return if find_action() returns false or 'end' is reached. // If nullable_array is set, then find_optimized() will treat the array is being nullable, i.e. it will skip the // first entry and compare correctly against null, etc. // // If find_null is set, it means that we search for a null. In that case, `value` is ignored. If find_null is set, // then nullable_array must be set too. template<class cond, Action action, size_t bitwidth, class Callback> bool Array::find_optimized(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback, bool nullable_array, bool find_null) const { REALM_ASSERT(!(find_null && !nullable_array)); REALM_ASSERT_DEBUG(start <= m_size && (end <= m_size || end == size_t(-1)) && start <= end); size_t start2 = start; cond c; if (end == npos) end = nullable_array ? size() - 1 : size(); if (nullable_array) { // We were called by find() of a nullable array. So skip first entry, take nulls in count, etc, etc. Fixme: // Huge speed optimizations are possible here! This is a very simple generic method. for (; start2 < end; start2++) { int64_t v = get<bitwidth>(start2 + 1); if (c(v, value, v == get(0), find_null)) { util::Optional<int64_t> v2(v == get(0) ? util::none : util::make_optional(v)); if (!find_action<action, Callback>(start2 + baseindex, v2, state, callback)) return false; // tell caller to stop aggregating/search } } return true; // tell caller to continue aggregating/search (on next array leafs) } // Test first few items with no initial time overhead if (start2 > 0) { if (m_size > start2 && c(get<bitwidth>(start2), value) && start2 < end) { if (!find_action<action, Callback>(start2 + baseindex, get<bitwidth>(start2), state, callback)) return false; } ++start2; if (m_size > start2 && c(get<bitwidth>(start2), value) && start2 < end) { if (!find_action<action, Callback>(start2 + baseindex, get<bitwidth>(start2), state, callback)) return false; } ++start2; if (m_size > start2 && c(get<bitwidth>(start2), value) && start2 < end) { if (!find_action<action, Callback>(start2 + baseindex, get<bitwidth>(start2), state, callback)) return false; } ++start2; if (m_size > start2 && c(get<bitwidth>(start2), value) && start2 < end) { if (!find_action<action, Callback>(start2 + baseindex, get<bitwidth>(start2), state, callback)) return false; } ++start2; } if (!(m_size > start2 && start2 < end)) return true; if (end == size_t(-1)) end = m_size; // Return immediately if no items in array can match (such as if cond == Greater && value == 100 && m_ubound == 15) if (!c.can_match(value, m_lbound, m_ubound)) return true; // optimization if all items are guaranteed to match (such as cond == NotEqual && value == 100 && m_ubound == 15) if (c.will_match(value, m_lbound, m_ubound)) { size_t end2; if (action == act_CallbackIdx) end2 = end; else { REALM_ASSERT_DEBUG(state->m_match_count < state->m_limit); size_t process = state->m_limit - state->m_match_count; end2 = end - start2 > process ? start2 + process : end; } if (action == act_Sum || action == act_Max || action == act_Min) { int64_t res; size_t res_ndx = 0; if (action == act_Sum) res = Array::sum(start2, end2); if (action == act_Max) Array::maximum(res, start2, end2, &res_ndx); if (action == act_Min) Array::minimum(res, start2, end2, &res_ndx); find_action<action, Callback>(res_ndx + baseindex, res, state, callback); // find_action will increment match count by 1, so we need to `-1` from the number of elements that // we performed the fast Array methods on. state->m_match_count += end2 - start2 - 1; } else if (action == act_Count) { state->m_state += end2 - start2; } else { for (; start2 < end2; start2++) if (!find_action<action, Callback>(start2 + baseindex, get<bitwidth>(start2), state, callback)) return false; } return true; } // finder cannot handle this bitwidth REALM_ASSERT_3(m_width, !=, 0); #if defined(REALM_COMPILER_SSE) // Only use SSE if payload is at least one SSE chunk (128 bits) in size. Also note taht SSE doesn't support // Less-than comparison for 64-bit values. if ((!(std::is_same<cond, Less>::value && m_width == 64)) && end - start2 >= sizeof(__m128i) && m_width >= 8 && (sseavx<42>() || (sseavx<30>() && std::is_same<cond, Equal>::value && m_width < 64))) { // find_sse() must start2 at 16-byte boundary, so search area before that using compare_equality() __m128i* const a = reinterpret_cast<__m128i*>(round_up(m_data + start2 * bitwidth / 8, sizeof (__m128i))); __m128i* const b = reinterpret_cast<__m128i*>(round_down(m_data + end * bitwidth / 8, sizeof (__m128i))); if (!compare<cond, action, bitwidth, Callback>(value, start2, (reinterpret_cast<char*>(a) - m_data) * 8 / no0(bitwidth), baseindex, state, callback)) return false; // Search aligned area with SSE if (b > a) { if (sseavx<42>()) { if (!find_sse<cond, action, bitwidth, Callback>(value, a, b - a, state, baseindex + ((reinterpret_cast<char*>(a) - m_data) * 8 / no0(bitwidth)), callback)) return false; } else if (sseavx<30>()) { if (!find_sse<Equal, action, bitwidth, Callback>(value, a, b - a, state, baseindex + ((reinterpret_cast<char*>(a) - m_data) * 8 / no0(bitwidth)), callback)) return false; } } // Search remainder with compare_equality() if (!compare<cond, action, bitwidth, Callback>(value, (reinterpret_cast<char*>(b) - m_data) * 8 / no0(bitwidth), end, baseindex, state, callback)) return false; return true; } else { return compare<cond, action, bitwidth, Callback>(value, start2, end, baseindex, state, callback); } #else return compare<cond, action, bitwidth, Callback>(value, start2, end, baseindex, state, callback); #endif } template<size_t width> inline int64_t Array::lower_bits() const { if (width == 1) return 0xFFFFFFFFFFFFFFFFULL; else if (width == 2) return 0x5555555555555555ULL; else if (width == 4) return 0x1111111111111111ULL; else if (width == 8) return 0x0101010101010101ULL; else if (width == 16) return 0x0001000100010001ULL; else if (width == 32) return 0x0000000100000001ULL; else if (width == 64) return 0x0000000000000001ULL; else { REALM_ASSERT_DEBUG(false); return int64_t(-1); } } // Tests if any chunk in 'value' is 0 template<size_t width> inline bool Array::test_zero(uint64_t value) const { uint64_t hasZeroByte; uint64_t lower = lower_bits<width>(); uint64_t upper = lower_bits<width>() * 1ULL << (width == 0 ? 0 : (width - 1ULL)); hasZeroByte = (value - lower) & ~value & upper; return hasZeroByte != 0; } // Finds first zero (if eq == true) or non-zero (if eq == false) element in v and returns its position. // IMPORTANT: This function assumes that at least 1 item matches (test this with test_zero() or other means first)! template<bool eq, size_t width> size_t Array::find_zero(uint64_t v) const { size_t start = 0; uint64_t hasZeroByte; // Warning free way of computing (1ULL << width) - 1 uint64_t mask = (width == 64 ? ~0ULL : ((1ULL << (width == 64 ? 0 : width)) - 1ULL)); if (eq == (((v >> (width * start)) & mask) == 0)) { return 0; } // Bisection optimization, speeds up small bitwidths with high match frequency. More partions than 2 do NOT pay // off because the work done by test_zero() is wasted for the cases where the value exists in first half, but // useful if it exists in last half. Sweet spot turns out to be the widths and partitions below. if (width <= 8) { hasZeroByte = test_zero<width>(v | 0xffffffff00000000ULL); if (eq ? !hasZeroByte : (v & 0x00000000ffffffffULL) == 0) { // 00?? -> increasing start += 64 / no0(width) / 2; if (width <= 4) { hasZeroByte = test_zero<width>(v | 0xffff000000000000ULL); if (eq ? !hasZeroByte : (v & 0x0000ffffffffffffULL) == 0) { // 000? start += 64 / no0(width) / 4; } } } else { if (width <= 4) { // ??00 hasZeroByte = test_zero<width>(v | 0xffffffffffff0000ULL); if (eq ? !hasZeroByte : (v & 0x000000000000ffffULL) == 0) { // 0?00 start += 64 / no0(width) / 4; } } } } while (eq == (((v >> (width * start)) & mask) != 0)) { // You must only call find_zero() if you are sure that at least 1 item matches REALM_ASSERT_3(start, <=, 8 * sizeof(v)); start++; } return start; } // Generate a magic constant used for later bithacks template<bool gt, size_t width> int64_t Array::find_gtlt_magic(int64_t v) const { uint64_t mask1 = (width == 64 ? ~0ULL : ((1ULL << (width == 64 ? 0 : width)) - 1ULL)); // Warning free way of computing (1ULL << width) - 1 uint64_t mask2 = mask1 >> 1; uint64_t magic = gt ? (~0ULL / no0(mask1) * (mask2 - v)) : (~0ULL / no0(mask1) * v); return magic; } template<bool gt, Action action, size_t width, class Callback> bool Array::find_gtlt_fast(uint64_t chunk, uint64_t magic, QueryState<int64_t>* state, size_t baseindex, Callback callback) const { // Tests if a a chunk of values contains values that are greater (if gt == true) or less (if gt == false) than v. // Fast, but limited to work when all values in the chunk are positive. uint64_t mask1 = (width == 64 ? ~0ULL : ((1ULL << (width == 64 ? 0 : width)) - 1ULL)); // Warning free way of computing (1ULL << width) - 1 uint64_t mask2 = mask1 >> 1; uint64_t m = gt ? (((chunk + magic) | chunk) & ~0ULL / no0(mask1) * (mask2 + 1)) : ((chunk - magic) & ~chunk&~0ULL/no0(mask1)*(mask2+1)); size_t p = 0; while (m) { if (find_action_pattern<action, Callback>(baseindex, m >> (no0(width) - 1), state, callback)) break; // consumed, so do not call find_action() size_t t = first_set_bit64(m) / no0(width); p += t; if (!find_action<action, Callback>(p + baseindex, (chunk >> (p * width)) & mask1, state, callback)) return false; if ((t + 1) * width == 64) m = 0; else m >>= (t + 1) * width; p++; } return true; } template<bool gt, Action action, size_t width, class Callback> bool Array::find_gtlt(int64_t v, uint64_t chunk, QueryState<int64_t>* state, size_t baseindex, Callback callback) const { // Find items in 'chunk' that are greater (if gt == true) or smaller (if gt == false) than 'v'. Fixme, __forceinline can make it crash in vS2010 - find out why if (width == 1) { for (size_t t = 0; t < 64; t++) { if (gt ? static_cast<int64_t>(chunk & 0x1) > v : static_cast<int64_t>(chunk & 0x1) < v) {if (!find_action<action, Callback>( t + baseindex, static_cast<int64_t>(chunk & 0x1), state, callback)) return false;} chunk >>= 1; } } else if (width == 2) { // Alot (50% +) faster than loop/compiler-unrolled loop if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 0 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 1 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 2 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 3 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 4 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 5 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 6 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 7 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 8 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 9 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 10 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 11 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 12 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 13 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 14 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 15 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 16 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 17 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 18 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 19 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 20 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 21 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 22 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 23 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 24 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 25 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 26 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 27 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 28 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 29 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 30 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 31 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2; } else if (width == 4) { // 128 ms: if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 0 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4; if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 1 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4; if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 2 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4; if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 3 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4; if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 4 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4; if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 5 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4; if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 6 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4; if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 7 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4; if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 8 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4; if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 9 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4; if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 10 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4; if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 11 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4; if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 12 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4; if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 13 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4; if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 14 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4; if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 15 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4; // 187 ms: // if (gt ? static_cast<int64_t>(chunk >> 0*4) & 0xf > v : static_cast<int64_t>(chunk >> 0*4) & 0xf < v) return 0; } else if (width == 8) { // 88 ms: if (gt ? static_cast<int8_t>(chunk) > v : static_cast<int8_t>(chunk) < v) {if (!find_action<action, Callback>( 0 + baseindex, static_cast<int8_t>(chunk), state, callback)) return false;} chunk >>= 8; if (gt ? static_cast<int8_t>(chunk) > v : static_cast<int8_t>(chunk) < v) {if (!find_action<action, Callback>( 1 + baseindex, static_cast<int8_t>(chunk), state, callback)) return false;} chunk >>= 8; if (gt ? static_cast<int8_t>(chunk) > v : static_cast<int8_t>(chunk) < v) {if (!find_action<action, Callback>( 2 + baseindex, static_cast<int8_t>(chunk), state, callback)) return false;} chunk >>= 8; if (gt ? static_cast<int8_t>(chunk) > v : static_cast<int8_t>(chunk) < v) {if (!find_action<action, Callback>( 3 + baseindex, static_cast<int8_t>(chunk), state, callback)) return false;} chunk >>= 8; if (gt ? static_cast<int8_t>(chunk) > v : static_cast<int8_t>(chunk) < v) {if (!find_action<action, Callback>( 4 + baseindex, static_cast<int8_t>(chunk), state, callback)) return false;} chunk >>= 8; if (gt ? static_cast<int8_t>(chunk) > v : static_cast<int8_t>(chunk) < v) {if (!find_action<action, Callback>( 5 + baseindex, static_cast<int8_t>(chunk), state, callback)) return false;} chunk >>= 8; if (gt ? static_cast<int8_t>(chunk) > v : static_cast<int8_t>(chunk) < v) {if (!find_action<action, Callback>( 6 + baseindex, static_cast<int8_t>(chunk), state, callback)) return false;} chunk >>= 8; if (gt ? static_cast<int8_t>(chunk) > v : static_cast<int8_t>(chunk) < v) {if (!find_action<action, Callback>( 7 + baseindex, static_cast<int8_t>(chunk), state, callback)) return false;} chunk >>= 8; //97 ms ms: // if (gt ? static_cast<int8_t>(chunk >> 0*8) > v : static_cast<int8_t>(chunk >> 0*8) < v) return 0; } else if (width == 16) { if (gt ? static_cast<short int>(chunk >> 0*16) > v : static_cast<short int>(chunk >> 0*16) < v) {if (!find_action<action, Callback>( 0 + baseindex, static_cast<short int>(chunk >> 0*16), state, callback)) return false;}; if (gt ? static_cast<short int>(chunk >> 1*16) > v : static_cast<short int>(chunk >> 1*16) < v) {if (!find_action<action, Callback>( 1 + baseindex, static_cast<short int>(chunk >> 1*16), state, callback)) return false;}; if (gt ? static_cast<short int>(chunk >> 2*16) > v : static_cast<short int>(chunk >> 2*16) < v) {if (!find_action<action, Callback>( 2 + baseindex, static_cast<short int>(chunk >> 2*16), state, callback)) return false;}; if (gt ? static_cast<short int>(chunk >> 3*16) > v : static_cast<short int>(chunk >> 3*16) < v) {if (!find_action<action, Callback>( 3 + baseindex, static_cast<short int>(chunk >> 3*16), state, callback)) return false;}; /* // Faster but disabled due to bug in VC2010 compiler (fixed in 2012 toolchain) where last 'if' is errorneously optimized away if (gt ? static_cast<short int>chunk > v : static_cast<short int>chunk < v) {if (!state->add_positive_local(0 + baseindex); else return 0;} chunk >>= 16; if (gt ? static_cast<short int>chunk > v : static_cast<short int>chunk < v) {if (!state->add_positive_local(1 + baseindex); else return 1;} chunk >>= 16; if (gt ? static_cast<short int>chunk > v : static_cast<short int>chunk < v) {if (!state->add_positive_local(2 + baseindex); else return 2;} chunk >>= 16; if (gt ? static_cast<short int>chunk > v : static_cast<short int>chunk < v) {if (!state->add_positive_local(3 + baseindex); else return 3;} chunk >>= 16; // Following illustrates it: #include <stdint.h> #include <stdio.h> #include <stdlib.h> size_t bug(int64_t v, uint64_t chunk) { bool gt = true; if (gt ? static_cast<short int>chunk > v : static_cast<short int>chunk < v) {return 0;} chunk >>= 16; if (gt ? static_cast<short int>chunk > v : static_cast<short int>chunk < v) {return 1;} chunk >>= 16; if (gt ? static_cast<short int>chunk > v : static_cast<short int>chunk < v) {return 2;} chunk >>= 16; if (gt ? static_cast<short int>chunk > v : static_cast<short int>chunk < v) {return 3;} chunk >>= 16; return -1; } int main(int argc, char const *const argv[]) { int64_t v; FIXME: We cannot use rand() as it is not thread-safe. if (rand()*rand() == 3) { v = rand()*rand()*rand()*rand()*rand(); printf("Change '3' to something else and run test again\n"); } else { v = 0x2222000000000000ULL; } size_t idx; idx = bug(200, v); if (idx != 3) printf("Compiler failed: idx == %d (expected idx == 3)\n", idx); v = 0x2222000000000000ULL; idx = bug(200, v); if (idx == 3) printf("Touching v made it work\n", idx); } */ } else if (width == 32) { if (gt ? static_cast<int>(chunk) > v : static_cast<int>(chunk) < v) {if (!find_action<action, Callback>( 0 + baseindex, static_cast<int>(chunk), state, callback)) return false;} chunk >>= 32; if (gt ? static_cast<int>(chunk) > v : static_cast<int>(chunk) < v) {if (!find_action<action, Callback>( 1 + baseindex, static_cast<int>(chunk), state, callback)) return false;} chunk >>= 32; } else if (width == 64) { if (gt ? static_cast<int64_t>(v) > v : static_cast<int64_t>(v) < v) {if (!find_action<action, Callback>( 0 + baseindex, static_cast<int64_t>(v), state, callback)) return false;}; } return true; } template<bool eq, Action action, size_t width, class Callback> inline bool Array::compare_equality(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback) const { // Find items in this Array that are equal (eq == true) or different (eq = false) from 'value' REALM_ASSERT_DEBUG(start <= m_size && (end <= m_size || end == size_t(-1)) && start <= end); size_t ee = round_up(start, 64 / no0(width)); ee = ee > end ? end : ee; for (; start < ee; ++start) if (eq ? (get<width>(start) == value) : (get<width>(start) != value)) { if (!find_action<action, Callback>(start + baseindex, get<width>(start), state, callback)) return false; } if (start >= end) return true; if (width != 32 && width != 64) { const int64_t* p = reinterpret_cast<const int64_t*>(m_data + (start * width / 8)); const int64_t* const e = reinterpret_cast<int64_t*>(m_data + (end * width / 8)) - 1; const uint64_t mask = (width == 64 ? ~0ULL : ((1ULL << (width == 64 ? 0 : width)) - 1ULL)); // Warning free way of computing (1ULL << width) - 1 const uint64_t valuemask = ~0ULL / no0(mask) * (value & mask); // the "== ? :" is to avoid division by 0 compiler error while (p < e) { uint64_t chunk = *p; uint64_t v2 = chunk ^ valuemask; start = (p - reinterpret_cast<int64_t*>(m_data)) * 8 * 8 / no0(width); size_t a = 0; while (eq ? test_zero<width>(v2) : v2) { if (find_action_pattern<action, Callback>(start + baseindex, cascade<width, eq>(v2), state, callback)) break; // consumed size_t t = find_zero<eq, width>(v2); a += t; if (a >= 64 / no0(width)) break; if (!find_action<action, Callback>(a + start + baseindex, get<width>(start + t), state, callback)) return false; v2 >>= (t + 1) * width; a += 1; } ++p; } // Loop ended because we are near end or end of array. No need to optimize search in remainder in this case because end of array means that // lots of search work has taken place prior to ending here. So time spent searching remainder is relatively tiny start = (p - reinterpret_cast<int64_t*>(m_data)) * 8 * 8 / no0(width); } while (start < end) { if (eq ? get<width>(start) == value : get<width>(start) != value) { if (!find_action<action, Callback>( start + baseindex, get<width>(start), state, callback)) return false; } ++start; } return true; } // There exists a couple of find() functions that take more or less template arguments. Always call the one that // takes as most as possible to get best performance. // This is the one installed into the m_vtable->finder slots. template<class cond, Action action, size_t bitwidth> bool Array::find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state) const { return find<cond, action, bitwidth>(value, start, end, baseindex, state, CallbackDummy()); } template<class cond, Action action, class Callback> bool Array::find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback, bool nullable_array, bool find_null) const { REALM_TEMPEX4(return find, cond, action, m_width, Callback, (value, start, end, baseindex, state, callback, nullable_array, find_null)); } template<class cond, Action action, size_t bitwidth, class Callback> bool Array::find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback, bool nullable_array, bool find_null) const { return find_optimized<cond, action, bitwidth, Callback>(value, start, end, baseindex, state, callback, nullable_array, find_null); } #ifdef REALM_COMPILER_SSE // 'items' is the number of 16-byte SSE chunks. Returns index of packed element relative to first integer of first chunk template<class cond, Action action, size_t width, class Callback> bool Array::find_sse(int64_t value, __m128i *data, size_t items, QueryState<int64_t>* state, size_t baseindex, Callback callback) const { __m128i search = {0}; // FIXME: Lasse, should these casts not be to int8_t, int16_t, int32_t respecitvely? if (width == 8) search = _mm_set1_epi8(static_cast<char>(value)); // FIXME: Lasse, Should this not be a cast to 'signed char'? else if (width == 16) search = _mm_set1_epi16(static_cast<short int>(value)); else if (width == 32) search = _mm_set1_epi32(static_cast<int>(value)); else if (width == 64) { if (std::is_same<cond, Less>::value) REALM_ASSERT(false); else search = _mm_set_epi64x(value, value); } return find_sse_intern<cond, action, width, Callback>(data, &search, items, state, baseindex, callback); } // Compares packed action_data with packed data (equal, less, etc) and performs aggregate action (max, min, sum, // find_all, etc) on value inside action_data for first match, if any template<class cond, Action action, size_t width, class Callback> REALM_FORCEINLINE bool Array::find_sse_intern(__m128i* action_data, __m128i* data, size_t items, QueryState<int64_t>* state, size_t baseindex, Callback callback) const { size_t i = 0; __m128i compare = {0}; unsigned int resmask; // Search loop. Unrolling it has been tested to NOT increase performance (apparently mem bound) for (i = 0; i < items; ++i) { // equal / not-equal if (std::is_same<cond, Equal>::value || std::is_same<cond, NotEqual>::value) { if (width == 8) compare = _mm_cmpeq_epi8(action_data[i], *data); if (width == 16) compare = _mm_cmpeq_epi16(action_data[i], *data); if (width == 32) compare = _mm_cmpeq_epi32(action_data[i], *data); if (width == 64) { compare = _mm_cmpeq_epi64(action_data[i], *data); // SSE 4.2 only } } // greater else if (std::is_same<cond, Greater>::value) { if (width == 8) compare = _mm_cmpgt_epi8(action_data[i], *data); if (width == 16) compare = _mm_cmpgt_epi16(action_data[i], *data); if (width == 32) compare = _mm_cmpgt_epi32(action_data[i], *data); if (width == 64) compare = _mm_cmpgt_epi64(action_data[i], *data); } // less else if (std::is_same<cond, Less>::value) { if (width == 8) compare = _mm_cmplt_epi8(action_data[i], *data); else if (width == 16) compare = _mm_cmplt_epi16(action_data[i], *data); else if (width == 32) compare = _mm_cmplt_epi32(action_data[i], *data); else REALM_ASSERT(false); } resmask = _mm_movemask_epi8(compare); if (std::is_same<cond, NotEqual>::value) resmask = ~resmask & 0x0000ffff; // if (resmask != 0) // printf("resmask=%d\n", resmask); size_t s = i * sizeof (__m128i) * 8 / no0(width); while (resmask != 0) { uint64_t upper = lower_bits<width / 8>() << (no0(width / 8) - 1); uint64_t pattern = resmask & upper; // fixme, bits at wrong offsets. Only OK because we only use them in 'count' aggregate if (find_action_pattern<action, Callback>(s + baseindex, pattern, state, callback)) break; size_t idx = first_set_bit(resmask) * 8 / no0(width); s += idx; if (!find_action<action, Callback>( s + baseindex, get_universal<width>(reinterpret_cast<char*>(action_data), s), state, callback)) return false; resmask >>= (idx + 1) * no0(width) / 8; ++s; } } return true; } #endif //REALM_COMPILER_SSE template<class cond, Action action, class Callback> bool Array::compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback) const { cond c; REALM_ASSERT_3(start, <=, end); if (start == end) return true; int64_t v; // We can compare first element without checking for out-of-range v = get(start); if (c(v, foreign->get(start))) { if (!find_action<action, Callback>(start + baseindex, v, state, callback)) return false; } start++; if (start + 3 < end) { v = get(start); if (c(v, foreign->get(start))) if (!find_action<action, Callback>(start + baseindex, v, state, callback)) return false; v = get(start + 1); if (c(v, foreign->get(start + 1))) if (!find_action<action, Callback>(start + 1 + baseindex, v, state, callback)) return false; v = get(start + 2); if (c(v, foreign->get(start + 2))) if (!find_action<action, Callback>(start + 2 + baseindex, v, state, callback)) return false; start += 3; } else if (start == end) { return true; } bool r; REALM_TEMPEX4(r = compare_leafs, cond, action, m_width, Callback, (foreign, start, end, baseindex, state, callback)) return r; } template<class cond, Action action, size_t width, class Callback> bool Array::compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback) const { size_t fw = foreign->m_width; bool r; REALM_TEMPEX5(r = compare_leafs_4, cond, action, width, Callback, fw, (foreign, start, end, baseindex, state, callback)) return r; } template<class cond, Action action, size_t width, class Callback, size_t foreign_width> bool Array::compare_leafs_4(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback) const { cond c; char* foreign_m_data = foreign->m_data; if (width == 0 && foreign_width == 0) { if (c(0, 0)) { while (start < end) { if (!find_action<action, Callback>(start + baseindex, 0, state, callback)) return false; start++; } } else { return true; } } #if defined(REALM_COMPILER_SSE) if (sseavx<42>() && width == foreign_width && (width == 8 || width == 16 || width == 32)) { // We can only use SSE if both bitwidths are equal and above 8 bits and all values are signed while (start < end && (((reinterpret_cast<size_t>(m_data) & 0xf) * 8 + start * width) % (128) != 0)) { int64_t v = get_universal<width>(m_data, start); int64_t fv = get_universal<foreign_width>(foreign_m_data, start); if (c(v, fv)) { if (!find_action<action, Callback>(start + baseindex, v, state, callback)) return false; } start++; } if (start == end) return true; size_t sse_items = (end - start) * width / 128; size_t sse_end = start + sse_items * 128 / no0(width); while (start < sse_end) { __m128i* a = reinterpret_cast<__m128i*>(m_data + start * width / 8); __m128i* b = reinterpret_cast<__m128i*>(foreign_m_data + start * width / 8); bool continue_search = find_sse_intern<cond, action, width, Callback>(a, b, 1, state, baseindex + start, callback); if (!continue_search) return false; start += 128 / no0(width); } } #endif #if 0 // this method turned out to be 33% slower than a naive loop. Find out why // index from which both arrays are 64-bit aligned size_t a = round_up(start, 8 * sizeof (int64_t) / (width < foreign_width ? width : foreign_width)); while (start < end && start < a) { int64_t v = get_universal<width>(m_data, start); int64_t fv = get_universal<foreign_width>(foreign_m_data, start); if (v == fv) r++; start++; } if (start >= end) return r; uint64_t chunk; uint64_t fchunk; size_t unroll_outer = (foreign_width > width ? foreign_width : width) / (foreign_width < width ? foreign_width : width); size_t unroll_inner = 64 / (foreign_width > width ? foreign_width : width); while (start + unroll_outer * unroll_inner < end) { // fetch new most narrow chunk if (foreign_width <= width) fchunk = *reinterpret_cast<int64_t*>(foreign_m_data + start * foreign_width / 8); else chunk = *reinterpret_cast<int64_t*>(m_data + start * width / 8); for (size_t uo = 0; uo < unroll_outer; uo++) { // fetch new widest chunk if (foreign_width > width) fchunk = *reinterpret_cast<int64_t*>(foreign_m_data + start * foreign_width / 8); else chunk = *reinterpret_cast<int64_t*>(m_data + start * width / 8); size_t newstart = start + unroll_inner; while (start < newstart) { // Isolate first value from chunk int64_t v = (chunk << (64 - width)) >> (64 - width); int64_t fv = (fchunk << (64 - foreign_width)) >> (64 - foreign_width); chunk >>= width; fchunk >>= foreign_width; // Sign extend if required v = (width <= 4) ? v : (width == 8) ? int8_t(v) : (width == 16) ? int16_t(v) : (width == 32) ? int32_t(v) : int64_t(v); fv = (foreign_width <= 4) ? fv : (foreign_width == 8) ? int8_t(fv) : (foreign_width == 16) ? int16_t(fv) : (foreign_width == 32) ? int32_t(fv) : int64_t(fv); if (v == fv) r++; start++; } } } #endif /* // Unrolling helped less than 2% (non-frequent matches). Todo, investigate further while (start + 1 < end) { int64_t v = get_universal<width>(m_data, start); int64_t v2 = get_universal<width>(m_data, start + 1); int64_t fv = get_universal<foreign_width>(foreign_m_data, start); int64_t fv2 = get_universal<foreign_width>(foreign_m_data, start + 1); if (c(v, fv)) { if (!find_action<action, Callback>(start + baseindex, v, state, callback)) return false; } if (c(v2, fv2)) { if (!find_action<action, Callback>(start + 1 + baseindex, v2, state, callback)) return false; } start += 2; } */ while (start < end) { int64_t v = get_universal<width>(m_data, start); int64_t fv = get_universal<foreign_width>(foreign_m_data, start); if (c(v, fv)) { if (!find_action<action, Callback>(start + baseindex, v, state, callback)) return false; } start++; } return true; } template<class cond, Action action, size_t bitwidth, class Callback> bool Array::compare(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback) const { bool ret = false; if (std::is_same<cond, Equal>::value) ret = compare_equality<true, action, bitwidth, Callback>(value, start, end, baseindex, state, callback); else if (std::is_same<cond, NotEqual>::value) ret = compare_equality<false, action, bitwidth, Callback>(value, start, end, baseindex, state, callback); else if (std::is_same<cond, Greater>::value) ret = compare_relation<true, action, bitwidth, Callback>(value, start, end, baseindex, state, callback); else if (std::is_same<cond, Less>::value) ret = compare_relation<false, action, bitwidth, Callback>(value, start, end, baseindex, state, callback); else REALM_ASSERT_DEBUG(false); return ret; } template<bool gt, Action action, size_t bitwidth, class Callback> bool Array::compare_relation(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback) const { REALM_ASSERT(start <= m_size && (end <= m_size || end == size_t(-1)) && start <= end); uint64_t mask = (bitwidth == 64 ? ~0ULL : ((1ULL << (bitwidth == 64 ? 0 : bitwidth)) - 1ULL)); // Warning free way of computing (1ULL << width) - 1 size_t ee = round_up(start, 64 / no0(bitwidth)); ee = ee > end ? end : ee; for (; start < ee; start++) { if (gt ? (get<bitwidth>(start) > value) : (get<bitwidth>(start) < value)) { if (!find_action<action, Callback>(start + baseindex, get<bitwidth>(start), state, callback)) return false; } } if (start >= end) return true; // none found, continue (return true) regardless what find_action() would have returned on match const int64_t* p = reinterpret_cast<const int64_t*>(m_data + (start * bitwidth / 8)); const int64_t* const e = reinterpret_cast<int64_t*>(m_data + (end * bitwidth / 8)) - 1; // Matches are rare enough to setup fast linear search for remaining items. We use // bit hacks from http://graphics.stanford.edu/~seander/bithacks.html#HasLessInWord if (bitwidth == 1 || bitwidth == 2 || bitwidth == 4 || bitwidth == 8 || bitwidth == 16) { uint64_t magic = find_gtlt_magic<gt, bitwidth>(value); // Bit hacks only work if searched item has its most significant bit clear for 'greater than' or // 'item <= 1 << bitwidth' for 'less than' if (value != int64_t((magic & mask)) && value >= 0 && bitwidth >= 2 && value <= static_cast<int64_t>((mask >> 1) - (gt ? 1 : 0))) { // 15 ms while (p < e) { uint64_t upper = lower_bits<bitwidth>() << (no0(bitwidth) - 1); const int64_t v = *p; size_t idx; // Bit hacks only works if all items in chunk have their most significant bit clear. Test this: upper = upper & v; if (!upper) { idx = find_gtlt_fast<gt, action, bitwidth, Callback>(v, magic, state, (p - reinterpret_cast<int64_t*>(m_data)) * 8 * 8 / no0(bitwidth) + baseindex, callback); } else idx = find_gtlt<gt, action, bitwidth, Callback>(value, v, state, (p - reinterpret_cast<int64_t*>(m_data)) * 8 * 8 / no0(bitwidth) + baseindex, callback); if (!idx) return false; ++p; } } else { // 24 ms while (p < e) { int64_t v = *p; if (!find_gtlt<gt, action, bitwidth, Callback>(value, v, state, (p - reinterpret_cast<int64_t*>(m_data)) * 8 * 8 / no0(bitwidth) + baseindex, callback)) return false; ++p; } } start = (p - reinterpret_cast<int64_t *>(m_data)) * 8 * 8 / no0(bitwidth); } // matchcount logic in SIMD no longer pays off for 32/64 bit ints because we have just 4/2 elements // Test unaligned end and/or values of width > 16 manually while (start < end) { if (gt ? get<bitwidth>(start) > value : get<bitwidth>(start) < value) { if (!find_action<action, Callback>( start + baseindex, get<bitwidth>(start), state, callback)) return false; } ++start; } return true; } template<class cond> size_t Array::find_first(int64_t value, size_t start, size_t end) const { REALM_ASSERT(start <= m_size && (end <= m_size || end == size_t(-1)) && start <= end); QueryState<int64_t> state; state.init(act_ReturnFirst, nullptr, 1); // todo, would be nice to avoid this in order to speed up find_first loops Finder finder = m_vtable->finder[cond::condition]; (this->*finder)(value, start, end, 0, &state); return static_cast<size_t>(state.m_state); } //************************************************************************************* // Finding code ends * //************************************************************************************* } // namespace realm #endif // REALM_ARRAY_HPP
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: Valve.VR.IVRTrackedCamera #include "Valve/VR/IVRTrackedCamera.hpp" // Including type: System.MulticastDelegate #include "System/MulticastDelegate.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: Valve::VR namespace Valve::VR { // Forward declaring type: EVRTrackedCameraError struct EVRTrackedCameraError; } // Forward declaring namespace: System namespace System { // Forward declaring type: IAsyncResult class IAsyncResult; // Forward declaring type: AsyncCallback class AsyncCallback; } // Completed forward declares // Type namespace: Valve.VR namespace Valve::VR { // Size: 0x70 #pragma pack(push, 1) // Autogenerated type: Valve.VR.IVRTrackedCamera/Valve.VR._ReleaseVideoStreamTextureGL // [TokenAttribute] Offset: FFFFFFFF // [UnmanagedFunctionPointerAttribute] Offset: E6C808 class IVRTrackedCamera::_ReleaseVideoStreamTextureGL : public System::MulticastDelegate { public: // Creating value type constructor for type: _ReleaseVideoStreamTextureGL _ReleaseVideoStreamTextureGL() noexcept {} // public System.Void .ctor(System.Object object, System.IntPtr method) // Offset: 0x186E1C0 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static IVRTrackedCamera::_ReleaseVideoStreamTextureGL* New_ctor(::Il2CppObject* object, System::IntPtr method) { static auto ___internal__logger = ::Logger::get().WithContext("Valve::VR::IVRTrackedCamera::_ReleaseVideoStreamTextureGL::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<IVRTrackedCamera::_ReleaseVideoStreamTextureGL*, creationType>(object, method))); } // public Valve.VR.EVRTrackedCameraError Invoke(System.UInt64 hTrackedCamera, System.UInt32 glTextureId) // Offset: 0x186E1D0 Valve::VR::EVRTrackedCameraError Invoke(uint64_t hTrackedCamera, uint glTextureId); // public System.IAsyncResult BeginInvoke(System.UInt64 hTrackedCamera, System.UInt32 glTextureId, System.AsyncCallback callback, System.Object object) // Offset: 0x186E454 System::IAsyncResult* BeginInvoke(uint64_t hTrackedCamera, uint glTextureId, System::AsyncCallback* callback, ::Il2CppObject* object); // public Valve.VR.EVRTrackedCameraError EndInvoke(System.IAsyncResult result) // Offset: 0x186E500 Valve::VR::EVRTrackedCameraError EndInvoke(System::IAsyncResult* result); }; // Valve.VR.IVRTrackedCamera/Valve.VR._ReleaseVideoStreamTextureGL #pragma pack(pop) } DEFINE_IL2CPP_ARG_TYPE(Valve::VR::IVRTrackedCamera::_ReleaseVideoStreamTextureGL*, "Valve.VR", "IVRTrackedCamera/_ReleaseVideoStreamTextureGL"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: Valve::VR::IVRTrackedCamera::_ReleaseVideoStreamTextureGL::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: Valve::VR::IVRTrackedCamera::_ReleaseVideoStreamTextureGL::Invoke // Il2CppName: Invoke template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<Valve::VR::EVRTrackedCameraError (Valve::VR::IVRTrackedCamera::_ReleaseVideoStreamTextureGL::*)(uint64_t, uint)>(&Valve::VR::IVRTrackedCamera::_ReleaseVideoStreamTextureGL::Invoke)> { static const MethodInfo* get() { static auto* hTrackedCamera = &::il2cpp_utils::GetClassFromName("System", "UInt64")->byval_arg; static auto* glTextureId = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::IVRTrackedCamera::_ReleaseVideoStreamTextureGL*), "Invoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{hTrackedCamera, glTextureId}); } }; // Writing MetadataGetter for method: Valve::VR::IVRTrackedCamera::_ReleaseVideoStreamTextureGL::BeginInvoke // Il2CppName: BeginInvoke template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::IAsyncResult* (Valve::VR::IVRTrackedCamera::_ReleaseVideoStreamTextureGL::*)(uint64_t, uint, System::AsyncCallback*, ::Il2CppObject*)>(&Valve::VR::IVRTrackedCamera::_ReleaseVideoStreamTextureGL::BeginInvoke)> { static const MethodInfo* get() { static auto* hTrackedCamera = &::il2cpp_utils::GetClassFromName("System", "UInt64")->byval_arg; static auto* glTextureId = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg; static auto* callback = &::il2cpp_utils::GetClassFromName("System", "AsyncCallback")->byval_arg; static auto* object = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::IVRTrackedCamera::_ReleaseVideoStreamTextureGL*), "BeginInvoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{hTrackedCamera, glTextureId, callback, object}); } }; // Writing MetadataGetter for method: Valve::VR::IVRTrackedCamera::_ReleaseVideoStreamTextureGL::EndInvoke // Il2CppName: EndInvoke template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<Valve::VR::EVRTrackedCameraError (Valve::VR::IVRTrackedCamera::_ReleaseVideoStreamTextureGL::*)(System::IAsyncResult*)>(&Valve::VR::IVRTrackedCamera::_ReleaseVideoStreamTextureGL::EndInvoke)> { static const MethodInfo* get() { static auto* result = &::il2cpp_utils::GetClassFromName("System", "IAsyncResult")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::IVRTrackedCamera::_ReleaseVideoStreamTextureGL*), "EndInvoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result}); } };
/*****************************************************************************/ /* Xdmf */ /* eXtensible Data Model and Format */ /* */ /* Id : XdmfBinaryController.cpp */ /* */ /* Author: */ /* Kenneth Leiter */ /* kenneth.leiter@arl.army.mil */ /* US Army Research Laboratory */ /* Aberdeen Proving Ground, MD */ /* */ /* Copyright @ 2011 US Army Research Laboratory */ /* All Rights Reserved */ /* See 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 above copyright notice */ /* for more information. */ /* */ /*****************************************************************************/ #include <fstream> #include <sstream> #include "XdmfArray.hpp" #include "XdmfArrayType.hpp" #include "XdmfBinaryController.hpp" #include "XdmfError.hpp" namespace { template<size_t T> struct ByteSwaper { static inline void swap(void * p){} static inline void swap(void * p, unsigned int length) { char * data = static_cast<char *>(p); for(unsigned int i=0; i<length; ++i, data+=T){ ByteSwaper<T>::swap(data); } } }; template<> void ByteSwaper<2>::swap(void * p){ char one_byte; char* data = static_cast<char*>(p); one_byte = data[0]; data[0] = data[1]; data[1] = one_byte; } template<> void ByteSwaper<4>::swap(void * p){ char one_byte; char* data = static_cast<char*>(p); one_byte = data[0]; data[0] = data[3]; data[3] = one_byte; one_byte = data[1]; data[1] = data[2]; data[2] = one_byte; } template<> void ByteSwaper<8>::swap(void * p){ char one_byte; char* data = static_cast<char*>(p); one_byte = data[0]; data[0] = data[7]; data[7] = one_byte; one_byte = data[1]; data[1] = data[6]; data[6] = one_byte; one_byte = data[2]; data[2] = data[5]; data[5] = one_byte; one_byte = data[3]; data[3] = data[4]; data[4] = one_byte; } } shared_ptr<XdmfBinaryController> XdmfBinaryController::New(const std::string & filePath, const shared_ptr<const XdmfArrayType> & type, const Endian & endian, const unsigned int seek, const std::vector<unsigned int> & dimensions) { shared_ptr<XdmfBinaryController> p(new XdmfBinaryController(filePath, type, endian, seek, dimensions)); return p; } XdmfBinaryController::XdmfBinaryController(const std::string & filePath, const shared_ptr<const XdmfArrayType> & type, const Endian & endian, const unsigned int seek, const std::vector<unsigned int> & dimensions) : XdmfHeavyDataController(filePath, type, dimensions), mEndian(endian), mSeek(seek) { } XdmfBinaryController::~XdmfBinaryController() { } std::string XdmfBinaryController::getDescriptor() const { return ""; } XdmfBinaryController::Endian XdmfBinaryController::getEndian() const { return mEndian; } std::string XdmfBinaryController::getName() const { return "Binary"; } void XdmfBinaryController::getProperties(std::map<std::string, std::string> & collectedProperties) const { collectedProperties["Format"] = this->getName(); std::stringstream seekStream; seekStream << mSeek; collectedProperties["Seek"] = seekStream.str(); if(mEndian == BIG) { collectedProperties["Endian"] = "Big"; } else if(mEndian == LITTLE) { collectedProperties["Endian"] = "Little"; } } unsigned int XdmfBinaryController::getSeek() const { return mSeek; } void XdmfBinaryController::read(XdmfArray * const array) { array->initialize(mType, mDimensions); std::ifstream fileStream(mFilePath.c_str(), std::ifstream::binary); if(!fileStream.good()) { XdmfError::message(XdmfError::FATAL, "Error reading " + mFilePath + " in XdmfBinaryController::read"); } fileStream.seekg(mSeek); if(!fileStream.good()) { XdmfError::message(XdmfError::FATAL, "Error seeking " + mFilePath + " in XdmfBinaryController::read"); } fileStream.read(static_cast<char *>(array->getValuesInternal()), array->getSize() * mType->getElementSize()); #if defined(XDMF_BIG_ENDIAN) const bool needByteSwap = mEndian == LITTLE; #else const bool needByteSwap = mEndian == BIG; #endif // XDMF_BIG_ENDIAN if(needByteSwap) { switch(mType->getElementSize()){ case 1: break; case 2: ByteSwaper<2>::swap(array->getValuesInternal(), array->getSize()); break; case 4: ByteSwaper<4>::swap(array->getValuesInternal(), array->getSize()); break; case 8: ByteSwaper<8>::swap(array->getValuesInternal(), array->getSize()); break; default: XdmfError::message(XdmfError::FATAL, "Cannot perform endianness swap for datatype"); break; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: MIT /** * @file * @brief Run-time type info enable or disable. * * @details When RTTI is enabled, defines a macro `AZ_TEMPLATE_RTTI`. When * the macro is not defined, RTTI is disabled. * * @details Each library has this header file. These headers are being configured by * `az_rtti_setup()` CMake macro. CMake install will patch this file during installation, depending * on the build flags. */ #pragma once /** * @def AZ_TEMPLATE_RTTI * @brief A macro indicating whether the code is built with RTTI or not. * * @details `AZ_RTTI` could be defined while building the Azure SDK with CMake, however, after * the build is completed, that information is not preserved for the code that consumes Azure SDK * headers, unless the code that consumes the SDK is the part of the same build process. To address * this issue, CMake install would patch the header it places in the installation directory, so that * condition: * `#if defined(AZ_RTTI) || (0)` * becomes, effectively, * `#if defined(AZ_RTTI) || (0 + 1)` * when the library was built with RTTI support, and will make no changes to the * condition when it was not. */ #if defined(AZ_RTTI) || (0 /*@AZ_TEMPLATE_RTTI@*/) #define AZ_TEMPLATE_RTTI #endif
#include "Material.h" #include "AssetManager.h" #include "rapidjson/error/en.h" #include <fstream> Material::Material(ID3D11Device* device, ID3D11DeviceContext* context, std::string assetID, std::string filepath) : Asset(device, context, assetID, filepath) { m_vertexShader = nullptr; m_pixelShader = nullptr; m_diffuseTexture = nullptr; m_specularTexture = nullptr; m_normalTexture = nullptr; m_sampler = nullptr; } Material::Material(ID3D11Device* device, ID3D11DeviceContext* context, std::string assetID) : Asset(device, context, assetID, "") { m_diffuseTexture = nullptr; m_specularTexture = nullptr; m_normalTexture = nullptr; m_sampler = nullptr; } Material::~Material() { m_vertexShader = nullptr; m_pixelShader = nullptr; m_diffuseTexture = nullptr; m_specularTexture = nullptr; m_normalTexture = nullptr; m_sampler = nullptr; } bool Material::create(VertexShader* vertexShader, PixelShader* pixelShader, const MaterialSettings& materialSettings) { m_vertexShader = vertexShader; m_pixelShader = pixelShader; setMaterialSettings(materialSettings); return true; } void Material::saveToJSON(rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { Asset::saveToJSON(writer); writer.Key("type"); writer.String("material"); } VertexShader* Material::getVertexShader() const { return m_vertexShader; } PixelShader* Material::getPixelShader() const { return m_pixelShader; } bool Material::loadFromFile() { // Load the json file std::ifstream ifs(m_filepath, std::ios::in | std::ios::binary); if (!ifs.is_open()) { char errorMessage[512]; strerror_s(errorMessage, 512, errno); std::string errString = std::string(errorMessage); Debug::warning("Failed to load file from " + m_filepath + " when creating material with ID " + m_assetID + ": " + errString); return false; } unsigned int length; ifs.seekg(0, std::ios::end); length = (unsigned int)ifs.tellg(); ifs.seekg(0, std::ios::beg); char* jsonStringBuffer = new char[length + 1]; ifs.read(jsonStringBuffer, length); jsonStringBuffer[length] = '\0'; rapidjson::Document dom; rapidjson::ParseResult result = dom.Parse(jsonStringBuffer); if (result.IsError()) { const char* errorMessage = rapidjson::GetParseError_En(result.Code()); Debug::error("Failed to load material at " + m_filepath + " because there was a parse error at character " + std::to_string(result.Offset()) + ": " + std::string(errorMessage)); delete[] jsonStringBuffer; return false; } delete[] jsonStringBuffer; ifs.close(); rapidjson::Value::MemberIterator vertexShader = dom.FindMember("vertexShader"); if (vertexShader != dom.MemberEnd()) { m_vertexShader = AssetManager::getAsset<VertexShader>(vertexShader->value.GetString()); } else { m_vertexShader = AssetManager::getAsset<VertexShader>(DEFAULT_SHADER_VERTEX); } rapidjson::Value::MemberIterator pixelShader = dom.FindMember("pixelShader"); if (pixelShader != dom.MemberEnd()) { m_pixelShader = AssetManager::getAsset<PixelShader>(pixelShader->value.GetString()); } else { m_pixelShader = AssetManager::getAsset<PixelShader>(DEFAULT_SHADER_PIXEL); } MaterialSettings settings; rapidjson::Value::MemberIterator diffuse = dom.FindMember("diffuse"); if (diffuse != dom.MemberEnd()) { settings.diffuseTextureID = diffuse->value.GetString(); } else { settings.diffuseTextureID = DEFAULT_TEXTURE_DIFFUSE; } rapidjson::Value::MemberIterator specular = dom.FindMember("specular"); if (specular != dom.MemberEnd()) { settings.specularTextureID = specular->value.GetString(); } else { settings.specularTextureID = DEFAULT_TEXTURE_WHITE; } rapidjson::Value::MemberIterator normal = dom.FindMember("normal"); if (normal != dom.MemberEnd()) { settings.normalTextureID = normal->value.GetString(); } else { settings.normalTextureID = DEFAULT_TEXTURE_NORMAL; } rapidjson::Value::MemberIterator sampler = dom.FindMember("sampler"); if (sampler != dom.MemberEnd()) { settings.samplerID = sampler->value.GetString(); } else { settings.samplerID = DEFAULT_SAMPLER; } setMaterialSettings(settings); return true; } MaterialSettings Material::getMaterialSettings() const { MaterialSettings settings; settings.diffuseTextureID = m_diffuseTexture->getAssetID(); settings.specularTextureID = m_specularTexture->getAssetID(); settings.normalTextureID = m_normalTexture->getAssetID(); settings.samplerID = m_sampler->getAssetID(); return settings; } void Material::setMaterialSettings(const MaterialSettings& settings) { Texture* diffuse = AssetManager::getAsset<Texture>(settings.diffuseTextureID); if (!diffuse) { diffuse = AssetManager::getAsset<Texture>(DEFAULT_TEXTURE_DIFFUSE); } Texture* specular = AssetManager::getAsset<Texture>(settings.specularTextureID); if (!specular) { specular = AssetManager::getAsset<Texture>(DEFAULT_TEXTURE_WHITE); } Texture* normal = AssetManager::getAsset<Texture>(settings.normalTextureID); if (!normal) { normal = AssetManager::getAsset<Texture>(DEFAULT_TEXTURE_NORMAL); } Sampler* sampler = AssetManager::getAsset<Sampler>(settings.samplerID); if (!sampler) { sampler = AssetManager::getAsset<Sampler>(DEFAULT_SAMPLER); } m_diffuseTexture = diffuse; m_specularTexture = specular; m_normalTexture = normal; m_sampler = sampler; } void Material::useMaterial() { if(m_vertexShader) m_vertexShader->SetShader(); if (m_pixelShader) { m_pixelShader->SetShader(); ID3D11ShaderResourceView* diffuseSRV = m_diffuseTexture->getSRV(); if (!diffuseSRV) { Debug::error("A texture used by a material must have a shader resource view."); return; } ID3D11ShaderResourceView* specularSRV = m_specularTexture->getSRV(); if (!specularSRV) { Debug::error("A texture used by a material must have a shader resource view."); return; } ID3D11ShaderResourceView* normalSRV = m_normalTexture->getSRV(); if (!normalSRV) { Debug::error("A texture used by a material must have a shader resource view."); return; } m_pixelShader->SetShaderResourceView("diffuseTexture", diffuseSRV); m_pixelShader->SetShaderResourceView("specularTexture", specularSRV); m_pixelShader->SetShaderResourceView("normalTexture", normalSRV); m_pixelShader->SetSamplerState("materialSampler", m_sampler->getSamplerState()); } }
//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #pragma once #include "ngraph/op/util/binary_elementwise_arithmetic.hpp" namespace ngraph { namespace op { /// \brief Elementwise minimum operation. class Minimum : public util::BinaryElementwiseArithmetic { public: NGRAPH_API static const std::string type_name; const std::string& description() const override { return type_name; } /// \brief Constructs a minimum operation. Minimum() = default; /// \brief Constructs a minimum operation. /// /// \param arg0 Node that produces the first input tensor. /// \param arg1 Node that produces the second input tensor. /// \param auto_broadcast Auto broadcast specification Minimum(const Output<Node>& arg0, const Output<Node>& arg1, const AutoBroadcastSpec& auto_broadcast = AutoBroadcastSpec()); virtual std::shared_ptr<Node> copy_with_new_args(const NodeVector& new_args) const override; virtual bool is_commutative() const override { return true; } protected: virtual void generate_adjoints(autodiff::Adjoints& adjoints, const NodeVector& deltas) override; }; } }
#include "defines.h" #include <stm32f4xx_hal.h> void HAL_NVIC_SetPriority(IRQn_Type, uint32_t, uint32_t) { } void HAL_NVIC_EnableIRQ(IRQn_Type) { } void HAL_NVIC_SystemReset() { } void HAL_NVIC_DisableIRQ(IRQn_Type) { }
// copyright (c) 2020-2021 hors<horsicq@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #include "dialogoptions.h" #include "ui_dialogoptions.h" DialogOptions::DialogOptions(QWidget *parent, XOptions *pOptions) : QDialog(parent), ui(new Ui::DialogOptions) { ui->setupUi(this); this->pOptions=pOptions; pOptions->setCheckBox(ui->checkBoxSaveLastDirectory,XOptions::ID_SAVELASTDIRECTORY); pOptions->setCheckBox(ui->checkBoxStayOnTop,XOptions::ID_STAYONTOP); pOptions->setCheckBox(ui->checkBoxSaveBackup,XOptions::ID_SAVEBACKUP); pOptions->setCheckBox(ui->checkBoxShowLogo,XOptions::ID_SHOWLOGO); pOptions->setComboBox(ui->comboBoxStyle,XOptions::ID_STYLE); pOptions->setComboBox(ui->comboBoxQss,XOptions::ID_QSS); pOptions->setComboBox(ui->comboBoxLanguage,XOptions::ID_LANG); pOptions->setLineEdit(ui->lineEditSearchSignatures,XOptions::ID_SEARCHSIGNATURESPATH); #ifdef WIN32 ui->checkBoxContext->setChecked(pOptions->checkContext(X_APPLICATIONNAME,"*")); #else ui->checkBoxContext->hide(); #endif } DialogOptions::~DialogOptions() { delete ui; } void DialogOptions::on_pushButtonOK_clicked() { pOptions->getCheckBox(ui->checkBoxSaveLastDirectory,XOptions::ID_SAVELASTDIRECTORY); pOptions->getCheckBox(ui->checkBoxStayOnTop,XOptions::ID_STAYONTOP); pOptions->getCheckBox(ui->checkBoxSaveBackup,XOptions::ID_SAVEBACKUP); pOptions->getCheckBox(ui->checkBoxShowLogo,XOptions::ID_SHOWLOGO); pOptions->getComboBox(ui->comboBoxStyle,XOptions::ID_STYLE); pOptions->getComboBox(ui->comboBoxQss,XOptions::ID_QSS); pOptions->getComboBox(ui->comboBoxLanguage,XOptions::ID_LANG); pOptions->getLineEdit(ui->lineEditSearchSignatures,XOptions::ID_SEARCHSIGNATURESPATH); #ifdef WIN32 if(pOptions->checkContext(X_APPLICATIONNAME,"*")!=ui->checkBoxContext->isChecked()) { if(ui->checkBoxContext->isChecked()) { pOptions->registerContext(X_APPLICATIONNAME,"*",qApp->applicationFilePath()); } else { pOptions->clearContext(X_APPLICATIONNAME,"*"); } } #endif if(pOptions->isRestartNeeded()) { QMessageBox::information(this,tr("Information"),tr("Please restart the application")); } this->close(); } void DialogOptions::on_pushButtonCancel_clicked() { this->close(); } void DialogOptions::on_toolButtonSearchSignatures_clicked() { QString sText=ui->lineEditSearchSignatures->text(); QString sInitDirectory=XBinary::convertPathName(sText); QString sDirectoryName=QFileDialog::getExistingDirectory(this,tr("Open directory")+QString("..."),sInitDirectory,QFileDialog::ShowDirsOnly); if(!sDirectoryName.isEmpty()) { ui->lineEditSearchSignatures->setText(sDirectoryName); } }
/* cout<<"loading file.. "<<endl; www.sourceforge.net/projects/tinyxml Original code (2.0 and earlier )copyright (c) 2000-2006 Lee Thomason (www.grinninglizard.com) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <ctype.h> #include <iostream> #ifdef TIXML_USE_STL #include <sstream> #endif #include <stdio.h> #include "tinyxml.h" bool TiXmlBase::condenseWhiteSpace = true; void TiXmlBase::PutString( const TIXML_STRING& str, TIXML_STRING* outString ) { int i=0; while( i<(int)str.length() ) { unsigned char c = (unsigned char) str[i]; if ( c == '&' && i < ( (int)str.length() - 2 ) && str[i+1] == '#' && str[i+2] == 'x' ) { // Hexadecimal character reference. // Pass through unchanged. // &#xA9; -- copyright symbol, for example. // // The -1 is a bug fix from Rob Laveaux. It keeps // an overflow from happening if there is no ';'. // There are actually 2 ways to exit this loop - // while fails (error case) and break (semicolon found). // However, there is no mechanism (currently) for // this function to return an error. while ( i<(int)str.length()-1 ) { outString->append( str.c_str() + i, 1 ); ++i; if ( str[i] == ';' ) break; } } else if ( c == '&' ) { outString->append( entity[0].str, entity[0].strLength ); ++i; } else if ( c == '<' ) { outString->append( entity[1].str, entity[1].strLength ); ++i; } else if ( c == '>' ) { outString->append( entity[2].str, entity[2].strLength ); ++i; } else if ( c == '\"' ) { outString->append( entity[3].str, entity[3].strLength ); ++i; } else if ( c == '\'' ) { outString->append( entity[4].str, entity[4].strLength ); ++i; } else if ( c < 32 ) { // Easy pass at non-alpha/numeric/symbol // Below 32 is symbolic. char buf[ 32 ]; #if defined(TIXML_SNPRINTF) TIXML_SNPRINTF( buf, sizeof(buf), "&#x%02X;", (unsigned) ( c & 0xff ) ); #else sprintf( buf, "&#x%02X;", (unsigned) ( c & 0xff ) ); #endif //*ME: warning C4267: convert 'size_t' to 'int' //*ME: Int-Cast to make compiler happy ... outString->append( buf, (int)strlen( buf ) ); ++i; } else { //char realc = (char) c; //outString->append( &realc, 1 ); *outString += (char) c; // somewhat more efficient function call. ++i; } } } TiXmlNode::TiXmlNode( NodeType _type ) : TiXmlBase() { parent = 0; type = _type; firstChild = 0; lastChild = 0; prev = 0; next = 0; } TiXmlNode::~TiXmlNode() { TiXmlNode* node = firstChild; TiXmlNode* temp = 0; while ( node ) { temp = node; node = node->next; delete temp; } } void TiXmlNode::CopyTo( TiXmlNode* target ) const { target->SetValue (value.c_str() ); target->userData = userData; } void TiXmlNode::Clear() { TiXmlNode* node = firstChild; TiXmlNode* temp = 0; while ( node ) { temp = node; node = node->next; delete temp; } firstChild = 0; lastChild = 0; } TiXmlNode* TiXmlNode::LinkEndChild( TiXmlNode* node ) { assert( node->parent == 0 || node->parent == this ); assert( node->GetDocument() == 0 || node->GetDocument() == this->GetDocument() ); if ( node->Type() == TiXmlNode::DOCUMENT ) { delete node; if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); return 0; } node->parent = this; node->prev = lastChild; node->next = 0; if ( lastChild ) lastChild->next = node; else firstChild = node; // it was an empty list. lastChild = node; return node; } TiXmlNode* TiXmlNode::InsertEndChild( const TiXmlNode& addThis ) { if ( addThis.Type() == TiXmlNode::DOCUMENT ) { if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); return 0; } TiXmlNode* node = addThis.Clone(); if ( !node ) return 0; return LinkEndChild( node ); } TiXmlNode* TiXmlNode::InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ) { if ( !beforeThis || beforeThis->parent != this ) { return 0; } if ( addThis.Type() == TiXmlNode::DOCUMENT ) { if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); return 0; } TiXmlNode* node = addThis.Clone(); if ( !node ) return 0; node->parent = this; node->next = beforeThis; node->prev = beforeThis->prev; if ( beforeThis->prev ) { beforeThis->prev->next = node; } else { assert( firstChild == beforeThis ); firstChild = node; } beforeThis->prev = node; return node; } TiXmlNode* TiXmlNode::InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ) { if ( !afterThis || afterThis->parent != this ) { return 0; } if ( addThis.Type() == TiXmlNode::DOCUMENT ) { if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); return 0; } TiXmlNode* node = addThis.Clone(); if ( !node ) return 0; node->parent = this; node->prev = afterThis; node->next = afterThis->next; if ( afterThis->next ) { afterThis->next->prev = node; } else { assert( lastChild == afterThis ); lastChild = node; } afterThis->next = node; return node; } TiXmlNode* TiXmlNode::ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ) { if ( replaceThis->parent != this ) return 0; TiXmlNode* node = withThis.Clone(); if ( !node ) return 0; node->next = replaceThis->next; node->prev = replaceThis->prev; if ( replaceThis->next ) replaceThis->next->prev = node; else lastChild = node; if ( replaceThis->prev ) replaceThis->prev->next = node; else firstChild = node; delete replaceThis; node->parent = this; return node; } bool TiXmlNode::RemoveChild( TiXmlNode* removeThis ) { if ( removeThis->parent != this ) { assert( 0 ); return false; } if ( removeThis->next ) removeThis->next->prev = removeThis->prev; else lastChild = removeThis->prev; if ( removeThis->prev ) removeThis->prev->next = removeThis->next; else firstChild = removeThis->next; delete removeThis; return true; } const TiXmlNode* TiXmlNode::FirstChild( const char * _value ) const { const TiXmlNode* node; for ( node = firstChild; node; node = node->next ) { if ( strcmp( node->Value(), _value ) == 0 ) return node; } return 0; } const TiXmlNode* TiXmlNode::LastChild( const char * _value ) const { const TiXmlNode* node; for ( node = lastChild; node; node = node->prev ) { if ( strcmp( node->Value(), _value ) == 0 ) return node; } return 0; } const TiXmlNode* TiXmlNode::IterateChildren( const TiXmlNode* previous ) const { if ( !previous ) { return FirstChild(); } else { assert( previous->parent == this ); return previous->NextSibling(); } } const TiXmlNode* TiXmlNode::IterateChildren( const char * val, const TiXmlNode* previous ) const { if ( !previous ) { return FirstChild( val ); } else { assert( previous->parent == this ); return previous->NextSibling( val ); } } const TiXmlNode* TiXmlNode::NextSibling( const char * _value ) const { const TiXmlNode* node; for ( node = next; node; node = node->next ) { if ( strcmp( node->Value(), _value ) == 0 ) return node; } return 0; } const TiXmlNode* TiXmlNode::PreviousSibling( const char * _value ) const { const TiXmlNode* node; for ( node = prev; node; node = node->prev ) { if ( strcmp( node->Value(), _value ) == 0 ) return node; } return 0; } void TiXmlElement::RemoveAttribute( const char * name ) { #ifdef TIXML_USE_STL TIXML_STRING str( name ); TiXmlAttribute* node = attributeSet.Find( str ); #else TiXmlAttribute* node = attributeSet.Find( name ); #endif if ( node ) { attributeSet.Remove( node ); delete node; } } const TiXmlElement* TiXmlNode::FirstChildElement() const { const TiXmlNode* node; for ( node = FirstChild(); node; node = node->NextSibling() ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } const TiXmlElement* TiXmlNode::FirstChildElement( const char * _value ) const { const TiXmlNode* node; for ( node = FirstChild( _value ); node; node = node->NextSibling( _value ) ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } const TiXmlElement* TiXmlNode::NextSiblingElement() const { const TiXmlNode* node; for ( node = NextSibling(); node; node = node->NextSibling() ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } const TiXmlElement* TiXmlNode::NextSiblingElement( const char * _value ) const { const TiXmlNode* node; for ( node = NextSibling( _value ); node; node = node->NextSibling( _value ) ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } const TiXmlDocument* TiXmlNode::GetDocument() const { const TiXmlNode* node; for( node = this; node; node = node->parent ) { if ( node->ToDocument() ) return node->ToDocument(); } return 0; } TiXmlElement::TiXmlElement (const char * _value) : TiXmlNode( TiXmlNode::ELEMENT ) { firstChild = lastChild = 0; value = _value; } #ifdef TIXML_USE_STL TiXmlElement::TiXmlElement( const std::string& _value ) : TiXmlNode( TiXmlNode::ELEMENT ) { firstChild = lastChild = 0; value = _value; } #endif TiXmlElement::TiXmlElement( const TiXmlElement& copy) : TiXmlNode( TiXmlNode::ELEMENT ) { firstChild = lastChild = 0; copy.CopyTo( this ); } void TiXmlElement::operator=( const TiXmlElement& base ) { ClearThis(); base.CopyTo( this ); } TiXmlElement::~TiXmlElement() { ClearThis(); } void TiXmlElement::ClearThis() { Clear(); while( attributeSet.First() ) { TiXmlAttribute* node = attributeSet.First(); attributeSet.Remove( node ); delete node; } } const char* TiXmlElement::Attribute( const char* name ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) return node->Value(); return 0; } #ifdef TIXML_USE_STL const std::string* TiXmlElement::Attribute( const std::string& name ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) return &node->ValueStr(); return 0; } #endif const char* TiXmlElement::Attribute( const char* name, int* i ) const { const char* s = Attribute( name ); if ( i ) { if ( s ) { *i = atoi( s ); } else { *i = 0; } } return s; } #ifdef TIXML_USE_STL const std::string* TiXmlElement::Attribute( const std::string& name, int* i ) const { const std::string* s = Attribute( name ); if ( i ) { if ( s ) { *i = atoi( s->c_str() ); } else { *i = 0; } } return s; } #endif const char* TiXmlElement::Attribute( const char* name, double* d ) const { const char* s = Attribute( name ); if ( d ) { if ( s ) { *d = atof( s ); } else { *d = 0; } } return s; } #ifdef TIXML_USE_STL const std::string* TiXmlElement::Attribute( const std::string& name, double* d ) const { const std::string* s = Attribute( name ); if ( d ) { if ( s ) { *d = atof( s->c_str() ); } else { *d = 0; } } return s; } #endif int TiXmlElement::QueryIntAttribute( const char* name, int* ival ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( !node ) return TIXML_NO_ATTRIBUTE; return node->QueryIntValue( ival ); } #ifdef TIXML_USE_STL int TiXmlElement::QueryIntAttribute( const std::string& name, int* ival ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( !node ) return TIXML_NO_ATTRIBUTE; return node->QueryIntValue( ival ); } #endif int TiXmlElement::QueryDoubleAttribute( const char* name, double* dval ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( !node ) return TIXML_NO_ATTRIBUTE; return node->QueryDoubleValue( dval ); } #ifdef TIXML_USE_STL int TiXmlElement::QueryDoubleAttribute( const std::string& name, double* dval ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( !node ) return TIXML_NO_ATTRIBUTE; return node->QueryDoubleValue( dval ); } #endif void TiXmlElement::SetAttribute( const char * name, int val ) { char buf[64]; #if defined(TIXML_SNPRINTF) TIXML_SNPRINTF( buf, sizeof(buf), "%d", val ); #else sprintf( buf, "%d", val ); #endif SetAttribute( name, buf ); } #ifdef TIXML_USE_STL void TiXmlElement::SetAttribute( const std::string& name, int val ) { std::ostringstream oss; oss << val; SetAttribute( name, oss.str() ); } #endif void TiXmlElement::SetDoubleAttribute( const char * name, double val ) { char buf[256]; #if defined(TIXML_SNPRINTF) TIXML_SNPRINTF( buf, sizeof(buf), "%f", val ); #else sprintf( buf, "%f", val ); #endif SetAttribute( name, buf ); } void TiXmlElement::SetAttribute( const char * cname, const char * cvalue ) { #ifdef TIXML_USE_STL TIXML_STRING _name( cname ); TIXML_STRING _value( cvalue ); #else const char* _name = cname; const char* _value = cvalue; #endif TiXmlAttribute* node = attributeSet.Find( _name ); if ( node ) { node->SetValue( _value ); return; } TiXmlAttribute* attrib = new TiXmlAttribute( cname, cvalue ); if ( attrib ) { attributeSet.Add( attrib ); } else { TiXmlDocument* document = GetDocument(); if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, TIXML_ENCODING_UNKNOWN ); } } #ifdef TIXML_USE_STL void TiXmlElement::SetAttribute( const std::string& name, const std::string& _value ) { TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) { node->SetValue( _value ); return; } TiXmlAttribute* attrib = new TiXmlAttribute( name, _value ); if ( attrib ) { attributeSet.Add( attrib ); } else { TiXmlDocument* document = GetDocument(); if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, TIXML_ENCODING_UNKNOWN ); } } #endif void TiXmlElement::Print( FILE* cfile, int depth ) const { int i; assert( cfile ); for ( i=0; i<depth; i++ ) { fprintf( cfile, " " ); } fprintf( cfile, "<%s", value.c_str() ); const TiXmlAttribute* attrib; for ( attrib = attributeSet.First(); attrib; attrib = attrib->Next() ) { fprintf( cfile, " " ); attrib->Print( cfile, depth ); } // There are 3 different formatting approaches: // 1) An element without children is printed as a <foo /> node // 2) An element with only a text child is printed as <foo> text </foo> // 3) An element with children is printed on multiple lines. TiXmlNode* node; if ( !firstChild ) { fprintf( cfile, " />" ); } else if ( firstChild == lastChild && firstChild->ToText() ) { fprintf( cfile, ">" ); firstChild->Print( cfile, depth + 1 ); fprintf( cfile, "</%s>", value.c_str() ); } else { fprintf( cfile, ">" ); for ( node = firstChild; node; node=node->NextSibling() ) { if ( !node->ToText() ) { fprintf( cfile, "\n" ); } node->Print( cfile, depth+1 ); } fprintf( cfile, "\n" ); for( i=0; i<depth; ++i ) { fprintf( cfile, " " ); } fprintf( cfile, "</%s>", value.c_str() ); } } void TiXmlElement::CopyTo( TiXmlElement* target ) const { // superclass: TiXmlNode::CopyTo( target ); // Element class: // Clone the attributes, then clone the children. const TiXmlAttribute* attribute = 0; for( attribute = attributeSet.First(); attribute; attribute = attribute->Next() ) { target->SetAttribute( attribute->Name(), attribute->Value() ); } TiXmlNode* node = 0; for ( node = firstChild; node; node = node->NextSibling() ) { target->LinkEndChild( node->Clone() ); } } bool TiXmlElement::Accept( TiXmlVisitor* visitor ) const { if ( visitor->VisitEnter( *this, attributeSet.First() ) ) { for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) { if ( !node->Accept( visitor ) ) break; } } return visitor->VisitExit( *this ); } TiXmlNode* TiXmlElement::Clone() const { TiXmlElement* clone = new TiXmlElement( Value() ); if ( !clone ) return 0; CopyTo( clone ); return clone; } const char* TiXmlElement::GetText() const { const TiXmlNode* child = this->FirstChild(); if ( child ) { const TiXmlText* childText = child->ToText(); if ( childText ) { return childText->Value(); } } return 0; } TiXmlDocument::TiXmlDocument() : TiXmlNode( TiXmlNode::DOCUMENT ) { tabsize = 4; useMicrosoftBOM = false; ClearError(); } TiXmlDocument::TiXmlDocument( const char * documentName ) : TiXmlNode( TiXmlNode::DOCUMENT ) { tabsize = 4; useMicrosoftBOM = false; value = documentName; ClearError(); } #ifdef TIXML_USE_STL TiXmlDocument::TiXmlDocument( const std::string& documentName ) : TiXmlNode( TiXmlNode::DOCUMENT ) { tabsize = 4; useMicrosoftBOM = false; value = documentName; ClearError(); } #endif TiXmlDocument::TiXmlDocument( const TiXmlDocument& copy ) : TiXmlNode( TiXmlNode::DOCUMENT ) { copy.CopyTo( this ); } void TiXmlDocument::operator=( const TiXmlDocument& copy ) { Clear(); copy.CopyTo( this ); } bool TiXmlDocument::LoadFile( TiXmlEncoding encoding ) { // See STL_STRING_BUG below. //StringToBuffer buf( value ); printf("loading file ..\n"); return LoadFile( Value(), encoding ); } bool TiXmlDocument::SaveFile() const { // See STL_STRING_BUG below. // StringToBuffer buf( value ); // // if ( buf.buffer && SaveFile( buf.buffer ) ) // return true; // // return false; return SaveFile( Value() ); } bool TiXmlDocument::LoadFile( const char* _filename, TiXmlEncoding encoding ) { // There was a really terrifying little bug here. The code: // value = filename // in the STL case, cause the assignment method of the std::string to // be called. What is strange, is that the std::string had the same // address as it's c_str() method, and so bad things happen. Looks // like a bug in the Microsoft STL implementation. // Add an extra string to avoid the crash. TIXML_STRING filename( _filename ); value = filename; // reading in binary mode so that tinyxml can normalize the EOL FILE* file = fopen( value.c_str (), "rb" ); if ( file ) { bool result = LoadFile( file, encoding ); fclose( file ); return result; } else { SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); return false; } } bool TiXmlDocument::LoadFile( FILE* file, TiXmlEncoding encoding ) { if ( !file ) { SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); return false; } // Delete the existing data: Clear(); location.Clear(); // Get the file size, so we can pre-allocate the string. HUGE speed impact. long length = 0; fseek( file, 0, SEEK_END ); length = ftell( file ); fseek( file, 0, SEEK_SET ); // Strange case, but good to handle up front. if ( length == 0 ) { SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); return false; } // If we have a file, assume it is all one big XML file, and read it in. // The document parser may decide the document ends sooner than the entire file, however. TIXML_STRING data; data.reserve( length ); // Subtle bug here. TinyXml did use fgets. But from the XML spec: // 2.11 End-of-Line Handling // <snip> // <quote> // ...the XML processor MUST behave as if it normalized all line breaks in external // parsed entities (including the document entity) on input, before parsing, by translating // both the two-character sequence #xD #xA and any #xD that is not followed by #xA to // a single #xA character. // </quote> // // It is not clear fgets does that, and certainly isn't clear it works cross platform. // Generally, you expect fgets to translate from the convention of the OS to the c/unix // convention, and not work generally. /* while( fgets( buf, sizeof(buf), file ) ) { data += buf; } */ char* buf = new char[ length+1 ]; buf[0] = 0; if ( fread( buf, length, 1, file ) != 1 ) { delete [] buf; SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); return false; } const char* lastPos = buf; const char* p = buf; buf[length] = 0; while( *p ) { assert( p < (buf+length) ); if ( *p == 0xa ) { // Newline character. No special rules for this. Append all the characters // since the last string, and include the newline. data.append( lastPos, (p-lastPos+1) ); // append, include the newline ++p; // move past the newline lastPos = p; // and point to the new buffer (may be 0) assert( p <= (buf+length) ); } else if ( *p == 0xd ) { // Carriage return. Append what we have so far, then // handle moving forward in the buffer. if ( (p-lastPos) > 0 ) { data.append( lastPos, p-lastPos ); // do not add the CR } data += (char)0xa; // a proper newline if ( *(p+1) == 0xa ) { // Carriage return - new line sequence p += 2; lastPos = p; assert( p <= (buf+length) ); } else { // it was followed by something else...that is presumably characters again. ++p; lastPos = p; assert( p <= (buf+length) ); } } else { ++p; } } // Handle any left over characters. if ( p-lastPos ) { data.append( lastPos, p-lastPos ); } delete[] buf; buf = 0; Parse( data.c_str(), 0, encoding ); if ( Error() ){ printf("%s", ErrorDesc()); return false; } else return true; } bool TiXmlDocument::SaveFile( const char * filename ) const { // The old c stuff lives on... FILE* fp = fopen( filename, "w" ); if ( fp ) { bool result = SaveFile( fp ); fclose( fp ); return result; } return false; } bool TiXmlDocument::SaveFile( FILE* fp ) const { if ( useMicrosoftBOM ) { const unsigned char TIXML_UTF_LEAD_0 = 0xefU; const unsigned char TIXML_UTF_LEAD_1 = 0xbbU; const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; fputc( TIXML_UTF_LEAD_0, fp ); fputc( TIXML_UTF_LEAD_1, fp ); fputc( TIXML_UTF_LEAD_2, fp ); } Print( fp, 0 ); return (ferror(fp) == 0); } void TiXmlDocument::CopyTo( TiXmlDocument* target ) const { TiXmlNode::CopyTo( target ); target->error = error; target->errorDesc = errorDesc.c_str (); TiXmlNode* node = 0; for ( node = firstChild; node; node = node->NextSibling() ) { target->LinkEndChild( node->Clone() ); } } TiXmlNode* TiXmlDocument::Clone() const { TiXmlDocument* clone = new TiXmlDocument(); if ( !clone ) return 0; CopyTo( clone ); return clone; } void TiXmlDocument::Print( FILE* cfile, int depth ) const { assert( cfile ); for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) { node->Print( cfile, depth ); fprintf( cfile, "\n" ); } } bool TiXmlDocument::Accept( TiXmlVisitor* visitor ) const { if ( visitor->VisitEnter( *this ) ) { for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) { if ( !node->Accept( visitor ) ) break; } } return visitor->VisitExit( *this ); } const TiXmlAttribute* TiXmlAttribute::Next() const { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( next->value.empty() && next->name.empty() ) return 0; return next; } /* TiXmlAttribute* TiXmlAttribute::Next() { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( next->value.empty() && next->name.empty() ) return 0; return next; } */ const TiXmlAttribute* TiXmlAttribute::Previous() const { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( prev->value.empty() && prev->name.empty() ) return 0; return prev; } /* TiXmlAttribute* TiXmlAttribute::Previous() { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( prev->value.empty() && prev->name.empty() ) return 0; return prev; } */ void TiXmlAttribute::Print( FILE* cfile, int /*depth*/, TIXML_STRING* str ) const { TIXML_STRING n, v; PutString( name, &n ); PutString( value, &v ); if (value.find ('\"') == TIXML_STRING::npos) { if ( cfile ) { fprintf (cfile, "%s=\"%s\"", n.c_str(), v.c_str() ); } if ( str ) { (*str) += n; (*str) += "=\""; (*str) += v; (*str) += "\""; } } else { if ( cfile ) { fprintf (cfile, "%s='%s'", n.c_str(), v.c_str() ); } if ( str ) { (*str) += n; (*str) += "='"; (*str) += v; (*str) += "'"; } } } int TiXmlAttribute::QueryIntValue( int* ival ) const { if ( sscanf( value.c_str(), "%d", ival ) == 1 ) return TIXML_SUCCESS; return TIXML_WRONG_TYPE; } int TiXmlAttribute::QueryDoubleValue( double* dval ) const { if ( sscanf( value.c_str(), "%lf", dval ) == 1 ) return TIXML_SUCCESS; return TIXML_WRONG_TYPE; } void TiXmlAttribute::SetIntValue( int _value ) { char buf [64]; #if defined(TIXML_SNPRINTF) TIXML_SNPRINTF(buf, sizeof(buf), "%d", _value); #else sprintf (buf, "%d", _value); #endif SetValue (buf); } void TiXmlAttribute::SetDoubleValue( double _value ) { char buf [256]; #if defined(TIXML_SNPRINTF) TIXML_SNPRINTF( buf, sizeof(buf), "%lf", _value); #else sprintf (buf, "%lf", _value); #endif SetValue (buf); } int TiXmlAttribute::IntValue() const { return atoi (value.c_str ()); } double TiXmlAttribute::DoubleValue() const { return atof (value.c_str ()); } TiXmlComment::TiXmlComment( const TiXmlComment& copy ) : TiXmlNode( TiXmlNode::COMMENT ) { copy.CopyTo( this ); } void TiXmlComment::operator=( const TiXmlComment& base ) { Clear(); base.CopyTo( this ); } void TiXmlComment::Print( FILE* cfile, int depth ) const { assert( cfile ); for ( int i=0; i<depth; i++ ) { fprintf( cfile, " " ); } fprintf( cfile, "<!--%s-->", value.c_str() ); } void TiXmlComment::CopyTo( TiXmlComment* target ) const { TiXmlNode::CopyTo( target ); } bool TiXmlComment::Accept( TiXmlVisitor* visitor ) const { return visitor->Visit( *this ); } TiXmlNode* TiXmlComment::Clone() const { TiXmlComment* clone = new TiXmlComment(); if ( !clone ) return 0; CopyTo( clone ); return clone; } void TiXmlText::Print( FILE* cfile, int depth ) const { assert( cfile ); if ( cdata ) { int i; fprintf( cfile, "\n" ); for ( i=0; i<depth; i++ ) { fprintf( cfile, " " ); } fprintf( cfile, "<![CDATA[%s]]>\n", value.c_str() ); // unformatted output } else { TIXML_STRING buffer; PutString( value, &buffer ); fprintf( cfile, "%s", buffer.c_str() ); } } void TiXmlText::CopyTo( TiXmlText* target ) const { TiXmlNode::CopyTo( target ); target->cdata = cdata; } bool TiXmlText::Accept( TiXmlVisitor* visitor ) const { return visitor->Visit( *this ); } TiXmlNode* TiXmlText::Clone() const { TiXmlText* clone = 0; clone = new TiXmlText( "" ); if ( !clone ) return 0; CopyTo( clone ); return clone; } TiXmlDeclaration::TiXmlDeclaration( const char * _version, const char * _encoding, const char * _standalone ) : TiXmlNode( TiXmlNode::DECLARATION ) { version = _version; encoding = _encoding; standalone = _standalone; } #ifdef TIXML_USE_STL TiXmlDeclaration::TiXmlDeclaration( const std::string& _version, const std::string& _encoding, const std::string& _standalone ) : TiXmlNode( TiXmlNode::DECLARATION ) { version = _version; encoding = _encoding; standalone = _standalone; } #endif TiXmlDeclaration::TiXmlDeclaration( const TiXmlDeclaration& copy ) : TiXmlNode( TiXmlNode::DECLARATION ) { copy.CopyTo( this ); } void TiXmlDeclaration::operator=( const TiXmlDeclaration& copy ) { Clear(); copy.CopyTo( this ); } void TiXmlDeclaration::Print( FILE* cfile, int /*depth*/, TIXML_STRING* str ) const { if ( cfile ) fprintf( cfile, "<?xml " ); if ( str ) (*str) += "<?xml "; if ( !version.empty() ) { if ( cfile ) fprintf (cfile, "version=\"%s\" ", version.c_str ()); if ( str ) { (*str) += "version=\""; (*str) += version; (*str) += "\" "; } } if ( !encoding.empty() ) { if ( cfile ) fprintf (cfile, "encoding=\"%s\" ", encoding.c_str ()); if ( str ) { (*str) += "encoding=\""; (*str) += encoding; (*str) += "\" "; } } if ( !standalone.empty() ) { if ( cfile ) fprintf (cfile, "standalone=\"%s\" ", standalone.c_str ()); if ( str ) { (*str) += "standalone=\""; (*str) += standalone; (*str) += "\" "; } } if ( cfile ) fprintf( cfile, "?>" ); if ( str ) (*str) += "?>"; } void TiXmlDeclaration::CopyTo( TiXmlDeclaration* target ) const { TiXmlNode::CopyTo( target ); target->version = version; target->encoding = encoding; target->standalone = standalone; } bool TiXmlDeclaration::Accept( TiXmlVisitor* visitor ) const { return visitor->Visit( *this ); } TiXmlNode* TiXmlDeclaration::Clone() const { TiXmlDeclaration* clone = new TiXmlDeclaration(); if ( !clone ) return 0; CopyTo( clone ); return clone; } void TiXmlUnknown::Print( FILE* cfile, int depth ) const { for ( int i=0; i<depth; i++ ) fprintf( cfile, " " ); fprintf( cfile, "<%s>", value.c_str() ); } void TiXmlUnknown::CopyTo( TiXmlUnknown* target ) const { TiXmlNode::CopyTo( target ); } bool TiXmlUnknown::Accept( TiXmlVisitor* visitor ) const { return visitor->Visit( *this ); } TiXmlNode* TiXmlUnknown::Clone() const { TiXmlUnknown* clone = new TiXmlUnknown(); if ( !clone ) return 0; CopyTo( clone ); return clone; } TiXmlAttributeSet::TiXmlAttributeSet() { sentinel.next = &sentinel; sentinel.prev = &sentinel; } TiXmlAttributeSet::~TiXmlAttributeSet() { assert( sentinel.next == &sentinel ); assert( sentinel.prev == &sentinel ); } void TiXmlAttributeSet::Add( TiXmlAttribute* addMe ) { #ifdef TIXML_USE_STL assert( !Find( TIXML_STRING( addMe->Name() ) ) ); // Shouldn't be multiply adding to the set. #else assert( !Find( addMe->Name() ) ); // Shouldn't be multiply adding to the set. #endif addMe->next = &sentinel; addMe->prev = sentinel.prev; sentinel.prev->next = addMe; sentinel.prev = addMe; } void TiXmlAttributeSet::Remove( TiXmlAttribute* removeMe ) { TiXmlAttribute* node; for( node = sentinel.next; node != &sentinel; node = node->next ) { if ( node == removeMe ) { node->prev->next = node->next; node->next->prev = node->prev; node->next = 0; node->prev = 0; return; } } assert( 0 ); // we tried to remove a non-linked attribute. } #ifdef TIXML_USE_STL const TiXmlAttribute* TiXmlAttributeSet::Find( const std::string& name ) const { for( const TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) { if ( node->name == name ) return node; } return 0; } /* TiXmlAttribute* TiXmlAttributeSet::Find( const std::string& name ) { for( TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) { if ( node->name == name ) return node; } return 0; } */ #endif const TiXmlAttribute* TiXmlAttributeSet::Find( const char* name ) const { for( const TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) { if ( strcmp( node->name.c_str(), name ) == 0 ) return node; } return 0; } /* TiXmlAttribute* TiXmlAttributeSet::Find( const char* name ) { for( TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) { if ( strcmp( node->name.c_str(), name ) == 0 ) return node; } return 0; } */ #ifdef TIXML_USE_STL std::istream& operator>> (std::istream & in, TiXmlNode & base) { TIXML_STRING tag; tag.reserve( 8 * 1000 ); base.StreamIn( &in, &tag ); base.Parse( tag.c_str(), 0, TIXML_DEFAULT_ENCODING ); return in; } #endif #ifdef TIXML_USE_STL std::ostream& operator<< (std::ostream & out, const TiXmlNode & base) { TiXmlPrinter printer; printer.SetStreamPrinting(); base.Accept( &printer ); out << printer.Str(); return out; } std::string& operator<< (std::string& out, const TiXmlNode& base ) { TiXmlPrinter printer; printer.SetStreamPrinting(); base.Accept( &printer ); out.append( printer.Str() ); return out; } #endif TiXmlHandle TiXmlHandle::FirstChild() const { if ( node ) { TiXmlNode* child = node->FirstChild(); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::FirstChild( const char * value ) const { if ( node ) { TiXmlNode* child = node->FirstChild( value ); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::FirstChildElement() const { if ( node ) { TiXmlElement* child = node->FirstChildElement(); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::FirstChildElement( const char * value ) const { if ( node ) { TiXmlElement* child = node->FirstChildElement( value ); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::Child( int count ) const { if ( node ) { int i; TiXmlNode* child = node->FirstChild(); for ( i=0; child && i<count; child = child->NextSibling(), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::Child( const char* value, int count ) const { if ( node ) { int i; TiXmlNode* child = node->FirstChild( value ); for ( i=0; child && i<count; child = child->NextSibling( value ), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::ChildElement( int count ) const { if ( node ) { int i; TiXmlElement* child = node->FirstChildElement(); for ( i=0; child && i<count; child = child->NextSiblingElement(), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::ChildElement( const char* value, int count ) const { if ( node ) { int i; TiXmlElement* child = node->FirstChildElement( value ); for ( i=0; child && i<count; child = child->NextSiblingElement( value ), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } bool TiXmlPrinter::VisitEnter( const TiXmlDocument& ) { return true; } bool TiXmlPrinter::VisitExit( const TiXmlDocument& ) { return true; } bool TiXmlPrinter::VisitEnter( const TiXmlElement& element, const TiXmlAttribute* firstAttribute ) { DoIndent(); buffer += "<"; buffer += element.Value(); for( const TiXmlAttribute* attrib = firstAttribute; attrib; attrib = attrib->Next() ) { buffer += " "; attrib->Print( 0, 0, &buffer ); } if ( !element.FirstChild() ) { buffer += " />"; DoLineBreak(); } else { buffer += ">"; if ( element.FirstChild()->ToText() && element.LastChild() == element.FirstChild() && element.FirstChild()->ToText()->CDATA() == false ) { simpleTextPrint = true; // no DoLineBreak()! } else { DoLineBreak(); } } ++depth; return true; } bool TiXmlPrinter::VisitExit( const TiXmlElement& element ) { --depth; if ( !element.FirstChild() ) { // nothing. } else { if ( simpleTextPrint ) { simpleTextPrint = false; } else { DoIndent(); } buffer += "</"; buffer += element.Value(); buffer += ">"; DoLineBreak(); } return true; } bool TiXmlPrinter::Visit( const TiXmlText& text ) { if ( text.CDATA() ) { DoIndent(); buffer += "<![CDATA["; buffer += text.Value(); buffer += "]]>"; DoLineBreak(); } else if ( simpleTextPrint ) { buffer += text.Value(); } else { DoIndent(); buffer += text.Value(); DoLineBreak(); } return true; } bool TiXmlPrinter::Visit( const TiXmlDeclaration& declaration ) { DoIndent(); declaration.Print( 0, 0, &buffer ); DoLineBreak(); return true; } bool TiXmlPrinter::Visit( const TiXmlComment& comment ) { DoIndent(); buffer += "<!--"; buffer += comment.Value(); buffer += "-->"; DoLineBreak(); return true; } bool TiXmlPrinter::Visit( const TiXmlUnknown& unknown ) { DoIndent(); buffer += "<"; buffer += unknown.Value(); buffer += ">"; DoLineBreak(); return true; }
/* * Copyright (C) 2004-2021 Intel Corporation. * SPDX-License-Identifier: MIT */ #include <stdio.h> #include "pin.H" #include <iostream> #include "control_manager.H" using namespace CONTROLLER; // // This test case combines detach.cpp and control.pp // It calls PIN_Detach() whenever a specified region is reached. // You can specify regions by "-skip, -start_address, -ppfile" etc. // // Contains knobs and instrumentation to recognize start/stop points CONTROL_MANAGER control; VOID Handler(EVENT_TYPE ev, VOID* v, CONTEXT* ctxt, VOID* ip, THREADID tid, BOOL bcast) { switch (ev) { case EVENT_START: if (ip == 0) { std::cerr << " IP zero before detach; use -skip/-ppfile/-start_address to specify detach location." << endl; ASSERTX(false); } std::cerr << "Start : Detaching at IP: " << hex << ip << endl; PIN_Detach(); break; case EVENT_STOP: std::cerr << "Stop" << endl; break; default: ASSERT(false, "Received control event " + decstr(ev) + "\n"); break; } } VOID helloWorld(VOID* v) { fprintf(stdout, "Hello world!\n"); } VOID byeWorld(VOID* v) { fprintf(stdout, "Byebye world!\n"); } INT32 Usage() { cerr << "This pin tool demonstrates uses CONTROL to identify start points in a program and does a PIN_Detach() at those " "points. \n" "\n"; cerr << KNOB_BASE::StringKnobSummary() << endl; return -1; } int main(int argc, char* argv[]) { if (PIN_Init(argc, argv)) { return Usage(); } // Activate alarm, must be done before PIN_StartProgram control.RegisterHandler(Handler, 0, FALSE); control.Activate(); // Callback function "byeWorld" is invoked // right before Pin releases control of the application // to allow it to return to normal execution PIN_AddDetachFunction(helloWorld, 0); PIN_AddDetachFunction(byeWorld, 0); // Never returns PIN_StartProgram(); return 0; }
//---------------------------------------------------- // file: UI_SceneOptions.cpp //---------------------------------------------------- #include "Pch.h" #pragma hdrstop #include "NetDeviceLog.h" #include "CustomControls.h" #include "UI_Main.h" #include "Scene.h" #include "UI_SceneOptions.h" #include "MenuTemplate.rh" //---------------------------------------------------- UI_SceneOptions OpDialog; //---------------------------------------------------- bool BrowseFolder( HWND parent, char *path ){ _ASSERTE( path ); char displayname[MAX_PATH]=""; BROWSEINFO info; memset(&info,0,sizeof(info)); info.hwndOwner = parent; info.pszDisplayName = displayname; info.lpszTitle = "Select folder"; info.ulFlags = 0; /*BIF_RETURNFSANCESTORS*/ LPITEMIDLIST item = SHBrowseForFolder( &info ); if( item ){ if( SHGetPathFromIDList( item, path ) ) return true; } return false; } //---------------------------------------------------- static BOOL CALLBACK MainSceneOptionsDialogProc( HWND hw, UINT msg, WPARAM wp, LPARAM lp){ LPPSHNOTIFY psn; switch( msg ){ case WM_INITDIALOG: SetDlgItemText( hw, IDC_LEVEL_NAME, Scene.m_LevelName ); break; case WM_NOTIFY: psn = (LPPSHNOTIFY)lp; if( psn->hdr.code == PSN_APPLY ){ GetDlgItemText( hw, IDC_LEVEL_NAME, Scene.m_LevelName, sizeof(Scene.m_LevelName) ); } break; default: return FALSE; } return TRUE; } static BOOL CALLBACK BuildSceneOptionsDialogProc( HWND hw, UINT msg, WPARAM wp, LPARAM lp){ LPPSHNOTIFY psn; switch( msg ){ case WM_INITDIALOG: UI.SetDlgItemFloat( hw, IDC_VIS_DX, Scene.m_BOPVisCellSize.x, 3 ); UI.SetDlgItemFloat( hw, IDC_VIS_DZ, Scene.m_BOPVisCellSize.z, 3 ); UI.SetDlgItemFloat( hw, IDC_IND_X_SUB, Scene.m_BOPIndentLow.x, 3 ); UI.SetDlgItemFloat( hw, IDC_IND_Z_SUB, Scene.m_BOPIndentLow.z, 3 ); UI.SetDlgItemFloat( hw, IDC_IND_X_ADD, Scene.m_BOPIndentHigh.x, 3 ); UI.SetDlgItemFloat( hw, IDC_IND_Z_ADD, Scene.m_BOPIndentHigh.z, 3 ); UI.SetDlgItemFloat( hw, IDC_COLL_CELL, Scene.m_BOPVisQuad, 3 ); UI.SetDlgItemFloat( hw, IDC_OPT_MINDIST, Scene.m_BOPConnectDist, 3 ); UI.SetDlgItemFloat( hw, IDC_OPT_MAXSIZE, Scene.m_BOPAvObjSize, 3 ); SetCheck( hw, IDC_ENABLE_OPT, Scene.m_BOPOptimize ); SetCheck( hw, IDC_ENABLE_LMAPS, Scene.m_BOPLightMaps ); break; case WM_NOTIFY: psn = (LPPSHNOTIFY)lp; if( psn->hdr.code == PSN_APPLY ){ Scene.m_BOPVisCellSize.x = UI.GetDlgItemFloat( hw, IDC_VIS_DX ); Scene.m_BOPVisCellSize.z = UI.GetDlgItemFloat( hw, IDC_VIS_DZ ); Scene.m_BOPIndentLow.x = UI.GetDlgItemFloat( hw, IDC_IND_X_SUB ); Scene.m_BOPIndentLow.z = UI.GetDlgItemFloat( hw, IDC_IND_Z_SUB ); Scene.m_BOPIndentHigh.x = UI.GetDlgItemFloat( hw, IDC_IND_X_ADD ); Scene.m_BOPIndentHigh.z = UI.GetDlgItemFloat( hw, IDC_IND_Z_ADD ); Scene.m_BOPVisQuad = UI.GetDlgItemFloat( hw, IDC_COLL_CELL ); Scene.m_BOPConnectDist = UI.GetDlgItemFloat( hw, IDC_OPT_MINDIST ); Scene.m_BOPAvObjSize = UI.GetDlgItemFloat( hw, IDC_OPT_MAXSIZE ); Scene.m_BOPOptimize = IsChecked( hw, IDC_ENABLE_OPT ); Scene.m_BOPLightMaps = IsChecked( hw, IDC_ENABLE_LMAPS ); } break; default: return FALSE; } return TRUE; } static BOOL CALLBACK PathsSceneOptionsDialogProc( HWND hw, UINT msg, WPARAM wp, LPARAM lp){ LPPSHNOTIFY psn; char pathbuffer[MAX_PATH]; switch( msg ){ case WM_INITDIALOG: SetDlgItemText( hw, IDC_LEVEL_PATH_T, Scene.m_FNLevelPath ); SetDlgItemText( hw, IDC_TEX_PATH_T, Scene.m_FNTexPath ); break; case WM_COMMAND: switch( LOWORD(wp)) { case IDC_LEVEL_PATH_B: GetDlgItemText( hw, IDC_LEVEL_PATH_T, pathbuffer, MAX_PATH ); if( BrowseFolder( hw, pathbuffer ) ) SetDlgItemText( hw, IDC_LEVEL_PATH_T, pathbuffer ); break; case IDC_TEX_PATH_B: GetDlgItemText( hw, IDC_TEX_PATH_T, pathbuffer, MAX_PATH ); if( BrowseFolder( hw, pathbuffer ) ) SetDlgItemText( hw, IDC_TEX_PATH_T, pathbuffer ); break; } break; case WM_NOTIFY: psn = (LPPSHNOTIFY)lp; if( psn->hdr.code == PSN_APPLY ){ GetDlgItemText( hw, IDC_LEVEL_PATH_T, Scene.m_FNLevelPath, sizeof(Scene.m_FNLevelPath) ); GetDlgItemText( hw, IDC_TEX_PATH_T, Scene.m_FNTexPath, sizeof(Scene.m_FNTexPath) ); } break; default: return FALSE; } return TRUE; } static BOOL CALLBACK FilesSceneOptionsDialogProc( HWND hw, UINT msg, WPARAM wp, LPARAM lp){ LPPSHNOTIFY psn; switch( msg ){ case WM_INITDIALOG: SetDlgItemText( hw, IDC_OGFS, Scene.m_BOPAddFiles ); SetDlgItemText( hw, IDC_FN_LTX, Scene.m_FNLtx ); SetDlgItemText( hw, IDC_FN_FORMS, Scene.m_FNForms ); SetDlgItemText( hw, IDC_FN_LIGHTS, Scene.m_FNLights ); SetDlgItemText( hw, IDC_FN_MESHLIST, Scene.m_FNMeshList ); SetDlgItemText( hw, IDC_FN_MAP, Scene.m_FNMap ); SetDlgItemText( hw, IDC_FN_VIS, Scene.m_FNVisibility ); break; case WM_NOTIFY: psn = (LPPSHNOTIFY)lp; if( psn->hdr.code == PSN_APPLY ){ GetDlgItemText( hw, IDC_OGFS, Scene.m_BOPAddFiles, sizeof(Scene.m_BOPAddFiles) ); GetDlgItemText( hw, IDC_FN_LTX, Scene.m_FNLtx, sizeof(Scene.m_FNLtx) ); GetDlgItemText( hw, IDC_FN_FORMS, Scene.m_FNForms, sizeof(Scene.m_FNForms) ); GetDlgItemText( hw, IDC_FN_LIGHTS, Scene.m_FNLights, sizeof(Scene.m_FNLights) ); GetDlgItemText( hw, IDC_FN_MESHLIST, Scene.m_FNMeshList, sizeof(Scene.m_FNMeshList) ); GetDlgItemText( hw, IDC_FN_MAP, Scene.m_FNMap, sizeof(Scene.m_FNMap) ); GetDlgItemText( hw, IDC_FN_VIS, Scene.m_FNVisibility, sizeof(Scene.m_FNVisibility) ); } break; default: return FALSE; } return TRUE; } static BOOL CALLBACK TextSceneOptionsDialogProc( HWND hw, UINT msg, WPARAM wp, LPARAM lp){ LPPSHNOTIFY psn; switch( msg ){ case WM_INITDIALOG: SetDlgItemText( hw, IDC_LEVEL_TEXT, Scene.m_BOPText ); break; case WM_NOTIFY: psn = (LPPSHNOTIFY)lp; if( psn->hdr.code == PSN_APPLY ){ GetDlgItemText( hw, IDC_LEVEL_TEXT, Scene.m_BOPText, sizeof(Scene.m_BOPText) ); } break; default: return FALSE; } return TRUE; } static bool SelColor( HWND hw, IFColor& color ){ static COLORREF custcolors[16]; static bool custcolorsinitialized = false; if( !custcolorsinitialized ){ for( int i=0; i<16; i++) custcolors[i] = RGB( i*16, i*16, i*16 ); custcolorsinitialized = true; } CHOOSECOLOR ccr; memset( &ccr, 0, sizeof(ccr) ); ccr.lStructSize = sizeof(ccr); ccr.hwndOwner = hw; ccr.rgbResult = color.colorref(); ccr.lpCustColors = custcolors; ccr.Flags = CC_ANYCOLOR|CC_FULLOPEN|CC_RGBINIT; if( ChooseColor( &ccr ) ){ color.set( GetRValue(ccr.rgbResult) / 255.f, GetGValue(ccr.rgbResult) / 255.f, GetBValue(ccr.rgbResult) / 255.f ); return true; } return false; } static BOOL CALLBACK LightSceneOptionsDialogProc( HWND hw, UINT msg, WPARAM wp, LPARAM lp){ IFColor color; LPPSHNOTIFY psn; HBRUSH hbr; LPDRAWITEMSTRUCT ds; switch( msg ){ case WM_INITDIALOG: UI.SetDlgItemFloat( hw, IDC_LIGHT_AMBIENT_R, Scene.m_GlobalAmbient.r, 3 ); UI.SetDlgItemFloat( hw, IDC_LIGHT_AMBIENT_G, Scene.m_GlobalAmbient.g, 3 ); UI.SetDlgItemFloat( hw, IDC_LIGHT_AMBIENT_B, Scene.m_GlobalAmbient.b, 3 ); UI.SetDlgItemFloat( hw, IDC_LIGHT_DIFFUSE_R, Scene.m_GlobalDiffuse.r, 3 ); UI.SetDlgItemFloat( hw, IDC_LIGHT_DIFFUSE_G, Scene.m_GlobalDiffuse.g, 3 ); UI.SetDlgItemFloat( hw, IDC_LIGHT_DIFFUSE_B, Scene.m_GlobalDiffuse.b, 3 ); UI.SetDlgItemFloat( hw, IDC_LIGHT_SPECULAR_R, Scene.m_GlobalSpecular.r, 3 ); UI.SetDlgItemFloat( hw, IDC_LIGHT_SPECULAR_G, Scene.m_GlobalSpecular.g, 3 ); UI.SetDlgItemFloat( hw, IDC_LIGHT_SPECULAR_B, Scene.m_GlobalSpecular.b, 3 ); InvalidateRect( GetDlgItem(hw,IDC_LIGHT_AMBIENT),0,0); InvalidateRect( GetDlgItem(hw,IDC_LIGHT_DIFFUSE),0,0); InvalidateRect( GetDlgItem(hw,IDC_LIGHT_SPECULAR),0,0); break; case WM_NOTIFY: psn = (LPPSHNOTIFY)lp; if( psn->hdr.code == PSN_APPLY ){ Scene.m_GlobalAmbient.r = UI.GetDlgItemFloat( hw, IDC_LIGHT_AMBIENT_R ); Scene.m_GlobalAmbient.g = UI.GetDlgItemFloat( hw, IDC_LIGHT_AMBIENT_G ); Scene.m_GlobalAmbient.b = UI.GetDlgItemFloat( hw, IDC_LIGHT_AMBIENT_B ); Scene.m_GlobalDiffuse.r = UI.GetDlgItemFloat( hw, IDC_LIGHT_DIFFUSE_R ); Scene.m_GlobalDiffuse.g = UI.GetDlgItemFloat( hw, IDC_LIGHT_DIFFUSE_G ); Scene.m_GlobalDiffuse.b = UI.GetDlgItemFloat( hw, IDC_LIGHT_DIFFUSE_B ); Scene.m_GlobalSpecular.r = UI.GetDlgItemFloat( hw, IDC_LIGHT_SPECULAR_R ); Scene.m_GlobalSpecular.g = UI.GetDlgItemFloat( hw, IDC_LIGHT_SPECULAR_G ); Scene.m_GlobalSpecular.b = UI.GetDlgItemFloat( hw, IDC_LIGHT_SPECULAR_B ); } break; case WM_COMMAND: switch( LOWORD(wp) ){ case IDC_LIGHT_AMBIENT: color.r = UI.GetDlgItemFloat( hw, IDC_LIGHT_AMBIENT_R ); color.g = UI.GetDlgItemFloat( hw, IDC_LIGHT_AMBIENT_G ); color.b = UI.GetDlgItemFloat( hw, IDC_LIGHT_AMBIENT_B ); if( SelColor( hw, color ) ){ UI.SetDlgItemFloat( hw, IDC_LIGHT_AMBIENT_R, color.r, 4 ); UI.SetDlgItemFloat( hw, IDC_LIGHT_AMBIENT_G, color.g, 4 ); UI.SetDlgItemFloat( hw, IDC_LIGHT_AMBIENT_B, color.b, 4 ); InvalidateRect( GetDlgItem(hw,LOWORD(wp)),0,0); } break; case IDC_LIGHT_DIFFUSE: color.r = UI.GetDlgItemFloat( hw, IDC_LIGHT_DIFFUSE_R ); color.g = UI.GetDlgItemFloat( hw, IDC_LIGHT_DIFFUSE_G ); color.b = UI.GetDlgItemFloat( hw, IDC_LIGHT_DIFFUSE_B ); if( SelColor( hw, color ) ){ UI.SetDlgItemFloat( hw, IDC_LIGHT_DIFFUSE_R, color.r, 4 ); UI.SetDlgItemFloat( hw, IDC_LIGHT_DIFFUSE_G, color.g, 4 ); UI.SetDlgItemFloat( hw, IDC_LIGHT_DIFFUSE_B, color.b, 4 ); InvalidateRect( GetDlgItem(hw,LOWORD(wp)),0,0); } break; case IDC_LIGHT_SPECULAR: color.r = UI.GetDlgItemFloat( hw, IDC_LIGHT_SPECULAR_R ); color.g = UI.GetDlgItemFloat( hw, IDC_LIGHT_SPECULAR_G ); color.b = UI.GetDlgItemFloat( hw, IDC_LIGHT_SPECULAR_B ); if( SelColor( hw, color ) ){ UI.SetDlgItemFloat( hw, IDC_LIGHT_SPECULAR_R, color.r, 4 ); UI.SetDlgItemFloat( hw, IDC_LIGHT_SPECULAR_G, color.g, 4 ); UI.SetDlgItemFloat( hw, IDC_LIGHT_SPECULAR_B, color.b, 4 ); InvalidateRect( GetDlgItem(hw,LOWORD(wp)),0,0); } break; } break; case WM_DRAWITEM: ds = (LPDRAWITEMSTRUCT)lp; switch( (UINT)wp ){ case IDC_LIGHT_AMBIENT: color.r = UI.GetDlgItemFloat( hw, IDC_LIGHT_AMBIENT_R ); color.g = UI.GetDlgItemFloat( hw, IDC_LIGHT_AMBIENT_G ); color.b = UI.GetDlgItemFloat( hw, IDC_LIGHT_AMBIENT_B ); hbr = CreateSolidBrush( color.colorref() ); FillRect( ds->hDC, &ds->rcItem, hbr ); DeleteObject( hbr ); break; case IDC_LIGHT_DIFFUSE: color.r = UI.GetDlgItemFloat( hw, IDC_LIGHT_DIFFUSE_R ); color.g = UI.GetDlgItemFloat( hw, IDC_LIGHT_DIFFUSE_G ); color.b = UI.GetDlgItemFloat( hw, IDC_LIGHT_DIFFUSE_B ); hbr = CreateSolidBrush( color.colorref() ); FillRect( ds->hDC, &ds->rcItem, hbr ); DeleteObject( hbr ); break; case IDC_LIGHT_SPECULAR: color.r = UI.GetDlgItemFloat( hw, IDC_LIGHT_SPECULAR_R ); color.g = UI.GetDlgItemFloat( hw, IDC_LIGHT_SPECULAR_G ); color.b = UI.GetDlgItemFloat( hw, IDC_LIGHT_SPECULAR_B ); hbr = CreateSolidBrush( color.colorref() ); FillRect( ds->hDC, &ds->rcItem, hbr ); DeleteObject( hbr ); break; } break; default: return FALSE; } return TRUE; } static DWORD WINAPI SceneOptionsThread( LPVOID ){ PROPSHEETHEADER m_PSHeader; PROPSHEETPAGE m_PSPages[6]; m_PSPages[0].dwSize = sizeof(PROPSHEETPAGE); m_PSPages[0].dwFlags = PSP_USETITLE; m_PSPages[0].hInstance = OpDialog.m_Instance; m_PSPages[0].pszTemplate = MAKEINTRESOURCE(IDD_SCENEPROP_MAIN); m_PSPages[0].pfnDlgProc = MainSceneOptionsDialogProc; m_PSPages[0].pszTitle = "Main Options"; m_PSPages[1].dwSize = sizeof(PROPSHEETPAGE); m_PSPages[1].dwFlags = PSP_USETITLE; m_PSPages[1].hInstance = OpDialog.m_Instance; m_PSPages[1].pszTemplate = MAKEINTRESOURCE(IDD_SCENEPROP_BUILD); m_PSPages[1].pfnDlgProc = BuildSceneOptionsDialogProc; m_PSPages[1].pszTitle = "Build Options"; m_PSPages[2].dwSize = sizeof(PROPSHEETPAGE); m_PSPages[2].dwFlags = PSP_USETITLE; m_PSPages[2].hInstance = OpDialog.m_Instance; m_PSPages[2].pszTemplate = MAKEINTRESOURCE(IDD_SCENEPROP_PATHS); m_PSPages[2].pfnDlgProc = PathsSceneOptionsDialogProc; m_PSPages[2].pszTitle = "Directories"; m_PSPages[3].dwSize = sizeof(PROPSHEETPAGE); m_PSPages[3].dwFlags = PSP_USETITLE; m_PSPages[3].hInstance = OpDialog.m_Instance; m_PSPages[3].pszTemplate = MAKEINTRESOURCE(IDD_SCENEPROP_FILES); m_PSPages[3].pfnDlgProc = FilesSceneOptionsDialogProc; m_PSPages[3].pszTitle = "Files"; m_PSPages[4].dwSize = sizeof(PROPSHEETPAGE); m_PSPages[4].dwFlags = PSP_USETITLE; m_PSPages[4].hInstance = OpDialog.m_Instance; m_PSPages[4].pszTemplate = MAKEINTRESOURCE(IDD_SCENEPROP_TEXT); m_PSPages[4].pfnDlgProc = TextSceneOptionsDialogProc; m_PSPages[4].pszTitle = "Text"; m_PSPages[5].dwSize = sizeof(PROPSHEETPAGE); m_PSPages[5].dwFlags = PSP_USETITLE; m_PSPages[5].hInstance = OpDialog.m_Instance; m_PSPages[5].pszTemplate = MAKEINTRESOURCE(IDD_SCENEPROP_LIGHT); m_PSPages[5].pfnDlgProc = LightSceneOptionsDialogProc; m_PSPages[5].pszTitle = "Global lighting"; memset( &m_PSHeader, 0, sizeof(m_PSHeader) ); m_PSHeader.dwSize = sizeof(m_PSHeader); m_PSHeader.dwFlags = PSH_DEFAULT|PSH_PROPSHEETPAGE; m_PSHeader.hwndParent = OpDialog.m_ParentWindow; m_PSHeader.hInstance = OpDialog.m_Instance; m_PSHeader.nPages = 6; m_PSHeader.nStartPage = 0; m_PSHeader.pszCaption = "Scene Properties"; m_PSHeader.ppsp = m_PSPages; PropertySheet( &m_PSHeader ); return 0; } //---------------------------------------------------- UI_SceneOptions::UI_SceneOptions(){ _ASSERTE( &OpDialog == this ); m_Instance = 0; m_ParentWindow = 0; m_ThreadID = 0; m_Thread = 0; } UI_SceneOptions::~UI_SceneOptions(){ } bool UI_SceneOptions::Open( HINSTANCE instance, HWND parent ){ if( m_Thread ){ DWORD exit_code = STILL_ACTIVE; GetExitCodeThread(m_Thread,&exit_code); if( exit_code == STILL_ACTIVE ) TerminateThread(m_Thread, 0 ); CloseHandle( m_Thread ); m_Thread = 0; } m_Instance = instance; m_ParentWindow = parent; m_Thread = CreateThread( 0, 0, SceneOptionsThread, 0, 0, &m_ThreadID ); return true; } //----------------------------------------------------
//LIC// ==================================================================== //LIC// This file forms part of oomph-lib, the object-oriented, //LIC// multi-physics finite-element library, available //LIC// at http://www.oomph-lib.org. //LIC// //LIC// Copyright (C) 2006-2021 Matthias Heil and Andrew Hazel //LIC// //LIC// This library is free software; you can redistribute it and/or //LIC// modify it under the terms of the GNU Lesser General Public //LIC// License as published by the Free Software Foundation; either //LIC// version 2.1 of the License, or (at your option) any later version. //LIC// //LIC// This library is distributed in the hope that it will be useful, //LIC// but WITHOUT ANY WARRANTY; without even the implied warranty of //LIC// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU //LIC// Lesser General Public License for more details. //LIC// //LIC// You should have received a copy of the GNU Lesser General Public //LIC// License along with this library; if not, write to the Free Software //LIC// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA //LIC// 02110-1301 USA. //LIC// //LIC// The authors may be contacted at oomph-lib@maths.man.ac.uk. //LIC// //LIC//==================================================================== // //Driver for a multi-physics problem that couples a Navier--Stokes //mesh to two advection diffusion meshes, giving double diffusive convection //in the Boussinesq approximation //Oomph-lib headers and derived elements are in a separate header file #include "db_nst_external_elements.h" // Both meshes are the standard rectangular quadmesh #include "meshes/rectangular_quadmesh.h" // Use the oomph and std namespaces using namespace oomph; using namespace std; //======start_of_namespace============================================ /// Namespace for the physical parameters in the problem //==================================================================== namespace Global_Physical_Variables { /// The Lewis number double Lewis = 10.0; /// Peclet number (identically one from our non-dimensionalisation) double Peclet=1.0; /// 1/Prandtl number double Inverse_Prandtl=1.0; /// Thermal Rayleigh number, set to be greater than /// the threshold for linear instability double Rayleigh_T = 1800.0; /// Solutal Rayleigh number double Rayleigh_S = -1000; /// Length of domain double Lambda = 1.414; /// Gravity vector Vector<double> Direction_of_gravity(2); } // end_of_namespace /// /////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////// //=======start_of_problem_class======================================= /// 2D Convection problem on two rectangular domains, discretised /// with refineable Navier-Stokes and Advection-Diffusion elements. /// The specific type of element is specified via the template parameters. //==================================================================== template<class NST_ELEMENT,class AD_ELEMENT> class RefineableDDConvectionProblem : public Problem { public: /// Constructor RefineableDDConvectionProblem(); /// Destructor. Empty ~RefineableDDConvectionProblem() { //Delete the meshes delete Conc_mesh_pt; delete Temp_mesh_pt; delete Nst_mesh_pt; //Delete the timestepper delete this->time_stepper_pt(); } /// Actions before the timestep (update the the time-dependent /// boundary conditions) void actions_before_implicit_timestep() { set_boundary_conditions(time_pt()->time()); } /// Set the boundary conditions void set_boundary_conditions(const double &time); /// Access function to the NST mesh. /// Casts the pointer to the base Mesh object to /// the actual mesh type. RefineableRectangularQuadMesh<NST_ELEMENT>* nst_mesh_pt() { return dynamic_cast<RefineableRectangularQuadMesh<NST_ELEMENT>*> (Nst_mesh_pt); } // end_of_nst_mesh /// Access function to the AD mesh. /// Casts the pointer to the base Mesh object to /// the actual mesh type. RefineableRectangularQuadMesh<AD_ELEMENT>* temp_mesh_pt() { return dynamic_cast<RefineableRectangularQuadMesh<AD_ELEMENT>*> (Temp_mesh_pt); } // end_of_ad_mesh /// Access function to the AD mesh. /// Casts the pointer to the base Mesh object to /// the actual mesh type. RefineableRectangularQuadMesh<AD_ELEMENT>* conc_mesh_pt() { return dynamic_cast<RefineableRectangularQuadMesh<AD_ELEMENT>*> (Conc_mesh_pt); } // end_of_ad_mesh /// Get kinetic energy and kinetic energy flux void get_kinetic_energy(double &E, double &Edot) { //Reset values to zero E = 0.0; Edot=0.0; //Loop over the elements unsigned n_element = nst_mesh_pt()->nelement(); for(unsigned e=0;e<n_element;e++) { NST_ELEMENT* elem_pt = dynamic_cast<NST_ELEMENT*>(nst_mesh_pt()->element_pt(e)); E += elem_pt->kin_energy(); Edot += elem_pt->d_kin_energy_dt(); } } /// Actions before adapt:(empty) void actions_before_adapt() {} /// Actions after adaptation, reset all sources, then /// re-pin a single pressure degree of freedom void actions_after_adapt() { //Unpin all the pressures in NST mesh to avoid pinning two pressures RefineableNavierStokesEquations<2>:: unpin_all_pressure_dofs(nst_mesh_pt()->element_pt()); //Pin the zero-th pressure dof in the zero-th element and set // its value to zero fix_pressure(0,0,0.0); // Set sources for temperature Multi_domain_functions::setup_multi_domain_interactions <NST_ELEMENT,AD_ELEMENT>(this,nst_mesh_pt(),temp_mesh_pt()); // Set sources for concentration Multi_domain_functions::setup_multi_domain_interactions <NST_ELEMENT,AD_ELEMENT>(this,nst_mesh_pt(),conc_mesh_pt(),1,0); } //end_of_actions_after_adapt /// Fix pressure in element e at pressure dof pdof and set to pvalue void fix_pressure(const unsigned &e, const unsigned &pdof, const double &pvalue) { //Cast to specific element and fix pressure in NST element if (nst_mesh_pt()->nelement()>0) { dynamic_cast<NST_ELEMENT*>(nst_mesh_pt()->element_pt(e))-> fix_pressure(pdof,pvalue); } } // end_of_fix_pressure /// Doc the solution. void doc_solution(); private: /// DocInfo object DocInfo Doc_info; protected: RefineableRectangularQuadMesh<NST_ELEMENT>* Nst_mesh_pt; RefineableRectangularQuadMesh<AD_ELEMENT>* Temp_mesh_pt; RefineableRectangularQuadMesh<AD_ELEMENT>* Conc_mesh_pt; }; // end of problem class //=======start_of_constructor============================================= /// Constructor for adaptive thermal convection problem //======================================================================== template<class NST_ELEMENT,class AD_ELEMENT> RefineableDDConvectionProblem<NST_ELEMENT,AD_ELEMENT>:: RefineableDDConvectionProblem() { //Allocate a timestepper add_time_stepper_pt(new BDF<2>); // Set output directory Doc_info.set_directory("RESLT_ref_multimesh"); // # of elements in x-direction unsigned n_x=9; // # of elements in y-direction unsigned n_y=8; // Domain length in x-direction double l_x=Global_Physical_Variables::Lambda; // Domain length in y-direction double l_y=1.0; // Build the meshes Nst_mesh_pt = new RefineableRectangularQuadMesh<NST_ELEMENT>(n_x,n_y,l_x,l_y, time_stepper_pt()); Temp_mesh_pt = new RefineableRectangularQuadMesh<AD_ELEMENT>(n_x,n_y,l_x,l_y, time_stepper_pt()); Conc_mesh_pt = new RefineableRectangularQuadMesh<AD_ELEMENT>(n_x,n_y,l_x,l_y, time_stepper_pt()); // Create/set error estimator Nst_mesh_pt->spatial_error_estimator_pt()=new Z2ErrorEstimator; Temp_mesh_pt->spatial_error_estimator_pt()=new Z2ErrorEstimator; Conc_mesh_pt->spatial_error_estimator_pt()=new Z2ErrorEstimator; // Set error targets for adaptive refinement Nst_mesh_pt->max_permitted_error()=0.5e-3; Nst_mesh_pt->min_permitted_error()=0.5e-4; Temp_mesh_pt->max_permitted_error()=0.5e-3; Temp_mesh_pt->min_permitted_error()=0.5e-4; Conc_mesh_pt->max_permitted_error()=0.5e-3; Conc_mesh_pt->min_permitted_error()=0.5e-4; // Set the boundary conditions for this problem: All nodes are // free by default -- only need to pin the ones that have Dirichlet // conditions here //Loop over the boundaries unsigned num_bound = nst_mesh_pt()->nboundary(); for(unsigned ibound=0;ibound<num_bound;ibound++) { //Loop over the number of nodes on the boundry unsigned num_nod= nst_mesh_pt()->nboundary_node(ibound); for (unsigned inod=0;inod<num_nod;inod++) { //If we are on the side-walls, the v-velocity //satisfies natural boundary conditions, so we only pin the //first value if ((ibound==1) || (ibound==3)) { nst_mesh_pt()->boundary_node_pt(ibound,inod)->pin(0); } else // On the top and bottom walls, we have "stress-free" conditions //which actually corresponds to transverse stress free and normal //zero velocity (symmetry) //Thus we pin the second value { nst_mesh_pt()->boundary_node_pt(ibound,inod)->pin(1); } } } //Pin the zero-th pressure dof in element 0 and set its value to //zero: fix_pressure(0,0,0.0); //Loop over the boundaries of the AD mesh num_bound = temp_mesh_pt()->nboundary(); for(unsigned ibound=0;ibound<num_bound;ibound++) { //Loop over the number of nodes on the boundry unsigned num_nod= temp_mesh_pt()->nboundary_node(ibound); for (unsigned inod=0;inod<num_nod;inod++) { //If we are on the side-walls, the temperature //satisfies natural boundary conditions, so we don't pin anything // in this mesh if ((ibound==1) || (ibound==3)) { } //Otherwise pin the temperature else // pin all values { temp_mesh_pt()->boundary_node_pt(ibound,inod)->pin(0); } } } //Loop over the boundaries of the AD mesh num_bound = conc_mesh_pt()->nboundary(); for(unsigned ibound=0;ibound<num_bound;ibound++) { //Loop over the number of nodes on the boundry unsigned num_nod= conc_mesh_pt()->nboundary_node(ibound); for (unsigned inod=0;inod<num_nod;inod++) { //If we are on the side-walls, the concentration //satisfies natural boundary conditions, so we don't pin anything // in this mesh if ((ibound==1) || (ibound==3)) { } //Otherwiwse pin the concentration else // pin all values { conc_mesh_pt()->boundary_node_pt(ibound,inod)->pin(0); } } } // Complete the build of all elements so they are fully functional // Loop over the elements to set up element-specific // things that cannot be handled by the (argument-free!) ELEMENT // constructor. unsigned n_nst_element = nst_mesh_pt()->nelement(); for(unsigned i=0;i<n_nst_element;i++) { // Upcast from GeneralsedElement to the present element NST_ELEMENT *el_pt = dynamic_cast<NST_ELEMENT*> (nst_mesh_pt()->element_pt(i)); // Set the Reynolds number (1/Pr in our non-dimensionalisation) el_pt->re_pt() = &Global_Physical_Variables::Inverse_Prandtl; // Set ReSt (also 1/Pr in our non-dimensionalisation) el_pt->re_st_pt() = &Global_Physical_Variables::Inverse_Prandtl; // Set the Rayleigh number el_pt->ra_t_pt() = &Global_Physical_Variables::Rayleigh_T; // Set the Solutal Rayleigh number el_pt->ra_s_pt() = &Global_Physical_Variables::Rayleigh_S; //Set Gravity vector el_pt->g_pt() = &Global_Physical_Variables::Direction_of_gravity; } unsigned n_temp_element = temp_mesh_pt()->nelement(); for(unsigned i=0;i<n_temp_element;i++) { // Upcast from GeneralsedElement to the present element AD_ELEMENT *el_pt = dynamic_cast<AD_ELEMENT*> (temp_mesh_pt()->element_pt(i)); // Set the Peclet number el_pt->pe_pt() = &Global_Physical_Variables::Peclet; // Set the timescale to be the same as the Navier--Stokes // equations (1.0) el_pt->pe_st_pt() =&Global_Physical_Variables::Peclet; //The mesh is fixed, so we can disable ALE el_pt->disable_ALE(); } unsigned n_conc_element = conc_mesh_pt()->nelement(); for(unsigned i=0;i<n_conc_element;i++) { // Upcast from GeneralsedElement to the present element AD_ELEMENT *el_pt = dynamic_cast<AD_ELEMENT*> (conc_mesh_pt()->element_pt(i)); // Set the Peclet number el_pt->pe_pt() = &Global_Physical_Variables::Lewis; // Set the Peclet number multiplied by the Strouhal number el_pt->pe_st_pt() =&Global_Physical_Variables::Lewis; //The mesh is fixed, so we can disable ALE el_pt->disable_ALE(); } // combine the submeshes add_sub_mesh(Nst_mesh_pt); add_sub_mesh(Temp_mesh_pt); add_sub_mesh(Conc_mesh_pt); build_global_mesh(); // Setup the interaction actions_after_adapt(); // Setup equation numbering scheme cout << "Number of equations: " << assign_eqn_numbers() << endl; // Set this to higher than default (10) Problem::Max_newton_iterations=20; } // end of constructor //===========start_of_set_boundary_conditions================ /// Set the boundary conditions as a function of continuous /// time //=========================================================== template<class NST_ELEMENT,class AD_ELEMENT> void RefineableDDConvectionProblem<NST_ELEMENT,AD_ELEMENT>:: set_boundary_conditions(const double &time) { // Loop over all the boundaries on the NST mesh unsigned num_bound=nst_mesh_pt()->nboundary(); for(unsigned ibound=0;ibound<num_bound;ibound++) { // Loop over the nodes on boundary unsigned num_nod=nst_mesh_pt()->nboundary_node(ibound); for(unsigned inod=0;inod<num_nod;inod++) { // Get pointer to node Node* nod_pt=nst_mesh_pt()->boundary_node_pt(ibound,inod); //If we are on the side walls we only set the x-velocity. if((ibound==1) || (ibound==3)) {nod_pt->set_value(0,0.0);} //If we are on the top and bottom walls we only set the y-velocity else {nod_pt->set_value(1,0.0);} } } // Loop over all the boundaries on the AD mesh num_bound=temp_mesh_pt()->nboundary(); for(unsigned ibound=0;ibound<num_bound;ibound++) { // Loop over the nodes on boundary unsigned num_nod=temp_mesh_pt()->nboundary_node(ibound); for(unsigned inod=0;inod<num_nod;inod++) { // Get pointer to node Node* nod_pt=temp_mesh_pt()->boundary_node_pt(ibound,inod); //If we are on the top boundary, set the temperature //to -0.5 (cooled) if(ibound==2) {nod_pt->set_value(0,-0.5);} //If we are on the bottom boundary, set the temperature //to 0.5 (heated) if(ibound==0) {nod_pt->set_value(0,0.5);} } } // Loop over all the boundaries on the AD mesh num_bound=conc_mesh_pt()->nboundary(); for(unsigned ibound=0;ibound<num_bound;ibound++) { // Loop over the nodes on boundary unsigned num_nod=conc_mesh_pt()->nboundary_node(ibound); for(unsigned inod=0;inod<num_nod;inod++) { // Get pointer to node Node* nod_pt=conc_mesh_pt()->boundary_node_pt(ibound,inod); //If we are on the top boundary, set the concentration to be low //to -0.5 (cooled) if(ibound==2) { nod_pt->set_value(0,-0.5); //Add small concentration imperfection if desired double epsilon = 0.01; //Read out the x position double x = nod_pt->x(0); //Set a sinusoidal perturbation in the concentration double value = sin(2.0*MathematicalConstants::Pi*x/1.5)* epsilon*time*exp(-10.0*time); nod_pt->set_value(0, -0.5 + value); } //If we are on the bottom boundary, set the concentration to be high //to 0.5 (heated) if(ibound==0) {nod_pt->set_value(0,0.5);} } } } // end_of_set_boundary_conditions //====================start_of_doc_solution=============================== /// Doc the solution //======================================================================== template<class NST_ELEMENT,class AD_ELEMENT> void RefineableDDConvectionProblem<NST_ELEMENT,AD_ELEMENT>::doc_solution() { //Declare an output stream and filename ofstream some_file; char filename[100]; // Number of plot points: npts x npts unsigned npts=5; // Output whole solution (this will output elements from one mesh //---------------------- followed by the other mesh at the moment...?) /*sprintf(filename,"%s/soln%i.dat",Doc_info.directory().c_str(), Doc_info.number()); some_file.open(filename); mesh_pt()->output(some_file,npts); some_file.close();*/ sprintf(filename,"%s/nst_soln%i.dat",Doc_info.directory().c_str(), Doc_info.number()); some_file.open(filename); nst_mesh_pt()->output(some_file,npts); some_file.close(); sprintf(filename,"%s/temp_soln%i.dat",Doc_info.directory().c_str(), Doc_info.number()); some_file.open(filename); temp_mesh_pt()->output(some_file,npts); some_file.close(); sprintf(filename,"%s/conc_soln%i.dat",Doc_info.directory().c_str(), Doc_info.number()); some_file.open(filename); conc_mesh_pt()->output(some_file,npts); some_file.close(); Doc_info.number()++; } // end of doc //===============start_of_main======================================== /// Driver code for 2D Boussinesq convection problem with /// adaptivity. //==================================================================== int main(int argc, char **argv) { // Set the direction of gravity Global_Physical_Variables::Direction_of_gravity[0] = 0.0; Global_Physical_Variables::Direction_of_gravity[1] = -1.0; // Create the problem with 2D nine-node refineable elements. RefineableDDConvectionProblem< RefineableQCrouzeixRaviartElementWithTwoExternalElement<2>, RefineableQAdvectionDiffusionElementWithExternalElement<2> > problem; // Apply the boundary condition at time zero problem.set_boundary_conditions(0.0); //Perform a single steady Newton solve problem.steady_newton_solve(); //Document the solution problem.doc_solution(); //Start a trace file ofstream trace("RESLT_ref_multimesh/trace.dat"); //Local variables for the kinetic energy and its rate of change double E=0.0, Edot = 0.0; //Output to the trace file problem.get_kinetic_energy(E,Edot); trace << problem.time_pt()->time() << " " << problem.nst_mesh_pt()->boundary_node_pt(1,8)->value(1) << " " << E << " " << Edot << std::endl; //Set the timestep double dt = 0.01; //Initialise the value of the timestep and set an impulsive start problem.assign_initial_values_impulsive(dt); //Set the number of timesteps to our default value unsigned n_steps = 2000; //If we have a command line argument, perform fewer steps //(used for self-test runs) if(argc > 1) {n_steps = 5;} bool first=true; unsigned n_refine = 0; //Perform n_steps timesteps for(unsigned i=0;i<n_steps;++i) { problem.unsteady_newton_solve(dt,n_refine,first); problem.doc_solution(); first = false; //Refine the last case for the demo if((argc > 1) && (i==3)) {n_refine=1;} //Only start to refine after 700 steps once the //limit cycle has essentially settled down if(i > 700) {n_refine=1;} //Output to the trace file problem.get_kinetic_energy(E,Edot); trace << problem.time_pt()->time() << " " << problem.nst_mesh_pt()->boundary_node_pt(1,8)->value(1) << " " << E << " " << Edot << std::endl; } trace.close(); } // end of main
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2018-2019 The BeetleCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/beetlecoin-config.h" #endif #include "addressbookpage.h" #include "ui_addressbookpage.h" #include "addresstablemodel.h" #include "bitcoingui.h" #include "csvmodelwriter.h" #include "editaddressdialog.h" #include "guiutil.h" #include <QIcon> #include <QMenu> #include <QMessageBox> #include <QSortFilterProxyModel> AddressBookPage::AddressBookPage(Mode mode, Tabs tab, QWidget* parent) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint), ui(new Ui::AddressBookPage), model(0), mode(mode), tab(tab) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->newAddress->setIcon(QIcon()); ui->copyAddress->setIcon(QIcon()); ui->deleteAddress->setIcon(QIcon()); ui->exportButton->setIcon(QIcon()); #endif switch (mode) { case ForSelection: switch (tab) { case SendingTab: setWindowTitle(tr("Choose the address to send coins to")); break; case ReceivingTab: setWindowTitle(tr("Choose the address to receive coins with")); break; } connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setFocus(); ui->closeButton->setText(tr("C&hoose")); ui->exportButton->hide(); break; case ForEditing: switch (tab) { case SendingTab: setWindowTitle(tr("Sending addresses")); break; case ReceivingTab: setWindowTitle(tr("Receiving addresses")); break; } break; } switch (tab) { case SendingTab: ui->labelExplanation->setText(tr("These are your BeetleCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.")); ui->deleteAddress->setVisible(true); break; case ReceivingTab: ui->labelExplanation->setText(tr("These are your BeetleCoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.")); ui->deleteAddress->setVisible(false); break; } // Context menu actions QAction* copyAddressAction = new QAction(tr("&Copy Address"), this); QAction* copyLabelAction = new QAction(tr("Copy &Label"), this); QAction* editAction = new QAction(tr("&Edit"), this); deleteAction = new QAction(ui->deleteAddress->text(), this); // Build context menu contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(editAction); if (tab == SendingTab) contextMenu->addAction(deleteAction); contextMenu->addSeparator(); // Connect signals for context menu actions connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction())); connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(accept())); } AddressBookPage::~AddressBookPage() { delete ui; } void AddressBookPage::setModel(AddressTableModel* model) { this->model = model; if (!model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); switch (tab) { case ReceivingTab: // Receive filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Receive); break; case SendingTab: // Send filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Send); break; } ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); // Set column widths #if QT_VERSION < 0x050000 ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #else ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #endif connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created address connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(selectNewAddress(QModelIndex, int, int))); selectionChanged(); } void AddressBookPage::on_copyAddress_clicked() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address); } void AddressBookPage::onCopyLabelAction() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label); } void AddressBookPage::onEditAction() { if (!model) return; if (!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if (indexes.isEmpty()) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::EditSendingAddress : EditAddressDialog::EditReceivingAddress, this); dlg.setModel(model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void AddressBookPage::on_newAddress_clicked() { if (!model) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::NewSendingAddress : EditAddressDialog::NewReceivingAddress, this); dlg.setModel(model); if (dlg.exec()) { newAddressToSelect = dlg.getAddress(); } } void AddressBookPage::on_deleteAddress_clicked() { QTableView* table = ui->tableView; if (!table->selectionModel()) return; QModelIndexList indexes = table->selectionModel()->selectedRows(); if (!indexes.isEmpty()) { table->model()->removeRow(indexes.at(0).row()); } } void AddressBookPage::selectionChanged() { // Set button states based on selected tab and selection QTableView* table = ui->tableView; if (!table->selectionModel()) return; if (table->selectionModel()->hasSelection()) { switch (tab) { case SendingTab: // In sending tab, allow deletion of selection ui->deleteAddress->setEnabled(true); ui->deleteAddress->setVisible(true); deleteAction->setEnabled(true); break; case ReceivingTab: // Deleting receiving addresses, however, is not allowed ui->deleteAddress->setEnabled(false); ui->deleteAddress->setVisible(false); deleteAction->setEnabled(false); break; } ui->copyAddress->setEnabled(true); } else { ui->deleteAddress->setEnabled(false); ui->copyAddress->setEnabled(false); } } void AddressBookPage::done(int retval) { QTableView* table = ui->tableView; if (!table->selectionModel() || !table->model()) return; // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } if (returnValue.isEmpty()) { // If no address entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void AddressBookPage::on_exportButton_clicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName(this, tr("Export Address List"), QString(), tr("Comma separated file (*.csv)"), NULL); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole); writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole); if (!writer.write()) { QMessageBox::critical(this, tr("Exporting Failed"), tr("There was an error trying to save the address list to %1. Please try again.").arg(filename)); } } void AddressBookPage::contextualMenu(const QPoint& point) { QModelIndex index = ui->tableView->indexAt(point); if (index.isValid()) { contextMenu->exec(QCursor::pos()); } } void AddressBookPage::selectNewAddress(const QModelIndex& parent, int begin, int /*end*/) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent)); if (idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) { // Select row of newly created address, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAddressToSelect.clear(); } }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Copyright 2018, Intel Corporation // // Modified to test pmem::obj containers // #include "unittest.hpp" #include <libpmemobj++/experimental/array.hpp> namespace pmem_exp = pmem::obj::experimental; template <int Dummy> struct NoCompare { }; int main() { START(); int result = 0; { typedef NoCompare<2> T; typedef pmem_exp::array<T, 0> C; C c1 = {{}}; // expected-error@algorithm:* 2 {{invalid operands to binary // expression}} result = (c1 == c1); result = (c1 < c1); } return result; }
#include <thread> #include <iostream> using namespace std; int X[] = {55,66,77,88,99}; void foo(int x) { cout << "hello" << x << X[1] <<"\n"; } int main() { thread t1(foo,42); thread t2(foo,22); thread t3(foo,12); t3.join(); t2.join(); t1.join(); }
////////////////////////////////////////////////////////////////////////////// /// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand /// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI /// /// Distributed under the Boost Software License, Version 1.0 /// See accompanying file LICENSE.txt or copy at /// http://www.boost.org/LICENSE_1_0.txt ////////////////////////////////////////////////////////////////////////////// #define NT2_UNIT_MODULE "nt2 cephes toolbox - atan/scalar Mode" ////////////////////////////////////////////////////////////////////////////// // Test behavior of cephes components in scalar mode ////////////////////////////////////////////////////////////////////////////// /// created by jt the 01/03/2011 /// modified by jt the 23/03/2011 #include <boost/type_traits/is_same.hpp> #include <nt2/sdk/functor/meta/call.hpp> #include <nt2/sdk/unit/tests.hpp> #include <nt2/sdk/unit/module.hpp> #include <nt2/sdk/memory/buffer.hpp> #include <nt2/sdk/constant/real.hpp> #include <nt2/sdk/constant/infinites.hpp> #include <nt2/include/functions/max.hpp> #include <nt2/toolbox/cephes/include/atan.hpp> // specific includes for arity 1 tests #include <nt2/include/functions/atan.hpp> NT2_TEST_CASE_TPL ( atan_real__1_0, NT2_REAL_TYPES) { using nt2::cephes::atan; using nt2::cephes::tag::atan_; typedef typename nt2::meta::as_integer<T>::type iT; typedef typename nt2::meta::call<atan_(T)>::type r_t; typedef typename nt2::meta::upgrade<T>::type u_t; typedef T wished_r_t; // return type conformity test NT2_TEST( (boost::is_same < r_t, wished_r_t >::value) ); std::cout << std::endl; double ulpd; ulpd=0.0; // random verifications static const uint32_t NR = NT2_NB_RANDOM_TEST; { NT2_CREATE_BUF(tab_a0,T, NR, T(-100), T(100)); double ulp0, ulpd ; ulpd=ulp0=0.0; T a0; for (uint32_t j =0; j < NR; ++j ) { std::cout << "for param " << " a0 = "<< u_t(a0 = tab_a0[j]) << std::endl; NT2_TEST_ULP_EQUAL( nt2::cephes::atan(a0),nt2::atan(a0),0.5); ulp0=nt2::max(ulpd,ulp0); } std::cout << "max ulp found is: " << ulp0 << std::endl; } } // end of test for real_