text
stringlengths
5
1.04M
/* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 otbNumberOfLinesStrippedStreamingManager_hxx #define otbNumberOfLinesStrippedStreamingManager_hxx #include "otbNumberOfLinesStrippedStreamingManager.h" #include "otbMacro.h" namespace otb { template <class TImage> NumberOfLinesStrippedStreamingManager<TImage>::NumberOfLinesStrippedStreamingManager() : m_NumberOfLinesPerStrip(0) { } template <class TImage> NumberOfLinesStrippedStreamingManager<TImage>::~NumberOfLinesStrippedStreamingManager() { } template <class TImage> void NumberOfLinesStrippedStreamingManager<TImage>::PrepareStreaming(itk::DataObject* /*input*/, const RegionType& region) { otbMsgDevMacro(<< "Activating STRIPPED_SET_NUMBEROFLINES streaming mode") if (m_NumberOfLinesPerStrip < 1) { itkWarningMacro(<< "DesiredNumberOfLines set to 0 : streaming disabled") } // Calculate number of splits unsigned long numberLinesOfRegion = region.GetSize()[1]; // Y dimension unsigned long nbSplit; if (numberLinesOfRegion > m_NumberOfLinesPerStrip && m_NumberOfLinesPerStrip > 0) { nbSplit = static_cast<unsigned long>(std::ceil(static_cast<double>(numberLinesOfRegion) / static_cast<double>(m_NumberOfLinesPerStrip))); } else { // Don't stream nbSplit = 1; } this->m_Splitter = itk::ImageRegionSplitter<itkGetStaticConstMacro(ImageDimension)>::New(); this->m_ComputedNumberOfSplits = this->m_Splitter->GetNumberOfSplits(region, nbSplit); otbMsgDevMacro(<< "Computed number of split : " << this->m_ComputedNumberOfSplits) // Save the region to generate the splits later this->m_Region = region; } } // End namespace otb #endif
#include <bits/stdc++.h> using namespace std; void solve(){ int n; cin >> n; for(int i=1;i<=n;i++){ int x, y, temp, left; cin >> x >> y; int total = 0; for(int j=0;j<x;j++){ cin >> temp; total += temp; } left = total % y; cout << "Case #" << i << ": " << left << endl; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); return 0; }
#include <bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define dd double #define ld long double #define sl(n) scanf("%lld", &n) #define si(n) scanf("%d", &n) #define sd(n) scanf("%lf", &n) #define pll pair <ll, ll> #define pii pair <int, int> #define mp make_pair #define pb push_back #define inf (1LL << 62) #define loop(i, start, stop, inc) for(ll i = start; i <= stop; i += inc) #define for1(i, stop) for(ll i = 1; i <= stop; i++) #define for0(i, stop) for(ll i = 0; i < stop; i++) #define rep1(i, start) for(ll i = start; i >= 1; i--) #define rep0(i, start) for(ll i = (start-1); i >= 0; i--) #define ms(n, i) memset(n, i, sizeof(n)) #define casep(n) printf("Case %lld:", ++n) #define pn printf("\n") #define pf printf #define fastio std::ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); ll ara[100009]; struct trie { trie *nxt[2]; trie() { nxt[0] = nxt[1] = nullptr; } }; trie *start; void add(ll num) { trie *cur = start; for(ll i = 32; i >= 0; i--) { bool bit = (num >> i) & 1; if(cur -> nxt[bit] == nullptr) cur->nxt[bit] = new trie(); cur = cur->nxt[bit]; } } ll solve(ll bit, trie *cur) { if(bit < 0) return 0; if(cur->nxt[0] != nullptr && cur->nxt[1] != nullptr) return (1LL << bit) + min(solve(bit-1, cur->nxt[0]), solve(bit-1, cur->nxt[1])); if(cur->nxt[0] != nullptr) return solve(bit-1, cur->nxt[0]); else if(cur->nxt[1] != nullptr) return solve(bit-1, cur->nxt[1]); } int main() { start = new trie(); ll n; sl(n); for1(i, n) { sl(ara[i]); add(ara[i]); } ll ans = solve(32, start); cout << ans << endl; return 0; }
//------------------------------------------------------------------------- /* Copyright (C) 2010-2019 EDuke32 developers and contributors Copyright (C) 2019 sirlemonhead, Nuke.YKT This file is part of PCExhumed. PCExhumed 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //------------------------------------------------------------------------- #include "ns.h" #include "engine.h" #include "exhumed.h" BEGIN_PS_NS int randA = 0; int randB = 0x11111111; int randC = 0x1010101; void SerializeRand(FSerializer& arc) { if (arc.BeginObject("rand")) { arc("a", randA) ("b", randB) ("c", randC) .EndObject(); } } void InitRandom() { randA = 0; randB = 0x11111111; randC = 0x1010101; } // TODO - checkme int RandomBit() { randA = (randA >> 1) | (((randA ^ ((randA >> 1) ^ (randA >> 2) ^ (randA >> 31) ^ (randA >> 6) ^ (randA >> 4))) & 1) << 31); randB = (randB >> 1) | ((((randB >> 2) ^ (randB >> 30)) & 1) << 30); randC = (randC >> 1) | ((((randC >> 1) ^ (randC >> 28)) & 1) << 28); return (((randA == 0) & randC) | (randB & randA)) & 1; } char RandomByte() { char randByte = RandomBit() << 7; randByte |= RandomBit() << 6; randByte |= RandomBit() << 5; randByte |= RandomBit() << 4; randByte |= RandomBit() << 3; randByte |= RandomBit() << 2; randByte |= RandomBit() << 1; randByte |= RandomBit(); return randByte; } uint16_t RandomWord() { short randWord = RandomByte() << 8; randWord |= RandomByte(); return randWord; } int RandomLong() { int randLong = IntToFixed(RandomWord()); randLong |= RandomWord(); return randLong; } int RandomSize(int nSize) { int randSize = 0; while (nSize > 0) { randSize = randSize * 2 | RandomBit(); nSize--; } return randSize; } END_PS_NS
//================================================================================================== /** EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #include <eve/function/div.hpp> #include <eve/concept/value.hpp> #include <eve/constant/oneotwoeps.hpp> #include <eve/constant/valmin.hpp> #include <eve/constant/valmax.hpp> #include <cmath> int main() { auto lmin = eve::valmin(eve::as<EVE_VALUE>()); auto lmax = [](){ if constexpr(eve::floating_value<EVE_VALUE>) return eve::oneotwoeps(eve::as<EVE_VALUE>()); else return eve::valmax(eve::as<EVE_VALUE>()); }(); auto arg0 = eve::bench::random_<EVE_VALUE>(lmin,lmax); auto arg1 = eve::bench::random_<EVE_VALUE>(EVE_VALUE(1),lmax); auto std__div = [](EVE_VALUE x, EVE_VALUE y){return EVE_VALUE(x+y); }; eve::bench::experiment xp; run<EVE_VALUE>(EVE_NAME(std__div) , xp, std__div, arg0, arg1); run<EVE_VALUE>(EVE_NAME(div) , xp, eve::div, arg0, arg1); run<EVE_TYPE> (EVE_NAME(div) , xp, eve::div, arg0, arg1); }
#ifndef CORE_HPP_ #define CORE_HPP_ #include "mem.hpp" #include <cmath> #include <cstring> #include <iostream> #include <memory> #include <sstream> #include <vector> namespace HiGIS::Core { /** * \brief Mix multiple structs by multi-inherit * * Mix provides a way to combine data of several structs without the need of verbose redirections. * Mix<A, B, C> will inherit A, B, C and thus have all members of A, B, C. * * Polymorphism is somehow permitted. Rules to pass Mix as arguments: * * 1. Allow `Mix<A, B, C> -> Mix<A, B>` * 2. Allow `Mix<A, B, C> -> &A or Mix<A, B, C> -> A` * 3. Do not allow `Mix<A, B, C> -> Mix<A, B>&`, use `Mix<A, B>(A&, B&)` to reconstruct */ template <typename... Is> struct Mix : public virtual Is... { public: Mix() : Is()... {} /** * \brief Allow construct from Mix with more Mixed structs, like from Mix<A, B, C> to Mix<A, B>. * * This enables implicit conversion when passing arguments (Polymorphism rule 1) */ template <typename T> Mix(T &t) : Is(t)... {} /** * \brief Allow construct from Mixed components, like from A, B, C to Mix<A, B, C>. * * This enables flexible reconstruction of Mix (Polymorphism rule 3) */ Mix(Is &... ts) : Is(ts)... {} }; /** * \brief Terminator at the end of each feature * \ingroup core */ const uint64_t TERMINATOR = ~0LL; enum GeoType { Unknown = -1, /** Also store simple polygon as a one-part multipolygon */ MultiPolygon = 6, /** Also store simple linestring as a one-part multilinestring */ MultiLineString = 5, MultiPoint = 4, Point = 1 }; using GeoBuffer = MemPool<uint64_t>; struct Extent { double xmin = INFINITY; double ymin = INFINITY; double xmax = -INFINITY; double ymax = -INFINITY; double *Values() { return reinterpret_cast<double *>(this); } }; // Stats struct FeatureExtents { MemPool<Extent> extents; }; using GeoStats = Mix<FeatureExtents>; struct GeoSummary { uint64_t feature_count; GeoType feature_type; struct Extent extent; std::string srs; // GeoSummary() : feature_count(0), feature_type(GeoType::Unknown) {} }; struct Index { MemPool<uint64_t> id_index; }; template <typename TIndex> using GeoDataT = Mix<GeoBuffer, GeoSummary, GeoStats, TIndex>; using GeoData = Mix<GeoBuffer, GeoSummary, GeoStats>; } // namespace HiGIS::Core #endif // CORE_HPP_ /** * \defgroup core Core * \brief Basic structures for HiGIS Core * * Generally, a geographical dataset consists of 4 possible parts: * * - Buffer for binary data * - Summary for overall description of the dataset, like feature count, total area, etc. * - Stats for descriptions of each feature, like extents, polygon areas, line lengths, etc. * - Index for spatial index for the dataset (not implemented yet) * * The module use Mix to provide a standard version of dataset named GeoData, consisting with a * standard version of Summary(GeoSummary), Stats(GeoStats) */ /** * \class HiGIS::Core::Mix * \ingroup core * \snippet test_core.cpp MixTest */ /** * \class GeoSummary * \ingroup core * \brief Basic definition for Summary */ /** * \class GeoBuffer * \ingroup core * \brief Buffer to store feature geometries * * The unit is universally 8 bytes instead of keeping variant units like 1, 4, 8 bytes, which is * space-consuming but is much easier to deal with Especially, it makes alignment possible so we can * scan from arbitrary points. Point coordinates as double are simply reinterprated and put into the * buffer, with its memory representation intact. */ /** * \class GeoStats * \ingroup core * \brief Basic definition for Stats */ /** * \class FeatureExtents * \ingroup core * \brief FeatureExtents Mixin for Stats */ /** * \class GeoData * \ingroup core * \brief Useful data definition for most cases */ /** * \enum GeoType * \ingroup core * * The types are basically from Shapefile. Polygon and MultiPolygon, LineString and MultiLineString * are not distinguished. The reason is that restricting polygons to have only one exterior ring is * not very useful. The non-multi versions are simply regarded as special cases. */
// // header.hpp // ~~~~~~~~~~ // // Copyright (c) 2003-2021 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER3_HEADER_HPP #define HTTP_SERVER3_HEADER_HPP #include <string> namespace http { namespace server3 { struct header { std::string name; std::string value; }; } // namespace server3 } // namespace http #endif // HTTP_SERVER3_HEADER_HPP
#include "routing/routing_options.hpp" #include "platform/settings.hpp" #include "indexer/classificator.hpp" #include "base/assert.hpp" #include "base/checked_cast.hpp" #include "base/logging.hpp" #include "base/macros.hpp" #include "base/string_utils.hpp" #include <initializer_list> #include <sstream> #include <utility> using namespace std; namespace routing { // RoutingOptions ------------------------------------------------------------------------------------- string const RoutingOptions::kAvoidRoutingOptionSettingsForCar = "avoid_routing_options_car"; // static RoutingOptions RoutingOptions::LoadCarOptionsFromSettings() { uint32_t mode = 0; if (!settings::Get(kAvoidRoutingOptionSettingsForCar, mode)) mode = 0; return RoutingOptions(base::checked_cast<RoadType>(mode)); } // static void RoutingOptions::SaveCarOptionsToSettings(RoutingOptions options) { settings::Set(kAvoidRoutingOptionSettingsForCar, strings::to_string(static_cast<int32_t>(options.GetOptions()))); } void RoutingOptions::Add(RoutingOptions::Road type) { m_options |= static_cast<RoadType>(type); } void RoutingOptions::Remove(RoutingOptions::Road type) { m_options &= ~static_cast<RoadType>(type); } bool RoutingOptions::Has(RoutingOptions::Road type) const { return (m_options & static_cast<RoadType>(type)) != 0; } // RoutingOptionsClassifier --------------------------------------------------------------------------- RoutingOptionsClassifier::RoutingOptionsClassifier() { Classificator const & c = classif(); initializer_list<pair<vector<string>, RoutingOptions::Road>> const types = { {{"highway", "motorway"}, RoutingOptions::Road::Motorway}, {{"hwtag", "toll"}, RoutingOptions::Road::Toll}, {{"route", "ferry"}, RoutingOptions::Road::Ferry}, {{"route", "ferry", "motorcar"}, RoutingOptions::Road::Ferry}, {{"route", "ferry", "motor_vehicle"}, RoutingOptions::Road::Ferry}, {{"highway", "track"}, RoutingOptions::Road::Dirty}, {{"highway", "road"}, RoutingOptions::Road::Dirty}, {{"psurface", "unpaved_bad"}, RoutingOptions::Road::Dirty}, {{"psurface", "unpaved_good"}, RoutingOptions::Road::Dirty} }; for (auto const & data : types) { auto const & stringType = data.first; auto const & optionType = data.second; ASSERT_EQUAL(m_data.count(c.GetTypeByPath(stringType)), 0, ()); m_data[c.GetTypeByPath(stringType)] = optionType; } } optional<RoutingOptions::Road> RoutingOptionsClassifier::Get(uint32_t type) const { auto const it = m_data.find(type); if (it == m_data.cend()) return {}; return it->second; } RoutingOptionsClassifier const & RoutingOptionsClassifier::Instance() { static RoutingOptionsClassifier instance; return instance; } RoutingOptions::Road ChooseMainRoutingOptionRoad(RoutingOptions options) { if (options.Has(RoutingOptions::Road::Toll)) return RoutingOptions::Road::Toll; if (options.Has(RoutingOptions::Road::Ferry)) return RoutingOptions::Road::Ferry; if (options.Has(RoutingOptions::Road::Dirty)) return RoutingOptions::Road::Dirty; if (options.Has(RoutingOptions::Road::Motorway)) return RoutingOptions::Road::Motorway; return RoutingOptions::Road::Usual; } string DebugPrint(RoutingOptions const & routingOptions) { ostringstream ss; ss << "RoutingOptions: {"; bool wasAppended = false; auto const append = [&](RoutingOptions::Road road) { if (routingOptions.Has(road)) { wasAppended = true; ss << " | " << DebugPrint(road); } }; append(RoutingOptions::Road::Usual); append(RoutingOptions::Road::Toll); append(RoutingOptions::Road::Motorway); append(RoutingOptions::Road::Ferry); append(RoutingOptions::Road::Dirty); if (wasAppended) ss << " | "; ss << "}"; return ss.str(); } string DebugPrint(RoutingOptions::Road type) { switch (type) { case RoutingOptions::Road::Toll: return "toll"; case RoutingOptions::Road::Motorway: return "motorway"; case RoutingOptions::Road::Ferry: return "ferry"; case RoutingOptions::Road::Dirty: return "dirty"; case RoutingOptions::Road::Usual: return "usual"; case RoutingOptions::Road::Max: return "max"; } UNREACHABLE(); } } // namespace routing
 #include "Node.h" // Constructor - Initializes the node Node::Node(char* dat, Node* nxt) { val = dat; next = nxt; } // getVal - Returns the integer value stored in the node char* Node::getVal() { return val; } // getNext - Returns a pointer for the next node in the linked list Node* Node::getNext() { return next; } // setNext - Stores the pointer to the next node in the list in the "next" field void Node::setNext(Node* nxt) { next = nxt; }
/*********************************************************************************************************************** * * * ANTIKERNEL v0.1 * * * * Copyright (c) 2012-2020 Andrew D. Zonenberg * * 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 author nor the names of any contributors may be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS "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 AUTHORS BE HELD 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 "../scopehal/scopehal.h" #include "Waterfall.h" #include "FFTFilter.h" using namespace std; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Construction / destruction WaterfallWaveform::WaterfallWaveform(size_t width, size_t height) : m_width(width) , m_height(height) { size_t npix = width*height; m_outdata = new float[npix]; for(size_t i=0; i<npix; i++) m_outdata[i] = 0; } WaterfallWaveform::~WaterfallWaveform() { delete[] m_outdata; m_outdata = NULL; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Construction / destruction Waterfall::Waterfall(const string& color) : Filter(OscilloscopeChannel::CHANNEL_TYPE_ANALOG, color, CAT_RF) , m_pixelsPerHz(0.001) , m_offsetHz(0) , m_width(1) , m_height(1) { m_xAxisUnit = Unit(Unit::UNIT_HZ); //Set up channels CreateInput("Spectrum"); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Factory methods bool Waterfall::ValidateChannel(size_t i, StreamDescriptor stream) { if(stream.m_channel == NULL) return false; if( (i == 0) && (stream.m_channel->GetType() == OscilloscopeChannel::CHANNEL_TYPE_ANALOG) && (stream.m_channel->GetXAxisUnits() == Unit::UNIT_HZ) ) { return true; } return false; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Accessors double Waterfall::GetOffset() { return 0; } double Waterfall::GetVoltageRange() { return 1; } string Waterfall::GetProtocolName() { return "Waterfall"; } bool Waterfall::IsOverlay() { //we create a new analog channel return false; } bool Waterfall::NeedsConfig() { //we auto-select the midpoint as our threshold return false; } void Waterfall::SetDefaultName() { char hwname[256]; snprintf(hwname, sizeof(hwname), "Waterfall(%s)", GetInputDisplayName(0).c_str()); m_hwname = hwname; m_displayname = m_hwname; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Actual decoder logic void Waterfall::Refresh() { //Make sure we've got valid inputs if(!VerifyAllInputsOKAndAnalog()) { SetData(NULL, 0); return; } //Get the input data auto din = GetAnalogInputWaveform(0); size_t inlen = din->m_samples.size(); //Initialize the capture //TODO: timestamps? do we need those? auto cap = dynamic_cast<WaterfallWaveform*>(GetData(0)); if(cap == NULL) cap = new WaterfallWaveform(m_width, m_height); cap->m_timescale = din->m_timescale; float* data = cap->GetData(); //Move the whole waterfall down by one row for(size_t y=0; y < m_height-1 ; y++) { for(size_t x=0; x<m_width; x++) data[y*m_width + x] = data[(y+1)*m_width + x]; } //Add the new data double hz_per_bin = din->m_timescale; double bins_per_pixel = 1.0f / (m_pixelsPerHz * hz_per_bin); double bin_offset = m_offsetHz / hz_per_bin; double vmin = 1.0 / 255.0; float vrange = m_inputs[0].m_channel->GetVoltageRange(); //db from min to max scale float vfs = vrange/2 - m_inputs[0].m_channel->GetOffset(); for(size_t x=0; x<m_width; x++) { //Look up the frequency bin for this position //For now, just do nearest neighbor interpolation size_t nbin = static_cast<size_t>(round(bins_per_pixel*x + bin_offset)); float value = 0; if(nbin < inlen) { float db = din->m_samples[nbin]; value = 1 - ( (db - vfs) / -vrange ); } //Cap values to prevent going off-scale-low with our color ramps if(value < vmin) value = vmin; data[(m_height-1)*m_width + x] = value; } SetData(cap, 0); }
/* Copyright (c) 2011, The Cinder Project: http://libcinder.org All rights reserved. This code is intended for use with the Cinder C++ library: http://libcinder.org 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. 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 HOLDER 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 "cinder/gl/TextureFont.h" #include "cinder/gl/Context.h" #include "cinder/gl/Vao.h" #include "cinder/gl/Vbo.h" #include "cinder/gl/scoped.h" #include "cinder/Text.h" #include "cinder/ip/Fill.h" #include "cinder/ip/Premultiply.h" #include "cinder/ImageIo.h" #include "cinder/Rand.h" #include "cinder/Utilities.h" #if defined( CINDER_COCOA ) #include "cinder/cocoa/CinderCocoa.h" #if defined( CINDER_MAC ) #include <ApplicationServices/ApplicationServices.h> #else #include <CoreGraphics/CoreGraphics.h> #endif #elif defined( CINDER_MSW ) #include <Windows.h> #undef min #undef max #elif defined( CINDER_ANDROID ) || defined( CINDER_LINUX ) #include "cinder/linux/FreeTypeUtil.h" #endif #include "cinder/Unicode.h" #include <set> using std::unordered_map; using namespace std; namespace cinder { namespace gl { #if defined( CINDER_COCOA ) TextureFont::TextureFont( const Font &font, const string &supportedChars, const TextureFont::Format &format ) : mFont( font ), mFormat( format ) { // get the glyph indices we'll need vector<Font::Glyph> tempGlyphs = font.getGlyphs( supportedChars ); set<Font::Glyph> glyphs( tempGlyphs.begin(), tempGlyphs.end() ); // determine the max glyph extents vec2 glyphExtents; for( set<Font::Glyph>::const_iterator glyphIt = glyphs.begin(); glyphIt != glyphs.end(); ++glyphIt ) { Rectf bb = font.getGlyphBoundingBox( *glyphIt ); glyphExtents.x = std::max( glyphExtents.x, bb.getWidth() ); glyphExtents.y = std::max( glyphExtents.y, bb.getHeight() ); } glyphExtents.x = ceil( glyphExtents.x ); glyphExtents.y = ceil( glyphExtents.y ); int glyphsWide = floor( mFormat.getTextureWidth() / (glyphExtents.x+3) ); int glyphsTall = floor( mFormat.getTextureHeight() / (glyphExtents.y+5) ); uint8_t curGlyphIndex = 0, curTextureIndex = 0; vec2 curOffset; CGGlyph renderGlyphs[glyphsWide*glyphsTall]; CGPoint renderPositions[glyphsWide*glyphsTall]; Surface surface( mFormat.getTextureWidth(), mFormat.getTextureHeight(), true ); ip::fill( &surface, ColorA8u( 0, 0, 0, 0 ) ); ColorA white( 1, 1, 1, 1 ); ::CGContextRef cgContext = cocoa::createCgBitmapContext( surface ); ::CGContextSetRGBFillColor( cgContext, 1, 1, 1, 1 ); ::CGContextSetFont( cgContext, font.getCgFontRef() ); ::CGContextSetFontSize( cgContext, font.getSize() ); ::CGContextSetTextMatrix( cgContext, CGAffineTransformIdentity ); std::unique_ptr<uint8_t[]> lumAlphaData( new uint8_t[mFormat.getTextureWidth()*mFormat.getTextureHeight()*2] ); for( set<Font::Glyph>::const_iterator glyphIt = glyphs.begin(); glyphIt != glyphs.end(); ) { GlyphInfo newInfo; newInfo.mTextureIndex = curTextureIndex; Rectf bb = font.getGlyphBoundingBox( *glyphIt ); vec2 ul = curOffset + vec2( 0, glyphExtents.y - bb.getHeight() ); vec2 lr = curOffset + vec2( glyphExtents.x, glyphExtents.y ); newInfo.mTexCoords = Area( floor( ul.x ), floor( ul.y ), ceil( lr.x ) + 3, ceil( lr.y ) + 2 ); newInfo.mOriginOffset.x = floor(bb.x1) - 1; newInfo.mOriginOffset.y = -(bb.getHeight()-1)-ceil( bb.y1+0.5f ); mGlyphMap[*glyphIt] = newInfo; renderGlyphs[curGlyphIndex] = *glyphIt; renderPositions[curGlyphIndex].x = curOffset.x - floor(bb.x1) + 1; renderPositions[curGlyphIndex].y = surface.getHeight() - (curOffset.y + glyphExtents.y) - ceil(bb.y1+0.5f); curOffset += ivec2( glyphExtents.x + 3, 0 ); ++glyphIt; if( ( ++curGlyphIndex == glyphsWide * glyphsTall ) || ( glyphIt == glyphs.end() ) ) { ::CGContextShowGlyphsAtPositions( cgContext, renderGlyphs, renderPositions, curGlyphIndex ); // pass premultiply and mipmapping preferences to Texture::Format if( ! mFormat.getPremultiply() ) ip::unpremultiply( &surface ); gl::Texture::Format textureFormat = gl::Texture::Format(); textureFormat.enableMipmapping( mFormat.hasMipmapping() ); GLint dataFormat; #if defined( CINDER_GL_ES ) dataFormat = GL_LUMINANCE_ALPHA; textureFormat.setInternalFormat( dataFormat ); #else dataFormat = GL_RG; textureFormat.setInternalFormat( dataFormat ); textureFormat.setSwizzleMask( { GL_RED, GL_RED, GL_RED, GL_GREEN } ); #endif if( mFormat.hasMipmapping() ) textureFormat.setMinFilter( GL_LINEAR_MIPMAP_LINEAR ); // under iOS format and interalFormat must match, so let's make a block of LUMINANCE_ALPHA data Surface8u::ConstIter iter( surface, surface.getBounds() ); size_t offset = 0; while( iter.line() ) { while( iter.pixel() ) { lumAlphaData.get()[offset+0] = iter.r(); lumAlphaData.get()[offset+1] = iter.a(); offset += 2; } } mTextures.push_back( gl::Texture::create( lumAlphaData.get(), dataFormat, mFormat.getTextureWidth(), mFormat.getTextureHeight(), textureFormat ) ); mTextures.back()->setTopDown( true ); ip::fill( &surface, ColorA8u( 0, 0, 0, 0 ) ); curOffset = vec2(); curGlyphIndex = 0; ++curTextureIndex; } else if( ( curGlyphIndex ) % glyphsWide == 0 ) { // wrap around curOffset.x = 0; curOffset.y += glyphExtents.y + 2; } } ::CGContextRelease( cgContext ); } #elif defined( CINDER_MSW_DESKTOP ) set<Font::Glyph> getNecessaryGlyphs( const Font &font, const string &supportedChars ) { set<Font::Glyph> result; GCP_RESULTS gcpResults; WCHAR *glyphIndices = NULL; std::u16string utf16 = toUtf16( supportedChars ); ::SelectObject( Font::getGlobalDc(), font.getHfont() ); gcpResults.lStructSize = sizeof(gcpResults); gcpResults.lpOutString = NULL; gcpResults.lpOrder = NULL; gcpResults.lpCaretPos = NULL; gcpResults.lpClass = NULL; uint32_t bufferSize = std::max<uint32_t>( (uint32_t)(utf16.length() * 1.2f), 16); // Initially guess number of chars plus a few while( true ) { if( glyphIndices ) { free( glyphIndices ); glyphIndices = NULL; } glyphIndices = (WCHAR*)malloc( bufferSize * sizeof(WCHAR) ); gcpResults.nGlyphs = bufferSize; gcpResults.lpDx = 0; gcpResults.lpGlyphs = glyphIndices; if( ! ::GetCharacterPlacementW( Font::getGlobalDc(), (wchar_t*)utf16.c_str(), utf16.length(), 0, &gcpResults, GCP_LIGATE | GCP_DIACRITIC | GCP_GLYPHSHAPE | GCP_REORDER ) ) { return set<Font::Glyph>(); // failure } if( gcpResults.lpGlyphs ) break; // Too small a buffer, try again bufferSize += bufferSize / 2; if( bufferSize > INT_MAX) { return set<Font::Glyph>(); // failure } } for( UINT i = 0; i < gcpResults.nGlyphs; i++ ) result.insert( glyphIndices[i] ); if( glyphIndices ) free( glyphIndices ); return result; } TextureFont::TextureFont( const Font &font, const string &utf8Chars, const Format &format ) : mFont( font ), mFormat( format ) { // get the glyph indices we'll need set<Font::Glyph> glyphs = getNecessaryGlyphs( font, utf8Chars ); // determine the max glyph extents ivec2 glyphExtents; for( set<Font::Glyph>::const_iterator glyphIt = glyphs.begin(); glyphIt != glyphs.end(); ++glyphIt ) { try { Rectf bb = font.getGlyphBoundingBox( *glyphIt ); glyphExtents.x = std::max<int>( glyphExtents.x, bb.getWidth() ); glyphExtents.y = std::max<int>( glyphExtents.y, bb.getHeight() ); } catch( FontGlyphFailureExc &e ) { } } ::SelectObject( Font::getGlobalDc(), mFont.getHfont() ); if( ( glyphExtents.x == 0 ) || ( glyphExtents.y == 0 ) ) return; int glyphsWide = mFormat.getTextureWidth() / glyphExtents.x; int glyphsTall = mFormat.getTextureHeight() / glyphExtents.y; uint8_t curGlyphIndex = 0, curTextureIndex = 0; ivec2 curOffset = ivec2( 0, 0 ); Channel channel( mFormat.getTextureWidth(), mFormat.getTextureHeight() ); ip::fill<uint8_t>( &channel, 0 ); std::unique_ptr<uint8_t[]> lumAlphaData( new uint8_t[mFormat.getTextureWidth()*mFormat.getTextureHeight()*2] ); GLYPHMETRICS gm = { 0, }; MAT2 identityMatrix = { {0,1},{0,0},{0,0},{0,1} }; size_t bufferSize = 1; BYTE *pBuff = new BYTE[bufferSize]; for( set<Font::Glyph>::const_iterator glyphIt = glyphs.begin(); glyphIt != glyphs.end(); ) { DWORD dwBuffSize = ::GetGlyphOutline( Font::getGlobalDc(), *glyphIt, GGO_GRAY8_BITMAP | GGO_GLYPH_INDEX, &gm, 0, NULL, &identityMatrix ); if( dwBuffSize == GDI_ERROR ) { ++glyphIt; continue; } if( dwBuffSize > bufferSize ) { delete[] pBuff; pBuff = new BYTE[dwBuffSize]; bufferSize = dwBuffSize; } else if( dwBuffSize == 0 ) { ++glyphIt; continue; } if( ::GetGlyphOutline( Font::getGlobalDc(), *glyphIt, GGO_METRICS | GGO_GLYPH_INDEX, &gm, 0, NULL, &identityMatrix ) == GDI_ERROR ) { ++glyphIt; continue; } if( ::GetGlyphOutline( Font::getGlobalDc(), *glyphIt, GGO_GRAY8_BITMAP | GGO_GLYPH_INDEX, &gm, dwBuffSize, pBuff, &identityMatrix ) == GDI_ERROR ) { ++glyphIt; continue; } // convert 6bit to 8bit gray for( INT p = 0; p < dwBuffSize; ++p ) pBuff[p] = ((uint32_t)pBuff[p]) * 255 / 64; int32_t alignedRowBytes = ( gm.gmBlackBoxX & 3 ) ? ( gm.gmBlackBoxX + 4 - ( gm.gmBlackBoxX & 3 ) ) : gm.gmBlackBoxX; Channel glyphChannel( gm.gmBlackBoxX, gm.gmBlackBoxY, alignedRowBytes, 1, pBuff ); channel.copyFrom( glyphChannel, glyphChannel.getBounds(), curOffset ); GlyphInfo newInfo; newInfo.mOriginOffset = vec2( gm.gmptGlyphOrigin.x, glyphExtents.y - gm.gmptGlyphOrigin.y ); newInfo.mTexCoords = Area( curOffset, curOffset + ivec2( gm.gmBlackBoxX, gm.gmBlackBoxY ) ); newInfo.mTextureIndex = curTextureIndex; mGlyphMap[*glyphIt] = newInfo; curOffset += ivec2( glyphExtents.x, 0 ); ++glyphIt; if( ( ++curGlyphIndex == glyphsWide * glyphsTall ) || ( glyphIt == glyphs.end() ) ) { Surface tempSurface( channel, SurfaceConstraintsDefault(), true ); tempSurface.getChannelAlpha().copyFrom( channel, channel.getBounds() ); if( ! format.getPremultiply() ) ip::unpremultiply( &tempSurface ); gl::Texture::Format textureFormat = gl::Texture::Format(); textureFormat.enableMipmapping( mFormat.hasMipmapping() ); Surface8u::ConstIter iter( tempSurface, tempSurface.getBounds() ); size_t offset = 0; while( iter.line() ) { while( iter.pixel() ) { lumAlphaData.get()[offset+0] = iter.r(); lumAlphaData.get()[offset+1] = iter.a(); offset += 2; } } #if defined( CINDER_GL_ES ) textureFormat.setInternalFormat( GL_LUMINANCE_ALPHA ); #else textureFormat.setInternalFormat( GL_RG ); array<GLint,4> swizzleMask = { GL_RED, GL_RED, GL_RED, GL_GREEN }; textureFormat.setSwizzleMask( swizzleMask ); #endif mTextures.push_back( gl::Texture::create( lumAlphaData.get(), textureFormat.getInternalFormat(), mFormat.getTextureWidth(), mFormat.getTextureHeight(), textureFormat ) ); mTextures.back()->setTopDown( true ); ip::fill<uint8_t>( &channel, 0 ); curOffset = ivec2( 0, 0 ); curGlyphIndex = 0; ++curTextureIndex; } else if( ( curGlyphIndex ) % glyphsWide == 0 ) { // wrap around curOffset.x = 0; curOffset.y += glyphExtents.y; } } delete [] pBuff; } #elif defined( CINDER_ANDROID ) || defined( CINDER_LINUX ) TextureFont::TextureFont( const Font &font, const string &utf8Chars, const Format &format ) : mFont( font ), mFormat( format ) { FT_Face face = font.getFreetypeFace(); std::u32string utf32Chars = ci::toUtf32( utf8Chars ); // Add a space if needed if( std::string::npos == utf8Chars.find( ' ' ) ) { utf32Chars += ci::toUtf32( " " ); } // get the glyph indices we'll need set<Font::Glyph> glyphs; for( const auto& ch : utf32Chars ) { FT_UInt glyphIndex = FT_Get_Char_Index( face, ch ); glyphs.insert( glyphIndex ); } // determine the max glyph extents vec2 glyphExtents; for( set<Font::Glyph>::const_iterator glyphIt = glyphs.begin(); glyphIt != glyphs.end(); ++glyphIt ) { Rectf bb = font.getGlyphBoundingBox( *glyphIt ); glyphExtents.x = std::max( glyphExtents.x, bb.getWidth() ); glyphExtents.y = std::max( glyphExtents.y, bb.getHeight() ); } glyphExtents.x = ceil( glyphExtents.x ); glyphExtents.y = ceil( glyphExtents.y ); int glyphsWide = floor( mFormat.getTextureWidth() / (glyphExtents.x+3) ); int glyphsTall = floor( mFormat.getTextureHeight() / (glyphExtents.y+5) ); uint8_t curGlyphIndex = 0, curTextureIndex = 0; vec2 curOffset; std::vector<FT_UInt> renderGlyphs( glyphsWide*glyphsTall ); std::vector<FT_Vector> renderPositions( glyphsWide*glyphsTall ); Surface surface( mFormat.getTextureWidth(), mFormat.getTextureHeight(), true ); ip::fill( &surface, ColorA8u( 0, 0, 0, 0 ) ); ColorA white( 1, 1, 1, 1 ); ivec2 surfaceSize = surface.getSize(); uint8_t* surfaceData = surface.getData(); size_t surfacePixelInc = surface.getPixelInc(); size_t surfaceRowBytes = surface.getRowBytes(); std::unique_ptr<uint8_t[]> lumAlphaData( new uint8_t[mFormat.getTextureWidth()*mFormat.getTextureHeight()*2] ); for( set<Font::Glyph>::const_iterator glyphIt = glyphs.begin(); glyphIt != glyphs.end(); ) { GlyphInfo newInfo; newInfo.mTextureIndex = curTextureIndex; Rectf bb = font.getGlyphBoundingBox( *glyphIt ); vec2 ul = curOffset + vec2( 0, glyphExtents.y - bb.getHeight() ); vec2 lr = curOffset + vec2( glyphExtents.x, glyphExtents.y ); newInfo.mTexCoords = Area( floor( ul.x ), floor( ul.y ), ceil( lr.x ) + 3, ceil( lr.y ) + 2 ); newInfo.mOriginOffset.x = floor(bb.x1) - 1; newInfo.mOriginOffset.y = -(bb.getHeight()-1)-ceil( bb.y1+0.5f ); mGlyphMap[*glyphIt] = newInfo; renderGlyphs[curGlyphIndex] = *glyphIt; renderPositions[curGlyphIndex].x = curOffset.x - floor(bb.x1) + 1; renderPositions[curGlyphIndex].y = surface.getHeight() - (curOffset.y + glyphExtents.y) - ceil(bb.y1+0.5f); curOffset += ivec2( glyphExtents.x + 3, 0 ); ++glyphIt; if( ( ++curGlyphIndex == glyphsWide * glyphsTall ) || ( glyphIt == glyphs.end() ) ) { for( size_t i = 0; i < (size_t)curGlyphIndex; ++i ) { FT_UInt glyphIndex = renderGlyphs[i]; FT_Vector glyphPos = renderPositions[i]; FT_Vector pen = { glyphPos.x*64, glyphPos.y*64 }; FT_Set_Transform( face, nullptr, &pen ); FT_Load_Glyph( face, glyphIndex, FT_LOAD_RENDER ); FT_GlyphSlot slot = face->glyph; ivec2 drawOffset = ivec2( slot->bitmap_left, surfaceSize.y - slot->bitmap_top ); ci::linux::ftutil::DrawBitmap( drawOffset, &(slot->bitmap), white, surfaceData, surfacePixelInc, surfaceRowBytes, surfaceSize ); FT_Load_Glyph( face, glyphIndex, FT_LOAD_DEFAULT ); Font::GlyphMetrics glyphMetrics; glyphMetrics.advance = ivec2( slot->advance.x, slot->advance.y ); //glyphMetrics.metrics = slot->metrics; mCachedGlyphMetrics[glyphIndex] = glyphMetrics; } // pass premultiply and mipmapping preferences to Texture::Format if( ! mFormat.getPremultiply() ) { ip::unpremultiply( &surface ); } gl::Texture::Format textureFormat = gl::Texture::Format(); textureFormat.enableMipmapping( mFormat.hasMipmapping() ); GLint dataFormat; #if defined( CINDER_GL_ES ) dataFormat = GL_LUMINANCE_ALPHA; textureFormat.setInternalFormat( dataFormat ); #else dataFormat = GL_RG; textureFormat.setInternalFormat( dataFormat ); textureFormat.setSwizzleMask( { GL_RED, GL_RED, GL_RED, GL_GREEN } ); #endif if( mFormat.hasMipmapping() ) textureFormat.setMinFilter( GL_LINEAR_MIPMAP_LINEAR ); // under iOS format and interalFormat must match, so let's make a block of LUMINANCE_ALPHA data Surface8u::ConstIter iter( surface, surface.getBounds() ); size_t offset = 0; while( iter.line() ) { while( iter.pixel() ) { lumAlphaData.get()[offset+0] = iter.r(); lumAlphaData.get()[offset+1] = iter.a(); offset += 2; } } mTextures.push_back( gl::Texture::create( lumAlphaData.get(), dataFormat, mFormat.getTextureWidth(), mFormat.getTextureHeight(), textureFormat ) ); mTextures.back()->setTopDown( true ); ip::fill( &surface, ColorA8u( 0, 0, 0, 0 ) ); curOffset = vec2(); curGlyphIndex = 0; ++curTextureIndex; } else if( ( curGlyphIndex ) % glyphsWide == 0 ) { // wrap around curOffset.x = 0; curOffset.y += glyphExtents.y + 2; } } } #endif void TextureFont::drawGlyphs( const vector<pair<Font::Glyph,vec2> > &glyphMeasures, const vec2 &baselineIn, const DrawOptions &options, const std::vector<ColorA8u> &colors ) { if( mTextures.empty() ) return; if( ! colors.empty() ) assert( glyphMeasures.size() == colors.size() ); auto shader = options.getGlslProg(); if( ! shader ) { auto shaderDef = ShaderDef().texture( mTextures[0] ).color(); shader = gl::getStockShader( shaderDef ); } ScopedTextureBind texBindScp( mTextures[0] ); ScopedGlslProg glslScp( shader ); vec2 baseline = baselineIn; const float scale = options.getScale(); for( size_t texIdx = 0; texIdx < mTextures.size(); ++texIdx ) { vector<float> verts, texCoords; vector<ColorA8u> vertColors; const gl::TextureRef &curTex = mTextures[texIdx]; #if defined( CINDER_GL_ES ) vector<uint16_t> indices; uint16_t curIdx = 0; GLenum indexType = GL_UNSIGNED_SHORT; #else vector<uint32_t> indices; uint32_t curIdx = 0; GLenum indexType = GL_UNSIGNED_INT; #endif if( options.getPixelSnap() ) baseline = vec2( floor( baseline.x ), floor( baseline.y ) ); for( vector<pair<Font::Glyph,vec2> >::const_iterator glyphIt = glyphMeasures.begin(); glyphIt != glyphMeasures.end(); ++glyphIt ) { unordered_map<Font::Glyph, GlyphInfo>::const_iterator glyphInfoIt = mGlyphMap.find( glyphIt->first ); if( (glyphInfoIt == mGlyphMap.end()) || (mGlyphMap[glyphIt->first].mTextureIndex != texIdx) ) continue; const GlyphInfo &glyphInfo = glyphInfoIt->second; Rectf destRect( glyphInfo.mTexCoords ); Rectf srcCoords = curTex->getAreaTexCoords( glyphInfo.mTexCoords ); destRect -= destRect.getUpperLeft(); destRect.scale( scale ); destRect += glyphIt->second * scale; destRect += vec2( floor( glyphInfo.mOriginOffset.x + 0.5f ), floor( glyphInfo.mOriginOffset.y ) ) * scale; destRect += vec2( baseline.x, baseline.y - mFont.getAscent() * scale ); if( options.getPixelSnap() ) destRect -= vec2( destRect.x1 - floor( destRect.x1 ), destRect.y1 - floor( destRect.y1 ) ); verts.push_back( destRect.getX2() ); verts.push_back( destRect.getY1() ); verts.push_back( destRect.getX1() ); verts.push_back( destRect.getY1() ); verts.push_back( destRect.getX2() ); verts.push_back( destRect.getY2() ); verts.push_back( destRect.getX1() ); verts.push_back( destRect.getY2() ); texCoords.push_back( srcCoords.getX2() ); texCoords.push_back( srcCoords.getY1() ); texCoords.push_back( srcCoords.getX1() ); texCoords.push_back( srcCoords.getY1() ); texCoords.push_back( srcCoords.getX2() ); texCoords.push_back( srcCoords.getY2() ); texCoords.push_back( srcCoords.getX1() ); texCoords.push_back( srcCoords.getY2() ); if( ! colors.empty() ) { for( int i = 0; i < 4; ++i ) vertColors.push_back( colors[glyphIt-glyphMeasures.begin()] ); } indices.push_back( curIdx + 0 ); indices.push_back( curIdx + 1 ); indices.push_back( curIdx + 2 ); indices.push_back( curIdx + 2 ); indices.push_back( curIdx + 1 ); indices.push_back( curIdx + 3 ); curIdx += 4; } if( curIdx == 0 ) continue; curTex->bind(); auto ctx = gl::context(); size_t dataSize = (verts.size() + texCoords.size()) * sizeof(float) + vertColors.size() * sizeof(ColorA8u); gl::ScopedVao vaoScp( ctx->getDefaultVao() ); ctx->getDefaultVao()->replacementBindBegin(); VboRef defaultElementVbo = ctx->getDefaultElementVbo( indices.size() * sizeof(curIdx) ); VboRef defaultArrayVbo = ctx->getDefaultArrayVbo( dataSize ); ScopedBuffer vboArrayScp( defaultArrayVbo ); ScopedBuffer vboElScp( defaultElementVbo ); size_t dataOffset = 0; int posLoc = shader->getAttribSemanticLocation( geom::Attrib::POSITION ); if( posLoc >= 0 ) { enableVertexAttribArray( posLoc ); vertexAttribPointer( posLoc, 2, GL_FLOAT, GL_FALSE, 0, (void*)0 ); defaultArrayVbo->bufferSubData( dataOffset, verts.size() * sizeof(float), verts.data() ); dataOffset += verts.size() * sizeof(float); } int texLoc = shader->getAttribSemanticLocation( geom::Attrib::TEX_COORD_0 ); if( texLoc >= 0 ) { enableVertexAttribArray( texLoc ); vertexAttribPointer( texLoc, 2, GL_FLOAT, GL_FALSE, 0, (void*)dataOffset ); defaultArrayVbo->bufferSubData( dataOffset, texCoords.size() * sizeof(float), texCoords.data() ); dataOffset += texCoords.size() * sizeof(float); } if( ! vertColors.empty() ) { int colorLoc = shader->getAttribSemanticLocation( geom::Attrib::COLOR ); if( colorLoc >= 0 ) { enableVertexAttribArray( colorLoc ); vertexAttribPointer( colorLoc, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, (void*)dataOffset ); defaultArrayVbo->bufferSubData( dataOffset, vertColors.size() * sizeof(ColorA8u), vertColors.data() ); dataOffset += vertColors.size() * sizeof(ColorA8u); } } defaultElementVbo->bufferSubData( 0, indices.size() * sizeof(curIdx), indices.data() ); ctx->getDefaultVao()->replacementBindEnd(); gl::setDefaultShaderVars(); ctx->drawElements( GL_TRIANGLES, (GLsizei)indices.size(), indexType, 0 ); } } void TextureFont::drawGlyphs( const std::vector<std::pair<Font::Glyph,vec2> > &glyphMeasures, const Rectf &clip, vec2 offset, const DrawOptions &options, const std::vector<ColorA8u> &colors ) { if( mTextures.empty() ) return; if( ! colors.empty() ) assert( glyphMeasures.size() == colors.size() ); auto shader = options.getGlslProg(); if( ! shader ) { auto shaderDef = ShaderDef().texture( mTextures[0] ).color(); shader = gl::getStockShader( shaderDef ); } ScopedTextureBind texBindScp( mTextures[0] ); ScopedGlslProg glslScp( shader ); const float scale = options.getScale(); for( size_t texIdx = 0; texIdx < mTextures.size(); ++texIdx ) { vector<float> verts, texCoords; vector<ColorA8u> vertColors; const gl::TextureRef &curTex = mTextures[texIdx]; #if defined( CINDER_GL_ES ) vector<uint16_t> indices; uint16_t curIdx = 0; GLenum indexType = GL_UNSIGNED_SHORT; #else vector<uint32_t> indices; uint32_t curIdx = 0; GLenum indexType = GL_UNSIGNED_INT; #endif if( options.getPixelSnap() ) offset = vec2( floor( offset.x ), floor( offset.y ) ); for( vector<pair<Font::Glyph,vec2> >::const_iterator glyphIt = glyphMeasures.begin(); glyphIt != glyphMeasures.end(); ++glyphIt ) { unordered_map<Font::Glyph, GlyphInfo>::const_iterator glyphInfoIt = mGlyphMap.find( glyphIt->first ); if( (glyphInfoIt == mGlyphMap.end()) || (mGlyphMap[glyphIt->first].mTextureIndex != texIdx) ) continue; const GlyphInfo &glyphInfo = glyphInfoIt->second; Rectf srcTexCoords = curTex->getAreaTexCoords( glyphInfo.mTexCoords ); Rectf destRect( glyphInfo.mTexCoords ); destRect -= destRect.getUpperLeft(); destRect.scale( scale ); destRect += glyphIt->second * scale; destRect += vec2( floor( glyphInfo.mOriginOffset.x + 0.5f ), floor( glyphInfo.mOriginOffset.y ) ) * scale; destRect += vec2( offset.x, offset.y ); if( options.getPixelSnap() ) destRect -= vec2( destRect.x1 - floor( destRect.x1 ), destRect.y1 - floor( destRect.y1 ) ); // clip Rectf clipped( destRect ); if( options.getClipHorizontal() ) { clipped.x1 = std::max( destRect.x1, clip.x1 ); clipped.x2 = std::min( destRect.x2, clip.x2 ); } if( options.getClipVertical() ) { clipped.y1 = std::max( destRect.y1, clip.y1 ); clipped.y2 = std::min( destRect.y2, clip.y2 ); } if( clipped.x1 >= clipped.x2 || clipped.y1 >= clipped.y2 ) continue; vec2 coordScale( 1 / (float)destRect.getWidth() / curTex->getWidth() * glyphInfo.mTexCoords.getWidth(), 1 / (float)destRect.getHeight() / curTex->getHeight() * glyphInfo.mTexCoords.getHeight() ); srcTexCoords.x1 = srcTexCoords.x1 + ( clipped.x1 - destRect.x1 ) * coordScale.x; srcTexCoords.x2 = srcTexCoords.x1 + ( clipped.x2 - clipped.x1 ) * coordScale.x; srcTexCoords.y1 = srcTexCoords.y1 + ( clipped.y1 - destRect.y1 ) * coordScale.y; srcTexCoords.y2 = srcTexCoords.y1 + ( clipped.y2 - clipped.y1 ) * coordScale.y; verts.push_back( clipped.getX2() ); verts.push_back( clipped.getY1() ); verts.push_back( clipped.getX1() ); verts.push_back( clipped.getY1() ); verts.push_back( clipped.getX2() ); verts.push_back( clipped.getY2() ); verts.push_back( clipped.getX1() ); verts.push_back( clipped.getY2() ); texCoords.push_back( srcTexCoords.getX2() ); texCoords.push_back( srcTexCoords.getY1() ); texCoords.push_back( srcTexCoords.getX1() ); texCoords.push_back( srcTexCoords.getY1() ); texCoords.push_back( srcTexCoords.getX2() ); texCoords.push_back( srcTexCoords.getY2() ); texCoords.push_back( srcTexCoords.getX1() ); texCoords.push_back( srcTexCoords.getY2() ); if( ! colors.empty() ) { for( int i = 0; i < 4; ++i ) vertColors.push_back( colors[glyphIt-glyphMeasures.begin()] ); } indices.push_back( curIdx + 0 ); indices.push_back( curIdx + 1 ); indices.push_back( curIdx + 2 ); indices.push_back( curIdx + 2 ); indices.push_back( curIdx + 1 ); indices.push_back( curIdx + 3 ); curIdx += 4; } if( curIdx == 0 ) continue; curTex->bind(); auto ctx = gl::context(); size_t dataSize = (verts.size() + texCoords.size()) * sizeof(float) + vertColors.size() * sizeof(ColorA8u); gl::ScopedVao vaoScp( ctx->getDefaultVao() ); ctx->getDefaultVao()->replacementBindBegin(); VboRef defaultElementVbo = ctx->getDefaultElementVbo( indices.size() * sizeof(curIdx) ); VboRef defaultArrayVbo = ctx->getDefaultArrayVbo( dataSize ); ScopedBuffer vboArrayScp( defaultArrayVbo ); ScopedBuffer vboElScp( defaultElementVbo ); size_t dataOffset = 0; int posLoc = shader->getAttribSemanticLocation( geom::Attrib::POSITION ); if( posLoc >= 0 ) { enableVertexAttribArray( posLoc ); vertexAttribPointer( posLoc, 2, GL_FLOAT, GL_FALSE, 0, (void*)0 ); defaultArrayVbo->bufferSubData( dataOffset, verts.size() * sizeof(float), verts.data() ); dataOffset += verts.size() * sizeof(float); } int texLoc = shader->getAttribSemanticLocation( geom::Attrib::TEX_COORD_0 ); if( texLoc >= 0 ) { enableVertexAttribArray( texLoc ); vertexAttribPointer( texLoc, 2, GL_FLOAT, GL_FALSE, 0, (void*)dataOffset ); defaultArrayVbo->bufferSubData( dataOffset, texCoords.size() * sizeof(float), texCoords.data() ); dataOffset += texCoords.size() * sizeof(float); } if( ! vertColors.empty() ) { int colorLoc = shader->getAttribSemanticLocation( geom::Attrib::COLOR ); if( colorLoc >= 0 ) { enableVertexAttribArray( colorLoc ); vertexAttribPointer( colorLoc, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, (void*)dataOffset ); defaultArrayVbo->bufferSubData( dataOffset, vertColors.size() * sizeof(ColorA8u), vertColors.data() ); dataOffset += vertColors.size() * sizeof(ColorA8u); } } defaultElementVbo->bufferSubData( 0, indices.size() * sizeof(curIdx), indices.data() ); ctx->getDefaultVao()->replacementBindEnd(); gl::setDefaultShaderVars(); ctx->drawElements( GL_TRIANGLES, (GLsizei)indices.size(), indexType, 0 ); } } void TextureFont::drawString( const std::string &str, const vec2 &baseline, const DrawOptions &options ) { TextBox tbox = TextBox().font( mFont ).text( str ).size( TextBox::GROW, TextBox::GROW ).ligate( options.getLigate() ); #if defined( CINDER_ANDROID ) || defined( CINDER_LINUX ) vector<pair<Font::Glyph,vec2> > glyphMeasures = tbox.measureGlyphs( getCachedGlyphMetrics() ); #else vector<pair<Font::Glyph,vec2> > glyphMeasures = tbox.measureGlyphs(); #endif drawGlyphs( glyphMeasures, baseline, options ); } void TextureFont::drawString( const std::string &str, const Rectf &fitRect, const vec2 &offset, const DrawOptions &options ) { TextBox tbox = TextBox().font( mFont ).text( str ).size( TextBox::GROW, fitRect.getHeight() ).ligate( options.getLigate() ); #if defined( CINDER_ANDROID ) || defined( CINDER_LINUX ) vector<pair<Font::Glyph,vec2> > glyphMeasures = tbox.measureGlyphs( getCachedGlyphMetrics() ); #else vector<pair<Font::Glyph,vec2> > glyphMeasures = tbox.measureGlyphs(); #endif drawGlyphs( glyphMeasures, fitRect, fitRect.getUpperLeft() + offset, options ); } void TextureFont::drawStringWrapped( const std::string &str, const Rectf &fitRect, const vec2 &offset, const DrawOptions &options ) { TextBox tbox = TextBox().font( mFont ).text( str ).size( fitRect.getWidth(), fitRect.getHeight() ).ligate( options.getLigate() ); #if defined( CINDER_ANDROID ) || defined( CINDER_LINUX ) vector<pair<Font::Glyph,vec2> > glyphMeasures = tbox.measureGlyphs( getCachedGlyphMetrics() ); #else vector<pair<Font::Glyph,vec2> > glyphMeasures = tbox.measureGlyphs(); #endif drawGlyphs( glyphMeasures, fitRect.getUpperLeft() + offset, options ); } vec2 TextureFont::measureString( const std::string &str, const DrawOptions &options ) const { TextBox tbox = TextBox().font( mFont ).text( str ).size( TextBox::GROW, TextBox::GROW ).ligate( options.getLigate() ); #if defined( CINDER_COCOA ) return tbox.measure(); #else #if defined( CINDER_ANDROID ) || defined( CINDER_LINUX ) vector<pair<Font::Glyph,vec2> > glyphMeasures = tbox.measureGlyphs( getCachedGlyphMetrics() ); #else vector<pair<Font::Glyph,vec2> > glyphMeasures = tbox.measureGlyphs(); #endif if( ! glyphMeasures.empty() ) { vec2 result = glyphMeasures.back().second; unordered_map<Font::Glyph, GlyphInfo>::const_iterator glyphInfoIt = mGlyphMap.find( glyphMeasures.back().first ); if( glyphInfoIt != mGlyphMap.end() ) result += glyphInfoIt->second.mOriginOffset + vec2( glyphInfoIt->second.mTexCoords.getSize() ); return result; } else { return vec2(); } #endif } #if defined( CINDER_COCOA ) vec2 TextureFont::measureStringWrapped( const std::string &str, const Rectf &fitRect, const DrawOptions &options ) const { TextBox tbox = TextBox().font( mFont ).text( str ).size( fitRect.getWidth(), fitRect.getHeight() ).ligate( options.getLigate() ); return tbox.measure(); } #endif vector<pair<Font::Glyph,vec2> > TextureFont::getGlyphPlacements( const std::string &str, const DrawOptions &options ) const { TextBox tbox = TextBox().font( mFont ).text( str ).size( TextBox::GROW, TextBox::GROW ).ligate( options.getLigate() ); return tbox.measureGlyphs(); } vector<pair<Font::Glyph,vec2> > TextureFont::getGlyphPlacements( const std::string &str, const Rectf &fitRect, const DrawOptions &options ) const { TextBox tbox = TextBox().font( mFont ).text( str ).size( TextBox::GROW, fitRect.getHeight() ).ligate( options.getLigate() ); return tbox.measureGlyphs(); } vector<pair<Font::Glyph,vec2> > TextureFont::getGlyphPlacementsWrapped( const std::string &str, const Rectf &fitRect, const DrawOptions &options ) const { TextBox tbox = TextBox().font( mFont ).text( str ).size( fitRect.getWidth(), fitRect.getHeight() ).ligate( options.getLigate() ); return tbox.measureGlyphs(); } } } // namespace cinder::gl
#include "components/ScrollableContainer.h" #include "Renderer.h" #include "Log.h" #define AUTO_SCROLL_RESET_DELAY 10000 // ms to reset to top after we reach the bottom #define AUTO_SCROLL_DELAY 8000 // ms to wait before we start to scroll #define AUTO_SCROLL_SPEED 50 // ms between scrolls ScrollableContainer::ScrollableContainer(Window* window) : GuiComponent(window), mAutoScrollDelay(0), mAutoScrollSpeed(0), mAutoScrollAccumulator(0), mScrollPos(0, 0), mScrollDir(0, 0), mAutoScrollResetAccumulator(0) { } void ScrollableContainer::render(const Eigen::Affine3f& parentTrans) { Eigen::Affine3f trans = parentTrans * getTransform(); Eigen::Vector2i clipPos((int)trans.translation().x(), (int)trans.translation().y()); Eigen::Vector3f dimScaled = trans * Eigen::Vector3f(mSize.x(), mSize.y(), 0); Eigen::Vector2i clipDim((int)dimScaled.x() - trans.translation().x(), (int)dimScaled.y() - trans.translation().y()); Renderer::pushClipRect(clipPos, clipDim); trans.translate(-Eigen::Vector3f(mScrollPos.x(), mScrollPos.y(), 0)); Renderer::setMatrix(trans); GuiComponent::renderChildren(trans); Renderer::popClipRect(); } void ScrollableContainer::setAutoScroll(bool autoScroll) { if(autoScroll) { mScrollDir << 0, 1; mAutoScrollDelay = AUTO_SCROLL_DELAY; mAutoScrollSpeed = AUTO_SCROLL_SPEED; reset(); }else{ mScrollDir << 0, 0; mAutoScrollDelay = 0; mAutoScrollSpeed = 0; mAutoScrollAccumulator = 0; } } Eigen::Vector2f ScrollableContainer::getScrollPos() const { return mScrollPos; } void ScrollableContainer::setScrollPos(const Eigen::Vector2f& pos) { mScrollPos = pos; } void ScrollableContainer::update(int deltaTime) { if(mAutoScrollSpeed != 0) { mAutoScrollAccumulator += deltaTime; //scale speed by our width! more text per line = slower scrolling const float widthMod = (680.0f / getSize().x()); while(mAutoScrollAccumulator >= mAutoScrollSpeed) { mScrollPos += mScrollDir; mAutoScrollAccumulator -= mAutoScrollSpeed; } } //clip scrolling within bounds if(mScrollPos.x() < 0) mScrollPos[0] = 0; if(mScrollPos.y() < 0) mScrollPos[1] = 0; const Eigen::Vector2f contentSize = getContentSize(); if(mScrollPos.x() + getSize().x() > contentSize.x()) { mScrollPos[0] = contentSize.x() - getSize().x(); mAtEnd = true; } if(contentSize.y() < getSize().y()) { mScrollPos[1] = 0; }else if(mScrollPos.y() + getSize().y() > contentSize.y()) { mScrollPos[1] = contentSize.y() - getSize().y(); mAtEnd = true; } if(mAtEnd) { mAutoScrollResetAccumulator += deltaTime; if(mAutoScrollResetAccumulator >= AUTO_SCROLL_RESET_DELAY) reset(); } GuiComponent::update(deltaTime); } //this should probably return a box to allow for when controls don't start at 0,0 Eigen::Vector2f ScrollableContainer::getContentSize() { Eigen::Vector2f max(0, 0); for(unsigned int i = 0; i < mChildren.size(); i++) { Eigen::Vector2f pos(mChildren.at(i)->getPosition()[0], mChildren.at(i)->getPosition()[1]); Eigen::Vector2f bottomRight = mChildren.at(i)->getSize() + pos; if(bottomRight.x() > max.x()) max.x() = bottomRight.x(); if(bottomRight.y() > max.y()) max.y() = bottomRight.y(); } return max; } void ScrollableContainer::reset() { mScrollPos << 0, 0; mAutoScrollResetAccumulator = 0; mAutoScrollAccumulator = -mAutoScrollDelay + mAutoScrollSpeed; mAtEnd = false; }
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/cloudwf/model/SaveGroupApRadioConfigResult.h> #include <json/json.h> using namespace AlibabaCloud::Cloudwf; using namespace AlibabaCloud::Cloudwf::Model; SaveGroupApRadioConfigResult::SaveGroupApRadioConfigResult() : ServiceResult() {} SaveGroupApRadioConfigResult::SaveGroupApRadioConfigResult(const std::string &payload) : ServiceResult() { parse(payload); } SaveGroupApRadioConfigResult::~SaveGroupApRadioConfigResult() {} void SaveGroupApRadioConfigResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; if(!value["Message"].isNull()) message_ = value["Message"].asString(); if(!value["Data"].isNull()) data_ = value["Data"].asString(); if(!value["ErrorCode"].isNull()) errorCode_ = std::stoi(value["ErrorCode"].asString()); if(!value["ErrorMsg"].isNull()) errorMsg_ = value["ErrorMsg"].asString(); } std::string SaveGroupApRadioConfigResult::getMessage()const { return message_; } std::string SaveGroupApRadioConfigResult::getErrorMsg()const { return errorMsg_; } std::string SaveGroupApRadioConfigResult::getData()const { return data_; } int SaveGroupApRadioConfigResult::getErrorCode()const { return errorCode_; } bool SaveGroupApRadioConfigResult::getSuccess()const { return success_; }
#include "VideoController.h" #include "fabutils.h" #include "monitor.h" #define BK_WIDTH 64 #define BK_HEIGHT 256 #define BORDER_HEIGHT 2 #define BORDER_WIDTH ((SCREEN_WIDTH - BK_WIDTH) / 2) // BK Palette colors #define COLOR_00 0x00 #define COLOR_01 0x30 #define COLOR_10 0x0C #define COLOR_11 0x03 #define BW_00 0x00 #define BW_01 0x15 #define BW_10 0x2A #define BW_11 0x3F // Text Mode #define BACK_COLOR 0x10 #define FORE_COLOR 0x2A #define FONT_HEIGHT 10 static const uint8_t screenModeZero = 0; static const uint8_t noScroll = 0330; static const uint8_t noExtendedMemory = 0x02; extern "C" void IRAM_ATTR drawScanline(void* arg, uint8_t* dest, int scanLine); void VideoController::Initialize(bkEnvironment* environment) { this->_environment = environment; this->ScreenMode = environment->GetPointer(0x0020); this->VideoRam = environment->GetPointer(0x4000); this->Scroll = environment->GetPointer(0xFFB4); this->ExtendedMemory = environment->GetPointer(0xFFB5); this->Palette512x256 = (uint32_t*)heap_caps_malloc(16 * 4, MALLOC_CAP_32BIT); this->Palette256x256color = (uint32_t*)heap_caps_malloc(16 * 4, MALLOC_CAP_32BIT); this->Palette256x256bw = (uint32_t*)heap_caps_malloc(16 * 4, MALLOC_CAP_32BIT); this->Attributes = (uint32_t**)heap_caps_malloc(TEXT_WIDTH * TEXT_HEIGHT * 4, MALLOC_CAP_32BIT); this->_normalAttribute = (uint32_t*)heap_caps_malloc(16 * 4, MALLOC_CAP_32BIT); this->_inversedAttribute = (uint32_t*)heap_caps_malloc(16 * 4, MALLOC_CAP_32BIT); for (int y = 0; y < TEXT_HEIGHT; y++) { for (int x = 0; x < TEXT_WIDTH; x++) { this->Characters[y * TEXT_WIDTH + x] = ' '; this->Attributes[y * TEXT_WIDTH + x] = this->_normalAttribute; } } } void VideoController::ShowScreenshot(uint8_t* screenShot) { this->ScreenMode = (uint8_t*)&screenModeZero; this->Scroll = (uint8_t*)&noScroll; this->ExtendedMemory = (uint8_t*)&noExtendedMemory; this->_palette512x256bw = this->Palette512x256; this->Palette512x256 = this->_normalAttribute; this->VideoRam = screenShot; } void VideoController::Resume() { this->ScreenMode = this->_environment->GetPointer(0x0020); this->Scroll = this->_environment->GetPointer(0xFFB4); this->ExtendedMemory = this->_environment->GetPointer(0xFFB5); this->Palette512x256 = this->_palette512x256bw; this->VideoRam = this->_environment->GetPointer(0x4000); } void VideoController::Start(char const* modeline) { this->setDrawScanlineCallback(drawScanline, this); this->begin(); this->setResolution(modeline); // Prepare palettes this->InitPalette(this->Palette512x256, BW_00, BW_11); uint8_t colors[] = { COLOR_00, COLOR_01, COLOR_10, COLOR_11 }; this->InitPalette(this->Palette256x256color, colors); uint8_t bw[] = { BW_00, BW_01, BW_10, BW_11 }; this->InitPalette(this->Palette256x256bw, bw); // Text mode this->InitPalette(this->_normalAttribute, BACK_COLOR, FORE_COLOR); this->InitPalette(this->_inversedAttribute, FORE_COLOR, BACK_COLOR); } void VideoController::InitPalette(uint32_t* palette, uint8_t backColor, uint8_t foreColor) { for (uint8_t i = 0; i < 16; i++) { uint8_t value = i; uint32_t attributeValue; for (uint8_t bit = 0; bit < 4; bit++) { VGA_PIXELINROW(((uint8_t*)&attributeValue), bit) = this->createRawPixel(value & 0x01 ? foreColor : backColor); value >>= 1; } *palette = attributeValue; palette++; } } void VideoController::InitPalette(uint32_t* palette, uint8_t* colors) { for (uint8_t i = 0; i < 16; i++) { uint8_t value = i; uint32_t attributeValue; uint8_t color = colors[value & 0x03]; VGA_PIXELINROW(((uint8_t*)&attributeValue), 0) = this->createRawPixel(color); VGA_PIXELINROW(((uint8_t*)&attributeValue), 1) = this->createRawPixel(color); value >>= 2; color = colors[value & 0x03]; VGA_PIXELINROW(((uint8_t*)&attributeValue), 2) = this->createRawPixel(color); VGA_PIXELINROW(((uint8_t*)&attributeValue), 3) = this->createRawPixel(color); *palette = attributeValue; palette++; } } void VideoController::Print(const char* str) { this->print((char*)str); } void VideoController::printChar(uint16_t x, uint16_t y, uint16_t ch) { VideoController::printChar(x, y, ch, 0xFF, 0xFF); } void VideoController::printChar(uint16_t x, uint16_t y, uint16_t ch, uint8_t foreColor, uint8_t backColor) { if (x >= TEXT_WIDTH || y >= TEXT_HEIGHT) { // Invalid return; } int offset = y * TEXT_WIDTH + x; this->Characters[offset] = ch; this->SetAttribute(x, y, foreColor, backColor); } void VideoController::print(const char* str, uint8_t foreColor, uint8_t backColor) { print((char*)str, foreColor, backColor); } void VideoController::print(char* str) { this->print(str, 0xFF, 0xFF); } void VideoController::print(char* str, uint8_t foreColor, uint8_t backColor) { while (*str) { printChar(cursor_x, cursor_y, *str++, foreColor, backColor); cursorNext(); } } void VideoController::cursorNext() { uint8_t x = cursor_x; uint8_t y = cursor_y; if (x < TEXT_WIDTH - 1) { x++; } else { if (y < TEXT_HEIGHT - 1) { x = 0; y++; } } this->SetCursorPosition(x, y); } void VideoController::SetCursorPosition(uint8_t x, uint8_t y) { this->cursor_x = x; this->cursor_y = y; if (this->cursor_x >= TEXT_WIDTH) { this->cursor_x = TEXT_WIDTH - 1; } if (this->cursor_y >= TEXT_HEIGHT) { this->cursor_y = TEXT_HEIGHT - 1; } } void VideoController::SetAttribute(uint8_t x, uint8_t y, uint8_t foreColor, uint8_t backColor) { uint32_t* attribute; uint16_t colors = foreColor << 8 | backColor; if (colors == 0xFFFF) { attribute = this->_normalAttribute; } else { attribute = this->_inversedAttribute; } this->Attributes[y * TEXT_WIDTH + x] = attribute; } uint8_t IRAM_ATTR VideoController::createRawPixel(uint8_t color) { // HACK: should call createRawPixel() instead return this->m_HVSync | color; } void IRAM_ATTR drawScanline(void* arg, uint8_t* dest, int scanLine) { auto controller = static_cast<VideoController*>(arg); if (scanLine == 0) { controller->Frames++; } uint8_t borderPixel = controller->createRawPixel(BACK_COLOR); // First 8 lines if (scanLine < 16) { memset(dest, borderPixel, SCREEN_WIDTH * 8); return; } // Left border // Saving time //memset(dest, borderPixel, BORDER_WIDTH * 8); uint32_t* dest32 = (uint32_t*)dest + (BORDER_WIDTH * 2); scanLine -= 16; int y = scanLine / 2; if (controller->_mode == 1 || scanLine < BORDER_HEIGHT * 2 || scanLine >= (BORDER_HEIGHT + ((((*controller->ExtendedMemory) & 0x02) != 0) ? BK_HEIGHT : 64)) * 2) { // Text mode int fontRow = y % FONT_HEIGHT; y /= FONT_HEIGHT; int startCoord = y * TEXT_WIDTH; uint8_t* characters = controller->Characters + startCoord; uint32_t** attributes = controller->Attributes + startCoord; uint32_t** lastAttribute = attributes + TEXT_WIDTH - 1; uint8_t* fontData = (uint8_t*)monitor + 0x137E + fontRow; // 8x10 font from BK ROM do { uint8_t character = *characters; uint8_t fontPixels = fontData[character * FONT_HEIGHT]; uint32_t* attribute = *attributes; dest32[0] = attribute[fontPixels & 0x0F]; dest32[1] = attribute[fontPixels >> 4]; dest32 += 2; attributes++; characters++; } while (attributes <= lastAttribute); } else { // BK Mode y -= BORDER_HEIGHT; // scroll y = (uint8_t)(y + *controller->Scroll - 0330); uint32_t* lastDest = dest32 + (2 * BK_WIDTH) - 1; uint8_t* pixels = controller->VideoRam + (y * BK_WIDTH); uint32_t* palette; if (*controller->ScreenMode == 0) { palette = controller->Palette512x256; } else { palette = controller->UseColorPalette ? controller->Palette256x256color : controller->Palette256x256bw; } do { uint8_t pixelsByte = *pixels; dest32[0] = palette[pixelsByte & 0x0F]; dest32[1] = palette[pixelsByte >> 4]; dest32 += 2; pixels++; } while (dest32 <= lastDest); } // Right border // Saving time //memset(dest32, borderPixel, BORDER_WIDTH * 8); }
#ifdef __amigaos4__ #include "libMacEmu.h" #include "missing.h" #endif #include "CTextDoc.h" #include "CScrollPane.h" #include "CEditText.h" #include "CDataFile.h" void CTextDoc::ITextDoc( CApplication *supervisor ) { const Boolean kPrintable = true; IDocument( supervisor, kPrintable); } void CTextDoc::NewFile() { printf("%s:%s:%d\n",__FILE__,__FUNCTION__,__LINE__); BuildWindow(); Str255 wTitle; short wCount; Str255 wNumber; itsWindow->GetTitle(wTitle); wCount = gDecorator->GetWCount(); ::NumToString(wCount,wNumber); LibMacEmu::ConcatPStrings(wTitle," - "); LibMacEmu::ConcatPStrings(wTitle, wNumber); itsWindow -> SetTitle(wTitle); itsWindow -> Select(); } void CTextDoc::OpenFile(SFReply *macReply) { printf("%s:%d:%d\n",__FILE__,__FUNCTION__,__LINE__); CDataFile *theDataFile; Handle theData; Str63 theName; OSErr theError; const long kMaxFileSize = 32000; theDataFile = new CDataFile; itsFile = theDataFile; theDataFile -> IDataFile(); theDataFile -> SFSpecify(macReply); theDataFile -> Open( fsRdPerm ); TRY { if (theDataFile->GetLength() > kMaxFileSize ) Failure(mFulErr, excExeedTELimit); theData = theDataFile -> ReadAll(); } CATCH { theDataFile-> Close(); } ENDTRY; TRY { theDataFile->Close(); BuildWindow(); fEditText -> SetTextHandle(theData); } CATCH { DisposeHandle(theData); } ENDTRY; DisposeHandle(theData); itsFile -> GetName( theName ); itsWindow -> SetTitle( theName ); itsWindow -> Select(); } Boolean CTextDoc::DoSave() { printf("%s:%d:%d\n",__FILE__,__FUNCTION__,__LINE__); Handle theData; if (itsFile == NULL) return (DoSaveFileAs()); else { CDataFile *theDataFile = (CDataFile *) itsFile; theData = fEditText->GetTextHandle(); theDataFile -> Open( fsWrPerm ); TRY { theDataFile -> WriteAll(theData); } CATCH { theDataFile -> Close(); } theDataFile -> Close(); dirty = FALSE; return(TRUE); } } Boolean CTextDoc::DoSaveAs( SFReply *macSFReply ) { printf("%s:%d:%d\n",__FILE__,__FUNCTION__,__LINE__); } void CTextDoc::BuildWindow() { printf("%s:%s:%d\n",__FILE__,__FUNCTION__,__LINE__); const short kWINDResourceID = 500; const Boolean kWindowFloats = TRUE; const Boolean kFitHorizontal = TRUE; const Boolean kFitVertical = TRUE; const Boolean kHasHorizontalScrollbar = TRUE; const Boolean kHasVerticalScrollbar = TRUE; const Boolean kHasGrowBox = TRUE; const short kEditTextWidth = 72 * 6; const Boolean kRedraw = TRUE; CWindow *aWindow = new CWindow; aWindow -> IWindow(kWINDResourceID, !kWindowFloats, gDesktop, this); // aWindow will know about CTextDoc itsWindow = aWindow; // CTextDoc will know about the window. printf("this -> itsWindow %08x\n", itsWindow); CScrollPane *theScrollPane = new CScrollPane; theScrollPane -> IScrollPane(aWindow, this, 10, 10, 0, 0, sizELASTIC, sizELASTIC, kEditTextWidth ); // theScrollPane => aWindow & CTextDoc theScrollPane -> FitToEnclFrame( kFitHorizontal, kFitVertical ); // The panel will be stretched to fit. CEditText *thePane = new CEditText; thePane -> IEditText(theScrollPane, this , 1, 1, 0, 0, sizELASTIC, sizELASTIC, kEditTextWidth ); // CEditText will know about CTextDoc Rect margin; ::SetRect( &margin, 2,2,-2,-2); thePane -> ChangeSize( &margin, !kRedraw ); gDecorator -> PlaceNewWindow( itsWindow ); }
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Copyright (C) 2013 Laszlo Papp <lpapp@kde.org> ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** 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 The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/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 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include <qmath.h> static const double PI = 3.14159265358979323846264338327950288; class tst_QMath : public QObject { Q_OBJECT private slots: void fastSinCos(); void degreesToRadians_data(); void degreesToRadians(); void radiansToDegrees_data(); void radiansToDegrees(); void qNextPowerOfTwo32S_data(); void qNextPowerOfTwo32S(); void qNextPowerOfTwo64S_data(); void qNextPowerOfTwo64S(); void qNextPowerOfTwo32U_data(); void qNextPowerOfTwo32U(); void qNextPowerOfTwo64U_data(); void qNextPowerOfTwo64U(); }; void tst_QMath::fastSinCos() { // Test evenly spaced angles from 0 to 2pi radians. const int LOOP_COUNT = 100000; for (int i = 0; i < LOOP_COUNT; ++i) { qreal angle = i * 2 * PI / (LOOP_COUNT - 1); QVERIFY(qAbs(qSin(angle) - qFastSin(angle)) < 1e-5); QVERIFY(qAbs(qCos(angle) - qFastCos(angle)) < 1e-5); } } void tst_QMath::degreesToRadians_data() { QTest::addColumn<float>("degreesFloat"); QTest::addColumn<float>("radiansFloat"); QTest::addColumn<double>("degreesDouble"); QTest::addColumn<double>("radiansDouble"); QTest::newRow( "pi" ) << 180.0f << float(M_PI) << 180.0 << PI; QTest::newRow( "doublepi" ) << 360.0f << float(2*M_PI) << 360.0 << 2*PI; QTest::newRow( "halfpi" ) << 90.0f << float(M_PI_2) << 90.0 << PI/2; QTest::newRow( "random" ) << 123.1234567f << 2.1489097058516724f << 123.123456789123456789 << 2.148909707407169856192285627; QTest::newRow( "bigrandom" ) << 987654321.9876543f << 17237819.79023679f << 987654321987654321.987654321987654321 << 17237819790236794.0; QTest::newRow( "zero" ) << 0.0f << 0.0f << 0.0 << 0.0; QTest::newRow( "minuspi" ) << -180.0f << float(-M_PI) << 180.0 << PI; QTest::newRow( "minusdoublepi" ) << -360.0f << float(-2*M_PI) << -360.0 << -2*PI; QTest::newRow( "minushalfpi" ) << -90.0f << float(-M_PI_2) << -90.0 << -PI/2; QTest::newRow( "minusrandom" ) << -123.1234567f << -2.1489097058516724f << -123.123456789123456789 << -2.148909707407169856192285627; QTest::newRow( "minusbigrandom" ) << -987654321.9876543f << -17237819.79023679f << -987654321987654321.987654321987654321 << -17237819790236794.0; } void tst_QMath::degreesToRadians() { QFETCH(float, degreesFloat); QFETCH(float, radiansFloat); QFETCH(double, degreesDouble); QFETCH(double, radiansDouble); QCOMPARE(qDegreesToRadians(degreesFloat), radiansFloat); QCOMPARE(qDegreesToRadians(degreesDouble), radiansDouble); } void tst_QMath::radiansToDegrees_data() { QTest::addColumn<float>("radiansFloat"); QTest::addColumn<float>("degreesFloat"); QTest::addColumn<double>("radiansDouble"); QTest::addColumn<double>("degreesDouble"); QTest::newRow( "pi" ) << float(M_PI) << 180.0f << PI << 180.0; QTest::newRow( "doublepi" ) << float(2*M_PI) << 360.0f << 2*PI << 360.0; QTest::newRow( "halfpi" ) << float(M_PI_2) << 90.0f<< PI/2 << 90.0; QTest::newRow( "random" ) << 123.1234567f << 7054.454427971739f << 123.123456789123456789 << 7054.4544330781363896676339209079742431640625; QTest::newRow( "bigrandom" ) << 987654321.9876543f << 56588424267.74745f << 987654321987654321.987654321987654321 << 56588424267747450880.0; QTest::newRow( "zero" ) << 0.0f << 0.0f << 0.0 << 0.0; QTest::newRow( "minuspi" ) << float(-M_PI) << -180.0f << -PI << -180.0; QTest::newRow( "minusdoublepi" ) << float(-2*M_PI) << -360.0f << -2*PI << -360.0; QTest::newRow( "minushalfpi" ) << float(-M_PI_2) << -90.0f << -PI/2 << -90.0; QTest::newRow( "minusrandom" ) << -123.1234567f << -7054.454427971739f << -123.123456789123456789 << -7054.4544330781363896676339209079742431640625; QTest::newRow( "minusbigrandom" ) << -987654321.9876543f << -56588424267.74745f << -987654321987654321.987654321987654321 << -56588424267747450880.0; } void tst_QMath::radiansToDegrees() { QFETCH(float, radiansFloat); QFETCH(float, degreesFloat); QFETCH(double, radiansDouble); QFETCH(double, degreesDouble); QCOMPARE(qRadiansToDegrees(radiansFloat), degreesFloat); QCOMPARE(qRadiansToDegrees(radiansDouble), degreesDouble); } void tst_QMath::qNextPowerOfTwo32S_data() { QTest::addColumn<qint32>("input"); QTest::addColumn<quint32>("output"); QTest::newRow("0") << 0 << 1U; QTest::newRow("1") << 1 << 2U; QTest::newRow("2") << 2 << 4U; QTest::newRow("17") << 17 << 32U; QTest::newRow("128") << 128 << 256U; QTest::newRow("65535") << 65535 << 65536U; QTest::newRow("65536") << 65536 << 131072U; QTest::newRow("2^30") << (1 << 30) << (1U << 31); QTest::newRow("2^30 + 1") << (1 << 30) + 1 << (1U << 31); QTest::newRow("2^31 - 1") << 0x7FFFFFFF << (1U<<31); QTest::newRow("-1") << -1 << 0U; QTest::newRow("-128") << -128 << 0U; QTest::newRow("-(2^31)") << int(0x80000000) << 0U; } void tst_QMath::qNextPowerOfTwo32S() { QFETCH(qint32, input); QFETCH(quint32, output); QCOMPARE(qNextPowerOfTwo(input), output); } void tst_QMath::qNextPowerOfTwo32U_data() { QTest::addColumn<quint32>("input"); QTest::addColumn<quint32>("output"); QTest::newRow("0") << 0U << 1U; QTest::newRow("1") << 1U << 2U; QTest::newRow("2") << 2U << 4U; QTest::newRow("17") << 17U << 32U; QTest::newRow("128") << 128U << 256U; QTest::newRow("65535") << 65535U << 65536U; QTest::newRow("65536") << 65536U << 131072U; QTest::newRow("2^30") << (1U << 30) << (1U << 31); QTest::newRow("2^30 + 1") << (1U << 30) + 1 << (1U << 31); QTest::newRow("2^31 - 1") << 2147483647U << 2147483648U; QTest::newRow("2^31") << 2147483648U << 0U; QTest::newRow("2^31 + 1") << 2147483649U << 0U; } void tst_QMath::qNextPowerOfTwo32U() { QFETCH(quint32, input); QFETCH(quint32, output); QCOMPARE(qNextPowerOfTwo(input), output); } void tst_QMath::qNextPowerOfTwo64S_data() { QTest::addColumn<qint64>("input"); QTest::addColumn<quint64>("output"); QTest::newRow("0") << Q_INT64_C(0) << Q_UINT64_C(1); QTest::newRow("1") << Q_INT64_C(1) << Q_UINT64_C(2); QTest::newRow("2") << Q_INT64_C(2) << Q_UINT64_C(4); QTest::newRow("17") << Q_INT64_C(17) << Q_UINT64_C(32); QTest::newRow("128") << Q_INT64_C(128) << Q_UINT64_C(256); QTest::newRow("65535") << Q_INT64_C(65535) << Q_UINT64_C(65536); QTest::newRow("65536") << Q_INT64_C(65536) << Q_UINT64_C(131072); QTest::newRow("2^31 - 1") << Q_INT64_C(2147483647) << Q_UINT64_C(0x80000000); QTest::newRow("2^31") << Q_INT64_C(2147483648) << Q_UINT64_C(0x100000000); QTest::newRow("2^31 + 1") << Q_INT64_C(2147483649) << Q_UINT64_C(0x100000000); QTest::newRow("2^63 - 1") << Q_INT64_C(0x7FFFFFFFFFFFFFFF) << Q_UINT64_C(0x8000000000000000); QTest::newRow("-1") << Q_INT64_C(-1) << Q_UINT64_C(0); QTest::newRow("-128") << Q_INT64_C(-128) << Q_UINT64_C(0); QTest::newRow("-(2^31)") << -Q_INT64_C(0x80000000) << Q_UINT64_C(0); QTest::newRow("-(2^63)") << (qint64)Q_INT64_C(0x8000000000000000) << Q_UINT64_C(0); } void tst_QMath::qNextPowerOfTwo64S() { QFETCH(qint64, input); QFETCH(quint64, output); QCOMPARE(qNextPowerOfTwo(input), output); } void tst_QMath::qNextPowerOfTwo64U_data() { QTest::addColumn<quint64>("input"); QTest::addColumn<quint64>("output"); QTest::newRow("0") << Q_UINT64_C(0) << Q_UINT64_C(1); QTest::newRow("1") << Q_UINT64_C(1) << Q_UINT64_C(2); QTest::newRow("2") << Q_UINT64_C(2) << Q_UINT64_C(4); QTest::newRow("17") << Q_UINT64_C(17) << Q_UINT64_C(32); QTest::newRow("128") << Q_UINT64_C(128) << Q_UINT64_C(256); QTest::newRow("65535") << Q_UINT64_C(65535) << Q_UINT64_C(65536); QTest::newRow("65536") << Q_UINT64_C(65536) << Q_UINT64_C(131072); QTest::newRow("2^63 - 1") << Q_UINT64_C(0x7FFFFFFFFFFFFFFF) << Q_UINT64_C(0x8000000000000000); QTest::newRow("2^63") << Q_UINT64_C(0x8000000000000000) << Q_UINT64_C(0); QTest::newRow("2^63 + 1") << Q_UINT64_C(0x8000000000000001) << Q_UINT64_C(0); } void tst_QMath::qNextPowerOfTwo64U() { QFETCH(quint64, input); QFETCH(quint64, output); QCOMPARE(qNextPowerOfTwo(input), output); } QTEST_APPLESS_MAIN(tst_QMath) #include "tst_qmath.moc"
// Copyright 2016 The SwiftShader 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 "Blitter.hpp" #include "Pipeline/ShaderCore.hpp" #include "Reactor/Reactor.hpp" #include "System/CPUID.hpp" #include "System/Debug.hpp" #include "System/Half.hpp" #include "System/Memory.hpp" #include "Vulkan/VkBuffer.hpp" #include "Vulkan/VkImage.hpp" #include <utility> #if defined(__i386__) || defined(__x86_64__) # include <xmmintrin.h> # include <emmintrin.h> #endif namespace { rr::RValue<rr::Int> PackFields(rr::Int4 const &ints, const sw::int4 shifts) { return (rr::Int(ints.x) << shifts[0]) | (rr::Int(ints.y) << shifts[1]) | (rr::Int(ints.z) << shifts[2]) | (rr::Int(ints.w) << shifts[3]); } } // namespace namespace sw { Blitter::Blitter() : blitMutex() , blitCache(1024) , cornerUpdateMutex() , cornerUpdateCache(64) // We only need one of these per format { } Blitter::~Blitter() { } void Blitter::clear(void *pixel, vk::Format format, vk::Image *dest, const vk::Format &viewFormat, const VkImageSubresourceRange &subresourceRange, const VkRect2D *renderArea) { VkImageAspectFlagBits aspect = static_cast<VkImageAspectFlagBits>(subresourceRange.aspectMask); vk::Format dstFormat = viewFormat.getAspectFormat(aspect); if(dstFormat == VK_FORMAT_UNDEFINED) { return; } float *pPixel = static_cast<float *>(pixel); if(viewFormat.isUnsignedNormalized() || viewFormat.isSRGBformat()) { pPixel[0] = sw::clamp(pPixel[0], 0.0f, 1.0f); pPixel[1] = sw::clamp(pPixel[1], 0.0f, 1.0f); pPixel[2] = sw::clamp(pPixel[2], 0.0f, 1.0f); pPixel[3] = sw::clamp(pPixel[3], 0.0f, 1.0f); } else if(viewFormat.isSignedNormalized()) { pPixel[0] = sw::clamp(pPixel[0], -1.0f, 1.0f); pPixel[1] = sw::clamp(pPixel[1], -1.0f, 1.0f); pPixel[2] = sw::clamp(pPixel[2], -1.0f, 1.0f); pPixel[3] = sw::clamp(pPixel[3], -1.0f, 1.0f); } if(fastClear(pixel, format, dest, dstFormat, subresourceRange, renderArea)) { return; } State state(format, dstFormat, 1, dest->getSampleCountFlagBits(), Options{ 0xF }); auto blitRoutine = getBlitRoutine(state); if(!blitRoutine) { return; } VkImageSubresource subres = { subresourceRange.aspectMask, subresourceRange.baseMipLevel, subresourceRange.baseArrayLayer }; uint32_t lastMipLevel = dest->getLastMipLevel(subresourceRange); uint32_t lastLayer = dest->getLastLayerIndex(subresourceRange); VkRect2D area = { { 0, 0 }, { 0, 0 } }; if(renderArea) { ASSERT(subresourceRange.levelCount == 1); area = *renderArea; } for(; subres.mipLevel <= lastMipLevel; subres.mipLevel++) { VkExtent3D extent = dest->getMipLevelExtent(aspect, subres.mipLevel); if(!renderArea) { area.extent.width = extent.width; area.extent.height = extent.height; } BlitData data = { pixel, nullptr, // source, dest format.bytes(), // sPitchB dest->rowPitchBytes(aspect, subres.mipLevel), // dPitchB 0, // sSliceB (unused in clear operations) dest->slicePitchBytes(aspect, subres.mipLevel), // dSliceB 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 0.0f, // x0, y0, z0, w, h, d area.offset.x, static_cast<int>(area.offset.x + area.extent.width), // x0d, x1d area.offset.y, static_cast<int>(area.offset.y + area.extent.height), // y0d, y1d 0, 1, // z0d, z1d 0, 0, 0, // sWidth, sHeight, sDepth false, // filter3D }; if(renderArea && dest->is3DSlice()) { // Reinterpret layers as depth slices subres.arrayLayer = 0; for(uint32_t depth = subresourceRange.baseArrayLayer; depth <= lastLayer; depth++) { data.dest = dest->getTexelPointer({ 0, 0, static_cast<int32_t>(depth) }, subres); blitRoutine(&data); } } else { for(subres.arrayLayer = subresourceRange.baseArrayLayer; subres.arrayLayer <= lastLayer; subres.arrayLayer++) { for(uint32_t depth = 0; depth < extent.depth; depth++) { data.dest = dest->getTexelPointer({ 0, 0, static_cast<int32_t>(depth) }, subres); blitRoutine(&data); } } } } dest->contentsChanged(subresourceRange); } bool Blitter::fastClear(void *clearValue, vk::Format clearFormat, vk::Image *dest, const vk::Format &viewFormat, const VkImageSubresourceRange &subresourceRange, const VkRect2D *renderArea) { if(clearFormat != VK_FORMAT_R32G32B32A32_SFLOAT && clearFormat != VK_FORMAT_D32_SFLOAT && clearFormat != VK_FORMAT_S8_UINT) { return false; } union ClearValue { struct { float r; float g; float b; float a; }; float rgb[3]; float d; uint32_t d_as_u32; uint32_t s; }; ClearValue &c = *reinterpret_cast<ClearValue *>(clearValue); uint32_t packed = 0; VkImageAspectFlagBits aspect = static_cast<VkImageAspectFlagBits>(subresourceRange.aspectMask); switch(viewFormat) { case VK_FORMAT_R5G6B5_UNORM_PACK16: packed = ((uint16_t)(31 * c.b + 0.5f) << 0) | ((uint16_t)(63 * c.g + 0.5f) << 5) | ((uint16_t)(31 * c.r + 0.5f) << 11); break; case VK_FORMAT_B5G6R5_UNORM_PACK16: packed = ((uint16_t)(31 * c.r + 0.5f) << 0) | ((uint16_t)(63 * c.g + 0.5f) << 5) | ((uint16_t)(31 * c.b + 0.5f) << 11); break; case VK_FORMAT_A8B8G8R8_UINT_PACK32: case VK_FORMAT_A8B8G8R8_UNORM_PACK32: case VK_FORMAT_R8G8B8A8_UNORM: packed = ((uint32_t)(255 * c.a + 0.5f) << 24) | ((uint32_t)(255 * c.b + 0.5f) << 16) | ((uint32_t)(255 * c.g + 0.5f) << 8) | ((uint32_t)(255 * c.r + 0.5f) << 0); break; case VK_FORMAT_B8G8R8A8_UNORM: packed = ((uint32_t)(255 * c.a + 0.5f) << 24) | ((uint32_t)(255 * c.r + 0.5f) << 16) | ((uint32_t)(255 * c.g + 0.5f) << 8) | ((uint32_t)(255 * c.b + 0.5f) << 0); break; case VK_FORMAT_B10G11R11_UFLOAT_PACK32: packed = R11G11B10F(c.rgb); break; case VK_FORMAT_E5B9G9R9_UFLOAT_PACK32: packed = RGB9E5(c.rgb); break; case VK_FORMAT_D32_SFLOAT: ASSERT(clearFormat == VK_FORMAT_D32_SFLOAT); packed = c.d_as_u32; // float reinterpreted as uint32 break; case VK_FORMAT_S8_UINT: ASSERT(clearFormat == VK_FORMAT_S8_UINT); packed = static_cast<uint8_t>(c.s); break; default: return false; } VkImageSubresource subres = { subresourceRange.aspectMask, subresourceRange.baseMipLevel, subresourceRange.baseArrayLayer }; uint32_t lastMipLevel = dest->getLastMipLevel(subresourceRange); uint32_t lastLayer = dest->getLastLayerIndex(subresourceRange); VkRect2D area = { { 0, 0 }, { 0, 0 } }; if(renderArea) { ASSERT(subresourceRange.levelCount == 1); area = *renderArea; } for(; subres.mipLevel <= lastMipLevel; subres.mipLevel++) { int rowPitchBytes = dest->rowPitchBytes(aspect, subres.mipLevel); int slicePitchBytes = dest->slicePitchBytes(aspect, subres.mipLevel); VkExtent3D extent = dest->getMipLevelExtent(aspect, subres.mipLevel); if(!renderArea) { area.extent.width = extent.width; area.extent.height = extent.height; } if(dest->is3DSlice()) { extent.depth = 1; // The 3D image is instead interpreted as a 2D image with layers } for(subres.arrayLayer = subresourceRange.baseArrayLayer; subres.arrayLayer <= lastLayer; subres.arrayLayer++) { for(uint32_t depth = 0; depth < extent.depth; depth++) { uint8_t *slice = (uint8_t *)dest->getTexelPointer( { area.offset.x, area.offset.y, static_cast<int32_t>(depth) }, subres); for(int j = 0; j < dest->getSampleCountFlagBits(); j++) { uint8_t *d = slice; switch(viewFormat.bytes()) { case 4: for(uint32_t i = 0; i < area.extent.height; i++) { ASSERT(d < dest->end()); sw::clear((uint32_t *)d, packed, area.extent.width); d += rowPitchBytes; } break; case 2: for(uint32_t i = 0; i < area.extent.height; i++) { ASSERT(d < dest->end()); sw::clear((uint16_t *)d, static_cast<uint16_t>(packed), area.extent.width); d += rowPitchBytes; } break; case 1: for(uint32_t i = 0; i < area.extent.height; i++) { ASSERT(d < dest->end()); memset(d, packed, area.extent.width); d += rowPitchBytes; } break; default: assert(false); } slice += slicePitchBytes; } } } } dest->contentsChanged(subresourceRange); return true; } Float4 Blitter::readFloat4(Pointer<Byte> element, const State &state) { Float4 c(0.0f, 0.0f, 0.0f, 1.0f); switch(state.sourceFormat) { case VK_FORMAT_B4G4R4A4_UNORM_PACK16: c.w = Float(Int(*Pointer<Byte>(element)) & Int(0xF)); c.x = Float((Int(*Pointer<Byte>(element)) >> 4) & Int(0xF)); c.y = Float(Int(*Pointer<Byte>(element + 1)) & Int(0xF)); c.z = Float((Int(*Pointer<Byte>(element + 1)) >> 4) & Int(0xF)); break; case VK_FORMAT_R8_SINT: case VK_FORMAT_R8_SNORM: c.x = Float(Int(*Pointer<SByte>(element))); c.w = float(0x7F); break; case VK_FORMAT_R8_UNORM: case VK_FORMAT_R8_UINT: case VK_FORMAT_R8_SRGB: c.x = Float(Int(*Pointer<Byte>(element))); c.w = float(0xFF); break; case VK_FORMAT_R16_SINT: case VK_FORMAT_R16_SNORM: c.x = Float(Int(*Pointer<Short>(element))); c.w = float(0x7FFF); break; case VK_FORMAT_R16_UNORM: case VK_FORMAT_R16_UINT: c.x = Float(Int(*Pointer<UShort>(element))); c.w = float(0xFFFF); break; case VK_FORMAT_R32_SINT: c.x = Float(*Pointer<Int>(element)); c.w = float(0x7FFFFFFF); break; case VK_FORMAT_R32_UINT: c.x = Float(*Pointer<UInt>(element)); c.w = float(0xFFFFFFFF); break; case VK_FORMAT_B8G8R8A8_SRGB: case VK_FORMAT_B8G8R8A8_UNORM: c = Float4(*Pointer<Byte4>(element)).zyxw; break; case VK_FORMAT_A8B8G8R8_SINT_PACK32: case VK_FORMAT_R8G8B8A8_SINT: case VK_FORMAT_A8B8G8R8_SNORM_PACK32: case VK_FORMAT_R8G8B8A8_SNORM: c = Float4(*Pointer<SByte4>(element)); break; case VK_FORMAT_A8B8G8R8_UINT_PACK32: case VK_FORMAT_A8B8G8R8_UNORM_PACK32: case VK_FORMAT_R8G8B8A8_UNORM: case VK_FORMAT_R8G8B8A8_UINT: case VK_FORMAT_A8B8G8R8_SRGB_PACK32: case VK_FORMAT_R8G8B8A8_SRGB: c = Float4(*Pointer<Byte4>(element)); break; case VK_FORMAT_R16G16B16A16_SINT: case VK_FORMAT_R16G16B16A16_SNORM: c = Float4(*Pointer<Short4>(element)); break; case VK_FORMAT_R16G16B16A16_UNORM: case VK_FORMAT_R16G16B16A16_UINT: c = Float4(*Pointer<UShort4>(element)); break; case VK_FORMAT_R32G32B32A32_SINT: c = Float4(*Pointer<Int4>(element)); break; case VK_FORMAT_R32G32B32A32_UINT: c = Float4(*Pointer<UInt4>(element)); break; case VK_FORMAT_R8G8_SINT: case VK_FORMAT_R8G8_SNORM: c.x = Float(Int(*Pointer<SByte>(element + 0))); c.y = Float(Int(*Pointer<SByte>(element + 1))); c.w = float(0x7F); break; case VK_FORMAT_R8G8_UNORM: case VK_FORMAT_R8G8_UINT: case VK_FORMAT_R8G8_SRGB: c.x = Float(Int(*Pointer<Byte>(element + 0))); c.y = Float(Int(*Pointer<Byte>(element + 1))); c.w = float(0xFF); break; case VK_FORMAT_R16G16_SINT: case VK_FORMAT_R16G16_SNORM: c.x = Float(Int(*Pointer<Short>(element + 0))); c.y = Float(Int(*Pointer<Short>(element + 2))); c.w = float(0x7FFF); break; case VK_FORMAT_R16G16_UNORM: case VK_FORMAT_R16G16_UINT: c.x = Float(Int(*Pointer<UShort>(element + 0))); c.y = Float(Int(*Pointer<UShort>(element + 2))); c.w = float(0xFFFF); break; case VK_FORMAT_R32G32_SINT: c.x = Float(*Pointer<Int>(element + 0)); c.y = Float(*Pointer<Int>(element + 4)); c.w = float(0x7FFFFFFF); break; case VK_FORMAT_R32G32_UINT: c.x = Float(*Pointer<UInt>(element + 0)); c.y = Float(*Pointer<UInt>(element + 4)); c.w = float(0xFFFFFFFF); break; case VK_FORMAT_R32G32B32A32_SFLOAT: c = *Pointer<Float4>(element); break; case VK_FORMAT_R32G32_SFLOAT: c.x = *Pointer<Float>(element + 0); c.y = *Pointer<Float>(element + 4); break; case VK_FORMAT_R32_SFLOAT: c.x = *Pointer<Float>(element); break; case VK_FORMAT_R16G16B16A16_SFLOAT: c.w = Float(*Pointer<Half>(element + 6)); case VK_FORMAT_R16G16B16_SFLOAT: c.z = Float(*Pointer<Half>(element + 4)); case VK_FORMAT_R16G16_SFLOAT: c.y = Float(*Pointer<Half>(element + 2)); case VK_FORMAT_R16_SFLOAT: c.x = Float(*Pointer<Half>(element)); break; case VK_FORMAT_B10G11R11_UFLOAT_PACK32: c = r11g11b10Unpack(*Pointer<UInt>(element)); break; case VK_FORMAT_E5B9G9R9_UFLOAT_PACK32: // This type contains a common 5 bit exponent (E) and a 9 bit the mantissa for R, G and B. c.x = Float(*Pointer<UInt>(element) & UInt(0x000001FF)); // R's mantissa (bits 0-8) c.y = Float((*Pointer<UInt>(element) & UInt(0x0003FE00)) >> 9); // G's mantissa (bits 9-17) c.z = Float((*Pointer<UInt>(element) & UInt(0x07FC0000)) >> 18); // B's mantissa (bits 18-26) c *= Float4( // 2^E, using the exponent (bits 27-31) and treating it as an unsigned integer value Float(UInt(1) << ((*Pointer<UInt>(element) & UInt(0xF8000000)) >> 27)) * // Since the 9 bit mantissa values currently stored in RGB were converted straight // from int to float (in the [0, 1<<9] range instead of the [0, 1] range), they // are (1 << 9) times too high. // Also, the exponent has 5 bits and we compute the exponent bias of floating point // formats using "2^(k-1) - 1", so, in this case, the exponent bias is 2^(5-1)-1 = 15 // Exponent bias (15) + number of mantissa bits per component (9) = 24 Float(1.0f / (1 << 24))); c.w = 1.0f; break; case VK_FORMAT_R5G6B5_UNORM_PACK16: c.x = Float(Int((*Pointer<UShort>(element) & UShort(0xF800)) >> UShort(11))); c.y = Float(Int((*Pointer<UShort>(element) & UShort(0x07E0)) >> UShort(5))); c.z = Float(Int(*Pointer<UShort>(element) & UShort(0x001F))); break; case VK_FORMAT_A1R5G5B5_UNORM_PACK16: c.w = Float(Int((*Pointer<UShort>(element) & UShort(0x8000)) >> UShort(15))); c.x = Float(Int((*Pointer<UShort>(element) & UShort(0x7C00)) >> UShort(10))); c.y = Float(Int((*Pointer<UShort>(element) & UShort(0x03E0)) >> UShort(5))); c.z = Float(Int(*Pointer<UShort>(element) & UShort(0x001F))); break; case VK_FORMAT_A2B10G10R10_UNORM_PACK32: case VK_FORMAT_A2B10G10R10_UINT_PACK32: c.x = Float(Int((*Pointer<UInt>(element) & UInt(0x000003FF)))); c.y = Float(Int((*Pointer<UInt>(element) & UInt(0x000FFC00)) >> 10)); c.z = Float(Int((*Pointer<UInt>(element) & UInt(0x3FF00000)) >> 20)); c.w = Float(Int((*Pointer<UInt>(element) & UInt(0xC0000000)) >> 30)); break; case VK_FORMAT_A2R10G10B10_UNORM_PACK32: case VK_FORMAT_A2R10G10B10_UINT_PACK32: c.z = Float(Int((*Pointer<UInt>(element) & UInt(0x000003FF)))); c.y = Float(Int((*Pointer<UInt>(element) & UInt(0x000FFC00)) >> 10)); c.x = Float(Int((*Pointer<UInt>(element) & UInt(0x3FF00000)) >> 20)); c.w = Float(Int((*Pointer<UInt>(element) & UInt(0xC0000000)) >> 30)); break; case VK_FORMAT_D16_UNORM: c.x = Float(Int((*Pointer<UShort>(element)))); break; case VK_FORMAT_X8_D24_UNORM_PACK32: c.x = Float(Int((*Pointer<UInt>(element) & UInt(0xFFFFFF00)) >> 8)); break; case VK_FORMAT_D32_SFLOAT: c.x = *Pointer<Float>(element); break; case VK_FORMAT_S8_UINT: c.x = Float(Int(*Pointer<Byte>(element))); break; default: UNSUPPORTED("Blitter source format %d", (int)state.sourceFormat); } return c; } void Blitter::write(Float4 &c, Pointer<Byte> element, const State &state) { bool writeR = state.writeRed; bool writeG = state.writeGreen; bool writeB = state.writeBlue; bool writeA = state.writeAlpha; bool writeRGBA = writeR && writeG && writeB && writeA; switch(state.destFormat) { case VK_FORMAT_R4G4_UNORM_PACK8: if(writeR | writeG) { if(!writeR) { *Pointer<Byte>(element) = (Byte(RoundInt(Float(c.y))) & Byte(0xF)) | (*Pointer<Byte>(element) & Byte(0xF0)); } else if(!writeG) { *Pointer<Byte>(element) = (*Pointer<Byte>(element) & Byte(0xF)) | (Byte(RoundInt(Float(c.x))) << Byte(4)); } else { *Pointer<Byte>(element) = (Byte(RoundInt(Float(c.y))) & Byte(0xF)) | (Byte(RoundInt(Float(c.x))) << Byte(4)); } } break; case VK_FORMAT_R4G4B4A4_UNORM_PACK16: if(writeR || writeG || writeB || writeA) { *Pointer<UShort>(element) = (writeR ? ((UShort(RoundInt(Float(c.x))) & UShort(0xF)) << UShort(12)) : (*Pointer<UShort>(element) & UShort(0x000F))) | (writeG ? ((UShort(RoundInt(Float(c.y))) & UShort(0xF)) << UShort(8)) : (*Pointer<UShort>(element) & UShort(0x00F0))) | (writeB ? ((UShort(RoundInt(Float(c.z))) & UShort(0xF)) << UShort(4)) : (*Pointer<UShort>(element) & UShort(0x0F00))) | (writeA ? (UShort(RoundInt(Float(c.w))) & UShort(0xF)) : (*Pointer<UShort>(element) & UShort(0xF000))); } break; case VK_FORMAT_B4G4R4A4_UNORM_PACK16: if(writeRGBA) { *Pointer<UShort>(element) = UShort(RoundInt(Float(c.w)) & Int(0xF)) | UShort((RoundInt(Float(c.x)) & Int(0xF)) << 4) | UShort((RoundInt(Float(c.y)) & Int(0xF)) << 8) | UShort((RoundInt(Float(c.z)) & Int(0xF)) << 12); } else { unsigned short mask = (writeA ? 0x000F : 0x0000) | (writeR ? 0x00F0 : 0x0000) | (writeG ? 0x0F00 : 0x0000) | (writeB ? 0xF000 : 0x0000); unsigned short unmask = ~mask; *Pointer<UShort>(element) = (*Pointer<UShort>(element) & UShort(unmask)) | ((UShort(RoundInt(Float(c.w)) & Int(0xF)) | UShort((RoundInt(Float(c.x)) & Int(0xF)) << 4) | UShort((RoundInt(Float(c.y)) & Int(0xF)) << 8) | UShort((RoundInt(Float(c.z)) & Int(0xF)) << 12)) & UShort(mask)); } break; case VK_FORMAT_B8G8R8A8_SRGB: case VK_FORMAT_B8G8R8A8_UNORM: if(writeRGBA) { Short4 c0 = RoundShort4(c.zyxw); *Pointer<Byte4>(element) = Byte4(PackUnsigned(c0, c0)); } else { if(writeB) { *Pointer<Byte>(element + 0) = Byte(RoundInt(Float(c.z))); } if(writeG) { *Pointer<Byte>(element + 1) = Byte(RoundInt(Float(c.y))); } if(writeR) { *Pointer<Byte>(element + 2) = Byte(RoundInt(Float(c.x))); } if(writeA) { *Pointer<Byte>(element + 3) = Byte(RoundInt(Float(c.w))); } } break; case VK_FORMAT_B8G8R8_SNORM: if(writeB) { *Pointer<SByte>(element + 0) = SByte(RoundInt(Float(c.z))); } if(writeG) { *Pointer<SByte>(element + 1) = SByte(RoundInt(Float(c.y))); } if(writeR) { *Pointer<SByte>(element + 2) = SByte(RoundInt(Float(c.x))); } break; case VK_FORMAT_B8G8R8_UNORM: case VK_FORMAT_B8G8R8_SRGB: if(writeB) { *Pointer<Byte>(element + 0) = Byte(RoundInt(Float(c.z))); } if(writeG) { *Pointer<Byte>(element + 1) = Byte(RoundInt(Float(c.y))); } if(writeR) { *Pointer<Byte>(element + 2) = Byte(RoundInt(Float(c.x))); } break; case VK_FORMAT_A8B8G8R8_UNORM_PACK32: case VK_FORMAT_R8G8B8A8_UNORM: case VK_FORMAT_A8B8G8R8_SRGB_PACK32: case VK_FORMAT_R8G8B8A8_SRGB: case VK_FORMAT_A8B8G8R8_UINT_PACK32: case VK_FORMAT_R8G8B8A8_UINT: case VK_FORMAT_R8G8B8A8_USCALED: case VK_FORMAT_A8B8G8R8_USCALED_PACK32: if(writeRGBA) { Short4 c0 = RoundShort4(c); *Pointer<Byte4>(element) = Byte4(PackUnsigned(c0, c0)); } else { if(writeR) { *Pointer<Byte>(element + 0) = Byte(RoundInt(Float(c.x))); } if(writeG) { *Pointer<Byte>(element + 1) = Byte(RoundInt(Float(c.y))); } if(writeB) { *Pointer<Byte>(element + 2) = Byte(RoundInt(Float(c.z))); } if(writeA) { *Pointer<Byte>(element + 3) = Byte(RoundInt(Float(c.w))); } } break; case VK_FORMAT_R32G32B32A32_SFLOAT: if(writeRGBA) { *Pointer<Float4>(element) = c; } else { if(writeR) { *Pointer<Float>(element) = c.x; } if(writeG) { *Pointer<Float>(element + 4) = c.y; } if(writeB) { *Pointer<Float>(element + 8) = c.z; } if(writeA) { *Pointer<Float>(element + 12) = c.w; } } break; case VK_FORMAT_R32G32B32_SFLOAT: if(writeR) { *Pointer<Float>(element) = c.x; } if(writeG) { *Pointer<Float>(element + 4) = c.y; } if(writeB) { *Pointer<Float>(element + 8) = c.z; } break; case VK_FORMAT_R32G32_SFLOAT: if(writeR && writeG) { *Pointer<Float2>(element) = Float2(c); } else { if(writeR) { *Pointer<Float>(element) = c.x; } if(writeG) { *Pointer<Float>(element + 4) = c.y; } } break; case VK_FORMAT_R32_SFLOAT: if(writeR) { *Pointer<Float>(element) = c.x; } break; case VK_FORMAT_R16G16B16A16_SFLOAT: if(writeA) { *Pointer<Half>(element + 6) = Half(c.w); } // [[fallthrough]] case VK_FORMAT_R16G16B16_SFLOAT: if(writeB) { *Pointer<Half>(element + 4) = Half(c.z); } // [[fallthrough]] case VK_FORMAT_R16G16_SFLOAT: if(writeG) { *Pointer<Half>(element + 2) = Half(c.y); } // [[fallthrough]] case VK_FORMAT_R16_SFLOAT: if(writeR) { *Pointer<Half>(element) = Half(c.x); } break; case VK_FORMAT_B10G11R11_UFLOAT_PACK32: { UInt rgb = r11g11b10Pack(c); UInt old = *Pointer<UInt>(element); unsigned int mask = (writeR ? 0x000007FF : 0) | (writeG ? 0x003FF800 : 0) | (writeB ? 0xFFC00000 : 0); *Pointer<UInt>(element) = (rgb & mask) | (old & ~mask); } break; case VK_FORMAT_E5B9G9R9_UFLOAT_PACK32: { ASSERT(writeRGBA); // Can't sensibly write just part of this format. // Vulkan 1.1.117 section 15.2.1 RGB to Shared Exponent Conversion constexpr int N = 9; // number of mantissa bits per component constexpr int B = 15; // exponent bias constexpr int E_max = 31; // maximum possible biased exponent value // Maximum representable value. constexpr float sharedexp_max = ((static_cast<float>(1 << N) - 1) / static_cast<float>(1 << N)) * static_cast<float>(1 << (E_max - B)); // Clamp components to valid range. NaN becomes 0. Float red_c = Min(IfThenElse(!(c.x > 0), Float(0), Float(c.x)), sharedexp_max); Float green_c = Min(IfThenElse(!(c.y > 0), Float(0), Float(c.y)), sharedexp_max); Float blue_c = Min(IfThenElse(!(c.z > 0), Float(0), Float(c.z)), sharedexp_max); // We're reducing the mantissa to 9 bits, so we must round up if the next // bit is 1. In other words add 0.5 to the new mantissa's position and // allow overflow into the exponent so we can scale correctly. constexpr int half = 1 << (23 - N); Float red_r = As<Float>(As<Int>(red_c) + half); Float green_r = As<Float>(As<Int>(green_c) + half); Float blue_r = As<Float>(As<Int>(blue_c) + half); // The largest component determines the shared exponent. It can't be lower // than 0 (after bias subtraction) so also limit to the mimimum representable. constexpr float min_s = 0.5f / (1 << B); Float max_s = Max(Max(red_r, green_r), Max(blue_r, min_s)); // Obtain the reciprocal of the shared exponent by inverting the bits, // and scale by the new mantissa's size. Note that the IEEE-754 single-precision // format has an implicit leading 1, but this shared component format does not. Float scale = As<Float>((As<Int>(max_s) & 0x7F800000) ^ 0x7F800000) * (1 << (N - 2)); UInt R9 = RoundInt(red_c * scale); UInt G9 = UInt(RoundInt(green_c * scale)); UInt B9 = UInt(RoundInt(blue_c * scale)); UInt E5 = (As<UInt>(max_s) >> 23) - 127 + 15 + 1; UInt E5B9G9R9 = (E5 << 27) | (B9 << 18) | (G9 << 9) | R9; *Pointer<UInt>(element) = E5B9G9R9; } break; case VK_FORMAT_B8G8R8A8_SNORM: if(writeB) { *Pointer<SByte>(element) = SByte(RoundInt(Float(c.z))); } if(writeG) { *Pointer<SByte>(element + 1) = SByte(RoundInt(Float(c.y))); } if(writeR) { *Pointer<SByte>(element + 2) = SByte(RoundInt(Float(c.x))); } if(writeA) { *Pointer<SByte>(element + 3) = SByte(RoundInt(Float(c.w))); } break; case VK_FORMAT_A8B8G8R8_SINT_PACK32: case VK_FORMAT_R8G8B8A8_SINT: case VK_FORMAT_A8B8G8R8_SNORM_PACK32: case VK_FORMAT_R8G8B8A8_SNORM: case VK_FORMAT_R8G8B8A8_SSCALED: case VK_FORMAT_A8B8G8R8_SSCALED_PACK32: if(writeA) { *Pointer<SByte>(element + 3) = SByte(RoundInt(Float(c.w))); } // [[fallthrough]] case VK_FORMAT_R8G8B8_SINT: case VK_FORMAT_R8G8B8_SNORM: case VK_FORMAT_R8G8B8_SSCALED: if(writeB) { *Pointer<SByte>(element + 2) = SByte(RoundInt(Float(c.z))); } // [[fallthrough]] case VK_FORMAT_R8G8_SINT: case VK_FORMAT_R8G8_SNORM: case VK_FORMAT_R8G8_SSCALED: if(writeG) { *Pointer<SByte>(element + 1) = SByte(RoundInt(Float(c.y))); } // [[fallthrough]] case VK_FORMAT_R8_SINT: case VK_FORMAT_R8_SNORM: case VK_FORMAT_R8_SSCALED: if(writeR) { *Pointer<SByte>(element) = SByte(RoundInt(Float(c.x))); } break; case VK_FORMAT_R8G8B8_UINT: case VK_FORMAT_R8G8B8_UNORM: case VK_FORMAT_R8G8B8_USCALED: case VK_FORMAT_R8G8B8_SRGB: if(writeB) { *Pointer<Byte>(element + 2) = Byte(RoundInt(Float(c.z))); } // [[fallthrough]] case VK_FORMAT_R8G8_UINT: case VK_FORMAT_R8G8_UNORM: case VK_FORMAT_R8G8_USCALED: case VK_FORMAT_R8G8_SRGB: if(writeG) { *Pointer<Byte>(element + 1) = Byte(RoundInt(Float(c.y))); } // [[fallthrough]] case VK_FORMAT_R8_UINT: case VK_FORMAT_R8_UNORM: case VK_FORMAT_R8_USCALED: case VK_FORMAT_R8_SRGB: if(writeR) { *Pointer<Byte>(element) = Byte(RoundInt(Float(c.x))); } break; case VK_FORMAT_R16G16B16A16_SINT: case VK_FORMAT_R16G16B16A16_SNORM: case VK_FORMAT_R16G16B16A16_SSCALED: if(writeRGBA) { *Pointer<Short4>(element) = Short4(RoundInt(c)); } else { if(writeR) { *Pointer<Short>(element) = Short(RoundInt(Float(c.x))); } if(writeG) { *Pointer<Short>(element + 2) = Short(RoundInt(Float(c.y))); } if(writeB) { *Pointer<Short>(element + 4) = Short(RoundInt(Float(c.z))); } if(writeA) { *Pointer<Short>(element + 6) = Short(RoundInt(Float(c.w))); } } break; case VK_FORMAT_R16G16B16_SINT: case VK_FORMAT_R16G16B16_SNORM: case VK_FORMAT_R16G16B16_SSCALED: if(writeR) { *Pointer<Short>(element) = Short(RoundInt(Float(c.x))); } if(writeG) { *Pointer<Short>(element + 2) = Short(RoundInt(Float(c.y))); } if(writeB) { *Pointer<Short>(element + 4) = Short(RoundInt(Float(c.z))); } break; case VK_FORMAT_R16G16_SINT: case VK_FORMAT_R16G16_SNORM: case VK_FORMAT_R16G16_SSCALED: if(writeR && writeG) { *Pointer<Short2>(element) = Short2(Short4(RoundInt(c))); } else { if(writeR) { *Pointer<Short>(element) = Short(RoundInt(Float(c.x))); } if(writeG) { *Pointer<Short>(element + 2) = Short(RoundInt(Float(c.y))); } } break; case VK_FORMAT_R16_SINT: case VK_FORMAT_R16_SNORM: case VK_FORMAT_R16_SSCALED: if(writeR) { *Pointer<Short>(element) = Short(RoundInt(Float(c.x))); } break; case VK_FORMAT_R16G16B16A16_UINT: case VK_FORMAT_R16G16B16A16_UNORM: case VK_FORMAT_R16G16B16A16_USCALED: if(writeRGBA) { *Pointer<UShort4>(element) = UShort4(RoundInt(c)); } else { if(writeR) { *Pointer<UShort>(element) = UShort(RoundInt(Float(c.x))); } if(writeG) { *Pointer<UShort>(element + 2) = UShort(RoundInt(Float(c.y))); } if(writeB) { *Pointer<UShort>(element + 4) = UShort(RoundInt(Float(c.z))); } if(writeA) { *Pointer<UShort>(element + 6) = UShort(RoundInt(Float(c.w))); } } break; case VK_FORMAT_R16G16B16_UINT: case VK_FORMAT_R16G16B16_UNORM: case VK_FORMAT_R16G16B16_USCALED: if(writeR) { *Pointer<UShort>(element) = UShort(RoundInt(Float(c.x))); } if(writeG) { *Pointer<UShort>(element + 2) = UShort(RoundInt(Float(c.y))); } if(writeB) { *Pointer<UShort>(element + 4) = UShort(RoundInt(Float(c.z))); } break; case VK_FORMAT_R16G16_UINT: case VK_FORMAT_R16G16_UNORM: case VK_FORMAT_R16G16_USCALED: if(writeR && writeG) { *Pointer<UShort2>(element) = UShort2(UShort4(RoundInt(c))); } else { if(writeR) { *Pointer<UShort>(element) = UShort(RoundInt(Float(c.x))); } if(writeG) { *Pointer<UShort>(element + 2) = UShort(RoundInt(Float(c.y))); } } break; case VK_FORMAT_R16_UINT: case VK_FORMAT_R16_UNORM: case VK_FORMAT_R16_USCALED: if(writeR) { *Pointer<UShort>(element) = UShort(RoundInt(Float(c.x))); } break; case VK_FORMAT_R32G32B32A32_SINT: if(writeRGBA) { *Pointer<Int4>(element) = RoundInt(c); } else { if(writeR) { *Pointer<Int>(element) = RoundInt(Float(c.x)); } if(writeG) { *Pointer<Int>(element + 4) = RoundInt(Float(c.y)); } if(writeB) { *Pointer<Int>(element + 8) = RoundInt(Float(c.z)); } if(writeA) { *Pointer<Int>(element + 12) = RoundInt(Float(c.w)); } } break; case VK_FORMAT_R32G32B32_SINT: if(writeB) { *Pointer<Int>(element + 8) = RoundInt(Float(c.z)); } // [[fallthrough]] case VK_FORMAT_R32G32_SINT: if(writeG) { *Pointer<Int>(element + 4) = RoundInt(Float(c.y)); } // [[fallthrough]] case VK_FORMAT_R32_SINT: if(writeR) { *Pointer<Int>(element) = RoundInt(Float(c.x)); } break; case VK_FORMAT_R32G32B32A32_UINT: if(writeRGBA) { *Pointer<UInt4>(element) = UInt4(RoundInt(c)); } else { if(writeR) { *Pointer<UInt>(element) = As<UInt>(RoundInt(Float(c.x))); } if(writeG) { *Pointer<UInt>(element + 4) = As<UInt>(RoundInt(Float(c.y))); } if(writeB) { *Pointer<UInt>(element + 8) = As<UInt>(RoundInt(Float(c.z))); } if(writeA) { *Pointer<UInt>(element + 12) = As<UInt>(RoundInt(Float(c.w))); } } break; case VK_FORMAT_R32G32B32_UINT: if(writeB) { *Pointer<UInt>(element + 8) = As<UInt>(RoundInt(Float(c.z))); } // [[fallthrough]] case VK_FORMAT_R32G32_UINT: if(writeG) { *Pointer<UInt>(element + 4) = As<UInt>(RoundInt(Float(c.y))); } // [[fallthrough]] case VK_FORMAT_R32_UINT: if(writeR) { *Pointer<UInt>(element) = As<UInt>(RoundInt(Float(c.x))); } break; case VK_FORMAT_R5G6B5_UNORM_PACK16: if(writeR && writeG && writeB) { *Pointer<UShort>(element) = UShort(PackFields(RoundInt(c.xyzz), { 11, 5, 0, 0 })); } else { unsigned short mask = (writeB ? 0x001F : 0x0000) | (writeG ? 0x07E0 : 0x0000) | (writeR ? 0xF800 : 0x0000); unsigned short unmask = ~mask; *Pointer<UShort>(element) = (*Pointer<UShort>(element) & UShort(unmask)) | (UShort(PackFields(RoundInt(c.xyzz), { 11, 5, 0, 0 })) & UShort(mask)); } break; case VK_FORMAT_R5G5B5A1_UNORM_PACK16: if(writeRGBA) { *Pointer<UShort>(element) = UShort(PackFields(RoundInt(c), { 11, 6, 1, 0 })); } else { unsigned short mask = (writeA ? 0x8000 : 0x0000) | (writeR ? 0x7C00 : 0x0000) | (writeG ? 0x03E0 : 0x0000) | (writeB ? 0x001F : 0x0000); unsigned short unmask = ~mask; *Pointer<UShort>(element) = (*Pointer<UShort>(element) & UShort(unmask)) | (UShort(PackFields(RoundInt(c), { 11, 6, 1, 0 })) & UShort(mask)); } break; case VK_FORMAT_B5G5R5A1_UNORM_PACK16: if(writeRGBA) { *Pointer<UShort>(element) = UShort(PackFields(RoundInt(c), { 1, 6, 11, 0 })); } else { unsigned short mask = (writeA ? 0x8000 : 0x0000) | (writeR ? 0x7C00 : 0x0000) | (writeG ? 0x03E0 : 0x0000) | (writeB ? 0x001F : 0x0000); unsigned short unmask = ~mask; *Pointer<UShort>(element) = (*Pointer<UShort>(element) & UShort(unmask)) | (UShort(PackFields(RoundInt(c), { 1, 6, 11, 0 })) & UShort(mask)); } break; case VK_FORMAT_A1R5G5B5_UNORM_PACK16: if(writeRGBA) { *Pointer<UShort>(element) = UShort(PackFields(RoundInt(c), { 10, 5, 0, 15 })); } else { unsigned short mask = (writeA ? 0x8000 : 0x0000) | (writeR ? 0x7C00 : 0x0000) | (writeG ? 0x03E0 : 0x0000) | (writeB ? 0x001F : 0x0000); unsigned short unmask = ~mask; *Pointer<UShort>(element) = (*Pointer<UShort>(element) & UShort(unmask)) | (UShort(PackFields(RoundInt(c), { 10, 5, 0, 15 })) & UShort(mask)); } break; case VK_FORMAT_A2B10G10R10_UNORM_PACK32: case VK_FORMAT_A2B10G10R10_UINT_PACK32: case VK_FORMAT_A2B10G10R10_SNORM_PACK32: if(writeRGBA) { *Pointer<UInt>(element) = As<UInt>(PackFields(RoundInt(c), { 0, 10, 20, 30 })); } else { unsigned int mask = (writeA ? 0xC0000000 : 0x0000) | (writeB ? 0x3FF00000 : 0x0000) | (writeG ? 0x000FFC00 : 0x0000) | (writeR ? 0x000003FF : 0x0000); unsigned int unmask = ~mask; *Pointer<UInt>(element) = (*Pointer<UInt>(element) & UInt(unmask)) | (As<UInt>(PackFields(RoundInt(c), { 0, 10, 20, 30 })) & UInt(mask)); } break; case VK_FORMAT_A2R10G10B10_UNORM_PACK32: case VK_FORMAT_A2R10G10B10_UINT_PACK32: case VK_FORMAT_A2R10G10B10_SNORM_PACK32: if(writeRGBA) { *Pointer<UInt>(element) = As<UInt>(PackFields(RoundInt(c), { 20, 10, 0, 30 })); } else { unsigned int mask = (writeA ? 0xC0000000 : 0x0000) | (writeR ? 0x3FF00000 : 0x0000) | (writeG ? 0x000FFC00 : 0x0000) | (writeB ? 0x000003FF : 0x0000); unsigned int unmask = ~mask; *Pointer<UInt>(element) = (*Pointer<UInt>(element) & UInt(unmask)) | (As<UInt>(PackFields(RoundInt(c), { 20, 10, 0, 30 })) & UInt(mask)); } break; case VK_FORMAT_D16_UNORM: *Pointer<UShort>(element) = UShort(RoundInt(Float(c.x))); break; case VK_FORMAT_X8_D24_UNORM_PACK32: *Pointer<UInt>(element) = UInt(RoundInt(Float(c.x)) << 8); break; case VK_FORMAT_D32_SFLOAT: *Pointer<Float>(element) = c.x; break; case VK_FORMAT_S8_UINT: *Pointer<Byte>(element) = Byte(RoundInt(Float(c.x))); break; default: UNSUPPORTED("Blitter destination format %d", (int)state.destFormat); break; } } Int4 Blitter::readInt4(Pointer<Byte> element, const State &state) { Int4 c(0, 0, 0, 1); switch(state.sourceFormat) { case VK_FORMAT_A8B8G8R8_SINT_PACK32: case VK_FORMAT_R8G8B8A8_SINT: c = Insert(c, Int(*Pointer<SByte>(element + 3)), 3); c = Insert(c, Int(*Pointer<SByte>(element + 2)), 2); // [[fallthrough]] case VK_FORMAT_R8G8_SINT: c = Insert(c, Int(*Pointer<SByte>(element + 1)), 1); // [[fallthrough]] case VK_FORMAT_R8_SINT: c = Insert(c, Int(*Pointer<SByte>(element)), 0); break; case VK_FORMAT_A2B10G10R10_UINT_PACK32: c = Insert(c, Int((*Pointer<UInt>(element) & UInt(0x000003FF))), 0); c = Insert(c, Int((*Pointer<UInt>(element) & UInt(0x000FFC00)) >> 10), 1); c = Insert(c, Int((*Pointer<UInt>(element) & UInt(0x3FF00000)) >> 20), 2); c = Insert(c, Int((*Pointer<UInt>(element) & UInt(0xC0000000)) >> 30), 3); break; case VK_FORMAT_A2R10G10B10_UINT_PACK32: c = Insert(c, Int((*Pointer<UInt>(element) & UInt(0x000003FF))), 2); c = Insert(c, Int((*Pointer<UInt>(element) & UInt(0x000FFC00)) >> 10), 1); c = Insert(c, Int((*Pointer<UInt>(element) & UInt(0x3FF00000)) >> 20), 0); c = Insert(c, Int((*Pointer<UInt>(element) & UInt(0xC0000000)) >> 30), 3); break; case VK_FORMAT_A8B8G8R8_UINT_PACK32: case VK_FORMAT_R8G8B8A8_UINT: c = Insert(c, Int(*Pointer<Byte>(element + 3)), 3); c = Insert(c, Int(*Pointer<Byte>(element + 2)), 2); // [[fallthrough]] case VK_FORMAT_R8G8_UINT: c = Insert(c, Int(*Pointer<Byte>(element + 1)), 1); // [[fallthrough]] case VK_FORMAT_R8_UINT: case VK_FORMAT_S8_UINT: c = Insert(c, Int(*Pointer<Byte>(element)), 0); break; case VK_FORMAT_R16G16B16A16_SINT: c = Insert(c, Int(*Pointer<Short>(element + 6)), 3); c = Insert(c, Int(*Pointer<Short>(element + 4)), 2); // [[fallthrough]] case VK_FORMAT_R16G16_SINT: c = Insert(c, Int(*Pointer<Short>(element + 2)), 1); // [[fallthrough]] case VK_FORMAT_R16_SINT: c = Insert(c, Int(*Pointer<Short>(element)), 0); break; case VK_FORMAT_R16G16B16A16_UINT: c = Insert(c, Int(*Pointer<UShort>(element + 6)), 3); c = Insert(c, Int(*Pointer<UShort>(element + 4)), 2); // [[fallthrough]] case VK_FORMAT_R16G16_UINT: c = Insert(c, Int(*Pointer<UShort>(element + 2)), 1); // [[fallthrough]] case VK_FORMAT_R16_UINT: c = Insert(c, Int(*Pointer<UShort>(element)), 0); break; case VK_FORMAT_R32G32B32A32_SINT: case VK_FORMAT_R32G32B32A32_UINT: c = *Pointer<Int4>(element); break; case VK_FORMAT_R32G32_SINT: case VK_FORMAT_R32G32_UINT: c = Insert(c, *Pointer<Int>(element + 4), 1); // [[fallthrough]] case VK_FORMAT_R32_SINT: case VK_FORMAT_R32_UINT: c = Insert(c, *Pointer<Int>(element), 0); break; default: UNSUPPORTED("Blitter source format %d", (int)state.sourceFormat); } return c; } void Blitter::write(Int4 &c, Pointer<Byte> element, const State &state) { bool writeR = state.writeRed; bool writeG = state.writeGreen; bool writeB = state.writeBlue; bool writeA = state.writeAlpha; bool writeRGBA = writeR && writeG && writeB && writeA; switch(state.destFormat) { case VK_FORMAT_A2B10G10R10_UINT_PACK32: case VK_FORMAT_A2R10G10B10_UINT_PACK32: c = Min(As<UInt4>(c), UInt4(0x03FF, 0x03FF, 0x03FF, 0x0003)); break; case VK_FORMAT_A8B8G8R8_UINT_PACK32: case VK_FORMAT_R8G8B8A8_UINT: case VK_FORMAT_R8G8B8_UINT: case VK_FORMAT_R8G8_UINT: case VK_FORMAT_R8_UINT: case VK_FORMAT_R8G8B8A8_USCALED: case VK_FORMAT_R8G8B8_USCALED: case VK_FORMAT_R8G8_USCALED: case VK_FORMAT_R8_USCALED: case VK_FORMAT_S8_UINT: c = Min(As<UInt4>(c), UInt4(0xFF)); break; case VK_FORMAT_R16G16B16A16_UINT: case VK_FORMAT_R16G16B16_UINT: case VK_FORMAT_R16G16_UINT: case VK_FORMAT_R16_UINT: case VK_FORMAT_R16G16B16A16_USCALED: case VK_FORMAT_R16G16B16_USCALED: case VK_FORMAT_R16G16_USCALED: case VK_FORMAT_R16_USCALED: c = Min(As<UInt4>(c), UInt4(0xFFFF)); break; case VK_FORMAT_A8B8G8R8_SINT_PACK32: case VK_FORMAT_R8G8B8A8_SINT: case VK_FORMAT_R8G8_SINT: case VK_FORMAT_R8_SINT: case VK_FORMAT_R8G8B8A8_SSCALED: case VK_FORMAT_R8G8B8_SSCALED: case VK_FORMAT_R8G8_SSCALED: case VK_FORMAT_R8_SSCALED: c = Min(Max(c, Int4(-0x80)), Int4(0x7F)); break; case VK_FORMAT_R16G16B16A16_SINT: case VK_FORMAT_R16G16B16_SINT: case VK_FORMAT_R16G16_SINT: case VK_FORMAT_R16_SINT: case VK_FORMAT_R16G16B16A16_SSCALED: case VK_FORMAT_R16G16B16_SSCALED: case VK_FORMAT_R16G16_SSCALED: case VK_FORMAT_R16_SSCALED: c = Min(Max(c, Int4(-0x8000)), Int4(0x7FFF)); break; default: break; } switch(state.destFormat) { case VK_FORMAT_B8G8R8A8_SINT: case VK_FORMAT_B8G8R8A8_SSCALED: if(writeA) { *Pointer<SByte>(element + 3) = SByte(Extract(c, 3)); } // [[fallthrough]] case VK_FORMAT_B8G8R8_SINT: case VK_FORMAT_B8G8R8_SSCALED: if(writeB) { *Pointer<SByte>(element) = SByte(Extract(c, 2)); } if(writeG) { *Pointer<SByte>(element + 1) = SByte(Extract(c, 1)); } if(writeR) { *Pointer<SByte>(element + 2) = SByte(Extract(c, 0)); } break; case VK_FORMAT_A8B8G8R8_SINT_PACK32: case VK_FORMAT_R8G8B8A8_SINT: case VK_FORMAT_R8G8B8A8_SSCALED: case VK_FORMAT_A8B8G8R8_SSCALED_PACK32: if(writeA) { *Pointer<SByte>(element + 3) = SByte(Extract(c, 3)); } // [[fallthrough]] case VK_FORMAT_R8G8B8_SINT: case VK_FORMAT_R8G8B8_SSCALED: if(writeB) { *Pointer<SByte>(element + 2) = SByte(Extract(c, 2)); } // [[fallthrough]] case VK_FORMAT_R8G8_SINT: case VK_FORMAT_R8G8_SSCALED: if(writeG) { *Pointer<SByte>(element + 1) = SByte(Extract(c, 1)); } // [[fallthrough]] case VK_FORMAT_R8_SINT: case VK_FORMAT_R8_SSCALED: if(writeR) { *Pointer<SByte>(element) = SByte(Extract(c, 0)); } break; case VK_FORMAT_A2B10G10R10_UINT_PACK32: case VK_FORMAT_A2B10G10R10_SINT_PACK32: case VK_FORMAT_A2B10G10R10_USCALED_PACK32: case VK_FORMAT_A2B10G10R10_SSCALED_PACK32: if(writeRGBA) { *Pointer<UInt>(element) = As<UInt>(PackFields(c, { 0, 10, 20, 30 })); } else { unsigned int mask = (writeA ? 0xC0000000 : 0x0000) | (writeB ? 0x3FF00000 : 0x0000) | (writeG ? 0x000FFC00 : 0x0000) | (writeR ? 0x000003FF : 0x0000); unsigned int unmask = ~mask; *Pointer<UInt>(element) = (*Pointer<UInt>(element) & UInt(unmask)) | (As<UInt>(PackFields(c, { 0, 10, 20, 30 })) & UInt(mask)); } break; case VK_FORMAT_A2R10G10B10_UINT_PACK32: case VK_FORMAT_A2R10G10B10_SINT_PACK32: case VK_FORMAT_A2R10G10B10_USCALED_PACK32: case VK_FORMAT_A2R10G10B10_SSCALED_PACK32: if(writeRGBA) { *Pointer<UInt>(element) = As<UInt>(PackFields(c, { 20, 10, 0, 30 })); } else { unsigned int mask = (writeA ? 0xC0000000 : 0x0000) | (writeR ? 0x3FF00000 : 0x0000) | (writeG ? 0x000FFC00 : 0x0000) | (writeB ? 0x000003FF : 0x0000); unsigned int unmask = ~mask; *Pointer<UInt>(element) = (*Pointer<UInt>(element) & UInt(unmask)) | (As<UInt>(PackFields(c, { 20, 10, 0, 30 })) & UInt(mask)); } break; case VK_FORMAT_B8G8R8A8_UINT: case VK_FORMAT_B8G8R8A8_USCALED: if(writeA) { *Pointer<Byte>(element + 3) = Byte(Extract(c, 3)); } // [[fallthrough]] case VK_FORMAT_B8G8R8_UINT: case VK_FORMAT_B8G8R8_USCALED: case VK_FORMAT_B8G8R8_SRGB: if(writeB) { *Pointer<Byte>(element) = Byte(Extract(c, 2)); } if(writeG) { *Pointer<Byte>(element + 1) = Byte(Extract(c, 1)); } if(writeR) { *Pointer<Byte>(element + 2) = Byte(Extract(c, 0)); } break; case VK_FORMAT_A8B8G8R8_UINT_PACK32: case VK_FORMAT_R8G8B8A8_UINT: case VK_FORMAT_R8G8B8A8_USCALED: case VK_FORMAT_A8B8G8R8_USCALED_PACK32: if(writeA) { *Pointer<Byte>(element + 3) = Byte(Extract(c, 3)); } // [[fallthrough]] case VK_FORMAT_R8G8B8_UINT: case VK_FORMAT_R8G8B8_USCALED: if(writeB) { *Pointer<Byte>(element + 2) = Byte(Extract(c, 2)); } // [[fallthrough]] case VK_FORMAT_R8G8_UINT: case VK_FORMAT_R8G8_USCALED: if(writeG) { *Pointer<Byte>(element + 1) = Byte(Extract(c, 1)); } // [[fallthrough]] case VK_FORMAT_R8_UINT: case VK_FORMAT_R8_USCALED: case VK_FORMAT_S8_UINT: if(writeR) { *Pointer<Byte>(element) = Byte(Extract(c, 0)); } break; case VK_FORMAT_R16G16B16A16_SINT: case VK_FORMAT_R16G16B16A16_SSCALED: if(writeA) { *Pointer<Short>(element + 6) = Short(Extract(c, 3)); } // [[fallthrough]] case VK_FORMAT_R16G16B16_SINT: case VK_FORMAT_R16G16B16_SSCALED: if(writeB) { *Pointer<Short>(element + 4) = Short(Extract(c, 2)); } // [[fallthrough]] case VK_FORMAT_R16G16_SINT: case VK_FORMAT_R16G16_SSCALED: if(writeG) { *Pointer<Short>(element + 2) = Short(Extract(c, 1)); } // [[fallthrough]] case VK_FORMAT_R16_SINT: case VK_FORMAT_R16_SSCALED: if(writeR) { *Pointer<Short>(element) = Short(Extract(c, 0)); } break; case VK_FORMAT_R16G16B16A16_UINT: case VK_FORMAT_R16G16B16A16_USCALED: if(writeA) { *Pointer<UShort>(element + 6) = UShort(Extract(c, 3)); } // [[fallthrough]] case VK_FORMAT_R16G16B16_UINT: case VK_FORMAT_R16G16B16_USCALED: if(writeB) { *Pointer<UShort>(element + 4) = UShort(Extract(c, 2)); } // [[fallthrough]] case VK_FORMAT_R16G16_UINT: case VK_FORMAT_R16G16_USCALED: if(writeG) { *Pointer<UShort>(element + 2) = UShort(Extract(c, 1)); } // [[fallthrough]] case VK_FORMAT_R16_UINT: case VK_FORMAT_R16_USCALED: if(writeR) { *Pointer<UShort>(element) = UShort(Extract(c, 0)); } break; case VK_FORMAT_R32G32B32A32_SINT: if(writeRGBA) { *Pointer<Int4>(element) = c; } else { if(writeR) { *Pointer<Int>(element) = Extract(c, 0); } if(writeG) { *Pointer<Int>(element + 4) = Extract(c, 1); } if(writeB) { *Pointer<Int>(element + 8) = Extract(c, 2); } if(writeA) { *Pointer<Int>(element + 12) = Extract(c, 3); } } break; case VK_FORMAT_R32G32B32_SINT: if(writeR) { *Pointer<Int>(element) = Extract(c, 0); } if(writeG) { *Pointer<Int>(element + 4) = Extract(c, 1); } if(writeB) { *Pointer<Int>(element + 8) = Extract(c, 2); } break; case VK_FORMAT_R32G32_SINT: if(writeR) { *Pointer<Int>(element) = Extract(c, 0); } if(writeG) { *Pointer<Int>(element + 4) = Extract(c, 1); } break; case VK_FORMAT_R32_SINT: if(writeR) { *Pointer<Int>(element) = Extract(c, 0); } break; case VK_FORMAT_R32G32B32A32_UINT: if(writeRGBA) { *Pointer<UInt4>(element) = As<UInt4>(c); } else { if(writeR) { *Pointer<UInt>(element) = As<UInt>(Extract(c, 0)); } if(writeG) { *Pointer<UInt>(element + 4) = As<UInt>(Extract(c, 1)); } if(writeB) { *Pointer<UInt>(element + 8) = As<UInt>(Extract(c, 2)); } if(writeA) { *Pointer<UInt>(element + 12) = As<UInt>(Extract(c, 3)); } } break; case VK_FORMAT_R32G32B32_UINT: if(writeB) { *Pointer<UInt>(element + 8) = As<UInt>(Extract(c, 2)); } // [[fallthrough]] case VK_FORMAT_R32G32_UINT: if(writeG) { *Pointer<UInt>(element + 4) = As<UInt>(Extract(c, 1)); } // [[fallthrough]] case VK_FORMAT_R32_UINT: if(writeR) { *Pointer<UInt>(element) = As<UInt>(Extract(c, 0)); } break; default: UNSUPPORTED("Blitter destination format %d", (int)state.destFormat); } } void Blitter::ApplyScaleAndClamp(Float4 &value, const State &state, bool preScaled) { float4 scale{}, unscale{}; if(state.clearOperation && state.sourceFormat.isUnnormalizedInteger() && !state.destFormat.isUnnormalizedInteger()) { // If we're clearing a buffer from an int or uint color into a normalized color, // then the whole range of the int or uint color must be scaled between 0 and 1. switch(state.sourceFormat) { case VK_FORMAT_R32G32B32A32_SINT: unscale = float4(static_cast<float>(0x7FFFFFFF)); break; case VK_FORMAT_R32G32B32A32_UINT: unscale = float4(static_cast<float>(0xFFFFFFFF)); break; default: UNSUPPORTED("Blitter source format %d", (int)state.sourceFormat); } } else { unscale = state.sourceFormat.getScale(); } scale = state.destFormat.getScale(); bool srcSRGB = state.sourceFormat.isSRGBformat(); bool dstSRGB = state.destFormat.isSRGBformat(); if(state.allowSRGBConversion && ((srcSRGB && !preScaled) || dstSRGB)) // One of the formats is sRGB encoded. { value *= preScaled ? Float4(1.0f / scale.x, 1.0f / scale.y, 1.0f / scale.z, 1.0f / scale.w) : // Unapply scale Float4(1.0f / unscale.x, 1.0f / unscale.y, 1.0f / unscale.z, 1.0f / unscale.w); // Apply unscale value = (srcSRGB && !preScaled) ? sRGBtoLinear(value) : LinearToSRGB(value); value *= Float4(scale.x, scale.y, scale.z, scale.w); // Apply scale } else if(unscale != scale) { value *= Float4(scale.x / unscale.x, scale.y / unscale.y, scale.z / unscale.z, scale.w / unscale.w); } if(state.sourceFormat.isFloatFormat() && !state.destFormat.isFloatFormat()) { value = Min(value, Float4(scale.x, scale.y, scale.z, scale.w)); value = Max(value, Float4(state.destFormat.isUnsignedComponent(0) ? 0.0f : -scale.x, state.destFormat.isUnsignedComponent(1) ? 0.0f : -scale.y, state.destFormat.isUnsignedComponent(2) ? 0.0f : -scale.z, state.destFormat.isUnsignedComponent(3) ? 0.0f : -scale.w)); } } Int Blitter::ComputeOffset(Int &x, Int &y, Int &pitchB, int bytes) { return y * pitchB + x * bytes; } Int Blitter::ComputeOffset(Int &x, Int &y, Int &z, Int &sliceB, Int &pitchB, int bytes) { return z * sliceB + y * pitchB + x * bytes; } Float4 Blitter::LinearToSRGB(const Float4 &c) { Float4 lc = Min(c, Float4(0.0031308f)) * Float4(12.92f); Float4 ec = Float4(1.055f) * power(c, Float4(1.0f / 2.4f)) - Float4(0.055f); Float4 s = c; s.xyz = Max(lc, ec); return s; } Float4 Blitter::sRGBtoLinear(const Float4 &c) { Float4 lc = c * Float4(1.0f / 12.92f); Float4 ec = power((c + Float4(0.055f)) * Float4(1.0f / 1.055f), Float4(2.4f)); Int4 linear = CmpLT(c, Float4(0.04045f)); Float4 s = c; s.xyz = As<Float4>((linear & As<Int4>(lc)) | (~linear & As<Int4>(ec))); // TODO: IfThenElse() return s; } Float4 Blitter::sample(Pointer<Byte> &source, Float &x, Float &y, Float &z, Int &sWidth, Int &sHeight, Int &sDepth, Int &sSliceB, Int &sPitchB, const State &state) { bool intSrc = state.sourceFormat.isUnnormalizedInteger(); int srcBytes = state.sourceFormat.bytes(); Float4 color; bool preScaled = false; if(!state.filter || intSrc) { Int X = Int(x); Int Y = Int(y); Int Z = Int(z); if(state.clampToEdge) { X = Clamp(X, 0, sWidth - 1); Y = Clamp(Y, 0, sHeight - 1); Z = Clamp(Z, 0, sDepth - 1); } Pointer<Byte> s = source + ComputeOffset(X, Y, Z, sSliceB, sPitchB, srcBytes); color = readFloat4(s, state); if(state.srcSamples > 1) // Resolve multisampled source { if(state.allowSRGBConversion && state.sourceFormat.isSRGBformat()) // sRGB -> RGB { ApplyScaleAndClamp(color, state); preScaled = true; } Float4 accum = color; for(int sample = 1; sample < state.srcSamples; sample++) { s += sSliceB; color = readFloat4(s, state); if(state.allowSRGBConversion && state.sourceFormat.isSRGBformat()) // sRGB -> RGB { ApplyScaleAndClamp(color, state); preScaled = true; } accum += color; } color = accum * Float4(1.0f / static_cast<float>(state.srcSamples)); } } else // Bilinear filtering { Float X = x; Float Y = y; Float Z = z; if(state.clampToEdge) { X = Min(Max(x, 0.5f), Float(sWidth) - 0.5f); Y = Min(Max(y, 0.5f), Float(sHeight) - 0.5f); Z = Min(Max(z, 0.5f), Float(sDepth) - 0.5f); } Float x0 = X - 0.5f; Float y0 = Y - 0.5f; Float z0 = Z - 0.5f; Int X0 = Max(Int(x0), 0); Int Y0 = Max(Int(y0), 0); Int Z0 = Max(Int(z0), 0); Int X1 = X0 + 1; Int Y1 = Y0 + 1; X1 = IfThenElse(X1 >= sWidth, X0, X1); Y1 = IfThenElse(Y1 >= sHeight, Y0, Y1); if(state.filter3D) { Int Z1 = Z0 + 1; Z1 = IfThenElse(Z1 >= sHeight, Z0, Z1); Pointer<Byte> s000 = source + ComputeOffset(X0, Y0, Z0, sSliceB, sPitchB, srcBytes); Pointer<Byte> s010 = source + ComputeOffset(X1, Y0, Z0, sSliceB, sPitchB, srcBytes); Pointer<Byte> s100 = source + ComputeOffset(X0, Y1, Z0, sSliceB, sPitchB, srcBytes); Pointer<Byte> s110 = source + ComputeOffset(X1, Y1, Z0, sSliceB, sPitchB, srcBytes); Pointer<Byte> s001 = source + ComputeOffset(X0, Y0, Z1, sSliceB, sPitchB, srcBytes); Pointer<Byte> s011 = source + ComputeOffset(X1, Y0, Z1, sSliceB, sPitchB, srcBytes); Pointer<Byte> s101 = source + ComputeOffset(X0, Y1, Z1, sSliceB, sPitchB, srcBytes); Pointer<Byte> s111 = source + ComputeOffset(X1, Y1, Z1, sSliceB, sPitchB, srcBytes); Float4 c000 = readFloat4(s000, state); Float4 c010 = readFloat4(s010, state); Float4 c100 = readFloat4(s100, state); Float4 c110 = readFloat4(s110, state); Float4 c001 = readFloat4(s001, state); Float4 c011 = readFloat4(s011, state); Float4 c101 = readFloat4(s101, state); Float4 c111 = readFloat4(s111, state); if(state.allowSRGBConversion && state.sourceFormat.isSRGBformat()) // sRGB -> RGB { ApplyScaleAndClamp(c000, state); ApplyScaleAndClamp(c010, state); ApplyScaleAndClamp(c100, state); ApplyScaleAndClamp(c110, state); ApplyScaleAndClamp(c001, state); ApplyScaleAndClamp(c011, state); ApplyScaleAndClamp(c101, state); ApplyScaleAndClamp(c111, state); preScaled = true; } Float4 fx = Float4(x0 - Float(X0)); Float4 fy = Float4(y0 - Float(Y0)); Float4 fz = Float4(z0 - Float(Z0)); Float4 ix = Float4(1.0f) - fx; Float4 iy = Float4(1.0f) - fy; Float4 iz = Float4(1.0f) - fz; color = ((c000 * ix + c010 * fx) * iy + (c100 * ix + c110 * fx) * fy) * iz + ((c001 * ix + c011 * fx) * iy + (c101 * ix + c111 * fx) * fy) * fz; } else { Pointer<Byte> s00 = source + ComputeOffset(X0, Y0, Z0, sSliceB, sPitchB, srcBytes); Pointer<Byte> s01 = source + ComputeOffset(X1, Y0, Z0, sSliceB, sPitchB, srcBytes); Pointer<Byte> s10 = source + ComputeOffset(X0, Y1, Z0, sSliceB, sPitchB, srcBytes); Pointer<Byte> s11 = source + ComputeOffset(X1, Y1, Z0, sSliceB, sPitchB, srcBytes); Float4 c00 = readFloat4(s00, state); Float4 c01 = readFloat4(s01, state); Float4 c10 = readFloat4(s10, state); Float4 c11 = readFloat4(s11, state); if(state.allowSRGBConversion && state.sourceFormat.isSRGBformat()) // sRGB -> RGB { ApplyScaleAndClamp(c00, state); ApplyScaleAndClamp(c01, state); ApplyScaleAndClamp(c10, state); ApplyScaleAndClamp(c11, state); preScaled = true; } Float4 fx = Float4(x0 - Float(X0)); Float4 fy = Float4(y0 - Float(Y0)); Float4 ix = Float4(1.0f) - fx; Float4 iy = Float4(1.0f) - fy; color = (c00 * ix + c01 * fx) * iy + (c10 * ix + c11 * fx) * fy; } } ApplyScaleAndClamp(color, state, preScaled); return color; } Blitter::BlitRoutineType Blitter::generate(const State &state) { BlitFunction function; { Pointer<Byte> blit(function.Arg<0>()); Pointer<Byte> source = *Pointer<Pointer<Byte>>(blit + OFFSET(BlitData, source)); Pointer<Byte> dest = *Pointer<Pointer<Byte>>(blit + OFFSET(BlitData, dest)); Int sPitchB = *Pointer<Int>(blit + OFFSET(BlitData, sPitchB)); Int dPitchB = *Pointer<Int>(blit + OFFSET(BlitData, dPitchB)); Int sSliceB = *Pointer<Int>(blit + OFFSET(BlitData, sSliceB)); Int dSliceB = *Pointer<Int>(blit + OFFSET(BlitData, dSliceB)); Float x0 = *Pointer<Float>(blit + OFFSET(BlitData, x0)); Float y0 = *Pointer<Float>(blit + OFFSET(BlitData, y0)); Float z0 = *Pointer<Float>(blit + OFFSET(BlitData, z0)); Float w = *Pointer<Float>(blit + OFFSET(BlitData, w)); Float h = *Pointer<Float>(blit + OFFSET(BlitData, h)); Float d = *Pointer<Float>(blit + OFFSET(BlitData, d)); Int x0d = *Pointer<Int>(blit + OFFSET(BlitData, x0d)); Int x1d = *Pointer<Int>(blit + OFFSET(BlitData, x1d)); Int y0d = *Pointer<Int>(blit + OFFSET(BlitData, y0d)); Int y1d = *Pointer<Int>(blit + OFFSET(BlitData, y1d)); Int z0d = *Pointer<Int>(blit + OFFSET(BlitData, z0d)); Int z1d = *Pointer<Int>(blit + OFFSET(BlitData, z1d)); Int sWidth = *Pointer<Int>(blit + OFFSET(BlitData, sWidth)); Int sHeight = *Pointer<Int>(blit + OFFSET(BlitData, sHeight)); Int sDepth = *Pointer<Int>(blit + OFFSET(BlitData, sDepth)); bool intSrc = state.sourceFormat.isUnnormalizedInteger(); bool intDst = state.destFormat.isUnnormalizedInteger(); bool intBoth = intSrc && intDst; int srcBytes = state.sourceFormat.bytes(); int dstBytes = state.destFormat.bytes(); bool hasConstantColorI = false; Int4 constantColorI; bool hasConstantColorF = false; Float4 constantColorF; if(state.clearOperation) { if(intBoth) // Integer types { constantColorI = readInt4(source, state); hasConstantColorI = true; } else { constantColorF = readFloat4(source, state); hasConstantColorF = true; ApplyScaleAndClamp(constantColorF, state); } } For(Int k = z0d, k < z1d, k++) { Float z = state.clearOperation ? RValue<Float>(z0) : z0 + Float(k) * d; Pointer<Byte> destSlice = dest + k * dSliceB; For(Int j = y0d, j < y1d, j++) { Float y = state.clearOperation ? RValue<Float>(y0) : y0 + Float(j) * h; Pointer<Byte> destLine = destSlice + j * dPitchB; For(Int i = x0d, i < x1d, i++) { Float x = state.clearOperation ? RValue<Float>(x0) : x0 + Float(i) * w; Pointer<Byte> d = destLine + i * dstBytes; if(hasConstantColorI) { for(int s = 0; s < state.destSamples; s++) { write(constantColorI, d, state); d += dSliceB; } } else if(hasConstantColorF) { for(int s = 0; s < state.destSamples; s++) { write(constantColorF, d, state); d += dSliceB; } } else if(intBoth) // Integer types do not support filtering { Int X = Int(x); Int Y = Int(y); Int Z = Int(z); if(state.clampToEdge) { X = Clamp(X, 0, sWidth - 1); Y = Clamp(Y, 0, sHeight - 1); Z = Clamp(Z, 0, sDepth - 1); } Pointer<Byte> s = source + ComputeOffset(X, Y, Z, sSliceB, sPitchB, srcBytes); // When both formats are true integer types, we don't go to float to avoid losing precision Int4 color = readInt4(s, state); for(int s = 0; s < state.destSamples; s++) { write(color, d, state); d += dSliceB; } } else { Float4 color = sample(source, x, y, z, sWidth, sHeight, sDepth, sSliceB, sPitchB, state); for(int s = 0; s < state.destSamples; s++) { write(color, d, state); d += dSliceB; } } } } } } return function("BlitRoutine"); } Blitter::BlitRoutineType Blitter::getBlitRoutine(const State &state) { marl::lock lock(blitMutex); auto blitRoutine = blitCache.lookup(state); if(!blitRoutine) { blitRoutine = generate(state); blitCache.add(state, blitRoutine); } return blitRoutine; } Blitter::CornerUpdateRoutineType Blitter::getCornerUpdateRoutine(const State &state) { marl::lock lock(cornerUpdateMutex); auto cornerUpdateRoutine = cornerUpdateCache.lookup(state); if(!cornerUpdateRoutine) { cornerUpdateRoutine = generateCornerUpdate(state); cornerUpdateCache.add(state, cornerUpdateRoutine); } return cornerUpdateRoutine; } void Blitter::blit(const vk::Image *src, vk::Image *dst, VkImageBlit region, VkFilter filter) { ASSERT(src->getFormat() != VK_FORMAT_UNDEFINED); ASSERT(dst->getFormat() != VK_FORMAT_UNDEFINED); // Vulkan 1.2 section 18.5. Image Copies with Scaling: // "The layerCount member of srcSubresource and dstSubresource must match" // "The aspectMask member of srcSubresource and dstSubresource must match" ASSERT(region.srcSubresource.layerCount == region.dstSubresource.layerCount); ASSERT(region.srcSubresource.aspectMask == region.dstSubresource.aspectMask); if(region.dstOffsets[0].x > region.dstOffsets[1].x) { std::swap(region.srcOffsets[0].x, region.srcOffsets[1].x); std::swap(region.dstOffsets[0].x, region.dstOffsets[1].x); } if(region.dstOffsets[0].y > region.dstOffsets[1].y) { std::swap(region.srcOffsets[0].y, region.srcOffsets[1].y); std::swap(region.dstOffsets[0].y, region.dstOffsets[1].y); } if(region.dstOffsets[0].z > region.dstOffsets[1].z) { std::swap(region.srcOffsets[0].z, region.srcOffsets[1].z); std::swap(region.dstOffsets[0].z, region.dstOffsets[1].z); } VkImageAspectFlagBits srcAspect = static_cast<VkImageAspectFlagBits>(region.srcSubresource.aspectMask); VkImageAspectFlagBits dstAspect = static_cast<VkImageAspectFlagBits>(region.dstSubresource.aspectMask); VkExtent3D srcExtent = src->getMipLevelExtent(srcAspect, region.srcSubresource.mipLevel); float widthRatio = static_cast<float>(region.srcOffsets[1].x - region.srcOffsets[0].x) / static_cast<float>(region.dstOffsets[1].x - region.dstOffsets[0].x); float heightRatio = static_cast<float>(region.srcOffsets[1].y - region.srcOffsets[0].y) / static_cast<float>(region.dstOffsets[1].y - region.dstOffsets[0].y); float depthRatio = static_cast<float>(region.srcOffsets[1].z - region.srcOffsets[0].z) / static_cast<float>(region.dstOffsets[1].z - region.dstOffsets[0].z); float x0 = region.srcOffsets[0].x + (0.5f - region.dstOffsets[0].x) * widthRatio; float y0 = region.srcOffsets[0].y + (0.5f - region.dstOffsets[0].y) * heightRatio; float z0 = region.srcOffsets[0].z + (0.5f - region.dstOffsets[0].z) * depthRatio; auto srcFormat = src->getFormat(srcAspect); auto dstFormat = dst->getFormat(dstAspect); bool doFilter = (filter != VK_FILTER_NEAREST); bool allowSRGBConversion = doFilter || (src->getSampleCountFlagBits() > 1) || (srcFormat.isSRGBformat() != dstFormat.isSRGBformat()); State state(src->getFormat(srcAspect), dst->getFormat(dstAspect), src->getSampleCountFlagBits(), dst->getSampleCountFlagBits(), Options{ doFilter, allowSRGBConversion }); state.clampToEdge = (region.srcOffsets[0].x < 0) || (region.srcOffsets[0].y < 0) || (static_cast<uint32_t>(region.srcOffsets[1].x) > srcExtent.width) || (static_cast<uint32_t>(region.srcOffsets[1].y) > srcExtent.height) || (doFilter && ((x0 < 0.5f) || (y0 < 0.5f))); state.filter3D = (region.srcOffsets[1].z - region.srcOffsets[0].z) != (region.dstOffsets[1].z - region.dstOffsets[0].z); auto blitRoutine = getBlitRoutine(state); if(!blitRoutine) { return; } BlitData data = { nullptr, // source nullptr, // dest src->rowPitchBytes(srcAspect, region.srcSubresource.mipLevel), // sPitchB dst->rowPitchBytes(dstAspect, region.dstSubresource.mipLevel), // dPitchB src->slicePitchBytes(srcAspect, region.srcSubresource.mipLevel), // sSliceB dst->slicePitchBytes(dstAspect, region.dstSubresource.mipLevel), // dSliceB x0, y0, z0, widthRatio, heightRatio, depthRatio, region.dstOffsets[0].x, // x0d region.dstOffsets[1].x, // x1d region.dstOffsets[0].y, // y0d region.dstOffsets[1].y, // y1d region.dstOffsets[0].z, // z0d region.dstOffsets[1].z, // z1d static_cast<int>(srcExtent.width), // sWidth static_cast<int>(srcExtent.height), // sHeight static_cast<int>(srcExtent.depth), // sDepth false, // filter3D }; VkImageSubresource srcSubres = { region.srcSubresource.aspectMask, region.srcSubresource.mipLevel, region.srcSubresource.baseArrayLayer }; VkImageSubresource dstSubres = { region.dstSubresource.aspectMask, region.dstSubresource.mipLevel, region.dstSubresource.baseArrayLayer }; VkImageSubresourceRange dstSubresRange = { region.dstSubresource.aspectMask, region.dstSubresource.mipLevel, 1, // levelCount region.dstSubresource.baseArrayLayer, region.dstSubresource.layerCount }; uint32_t lastLayer = src->getLastLayerIndex(dstSubresRange); for(; dstSubres.arrayLayer <= lastLayer; srcSubres.arrayLayer++, dstSubres.arrayLayer++) { data.source = src->getTexelPointer({ 0, 0, 0 }, srcSubres); data.dest = dst->getTexelPointer({ 0, 0, 0 }, dstSubres); ASSERT(data.source < src->end()); ASSERT(data.dest < dst->end()); blitRoutine(&data); } dst->contentsChanged(dstSubresRange); } void Blitter::resolve(const vk::Image *src, vk::Image *dst, VkImageResolve region) { // "The aspectMask member of srcSubresource and dstSubresource must only contain VK_IMAGE_ASPECT_COLOR_BIT" ASSERT(region.srcSubresource.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT); ASSERT(region.dstSubresource.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT); // "The layerCount member of srcSubresource and dstSubresource must match" ASSERT(region.srcSubresource.layerCount == region.dstSubresource.layerCount); // We use this method both for explicit resolves from vkCmdResolveImage, and implicit ones for resolve attachments. // - vkCmdResolveImage: "srcImage and dstImage must have been created with the same image format." // - VkSubpassDescription: "each resolve attachment that is not VK_ATTACHMENT_UNUSED must have the same VkFormat as its corresponding color attachment." ASSERT(src->getFormat() == dst->getFormat()); if(fastResolve(src, dst, region)) { return; } // Fall back to a generic blit which performs the resolve. VkImageBlit blitRegion; blitRegion.srcOffsets[0] = blitRegion.srcOffsets[1] = region.srcOffset; blitRegion.srcOffsets[1].x += region.extent.width; blitRegion.srcOffsets[1].y += region.extent.height; blitRegion.srcOffsets[1].z += region.extent.depth; blitRegion.dstOffsets[0] = blitRegion.dstOffsets[1] = region.dstOffset; blitRegion.dstOffsets[1].x += region.extent.width; blitRegion.dstOffsets[1].y += region.extent.height; blitRegion.dstOffsets[1].z += region.extent.depth; blitRegion.srcSubresource = region.srcSubresource; blitRegion.dstSubresource = region.dstSubresource; blit(src, dst, blitRegion, VK_FILTER_NEAREST); } static inline uint32_t averageByte4(uint32_t x, uint32_t y) { return (x & y) + (((x ^ y) >> 1) & 0x7F7F7F7F) + ((x ^ y) & 0x01010101); } bool Blitter::fastResolve(const vk::Image *src, vk::Image *dst, VkImageResolve region) { if(region.dstOffset != VkOffset3D{ 0, 0, 0 }) { return false; } if(region.srcOffset != VkOffset3D{ 0, 0, 0 }) { return false; } if(region.srcSubresource.layerCount != 1) { return false; } if(region.extent != src->getExtent() || region.extent != dst->getExtent() || region.extent.depth != 1) { return false; } VkImageSubresource srcSubresource = { region.srcSubresource.aspectMask, region.srcSubresource.mipLevel, region.srcSubresource.baseArrayLayer }; VkImageSubresource dstSubresource = { region.dstSubresource.aspectMask, region.dstSubresource.mipLevel, region.dstSubresource.baseArrayLayer }; VkImageSubresourceRange dstSubresourceRange = { region.dstSubresource.aspectMask, region.dstSubresource.mipLevel, 1, // levelCount region.dstSubresource.baseArrayLayer, region.dstSubresource.layerCount }; void *source = src->getTexelPointer({ 0, 0, 0 }, srcSubresource); uint8_t *dest = reinterpret_cast<uint8_t *>(dst->getTexelPointer({ 0, 0, 0 }, dstSubresource)); auto format = src->getFormat(); auto samples = src->getSampleCountFlagBits(); auto extent = src->getExtent(); int width = extent.width; int height = extent.height; int pitch = src->rowPitchBytes(VK_IMAGE_ASPECT_COLOR_BIT, region.srcSubresource.mipLevel); int slice = src->slicePitchBytes(VK_IMAGE_ASPECT_COLOR_BIT, region.srcSubresource.mipLevel); uint8_t *source0 = (uint8_t *)source; uint8_t *source1 = source0 + slice; uint8_t *source2 = source1 + slice; uint8_t *source3 = source2 + slice; const bool SSE2 = CPUID::supportsSSE2(); if(format == VK_FORMAT_R8G8B8A8_UNORM || format == VK_FORMAT_B8G8R8A8_UNORM || format == VK_FORMAT_A8B8G8R8_UNORM_PACK32) { if(samples == 4) { for(int y = 0; y < height; y++) { int x = 0; #if defined(__i386__) || defined(__x86_64__) if(SSE2) { for(; (x + 3) < width; x += 4) { __m128i c0 = _mm_loadu_si128((__m128i *)(source0 + 4 * x)); __m128i c1 = _mm_loadu_si128((__m128i *)(source1 + 4 * x)); __m128i c2 = _mm_loadu_si128((__m128i *)(source2 + 4 * x)); __m128i c3 = _mm_loadu_si128((__m128i *)(source3 + 4 * x)); c0 = _mm_avg_epu8(c0, c1); c2 = _mm_avg_epu8(c2, c3); c0 = _mm_avg_epu8(c0, c2); _mm_storeu_si128((__m128i *)(dest + 4 * x), c0); } } #endif for(; x < width; x++) { uint32_t c0 = *(uint32_t *)(source0 + 4 * x); uint32_t c1 = *(uint32_t *)(source1 + 4 * x); uint32_t c2 = *(uint32_t *)(source2 + 4 * x); uint32_t c3 = *(uint32_t *)(source3 + 4 * x); uint32_t c01 = averageByte4(c0, c1); uint32_t c23 = averageByte4(c2, c3); uint32_t c03 = averageByte4(c01, c23); *(uint32_t *)(dest + 4 * x) = c03; } source0 += pitch; source1 += pitch; source2 += pitch; source3 += pitch; dest += pitch; ASSERT(source0 < src->end()); ASSERT(source3 < src->end()); ASSERT(dest < dst->end()); } } else UNSUPPORTED("Samples: %d", samples); } else { return false; } dst->contentsChanged(dstSubresourceRange); return true; } void Blitter::copy(const vk::Image *src, uint8_t *dst, unsigned int dstPitch) { VkExtent3D extent = src->getExtent(); size_t rowBytes = src->getFormat(VK_IMAGE_ASPECT_COLOR_BIT).bytes() * extent.width; unsigned int srcPitch = src->rowPitchBytes(VK_IMAGE_ASPECT_COLOR_BIT, 0); ASSERT(dstPitch >= rowBytes && srcPitch >= rowBytes && src->getMipLevelExtent(VK_IMAGE_ASPECT_COLOR_BIT, 0).height >= extent.height); const uint8_t *s = (uint8_t *)src->getTexelPointer({ 0, 0, 0 }, { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0 }); uint8_t *d = dst; for(uint32_t y = 0; y < extent.height; y++) { memcpy(d, s, rowBytes); s += srcPitch; d += dstPitch; } } void Blitter::computeCubeCorner(Pointer<Byte> &layer, Int &x0, Int &x1, Int &y0, Int &y1, Int &pitchB, const State &state) { int bytes = state.sourceFormat.bytes(); Float4 c = readFloat4(layer + ComputeOffset(x0, y1, pitchB, bytes), state) + readFloat4(layer + ComputeOffset(x1, y0, pitchB, bytes), state) + readFloat4(layer + ComputeOffset(x1, y1, pitchB, bytes), state); c *= Float4(1.0f / 3.0f); write(c, layer + ComputeOffset(x0, y0, pitchB, bytes), state); } Blitter::CornerUpdateRoutineType Blitter::generateCornerUpdate(const State &state) { // Reading and writing from/to the same image ASSERT(state.sourceFormat == state.destFormat); ASSERT(state.srcSamples == state.destSamples); // Vulkan 1.2: "If samples is not VK_SAMPLE_COUNT_1_BIT, then imageType must be // VK_IMAGE_TYPE_2D, flags must not contain VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT" ASSERT(state.srcSamples == 1); CornerUpdateFunction function; { Pointer<Byte> blit(function.Arg<0>()); Pointer<Byte> layers = *Pointer<Pointer<Byte>>(blit + OFFSET(CubeBorderData, layers)); Int pitchB = *Pointer<Int>(blit + OFFSET(CubeBorderData, pitchB)); UInt layerSize = *Pointer<Int>(blit + OFFSET(CubeBorderData, layerSize)); UInt dim = *Pointer<Int>(blit + OFFSET(CubeBorderData, dim)); // Low Border, Low Pixel, High Border, High Pixel Int LB(-1), LP(0), HB(dim), HP(dim - 1); for(int face = 0; face < 6; face++) { computeCubeCorner(layers, LB, LP, LB, LP, pitchB, state); computeCubeCorner(layers, LB, LP, HB, HP, pitchB, state); computeCubeCorner(layers, HB, HP, LB, LP, pitchB, state); computeCubeCorner(layers, HB, HP, HB, HP, pitchB, state); layers = layers + layerSize; } } return function("BlitRoutine"); } void Blitter::updateBorders(vk::Image *image, const VkImageSubresource &subresource) { ASSERT(image->getArrayLayers() >= (subresource.arrayLayer + 6)); // From Vulkan 1.1 spec, section 11.5. Image Views: // "For cube and cube array image views, the layers of the image view starting // at baseArrayLayer correspond to faces in the order +X, -X, +Y, -Y, +Z, -Z." VkImageSubresource posX = subresource; VkImageSubresource negX = posX; negX.arrayLayer++; VkImageSubresource posY = negX; posY.arrayLayer++; VkImageSubresource negY = posY; negY.arrayLayer++; VkImageSubresource posZ = negY; posZ.arrayLayer++; VkImageSubresource negZ = posZ; negZ.arrayLayer++; // Copy top / bottom copyCubeEdge(image, posX, BOTTOM, negY, RIGHT); copyCubeEdge(image, posY, BOTTOM, posZ, TOP); copyCubeEdge(image, posZ, BOTTOM, negY, TOP); copyCubeEdge(image, negX, BOTTOM, negY, LEFT); copyCubeEdge(image, negY, BOTTOM, negZ, BOTTOM); copyCubeEdge(image, negZ, BOTTOM, negY, BOTTOM); copyCubeEdge(image, posX, TOP, posY, RIGHT); copyCubeEdge(image, posY, TOP, negZ, TOP); copyCubeEdge(image, posZ, TOP, posY, BOTTOM); copyCubeEdge(image, negX, TOP, posY, LEFT); copyCubeEdge(image, negY, TOP, posZ, BOTTOM); copyCubeEdge(image, negZ, TOP, posY, TOP); // Copy left / right copyCubeEdge(image, posX, RIGHT, negZ, LEFT); copyCubeEdge(image, posY, RIGHT, posX, TOP); copyCubeEdge(image, posZ, RIGHT, posX, LEFT); copyCubeEdge(image, negX, RIGHT, posZ, LEFT); copyCubeEdge(image, negY, RIGHT, posX, BOTTOM); copyCubeEdge(image, negZ, RIGHT, negX, LEFT); copyCubeEdge(image, posX, LEFT, posZ, RIGHT); copyCubeEdge(image, posY, LEFT, negX, TOP); copyCubeEdge(image, posZ, LEFT, negX, RIGHT); copyCubeEdge(image, negX, LEFT, negZ, RIGHT); copyCubeEdge(image, negY, LEFT, negX, BOTTOM); copyCubeEdge(image, negZ, LEFT, posX, RIGHT); // Compute corner colors VkImageAspectFlagBits aspect = static_cast<VkImageAspectFlagBits>(subresource.aspectMask); vk::Format format = image->getFormat(aspect); VkSampleCountFlagBits samples = image->getSampleCountFlagBits(); State state(format, format, samples, samples, Options{ 0xF }); // Vulkan 1.2: "If samples is not VK_SAMPLE_COUNT_1_BIT, then imageType must be // VK_IMAGE_TYPE_2D, flags must not contain VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT" ASSERT(samples == VK_SAMPLE_COUNT_1_BIT); auto cornerUpdateRoutine = getCornerUpdateRoutine(state); if(!cornerUpdateRoutine) { return; } VkExtent3D extent = image->getMipLevelExtent(aspect, subresource.mipLevel); CubeBorderData data = { image->getTexelPointer({ 0, 0, 0 }, posX), image->rowPitchBytes(aspect, subresource.mipLevel), static_cast<uint32_t>(image->getLayerSize(aspect)), extent.width }; cornerUpdateRoutine(&data); } void Blitter::copyCubeEdge(vk::Image *image, const VkImageSubresource &dstSubresource, Edge dstEdge, const VkImageSubresource &srcSubresource, Edge srcEdge) { ASSERT(srcSubresource.aspectMask == dstSubresource.aspectMask); ASSERT(srcSubresource.mipLevel == dstSubresource.mipLevel); ASSERT(srcSubresource.arrayLayer != dstSubresource.arrayLayer); // Figure out if the edges to be copied in reverse order respectively from one another // The copy should be reversed whenever the same edges are contiguous or if we're // copying top <-> right or bottom <-> left. This is explained by the layout, which is: // // | +y | // | -x | +z | +x | -z | // | -y | bool reverse = (srcEdge == dstEdge) || ((srcEdge == TOP) && (dstEdge == RIGHT)) || ((srcEdge == RIGHT) && (dstEdge == TOP)) || ((srcEdge == BOTTOM) && (dstEdge == LEFT)) || ((srcEdge == LEFT) && (dstEdge == BOTTOM)); VkImageAspectFlagBits aspect = static_cast<VkImageAspectFlagBits>(srcSubresource.aspectMask); int bytes = image->getFormat(aspect).bytes(); int pitchB = image->rowPitchBytes(aspect, srcSubresource.mipLevel); VkExtent3D extent = image->getMipLevelExtent(aspect, srcSubresource.mipLevel); int w = extent.width; int h = extent.height; if(w != h) { UNSUPPORTED("Cube doesn't have square faces : (%d, %d)", w, h); } // Src is expressed in the regular [0, width-1], [0, height-1] space bool srcHorizontal = ((srcEdge == TOP) || (srcEdge == BOTTOM)); int srcDelta = srcHorizontal ? bytes : pitchB; VkOffset3D srcOffset = { (srcEdge == RIGHT) ? (w - 1) : 0, (srcEdge == BOTTOM) ? (h - 1) : 0, 0 }; // Dst contains borders, so it is expressed in the [-1, width], [-1, height] space bool dstHorizontal = ((dstEdge == TOP) || (dstEdge == BOTTOM)); int dstDelta = (dstHorizontal ? bytes : pitchB) * (reverse ? -1 : 1); VkOffset3D dstOffset = { (dstEdge == RIGHT) ? w : -1, (dstEdge == BOTTOM) ? h : -1, 0 }; // Don't write in the corners if(dstHorizontal) { dstOffset.x += reverse ? w : 1; } else { dstOffset.y += reverse ? h : 1; } const uint8_t *src = static_cast<const uint8_t *>(image->getTexelPointer(srcOffset, srcSubresource)); uint8_t *dst = static_cast<uint8_t *>(image->getTexelPointer(dstOffset, dstSubresource)); ASSERT((src < image->end()) && ((src + (w * srcDelta)) < image->end())); ASSERT((dst < image->end()) && ((dst + (w * dstDelta)) < image->end())); for(int i = 0; i < w; ++i, dst += dstDelta, src += srcDelta) { memcpy(dst, src, bytes); } } } // namespace sw
// Copyright (c) 2017-2020 The Particl Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/mnemonicdialog.h> #include <qt/forms/ui_mnemonicdialog.h> #include <qt/guiutil.h> #include <qt/walletmodel.h> #include <interfaces/wallet.h> #include <interfaces/node.h> #include <rpc/rpcutil.h> #include <util/system.h> #include <key/mnemonic.h> #include <key/extkey.h> #include <QDebug> void RPCThread::run() { bool passed = false; util::Ref context{m_node}; CallRPCVoidRv(m_command.toStdString(), context, m_wallet.toStdString(), &passed, m_rv, true); Q_EMIT complete(passed); // Can't pass back a UniValue or signal won't get detected ? } MnemonicDialog::MnemonicDialog(QWidget *parent, WalletModel *wm) : QDialog(parent), walletModel(wm), ui(new Ui::MnemonicDialog) { setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint); ui->setupUi(this); QObject::connect(ui->btnCancel2, &QPushButton::clicked, this, &MnemonicDialog::on_btnCancel_clicked); QObject::connect(ui->btnCancel3, &QPushButton::clicked, this, &MnemonicDialog::on_btnCancel_clicked); QObject::connect(this, &MnemonicDialog::startRescan, walletModel, &WalletModel::startRescan, Qt::QueuedConnection); setWindowTitle(QString("HD Wallet Setup - %1").arg(QString::fromStdString(wm->wallet().getWalletName()))); ui->edtPath->setPlaceholderText(tr("Path to derive account from, if not using default. (optional, default=%1)").arg(QString::fromStdString(GetDefaultAccountPath()))); ui->edtPassword->setPlaceholderText(tr("Enter a passphrase to protect your Recovery Phrase. (optional)")); #if QT_VERSION >= 0x050200 ui->tbxMnemonic->setPlaceholderText(tr("Enter your BIP39 compliant Recovery Phrase/Mnemonic.")); #endif #if ENABLE_USBDEVICE #else ui->tabWidget->setTabEnabled(2, false); #endif if (!wm->wallet().isDefaultAccountSet()) { ui->lblHelp->setText(QString( "Wallet %1 has no HD account loaded.\n" "An account must first be loaded in order to generate receiving addresses.\n" "Importing a recovery phrase will load a new master key and account.\n" "You can generate a new recovery phrase from the 'Create' page below.\n").arg(QString::fromStdString(wm->wallet().getWalletName()))); } else { ui->lblHelp->setText(QString( "Wallet %1 already has an HD account loaded.\n" "By importing another recovery phrase a new account will be created and set as the default.\n" "The wallet will receive on addresses from the new and existing account/s.\n" "New addresses will be generated from the new account.\n").arg(QString::fromStdString(wm->wallet().getWalletName()))); } ui->cbxLanguage->clear(); for (int l = 1; l < mnemonic::WLL_MAX; ++l) { if (mnemonic::HaveLanguage(l)) { ui->cbxLanguage->addItem(mnemonic::mnLanguagesDesc[l], QString(mnemonic::mnLanguagesTag[l])); } } return; }; MnemonicDialog::~MnemonicDialog() { if (m_thread) { m_thread->wait(); delete m_thread; } }; void MnemonicDialog::on_btnCancel_clicked() { close(); return; }; void MnemonicDialog::on_btnImport_clicked() { QString sCommand = (ui->chkImportChain->checkState() == Qt::Unchecked) ? "extkeyimportmaster" : "extkeygenesisimport"; sCommand += " \"" + ui->tbxMnemonic->toPlainText() + "\""; QString sPassword = ui->edtPassword->text(); sCommand += " \"" + sPassword + "\" false \"Master Key\" \"Default Account\" -1"; UniValue rv; if (walletModel->tryCallRpc(sCommand, rv)) { close(); if (!rv["warnings"].isNull()) { for (size_t i = 0; i < rv["warnings"].size(); ++i) { walletModel->warningBox(tr("Import"), QString::fromStdString(rv["warnings"][i].get_str())); } } startRescan(); } return; }; void MnemonicDialog::on_btnGenerate_clicked() { int nBytesEntropy = ui->spinEntropy->value(); QString sLanguage = ui->cbxLanguage->itemData(ui->cbxLanguage->currentIndex()).toString(); QString sCommand = "mnemonic new \"\" " + sLanguage + " " + QString::number(nBytesEntropy); UniValue rv; if (walletModel->tryCallRpc(sCommand, rv)) { ui->tbxMnemonicOut->setText(QString::fromStdString(rv["mnemonic"].get_str())); } return; }; void MnemonicDialog::on_btnImportFromHwd_clicked() { if (m_thread) { qWarning() << "MnemonicDialog hwd thread exists."; return; } QString sCommand = "initaccountfromdevice \"From Hardware Device\""; QString sPath = ui->edtPath->text(); sCommand += " \"" + sPath + "\" true -1"; ui->tbxHwdOut->appendPlainText("Waiting for device."); setEnabled(false); m_thread = new RPCThread(sCommand, walletModel->m_node, walletModel->getWalletName(), &m_rv); connect(m_thread, &RPCThread::complete, this, &MnemonicDialog::hwImportComplete); m_thread->setObjectName("particl-hwImport"); m_thread->start(); return; }; void MnemonicDialog::hwImportComplete(bool passed) { setEnabled(true); m_thread->wait(); delete m_thread; m_thread = nullptr; if (!passed) { QString sError; if (m_rv["Error"].isStr()) { sError = QString::fromStdString(m_rv["Error"].get_str()); } else { sError = QString::fromStdString(m_rv.write(1)); } ui->tbxHwdOut->appendPlainText(sError); if (sError == "No device found." || sError.indexOf("6982") > -1) { #ifndef WIN32 #ifndef MAC_OSX ui->tbxHwdOut->appendPlainText("Have you added a udev rule for your device?"); #endif #endif ui->tbxHwdOut->appendPlainText("The Particl app on your device must be open before importing."); } } else { UniValue rv; QString sCommand = "devicegetnewstealthaddress \"default stealth\""; walletModel->tryCallRpc(sCommand, rv); close(); startRescan(); } return; };
#ifndef EbfDataParser_CXX #define EbfDataParser_CXX 1 /** @class EbfDataParser.cxx @brief Implementation of the EbfDataParser class $Header: /nfs/slac/g/glast/ground/cvs/GlastRelease-scons/ldfReader/src/iterators/EbfDataParser.cxx,v 1.10 2009/09/12 04:00:40 heather Exp $ */ // ldfReader includes //#include "EbfDataParser.h" #include "ldfReader/iterators/EbfDataParser.h" #include "ldfReader/data/LatData.h" #include "ldfReader/LdfException.h" #include "../EbfDebug.h" #include <map> namespace { } // end default namespace namespace ldfReader { enum { Pri_Id_BtAncEvt = Pri_Base_OEF + 0x030 }; /*! Beam Test Ancillary Event */ enum { Pri_Id_BtAncHdr = Pri_Base_OEF + 0x040 }; /*! Beam Test Ancillary Header */ enum { Pri_Id_BtAncTlr = Pri_Base_OEF + 0x050 }; /*! Beam Test Ancillary Trailer */ enum { Sec_Id_BtAncEvt = 0x12c }; /*! Beamtest Ancillary Event */ enum { Sec_Id_BtAncHdr = 0x0c8 }; /*! Beamtest Ancillary Header */ enum { Sec_Id_BtAncTlr = 0x064 }; /*! Beamtest Ancillary Trailer*/ EbfDataParser::EbfDataParser(const char* prefix, ACDmap* a, CALmap* c, TKRmap* t) : AcdParser(prefix), AdfParser(), CalParser(prefix), TkrParser(prefix), DiagnosticParser(prefix), ErrParser(prefix), OswParser(), EBFiteratorBase(a, c, t), m_prefix(prefix) { } unsigned int EbfDataParser::iterate2(const unsigned char* buf, unsigned int len, bool swap) { return EBFiteratorBase::iterate(buf,len,swap); } int EbfDataParser::OSW_UDF(const EBFevent* /* event */, const OSWcontribution* contribution) const { printf("%sUndefined OSW contribution encountered with identity %08x\n", m_prefix, contribution->identity().value()); return 0; } int EbfDataParser::OSW_time(const EBFevent* /*event*/, const OSWtimeContribution* contribution) const { const struct timespec* ts = contribution->timeStamp(); const OSWtimeBase* tb = contribution->timebase(); printf("%s OSWtime:\n", m_prefix); printf("%s Event GMT timestamp = %ld.%09ld seconds after 1/1/1970\n", m_prefix, ts->tv_sec, ts->tv_nsec); printf("%s PPC timebase = 0x%08x%08x\n", m_prefix, tb->upper(), tb->lower()); printf("%s Extended event no. = 0x%08x = %d\n", m_prefix, contribution->evtSequence(), contribution->evtSequence()); return 0; } int EbfDataParser::UDF(const LATcontribution* event, const LATcontribution* /*end*/) { //(LATcontribution*) eventString = const_cast<LATcontribution*>event; if (event->identity().getPrimary() == Pri_Id_BtAncEvt) { if (EbfDebug::getDebug()==EbfDebug::ALL) printf("Found BtAncEvt, 0x%08X\n", event->identity().value()); const unsigned char* buf = (const_cast<LATcontribution*>(event))->string(false); /*int status = */m_adf.parseEvent(buf); //unsigned int *h = &((unsigned int*)buf)[0]; //unsigned int ver =(h[0] >> 20) & 0xfff; //unsigned int evtLen = h[1]; //printf("ver: 0x%08X %u, len: 0x%08X %u\n", ver, ver, h[1], h[1]); //unsigned int evtNum = h[2] & 0xfffffff; //unsigned int spillNum = (h[3] >> 12) & 0xffff; //unsigned int spillSize = h[3] & 0xfff; //printf("evtNum: %u, spillNum %u, spillSize: %u\n", evtNum, spillNum, spillSize); //unsigned int remainingBytes = len - 16; } else if (event->identity().getPrimary() == Pri_Id_BtAncHdr) { if (EbfDebug::getDebug()==EbfDebug::ALL) printf("Found BtAncHdr, 0x%08X\n", event->identity().value()); const unsigned char* buf = (const_cast<LATcontribution*>(event))->string(false); /*int status =*/m_adf.parseHeader(buf); //unsigned int *h = &((unsigned int*)buf)[0]; //unsigned int ver =(h[0] >> 20) & 0xfff; //printf("ver: 0x%08X %u, len: 0x%08X %u\n", ver, ver, h[1], h[1]); //unsigned int runNum = h[2]; //printf("runNum 0x%08X %u\n", runNum, runNum); } else if (event->identity().getPrimary() == Pri_Id_BtAncTlr) { if (EbfDebug::getDebug()==EbfDebug::ALL) printf("Found BtAncTlr, 0x%08X\n", event->identity().value()); const unsigned char* buf = (const_cast<LATcontribution*>(event))->string(false); /*int status = */m_adf.parseTrailer(buf); } else { fprintf(stderr, "EbfDataParser::UDF: " "Found unrecognized LATdatagram contribution type 0x%08X\n", event->identity().value()); } return 0; } int EbfDataParser::UDF(const EBFevent* /*event*/, const EBFcontribution* /*contribution*/) { printf("Found UDF in EbfDataParser\n"); //fprintf (stderr, "\nUndefined EBF component\n"); //((MyEBFcontribution*)contribution)->dump(" "); return 0; } int EbfDataParser::GLT(const EBFevent* event, const EBFcontribution* ebf) { const GLTcontribution *glt = (const GLTcontribution*)ebf; //if (EbfDebug::getDebug()) printf("\nGLT:\n"); ldfReader::LatData::instance()->setSummary(event->summary()); //ldfReader::LatData::instance()->summaryData().print(); // N.B. the payload of the GEM contribution will change in the future //unsigned seconds = ((unsigned*)gem->data())[0]; //unsigned nanoSeconds = ((unsigned*)gem->data())[1]; //ldfReader::LatData::instance()->setTime(seconds, nanoSeconds); // Only attempt to retrieve time if this is an older EBF file if (ldfReader::LatData::instance()->getFormatIdentity() < ID_WITH_OSW ) { const struct timespec* ts = glt->timeStamp(); const OSWtimeBase* tb = glt->timebase(); ldfReader::LatData::instance()->setTime(ts->tv_sec, ts->tv_nsec); if (glt->payloadSize() > 8) { // Timebase does not exist in old data unsigned upperPpcWord = tb->upper();//((unsigned*)gem->data())[2]; unsigned lowerPpcWord = tb->lower();//((unsigned*)gem->data())[3]; ldfReader::LatData::instance()->setPpcTimeBase(upperPpcWord, lowerPpcWord); } } return 0; } int EbfDataParser::GEM(const EBFevent *event, const EBFcontribution *ebf_contribution) { const GEMcontribution *contribution = (const GEMcontribution*) ebf_contribution; //if (EbfDebug::getDebug()) printf("\nEbfDataParser::GEM:\n"); ldfReader::GemData gem; // Set EventSummary here - in case there is no OSW ldfReader::LatData::instance()->setSummary(event->summary()); ldfReader::EventSummaryCommon summary(((EBFcontribution*)contribution)->summary()); gem.setExist(); gem.initPacketError(contribution->packetError()); gem.setSummary(summary); gem.initLength(((EBFcontribution*)contribution)->length()); const GEMtileList *onlineTiles = contribution->tileList(); ldfReader::GemDataTileList tileList(onlineTiles->XZM(), onlineTiles->XZP(), onlineTiles->YZM(), onlineTiles->YZP(), onlineTiles->XY(), onlineTiles->RBN(), onlineTiles->NA()); ldfReader::GemDataOnePpsTime time(contribution->onePPStime().timebase(), contribution->onePPStime().seconds()); gem.initTrigger(contribution->tkrVector(), contribution->roiVector(), contribution->calLEvector(), contribution->calHEvector(), contribution->cnoVector(), contribution->conditionSummary(), contribution->missed(), tileList); GemDataCondArrivalTime condArrTime; condArrTime.init(contribution->condArrTime().datum()); gem.initSummary(contribution->liveTime(), contribution->prescaled(), contribution->discarded(), condArrTime, contribution->triggerTime(), time, contribution->deltaEventTime(), contribution->deltaWindowOpenTime()); ldfReader::LatData::instance()->setGem(gem); if (EbfDebug::getDebug()==EbfDebug::ALL) { gem.print(); summary.print(); } return 0; } int EbfDataParser::commonComponentData(EBFcontribution *contribution) { /*int len =*/ contribution->length(); // printed in hex /*int error =*/ contribution->packetError(); /*int seqNum =*/ contribution->sequence(); // LCB header printed in hex /*int header =*/ contribution->header(); return 0; } int EbfDataParser::handleError(const EBFevent* e, unsigned code, unsigned p1, unsigned p2) const { int rc = EBFiteratorBase::handleError(e, code, p1, p2); _handleErrorCommon(); return rc; } int EbfDataParser::handleError(const EBFcontribution* c, unsigned code, unsigned p1, unsigned p2) const { ldfReader::LatData* latData = ldfReader::LatData::instance(); switch (code) { case EBFcontributionIterator::ERR_TrgParityError: { latData->setTrgParityErrorFlag(); break; } case EBFcontributionIterator::ERR_PacketError: { latData->setPacketErrorFlag(); /* ERR_PacketError gets an additional parameter */ // char *type; // // switch (p1) // { // case EBFcontribution::Parity: type = "parity"; break; // case EBFcontribution::Truncated: type = "truncated"; break; // case EBFcontribution::WriteFault: type = "write fault"; break; // case EBFcontribution::TimedOut: type = "timed out"; break; // default: type = "unknown"; break; // } // fprintf(stream(), // "EBFcontributionIterator: For EBFcontribution at %p:\n" // " Skipping contribution with source ID %d " // "and 'packet %s' (%d) error\n", // c, p2, type, p1); break; } default: { break; } } // Call base method int rc = EBFiteratorBase::handleError(c, code, p1, p2); _handleErrorCommon(); return rc; } int EbfDataParser::handleError(const AEMcontribution* c, unsigned code, unsigned p1, unsigned p2) const { int rc = EBFiteratorBase::handleError(c, code, p1, p2); _handleErrorCommon(); return rc; } int EbfDataParser::handleError(const TEMcontribution* c, unsigned code, unsigned p1, unsigned p2) const { ErrParser::handleError(c,code,p1,p2); int rc=code; // Always print out log messages that are not TEMbug if ((EbfDebug::getDebug() >= EbfDebug::ERRMSG) || (code != ERR_TEMbug)) { rc = EBFiteratorBase::handleError(c, code, p1, p2); _handleErrorCommon(); } return rc; } int EbfDataParser::handleError(const CALcontribution* c, unsigned code, unsigned p1, unsigned p2) const { int rc = EBFiteratorBase::handleError(c, code, p1, p2); _handleErrorCommon(); return rc; } int EbfDataParser::handleError(const TKRcontribution* c, unsigned code, unsigned p1, unsigned p2) const { int rc = EBFiteratorBase::handleError(c, code, p1, p2); _handleErrorCommon(); return rc; } void EbfDataParser::_handleErrorCommon() const { ldfReader::LatData* latData = ldfReader::LatData::instance(); unsigned long long evtId = ((latData->contextExists()) ? latData->eventId() : latData->getOsw().evtSequence()); // Hoping that it doesn't matter which stream( ) function we call fprintf(EBFiteratorBase::stream(), "\n Event: %llu Apid: %d\n", evtId, latData->getCcsds().getApid()); } } // end namespace #endif
#ifndef PYTHONIC_NUMPY_LINALG_NORM_HPP #define PYTHONIC_NUMPY_LINALG_NORM_HPP #include "pythonic/include/numpy/linalg/norm.hpp" #include "pythonic/numpy/abs.hpp" #include "pythonic/numpy/conj.hpp" #include "pythonic/numpy/asfarray.hpp" #include "pythonic/numpy/inf.hpp" #include "pythonic/numpy/max.hpp" #include "pythonic/numpy/min.hpp" #include "pythonic/numpy/power.hpp" #include "pythonic/numpy/real.hpp" #include "pythonic/numpy/sqrt.hpp" #include "pythonic/numpy/square.hpp" #include "pythonic/numpy/sum.hpp" #include "pythonic/__builtin__/NotImplementedError.hpp" namespace pythonic { namespace numpy { namespace linalg { template <class Array> auto norm(Array &&array, types::none_type ord, types::none_type axis) -> decltype( pythonic::numpy::functor::sqrt{}(pythonic::numpy::functor::sum{}( pythonic::numpy::functor::square{}( pythonic::numpy::functor::abs{}( pythonic::numpy::functor::asfarray{}( std::forward<Array>(array))))))) { return pythonic::numpy::functor::sqrt{}(pythonic::numpy::functor::sum{}( pythonic::numpy::functor::square{}(pythonic::numpy::functor::abs{}( pythonic::numpy::functor::asfarray{}( std::forward<Array>(array)))))); } template <class Array> norm_t<Array> norm(Array &&x, double ord, types::none_type) { switch (std::decay<Array>::type::value) { case 1: return norm(std::forward<Array>(x), ord, 0L); case 2: return norm(std::forward<Array>(x), ord, types::array<long, 2>{{0L, 1L}}); default: throw pythonic::__builtin__::NotImplementedError( "Invalid norm order for matrices."); } } template <class Array> norm_t<Array> norm(Array &&x, double ord, long axis) { auto &&y = pythonic::numpy::functor::asfarray{}(x); if (ord == inf) return pythonic::numpy::functor::max{}( pythonic::numpy::functor::abs{}(y), axis); else if (ord == -inf) return pythonic::numpy::functor::min{}( pythonic::numpy::functor::abs{}(y), axis); else if (ord == 0.) return pythonic::numpy::functor::sum{}(y != 0., axis); else if (ord == 1.) return pythonic::numpy::functor::sum{}( pythonic::numpy::functor::abs{}(y), axis); else if (ord == 2.) return pythonic::numpy::functor::sqrt{}( pythonic::numpy::functor::sum{}( pythonic::numpy::functor::real{}( pythonic::numpy::functor::conj{}(y)*y), axis)); else { return pythonic::numpy::functor::power{}( pythonic::numpy::functor::sum{}( pythonic::numpy::functor::power{}( pythonic::numpy::functor::abs{}(y), ord), axis), 1. / ord); } } template <class Array> norm_t<Array> norm(Array &&x, types::none_type ord, double axis) { return norm(std::forward<Array>(x), 2., axis); } template <class Array> norm_t<Array> norm(Array &&x, double ord, types::array<long, 1> axis) { return norm(std::forward<Array>(x), ord, axis[0]); } template <class Array> norm_t<Array> norm(Array &&array, double ord, types::array<long, 2> axis) { throw pythonic::__builtin__::NotImplementedError("We need more dev!"); } DEFINE_FUNCTOR(pythonic::numpy::linalg, norm); } } } #endif
/////////////////////////////////////////////////////////////////////// // File: ltrresultiterator.cpp // Description: Iterator for tesseract results in strict left-to-right // order that avoids using tesseract internal data structures. // Author: Ray Smith // // (C) Copyright 2010, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #include "ltrresultiterator.h" #include "allheaders.h" #include "pageres.h" #include "strngs.h" #include "tesseractclass.h" namespace tesseract { LTRResultIterator::LTRResultIterator(PAGE_RES* page_res, Tesseract* tesseract, int scale, int scaled_yres, int rect_left, int rect_top, int rect_width, int rect_height) : PageIterator(page_res, tesseract, scale, scaled_yres, rect_left, rect_top, rect_width, rect_height), line_separator_("\n"), paragraph_separator_("\n") {} // Destructor. // It is defined here, so the compiler can create a single vtable // instead of weak vtables in every compilation unit. LTRResultIterator::~LTRResultIterator() = default; // Returns the null terminated UTF-8 encoded text string for the current // object at the given level. Use delete [] to free after use. char* LTRResultIterator::GetUTF8Text(PageIteratorLevel level) const { if (it_->word() == nullptr) return nullptr; // Already at the end! STRING text; PAGE_RES_IT res_it(*it_); WERD_CHOICE* best_choice = res_it.word()->best_choice; ASSERT_HOST(best_choice != nullptr); if (level == RIL_SYMBOL) { text = res_it.word()->BestUTF8(blob_index_, false); } else if (level == RIL_WORD) { text = best_choice->unichar_string(); } else { bool eol = false; // end of line? bool eop = false; // end of paragraph? do { // for each paragraph in a block do { // for each text line in a paragraph do { // for each word in a text line best_choice = res_it.word()->best_choice; ASSERT_HOST(best_choice != nullptr); text += best_choice->unichar_string(); text += " "; res_it.forward(); eol = res_it.row() != res_it.prev_row(); } while (!eol); text.truncate_at(text.length() - 1); text += line_separator_; eop = res_it.block() != res_it.prev_block() || res_it.row()->row->para() != res_it.prev_row()->row->para(); } while (level != RIL_TEXTLINE && !eop); if (eop) text += paragraph_separator_; } while (level == RIL_BLOCK && res_it.block() == res_it.prev_block()); } int length = text.length() + 1; char* result = new char[length]; strncpy(result, text.string(), length); return result; } // Set the string inserted at the end of each text line. "\n" by default. void LTRResultIterator::SetLineSeparator(const char* new_line) { line_separator_ = new_line; } // Set the string inserted at the end of each paragraph. "\n" by default. void LTRResultIterator::SetParagraphSeparator(const char* new_para) { paragraph_separator_ = new_para; } // Returns the mean confidence of the current object at the given level. // The number should be interpreted as a percent probability. (0.0f-100.0f) float LTRResultIterator::Confidence(PageIteratorLevel level) const { if (it_->word() == nullptr) return 0.0f; // Already at the end! float mean_certainty = 0.0f; int certainty_count = 0; PAGE_RES_IT res_it(*it_); WERD_CHOICE* best_choice = res_it.word()->best_choice; ASSERT_HOST(best_choice != nullptr); switch (level) { case RIL_BLOCK: do { best_choice = res_it.word()->best_choice; ASSERT_HOST(best_choice != nullptr); mean_certainty += best_choice->certainty(); ++certainty_count; res_it.forward(); } while (res_it.block() == res_it.prev_block()); break; case RIL_PARA: do { best_choice = res_it.word()->best_choice; ASSERT_HOST(best_choice != nullptr); mean_certainty += best_choice->certainty(); ++certainty_count; res_it.forward(); } while (res_it.block() == res_it.prev_block() && res_it.row()->row->para() == res_it.prev_row()->row->para()); break; case RIL_TEXTLINE: do { best_choice = res_it.word()->best_choice; ASSERT_HOST(best_choice != nullptr); mean_certainty += best_choice->certainty(); ++certainty_count; res_it.forward(); } while (res_it.row() == res_it.prev_row()); break; case RIL_WORD: mean_certainty += best_choice->certainty(); ++certainty_count; break; case RIL_SYMBOL: mean_certainty += best_choice->certainty(blob_index_); ++certainty_count; } if (certainty_count > 0) { mean_certainty /= certainty_count; return ClipToRange(100 + 5 * mean_certainty, 0.0f, 100.0f); } return 0.0f; } void LTRResultIterator::RowAttributes(float* row_height, float* descenders, float* ascenders) const { *row_height = it_->row()->row->x_height() + it_->row()->row->ascenders() - it_->row()->row->descenders(); *descenders = it_->row()->row->descenders(); *ascenders = it_->row()->row->ascenders(); } // Returns the font attributes of the current word. If iterating at a higher // level object than words, eg textlines, then this will return the // attributes of the first word in that textline. // The actual return value is a string representing a font name. It points // to an internal table and SHOULD NOT BE DELETED. Lifespan is the same as // the iterator itself, ie rendered invalid by various members of // TessBaseAPI, including Init, SetImage, End or deleting the TessBaseAPI. // Pointsize is returned in printers points (1/72 inch.) const char* LTRResultIterator::WordFontAttributes( bool* is_bold, bool* is_italic, bool* is_underlined, bool* is_monospace, bool* is_serif, bool* is_smallcaps, int* pointsize, int* font_id) const { const char* result = nullptr; if (it_->word() == nullptr) { // Already at the end! *pointsize = 0; } else { float row_height = it_->row()->row->x_height() + it_->row()->row->ascenders() - it_->row()->row->descenders(); // Convert from pixels to printers points. *pointsize = scaled_yres_ > 0 ? static_cast<int>(row_height * kPointsPerInch / scaled_yres_ + 0.5) : 0; const FontInfo* font_info = it_->word()->fontinfo; if (font_info) { // Font information available. *font_id = font_info->universal_id; *is_bold = font_info->is_bold(); *is_italic = font_info->is_italic(); *is_underlined = false; // TODO(rays) fix this! *is_monospace = font_info->is_fixed_pitch(); *is_serif = font_info->is_serif(); *is_smallcaps = it_->word()->small_caps; result = font_info->name; } } if (!result) { *is_bold = false; *is_italic = false; *is_underlined = false; *is_monospace = false; *is_serif = false; *is_smallcaps = false; *font_id = -1; } return result; } // Returns the name of the language used to recognize this word. const char* LTRResultIterator::WordRecognitionLanguage() const { if (it_->word() == nullptr || it_->word()->tesseract == nullptr) return nullptr; return it_->word()->tesseract->lang.string(); } // Return the overall directionality of this word. StrongScriptDirection LTRResultIterator::WordDirection() const { if (it_->word() == nullptr) return DIR_NEUTRAL; bool has_rtl = it_->word()->AnyRtlCharsInWord(); bool has_ltr = it_->word()->AnyLtrCharsInWord(); if (has_rtl && !has_ltr) return DIR_RIGHT_TO_LEFT; if (has_ltr && !has_rtl) return DIR_LEFT_TO_RIGHT; if (!has_ltr && !has_rtl) return DIR_NEUTRAL; return DIR_MIX; } // Returns true if the current word was found in a dictionary. bool LTRResultIterator::WordIsFromDictionary() const { if (it_->word() == nullptr) return false; // Already at the end! int permuter = it_->word()->best_choice->permuter(); return permuter == SYSTEM_DAWG_PERM || permuter == FREQ_DAWG_PERM || permuter == USER_DAWG_PERM; } // Returns the number of blanks before the current word. int LTRResultIterator::BlanksBeforeWord() const { if (it_->word() == nullptr) return 1; return it_->word()->word->space(); } // Returns true if the current word is numeric. bool LTRResultIterator::WordIsNumeric() const { if (it_->word() == nullptr) return false; // Already at the end! int permuter = it_->word()->best_choice->permuter(); return permuter == NUMBER_PERM; } // Returns true if the word contains blamer information. bool LTRResultIterator::HasBlamerInfo() const { return it_->word() != nullptr && it_->word()->blamer_bundle != nullptr && it_->word()->blamer_bundle->HasDebugInfo(); } // Returns the pointer to ParamsTrainingBundle stored in the BlamerBundle // of the current word. const void* LTRResultIterator::GetParamsTrainingBundle() const { return (it_->word() != nullptr && it_->word()->blamer_bundle != nullptr) ? &(it_->word()->blamer_bundle->params_training_bundle()) : nullptr; } // Returns the pointer to the string with blamer information for this word. // Assumes that the word's blamer_bundle is not nullptr. const char* LTRResultIterator::GetBlamerDebug() const { return it_->word()->blamer_bundle->debug().string(); } // Returns the pointer to the string with misadaption information for this word. // Assumes that the word's blamer_bundle is not nullptr. const char* LTRResultIterator::GetBlamerMisadaptionDebug() const { return it_->word()->blamer_bundle->misadaption_debug().string(); } // Returns true if a truth string was recorded for the current word. bool LTRResultIterator::HasTruthString() const { if (it_->word() == nullptr) return false; // Already at the end! if (it_->word()->blamer_bundle == nullptr || it_->word()->blamer_bundle->NoTruth()) { return false; // no truth information for this word } return true; } // Returns true if the given string is equivalent to the truth string for // the current word. bool LTRResultIterator::EquivalentToTruth(const char* str) const { if (!HasTruthString()) return false; ASSERT_HOST(it_->word()->uch_set != nullptr); WERD_CHOICE str_wd(str, *(it_->word()->uch_set)); return it_->word()->blamer_bundle->ChoiceIsCorrect(&str_wd); } // Returns the null terminated UTF-8 encoded truth string for the current word. // Use delete [] to free after use. char* LTRResultIterator::WordTruthUTF8Text() const { if (!HasTruthString()) return nullptr; STRING truth_text = it_->word()->blamer_bundle->TruthString(); int length = truth_text.length() + 1; char* result = new char[length]; strncpy(result, truth_text.string(), length); return result; } // Returns the null terminated UTF-8 encoded normalized OCR string for the // current word. Use delete [] to free after use. char* LTRResultIterator::WordNormedUTF8Text() const { if (it_->word() == nullptr) return nullptr; // Already at the end! STRING ocr_text; WERD_CHOICE* best_choice = it_->word()->best_choice; const UNICHARSET* unicharset = it_->word()->uch_set; ASSERT_HOST(best_choice != nullptr); for (int i = 0; i < best_choice->length(); ++i) { ocr_text += unicharset->get_normed_unichar(best_choice->unichar_id(i)); } int length = ocr_text.length() + 1; char* result = new char[length]; strncpy(result, ocr_text.string(), length); return result; } // Returns a pointer to serialized choice lattice. // Fills lattice_size with the number of bytes in lattice data. const char* LTRResultIterator::WordLattice(int* lattice_size) const { if (it_->word() == nullptr) return nullptr; // Already at the end! if (it_->word()->blamer_bundle == nullptr) return nullptr; *lattice_size = it_->word()->blamer_bundle->lattice_size(); return it_->word()->blamer_bundle->lattice_data(); } // Returns true if the current symbol is a superscript. // If iterating at a higher level object than symbols, eg words, then // this will return the attributes of the first symbol in that word. bool LTRResultIterator::SymbolIsSuperscript() const { if (cblob_it_ == nullptr && it_->word() != nullptr) return it_->word()->best_choice->BlobPosition(blob_index_) == SP_SUPERSCRIPT; return false; } // Returns true if the current symbol is a subscript. // If iterating at a higher level object than symbols, eg words, then // this will return the attributes of the first symbol in that word. bool LTRResultIterator::SymbolIsSubscript() const { if (cblob_it_ == nullptr && it_->word() != nullptr) return it_->word()->best_choice->BlobPosition(blob_index_) == SP_SUBSCRIPT; return false; } // Returns true if the current symbol is a dropcap. // If iterating at a higher level object than symbols, eg words, then // this will return the attributes of the first symbol in that word. bool LTRResultIterator::SymbolIsDropcap() const { if (cblob_it_ == nullptr && it_->word() != nullptr) return it_->word()->best_choice->BlobPosition(blob_index_) == SP_DROPCAP; return false; } ChoiceIterator::ChoiceIterator(const LTRResultIterator& result_it) { ASSERT_HOST(result_it.it_->word() != nullptr); word_res_ = result_it.it_->word(); oemLSTM_ = word_res_->tesseract->AnyLSTMLang(); oemLegacy_ = word_res_->tesseract->AnyTessLang(); rating_coefficient_ = word_res_->tesseract->lstm_rating_coefficient; BLOB_CHOICE_LIST* choices = nullptr; tstep_index_ = &result_it.blob_index_; if (oemLSTM_ && !word_res_->CTC_symbol_choices.empty()) { auto index = *tstep_index_; if (word_res_->leading_space) ++index; if (index < word_res_->CTC_symbol_choices.size()) { LSTM_choices_ = &word_res_->CTC_symbol_choices[index]; filterSpaces(); } } if (oemLegacy_ && word_res_->ratings != nullptr) choices = word_res_->GetBlobChoices(result_it.blob_index_); if (choices != nullptr && !choices->empty()) { choice_it_ = new BLOB_CHOICE_IT(choices); choice_it_->mark_cycle_pt(); } else { choice_it_ = nullptr; } if (LSTM_choices_ != nullptr && !LSTM_choices_->empty()) { LSTM_choice_it_ = LSTM_choices_->begin(); } } ChoiceIterator::~ChoiceIterator() { delete choice_it_; } // Moves to the next choice for the symbol and returns false if there // are none left. bool ChoiceIterator::Next() { if (oemLSTM_ && LSTM_choices_ != nullptr && !LSTM_choices_->empty()) { if (LSTM_choice_it_ != LSTM_choices_->end() && next(LSTM_choice_it_) == LSTM_choices_->end()) { return false; } else { ++LSTM_choice_it_; return true; } } else { if (choice_it_ == nullptr) return false; choice_it_->forward(); return !choice_it_->cycled_list(); } } // Returns the null terminated UTF-8 encoded text string for the current // choice. Do NOT use delete [] to free after use. const char* ChoiceIterator::GetUTF8Text() const { if (oemLSTM_ && LSTM_choices_ != nullptr && !LSTM_choices_->empty()) { std::pair<const char*, float> choice = *LSTM_choice_it_; return choice.first; } else { if (choice_it_ == nullptr) return nullptr; UNICHAR_ID id = choice_it_->data()->unichar_id(); return word_res_->uch_set->id_to_unichar_ext(id); } } // Returns the confidence of the current choice depending on the used language // data. If only LSTM traineddata is used the value range is 0.0f - 1.0f. All // choices for one symbol should roughly add up to 1.0f. // If only traineddata of the legacy engine is used, the number should be // interpreted as a percent probability. (0.0f-100.0f) In this case probabilities // won't add up to 100. Each one stands on its own. float ChoiceIterator::Confidence() const { float confidence; if (oemLSTM_ && LSTM_choices_ != nullptr && !LSTM_choices_->empty()) { std::pair<const char*, float> choice = *LSTM_choice_it_; confidence = 100 - rating_coefficient_ * choice.second; } else { if (choice_it_ == nullptr) return 0.0f; confidence = 100 + 5 * choice_it_->data()->certainty(); } return ClipToRange(confidence, 0.0f, 100.0f); } // Returns the set of timesteps which belong to the current symbol std::vector<std::vector<std::pair<const char*, float>>>* ChoiceIterator::Timesteps() const { if (word_res_->symbol_steps.empty() || !oemLSTM_) return nullptr; if (word_res_->leading_space) { return &word_res_->symbol_steps[*(tstep_index_) + 1]; } else { return &word_res_->symbol_steps[*tstep_index_]; } } void ChoiceIterator::filterSpaces() { if (LSTM_choices_->empty()) return; std::vector<std::pair<const char*, float>>::iterator it; for (it = LSTM_choices_->begin(); it != LSTM_choices_->end();) { if (!strcmp(it->first, " ")) { it = LSTM_choices_->erase(it); } else { ++it; } } } } // namespace tesseract.
#include <chrono> #include <string> #include <vector> #include "common/config/utility.h" #include "common/http/message_impl.h" #include "common/json/json_loader.h" #include "common/upstream/cds_api_impl.h" #include "test/common/upstream/utility.h" #include "test/mocks/local_info/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using testing::InSequence; using testing::Invoke; using testing::Return; using testing::ReturnRef; using testing::_; namespace Envoy { namespace Upstream { class CdsApiImplTest : public testing::Test { public: CdsApiImplTest() : request_(&cm_.async_client_) {} void setup(bool v2_rest = false) { v2_rest_ = v2_rest; const std::string config_json = R"EOF( { "cluster": { "name": "foo_cluster" } } )EOF"; Json::ObjectSharedPtr config = Json::Factory::loadFromString(config_json); envoy::api::v2::ConfigSource cds_config; Config::Utility::translateCdsConfig(*config, cds_config); if (v2_rest) { cds_config.mutable_api_config_source()->set_api_type(envoy::api::v2::ApiConfigSource::REST); } Upstream::ClusterManager::ClusterInfoMap cluster_map; Upstream::MockCluster cluster; cluster_map.emplace("foo_cluster", cluster); EXPECT_CALL(cm_, clusters()).WillOnce(Return(cluster_map)); EXPECT_CALL(cluster, info()); EXPECT_CALL(*cluster.info_, addedViaApi()); EXPECT_CALL(cluster, info()); EXPECT_CALL(*cluster.info_, type()); cds_ = CdsApiImpl::create(cds_config, eds_config_, cm_, dispatcher_, random_, local_info_, store_); cds_->setInitializedCb([this]() -> void { initialized_.ready(); }); expectRequest(); cds_->initialize(); } void expectAdd(const std::string& cluster_name) { EXPECT_CALL(cm_, addOrUpdatePrimaryCluster(_)) .WillOnce(Invoke([cluster_name](const envoy::api::v2::Cluster& cluster) -> bool { EXPECT_EQ(cluster_name, cluster.name()); return true; })); } void expectRequest() { EXPECT_CALL(cm_, httpAsyncClientForCluster("foo_cluster")); EXPECT_CALL(cm_.async_client_, send_(_, _, _)) .WillOnce( Invoke([&](Http::MessagePtr& request, Http::AsyncClient::Callbacks& callbacks, const Optional<std::chrono::milliseconds>&) -> Http::AsyncClient::Request* { EXPECT_EQ((Http::TestHeaderMapImpl{ {":method", v2_rest_ ? "POST" : "GET"}, {":path", v2_rest_ ? "/v2/discovery:clusters" : "/v1/clusters/cluster_name/node_name"}, {":authority", "foo_cluster"}}), request->headers()); callbacks_ = &callbacks; return &request_; })); } ClusterManager::ClusterInfoMap makeClusterMap(std::vector<std::string> clusters) { ClusterManager::ClusterInfoMap map; for (auto cluster : clusters) { map.emplace(cluster, cm_.thread_local_cluster_.cluster_); } return map; } bool v2_rest_{}; NiceMock<MockClusterManager> cm_; NiceMock<Event::MockDispatcher> dispatcher_; NiceMock<Runtime::MockRandomGenerator> random_; NiceMock<LocalInfo::MockLocalInfo> local_info_; Stats::IsolatedStoreImpl store_; Http::MockAsyncClientRequest request_; CdsApiPtr cds_; Event::MockTimer* interval_timer_; Http::AsyncClient::Callbacks* callbacks_{}; ReadyWatcher initialized_; Optional<envoy::api::v2::ConfigSource> eds_config_; }; // Negative test for protoc-gen-validate constraints. TEST_F(CdsApiImplTest, ValidateFail) { InSequence s; setup(true); Protobuf::RepeatedPtrField<envoy::api::v2::Cluster> clusters; clusters.Add(); EXPECT_THROW(dynamic_cast<CdsApiImpl*>(cds_.get())->onConfigUpdate(clusters), ProtoValidationException); EXPECT_CALL(request_, cancel()); } TEST_F(CdsApiImplTest, InvalidOptions) { const std::string config_json = R"EOF( { "cluster": { "name": "foo_cluster" } } )EOF"; Json::ObjectSharedPtr config = Json::Factory::loadFromString(config_json); local_info_.node_.set_cluster(""); local_info_.node_.set_id(""); envoy::api::v2::ConfigSource cds_config; Config::Utility::translateCdsConfig(*config, cds_config); EXPECT_THROW( CdsApiImpl::create(cds_config, eds_config_, cm_, dispatcher_, random_, local_info_, store_), EnvoyException); } TEST_F(CdsApiImplTest, Basic) { interval_timer_ = new Event::MockTimer(&dispatcher_); InSequence s; setup(); const std::string response1_json = fmt::sprintf( "{%s}", clustersJson({defaultStaticClusterJson("cluster1"), defaultStaticClusterJson("cluster2")})); Http::MessagePtr message(new Http::ResponseMessageImpl( Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "200"}}})); message->body().reset(new Buffer::OwnedImpl(response1_json)); EXPECT_CALL(cm_, clusters()).WillOnce(Return(ClusterManager::ClusterInfoMap{})); expectAdd("cluster1"); expectAdd("cluster2"); EXPECT_CALL(initialized_, ready()); EXPECT_CALL(*interval_timer_, enableTimer(_)); EXPECT_EQ("", cds_->versionInfo()); EXPECT_EQ(0UL, store_.gauge("cluster_manager.cds.version").value()); callbacks_->onSuccess(std::move(message)); EXPECT_EQ(Config::Utility::computeHashedVersion(response1_json).first, cds_->versionInfo()); EXPECT_EQ(4054905652974790809U, store_.gauge("cluster_manager.cds.version").value()); expectRequest(); interval_timer_->callback_(); const std::string response2_json = fmt::sprintf( "{%s}", clustersJson({defaultStaticClusterJson("cluster1"), defaultStaticClusterJson("cluster3")})); message.reset(new Http::ResponseMessageImpl( Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "200"}}})); message->body().reset(new Buffer::OwnedImpl(response2_json)); EXPECT_CALL(cm_, clusters()).WillOnce(Return(makeClusterMap({"cluster1", "cluster2"}))); expectAdd("cluster1"); expectAdd("cluster3"); EXPECT_CALL(cm_, removePrimaryCluster("cluster2")); EXPECT_CALL(*interval_timer_, enableTimer(_)); callbacks_->onSuccess(std::move(message)); EXPECT_EQ(2UL, store_.counter("cluster_manager.cds.update_attempt").value()); EXPECT_EQ(2UL, store_.counter("cluster_manager.cds.update_success").value()); EXPECT_EQ(Config::Utility::computeHashedVersion(response2_json).first, cds_->versionInfo()); EXPECT_EQ(1872764556139482420U, store_.gauge("cluster_manager.cds.version").value()); } TEST_F(CdsApiImplTest, Failure) { interval_timer_ = new Event::MockTimer(&dispatcher_); InSequence s; setup(); const std::string response_json = R"EOF( { "clusters" : {} } )EOF"; Http::MessagePtr message(new Http::ResponseMessageImpl( Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "200"}}})); message->body().reset(new Buffer::OwnedImpl(response_json)); EXPECT_CALL(initialized_, ready()); EXPECT_CALL(*interval_timer_, enableTimer(_)); callbacks_->onSuccess(std::move(message)); expectRequest(); interval_timer_->callback_(); EXPECT_CALL(*interval_timer_, enableTimer(_)); callbacks_->onFailure(Http::AsyncClient::FailureReason::Reset); EXPECT_EQ("", cds_->versionInfo()); EXPECT_EQ(2UL, store_.counter("cluster_manager.cds.update_attempt").value()); EXPECT_EQ(2UL, store_.counter("cluster_manager.cds.update_failure").value()); EXPECT_EQ(0UL, store_.gauge("cluster_manager.cds.version").value()); } TEST_F(CdsApiImplTest, FailureArray) { interval_timer_ = new Event::MockTimer(&dispatcher_); InSequence s; setup(); const std::string response_json = R"EOF( [] )EOF"; Http::MessagePtr message(new Http::ResponseMessageImpl( Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "200"}}})); message->body().reset(new Buffer::OwnedImpl(response_json)); EXPECT_CALL(initialized_, ready()); EXPECT_CALL(*interval_timer_, enableTimer(_)); callbacks_->onSuccess(std::move(message)); EXPECT_EQ("", cds_->versionInfo()); EXPECT_EQ(1UL, store_.counter("cluster_manager.cds.update_attempt").value()); EXPECT_EQ(1UL, store_.counter("cluster_manager.cds.update_failure").value()); EXPECT_EQ(0UL, store_.gauge("cluster_manager.cds.version").value()); } } // namespace Upstream } // namespace Envoy
// Copyright (c) 2007-2018 Hartmut Kaiser // Copyright (c) 2011 Bryce Lelbach // // SPDX-License-Identifier: BSL-1.0 // 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) #if !defined(HPX_APPLIER_APPLY_NOV_27_2008_0957AM) #define HPX_APPLIER_APPLY_NOV_27_2008_0957AM #include <hpx/config.hpp> #include <hpx/assertion.hpp> #include <hpx/runtime/actions/action_priority.hpp> #include <hpx/runtime/agas/interface.hpp> #include <hpx/runtime/applier/apply_helper.hpp> #include <hpx/runtime/applier/detail/apply_implementations.hpp> #include <hpx/runtime/components/client_base.hpp> #include <hpx/runtime/naming/address.hpp> #include <hpx/runtime/naming/id_type.hpp> #include <hpx/runtime/naming/name.hpp> #include <hpx/runtime/parcelset/detail/parcel_await.hpp> #include <hpx/runtime/parcelset/put_parcel.hpp> #include <hpx/runtime/parcelset_fwd.hpp> #include <hpx/traits/component_type_is_compatible.hpp> #include <hpx/traits/extract_action.hpp> #include <hpx/functional/traits/is_action.hpp> #include <hpx/traits/is_continuation.hpp> #include <hpx/traits/is_distribution_policy.hpp> #include <hpx/traits/is_valid_action.hpp> #include <type_traits> #include <utility> // FIXME: Error codes? namespace hpx { /////////////////////////////////////////////////////////////////////////// // Invoked by a running HPX-thread to apply an action to any resource namespace applier { namespace detail { #if defined(HPX_HAVE_NETWORKING) /////////////////////////////////////////////////////////////////////// template <typename Action> inline naming::address&& complement_addr(naming::address& addr) { if (components::component_invalid == addr.type_) { addr.type_ = components::get_component_type< typename Action::component_type>(); } return std::move(addr); } template <typename Action, typename ...Ts> inline bool put_parcel(naming::id_type const& id, naming::address&& addr, threads::thread_priority priority, Ts&&... vs) { typedef typename hpx::traits::extract_action<Action>::type action_type; action_type act; parcelset::put_parcel(id, complement_addr<action_type>(addr), act, priority, std::forward<Ts>(vs)...); return false; // destinations are remote } template <typename Action, typename Continuation, typename ...Ts> inline bool put_parcel_cont(naming::id_type const& id, naming::address&& addr, threads::thread_priority priority, Continuation && cont, Ts&&... vs) { typedef typename hpx::traits::extract_action<Action>::type action_type; action_type act; parcelset::put_parcel(id, complement_addr<action_type>(addr), std::forward<Continuation>(cont), act, priority, std::forward<Ts>(vs)...); return false; // destinations are remote } template <typename Action, typename ...Ts> inline bool put_parcel_cb(naming::id_type const& id, naming::address&& addr, threads::thread_priority priority, parcelset::write_handler_type const& cb, Ts&&... vs) { typedef typename hpx::traits::extract_action<Action>::type action_type; action_type act; parcelset::put_parcel_cb(cb, id, complement_addr<action_type>(addr), act, priority, std::forward<Ts>(vs)...); return false; // destinations are remote } template <typename Action, typename ...Ts> inline bool put_parcel_cb(naming::id_type const& id, naming::address&& addr, threads::thread_priority priority, parcelset::write_handler_type && cb, Ts&&... vs) { typedef typename hpx::traits::extract_action<Action>::type action_type; action_type act; parcelset::put_parcel_cb(std::move(cb), id, complement_addr<action_type>(addr), act, priority, std::forward<Ts>(vs)...); return false; // destinations are remote } template <typename Action, typename Continuation, typename ...Ts> inline bool put_parcel_cont_cb(naming::id_type const& id, naming::address&& addr, threads::thread_priority priority, Continuation && cont, parcelset::write_handler_type const& cb, Ts&&... vs) { typedef typename hpx::traits::extract_action<Action>::type action_type; action_type act; parcelset::put_parcel_cb(cb, id, complement_addr<action_type>(addr), std::forward<Continuation>(cont), act, priority, std::forward<Ts>(vs)...); return false; // destinations are remote } template <typename Action, typename Continuation, typename ...Ts> inline bool put_parcel_cont_cb(naming::id_type const& id, naming::address&& addr, threads::thread_priority priority, Continuation && cont, parcelset::write_handler_type && cb, Ts&&... vs) { typedef typename hpx::traits::extract_action<Action>::type action_type; action_type act; parcelset::put_parcel_cb(std::move(cb), id, complement_addr<action_type>(addr), std::forward<Continuation>(cont), act, priority, std::forward<Ts>(vs)...); return false; // destinations are remote } // We know it is remote. template <typename Action, typename ...Ts> inline bool apply_r_p(naming::address&& addr, naming::id_type const& id, threads::thread_priority priority, Ts&&... vs) { // If remote, create a new parcel to be sent to the destination // Create a new parcel with the gid, action, and arguments return detail::put_parcel<Action>(id, std::move(addr), priority, std::forward<Ts>(vs)...); } template <typename Action, typename ...Ts> inline bool apply_r (naming::address&& addr, naming::id_type const& gid, Ts&&... vs) { return apply_r_p<Action>(std::move(addr), gid, actions::action_priority<Action>(), std::forward<Ts>(vs)...); } #endif // We know it is local and has to be directly executed. template <typename Action, typename ...Ts> inline bool apply_l_p(naming::id_type const& target, naming::address&& addr, threads::thread_priority priority, Ts&&... vs) { typedef typename hpx::traits::extract_action<Action>::type action_type; HPX_ASSERT(traits::component_type_is_compatible< typename action_type::component_type>::call(addr)); threads::thread_init_data data; apply_helper<action_type>::call(std::move(data), target, addr.address_, addr.type_, priority, std::forward<Ts>(vs)...); return true; // no parcel has been sent (dest is local) } // same as above, but taking all arguments by value template <typename Action, typename ...Ts> inline bool apply_l_p_val(naming::id_type const& target, naming::address&& addr, threads::thread_priority priority, Ts... vs) { typedef typename hpx::traits::extract_action<Action>::type action_type; HPX_ASSERT(traits::component_type_is_compatible< typename action_type::component_type>::call(addr)); threads::thread_init_data data; apply_helper<action_type>::call(std::move(data), target, addr.address_, addr.type_, priority, std::move(vs)...); return true; // no parcel has been sent (dest is local) } template <typename Action, typename ...Ts> inline bool apply_l (naming::id_type const& target, naming::address && addr, Ts&&... vs) { return apply_l_p<Action>(target, std::move(addr), actions::action_priority<Action>(), std::forward<Ts>(vs)...); } }} /////////////////////////////////////////////////////////////////////////// template <typename Action, typename ...Ts> inline bool apply_p(naming::id_type const& id, threads::thread_priority priority, Ts&&... vs) { return hpx::detail::apply_impl<Action>(id, priority, std::forward<Ts>(vs)...); } template <typename Action, typename Client, typename Stub, typename ...Ts> inline bool apply_p(components::client_base<Client, Stub> const& c, threads::thread_priority priority, Ts&&... vs) { // make sure the action is compatible with the component type typedef typename components::client_base< Client, Stub >::server_component_type component_type; typedef traits::is_valid_action<Action, component_type> is_valid; static_assert(is_valid::value, "The action to invoke is not supported by the target"); return hpx::detail::apply_impl<Action>( c.get_id(), priority, std::forward<Ts>(vs)...); } template <typename Action, typename DistPolicy, typename ...Ts> inline typename std::enable_if< traits::is_distribution_policy<DistPolicy>::value, bool >::type apply_p(DistPolicy const& policy, threads::thread_priority priority, Ts&&... vs) { return policy.template apply<Action>(priority, std::forward<Ts>(vs)...); } namespace detail { // dispatch point used for apply implementations template <typename Func, typename Enable = void> struct apply_dispatch; template <typename Action> struct apply_dispatch<Action, typename std::enable_if< traits::is_action<Action>::value >::type> { template <typename Component, typename Signature, typename Derived, typename ...Ts> HPX_FORCEINLINE static bool call(hpx::actions::basic_action<Component, Signature, Derived>, naming::id_type const& id, Ts&&... ts) { return apply_p<Derived>(id, actions::action_priority<Derived>(), std::forward<Ts>(ts)...); } template <typename Component, typename Signature, typename Derived, typename Client, typename Stub, typename ...Ts> HPX_FORCEINLINE static bool call(hpx::actions::basic_action<Component, Signature, Derived>, components::client_base<Client, Stub> const& c, Ts&&... ts) { // make sure the action is compatible with the component type typedef typename components::client_base< Client, Stub >::server_component_type component_type; typedef traits::is_valid_action<Derived, component_type> is_valid; static_assert(is_valid::value, "The action to invoke is not supported by the target"); return apply_p<Derived>(c.get_id(), actions::action_priority<Derived>(), std::forward<Ts>(ts)...); } template <typename Component, typename Signature, typename Derived, typename DistPolicy, typename ...Ts> HPX_FORCEINLINE static typename std::enable_if< traits::is_distribution_policy<DistPolicy>::value, bool >::type call(hpx::actions::basic_action<Component, Signature, Derived>, DistPolicy const& policy, Ts&&... ts) { return apply_p<Derived>(policy, actions::action_priority<Derived>(), std::forward<Ts>(ts)...); } }; } template <typename Action, typename ...Ts> inline bool apply(naming::id_type const& id, Ts&&... vs) { return apply_p<Action>(id, actions::action_priority<Action>(), std::forward<Ts>(vs)...); } template <typename Action, typename Client, typename Stub, typename ...Ts> inline bool apply(components::client_base<Client, Stub> const& c, Ts&&... vs) { // make sure the action is compatible with the component type typedef typename components::client_base< Client, Stub >::server_component_type component_type; typedef traits::is_valid_action<Action, component_type> is_valid; static_assert(is_valid::value, "The action to invoke is not supported by the target"); return apply_p<Action>(c.get_id(), actions::action_priority<Action>(), std::forward<Ts>(vs)...); } template <typename Action, typename DistPolicy, typename ...Ts> inline typename std::enable_if< traits::is_distribution_policy<DistPolicy>::value, bool >::type apply(DistPolicy const& policy, Ts&&... vs) { return apply_p<Action>(policy, actions::action_priority<Action>(), std::forward<Ts>(vs)...); } /////////////////////////////////////////////////////////////////////////// namespace applier { namespace detail { #if defined(HPX_HAVE_NETWORKING) template <typename Action, typename Continuation, typename ...Ts> inline bool apply_r_p(naming::address&& addr, Continuation && c, naming::id_type const& id, threads::thread_priority priority, Ts&&... vs) { // If remote, create a new parcel to be sent to the destination // Create a new parcel with the gid, action, and arguments return detail::put_parcel_cont<Action>(id, std::move(addr), priority, std::forward<Continuation>(c), std::forward<Ts>(vs)...); } template <typename Action, typename Continuation, typename ...Ts> inline typename std::enable_if< traits::is_continuation<Continuation>::value, bool >::type apply_r (naming::address&& addr, Continuation && c, naming::id_type const& gid, Ts&&... vs) { return apply_r_p<Action>(std::move(addr), std::forward<Continuation>(c), gid, actions::action_priority<Action>(), std::forward<Ts>(vs)...); } template <typename Action> inline bool apply_r_sync_p(naming::address&& addr, naming::id_type const& id, threads::thread_priority priority) { typedef typename hpx::traits::extract_action<Action>::type action_type_; // If remote, create a new parcel to be sent to the destination // Create a new parcel with the gid, action, and arguments // Send the parcel through the parcel handler HPX_ASSERT(id.get_management_type() == naming::id_type::unmanaged); naming::gid_type gid = id.get_gid(); parcelset::parcel p = parcelset::detail::create_parcel::call( std::move(gid), complement_addr<action_type_>(addr), action_type_(), priority ); parcelset::detail::parcel_await_apply(std::move(p), parcelset::write_handler_type(), 0, [](parcelset::parcel&& p, parcelset::write_handler_type&&) { hpx::parcelset::sync_put_parcel(std::move(p)); }); return false; // destination is remote } template <typename Action> inline bool apply_r_sync(naming::address&& addr, naming::id_type const& gid) { return apply_r_sync_p<Action>(std::move(addr), gid, actions::action_priority<Action>()); } #endif // We know it is local and has to be directly executed. template <typename Action, typename Continuation, typename ...Ts> inline bool apply_l_p(Continuation && cont, naming::id_type const& target, naming::address&& addr, threads::thread_priority priority, Ts&&... vs) { typedef typename hpx::traits::extract_action< Action >::type action_type; HPX_ASSERT(traits::component_type_is_compatible< typename action_type::component_type>::call(addr)); threads::thread_init_data data; #ifdef HPX_HAVE_APEX data.timer_data = hpx::util::external_timer::new_task( data.description, data.parent_locality_id, data.parent_id); #endif apply_helper<action_type>::call(std::move(data), std::forward<Continuation>(cont), target, addr.address_, addr.type_, priority, std::forward<Ts>(vs)...); return true; // no parcel has been sent (dest is local) } template <typename Action, typename Continuation, typename ...Ts> inline typename std::enable_if< traits::is_continuation<Continuation>::value, bool >::type apply_l (Continuation && c, naming::id_type const& target, naming::address& addr, Ts&&... vs) { return apply_l_p<Action>(std::forward<Continuation>(c), target, std::move(addr), actions::action_priority<Action>(), std::forward<Ts>(vs)...); } }} /////////////////////////////////////////////////////////////////////////// template <typename Action, typename Continuation, typename ...Ts> inline typename std::enable_if< traits::is_continuation<Continuation>::value, bool >::type apply_p(Continuation && c, naming::id_type const& gid, threads::thread_priority priority, Ts&&... vs) { return hpx::detail::apply_impl<Action>( std::forward<Continuation>(c), gid, priority, std::forward<Ts>(vs)...); } template <typename Action, typename Continuation, typename Client, typename Stub, typename ...Ts> inline typename std::enable_if< traits::is_continuation<Continuation>::value, bool >::type apply_p(Continuation && cont, components::client_base<Client, Stub> const& c, threads::thread_priority priority, Ts&&... vs) { // make sure the action is compatible with the component type typedef typename components::client_base< Client, Stub >::server_component_type component_type; typedef traits::is_valid_action<Action, component_type> is_valid; static_assert(is_valid::value, "The action to invoke is not supported by the target"); return hpx::detail::apply_impl<Action>( std::forward<Continuation>(cont), c.get_id(), priority, std::forward<Ts>(vs)...); } template <typename Action, typename Continuation, typename DistPolicy, typename ...Ts> inline typename std::enable_if< traits::is_continuation<Continuation>::value && traits::is_distribution_policy<DistPolicy>::value, bool >::type apply_p(Continuation && c, DistPolicy const& policy, threads::thread_priority priority, Ts&&... vs) { return policy.template apply<Action>( std::forward<Continuation>(c), priority, std::forward<Ts>(vs)...); } namespace detail { template <typename Continuation> struct apply_dispatch<Continuation, typename std::enable_if< traits::is_continuation<Continuation>::value >::type> { template <typename Component, typename Signature, typename Derived, typename ...Ts> HPX_FORCEINLINE static bool call(Continuation && c, hpx::actions::basic_action<Component, Signature, Derived>, naming::id_type const& id, Ts&&... ts) { return apply_p<Derived>(std::forward<Continuation>(c), id, actions::action_priority<Derived>(), std::forward<Ts>(ts)...); } template <typename Continuation_, typename Component, typename Signature, typename Derived, typename Client, typename Stub, typename ...Ts> HPX_FORCEINLINE static bool call(Continuation_ && cont, hpx::actions::basic_action<Component, Signature, Derived>, components::client_base<Client, Stub> const& c, Ts&&... ts) { // make sure the action is compatible with the component type typedef typename components::client_base< Client, Stub >::server_component_type component_type; typedef traits::is_valid_action<Derived, component_type> is_valid; static_assert(is_valid::value, "The action to invoke is not supported by the target"); return apply_p<Derived>(std::forward<Continuation>(cont), c.get_id(), actions::action_priority<Derived>(), std::forward<Ts>(ts)...); } template <typename Component, typename Signature, typename Derived, typename DistPolicy, typename ...Ts> HPX_FORCEINLINE static typename std::enable_if< traits::is_distribution_policy<DistPolicy>::value, bool >::type call(Continuation && c, hpx::actions::basic_action<Component, Signature, Derived>, DistPolicy const& policy, Ts&&... ts) { return apply_p<Derived>(std::forward<Continuation>(c), policy, actions::action_priority<Derived>(), std::forward<Ts>(ts)...); } }; } template <typename Action, typename Continuation, typename ...Ts> inline typename std::enable_if< traits::is_continuation<Continuation>::value, bool >::type apply(Continuation && c, naming::id_type const& gid, Ts&&... vs) { return apply_p<Action>(std::forward<Continuation>(c), gid, actions::action_priority<Action>(), std::forward<Ts>(vs)...); } template <typename Action, typename Continuation, typename Client, typename Stub, typename ...Ts> inline typename std::enable_if< traits::is_continuation<Continuation>::value, bool >::type apply(Continuation && cont, components::client_base<Client, Stub> const& c, Ts&&... vs) { // make sure the action is compatible with the component type typedef typename components::client_base< Client, Stub >::server_component_type component_type; typedef traits::is_valid_action<Action, component_type> is_valid; static_assert(is_valid::value, "The action to invoke is not supported by the target"); return apply_p<Action>(std::forward<Continuation>(cont), c.get_id(), actions::action_priority<Action>(), std::forward<Ts>(vs)...); } template <typename Action, typename Continuation, typename DistPolicy, typename ...Ts> inline typename std::enable_if< traits::is_distribution_policy<DistPolicy>::value && traits::is_continuation<Continuation>::value, bool >::type apply(Continuation && c, DistPolicy const& policy, Ts&&... vs) { return apply_p<Action>(std::forward<Continuation>(c), policy, actions::action_priority<Action>(), std::forward<Ts>(vs)...); } /////////////////////////////////////////////////////////////////////////// #if defined(HPX_HAVE_NETWORKING) namespace applier { namespace detail { template <typename Action, typename ...Ts> inline bool apply_c_p(naming::address&& addr, naming::id_type const& contgid, naming::id_type const& gid, threads::thread_priority priority, Ts&&... vs) { typedef typename hpx::traits::extract_action<Action>::local_result_type local_result_type; typedef typename hpx::traits::extract_action<Action>::remote_result_type remote_result_type; return apply_r_p<Action>(std::move(addr), actions::typed_continuation< local_result_type, remote_result_type>(contgid), gid, priority, std::forward<Ts>(vs)...); } template <typename Action, typename ...Ts> inline bool apply_c(naming::address&& addr, naming::id_type const& contgid, naming::id_type const& gid, Ts&&... vs) { typedef typename hpx::traits::extract_action<Action>::local_result_type local_result_type; typedef typename hpx::traits::extract_action<Action>::remote_result_type remote_result_type; return apply_r_p<Action>(std::move(addr), actions::typed_continuation< local_result_type, remote_result_type>(contgid), gid, actions::action_priority<Action>(), std::forward<Ts>(vs)...); } }} #endif /////////////////////////////////////////////////////////////////////////// template <typename Action, typename ...Ts> inline bool apply_c_p(naming::id_type const& contgid, naming::id_type const& gid, threads::thread_priority priority, Ts&&... vs) { typedef typename hpx::traits::extract_action<Action>::local_result_type local_result_type; typedef typename hpx::traits::extract_action<Action>::remote_result_type remote_result_type; return apply_p<Action>( actions::typed_continuation< local_result_type, remote_result_type >(contgid), gid, priority, std::forward<Ts>(vs)...); } template <typename Action, typename ...Ts> inline bool apply_c(naming::id_type const& contgid, naming::id_type const& gid, Ts&&... vs) { typedef typename hpx::traits::extract_action<Action>::local_result_type local_result_type; typedef typename hpx::traits::extract_action<Action>::remote_result_type remote_result_type; return apply_p<Action>( actions::typed_continuation< local_result_type, remote_result_type >(contgid), gid, actions::action_priority<Action>(), std::forward<Ts>(vs)...); } template <typename Component, typename Signature, typename Derived, typename ...Ts> inline bool apply_c( hpx::actions::basic_action<Component, Signature, Derived> /*act*/, naming::id_type const& contgid, naming::id_type const& gid, Ts&&... vs) { typedef typename hpx::traits::extract_action<Derived>::local_result_type local_result_type; typedef typename hpx::traits::extract_action<Derived>::remote_result_type remote_result_type; return apply_p<Derived>( actions::typed_continuation< local_result_type, remote_result_type >(contgid), gid, actions::action_priority<Derived>(), std::forward<Ts>(vs)...); } } #endif
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/cls/v20201016/model/DeleteConfigFromMachineGroupResponse.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Cls::V20201016::Model; using namespace std; DeleteConfigFromMachineGroupResponse::DeleteConfigFromMachineGroupResponse() { } CoreInternalOutcome DeleteConfigFromMachineGroupResponse::Deserialize(const string &payload) { rapidjson::Document d; d.Parse(payload.c_str()); if (d.HasParseError() || !d.IsObject()) { return CoreInternalOutcome(Core::Error("response not json format")); } if (!d.HasMember("Response") || !d["Response"].IsObject()) { return CoreInternalOutcome(Core::Error("response `Response` is null or not object")); } rapidjson::Value &rsp = d["Response"]; if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString()) { return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string")); } string requestId(rsp["RequestId"].GetString()); SetRequestId(requestId); if (rsp.HasMember("Error")) { if (!rsp["Error"].IsObject() || !rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() || !rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString()) { return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId)); } string errorCode(rsp["Error"]["Code"].GetString()); string errorMsg(rsp["Error"]["Message"].GetString()); return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId)); } return CoreInternalOutcome(true); } string DeleteConfigFromMachineGroupResponse::ToJsonString() const { rapidjson::Document value; value.SetObject(); rapidjson::Document::AllocatorType& allocator = value.GetAllocator(); rapidjson::Value iKey(rapidjson::kStringType); string key = "RequestId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); value.Accept(writer); return buffer.GetString(); }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "core/workers/DedicatedWorkerMessagingProxy.h" #include "core/workers/DedicatedWorkerThread.h" #include "core/workers/WorkerClients.h" namespace blink { DedicatedWorkerMessagingProxy::DedicatedWorkerMessagingProxy(InProcessWorkerBase* workerObject, PassOwnPtrWillBeRawPtr<WorkerClients> workerClients) : WorkerMessagingProxy(workerObject, workerClients) { } DedicatedWorkerMessagingProxy::~DedicatedWorkerMessagingProxy() { } PassRefPtr<WorkerThread> DedicatedWorkerMessagingProxy::createWorkerThread(double originTime) { return DedicatedWorkerThread::create(loaderProxy(), workerObjectProxy(), originTime); } } // namespace blink
/* * Copyright (c) 2022 Fachgebiet Simulation, Systemoptimierung und Robotik, TU Darmstadt. * * This file is part of RoboTrace * (see https://github.com/tu-darmstadt-ros-pkg/robo_trace) * and is governed by a BSD-style license * that can be found in the LICENSE file. */ // Base #include "robo_trace/modes/replay/time.hpp" // RosGraph #include "rosgraph_msgs/Clock.h" namespace robo_trace::replay { TimeManager::TimeManager(ros::NodeHandle& node_handle) : m_node_handle(node_handle), m_time_scale(1.0) { // Disable publications by default. setTimePublishFrequency(-1.0); // TODO: Make the topic name configurable maybe? m_publication_publisher = m_node_handle.advertise<rosgraph_msgs::Clock>("clock", 1); } TimeManager::~TimeManager() = default; bool TimeManager::isHorizonReached() { return ros::WallTime::now() > m_horizon_wc; } double TimeManager::getTimeScale() const { return m_time_scale; } void TimeManager::setTimeScale(double time_scale) { m_time_scale = time_scale; } const ros::Time& TimeManager::getStartTimeReal() const { return m_start_time_real; } void TimeManager::setStartTimeReal(const ros::Time& time) { m_start_time_real = time; } const ros::Time& TimeManager::getStartTimeTranslated() const { return m_start_time_translated; } void TimeManager::setStartTimeTranslated(const ros::Time & time) { m_start_time_translated = time; } double TimeManager::getTimePublishFrequency() const { return m_publication_frequency; } void TimeManager::setTimePublishFrequency(double publish_frequency) { m_publication_frequency = publish_frequency; m_publication_enabled = (publish_frequency > 0); m_publication_wall_step.fromSec(1.0 / publish_frequency); } const ros::Time& TimeManager::getCurrentTime() const { return m_current_time; } void TimeManager::setCurrentTime(const ros::Time& time) { m_current_time = time; } const ros::Time& TimeManager::getExecutionHorizon() const { return m_horizon; } void TimeManager::setExecutionHorizon(const ros::Time& horizon) { m_horizon = horizon; const ros::Time time_translated = m_start_time_translated + (horizon - m_start_time_real) * (1.0 / m_time_scale); m_horizon_wc = ros::WallTime(time_translated.sec, time_translated.nsec); } void TimeManager::advance(const ros::Duration& duration) { m_start_time_translated += duration; } void TimeManager::run(const ros::WallDuration& duration) { if (m_publication_enabled) { rosgraph_msgs::Clock msg_clock_time; ros::WallTime time_current = ros::WallTime::now(); ros::WallTime time_end = time_current + duration; while (time_current < time_end && time_current < m_horizon_wc) { ros::WallDuration time_left_till_wc_horizon = m_horizon_wc - ros::WallTime::now(); ros::Duration duration_till_wc_horizon(time_left_till_wc_horizon.sec, time_left_till_wc_horizon.nsec); duration_till_wc_horizon *= m_time_scale; m_current_time = m_horizon - duration_till_wc_horizon; if (m_current_time >= m_horizon) m_current_time = m_horizon; if (time_current >= m_publication_next_time) { msg_clock_time.clock = m_current_time; m_publication_publisher.publish(msg_clock_time); m_publication_next_time = time_current + m_publication_wall_step; } ros::WallTime time_target = time_end; if (time_target > m_horizon_wc) { time_target = m_horizon_wc; } if (time_target > m_publication_next_time) { time_target = m_publication_next_time; } ros::WallTime::sleepUntil(time_target); time_current = ros::WallTime::now(); } } else { ros::WallDuration time_left_till_wc_horizon = m_horizon_wc - ros::WallTime::now(); ros::Duration duration_till_wc_horizon(time_left_till_wc_horizon.sec, time_left_till_wc_horizon.nsec); duration_till_wc_horizon *= m_time_scale; m_current_time = m_horizon - duration_till_wc_horizon; if (m_current_time >= m_horizon) { m_current_time = m_horizon; } ros::WallTime time_target = ros::WallTime::now() + duration; if (time_target > m_horizon_wc) { time_target = m_horizon_wc; } ros::WallTime::sleepUntil(time_target); } } void TimeManager::stalled(const ros::WallDuration& duration) { if (m_publication_enabled) { rosgraph_msgs::Clock msg_clock_time; ros::WallTime time_current = ros::WallTime::now(); ros::WallTime time_end = time_current + duration; while (time_current < time_end) { if (time_current > m_publication_next_time) { msg_clock_time.clock = m_current_time; m_publication_publisher.publish(msg_clock_time); m_publication_next_time = time_current + m_publication_wall_step; } ros::WallTime time_target = time_end; // Clip to the next timestamp, where we need to publish time information. if (time_target > m_publication_next_time) { time_target = m_publication_next_time; } ros::WallTime::sleepUntil(time_target); time_current = ros::WallTime::now(); } } else { duration.sleep(); } } void TimeManager::step() { m_current_time = m_horizon; if (!m_publication_enabled) { return; } rosgraph_msgs::Clock msg_clock_time; msg_clock_time.clock = m_current_time; m_publication_publisher.publish(msg_clock_time); m_publication_next_time = ros::WallTime::now() + m_publication_wall_step; } }
#include "AppHdr.h" #include "stairs.h" #include <sstream> #include "abyss.h" #include "act-iter.h" #include "areas.h" #include "artefact.h" #include "bloodspatter.h" #include "branch.h" #include "chardump.h" #include "colour.h" #include "coordit.h" #include "delay.h" #include "dgn-overview.h" #include "directn.h" #include "env.h" #include "files.h" #include "god-passive.h" // passive_t::slow_abyss #include "hints.h" #include "hiscores.h" #include "item-name.h" #include "items.h" #include "level-state-type.h" #include "losglobal.h" #include "mapmark.h" #include "message.h" #include "mon-death.h" #include "movement.h" #include "notes.h" #include "orb-type.h" #include "output.h" #include "prompt.h" #include "religion.h" #include "spl-clouds.h" #include "spl-damage.h" #include "spl-other.h" #include "state.h" #include "stringutil.h" #include "terrain.h" #ifdef USE_TILE_LOCAL #include "tilepick.h" #endif #include "tiles-build-specific.h" #include "traps.h" #include "travel.h" #include "view.h" #include "xom.h" bool check_annotation_exclusion_warning() { level_id next_level_id = level_id::get_next_level_id(you.pos()); crawl_state.level_annotation_shown = false; bool might_be_dangerous = false; if (level_annotation_has("!", next_level_id) && next_level_id != level_id::current() && is_connected_branch(next_level_id)) { mprf(MSGCH_PROMPT, "Warning, next level annotated: <yellow>%s</yellow>", get_level_annotation(next_level_id).c_str()); might_be_dangerous = true; crawl_state.level_annotation_shown = true; } else if (is_exclude_root(you.pos()) && feat_is_travelable_stair(grd(you.pos())) && !strstr(get_exclusion_desc(you.pos()).c_str(), "cloud")) { mprf(MSGCH_WARN, "This staircase is marked as excluded!"); might_be_dangerous = true; } if (feat_is_travelable_stair(grd(you.pos()))) { if (LevelInfo *li = travel_cache.find_level_info(level_id::current())) { if (const stair_info *si = li->get_stair(you.pos())) { if (stairs_destination_is_excluded(*si)) { mprf(MSGCH_WARN, "This staircase leads to a travel-excluded area!"); might_be_dangerous = true; } } } } if (might_be_dangerous && !yesno("Enter next level anyway?", true, 'n', true, false)) { canned_msg(MSG_OK); interrupt_activity(activity_interrupt::force); crawl_state.level_annotation_shown = false; return false; } return true; } static void _player_change_level_reset() { you.prev_targ = MHITNOT; if (you.pet_target != MHITYOU) you.pet_target = MHITNOT; you.prev_grd_targ.reset(); } static void _player_change_level(level_id lev) { you.depth = lev.depth; you.where_are_you = lev.branch; } static void _maybe_destroy_shaft(const coord_def &p) { trap_def* trap = trap_at(p); if (trap && trap->type == TRAP_SHAFT) trap->destroy(true); } static bool _stair_moves_pre(dungeon_feature_type stair) { if (crawl_state.prev_cmd == CMD_WIZARD) return false; if (stair != grd(you.pos())) return false; if (feat_stair_direction(stair) == CMD_NO_CMD) return false; if (!you.duration[DUR_REPEL_STAIRS_CLIMB]) return false; int pct; if (you.duration[DUR_REPEL_STAIRS_MOVE]) pct = 29; else pct = 50; // When the effect is still strong, the chance to actually catch a stair // is smaller. (Assuming the duration starts out at 500.) const int dur = max(0, you.duration[DUR_REPEL_STAIRS_CLIMB] - 200); pct += dur/20; if (!x_chance_in_y(pct, 100)) return false; // Get feature name before sliding stair over. string stair_str = feature_description_at(you.pos(), false, DESC_THE); if (!slide_feature_over(you.pos())) return false; string verb = stair_climb_verb(stair); mprf("%s moves away as you attempt to %s it!", stair_str.c_str(), verb.c_str()); you.turn_is_over = true; return true; } static void _climb_message(dungeon_feature_type stair, bool going_up, branch_type old_branch) { if (!is_connected_branch(old_branch)) return; if (feat_is_portal(stair)) mpr("The world spins around you as you enter the gateway."); else if (feat_is_escape_hatch(stair)) { if (going_up) mpr("A mysterious force pulls you upwards."); else { mprf("You %s downwards.", you.airborne() ? "fly" : "slide"); } mpr("The hatch slams shut behind you."); } else if (feat_is_gate(stair)) { mprf("You %s %s through the gate.", you.airborne() ? "fly" : "go", going_up ? "up" : "down"); } else { mprf("You %s %swards.", you.airborne() ? "fly" : "climb", going_up ? "up" : "down"); } } static void _clear_golubria_traps() { for (auto c : find_golubria_on_level()) { trap_def *trap = trap_at(c); if (trap && trap->type == TRAP_GOLUBRIA) trap->destroy(); } } static void _clear_prisms() { for (auto &mons : menv_real) if (mons.type == MONS_FULMINANT_PRISM) mons.reset(); } void leaving_level_now(dungeon_feature_type stair_used) { if (stair_used == DNGN_EXIT_ZIGGURAT) { if (you.depth == 27) you.zigs_completed++; mark_milestone("zig.exit", make_stringf("left a ziggurat at level %d.", you.depth)); } if (stair_used == DNGN_EXIT_ABYSS) { #ifdef DEBUG auto &vault_list = you.vault_list[level_id::current()]; vault_list.push_back("[exit]"); #endif } dungeon_events.fire_position_event(DET_PLAYER_CLIMBS, you.pos()); dungeon_events.fire_event(DET_LEAVING_LEVEL); _clear_golubria_traps(); _clear_prisms(); end_recall(); } static void _update_travel_cache(const level_id& old_level, const coord_def& stair_pos) { // If the old level is gone, nothing to save. if (!you.save || !you.save->has_chunk(old_level.describe())) return; // Update stair information for the stairs we just ascended, and the // down stairs we're currently on. level_id new_level_id = level_id::current(); if (can_travel_interlevel()) { LevelInfo &old_level_info = travel_cache.get_level_info(old_level); LevelInfo &new_level_info = travel_cache.get_level_info(new_level_id); new_level_info.update(); // First we update the old level's stair. level_pos lp; lp.id = new_level_id; lp.pos = you.pos(); bool guess = false; // Ugly hack warning: // The stairs in the Vestibule of Hell exhibit special behaviour: // they always lead back to the dungeon level that the player // entered the Vestibule from. This means that we need to pretend // we don't know where the upstairs from the Vestibule go each time // we take it. If we don't, interlevel travel may try to use portals // to Hell as shortcuts between dungeon levels, which won't work, // and will confuse the dickens out of the player (well, it confused // the dickens out of me when it happened). if ((new_level_id == BRANCH_DUNGEON || new_level_id == BRANCH_DEPTHS) && old_level == BRANCH_VESTIBULE) { old_level_info.clear_stairs(DNGN_EXIT_HELL); } else old_level_info.update_stair(stair_pos, lp, guess); // We *guess* that going up a staircase lands us on a downstair, // and that we can descend that downstair and get back to where we // came from. This assumption is guaranteed false when climbing out // of one of the branches of Hell. if (new_level_id != BRANCH_VESTIBULE || !is_hell_subbranch(old_level.branch)) { // Set the new level's stair, assuming arbitrarily that going // downstairs will land you on the same upstairs you took to // begin with (not necessarily true). lp.id = old_level; lp.pos = stair_pos; new_level_info.update_stair(you.pos(), lp, true); } } } // These checks are probably unnecessary. static bool _check_stairs(const dungeon_feature_type ftype, bool going_up) { // If it's not bidirectional, check that the player is headed // in the right direction. if (!feat_is_bidirectional_portal(ftype)) { if (feat_stair_direction(ftype) != (going_up ? CMD_GO_UPSTAIRS : CMD_GO_DOWNSTAIRS)) { if (ftype == DNGN_STONE_ARCH) mpr("There is nothing on the other side of the stone arch."); else if (ftype == DNGN_ABANDONED_SHOP) mpr("This shop has been abandoned, nothing of value remains."); else if (going_up) mpr("You can't go up here!"); else mpr("You can't go down here!"); return false; } } return true; } static bool _check_fall_down_stairs(const dungeon_feature_type ftype, bool going_up) { if (!you.airborne() && you.confused() && !feat_is_escape_hatch(ftype) && coinflip()) { const char* fall_where = "down the stairs"; if (!feat_is_staircase(ftype)) fall_where = "through the gate"; mprf("In your confused state, you trip and fall %s%s.", going_up ? "back " : "", fall_where); if (!feat_is_staircase(ftype)) ouch(1, KILLED_BY_FALLING_THROUGH_GATE); else ouch(1, KILLED_BY_FALLING_DOWN_STAIRS); // Note that if going downstairs, this only does damage. // It doesn't cancel the level transition. if (going_up) { you.turn_is_over = true; return true; } } return false; } static void _rune_effect(dungeon_feature_type ftype) { // Nothing even remotely flashy for Zig. if (ftype != DNGN_ENTER_ZIGGURAT) { vector<int> runes; for (int i = 0; i < NUM_RUNE_TYPES; i++) if (you.runes[i]) runes.push_back(i); ASSERT(runes.size() >= 1); shuffle_array(runes); // Zot is extra flashy. if (ftype == DNGN_ENTER_ZOT) { ASSERT(runes.size() >= 3); mprf("You insert the %s rune into the lock.", rune_type_name(runes[2])); #ifdef USE_TILE_LOCAL tiles.add_overlay(you.pos(), tileidx_zap(rune_colour(runes[2]))); update_screen(); #else flash_view(UA_BRANCH_ENTRY, rune_colour(runes[2])); #endif mpr("The lock glows eerily!"); // included in default force_more_message mprf("You insert the %s rune into the lock.", rune_type_name(runes[1])); big_cloud(CLOUD_BLUE_SMOKE, &you, you.pos(), 20, 7 + random2(7)); viewwindow(); mpr("Heavy smoke blows from the lock!"); // included in default force_more_message } mprf("You insert the %s rune into the lock.", rune_type_name(runes[0])); if (silenced(you.pos())) mpr("The gate opens wide!"); else mpr("With a soft hiss the gate opens wide!"); // these are included in default force_more_message } } static void _gauntlet_effect() { // already doomed if (you.species == SP_FORMICID) return; mprf(MSGCH_WARN, "The nature of this place prevents you from teleporting."); if (you.has_mutation(MUT_TELEPORT, true) || you.wearing(EQ_RINGS, RING_TELEPORTATION, true) || you.scan_artefacts(ARTP_CAUSE_TELEPORTATION, true)) { mpr("You feel stable on this floor."); } } static void _new_level_amuses_xom(dungeon_feature_type feat, dungeon_feature_type old_feat, bool shaft, int shaft_depth, bool voluntary) { switch (you.where_are_you) { default: // Xom thinks it's funny if you enter a new level via shaft // or escape hatch, for shafts it's funnier the deeper you fell. if (shaft || feat_is_escape_hatch(feat)) xom_is_stimulated(shaft_depth * 50); else if (!is_connected_branch(you.where_are_you)) xom_is_stimulated(25); else xom_is_stimulated(10); break; case BRANCH_ZIGGURAT: // The best way to die currently. xom_is_stimulated(50); break; case BRANCH_PANDEMONIUM: xom_is_stimulated(100); break; case BRANCH_ABYSS: if (voluntary && old_feat == DNGN_ENTER_ABYSS) xom_is_stimulated(100, XM_INTRIGUED); else xom_is_stimulated(200); break; } } /** * Determine destination level. * * @param how How the player is trying to travel. * (e.g. stairs, traps, portals, etc) * @param forced True if the player is forcing the traveling attempt. * (e.g. forcibly exiting the abyss, etc) * @param going_up True if the player is going upstairs. * @param known_shaft True if the player is intentionally shafting themself. * @return The destination level, if valid. Note the default value * of dest is not valid (since depth = -1) and this is * generally what is returned for invalid destinations. * But note the special case when failing to climb stairs * when attempting to leave the dungeon, depth = 1. */ static level_id _travel_destination(const dungeon_feature_type how, bool forced, bool going_up, bool known_shaft) { const bool shaft = known_shaft || how == DNGN_TRAP_SHAFT; level_id shaft_dest; level_id dest; if (shaft) { if (!is_valid_shaft_level()) { if (known_shaft) mpr("The shaft disappears in a puff of logic!"); _maybe_destroy_shaft(you.pos()); return dest; } shaft_dest = you.shaft_dest(); } // How far down you fall via a shaft or hatch. const int shaft_depth = (shaft ? shaft_dest.depth - you.depth : 1); // Only check the current position for a legal stair traverse. // Check that we're going the right way (if we're not falling through // a shaft or being forced). if (!shaft && !forced && !_check_stairs(how, going_up)) return dest; // Up and down both work for some portals. // Canonicalize the direction: hell exits into the vestibule are considered // going up; everything else is going down. This mostly affects which way you // fall if confused. if (feat_is_bidirectional_portal(how)) going_up = (how == DNGN_ENTER_HELL && player_in_hell(false)); if (_stair_moves_pre(how)) return dest; // Falling down is checked before the transition if going upstairs, since // it might prevent the transition itself. if (going_up && _check_fall_down_stairs(how, true)) { // TODO: This probably causes an obscure bug where confused players // going 'down' into the vestibule are twice as likely to fall, because // they have to pass a check here, and later in floor_transition // Right solution is probably to use the canonicalized direction everywhere // If player falls down the stairs trying to leave the dungeon, we set // the destination depth to 1 (i.e. D:1) if (how == DNGN_EXIT_DUNGEON) dest.depth = 1; return dest; } if (shaft) { if (shaft_dest == level_id::current()) { if (known_shaft) { mpr("Strange, the shaft seems to lead back to this level."); mpr("The strain on the space-time continuum destroys the " "shaft!"); } _maybe_destroy_shaft(you.pos()); return dest; } if (!known_shaft) { mark_milestone("shaft", "fell down a shaft to " + shaft_dest.describe() + "."); } mprf("You %s into a shaft and drop %d floor%s!", you.airborne() ? "are sucked" : "fall", shaft_depth, shaft_depth > 1 ? "s" : ""); // Shafts are one-time-use. mpr("The shaft crumbles and collapses."); _maybe_destroy_shaft(you.pos()); } // Maybe perform the entry sequence (we check that they have enough runes // in main.cc: _can_take_stairs()) for (branch_iterator it; it; ++it) { if (how != it->entry_stairs) continue; if (!you.level_visited(level_id(it->id, 1)) && runes_for_branch(it->id) > 0) { _rune_effect(how); } break; } // Markers might be deleted when removing portals. const string dst = env.markers.property_at(you.pos(), MAT_ANY, "dst"); if (shaft) return shaft_dest; else return stair_destination(how, dst, true); } /** * Check to see if transition will actually move the player. * * @param dest The destination level (branch and depth). * @param feat The dungeon feature the player is standing on. * @param going_up True if the player is trying to go up stairs. * @return True if the level transition should happen. */ static bool _level_transition_moves_player(level_id dest, dungeon_feature_type feat, bool going_up) { bool trying_to_exit = feat == DNGN_EXIT_DUNGEON && going_up; // When exiting the dungeon, dest is not valid (depth = -1) // So the player can transition with an invalid dest ONLY when exiting. // Otherwise (i.e. not exiting) dest must be valid. return dest.is_valid() != trying_to_exit; } /** * Transition to a different level. * * @param how The type of stair/portal tile the player is being conveyed through * @param whence The tile the player was on at the beginning of the transition * (likely the same as how, unless forced is true) * @param whither The destination level * @param shaft Is the player going down a shaft? */ void floor_transition(dungeon_feature_type how, const dungeon_feature_type whence, level_id whither, bool forced, bool going_up, bool shaft, bool update_travel_cache) { const level_id old_level = level_id::current(); // Clean up fake blood. heal_flayed_effect(&you, true, true); // Magical level changes (which currently only exist "downwards") need this. clear_trapping_net(); end_searing_ray(); you.stop_constricting_all(); you.stop_being_constricted(); you.clear_beholders(); you.clear_fearmongers(); dec_frozen_ramparts(you.duration[DUR_FROZEN_RAMPARTS]); if (!forced) { // Break ice armour remove_ice_armour_movement(); // Check for barbs and apply apply_barbs_damage(); } // Fire level-leaving trigger. leaving_level_now(how); // Not entirely accurate - the player could die before // reaching the Abyss. if (!forced && whence == DNGN_ENTER_ABYSS) { mark_milestone("abyss.enter", "entered the Abyss!"); take_note(Note(NOTE_MESSAGE, 0, 0, "Voluntarily entered the Abyss."), true); } else if (!forced && whence == DNGN_EXIT_THROUGH_ABYSS) { mark_milestone("abyss.enter", "escaped (hah) into the Abyss!"); take_note(Note(NOTE_MESSAGE, 0, 0, "Took an exit into the Abyss."), true); } else if (how == DNGN_EXIT_ABYSS && you.chapter != CHAPTER_POCKET_ABYSS) { mark_milestone("abyss.exit", "escaped from the Abyss!"); you.attribute[ATTR_BANISHMENT_IMMUNITY] = you.elapsed_time + 100 + random2(100); you.banished_by = ""; you.banished_power = 0; } // Interlevel travel data. const bool collect_travel_data = can_travel_interlevel(); if (collect_travel_data) { LevelInfo &old_level_info = travel_cache.get_level_info(old_level); old_level_info.update(); } const coord_def stair_pos = you.pos(); if (how == DNGN_EXIT_DUNGEON) { you.depth = 0; mpr("You have escaped!"); if (player_has_orb()) ouch(INSTANT_DEATH, KILLED_BY_WINNING); ouch(INSTANT_DEATH, KILLED_BY_LEAVING); } if (how == DNGN_ENTER_ZIGGURAT) dungeon_terrain_changed(you.pos(), DNGN_STONE_ARCH); if (how == DNGN_ENTER_PANDEMONIUM || how == DNGN_ENTER_ABYSS || feat_is_portal_entrance(how)) { you.level_stack.push_back(level_pos::current()); } // Actually change the player's branch and depth, along with some cleanup. _player_change_level_reset(); _player_change_level(whither); // Some branch specific messages. if (old_level.branch == BRANCH_VESTIBULE && !is_hell_subbranch(you.where_are_you)) { mpr("Thank you for visiting Hell. Please come again soon."); } if (how == DNGN_EXIT_ABYSS || how == DNGN_EXIT_PANDEMONIUM || how == DNGN_EXIT_THROUGH_ABYSS) { mpr("You pass through the gate."); take_note(Note(NOTE_MESSAGE, 0, 0, how == DNGN_EXIT_ABYSS ? "Escaped the Abyss" : how == DNGN_EXIT_PANDEMONIUM ? "Escaped Pandemonium" : how == DNGN_EXIT_THROUGH_ABYSS ? "Escaped into the Abyss" : "Buggered into bugdom"), true); if (!you.wizard || !crawl_state.is_replaying_keys()) more(); } // Fixup exits from the Hell branches. if (player_in_branch(BRANCH_VESTIBULE) && is_hell_subbranch(old_level.branch)) { how = branches[old_level.branch].entry_stairs; } // Check for falling down the stairs or portal. if (!going_up && !shaft && !forced) _check_fall_down_stairs(how, false); if (shaft) how = DNGN_TRAP_SHAFT; switch (you.where_are_you) { case BRANCH_ABYSS: // There are no abyssal stairs that go up, so this whole case is only // when going down. you.props.erase(ABYSS_SPAWNED_XP_EXIT_KEY); if (old_level.branch == BRANCH_ABYSS) { mprf(MSGCH_BANISHMENT, "You plunge deeper into the Abyss."); if (!you.runes[RUNE_ABYSSAL] && you.depth >= ABYSSAL_RUNE_MIN_LEVEL) mpr("The abyssal rune of Zot can be found at this depth."); break; } if (!forced) mpr("You enter the Abyss!"); mpr("To return, you must find a gate leading back."); mpr("Killing monsters will force the Abyss to allow you passage."); if (have_passive(passive_t::slow_abyss)) { mprf(MSGCH_GOD, you.religion, "You feel %s slowing down the madness of this place.", god_name(you.religion).c_str()); } you.props[ABYSS_STAIR_XP_KEY] = EXIT_XP_COST; // Re-entering the Abyss halves accumulated speed. you.abyss_speed /= 2; learned_something_new(HINT_ABYSS); break; case BRANCH_PANDEMONIUM: if (old_level.branch == BRANCH_PANDEMONIUM) mpr("You pass into a different region of Pandemonium."); break; default: // This hits both cases. if (!shaft) _climb_message(how, going_up, old_level.branch); break; } // Did we enter a different branch? if (!player_in_branch(old_level.branch)) { const branch_type branch = you.where_are_you; if (branch_entered(branch)) mprf("Welcome back to %s!", branches[branch].longname); else if (how == branches[branch].entry_stairs) { if (branches[branch].entry_message) mpr(branches[branch].entry_message); else if (branch != BRANCH_ABYSS) // too many messages... mprf("Welcome to %s!", branches[branch].longname); } if (branch == BRANCH_GAUNTLET) _gauntlet_effect(); const set<branch_type> boring_branch_exits = { BRANCH_TEMPLE, BRANCH_BAZAAR, BRANCH_TROVE }; // Did we leave a notable branch for the first time? if (boring_branch_exits.count(old_level.branch) == 0 && !you.branches_left[old_level.branch]) { string old_branch_string = branches[old_level.branch].longname; if (starts_with(old_branch_string, "The ")) old_branch_string[0] = tolower_safe(old_branch_string[0]); mark_milestone("br.exit", "left " + old_branch_string + ".", old_level.describe()); you.branches_left.set(old_level.branch); } if (how == branches[branch].entry_stairs) { const string noise_desc = branch_noise_desc(branch); if (!noise_desc.empty()) mpr(noise_desc); const string rune_msg = branch_rune_desc(branch, true); if (!rune_msg.empty()) mpr(rune_msg); } // Entered a branch from its parent. if (parent_branch(branch) == old_level.branch) enter_branch(branch, old_level); } // Warn Formicids if they cannot shaft here if (you.species == SP_FORMICID && !is_valid_shaft_level()) mpr("Beware, you cannot shaft yourself on this level."); const bool newlevel = load_level(how, LOAD_ENTER_LEVEL, old_level); if (newlevel) { _new_level_amuses_xom(how, whence, shaft, (shaft ? whither.depth - old_level.depth : 1), !forced); } // This should maybe go in load_level? if (you.where_are_you == BRANCH_ABYSS) generate_random_blood_spatter_on_level(); you.turn_is_over = true; save_game_state(); new_level(); moveto_location_effects(whence); trackers_init_new_level(); if (update_travel_cache && !shaft) _update_travel_cache(old_level, stair_pos); // Preventing obvious finding of stairs at your position. env.map_seen.set(you.pos()); viewwindow(); // There's probably a reason for this. I don't know it. if (going_up) seen_monsters_react(); else maybe_update_stashes(); autotoggle_autopickup(false); request_autopickup(); } /** * Try to go up or down stairs. * * @param force_stair The type of stair/portal to take. By default, * use whatever tile is under the player. But this can be overridden * (e.g. passing DNGN_EXIT_ABYSS forces the player out of the abyss) * @param going_up True if the player is going upstairs * @param force_known_shaft True if player is shafting themselves via ability. * @param update_travel_cache True if travel cache should be updated. */ void take_stairs(dungeon_feature_type force_stair, bool going_up, bool force_known_shaft, bool update_travel_cache) { const dungeon_feature_type old_feat = orig_terrain(you.pos()); dungeon_feature_type how = force_stair ? force_stair : old_feat; // Taking a shaft manually (stepping on a known shaft, or using shaft ability) const bool known_shaft = (!force_stair && get_trap_type(you.pos()) == TRAP_SHAFT) || (force_stair == DNGN_TRAP_SHAFT && force_known_shaft); // Latter case is falling down a shaft. const bool shaft = known_shaft || force_stair == DNGN_TRAP_SHAFT; level_id whither = _travel_destination(how, bool(force_stair), going_up, known_shaft); if (!_level_transition_moves_player(whither, old_feat, going_up)) return; floor_transition(how, old_feat, whither, bool(force_stair), going_up, shaft, update_travel_cache); } void up_stairs(dungeon_feature_type force_stair, bool update_travel_cache) { take_stairs(force_stair, true, false, update_travel_cache); } // Find the other end of the stair or portal at location pos on the current // level. for_real is true if we are actually traversing the feature rather // than merely asking what is on the other side. level_id stair_destination(coord_def pos, bool for_real) { return stair_destination(orig_terrain(pos), env.markers.property_at(pos, MAT_ANY, "dst"), for_real); } // Find the other end of a stair or portal on the current level. feat is the // type of feature (DNGN_EXIT_ABYSS, for example), dst is the target of a // portal vault entrance (and is ignored for other types of features), and // for_real is true if we are actually traversing the feature rather than // merely asking what is on the other side. level_id stair_destination(dungeon_feature_type feat, const string &dst, bool for_real) { #if TAG_MAJOR_VERSION == 34 if (feat == DNGN_ESCAPE_HATCH_UP && player_in_branch(BRANCH_LABYRINTH)) feat = DNGN_EXIT_LABYRINTH; #else UNUSED(dst); // see below in the switch #endif if (branches[you.where_are_you].exit_stairs == feat && parent_branch(you.where_are_you) < NUM_BRANCHES && feat != DNGN_EXIT_ZIGGURAT) { level_id lev = brentry[you.where_are_you]; if (!lev.is_valid()) { // Wizmode, the branch wasn't generated this game. // Pick the middle of the range instead. lev = level_id(branches[you.where_are_you].parent_branch, (branches[you.where_are_you].mindepth + branches[you.where_are_you].maxdepth) / 2); ASSERT(lev.is_valid()); } return lev; } if (feat_is_portal_exit(feat)) feat = DNGN_EXIT_PANDEMONIUM; switch (feat) { case DNGN_ESCAPE_HATCH_UP: case DNGN_STONE_STAIRS_UP_I: case DNGN_STONE_STAIRS_UP_II: case DNGN_STONE_STAIRS_UP_III: if (you.depth <= 1) { if (you.wizard && !for_real) return level_id(); die("upstairs from top of a branch"); } return level_id(you.where_are_you, you.depth - 1); case DNGN_EXIT_HELL: // If set, it would be found as a branch exit. if (you.wizard) { if (for_real) { mprf(MSGCH_ERROR, "Error: no Hell exit level, how in the " "Vestibule did you get here? Let's go to D:1."); } return level_id(BRANCH_DUNGEON, 1); } else die("hell exit without return destination"); case DNGN_ABYSSAL_STAIR: ASSERT(player_in_branch(BRANCH_ABYSS)); push_features_to_abyss(); case DNGN_ESCAPE_HATCH_DOWN: case DNGN_STONE_STAIRS_DOWN_I: case DNGN_STONE_STAIRS_DOWN_II: case DNGN_STONE_STAIRS_DOWN_III: { ASSERT(!at_branch_bottom()); level_id lev = level_id::current(); lev.depth++; return lev; } case DNGN_TRANSIT_PANDEMONIUM: return level_id(BRANCH_PANDEMONIUM); case DNGN_EXIT_THROUGH_ABYSS: return level_id(BRANCH_ABYSS); #if TAG_MAJOR_VERSION == 34 case DNGN_ENTER_PORTAL_VAULT: if (dst.empty()) { if (for_real) die("portal without a destination"); else return level_id(); } try { return level_id::parse_level_id(dst); } catch (const bad_level_id &err) { die("Invalid destination for portal: %s", err.what()); } #endif case DNGN_ENTER_HELL: if (for_real && !player_in_hell()) brentry[BRANCH_VESTIBULE] = level_id::current(); return level_id(BRANCH_VESTIBULE); case DNGN_EXIT_ABYSS: if (you.chapter == CHAPTER_POCKET_ABYSS) return level_id(BRANCH_DUNGEON, 1); #if TAG_MAJOR_VERSION == 34 case DNGN_EXIT_PORTAL_VAULT: #endif case DNGN_EXIT_PANDEMONIUM: if (you.level_stack.empty()) { if (you.wizard) { if (for_real) { mprf(MSGCH_ERROR, "Error: no return path. You did create " "the exit manually, didn't you? Let's go to D:1."); } return level_id(BRANCH_DUNGEON, 1); } die("no return path from a portal (%s)", level_id::current().describe().c_str()); } return you.level_stack.back().id; case DNGN_ENTER_ABYSS: push_features_to_abyss(); break; default: break; } // Try to find a branch stair. for (branch_iterator it; it; ++it) { if (it->entry_stairs == feat) return level_id(it->id); } return level_id(); } // TODO(Zannick): Fully merge with up_stairs into take_stairs. void down_stairs(dungeon_feature_type force_stair, bool force_known_shaft, bool update_travel_cache) { take_stairs(force_stair, false, force_known_shaft, update_travel_cache); } static void _update_level_state() { env.level_state = 0; vector<coord_def> golub = find_golubria_on_level(); if (!golub.empty()) env.level_state |= LSTATE_GOLUBRIA; for (monster_iterator mon_it; mon_it; ++mon_it) { if (mons_allows_beogh(**mon_it)) env.level_state |= LSTATE_BEOGH; if (mon_it->has_ench(ENCH_STILL_WINDS)) env.level_state |= LSTATE_STILL_WINDS; if (mon_it->has_ench(ENCH_AWAKEN_FOREST)) { env.forest_awoken_until = you.elapsed_time + mon_it->get_ench(ENCH_AWAKEN_FOREST).duration; } } #if TAG_MAJOR_VERSION == 34 const bool have_ramparts = you.duration[DUR_FROZEN_RAMPARTS]; const auto &ramparts_pos = you.props[FROZEN_RAMPARTS_KEY].get_coord(); #endif for (rectangle_iterator ri(0); ri; ++ri) { if (grd(*ri) == DNGN_SLIMY_WALL) env.level_state |= LSTATE_SLIMY_WALL; if (is_icecovered(*ri)) #if TAG_MAJOR_VERSION == 34 { // Buggy versions of Frozen Ramparts didn't properly clear // FPROP_ICY from walls in some cases, so we detect invalid walls // and remove the flag. if (have_ramparts && ramparts_pos.distance_from(*ri) <= 3 && cell_see_cell(*ri, ramparts_pos, LOS_NO_TRANS)) { #endif env.level_state |= LSTATE_ICY_WALL; #if TAG_MAJOR_VERSION == 34 } else env.pgrid(*ri) &= ~FPROP_ICY; } #endif } env.orb_pos = coord_def(); if (item_def* orb = find_floor_item(OBJ_ORBS, ORB_ZOT)) env.orb_pos = orb->pos; else if (player_has_orb()) { env.orb_pos = you.pos(); invalidate_agrid(true); } } void new_level(bool restore) { print_stats_level(); #ifdef DGL_WHEREIS whereis_record(); #endif _update_level_state(); if (restore) return; cancel_tornado(); if (player_in_branch(BRANCH_ZIGGURAT)) you.zig_max = max(you.zig_max, you.depth); }
/********** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ // "liveMedia" // Copyright (c) 1996-2013 Live Networks, Inc. All rights reserved. // A 'ServerMediaSubsession' object that creates new, unicast, "RTPSink"s // on demand, from an H264 video track within a Matroska file. // C++ header #ifndef _H264_VIDEO_MATROSKA_FILE_SERVER_MEDIA_SUBSESSION_HH #define _H264_VIDEO_MATROSKA_FILE_SERVER_MEDIA_SUBSESSION_HH #ifndef _H264_VIDEO_FILE_SERVER_MEDIA_SUBSESSION_HH #include "H264VideoFileServerMediaSubsession.hh" #endif #ifndef _MATROSKA_FILE_SERVER_DEMUX_HH #include "MatroskaFileServerDemux.hh" #endif class H264VideoMatroskaFileServerMediaSubsession: public H264VideoFileServerMediaSubsession { public: static H264VideoMatroskaFileServerMediaSubsession* createNew(MatroskaFileServerDemux& demux, unsigned trackNumber); private: H264VideoMatroskaFileServerMediaSubsession(MatroskaFileServerDemux& demux, unsigned trackNumber); // called only by createNew(); virtual ~H264VideoMatroskaFileServerMediaSubsession(); private: // redefined virtual functions virtual float duration() const; virtual void seekStreamSource(FramedSource* inputSource, double& seekNPT, double streamDuration, u_int64_t& numBytes); virtual FramedSource* createNewStreamSource(unsigned clientSessionId, unsigned& estBitrate); private: MatroskaFileServerDemux& fOurDemux; unsigned fTrackNumber; // We store one SPS, and one PPS, for use in our input 'framer's: unsigned fSPSSize; u_int8_t* fSPS; unsigned fPPSSize; u_int8_t* fPPS; }; #endif
/******************************************************************************* * dpt/util/macros.hpp * * Part of dpt - Distributed Patricia Trie * * Copyright (C) 2016 Florian Kurpicz <florian.kurpicz@tu-dortmund.de> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #pragma once #if defined(__GNUC__) || defined(__clang__) #define DSSS_LIKELY(c) __builtin_expect((c), 1) #define DSSS_UNLIKELY(c) __builtin_expect((c), 0) #else #define DSSS_LIKELY(c) c #define DSSS_UNLIKELY(c) c #endif #if defined(__GNUC__) || defined(__clang__) #define DSSS_ATTRIBUTE_PACKED __attribute__ ((packed)) #else #define DSSS_ATTRIBUTE_PACKED #endif /******************************************************************************/
/* * ShaderConductor * * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. * * MIT License * * 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. */ #ifndef SHADER_CONDUCTOR_HPP #define SHADER_CONDUCTOR_HPP #pragma once #include <functional> #if defined(__clang__) #define SC_SYMBOL_EXPORT __attribute__((__visibility__("default"))) #define SC_SYMBOL_IMPORT #elif defined(__GNUC__) #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) #define SC_SYMBOL_EXPORT __attribute__((__dllexport__)) #define SC_SYMBOL_IMPORT __attribute__((__dllimport__)) #else #define SC_SYMBOL_EXPORT __attribute__((__visibility__("default"))) #define SC_SYMBOL_IMPORT #endif #elif defined(_MSC_VER) #define SC_SYMBOL_EXPORT __declspec(dllexport) #define SC_SYMBOL_IMPORT __declspec(dllimport) #endif #ifdef SHADER_CONDUCTOR_SOURCE #define SC_API SC_SYMBOL_EXPORT #else #define SC_API SC_SYMBOL_IMPORT #endif namespace ShaderConductor { enum class ShaderStage : uint32_t { VertexShader, PixelShader, GeometryShader, HullShader, DomainShader, ComputeShader, NumShaderStages, }; enum class ShadingLanguage : uint32_t { Dxil = 0, SpirV, Hlsl, Glsl, Essl, Msl_macOS, Msl_iOS, NumShadingLanguages, }; enum class ShaderResourceType : uint32_t { ConstantBuffer, Parameter, Texture, Sampler, ShaderResourceView, UnorderedAccessView, NumShaderResourceType, }; struct MacroDefine { const char* name; const char* value; }; class SC_API Blob { public: Blob() noexcept; Blob(const void* data, uint32_t size); Blob(const Blob& other); Blob(Blob&& other) noexcept; ~Blob() noexcept; Blob& operator=(const Blob& other); Blob& operator=(Blob&& other) noexcept; void Reset(); void Reset(const void* data, uint32_t size); const void* Data() const noexcept; uint32_t Size() const noexcept; private: class BlobImpl; BlobImpl* m_impl = nullptr; }; class SC_API Compiler { public: struct ShaderModel { uint8_t major_ver : 6; uint8_t minor_ver : 2; uint32_t FullVersion() const noexcept { return (major_ver << 2) | minor_ver; } bool operator<(const ShaderModel& other) const noexcept { return this->FullVersion() < other.FullVersion(); } bool operator==(const ShaderModel& other) const noexcept { return this->FullVersion() == other.FullVersion(); } bool operator>(const ShaderModel& other) const noexcept { return other < *this; } bool operator<=(const ShaderModel& other) const noexcept { return (*this < other) || (*this == other); } bool operator>=(const ShaderModel& other) const noexcept { return (*this > other) || (*this == other); } }; struct SourceDesc { const char* source; const char* fileName; const char* entryPoint; ShaderStage stage; const MacroDefine* defines; uint32_t numDefines; std::function<Blob(const char* includeName)> loadIncludeCallback; }; struct Options { bool packMatricesInRowMajor = true; // Experimental: Decide how a matrix get packed bool enable16bitTypes = false; // Enable 16-bit types, such as half, uint16_t. Requires shader model 6.2+ bool enableDebugInfo = false; // Embed debug info into the binary bool disableOptimizations = false; // Force to turn off optimizations. Ignore optimizationLevel below. bool inheritCombinedSamplerBindings = false; // If textures and samplers are combined, inherit the binding of the texture int optimizationLevel = 3; // 0 to 3, no optimization to most optimization ShaderModel shaderModel = {6, 0}; int shiftAllTexturesBindings = 0; int shiftAllSamplersBindings = 0; int shiftAllCBuffersBindings = 0; int shiftAllUABuffersBindings = 0; }; struct TargetDesc { ShadingLanguage language; const char* version; bool asModule; }; struct ReflectionDesc { char name[256]; // Name of the resource ShaderResourceType type; // Type of resource (e.g. texture, cbuffer, etc.) uint32_t bufferBindPoint; // Buffer's starting bind point uint32_t bindPoint; // Starting bind point uint32_t bindCount; // Number of contiguous bind points (for arrays) }; struct ReflectionResultDesc { Blob descs; // The underneath type is ReflectionDesc uint32_t descCount = 0; uint32_t instructionCount = 0; }; struct ResultDesc { Blob target; bool isText; Blob errorWarningMsg; bool hasError; ReflectionResultDesc reflection; }; struct DisassembleDesc { ShadingLanguage language; const uint8_t* binary; uint32_t binarySize; }; struct ModuleDesc { const char* name; Blob target; }; struct LinkDesc { const char* entryPoint; ShaderStage stage; const ModuleDesc** modules; uint32_t numModules; }; public: static ResultDesc Compile(const SourceDesc& source, const Options& options, const TargetDesc& target); static void Compile(const SourceDesc& source, const Options& options, const TargetDesc* targets, uint32_t numTargets, ResultDesc* results); static ResultDesc Disassemble(const DisassembleDesc& source); // Currently only Dxil on Windows supports linking static bool LinkSupport(); static ResultDesc Link(const LinkDesc& modules, const Options& options, const TargetDesc& target); }; } // namespace ShaderConductor #endif // SHADER_CONDUCTOR_HPP
/* * 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/core/utils/Outcome.h> #include <aws/core/auth/AWSAuthSigner.h> #include <aws/core/client/CoreErrors.h> #include <aws/core/client/RetryStrategy.h> #include <aws/core/http/HttpClient.h> #include <aws/core/http/HttpResponse.h> #include <aws/core/http/HttpClientFactory.h> #include <aws/core/auth/AWSCredentialsProviderChain.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <aws/core/utils/threading/Executor.h> #include <aws/core/utils/DNS.h> #include <aws/core/utils/logging/LogMacros.h> #include <aws/secretsmanager/SecretsManagerClient.h> #include <aws/secretsmanager/SecretsManagerEndpoint.h> #include <aws/secretsmanager/SecretsManagerErrorMarshaller.h> #include <aws/secretsmanager/model/CancelRotateSecretRequest.h> #include <aws/secretsmanager/model/CreateSecretRequest.h> #include <aws/secretsmanager/model/DeleteResourcePolicyRequest.h> #include <aws/secretsmanager/model/DeleteSecretRequest.h> #include <aws/secretsmanager/model/DescribeSecretRequest.h> #include <aws/secretsmanager/model/GetRandomPasswordRequest.h> #include <aws/secretsmanager/model/GetResourcePolicyRequest.h> #include <aws/secretsmanager/model/GetSecretValueRequest.h> #include <aws/secretsmanager/model/ListSecretVersionIdsRequest.h> #include <aws/secretsmanager/model/ListSecretsRequest.h> #include <aws/secretsmanager/model/PutResourcePolicyRequest.h> #include <aws/secretsmanager/model/PutSecretValueRequest.h> #include <aws/secretsmanager/model/RestoreSecretRequest.h> #include <aws/secretsmanager/model/RotateSecretRequest.h> #include <aws/secretsmanager/model/TagResourceRequest.h> #include <aws/secretsmanager/model/UntagResourceRequest.h> #include <aws/secretsmanager/model/UpdateSecretRequest.h> #include <aws/secretsmanager/model/UpdateSecretVersionStageRequest.h> using namespace Aws; using namespace Aws::Auth; using namespace Aws::Client; using namespace Aws::SecretsManager; using namespace Aws::SecretsManager::Model; using namespace Aws::Http; using namespace Aws::Utils::Json; static const char* SERVICE_NAME = "secretsmanager"; static const char* ALLOCATION_TAG = "SecretsManagerClient"; SecretsManagerClient::SecretsManagerClient(const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<DefaultAWSCredentialsProviderChain>(ALLOCATION_TAG), SERVICE_NAME, clientConfiguration.region), Aws::MakeShared<SecretsManagerErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } SecretsManagerClient::SecretsManagerClient(const AWSCredentials& credentials, const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<SimpleAWSCredentialsProvider>(ALLOCATION_TAG, credentials), SERVICE_NAME, clientConfiguration.region), Aws::MakeShared<SecretsManagerErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } SecretsManagerClient::SecretsManagerClient(const std::shared_ptr<AWSCredentialsProvider>& credentialsProvider, const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, credentialsProvider, SERVICE_NAME, clientConfiguration.region), Aws::MakeShared<SecretsManagerErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } SecretsManagerClient::~SecretsManagerClient() { } void SecretsManagerClient::init(const ClientConfiguration& config) { m_configScheme = SchemeMapper::ToString(config.scheme); if (config.endpointOverride.empty()) { m_uri = m_configScheme + "://" + SecretsManagerEndpoint::ForRegion(config.region, config.useDualStack); } else { OverrideEndpoint(config.endpointOverride); } } void SecretsManagerClient::OverrideEndpoint(const Aws::String& endpoint) { if (endpoint.compare(0, 7, "http://") == 0 || endpoint.compare(0, 8, "https://") == 0) { m_uri = endpoint; } else { m_uri = m_configScheme + "://" + endpoint; } } CancelRotateSecretOutcome SecretsManagerClient::CancelRotateSecret(const CancelRotateSecretRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return CancelRotateSecretOutcome(CancelRotateSecretResult(outcome.GetResult())); } else { return CancelRotateSecretOutcome(outcome.GetError()); } } CancelRotateSecretOutcomeCallable SecretsManagerClient::CancelRotateSecretCallable(const CancelRotateSecretRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< CancelRotateSecretOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CancelRotateSecret(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void SecretsManagerClient::CancelRotateSecretAsync(const CancelRotateSecretRequest& request, const CancelRotateSecretResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->CancelRotateSecretAsyncHelper( request, handler, context ); } ); } void SecretsManagerClient::CancelRotateSecretAsyncHelper(const CancelRotateSecretRequest& request, const CancelRotateSecretResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, CancelRotateSecret(request), context); } CreateSecretOutcome SecretsManagerClient::CreateSecret(const CreateSecretRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return CreateSecretOutcome(CreateSecretResult(outcome.GetResult())); } else { return CreateSecretOutcome(outcome.GetError()); } } CreateSecretOutcomeCallable SecretsManagerClient::CreateSecretCallable(const CreateSecretRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< CreateSecretOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateSecret(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void SecretsManagerClient::CreateSecretAsync(const CreateSecretRequest& request, const CreateSecretResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->CreateSecretAsyncHelper( request, handler, context ); } ); } void SecretsManagerClient::CreateSecretAsyncHelper(const CreateSecretRequest& request, const CreateSecretResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, CreateSecret(request), context); } DeleteResourcePolicyOutcome SecretsManagerClient::DeleteResourcePolicy(const DeleteResourcePolicyRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return DeleteResourcePolicyOutcome(DeleteResourcePolicyResult(outcome.GetResult())); } else { return DeleteResourcePolicyOutcome(outcome.GetError()); } } DeleteResourcePolicyOutcomeCallable SecretsManagerClient::DeleteResourcePolicyCallable(const DeleteResourcePolicyRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DeleteResourcePolicyOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteResourcePolicy(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void SecretsManagerClient::DeleteResourcePolicyAsync(const DeleteResourcePolicyRequest& request, const DeleteResourcePolicyResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DeleteResourcePolicyAsyncHelper( request, handler, context ); } ); } void SecretsManagerClient::DeleteResourcePolicyAsyncHelper(const DeleteResourcePolicyRequest& request, const DeleteResourcePolicyResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DeleteResourcePolicy(request), context); } DeleteSecretOutcome SecretsManagerClient::DeleteSecret(const DeleteSecretRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return DeleteSecretOutcome(DeleteSecretResult(outcome.GetResult())); } else { return DeleteSecretOutcome(outcome.GetError()); } } DeleteSecretOutcomeCallable SecretsManagerClient::DeleteSecretCallable(const DeleteSecretRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DeleteSecretOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteSecret(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void SecretsManagerClient::DeleteSecretAsync(const DeleteSecretRequest& request, const DeleteSecretResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DeleteSecretAsyncHelper( request, handler, context ); } ); } void SecretsManagerClient::DeleteSecretAsyncHelper(const DeleteSecretRequest& request, const DeleteSecretResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DeleteSecret(request), context); } DescribeSecretOutcome SecretsManagerClient::DescribeSecret(const DescribeSecretRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return DescribeSecretOutcome(DescribeSecretResult(outcome.GetResult())); } else { return DescribeSecretOutcome(outcome.GetError()); } } DescribeSecretOutcomeCallable SecretsManagerClient::DescribeSecretCallable(const DescribeSecretRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeSecretOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeSecret(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void SecretsManagerClient::DescribeSecretAsync(const DescribeSecretRequest& request, const DescribeSecretResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeSecretAsyncHelper( request, handler, context ); } ); } void SecretsManagerClient::DescribeSecretAsyncHelper(const DescribeSecretRequest& request, const DescribeSecretResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeSecret(request), context); } GetRandomPasswordOutcome SecretsManagerClient::GetRandomPassword(const GetRandomPasswordRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return GetRandomPasswordOutcome(GetRandomPasswordResult(outcome.GetResult())); } else { return GetRandomPasswordOutcome(outcome.GetError()); } } GetRandomPasswordOutcomeCallable SecretsManagerClient::GetRandomPasswordCallable(const GetRandomPasswordRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< GetRandomPasswordOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetRandomPassword(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void SecretsManagerClient::GetRandomPasswordAsync(const GetRandomPasswordRequest& request, const GetRandomPasswordResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->GetRandomPasswordAsyncHelper( request, handler, context ); } ); } void SecretsManagerClient::GetRandomPasswordAsyncHelper(const GetRandomPasswordRequest& request, const GetRandomPasswordResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, GetRandomPassword(request), context); } GetResourcePolicyOutcome SecretsManagerClient::GetResourcePolicy(const GetResourcePolicyRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return GetResourcePolicyOutcome(GetResourcePolicyResult(outcome.GetResult())); } else { return GetResourcePolicyOutcome(outcome.GetError()); } } GetResourcePolicyOutcomeCallable SecretsManagerClient::GetResourcePolicyCallable(const GetResourcePolicyRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< GetResourcePolicyOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetResourcePolicy(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void SecretsManagerClient::GetResourcePolicyAsync(const GetResourcePolicyRequest& request, const GetResourcePolicyResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->GetResourcePolicyAsyncHelper( request, handler, context ); } ); } void SecretsManagerClient::GetResourcePolicyAsyncHelper(const GetResourcePolicyRequest& request, const GetResourcePolicyResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, GetResourcePolicy(request), context); } GetSecretValueOutcome SecretsManagerClient::GetSecretValue(const GetSecretValueRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return GetSecretValueOutcome(GetSecretValueResult(outcome.GetResult())); } else { return GetSecretValueOutcome(outcome.GetError()); } } GetSecretValueOutcomeCallable SecretsManagerClient::GetSecretValueCallable(const GetSecretValueRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< GetSecretValueOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetSecretValue(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void SecretsManagerClient::GetSecretValueAsync(const GetSecretValueRequest& request, const GetSecretValueResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->GetSecretValueAsyncHelper( request, handler, context ); } ); } void SecretsManagerClient::GetSecretValueAsyncHelper(const GetSecretValueRequest& request, const GetSecretValueResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, GetSecretValue(request), context); } ListSecretVersionIdsOutcome SecretsManagerClient::ListSecretVersionIds(const ListSecretVersionIdsRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return ListSecretVersionIdsOutcome(ListSecretVersionIdsResult(outcome.GetResult())); } else { return ListSecretVersionIdsOutcome(outcome.GetError()); } } ListSecretVersionIdsOutcomeCallable SecretsManagerClient::ListSecretVersionIdsCallable(const ListSecretVersionIdsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListSecretVersionIdsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListSecretVersionIds(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void SecretsManagerClient::ListSecretVersionIdsAsync(const ListSecretVersionIdsRequest& request, const ListSecretVersionIdsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListSecretVersionIdsAsyncHelper( request, handler, context ); } ); } void SecretsManagerClient::ListSecretVersionIdsAsyncHelper(const ListSecretVersionIdsRequest& request, const ListSecretVersionIdsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListSecretVersionIds(request), context); } ListSecretsOutcome SecretsManagerClient::ListSecrets(const ListSecretsRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return ListSecretsOutcome(ListSecretsResult(outcome.GetResult())); } else { return ListSecretsOutcome(outcome.GetError()); } } ListSecretsOutcomeCallable SecretsManagerClient::ListSecretsCallable(const ListSecretsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListSecretsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListSecrets(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void SecretsManagerClient::ListSecretsAsync(const ListSecretsRequest& request, const ListSecretsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListSecretsAsyncHelper( request, handler, context ); } ); } void SecretsManagerClient::ListSecretsAsyncHelper(const ListSecretsRequest& request, const ListSecretsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListSecrets(request), context); } PutResourcePolicyOutcome SecretsManagerClient::PutResourcePolicy(const PutResourcePolicyRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return PutResourcePolicyOutcome(PutResourcePolicyResult(outcome.GetResult())); } else { return PutResourcePolicyOutcome(outcome.GetError()); } } PutResourcePolicyOutcomeCallable SecretsManagerClient::PutResourcePolicyCallable(const PutResourcePolicyRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< PutResourcePolicyOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->PutResourcePolicy(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void SecretsManagerClient::PutResourcePolicyAsync(const PutResourcePolicyRequest& request, const PutResourcePolicyResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->PutResourcePolicyAsyncHelper( request, handler, context ); } ); } void SecretsManagerClient::PutResourcePolicyAsyncHelper(const PutResourcePolicyRequest& request, const PutResourcePolicyResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, PutResourcePolicy(request), context); } PutSecretValueOutcome SecretsManagerClient::PutSecretValue(const PutSecretValueRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return PutSecretValueOutcome(PutSecretValueResult(outcome.GetResult())); } else { return PutSecretValueOutcome(outcome.GetError()); } } PutSecretValueOutcomeCallable SecretsManagerClient::PutSecretValueCallable(const PutSecretValueRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< PutSecretValueOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->PutSecretValue(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void SecretsManagerClient::PutSecretValueAsync(const PutSecretValueRequest& request, const PutSecretValueResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->PutSecretValueAsyncHelper( request, handler, context ); } ); } void SecretsManagerClient::PutSecretValueAsyncHelper(const PutSecretValueRequest& request, const PutSecretValueResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, PutSecretValue(request), context); } RestoreSecretOutcome SecretsManagerClient::RestoreSecret(const RestoreSecretRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return RestoreSecretOutcome(RestoreSecretResult(outcome.GetResult())); } else { return RestoreSecretOutcome(outcome.GetError()); } } RestoreSecretOutcomeCallable SecretsManagerClient::RestoreSecretCallable(const RestoreSecretRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< RestoreSecretOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->RestoreSecret(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void SecretsManagerClient::RestoreSecretAsync(const RestoreSecretRequest& request, const RestoreSecretResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->RestoreSecretAsyncHelper( request, handler, context ); } ); } void SecretsManagerClient::RestoreSecretAsyncHelper(const RestoreSecretRequest& request, const RestoreSecretResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, RestoreSecret(request), context); } RotateSecretOutcome SecretsManagerClient::RotateSecret(const RotateSecretRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return RotateSecretOutcome(RotateSecretResult(outcome.GetResult())); } else { return RotateSecretOutcome(outcome.GetError()); } } RotateSecretOutcomeCallable SecretsManagerClient::RotateSecretCallable(const RotateSecretRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< RotateSecretOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->RotateSecret(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void SecretsManagerClient::RotateSecretAsync(const RotateSecretRequest& request, const RotateSecretResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->RotateSecretAsyncHelper( request, handler, context ); } ); } void SecretsManagerClient::RotateSecretAsyncHelper(const RotateSecretRequest& request, const RotateSecretResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, RotateSecret(request), context); } TagResourceOutcome SecretsManagerClient::TagResource(const TagResourceRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return TagResourceOutcome(NoResult()); } else { return TagResourceOutcome(outcome.GetError()); } } TagResourceOutcomeCallable SecretsManagerClient::TagResourceCallable(const TagResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< TagResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->TagResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void SecretsManagerClient::TagResourceAsync(const TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->TagResourceAsyncHelper( request, handler, context ); } ); } void SecretsManagerClient::TagResourceAsyncHelper(const TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, TagResource(request), context); } UntagResourceOutcome SecretsManagerClient::UntagResource(const UntagResourceRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return UntagResourceOutcome(NoResult()); } else { return UntagResourceOutcome(outcome.GetError()); } } UntagResourceOutcomeCallable SecretsManagerClient::UntagResourceCallable(const UntagResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UntagResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UntagResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void SecretsManagerClient::UntagResourceAsync(const UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UntagResourceAsyncHelper( request, handler, context ); } ); } void SecretsManagerClient::UntagResourceAsyncHelper(const UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UntagResource(request), context); } UpdateSecretOutcome SecretsManagerClient::UpdateSecret(const UpdateSecretRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return UpdateSecretOutcome(UpdateSecretResult(outcome.GetResult())); } else { return UpdateSecretOutcome(outcome.GetError()); } } UpdateSecretOutcomeCallable SecretsManagerClient::UpdateSecretCallable(const UpdateSecretRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UpdateSecretOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateSecret(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void SecretsManagerClient::UpdateSecretAsync(const UpdateSecretRequest& request, const UpdateSecretResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UpdateSecretAsyncHelper( request, handler, context ); } ); } void SecretsManagerClient::UpdateSecretAsyncHelper(const UpdateSecretRequest& request, const UpdateSecretResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UpdateSecret(request), context); } UpdateSecretVersionStageOutcome SecretsManagerClient::UpdateSecretVersionStage(const UpdateSecretVersionStageRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return UpdateSecretVersionStageOutcome(UpdateSecretVersionStageResult(outcome.GetResult())); } else { return UpdateSecretVersionStageOutcome(outcome.GetError()); } } UpdateSecretVersionStageOutcomeCallable SecretsManagerClient::UpdateSecretVersionStageCallable(const UpdateSecretVersionStageRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UpdateSecretVersionStageOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateSecretVersionStage(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void SecretsManagerClient::UpdateSecretVersionStageAsync(const UpdateSecretVersionStageRequest& request, const UpdateSecretVersionStageResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UpdateSecretVersionStageAsyncHelper( request, handler, context ); } ); } void SecretsManagerClient::UpdateSecretVersionStageAsyncHelper(const UpdateSecretVersionStageRequest& request, const UpdateSecretVersionStageResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UpdateSecretVersionStage(request), context); }
//============================================================================= /** * @file Message_Block_Large_Copy_Test.cpp * * $Id: Message_Block_Large_Copy_Test.cpp 96760 2013-02-05 21:11:03Z stanleyk $ * * This test program tests large Message Block duplication and cloning. * * * @author Phillip LaBanca <labancap@ociweb.com> */ //============================================================================= #include "test_config.h" #include "ace/Message_Block.h" size_t run_duplicate_test (const size_t msg_block_count, const char * block, const size_t msg_block_size) { size_t rc = 0; ACE_Message_Block* mb_top = new ACE_Message_Block (); ACE_Message_Block* mb = mb_top; for (size_t j = 0; j != msg_block_count; ++j) { ACE_Message_Block* next = new ACE_Message_Block (block, msg_block_size); next->copy (block); mb->cont (next); mb = next; } ACE_Message_Block* mb_test = mb_top->duplicate (); if (mb_test != 0) { rc = mb_test->total_size(); ACE_ERROR ((LM_DEBUG, ACE_TEXT ("(%P|%t) %u top reference_count ()\n"), mb_top->reference_count ())); ACE_ERROR ((LM_DEBUG, ACE_TEXT ("(%P|%t) duplicated: %@ %d %d\n"), mb_test, mb_test->total_size(), mb_test->total_length())); mb_test-> release(); } ACE_ERROR ((LM_DEBUG, ACE_TEXT ("(%P|%t) %u top reference_count ()\n"), mb_top->reference_count ())); mb_top-> release (); return rc; } size_t run_clone_test (const size_t msg_block_count, const char * block, const size_t msg_block_size) { size_t rc = 0; ACE_Message_Block* mb_top = new ACE_Message_Block (); ACE_Message_Block* mb = mb_top; for (size_t j = 0; j != msg_block_count; ++j) { ACE_Message_Block* next = new ACE_Message_Block (block, msg_block_size); next->copy (block); mb->cont (next); mb = next; } ACE_Message_Block* mb_test = mb_top->clone (); if (mb_test != 0) { rc = mb_test->total_size(); ACE_ERROR ((LM_DEBUG, ACE_TEXT ("(%P|%t) %u top reference_count ()\n"), mb_top->reference_count ())); ACE_ERROR ((LM_DEBUG, ACE_TEXT ("(%P|%t) cloned: %@ %d %d\n"), mb_test, mb_test->total_size(), mb_test->total_length())); mb_test-> release(); } ACE_ERROR ((LM_DEBUG, ACE_TEXT ("(%P|%t) %u top reference_count ()\n"), mb_top->reference_count ())); mb_top-> release(); return rc; } int run_main (int , ACE_TCHAR *[]) { int rc = 0; ACE_START_TEST (ACE_TEXT ("Message_Block_Large_Copy_Test")); { // Message_Block size() and Length() of 24,000,000 const size_t MSG_BLOCK_COUNT = 8000; const size_t MSG_BLOCK_SIZE = 3000; const size_t MSG_BLOCK_TOTAL = MSG_BLOCK_COUNT * MSG_BLOCK_SIZE; ACE_ERROR ((LM_DEBUG, ACE_TEXT ("(%P|%t) %u blocks %u bytes each, total %u\n"), MSG_BLOCK_COUNT, MSG_BLOCK_SIZE, MSG_BLOCK_TOTAL)); char block[MSG_BLOCK_SIZE]; for(size_t j = 0 ; j != MSG_BLOCK_SIZE; j++) block[j] = 'A'; block[MSG_BLOCK_SIZE-1] = 0; size_t duplicate_total = run_duplicate_test ( MSG_BLOCK_COUNT, block, MSG_BLOCK_SIZE); if (duplicate_total != MSG_BLOCK_TOTAL ) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%P|%t) duplicate(): returned total of %u\n"), duplicate_total)); rc = 1; } size_t clone_total = run_clone_test ( MSG_BLOCK_COUNT, block, MSG_BLOCK_SIZE); if (clone_total != MSG_BLOCK_TOTAL ) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%P|%t) clone(): returned total of %u \n"), clone_total)); rc = 1; } } ACE_END_TEST; return rc; }
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/loader/threadable_loading_context.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/loader/worker_fetch_context.h" #include "third_party/blink/renderer/core/workers/worker_global_scope.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h" namespace blink { class DocumentThreadableLoadingContext final : public ThreadableLoadingContext { public: explicit DocumentThreadableLoadingContext(Document& document) : document_(&document) {} ~DocumentThreadableLoadingContext() override = default; ResourceFetcher* GetResourceFetcher() override { DCHECK(IsContextThread()); return document_->Fetcher(); } ExecutionContext* GetExecutionContext() override { DCHECK(IsContextThread()); return document_.Get(); } void Trace(blink::Visitor* visitor) override { visitor->Trace(document_); ThreadableLoadingContext::Trace(visitor); } private: bool IsContextThread() const { return document_->IsContextThread(); } Member<Document> document_; }; class WorkerThreadableLoadingContext : public ThreadableLoadingContext { public: explicit WorkerThreadableLoadingContext( WorkerGlobalScope& worker_global_scope) : worker_global_scope_(&worker_global_scope) {} ~WorkerThreadableLoadingContext() override = default; ResourceFetcher* GetResourceFetcher() override { DCHECK(IsContextThread()); return worker_global_scope_->EnsureFetcher(); } ExecutionContext* GetExecutionContext() override { DCHECK(IsContextThread()); return worker_global_scope_.Get(); } void Trace(blink::Visitor* visitor) override { visitor->Trace(worker_global_scope_); ThreadableLoadingContext::Trace(visitor); } private: bool IsContextThread() const { DCHECK(worker_global_scope_); return worker_global_scope_->IsContextThread(); } Member<WorkerGlobalScope> worker_global_scope_; }; ThreadableLoadingContext* ThreadableLoadingContext::Create( ExecutionContext& context) { if (context.IsDocument()) return new DocumentThreadableLoadingContext(ToDocument(context)); if (context.IsWorkerGlobalScope()) return new WorkerThreadableLoadingContext(ToWorkerGlobalScope(context)); NOTREACHED(); return nullptr; } BaseFetchContext* ThreadableLoadingContext::GetFetchContext() { return static_cast<BaseFetchContext*>(&GetResourceFetcher()->Context()); } } // namespace blink
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2017 - ROLI Ltd. JUCE is an open source library subject to commercial or open-source licensing. By using JUCE, you agree to the terms of both the JUCE 5 End-User License Agreement and JUCE 5 Privacy Policy (both updated and effective as of the 27th April 2017). End User License Agreement: www.juce.com/juce-5-licence Privacy Policy: www.juce.com/juce-5-privacy-policy Or: You may also use this code under the terms of the GPL v3 (see www.gnu.org/licenses). JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { struct MarkerListScope : public Expression::Scope { MarkerListScope (Component& comp) : component (comp) {} // Suppress a VS2013 compiler warning MarkerListScope& operator= (const MarkerListScope&) = delete; Expression getSymbolValue (const String& symbol) const override { switch (RelativeCoordinate::StandardStrings::getTypeOf (symbol)) { case RelativeCoordinate::StandardStrings::width: return Expression ((double) component.getWidth()); case RelativeCoordinate::StandardStrings::height: return Expression ((double) component.getHeight()); default: break; } MarkerList* list; if (auto* marker = findMarker (component, symbol, list)) return Expression (marker->position.getExpression().evaluate (*this)); return Expression::Scope::getSymbolValue (symbol); } void visitRelativeScope (const String& scopeName, Visitor& visitor) const override { if (scopeName == RelativeCoordinate::Strings::parent) { if (auto* parent = component.getParentComponent()) { visitor.visit (MarkerListScope (*parent)); return; } } Expression::Scope::visitRelativeScope (scopeName, visitor); } String getScopeUID() const override { return String::toHexString ((pointer_sized_int) (void*) &component) + "m"; } static const MarkerList::Marker* findMarker (Component& component, const String& name, MarkerList*& list) { const MarkerList::Marker* marker = nullptr; list = component.getMarkers (true); if (list != nullptr) marker = list->getMarker (name); if (marker == nullptr) { list = component.getMarkers (false); if (list != nullptr) marker = list->getMarker (name); } return marker; } Component& component; }; //============================================================================== RelativeCoordinatePositionerBase::ComponentScope::ComponentScope (Component& comp) : component (comp) { } Expression RelativeCoordinatePositionerBase::ComponentScope::getSymbolValue (const String& symbol) const { switch (RelativeCoordinate::StandardStrings::getTypeOf (symbol)) { case RelativeCoordinate::StandardStrings::x: case RelativeCoordinate::StandardStrings::left: return Expression ((double) component.getX()); case RelativeCoordinate::StandardStrings::y: case RelativeCoordinate::StandardStrings::top: return Expression ((double) component.getY()); case RelativeCoordinate::StandardStrings::width: return Expression ((double) component.getWidth()); case RelativeCoordinate::StandardStrings::height: return Expression ((double) component.getHeight()); case RelativeCoordinate::StandardStrings::right: return Expression ((double) component.getRight()); case RelativeCoordinate::StandardStrings::bottom: return Expression ((double) component.getBottom()); default: break; } if (Component* const parent = component.getParentComponent()) { MarkerList* list; if (const MarkerList::Marker* const marker = MarkerListScope::findMarker (*parent, symbol, list)) { MarkerListScope scope (*parent); return Expression (marker->position.getExpression().evaluate (scope)); } } return Expression::Scope::getSymbolValue (symbol); } void RelativeCoordinatePositionerBase::ComponentScope::visitRelativeScope (const String& scopeName, Visitor& visitor) const { if (auto* targetComp = (scopeName == RelativeCoordinate::Strings::parent) ? component.getParentComponent() : findSiblingComponent (scopeName)) visitor.visit (ComponentScope (*targetComp)); else Expression::Scope::visitRelativeScope (scopeName, visitor); } String RelativeCoordinatePositionerBase::ComponentScope::getScopeUID() const { return String::toHexString ((pointer_sized_int) (void*) &component); } Component* RelativeCoordinatePositionerBase::ComponentScope::findSiblingComponent (const String& componentID) const { if (Component* const parent = component.getParentComponent()) return parent->findChildWithID (componentID); return nullptr; } //============================================================================== class RelativeCoordinatePositionerBase::DependencyFinderScope : public ComponentScope { public: DependencyFinderScope (Component& comp, RelativeCoordinatePositionerBase& p, bool& result) : ComponentScope (comp), positioner (p), ok (result) { } Expression getSymbolValue (const String& symbol) const override { switch (RelativeCoordinate::StandardStrings::getTypeOf (symbol)) { case RelativeCoordinate::StandardStrings::x: case RelativeCoordinate::StandardStrings::left: case RelativeCoordinate::StandardStrings::y: case RelativeCoordinate::StandardStrings::top: case RelativeCoordinate::StandardStrings::width: case RelativeCoordinate::StandardStrings::height: case RelativeCoordinate::StandardStrings::right: case RelativeCoordinate::StandardStrings::bottom: positioner.registerComponentListener (component); break; default: if (Component* const parent = component.getParentComponent()) { MarkerList* list; if (MarkerListScope::findMarker (*parent, symbol, list) != nullptr) { positioner.registerMarkerListListener (list); } else { // The marker we want doesn't exist, so watch all lists in case they change and the marker appears later.. positioner.registerMarkerListListener (parent->getMarkers (true)); positioner.registerMarkerListListener (parent->getMarkers (false)); ok = false; } } break; } return ComponentScope::getSymbolValue (symbol); } void visitRelativeScope (const String& scopeName, Visitor& visitor) const override { if (Component* const targetComp = (scopeName == RelativeCoordinate::Strings::parent) ? component.getParentComponent() : findSiblingComponent (scopeName)) { visitor.visit (DependencyFinderScope (*targetComp, positioner, ok)); } else { // The named component doesn't exist, so we'll watch the parent for changes in case it appears later.. if (Component* const parent = component.getParentComponent()) positioner.registerComponentListener (*parent); positioner.registerComponentListener (component); ok = false; } } private: RelativeCoordinatePositionerBase& positioner; bool& ok; }; //============================================================================== RelativeCoordinatePositionerBase::RelativeCoordinatePositionerBase (Component& comp) : Component::Positioner (comp), registeredOk (false) { } RelativeCoordinatePositionerBase::~RelativeCoordinatePositionerBase() { unregisterListeners(); } void RelativeCoordinatePositionerBase::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/) { apply(); } void RelativeCoordinatePositionerBase::componentParentHierarchyChanged (Component&) { apply(); } void RelativeCoordinatePositionerBase::componentChildrenChanged (Component& changed) { if (getComponent().getParentComponent() == &changed && ! registeredOk) apply(); } void RelativeCoordinatePositionerBase::componentBeingDeleted (Component& comp) { jassert (sourceComponents.contains (&comp)); sourceComponents.removeFirstMatchingValue (&comp); registeredOk = false; } void RelativeCoordinatePositionerBase::markersChanged (MarkerList*) { apply(); } void RelativeCoordinatePositionerBase::markerListBeingDeleted (MarkerList* markerList) { jassert (sourceMarkerLists.contains (markerList)); sourceMarkerLists.removeFirstMatchingValue (markerList); } void RelativeCoordinatePositionerBase::apply() { if (! registeredOk) { unregisterListeners(); registeredOk = registerCoordinates(); } applyToComponentBounds(); } bool RelativeCoordinatePositionerBase::addCoordinate (const RelativeCoordinate& coord) { bool ok = true; DependencyFinderScope finderScope (getComponent(), *this, ok); coord.getExpression().evaluate (finderScope); return ok; } bool RelativeCoordinatePositionerBase::addPoint (const RelativePoint& point) { const bool ok = addCoordinate (point.x); return addCoordinate (point.y) && ok; } void RelativeCoordinatePositionerBase::registerComponentListener (Component& comp) { if (! sourceComponents.contains (&comp)) { comp.addComponentListener (this); sourceComponents.add (&comp); } } void RelativeCoordinatePositionerBase::registerMarkerListListener (MarkerList* const list) { if (list != nullptr && ! sourceMarkerLists.contains (list)) { list->addListener (this); sourceMarkerLists.add (list); } } void RelativeCoordinatePositionerBase::unregisterListeners() { for (int i = sourceComponents.size(); --i >= 0;) sourceComponents.getUnchecked(i)->removeComponentListener (this); for (int i = sourceMarkerLists.size(); --i >= 0;) sourceMarkerLists.getUnchecked(i)->removeListener (this); sourceComponents.clear(); sourceMarkerLists.clear(); } } // namespace juce
//========= Copyright Valve Corporation, All rights reserved. ============// // // Run procedural glint generation inner loop in pixel shader // // $Header: $ // $NoKeywords: $ //===========================================================================// #include "BaseVSShader.h" #include "shaderlib/cshader.h" #include "eyeglint_vs20.inc" #include "eyeglint_ps20.inc" #include "eyeglint_ps20b.inc" DEFINE_FALLBACK_SHADER( EyeGlint, EyeGlint_dx9 ) BEGIN_VS_SHADER( EyeGlint_dx9, "Help for EyeGlint" ) BEGIN_SHADER_PARAMS END_SHADER_PARAMS SHADER_INIT { } SHADER_FALLBACK { if ( g_pHardwareConfig->GetDXSupportLevel() < 90 ) { return "Wireframe"; } return 0; } SHADER_DRAW { SHADOW_STATE { pShaderShadow->EnableDepthWrites( false ); pShaderShadow->EnableBlending( true ); pShaderShadow->BlendFunc( SHADER_BLEND_ONE, SHADER_BLEND_ONE ); // Additive blending int pTexCoords[3] = { 2, 2, 3 }; pShaderShadow->VertexShaderVertexFormat( VERTEX_POSITION, 3, pTexCoords, 0 ); pShaderShadow->EnableCulling( false ); pShaderShadow->EnableSRGBWrite( false ); // linear texture DECLARE_STATIC_VERTEX_SHADER( eyeglint_vs20 ); SET_STATIC_VERTEX_SHADER( eyeglint_vs20 ); SET_STATIC_PS2X_PIXEL_SHADER_NO_COMBOS( eyeglint ); } DYNAMIC_STATE { DECLARE_DYNAMIC_VERTEX_SHADER( eyeglint_vs20 ); SET_DYNAMIC_VERTEX_SHADER( eyeglint_vs20 ); SET_DYNAMIC_PS2X_PIXEL_SHADER_NO_COMBOS( eyeglint ); } Draw(); } END_SHADER
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2019 The WaStaKe Core 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/wastake-config.h" #endif #include "net.h" #include "addrman.h" #include "chainparams.h" #include "clientversion.h" #include "miner.h" #include "obfuscation.h" #include "primitives/transaction.h" #include "ui_interface.h" #include "wallet.h" #ifdef WIN32 #include <string.h> #else #include <fcntl.h> #endif #ifdef USE_UPNP #include <miniupnpc/miniupnpc.h> #include <miniupnpc/miniwget.h> #include <miniupnpc/upnpcommands.h> #include <miniupnpc/upnperrors.h> #endif #include <boost/filesystem.hpp> #include <boost/thread.hpp> // Dump addresses to peers.dat every 15 minutes (900s) #define DUMP_ADDRESSES_INTERVAL 900 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL) #define MSG_NOSIGNAL 0 #endif // Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h. // Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version. #ifdef WIN32 #ifndef PROTECTION_LEVEL_UNRESTRICTED #define PROTECTION_LEVEL_UNRESTRICTED 10 #endif #ifndef IPV6_PROTECTION_LEVEL #define IPV6_PROTECTION_LEVEL 23 #endif #endif using namespace boost; using namespace std; namespace { const int MAX_OUTBOUND_CONNECTIONS = 16; struct ListenSocket { SOCKET socket; bool whitelisted; ListenSocket(SOCKET socket, bool whitelisted) : socket(socket), whitelisted(whitelisted) {} }; } // // Global state variables // bool fDiscover = true; bool fListen = true; uint64_t nLocalServices = NODE_NETWORK; CCriticalSection cs_mapLocalHost; map<CNetAddr, LocalServiceInfo> mapLocalHost; static bool vfReachable[NET_MAX] = {}; static bool vfLimited[NET_MAX] = {}; static CNode* pnodeLocalHost = NULL; uint64_t nLocalHostNonce = 0; static std::vector<ListenSocket> vhListenSocket; CAddrMan addrman; int nMaxConnections = 125; bool fAddressesInitialized = false; vector<CNode*> vNodes; CCriticalSection cs_vNodes; map<CInv, CDataStream> mapRelay; deque<pair<int64_t, CInv> > vRelayExpiration; CCriticalSection cs_mapRelay; limitedmap<CInv, int64_t> mapAlreadyAskedFor(MAX_INV_SZ); static deque<string> vOneShots; CCriticalSection cs_vOneShots; set<CNetAddr> setservAddNodeAddresses; CCriticalSection cs_setservAddNodeAddresses; vector<std::string> vAddedNodes; CCriticalSection cs_vAddedNodes; NodeId nLastNodeId = 0; CCriticalSection cs_nLastNodeId; static CSemaphore* semOutbound = NULL; boost::condition_variable messageHandlerCondition; // Signals for message handling static CNodeSignals g_signals; CNodeSignals& GetNodeSignals() { return g_signals; } void AddOneShot(string strDest) { LOCK(cs_vOneShots); vOneShots.push_back(strDest); } unsigned short GetListenPort() { return (unsigned short)(GetArg("-port", Params().GetDefaultPort())); } // find 'best' local address for a particular peer bool GetLocal(CService& addr, const CNetAddr* paddrPeer) { if (!fListen) return false; int nBestScore = -1; int nBestReachability = -1; { LOCK(cs_mapLocalHost); for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) { int nScore = (*it).second.nScore; int nReachability = (*it).first.GetReachabilityFrom(paddrPeer); if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) { addr = CService((*it).first, (*it).second.nPort); nBestReachability = nReachability; nBestScore = nScore; } } } return nBestScore >= 0; } // get best local address for a particular peer as a CAddress // Otherwise, return the unroutable 0.0.0.0 but filled in with // the normal parameters, since the IP may be changed to a useful // one by discovery. CAddress GetLocalAddress(const CNetAddr* paddrPeer) { CAddress ret(CService("0.0.0.0", GetListenPort()), 0); CService addr; if (GetLocal(addr, paddrPeer)) { ret = CAddress(addr); } ret.nServices = nLocalServices; ret.nTime = GetAdjustedTime(); return ret; } bool RecvLine(SOCKET hSocket, string& strLine) { strLine = ""; while (true) { char c; int nBytes = recv(hSocket, &c, 1, 0); if (nBytes > 0) { if (c == '\n') continue; if (c == '\r') return true; strLine += c; if (strLine.size() >= 9000) return true; } else if (nBytes <= 0) { boost::this_thread::interruption_point(); if (nBytes < 0) { int nErr = WSAGetLastError(); if (nErr == WSAEMSGSIZE) continue; if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS) { MilliSleep(10); continue; } } if (!strLine.empty()) return true; if (nBytes == 0) { // socket closed LogPrint("net", "socket closed\n"); return false; } else { // socket error int nErr = WSAGetLastError(); LogPrint("net", "recv failed: %s\n", NetworkErrorString(nErr)); return false; } } } } int GetnScore(const CService& addr) { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == LOCAL_NONE) return 0; return mapLocalHost[addr].nScore; } // Is our peer's addrLocal potentially useful as an external IP source? bool IsPeerAddrLocalGood(CNode* pnode) { return fDiscover && pnode->addr.IsRoutable() && pnode->addrLocal.IsRoutable() && !IsLimited(pnode->addrLocal.GetNetwork()); } // pushes our own address to a peer void AdvertiseLocal(CNode* pnode) { if (fListen && pnode->fSuccessfullyConnected) { CAddress addrLocal = GetLocalAddress(&pnode->addr); // If discovery is enabled, sometimes give our peer the address it // tells us that it sees us as in case it has a better idea of our // address than we do. if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() || GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8 : 2) == 0)) { addrLocal.SetIP(pnode->addrLocal); } if (addrLocal.IsRoutable()) { LogPrintf("AdvertizeLocal: advertizing address %s\n", addrLocal.ToString()); pnode->PushAddress(addrLocal); } } } void SetReachable(enum Network net, bool fFlag) { LOCK(cs_mapLocalHost); vfReachable[net] = fFlag; if (net == NET_IPV6 && fFlag) vfReachable[NET_IPV4] = true; } // learn a new local address bool AddLocal(const CService& addr, int nScore) { if (!addr.IsRoutable()) return false; if (!fDiscover && nScore < LOCAL_MANUAL) return false; if (IsLimited(addr)) return false; LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore); { LOCK(cs_mapLocalHost); bool fAlready = mapLocalHost.count(addr) > 0; LocalServiceInfo& info = mapLocalHost[addr]; if (!fAlready || nScore >= info.nScore) { info.nScore = nScore + (fAlready ? 1 : 0); info.nPort = addr.GetPort(); } SetReachable(addr.GetNetwork()); } return true; } bool AddLocal(const CNetAddr& addr, int nScore) { return AddLocal(CService(addr, GetListenPort()), nScore); } bool RemoveLocal(const CService& addr) { LOCK(cs_mapLocalHost); LogPrintf("RemoveLocal(%s)\n", addr.ToString()); mapLocalHost.erase(addr); return true; } /** Make a particular network entirely off-limits (no automatic connects to it) */ void SetLimited(enum Network net, bool fLimited) { if (net == NET_UNROUTABLE) return; LOCK(cs_mapLocalHost); vfLimited[net] = fLimited; } bool IsLimited(enum Network net) { LOCK(cs_mapLocalHost); return vfLimited[net]; } bool IsLimited(const CNetAddr& addr) { return IsLimited(addr.GetNetwork()); } /** vote for a local address */ bool SeenLocal(const CService& addr) { { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == 0) return false; mapLocalHost[addr].nScore++; } return true; } /** check whether a given address is potentially local */ bool IsLocal(const CService& addr) { LOCK(cs_mapLocalHost); return mapLocalHost.count(addr) > 0; } /** check whether a given network is one we can probably connect to */ bool IsReachable(enum Network net) { LOCK(cs_mapLocalHost); return vfReachable[net] && !vfLimited[net]; } /** check whether a given address is in a network we can probably connect to */ bool IsReachable(const CNetAddr& addr) { enum Network net = addr.GetNetwork(); return IsReachable(net); } void AddressCurrentlyConnected(const CService& addr) { addrman.Connected(addr); } uint64_t CNode::nTotalBytesRecv = 0; uint64_t CNode::nTotalBytesSent = 0; CCriticalSection CNode::cs_totalBytesRecv; CCriticalSection CNode::cs_totalBytesSent; CNode* FindNode(const CNetAddr& ip) { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) if ((CNetAddr)pnode->addr == ip) return (pnode); return NULL; } CNode* FindNode(const std::string& addrName) { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) if (pnode->addrName == addrName) return (pnode); return NULL; } CNode* FindNode(const CService& addr) { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) { if (Params().NetworkID() == CBaseChainParams::REGTEST) { //if using regtest, just check the IP if ((CNetAddr)pnode->addr == (CNetAddr)addr) return (pnode); } else { if (pnode->addr == addr) return (pnode); } } return NULL; } CNode* ConnectNode(CAddress addrConnect, const char* pszDest, bool obfuScationMaster) { if (pszDest == NULL) { // we clean masternode connections in CMasternodeMan::ProcessMasternodeConnections() // so should be safe to skip this and connect to local Hot MN on CActiveMasternode::ManageStatus() if (IsLocal(addrConnect) && !obfuScationMaster) return NULL; // Look for an existing connection CNode* pnode = FindNode((CService)addrConnect); if (pnode) { pnode->fObfuScationMaster = obfuScationMaster; pnode->AddRef(); return pnode; } } /// debug print LogPrint("net", "trying connection %s lastseen=%.1fhrs\n", pszDest ? pszDest : addrConnect.ToString(), pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime) / 3600.0); // Connect SOCKET hSocket; bool proxyConnectionFailed = false; if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort(), nConnectTimeout, &proxyConnectionFailed) : ConnectSocket(addrConnect, hSocket, nConnectTimeout, &proxyConnectionFailed)) { if (!IsSelectableSocket(hSocket)) { LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n"); CloseSocket(hSocket); return NULL; } addrman.Attempt(addrConnect); // Add node CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false); pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); } pnode->nTimeConnected = GetTime(); if (obfuScationMaster) pnode->fObfuScationMaster = true; return pnode; } else if (!proxyConnectionFailed) { // If connecting to the node failed, and failure is not caused by a problem connecting to // the proxy, mark this as an attempt. addrman.Attempt(addrConnect); } return NULL; } void CNode::CloseSocketDisconnect() { fDisconnect = true; if (hSocket != INVALID_SOCKET) { LogPrint("net", "disconnecting peer=%d\n", id); CloseSocket(hSocket); } // in case this fails, we'll empty the recv buffer when the CNode is deleted TRY_LOCK(cs_vRecvMsg, lockRecv); if (lockRecv) vRecvMsg.clear(); } bool CNode::DisconnectOldProtocol(int nVersionRequired, string strLastCommand) { fDisconnect = false; if (nVersion < nVersionRequired) { LogPrintf("%s : peer=%d using obsolete version %i; disconnecting\n", __func__, id, nVersion); PushMessage("reject", strLastCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", ActiveProtocol())); fDisconnect = true; } return fDisconnect; } void CNode::PushVersion() { int nBestHeight = g_signals.GetHeight().get_value_or(0); /// when NTP implemented, change to just nTime = GetAdjustedTime() int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime()); CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0", 0))); CAddress addrMe = GetLocalAddress(&addr); GetRandBytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce)); if (fLogIPs) LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), id); else LogPrint("net", "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), id); PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe, nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight, true); } std::map<CNetAddr, int64_t> CNode::setBanned; CCriticalSection CNode::cs_setBanned; void CNode::ClearBanned() { setBanned.clear(); } bool CNode::IsBanned(CNetAddr ip) { bool fResult = false; { LOCK(cs_setBanned); std::map<CNetAddr, int64_t>::iterator i = setBanned.find(ip); if (i != setBanned.end()) { int64_t t = (*i).second; if (GetTime() < t) fResult = true; } } return fResult; } bool CNode::Ban(const CNetAddr& addr) { int64_t banTime = GetTime() + GetArg("-bantime", 60 * 60 * 24); // Default 24-hour ban { LOCK(cs_setBanned); if (setBanned[addr] < banTime) setBanned[addr] = banTime; } return true; } std::vector<CSubNet> CNode::vWhitelistedRange; CCriticalSection CNode::cs_vWhitelistedRange; bool CNode::IsWhitelistedRange(const CNetAddr& addr) { LOCK(cs_vWhitelistedRange); BOOST_FOREACH (const CSubNet& subnet, vWhitelistedRange) { if (subnet.Match(addr)) return true; } return false; } void CNode::AddWhitelistedRange(const CSubNet& subnet) { LOCK(cs_vWhitelistedRange); vWhitelistedRange.push_back(subnet); } #undef X #define X(name) stats.name = name void CNode::copyStats(CNodeStats& stats) { stats.nodeid = this->GetId(); X(nServices); X(nLastSend); X(nLastRecv); X(nTimeConnected); X(addrName); X(nVersion); X(cleanSubVer); X(fInbound); X(nStartingHeight); X(nSendBytes); X(nRecvBytes); X(fWhitelisted); // It is common for nodes with good ping times to suddenly become lagged, // due to a new block arriving or other large transfer. // Merely reporting pingtime might fool the caller into thinking the node was still responsive, // since pingtime does not update until the ping is complete, which might take a while. // So, if a ping is taking an unusually long time in flight, // the caller can immediately detect that this is happening. int64_t nPingUsecWait = 0; if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) { nPingUsecWait = GetTimeMicros() - nPingUsecStart; } // Raw ping time is in microseconds, but show it to user as whole seconds (wastake users should be well used to small numbers with many decimal places by now :) stats.dPingTime = (((double)nPingUsecTime) / 1e6); stats.dPingWait = (((double)nPingUsecWait) / 1e6); // Leave string empty if addrLocal invalid (not filled in yet) stats.addrLocal = addrLocal.IsValid() ? addrLocal.ToString() : ""; } #undef X // requires LOCK(cs_vRecvMsg) bool CNode::ReceiveMsgBytes(const char* pch, unsigned int nBytes) { while (nBytes > 0) { // get current incomplete message, or create a new one if (vRecvMsg.empty() || vRecvMsg.back().complete()) vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion)); CNetMessage& msg = vRecvMsg.back(); // absorb network data int handled; if (!msg.in_data) handled = msg.readHeader(pch, nBytes); else handled = msg.readData(pch, nBytes); if (handled < 0) return false; if (msg.in_data && msg.hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) { LogPrint("net", "Oversized message from peer=%i, disconnecting", GetId()); return false; } pch += handled; nBytes -= handled; if (msg.complete()) { msg.nTime = GetTimeMicros(); messageHandlerCondition.notify_one(); } } return true; } int CNetMessage::readHeader(const char* pch, unsigned int nBytes) { // copy data to temporary parsing buffer unsigned int nRemaining = 24 - nHdrPos; unsigned int nCopy = std::min(nRemaining, nBytes); memcpy(&hdrbuf[nHdrPos], pch, nCopy); nHdrPos += nCopy; // if header incomplete, exit if (nHdrPos < 24) return nCopy; // deserialize to CMessageHeader try { hdrbuf >> hdr; } catch (const std::exception&) { return -1; } // reject messages larger than MAX_SIZE if (hdr.nMessageSize > MAX_SIZE) return -1; // switch state to reading message data in_data = true; return nCopy; } int CNetMessage::readData(const char* pch, unsigned int nBytes) { unsigned int nRemaining = hdr.nMessageSize - nDataPos; unsigned int nCopy = std::min(nRemaining, nBytes); if (vRecv.size() < nDataPos + nCopy) { // Allocate up to 256 KiB ahead, but never more than the total message size. vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024)); } memcpy(&vRecv[nDataPos], pch, nCopy); nDataPos += nCopy; return nCopy; } // requires LOCK(cs_vSend) void SocketSendData(CNode* pnode) { std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin(); while (it != pnode->vSendMsg.end()) { const CSerializeData& data = *it; assert(data.size() > pnode->nSendOffset); int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT); if (nBytes > 0) { pnode->nLastSend = GetTime(); pnode->nSendBytes += nBytes; pnode->nSendOffset += nBytes; pnode->RecordBytesSent(nBytes); if (pnode->nSendOffset == data.size()) { pnode->nSendOffset = 0; pnode->nSendSize -= data.size(); it++; } else { // could not send full message; stop sending more break; } } else { if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { LogPrintf("socket send error %s\n", NetworkErrorString(nErr)); pnode->CloseSocketDisconnect(); } } // couldn't send anything at all break; } } if (it == pnode->vSendMsg.end()) { assert(pnode->nSendOffset == 0); assert(pnode->nSendSize == 0); } pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it); } static list<CNode*> vNodesDisconnected; void ThreadSocketHandler() { unsigned int nPrevNodeCount = 0; while (true) { // // Disconnect nodes // { LOCK(cs_vNodes); // Disconnect unused nodes vector<CNode*> vNodesCopy = vNodes; BOOST_FOREACH (CNode* pnode, vNodesCopy) { if (pnode->fDisconnect || (pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty())) { // remove from vNodes vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end()); // release outbound grant (if any) pnode->grantOutbound.Release(); // close socket and cleanup pnode->CloseSocketDisconnect(); // hold in disconnected pool until all refs are released if (pnode->fNetworkNode || pnode->fInbound) pnode->Release(); vNodesDisconnected.push_back(pnode); } } } { // Delete disconnected nodes list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected; BOOST_FOREACH (CNode* pnode, vNodesDisconnectedCopy) { // wait until threads are done using it if (pnode->GetRefCount() <= 0) { bool fDelete = false; { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { TRY_LOCK(pnode->cs_inventory, lockInv); if (lockInv) fDelete = true; } } } if (fDelete) { vNodesDisconnected.remove(pnode); delete pnode; } } } } size_t vNodesSize; { LOCK(cs_vNodes); vNodesSize = vNodes.size(); } if(vNodesSize != nPrevNodeCount) { nPrevNodeCount = vNodesSize; uiInterface.NotifyNumConnectionsChanged(nPrevNodeCount); } // // Find which sockets have data to receive // struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 50000; // frequency to poll pnode->vSend fd_set fdsetRecv; fd_set fdsetSend; fd_set fdsetError; FD_ZERO(&fdsetRecv); FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); SOCKET hSocketMax = 0; bool have_fds = false; BOOST_FOREACH (const ListenSocket& hListenSocket, vhListenSocket) { FD_SET(hListenSocket.socket, &fdsetRecv); hSocketMax = max(hSocketMax, hListenSocket.socket); have_fds = true; } { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) { if (pnode->hSocket == INVALID_SOCKET) continue; FD_SET(pnode->hSocket, &fdsetError); hSocketMax = max(hSocketMax, pnode->hSocket); have_fds = true; // Implement the following logic: // * If there is data to send, select() for sending data. As this only // happens when optimistic write failed, we choose to first drain the // write buffer in this case before receiving more. This avoids // needlessly queueing received data, if the remote peer is not themselves // receiving data. This means properly utilizing TCP flow control signalling. // * Otherwise, if there is no (complete) message in the receive buffer, // or there is space left in the buffer, select() for receiving data. // * (if neither of the above applies, there is certainly one message // in the receiver buffer ready to be processed). // Together, that means that at least one of the following is always possible, // so we don't deadlock: // * We send some data. // * We wait for data to be received (and disconnect after timeout). // * We process a message in the buffer (message handler thread). { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend && !pnode->vSendMsg.empty()) { FD_SET(pnode->hSocket, &fdsetSend); continue; } } { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv && (pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() || pnode->GetTotalRecvSize() <= ReceiveFloodSize())) FD_SET(pnode->hSocket, &fdsetRecv); } } } int nSelect = select(have_fds ? hSocketMax + 1 : 0, &fdsetRecv, &fdsetSend, &fdsetError, &timeout); boost::this_thread::interruption_point(); if (nSelect == SOCKET_ERROR) { if (have_fds) { int nErr = WSAGetLastError(); LogPrintf("socket select error %s\n", NetworkErrorString(nErr)); for (unsigned int i = 0; i <= hSocketMax; i++) FD_SET(i, &fdsetRecv); } FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); MilliSleep(timeout.tv_usec / 1000); } // // Accept new connections // BOOST_FOREACH (const ListenSocket& hListenSocket, vhListenSocket) { if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv)) { struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len); CAddress addr; int nInbound = 0; if (hSocket != INVALID_SOCKET) if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) LogPrintf("Warning: Unknown socket family\n"); bool whitelisted = hListenSocket.whitelisted || CNode::IsWhitelistedRange(addr); { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) if (pnode->fInbound) nInbound++; } if (hSocket == INVALID_SOCKET) { int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK) LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr)); } else if (!IsSelectableSocket(hSocket)) { LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToString()); CloseSocket(hSocket); } else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS) { LogPrint("net", "connection from %s dropped (full)\n", addr.ToString()); CloseSocket(hSocket); } else if (CNode::IsBanned(addr) && !whitelisted) { LogPrintf("connection from %s dropped (banned)\n", addr.ToString()); CloseSocket(hSocket); } else { CNode* pnode = new CNode(hSocket, addr, "", true); pnode->AddRef(); pnode->fWhitelisted = whitelisted; { LOCK(cs_vNodes); vNodes.push_back(pnode); } } } } // // Service each socket // vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH (CNode* pnode, vNodesCopy) pnode->AddRef(); } BOOST_FOREACH (CNode* pnode, vNodesCopy) { boost::this_thread::interruption_point(); // // Receive // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError)) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { { // typical socket buffer is 8K-64K char pchBuf[0x10000]; int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT); if (nBytes > 0) { if (!pnode->ReceiveMsgBytes(pchBuf, nBytes)) pnode->CloseSocketDisconnect(); pnode->nLastRecv = GetTime(); pnode->nRecvBytes += nBytes; pnode->RecordBytesRecv(nBytes); } else if (nBytes == 0) { // socket closed gracefully if (!pnode->fDisconnect) LogPrint("net", "socket closed\n"); pnode->CloseSocketDisconnect(); } else if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { if (!pnode->fDisconnect) LogPrintf("socket recv error %s\n", NetworkErrorString(nErr)); pnode->CloseSocketDisconnect(); } } } } } // // Send // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetSend)) { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) SocketSendData(pnode); } // // Inactivity checking // int64_t nTime = GetTime(); if (nTime - pnode->nTimeConnected > 60) { if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) { LogPrint("net", "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->id); pnode->fDisconnect = true; } else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL) { LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend); pnode->fDisconnect = true; } else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90 * 60)) { LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv); pnode->fDisconnect = true; } else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros()) { LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart)); pnode->fDisconnect = true; } } } { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodesCopy) pnode->Release(); } } } #ifdef USE_UPNP void ThreadMapPort() { std::string port = strprintf("%u", GetListenPort()); const char* multicastif = 0; const char* minissdpdpath = 0; struct UPNPDev* devlist = 0; char lanaddr[64]; #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0); #elif MINIUPNPC_API_VERSION < 14 /* miniupnpc 1.6 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error); #else /* miniupnpc 1.9.20150730 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error); #endif struct UPNPUrls urls; struct IGDdatas data; int r; r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)); if (r == 1) { if (fDiscover) { char externalIPAddress[40]; r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress); if (r != UPNPCOMMAND_SUCCESS) LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r); else { if (externalIPAddress[0]) { LogPrintf("UPnP: ExternalIPAddress = %s\n", externalIPAddress); AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP); } else LogPrintf("UPnP: GetExternalIPAddress failed.\n"); } } string strDesc = "wastake " + FormatFullVersion(); try { while (true) { #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0); #else /* miniupnpc 1.6 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0"); #endif if (r != UPNPCOMMAND_SUCCESS) LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n", port, port, lanaddr, r, strupnperror(r)); else LogPrintf("UPnP Port Mapping successful.\n"); ; MilliSleep(20 * 60 * 1000); // Refresh every 20 minutes } } catch (boost::thread_interrupted) { r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0); LogPrintf("UPNP_DeletePortMapping() returned : %d\n", r); freeUPNPDevlist(devlist); devlist = 0; FreeUPNPUrls(&urls); throw; } } else { LogPrintf("No valid UPnP IGDs found\n"); freeUPNPDevlist(devlist); devlist = 0; if (r != 0) FreeUPNPUrls(&urls); } } void MapPort(bool fUseUPnP) { static boost::thread* upnp_thread = NULL; if (fUseUPnP) { if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; } upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort)); } else if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; upnp_thread = NULL; } } #else void MapPort(bool) { // Intentionally left blank. } #endif void ThreadDNSAddressSeed() { // goal: only query DNS seeds if address need is acute if ((addrman.size() > 0) && (!GetBoolArg("-forcednsseed", false))) { MilliSleep(11 * 1000); LOCK(cs_vNodes); if (vNodes.size() >= 2) { LogPrintf("P2P peers available. Skipped DNS seeding.\n"); return; } } const vector<CDNSSeedData>& vSeeds = Params().DNSSeeds(); int found = 0; LogPrintf("Loading addresses from DNS seeds (could take a while)\n"); BOOST_FOREACH (const CDNSSeedData& seed, vSeeds) { if (HaveNameProxy()) { AddOneShot(seed.host); } else { vector<CNetAddr> vIPs; vector<CAddress> vAdd; if (LookupHost(seed.host.c_str(), vIPs)) { BOOST_FOREACH (CNetAddr& ip, vIPs) { int nOneDay = 24 * 3600; CAddress addr = CAddress(CService(ip, Params().GetDefaultPort())); addr.nTime = GetTime() - 3 * nOneDay - GetRand(4 * nOneDay); // use a random age between 3 and 7 days old vAdd.push_back(addr); found++; } } addrman.Add(vAdd, CNetAddr(seed.name, true)); } } LogPrintf("%d addresses found from DNS seeds\n", found); } void DumpAddresses() { int64_t nStart = GetTimeMillis(); CAddrDB adb; adb.Write(addrman); LogPrint("net", "Flushed %d addresses to peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart); } void static ProcessOneShot() { string strDest; { LOCK(cs_vOneShots); if (vOneShots.empty()) return; strDest = vOneShots.front(); vOneShots.pop_front(); } CAddress addr; CSemaphoreGrant grant(*semOutbound, true); if (grant) { if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true)) AddOneShot(strDest); } } void ThreadOpenConnections() { // Connect to specific addresses if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { for (int64_t nLoop = 0;; nLoop++) { ProcessOneShot(); BOOST_FOREACH (string strAddr, mapMultiArgs["-connect"]) { CAddress addr; OpenNetworkConnection(addr, NULL, strAddr.c_str()); for (int i = 0; i < 10 && i < nLoop; i++) { MilliSleep(500); } } MilliSleep(500); } } // Initiate network connections int64_t nStart = GetTime(); while (true) { ProcessOneShot(); MilliSleep(500); CSemaphoreGrant grant(*semOutbound); boost::this_thread::interruption_point(); // Add seed nodes if DNS seeds are all down (an infrastructure attack?). if (addrman.size() == 0 && (GetTime() - nStart > 60)) { static bool done = false; if (!done) { LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n"); addrman.Add(Params().FixedSeeds(), CNetAddr("127.0.0.1")); done = true; } } // // Choose an address to connect to based on most recently seen // CAddress addrConnect; // Only connect out to one peer per network group (/16 for IPv4). // Do this here so we don't have to critsect vNodes inside mapAddresses critsect. int nOutbound = 0; set<vector<unsigned char> > setConnected; { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) { if (!pnode->fInbound) { setConnected.insert(pnode->addr.GetGroup()); nOutbound++; } } } int64_t nANow = GetAdjustedTime(); int nTries = 0; while (true) { MilliSleep(250); CAddress addr = addrman.Select(); // if we selected an invalid address, restart if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr)) break; // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman, // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates // already-connected network ranges, ...) before trying new addrman addresses. nTries++; if (nTries > 100) break; if (IsLimited(addr)) continue; // only consider very recently tried nodes after 30 failed attempts if (nANow - addr.nLastTry < 600 && nTries < 30) continue; // do not allow non-default ports, unless after 50 invalid addresses selected already if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50) continue; addrConnect = addr; break; } if (addrConnect.IsValid()) OpenNetworkConnection(addrConnect, &grant); } } void ThreadOpenAddedConnections() { { LOCK(cs_vAddedNodes); vAddedNodes = mapMultiArgs["-addnode"]; } if (HaveNameProxy()) { while (true) { list<string> lAddresses(0); { LOCK(cs_vAddedNodes); BOOST_FOREACH (string& strAddNode, vAddedNodes) lAddresses.push_back(strAddNode); } BOOST_FOREACH (string& strAddNode, lAddresses) { CAddress addr; CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(addr, &grant, strAddNode.c_str()); MilliSleep(500); } MilliSleep(120000); // Retry every 2 minutes } } for (unsigned int i = 0; true; i++) { list<string> lAddresses(0); { LOCK(cs_vAddedNodes); BOOST_FOREACH (string& strAddNode, vAddedNodes) lAddresses.push_back(strAddNode); } list<vector<CService> > lservAddressesToAdd(0); BOOST_FOREACH (string& strAddNode, lAddresses) { vector<CService> vservNode(0); if (Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0)) { lservAddressesToAdd.push_back(vservNode); { LOCK(cs_setservAddNodeAddresses); BOOST_FOREACH (CService& serv, vservNode) setservAddNodeAddresses.insert(serv); } } } // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry // (keeping in mind that addnode entries can have many IPs if fNameLookup) { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++) BOOST_FOREACH (CService& addrNode, *(it)) if (pnode->addr == addrNode) { it = lservAddressesToAdd.erase(it); it--; break; } } BOOST_FOREACH (vector<CService>& vserv, lservAddressesToAdd) { CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant); MilliSleep(500); } MilliSleep(120000); // Retry every 2 minutes } } // if successful, this moves the passed grant to the constructed node bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant* grantOutbound, const char* pszDest, bool fOneShot) { // // Initiate outbound network connection // boost::this_thread::interruption_point(); if (!pszDest) { if (IsLocal(addrConnect) || FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) || FindNode(addrConnect.ToStringIPPort())) return false; } else if (FindNode(pszDest)) return false; CNode* pnode = ConnectNode(addrConnect, pszDest); boost::this_thread::interruption_point(); if (!pnode) return false; if (grantOutbound) grantOutbound->MoveTo(pnode->grantOutbound); pnode->fNetworkNode = true; if (fOneShot) pnode->fOneShot = true; return true; } void ThreadMessageHandler() { boost::mutex condition_mutex; boost::unique_lock<boost::mutex> lock(condition_mutex); static int64_t nLastRebroadcast = 0; SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL); while (true) { vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; for (CNode* pnode : vNodesCopy) { pnode->AddRef(); } } // Poll the connected nodes for messages CNode* pnodeTrickle = nullptr; if (!vNodesCopy.empty()) pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())]; bool fSleep = true; bool performRebroadcast = !IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60); for (CNode* pnode : vNodesCopy) { if (pnode->fDisconnect) continue; // Receive messages { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { if (!g_signals.ProcessMessages(pnode)) pnode->CloseSocketDisconnect(); if (pnode->nSendSize < SendBufferSize()) { if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete())) { fSleep = false; } } } } boost::this_thread::interruption_point(); // Send messages { TRY_LOCK(pnode->cs_vSend, lockSend); if(lockSend) { g_signals.SendMessages(pnode, pnode == pnodeTrickle || pnode->fWhitelisted); if(performRebroadcast) { // Periodically clear setAddrKnown to allow refresh broadcasts if (nLastRebroadcast) pnode->setAddrKnown.clear(); // Rebroadcast our address AdvertiseLocal(pnode); nLastRebroadcast = GetTime(); } } } boost::this_thread::interruption_point(); } { LOCK(cs_vNodes); for (CNode* pnode : vNodesCopy) pnode->Release(); } if (fSleep) messageHandlerCondition.timed_wait(lock, boost::posix_time::microsec_clock::universal_time() + boost::posix_time::milliseconds(100)); } } // ppcoin: stake minter thread void static ThreadStakeMinter() { boost::this_thread::interruption_point(); LogPrintf("ThreadStakeMinter started\n"); CWallet* pwallet = pwalletMain; try { BitcoinMiner(pwallet, true); boost::this_thread::interruption_point(); } catch (std::exception& e) { LogPrintf("ThreadStakeMinter() exception \n"); } catch (...) { LogPrintf("ThreadStakeMinter() error \n"); } LogPrintf("ThreadStakeMinter exiting,\n"); } bool BindListenPort(const CService& addrBind, string& strError, bool fWhitelisted) { strError = ""; int nOne = 1; // Create socket for listening for incoming connections struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString()); LogPrintf("%s\n", strError); return false; } SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP); if (hListenSocket == INVALID_SOCKET) { strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError())); LogPrintf("%s\n", strError); return false; } if (!IsSelectableSocket(hListenSocket)) { strError = "Error: Couldn't create a listenable socket for incoming connections"; LogPrintf("%s\n", strError); return false; } #ifndef WIN32 #ifdef SO_NOSIGPIPE // Different way of disabling SIGPIPE on BSD setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int)); #endif // Allow binding if the port is still in TIME_WAIT state after // the program was closed and restarted. Not an issue on windows! setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int)); #endif // Set to non-blocking, incoming connections will also inherit this if (!SetSocketNonBlocking(hListenSocket, true)) { strError = strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError())); LogPrintf("%s\n", strError); return false; } // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option // and enable it by default or not. Try to enable it, if possible. if (addrBind.IsIPv6()) { #ifdef IPV6_V6ONLY #ifdef WIN32 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int)); #else setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int)); #endif #endif #ifdef WIN32 int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED; setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int)); #endif } if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) { int nErr = WSAGetLastError(); if (nErr == WSAEADDRINUSE) strError = strprintf(_("Unable to bind to %s on this computer. WSK is probably already running."), addrBind.ToString()); else strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr)); LogPrintf("%s\n", strError); CloseSocket(hListenSocket); return false; } LogPrintf("Bound to %s\n", addrBind.ToString()); // Listen for incoming connections if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) { strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError())); LogPrintf("%s\n", strError); CloseSocket(hListenSocket); return false; } vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted)); if (addrBind.IsRoutable() && fDiscover && !fWhitelisted) AddLocal(addrBind, LOCAL_BIND); return true; } void static Discover(boost::thread_group& threadGroup) { if (!fDiscover) return; #ifdef WIN32 // Get local host IP char pszHostName[256] = ""; if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) { vector<CNetAddr> vaddr; if (LookupHost(pszHostName, vaddr)) { BOOST_FOREACH (const CNetAddr& addr, vaddr) { if (AddLocal(addr, LOCAL_IF)) LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString()); } } } #else // Get local host ip struct ifaddrs* myaddrs; if (getifaddrs(&myaddrs) == 0) { for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; if ((ifa->ifa_flags & IFF_UP) == 0) continue; if (strcmp(ifa->ifa_name, "lo") == 0) continue; if (strcmp(ifa->ifa_name, "lo0") == 0) continue; if (ifa->ifa_addr->sa_family == AF_INET) { struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr); CNetAddr addr(s4->sin_addr); if (AddLocal(addr, LOCAL_IF)) LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString()); } else if (ifa->ifa_addr->sa_family == AF_INET6) { struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr); CNetAddr addr(s6->sin6_addr); if (AddLocal(addr, LOCAL_IF)) LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString()); } } freeifaddrs(myaddrs); } #endif } void StartNode(boost::thread_group& threadGroup) { uiInterface.InitMessage(_("Loading addresses...")); // Load addresses for peers.dat int64_t nStart = GetTimeMillis(); { CAddrDB adb; if (!adb.Read(addrman)) LogPrintf("Invalid or missing peers.dat; recreating\n"); } LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart); fAddressesInitialized = true; if (semOutbound == NULL) { // initialize semaphore int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections); semOutbound = new CSemaphore(nMaxOutbound); } if (pnodeLocalHost == NULL) pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices)); Discover(threadGroup); // // Start threads // if (!GetBoolArg("-dnsseed", true)) LogPrintf("DNS seeding disabled\n"); else threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "dnsseed", &ThreadDNSAddressSeed)); // Map ports with UPnP MapPort(GetBoolArg("-upnp", DEFAULT_UPNP)); // Send and receive from sockets, accept connections threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler)); // Initiate outbound connections from -addnode threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections)); // Initiate outbound connections threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections)); // Process messages threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler)); // Dump network addresses threadGroup.create_thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, DUMP_ADDRESSES_INTERVAL * 1000)); // ppcoin:mint proof-of-stake blocks in the background if (GetBoolArg("-staking", true)) threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "stakemint", &ThreadStakeMinter)); } bool StopNode() { LogPrintf("StopNode()\n"); MapPort(false); if (semOutbound) for (int i = 0; i < MAX_OUTBOUND_CONNECTIONS; i++) semOutbound->post(); if (fAddressesInitialized) { DumpAddresses(); fAddressesInitialized = false; } return true; } class CNetCleanup { public: CNetCleanup() {} ~CNetCleanup() { // Close sockets BOOST_FOREACH (CNode* pnode, vNodes) if (pnode->hSocket != INVALID_SOCKET) CloseSocket(pnode->hSocket); BOOST_FOREACH (ListenSocket& hListenSocket, vhListenSocket) if (hListenSocket.socket != INVALID_SOCKET) if (!CloseSocket(hListenSocket.socket)) LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError())); // clean up some globals (to help leak detection) BOOST_FOREACH (CNode* pnode, vNodes) delete pnode; BOOST_FOREACH (CNode* pnode, vNodesDisconnected) delete pnode; vNodes.clear(); vNodesDisconnected.clear(); vhListenSocket.clear(); delete semOutbound; semOutbound = NULL; delete pnodeLocalHost; pnodeLocalHost = NULL; #ifdef WIN32 // Shutdown Windows Sockets WSACleanup(); #endif } } instance_of_cnetcleanup; void CExplicitNetCleanup::callCleanup() { // Explicit call to destructor of CNetCleanup because it's not implicitly called // when the wallet is restarted from within the wallet itself. CNetCleanup* tmp = new CNetCleanup(); delete tmp; // Stroustrup's gonna kill me for that } void RelayTransaction(const CTransaction& tx) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(10000); ss << tx; RelayTransaction(tx, ss); } void RelayTransaction(const CTransaction& tx, const CDataStream& ss) { CInv inv(MSG_TX, tx.GetHash()); { LOCK(cs_mapRelay); // Expire old relay messages while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime()) { mapRelay.erase(vRelayExpiration.front().second); vRelayExpiration.pop_front(); } // Save original serialized message so newer versions are preserved mapRelay.insert(std::make_pair(inv, ss)); vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv)); } LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) { if (!pnode->fRelayTxes) continue; LOCK(pnode->cs_filter); if (pnode->pfilter) { if (pnode->pfilter->IsRelevantAndUpdate(tx)) pnode->PushInventory(inv); } else pnode->PushInventory(inv); } } void RelayTransactionLockReq(const CTransaction& tx, bool relayToAll) { CInv inv(MSG_TXLOCK_REQUEST, tx.GetHash()); //broadcast the new lock LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) { if (!relayToAll && !pnode->fRelayTxes) continue; pnode->PushMessage("ix", tx); } } void RelayInv(CInv& inv) { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes){ if((pnode->nServices==NODE_BLOOM_WITHOUT_MN) && inv.IsMasterNodeType())continue; if (pnode->nVersion >= ActiveProtocol()) pnode->PushInventory(inv); } } void CNode::RecordBytesRecv(uint64_t bytes) { LOCK(cs_totalBytesRecv); nTotalBytesRecv += bytes; } void CNode::RecordBytesSent(uint64_t bytes) { LOCK(cs_totalBytesSent); nTotalBytesSent += bytes; } uint64_t CNode::GetTotalBytesRecv() { LOCK(cs_totalBytesRecv); return nTotalBytesRecv; } uint64_t CNode::GetTotalBytesSent() { LOCK(cs_totalBytesSent); return nTotalBytesSent; } void CNode::Fuzz(int nChance) { if (!fSuccessfullyConnected) return; // Don't fuzz initial handshake if (GetRand(nChance) != 0) return; // Fuzz 1 of every nChance messages switch (GetRand(3)) { case 0: // xor a random byte with a random value: if (!ssSend.empty()) { CDataStream::size_type pos = GetRand(ssSend.size()); ssSend[pos] ^= (unsigned char)(GetRand(256)); } break; case 1: // delete a random byte: if (!ssSend.empty()) { CDataStream::size_type pos = GetRand(ssSend.size()); ssSend.erase(ssSend.begin() + pos); } break; case 2: // insert a random byte at a random position { CDataStream::size_type pos = GetRand(ssSend.size()); char ch = (char)GetRand(256); ssSend.insert(ssSend.begin() + pos, ch); } break; } // Chance of more than one change half the time: // (more changes exponentially less likely): Fuzz(2); } // // CAddrDB // CAddrDB::CAddrDB() { pathAddr = GetDataDir() / "peers.dat"; } bool CAddrDB::Write(const CAddrMan& addr) { // Generate random temporary filename unsigned short randv = 0; GetRandBytes((unsigned char*)&randv, sizeof(randv)); std::string tmpfn = strprintf("peers.dat.%04x", randv); // serialize addresses, checksum data up to that point, then append csum CDataStream ssPeers(SER_DISK, CLIENT_VERSION); ssPeers << FLATDATA(Params().MessageStart()); ssPeers << addr; uint256 hash = Hash(ssPeers.begin(), ssPeers.end()); ssPeers << hash; // open output file, and associate with CAutoFile boost::filesystem::path pathAddr = GetDataDir() / "peers.dat"; FILE* file = fopen(pathAddr.string().c_str(), "wb"); CAutoFile fileout(file, SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("%s : Failed to open file %s", __func__, pathAddr.string()); // Write and commit header, data try { fileout << ssPeers; } catch (std::exception& e) { return error("%s : Serialize or I/O error - %s", __func__, e.what()); } FileCommit(fileout.Get()); fileout.fclose(); return true; } bool CAddrDB::Read(CAddrMan& addr) { // open input file, and associate with CAutoFile FILE* file = fopen(pathAddr.string().c_str(), "rb"); CAutoFile filein(file, SER_DISK, CLIENT_VERSION); if (filein.IsNull()) return error("%s : Failed to open file %s", __func__, pathAddr.string()); // use file size to size memory buffer int fileSize = boost::filesystem::file_size(pathAddr); int dataSize = fileSize - sizeof(uint256); // Don't try to resize to a negative number if file is small if (dataSize < 0) dataSize = 0; vector<unsigned char> vchData; vchData.resize(dataSize); uint256 hashIn; // read data and checksum from file try { filein.read((char*)&vchData[0], dataSize); filein >> hashIn; } catch (std::exception& e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } filein.fclose(); CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION); // verify stored checksum matches input data uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end()); if (hashIn != hashTmp) return error("%s : Checksum mismatch, data corrupted", __func__); unsigned char pchMsgTmp[4]; try { // de-serialize file header (network specific magic number) and .. ssPeers >> FLATDATA(pchMsgTmp); // ... verify the network matches ours if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) return error("%s : Invalid network magic number", __func__); // de-serialize address data into one CAddrMan object ssPeers >> addr; } catch (std::exception& e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } return true; } unsigned int ReceiveFloodSize() { return 1000 * GetArg("-maxreceivebuffer", 5 * 1000); } unsigned int SendBufferSize() { return 1000 * GetArg("-maxsendbuffer", 1 * 1000); } CNode::CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn, bool fInboundIn) : ssSend(SER_NETWORK, INIT_PROTO_VERSION), setAddrKnown(5000) { nServices = 0; hSocket = hSocketIn; nRecvVersion = INIT_PROTO_VERSION; nLastSend = 0; nLastRecv = 0; nSendBytes = 0; nRecvBytes = 0; nTimeConnected = GetTime(); addr = addrIn; addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn; nVersion = 0; strSubVer = ""; fWhitelisted = false; fOneShot = false; fClient = false; // set by version message fInbound = fInboundIn; fNetworkNode = false; fSuccessfullyConnected = false; fDisconnect = false; nRefCount = 0; nSendSize = 0; nSendOffset = 0; hashContinue = 0; nStartingHeight = -1; fGetAddr = false; fRelayTxes = false; setInventoryKnown.max_size(SendBufferSize() / 1000); pfilter = new CBloomFilter(); nPingNonceSent = 0; nPingUsecStart = 0; nPingUsecTime = 0; fPingQueued = false; fObfuScationMaster = false; { LOCK(cs_nLastNodeId); id = nLastNodeId++; } if (fLogIPs) LogPrint("net", "Added connection to %s peer=%d\n", addrName, id); else LogPrint("net", "Added connection peer=%d\n", id); // Be shy and don't send version until we hear if (hSocket != INVALID_SOCKET && !fInbound) PushVersion(); GetNodeSignals().InitializeNode(GetId(), this); } CNode::~CNode() { CloseSocket(hSocket); if (pfilter) delete pfilter; GetNodeSignals().FinalizeNode(GetId()); } void CNode::AskFor(const CInv& inv) { if (mapAskFor.size() > MAPASKFOR_MAX_SZ) return; // We're using mapAskFor as a priority queue, // the key is the earliest time the request can be sent int64_t nRequestTime; limitedmap<CInv, int64_t>::const_iterator it = mapAlreadyAskedFor.find(inv); if (it != mapAlreadyAskedFor.end()) nRequestTime = it->second; else nRequestTime = 0; LogPrint("net", "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime / 1000000), id); // Make sure not to reuse time indexes to keep things in the same order int64_t nNow = GetTimeMicros() - 1000000; static int64_t nLastTime; ++nLastTime; nNow = std::max(nNow, nLastTime); nLastTime = nNow; // Each retry is 2 minutes after the last nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow); if (it != mapAlreadyAskedFor.end()) mapAlreadyAskedFor.update(it, nRequestTime); else mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime)); mapAskFor.insert(std::make_pair(nRequestTime, inv)); } void CNode::BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend) { ENTER_CRITICAL_SECTION(cs_vSend); assert(ssSend.size() == 0); ssSend << CMessageHeader(pszCommand, 0); LogPrint("net", "sending: %s ", SanitizeString(pszCommand)); } void CNode::AbortMessage() UNLOCK_FUNCTION(cs_vSend) { ssSend.clear(); LEAVE_CRITICAL_SECTION(cs_vSend); LogPrint("net", "(aborted)\n"); } void CNode::EndMessage() UNLOCK_FUNCTION(cs_vSend) { // The -*messagestest options are intentionally not documented in the help message, // since they are only used during development to debug the networking code and are // not intended for end-users. if (mapArgs.count("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 2)) == 0) { LogPrint("net", "dropmessages DROPPING SEND MESSAGE\n"); AbortMessage(); return; } if (mapArgs.count("-fuzzmessagestest")) Fuzz(GetArg("-fuzzmessagestest", 10)); if (ssSend.size() == 0) return; // Set the size unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE; memcpy((char*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], &nSize, sizeof(nSize)); // Set the checksum uint256 hash = Hash(ssSend.begin() + CMessageHeader::HEADER_SIZE, ssSend.end()); unsigned int nChecksum = 0; memcpy(&nChecksum, &hash, sizeof(nChecksum)); assert(ssSend.size() >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum)); memcpy((char*)&ssSend[CMessageHeader::CHECKSUM_OFFSET], &nChecksum, sizeof(nChecksum)); LogPrint("net", "(%d bytes) peer=%d\n", nSize, id); std::deque<CSerializeData>::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData()); ssSend.GetAndClear(*it); nSendSize += (*it).size(); // If write queue empty, attempt "optimistic write" if (it == vSendMsg.begin()) SocketSendData(this); LEAVE_CRITICAL_SECTION(cs_vSend); }
// SPDX-License-Identifier: BSD-3-Clause // Copyright Contributors to the OpenColorIO Project. #include "transforms/MatrixTransform.cpp" #include "UnitTest.h" namespace OCIO = OCIO_NAMESPACE; OCIO_ADD_TEST(MatrixTransform, basic) { OCIO::MatrixTransformRcPtr matrix = OCIO::MatrixTransform::Create(); OCIO_CHECK_EQUAL(matrix->getDirection(), OCIO::TRANSFORM_DIR_FORWARD); double m44[16]; double offset4[4]; matrix->getMatrix(m44); matrix->getOffset(offset4); OCIO_CHECK_EQUAL(m44[0], 1.0); OCIO_CHECK_EQUAL(m44[1], 0.0); OCIO_CHECK_EQUAL(m44[2], 0.0); OCIO_CHECK_EQUAL(m44[3], 0.0); OCIO_CHECK_EQUAL(m44[4], 0.0); OCIO_CHECK_EQUAL(m44[5], 1.0); OCIO_CHECK_EQUAL(m44[6], 0.0); OCIO_CHECK_EQUAL(m44[7], 0.0); OCIO_CHECK_EQUAL(m44[8], 0.0); OCIO_CHECK_EQUAL(m44[9], 0.0); OCIO_CHECK_EQUAL(m44[10], 1.0); OCIO_CHECK_EQUAL(m44[11], 0.0); OCIO_CHECK_EQUAL(m44[12], 0.0); OCIO_CHECK_EQUAL(m44[13], 0.0); OCIO_CHECK_EQUAL(m44[14], 0.0); OCIO_CHECK_EQUAL(m44[15], 1.0); OCIO_CHECK_EQUAL(offset4[0], 0.0); OCIO_CHECK_EQUAL(offset4[1], 0.0); OCIO_CHECK_EQUAL(offset4[2], 0.0); OCIO_CHECK_EQUAL(offset4[3], 0.0); matrix->setDirection(OCIO::TRANSFORM_DIR_INVERSE); OCIO_CHECK_EQUAL(matrix->getDirection(), OCIO::TRANSFORM_DIR_INVERSE); m44[0] = 1.0; m44[1] = 1.01; m44[2] = 1.02; m44[3] = 1.03; m44[4] = 1.04; m44[5] = 1.05; m44[6] = 1.06; m44[7] = 1.07; m44[8] = 1.08; m44[9] = 1.09; m44[10] = 1.10; m44[11] = 1.11; m44[12] = 1.12; m44[13] = 1.13; m44[14] = 1.14; m44[15] = 1.15; offset4[0] = 1.0; offset4[1] = 1.1; offset4[2] = 1.2; offset4[3] = 1.3; matrix->setMatrix(m44); matrix->setOffset(offset4); double m44r[16]; double offset4r[4]; matrix->getMatrix(m44r); matrix->getOffset(offset4r); for (int i = 0; i < 16; ++i) { OCIO_CHECK_EQUAL(m44r[i], m44[i]); } OCIO_CHECK_EQUAL(offset4r[0], 1.0); OCIO_CHECK_EQUAL(offset4r[1], 1.1); OCIO_CHECK_EQUAL(offset4r[2], 1.2); OCIO_CHECK_EQUAL(offset4r[3], 1.3); OCIO_CHECK_EQUAL(matrix->getFileInputBitDepth(), OCIO::BIT_DEPTH_UNKNOWN); OCIO_CHECK_EQUAL(matrix->getFileOutputBitDepth(), OCIO::BIT_DEPTH_UNKNOWN); matrix->setFileInputBitDepth(OCIO::BIT_DEPTH_UINT8); matrix->setFileOutputBitDepth(OCIO::BIT_DEPTH_UINT10); OCIO_CHECK_EQUAL(matrix->getFileInputBitDepth(), OCIO::BIT_DEPTH_UINT8); OCIO_CHECK_EQUAL(matrix->getFileOutputBitDepth(), OCIO::BIT_DEPTH_UINT10); // File bit-depth does not affect values. matrix->getMatrix(m44r); matrix->getOffset(offset4r); for (int i = 0; i < 16; ++i) { OCIO_CHECK_EQUAL(m44r[i], m44[i]); } OCIO_CHECK_EQUAL(offset4r[0], 1.0); OCIO_CHECK_EQUAL(offset4r[1], 1.1); OCIO_CHECK_EQUAL(offset4r[2], 1.2); OCIO_CHECK_EQUAL(offset4r[3], 1.3); } OCIO_ADD_TEST(MatrixTransform, equals) { OCIO::MatrixTransformRcPtr matrix1 = OCIO::MatrixTransform::Create(); OCIO::MatrixTransformRcPtr matrix2 = OCIO::MatrixTransform::Create(); OCIO_CHECK_ASSERT(matrix1->equals(*matrix2)); matrix1->setDirection(OCIO::TRANSFORM_DIR_INVERSE); OCIO_CHECK_ASSERT(!matrix1->equals(*matrix2)); matrix1->setDirection(OCIO::TRANSFORM_DIR_FORWARD); double m44[16]; double offset4[4]; matrix1->getMatrix(m44); matrix1->getOffset(offset4); m44[0] = 1.0 + 1e-6; matrix1->setMatrix(m44); OCIO_CHECK_ASSERT(!matrix1->equals(*matrix2)); m44[0] = 1.0; matrix1->setMatrix(m44); OCIO_CHECK_ASSERT(matrix1->equals(*matrix2)); offset4[0] = 1e-6; matrix1->setOffset(offset4); OCIO_CHECK_ASSERT(!matrix1->equals(*matrix2)); }
/* * Copyright (c) 2017 - 2018, Intel Corporation * * 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 "runtime/helpers/abort.h" #include <exception> namespace OCLRT { void abortExecution() { throw std::exception(); } } // namespace OCLRT
#include "system.h" #include <unistd.h> #include <cstddef> #include <set> #include <string> #include <vector> #include "linux_parser.h" #include "process.h" #include "processor.h" using std::set; using std::size_t; using std::string; using std::vector; // TODO: Return the system's CPU Processor& System::Cpu() { // Processor cpu; return cpu_; } // TODO: Return a container composed of the system's processes vector<Process>& System::Processes() { return processes_; } // DONE: Return the system's kernel identifier (string) std::string System::Kernel() { LinuxParser::Kernel(kernel_); return kernel_; } // DONE: Return the system's memory utilization float System::MemoryUtilization() { // This implementation uses the formula: // Used Mem = (MemTotal-(MemFree + Buffers + Cached))/MemTotal <- not in // percentage as that is handled by ncurses_display.cpp // Cached=Cached + SReclaimable - Shmem float mem_utilization{0.0}, total_cached{0.0}; LinuxParser::MemoryUtilization(memory_); // 0 1 2 3 4 5 //"MemTotal", "MemFree", "Buffers", "Cached", "Shmem","SReclaimable" total_cached = memory_.values[MemType::kCached_] + memory_.values[MemType::kSReclaimable_] - memory_.values[MemType::kShmem_]; mem_utilization = (memory_.values[MemType::kMemTotal_] - (memory_.values[MemType::kMemFree_] + memory_.values[MemType::kBuffers_] + total_cached)) / memory_.values[MemType::kMemTotal_]; return mem_utilization; } // DONE: Return the operating system name std::string System::OperatingSystem() { LinuxParser::OperatingSystem(os_); return os_; } // DONE: Return the number of processes actively running on the system int System::RunningProcesses() { LinuxParser::RunningProcesses(running_processes); return running_processes; } // DONE: Return the total number of processes on the system int System::TotalProcesses() { LinuxParser::TotalProcesses(total_processes); return total_processes; } // DONE: Return the number of seconds since the system started running long System::UpTime() { LinuxParser::UpTime(uptime_); return uptime_; }
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2012 Bryce Adelstein-Lelbach // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) /////////////////////////////////////////////////////////////////////////////// #include <hpx/hpx_main.hpp> #include <hpx/include/components.hpp> #include <hpx/include/actions.hpp> #include <hpx/include/iostreams.hpp> #include <hpx/util/lightweight_test.hpp> bool a_ctor = false; bool a_dtor = false; bool b_ctor = false; bool b_dtor = false; /////////////////////////////////////////////////////////////////////////////// // Abstract struct A : hpx::components::abstract_managed_component_base<A> { A() { a_ctor = true; } virtual ~A() { a_dtor = true; } virtual std::string test0() const = 0; std::string test0_nonvirt() const { return test0(); } HPX_DEFINE_COMPONENT_ACTION(A, test0_nonvirt, test0_action); }; HPX_DEFINE_GET_COMPONENT_TYPE(A); typedef A::test0_action test0_action; HPX_REGISTER_ACTION_DECLARATION(test0_action); HPX_REGISTER_ACTION(test0_action); /////////////////////////////////////////////////////////////////////////////// // Concrete struct B : A, hpx::components::managed_component_base<B> { typedef hpx::components::managed_component_base<B>::wrapping_type wrapping_type; using hpx::components::managed_component_base<B>::decorate_action; using hpx::components::managed_component_base<B>::schedule_thread; using hpx::components::managed_component_base<B>::is_target_valid; typedef B type_holder; typedef A base_type_holder; B() { b_ctor = true; } ~B() { b_dtor = true; } std::string test0() const { return "B"; } std::string test1() const { return "B"; } HPX_DEFINE_COMPONENT_ACTION(B, test1, test1_action); }; typedef hpx::components::managed_component<B> serverB_type; HPX_REGISTER_DERIVED_COMPONENT_FACTORY(serverB_type, B, "A"); typedef B::test1_action test1_action; HPX_REGISTER_ACTION_DECLARATION(test1_action); HPX_REGISTER_ACTION(test1_action); /////////////////////////////////////////////////////////////////////////////// struct clientA : hpx::components::client_base<clientA, A> { typedef hpx::components::client_base<clientA, A> base_type; clientA(hpx::shared_future<hpx::id_type> const& gid) : base_type(gid) {} std::string test0() { test0_action act; return act(base_type::get_id()); } }; /////////////////////////////////////////////////////////////////////////////// struct clientB : hpx::components::client_base<clientB, B> { typedef hpx::components::client_base<clientB, B> base_type; clientB(hpx::shared_future<hpx::id_type> const& gid) : base_type(gid) {} std::string test0() { test0_action act; return act(base_type::get_id()); } std::string test1() { test1_action act; return act(base_type::get_id()); } }; /////////////////////////////////////////////////////////////////////////////// void reset_globals() { a_ctor = false; a_dtor = false; b_ctor = false; b_dtor = false; } int main() { /////////////////////////////////////////////////////////////////////////// { // Client to A, instance of B clientA obj(hpx::components::new_<B>(hpx::find_here())); HPX_TEST_EQ(obj.test0(), "B"); } HPX_TEST(a_ctor); HPX_TEST(a_dtor); HPX_TEST(b_ctor); HPX_TEST(b_dtor); reset_globals(); /////////////////////////////////////////////////////////////////////////// { // Client to B, instance of B clientB obj(hpx::components::new_<B>(hpx::find_here())); HPX_TEST_EQ(obj.test0(), "B"); HPX_TEST_EQ(obj.test1(), "B"); } HPX_TEST(a_ctor); HPX_TEST(a_dtor); HPX_TEST(b_ctor); HPX_TEST(b_dtor); reset_globals(); return 0; }
/* * Copyright 2010-2016 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/ec2/model/CancelSpotFleetRequestsRequest.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> using namespace Aws::EC2::Model; using namespace Aws::Utils; CancelSpotFleetRequestsRequest::CancelSpotFleetRequestsRequest() : m_dryRun(false), m_dryRunHasBeenSet(false), m_spotFleetRequestIdsHasBeenSet(false), m_terminateInstances(false), m_terminateInstancesHasBeenSet(false) { } Aws::String CancelSpotFleetRequestsRequest::SerializePayload() const { Aws::StringStream ss; ss << "Action=CancelSpotFleets&"; if(m_dryRunHasBeenSet) { ss << "DryRun=" << m_dryRun << "&"; } if(m_spotFleetRequestIdsHasBeenSet) { unsigned spotFleetRequestIdsCount = 1; for(auto& item : m_spotFleetRequestIds) { ss << "SpotFleetRequestId." << spotFleetRequestIdsCount << "=" << StringUtils::URLEncode(item.c_str()) << "&"; spotFleetRequestIdsCount++; } } if(m_terminateInstancesHasBeenSet) { ss << "TerminateInstances=" << m_terminateInstances << "&"; } ss << "Version=2015-10-01"; return ss.str(); }
#include "stdafx.h" /* * Copyright (c) 2007-2012 SlimDX Group * * 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 <windows.h> #include <dsound.h> #include "../Utilities.h" #include "CaptureEffectDescription.h" namespace SlimDX { namespace DirectSound { DSCEFFECTDESC CaptureEffectDescription::Marshal() { DSCEFFECTDESC description; ZeroMemory( &description, sizeof(description) ); description.dwSize = sizeof( DSCEFFECTDESC ); description.guidDSCFXClass = Utilities::ConvertManagedGuid( CaptureEffectClass ); description.guidDSCFXInstance = Utilities::ConvertManagedGuid( CaptureEffectInstance ); description.dwFlags = DSCFX_LOCSOFTWARE; description.dwReserved1 = 0; description.dwReserved2 = 0; if( LocateInHardware ) description.dwFlags = DSCFX_LOCHARDWARE; return description; } bool CaptureEffectDescription::operator == ( CaptureEffectDescription left, CaptureEffectDescription right ) { return CaptureEffectDescription::Equals( left, right ); } bool CaptureEffectDescription::operator != ( CaptureEffectDescription left, CaptureEffectDescription right ) { return !CaptureEffectDescription::Equals( left, right ); } int CaptureEffectDescription::GetHashCode() { return LocateInSoftware.GetHashCode() + LocateInHardware.GetHashCode() + CaptureEffectInstance.GetHashCode() + CaptureEffectClass.GetHashCode(); } bool CaptureEffectDescription::Equals( Object^ value ) { if( value == nullptr ) return false; if( value->GetType() != GetType() ) return false; return Equals( safe_cast<CaptureEffectDescription>( value ) ); } bool CaptureEffectDescription::Equals( CaptureEffectDescription value ) { return ( LocateInSoftware == value.LocateInSoftware && LocateInHardware == value.LocateInHardware && CaptureEffectInstance == value.CaptureEffectInstance && CaptureEffectClass == value.CaptureEffectClass ); } bool CaptureEffectDescription::Equals( CaptureEffectDescription% value1, CaptureEffectDescription% value2 ) { return value1.Equals( value2 ); } } }
#include "exe/process_wide.h" #include "common/common/assert.h" #include "common/event/libevent.h" #include "common/http/http2/nghttp2.h" #include "server/proto_descriptors.h" #include "ares.h" #ifdef ENVOY_GOOGLE_GRPC #include "grpc/grpc.h" #endif namespace Envoy { namespace { // Static variable to count initialization pairs. For tests like // main_common_test, we need to count to avoid double initialization or // shutdown. uint32_t process_wide_initialized; } // namespace ProcessWide::ProcessWide() : initialization_depth_(process_wide_initialized) { if (process_wide_initialized++ == 0) { #ifdef ENVOY_GOOGLE_GRPC grpc_init(); #endif ares_library_init(ARES_LIB_INIT_ALL); Event::Libevent::Global::initialize(); RELEASE_ASSERT(Envoy::Server::validateProtoDescriptors(), ""); Http::Http2::initializeNghttp2Logging(); } } ProcessWide::~ProcessWide() { ASSERT(process_wide_initialized > 0); if (--process_wide_initialized == 0) { process_wide_initialized = false; ares_library_cleanup(); #ifdef ENVOY_GOOGLE_GRPC grpc_shutdown(); #endif } ASSERT(process_wide_initialized == initialization_depth_); } } // namespace Envoy
#include "stdafx.h" #include <ole2.h> #include <aclapi.h> #include "iadmw.h" #include "iiscnfg.h" #include "log.h" #include "mdkey.h" #include "dcomperm.h" #include "other.h" #include "mdacl.h" #include <sddl.h> // ConvertSidToStringSid extern int g_GlobalDebugCrypto; #ifndef _CHICAGO_ BOOL CleanAdminACL(SECURITY_DESCRIPTOR *pSD) { // iisDebugOut((LOG_TYPE_TRACE, _T("CleanAdminACL(): Start.\n"))); BOOL fSetData = FALSE; BOOL b= FALSE, bDaclPresent = FALSE, bDaclDefaulted = FALSE;; PACL pDacl = NULL; LPVOID pAce = NULL; int i = 0; ACE_HEADER *pAceHeader; ACCESS_MASK dwOldMask, dwNewMask, dwExtraMask, dwMask; dwMask = (MD_ACR_READ | MD_ACR_WRITE | MD_ACR_RESTRICTED_WRITE | MD_ACR_UNSECURE_PROPS_READ | MD_ACR_ENUM_KEYS | MD_ACR_WRITE_DAC); b = GetSecurityDescriptorDacl(pSD, &bDaclPresent, &pDacl, &bDaclDefaulted); if (NULL == pDacl) { return FALSE; } if (b) { //iisDebugOut((LOG_TYPE_TRACE, _T("CleanAdminACL:ACE count: %d\n"), (int)pDacl->AceCount)); for (i=0; i<(int)pDacl->AceCount; i++) { b = GetAce(pDacl, i, &pAce); if (b) { pAceHeader = (ACE_HEADER *)pAce; switch (pAceHeader->AceType) { case ACCESS_ALLOWED_ACE_TYPE: dwOldMask = ((ACCESS_ALLOWED_ACE *)pAce)->Mask; dwExtraMask = dwOldMask & (~dwMask); if (dwExtraMask) { fSetData = TRUE; dwNewMask = dwOldMask & dwMask; ((ACCESS_ALLOWED_ACE *)pAce)->Mask = dwNewMask; } break; case ACCESS_DENIED_ACE_TYPE: dwOldMask = ((ACCESS_DENIED_ACE *)pAce)->Mask; dwExtraMask = dwOldMask & (~dwMask); if (dwExtraMask) { fSetData = TRUE; dwNewMask = dwOldMask & dwMask; ((ACCESS_DENIED_ACE *)pAce)->Mask = dwNewMask; } break; case SYSTEM_AUDIT_ACE_TYPE: dwOldMask = ((SYSTEM_AUDIT_ACE *)pAce)->Mask; dwExtraMask = dwOldMask & (~dwMask); if (dwExtraMask) { fSetData = TRUE; dwNewMask = dwOldMask & dwMask; ((SYSTEM_AUDIT_ACE *)pAce)->Mask = dwNewMask; } break; default: break; } } else { //iisDebugOut((LOG_TYPE_TRACE, _T("CleanAdminACL:GetAce:err=%x\n"), GetLastError())); } } } else { //iisDebugOut((LOG_TYPE_TRACE, _T("CleanAdminACL:GetSecurityDescriptorDacl:err=%x\n"), GetLastError())); } //iisDebugOut_End(_T("CleanAdminACL"),LOG_TYPE_TRACE); return (fSetData); } void FixAdminACL(LPTSTR szKeyPath) { // iisDebugOutSafeParams((LOG_TYPE_TRACE, _T("FixAdminACL Path=%1!s!. Start.\n"), szKeyPath)); BOOL bFound = FALSE, b = FALSE; DWORD attr, uType, dType, cbLen; CMDKey cmdKey; BUFFER bufData; CString csName, csValue; PBYTE pData; int BufSize; SECURITY_DESCRIPTOR *pSD; cmdKey.OpenNode(szKeyPath); if ( (METADATA_HANDLE)cmdKey ) { pData = (PBYTE)(bufData.QueryPtr()); BufSize = bufData.QuerySize(); cbLen = 0; bFound = cmdKey.GetData(MD_ADMIN_ACL, &attr, &uType, &dType, &cbLen, pData, BufSize); if (!bFound && (cbLen > 0)) { if ( ! (bufData.Resize(cbLen)) ) { cmdKey.Close(); return; // insufficient memory } else { pData = (PBYTE)(bufData.QueryPtr()); BufSize = cbLen; cbLen = 0; bFound = cmdKey.GetData(MD_ADMIN_ACL, &attr, &uType, &dType, &cbLen, pData, BufSize); } } cmdKey.Close(); if (bFound && (dType == BINARY_METADATA)) { pSD = (SECURITY_DESCRIPTOR *)pData; b = CleanAdminACL(pSD); if (b) { // need to reset the data DWORD dwLength = GetSecurityDescriptorLength(pSD); cmdKey.OpenNode(szKeyPath); if ( (METADATA_HANDLE)cmdKey ) { cmdKey.SetData(MD_ADMIN_ACL,METADATA_INHERIT | METADATA_REFERENCE | METADATA_SECURE,IIS_MD_UT_SERVER,BINARY_METADATA,dwLength,(LPBYTE)pSD); cmdKey.Close(); } } } } //iisDebugOut_End1(_T("FixAdminACL"),szKeyPath,LOG_TYPE_TRACE); return; } #endif //_CHICAGO_ #ifndef _CHICAGO_ DWORD SetAdminACL(LPCTSTR szKeyPath, DWORD dwAccessForEveryoneAccount) { iisDebugOut_Start1(_T("SetAdminACL"), szKeyPath, LOG_TYPE_TRACE); int iErr=0; DWORD dwErr=0; DWORD dwRetCode = ERROR_SUCCESS; BOOL b = FALSE; DWORD dwLength = 0; PSECURITY_DESCRIPTOR pSD = NULL; PSECURITY_DESCRIPTOR outpSD = NULL; DWORD cboutpSD = 0; PACL pACLNew = NULL; DWORD cbACL = 0; PSID pAdminsSID = NULL, pEveryoneSID = NULL; BOOL bWellKnownSID = FALSE; // Initialize a new security descriptor pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH); if (!pSD) { iisDebugOut((LOG_TYPE_ERROR, _T("SetAdminACL:LocalAlloc FAILED.out of memory. GetLastError()= 0x%x\n"), ERROR_NOT_ENOUGH_MEMORY)); dwRetCode = ERROR_OUTOFMEMORY; goto Cleanup; } iErr = InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION); if (iErr == 0) { iisDebugOut((LOG_TYPE_ERROR, _T("SetAdminACL:InitializeSecurityDescriptor FAILED. GetLastError()= 0x%x\n"), GetLastError() )); dwRetCode = GetLastError() != ERROR_SUCCESS ? GetLastError() : ERROR_OUTOFMEMORY; goto Cleanup; } // Get Local Admins Sid dwErr = GetPrincipalSID (_T("Administrators"), &pAdminsSID, &bWellKnownSID); if (dwErr != ERROR_SUCCESS) { iisDebugOut((LOG_TYPE_ERROR, _T("SetAdminACL:GetPrincipalSID(Administrators) FAILED. Return Code = 0x%x\n"), dwErr)); dwRetCode = dwErr; goto Cleanup; } // Get everyone Sid dwErr = GetPrincipalSID (_T("Everyone"), &pEveryoneSID, &bWellKnownSID); if (dwErr != ERROR_SUCCESS) { iisDebugOut((LOG_TYPE_ERROR, _T("SetAdminACL:GetPrincipalSID(Everyone) FAILED. Return Code = 0x%x\n"), dwErr)); dwRetCode = dwErr; goto Cleanup; } // Calculate the length needed for the ACL cbACL = sizeof(ACL) + (sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(pAdminsSID) - sizeof(DWORD)); if ( dwAccessForEveryoneAccount != 0x00 ) { // Add room for everyone ACL cbACL += sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(pEveryoneSID) - sizeof(DWORD); } pACLNew = (PACL) LocalAlloc(LPTR, cbACL); if ( !pACLNew ) { iisDebugOut((LOG_TYPE_ERROR, _T("SetAdminACL:pACLNew LocalAlloc(LPTR, FAILED. size = %u GetLastError()= 0x%x\n"), cbACL, GetLastError())); dwRetCode = ERROR_OUTOFMEMORY; goto Cleanup; } if (!InitializeAcl(pACLNew, cbACL, ACL_REVISION)) { iisDebugOut((LOG_TYPE_ERROR, _T("SetAdminACL:InitializeAcl FAILED. GetLastError()= 0x%x\n"), GetLastError)); dwRetCode = GetLastError() != ERROR_SUCCESS ? GetLastError() : ERROR_OUTOFMEMORY; goto Cleanup; } if (!AddAccessAllowedAce(pACLNew,ACL_REVISION,(MD_ACR_READ |MD_ACR_WRITE |MD_ACR_RESTRICTED_WRITE |MD_ACR_UNSECURE_PROPS_READ |MD_ACR_ENUM_KEYS |MD_ACR_WRITE_DAC),pAdminsSID)) { iisDebugOut((LOG_TYPE_ERROR, _T("SetAdminACL:AddAccessAllowedAce(pAdminsSID) FAILED. GetLastError()= 0x%x\n"), GetLastError)); dwRetCode = GetLastError() != ERROR_SUCCESS ? GetLastError() : ERROR_OUTOFMEMORY; goto Cleanup; } if ( dwAccessForEveryoneAccount != 0x00 ) { if (!AddAccessAllowedAce(pACLNew,ACL_REVISION,dwAccessForEveryoneAccount,pEveryoneSID)) { iisDebugOut((LOG_TYPE_ERROR, _T("SetAdminACL:AddAccessAllowedAce(pEveryoneSID) FAILED. GetLastError()= 0x%x\n"), GetLastError())); dwRetCode = GetLastError() != ERROR_SUCCESS ? GetLastError() : ERROR_OUTOFMEMORY; goto Cleanup; } } // Add the ACL to the security descriptor b = SetSecurityDescriptorDacl(pSD, TRUE, pACLNew, FALSE); if (!b) { iisDebugOut((LOG_TYPE_ERROR, _T("SetAdminACL:SetSecurityDescriptorDacl(pACLNew) FAILED. GetLastError()= 0x%x\n"), GetLastError())); dwRetCode = GetLastError() != ERROR_SUCCESS ? GetLastError() : ERROR_OUTOFMEMORY; goto Cleanup; } b = SetSecurityDescriptorOwner(pSD, pAdminsSID, TRUE); if (!b) { iisDebugOut((LOG_TYPE_ERROR, _T("SetAdminACL:SetSecurityDescriptorOwner(pAdminsSID) FAILED. GetLastError()= 0x%x\n"), GetLastError())); dwRetCode = GetLastError() != ERROR_SUCCESS ? GetLastError() : ERROR_OUTOFMEMORY; goto Cleanup; } b = SetSecurityDescriptorGroup(pSD, pAdminsSID, TRUE); if (!b) { iisDebugOut((LOG_TYPE_ERROR, _T("SetAdminACL:SetSecurityDescriptorGroup(pAdminsSID) FAILED. GetLastError()= 0x%x\n"), GetLastError())); dwRetCode = GetLastError() != ERROR_SUCCESS ? GetLastError() : ERROR_OUTOFMEMORY; goto Cleanup; } // Security descriptor blob must be self relative b = MakeSelfRelativeSD(pSD, outpSD, &cboutpSD); outpSD = (PSECURITY_DESCRIPTOR)GlobalAlloc(GPTR, cboutpSD); if ( !outpSD ) { iisDebugOut((LOG_TYPE_ERROR, _T("SetAdminACL:GlobalAlloc FAILED. cboutpSD = %u GetLastError()= 0x%x\n"), cboutpSD, GetLastError())); dwRetCode = ERROR_OUTOFMEMORY; goto Cleanup; } b = MakeSelfRelativeSD( pSD, outpSD, &cboutpSD ); if (!b) { iisDebugOut((LOG_TYPE_ERROR, _T("SetAdminACL:MakeSelfRelativeSD() FAILED. cboutpSD = %u GetLastError()= 0x%x\n"),cboutpSD, GetLastError())); dwRetCode = GetLastError() != ERROR_SUCCESS ? GetLastError() : ERROR_OUTOFMEMORY; goto Cleanup; } if (outpSD) { if (IsValidSecurityDescriptor(outpSD)) { // Apply the new security descriptor to the metabase iisDebugOut_Start(_T("SetAdminACL:Write the new security descriptor to the Metabase"),LOG_TYPE_TRACE); iisDebugOut((LOG_TYPE_TRACE, _T("SetAdminACL: At this point we have already been able to write basic entries to the metabase, so..."))); iisDebugOut((LOG_TYPE_TRACE, _T("SetAdminACL: If this has a problem then there is a problem with setting up encryption for the metabase (Crypto)."))); //DoesAdminACLExist(szKeyPath); if (g_GlobalDebugCrypto == 2) { // if we want to call this over and over... do { dwRetCode = WriteSDtoMetaBase(outpSD, szKeyPath); if (FAILED(dwRetCode)) { OutputDebugString(_T("\nCalling WriteSDtoMetaBase again...Set iis!g_GlobalDebugCrypto to 0 to stop looping on failure.")); OutputDebugString(_T("\nSet iis!g_GlobalDebugCrypto to 0 to stop looping on crypto failure.\n")); } } while (FAILED(dwRetCode) && g_GlobalDebugCrypto == 2); } else { dwRetCode = WriteSDtoMetaBase(outpSD, szKeyPath); } //DoesAdminACLExist(szKeyPath); iisDebugOut_End(_T("SetAdminACL:Write the new security descriptor to the Metabase"),LOG_TYPE_TRACE); } else { iisDebugOut((LOG_TYPE_ERROR, _T("SetAdminACL:IsValidSecurityDescriptor.4.SelfRelative(%u) FAILED!"),outpSD)); } } if (outpSD){GlobalFree(outpSD);outpSD=NULL;} Cleanup: // both of Administrators and Everyone are well-known SIDs, use FreeSid() to free them. if (pAdminsSID){FreeSid(pAdminsSID);} if (pEveryoneSID){FreeSid(pEveryoneSID);} if (pSD){LocalFree((HLOCAL) pSD);} if (pACLNew){LocalFree((HLOCAL) pACLNew);} iisDebugOut_End1(_T("SetAdminACL"),szKeyPath,LOG_TYPE_TRACE); return (dwRetCode); } DWORD SetAdminACL_wrap(LPCTSTR szKeyPath, DWORD dwAccessForEveryoneAccount, BOOL bDisplayMsgOnErrFlag) { int bFinishedFlag = FALSE; UINT iMsg = NULL; DWORD dwReturn = ERROR_SUCCESS; LogHeapState(FALSE, __FILE__, __LINE__); do { dwReturn = SetAdminACL(szKeyPath, dwAccessForEveryoneAccount); LogHeapState(FALSE, __FILE__, __LINE__); if (FAILED(dwReturn)) { if (bDisplayMsgOnErrFlag == TRUE) { iMsg = MyMessageBox( NULL, IDS_RETRY, MB_ABORTRETRYIGNORE | MB_SETFOREGROUND ); switch ( iMsg ) { case IDIGNORE: dwReturn = ERROR_SUCCESS; goto SetAdminACL_wrap_Exit; case IDABORT: dwReturn = ERROR_OPERATION_ABORTED; goto SetAdminACL_wrap_Exit; case IDRETRY: break; default: break; } } else { // return whatever err happened goto SetAdminACL_wrap_Exit; } } else { break; } } while ( FAILED(dwReturn) ); SetAdminACL_wrap_Exit: return dwReturn; } #endif #ifndef _CHICAGO_ DWORD WriteSDtoMetaBase(PSECURITY_DESCRIPTOR outpSD, LPCTSTR szKeyPath) { iisDebugOut_Start(_T("WriteSDtoMetaBase"), LOG_TYPE_TRACE); DWORD dwReturn = ERROR_ACCESS_DENIED; DWORD dwLength = 0; DWORD dwMDFlags = 0; CMDKey cmdKey; HRESULT hReturn = E_FAIL; int iSavedFlag = 0; dwMDFlags = METADATA_INHERIT | METADATA_REFERENCE | METADATA_SECURE,IIS_MD_UT_SERVER,BINARY_METADATA; iSavedFlag = g_GlobalDebugCrypto; if (!outpSD) { dwReturn = ERROR_INVALID_SECURITY_DESCR; goto WriteSDtoMetaBase_Exit; } // Apply the new security descriptor to the metabase dwLength = GetSecurityDescriptorLength(outpSD); // open the metabase // stick it into the metabase. warning those hoses a lot because // it uses encryption. rsabase.dll // Check for special debug flag in metabase to break right before this call! if (g_GlobalDebugCrypto != 0) { // special flag to say... hey "stop setup so that the crypto team can debug they're stuff" iisDebugOut((LOG_TYPE_TRACE, _T("Breakpoint enabled thru setup (to debug crypto api). look at debugoutput."))); OutputDebugString(_T("\n\nBreakpoint enabled thru setup (to debug crypto api)")); OutputDebugString(_T("\n1.in this process:")); OutputDebugString(_T("\n set breakpoint on admwprox!IcpGetContainerHelper")); OutputDebugString(_T("\n set breakpoint on advapi32!CryptAcquireContextW")); OutputDebugString(_T("\n IcpGetKeyHelper will call CryptAcquireContext and try to open an existing key container,")); OutputDebugString(_T("\n if it doesn't exist it will return NTE_BAD_KEYSET, and IcpGetContainerHelper will try to create the container.")); OutputDebugString(_T("\n2.in the inetinfo process:")); OutputDebugString(_T("\n set breakpoint on admwprox!IcpGetContainerHelper")); OutputDebugString(_T("\n set breakpoint on advapi32!CryptAcquireContextW\n")); } hReturn = cmdKey.CreateNode(METADATA_MASTER_ROOT_HANDLE, szKeyPath); if ( (METADATA_HANDLE)cmdKey ) { TCHAR szErrorString[50]; iisDebugOut((LOG_TYPE_TRACE, _T("WriteSDtoMetaBase:cmdKey():SetData(MD_ADMIN_ACL), dwdata = %d; outpSD = %x, Start\n"), dwLength, (DWORD_PTR) outpSD )); if (g_GlobalDebugCrypto != 0) { OutputDebugString(_T("\nCalling SetData....\n")); DebugBreak(); } dwReturn = cmdKey.SetData(MD_ADMIN_ACL,dwMDFlags,IIS_MD_UT_SERVER,BINARY_METADATA,dwLength,(LPBYTE)outpSD); if (FAILED(dwReturn)) { iisDebugOut((LOG_TYPE_ERROR, _T("WriteSDtoMetaBase:cmdKey():SetData(MD_ADMIN_ACL), FAILED. Code=0x%x.End.\n"), dwReturn)); if (g_GlobalDebugCrypto != 0) { _stprintf(szErrorString, _T("\r\nSetData Failed. code=0x%x\r\n\r\n"), dwReturn); OutputDebugString(szErrorString); } } else { dwReturn = ERROR_SUCCESS; iisDebugOut((LOG_TYPE_TRACE, _T("WriteSDtoMetaBase:cmdKey():SetData(MD_ADMIN_ACL), Success.End.\n"))); if (g_GlobalDebugCrypto != 0) { _stprintf(szErrorString, _T("\r\nSetData Succeeded. code=0x%x\r\n\r\n"), dwReturn); OutputDebugString(szErrorString); } } cmdKey.Close(); } else { dwReturn = hReturn; } WriteSDtoMetaBase_Exit: g_GlobalDebugCrypto = iSavedFlag; iisDebugOut((LOG_TYPE_TRACE, _T("WriteSDtoMetaBase:End. Return=0x%x"), dwReturn)); return dwReturn; } DWORD WriteSessiontoMetaBase(LPCTSTR szKeyPath) { iisDebugOut_Start(_T("WriteSessiontoMetaBase"), LOG_TYPE_TRACE); DWORD dwReturn = ERROR_ACCESS_DENIED; CMDKey cmdKey; HRESULT hReturn = E_FAIL; hReturn = cmdKey.CreateNode(METADATA_MASTER_ROOT_HANDLE, szKeyPath); if ( (METADATA_HANDLE)cmdKey ) { dwReturn = cmdKey.SetData(9999,METADATA_NO_ATTRIBUTES,IIS_MD_UT_SERVER,BINARY_METADATA,0,(LPBYTE)""); if (FAILED(dwReturn)) { iisDebugOut((LOG_TYPE_ERROR, _T("WriteSessiontoMetaBase:cmdKey():SetData(), FAILED. Code=0x%x.End.\n"), dwReturn)); } else { dwReturn = ERROR_SUCCESS; iisDebugOut((LOG_TYPE_TRACE, _T("WriteSessiontoMetaBase:cmdKey():SetData(), Success.End.\n"))); } cmdKey.Close(); } else { dwReturn = hReturn; } iisDebugOut((LOG_TYPE_TRACE, _T("WriteSessiontoMetaBase:End. Return=0x%x"), dwReturn)); return dwReturn; } #endif //---------------------------------------------------------------------------- // Test if the given account name is an account on the local machine or not. //---------------------------------------------------------------------------- BOOL IsLocalAccount(LPCTSTR pAccnt, DWORD *dwErr ) { BOOL fIsLocalAccount = FALSE; CString csDomain, csComputer; DWORD cbDomain = 0; PSID pSid = NULL; DWORD cbSid = 0; SID_NAME_USE snu; // get the computer name cbDomain = _MAX_PATH; GetComputerName( csComputer.GetBuffer( cbDomain ), // address of name buffer &cbDomain // address of size of name buffer ); csComputer.ReleaseBuffer(); cbDomain = 0; // have security look up the account name and get the domain name. We dont' care about // the other stuff it can return, so pass in nulls BOOL fLookup = LookupAccountName( NULL, // address of string for system name pAccnt, // address of string for account name NULL, // address of security identifier &cbSid, // address of size of security identifier NULL,// address of string for referenced domain &cbDomain, // address of size of domain string &snu // address of SID-type indicator ); // check the error - it should be insufficient buffer *dwErr = GetLastError(); if (*dwErr != ERROR_INSUFFICIENT_BUFFER) return FALSE; // allocate the sid pSid = (PSID) malloc (cbSid); if (!pSid ) { *dwErr = GetLastError(); return FALSE; } // do the real lookup fLookup = LookupAccountName (NULL,pAccnt,pSid,&cbSid,csDomain.GetBuffer(cbDomain+2),&cbDomain,&snu); csDomain.ReleaseBuffer(); // free the pSid we allocated above and set the final error code *dwErr = GetLastError(); free( pSid ); pSid = NULL; // compare the domain to the machine name, if it is the same, then set the sub auth if ( fLookup && (csDomain.CompareNoCase(csComputer) == 0) ) fIsLocalAccount = TRUE; // return the answer return fIsLocalAccount; } // pDomainUserName can be one of the following: // // domainname\username <-- this function returns true // computername\username <-- this function returns false // username <-- this function returns false // int IsDomainSpecifiedOtherThanLocalMachine(LPCTSTR pDomainUserName) { int iReturn = TRUE; TCHAR szTempDomainUserName[_MAX_PATH]; iisDebugOut_Start1(_T("IsDomainSpecifiedOtherThanLocalMachine"),pDomainUserName); CString csComputer; DWORD cbDomain = 0; // Make a copy to be sure not to move the pointer around. _tcscpy(szTempDomainUserName, pDomainUserName); // Check if there is a "\" in there. LPTSTR pch = NULL; pch = _tcschr(szTempDomainUserName, _T('\\')); if (!pch) { // no '\' found so, they must be specifying only the username, return false iReturn = FALSE; goto IsDomainSpecifiedOtherThanLocalMachine_Exit; } // We have at least a '\' in there, so set default return to true. // let's check if the name is the local computername! // get the computer name cbDomain = _MAX_PATH; if (0 == GetComputerName(csComputer.GetBuffer( cbDomain ),&cbDomain) ) { // failed to get computername so, let's bail iReturn = TRUE; csComputer.ReleaseBuffer(); goto IsDomainSpecifiedOtherThanLocalMachine_Exit; } csComputer.ReleaseBuffer(); cbDomain = 0; // trim off the '\' character to leave just the domain\computername so we can check against it. *pch = _T('\0'); // Compare the domainname with the computername // if they match then it's the local system account. iReturn = TRUE; iisDebugOut((LOG_TYPE_TRACE, _T("IsDomainSpecifiedOtherThanLocalMachine(): %s -- %s.\n"), szTempDomainUserName, csComputer)); if ( 0 == csComputer.CompareNoCase(szTempDomainUserName) ) { // The domain name and the computername are the same. // it is the same place. iReturn = FALSE; } IsDomainSpecifiedOtherThanLocalMachine_Exit: iisDebugOut((LOG_TYPE_TRACE, _T("IsDomainSpecifiedOtherThanLocalMachine():%s.End.Ret=%d.\n"), pDomainUserName,iReturn)); return iReturn; } #ifndef _CHICAGO_ void DumpAdminACL(HANDLE hFile,PSECURITY_DESCRIPTOR pSD) { BOOL b= FALSE, bDaclPresent = FALSE, bDaclDefaulted = FALSE;; PACL pDacl = NULL; ACCESS_ALLOWED_ACE* pAce; iisDebugOut((LOG_TYPE_TRACE, _T("DumpAdminACL:Start\n"))); b = GetSecurityDescriptorDacl(pSD, &bDaclPresent, &pDacl, &bDaclDefaulted); if (NULL == pDacl) { iisDebugOut((LOG_TYPE_TRACE, _T("DumpAdminACL:No Security.\n"))); return; } if (b) { iisDebugOut((LOG_TYPE_TRACE, _T("DumpAdminACL:ACE count: %d\n"), (int)pDacl->AceCount)); // get dacl length DWORD cbDacl = pDacl->AclSize; // now check if SID's ACE is there for (int i = 0; i < pDacl->AceCount; i++) { if (!GetAce(pDacl, i, (LPVOID *) &pAce)) { iisDebugOut((LOG_TYPE_TRACE, _T("DumpAdminACL:GetAce failed with 0x%x\n"),GetLastError())); } if (IsValidSid( (PSID) &(pAce->SidStart) ) ) { LPTSTR pszSid; LPCTSTR ServerName = NULL; // local machine DWORD cbName = UNLEN+1; TCHAR ReferencedDomainName[200]; DWORD cbReferencedDomainName = sizeof(ReferencedDomainName); SID_NAME_USE sidNameUse = SidTypeUser; TCHAR szUserName[UNLEN + 1]; // dump out the sid in string format if (ConvertSidToStringSid( (PSID) &(pAce->SidStart) , &pszSid)) { _tcscpy(szUserName, _T("(unknown...)")); if (LookupAccountSid(ServerName, (PSID) &(pAce->SidStart), szUserName, &cbName, ReferencedDomainName, &cbReferencedDomainName, &sidNameUse)) { // Get the rights for this user. // pAce->Mask DWORD dwBytesWritten = 0; TCHAR szBuf[UNLEN+1 + 20 + 20]; memset(szBuf, 0, _tcslen(szBuf) * sizeof(TCHAR)); /* typedef struct _ACCESS_ALLOWED_ACE { ACE_HEADER Header; ACCESS_MASK Mask; ULONG SidStart; } ACCESS_ALLOWED_ACE; typedef struct _ACE_HEADER { UCHAR AceType; UCHAR AceFlags; USHORT AceSize; } ACE_HEADER; typedef ACE_HEADER *PACE_HEADER; typedef ULONG ACCESS_MASK; */ _stprintf(szBuf, _T("%s,%s,0x%x,0x%x,0x%x,0x%x\r\n"), szUserName, pszSid, pAce->Header.AceType, pAce->Header.AceFlags, pAce->Header.AceSize, pAce->Mask ); if (hFile != NULL && hFile != INVALID_HANDLE_VALUE) { if (WriteFile(hFile, szBuf, _tcslen(szBuf) * sizeof(TCHAR), &dwBytesWritten, NULL ) == FALSE ) {iisDebugOut((LOG_TYPE_WARN, _T("WriteFile Failed=0x%x.\n"), GetLastError()));} } else { // echo to logfile iisDebugOut((LOG_TYPE_TRACE, _T("DumpAdminACL:Sid[%i]=%s,%s,0x%x,0x%x,0x%x,0x%x\n"),i, pszSid, szUserName, pAce->Header.AceType, pAce->Header.AceFlags, pAce->Header.AceSize, pAce->Mask )); } } else { iisDebugOut((LOG_TYPE_TRACE, _T("DumpAdminACL:Sid[%i]=%s='%s'\n"),i,pszSid,szUserName)); } LocalFree(LocalHandle(pszSid)); } } else { iisDebugOut((LOG_TYPE_TRACE, _T("DumpAdminACL:IsVAlidSid failed with 0x%x\n"),GetLastError())); } } } iisDebugOut((LOG_TYPE_TRACE, _T("DumpAdminACL:End\n"))); return; } #endif DWORD MDDumpAdminACL(CString csKeyPath) { DWORD dwReturn = ERROR_ACCESS_DENIED; BOOL bFound = FALSE; DWORD attr, uType, dType, cbLen; CMDKey cmdKey; BUFFER bufData; PBYTE pData; int BufSize; PSECURITY_DESCRIPTOR pOldSd = NULL; cmdKey.OpenNode(csKeyPath); if ( (METADATA_HANDLE) cmdKey ) { pData = (PBYTE)(bufData.QueryPtr()); BufSize = bufData.QuerySize(); cbLen = 0; bFound = cmdKey.GetData(MD_ADMIN_ACL, &attr, &uType, &dType, &cbLen, pData, BufSize); if (!bFound) { if (cbLen > 0) { if ( ! (bufData.Resize(cbLen)) ) { iisDebugOut((LOG_TYPE_ERROR, _T("MDDumpAdminACL(): cmdKey.GetData. failed to resize to %d.!\n"), cbLen)); } else { pData = (PBYTE)(bufData.QueryPtr()); BufSize = cbLen; cbLen = 0; bFound = cmdKey.GetData(MD_ADMIN_ACL, &attr, &uType, &dType, &cbLen, pData, BufSize); } } } cmdKey.Close(); if (bFound) { // dump out the info // We've got the acl pOldSd = (PSECURITY_DESCRIPTOR) pData; if (IsValidSecurityDescriptor(pOldSd)) { #ifndef _CHICAGO_ DumpAdminACL(INVALID_HANDLE_VALUE,pOldSd); dwReturn = ERROR_SUCCESS; #endif } } else { dwReturn = ERROR_PATH_NOT_FOUND; } } return dwReturn; } // function: AddUserToMetabaseACL_Rec // // Add a user to a metabase acl recursively. This will add them // directly to the location you specify, and then to any other // location that is a child of it, that has an ACL set // DWORD AddUserToMetabaseACL_Rec(CString csKeyPath, LPTSTR szUserToAdd, DWORD dwAccessMask ) { CMDKey cmdKey; DWORD dwRet; CStringList AclList; POSITION pos; CString csPath; CString csFullPath; CString csNewPath; dwRet = AddUserToMetabaseACL( csKeyPath, szUserToAdd, dwAccessMask ); if ( dwRet != ERROR_SUCCESS ) { // Failed, so lets exit return dwRet; } if ( FAILED( cmdKey.OpenNode(csKeyPath) ) || FAILED( cmdKey.GetDataPaths( MD_ADMIN_ACL, BINARY_METADATA, AclList ) ) ) { return ERROR_ACCESS_DENIED; } // Close Metabase cmdKey.Close(); pos = AclList.GetHeadPosition(); while ( NULL != pos ) { csPath = AclList.GetNext( pos ); if ( ( _tcscmp( csPath.GetBuffer(0), _T("/") ) == 0 ) || ( _tcsnicmp( csPath.GetBuffer(0), METABASEPATH_SCHEMA, _tcslen( METABASEPATH_SCHEMA ) ) == 0 ) ) { // If we are at the root of where we set it, then skip this one, // since this is already set. Or if we are in the schema, it // should not be changed continue; } if ( _tcscmp( csKeyPath.GetBuffer(0), _T("/") ) == 0 ) { // If the root of the acl we are at is the root, then don't // add '/' to it, since it already starts with a '/' csFullPath = csPath; } else { csFullPath = csKeyPath + csPath; } dwRet = AddUserToMetabaseACL( csFullPath, szUserToAdd, dwAccessMask ); if ( dwRet != ERROR_SUCCESS ) { return dwRet; } } return dwRet; } DWORD AddUserToMetabaseACL(CString csKeyPath, LPTSTR szUserToAdd, DWORD dwAccessMask ) { DWORD dwReturn = ERROR_ACCESS_DENIED; BOOL bFound = FALSE; DWORD attr, uType, dType, cbLen; CMDKey cmdKey; BUFFER bufData; PBYTE pData; int BufSize; PSECURITY_DESCRIPTOR pOldSd = NULL; PSECURITY_DESCRIPTOR pNewSd = NULL; cmdKey.OpenNode(csKeyPath); if ( (METADATA_HANDLE) cmdKey ) { pData = (PBYTE)(bufData.QueryPtr()); BufSize = bufData.QuerySize(); cbLen = 0; bFound = cmdKey.GetData(MD_ADMIN_ACL, &attr, &uType, &dType, &cbLen, pData, BufSize); if (!bFound) { if (cbLen > 0) { if ( ! (bufData.Resize(cbLen)) ) { iisDebugOut((LOG_TYPE_ERROR, _T("AddUserToMetabaseACL(): cmdKey.GetData. failed to resize to %d.!\n"), cbLen)); } else { pData = (PBYTE)(bufData.QueryPtr()); BufSize = cbLen; cbLen = 0; bFound = cmdKey.GetData(MD_ADMIN_ACL, &attr, &uType, &dType, &cbLen, pData, BufSize); } } } cmdKey.Close(); if (bFound) { // We've got the acl // so now we want to add a user to it. pOldSd = (PSECURITY_DESCRIPTOR) pData; if (IsValidSecurityDescriptor(pOldSd)) { PSID principalSID = NULL; BOOL bWellKnownSID = FALSE; if ( dwAccessMask == 0x00 ) { // If accessmask is not set, then lets set it dwAccessMask = ( MD_ACR_READ | MD_ACR_WRITE | MD_ACR_RESTRICTED_WRITE | MD_ACR_UNSECURE_PROPS_READ | MD_ACR_ENUM_KEYS | MD_ACR_WRITE_DAC ); } // Get the SID for the certain string (administrator or everyone or whoever) dwReturn = GetPrincipalSID(szUserToAdd, &principalSID, &bWellKnownSID); if (dwReturn != ERROR_SUCCESS) { iisDebugOut((LOG_TYPE_WARN, _T("AddUserToMetabaseACL:GetPrincipalSID(%s) FAILED. Error()= 0x%x\n"), szUserToAdd, dwReturn)); return dwReturn; } #ifndef _CHICAGO_ if (FALSE == AddUserAccessToSD(pOldSd,principalSID,dwAccessMask,ACCESS_ALLOWED_ACE_TYPE,&pNewSd)) { iisDebugOut((LOG_TYPE_ERROR, _T("AddUserToMetabaseACL:AddUserAccessToSD FAILED\n"))); return dwReturn; } if (pNewSd) { // We have a new self relative SD // lets write it to the metabase. if (IsValidSecurityDescriptor(pNewSd)) { dwReturn = WriteSDtoMetaBase(pNewSd, csKeyPath); } } #endif } } else { dwReturn = ERROR_PATH_NOT_FOUND; } } if (pNewSd){GlobalFree(pNewSd);} iisDebugOut((LOG_TYPE_TRACE, _T("AddUserToMetabaseACL():End. Return=0x%x.\n"), dwReturn)); return dwReturn; } DWORD DoesAdminACLExist(CString csKeyPath) { DWORD dwReturn = FALSE; BOOL bFound = FALSE; DWORD attr, uType, dType, cbLen; CMDKey cmdKey; BUFFER bufData; PBYTE pData; int BufSize; cmdKey.OpenNode(csKeyPath); if ( (METADATA_HANDLE) cmdKey ) { pData = (PBYTE)(bufData.QueryPtr()); BufSize = bufData.QuerySize(); cbLen = 0; bFound = cmdKey.GetData(MD_ADMIN_ACL, &attr, &uType, &dType, &cbLen, pData, BufSize); if (bFound) { dwReturn = TRUE; } else { if (cbLen > 0) { if ( ! (bufData.Resize(cbLen)) ) { iisDebugOut((LOG_TYPE_ERROR, _T("DoesAdminACLExist(): cmdKey.GetData. failed to resize to %d.!\n"), cbLen)); } else { pData = (PBYTE)(bufData.QueryPtr()); BufSize = cbLen; cbLen = 0; bFound = cmdKey.GetData(MD_ADMIN_ACL, &attr, &uType, &dType, &cbLen, pData, BufSize); if (bFound) { dwReturn = TRUE; } } } } cmdKey.Close(); } if (dwReturn != TRUE) { //No the acl Does not exist } iisDebugOut((LOG_TYPE_TRACE, _T("DoesAdminACLExist():End. Return=0x%x.\n"), dwReturn)); return dwReturn; }
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync_file_system/local/local_file_sync_context.h" #include <stdint.h> #include <utility> #include <vector> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/location.h" #include "base/macros.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/sync_file_system/local/canned_syncable_file_system.h" #include "chrome/browser/sync_file_system/local/local_file_change_tracker.h" #include "chrome/browser/sync_file_system/local/sync_file_system_backend.h" #include "chrome/browser/sync_file_system/sync_file_metadata.h" #include "chrome/browser/sync_file_system/sync_status_code.h" #include "chrome/browser/sync_file_system/syncable_file_system_util.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/mock_blob_url_request_context.h" #include "content/public/test/test_browser_thread_bundle.h" #include "storage/browser/blob/scoped_file.h" #include "storage/browser/fileapi/file_system_context.h" #include "storage/browser/fileapi/file_system_operation_runner.h" #include "storage/browser/fileapi/isolated_context.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/leveldatabase/src/helpers/memenv/memenv.h" #include "third_party/leveldatabase/src/include/leveldb/env.h" #define FPL FILE_PATH_LITERAL using content::BrowserThread; using storage::FileSystemContext; using storage::FileSystemURL; using storage::FileSystemURLSet; // This tests LocalFileSyncContext behavior in multi-thread / // multi-file-system-context environment. // Basic combined tests (single-thread / single-file-system-context) // that involve LocalFileSyncContext are also in // syncable_file_system_unittests.cc. namespace sync_file_system { namespace { const char kOrigin1[] = "http://example.com"; const char kOrigin2[] = "http://chromium.org"; } class LocalFileSyncContextTest : public testing::Test { protected: LocalFileSyncContextTest() : thread_bundle_( content::TestBrowserThreadBundle::REAL_FILE_THREAD | content::TestBrowserThreadBundle::REAL_IO_THREAD), status_(SYNC_FILE_ERROR_FAILED), file_error_(base::File::FILE_ERROR_FAILED), async_modify_finished_(false), has_inflight_prepare_for_sync_(false) {} void SetUp() override { RegisterSyncableFileSystem(); ASSERT_TRUE(dir_.CreateUniqueTempDir()); in_memory_env_.reset(leveldb::NewMemEnv(leveldb::Env::Default())); ui_task_runner_ = base::ThreadTaskRunnerHandle::Get(); io_task_runner_ = BrowserThread::GetMessageLoopProxyForThread( BrowserThread::IO); file_task_runner_ = BrowserThread::GetMessageLoopProxyForThread( BrowserThread::IO); } void TearDown() override { RevokeSyncableFileSystem(); } void StartPrepareForSync(FileSystemContext* file_system_context, const FileSystemURL& url, LocalFileSyncContext::SyncMode sync_mode, SyncFileMetadata* metadata, FileChangeList* changes, storage::ScopedFile* snapshot) { ASSERT_TRUE(changes != nullptr); ASSERT_FALSE(has_inflight_prepare_for_sync_); status_ = SYNC_STATUS_UNKNOWN; has_inflight_prepare_for_sync_ = true; sync_context_->PrepareForSync( file_system_context, url, sync_mode, base::Bind(&LocalFileSyncContextTest::DidPrepareForSync, base::Unretained(this), metadata, changes, snapshot)); } SyncStatusCode PrepareForSync(FileSystemContext* file_system_context, const FileSystemURL& url, LocalFileSyncContext::SyncMode sync_mode, SyncFileMetadata* metadata, FileChangeList* changes, storage::ScopedFile* snapshot) { StartPrepareForSync(file_system_context, url, sync_mode, metadata, changes, snapshot); base::RunLoop().Run(); return status_; } base::Closure GetPrepareForSyncClosure( FileSystemContext* file_system_context, const FileSystemURL& url, LocalFileSyncContext::SyncMode sync_mode, SyncFileMetadata* metadata, FileChangeList* changes, storage::ScopedFile* snapshot) { return base::Bind(&LocalFileSyncContextTest::StartPrepareForSync, base::Unretained(this), base::Unretained(file_system_context), url, sync_mode, metadata, changes, snapshot); } void DidPrepareForSync(SyncFileMetadata* metadata_out, FileChangeList* changes_out, storage::ScopedFile* snapshot_out, SyncStatusCode status, const LocalFileSyncInfo& sync_file_info, storage::ScopedFile snapshot) { ASSERT_TRUE(ui_task_runner_->RunsTasksOnCurrentThread()); has_inflight_prepare_for_sync_ = false; status_ = status; *metadata_out = sync_file_info.metadata; *changes_out = sync_file_info.changes; if (snapshot_out) *snapshot_out = std::move(snapshot); base::MessageLoop::current()->QuitWhenIdle(); } SyncStatusCode ApplyRemoteChange(FileSystemContext* file_system_context, const FileChange& change, const base::FilePath& local_path, const FileSystemURL& url, SyncFileType expected_file_type) { SCOPED_TRACE(testing::Message() << "ApplyChange for " << url.DebugString()); // First we should call PrepareForSync to disable writing. SyncFileMetadata metadata; FileChangeList changes; EXPECT_EQ(SYNC_STATUS_OK, PrepareForSync(file_system_context, url, LocalFileSyncContext::SYNC_EXCLUSIVE, &metadata, &changes, nullptr)); EXPECT_EQ(expected_file_type, metadata.file_type); status_ = SYNC_STATUS_UNKNOWN; sync_context_->ApplyRemoteChange( file_system_context, change, local_path, url, base::Bind(&LocalFileSyncContextTest::DidApplyRemoteChange, base::Unretained(this), base::RetainedRef(file_system_context), url)); base::RunLoop().Run(); return status_; } void DidApplyRemoteChange(FileSystemContext* file_system_context, const FileSystemURL& url, SyncStatusCode status) { status_ = status; sync_context_->FinalizeExclusiveSync( file_system_context, url, status == SYNC_STATUS_OK /* clear_local_changes */, base::MessageLoop::QuitWhenIdleClosure()); } void StartModifyFileOnIOThread(CannedSyncableFileSystem* file_system, const FileSystemURL& url) { ASSERT_TRUE(file_system != nullptr); if (!io_task_runner_->RunsTasksOnCurrentThread()) { async_modify_finished_ = false; ASSERT_TRUE(ui_task_runner_->RunsTasksOnCurrentThread()); io_task_runner_->PostTask( FROM_HERE, base::Bind(&LocalFileSyncContextTest::StartModifyFileOnIOThread, base::Unretained(this), file_system, url)); return; } ASSERT_TRUE(io_task_runner_->RunsTasksOnCurrentThread()); file_error_ = base::File::FILE_ERROR_FAILED; file_system->operation_runner()->Truncate( url, 1, base::Bind(&LocalFileSyncContextTest::DidModifyFile, base::Unretained(this))); } base::File::Error WaitUntilModifyFileIsDone() { while (!async_modify_finished_) base::RunLoop().RunUntilIdle(); return file_error_; } void DidModifyFile(base::File::Error error) { if (!ui_task_runner_->RunsTasksOnCurrentThread()) { ASSERT_TRUE(io_task_runner_->RunsTasksOnCurrentThread()); ui_task_runner_->PostTask( FROM_HERE, base::Bind(&LocalFileSyncContextTest::DidModifyFile, base::Unretained(this), error)); return; } ASSERT_TRUE(ui_task_runner_->RunsTasksOnCurrentThread()); file_error_ = error; async_modify_finished_ = true; } void SimulateFinishSync(FileSystemContext* file_system_context, const FileSystemURL& url, SyncStatusCode status, LocalFileSyncContext::SyncMode sync_mode) { if (sync_mode == LocalFileSyncContext::SYNC_SNAPSHOT) { sync_context_->FinalizeSnapshotSync( file_system_context, url, status, base::Bind(&base::DoNothing)); } else { sync_context_->FinalizeExclusiveSync( file_system_context, url, status == SYNC_STATUS_OK /* clear_local_changes */, base::Bind(&base::DoNothing)); } } void PrepareForSync_Basic(LocalFileSyncContext::SyncMode sync_mode, SyncStatusCode simulate_sync_finish_status) { CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext( sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const FileSystemURL kFile(file_system.URL("file")); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kFile)); SyncFileMetadata metadata; FileChangeList changes; EXPECT_EQ(SYNC_STATUS_OK, PrepareForSync(file_system.file_system_context(), kFile, sync_mode, &metadata, &changes, nullptr)); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); // We should see the same set of changes. file_system.GetChangesForURLInTracker(kFile, &changes); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); SimulateFinishSync(file_system.file_system_context(), kFile, simulate_sync_finish_status, sync_mode); file_system.GetChangesForURLInTracker(kFile, &changes); if (simulate_sync_finish_status == SYNC_STATUS_OK) { // The change's cleared. EXPECT_TRUE(changes.empty()); } else { EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); } sync_context_->ShutdownOnUIThread(); sync_context_ = nullptr; file_system.TearDown(); } void PrepareForSync_WriteDuringSync( LocalFileSyncContext::SyncMode sync_mode) { CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext( sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const FileSystemURL kFile(file_system.URL("file")); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kFile)); SyncFileMetadata metadata; FileChangeList changes; storage::ScopedFile snapshot; EXPECT_EQ(SYNC_STATUS_OK, PrepareForSync(file_system.file_system_context(), kFile, sync_mode, &metadata, &changes, &snapshot)); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); EXPECT_EQ(sync_mode == LocalFileSyncContext::SYNC_SNAPSHOT, !snapshot.path().empty()); // Tracker keeps same set of changes. file_system.GetChangesForURLInTracker(kFile, &changes); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); StartModifyFileOnIOThread(&file_system, kFile); if (sync_mode == LocalFileSyncContext::SYNC_SNAPSHOT) { // Write should succeed. EXPECT_EQ(base::File::FILE_OK, WaitUntilModifyFileIsDone()); } else { base::RunLoop().RunUntilIdle(); EXPECT_FALSE(async_modify_finished_); } SimulateFinishSync(file_system.file_system_context(), kFile, SYNC_STATUS_OK, sync_mode); EXPECT_EQ(base::File::FILE_OK, WaitUntilModifyFileIsDone()); // Sync succeeded, but the other change that was made during or // after sync is recorded. file_system.GetChangesForURLInTracker(kFile, &changes); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); sync_context_->ShutdownOnUIThread(); sync_context_ = nullptr; file_system.TearDown(); } base::ScopedTempDir dir_; std::unique_ptr<leveldb::Env> in_memory_env_; // These need to remain until the very end. content::TestBrowserThreadBundle thread_bundle_; scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_; scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_; scoped_refptr<base::SingleThreadTaskRunner> file_task_runner_; scoped_refptr<LocalFileSyncContext> sync_context_; SyncStatusCode status_; base::File::Error file_error_; bool async_modify_finished_; bool has_inflight_prepare_for_sync_; }; TEST_F(LocalFileSyncContextTest, ConstructAndDestruct) { sync_context_ = new LocalFileSyncContext( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); sync_context_->ShutdownOnUIThread(); } TEST_F(LocalFileSyncContextTest, InitializeFileSystemContext) { CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); // Initializes file_system using |sync_context_|. EXPECT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext(sync_context_.get())); // Make sure everything's set up for file_system to be able to handle // syncable file system operations. EXPECT_TRUE(file_system.backend()->sync_context() != nullptr); EXPECT_TRUE(file_system.backend()->change_tracker() != nullptr); EXPECT_EQ(sync_context_.get(), file_system.backend()->sync_context()); // Calling MaybeInitialize for the same context multiple times must be ok. EXPECT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext(sync_context_.get())); EXPECT_EQ(sync_context_.get(), file_system.backend()->sync_context()); // Opens the file_system, perform some operation and see if the change tracker // correctly captures the change. EXPECT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const FileSystemURL kURL(file_system.URL("foo")); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kURL)); FileSystemURLSet urls; file_system.GetChangedURLsInTracker(&urls); ASSERT_EQ(1U, urls.size()); EXPECT_TRUE(ContainsKey(urls, kURL)); // Finishing the test. sync_context_->ShutdownOnUIThread(); file_system.TearDown(); } TEST_F(LocalFileSyncContextTest, MultipleFileSystemContexts) { CannedSyncableFileSystem file_system1(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); CannedSyncableFileSystem file_system2(GURL(kOrigin2), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system1.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); file_system2.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); // Initializes file_system1 and file_system2. EXPECT_EQ(SYNC_STATUS_OK, file_system1.MaybeInitializeFileSystemContext(sync_context_.get())); EXPECT_EQ(SYNC_STATUS_OK, file_system2.MaybeInitializeFileSystemContext(sync_context_.get())); EXPECT_EQ(base::File::FILE_OK, file_system1.OpenFileSystem()); EXPECT_EQ(base::File::FILE_OK, file_system2.OpenFileSystem()); const FileSystemURL kURL1(file_system1.URL("foo")); const FileSystemURL kURL2(file_system2.URL("bar")); // Creates a file in file_system1. EXPECT_EQ(base::File::FILE_OK, file_system1.CreateFile(kURL1)); // file_system1's tracker must have recorded the change. FileSystemURLSet urls; file_system1.GetChangedURLsInTracker(&urls); ASSERT_EQ(1U, urls.size()); EXPECT_TRUE(ContainsKey(urls, kURL1)); // file_system1's tracker must have no change. urls.clear(); file_system2.GetChangedURLsInTracker(&urls); ASSERT_TRUE(urls.empty()); // Creates a directory in file_system2. EXPECT_EQ(base::File::FILE_OK, file_system2.CreateDirectory(kURL2)); // file_system1's tracker must have the change for kURL1 as before. urls.clear(); file_system1.GetChangedURLsInTracker(&urls); ASSERT_EQ(1U, urls.size()); EXPECT_TRUE(ContainsKey(urls, kURL1)); // file_system2's tracker now must have the change for kURL2. urls.clear(); file_system2.GetChangedURLsInTracker(&urls); ASSERT_EQ(1U, urls.size()); EXPECT_TRUE(ContainsKey(urls, kURL2)); SyncFileMetadata metadata; FileChangeList changes; EXPECT_EQ(SYNC_STATUS_OK, PrepareForSync(file_system1.file_system_context(), kURL1, LocalFileSyncContext::SYNC_EXCLUSIVE, &metadata, &changes, nullptr)); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); EXPECT_EQ(SYNC_FILE_TYPE_FILE, metadata.file_type); EXPECT_EQ(0, metadata.size); changes.clear(); EXPECT_EQ(SYNC_STATUS_OK, PrepareForSync(file_system2.file_system_context(), kURL2, LocalFileSyncContext::SYNC_EXCLUSIVE, &metadata, &changes, nullptr)); EXPECT_EQ(1U, changes.size()); EXPECT_FALSE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); EXPECT_EQ(SYNC_FILE_TYPE_DIRECTORY, metadata.file_type); EXPECT_EQ(0, metadata.size); sync_context_->ShutdownOnUIThread(); sync_context_ = nullptr; file_system1.TearDown(); file_system2.TearDown(); } TEST_F(LocalFileSyncContextTest, PrepareSync_SyncSuccess_Exclusive) { PrepareForSync_Basic(LocalFileSyncContext::SYNC_EXCLUSIVE, SYNC_STATUS_OK); } TEST_F(LocalFileSyncContextTest, PrepareSync_SyncSuccess_Snapshot) { PrepareForSync_Basic(LocalFileSyncContext::SYNC_SNAPSHOT, SYNC_STATUS_OK); } TEST_F(LocalFileSyncContextTest, PrepareSync_SyncFailure_Exclusive) { PrepareForSync_Basic(LocalFileSyncContext::SYNC_EXCLUSIVE, SYNC_STATUS_FAILED); } TEST_F(LocalFileSyncContextTest, PrepareSync_SyncFailure_Snapshot) { PrepareForSync_Basic(LocalFileSyncContext::SYNC_SNAPSHOT, SYNC_STATUS_FAILED); } TEST_F(LocalFileSyncContextTest, PrepareSync_WriteDuringSync_Exclusive) { PrepareForSync_WriteDuringSync(LocalFileSyncContext::SYNC_EXCLUSIVE); } TEST_F(LocalFileSyncContextTest, PrepareSync_WriteDuringSync_Snapshot) { PrepareForSync_WriteDuringSync(LocalFileSyncContext::SYNC_SNAPSHOT); } // LocalFileSyncContextTest.PrepareSyncWhileWriting is flaky on android. // http://crbug.com/239793 // It is also flaky on the TSAN v2 bots, and hangs other bots. // http://crbug.com/305905. TEST_F(LocalFileSyncContextTest, DISABLED_PrepareSyncWhileWriting) { CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); EXPECT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext(sync_context_.get())); EXPECT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const FileSystemURL kURL1(file_system.URL("foo")); // Creates a file in file_system. EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kURL1)); // Kick file write on IO thread. StartModifyFileOnIOThread(&file_system, kURL1); // Until the operation finishes PrepareForSync should return BUSY error. SyncFileMetadata metadata; metadata.file_type = SYNC_FILE_TYPE_UNKNOWN; FileChangeList changes; EXPECT_EQ(SYNC_STATUS_FILE_BUSY, PrepareForSync(file_system.file_system_context(), kURL1, LocalFileSyncContext::SYNC_EXCLUSIVE, &metadata, &changes, nullptr)); EXPECT_EQ(SYNC_FILE_TYPE_FILE, metadata.file_type); // Register PrepareForSync method to be invoked when kURL1 becomes // syncable. (Actually this may be done after all operations are done // on IO thread in this test.) metadata.file_type = SYNC_FILE_TYPE_UNKNOWN; changes.clear(); sync_context_->RegisterURLForWaitingSync( kURL1, GetPrepareForSyncClosure(file_system.file_system_context(), kURL1, LocalFileSyncContext::SYNC_EXCLUSIVE, &metadata, &changes, nullptr)); // Wait for the completion. EXPECT_EQ(base::File::FILE_OK, WaitUntilModifyFileIsDone()); // The PrepareForSync must have been started; wait until DidPrepareForSync // is done. base::RunLoop().Run(); ASSERT_FALSE(has_inflight_prepare_for_sync_); // Now PrepareForSync should have run and returned OK. EXPECT_EQ(SYNC_STATUS_OK, status_); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); EXPECT_EQ(SYNC_FILE_TYPE_FILE, metadata.file_type); EXPECT_EQ(1, metadata.size); sync_context_->ShutdownOnUIThread(); sync_context_ = nullptr; file_system.TearDown(); } TEST_F(LocalFileSyncContextTest, ApplyRemoteChangeForDeletion) { CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext(sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); // Record the initial usage (likely 0). int64_t initial_usage = -1; int64_t quota = -1; EXPECT_EQ(storage::kQuotaStatusOk, file_system.GetUsageAndQuota(&initial_usage, &quota)); // Create a file and directory in the file_system. const FileSystemURL kFile(file_system.URL("file")); const FileSystemURL kDir(file_system.URL("dir")); const FileSystemURL kChild(file_system.URL("dir/child")); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kFile)); EXPECT_EQ(base::File::FILE_OK, file_system.CreateDirectory(kDir)); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kChild)); // file_system's change tracker must have recorded the creation. FileSystemURLSet urls; file_system.GetChangedURLsInTracker(&urls); ASSERT_EQ(3U, urls.size()); ASSERT_TRUE(ContainsKey(urls, kFile)); ASSERT_TRUE(ContainsKey(urls, kDir)); ASSERT_TRUE(ContainsKey(urls, kChild)); for (FileSystemURLSet::iterator iter = urls.begin(); iter != urls.end(); ++iter) { file_system.ClearChangeForURLInTracker(*iter); } // At this point the usage must be greater than the initial usage. int64_t new_usage = -1; EXPECT_EQ(storage::kQuotaStatusOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_GT(new_usage, initial_usage); // Now let's apply remote deletion changes. FileChange change(FileChange::FILE_CHANGE_DELETE, SYNC_FILE_TYPE_FILE); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, base::FilePath(), kFile, SYNC_FILE_TYPE_FILE)); // The implementation doesn't check file type for deletion, and it must be ok // even if we don't know if the deletion change was for a file or a directory. change = FileChange(FileChange::FILE_CHANGE_DELETE, SYNC_FILE_TYPE_UNKNOWN); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, base::FilePath(), kDir, SYNC_FILE_TYPE_DIRECTORY)); // Check the directory/files are deleted successfully. EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.FileExists(kFile)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.DirectoryExists(kDir)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.FileExists(kChild)); // The changes applied by ApplyRemoteChange should not be recorded in // the change tracker. urls.clear(); file_system.GetChangedURLsInTracker(&urls); EXPECT_TRUE(urls.empty()); // The quota usage data must have reflected the deletion. EXPECT_EQ(storage::kQuotaStatusOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_EQ(new_usage, initial_usage); sync_context_->ShutdownOnUIThread(); sync_context_ = nullptr; file_system.TearDown(); } TEST_F(LocalFileSyncContextTest, ApplyRemoteChangeForDeletion_ForRoot) { CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext(sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); // Record the initial usage (likely 0). int64_t initial_usage = -1; int64_t quota = -1; EXPECT_EQ(storage::kQuotaStatusOk, file_system.GetUsageAndQuota(&initial_usage, &quota)); // Create a file and directory in the file_system. const FileSystemURL kFile(file_system.URL("file")); const FileSystemURL kDir(file_system.URL("dir")); const FileSystemURL kChild(file_system.URL("dir/child")); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kFile)); EXPECT_EQ(base::File::FILE_OK, file_system.CreateDirectory(kDir)); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kChild)); // At this point the usage must be greater than the initial usage. int64_t new_usage = -1; EXPECT_EQ(storage::kQuotaStatusOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_GT(new_usage, initial_usage); const FileSystemURL kRoot(file_system.URL("")); // Now let's apply remote deletion changes for the root. FileChange change(FileChange::FILE_CHANGE_DELETE, SYNC_FILE_TYPE_DIRECTORY); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, base::FilePath(), kRoot, SYNC_FILE_TYPE_DIRECTORY)); // Check the directory/files are deleted successfully. EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.FileExists(kFile)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.DirectoryExists(kDir)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.FileExists(kChild)); // All changes made for the previous creation must have been also reset. FileSystemURLSet urls; file_system.GetChangedURLsInTracker(&urls); EXPECT_TRUE(urls.empty()); // The quota usage data must have reflected the deletion. EXPECT_EQ(storage::kQuotaStatusOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_EQ(new_usage, initial_usage); sync_context_->ShutdownOnUIThread(); sync_context_ = nullptr; file_system.TearDown(); } TEST_F(LocalFileSyncContextTest, ApplyRemoteChangeForAddOrUpdate) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext(sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const FileSystemURL kFile1(file_system.URL("file1")); const FileSystemURL kFile2(file_system.URL("file2")); const FileSystemURL kDir(file_system.URL("dir")); const char kTestFileData0[] = "0123456789"; const char kTestFileData1[] = "Lorem ipsum!"; const char kTestFileData2[] = "This is sample test data."; // Create kFile1 and populate it with kTestFileData0. EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kFile1)); EXPECT_EQ(static_cast<int64_t>(arraysize(kTestFileData0) - 1), file_system.WriteString(kFile1, kTestFileData0)); // kFile2 and kDir are not there yet. EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.FileExists(kFile2)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.DirectoryExists(kDir)); // file_system's change tracker must have recorded the creation. FileSystemURLSet urls; file_system.GetChangedURLsInTracker(&urls); ASSERT_EQ(1U, urls.size()); EXPECT_TRUE(ContainsKey(urls, kFile1)); file_system.ClearChangeForURLInTracker(*urls.begin()); // Prepare temporary files which represent the remote file data. const base::FilePath kFilePath1(temp_dir.path().Append(FPL("file1"))); const base::FilePath kFilePath2(temp_dir.path().Append(FPL("file2"))); ASSERT_EQ(static_cast<int>(arraysize(kTestFileData1) - 1), base::WriteFile(kFilePath1, kTestFileData1, arraysize(kTestFileData1) - 1)); ASSERT_EQ(static_cast<int>(arraysize(kTestFileData2) - 1), base::WriteFile(kFilePath2, kTestFileData2, arraysize(kTestFileData2) - 1)); // Record the usage. int64_t usage = -1, new_usage = -1; int64_t quota = -1; EXPECT_EQ(storage::kQuotaStatusOk, file_system.GetUsageAndQuota(&usage, &quota)); // Here in the local filesystem we have: // * kFile1 with kTestFileData0 // // In the remote side let's assume we have: // * kFile1 with kTestFileData1 // * kFile2 with kTestFileData2 // * kDir // // By calling ApplyChange's: // * kFile1 will be updated to have kTestFileData1 // * kFile2 will be created // * kDir will be created // Apply the remote change to kFile1 (which will update the file). FileChange change(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, kFilePath1, kFile1, SYNC_FILE_TYPE_FILE)); // Check if the usage has been increased by (kTestFileData1 - kTestFileData0). const int updated_size = arraysize(kTestFileData1) - arraysize(kTestFileData0); EXPECT_EQ(storage::kQuotaStatusOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_EQ(updated_size, new_usage - usage); // Apply remote changes to kFile2 and kDir (should create a file and // directory respectively). // They are non-existent yet so their expected file type (the last // parameter of ApplyRemoteChange) are // SYNC_FILE_TYPE_UNKNOWN. change = FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, kFilePath2, kFile2, SYNC_FILE_TYPE_UNKNOWN)); change = FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_DIRECTORY); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, base::FilePath(), kDir, SYNC_FILE_TYPE_UNKNOWN)); // Calling ApplyRemoteChange with different file type should be handled as // overwrite. change = FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, kFilePath1, kDir, SYNC_FILE_TYPE_DIRECTORY)); EXPECT_EQ(base::File::FILE_OK, file_system.FileExists(kDir)); change = FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_DIRECTORY); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, kFilePath1, kDir, SYNC_FILE_TYPE_FILE)); // Creating a file/directory must have increased the usage more than // the size of kTestFileData2. new_usage = usage; EXPECT_EQ(storage::kQuotaStatusOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_GT(new_usage, static_cast<int64_t>(usage + arraysize(kTestFileData2) - 1)); // The changes applied by ApplyRemoteChange should not be recorded in // the change tracker. urls.clear(); file_system.GetChangedURLsInTracker(&urls); EXPECT_TRUE(urls.empty()); // Make sure all three files/directory exist. EXPECT_EQ(base::File::FILE_OK, file_system.FileExists(kFile1)); EXPECT_EQ(base::File::FILE_OK, file_system.FileExists(kFile2)); EXPECT_EQ(base::File::FILE_OK, file_system.DirectoryExists(kDir)); sync_context_->ShutdownOnUIThread(); file_system.TearDown(); } TEST_F(LocalFileSyncContextTest, ApplyRemoteChangeForAddOrUpdate_NoParent) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext(sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const char kTestFileData[] = "Lorem ipsum!"; const FileSystemURL kDir(file_system.URL("dir")); const FileSystemURL kFile(file_system.URL("dir/file")); // Either kDir or kFile not exist yet. EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.FileExists(kDir)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.FileExists(kFile)); // Prepare a temporary file which represents remote file data. const base::FilePath kFilePath(temp_dir.path().Append(FPL("file"))); ASSERT_EQ(static_cast<int>(arraysize(kTestFileData) - 1), base::WriteFile(kFilePath, kTestFileData, arraysize(kTestFileData) - 1)); // Calling ApplyChange's with kFilePath should create // kFile along with kDir. FileChange change(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, kFilePath, kFile, SYNC_FILE_TYPE_UNKNOWN)); // The changes applied by ApplyRemoteChange should not be recorded in // the change tracker. FileSystemURLSet urls; urls.clear(); file_system.GetChangedURLsInTracker(&urls); EXPECT_TRUE(urls.empty()); // Make sure kDir and kFile are created by ApplyRemoteChange. EXPECT_EQ(base::File::FILE_OK, file_system.FileExists(kFile)); EXPECT_EQ(base::File::FILE_OK, file_system.DirectoryExists(kDir)); sync_context_->ShutdownOnUIThread(); file_system.TearDown(); } } // namespace sync_file_system
/* $Id$ * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "serialization/EtchValidatorStructValue.h" #include "support/EtchRuntime.h" const EtchObjectType* EtchValidatorStructValue::TYPE() { const static EtchObjectType TYPE(EOTID_VALIDATOR_STRUCT_VALUE, NULL); return &TYPE; } EtchValidatorStructValue::EtchValidatorStructValue(EtchRuntime* runtime, EtchType* type, capu::uint32_t ndim) : EtchTypeValidator(EtchValidatorStructValue::TYPE(), EtchStructValue::TYPE(), EtchStructValue::TYPE(), ndim) , mRuntime(runtime), mType(type) { } EtchValidatorStructValue::EtchValidatorStructValue(const EtchValidatorStructValue& other) : EtchTypeValidator(other), mRuntime(other.mRuntime), mType(other.mType) { } EtchValidatorStructValue::~EtchValidatorStructValue() { } status_t EtchValidatorStructValue::validateValue(capu::SmartPointer<EtchObject> value, capu::SmartPointer<EtchObject>& result) { if (validate(value)) { result = value; ETCH_LOG_TRACE(mRuntime->getLogger(), mRuntime->getLogger().getValidatorContext(), "Struct object has been validated"); return ETCH_OK; } else { ETCH_LOG_WARN(mRuntime->getLogger(), mRuntime->getLogger().getValidatorContext(), "Struct object validation failed"); return ETCH_ERROR; } } capu::bool_t EtchValidatorStructValue::validate(capu::SmartPointer<EtchObject> value) { if (mExpectedType == NULL) return false; if (value.get() == NULL) return false; if (value->getObjectType()->equals(mExpectedType)) return true; //handle array if ((value->getObjectType()->isArray()) && (mExpectedType->isArray())) { //TODO: move getDim to EtchObjectType and set it dynamically during creation of the object EtchNativeArray<capu::SmartPointer<EtchObject> > *array = (EtchNativeArray<capu::SmartPointer<EtchObject> > *) value.get(); if (array->getDim() != mNDims) { return false; } const EtchObjectType* type = array->getObjectType()->getObjectComponentType(); const EtchObjectType* type2 = mExpectedType->getObjectComponentType(); return type->equals(type2); } return (dynamic_cast<EtchValidatorStructValue*> (value.get()) != NULL); } status_t EtchValidatorStructValue::getElementValidator(capu::SmartPointer<EtchValidator> &val) { return Get(mRuntime, mType, mNDims - 1, val); } status_t EtchValidatorStructValue::Get(EtchRuntime* runtime, EtchType* type, capu::uint32_t ndim, capu::SmartPointer<EtchValidator> &val) { if (ndim > MAX_NDIMS) { return ETCH_EINVAL; } ETCH_LOG_TRACE(runtime->getLogger(), runtime->getLogger().getValidatorContext(), "EtchValidatorShort has been created"); val = capu::SmartPointer <EtchValidator > (new EtchValidatorStructValue(runtime, type, ndim)); return ETCH_OK; } EtchType* EtchValidatorStructValue::getType() { return mType; }
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:00 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.MulticastDelegate #include "System/MulticastDelegate.hpp" // Including type: OVR.OpenVR.IVRSystem #include "OVR/OpenVR/IVRSystem.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Skipping declaration: IntPtr because it is already included! // Forward declaring type: IAsyncResult class IAsyncResult; // Forward declaring type: AsyncCallback class AsyncCallback; } // Forward declaring namespace: OVR::OpenVR namespace OVR::OpenVR { // Forward declaring type: ETextureType struct ETextureType; } // Completed forward declares // Type namespace: OVR.OpenVR namespace OVR::OpenVR { // Autogenerated type: OVR.OpenVR.IVRSystem/_GetOutputDevice class IVRSystem::_GetOutputDevice : public System::MulticastDelegate { public: // public System.Void .ctor(System.Object object, System.IntPtr method) // Offset: 0x16A516C static IVRSystem::_GetOutputDevice* New_ctor(::Il2CppObject* object, System::IntPtr method); // public System.Void Invoke(System.UInt64 pnDevice, OVR.OpenVR.ETextureType textureType, System.IntPtr pInstance) // Offset: 0x16A5180 void Invoke(uint64_t& pnDevice, OVR::OpenVR::ETextureType textureType, System::IntPtr pInstance); // public System.IAsyncResult BeginInvoke(System.UInt64 pnDevice, OVR.OpenVR.ETextureType textureType, System.IntPtr pInstance, System.AsyncCallback callback, System.Object object) // Offset: 0x16A5404 System::IAsyncResult* BeginInvoke(uint64_t& pnDevice, OVR::OpenVR::ETextureType textureType, System::IntPtr pInstance, System::AsyncCallback* callback, ::Il2CppObject* object); // public System.Void EndInvoke(System.UInt64 pnDevice, System.IAsyncResult result) // Offset: 0x16A54D4 void EndInvoke(uint64_t& pnDevice, System::IAsyncResult* result); }; // OVR.OpenVR.IVRSystem/_GetOutputDevice } DEFINE_IL2CPP_ARG_TYPE(OVR::OpenVR::IVRSystem::_GetOutputDevice*, "OVR.OpenVR", "IVRSystem/_GetOutputDevice"); #pragma pack(pop)
// // Copyright (C) 2013 Opensim Ltd. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program; if not, see <http://www.gnu.org/licenses/>. // #include <fstream> #include "cstringtokenizer.h" #include "inet/common/INETDefs.h" #include "inet/common/scenario/IScriptable.h" #include "inet/networklayer/common/IRoutingTable.h" #include "inet/networklayer/common/IL3AddressType.h" using namespace std; namespace inet { struct DestFilter { vector<L3Address> destAddresses; vector<int> prefixLengths; DestFilter(const char *str); bool matches(IRoute *route); }; DestFilter::DestFilter(const char *str) { if (str) { cStringTokenizer tokenizer(str); while (tokenizer.hasMoreTokens()) { const char *dest = tokenizer.nextToken(); const char *end = strchr(dest, '/'); if (end) { destAddresses.push_back(L3Address(string(dest,end).c_str())); prefixLengths.push_back(atoi(end+1)); } else { L3Address dest = L3Address(dest); destAddresses.push_back(dest); prefixLengths.push_back(dest.getAddressType()->getMaxPrefixLength()); } } } } bool DestFilter::matches(IRoute *route) { if (destAddresses.empty()) return true; for (int i = 0; i < (int)destAddresses.size(); ++i) { L3Address &dest = destAddresses[i]; int prefixLength = prefixLengths[i]; if (route->getDestinationAsGeneric().matches(dest, prefixLength)) return true; } return false; } class INET_API RoutingTableLogger : public cSimpleModule, public IScriptable { ofstream out; protected: virtual void initialize(); virtual void finish(); virtual void processCommand(const cXMLElement &node); private: IRoutingTable *findRoutingTableInNode(cModule *node); void dumpRoutes(cModule *node, IRoutingTable *rt, DestFilter &filter); }; Define_Module(RoutingTableLogger); void RoutingTableLogger::initialize() { const char *filename = par("outputFile"); if (filename && (*filename)) { out.open(filename); if (out.fail()) throw cRuntimeError("Failed to open output file: %s", filename); } } void RoutingTableLogger::finish() { out << "END" << endl; } void RoutingTableLogger::processCommand(const cXMLElement &command) { Enter_Method_Silent(); const char *tag = command.getTagName(); if (!strcmp(tag, "dump-routes")) { const char *nodes = command.getAttribute("nodes"); if (!nodes) error("missing @nodes attribute"); DestFilter filter(command.getAttribute("dest")); cStringTokenizer tokenizer(nodes); while(tokenizer.hasMoreTokens()) { const char *nodeName = tokenizer.nextToken(); cModule *node = simulation.getModuleByPath(nodeName); if (!node) error("module '%s' not found at %s", nodeName, command.getSourceLocation()); IRoutingTable *rt = findRoutingTableInNode(node); dumpRoutes(node, rt, filter); } } } IRoutingTable *RoutingTableLogger::findRoutingTableInNode(cModule *node) { for (cModule::SubmoduleIterator i(node); !i.end(); i++) { IRoutingTable *rt = dynamic_cast<IRoutingTable*>(i()); if (rt) return rt; } return NULL; } void RoutingTableLogger::dumpRoutes(cModule *node, IRoutingTable *rt, DestFilter &filter) { out << node->getFullName() << " " << simTime() << endl; for (int i = 0; i < rt->getNumRoutes(); ++i) { IRoute *route = rt->getRoute(i); if (filter.matches(route)) { out << route->getDestinationAsGeneric() << "/" << route->getPrefixLength() << " " << route->getNextHopAsGeneric() << " " << (route->getInterface() ? route->getInterface()->getName() : "*") << " " << IRoute::sourceTypeName(route->getSourceType()) << " " << route->getMetric() << endl; } } } } // namespace inet
#pragma once #include "sc_template.hpp" #include "sc_template_named_struct.hpp" #include "sc_template_params.hpp" #include <limits> #include <string> class ScTemplateSearchImpl; /*! * \brief This class allows to run template based search. */ class ScTemplateSearch final { public: class Iterator { friend class ScTemplateSearch; protected: static size_t const kEndIndex = std::numeric_limits<size_t>::max(); Iterator(ScTemplateSearchImpl & search, ScTemplateNamedStruct & namedStruct, size_t idx = kEndIndex) : m_search(search) , m_struct(namedStruct) , m_index(idx) { } public: bool operator == (Iterator const & other) const; bool operator != (Iterator const & other) const; Iterator & operator ++ (); ScTemplateNamedStruct const & operator * () const; ScAddr operator[](std::string const & name) const; ScAddr operator[](ScAddr const & addr) const; private: ScTemplateSearchImpl & m_search; ScTemplateNamedStruct & m_struct; size_t m_index = std::numeric_limits<size_t>::max(); }; ScTemplateSearch(ScMemoryContext & ctx, ScTemplate const & templ, ScTemplateParams const & params = {}, ScAddr const & structAddr = ScAddr::Empty); ~ScTemplateSearch(); Iterator begin(); Iterator end(); protected: std::pair<ScTemplateNamedStruct const &, bool> DoStep(); private: void ApplyParameters(); private: ScMemoryContext & m_ctx; ScTemplate const & m_template; ScTemplatePtr m_templateWithParams; ScAddr m_structAddr; ScTemplateParams m_params; std::unique_ptr<ScTemplateSearchImpl> m_impl; ScTemplateNamedStruct m_result; };
/* * Copyright (C) Huawei Technologies Co., Ltd. 2019-2020. ALL RIGHTS RESERVED. * See file LICENSE for terms. */ extern "C" { #include <ucg/builtin/plan/builtin_plan.h> } #include "ucg_test.h" #include "ucg_plan_test.h" TEST_F(ucg_plan_test, ucg_plan_1_test) { ucg_plan_test example(4, 8, 0); size_t msg_size = UCG_GROUP_MED_MSG_SIZE - 1024; ucg_plan_t *plan = NULL; ucs_status_t ret = ucg_builtin_component.create(&ucg_builtin_component, example.m_ucg_worker, example.m_group, 23, 0, NULL, example.m_group_params); EXPECT_EQ(UCS_OK, ret); ret = ucg_builtin_component.plan(&ucg_builtin_component, &example.m_coll_type, msg_size, example.m_group, example.m_coll_params, &plan); EXPECT_EQ(UCS_OK, ret); } TEST_F(ucg_plan_test, ucg_plan_2_test) { ucg_plan_test example(4, 8, 0); size_t msg_size = UCG_GROUP_MED_MSG_SIZE + 1024; ucg_plan_t *plan = NULL; ucs_status_t ret = ucg_builtin_component.create(&ucg_builtin_component, example.m_ucg_worker, example.m_group, 23, 0, NULL, example.m_group_params); EXPECT_EQ(UCS_OK, ret); ret = ucg_builtin_component.plan(&ucg_builtin_component, &example.m_coll_type, msg_size, example.m_group, example.m_coll_params, &plan); EXPECT_EQ(UCS_OK, ret); } TEST_F(ucg_plan_test, ucg_plan_3_test) { ucg_plan_test example(4, 8, 0); size_t msg_size = UCG_GROUP_MED_MSG_SIZE - 1024; ucg_plan_t *plan = NULL; ucs_status_t ret = ucg_builtin_component.create(&ucg_builtin_component, example.m_ucg_worker, example.m_group, 23, 0, NULL, example.m_group_params); EXPECT_EQ(UCS_OK, ret); ret = ucg_builtin_component.plan(&ucg_builtin_component, &example.m_coll_type, msg_size, example.m_group, example.m_coll_params, &plan); EXPECT_EQ(UCS_OK, ret); } /* TEST_F(ucg_plan_test, ucg_plan_4_test) { ucg_plan_test example(4, 8, 0); size_t msg_size = UCG_GROUP_MED_MSG_SIZE + 1024; ucg_plan_t *plan; ucs_status_t ret = ucg_builtin_component.create(&ucg_builtin_component, example.m_ucg_worker, example.m_group, 23, 0, NULL, example.m_group_params); EXPECT_EQ(UCS_OK, ret); ret = ucg_builtin_component.plan(&ucg_builtin_component, &example.m_coll_type, msg_size, example.m_group, example.m_coll_params, &plan); EXPECT_EQ(UCS_OK, ret); } */ TEST_F(ucg_plan_test, algorithm_selection) { ucs_status_t ret; unsigned idx; for (idx = 0; idx < UCG_ALGORITHM_ALLREDUCE_LAST; idx++) { ret = ucg_builtin_allreduce_algo_switch((enum ucg_builtin_allreduce_algorithm) idx, &ucg_algo); ASSERT_EQ(UCS_OK, ret); } for (idx = 0; idx < UCG_ALGORITHM_BARRIER_LAST; idx++) { ret = ucg_builtin_barrier_algo_switch((enum ucg_builtin_barrier_algorithm) idx, &ucg_algo); ASSERT_EQ(UCS_OK, ret); } for (idx = 0; idx < UCG_ALGORITHM_BCAST_LAST; idx++) { ret = ucg_builtin_bcast_algo_switch((enum ucg_builtin_bcast_algorithm) idx, &ucg_algo); ASSERT_EQ(UCS_OK, ret); } } TEST_F(ucg_plan_test, topo_level) { ucs_status_t ret; ucg_algo.topo_level = UCG_GROUP_HIERARCHY_LEVEL_NODE; enum ucg_group_member_distance domain_distance = UCG_GROUP_MEMBER_DISTANCE_SELF; ret = choose_distance_from_topo_aware_level(&domain_distance); ASSERT_EQ(UCS_OK, ret); ucg_algo.topo_level = UCG_GROUP_HIERARCHY_LEVEL_SOCKET; ret = choose_distance_from_topo_aware_level(&domain_distance); ASSERT_EQ(UCS_OK, ret); ucg_algo.topo_level = UCG_GROUP_HIERARCHY_LEVEL_L3CACHE; ret = choose_distance_from_topo_aware_level(&domain_distance); ASSERT_EQ(UCS_OK, ret); } TEST_F(ucg_plan_test, check_continus_number) { ucg_group_params_t group_params; group_params.member_count = 4; group_params.topo_map = (char **)malloc(sizeof(char *) * group_params.member_count); group_params.topo_map[0] = new char[4] {UCG_GROUP_MEMBER_DISTANCE_SELF, UCG_GROUP_MEMBER_DISTANCE_HOST, UCG_GROUP_MEMBER_DISTANCE_NET, UCG_GROUP_MEMBER_DISTANCE_NET}; group_params.topo_map[1] = new char[4] {UCG_GROUP_MEMBER_DISTANCE_HOST, UCG_GROUP_MEMBER_DISTANCE_SELF, UCG_GROUP_MEMBER_DISTANCE_NET, UCG_GROUP_MEMBER_DISTANCE_NET}; group_params.topo_map[2] = new char[4] {UCG_GROUP_MEMBER_DISTANCE_NET, UCG_GROUP_MEMBER_DISTANCE_NET, UCG_GROUP_MEMBER_DISTANCE_SELF, UCG_GROUP_MEMBER_DISTANCE_HOST}; group_params.topo_map[3] = new char[4] {UCG_GROUP_MEMBER_DISTANCE_NET, UCG_GROUP_MEMBER_DISTANCE_NET, UCG_GROUP_MEMBER_DISTANCE_HOST, UCG_GROUP_MEMBER_DISTANCE_SELF}; unsigned discount = 0; ucs_status_t status = ucg_builtin_check_continuous_number(&group_params, UCG_GROUP_MEMBER_DISTANCE_HOST, &discount); ASSERT_EQ(UCS_OK, status); ASSERT_EQ(0u, discount); group_params.topo_map[0] = new char[4] {UCG_GROUP_MEMBER_DISTANCE_SELF, UCG_GROUP_MEMBER_DISTANCE_HOST, UCG_GROUP_MEMBER_DISTANCE_HOST, UCG_GROUP_MEMBER_DISTANCE_SOCKET}; group_params.topo_map[1] = new char[4] {UCG_GROUP_MEMBER_DISTANCE_HOST, UCG_GROUP_MEMBER_DISTANCE_SELF, UCG_GROUP_MEMBER_DISTANCE_SOCKET, UCG_GROUP_MEMBER_DISTANCE_HOST}; group_params.topo_map[2] = new char[4] {UCG_GROUP_MEMBER_DISTANCE_HOST, UCG_GROUP_MEMBER_DISTANCE_SOCKET, UCG_GROUP_MEMBER_DISTANCE_SELF, UCG_GROUP_MEMBER_DISTANCE_HOST}; group_params.topo_map[3] = new char[4] {UCG_GROUP_MEMBER_DISTANCE_SOCKET, UCG_GROUP_MEMBER_DISTANCE_HOST, UCG_GROUP_MEMBER_DISTANCE_HOST, UCG_GROUP_MEMBER_DISTANCE_SELF}; discount = 0; status = ucg_builtin_check_continuous_number(&group_params, UCG_GROUP_MEMBER_DISTANCE_SOCKET, &discount); ASSERT_EQ(UCS_OK, status); ASSERT_EQ(1u, discount); } TEST_F(ucg_plan_test, choose_type) { enum ucg_collective_modifiers flags[] = \ { UCG_GROUP_COLLECTIVE_MODIFIER_SINGLE_SOURCE, UCG_GROUP_COLLECTIVE_MODIFIER_SINGLE_DESTINATION, \ UCG_GROUP_COLLECTIVE_MODIFIER_AGGREGATE, UCG_GROUP_COLLECTIVE_MODIFIER_AGGREGATE, UCG_GROUP_COLLECTIVE_MODIFIER_AGGREGATE, \ UCG_GROUP_COLLECTIVE_MODIFIER_ALLGATHER, UCG_GROUP_COLLECTIVE_MODIFIER_ALLGATHER}; enum ucg_builtin_plan_topology_type expect_result[] = {UCG_PLAN_TREE_FANOUT, UCG_PLAN_TREE_FANIN, \ UCG_PLAN_RECURSIVE, UCG_PLAN_RING, UCG_PLAN_TREE_FANIN_FANOUT, \ UCG_PLAN_BRUCK, UCG_PLAN_RECURSIVE}; enum ucg_builtin_plan_topology_type ret_type; /* TODO */ unsigned case_num = 7; for (unsigned i = 0; i < case_num; i++) { switch (i) { case 2: ucg_algo.recursive = 1; ucg_algo.ring = 0; ucg_algo.bruck = 0; break; case 3: ucg_algo.recursive = 0; ucg_algo.ring = 1; ucg_algo.bruck = 0; break; case 5: ucg_algo.recursive = 0; ucg_algo.ring = 0; ucg_algo.bruck = 1; break; default: ucg_algo.recursive = 0; ucg_algo.ring = 0; ucg_algo.bruck = 0; break; } ret_type = ucg_builtin_choose_type(flags[i]); ASSERT_EQ(expect_result[i], ret_type); } } /* TODO: add verification to below functions */ /* TEST_F(ucg_plan_test, plan_decision_in_discontinuous_case) { ucg_plan_test example(2, 2, 0); unsigned op_num = 3; enum ucg_collective_modifiers modifiers[op_num] = { (enum ucg_collective_modifiers ) (UCG_GROUP_COLLECTIVE_MODIFIER_BROADCAST | UCG_GROUP_COLLECTIVE_MODIFIER_SINGLE_SOURCE), \ (enum ucg_collective_modifiers) (UCG_GROUP_COLLECTIVE_MODIFIER_AGGREGATE | UCG_GROUP_COLLECTIVE_MODIFIER_BROADCAST | UCG_GROUP_COLLECTIVE_MODIFIER_BARRIER), \ (enum ucg_collective_modifiers) (UCG_GROUP_COLLECTIVE_MODIFIER_AGGREGATE | UCG_GROUP_COLLECTIVE_MODIFIER_BROADCAST) }; unsigned size_num = 2; size_t msg_size[size_num] = {UCG_GROUP_MED_MSG_SIZE - 10, UCG_GROUP_MED_MSG_SIZE + 10}; for (unsigned i = 0; i < op_num; i++) { for (unsigned j = 0; j < size_num; j++) { ucg_builtin_plan_decision_in_discontinuous_case(msg_size[j], example.m_group_params, modifiers[i], example.m_coll_params); } } } */ TEST_F(ucg_plan_test, plan_decision_fixed) { ucg_plan_test example(2, 2, 0); unsigned op_num = 3; enum ucg_collective_modifiers modifiers[op_num] = { (enum ucg_collective_modifiers ) (UCG_GROUP_COLLECTIVE_MODIFIER_BROADCAST | UCG_GROUP_COLLECTIVE_MODIFIER_SINGLE_SOURCE), \ (enum ucg_collective_modifiers) (UCG_GROUP_COLLECTIVE_MODIFIER_AGGREGATE | UCG_GROUP_COLLECTIVE_MODIFIER_BROADCAST | UCG_GROUP_COLLECTIVE_MODIFIER_BARRIER), \ (enum ucg_collective_modifiers) (UCG_GROUP_COLLECTIVE_MODIFIER_AGGREGATE | UCG_GROUP_COLLECTIVE_MODIFIER_BROADCAST) }; unsigned size_num = 2; size_t msg_size[size_num] = {UCG_GROUP_MED_MSG_SIZE - 10, UCG_GROUP_MED_MSG_SIZE + 10}; unsigned data_num = 2; unsigned large_data[data_num] = {100, 10000}; example.m_coll_params->send.dt_len = 200; enum ucg_builtin_bcast_algorithm bcast_algo_decision; enum ucg_builtin_allreduce_algorithm allreduce_algo_decision; enum ucg_builtin_barrier_algorithm barrier_algo_decision; for (unsigned i = 0; i < op_num; i++) { for (unsigned j = 0; j < size_num; j++) { for (unsigned k = 0; k < data_num; k++) { plan_decision_fixed(msg_size[j], example.m_group_params, modifiers[i], example.m_coll_params, large_data[k], 0, &bcast_algo_decision, &allreduce_algo_decision, &barrier_algo_decision); } } } } TEST_F(ucg_plan_test, plan_chooose_ops) { ucg_plan_test example(2, 2, 0); unsigned op_num = 3; enum ucg_collective_modifiers modifiers[op_num] = { (enum ucg_collective_modifiers ) (UCG_GROUP_COLLECTIVE_MODIFIER_BROADCAST | UCG_GROUP_COLLECTIVE_MODIFIER_SINGLE_SOURCE), \ (enum ucg_collective_modifiers) (UCG_GROUP_COLLECTIVE_MODIFIER_AGGREGATE | UCG_GROUP_COLLECTIVE_MODIFIER_BROADCAST | UCG_GROUP_COLLECTIVE_MODIFIER_BARRIER), \ (enum ucg_collective_modifiers) (UCG_GROUP_COLLECTIVE_MODIFIER_AGGREGATE | UCG_GROUP_COLLECTIVE_MODIFIER_BROADCAST) }; for (unsigned i = 0; i < op_num; i++) { ucg_builtin_plan_choose_ops(example.m_planc, modifiers[i]); } } TEST_F(ucg_plan_test, test_algorithm_decision) { ucg_plan_test example(2, 2, 0); ucs_status_t ret = ucg_builtin_algorithm_decision(&(example.m_coll_type), 1024, example.m_group_params, example.m_coll_params, example.m_planc); ASSERT_EQ(UCS_OK, ret); }
#include <math.h> #include <stdio.h> #include "../../../../include/eddl/hardware/fpga/fpga_enables.h" extern "C" { #ifdef K_ENABLED_RAND_UNIFORM void k_rand_uniform(float *A, float v) { #pragma HLS INTERFACE m_axi port=A offset=slave bundle=gmem #pragma HLS INTERFACE s_axilite port=A bundle=control #pragma HLS INTERFACE s_axilite port=v bundle=control } #endif #ifdef K_ENABLED_RAND_SIGNED_UNIFORM void k_rand_signed_uniform(float *A, float v) { #pragma HLS INTERFACE m_axi port=A offset=slave bundle=gmem #pragma HLS INTERFACE s_axilite port=A bundle=control #pragma HLS INTERFACE s_axilite port=v bundle=control } #endif #ifdef K_ENABLED_RAND_BINARY void k_rand_binary(float *A, float v) { #pragma HLS INTERFACE m_axi port=A offset=slave bundle=gmem #pragma HLS INTERFACE s_axilite port=A bundle=control #pragma HLS INTERFACE s_axilite port=v bundle=control } #endif #ifdef K_ENABLED_RAND_NORMAL void k_rand_normal(float *A, float m, float s, bool fast_math) { #pragma HLS INTERFACE m_axi port=A offset=slave bundle=gmem #pragma HLS INTERFACE s_axilite port=A bundle=control #pragma HLS INTERFACE s_axilite port=m bundle=control #pragma HLS INTERFACE s_axilite port=s bundle=control #pragma HLS INTERFACE s_axilite port=fast_math bundle=control } #endif }
/**************************************************************************** * * Copyright (c) 2020, 2021 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. * ****************************************************************************/ #include "param_translation.h" #include <px4_platform_common/log.h> #include <lib/drivers/device/Device.hpp> #include <drivers/drv_sensor.h> #include <lib/parameters/param.h> #include <lib/mathlib/mathlib.h> bool param_modify_on_import(bson_node_t node) { // migrate COM_ARM_AUTH -> COM_ARM_AUTH_ID, COM_ARM_AUTH_MET and COM_ARM_AUTH_TO (2020-11-06). This can be removed after the next release (current release=1.11) if (node->type == BSON_INT32) { if (strcmp("COM_ARM_AUTH", node->name) == 0) { union { struct { uint8_t authorizer_system_id; uint16_t auth_method_arm_timeout_msec; uint8_t authentication_method; } __attribute__((packed)) struct_value; int32_t param_value; } old_param; old_param.param_value = node->i32; int32_t method = old_param.struct_value.authentication_method; param_set_no_notification(param_find("COM_ARM_AUTH_MET"), &method); float timeout = old_param.struct_value.auth_method_arm_timeout_msec / 1000.f; param_set_no_notification(param_find("COM_ARM_AUTH_TO"), &timeout); strcpy(node->name, "COM_ARM_AUTH_ID"); node->i32 = old_param.struct_value.authorizer_system_id; PX4_INFO("migrating COM_ARM_AUTH: %" PRId32 " -> COM_ARM_AUTH_ID:%" PRId8 ", COM_ARM_AUTH_MET: %" PRId32 " and COM_ARM_AUTH_TO: %f", old_param.param_value, old_param.struct_value.authorizer_system_id, method, (double)timeout); } } // 2021-08-27: translate LED_RGB_MAXBRT (0-15) to SYS_RGB_MAXBRT(0.f-1.f) if (node->type == BSON_INT32) { if (strcmp("LED_RGB_MAXBRT", node->name) == 0) { // convert integer (0-15) to float percentage node->d = math::constrain(static_cast<double>(node->i32) / 15., 0., 1.); node->type = BSON_DOUBLE; strcpy(node->name, "SYS_RGB_MAXBRT"); PX4_INFO("param migrating LED_RGB_MAXBRT (removed) -> SYS_RGB_MAXBRT: value=%.3f", node->d); return true; } } // 2020-08-23 (v1.12 alpha): translate GPS blending parameters from EKF2 -> SENS { if (strcmp("EKF2_GPS_MASK", node->name) == 0) { strcpy(node->name, "SENS_GPS_MASK"); PX4_INFO("copying %s -> %s", "EKF2_GPS_MASK", "SENS_GPS_MASK"); return true; } if (strcmp("EKF2_GPS_TAU", node->name) == 0) { strcpy(node->name, "SENS_GPS_TAU"); PX4_INFO("copying %s -> %s", "EKF2_GPS_TAU", "SENS_GPS_TAU"); return true; } } // 2021-01-31 (v1.12 alpha): translate PWM_MIN/PWM_MAX/PWM_DISARMED to PWM_MAIN { if (strcmp("PWM_MIN", node->name) == 0) { strcpy(node->name, "PWM_MAIN_MIN"); PX4_INFO("copying %s -> %s", "PWM_MIN", "PWM_MAIN_MIN"); return true; } if (strcmp("PWM_MAX", node->name) == 0) { strcpy(node->name, "PWM_MAIN_MAX"); PX4_INFO("copying %s -> %s", "PWM_MAX", "PWM_MAIN_MAX"); return true; } if (strcmp("PWM_RATE", node->name) == 0) { strcpy(node->name, "PWM_MAIN_RATE"); PX4_INFO("copying %s -> %s", "PWM_RATE", "PWM_MAIN_RATE"); return true; } if (strcmp("PWM_DISARMED", node->name) == 0) { strcpy(node->name, "PWM_MAIN_DISARM"); PX4_INFO("copying %s -> %s", "PWM_DISARMED", "PWM_MAIN_DISARM"); return true; } } // 2021-04-30: translate ASPD_STALL to FW_AIRSPD_STALL { if (strcmp("ASPD_STALL", node->name) == 0) { strcpy(node->name, "FW_AIRSPD_STALL"); PX4_INFO("copying %s -> %s", "ASPD_STALL", "FW_AIRSPD_STALL"); return true; } } // 2021-07-12: translate VT_DWN_PITCH_MAX to VT_PITCH_MIN { if (strcmp("VT_DWN_PITCH_MAX", node->name) == 0) { strcpy(node->name, "VT_PITCH_MIN"); node->d *= -1; PX4_INFO("copying and inverting sign %s -> %s", "VT_DWN_PITCH_MAX", "VT_PITCH_MIN"); return true; } } // 2021-10-21: translate NAV_GPSF_LT to FW_GPSF_LT and NAV_GPSF_R to FW_GPSF_R { if (strcmp("NAV_GPSF_LT", node->name) == 0) { strcpy(node->name, "FW_GPSF_LT"); node->i32 = static_cast<int32_t>(node->d); node->type = BSON_INT32; PX4_INFO("copying %s -> %s", "NAV_GPSF_LT", "FW_GPSF_LT"); return true; } if (strcmp("NAV_GPSF_R", node->name) == 0) { strcpy(node->name, "FW_GPSF_R"); PX4_INFO("copying %s -> %s", "NAV_GPSF_R", "FW_GPSF_R"); return true; } } // 2022-03-15: translate notch filter IMU_GYRO_NF_FREQ to IMU_GYRO_NF0_FRQ and IMU_GYRO_NF_BW -> IMU_GYRO_NF0_BW { if (strcmp("IMU_GYRO_NF_FREQ", node->name) == 0) { strcpy(node->name, "IMU_GYRO_NF0_FRQ"); PX4_INFO("copying %s -> %s", "IMU_GYRO_NF_FREQ", "IMU_GYRO_NF0_FRQ"); return true; } if (strcmp("IMU_GYRO_NF_BW", node->name) == 0) { strcpy(node->name, "IMU_GYRO_NF0_BW"); PX4_INFO("copying %s -> %s", "IMU_GYRO_NF_BW", "IMU_GYRO_NF0_BW"); return true; } } // 2022-04-25 (v1.13 alpha): translate MS4525->MS4525DO and MS5525->MS5525DSO { if (strcmp("SENS_EN_MS4525", node->name) == 0) { strcpy(node->name, "SENS_EN_MS4525DO"); PX4_INFO("copying %s -> %s", "SENS_EN_MS4525", "SENS_EN_MS4525DO"); return true; } if (strcmp("SENS_EN_MS5525", node->name) == 0) { strcpy(node->name, "SENS_EN_MS5525DS"); PX4_INFO("copying %s -> %s", "SENS_EN_MS5525", "SENS_EN_MS5525DS"); return true; } } return false; }
#pragma once #include "state.hpp" template<Player turn> extern float move_score(const State& state, Move move); extern void calculate_probability(int, const sheena::Array<Move, MaxLegalMove>&, sheena::Array<float, MaxLegalMove>&, float max_score); extern void load_proabiblity();
// // main.cpp // Database2 // // Created by rick gessner on 3/17/19. // Copyright © 2019 rick gessner. All rights reserved. // #include <iostream> #include <sstream> #include <fstream> #include <filesystem> #include "AppProcessor.hpp" #include "Tokenizer.hpp" #include "Errors.hpp" #include "Storage.hpp" #include "FolderReader.hpp" // USE: --------------------------------------------- static std::map<int, std::string> theErrorMessages = { {ECE141::illegalIdentifier, "Illegal identifier"}, {ECE141::unknownIdentifier, "Unknown identifier"}, {ECE141::databaseExists, "Database exists"}, {ECE141::tableExists, "Table Exists"}, {ECE141::syntaxError, "Syntax Error"}, {ECE141::unknownCommand, "Unknown command"}, {ECE141::unknownDatabase,"Unknown database"}, {ECE141::unknownTable, "Unknown table"}, {ECE141::unknownError, "Unknown error"}, {ECE141::noDatabaseSpecified, "No Database Specified"} }; void showError(ECE141::StatusResult &aResult) { std::string theMessage="Unknown Error"; if(theErrorMessages.count(aResult.code)) { theMessage=theErrorMessages[aResult.code]; } std::cout << "Error (" << aResult.code << ") " << theMessage << "\n"; } // input : isStream & CommandProcessor (AppCmdProcessor) // output : Status Result //build a tokenizer, tokenize input, ask processors to handle... ECE141::StatusResult handleInput(std::istream &aStream, ECE141::CommandProcessor &aProcessor) { ECE141::Tokenizer theTokenizer(aStream); //tokenize the input from aStream... ECE141::StatusResult theResult=theTokenizer.tokenize(); while(theResult && theTokenizer.more()) { if(";"==theTokenizer.current().data) { theTokenizer.next(); //skip the ";"... } else theResult=aProcessor.processInput(theTokenizer); } return theResult; } //---------------------------------------------- int main(int argc, const char * argv[]) { //const char* path = ECE141::StorageInfo::getDefaultStoragePath(); ECE141::AppCmdProcessor theProcessor; //add your db processor here too! ECE141::StatusResult theResult{}; ECE141::TestListener aListener{}; // Test FolderReader // std::string dir = std::filesystem::canonical("."); // std::cout << "Current Directory is: " << dir << std::endl; // ECE141::FolderReader reader(dir.c_str()); // std::cout << "Test FolderReader" << std::endl; // std::cout << (reader.exists(dir.c_str()) ? "\t The current path exist OK" : "The currnt path does not exist") << std::endl; // std::string extension = ".hpp"; // std::cout << "\t Test each: input extension is " << extension << std::endl; // reader.each(aListener, extension); if(argc>1) { std::ifstream theStream(argv[1]); return handleInput(theStream, theProcessor); } else { std::string theUserInput; bool running=true; do { std::cout << "\n> "; if(std::getline(std::cin, theUserInput)) { if(theUserInput.length()) { std::stringstream theStream(theUserInput); theResult=handleInput(theStream, theProcessor); if(!theResult) showError(theResult); } if(ECE141::userTerminated==theResult.code) running=false; // if return userTerminated status result -> QUIT! } } while (running); } return 0; }
/* * processor.cpp * * Created on: 2010-8-3 * Author: Argon */ #include "field.h" #include "duel.h" #include "card.h" #include "group.h" #include "effect.h" #include "interpreter.h" #include "ocgapi.h" #include <iterator> void field::add_process(uint16 type, uint16 step, effect* peffect, group* target, ptr arg1, ptr arg2) { processor_unit new_unit; new_unit.type = type; new_unit.step = step; new_unit.peffect = peffect; new_unit.ptarget = target; new_unit.arg1 = arg1; new_unit.arg2 = arg2; core.subunits.push_back(new_unit); } int32 field::process() { if (core.subunits.size()) core.units.splice(core.units.begin(), core.subunits); if (core.units.size() == 0) return PROCESSOR_END + pduel->bufferlen; processor_list::iterator it = core.units.begin(); switch (it->type) { case PROCESSOR_ADJUST: { if (adjust_step(it->step)) core.units.pop_front(); else { it->step++; } return pduel->bufferlen; } case PROCESSOR_TURN: { if (process_turn(it->step, it->arg1)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_WAIT: { core.units.pop_front(); return PROCESSOR_WAITING + pduel->bufferlen; } case PROCESSOR_REFRESH_LOC: { if (refresh_location_info(it->step)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_SELECT_BATTLECMD: { if (select_battle_command(it->step, it->arg1)) { core.units.pop_front(); return pduel->bufferlen; } else { it->step = 1; return PROCESSOR_WAITING + pduel->bufferlen; } } case PROCESSOR_SELECT_IDLECMD: { if (select_idle_command(it->step, it->arg1)) { core.units.pop_front(); return pduel->bufferlen; } else { it->step = 1; return PROCESSOR_WAITING + pduel->bufferlen; } } case PROCESSOR_SELECT_EFFECTYN: { if (select_effect_yes_no(it->step, it->arg1, (card*)it->ptarget)) { core.units.pop_front(); return pduel->bufferlen; } else { it->step = 1; return PROCESSOR_WAITING + pduel->bufferlen; } } case PROCESSOR_SELECT_YESNO: { if (select_yes_no(it->step, it->arg1, it->arg2)) { core.units.pop_front(); return pduel->bufferlen; } else { it->step = 1; return PROCESSOR_WAITING + pduel->bufferlen; } } case PROCESSOR_SELECT_OPTION: { if (select_option(it->step, it->arg1)) { core.units.pop_front(); return pduel->bufferlen; } else { it->step = 1; return PROCESSOR_WAITING + pduel->bufferlen; } } case PROCESSOR_SELECT_CARD: { if (select_card(it->step, it->arg1 & 0xff, (it->arg1 >> 16) & 0xff, (it->arg2) & 0xff, (it->arg2 >> 16) & 0xff)) { core.units.pop_front(); return pduel->bufferlen; } else { it->step = 1; return PROCESSOR_WAITING + pduel->bufferlen; } } case PROCESSOR_SELECT_CHAIN: { if (select_chain(it->step, it->arg1, (it->arg2 & 0xffff), it->arg2 >> 16)) { core.units.pop_front(); return pduel->bufferlen; } else { it->step = 1; return PROCESSOR_WAITING + pduel->bufferlen; } } case PROCESSOR_SELECT_DISFIELD: case PROCESSOR_SELECT_PLACE: { if (select_place(it->step, it->arg1 & 0xffff, it->arg2, (it->arg1 >> 16) & 0xffff)) { core.units.pop_front(); return pduel->bufferlen; } else { it->step = 1; return PROCESSOR_WAITING + pduel->bufferlen; } } case PROCESSOR_SELECT_POSITION: { if (select_position(it->step, it->arg1 & 0xffff, it->arg2, (it->arg1 >> 16) & 0xffff)) { core.units.pop_front(); return pduel->bufferlen; } else { it->step = 1; return PROCESSOR_WAITING + pduel->bufferlen; } } case PROCESSOR_SELECT_TRIBUTE_P: { if (select_tribute(it->step, it->arg1 & 0xff, (it->arg1 >> 16) & 0xff, (it->arg2) & 0xff, (it->arg2 >> 16) & 0xff)) { core.units.pop_front(); return pduel->bufferlen; } else { it->step = 1; return PROCESSOR_WAITING + pduel->bufferlen; } } case PROCESSOR_SORT_CHAIN: { if (sort_chain(it->step, it->arg1)) { core.units.pop_front(); } else { it->step++; } return pduel->bufferlen; } case PROCESSOR_SELECT_COUNTER: { if (select_counter(it->step, it->arg1, (it->arg2) & 0xffff, (it->arg2 >> 16) & 0xffff)) { core.units.pop_front(); return pduel->bufferlen; } else { it->step = 1; return PROCESSOR_WAITING + pduel->bufferlen; } } case PROCESSOR_SELECT_SUM: { if (select_with_sum_limit(it->step, it->arg2 & 0xffff, it->arg1, (it->arg2 >> 16) & 0xff, (it->arg2 >> 24) & 0xff)) { core.units.pop_front(); return pduel->bufferlen; } else { it->step = 1; return PROCESSOR_WAITING + pduel->bufferlen; } } case PROCESSOR_SORT_CARD: { if (sort_card(it->step, it->arg1, it->arg2)) { core.units.pop_front(); return pduel->bufferlen; } else { it->step = 1; return PROCESSOR_WAITING + pduel->bufferlen; } } case PROCESSOR_SELECT_RELEASE: { if (select_release_cards(it->step, it->arg1 & 0xff, (it->arg1 >> 16) & 0xff, (it->arg1 >> 24) & 0xff, (it->arg2) & 0xff, (it->arg2 >> 16) & 0xff)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_SELECT_TRIBUTE: { if (select_tribute_cards(it->step, it->arg1 & 0xff, (it->arg1 >> 16) & 0xff, (it->arg2) & 0xff, (it->arg2 >> 16) & 0xff)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_POINT_EVENT: { if(process_point_event(it->step, it->arg1 & 0xff, (it->arg1 >> 8) & 0xff, it->arg2)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_QUICK_EFFECT: { if(process_quick_effect(it->step, it->arg1, it->arg2)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_IDLE_COMMAND: { if(process_idle_command(it->step)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_PHASE_EVENT: { if(process_phase_event(it->step, it->arg1)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_BATTLE_COMMAND: { if(process_battle_command(it->step)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_DAMAGE_STEP: { if(process_damage_step(it->step)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_ADD_CHAIN: { if (add_chain(it->step)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_SOLVE_CHAIN: { if (solve_chain(it->step, it->arg1, it->arg2)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_SOLVE_CONTINUOUS: { if (solve_continuous(it->step, it->peffect, it->arg1)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_EXECUTE_COST: { if (execute_cost(it->step, it->peffect, it->arg1)) { core.units.pop_front(); core.solving_event.pop_front(); } else it->step++; return pduel->bufferlen; } case PROCESSOR_EXECUTE_OPERATION: { if (execute_operation(it->step, it->peffect, it->arg1)) { core.units.pop_front(); core.solving_event.pop_front(); } else it->step++; return pduel->bufferlen; } case PROCESSOR_EXECUTE_TARGET: { if (execute_target(it->step, it->peffect, it->arg1)) { core.units.pop_front(); core.solving_event.pop_front(); } else it->step++; return pduel->bufferlen; } case PROCESSOR_DESTROY: { if (destroy(it->step, it->ptarget, it->peffect, it->arg1, it->arg2)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_RELEASE: { if (release(it->step, it->ptarget, it->peffect, it->arg1, it->arg2)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_SENDTO: { if (send_to(it->step, it->ptarget, it->peffect, it->arg1, it->arg2)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_DESTROY_STEP: { if(destroy(it->step, it->ptarget, (card*)it->arg1, it->arg2)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_RELEASE_STEP: { if (release(it->step, it->ptarget, (card*)it->arg1)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_SENDTO_STEP: { if (send_to(it->step, it->ptarget, (card*)it->arg1)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_MOVETOFIELD: { if (move_to_field(it->step, (card*)it->ptarget, it->arg1, it->arg2 & 0xff, (it->arg2 >> 8) & 0xff)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_CHANGEPOS: { if (change_position(it->step, it->ptarget, it->peffect, it->arg1, it->arg2)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_OPERATION_REPLACE: { if (operation_replace(it->step, it->peffect, it->ptarget, it->arg1, it->arg2)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_SUMMON_RULE: { if (summon(it->step, it->arg1, (card*)it->ptarget, it->peffect, it->arg2 & 0xff, (it->arg2 >> 8) & 0xff)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_SPSUMMON_RULE: { if (special_summon_rule(it->step, it->arg1, (card*)it->ptarget, it->arg2)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_SPSUMMON: { if (special_summon(it->step, it->peffect, it->arg1, it->ptarget)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_FLIP_SUMMON: { if (flip_summon(it->step, it->arg1, (card*)(it->ptarget))) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_MSET: { if (mset(it->step, it->arg1, (card*)(it->ptarget), it->peffect, it->arg2 & 0xff, (it->arg2 >> 8) & 0xff)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_SSET: { if (sset(it->step, it->arg1, it->arg2, (card*)(it->ptarget))) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_SPSUMMON_STEP: { if (special_summon_step(it->step, it->ptarget, (card*)(it->arg2))) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_SSET_G: { if (sset_g(it->step, it->arg1, it->arg2, it->ptarget)) { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_INT); core.units.pop_front(); } else it->step++; return pduel->bufferlen; } case PROCESSOR_DRAW : { if (draw(it->step, it->peffect, it->arg1, (it->arg2 >> 28) & 0xf, (it->arg2 >> 24) & 0xf, it->arg2 & 0xffffff)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_DAMAGE: { int32 reason = it->arg1; effect* peffect = 0; card* pcard = 0; if(reason & REASON_BATTLE) pcard = (card*)it->peffect; else peffect = it->peffect; if (damage(it->step, peffect, reason, (it->arg2 >> 28) & 0xf, pcard, (it->arg2 >> 24) & 0xf, it->arg2 & 0xffffff)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_RECOVER: { if (recover(it->step, it->peffect, it->arg1, (it->arg2 >> 28) & 0xf, (it->arg2 >> 24) & 0xf, it->arg2 & 0xffffff)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_EQUIP: { if (equip(it->step, it->arg2 & 0xffff, (card*)it->arg1, (card*)it->ptarget, (it->arg2 >> 16) & 0xff, (it->arg2 >> 24) & 0xff)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_GET_CONTROL: { if (get_control(it->step, it->peffect, (it->arg2 >> 28) & 0xf, (card*)it->ptarget, (it->arg2 >> 24) & 0xf, (it->arg2 >> 8) & 0x3ff, it->arg2 & 0xff)) { core.units.pop_front(); } else it->step++; return pduel->bufferlen; } case PROCESSOR_SWAP_CONTROL: { if (swap_control(it->step, it->peffect, (it->arg2 >> 28) & 0xf, (card*)it->ptarget, (card*)it->arg1, (it->arg2 >> 8) & 0x3ff, it->arg2 & 0xff)) { core.units.pop_front(); } else it->step++; return pduel->bufferlen; } case PROCESSOR_CONTROL_ADJUST: { if (control_adjust(it->step)) { core.units.pop_front(); } else it->step++; return pduel->bufferlen; } case PROCESSOR_SELF_DESTROY: { if (self_destroy(it->step)) { core.units.pop_front(); } else it->step++; return pduel->bufferlen; } case PROCESSOR_PAY_LPCOST: { if (pay_lp_cost(it->step, it->arg1, it->arg2)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_REMOVE_COUNTER: { if (remove_counter(it->step, (ptr)it->peffect, (card*)it->ptarget, (it->arg1 >> 16) & 0xff, (it->arg1 >> 8) & 0xff, it->arg1 & 0xff, it->arg2 & 0xffff, it->arg2 >> 16)) { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_BOOLEAN); core.units.pop_front(); } else it->step++; return pduel->bufferlen; } case PROCESSOR_ATTACK_DISABLE: { if(it->step == 0) { card* attacker = core.attacker; if(!attacker || (attacker->fieldid_r != core.pre_field[0]) || (attacker->current.location != LOCATION_MZONE) || !attacker->is_capable_attack() || !attacker->is_affect_by_effect(core.reason_effect)) { returns.ivalue[0] = 0; pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_BOOLEAN); core.units.pop_front(); } else { effect* peffect = pduel->new_effect(); peffect->code = EFFECT_ATTACK_DISABLED; peffect->type = EFFECT_TYPE_SINGLE; attacker->add_effect(peffect); attacker->set_status(STATUS_ATTACK_CANCELED, TRUE); raise_event(attacker, EVENT_ATTACK_DISABLED, core.reason_effect, 0, core.reason_player, PLAYER_NONE, 0); process_instant_event(); it->step++; } } else { returns.ivalue[0] = 1; pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_BOOLEAN); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_DESTROY_S: { if(it->step == 0) { add_process(PROCESSOR_DESTROY, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_INT); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_RELEASE_S: { if(it->step == 0) { add_process(PROCESSOR_RELEASE, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_INT); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_SENDTO_S: { if(it->step == 0) { add_process(PROCESSOR_SENDTO, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_INT); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_CHANGEPOS_S: { if(it->step == 0) { add_process(PROCESSOR_CHANGEPOS, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_INT); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_ANNOUNCE_RACE: { if(announce_race(it->step, it->arg1 & 0xffff, it->arg1 >> 16, it->arg2)) { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_INT); core.units.pop_front(); } else { it->step++; } return PROCESSOR_WAITING + pduel->bufferlen; } case PROCESSOR_ANNOUNCE_ATTRIB: { if(announce_attribute(it->step, it->arg1 & 0xffff, it->arg1 >> 16, it->arg2)) { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_INT); core.units.pop_front(); } else { it->step++; } return PROCESSOR_WAITING + pduel->bufferlen; } case PROCESSOR_ANNOUNCE_CARD: { if(announce_card(it->step, it->arg1, it->arg2)) { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_INT); core.units.pop_front(); } else { it->step++; } return PROCESSOR_WAITING + pduel->bufferlen; } case PROCESSOR_ANNOUNCE_NUMBER: { if(announce_number(it->step, it->arg1)) { pduel->lua->add_param(core.select_options[returns.ivalue[0]], PARAM_TYPE_INT); pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_INT); core.units.pop_front(); } else { it->step++; } return PROCESSOR_WAITING + pduel->bufferlen; } case PROCESSOR_TOSS_DICE: { if(toss_dice(it->step, it->peffect, it->arg1 >> 16, it->arg1 & 0xff, it->arg2 & 0xff, it->arg2 >> 16)) { for(int32 i = 0; i < (it->arg2 & 0xff) + (it->arg2 >> 16); ++i) pduel->lua->add_param(core.dice_result[i], PARAM_TYPE_INT); core.units.pop_front(); } else it->step++; return pduel->bufferlen; } case PROCESSOR_TOSS_COIN: { if (toss_coin(it->step, it->peffect, (it->arg1 >> 16), it->arg1 & 0xff, it->arg2)) { for(int32 i = 0; i < it->arg2; ++i) pduel->lua->add_param(core.coin_result[i], PARAM_TYPE_INT); core.units.pop_front(); } else it->step++; return pduel->bufferlen; } case PROCESSOR_SELECT_EFFECTYN_S: { if(it->step == 0) { add_process(PROCESSOR_SELECT_EFFECTYN, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_BOOLEAN); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_SELECT_YESNO_S: { if(it->step == 0) { add_process(PROCESSOR_SELECT_YESNO, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_BOOLEAN); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_SELECT_OPTION_S: { if(it->step == 0) { add_process(PROCESSOR_SELECT_OPTION, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_INT); pduel->write_buffer8(MSG_HINT); pduel->write_buffer8(HINT_OPSELECTED); pduel->write_buffer8(it->arg1); pduel->write_buffer32(core.select_options[returns.ivalue[0]]); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_SELECT_CARD_S: { if(it->step == 0) { add_process(PROCESSOR_SELECT_CARD, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { group* pgroup = pduel->new_group(); card* pcard; for(int32 i = 0; i < returns.bvalue[0]; ++i) { pcard = core.select_cards[returns.bvalue[i + 1]]; pgroup->container.insert(pcard); } pduel->lua->add_param(pgroup, PARAM_TYPE_GROUP); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_SELECT_PLACE_S: break; case PROCESSOR_SELECT_POSITION_S: { if(it->step == 0) { add_process(PROCESSOR_SELECT_POSITION, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_INT); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_SELECT_RELEASE_S: { if(it->step == 0) { add_process(PROCESSOR_SELECT_RELEASE, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { group* pgroup = pduel->new_group(); card* pcard; for(int32 i = 0; i < returns.bvalue[0]; ++i) { pcard = core.select_cards[returns.bvalue[i + 1]]; pgroup->container.insert(pcard); } pduel->lua->add_param(pgroup, PARAM_TYPE_GROUP); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_SELECT_TRIBUTE_S: { if(it->step == 0) { add_process(PROCESSOR_SELECT_TRIBUTE, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { group* pgroup = pduel->new_group(); card* pcard; for(int32 i = 0; i < returns.bvalue[0]; ++i) { pcard = core.select_cards[returns.bvalue[i + 1]]; pgroup->container.insert(pcard); } pduel->lua->add_param(pgroup, PARAM_TYPE_GROUP); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_SORT_CARDS_S: core.units.pop_front(); break; case PROCESSOR_SELECT_TARGET: { if(it->step == 0) { add_process(PROCESSOR_SELECT_CARD, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { if(core.continuous_chain.size()) { if(!core.continuous_chain.rbegin()->target_cards) { core.continuous_chain.rbegin()->target_cards = pduel->new_group(); core.continuous_chain.rbegin()->target_cards->is_readonly = TRUE; } for(int32 i = 0; i < returns.bvalue[0]; ++i) core.continuous_chain.rbegin()->target_cards->container.insert(core.select_cards[returns.bvalue[i + 1]]); pduel->lua->add_param(core.continuous_chain.rbegin()->target_cards, PARAM_TYPE_GROUP); } else if(core.current_chain.size()) { effect* peffect = core.current_chain.rbegin()->triggering_effect; if(!core.current_chain.rbegin()->target_cards) { core.current_chain.rbegin()->target_cards = pduel->new_group(); core.current_chain.rbegin()->target_cards->is_readonly = TRUE; } group* tg = core.current_chain.rbegin()->target_cards; group* pret = pduel->new_group(); for(int32 i = 0; i < returns.bvalue[0]; ++i) { tg->container.insert(core.select_cards[returns.bvalue[i + 1]]); pret->container.insert(core.select_cards[returns.bvalue[i + 1]]); } if((returns.bvalue[0] > 0) && (peffect->is_flag(EFFECT_FLAG_CARD_TARGET))) { for(int32 i = 0; i < returns.bvalue[0]; ++i) { card* pcard = core.select_cards[returns.bvalue[i + 1]]; if(pcard->current.location & 0x30) move_card(pcard->current.controler, pcard, pcard->current.location, 0); pduel->write_buffer8(MSG_BECOME_TARGET); pduel->write_buffer8(1); pduel->write_buffer32(pcard->get_info_location()); } } for(auto cit = pret->container.begin(); cit != pret->container.end(); ++cit) (*cit)->create_relation(core.current_chain.back()); pduel->lua->add_param(pret, PARAM_TYPE_GROUP); } core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_SELECT_FUSION: { if(it->step == 0) { tevent e; e.event_cards = it->ptarget; e.reason_effect = it->peffect; e.reason_player = it->arg1; core.fusion_materials.clear(); if(!it->peffect) { core.units.pop_front(); return pduel->bufferlen; } core.sub_solving_event.push_back(e); pduel->lua->add_param(it->arg2, PARAM_TYPE_CARD); pduel->lua->add_param(it->arg1 >> 16, PARAM_TYPE_INT); add_process(PROCESSOR_EXECUTE_OPERATION, 0, it->peffect, 0, it->arg1 & 0xffff, 0); it->step++; } else { group* pgroup = pduel->new_group(core.fusion_materials); if(it->arg2) pgroup->container.insert((card*)it->arg2); pduel->lua->add_param(pgroup, PARAM_TYPE_GROUP); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_SELECT_SYNCHRO: { int32 ret = TRUE; if(!(it->arg1 >> 16)) ret = select_synchro_material(it->step, it->arg1 & 0xffff, (card*)it->ptarget, it->arg2 & 0xffff, it->arg2 >> 16, 0, (group*)it->peffect); else ret = select_synchro_material(it->step, it->arg1 & 0xffff, (card*)it->ptarget, it->arg2 & 0xffff, it->arg2 >> 16, (card*)it->peffect, 0); if(ret) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_SELECT_SUM_S: { if(it->step == 0) { add_process(PROCESSOR_SELECT_SUM, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { group* pgroup = pduel->new_group(); int32 mcount = core.must_select_cards.size(); for(int32 i = mcount; i < returns.bvalue[0]; ++i) { card* pcard = core.select_cards[returns.bvalue[i + 1]]; pgroup->container.insert(pcard); } core.must_select_cards.clear(); pduel->lua->add_param(pgroup, PARAM_TYPE_GROUP); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_SELECT_DISFIELD_S: { if(it->step == 0) { add_process(PROCESSOR_SELECT_DISFIELD, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { int32 playerid = it->arg1 & 0xffff; int32 count = (it->arg1) >> 16; int32 dfflag = 0; uint8 p, l, s, pa = 0; for(int32 i = 0; i < count; ++i) { p = returns.bvalue[pa]; l = returns.bvalue[pa + 1]; s = returns.bvalue[pa + 2]; dfflag |= 1 << (s + (p == playerid ? 0 : 16) + (l == LOCATION_MZONE ? 0 : 8)); pa += 3; } pduel->lua->add_param(dfflag, PARAM_TYPE_INT); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_SPSUMMON_S: { if(it->step == 0) { add_process(PROCESSOR_SPSUMMON, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_INT); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_SPSUMMON_STEP_S: { if(it->step == 0) { add_process(PROCESSOR_SPSUMMON_STEP, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_BOOLEAN); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_SPSUMMON_COMP_S: { if(it->step == 0) { add_process(PROCESSOR_SPSUMMON, 1, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_INT); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_RANDOM_SELECT_S: { uint32 count = it->arg2; group* pgroup = it->ptarget; group* newgroup = pduel->new_group(); if(count > pgroup->container.size()) count = pgroup->container.size(); if(count == 0) { pduel->lua->add_param(newgroup, PARAM_TYPE_GROUP); core.units.pop_front(); return pduel->bufferlen; } duel* pduel = pgroup->pduel; if(count == pgroup->container.size()) newgroup->container = pgroup->container; else { while(newgroup->container.size() < count) { int32 i = pduel->get_next_integer(0, pgroup->container.size() - 1); auto cit = pgroup->container.begin(); std::advance(cit, i); newgroup->container.insert(*cit); } } pduel->lua->add_param(newgroup, PARAM_TYPE_GROUP); pduel->write_buffer8(MSG_RANDOM_SELECTED); pduel->write_buffer8(it->arg1); pduel->write_buffer8(count); for(auto cit = newgroup->container.begin(); cit != newgroup->container.end(); ++cit) { pduel->write_buffer32((*cit)->get_info_location()); } core.units.pop_front(); return pduel->bufferlen; } case PROCESSOR_SELECT_XMATERIAL: { if (select_xyz_material(it->step, it->arg1 & 0xffff, it->arg1 >> 16, (card*)it->ptarget, it->arg2 & 0xffff, it->arg2 >> 16)) core.units.pop_front(); else it->step++; return pduel->bufferlen; } case PROCESSOR_DRAW_S: { if(it->step == 0) { add_process(PROCESSOR_DRAW, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_INT); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_DAMAGE_S: { if(it->step == 0) { add_process(PROCESSOR_DAMAGE, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_INT); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_RECOVER_S: { if(it->step == 0) { add_process(PROCESSOR_RECOVER, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_INT); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_EQUIP_S: { if(it->step == 0) { add_process(PROCESSOR_EQUIP, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_BOOLEAN); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_GET_CONTROL_S: { if(it->step == 0) { add_process(PROCESSOR_GET_CONTROL, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_BOOLEAN); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_SWAP_CONTROL_S: { if(it->step == 0) { add_process(PROCESSOR_SWAP_CONTROL, 0, it->peffect, it->ptarget, it->arg1, it->arg2); it->step++; } else { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_BOOLEAN); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_DISCARD_HAND_S: { if(it->step == 0) { pduel->write_buffer8(MSG_HINT); pduel->write_buffer8(HINT_SELECTMSG); pduel->write_buffer8(it->arg1); if(((ptr)it->ptarget) & REASON_DISCARD) pduel->write_buffer32(501); else pduel->write_buffer32(504); add_process(PROCESSOR_SELECT_CARD, 0, 0, 0, it->arg1, it->arg2); it->step++; } else if(it->step == 1) { card_set cset; card* pcard; for(int32 i = 0; i < returns.bvalue[0]; ++i) { pcard = core.select_cards[returns.bvalue[i + 1]]; cset.insert(pcard); } if(cset.size()) send_to(&cset, core.reason_effect, (ptr)(it->ptarget), core.reason_player, it->arg1, LOCATION_GRAVE, 0, POS_FACEUP); else returns.ivalue[0] = 0; it->step++; } else { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_INT); core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_DISCARD_DECK_S: { if(discard_deck(it->step, it->arg1 & 0xff, it->arg1 >> 16, it->arg2)) { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_INT); core.units.pop_front(); } else { it->step++; } return pduel->bufferlen; } case PROCESSOR_SORT_DECK_S: { uint8 sort_player = it->arg1 & 0xffff; uint8 target_player = it->arg1 >> 16; uint8 count = it->arg2, i = 0; if(count > player[target_player].list_main.size()) count = player[target_player].list_main.size(); if(it->step == 0) { core.select_cards.clear(); for(auto clit = player[target_player].list_main.rbegin(); i < count; ++i, ++clit) core.select_cards.push_back(*clit); add_process(PROCESSOR_SORT_CARD, 0, 0, 0, sort_player, 0); it->step++; } else { if(returns.bvalue[0] != -1) { card* tc[16]; for(i = 0; i < count; ++i) player[target_player].list_main.pop_back(); for(i = 0; i < count; ++i) tc[(int32)returns.bvalue[i]] = core.select_cards[i]; for(i = 0; i < count; ++i) { player[target_player].list_main.push_back(tc[count - i - 1]); tc[count - i - 1]->current.sequence = player[target_player].list_main.size() - 1; } } if(core.global_flag & GLOBALFLAG_DECK_REVERSE_CHECK) { if(count > 0) { card* ptop = player[target_player].list_main.back(); if(core.deck_reversed || (ptop->current.position == POS_FACEUP_DEFENCE)) { pduel->write_buffer8(MSG_DECK_TOP); pduel->write_buffer8(target_player); pduel->write_buffer8(0); if(ptop->current.position != POS_FACEUP_DEFENCE) pduel->write_buffer32(ptop->data.code); else pduel->write_buffer32(ptop->data.code | 0x80000000); } } } core.units.pop_front(); } return pduel->bufferlen; } case PROCESSOR_REMOVEOL_S: { if(remove_overlay_card(it->step, (ptr)(it->peffect), (card*)(it->ptarget), it->arg1 >> 16, (it->arg1 >> 8) & 0xff, it->arg1 & 0xff, it->arg2 & 0xffff, it->arg2 >> 16)) { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_BOOLEAN); core.units.pop_front(); } else { it->step++; } return pduel->bufferlen; } case PROCESSOR_MOVETOFIELD_S: { if (move_to_field(it->step, (card*)it->ptarget, it->arg1, it->arg2 & 0xff, (it->arg2 >> 8) & 0xff)) { pduel->lua->add_param(returns.ivalue[0], PARAM_TYPE_BOOLEAN); core.units.pop_front(); } else it->step++; return pduel->bufferlen; } } return pduel->bufferlen; } int32 field::execute_cost(uint16 step, effect * triggering_effect, uint8 triggering_player) { if(!triggering_effect->cost) { core.solving_event.splice(core.solving_event.begin(), core.sub_solving_event); pduel->lua->params.clear(); return TRUE; } if (step == 0) { core.solving_event.splice(core.solving_event.begin(), core.sub_solving_event); const tevent& e = core.solving_event.front(); pduel->lua->add_param(1, PARAM_TYPE_INT, true); pduel->lua->add_param(e.reason_player, PARAM_TYPE_INT, true); pduel->lua->add_param(e.reason, PARAM_TYPE_INT, true); pduel->lua->add_param(e.reason_effect , PARAM_TYPE_EFFECT, true); pduel->lua->add_param(e.event_value, PARAM_TYPE_INT, true); pduel->lua->add_param(e.event_player, PARAM_TYPE_INT, true); pduel->lua->add_param(e.event_cards , PARAM_TYPE_GROUP, true); pduel->lua->add_param(triggering_player, PARAM_TYPE_INT, true); pduel->lua->add_param(triggering_effect, PARAM_TYPE_EFFECT, true); if(core.check_level == 0) { core.shuffle_deck_check[0] = FALSE; core.shuffle_deck_check[1] = FALSE; core.shuffle_hand_check[0] = FALSE; core.shuffle_hand_check[1] = FALSE; } core.shuffle_check_disabled = FALSE; core.check_level++; } core.reason_effect = triggering_effect; core.reason_player = triggering_player; uint32 count = pduel->lua->params.size(); uint32 yield_value = 0; int32 result = pduel->lua->call_coroutine(triggering_effect->cost, count, &yield_value, step); returns.ivalue[0] = yield_value; if (result == COROUTINE_FINISH || result == COROUTINE_ERROR || result == OPERATION_FAIL) { core.reason_effect = 0; core.reason_player = PLAYER_NONE; core.check_level--; if(core.check_level == 0) { if(core.shuffle_hand_check[0]) shuffle(0, LOCATION_HAND); if(core.shuffle_hand_check[1]) shuffle(1, LOCATION_HAND); if(core.shuffle_deck_check[0]) shuffle(0, LOCATION_DECK); if(core.shuffle_deck_check[1]) shuffle(1, LOCATION_DECK); } core.shuffle_check_disabled = FALSE; return TRUE; } return FALSE; } int32 field::execute_operation(uint16 step, effect * triggering_effect, uint8 triggering_player) { if(!triggering_effect->operation) { core.solving_event.splice(core.solving_event.begin(), core.sub_solving_event); pduel->lua->params.clear(); return TRUE; } if (step == 0) { core.solving_event.splice(core.solving_event.begin(), core.sub_solving_event); const tevent& e = core.solving_event.front(); pduel->lua->add_param(e.reason_player, PARAM_TYPE_INT, true); pduel->lua->add_param(e.reason, PARAM_TYPE_INT, true); pduel->lua->add_param(e.reason_effect , PARAM_TYPE_EFFECT, true); pduel->lua->add_param(e.event_value, PARAM_TYPE_INT, true); pduel->lua->add_param(e.event_player, PARAM_TYPE_INT, true); pduel->lua->add_param(e.event_cards , PARAM_TYPE_GROUP, true); pduel->lua->add_param(triggering_player, PARAM_TYPE_INT, true); pduel->lua->add_param(triggering_effect, PARAM_TYPE_EFFECT, true); if(core.check_level == 0) { core.shuffle_deck_check[0] = FALSE; core.shuffle_deck_check[1] = FALSE; core.shuffle_hand_check[0] = FALSE; core.shuffle_hand_check[1] = FALSE; } core.shuffle_check_disabled = FALSE; core.check_level++; } core.reason_effect = triggering_effect; core.reason_player = triggering_player; uint32 count = pduel->lua->params.size(); uint32 yield_value = 0; int32 result = pduel->lua->call_coroutine(triggering_effect->operation, count, &yield_value, step); returns.ivalue[0] = yield_value; if (result == COROUTINE_FINISH || result == COROUTINE_ERROR || result == OPERATION_FAIL) { core.reason_effect = 0; core.reason_player = PLAYER_NONE; core.check_level--; if(core.check_level == 0) { if(core.shuffle_hand_check[0]) shuffle(0, LOCATION_HAND); if(core.shuffle_hand_check[1]) shuffle(1, LOCATION_HAND); if(core.shuffle_deck_check[0]) shuffle(0, LOCATION_DECK); if(core.shuffle_deck_check[1]) shuffle(1, LOCATION_DECK); cost[0].count = 0; cost[1].count = 0; cost[0].amount = 0; cost[1].amount = 0; } core.shuffle_check_disabled = FALSE; return TRUE; } return FALSE; } int32 field::execute_target(uint16 step, effect * triggering_effect, uint8 triggering_player) { if(!triggering_effect->target) { core.solving_event.splice(core.solving_event.begin(), core.sub_solving_event); pduel->lua->params.clear(); return TRUE; } if (step == 0) { core.solving_event.splice(core.solving_event.begin(), core.sub_solving_event); const tevent& e = core.solving_event.front(); pduel->lua->add_param(1, PARAM_TYPE_INT, true); pduel->lua->add_param(e.reason_player, PARAM_TYPE_INT, true); pduel->lua->add_param(e.reason, PARAM_TYPE_INT, true); pduel->lua->add_param(e.reason_effect , PARAM_TYPE_EFFECT, true); pduel->lua->add_param(e.event_value, PARAM_TYPE_INT, true); pduel->lua->add_param(e.event_player, PARAM_TYPE_INT, true); pduel->lua->add_param(e.event_cards , PARAM_TYPE_GROUP, true); pduel->lua->add_param(triggering_player, PARAM_TYPE_INT, true); pduel->lua->add_param(triggering_effect, PARAM_TYPE_EFFECT, true); if(core.check_level == 0) { core.shuffle_deck_check[0] = FALSE; core.shuffle_deck_check[1] = FALSE; core.shuffle_hand_check[0] = FALSE; core.shuffle_hand_check[1] = FALSE; } core.shuffle_check_disabled = FALSE; core.check_level++; } core.reason_effect = triggering_effect; core.reason_player = triggering_player; uint32 count = pduel->lua->params.size(); uint32 yield_value = 0; int32 result = pduel->lua->call_coroutine(triggering_effect->target, count, &yield_value, step); returns.ivalue[0] = yield_value; if (result == COROUTINE_FINISH || result == COROUTINE_ERROR || result == OPERATION_FAIL) { core.reason_effect = 0; core.reason_player = PLAYER_NONE; core.check_level--; if(core.check_level == 0) { if(core.shuffle_hand_check[0]) shuffle(0, LOCATION_HAND); if(core.shuffle_hand_check[1]) shuffle(1, LOCATION_HAND); if(core.shuffle_deck_check[0]) shuffle(0, LOCATION_DECK); if(core.shuffle_deck_check[1]) shuffle(1, LOCATION_DECK); } core.shuffle_check_disabled = FALSE; return TRUE; } return FALSE; } void field::raise_event(card* event_card, uint32 event_code, effect* reason_effect, uint32 reason, uint8 reason_player, uint8 event_player, uint32 event_value) { tevent new_event; new_event.trigger_card = 0; if (event_card) { group* pgroup = pduel->new_group(event_card); pgroup->is_readonly = TRUE; new_event.event_cards = pgroup; } else new_event.event_cards = 0; new_event.event_code = event_code; new_event.reason_effect = reason_effect; new_event.reason = reason; new_event.reason_player = reason_player; new_event.event_player = event_player; new_event.event_value = event_value; core.queue_event.push_back(new_event); } void field::raise_event(card_set* event_cards, uint32 event_code, effect* reason_effect, uint32 reason, uint8 reason_player, uint8 event_player, uint32 event_value) { tevent new_event; new_event.trigger_card = 0; if (event_cards) { group* pgroup = pduel->new_group(*event_cards); pgroup->is_readonly = TRUE; new_event.event_cards = pgroup; } else new_event.event_cards = 0; new_event.event_code = event_code; new_event.reason_effect = reason_effect; new_event.reason = reason; new_event.reason_player = reason_player; new_event.event_player = event_player; new_event.event_value = event_value; core.queue_event.push_back(new_event); } void field::raise_single_event(card* trigger_card, card_set* event_cards, uint32 event_code, effect * reason_effect, uint32 reason, uint8 reason_player, uint8 event_player, uint32 event_value) { tevent new_event; new_event.trigger_card = trigger_card; if (event_cards) { group* pgroup = pduel->new_group(*event_cards); pgroup->is_readonly = TRUE; new_event.event_cards = pgroup; } else new_event.event_cards = 0; new_event.event_code = event_code; new_event.reason_effect = reason_effect; new_event.reason = reason; new_event.reason_player = reason_player; new_event.event_player = event_player; new_event.event_value = event_value; core.single_event.push_back(new_event); } int32 field::check_event(uint32 code, tevent * pe) { for(auto eit = core.point_event.begin(); eit != core.point_event.end(); ++eit) { if(eit->event_code == code) { if(pe) *pe = *eit; return TRUE; } } for(auto eit = core.instant_event.begin(); eit != core.instant_event.end(); ++eit) { if(eit->event_code == code) { if(pe) *pe = *eit; return TRUE; } } return FALSE; } int32 field::check_event_c(effect* peffect, uint8 playerid, int32 neglect_con, int32 neglect_cost, int32 copy_info, tevent* pe) { if(peffect->code == EVENT_FREE_CHAIN) { return peffect->is_activate_ready(playerid, nil_event, neglect_con, neglect_cost, FALSE); } for(auto eit = core.point_event.begin(); eit != core.point_event.end(); ++eit) { if(eit->event_code == peffect->code && peffect->is_activate_ready(playerid, *eit, neglect_con, neglect_cost, FALSE)) { if(pe) *pe = *eit; if(copy_info && !pduel->lua->no_action && core.current_chain.size()) { core.current_chain.back().evt = *eit; } return TRUE; } } for(auto eit = core.instant_event.begin(); eit != core.instant_event.end(); ++eit) { if(eit->event_code == peffect->code && peffect->is_activate_ready(playerid, *eit, neglect_con, neglect_cost, FALSE)) { if(pe) *pe = *eit; if(copy_info && !pduel->lua->no_action && core.current_chain.size()) { core.current_chain.back().evt = *eit; } return TRUE; } } return FALSE; } int32 field::check_hint_timing(effect* peffect) { int32 p = peffect->get_handler_player(); if(p == 0) return (peffect->hint_timing[0] & core.hint_timing[0]) || (peffect->hint_timing[1] & core.hint_timing[1]); else return (peffect->hint_timing[0] & core.hint_timing[1]) || (peffect->hint_timing[1] & core.hint_timing[0]); } int32 field::process_phase_event(int16 step, int32 phase) { switch(step) { case 0: { if((phase == PHASE_DRAW && is_player_affected_by_effect(infos.turn_player, EFFECT_SKIP_DP)) || (phase == PHASE_STANDBY && is_player_affected_by_effect(infos.turn_player, EFFECT_SKIP_SP)) || (phase == PHASE_BATTLE_START && is_player_affected_by_effect(infos.turn_player, EFFECT_SKIP_BP))) { core.units.begin()->step = 24; return FALSE; } int32 phase_event = EVENT_PHASE + phase; effect* peffect; nil_event.event_code = phase_event; nil_event.event_player = infos.turn_player; int32 check_player = infos.turn_player; if(core.units.begin()->arg2 & 0x2) check_player = 1 - infos.turn_player; chain newchain; core.select_chains.clear(); int32 tf_count = 0, to_count = 0, fc_count = 0, cn_count = 0; auto pr = effects.trigger_f_effect.equal_range(phase_event); for(; pr.first != pr.second; ++pr.first) { peffect = pr.first->second; peffect->s_range = peffect->handler->current.location; peffect->o_range = peffect->handler->current.sequence; if(!peffect->is_activateable(check_player, nil_event)) continue; peffect->id = infos.field_id++; newchain.triggering_effect = peffect; core.select_chains.push_back(newchain); tf_count++; } pr = effects.continuous_effect.equal_range(phase_event); for(; pr.first != pr.second;) { peffect = pr.first->second; ++pr.first; if(peffect->get_handler_player() != check_player || !peffect->is_activateable(check_player, nil_event)) continue; peffect->id = infos.field_id++; newchain.triggering_effect = peffect; core.select_chains.push_back(newchain); cn_count++; } for(auto eit = effects.pheff.begin(); eit != effects.pheff.end(); ++eit) { peffect = *eit; if(peffect->code != EFFECT_SET_CONTROL) continue; if(peffect->get_owner_player() != check_player) continue; if(!(peffect->reset_flag & phase)) continue; uint8 pid = peffect->get_handler_player(); uint8 tp = infos.turn_player; if(!(((peffect->reset_flag & RESET_SELF_TURN) && pid == tp) || ((peffect->reset_flag & RESET_OPPO_TURN) && pid != tp))) continue; if((peffect->reset_count & 0xff) != 1) continue; newchain.triggering_effect = peffect; core.select_chains.push_back(newchain); cn_count++; } core.spe_effect[check_player] = 0; if(!core.hand_adjusted) { pr = effects.trigger_o_effect.equal_range(phase_event); for(; pr.first != pr.second; ++pr.first) { peffect = pr.first->second; peffect->s_range = peffect->handler->current.location; peffect->o_range = peffect->handler->current.sequence; if(!peffect->is_activateable(check_player, nil_event)) continue; peffect->id = infos.field_id++; newchain.triggering_effect = peffect; core.select_chains.push_back(newchain); to_count++; core.spe_effect[check_player]++; } if(phase == PHASE_DRAW) core.hint_timing[infos.turn_player] = TIMING_DRAW_PHASE; else if(phase == PHASE_STANDBY) core.hint_timing[infos.turn_player] = TIMING_STANDBY_PHASE; else if(phase == PHASE_BATTLE_START) core.hint_timing[infos.turn_player] = TIMING_BATTLE_START; else if(phase == PHASE_BATTLE) core.hint_timing[infos.turn_player] = TIMING_BATTLE_END; else core.hint_timing[infos.turn_player] = TIMING_END_PHASE; pr = effects.activate_effect.equal_range(EVENT_FREE_CHAIN); for(; pr.first != pr.second; ++pr.first) { peffect = pr.first->second; peffect->s_range = peffect->handler->current.location; peffect->o_range = peffect->handler->current.sequence; if(!peffect->is_chainable(check_player) || !peffect->is_activateable(check_player, nil_event)) continue; peffect->id = infos.field_id++; newchain.triggering_effect = peffect; if(check_hint_timing(peffect)) core.spe_effect[check_player]++; core.select_chains.push_back(newchain); fc_count++; } pr = effects.quick_o_effect.equal_range(EVENT_FREE_CHAIN); for(; pr.first != pr.second; ++pr.first) { peffect = pr.first->second; peffect->s_range = peffect->handler->current.location; peffect->o_range = peffect->handler->current.sequence; if(!peffect->is_chainable(check_player) || !peffect->is_activateable(check_player, nil_event)) continue; peffect->id = infos.field_id++; newchain.triggering_effect = peffect; if(check_hint_timing(peffect)) core.spe_effect[check_player]++; core.select_chains.push_back(newchain); fc_count++; } } if(core.select_chains.size() == 0) { returns.ivalue[0] = -1; core.units.begin()->step = 1; return FALSE; } else if(tf_count == 0 && cn_count == 1 && to_count == 0 && fc_count == 0) { returns.ivalue[0] = 0; core.units.begin()->step = 1; return FALSE; } else if(tf_count == 0 && to_count == 1 && fc_count == 0 && cn_count == 0) { add_process(PROCESSOR_SELECT_EFFECTYN, 0, 0, (group*)core.select_chains[0].triggering_effect->handler, check_player, 0); return FALSE; } else { pduel->write_buffer8(MSG_HINT); pduel->write_buffer8(HINT_EVENT); pduel->write_buffer8(check_player); if(infos.phase == PHASE_DRAW) pduel->write_buffer32(20); else if(infos.phase == PHASE_STANDBY) pduel->write_buffer32(21); else if(infos.phase == PHASE_BATTLE_START) pduel->write_buffer32(28); else if(infos.phase == PHASE_BATTLE) pduel->write_buffer32(25); else pduel->write_buffer32(26); add_process(PROCESSOR_SELECT_CHAIN, 0, 0, 0, check_player, core.spe_effect[check_player] | (tf_count + cn_count ? 0x10000 : 0)); core.units.begin()->step = 1; return FALSE; } return FALSE; } case 1: { returns.ivalue[0]--; return FALSE; } case 2: { int32 priority_passed = core.units.begin()->arg2 & 0x1; int32 is_opponent = core.units.begin()->arg2 & 0x2; if(returns.ivalue[0] == -1) { if(priority_passed) core.units.begin()->step = 19; else { priority_passed = 1; is_opponent ^= 0x2; core.units.begin()->arg2 = is_opponent | priority_passed; core.units.begin()->step = -1; } return FALSE; } priority_passed = 0; core.units.begin()->arg2 = is_opponent | priority_passed; chain newchain = core.select_chains[returns.ivalue[0]]; effect* peffect = newchain.triggering_effect; if(!(peffect->type & EFFECT_TYPE_ACTIONS)) { if(peffect->is_flag(EFFECT_FLAG_FIELD_ONLY)) remove_effect(peffect); else peffect->handler->remove_effect(peffect); adjust_all(); core.units.begin()->step = 3; } else if(!(peffect->type & EFFECT_TYPE_CONTINUOUS)) { int32 check_player = infos.turn_player; if(is_opponent) check_player = 1 - infos.turn_player; newchain.flag = 0; newchain.chain_id = infos.field_id++; newchain.evt = nil_event; newchain.triggering_controler = peffect->handler->current.controler; newchain.triggering_location = peffect->handler->current.location; newchain.triggering_sequence = peffect->handler->current.sequence; newchain.triggering_player = check_player; core.new_chains.push_back(newchain); peffect->handler->set_status(STATUS_CHAINING, TRUE); peffect->dec_count(check_player); core.select_chains.clear(); add_process(PROCESSOR_ADD_CHAIN, 0, 0, 0, 0, 0); add_process(PROCESSOR_QUICK_EFFECT, 0, 0, 0, FALSE, 1 - check_player); infos.priorities[0] = 0; infos.priorities[1] = 0; } else { core.select_chains.clear(); core.sub_solving_event.push_back(nil_event); add_process(PROCESSOR_SOLVE_CONTINUOUS, 0, peffect, 0, peffect->get_handler_player(), 0); core.units.begin()->step = 3; } return FALSE; } case 3: { if(core.chain_limit) { luaL_unref(pduel->lua->lua_state, LUA_REGISTRYINDEX, core.chain_limit); core.chain_limit = 0; } for(auto cait = core.current_chain.begin(); cait != core.current_chain.end(); ++cait) cait->triggering_effect->handler->set_status(STATUS_CHAINING, FALSE); add_process(PROCESSOR_SOLVE_CHAIN, 0, 0, 0, FALSE, 0); core.units.begin()->step = -1; return FALSE; } case 4: { adjust_instant(); add_process(PROCESSOR_POINT_EVENT, 0, 0, 0, 0, 0); core.units.begin()->step = -1; return FALSE; } case 20: { if(phase != PHASE_END) { core.units.begin()->step = 24; return FALSE; } int32 limit = 6; effect_set eset; filter_player_effect(infos.turn_player, EFFECT_HAND_LIMIT, &eset); if(eset.size()) limit = eset.get_last()->get_value(); int32 hd = player[infos.turn_player].list_hand.size(); if(hd <= limit) { core.units.begin()->step = 24; return FALSE; } core.select_cards.clear(); for(auto cit = player[infos.turn_player].list_hand.begin(); cit != player[infos.turn_player].list_hand.end(); ++cit) core.select_cards.push_back(*cit); pduel->write_buffer8(MSG_HINT); pduel->write_buffer8(HINT_SELECTMSG); pduel->write_buffer8(infos.turn_player); pduel->write_buffer32(501); add_process(PROCESSOR_SELECT_CARD, 0, 0, 0, infos.turn_player, hd - limit + ((hd - limit) << 16)); return FALSE; } case 21: { card_set cset; for(int32 i = 0; i < returns.bvalue[0]; ++i) cset.insert(core.select_cards[returns.bvalue[i + 1]]); send_to(&cset, 0, REASON_RULE + REASON_DISCARD + REASON_ADJUST, infos.turn_player, PLAYER_NONE, LOCATION_GRAVE, 0, POS_FACEUP); return FALSE; } case 22: { core.hand_adjusted = TRUE; add_process(PROCESSOR_POINT_EVENT, 0, 0, 0, 0, 0); core.units.begin()->step = -1; core.units.begin()->arg2 = 0; return FALSE; } case 25: { core.hint_timing[infos.turn_player] = 0; reset_phase(phase); adjust_all(); return FALSE; } case 26: { core.quick_f_chain.clear(); core.instant_event.clear(); core.point_event.clear(); return TRUE; } } return TRUE; } int32 field::process_point_event(int16 step, int32 skip_trigger, int32 skip_freechain, int32 skip_new) { switch(step) { case 0: { core.select_chains.clear(); core.point_event.splice(core.point_event.end(), core.instant_event); if(skip_trigger) { core.units.begin()->step = 7; return FALSE; } core.new_fchain_s.splice(core.new_fchain_s.begin(), core.new_fchain); core.new_ochain_s.splice(core.new_ochain_s.begin(), core.new_ochain); core.tpchain.clear(); core.ntpchain.clear(); core.delayed_quick.clear(); core.delayed_quick_break.swap(core.delayed_quick); core.current_player = infos.turn_player; core.units.begin()->step = 1; return FALSE; } case 1: { return FALSE; } case 2: { //forced trigger for (auto clit = core.new_fchain_s.begin(); clit != core.new_fchain_s.end(); ++clit) { effect* peffect = clit->triggering_effect; if(!peffect->is_flag(EFFECT_FLAG_EVENT_PLAYER | EFFECT_FLAG_BOTH_SIDE) && peffect->handler->is_has_relation(*clit)) { clit->triggering_player = peffect->handler->current.controler; clit->triggering_controler = peffect->handler->current.controler; clit->triggering_location = peffect->handler->current.location; clit->triggering_sequence = peffect->handler->current.sequence; } uint8 tp = clit->triggering_player; bool act = true; if(peffect->is_chainable(tp) && peffect->is_activateable(tp, clit->evt, TRUE) && (peffect->code == EVENT_FLIP && infos.phase == PHASE_DAMAGE || (clit->triggering_location & 0x43) || !(peffect->handler->current.location & 0x43) || peffect->handler->is_position(POS_FACEUP))) { if(peffect->is_flag(EFFECT_FLAG_CHAIN_UNIQUE)) { if(tp == infos.turn_player) { for(auto tpit = core.tpchain.begin(); tpit != core.tpchain.end(); ++tpit) { if(tpit->triggering_effect->handler->data.code == peffect->handler->data.code) { act = false; break; } } } else { for(auto ntpit = core.ntpchain.begin(); ntpit != core.ntpchain.end(); ++ntpit) { if(ntpit->triggering_effect->handler->data.code == peffect->handler->data.code) { act = false; break; } } } } } else act = false; if(act) { if(tp == infos.turn_player) core.tpchain.push_back(*clit); else core.ntpchain.push_back(*clit); peffect->handler->set_status(STATUS_CHAINING, TRUE); peffect->dec_count(tp); if(peffect->is_flag(EFFECT_FLAG_CVAL_CHECK)) peffect->get_value(); } } core.new_fchain_s.clear(); if(core.current_player == infos.turn_player) { if(core.tpchain.size() > 1) add_process(PROCESSOR_SORT_CHAIN, 0, 0, 0, 1, infos.turn_player); } else { if(core.ntpchain.size() > 1) add_process(PROCESSOR_SORT_CHAIN, 0, 0, 0, 0, infos.turn_player); } return FALSE; } case 3: { if(core.current_player == infos.turn_player) { core.new_chains.splice(core.new_chains.end(), core.tpchain); if(core.new_chains.size()) add_process(PROCESSOR_ADD_CHAIN, 0, 0, 0, 0, 0); core.current_player = 1 - infos.turn_player; core.units.begin()->step = 1; } else { core.new_chains.splice(core.new_chains.end(), core.ntpchain); if(core.new_chains.size()) add_process(PROCESSOR_ADD_CHAIN, 0, 0, 0, 0, 0); } return FALSE; } case 4: { //optional trigger if(core.new_ochain_s.size() == 0) { core.units.begin()->step = 6; return FALSE; } for (auto clit = core.new_ochain_s.begin(); clit != core.new_ochain_s.end(); ++clit) { effect* peffect = clit->triggering_effect; if((!peffect->is_flag(EFFECT_FLAG_EVENT_PLAYER | EFFECT_FLAG_BOTH_SIDE) && peffect->handler->is_has_relation(*clit)) || (!(peffect->is_flag(EFFECT_FLAG_FIELD_ONLY)) && (peffect->type & EFFECT_TYPE_FIELD) && (peffect->range & LOCATION_HAND) && peffect->handler->current.location == LOCATION_HAND)) { if(!peffect->handler->is_has_relation(*clit)) peffect->handler->create_relation(*clit); clit->triggering_player = peffect->handler->current.controler; clit->triggering_controler = peffect->handler->current.controler; clit->triggering_location = peffect->handler->current.location; clit->triggering_sequence = peffect->handler->current.sequence; } if(clit->triggering_player == infos.turn_player) core.tpchain.push_back(*clit); else core.ntpchain.push_back(*clit); } core.new_ochain_s.clear(); core.new_ochain_s.splice(core.new_ochain_s.end(), core.tpchain); core.new_ochain_s.splice(core.new_ochain_s.end(), core.ntpchain); core.new_ochain_h.clear(); core.tmp_chain.clear(); core.current_player = infos.turn_player; return FALSE; } case 5: { if(core.new_ochain_s.size() == 0) { if(core.current_player == infos.turn_player) { if(core.tpchain.size() > 1) add_process(PROCESSOR_SORT_CHAIN, 0, 0, 0, 1, infos.turn_player); core.new_ochain_s.splice(core.new_ochain_s.end(), core.tmp_chain); } else { if(core.ntpchain.size() > 1) add_process(PROCESSOR_SORT_CHAIN, 0, 0, 0, 0, infos.turn_player); } core.units.begin()->step = 6; return FALSE; } auto clit = core.new_ochain_s.begin(); effect* peffect = clit->triggering_effect; uint8 tp = clit->triggering_player; bool act = true; if(peffect->is_chainable(tp) && peffect->is_activateable(tp, clit->evt, TRUE) && (peffect->code == EVENT_FLIP && infos.phase == PHASE_DAMAGE || (clit->triggering_location & 0x43) || !(peffect->handler->current.location & 0x43) || peffect->handler->is_position(POS_FACEUP))) { if(!(peffect->is_flag(EFFECT_FLAG_FIELD_ONLY)) && clit->triggering_location == LOCATION_HAND && (((peffect->type & EFFECT_TYPE_SINGLE) && !(peffect->is_flag(EFFECT_FLAG_SINGLE_RANGE)) && peffect->handler->is_has_relation(*clit)) || (peffect->range & LOCATION_HAND))) { core.new_ochain_h.push_back(*clit); act = false; } else if((peffect->is_flag(EFFECT_FLAG_FIELD_ONLY)) || !(peffect->type & EFFECT_TYPE_FIELD) || peffect->in_range(clit->triggering_location, clit->triggering_sequence)) { if(peffect->is_flag(EFFECT_FLAG_CHAIN_UNIQUE)) { if(tp == infos.turn_player) { for(auto tpit = core.tpchain.begin(); tpit != core.tpchain.end(); ++tpit) { if(tpit->triggering_effect->handler->data.code == peffect->handler->data.code) { act = false; break; } } } else { for(auto ntpit = core.ntpchain.begin(); ntpit != core.ntpchain.end(); ++ntpit) { if(ntpit->triggering_effect->handler->data.code == peffect->handler->data.code) { act = false; break; } } } } } else act = false; } else act = false; if(act) { if(tp == core.current_player) add_process(PROCESSOR_SELECT_EFFECTYN, 0, 0, (group*)peffect->handler, tp, 0); else { core.tmp_chain.push_back(*clit); returns.ivalue[0] = FALSE; } } else returns.ivalue[0] = FALSE; return FALSE; } case 6: { if(!returns.ivalue[0]) { core.new_ochain_s.pop_front(); core.units.begin()->step = 4; return FALSE; } auto clit = core.new_ochain_s.begin(); effect* peffect = clit->triggering_effect; card* pcard = peffect->handler; uint8 tp = clit->triggering_player; core.select_effects.clear(); core.select_options.clear(); uintptr_t index = 0; core.select_effects.push_back((effect*)index); core.select_options.push_back(peffect->description); while(++clit != core.new_ochain_s.end()) { ++index; peffect = clit->triggering_effect; if(pcard != peffect->handler) continue; bool act = true; if(peffect->is_chainable(tp) && peffect->is_activateable(tp, clit->evt, TRUE) && (peffect->code == EVENT_FLIP && infos.phase == PHASE_DAMAGE || (clit->triggering_location & 0x43) || !(peffect->handler->current.location & 0x43) || peffect->handler->is_position(POS_FACEUP))) { if(!(peffect->is_flag(EFFECT_FLAG_FIELD_ONLY)) && clit->triggering_location == LOCATION_HAND && (((peffect->type & EFFECT_TYPE_SINGLE) && !(peffect->is_flag(EFFECT_FLAG_SINGLE_RANGE)) && peffect->handler->is_has_relation(*clit)) || (peffect->range & LOCATION_HAND))) { continue; } else if((peffect->is_flag(EFFECT_FLAG_FIELD_ONLY)) || !(peffect->type & EFFECT_TYPE_FIELD) || peffect->in_range(clit->triggering_location, clit->triggering_sequence)) { if(peffect->is_flag(EFFECT_FLAG_CHAIN_UNIQUE)) { if(tp == infos.turn_player) { for(auto tpit = core.tpchain.begin(); tpit != core.tpchain.end(); ++tpit) { if(tpit->triggering_effect->handler->data.code == peffect->handler->data.code) { act = false; break; } } } else { for(auto ntpit = core.ntpchain.begin(); ntpit != core.ntpchain.end(); ++ntpit) { if(ntpit->triggering_effect->handler->data.code == peffect->handler->data.code) { act = false; break; } } } } } else continue; } else continue; if(act) { core.select_effects.push_back((effect*)index); core.select_options.push_back(peffect->description); } } if(core.select_options.size() > 1) { add_process(PROCESSOR_SELECT_OPTION, 0, 0, 0, tp, 0); core.units.begin()->step = 19; return FALSE; } clit = core.new_ochain_s.begin(); peffect = clit->triggering_effect; peffect->handler->set_status(STATUS_CHAINING, TRUE); peffect->dec_count(tp); if(tp == infos.turn_player) core.tpchain.push_back(*clit); else core.ntpchain.push_back(*clit); if(peffect->is_flag(EFFECT_FLAG_CVAL_CHECK)) peffect->get_value(); core.new_ochain_s.pop_front(); core.units.begin()->step = 4; return FALSE; } case 7: { if(core.current_player == infos.turn_player) { core.new_chains.splice(core.new_chains.end(), core.tpchain); if(core.new_chains.size()) add_process(PROCESSOR_ADD_CHAIN, 0, 0, 0, 0, 0); core.current_player = 1 - infos.turn_player; core.units.begin()->step = 4; } else { core.new_chains.splice(core.new_chains.end(), core.ntpchain); if(core.new_chains.size()) add_process(PROCESSOR_ADD_CHAIN, 0, 0, 0, 0, 0); } return FALSE; } case 8: { if(!(core.duel_options & DUEL_OBSOLETE_RULING) || (infos.phase != PHASE_MAIN1 && infos.phase != PHASE_MAIN2)) return FALSE; // Obsolete ignition effect ruling tevent e; if(core.current_chain.size() == 0 && (check_event(EVENT_SUMMON_SUCCESS, &e) || check_event(EVENT_SPSUMMON_SUCCESS, &e) || check_event(EVENT_FLIP_SUMMON_SUCCESS, &e)) && e.reason_player == infos.turn_player) { chain newchain; tevent e; e.event_cards = 0; e.event_value = 0; e.event_player = PLAYER_NONE; e.reason_effect = 0; e.reason = 0; e.reason_player = PLAYER_NONE; for(auto eit = effects.ignition_effect.begin(); eit != effects.ignition_effect.end(); ++eit) { effect* peffect = eit->second; e.event_code = peffect->code; if(peffect->handler->current.location == LOCATION_MZONE && peffect->is_chainable(infos.turn_player) && peffect->is_activateable(infos.turn_player, e)) { newchain.flag = 0; newchain.chain_id = infos.field_id++; newchain.evt = e; newchain.triggering_controler = peffect->handler->current.controler; newchain.triggering_effect = peffect; newchain.triggering_location = peffect->handler->current.location; newchain.triggering_sequence = peffect->handler->current.sequence; newchain.triggering_player = infos.turn_player; core.select_chains.push_back(newchain); } } } return FALSE; } case 9: { infos.priorities[0] = 0; infos.priorities[1] = 0; if(core.current_chain.size() == 0) { if(!core.hand_adjusted) add_process(PROCESSOR_QUICK_EFFECT, 0, 0, 0, skip_freechain, infos.turn_player); } else add_process(PROCESSOR_QUICK_EFFECT, 0, 0, 0, skip_freechain, 1 - core.current_chain.back().triggering_player); return FALSE; } case 10: { core.new_ochain_h.clear(); if(core.chain_limit) { luaL_unref(pduel->lua->lua_state, LUA_REGISTRYINDEX, core.chain_limit); core.chain_limit = 0; } if(core.current_chain.size()) { for(auto cait = core.current_chain.begin(); cait != core.current_chain.end(); ++cait) cait->triggering_effect->handler->set_status(STATUS_CHAINING, FALSE); add_process(PROCESSOR_SOLVE_CHAIN, 0, 0, 0, skip_trigger | ((skip_freechain | skip_new) << 8), skip_new); } else { core.used_event.splice(core.used_event.end(), core.point_event); if(core.chain_limit_p) { luaL_unref(pduel->lua->lua_state, LUA_REGISTRYINDEX, core.chain_limit_p); core.chain_limit_p = 0; } reset_chain(); returns.ivalue[0] = FALSE; } return TRUE; } case 20: { uintptr_t index = (uintptr_t)core.select_effects[returns.ivalue[0]]; auto clit = core.new_ochain_s.begin(); std::advance(clit, index); effect* peffect = clit->triggering_effect; uint8 tp = clit->triggering_player; peffect->handler->set_status(STATUS_CHAINING, TRUE); peffect->dec_count(tp); if(tp == infos.turn_player) core.tpchain.push_back(*clit); else core.ntpchain.push_back(*clit); if(peffect->is_flag(EFFECT_FLAG_CVAL_CHECK)) peffect->get_value(); core.new_ochain_s.erase(clit); core.units.begin()->step = 4; return FALSE; } } return TRUE; } int32 field::process_quick_effect(int16 step, int32 skip_freechain, uint8 priority) { event_list::iterator evit; effect* peffect; switch(step) { case 0: { core.tpchain.clear(); core.ntpchain.clear(); if(!core.quick_f_chain.size()) return FALSE; bool act = true; for(auto ifit = core.quick_f_chain.begin(); ifit != core.quick_f_chain.end(); ++ifit) { peffect = ifit->first; if(peffect->is_chainable(ifit->second.triggering_player) && peffect->check_count_limit(ifit->second.triggering_player) && peffect->handler->is_has_relation(ifit->second)) { if(ifit->second.triggering_player == infos.turn_player) { act = true; if(peffect->is_flag(EFFECT_FLAG_CHAIN_UNIQUE)) { for (auto cait = core.tpchain.begin(); cait != core.tpchain.end(); ++cait) { if (cait->triggering_effect->handler->data.code == peffect->handler->data.code) { act = false; break; } } for (auto cait = core.current_chain.begin(); cait != core.current_chain.end(); ++cait) { if ((cait->triggering_effect->handler->data.code == peffect->handler->data.code) && (cait->triggering_player == infos.turn_player)) { act = false; break; } } } if(act) { core.tpchain.push_back(ifit->second); peffect->handler->set_status(STATUS_CHAINING, TRUE); peffect->dec_count(infos.turn_player); } } else { act = true; if(peffect->is_flag(EFFECT_FLAG_CHAIN_UNIQUE)) { for (auto cait = core.ntpchain.begin(); cait != core.ntpchain.end(); ++cait) { if (cait->triggering_effect->handler->data.code == peffect->handler->data.code) { act = false; break; } } for (auto cait = core.current_chain.begin(); cait != core.current_chain.end(); ++cait) { if ((cait->triggering_effect->handler->data.code == peffect->handler->data.code) && (cait->triggering_player != infos.turn_player)) { act = false; break; } } } if(act) { core.ntpchain.push_back(ifit->second); peffect->handler->set_status(STATUS_CHAINING, TRUE); peffect->dec_count(1 - infos.turn_player); } } } } core.quick_f_chain.clear(); if(core.tpchain.size() > 1) add_process(PROCESSOR_SORT_CHAIN, 0, 0, 0, 1, infos.turn_player); if(core.ntpchain.size() > 1) add_process(PROCESSOR_SORT_CHAIN, 0, 0, 0, 0, infos.turn_player); return FALSE; } case 1: { if(core.tpchain.size() == 0 && core.ntpchain.size() == 0) { chain newchain; evit = core.point_event.begin(); bool pev = true; if(evit == core.point_event.end()) { evit = core.instant_event.begin(); pev = false; } while(pev || (evit != core.instant_event.end())) { auto pr = effects.activate_effect.equal_range(evit->event_code); for(; pr.first != pr.second; ++pr.first) { peffect = pr.first->second; peffect->s_range = peffect->handler->current.location; peffect->o_range = peffect->handler->current.sequence; if(peffect->is_chainable(priority) && peffect->is_activateable(priority, *evit)) { newchain.flag = 0; newchain.chain_id = infos.field_id++; newchain.evt = *evit; newchain.triggering_controler = peffect->handler->current.controler; newchain.triggering_effect = peffect; newchain.triggering_location = peffect->handler->current.location; newchain.triggering_sequence = peffect->handler->current.sequence; newchain.triggering_player = priority; core.select_chains.push_back(newchain); core.delayed_quick_tmp.erase(std::make_pair(peffect, *evit)); core.delayed_quick_break.erase(std::make_pair(peffect, *evit)); } } pr = effects.quick_o_effect.equal_range(evit->event_code); for(; pr.first != pr.second; ++pr.first) { peffect = pr.first->second; peffect->s_range = peffect->handler->current.location; peffect->o_range = peffect->handler->current.sequence; if(peffect->is_chainable(priority) && peffect->is_activateable(priority, *evit)) { newchain.flag = 0; newchain.chain_id = infos.field_id++; newchain.evt = *evit; newchain.triggering_controler = peffect->handler->current.controler; newchain.triggering_effect = peffect; newchain.triggering_location = peffect->handler->current.location; newchain.triggering_sequence = peffect->handler->current.sequence; newchain.triggering_player = priority; core.select_chains.push_back(newchain); core.delayed_quick_tmp.erase(std::make_pair(peffect, *evit)); core.delayed_quick_break.erase(std::make_pair(peffect, *evit)); } } ++evit; if(pev && evit == core.point_event.end()) { evit = core.instant_event.begin(); pev = false; } } for(auto clit = core.new_ochain_h.begin(); clit != core.new_ochain_h.end(); ++clit) { peffect = clit->triggering_effect; bool act = true; if(clit->triggering_player == priority && !peffect->handler->is_status(STATUS_CHAINING) && peffect->handler->is_has_relation(*clit) && peffect->is_chainable(priority) && peffect->is_activateable(priority, clit->evt, TRUE)) { for(auto cait = core.current_chain.begin(); cait != core.current_chain.end(); ++cait) { if(cait->triggering_player == priority) { effect* pchaineff = cait->triggering_effect; if(!(pchaineff->is_flag(EFFECT_FLAG_FIELD_ONLY)) && (pchaineff->type & EFFECT_TYPE_TRIGGER_O) && (!(pchaineff->type & EFFECT_TYPE_SINGLE) || (pchaineff->is_flag(EFFECT_FLAG_SINGLE_RANGE))) && (pchaineff->range & LOCATION_HAND)) { act = false; break; } if((peffect->is_flag(EFFECT_FLAG_CHAIN_UNIQUE)) && (cait->triggering_effect->handler->data.code == peffect->handler->data.code)) { act = false; break; } } } } else act = false; if(act) core.select_chains.push_back(*clit); } if(core.global_flag & GLOBALFLAG_DELAYED_QUICKEFFECT) { for(auto eit = core.delayed_quick.begin(); eit != core.delayed_quick.end(); ++eit) { peffect = eit->first; peffect->s_range = peffect->handler->current.location; peffect->o_range = peffect->handler->current.sequence; const tevent& evt = eit->second; if(peffect->is_chainable(priority) && peffect->is_activateable(priority, evt, TRUE, FALSE, FALSE)) { newchain.flag = 0; newchain.chain_id = infos.field_id++; newchain.evt = evt; newchain.triggering_controler = peffect->handler->current.controler; newchain.triggering_effect = peffect; newchain.triggering_location = peffect->handler->current.location; newchain.triggering_sequence = peffect->handler->current.sequence; newchain.triggering_player = priority; core.select_chains.push_back(newchain); } } } core.spe_effect[priority] = core.select_chains.size(); if(!skip_freechain) { nil_event.event_code = EVENT_FREE_CHAIN; auto pr = effects.activate_effect.equal_range(EVENT_FREE_CHAIN); for(; pr.first != pr.second; ++pr.first) { peffect = pr.first->second; peffect->s_range = peffect->handler->current.location; peffect->o_range = peffect->handler->current.sequence; if(peffect->is_chainable(priority) && peffect->is_activateable(priority, nil_event)) { newchain.flag = 0; newchain.chain_id = infos.field_id++; newchain.evt = nil_event; newchain.triggering_controler = peffect->handler->current.controler; newchain.triggering_effect = peffect; newchain.triggering_location = peffect->handler->current.location; newchain.triggering_sequence = peffect->handler->current.sequence; newchain.triggering_player = priority; core.select_chains.push_back(newchain); if(check_hint_timing(peffect)) core.spe_effect[priority]++; } } pr = effects.quick_o_effect.equal_range(EVENT_FREE_CHAIN); for(; pr.first != pr.second; ++pr.first) { peffect = pr.first->second; peffect->s_range = peffect->handler->current.location; peffect->o_range = peffect->handler->current.sequence; if(peffect->is_chainable(priority) && peffect->is_activateable(priority, nil_event)) { newchain.flag = 0; newchain.chain_id = infos.field_id++; newchain.evt = nil_event; newchain.triggering_controler = peffect->handler->current.controler; newchain.triggering_effect = peffect; newchain.triggering_location = peffect->handler->current.location; newchain.triggering_sequence = peffect->handler->current.sequence; newchain.triggering_player = priority; core.select_chains.push_back(newchain); if(check_hint_timing(peffect)) core.spe_effect[priority]++; } } } if(core.current_chain.size() || (core.hint_timing[0] & TIMING_ATTACK) || (core.hint_timing[1] & TIMING_ATTACK)) core.spe_effect[priority] = core.select_chains.size(); if(!(core.duel_options & DUEL_NO_CHAIN_HINT) || core.select_chains.size()) add_process(PROCESSOR_SELECT_CHAIN, 0, 0, 0, priority, core.spe_effect[priority]); } else { core.new_chains.splice(core.new_chains.end(), core.tpchain); core.new_chains.splice(core.new_chains.end(), core.ntpchain); add_process(PROCESSOR_ADD_CHAIN, 0, 0, 0, 0, 0); add_process(PROCESSOR_QUICK_EFFECT, 0, 0, 0, FALSE, 1 - core.new_chains.back().triggering_player); infos.priorities[0] = 0; infos.priorities[1] = 0; return TRUE; } return FALSE; } case 2: { if(core.select_chains.size() && returns.ivalue[0] != -1) { chain newchain = core.select_chains[returns.ivalue[0]]; core.new_chains.push_back(newchain); effect* peffect = newchain.triggering_effect; core.delayed_quick.erase(std::make_pair(peffect, newchain.evt)); peffect->handler->set_status(STATUS_CHAINING, TRUE); peffect->dec_count(priority); add_process(PROCESSOR_ADD_CHAIN, 0, 0, 0, 0, 0); add_process(PROCESSOR_QUICK_EFFECT, 0, 0, 0, FALSE, 1 - priority); infos.priorities[0] = 0; infos.priorities[1] = 0; } else { infos.priorities[priority] = 1; if(!infos.priorities[0] || !infos.priorities[1]) add_process(PROCESSOR_QUICK_EFFECT, 1, 0, 0, skip_freechain, 1 - priority); else { core.hint_timing[0] &= TIMING_DAMAGE_STEP | TIMING_DAMAGE_CAL; core.hint_timing[1] &= TIMING_DAMAGE_STEP | TIMING_DAMAGE_CAL; core.delayed_quick.clear(); } } core.select_chains.clear(); return TRUE; } } return TRUE; } int32 field::process_instant_event() { if (core.queue_event.size() == 0) return TRUE; effect* peffect; chain newchain; effect_vector tp; effect_vector ntp; event_list tev; event_list ntev; effect_vector::iterator eit; event_list::iterator evit; for(auto elit = core.queue_event.begin(); elit != core.queue_event.end(); ++elit) { //continuous events auto pr = effects.continuous_effect.equal_range(elit->event_code); for(; pr.first != pr.second; ++pr.first) { peffect = pr.first->second; uint8 owner_player = peffect->get_handler_player(); if(peffect->is_activateable(owner_player, *elit)) { if((peffect->is_flag(EFFECT_FLAG_DELAY)) && (core.chain_solving || core.conti_solving)) { if(owner_player == infos.turn_player) { core.delayed_tp.push_back(peffect); core.delayed_tev.push_back(*elit); } else { core.delayed_ntp.push_back(peffect); core.delayed_ntev.push_back(*elit); } } else { if(owner_player == infos.turn_player) { tp.push_back(peffect); tev.push_back(*elit); } else { ntp.push_back(peffect); ntev.push_back(*elit); } } } } if(elit->event_code == EVENT_ADJUST || ((elit->event_code & 0xf000) == EVENT_PHASE_START)) continue; //triggers pr = effects.trigger_f_effect.equal_range(elit->event_code); for(; pr.first != pr.second; ++pr.first) { peffect = pr.first->second; if(!peffect->is_condition_check(peffect->handler->current.controler, *elit)) continue; peffect->s_range = peffect->handler->current.location; peffect->o_range = peffect->handler->current.sequence; newchain.flag = 0; newchain.chain_id = infos.field_id++; newchain.evt = *elit; newchain.triggering_effect = peffect; newchain.triggering_controler = peffect->handler->current.controler; newchain.triggering_location = peffect->handler->current.location; newchain.triggering_sequence = peffect->handler->current.sequence; if((peffect->is_flag(EFFECT_FLAG_EVENT_PLAYER)) && (elit->event_player == 0 || elit->event_player == 1)) newchain.triggering_player = elit->event_player; else newchain.triggering_player = peffect->handler->current.controler; core.new_fchain.push_back(newchain); peffect->handler->create_relation(newchain); } pr = effects.trigger_o_effect.equal_range(elit->event_code); for(; pr.first != pr.second; ++pr.first) { peffect = pr.first->second; if(!peffect->is_condition_check(peffect->handler->current.controler, *elit)) continue; peffect->s_range = peffect->handler->current.location; peffect->o_range = peffect->handler->current.sequence; newchain.flag = 0; newchain.chain_id = infos.field_id++; newchain.evt = *elit; newchain.triggering_effect = peffect; newchain.triggering_controler = peffect->handler->current.controler; newchain.triggering_location = peffect->handler->current.location; newchain.triggering_sequence = peffect->handler->current.sequence; if((peffect->is_flag(EFFECT_FLAG_EVENT_PLAYER)) && (elit->event_player == 0 || elit->event_player == 1)) newchain.triggering_player = elit->event_player; else newchain.triggering_player = peffect->handler->current.controler; core.new_ochain.push_back(newchain); if((peffect->is_flag(EFFECT_FLAG_FIELD_ONLY)) || ((peffect->type & EFFECT_TYPE_SINGLE) && !(peffect->is_flag(EFFECT_FLAG_SINGLE_RANGE))) || !(peffect->range & LOCATION_HAND) || (peffect->range & peffect->handler->current.location)) peffect->handler->create_relation(newchain); } //instant_f pr = effects.quick_f_effect.equal_range(elit->event_code); for(; pr.first != pr.second; ++pr.first) { peffect = pr.first->second; peffect->s_range = peffect->handler->current.location; peffect->o_range = peffect->handler->current.sequence; if(peffect->is_activateable(peffect->handler->current.controler, *elit)) { newchain.flag = 0; newchain.chain_id = infos.field_id++; newchain.evt = *elit; newchain.triggering_effect = peffect; newchain.triggering_controler = peffect->handler->current.controler; newchain.triggering_location = peffect->handler->current.location; newchain.triggering_sequence = peffect->handler->current.sequence; if((peffect->is_flag(EFFECT_FLAG_EVENT_PLAYER)) && (elit->event_player == 0 || elit->event_player == 1)) newchain.triggering_player = elit->event_player; else newchain.triggering_player = peffect->handler->current.controler; core.quick_f_chain[peffect] = newchain; peffect->handler->create_relation(newchain); } } if(!(core.global_flag & GLOBALFLAG_DELAYED_QUICKEFFECT)) continue; //delayed quick effect pr = effects.activate_effect.equal_range(elit->event_code); for(; pr.first != pr.second; ++pr.first) { peffect = pr.first->second; if((peffect->is_flag(EFFECT_FLAG_DELAY)) && peffect->is_condition_check(peffect->handler->current.controler, *elit)) core.delayed_quick_tmp.insert(std::make_pair(peffect, *elit)); } pr = effects.quick_o_effect.equal_range(elit->event_code); for(; pr.first != pr.second; ++pr.first) { peffect = pr.first->second; if((peffect->is_flag(EFFECT_FLAG_DELAY)) && peffect->is_condition_check(peffect->handler->current.controler, *elit)) core.delayed_quick_tmp.insert(std::make_pair(peffect, *elit)); } } for(eit = tp.begin(), evit = tev.begin(); eit != tp.end(); ++eit, ++evit) { core.sub_solving_event.push_back(*evit); add_process(PROCESSOR_SOLVE_CONTINUOUS, 0, (*eit), 0, (*eit)->get_handler_player(), 0); } for(eit = ntp.begin(), evit = ntev.begin(); eit != ntp.end(); ++eit, ++evit) { core.sub_solving_event.push_back(*evit); add_process(PROCESSOR_SOLVE_CONTINUOUS, 0, (*eit), 0, (*eit)->get_handler_player(), 0); } core.instant_event.splice(core.instant_event.end(), core.queue_event); return TRUE; } int32 field::process_single_event() { if(core.single_event.size() == 0) return TRUE; effect_vector tp; effect_vector ntp; event_list tev; event_list ntev; for(auto elit = core.single_event.begin(); elit != core.single_event.end(); ++elit) { card* starget = elit->trigger_card; uint32 ev = elit->event_code; auto pr = starget->single_effect.equal_range(ev); const tevent& e = *elit; for(; pr.first != pr.second; ++pr.first) { effect* peffect = pr.first->second; if(!(peffect->type & EFFECT_TYPE_ACTIONS)) continue; if((peffect->type & EFFECT_TYPE_FLIP) && (e.event_value & (NO_FLIP_EFFECT >> 16))) continue; //continuous & trigger (single) if(peffect->type & EFFECT_TYPE_CONTINUOUS) { uint8 owner_player = peffect->get_handler_player(); if(peffect->is_activateable(owner_player, e)) { if((peffect->is_flag(EFFECT_FLAG_DELAY)) && (core.chain_solving || core.conti_solving)) { if(owner_player == infos.turn_player) { core.delayed_tp.push_back(peffect); core.delayed_tev.push_back(e); } else { core.delayed_ntp.push_back(peffect); core.delayed_ntev.push_back(e); } } else { if(owner_player == infos.turn_player) { tp.push_back(peffect); tev.push_back(e); } else { ntp.push_back(peffect); ntev.push_back(e); } } } } else { if(!peffect->is_condition_check(peffect->handler->current.controler, e)) continue; peffect->s_range = peffect->handler->current.location; peffect->o_range = peffect->handler->current.sequence; chain newchain; newchain.flag = 0; newchain.chain_id = infos.field_id++; newchain.evt = e; newchain.triggering_effect = peffect; newchain.triggering_controler = peffect->handler->current.controler; newchain.triggering_location = peffect->handler->current.location; newchain.triggering_sequence = peffect->handler->current.sequence; if((peffect->is_flag(EFFECT_FLAG_EVENT_PLAYER)) && (elit->event_player == 0 || elit->event_player == 1)) newchain.triggering_player = elit->event_player; else { if(peffect->handler->current.reason & REASON_TEMPORARY) newchain.triggering_player = peffect->handler->previous.controler; else newchain.triggering_player = newchain.triggering_controler; } if(core.flip_delayed && ev == EVENT_FLIP) { if (peffect->type & EFFECT_TYPE_TRIGGER_O) core.new_ochain_b.push_back(newchain); else core.new_fchain_b.push_back(newchain); } else { if (peffect->type & EFFECT_TYPE_TRIGGER_O) core.new_ochain.push_back(newchain); else core.new_fchain.push_back(newchain); } peffect->handler->create_relation(newchain); } } } effect_vector::iterator eit; event_list::iterator evit; for(eit = tp.begin(), evit = tev.begin(); eit != tp.end(); ++eit, ++evit) { core.sub_solving_event.push_back(*evit); add_process(PROCESSOR_SOLVE_CONTINUOUS, 0, (*eit), 0, (*eit)->get_handler_player(), 0); } for(eit = ntp.begin(), evit = ntev.begin(); eit != ntp.end(); ++eit, ++evit) { core.sub_solving_event.push_back(*evit); add_process(PROCESSOR_SOLVE_CONTINUOUS, 0, (*eit), 0, (*eit)->get_handler_player(), 0); } core.single_event.clear(); return TRUE; } int32 field::process_idle_command(uint16 step) { switch(step) { case 0: { card* pcard; effect* peffect; core.select_chains.clear(); chain newchain; nil_event.event_code = EVENT_FREE_CHAIN; core.to_bp = TRUE; core.to_ep = TRUE; if((!(core.duel_options & DUEL_ATTACK_FIRST_TURN) && infos.turn_id == 1) || infos.phase == PHASE_MAIN2 || is_player_affected_by_effect(infos.turn_player, EFFECT_CANNOT_BP)) core.to_bp = FALSE; if(core.to_bp && infos.phase == PHASE_MAIN1 && is_player_affected_by_effect(infos.turn_player, EFFECT_CANNOT_EP)) core.to_ep = FALSE; if((infos.phase == PHASE_MAIN1 && is_player_affected_by_effect(infos.turn_player, EFFECT_SKIP_M1)) || (infos.phase == PHASE_MAIN2 && is_player_affected_by_effect(infos.turn_player, EFFECT_SKIP_M2))) { if(core.to_bp && core.to_ep) { core.select_options.clear(); core.select_options.push_back(80); core.select_options.push_back(81); add_process(PROCESSOR_SELECT_OPTION, 0, 0, 0, infos.turn_player, 0); core.units.begin()->step = 11; } else if(core.to_bp) { core.units.begin()->arg1 = 6; core.units.begin()->step = 10; reset_phase(infos.phase); adjust_all(); } else { core.units.begin()->arg1 = 7; core.units.begin()->step = 10; reset_phase(infos.phase); adjust_all(); } return FALSE; } if((infos.phase == PHASE_MAIN2) && core.skip_m2) { core.skip_m2 = FALSE; returns.ivalue[0] = 7; return FALSE; } auto pr = effects.activate_effect.equal_range(EVENT_FREE_CHAIN); for(; pr.first != pr.second; ++pr.first) { peffect = pr.first->second; peffect->s_range = peffect->handler->current.location; peffect->o_range = peffect->handler->current.sequence; newchain.triggering_effect = peffect; if(peffect->is_activateable(infos.turn_player, nil_event)) core.select_chains.push_back(newchain); } pr = effects.quick_o_effect.equal_range(EVENT_FREE_CHAIN); for(; pr.first != pr.second; ++pr.first) { peffect = pr.first->second; peffect->s_range = peffect->handler->current.location; peffect->o_range = peffect->handler->current.sequence; newchain.triggering_effect = peffect; if(peffect->is_activateable(infos.turn_player, nil_event)) core.select_chains.push_back(newchain); } for(auto eit = effects.ignition_effect.begin(); eit != effects.ignition_effect.end(); ++eit) { peffect = eit->second; peffect->s_range = peffect->handler->current.location; peffect->o_range = peffect->handler->current.sequence; newchain.triggering_effect = peffect; if(peffect->is_activateable(infos.turn_player, nil_event)) core.select_chains.push_back(newchain); } core.summonable_cards.clear(); for(auto clit = player[infos.turn_player].list_hand.begin(); clit != player[infos.turn_player].list_hand.end(); ++clit) if((*clit)->is_can_be_summoned(infos.turn_player, FALSE, 0, 0)) core.summonable_cards.push_back(*clit); for(int i = 0; i < 5; ++i) { if(player[infos.turn_player].list_mzone[i] && player[infos.turn_player].list_mzone[i]->is_can_be_summoned(infos.turn_player, FALSE, 0, 0)) core.summonable_cards.push_back(player[infos.turn_player].list_mzone[i]); } core.spsummonable_cards.clear(); effect_set eset; filter_field_effect(EFFECT_SPSUMMON_PROC, &eset); for(int32 i = 0; i < eset.size(); ++i) { pcard = eset[i]->handler; if(!eset[i]->check_count_limit(pcard->current.controler)) continue; if(pcard->current.controler == infos.turn_player && pcard->is_special_summonable(infos.turn_player, 0)) core.spsummonable_cards.push_back(pcard); } eset.clear(); filter_field_effect(EFFECT_SPSUMMON_PROC_G, &eset); for(int32 i = 0; i < eset.size(); ++i) { pcard = eset[i]->handler; if(!eset[i]->check_count_limit(infos.turn_player)) continue; if(pcard->current.controler != infos.turn_player && !(eset[i]->is_flag(EFFECT_FLAG_BOTH_SIDE))) continue; effect* oreason = core.reason_effect; uint8 op = core.reason_player; core.reason_effect = eset[i]; core.reason_player = pcard->current.controler; save_lp_cost(); pduel->lua->add_param(eset[i], PARAM_TYPE_EFFECT); pduel->lua->add_param(pcard, PARAM_TYPE_CARD); if(pduel->lua->check_condition(eset[i]->condition, 2)) core.spsummonable_cards.push_back(pcard); restore_lp_cost(); core.reason_effect = oreason; core.reason_player = op; } core.repositionable_cards.clear(); for(int i = 0; i < 5; ++i) { pcard = player[infos.turn_player].list_mzone[i]; if(pcard && ((pcard->is_position(POS_FACEUP | POS_FACEDOWN_ATTACK) && pcard->is_capable_change_position(infos.turn_player)) || (pcard->is_position(POS_FACEDOWN) && pcard->is_can_be_flip_summoned(infos.turn_player)))) core.repositionable_cards.push_back(player[infos.turn_player].list_mzone[i]); } core.msetable_cards.clear(); core.ssetable_cards.clear(); for(auto clit = player[infos.turn_player].list_hand.begin(); clit != player[infos.turn_player].list_hand.end(); ++clit) { if((*clit)->is_setable_mzone(infos.turn_player, FALSE, 0, 0)) core.msetable_cards.push_back(*clit); if((*clit)->is_setable_szone(infos.turn_player)) core.ssetable_cards.push_back(*clit); } add_process(PROCESSOR_SELECT_IDLECMD, 0, 0, 0, infos.turn_player, 0); return FALSE; } case 1: { uint32 ctype = returns.ivalue[0] & 0xffff; uint32 sel = returns.ivalue[0] >> 16; if(ctype == 5) { chain newchain = core.select_chains[sel]; effect* peffect = newchain.triggering_effect; newchain.flag = 0; newchain.chain_id = infos.field_id++; newchain.evt.event_code = peffect->code; newchain.evt.event_player = PLAYER_NONE; newchain.evt.event_value = 0; newchain.evt.event_cards = 0; newchain.evt.reason = 0; newchain.evt.reason_effect = 0; newchain.evt.reason_player = PLAYER_NONE; newchain.triggering_controler = peffect->handler->current.controler; newchain.triggering_location = peffect->handler->current.location; newchain.triggering_sequence = peffect->handler->current.sequence; newchain.triggering_player = infos.turn_player; core.new_chains.push_back(newchain); peffect->handler->set_status(STATUS_CHAINING, TRUE); peffect->dec_count(infos.turn_player); core.select_chains.clear(); add_process(PROCESSOR_ADD_CHAIN, 0, 0, 0, 0, 0); add_process(PROCESSOR_QUICK_EFFECT, 0, 0, 0, FALSE, 1 - infos.turn_player); infos.priorities[0] = 0; infos.priorities[1] = 0; core.select_chains.clear(); return FALSE; } else if(ctype == 0) { core.units.begin()->step = 4; return FALSE; } else if(ctype == 1) { core.units.begin()->step = 5; return FALSE; } else if(ctype == 2) { core.units.begin()->step = 6; return FALSE; } else if(ctype == 3) { core.units.begin()->step = 7; return FALSE; } else if(ctype == 4) { core.units.begin()->step = 8; return FALSE; } else if (ctype == 8) { core.units.begin()->step = -1; shuffle(infos.turn_player, LOCATION_HAND); infos.can_shuffle = FALSE; return FALSE; } else { core.units.begin()->step = 9; pduel->write_buffer8(MSG_HINT); pduel->write_buffer8(HINT_EVENT); pduel->write_buffer8(1 - infos.turn_player); pduel->write_buffer32(23); core.select_chains.clear(); core.hint_timing[infos.turn_player] = TIMING_MAIN_END; add_process(PROCESSOR_QUICK_EFFECT, 0, 0, 0, FALSE, 1 - infos.turn_player); infos.priorities[infos.turn_player] = 1; infos.priorities[1 - infos.turn_player] = 0; core.units.begin()->arg1 = ctype; return FALSE; } return TRUE; } case 2: { if(core.chain_limit) { luaL_unref(pduel->lua->lua_state, LUA_REGISTRYINDEX, core.chain_limit); core.chain_limit = 0; } chain_array::iterator cait; for(cait = core.current_chain.begin(); cait != core.current_chain.end(); ++cait) cait->triggering_effect->handler->set_status(STATUS_CHAINING, FALSE); add_process(PROCESSOR_SOLVE_CHAIN, 0, 0, 0, FALSE, 0); core.units.begin()->step = -1; return FALSE; } case 5: { card* target = core.summonable_cards[returns.ivalue[0] >> 16]; core.summon_cancelable = TRUE; summon(infos.turn_player, target, 0, FALSE, 0); core.units.begin()->step = -1; return FALSE; } case 6: { card* target = core.spsummonable_cards[returns.ivalue[0] >> 16]; core.summon_cancelable = TRUE; special_summon_rule(infos.turn_player, target, 0); core.units.begin()->step = -1; return FALSE; } case 7: { card* target = core.repositionable_cards[returns.ivalue[0] >> 16]; if(target->is_position(POS_FACEUP_ATTACK)) { core.phase_action = TRUE; change_position(target, 0, infos.turn_player, POS_FACEUP_DEFENCE, FALSE); adjust_all(); add_process(PROCESSOR_POINT_EVENT, 0, 0, 0, FALSE, 0); } else if(target->is_position(POS_FACEUP_DEFENCE)) { core.phase_action = TRUE; change_position(target, 0, infos.turn_player, POS_FACEUP_ATTACK, FALSE); adjust_all(); add_process(PROCESSOR_POINT_EVENT, 0, 0, 0, FALSE, 0); } else if(target->is_position(POS_FACEDOWN_ATTACK)) { core.units.begin()->ptarget = (group*)target; int32 positions = 0; if(target->is_capable_change_position(infos.turn_player)) positions |= POS_FACEDOWN_DEFENCE; if(target->is_can_be_flip_summoned(infos.turn_player)) positions |= POS_FACEUP_ATTACK; add_process(PROCESSOR_SELECT_POSITION, 0, 0, 0, infos.turn_player + (positions << 16), target->data.code); core.units.begin()->step = 12; return FALSE; } else add_process(PROCESSOR_FLIP_SUMMON, 0, 0, (group*)target, target->current.controler, 0); target->set_status(STATUS_FORM_CHANGED, TRUE); core.units.begin()->step = -1; return FALSE; } case 8: { card* target = core.msetable_cards[returns.ivalue[0] >> 16]; core.summon_cancelable = TRUE; add_process(PROCESSOR_MSET, 0, 0, (group*)target, target->current.controler, 0); core.units.begin()->step = -1; return FALSE; } case 9: { card* target = core.ssetable_cards[returns.ivalue[0] >> 16]; add_process(PROCESSOR_SSET, 0, 0, (group*)target, target->current.controler, target->current.controler); core.units.begin()->step = -1; return FALSE; } case 10: { //end announce if(core.chain_limit) { luaL_unref(pduel->lua->lua_state, LUA_REGISTRYINDEX, core.chain_limit); core.chain_limit = 0; } if(core.current_chain.size()) { for(auto cait = core.current_chain.begin(); cait != core.current_chain.end(); ++cait) cait->triggering_effect->handler->set_status(STATUS_CHAINING, FALSE); add_process(PROCESSOR_SOLVE_CHAIN, 0, 0, 0, FALSE, 0); core.units.begin()->step = -1; return FALSE; } reset_phase(infos.phase); adjust_all(); return FALSE; } case 11: { returns.ivalue[0] = core.units.begin()->arg1; infos.can_shuffle = TRUE; return TRUE; } case 12: { if(returns.ivalue[0] == 0) core.units.begin()->arg1 = 6; else core.units.begin()->arg1 = 7; reset_phase(infos.phase); adjust_all(); core.units.begin()->step = 10; return FALSE; } case 13: { card* target = (card*)core.units.begin()->ptarget; if(returns.ivalue[0] == POS_FACEUP_ATTACK) add_process(PROCESSOR_FLIP_SUMMON, 0, 0, (group*)target, target->current.controler, 0); else { core.phase_action = TRUE; change_position(target, 0, infos.turn_player, POS_FACEDOWN_DEFENCE, FALSE); adjust_all(); add_process(PROCESSOR_POINT_EVENT, 0, 0, 0, FALSE, 0); } target->set_status(STATUS_FORM_CHANGED, TRUE); core.units.begin()->step = -1; return FALSE; } } return TRUE; } int32 field::process_battle_command(uint16 step) { switch(step) { case 0: { effect* peffect = 0; card* pcard = 0; core.select_chains.clear(); chain newchain; nil_event.event_code = EVENT_FREE_CHAIN; if(!core.chain_attack) core.chain_attack_target = 0; core.attacker = 0; core.attack_target = 0; if((peffect = is_player_affected_by_effect(infos.turn_player, EFFECT_SKIP_BP))) { core.units.begin()->step = 41; if(core.phase_action || core.battle_phase_action) core.units.begin()->arg1 = 2; else core.units.begin()->arg1 = 3; if(is_player_affected_by_effect(infos.turn_player, EFFECT_BP_TWICE)) core.units.begin()->arg2 = 1; else core.units.begin()->arg2 = 0; if(!peffect->value){ infos.phase = PHASE_BATTLE; add_process(PROCESSOR_PHASE_EVENT, 0, 0, 0, PHASE_BATTLE, 0); } else { core.hint_timing[infos.turn_player] = 0; reset_phase(PHASE_BATTLE); adjust_all(); } return FALSE; } core.battle_phase_action = TRUE; auto pr = effects.activate_effect.equal_range(EVENT_FREE_CHAIN); for(; pr.first != pr.second; ++pr.first) { peffect = pr.first->second; peffect->s_range = peffect->handler->current.location; peffect->o_range = peffect->handler->current.sequence; newchain.triggering_effect = peffect; if(peffect->is_activateable(infos.turn_player, nil_event) && peffect->get_speed() > 1) core.select_chains.push_back(newchain); } pr = effects.quick_o_effect.equal_range(EVENT_FREE_CHAIN); for(; pr.first != pr.second; ++pr.first) { peffect = pr.first->second; peffect->s_range = peffect->handler->current.location; peffect->o_range = peffect->handler->current.sequence; newchain.triggering_effect = peffect; if(peffect->is_activateable(infos.turn_player, nil_event)) core.select_chains.push_back(newchain); } core.attackable_cards.clear(); card_vector first_attack; card_vector must_attack; if(!is_player_affected_by_effect(infos.turn_player, EFFECT_CANNOT_ATTACK_ANNOUNCE)) { for(uint32 i = 0; i < 5; ++i) { pcard = player[infos.turn_player].list_mzone[i]; if(!pcard) continue; if(!pcard->is_capable_attack_announce(infos.turn_player)) continue; core.select_cards.clear(); uint8 chain_attack = FALSE; if(core.chain_attack && core.pre_field[0] == pcard->fieldid_r) chain_attack = TRUE; get_attack_target(pcard, &core.select_cards, chain_attack); if(core.select_cards.size() == 0 && pcard->operation_param == 0) continue; core.attackable_cards.push_back(pcard); if(pcard->is_affected_by_effect(EFFECT_FIRST_ATTACK)) first_attack.push_back(pcard); if(pcard->is_affected_by_effect(EFFECT_MUST_ATTACK)) must_attack.push_back(pcard); } if(first_attack.size()) core.attackable_cards = first_attack; } core.to_m2 = TRUE; core.to_ep = TRUE; if(must_attack.size() || is_player_affected_by_effect(infos.turn_player, EFFECT_CANNOT_M2)) core.to_m2 = FALSE; if(must_attack.size()) core.to_ep = FALSE; core.attack_cancelable = TRUE; add_process(PROCESSOR_SELECT_BATTLECMD, 0, 0, 0, infos.turn_player, 0); return FALSE; } case 1: { int32 ctype = returns.ivalue[0] & 0xffff; int32 sel = returns.ivalue[0] >> 16; if(ctype == 0) { chain newchain = core.select_chains[sel]; effect* peffect = newchain.triggering_effect; newchain.flag = 0; newchain.chain_id = infos.field_id++; newchain.evt.event_code = peffect->code; newchain.evt.event_player = PLAYER_NONE; newchain.evt.event_value = 0; newchain.evt.event_cards = 0; newchain.evt.reason = 0; newchain.evt.reason_effect = 0; newchain.evt.reason_player = PLAYER_NONE; newchain.triggering_controler = peffect->handler->current.controler; newchain.triggering_location = peffect->handler->current.location; newchain.triggering_sequence = peffect->handler->current.sequence; newchain.triggering_player = infos.turn_player; core.new_chains.push_back(newchain); peffect->handler->set_status(STATUS_CHAINING, TRUE); peffect->dec_count(infos.turn_player); core.select_chains.clear(); add_process(PROCESSOR_ADD_CHAIN, 0, 0, 0, 0, 0); add_process(PROCESSOR_QUICK_EFFECT, 0, 0, 0, FALSE, 1 - infos.turn_player); infos.priorities[0] = 0; infos.priorities[1] = 0; core.select_chains.clear(); return FALSE; } else if(ctype == 1) { core.units.begin()->step = 2; card* attacker = core.attackable_cards[sel]; if(core.chain_attack && core.pre_field[0] != attacker->fieldid_r) { core.chain_attack = FALSE; core.chain_attack_target = 0; } core.attacker = attacker; core.attacker->set_status(STATUS_ATTACK_CANCELED, FALSE); core.pre_field[0] = core.attacker->fieldid_r; core.phase_action = TRUE; effect_set eset; filter_player_effect(infos.turn_player, EFFECT_ATTACK_COST, &eset, FALSE); core.attacker->filter_effect(EFFECT_ATTACK_COST, &eset); for(int32 i = 0; i < eset.size(); ++i) { if(eset[i]->operation) { core.attack_cancelable = FALSE; core.sub_solving_event.push_back(nil_event); add_process(PROCESSOR_EXECUTE_OPERATION, 0, eset[i], 0, infos.turn_player, 0); } } return FALSE; } else { core.units.begin()->step = 39; core.units.begin()->arg1 = ctype; pduel->write_buffer8(MSG_HINT); pduel->write_buffer8(HINT_EVENT); pduel->write_buffer8(1 - infos.turn_player); pduel->write_buffer32(29); core.select_chains.clear(); core.hint_timing[infos.turn_player] = TIMING_BATTLE_STEP_END; add_process(PROCESSOR_QUICK_EFFECT, 0, 0, 0, FALSE, 1 - infos.turn_player); infos.priorities[infos.turn_player] = 1; infos.priorities[1 - infos.turn_player] = 0; return FALSE; } return TRUE; } case 2: { if(core.chain_limit) { luaL_unref(pduel->lua->lua_state, LUA_REGISTRYINDEX, core.chain_limit); core.chain_limit = 0; } for(auto cait = core.current_chain.begin(); cait != core.current_chain.end(); ++cait) cait->triggering_effect->handler->set_status(STATUS_CHAINING, FALSE); add_process(PROCESSOR_SOLVE_CHAIN, 0, 0, 0, FALSE, 0); core.units.begin()->step = -1; return FALSE; } case 3: { //Filter Targers if(core.attacker->current.location != LOCATION_MZONE || core.attacker->fieldid_r != core.pre_field[0]) { core.units.begin()->step = -1; return FALSE; } core.select_cards.clear(); core.units.begin()->arg1 = FALSE; core.units.begin()->arg2 = get_attack_target(core.attacker, &core.select_cards, core.chain_attack); return FALSE; } case 4: { //confirm attack_target card_vector auto_be_attack; card* atarget; for(uint32 i = 0; i < 5; ++i) { atarget = player[1 - infos.turn_player].list_mzone[i]; if(atarget && atarget->is_affected_by_effect(EFFECT_AUTO_BE_ATTACKED)) auto_be_attack.push_back(atarget); } if(auto_be_attack.size()) { core.select_cards = auto_be_attack; if(core.select_cards.size() == 1) returns.bvalue[1] = 0; else add_process(PROCESSOR_SELECT_CARD, 0, 0, 0, 1 - infos.turn_player + (core.attack_cancelable ? 0x20000 : 0), 0x10001); core.units.begin()->step = 5; return FALSE; } if(core.attacker->operation_param) { if(core.select_cards.size() == 0) { returns.ivalue[0] = -2; core.units.begin()->step = 5; return FALSE; } for(int32 i = 0; i < 5; ++i) { if(player[1 - infos.turn_player].list_mzone[i]) { add_process(PROCESSOR_SELECT_YESNO, 0, 0, 0, infos.turn_player, 31); return FALSE; } } returns.ivalue[0] = -2; core.units.begin()->step = 5; return FALSE; } if(core.units.begin()->arg2) { if(core.select_cards.size() == 1) returns.bvalue[1] = 0; else add_process(PROCESSOR_SELECT_CARD, 0, 0, 0, 1 - infos.turn_player + (core.attack_cancelable ? 0x20000 : 0), 0x10001); core.units.begin()->step = 5; return FALSE; } if(core.select_cards.size() == 0) { if(!core.attack_cancelable) { core.attacker->announce_count++; core.attacker->announced_cards.addcard(0); } core.units.begin()->step = -1; return FALSE; } add_process(PROCESSOR_SELECT_CARD, 0, 0, 0, infos.turn_player + (core.attack_cancelable ? 0x20000 : 0), 0x10001); core.units.begin()->step = 5; return FALSE; } case 5: { if(returns.ivalue[0]) { returns.ivalue[0] = -2; return FALSE; } else { if(core.select_cards.size()) add_process(PROCESSOR_SELECT_CARD, 0, 0, 0, infos.turn_player + (core.attack_cancelable ? 0x20000 : 0), 0x10001); else core.units.begin()->step = -1; } return FALSE; } case 6: { if(returns.ivalue[0] == -1) { //rollback if(core.units.begin()->arg1) { core.attacker->announce_count++; core.attacker->announced_cards.addcard(core.attack_target); } core.units.begin()->step = -1; return FALSE; } if(returns.ivalue[0] == -2) core.attack_target = 0; else core.attack_target = core.select_cards[returns.bvalue[1]]; if(core.attack_target) core.pre_field[1] = core.attack_target->fieldid_r; else core.pre_field[1] = 0; return FALSE; } case 7: { core.attack_cancelable = TRUE; core.sub_attacker = 0; core.sub_attack_target = (card*)0xffffffff; core.attack_state_count[infos.turn_player]++; check_card_counter(core.attacker, 5, infos.turn_player); pduel->write_buffer8(MSG_ATTACK); pduel->write_buffer32(core.attacker->get_info_location()); if(core.attack_target) { raise_single_event(core.attack_target, 0, EVENT_BE_BATTLE_TARGET, 0, 0, 0, 1 - infos.turn_player, 0); raise_event(core.attack_target, EVENT_BE_BATTLE_TARGET, 0, 0, 0, 1 - infos.turn_player, 0); pduel->write_buffer32(core.attack_target->get_info_location()); } else pduel->write_buffer32(0); if(core.attacker->current.location != LOCATION_MZONE) { core.units.begin()->step = -1; return FALSE; } core.attack_rollback = FALSE; for(uint32 i = 0; i < 5; ++i) { if(player[1 - infos.turn_player].list_mzone[i]) core.opp_mzone[i] = player[1 - infos.turn_player].list_mzone[i]->fieldid_r; else core.opp_mzone[i] = 0; } //core.units.begin()->arg1 ---> is rollbacked if(!core.units.begin()->arg1) { raise_single_event(core.attacker, 0, EVENT_ATTACK_ANNOUNCE, 0, 0, 0, infos.turn_player, 0); raise_event(core.attacker, EVENT_ATTACK_ANNOUNCE, 0, 0, 0, infos.turn_player, 0); } core.units.begin()->arg2 = (core.attacker->current.controler << 16) + core.attacker->fieldid_r; process_single_event(); process_instant_event(); core.hint_timing[infos.turn_player] = TIMING_ATTACK; add_process(PROCESSOR_POINT_EVENT, 0, 0, 0, 0, 0); return FALSE; } case 8: { if(is_player_affected_by_effect(infos.turn_player, EFFECT_SKIP_BP) || core.attack_rollback) { core.units.begin()->step = 9; return FALSE; } pduel->write_buffer8(MSG_HINT); pduel->write_buffer8(HINT_EVENT); pduel->write_buffer8(0); pduel->write_buffer32(24); pduel->write_buffer8(MSG_HINT); pduel->write_buffer8(HINT_EVENT); pduel->write_buffer8(1); pduel->write_buffer32(24); core.hint_timing[0] = TIMING_BATTLE_PHASE; core.hint_timing[1] = TIMING_BATTLE_PHASE; add_process(PROCESSOR_POINT_EVENT, 0, 0, 0, 0, 0); return FALSE; } case 9: { if(returns.ivalue[0]) core.units.begin()->step = 7; else adjust_all(); return FALSE; } case 10: { uint8 rollback = core.attack_rollback; bool atk_disabled = false; uint32 acon = core.units.begin()->arg2 >> 16; uint32 afid = core.units.begin()->arg2 & 0xffff; if(core.attacker->is_affected_by_effect(EFFECT_ATTACK_DISABLED)) { core.attacker->reset(EFFECT_ATTACK_DISABLED, RESET_CODE); atk_disabled = true; pduel->write_buffer8(MSG_ATTACK_DISABLED); core.attacker->set_status(STATUS_ATTACK_CANCELED, TRUE); } effect* peffect; if((peffect = is_player_affected_by_effect(infos.turn_player, EFFECT_SKIP_BP))) { core.units.begin()->step = 41; core.units.begin()->arg1 = 2; if(is_player_affected_by_effect(infos.turn_player, EFFECT_BP_TWICE)) core.units.begin()->arg2 = 1; else core.units.begin()->arg2 = 0; reset_phase(PHASE_DAMAGE); if(core.attacker->fieldid_r == afid) { if(!atk_disabled) { core.attacker->attacked_cards.addcard(core.attack_target); } core.attacker->announce_count++; attack_all_target_check(); } if(!peffect->value) { infos.phase = PHASE_BATTLE; add_process(PROCESSOR_PHASE_EVENT, 0, 0, 0, PHASE_BATTLE, 0); } else { core.hint_timing[infos.turn_player] = 0; reset_phase(PHASE_BATTLE); adjust_all(); } return FALSE; } if(atk_disabled || !core.attacker->is_capable_attack() || core.attacker->is_status(STATUS_ATTACK_CANCELED) || core.attacker->current.controler != acon || core.attacker->fieldid_r != afid) { core.chain_attack = FALSE; if(core.attacker->fieldid_r == afid) { core.attacker->announce_count++; core.attacker->announced_cards.addcard(core.attack_target); attack_all_target_check(); if(!core.attacker->is_status(STATUS_ATTACK_CANCELED)) { core.attacker->attacked_cards.addcard(core.attack_target); } } core.units.begin()->step = -1; reset_phase(PHASE_DAMAGE); adjust_all(); return FALSE; } if((core.sub_attacker && core.sub_attacker->is_position(POS_FACEUP) && core.sub_attacker->current.location == LOCATION_MZONE) || ((core.sub_attack_target != (card*)0xffffffff) && (!core.sub_attack_target || core.sub_attack_target->current.location == LOCATION_MZONE))) { if(core.sub_attacker) core.attacker = core.sub_attacker; if(core.sub_attack_target != (card*)0xffffffff) { core.attack_target = core.sub_attack_target; if(core.attack_target) { raise_single_event(core.attack_target, 0, EVENT_BE_BATTLE_TARGET, 0, REASON_REPLACE, 0, 1 - infos.turn_player, 0); raise_event(core.attack_target, EVENT_BE_BATTLE_TARGET, 0, REASON_REPLACE, 0, 1 - infos.turn_player, 0); process_single_event(); process_instant_event(); add_process(PROCESSOR_POINT_EVENT, 0, 0, 0, 0, 0); } } core.sub_attacker = 0; core.sub_attack_target = (card*)0xffffffff; core.attacker->announce_count++; core.attacker->announced_cards.addcard(core.attack_target); attack_all_target_check(); core.attacker->attacked_cards.addcard(core.attack_target); pduel->write_buffer8(MSG_ATTACK); pduel->write_buffer32(core.attacker->get_info_location()); if(core.attack_target) { pduel->write_buffer32(core.attack_target->get_info_location()); } else { pduel->write_buffer32(0); } core.units.begin()->step = 19; return FALSE; } core.select_cards.clear(); core.units.begin()->arg2 = get_attack_target(core.attacker, &core.select_cards, core.chain_attack); for(uint32 i = 0; i < 5; ++i) { if(player[1 - infos.turn_player].list_mzone[i]) { if(!core.opp_mzone[i] || core.opp_mzone[i] != player[1 - infos.turn_player].list_mzone[i]->fieldid_r) { rollback = true; break; } } else { if(core.opp_mzone[i]) { rollback = true; break; } } } if(!core.attack_target && !core.attacker->operation_param) rollback = true; if(!rollback) { core.attacker->announce_count++; core.attacker->announced_cards.addcard(core.attack_target); attack_all_target_check(); core.attacker->attacked_cards.addcard(core.attack_target); core.units.begin()->step = 19; adjust_instant(); adjust_all(); return FALSE; } if(!core.select_cards.size() && !core.attacker->operation_param) { core.attacker->announce_count++; attack_all_target_check(); core.units.begin()->step = -1; reset_phase(PHASE_DAMAGE); adjust_instant(); adjust_all(); return FALSE; } if(!core.attacker->is_affected_by_effect(EFFECT_MUST_ATTACK)) add_process(PROCESSOR_SELECT_YESNO, 0, 0, 0, infos.turn_player, 30); else { returns.ivalue[0] = TRUE; core.attack_cancelable = FALSE; } return FALSE; } case 11: { if(returns.ivalue[0]) { core.units.begin()->arg1 = TRUE; core.units.begin()->step = 3; return FALSE; } core.attacker->announce_count++; core.attacker->announced_cards.addcard(core.attack_target); attack_all_target_check(); core.units.begin()->step = -1; reset_phase(PHASE_DAMAGE); adjust_instant(); adjust_all(); return FALSE; } case 20: { infos.phase = PHASE_DAMAGE; core.chain_attack = FALSE; pduel->write_buffer8(MSG_DAMAGE_STEP_START); core.units.begin()->arg1 = FALSE; core.damage_calculated = FALSE; core.selfdes_disabled = TRUE; core.flip_delayed = TRUE; if(core.sub_attacker) core.attacker = core.sub_attacker; if(core.sub_attack_target != (card*)0xffffffff) core.attack_target = core.sub_attack_target; core.pre_field[0] = core.attacker->fieldid_r; if(core.attack_target) core.pre_field[1] = core.attack_target->fieldid_r; else core.pre_field[1] = 0; core.attacker->attacked_count++; raise_single_event(core.attacker, 0, EVENT_BATTLE_START, 0, 0, 0, 0, 0); if(core.attack_target) raise_single_event(core.attack_target, 0, EVENT_BATTLE_START, 0, 0, 0, 0, 1); raise_event((card*)0, EVENT_BATTLE_START, 0, 0, 0, 0, 0); process_single_event(); process_instant_event(); pduel->write_buffer8(MSG_HINT); pduel->write_buffer8(HINT_EVENT); pduel->write_buffer8(0); pduel->write_buffer32(40); pduel->write_buffer8(MSG_HINT); pduel->write_buffer8(HINT_EVENT); pduel->write_buffer8(1); pduel->write_buffer32(40); add_process(PROCESSOR_POINT_EVENT, 0, 0, 0, 0, TRUE); core.temp_var[2] = 0; return FALSE; } case 21: { if(core.attacker->current.location != LOCATION_MZONE || core.attacker->fieldid_r != core.pre_field[0] || (core.attack_target && (core.attack_target->current.location != LOCATION_MZONE || core.attack_target->fieldid_r != core.pre_field[1]))) { core.units.begin()->step = 37; return FALSE; } if(!core.attack_target) { return FALSE; } core.sub_attacker = 0; core.sub_attack_target = (card*)0xffffffff; core.attacker->temp.position = core.attacker->current.position; core.attack_target->temp.position = core.attack_target->current.position; if(core.attack_target->is_position(POS_FACEDOWN)) { change_position(core.attack_target, 0, PLAYER_NONE, core.attack_target->current.position >> 1, 0, TRUE); adjust_all(); } return FALSE; } case 22: { int32 r = core.temp_var[2] == 0 ? 0 : REASON_REPLACE; raise_single_event(core.attacker, 0, EVENT_BATTLE_CONFIRM, 0, r, 0, 0, 0); if(core.attack_target) { if(core.attack_target->temp.position & POS_FACEDOWN) core.pre_field[1] = core.attack_target->fieldid_r; raise_single_event(core.attack_target, 0, EVENT_BATTLE_CONFIRM, 0, r, 0, 0, 1); } raise_event((card*)0, EVENT_BATTLE_CONFIRM, 0, 0, 0, 0, 0); process_single_event(); process_instant_event(); pduel->write_buffer8(MSG_HINT); pduel->write_buffer8(HINT_EVENT); pduel->write_buffer8(0); pduel->write_buffer32(41); pduel->write_buffer8(MSG_HINT); pduel->write_buffer8(HINT_EVENT); pduel->write_buffer8(1); pduel->write_buffer32(41); core.hint_timing[infos.turn_player] = TIMING_DAMAGE_STEP; add_process(PROCESSOR_POINT_EVENT, 0, 0, 0, 0, 0); return FALSE; } case 23: { if((core.sub_attack_target != (card*)0xffffffff) || core.sub_attacker) { if(core.sub_attacker) core.attacker = core.sub_attacker; if(core.sub_attack_target != (card*)0xffffffff) core.attack_target = core.sub_attack_target; core.units.begin()->step = 20; core.pre_field[0] = core.attacker->fieldid_r; if(core.attack_target) core.pre_field[1] = core.attack_target->fieldid_r; else core.pre_field[1] = 0; core.temp_var[2] = 1; return FALSE; } if(core.attacker->current.location != LOCATION_MZONE || core.attacker->fieldid_r != core.pre_field[0] || ((core.attacker->current.position & POS_DEFENCE) && !(core.attacker->is_affected_by_effect(EFFECT_DEFENCE_ATTACK))) || (core.attack_target && (core.attack_target->current.location != LOCATION_MZONE || core.attack_target->fieldid_r != core.pre_field[1]))) { core.units.begin()->step = 37; return FALSE; } return FALSE; } case 24: { infos.phase = PHASE_DAMAGE_CAL; calculate_battle_damage(0, 0, 0); raise_single_event(core.attacker, 0, EVENT_PRE_DAMAGE_CALCULATE, 0, 0, 0, 0, 0); if(core.attack_target) raise_single_event(core.attack_target, 0, EVENT_PRE_DAMAGE_CALCULATE, 0, 0, 0, 0, 1); raise_event((card*)0, EVENT_PRE_DAMAGE_CALCULATE, 0, 0, 0, 0, 0); process_single_event(); process_instant_event(); pduel->write_buffer8(MSG_HINT); pduel->write_buffer8(HINT_EVENT); pduel->write_buffer8(0); pduel->write_buffer32(42); pduel->write_buffer8(MSG_HINT); pduel->write_buffer8(HINT_EVENT); pduel->write_buffer8(1); pduel->write_buffer32(42); core.hint_timing[infos.turn_player] = TIMING_DAMAGE_CAL; add_process(PROCESSOR_POINT_EVENT, 0, 0, 0, 0, TRUE); return FALSE; } case 25: { if(core.attacker->current.location != LOCATION_MZONE || core.attacker->fieldid_r != core.pre_field[0] || (core.attack_target && (core.attack_target->current.location != LOCATION_MZONE || core.attack_target->fieldid_r != core.pre_field[1]))) { core.units.begin()->step = 37; return FALSE; } raise_single_event(core.attacker, 0, EVENT_DAMAGE_CALCULATING, 0, 0, 0, 0, 0); if(core.attack_target) raise_single_event(core.attack_target, 0, EVENT_DAMAGE_CALCULATING, 0, 0, 0, 0, 1); raise_event((card*)0, EVENT_DAMAGE_CALCULATING, 0, 0, 0, 0, 0); process_single_event(); process_instant_event(); //this timing does not exist in Master Rule 3 core.new_ochain.clear(); core.new_fchain.clear(); return FALSE; } case 26: { uint32 aa = core.attacker->get_attack(), ad = core.attacker->get_defence(); uint32 da = 0, dd = 0; uint8 pa = core.attacker->current.controler, pd; core.attacker->q_cache.attack = aa; core.attacker->q_cache.defence = ad; core.attacker->set_status(STATUS_BATTLE_DESTROYED, FALSE); if(core.attack_target) { da = core.attack_target->get_attack(); dd = core.attack_target->get_defence(); core.attack_target->q_cache.attack = da; core.attack_target->q_cache.defence = dd; core.attack_target->set_status(STATUS_BATTLE_DESTROYED, FALSE); pd = core.attack_target->current.controler; if(pa != pd) { core.attacker->set_status(STATUS_OPPO_BATTLE, TRUE); core.attack_target->set_status(STATUS_OPPO_BATTLE, TRUE); } } effect* damchange = 0; card* reason_card = 0; uint8 bd[2]; calculate_battle_damage(&damchange, &reason_card, bd); if(bd[0]) { effect* indestructable_effect = core.attacker->is_affected_by_effect(EFFECT_INDESTRUCTABLE_BATTLE, core.attack_target); if(indestructable_effect) { pduel->write_buffer8(MSG_HINT); pduel->write_buffer8(HINT_CARD); pduel->write_buffer8(0); pduel->write_buffer32(indestructable_effect->owner->data.code); bd[0] = FALSE; } else core.attacker->set_status(STATUS_BATTLE_DESTROYED, TRUE); } if(bd[1]) { effect* indestructable_effect = core.attack_target->is_affected_by_effect(EFFECT_INDESTRUCTABLE_BATTLE, core.attacker); if(indestructable_effect) { pduel->write_buffer8(MSG_HINT); pduel->write_buffer8(HINT_CARD); pduel->write_buffer8(0); pduel->write_buffer32(indestructable_effect->owner->data.code); bd[1] = FALSE; } else core.attack_target->set_status(STATUS_BATTLE_DESTROYED, TRUE); } pduel->write_buffer8(MSG_BATTLE); pduel->write_buffer32(core.attacker->get_info_location()); pduel->write_buffer32(aa); pduel->write_buffer32(ad); pduel->write_buffer8(bd[0]); if(core.attack_target) { pduel->write_buffer32(core.attack_target->get_info_location()); pduel->write_buffer32(da); pduel->write_buffer32(dd); pduel->write_buffer8(bd[1]); } else { pduel->write_buffer32(0); pduel->write_buffer32(0); pduel->write_buffer32(0); pduel->write_buffer8(0); } core.units.begin()->peffect = damchange; if(reason_card) core.temp_var[0] = reason_card->current.controler; if(!reason_card) core.temp_var[1] = 0; else if(reason_card == core.attacker) core.temp_var[1] = 1; else core.temp_var[1] = 2; if(!damchange) { if(core.battle_damage[infos.turn_player]) { raise_single_event(core.attacker, 0, EVENT_PRE_BATTLE_DAMAGE, 0, 0, reason_card->current.controler, infos.turn_player, core.battle_damage[infos.turn_player]); if(core.attack_target) raise_single_event(core.attack_target, 0, EVENT_PRE_BATTLE_DAMAGE, 0, 0, reason_card->current.controler, infos.turn_player, core.battle_damage[infos.turn_player]); raise_event(reason_card, EVENT_PRE_BATTLE_DAMAGE, 0, 0, reason_card->current.controler, infos.turn_player, core.battle_damage[infos.turn_player]); } if(core.battle_damage[1 - infos.turn_player]) { raise_single_event(core.attacker, 0, EVENT_PRE_BATTLE_DAMAGE, 0, 0, reason_card->current.controler, 1 - infos.turn_player, core.battle_damage[1 - infos.turn_player]); if(core.attack_target) raise_single_event(core.attack_target, 0, EVENT_PRE_BATTLE_DAMAGE, 0, 0, reason_card->current.controler, 1 - infos.turn_player, core.battle_damage[1 - infos.turn_player]); raise_event(reason_card, EVENT_PRE_BATTLE_DAMAGE, 0, 0, reason_card->current.controler, 1 - infos.turn_player, core.battle_damage[1 - infos.turn_player]); } } process_single_event(); process_instant_event(); //this timing does not exist in Master Rule 3 core.damage_calculated = TRUE; if(core.effect_damage_step) return TRUE; return FALSE; } case 27: { infos.phase = PHASE_DAMAGE; core.hint_timing[infos.turn_player] = 0; core.chain_attack = FALSE; core.attacker->battled_cards.addcard(core.attack_target); if(core.attack_target) core.attack_target->battled_cards.addcard(core.attacker); uint8 reason_player = core.temp_var[0]; card* reason_card = 0; if(core.temp_var[1] == 1) reason_card = core.attacker; else if(core.temp_var[1] == 2) reason_card = core.attack_target; effect* damchange = core.units.begin()->peffect; if(!damchange) { if(core.battle_damage[0]) damage(0, REASON_BATTLE, reason_player, reason_card, 0, core.battle_damage[0]); if(core.battle_damage[1]) damage(0, REASON_BATTLE, reason_player, reason_card, 1, core.battle_damage[1]); } else { if(core.battle_damage[0]) damage(damchange, REASON_EFFECT, reason_player, reason_card, 0, core.battle_damage[0]); if(core.battle_damage[1]) damage(damchange, REASON_EFFECT, reason_player, reason_card, 1, core.battle_damage[1]); } reset_phase(PHASE_DAMAGE_CAL); adjust_all(); return FALSE; } case 28: { card_set des; effect* peffect; uint32 dest, seq; if(core.attacker->is_status(STATUS_BATTLE_DESTROYED) && core.attacker->current.location == LOCATION_MZONE && core.attacker->fieldid_r == core.pre_field[0]) { des.insert(core.attacker); core.attacker->temp.reason = core.attacker->current.reason; core.attacker->temp.reason_card = core.attacker->current.reason_card; core.attacker->temp.reason_effect = core.attacker->current.reason_effect; core.attacker->temp.reason_player = core.attacker->current.reason_player; core.attacker->current.reason_effect = 0; core.attacker->current.reason = REASON_BATTLE; core.attacker->current.reason_card = core.attack_target; core.attacker->current.reason_player = core.attack_target->current.controler; dest = LOCATION_GRAVE; seq = 0; if((peffect = core.attack_target->is_affected_by_effect(EFFECT_BATTLE_DESTROY_REDIRECT)) && (core.attacker->data.type & TYPE_MONSTER)) { dest = peffect->get_value(core.attacker); seq = dest >> 16; dest &= 0xffff; } core.attacker->operation_param = (POS_FACEUP << 24) + (((uint32)core.attacker->owner) << 16) + (dest << 8) + seq; } if(core.attack_target && core.attack_target->is_status(STATUS_BATTLE_DESTROYED) && core.attack_target->current.location == LOCATION_MZONE && core.attack_target->fieldid_r == core.pre_field[1]) { des.insert(core.attack_target); core.attack_target->temp.reason = core.attack_target->current.reason; core.attack_target->temp.reason_card = core.attack_target->current.reason_card; core.attack_target->temp.reason_effect = core.attack_target->current.reason_effect; core.attack_target->temp.reason_player = core.attack_target->current.reason_player; core.attack_target->current.reason_effect = 0; core.attack_target->current.reason = REASON_BATTLE; core.attack_target->current.reason_card = core.attacker; core.attack_target->current.reason_player = core.attacker->current.controler; dest = LOCATION_GRAVE; seq = 0; if((peffect = core.attacker->is_affected_by_effect(EFFECT_BATTLE_DESTROY_REDIRECT)) && (core.attack_target->data.type & TYPE_MONSTER)) { dest = peffect->get_value(core.attack_target); seq = dest >> 16; dest &= 0xffff; } core.attack_target->operation_param = (POS_FACEUP << 24) + (((uint32)core.attack_target->owner) << 16) + (dest << 8) + seq; } core.attacker->set_status(STATUS_BATTLE_DESTROYED, FALSE); if(core.attack_target) core.attack_target->set_status(STATUS_BATTLE_DESTROYED, FALSE); core.battle_destroy_rep.clear(); core.desrep_chain.clear(); if(des.size()) { group* ng = pduel->new_group(); ng->container.swap(des); ng->is_readonly = TRUE; add_process(PROCESSOR_DESTROY, 10, 0, ng, REASON_BATTLE, PLAYER_NONE); core.units.begin()->ptarget = ng; } return FALSE; } case 29: { core.selfdes_disabled = FALSE; group* des = core.units.begin()->ptarget; if(des && des->container.size()) { for(auto cit = des->container.begin(); cit != des->container.end(); ++cit) { (*cit)->set_status(STATUS_BATTLE_DESTROYED, TRUE); (*cit)->filter_disable_related_cards(); } } adjust_all(); return FALSE; } case 30: { //EVENT_BATTLE_END was here, but this timing does not exist in Master Rule 3 core.units.begin()->arg1 = 1; return FALSE; } case 31: { core.flip_delayed = FALSE; core.new_fchain.splice(core.new_fchain.begin(), core.new_fchain_b); core.new_ochain.splice(core.new_ochain.begin(), core.new_ochain_b); raise_single_event(core.attacker, 0, EVENT_BATTLED, 0, 0, PLAYER_NONE, 0, 0); if(core.attack_target) raise_single_event(core.attack_target, 0, EVENT_BATTLED, 0, 0, PLAYER_NONE, 0, 1); raise_event((card*)0, EVENT_BATTLED, 0, 0, PLAYER_NONE, 0, 0); process_single_event(); process_instant_event(); pduel->write_buffer8(MSG_HINT); pduel->write_buffer8(HINT_EVENT); pduel->write_buffer8(0); pduel->write_buffer32(43); pduel->write_buffer8(MSG_HINT); pduel->write_buffer8(HINT_EVENT); pduel->write_buffer8(1); pduel->write_buffer32(43); add_process(PROCESSOR_POINT_EVENT, 0, 0, 0, 0, TRUE); return FALSE; } case 32: { group* des = core.units.begin()->ptarget; if(core.battle_destroy_rep.size()) destroy(&core.battle_destroy_rep, 0, REASON_EFFECT, PLAYER_NONE); if(core.desrep_chain.size()) add_process(PROCESSOR_OPERATION_REPLACE, 15, 0, 0, 0, 0); if(des) { card_set::iterator cit, rm; for(cit = des->container.begin(); cit != des->container.end();) { rm = cit++; if((*rm)->current.location != LOCATION_MZONE || ((*rm)->fieldid_r != core.pre_field[0] && (*rm)->fieldid_r != core.pre_field[1])) des->container.erase(rm); } add_process(PROCESSOR_DESTROY, 3, 0, des, REASON_BATTLE, PLAYER_NONE); } adjust_all(); return FALSE; } case 33: { core.units.begin()->ptarget = 0; card_set ing; card_set ed; if(core.attacker->is_status(STATUS_BATTLE_DESTROYED) && (core.attacker->current.reason & REASON_BATTLE)) { raise_single_event(core.attack_target, 0, EVENT_BATTLE_DESTROYING, 0, core.attacker->current.reason, core.attack_target->current.controler, 0, 1); raise_single_event(core.attacker, 0, EVENT_BATTLE_DESTROYED, 0, core.attacker->current.reason, core.attack_target->current.controler, 0, 0); raise_single_event(core.attacker, 0, EVENT_DESTROYED, 0, core.attacker->current.reason, core.attack_target->current.controler, 0, 0); ing.insert(core.attack_target); ed.insert(core.attacker); } if(core.attack_target && core.attack_target->is_status(STATUS_BATTLE_DESTROYED) && (core.attack_target->current.reason & REASON_BATTLE)) { raise_single_event(core.attacker, 0, EVENT_BATTLE_DESTROYING, 0, core.attack_target->current.reason, core.attacker->current.controler, 0, 0); raise_single_event(core.attack_target, 0, EVENT_BATTLE_DESTROYED, 0, core.attack_target->current.reason, core.attacker->current.controler, 0, 1); raise_single_event(core.attack_target, 0, EVENT_DESTROYED, 0, core.attack_target->current.reason, core.attacker->current.controler, 0, 1); ing.insert(core.attacker); ed.insert(core.attack_target); } if(ing.size()) raise_event(&ing, EVENT_BATTLE_DESTROYING, 0, 0, 0, 0, 0); if(ed.size()) { raise_event(&ed, EVENT_BATTLE_DESTROYED, 0, 0, 0, 0, 0); raise_event(&ed, EVENT_DESTROYED, 0, 0, 0, 0, 0); } raise_single_event(core.attacker, 0, EVENT_DAMAGE_STEP_END, 0, 0, 0, 0, 0); if(core.attack_target) raise_single_event(core.attack_target, 0, EVENT_DAMAGE_STEP_END, 0, 0, 0, 0, 1); raise_event((card*)0, EVENT_DAMAGE_STEP_END, 0, 0, 0, 0, 0); core.attacker->set_status(STATUS_BATTLE_DESTROYED, FALSE); if(core.attack_target) core.attack_target->set_status(STATUS_BATTLE_DESTROYED, FALSE); process_single_event(); process_instant_event(); pduel->write_buffer8(MSG_HINT); pduel->write_buffer8(HINT_EVENT); pduel->write_buffer8(0); pduel->write_buffer32(44); pduel->write_buffer8(MSG_HINT); pduel->write_buffer8(HINT_EVENT); pduel->write_buffer8(1); pduel->write_buffer32(44); add_process(PROCESSOR_POINT_EVENT, 0, 0, 0, 0, TRUE); core.units.begin()->step = 38; return FALSE; } case 38: { core.units.begin()->arg1 = 0; core.damage_calculated = TRUE; core.selfdes_disabled = FALSE; core.flip_delayed = FALSE; core.new_fchain.splice(core.new_fchain.begin(), core.new_fchain_b); core.new_ochain.splice(core.new_ochain.begin(), core.new_ochain_b); if(core.new_fchain.size() || core.new_ochain.size()) add_process(PROCESSOR_POINT_EVENT, 0, 0, 0, 0, 0); return FALSE; } case 39: { //end of damage step core.attacker->set_status(STATUS_OPPO_BATTLE, FALSE); if(core.attack_target) core.attack_target->set_status(STATUS_OPPO_BATTLE, FALSE); core.units.begin()->step = -1; infos.phase = PHASE_BATTLE_STEP; pduel->write_buffer8(MSG_DAMAGE_STEP_END); reset_phase(PHASE_DAMAGE); adjust_all(); if(core.effect_damage_step) return TRUE; return FALSE; } case 40: { if(core.chain_limit) { luaL_unref(pduel->lua->lua_state, LUA_REGISTRYINDEX, core.chain_limit); core.chain_limit = 0; } if(core.current_chain.size()) { for(auto cait = core.current_chain.begin(); cait != core.current_chain.end(); ++cait) cait->triggering_effect->handler->set_status(STATUS_CHAINING, FALSE); add_process(PROCESSOR_SOLVE_CHAIN, 0, 0, 0, FALSE, 0); core.units.begin()->step = -1; return FALSE; } reset_phase(PHASE_BATTLE_STEP); adjust_all(); return FALSE; } case 41: { // normal end of battle step if(is_player_affected_by_effect(infos.turn_player, EFFECT_BP_TWICE)) core.units.begin()->arg2 = 1; else core.units.begin()->arg2 = 0; infos.phase = PHASE_BATTLE; add_process(PROCESSOR_PHASE_EVENT, 0, 0, 0, PHASE_BATTLE, 0); adjust_all(); return FALSE; } case 42: { core.attacker = 0; core.attack_target = 0; returns.ivalue[0] = core.units.begin()->arg1; returns.ivalue[1] = core.units.begin()->arg2; return TRUE; } } return TRUE; } int32 field::process_damage_step(uint16 step) { switch(step) { case 0: { core.effect_damage_step = 1; card* tmp = core.attacker; core.attacker = (card*)core.units.begin()->peffect; core.units.begin()->peffect = (effect*)tmp; tmp = core.attack_target; core.attack_target = (card*)core.units.begin()->ptarget; core.units.begin()->ptarget = (group*)tmp; core.units.begin()->arg1 = infos.phase; if(core.attacker->current.location != LOCATION_MZONE || core.attack_target->current.location != LOCATION_MZONE) { core.units.begin()->step = 2; return FALSE; } pduel->write_buffer8(MSG_ATTACK); pduel->write_buffer32(core.attacker->get_info_location()); pduel->write_buffer32(core.attack_target->get_info_location()); infos.phase = PHASE_DAMAGE; pduel->write_buffer8(MSG_DAMAGE_STEP_START); core.pre_field[0] = core.attacker->fieldid_r; core.attacker->attacked_count++; if(core.attack_target) core.pre_field[1] = core.attack_target->fieldid_r; else core.pre_field[1] = 0; if(core.attack_target->is_position(POS_FACEDOWN)) { change_position(core.attack_target, 0, PLAYER_NONE, core.attack_target->current.position >> 1, 0, TRUE); adjust_all(); } return FALSE; } case 1: { infos.phase = PHASE_DAMAGE_CAL; raise_single_event(core.attacker, 0, EVENT_DAMAGE_CALCULATING, 0, 0, 0, 0, 0); if(core.attack_target) raise_single_event(core.attack_target, 0, EVENT_DAMAGE_CALCULATING, 0, 0, 0, 0, 1); raise_event((card*)0, EVENT_DAMAGE_CALCULATING, 0, 0, 0, 0, 0); process_single_event(); process_instant_event(); add_process(PROCESSOR_BATTLE_COMMAND, 26, 0, 0, 0, 0); core.units.begin()->step = 2; core.reserved = core.units.front(); return TRUE; } case 2: { core.effect_damage_step = 2; add_process(PROCESSOR_BATTLE_COMMAND, 27, 0, 0, 0, 0); return FALSE; } case 3: { core.attacker = (card*)core.units.begin()->peffect; core.attack_target = (card*)core.units.begin()->ptarget; if(core.attacker) core.attacker->set_status(STATUS_ATTACK_CANCELED, TRUE); if(core.attack_target) core.attack_target->set_status(STATUS_ATTACK_CANCELED, TRUE); core.effect_damage_step = 0; infos.phase = core.units.begin()->arg1; return TRUE; } } return TRUE; } void field::calculate_battle_damage(effect** pdamchange, card** preason_card, uint8* battle_destroyed) { uint32 aa = core.attacker->get_attack(), ad = core.attacker->get_defence(); uint32 da = 0, dd = 0, a = aa, d; uint8 pa = core.attacker->current.controler, pd; uint8 damp = 0; effect* damchange = 0; card* reason_card = 0; uint8 bd[2] = {FALSE, FALSE}; core.battle_damage[0] = core.battle_damage[1] = 0; if(core.attacker->is_position(POS_FACEUP_DEFENCE)) { effect* defattack = core.attacker->is_affected_by_effect(EFFECT_DEFENCE_ATTACK); if(defattack && defattack->get_value(core.attacker)) a = ad; } if(core.attack_target) { da = core.attack_target->get_attack(); dd = core.attack_target->get_defence(); pd = core.attack_target->current.controler; if(core.attack_target->is_position(POS_ATTACK)) { d = da; if(a > d) { damchange = core.attacker->is_affected_by_effect(EFFECT_BATTLE_DAMAGE_TO_EFFECT); if(damchange) { damp = pd; core.battle_damage[damp] = a - d; reason_card = core.attacker; } else if(!core.attacker->is_affected_by_effect(EFFECT_NO_BATTLE_DAMAGE) && !core.attack_target->is_affected_by_effect(EFFECT_AVOID_BATTLE_DAMAGE, core.attacker) && !is_player_affected_by_effect(pd, EFFECT_AVOID_BATTLE_DAMAGE)) { if(core.attack_target->is_affected_by_effect(EFFECT_REFLECT_BATTLE_DAMAGE, core.attacker)) damp = 1 - pd; else damp = pd; if(is_player_affected_by_effect(damp, EFFECT_REFLECT_BATTLE_DAMAGE)) damp = 1 - damp; if(damp == pd || (!core.attacker->is_affected_by_effect(EFFECT_AVOID_BATTLE_DAMAGE, core.attack_target) && !is_player_affected_by_effect(damp, EFFECT_AVOID_BATTLE_DAMAGE))) { core.battle_damage[damp] = a - d; reason_card = core.attacker; } } bd[1] = TRUE; } else if (a < d) { damchange = core.attack_target->is_affected_by_effect(EFFECT_BATTLE_DAMAGE_TO_EFFECT); if(damchange) { damp = pa; core.battle_damage[damp] = d - a; reason_card = core.attack_target; } else if(!core.attack_target->is_affected_by_effect(EFFECT_NO_BATTLE_DAMAGE) && !core.attacker->is_affected_by_effect(EFFECT_AVOID_BATTLE_DAMAGE, core.attack_target) && !is_player_affected_by_effect(pa, EFFECT_AVOID_BATTLE_DAMAGE)) { if(core.attacker->is_affected_by_effect(EFFECT_REFLECT_BATTLE_DAMAGE, core.attack_target)) damp = 1 - pa; else damp = pa; if(is_player_affected_by_effect(damp, EFFECT_REFLECT_BATTLE_DAMAGE)) damp = 1 - damp; if(damp == pa || (!core.attack_target->is_affected_by_effect(EFFECT_AVOID_BATTLE_DAMAGE, core.attacker) && !is_player_affected_by_effect(damp, EFFECT_AVOID_BATTLE_DAMAGE))) { core.battle_damage[damp] = d - a; reason_card = core.attack_target; } } bd[0] = TRUE; } else { if(a != 0) { bd[0] = TRUE; bd[1] = TRUE; } } } else { d = dd; if(a > d) { effect_set eset; uint8 dp[2]; dp[0] = dp[1] = 0; core.attacker->filter_effect(EFFECT_PIERCE, &eset); if(eset.size() && !core.attacker->is_affected_by_effect(EFFECT_NO_BATTLE_DAMAGE) && !core.attack_target->is_affected_by_effect(EFFECT_AVOID_BATTLE_DAMAGE, core.attacker)) { for(int32 i = 0; i < eset.size(); ++i) dp[1 - eset[i]->get_handler_player()] = 1; if(dp[0] && is_player_affected_by_effect(0, EFFECT_AVOID_BATTLE_DAMAGE)) dp[0] = 0; if(dp[1] && is_player_affected_by_effect(1, EFFECT_AVOID_BATTLE_DAMAGE)) dp[1] = 0; if(dp[pd] && core.attack_target->is_affected_by_effect(EFFECT_REFLECT_BATTLE_DAMAGE, core.attacker)) { dp[pd] = 0; dp[1 - pd] = 1; } if(dp[pd] && is_player_affected_by_effect(pd, EFFECT_REFLECT_BATTLE_DAMAGE)) { dp[pd] = 0; dp[1 - pd] = 1; } if(dp[1 - pd] && is_player_affected_by_effect(1 - pd, EFFECT_REFLECT_BATTLE_DAMAGE)) { dp[pd] = 1; dp[1 - pd] = 0; } if(dp[pd] && !core.attack_target->is_affected_by_effect(EFFECT_AVOID_BATTLE_DAMAGE, core.attacker) && !is_player_affected_by_effect(pd, EFFECT_AVOID_BATTLE_DAMAGE)) core.battle_damage[pd] = a - d; if(dp[1 - pd] && !core.attacker->is_affected_by_effect(EFFECT_AVOID_BATTLE_DAMAGE, core.attack_target) && !is_player_affected_by_effect(1 - pd, EFFECT_AVOID_BATTLE_DAMAGE)) core.battle_damage[1 - pd] = a - d; reason_card = core.attacker; } bd[1] = TRUE; } else if (a < d) { damchange = core.attack_target->is_affected_by_effect(EFFECT_BATTLE_DAMAGE_TO_EFFECT); if(damchange) { damp = pa; core.battle_damage[damp] = d - a; reason_card = core.attack_target; } else if(!core.attack_target->is_affected_by_effect(EFFECT_NO_BATTLE_DAMAGE) && !core.attacker->is_affected_by_effect(EFFECT_AVOID_BATTLE_DAMAGE, core.attack_target) && !is_player_affected_by_effect(pa, EFFECT_AVOID_BATTLE_DAMAGE)) { if(core.attacker->is_affected_by_effect(EFFECT_REFLECT_BATTLE_DAMAGE, core.attack_target)) damp = 1 - pa; else damp = pa; if(is_player_affected_by_effect(damp, EFFECT_REFLECT_BATTLE_DAMAGE)) damp = 1 - damp; if(damp == pa || (!core.attack_target->is_affected_by_effect(EFFECT_AVOID_BATTLE_DAMAGE, core.attacker) && !is_player_affected_by_effect(damp, EFFECT_AVOID_BATTLE_DAMAGE))) { core.battle_damage[damp] = d - a; reason_card = core.attack_target; } } } } } else { damchange = core.attacker->is_affected_by_effect(EFFECT_BATTLE_DAMAGE_TO_EFFECT); if(damchange) { damp = 1 - pa; core.battle_damage[damp] = a; reason_card = core.attacker; } else if(!core.attacker->is_affected_by_effect(EFFECT_NO_BATTLE_DAMAGE) && !is_player_affected_by_effect(1 - pa, EFFECT_AVOID_BATTLE_DAMAGE)) { damp = 1 - pa; if(is_player_affected_by_effect(damp, EFFECT_REFLECT_BATTLE_DAMAGE)) damp = 1 - damp; if(!is_player_affected_by_effect(damp, EFFECT_AVOID_BATTLE_DAMAGE)) { core.battle_damage[damp] = a; reason_card = core.attacker; } } } if(pdamchange) *pdamchange = damchange; if(preason_card) *preason_card = reason_card; if(battle_destroyed) { battle_destroyed[0] = bd[0]; battle_destroyed[1] = bd[1]; } } int32 field::process_turn(uint16 step, uint8 turn_player) { switch(step) { case 0: { //Pre Draw card* pcard; for(auto elit = core.used_event.begin(); elit != core.used_event.end(); ++elit) { if(elit->event_cards) pduel->delete_group(elit->event_cards); } core.used_event.clear(); for(auto eit = core.reseted_effects.begin(); eit != core.reseted_effects.end(); ++eit) { pduel->delete_effect(*eit); } core.reseted_effects.clear(); core.effect_count_code.clear(); for(uint8 p = 0; p < 2; ++p) { for(uint8 i = 0; i < 5; ++i) { pcard = player[p].list_mzone[i]; if(!pcard) continue; pcard->set_status(STATUS_SUMMON_TURN, FALSE); pcard->set_status(STATUS_FLIP_SUMMON_TURN, FALSE); pcard->set_status(STATUS_SPSUMMON_TURN, FALSE); pcard->set_status(STATUS_SET_TURN, FALSE); pcard->set_status(STATUS_FORM_CHANGED, FALSE); pcard->announce_count = 0; pcard->attacked_count = 0; pcard->announced_cards.clear(); pcard->attacked_cards.clear(); pcard->battled_cards.clear(); pcard->attack_all_target = TRUE; } for(uint8 i = 0; i < 8; ++i) { pcard = player[p].list_szone[i]; if(!pcard) continue; pcard->set_status(STATUS_SET_TURN, FALSE); } core.summon_state_count[p] = 0; core.normalsummon_state_count[p] = 0; core.flipsummon_state_count[p] = 0; core.spsummon_state_count[p] = 0; core.spsummon_state_count_rst[p] = 0; core.attack_state_count[p] = 0; core.battle_phase_count[p] = 0; core.summon_count[p] = 0; core.extra_summon[p] = 0; core.spsummon_once_map[p].clear(); core.spsummon_once_map_rst[p].clear(); } core.spsummon_rst = false; for(auto rit = effects.rechargeable.begin(); rit != effects.rechargeable.end(); ++rit) if(!((*rit)->is_flag(EFFECT_FLAG_NO_TURN_RESET))) (*rit)->recharge(); for(auto iter = core.summon_counter.begin(); iter != core.summon_counter.end(); ++iter) iter->second.second = 0; for(auto iter = core.normalsummon_counter.begin(); iter != core.normalsummon_counter.end(); ++iter) iter->second.second = 0; for(auto iter = core.spsummon_counter.begin(); iter != core.spsummon_counter.end(); ++iter) iter->second.second = 0; for(auto iter = core.flipsummon_counter.begin(); iter != core.flipsummon_counter.end(); ++iter) iter->second.second = 0; for(auto iter = core.attack_counter.begin(); iter != core.attack_counter.end(); ++iter) iter->second.second = 0; for(auto iter = core.chain_counter.begin(); iter != core.chain_counter.end(); ++iter) iter->second.second = 0; if(core.global_flag & GLOBALFLAG_SPSUMMON_COUNT) { for(auto iter = effects.spsummon_count_eff.begin(); iter != effects.spsummon_count_eff.end(); ++iter) { effect* peffect = *iter; card* pcard = peffect->handler; if(!(peffect->is_flag(EFFECT_FLAG_NO_TURN_RESET))) { pcard->spsummon_counter[0] = pcard->spsummon_counter[1] = 0; pcard->spsummon_counter_rst[0] = pcard->spsummon_counter_rst[1] = 0; } } } infos.turn_id++; infos.turn_player = turn_player; pduel->write_buffer8(MSG_NEW_TURN); pduel->write_buffer8(turn_player); if((core.duel_options & DUEL_TAG_MODE) && infos.turn_id != 1) tag_swap(turn_player); if(is_player_affected_by_effect(infos.turn_player, EFFECT_SKIP_TURN)) { core.units.begin()->step = 17; reset_phase(PHASE_DRAW); reset_phase(PHASE_STANDBY); reset_phase(PHASE_END); adjust_all(); return FALSE; } infos.phase = PHASE_DRAW; core.phase_action = FALSE; core.hand_adjusted = FALSE; raise_event((card*)0, EVENT_PHASE_START + PHASE_DRAW, 0, 0, 0, turn_player, 0); process_instant_event(); adjust_all(); return FALSE; } case 1: { core.new_fchain.clear(); core.new_ochain.clear(); core.quick_f_chain.clear(); core.delayed_quick_tmp.clear(); if(is_player_affected_by_effect(infos.turn_player, EFFECT_SKIP_DP)) { core.units.begin()->step = 2; reset_phase(PHASE_DRAW); adjust_all(); return FALSE; } pduel->write_buffer8(MSG_NEW_PHASE); pduel->write_buffer16(infos.phase); raise_event((card*)0, EVENT_PREDRAW, 0, 0, 0, turn_player, 0); process_instant_event(); if(core.new_fchain.size() || core.new_ochain.size()) add_process(PROCESSOR_POINT_EVENT, 0, 0, 0, 0, 0); return FALSE; } case 2: { // Draw, new ruling if((core.duel_options & DUEL_OBSOLETE_RULING) || (infos.turn_id > 1)) { int32 count = get_draw_count(infos.turn_player); if(count > 0) { draw(0, REASON_RULE, turn_player, turn_player, count); add_process(PROCESSOR_POINT_EVENT, 0, 0, 0, 0, 0); } } add_process(PROCESSOR_PHASE_EVENT, 0, 0, 0, PHASE_DRAW, 0); return FALSE; } case 3: { // EVENT_PHASE_PRESTART is removed return FALSE; } case 4: { //Standby Phase infos.phase = PHASE_STANDBY; core.phase_action = FALSE; core.new_fchain.clear(); core.new_ochain.clear(); core.quick_f_chain.clear(); core.delayed_quick_tmp.clear(); if(is_player_affected_by_effect(infos.turn_player, EFFECT_SKIP_SP)) { core.units.begin()->step = 5; reset_phase(PHASE_STANDBY); adjust_all(); return FALSE; } pduel->write_buffer8(MSG_NEW_PHASE); pduel->write_buffer16(infos.phase); raise_event((card*)0, EVENT_PHASE_START + PHASE_STANDBY, 0, 0, 0, turn_player, 0); process_instant_event(); return FALSE; } case 5: { // EVENT_PHASE_START + PHASE_STANDBY is a special case(c89642993) if(core.new_fchain.size() || core.new_ochain.size() || core.instant_event.back().event_code != EVENT_PHASE_START + PHASE_STANDBY) add_process(PROCESSOR_POINT_EVENT, 0, 0, 0, 0, 0); add_process(PROCESSOR_PHASE_EVENT, 0, 0, 0, PHASE_STANDBY, 0); return FALSE; } case 6: { //Main1 infos.phase = PHASE_MAIN1; core.phase_action = FALSE; raise_event((card*)0, EVENT_PHASE_START + PHASE_MAIN1, 0, 0, 0, turn_player, 0); process_instant_event(); adjust_all(); return FALSE; } case 7: { return FALSE; } case 8: { core.new_fchain.clear(); core.new_ochain.clear(); core.quick_f_chain.clear(); core.delayed_quick_tmp.clear(); pduel->write_buffer8(MSG_NEW_PHASE); pduel->write_buffer16(infos.phase); add_process(PROCESSOR_IDLE_COMMAND, 0, 0, 0, 0, 0); return FALSE; } case 9: { if(returns.ivalue[0] == 7) { // End Phase core.units.begin()->step = 14; return FALSE; } infos.phase = PHASE_BATTLE_START; core.new_fchain.clear(); core.new_ochain.clear(); core.quick_f_chain.clear(); core.delayed_quick_tmp.clear(); core.phase_action = FALSE; core.battle_phase_action = FALSE; core.battle_phase_count[infos.turn_player]++; pduel->write_buffer8(MSG_NEW_PHASE); pduel->write_buffer16(infos.phase); raise_event((card*)0, EVENT_PHASE_START + PHASE_BATTLE_START, 0, 0, 0, turn_player, 0); process_instant_event(); adjust_all(); return FALSE; } case 10: { add_process(PROCESSOR_PHASE_EVENT, 0, 0, 0, PHASE_BATTLE_START, 0); return FALSE; } case 11: { infos.phase = PHASE_BATTLE_STEP; core.new_fchain.clear(); core.new_ochain.clear(); core.quick_f_chain.clear(); core.delayed_quick_tmp.clear(); core.phase_action = FALSE; core.chain_attack = FALSE; add_process(PROCESSOR_BATTLE_COMMAND, 0, 0, 0, 0, 0); return FALSE; } case 12: { if(core.units.begin()->arg2 == 0 && returns.ivalue[1]) { // 2nd Battle Phase core.units.begin()->arg2 = 1; core.units.begin()->step = 8; for(uint8 p = 0; p < 2; ++p) { for(uint8 i = 0; i < 5; ++i) { card* pcard = player[p].list_mzone[i]; if(!pcard) continue; pcard->announce_count = 0; pcard->attacked_count = 0; pcard->announced_cards.clear(); pcard->attacked_cards.clear(); pcard->battled_cards.clear(); } } return FALSE; } core.skip_m2 = FALSE; if(returns.ivalue[0] == 3) { // End Phase core.skip_m2 = TRUE; } //Main2 infos.phase = PHASE_MAIN2; core.phase_action = FALSE; raise_event((card*)0, EVENT_PHASE_START + PHASE_MAIN2, 0, 0, 0, turn_player, 0); process_instant_event(); adjust_all(); return FALSE; } case 13: { if(core.new_fchain.size() || core.new_ochain.size()) add_process(PROCESSOR_POINT_EVENT, 0, 0, 0, 0, 0); return FALSE; } case 14: { core.new_fchain.clear(); core.new_ochain.clear(); core.quick_f_chain.clear(); core.delayed_quick_tmp.clear(); pduel->write_buffer8(MSG_NEW_PHASE); pduel->write_buffer16(infos.phase); infos.can_shuffle = TRUE; add_process(PROCESSOR_IDLE_COMMAND, 0, 0, 0, 0, 0); return FALSE; } case 15: { //End Phase infos.phase = PHASE_END; core.phase_action = FALSE; pduel->write_buffer8(MSG_NEW_PHASE); pduel->write_buffer16(infos.phase); raise_event((card*)0, EVENT_PHASE_START + PHASE_END, 0, 0, 0, turn_player, 0); process_instant_event(); adjust_all(); return FALSE; } case 16: { if(core.new_fchain.size() || core.new_ochain.size()) add_process(PROCESSOR_POINT_EVENT, 0, 0, 0, 0, 0); return FALSE; } case 17: { core.new_fchain.clear(); core.new_ochain.clear(); core.quick_f_chain.clear(); core.delayed_quick_tmp.clear(); add_process(PROCESSOR_PHASE_EVENT, 0, 0, 0, PHASE_END, 0); return FALSE; } case 18: { raise_event((card*)0, EVENT_TURN_END, 0, 0, 0, turn_player, 0); process_instant_event(); adjust_all(); return FALSE; } case 19: { core.new_fchain.clear(); core.new_ochain.clear(); core.quick_f_chain.clear(); core.delayed_quick_tmp.clear(); core.units.begin()->step = -1; core.units.begin()->arg1 = 1 - core.units.begin()->arg1; return FALSE; } } return TRUE; } int32 field::add_chain(uint16 step) { switch (step) { case 0: { auto& clit = core.new_chains.front(); effect* peffect = clit.triggering_effect; if (!core.new_chains.size()) return TRUE; effect_set eset; filter_player_effect(clit.triggering_player, EFFECT_ACTIVATE_COST, &eset); for(int32 i = 0; i < eset.size(); ++i) { pduel->lua->add_param(eset[i], PARAM_TYPE_EFFECT); pduel->lua->add_param(clit.triggering_effect, PARAM_TYPE_EFFECT); pduel->lua->add_param(clit.triggering_player, PARAM_TYPE_INT); if(!pduel->lua->check_condition(eset[i]->target, 3)) continue; if(eset[i]->operation) { core.sub_solving_event.push_back(clit.evt); add_process(PROCESSOR_EXECUTE_OPERATION, 0, eset[i], 0, clit.triggering_player, 0); } } if(peffect->type & EFFECT_TYPE_ACTIVATE) { break_effect(); int32 ecode = 0; if(peffect->handler->current.location == LOCATION_HAND) { if(peffect->handler->data.type & TYPE_TRAP) ecode = EFFECT_TRAP_ACT_IN_HAND; else if((peffect->handler->data.type & TYPE_SPELL) && (peffect->handler->data.type & TYPE_QUICKPLAY) && infos.turn_player != peffect->handler->current.controler) ecode = EFFECT_QP_ACT_IN_NTPHAND; } else if(peffect->handler->current.location == LOCATION_SZONE) { if((peffect->handler->data.type & TYPE_TRAP) && peffect->handler->get_status(STATUS_SET_TURN)) ecode = EFFECT_TRAP_ACT_IN_SET_TURN; } if(ecode) { eset.clear(); peffect->handler->filter_effect(ecode, &eset); effect* pactin = 0; for(int32 i = 0; i < eset.size(); ++i) { if(!(eset[i]->is_flag(EFFECT_FLAG_COUNT_LIMIT))) { pactin = eset[i]; break; } } if(!pactin) { for(int32 i = 0; i < eset.size(); ++i) { if(eset[i]->check_count_limit(peffect->handler->current.controler)) { eset[i]->dec_count(peffect->handler->current.controler); break; } } } } if(peffect->handler->current.location == LOCATION_HAND) { peffect->handler->enable_field_effect(FALSE); peffect->handler->set_status(STATUS_ACT_FROM_HAND, TRUE); move_to_field(peffect->handler, peffect->handler->current.controler, peffect->handler->current.controler, LOCATION_SZONE, POS_FACEUP); } else { peffect->handler->set_status(STATUS_ACT_FROM_HAND, FALSE); change_position(peffect->handler, 0, peffect->handler->current.controler, POS_FACEUP, 0); } } if(peffect->handler->current.location & 0x30) move_card(peffect->handler->current.controler, peffect->handler, peffect->handler->current.location, 0); return FALSE; } case 1: { auto& clit = core.new_chains.front(); effect* peffect = clit.triggering_effect; card* phandler = peffect->handler; if(peffect->type & EFFECT_TYPE_ACTIVATE) { clit.triggering_controler = phandler->current.controler; clit.triggering_location = phandler->current.location; clit.triggering_sequence = phandler->current.sequence; } pduel->write_buffer8(MSG_CHAINING); pduel->write_buffer32(phandler->data.code); pduel->write_buffer32(phandler->get_info_location()); pduel->write_buffer8(clit.triggering_controler); pduel->write_buffer8(clit.triggering_location); pduel->write_buffer8(clit.triggering_sequence); pduel->write_buffer32(peffect->description); pduel->write_buffer8(core.current_chain.size() + 1); break_effect(); if(core.chain_limit) { luaL_unref(pduel->lua->lua_state, LUA_REGISTRYINDEX, core.chain_limit); core.chain_limit = 0; } peffect->card_type = peffect->handler->get_type(); if((peffect->card_type & 0x5) == 0x5) peffect->card_type -= TYPE_TRAP; peffect->active_type = peffect->card_type; clit.chain_count = core.current_chain.size() + 1; clit.target_cards = 0; clit.target_player = PLAYER_NONE; clit.target_param = 0; clit.disable_reason = 0; clit.disable_player = PLAYER_NONE; clit.replace_op = 0; if(phandler->current.location == LOCATION_HAND) clit.flag |= CHAIN_HAND_EFFECT; core.current_chain.push_back(clit); check_chain_counter(peffect, clit.triggering_player, clit.chain_count); // triggered events which are not caused by RaiseEvent create relation with the handler if(!(peffect->is_flag(EFFECT_FLAG_FIELD_ONLY)) && (!(peffect->type & 0x2a0) || (peffect->code & EVENT_PHASE) == EVENT_PHASE)) { peffect->handler->create_relation(clit); } peffect->effect_owner = clit.triggering_player; // DISABLE_CHAIN should be check before cost effect* deffect; if(!(peffect->is_flag(EFFECT_FLAG_FIELD_ONLY)) && phandler->is_has_relation(clit) && (deffect = phandler->is_affected_by_effect(EFFECT_DISABLE_EFFECT))) { effect* negeff = pduel->new_effect(); negeff->owner = deffect->owner; negeff->type = EFFECT_TYPE_SINGLE; negeff->code = EFFECT_DISABLE_CHAIN; negeff->reset_flag = RESET_CHAIN | RESET_EVENT | deffect->get_value(); phandler->add_effect(negeff); } if(peffect->cost) { core.sub_solving_event.push_back(clit.evt); add_process(PROCESSOR_EXECUTE_COST, 0, peffect, 0, clit.triggering_player, 0); } core.new_chains.pop_front(); return FALSE; } case 2: { auto& clit = core.current_chain.back(); effect* peffect = clit.triggering_effect; if(peffect->target) { core.sub_solving_event.push_back(clit.evt); add_process(PROCESSOR_EXECUTE_TARGET, 0, peffect, 0, clit.triggering_player, 0); } return FALSE; } case 3: { break_effect(); auto& clit = core.current_chain.back(); effect* peffect = clit.triggering_effect; if(clit.target_cards && clit.target_cards->container.size()) { if(peffect->is_flag(EFFECT_FLAG_CARD_TARGET)) { for(auto cit = clit.target_cards->container.begin(); cit != clit.target_cards->container.end(); ++cit) raise_single_event(*cit, 0, EVENT_BECOME_TARGET, peffect, 0, clit.triggering_player, 0, clit.chain_count); process_single_event(); if(clit.target_cards->container.size()) raise_event(&clit.target_cards->container, EVENT_BECOME_TARGET, peffect, 0, clit.triggering_player, clit.triggering_player, clit.chain_count); } } if(peffect->type & EFFECT_TYPE_ACTIVATE) { core.leave_confirmed.insert(peffect->handler); if(!(peffect->handler->data.type & (TYPE_CONTINUOUS + TYPE_FIELD + TYPE_EQUIP + TYPE_PENDULUM)) && !peffect->handler->is_affected_by_effect(EFFECT_REMAIN_FIELD)) peffect->handler->set_status(STATUS_LEAVE_CONFIRMED, TRUE); } core.phase_action = TRUE; if(clit.opinfos.count(0x200)) { core.spsummon_rst = true; set_spsummon_counter(clit.triggering_player, true, true); if(clit.opinfos[0x200].op_player == PLAYER_ALL) set_spsummon_counter(1 - clit.triggering_player, true, true); if((core.global_flag & GLOBALFLAG_SPSUMMON_ONCE) && (peffect->is_flag(EFFECT_FLAG_CARD_TARGET))) { auto& optarget = clit.opinfos[0x200]; if(optarget.op_cards) { if(optarget.op_player == PLAYER_ALL) { auto opit = optarget.op_cards->container.begin(); uint32 sumplayer = optarget.op_param; if((*opit)->spsummon_code) { core.spsummon_once_map[sumplayer][(*opit)->spsummon_code]++; core.spsummon_once_map_rst[sumplayer][(*opit)->spsummon_code]++; } ++opit; if((*opit)->spsummon_code) { core.spsummon_once_map[1 - sumplayer][(*opit)->spsummon_code]++; core.spsummon_once_map_rst[1 - sumplayer][(*opit)->spsummon_code]++; } } else { uint32 sumplayer = clit.triggering_player; if(optarget.op_player == 1) sumplayer = 1 - sumplayer; for(auto opit = optarget.op_cards->container.begin(); opit != optarget.op_cards->container.end(); ++opit) { if((*opit)->spsummon_code) { core.spsummon_once_map[sumplayer][(*opit)->spsummon_code]++; core.spsummon_once_map_rst[sumplayer][(*opit)->spsummon_code]++; } } } } } } pduel->write_buffer8(MSG_CHAINED); pduel->write_buffer8(clit.chain_count); raise_event(peffect->handler, EVENT_CHAINING, peffect, 0, clit.triggering_player, clit.triggering_player, clit.chain_count); process_instant_event(); if(core.new_chains.size()) add_process(PROCESSOR_ADD_CHAIN, 0, 0, 0, 0, 0); adjust_all(); return TRUE; } } return TRUE; } int32 field::sort_chain(uint16 step, uint8 tp) { switch(step) { case 0: { core.select_cards.clear(); if(tp) for(auto clit = core.tpchain.begin(); clit != core.tpchain.end(); ++clit) core.select_cards.push_back(clit->triggering_effect->handler); else for(auto clit = core.ntpchain.begin(); clit != core.ntpchain.end(); ++clit) core.select_cards.push_back(clit->triggering_effect->handler); add_process(PROCESSOR_SORT_CARD, 0, 0, 0, tp ? infos.turn_player : (1 - infos.turn_player), 1); return FALSE; } case 1: { #ifdef _IRR_ANDROID_PLATFORM_ if(returns.bvalue[0] == 0xff) #else if(returns.bvalue[0] == -1) #endif return TRUE; chain_list::iterator clit; int32 i = 0, count; chain_array ch(8); if(tp) { count = core.tpchain.size(); for(i = 0, clit = core.tpchain.begin(); i < count; ++clit, ++i) ch[returns.bvalue[i]] = *clit; core.tpchain.clear(); for(i = 0; i < count; ++i) core.tpchain.push_back(ch[i]); } else { count = core.ntpchain.size(); for(i = 0, clit = core.ntpchain.begin(); i < count; ++clit, ++i) ch[returns.bvalue[i]] = *clit; core.ntpchain.clear(); for(i = 0; i < count; ++i) core.ntpchain.push_back(ch[i]); } return TRUE; } } return TRUE; } int32 field::solve_continuous(uint16 step, effect * peffect, uint8 triggering_player) { switch(step) { case 0: { core.solving_event.splice(core.solving_event.begin(), core.sub_solving_event); if(!peffect->check_count_limit(triggering_player)) { core.solving_event.pop_front(); return TRUE; } chain newchain; newchain.chain_id = 0; newchain.chain_count = 0; newchain.triggering_effect = peffect; newchain.triggering_player = triggering_player; newchain.evt = core.solving_event.front(); newchain.target_cards = 0; newchain.target_player = PLAYER_NONE; newchain.target_param = 0; newchain.disable_player = PLAYER_NONE; newchain.disable_reason = 0; newchain.flag = 0; core.continuous_chain.push_back(newchain); if(peffect->is_flag(EFFECT_FLAG_DELAY)) core.conti_solving = TRUE; if(!peffect->target) return FALSE; core.sub_solving_event.push_back(core.solving_event.front()); add_process(PROCESSOR_EXECUTE_TARGET, 0, peffect, 0, triggering_player, 0); return FALSE; } case 1: { return FALSE; } case 2: { if(!peffect->operation) return FALSE; peffect->dec_count(triggering_player); core.sub_solving_event.push_back(core.solving_event.front()); add_process(PROCESSOR_EXECUTE_OPERATION, 0, peffect, 0, triggering_player, 0); return FALSE; } case 3: { if(core.continuous_chain.back().target_cards) pduel->delete_group(core.continuous_chain.back().target_cards); for(auto oit = core.continuous_chain.back().opinfos.begin(); oit != core.continuous_chain.back().opinfos.end(); ++oit) { if(oit->second.op_cards) pduel->delete_group(oit->second.op_cards); } core.continuous_chain.pop_back(); core.solving_event.pop_front(); if(peffect->is_flag(EFFECT_FLAG_DELAY)) { core.conti_solving = FALSE; adjust_all(); if(core.conti_player == infos.turn_player) { if(core.delayed_tp.size()) { core.sub_solving_event.push_back(core.delayed_tev.front()); add_process(PROCESSOR_SOLVE_CONTINUOUS, 0, core.delayed_tp.front(), 0, infos.turn_player, 0); core.delayed_tp.pop_front(); core.delayed_tev.pop_front(); } else core.conti_player = 1 - infos.turn_player; } if(core.conti_player == 1 - infos.turn_player) { if(core.delayed_ntp.size()) { core.sub_solving_event.push_back(core.delayed_ntev.front()); add_process(PROCESSOR_SOLVE_CONTINUOUS, 0, core.delayed_ntp.front(), 0, 1 - infos.turn_player, 0); core.delayed_ntp.pop_front(); core.delayed_ntev.pop_front(); } else if(core.delayed_tp.size()) { core.conti_player = infos.turn_player; core.sub_solving_event.push_back(core.delayed_tev.front()); add_process(PROCESSOR_SOLVE_CONTINUOUS, 0, core.delayed_tp.front(), 0, infos.turn_player, 0); core.delayed_tp.pop_front(); core.delayed_tev.pop_front(); } else core.conti_player = PLAYER_NONE; } } return TRUE; } } return TRUE; } int32 field::solve_chain(uint16 step, uint32 chainend_arg1, uint32 chainend_arg2) { if(core.current_chain.size() == 0 && step == 0) return TRUE; chain_array::reverse_iterator cait = core.current_chain.rbegin(); switch(step) { case 0: { if(core.spsummon_rst) { set_spsummon_counter(0, false, true); set_spsummon_counter(1, false, true); for(int plr = 0; plr < 2; ++plr) { for(auto iter = core.spsummon_once_map[plr].begin(); iter != core.spsummon_once_map[plr].end(); ++iter) { auto spcode = iter->first; core.spsummon_once_map[plr][spcode] -= core.spsummon_once_map_rst[plr][spcode]; core.spsummon_once_map_rst[plr][spcode] = 0; } } core.spsummon_rst = false; } pduel->write_buffer8(MSG_CHAIN_SOLVING); pduel->write_buffer8(cait->chain_count); add_to_disable_check_list(cait->triggering_effect->handler); adjust_instant(); raise_event((card*)0, EVENT_CHAIN_ACTIVATING, cait->triggering_effect, 0, cait->triggering_player, cait->triggering_player, cait->chain_count); process_instant_event(); return FALSE; } case 1: { effect* peffect = cait->triggering_effect; if(cait->flag & CHAIN_DISABLE_ACTIVATE && is_chain_negatable(cait->chain_count)) { remove_oath_effect(peffect); if((peffect->is_flag(EFFECT_FLAG_COUNT_LIMIT)) && (peffect->count_code & EFFECT_COUNT_CODE_OATH)) { dec_effect_code(peffect->count_code, cait->triggering_player); } check_chain_counter(peffect, cait->triggering_player, cait->chain_count, true); raise_event((card*)0, EVENT_CHAIN_NEGATED, peffect, 0, cait->triggering_player, cait->triggering_player, cait->chain_count); process_instant_event(); core.units.begin()->step = 9; return FALSE; } for(auto oeit = effects.oath.begin(); oeit != effects.oath.end(); ++oeit) if(oeit->second == peffect) oeit->second = 0; break_effect(); core.chain_solving = TRUE; card* pcard = peffect->handler; if((peffect->type & EFFECT_TYPE_ACTIVATE) && pcard->is_has_relation(*cait)) { pcard->set_status(STATUS_ACTIVATED, TRUE); pcard->enable_field_effect(TRUE); if(core.duel_options & DUEL_OBSOLETE_RULING) { if(pcard->data.type & TYPE_FIELD) { card* fscard = player[1 - pcard->current.controler].list_szone[5]; if(fscard && fscard->is_position(POS_FACEUP)) fscard->enable_field_effect(FALSE); } } adjust_instant(); } raise_event((card*)0, EVENT_CHAIN_SOLVING, peffect, 0, cait->triggering_player, cait->triggering_player, cait->chain_count); process_instant_event(); return FALSE; } case 2: { core.spsummon_state_count_tmp[0] = core.spsummon_state_count[0]; core.spsummon_state_count_tmp[1] = core.spsummon_state_count[1]; card* pcard = cait->triggering_effect->handler; if(is_chain_disablable(cait->chain_count)) { if((cait->flag & CHAIN_DISABLE_EFFECT) || pcard->is_affected_by_effect(EFFECT_DISABLE_CHAIN) || ((cait->triggering_location & LOCATION_ONFIELD) && pcard->is_affected_by_effect(EFFECT_DISABLE_CHAIN_FIELD)) || (pcard->is_status(STATUS_DISABLED) && pcard->is_has_relation(*cait))) { if(!(cait->flag & CHAIN_DISABLE_EFFECT)) { pduel->write_buffer8(MSG_CHAIN_DISABLED); pduel->write_buffer8(cait->chain_count); } raise_event((card*)0, EVENT_CHAIN_DISABLED, cait->triggering_effect, 0, cait->triggering_player, cait->triggering_player, cait->chain_count); process_instant_event(); core.units.begin()->step = 3; return FALSE; } } if(cait->replace_op) { core.units.begin()->peffect = (effect*)(size_t)cait->triggering_effect->operation; cait->triggering_effect->operation = cait->replace_op; } else core.units.begin()->peffect = 0; if(cait->triggering_effect->operation) { core.sub_solving_event.push_back(cait->evt); add_process(PROCESSOR_EXECUTE_OPERATION, 0, cait->triggering_effect, 0, cait->triggering_player, 0); } return FALSE; } case 3: { effect* peffect = cait->triggering_effect; if(core.units.begin()->peffect) { peffect->operation = (ptr)core.units.begin()->peffect; } core.special_summoning.clear(); core.equiping_cards.clear(); return FALSE; } case 4: { if(core.units.begin()->peffect == 0) { if(cait->opinfos.count(0x200)) { if(core.spsummon_state_count_tmp[cait->triggering_player] == core.spsummon_state_count[cait->triggering_player]) set_spsummon_counter(cait->triggering_player); if(cait->opinfos[0x200].op_player == PLAYER_ALL && core.spsummon_state_count_tmp[1 - cait->triggering_player] == core.spsummon_state_count[1 - cait->triggering_player]) set_spsummon_counter(1 - cait->triggering_player); //sometimes it may add twice, only works for once per turn if(cait->triggering_effect->is_flag(EFFECT_FLAG_CARD_TARGET)) { auto& optarget = cait->opinfos[0x200]; if(optarget.op_cards) { if(optarget.op_player == PLAYER_ALL) { uint32 sumplayer = optarget.op_param; if(core.global_flag & GLOBALFLAG_SPSUMMON_ONCE) { auto opit = optarget.op_cards->container.begin(); if((*opit)->spsummon_code) core.spsummon_once_map[sumplayer][(*opit)->spsummon_code]++; ++opit; if((*opit)->spsummon_code) core.spsummon_once_map[1 - sumplayer][(*opit)->spsummon_code]++; } auto opit = optarget.op_cards->container.begin(); check_card_counter(*opit, 3, sumplayer); ++opit; check_card_counter(*opit, 3, 1 - sumplayer); } else { uint32 sumplayer = cait->triggering_player; if(optarget.op_player == 1) sumplayer = 1 - sumplayer; for(auto opit = optarget.op_cards->container.begin(); opit != optarget.op_cards->container.end(); ++opit) { if((core.global_flag & GLOBALFLAG_SPSUMMON_ONCE) && (*opit)->spsummon_code) core.spsummon_once_map[sumplayer][(*opit)->spsummon_code]++; check_card_counter(*opit, 3, sumplayer); } } } } } } core.spsummon_state_count_tmp[0] = 0; core.spsummon_state_count_tmp[1] = 0; core.chain_solving = FALSE; effect_vector::iterator eit; event_list::iterator evit; if(core.delayed_tp.size()) { core.conti_player = infos.turn_player; core.sub_solving_event.push_back(core.delayed_tev.front()); add_process(PROCESSOR_SOLVE_CONTINUOUS, 0, core.delayed_tp.front(), 0, infos.turn_player, 0); core.delayed_tp.pop_front(); core.delayed_tev.pop_front(); } else if(core.delayed_ntp.size()) { core.conti_player = 1 - infos.turn_player; core.sub_solving_event.push_back(core.delayed_ntev.front()); add_process(PROCESSOR_SOLVE_CONTINUOUS, 0, core.delayed_ntp.front(), 0, 1 - infos.turn_player, 0); core.delayed_ntp.pop_front(); core.delayed_ntev.pop_front(); } else core.conti_player = PLAYER_NONE; pduel->write_buffer8(MSG_CHAIN_SOLVED); pduel->write_buffer8(cait->chain_count); raise_event((card*)0, EVENT_CHAIN_SOLVED, cait->triggering_effect, 0, cait->triggering_player, cait->triggering_player, cait->chain_count); adjust_disable_check_list(); process_instant_event(); core.units.begin()->step = 9; return FALSE; } case 10: { effect* peffect = cait->triggering_effect; card* pcard = peffect->handler; if((cait->flag & CHAIN_HAND_EFFECT) && !pcard->is_position(POS_FACEUP) && (pcard->current.location == LOCATION_HAND)) shuffle(pcard->current.controler, LOCATION_HAND); if(cait->target_cards && cait->target_cards->container.size()) { for(auto cit = cait->target_cards->container.begin(); cit != cait->target_cards->container.end(); ++cit) (*cit)->release_relation(*cait); } if((pcard->data.type & TYPE_EQUIP) && (peffect->type & EFFECT_TYPE_ACTIVATE) && !pcard->equiping_target && (pcard->current.location == LOCATION_SZONE)) pcard->set_status(STATUS_LEAVE_CONFIRMED, TRUE); if(core.duel_options & DUEL_OBSOLETE_RULING) { if((pcard->data.type & TYPE_FIELD) && (peffect->type & EFFECT_TYPE_ACTIVATE) && !pcard->is_status(STATUS_LEAVE_CONFIRMED) && pcard->is_has_relation(*cait)) { card* fscard = player[1 - pcard->current.controler].list_szone[5]; if(fscard && fscard->is_position(POS_FACEUP)) destroy(fscard, 0, REASON_RULE, 1 - pcard->current.controler); } } peffect->active_type = 0; pcard->release_relation(*cait); if(cait->target_cards) pduel->delete_group(cait->target_cards); for(auto oit = cait->opinfos.begin(); oit != cait->opinfos.end(); ++oit) { if(oit->second.op_cards) pduel->delete_group(oit->second.op_cards); } for(auto cit = core.delayed_enable_set.begin(); cit != core.delayed_enable_set.end(); ++cit) { if((*cit)->current.location == LOCATION_MZONE) (*cit)->enable_field_effect(TRUE); } core.delayed_enable_set.clear(); adjust_all(); core.current_chain.pop_back(); if(!core.current_chain.size()) { if(core.chain_limit) { luaL_unref(pduel->lua->lua_state, LUA_REGISTRYINDEX, core.chain_limit); core.chain_limit = 0; } return FALSE; } core.units.begin()->step = -1; return FALSE; } case 11: { for(auto cit = core.leave_confirmed.begin(); cit != core.leave_confirmed.end();) { auto rm = cit++; if(!(*rm)->is_status(STATUS_LEAVE_CONFIRMED)) core.leave_confirmed.erase(rm); } if(core.leave_confirmed.size()) send_to(&core.leave_confirmed, 0, REASON_RULE, PLAYER_NONE, PLAYER_NONE, LOCATION_GRAVE, 0, POS_FACEUP); return FALSE; } case 12: { core.used_event.splice(core.used_event.end(), core.point_event); pduel->write_buffer8(MSG_CHAIN_END); if(core.chain_limit_p) { luaL_unref(pduel->lua->lua_state, LUA_REGISTRYINDEX, core.chain_limit_p); core.chain_limit_p = 0; } reset_chain(); if(core.summoning_card || core.effect_damage_step == 1) core.subunits.push_back(core.reserved); return FALSE; } case 13: { raise_event((card*)0, EVENT_CHAIN_END, 0, 0, 0, 0, 0); process_instant_event(); core.hint_timing[0] |= TIMING_CHAIN_END; core.hint_timing[1] |= TIMING_CHAIN_END; add_process(PROCESSOR_POINT_EVENT, 0, 0, 0, chainend_arg1, chainend_arg2); returns.ivalue[0] = TRUE; return TRUE; } } return TRUE; } int32 field::break_effect() { core.hint_timing[0] &= TIMING_DAMAGE_STEP | TIMING_DAMAGE_CAL; core.hint_timing[1] &= TIMING_DAMAGE_STEP | TIMING_DAMAGE_CAL; for (auto chit = core.new_ochain.begin(); chit != core.new_ochain.end();) { auto rm = chit++; effect* peffect = rm->triggering_effect; if (!(peffect->is_flag(EFFECT_FLAG_DELAY))) { if ((peffect->is_flag(EFFECT_FLAG_FIELD_ONLY)) || !(peffect->type & EFFECT_TYPE_FIELD) || peffect->in_range(rm->triggering_location, rm->triggering_sequence)) { pduel->write_buffer8(MSG_MISSED_EFFECT); pduel->write_buffer32(peffect->handler->get_info_location()); pduel->write_buffer32(peffect->handler->data.code); } core.new_ochain.erase(rm); } } if(core.global_flag & GLOBALFLAG_DELAYED_QUICKEFFECT) { core.delayed_quick_break.insert(core.delayed_quick_tmp.begin(), core.delayed_quick_tmp.end()); core.delayed_quick_tmp.clear(); } core.used_event.splice(core.used_event.end(), core.instant_event); adjust_instant(); return 0; } void field::adjust_instant() { adjust_disable_check_list(); adjust_self_destroy_set(); } // this includes adjust_instant() void field::adjust_all() { core.readjust_map.clear(); add_process(PROCESSOR_ADJUST, 0, 0, 0, 0, 0); } void field::refresh_location_info_instant() { effect_set eset; uint32 value, p; int32 dis1 = player[0].disabled_location | (player[1].disabled_location << 16); player[0].disabled_location = 0; player[1].disabled_location = 0; filter_field_effect(EFFECT_DISABLE_FIELD, &eset); for (int32 i = 0; i < eset.size(); ++i) { value = eset[i]->get_value(); player[0].disabled_location |= value & 0x1f1f; player[1].disabled_location |= (value >> 16) & 0x1f1f; } eset.clear(); filter_field_effect(EFFECT_USE_EXTRA_MZONE, &eset); for (int32 i = 0; i < eset.size(); ++i) { p = eset[i]->get_handler_player(); value = eset[i]->get_value(); player[p].disabled_location |= (value >> 16) & 0x1f; } eset.clear(); filter_field_effect(EFFECT_USE_EXTRA_SZONE, &eset); for (int32 i = 0; i < eset.size(); ++i) { p = eset[i]->get_handler_player(); value = eset[i]->get_value(); player[p].disabled_location |= (value >> 8) & 0x1f00; } int32 dis2 = player[0].disabled_location | (player[1].disabled_location << 16); if(dis1 != dis2) { pduel->write_buffer8(MSG_FIELD_DISABLED); pduel->write_buffer32(dis2); } } int32 field::refresh_location_info(uint16 step) { switch(step) { case 0: { effect_set eset; uint32 value; int32 p; core.units.begin()->arg2 = player[0].disabled_location | (player[1].disabled_location << 16); player[0].disabled_location = 0; player[1].disabled_location = 0; core.disfield_effects.clear(); core.extraz_effects.clear(); core.extraz_effects_e.clear(); filter_field_effect(EFFECT_DISABLE_FIELD, &eset); for (int32 i = 0; i < eset.size(); ++i) { value = eset[i]->get_value(); if(value) { player[0].disabled_location |= value & 0x1f1f; player[1].disabled_location |= (value >> 16) & 0x1f1f; } else core.disfield_effects.add_item(eset[i]); } eset.clear(); filter_field_effect(EFFECT_USE_EXTRA_MZONE, &eset); for (int32 i = 0; i < eset.size(); ++i) { p = eset[i]->get_handler_player(); value = eset[i]->get_value(); player[p].disabled_location |= (value >> 16) & 0x1f; if(field_used_count[(value >> 16) & 0x1f] == 0) core.extraz_effects_e.add_item(eset[i]); else if((uint32)field_used_count[(value >> 16) & 0x1f] < (value & 0xffff)) core.extraz_effects.add_item(eset[i]); } eset.clear(); filter_field_effect(EFFECT_USE_EXTRA_SZONE, &eset); for (int32 i = 0; i < eset.size(); ++i) { p = eset[i]->get_handler_player(); value = eset[i]->get_value(); player[p].disabled_location |= (value >> 8) & 0x1f00; if(field_used_count[(value >> 16) & 0x1f] == 0) core.extraz_effects_e.add_item(eset[i]); else if((uint32)field_used_count[(value >> 16) & 0x1f] < (value & 0xffff)) core.extraz_effects.add_item(eset[i]); } return FALSE; } case 1: { if(core.disfield_effects.count == 0) { core.units.begin()->step = 2; return FALSE; } effect* peffect = core.disfield_effects[0]; core.units.begin()->peffect = peffect; core.disfield_effects.remove_item(0); if(!peffect->operation) { peffect->value = 0x80; core.units.begin()->step = 0; return FALSE; } core.sub_solving_event.push_back(nil_event); add_process(PROCESSOR_EXECUTE_OPERATION, 0, peffect, 0, peffect->get_handler_player(), 0); return FALSE; } case 2: { returns.ivalue[0] &= 0x1f1f1f1f; if(returns.ivalue[0] == 0) returns.ivalue[0] = 0x80; if(core.units.begin()->peffect->get_handler_player() == 0) { core.units.begin()->peffect->value = returns.ivalue[0]; player[0].disabled_location |= returns.ivalue[0] & 0x1f1f; player[1].disabled_location |= (returns.ivalue[0] >> 16) & 0x1f1f; } else { core.units.begin()->peffect->value = ((returns.ivalue[0] << 16) | (returns.ivalue[0] >> 16)); player[1].disabled_location |= returns.ivalue[0] & 0x1f1f; player[0].disabled_location |= (returns.ivalue[0] >> 16) & 0x1f1f; } core.units.begin()->step = 0; return FALSE; } case 3: { if(core.extraz_effects.count == 0) { core.units.begin()->step = 4; return FALSE; } effect* peffect = core.extraz_effects[0]; core.units.begin()->peffect = peffect; core.extraz_effects.remove_item(0); int32 p = peffect->get_handler_player(); int32 loc = (peffect->code == EFFECT_USE_EXTRA_MZONE) ? LOCATION_MZONE : LOCATION_SZONE; if((loc == LOCATION_MZONE && ((player[p].disabled_location & 0x1f) == 0x1f)) || (loc == LOCATION_SZONE && ((player[p].disabled_location & 0x1f00) == 0x1f00))) { core.units.begin()->step = 2; return FALSE; } int32 val = peffect->get_value(); int32 count1 = (val & 0xffff) - field_used_count[(val >> 16) & 0x1f]; uint32 flag = 0; int32 count2 = get_useable_count(p, loc, PLAYER_NONE, 0, &flag); if(count1 > count2) count1 = count2; if(count1 == 0) { core.units.begin()->step = 4; return FALSE; } core.units.begin()->arg1 = count1; if(loc == LOCATION_SZONE) flag = ((flag << 8) & 0xff00) | 0xffff00ff; else flag = (flag & 0xff) | 0xffffff00; flag |= 0xe0e0e0e0; add_process(PROCESSOR_SELECT_DISFIELD, 0, 0, 0, p + (count1 << 16), flag); return FALSE; } case 4: { uint32 count1 = core.units.begin()->arg1; uint32 selflag = 0; uint8 s, pt = 0; for(uint32 i = 0; i < count1; ++i) { s = returns.bvalue[pt + 2]; selflag |= 1 << s; pt += 3; } effect* peffect = core.units.begin()->peffect; if(peffect->code == EFFECT_USE_EXTRA_MZONE) player[peffect->get_handler_player()].disabled_location |= selflag; else player[peffect->get_handler_player()].disabled_location |= selflag << 8; peffect->value = ((int32)peffect->value) | (selflag << 16); core.units.begin()->step = 2; return FALSE; } case 5: { if(core.extraz_effects_e.count == 0) { core.units.begin()->step = 6; return FALSE; } effect* peffect = core.extraz_effects_e[0]; core.units.begin()->peffect = peffect; core.extraz_effects_e.remove_item(0); int32 p = peffect->get_handler_player(); int32 loc = (peffect->code == EFFECT_USE_EXTRA_MZONE) ? LOCATION_MZONE : LOCATION_SZONE; if(((loc == LOCATION_MZONE) && ((player[p].disabled_location & 0x1f) == 0x1f)) || ((loc == LOCATION_SZONE) && ((player[p].disabled_location & 0x1f00) == 0x1f00))) { core.units.begin()->step = 4; return FALSE; } int32 val = peffect->get_value(); int32 count1 = (val & 0xffff) - field_used_count[(val >> 16) & 0x1f]; uint32 flag = 0; int32 count2 = get_useable_count(p, loc, PLAYER_NONE, 0, &flag); if(count1 > count2) count1 = count2; if(count1 == 0) { core.units.begin()->step = 6; return FALSE; } core.units.begin()->arg1 = count1; if(loc == LOCATION_SZONE) flag = ((flag << 8) & 0xff00) | 0xffff00ff; else flag = (flag & 0xff) | 0xffffff00; flag |= 0xe0e0e0e0; add_process(PROCESSOR_SELECT_DISFIELD, 0, 0, 0, p + (count1 << 16), flag); return FALSE; } case 6: { uint32 count1 = core.units.begin()->arg1; uint32 selflag = 0; uint8 s, pt = 0; for(uint32 i = 0; i < count1; ++i) { s = returns.bvalue[pt + 2]; selflag |= 1 << s; pt += 3; } effect* peffect = core.units.begin()->peffect; if(peffect->code == EFFECT_USE_EXTRA_MZONE) player[peffect->get_handler_player()].disabled_location |= selflag; else player[peffect->get_handler_player()].disabled_location |= selflag << 8; peffect->value = ((int32)peffect->value) | (selflag << 16); core.units.begin()->step = 4; return FALSE; } case 7: { uint32 dis = player[0].disabled_location | (player[1].disabled_location << 16); if(dis != (uint32)core.units.begin()->arg2) { pduel->write_buffer8(MSG_FIELD_DISABLED); pduel->write_buffer32(dis); } return TRUE; } } return TRUE; } int32 field::adjust_step(uint16 step) { //win, isable, control, self_des, equip, position, trap_monster switch(step) { case 0: { core.re_adjust = FALSE; return FALSE; } case 1: { //win check uint32 winp = 5, rea = 1; if(player[0].lp <= 0 && player[1].lp > 0) { winp = 1; rea = 1; } if(core.overdraw[0] && !core.overdraw[1]) { winp = 1; rea = 2; } if(player[1].lp <= 0 && player[0].lp > 0) { winp = 0; rea = 1; } if(core.overdraw[1] && !core.overdraw[0]) { winp = 0; rea = 2; } if(player[1].lp <= 0 && player[0].lp <= 0) { winp = PLAYER_NONE; rea = 1; } if(core.overdraw[1] && core.overdraw[0]) { winp = PLAYER_NONE; rea = 2; } if(winp != 5) { pduel->write_buffer8(MSG_WIN); pduel->write_buffer8(winp); pduel->write_buffer8(rea); core.overdraw[0] = core.overdraw[1] = FALSE; core.win_player = 5; core.win_reason = 0; } else if(core.win_player != 5) { pduel->write_buffer8(MSG_WIN); pduel->write_buffer8(core.win_player); pduel->write_buffer8(core.win_reason); core.win_player = 5; core.win_reason = 0; core.overdraw[0] = core.overdraw[1] = FALSE; } return FALSE; } case 2: { //disable check uint8 tp = infos.turn_player; card* pcard; for(uint8 p = 0; p < 2; ++p) { for(uint8 i = 0; i < 5; ++i) { pcard = player[tp].list_mzone[i]; if(pcard) add_to_disable_check_list(pcard); } for(uint8 i = 0; i < 8; ++i) { pcard = player[tp].list_szone[i]; if(pcard) add_to_disable_check_list(pcard); } tp = 1 - tp; } adjust_disable_check_list(); add_process(PROCESSOR_REFRESH_LOC, 0, 0, 0, 0, 0); return FALSE; } case 3: { //trap monster card* pcard; uint8 tp = infos.turn_player; for(uint8 p = 0; p < 2; ++p) { for(uint8 i = 0; i < 5; ++i) { pcard = player[tp].list_mzone[i]; if(!pcard) continue; if((pcard->get_type()&TYPE_TRAPMONSTER) && pcard->is_affected_by_effect(EFFECT_DISABLE_TRAPMONSTER)) { pcard->reset(RESET_TURN_SET, RESET_EVENT); refresh_location_info_instant(); move_to_field(pcard, tp, tp, LOCATION_SZONE, pcard->current.position); core.re_adjust = TRUE; } } tp = 1 - tp; } return FALSE; } case 4: { //remove brainwashing effect_set eset; uint32 res = 0; if(core.global_flag & GLOBALFLAG_BRAINWASHING_CHECK) { filter_field_effect(EFFECT_REMOVE_BRAINWASHING, &eset, FALSE); res = eset.size() ? TRUE : FALSE; if(res) { card* pcard; for(uint8 p = 0; p < 2; ++p) { for(uint8 i = 0; i < 5; ++i) { pcard = player[p].list_mzone[i]; // remove EFFECT_SET_CONTROL if(pcard && pcard->is_affected_by_effect(EFFECT_REMOVE_BRAINWASHING)) pcard->reset(EFFECT_SET_CONTROL, RESET_CODE); } } } core.remove_brainwashing = res; } return FALSE; } case 5: { //1-5 control card* pcard; uint8 cur, ref; core.control_adjust_set[0].clear(); core.control_adjust_set[1].clear(); for(uint8 p = 0; p < 2; ++p) { for(uint8 i = 0; i < 5; ++i) { pcard = player[p].list_mzone[i]; if(!pcard) continue; cur = pcard->current.controler; ref = pcard->refresh_control_status(); if(cur != ref && pcard->is_capable_change_control()) { core.control_adjust_set[p].insert(pcard); pcard->operation_param = ref; } } } if(core.control_adjust_set[0].size() || core.control_adjust_set[1].size()) { core.re_adjust = TRUE; add_process(PROCESSOR_CONTROL_ADJUST, 0, 0, 0, 0, 0); } core.units.begin()->step = 7; return FALSE; } case 6: { return FALSE; } case 7: { return FALSE; } case 8: { if(core.selfdes_disabled) { core.units.begin()->step = 10; return FALSE; } //self destroy adjust_self_destroy_set(); return FALSE; } case 9: { return FALSE; } case 10: { //equip check uint8 tp = infos.turn_player; card* pcard; core.destroy_set.clear(); for(uint8 p = 0; p < 2; ++p) { for(uint8 i = 0; i < 5; ++i) { pcard = player[tp].list_szone[i]; if(pcard && pcard->equiping_target && !pcard->is_affected_by_effect(EFFECT_EQUIP_LIMIT, pcard->equiping_target)) core.destroy_set.insert(pcard); } tp = 1 - tp; } if(core.destroy_set.size()) { core.re_adjust = TRUE; destroy(&core.destroy_set, 0, REASON_RULE, PLAYER_NONE); } return FALSE; } case 11: { //position uint32 tp = infos.turn_player, pos; card* pcard; card_set pos_adjust; effect_set eset; for(uint8 p = 0; p < 2; ++p) { for(uint8 i = 0; i < 5; ++i) { pcard = player[tp].list_mzone[i]; if(!pcard || pcard->is_affected_by_effect(EFFECT_CANNOT_CHANGE_POS_E)) continue; eset.clear(); pcard->filter_effect(EFFECT_SET_POSITION, &eset); if(eset.size()) { pos = eset.get_last()->get_value(); if((pos & 0xff) != pcard->current.position) { pos_adjust.insert(pcard); pcard->operation_param = pos; if(pcard->is_status(STATUS_JUST_POS)) pcard->set_status(STATUS_CONTINUOUS_POS, TRUE); else pcard->set_status(STATUS_CONTINUOUS_POS, FALSE); } else pcard->set_status(STATUS_CONTINUOUS_POS, FALSE); pcard->set_status(STATUS_JUST_POS, FALSE); } } tp = 1 - tp; } if(pos_adjust.size()) { core.re_adjust = TRUE; group* ng = pduel->new_group(); ng->container.swap(pos_adjust); ng->is_readonly = TRUE; add_process(PROCESSOR_CHANGEPOS, 0, 0, ng, PLAYER_NONE, TRUE); } return FALSE; } case 12: { //shuffle check for(uint32 i = 0; i < player[0].list_hand.size(); ++i) { card* pcard = player[0].list_hand[i]; effect* pub = pcard->is_affected_by_effect(EFFECT_PUBLIC); if(!pub && pcard->is_position(POS_FACEUP)) core.shuffle_hand_check[0] = TRUE; pcard->current.position = pub ? POS_FACEUP : POS_FACEDOWN; } for(uint32 i = 0; i < player[1].list_hand.size(); ++i) { card* pcard = player[1].list_hand[i]; effect* pub = pcard->is_affected_by_effect(EFFECT_PUBLIC); if(!pub && pcard->is_position(POS_FACEUP)) core.shuffle_hand_check[1] = TRUE; pcard->current.position = pub ? POS_FACEUP : POS_FACEDOWN; } if(core.shuffle_hand_check[infos.turn_player]) shuffle(infos.turn_player, LOCATION_HAND); if(core.shuffle_hand_check[1 - infos.turn_player]) shuffle(1 - infos.turn_player, LOCATION_HAND); return FALSE; } case 13: { //reverse_deck effect_set eset; uint32 res = 0; if(core.global_flag & GLOBALFLAG_DECK_REVERSE_CHECK) { filter_field_effect(EFFECT_REVERSE_DECK, &eset, FALSE); res = eset.size() ? TRUE : FALSE; if(core.deck_reversed ^ res) { reverse_deck(0); reverse_deck(1); pduel->write_buffer8(MSG_REVERSE_DECK); if(res) { if(player[0].list_main.size()) { card* ptop = player[0].list_main.back(); pduel->write_buffer8(MSG_DECK_TOP); pduel->write_buffer8(0); pduel->write_buffer8(0); if(ptop->current.position != POS_FACEUP_DEFENCE) pduel->write_buffer32(ptop->data.code); else pduel->write_buffer32(ptop->data.code | 0x80000000); } if(player[1].list_main.size()) { card* ptop = player[1].list_main.back(); pduel->write_buffer8(MSG_DECK_TOP); pduel->write_buffer8(1); pduel->write_buffer8(0); if(ptop->current.position != POS_FACEUP_DEFENCE) pduel->write_buffer32(ptop->data.code); else pduel->write_buffer32(ptop->data.code | 0x80000000); } } } core.deck_reversed = res; } return FALSE; } case 14: { //attack cancel card* attacker = core.attacker; if(!attacker) return FALSE; if(attacker->is_affected_by_effect(EFFECT_CANNOT_ATTACK)) attacker->set_status(STATUS_ATTACK_CANCELED, TRUE); if(core.attack_rollback) return FALSE; for(uint32 i = 0; i < 5; ++i) { card* pcard = player[1 - infos.turn_player].list_mzone[i]; if(pcard) { if(!core.opp_mzone[i] || core.opp_mzone[i] != pcard->fieldid_r) { core.attack_rollback = TRUE; break; } } else { if(core.opp_mzone[i]) { core.attack_rollback = TRUE; break; } } } return FALSE; } case 15: { raise_event((card*)0, EVENT_ADJUST, 0, 0, PLAYER_NONE, PLAYER_NONE, 0); process_instant_event(); return FALSE; } case 16: { if(core.re_adjust) { core.units.begin()->step = -1; return FALSE; } if(core.shuffle_hand_check[0]) shuffle(0, LOCATION_HAND); if(core.shuffle_hand_check[1]) shuffle(1, LOCATION_HAND); if(core.shuffle_deck_check[0]) shuffle(0, LOCATION_DECK); if(core.shuffle_deck_check[1]) shuffle(1, LOCATION_DECK); return TRUE; } } return TRUE; }
--- components/crash/content/app/crashpad.cc.orig 2019-04-30 22:22:41 UTC +++ components/crash/content/app/crashpad.cc @@ -104,6 +104,12 @@ void InitializeCrashpadImpl(bool initial_client, const base::FilePath& exe_path, const std::vector<std::string>& initial_arguments, bool embedded_handler) { + +#if defined(OS_BSD) + NOTIMPLEMENTED(); + return; +#endif + static bool initialized = false; DCHECK(!initialized); initialized = true; @@ -124,7 +130,7 @@ void InitializeCrashpadImpl(bool initial_client, DCHECK(browser_process || process_type == "Chrome Installer" || process_type == "notification-helper" || process_type == "GCPW Installer" || process_type == "GCPW DLL"); -#elif defined(OS_LINUX) || defined(OS_ANDROID) +#elif defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_BSD) DCHECK(browser_process); #else #error Port. @@ -192,7 +198,7 @@ void InitializeCrashpadImpl(bool initial_client, // other "main, first process" to initialize things. There is no "relauncher" // on Windows, so this is synonymous with initial_client. const bool should_initialize_database_and_set_upload_policy = initial_client; -#elif defined(OS_LINUX) || defined(OS_ANDROID) +#elif defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_BSD) const bool should_initialize_database_and_set_upload_policy = browser_process; #endif if (should_initialize_database_and_set_upload_policy) { @@ -272,7 +278,9 @@ bool GetUploadsEnabled() { #if !defined(OS_ANDROID) void DumpWithoutCrashing() { +#if !defined(OS_BSD) CRASHPAD_SIMULATE_CRASH(); +#endif } #endif
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dr. Frank Celler //////////////////////////////////////////////////////////////////////////////// #include "MMFilesDatafile.h" #include "ApplicationFeatures/PageSizeFeature.h" #include "Basics/FileUtils.h" #include "Basics/OpenFilesTracker.h" #include "Basics/StaticStrings.h" #include "Basics/StringUtils.h" #include "Basics/encoding.h" #include "Basics/files.h" #include "Basics/hashes.h" #include "Basics/memory-map.h" #include "Basics/tri-strings.h" #include "Logger/Logger.h" #include "MMFiles/MMFilesDatafileHelper.h" #include "VocBase/ticks.h" #include <sstream> #include <iomanip> using namespace arangodb; using namespace arangodb::basics; namespace { /// @brief create a hex string representation of the value static std::string hexValue(uint64_t value) { static const uint64_t Bits[] = { 56, 48, 40, 32, 24, 16, 8, 0 }; std::string line("0x"); for (uint64_t i = 0; i < 8; ++i) { uint8_t c = static_cast<uint8_t>((static_cast<uint64_t>(value) >> Bits[i]) & 0xFFULL); uint8_t n1 = c >> 4; uint8_t n2 = c & 0x0F; line.push_back((n1 < 10) ? ('0' + n1) : 'A' + n1 - 10); line.push_back((n2 < 10) ? ('0' + n2) : 'A' + n2 - 10); } return line; } /// @brief calculate a CRC value the same way as ArangoDB 2.8 did static TRI_voc_crc_t Crc28(TRI_voc_crc_t crc, void const* data, size_t length) { static TRI_voc_crc_t const CrcPolynomial = 0xEDB88320; unsigned char* current = (unsigned char*) data; while (length--) { crc ^= *current++; for (unsigned int i = 0; i < 8; ++i) { if (crc & 1) { crc = (crc >> 1) ^ CrcPolynomial; } else { crc = crc >> 1; } } } return crc; } /// @brief check if a marker appears to be created by ArangoDB 2.8 static bool IsMarker28(void const* marker, size_t length) { struct Marker28 { uint32_t _size; TRI_voc_crc_t _crc; uint32_t _type; #ifdef TRI_PADDING_32 char _padding_df_marker[4]; #endif TRI_voc_tick_t _tick; }; uint32_t zero = 0; off_t o = offsetof(Marker28, _crc); size_t n = sizeof(TRI_voc_crc_t); char const* ptr = static_cast<char const*>(marker); Marker28 const* m = static_cast<Marker28 const*>(marker); if (m->_size < o + n || (m->_size - o - n > length)) { return false; } TRI_voc_crc_t crc = TRI_InitialCrc32(); crc = Crc28(crc, ptr, o); crc = Crc28(crc, (char*) &zero, n); crc = Crc28(crc, ptr + o + n, m->_size - o - n); crc = TRI_FinalCrc32(crc); return crc == m->_crc; } /// @brief calculates the actual CRC of a marker, without bounds checks static TRI_voc_crc_t CalculateCrcValue(MMFilesMarker const* marker) { uint32_t zero = 0; off_t o = marker->offsetOfCrc(); size_t n = sizeof(TRI_voc_crc_t); char const* ptr = reinterpret_cast<char const*>(marker); TRI_voc_crc_t crc = TRI_InitialCrc32(); crc = TRI_BlockCrc32(crc, ptr, o); crc = TRI_BlockCrc32(crc, (char*)&zero, n); crc = TRI_BlockCrc32(crc, ptr + o + n, marker->getSize() - o - n); crc = TRI_FinalCrc32(crc); return crc; } /// @brief checks a CRC of a marker, with bounds checks static bool CheckCrcMarker(MMFilesMarker const* marker, char const* end) { uint32_t const size = marker->getSize(); if (size < sizeof(MMFilesMarker)) { return false; } if (reinterpret_cast<char const*>(marker) + size > end) { return false; } auto expected = CalculateCrcValue(marker); return marker->getCrc() == expected; } //////////////////////////////////////////////////////////////////////////////// /// @brief extract the numeric part from a filename /// the filename must look like this: /.*type-abc\.ending$/, where abc is /// a number, and type and ending are arbitrary letters //////////////////////////////////////////////////////////////////////////////// static uint64_t GetNumericFilenamePart(char const* filename) { char const* pos1 = strrchr(filename, '.'); if (pos1 == nullptr) { return 0; } char const* pos2 = strrchr(filename, '-'); if (pos2 == nullptr || pos2 > pos1) { return 0; } return StringUtils::uint64(pos2 + 1, pos1 - pos2 - 1); } } //////////////////////////////////////////////////////////////////////////////// /// @brief creates a new anonymous datafile /// /// this is only supported on certain platforms (Linux, MacOS) //////////////////////////////////////////////////////////////////////////////// #ifdef TRI_HAVE_ANONYMOUS_MMAP static MMFilesDatafile* CreateAnonymousDatafile(TRI_voc_fid_t fid, uint32_t maximalSize) { #ifdef TRI_MMAP_ANONYMOUS // fd -1 is required for "real" anonymous regions int fd = -1; int flags = TRI_MMAP_ANONYMOUS | MAP_SHARED; #else // ugly workaround if MAP_ANONYMOUS is not available int fd = TRI_TRACKED_OPEN_FILE("/dev/zero", O_RDWR | TRI_O_CLOEXEC); if (fd == -1) { return nullptr; } int flags = MAP_PRIVATE; #endif // memory map the data void* data; void* mmHandle; int res = TRI_MMFile(nullptr, maximalSize, PROT_WRITE | PROT_READ, flags, fd, &mmHandle, 0, &data); #ifdef MAP_ANONYMOUS // nothing to do #else // close auxilliary file TRI_TRACKED_CLOSE_FILE(fd); fd = -1; #endif if (res != TRI_ERROR_NO_ERROR) { TRI_set_errno(res); LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "cannot memory map anonymous region: " << TRI_last_error(); LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "The database directory might reside on a shared folder " "(VirtualBox, VMWare) or an NFS " "mounted volume which does not allow memory mapped files."; return nullptr; } return new MMFilesDatafile(StaticStrings::Empty, fd, mmHandle, maximalSize, 0, fid, static_cast<char*>(data)); } #endif //////////////////////////////////////////////////////////////////////////////// /// @brief creates a new physical datafile //////////////////////////////////////////////////////////////////////////////// static MMFilesDatafile* CreatePhysicalDatafile(std::string const& filename, TRI_voc_fid_t fid, uint32_t maximalSize) { TRI_ASSERT(!filename.empty()); int fd = TRI_CreateDatafile(filename, maximalSize); if (fd < 0) { // an error occurred return nullptr; } // memory map the data void* data; void* mmHandle; int flags = MAP_SHARED; #ifdef __linux__ // try populating the mapping already flags |= MAP_POPULATE; #endif int res = TRI_MMFile(nullptr, maximalSize, PROT_WRITE | PROT_READ, flags, fd, &mmHandle, 0, &data); if (res != TRI_ERROR_NO_ERROR) { TRI_set_errno(res); TRI_TRACKED_CLOSE_FILE(fd); // remove empty file TRI_UnlinkFile(filename.c_str()); LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "cannot memory map file '" << filename << "': '" << TRI_errno_string(res) << "'"; LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "The database directory might reside on a shared folder " "(VirtualBox, VMWare) or an NFS-mounted volume which does not allow memory mapped files."; return nullptr; } // create datafile structure try { return new MMFilesDatafile(filename, fd, mmHandle, maximalSize, 0, fid, static_cast<char*>(data)); } catch (...) { TRI_TRACKED_CLOSE_FILE(fd); return nullptr; } } /// @brief whether or not a datafile is empty int MMFilesDatafile::judge(std::string const& filename) { off_t filesize = basics::FileUtils::size(filename); if (filesize == 0) { // empty logfile return TRI_ERROR_ARANGO_DATAFILE_EMPTY; } if (filesize < static_cast<off_t>(256 * sizeof(uint64_t))) { // too small return TRI_ERROR_ARANGO_DATAFILE_UNREADABLE; } int fd = TRI_TRACKED_OPEN_FILE(filename.c_str(), O_RDONLY | TRI_O_CLOEXEC); if (fd < 0) { return TRI_ERROR_ARANGO_DATAFILE_UNREADABLE; } uint64_t buffer[256]; if (!TRI_ReadPointer(fd, &buffer, 256 * sizeof(uint64_t))) { TRI_TRACKED_CLOSE_FILE(fd); return TRI_ERROR_ARANGO_DATAFILE_UNREADABLE; } uint64_t* ptr = buffer; uint64_t* end = buffer + 256; while (ptr < end) { if (*ptr != 0) { TRI_TRACKED_CLOSE_FILE(fd); return TRI_ERROR_NO_ERROR; } ++ptr; } TRI_TRACKED_CLOSE_FILE(fd); return TRI_ERROR_ARANGO_DATAFILE_EMPTY; } /// @brief creates either an anonymous or a physical datafile MMFilesDatafile* MMFilesDatafile::create(std::string const& filename, TRI_voc_fid_t fid, uint32_t maximalSize, bool withInitialMarkers) { size_t pageSize = PageSizeFeature::getPageSize(); TRI_ASSERT(pageSize >= 256); // use multiples of page-size maximalSize = (uint32_t)(((maximalSize + pageSize - 1) / pageSize) * pageSize); // sanity check maximal size if (sizeof(MMFilesDatafileHeaderMarker) + sizeof(MMFilesDatafileFooterMarker) > maximalSize) { LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "cannot create datafile, maximal size '" << maximalSize << "' is too small"; TRI_set_errno(TRI_ERROR_ARANGO_MAXIMAL_SIZE_TOO_SMALL); return nullptr; } // create either an anonymous or a physical datafile std::unique_ptr<MMFilesDatafile> datafile; if (filename.empty()) { #ifdef TRI_HAVE_ANONYMOUS_MMAP datafile.reset(CreateAnonymousDatafile(fid, maximalSize)); #endif } else { datafile.reset(CreatePhysicalDatafile(filename, fid, maximalSize)); } if (datafile == nullptr) { // an error occurred during creation return nullptr; } datafile->setState(TRI_DF_STATE_WRITE); if (withInitialMarkers) { int res = datafile->writeInitialHeaderMarker(fid, maximalSize); if (res != TRI_ERROR_NO_ERROR) { LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "cannot write header to datafile '" << datafile->getName() << "'"; TRI_UNMMFile(const_cast<char*>(datafile->data()), datafile->initSize(), datafile->fd(), &datafile->_mmHandle); datafile->close(); return nullptr; } } LOG_TOPIC(DEBUG, arangodb::Logger::DATAFILES) << "created datafile '" << datafile->getName() << "' of size " << maximalSize << " and page-size " << pageSize; return datafile.release(); } //////////////////////////////////////////////////////////////////////////////// /// @brief returns the name for a marker //////////////////////////////////////////////////////////////////////////////// char const* TRI_NameMarkerDatafile(MMFilesMarkerType type) { switch (type) { // general markers case TRI_DF_MARKER_HEADER: return "datafile header"; case TRI_DF_MARKER_FOOTER: return "footer"; case TRI_DF_MARKER_BLANK: return "blank marker (used when repairing datafiles)"; case TRI_DF_MARKER_COL_HEADER: return "collection header"; case TRI_DF_MARKER_PROLOGUE: return "prologue"; case TRI_DF_MARKER_VPACK_DOCUMENT: return "document"; case TRI_DF_MARKER_VPACK_REMOVE: return "remove document"; case TRI_DF_MARKER_VPACK_CREATE_COLLECTION: return "create collection"; case TRI_DF_MARKER_VPACK_DROP_COLLECTION: return "drop collection"; case TRI_DF_MARKER_VPACK_RENAME_COLLECTION: return "rename collection"; case TRI_DF_MARKER_VPACK_CHANGE_COLLECTION: return "change collection"; case TRI_DF_MARKER_VPACK_CREATE_INDEX: return "create index"; case TRI_DF_MARKER_VPACK_DROP_INDEX: return "drop index"; case TRI_DF_MARKER_VPACK_CREATE_DATABASE: return "create database"; case TRI_DF_MARKER_VPACK_DROP_DATABASE: return "drop database"; case TRI_DF_MARKER_VPACK_BEGIN_TRANSACTION: return "begin transaction"; case TRI_DF_MARKER_VPACK_COMMIT_TRANSACTION: return "commit transaction"; case TRI_DF_MARKER_VPACK_ABORT_TRANSACTION: return "abort transaction"; case TRI_DF_MARKER_VPACK_CREATE_VIEW: return "create view"; case TRI_DF_MARKER_VPACK_DROP_VIEW: return "drop view"; case TRI_DF_MARKER_VPACK_CHANGE_VIEW: return "change view"; default: return "unknown"; } } //////////////////////////////////////////////////////////////////////////////// /// @brief checks whether a marker is valid //////////////////////////////////////////////////////////////////////////////// bool TRI_IsValidMarkerDatafile(MMFilesMarker const* marker) { if (marker == nullptr) { return false; } // check marker type MMFilesMarkerType const type = marker->getType(); if (type <= TRI_DF_MARKER_MIN) { // marker type is less than minimum allowed type value return false; } if (type >= TRI_DF_MARKER_MAX) { // marker type is greater than maximum allowed type value return false; } if (marker->getSize() >= MMFilesDatafileHelper::MaximalMarkerSize()) { // a single marker bigger than this limit seems unreasonable // note: this is an arbitrary limit return false; } return true; } /// @brief reserves room for an element, advances the pointer /// note: maximalJournalSize is the collection's maximalJournalSize property, /// which may be different from the size of the current datafile /// some callers do not set the value of maximalJournalSize int MMFilesDatafile::reserveElement(uint32_t size, MMFilesMarker** position, uint32_t maximalJournalSize) { *position = nullptr; size = encoding::alignedSize<uint32_t>(size); if (_state != TRI_DF_STATE_WRITE) { if (_state == TRI_DF_STATE_READ) { LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "cannot reserve marker, datafile is read-only"; return TRI_ERROR_ARANGO_READ_ONLY; } return TRI_ERROR_ARANGO_ILLEGAL_STATE; } // check the maximal size if (size + MMFilesDatafileHelper::JournalOverhead() > _maximalSize) { // marker is bigger than journal size. // adding the marker to this datafile will not work if (maximalJournalSize <= _maximalSize) { // the collection property 'maximalJournalSize' is equal to // or smaller than the size of this datafile // creating a new file and writing the marker into it will not work either return TRI_ERROR_ARANGO_DOCUMENT_TOO_LARGE; } // if we get here, the collection's 'maximalJournalSize' property is // higher than the size of this datafile. // maybe the marker will fit into a new datafile with the bigger size? if (size + MMFilesDatafileHelper::JournalOverhead() > maximalJournalSize) { // marker still won't fit return TRI_ERROR_ARANGO_DOCUMENT_TOO_LARGE; } // intentionally falls through } // add the marker, leave enough room for the footer if (_currentSize + size + _footerSize > _maximalSize) { _lastError = TRI_set_errno(TRI_ERROR_ARANGO_DATAFILE_FULL); _full = true; LOG_TOPIC(TRACE, arangodb::Logger::DATAFILES) << "cannot write marker, not enough space"; return TRI_ERROR_ARANGO_DATAFILE_FULL; } *position = reinterpret_cast<MMFilesMarker*>(_next); TRI_ASSERT(*position != nullptr); advanceWritePosition(size); return TRI_ERROR_NO_ERROR; } void MMFilesDatafile::sequentialAccess() { TRI_MMFileAdvise(_data, _initSize, TRI_MADVISE_SEQUENTIAL); } void MMFilesDatafile::randomAccess() { TRI_MMFileAdvise(_data, _initSize, TRI_MADVISE_RANDOM); } void MMFilesDatafile::willNeed() { TRI_MMFileAdvise(_data, _initSize, TRI_MADVISE_WILLNEED); } void MMFilesDatafile::dontNeed() { TRI_MMFileAdvise(_data, _initSize, TRI_MADVISE_DONTNEED); } bool MMFilesDatafile::readOnly() { return (TRI_ProtectMMFile(_data, _initSize, PROT_READ, _fd) == TRI_ERROR_NO_ERROR); } bool MMFilesDatafile::readWrite() { return (TRI_ProtectMMFile(_data, _initSize, PROT_READ | PROT_WRITE, _fd) == TRI_ERROR_NO_ERROR); } void MMFilesDatafile::dontDump() { TRI_MMFileAdvise(_data, _initSize, TRI_MADVISE_DONTDUMP); } int MMFilesDatafile::lockInMemory() { TRI_ASSERT(!_lockedInMemory); int res = TRI_MMFileLock(_data, _initSize); if (res == TRI_ERROR_NO_ERROR) { _lockedInMemory = true; } return res; } int MMFilesDatafile::unlockFromMemory() { if (!_lockedInMemory) { return TRI_ERROR_NO_ERROR; } int res = TRI_MMFileUnlock(_data, _initSize); if (res == TRI_ERROR_NO_ERROR) { _lockedInMemory = false; } return res; } /// @brief writes a marker to the datafile /// this function will write the marker as-is, without any CRC or tick updates int MMFilesDatafile::writeElement(void* position, MMFilesMarker const* marker) { TRI_ASSERT(marker->getTick() > 0); TRI_ASSERT(marker->getSize() > 0); TRI_UpdateTicksDatafile(this, marker); if (_state != TRI_DF_STATE_WRITE) { if (_state == TRI_DF_STATE_READ) { LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "cannot write marker, datafile is read-only"; return TRI_ERROR_ARANGO_READ_ONLY; } return TRI_ERROR_ARANGO_ILLEGAL_STATE; } TRI_ASSERT(position != nullptr); // out of bounds check for writing into a datafile if (position == nullptr || position < (void*)_data || position >= (void*)(_data + maximalSize())) { LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "logic error. writing out of bounds of datafile '" << getName() << "'"; return TRI_ERROR_ARANGO_ILLEGAL_STATE; } memcpy(position, marker, static_cast<size_t>(marker->getSize())); TRI_IF_FAILURE("BreakHeaderMarker") { #ifdef ARANGODB_ENABLE_FAILURE_TESTS if (marker->getType() == TRI_DF_MARKER_HEADER && getName().find("logfile-") == std::string::npos) { // intentionally corrupt the marker reinterpret_cast<MMFilesMarker*>(position)->breakIt(); } #endif } return TRI_ERROR_NO_ERROR; } //////////////////////////////////////////////////////////////////////////////// /// @brief update tick values for a datafile //////////////////////////////////////////////////////////////////////////////// void TRI_UpdateTicksDatafile(MMFilesDatafile* datafile, MMFilesMarker const* marker) { MMFilesMarkerType const type = marker->getType(); if (type != TRI_DF_MARKER_HEADER && type != TRI_DF_MARKER_FOOTER && type != TRI_DF_MARKER_COL_HEADER) { // every marker but headers / footers counts TRI_voc_tick_t tick = marker->getTick(); if (datafile->_tickMin == 0) { datafile->_tickMin = tick; } if (datafile->_tickMax < tick) { datafile->_tickMax = tick; } if (datafile->_dataMin == 0) { datafile->_dataMin = tick; } if (datafile->_dataMax < tick) { datafile->_dataMax = tick; } } } //////////////////////////////////////////////////////////////////////////////// /// @brief checksums and writes a marker to the datafile //////////////////////////////////////////////////////////////////////////////// int MMFilesDatafile::writeCrcElement(void* position, MMFilesMarker* marker) { TRI_ASSERT(marker->getTick() != 0); if (isPhysical()) { TRI_voc_crc_t crc = TRI_InitialCrc32(); crc = TRI_BlockCrc32(crc, (char const*)marker, marker->getSize()); marker->setCrc(TRI_FinalCrc32(crc)); } return writeElement(position, marker); } //////////////////////////////////////////////////////////////////////////////// /// @brief iterates over a datafile /// also may set datafile's min/max tick values /// deprecated //////////////////////////////////////////////////////////////////////////////// bool TRI_IterateDatafile(MMFilesDatafile* datafile, bool (*iterator)(MMFilesMarker const*, void*, MMFilesDatafile*), void* data) { TRI_ASSERT(iterator != nullptr); LOG_TOPIC(DEBUG, arangodb::Logger::DATAFILES) << "iterating over datafile '" << datafile->getName() << "', fid: " << datafile->fid() << ", size: " << datafile->currentSize(); char const* ptr = datafile->data(); char const* end = ptr + datafile->currentSize(); if (datafile->state() != TRI_DF_STATE_READ && datafile->state() != TRI_DF_STATE_WRITE) { TRI_set_errno(TRI_ERROR_ARANGO_ILLEGAL_STATE); return false; } TRI_voc_tick_t maxTick = 0; TRI_DEFER(TRI_UpdateTickServer(maxTick)); while (ptr < end) { auto const* marker = reinterpret_cast<MMFilesMarker const*>(ptr); if (marker->getSize() == 0) { return true; } TRI_voc_tick_t tick = marker->getTick(); if (tick > maxTick) { maxTick = tick; } // update the tick statistics TRI_UpdateTicksDatafile(datafile, marker); if (!iterator(marker, data, datafile)) { return false; } ptr += MMFilesDatafileHelper::AlignedMarkerSize<size_t>(marker); } return true; } /// @brief iterates over a datafile /// also may set datafile's min/max tick values bool TRI_IterateDatafile(MMFilesDatafile* datafile, std::function<bool(MMFilesMarker const*, MMFilesDatafile*)> const& cb) { LOG_TOPIC(DEBUG, arangodb::Logger::DATAFILES) << "iterating over datafile '" << datafile->getName() << "', fid: " << datafile->fid() << ", size: " << datafile->currentSize(); char const* ptr = datafile->data(); char const* end = ptr + datafile->currentSize(); if (datafile->state() != TRI_DF_STATE_READ && datafile->state() != TRI_DF_STATE_WRITE) { TRI_set_errno(TRI_ERROR_ARANGO_ILLEGAL_STATE); return false; } TRI_voc_tick_t maxTick = 0; TRI_DEFER(TRI_UpdateTickServer(maxTick)); while (ptr < end) { auto const* marker = reinterpret_cast<MMFilesMarker const*>(ptr); if (marker->getSize() == 0) { return true; } TRI_voc_tick_t tick = marker->getTick(); if (tick > maxTick) { maxTick = tick; } // update the tick statistics TRI_UpdateTicksDatafile(datafile, marker); if (!cb(marker, datafile)) { return false; } ptr += MMFilesDatafileHelper::AlignedMarkerSize<size_t>(marker); } return true; } /// @brief renames a datafile int MMFilesDatafile::rename(std::string const& filename) { // this function must not be called for non-physical datafiles TRI_ASSERT(isPhysical()); TRI_ASSERT(!filename.empty()); if (TRI_ExistsFile(filename.c_str())) { LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "cannot overwrite datafile '" << filename << "'"; _lastError = TRI_ERROR_ARANGO_DATAFILE_ALREADY_EXISTS; return TRI_ERROR_ARANGO_DATAFILE_ALREADY_EXISTS; } int res = TRI_RenameFile(_filename.c_str(), filename.c_str()); if (res != TRI_ERROR_NO_ERROR) { _state = TRI_DF_STATE_RENAME_ERROR; _lastError = TRI_ERROR_SYS_ERROR; return res; } _filename = filename; return TRI_ERROR_NO_ERROR; } /// @brief seals a datafile, writes a footer, sets it to read-only int MMFilesDatafile::seal() { if (_state == TRI_DF_STATE_READ) { return TRI_ERROR_ARANGO_READ_ONLY; } if (_state != TRI_DF_STATE_WRITE) { return TRI_ERROR_ARANGO_ILLEGAL_STATE; } if (_isSealed) { return TRI_ERROR_ARANGO_DATAFILE_SEALED; } // set a proper tick value if (_tickMax == 0) { _tickMax = TRI_NewTickServer(); } // create the footer MMFilesDatafileFooterMarker footer = MMFilesDatafileHelper::CreateFooterMarker(_tickMax); // reserve space and write footer to file _footerSize = 0; MMFilesMarker* position; int res = reserveElement(footer.base.getSize(), &position, 0); if (res == TRI_ERROR_NO_ERROR) { TRI_ASSERT(position != nullptr); res = writeCrcElement(position, &footer.base); } if (res != TRI_ERROR_NO_ERROR) { return res; } // sync file TRI_ASSERT(_data != nullptr); TRI_ASSERT(_written != nullptr); res = this->sync(_synced, reinterpret_cast<char const*>(_data) + _currentSize); if (res != TRI_ERROR_NO_ERROR) { LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "msync failed with: " << TRI_errno_string(res); } // intentionally ignore return value of protection here because this call // would only restrict further file accesses (which is not required // for ArangoDB to work) readOnly(); if (res != TRI_ERROR_NO_ERROR) { return _lastError; } // seal datafile _isSealed = true; _state = TRI_DF_STATE_READ; // note: _initSize must remain constant //TRI_ASSERT(_initSize == _maximalSize); _maximalSize = _currentSize; if (isPhysical()) { // From now on we predict random access (until collection or compaction): randomAccess(); } return TRI_ERROR_NO_ERROR; } /// @brief truncates a datafile and seals it /// this is called from the recovery procedure only int MMFilesDatafile::truncate(std::string const& path, uint32_t position) { // this function must not be called for non-physical datafiles TRI_ASSERT(!path.empty()); std::unique_ptr<MMFilesDatafile> datafile(MMFilesDatafile::openHelper(path, true)); if (datafile == nullptr) { return TRI_ERROR_ARANGO_DATAFILE_UNREADABLE; } return datafile->truncateAndSeal(position); } /// @brief try to repair a datafile bool MMFilesDatafile::tryRepair(std::string const& path) { // this function must not be called for non-physical datafiles TRI_ASSERT(!path.empty()); std::unique_ptr<MMFilesDatafile> datafile(MMFilesDatafile::openHelper(path, true)); if (datafile == nullptr) { return false; } // set to read/write access if (!datafile->readWrite()) { LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "unable to change file protection for datafile '" << datafile->getName() << "'"; return false; } return datafile->tryRepair(); } //////////////////////////////////////////////////////////////////////////////// /// @brief diagnoses a marker //////////////////////////////////////////////////////////////////////////////// static std::string DiagnoseMarker(MMFilesMarker const* marker, char const* end) { std::ostringstream result; if (marker == nullptr) { return "marker is undefined. should not happen"; } // check marker type MMFilesMarkerType type = marker->getType(); if (type <= TRI_DF_MARKER_MIN) { // marker type is less than minimum allowed type value result << "marker type value (" << static_cast<int>(type) << ") is wrong. expecting value higher than " << TRI_DF_MARKER_MIN; return result.str(); } if (type >= TRI_DF_MARKER_MAX) { // marker type is greater than maximum allowed type value result << "marker type value (" << static_cast<int>(type) << ") is wrong. expecting value less than " << TRI_DF_MARKER_MAX; return result.str(); } uint32_t size = marker->getSize(); if (size >= MMFilesDatafileHelper::MaximalMarkerSize()) { // a single marker bigger than this size seems unreasonable // note: this is an arbitrary limit result << "marker size value (" << size << ") is wrong. expecting value less than " << MMFilesDatafileHelper::MaximalMarkerSize(); return result.str(); } if (size < sizeof(MMFilesMarker)) { result << "marker size is too small (" << size << "). expecting at least " << sizeof(MMFilesMarker) << " bytes"; return result.str(); } if (reinterpret_cast<char const*>(marker) + size > end) { return "marker size is beyond end of datafile"; } TRI_voc_crc_t crc = CalculateCrcValue(marker); if (marker->getCrc() == crc) { return "crc checksum is correct"; } result << "crc checksum (hex " << std::hex << marker->getCrc() << ") is wrong. expecting (hex " << std::hex << crc << ")"; return result.str(); } MMFilesDatafile::MMFilesDatafile(std::string const& filename, int fd, void* mmHandle, uint32_t maximalSize, uint32_t currentSize, TRI_voc_fid_t fid, char* data) : _filename(filename), _fid(fid), _state(TRI_DF_STATE_READ), _fd(fd), _mmHandle(mmHandle), _initSize(maximalSize), _maximalSize(maximalSize), _currentSize(currentSize), _footerSize(sizeof(MMFilesDatafileFooterMarker)), _full(false), _isSealed(false), _lockedInMemory(false), _data(data), _next(data + currentSize), _tickMin(0), _tickMax(0), _dataMin(0), _dataMax(0), _lastError(TRI_ERROR_NO_ERROR), _synced(data), _written(nullptr) { // filename is a string for physical datafiles, and NULL for anonymous regions // fd is a positive value for physical datafiles, and -1 for anonymous regions if (filename.empty()) { TRI_ASSERT(fd == -1); } else { TRI_ASSERT(fd >= 0); // Advise OS that sequential access is going to happen: sequentialAccess(); } dontDump(); } MMFilesDatafile::~MMFilesDatafile() { try { this->close(); } catch (...) { // silently continue as this is the destructor } } /// @brief return the name of a datafile std::string MMFilesDatafile::getName() const { if (_filename.empty()) { // anonymous regions do not have a filename return "anonymous region"; } // return name of the physical file return _filename; } /// @brief close a datafile int MMFilesDatafile::close() { if (_state == TRI_DF_STATE_READ || _state == TRI_DF_STATE_WRITE || _state == TRI_DF_STATE_OPEN_ERROR) { int res = TRI_UNMMFile(_data, _initSize, _fd, &_mmHandle); if (res != TRI_ERROR_NO_ERROR) { // leave file open here as it will still be memory-mapped LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "munmap failed with: " << res; _state = TRI_DF_STATE_WRITE_ERROR; _lastError = res; return res; } if (isPhysical()) { TRI_ASSERT(_fd >= 0); int res = TRI_TRACKED_CLOSE_FILE(_fd); if (res != TRI_ERROR_NO_ERROR) { LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "unable to close datafile '" << getName() << "': " << res; } } _state = TRI_DF_STATE_CLOSED; _data = nullptr; _next = nullptr; _fd = -1; return TRI_ERROR_NO_ERROR; } if (_state == TRI_DF_STATE_CLOSED) { TRI_ASSERT(_fd == -1); LOG_TOPIC(TRACE, arangodb::Logger::DATAFILES) << "closing an already closed datafile '" << getName() << "'"; return TRI_ERROR_NO_ERROR; } LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "attempting to close datafile with an invalid state"; return TRI_ERROR_ARANGO_ILLEGAL_STATE; } int MMFilesDatafile::sync() { if (_synced < _written) { return sync(_synced, _written); } return TRI_ERROR_NO_ERROR; } /// @brief sync the data of a datafile int MMFilesDatafile::sync(char const* begin, char const* end) { if (!isPhysical()) { // we only need to care about physical datafiles // anonymous regions do not need to be synced return TRI_ERROR_NO_ERROR; } TRI_ASSERT(_fd >= 0); if (begin == end) { // no need to sync return TRI_ERROR_NO_ERROR; } int res = TRI_MSync(_fd, begin, end); if (res != TRI_ERROR_NO_ERROR) { _state = TRI_DF_STATE_WRITE_ERROR; _lastError = res; LOG_TOPIC(ERR, Logger::COLLECTOR) << "msync failed with: " << TRI_errno_string(res); } else { _synced = const_cast<char*>(end); } return res; } /// @brief truncates a datafile /// Create a truncated datafile, seal it and rename the old. int MMFilesDatafile::truncateAndSeal(uint32_t position) { TRI_ERRORBUF; void* data; void* mmHandle; // this function must not be called for non-physical datafiles TRI_ASSERT(isPhysical()); size_t pageSize = PageSizeFeature::getPageSize(); // use multiples of page-size size_t maximalSize = ((position + sizeof(MMFilesDatafileFooterMarker) + pageSize - 1) / pageSize) * pageSize; // sanity check if (sizeof(MMFilesDatafileHeaderMarker) + sizeof(MMFilesDatafileFooterMarker) > maximalSize) { LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "cannot create datafile '" << getName() << "', maximal size " << maximalSize << " is too small"; return TRI_ERROR_ARANGO_MAXIMAL_SIZE_TOO_SMALL; } // open the file std::string filename = getName() + ".new"; int fd = TRI_TRACKED_CREATE_FILE(filename.c_str(), O_CREAT | O_EXCL | O_RDWR | TRI_O_CLOEXEC, S_IRUSR | S_IWUSR); if (fd < 0) { TRI_SYSTEM_ERROR(); LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "cannot create new datafile '" << filename << "': " << TRI_GET_ERRORBUF; return TRI_set_errno(TRI_ERROR_SYS_ERROR); } // go back to the beginning of the file TRI_lseek_t offset = TRI_LSEEK(fd, (TRI_lseek_t)(maximalSize - 1), SEEK_SET); if (offset == (TRI_lseek_t)-1) { TRI_SYSTEM_ERROR(); TRI_set_errno(TRI_ERROR_SYS_ERROR); TRI_TRACKED_CLOSE_FILE(fd); // remove empty file TRI_UnlinkFile(filename.c_str()); LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "cannot seek in new datafile '" << filename << "': " << TRI_GET_ERRORBUF; return TRI_ERROR_SYS_ERROR; } char zero = 0; long written = TRI_WRITE(fd, &zero, 1); if (written < 0) { TRI_SYSTEM_ERROR(); TRI_set_errno(TRI_ERROR_SYS_ERROR); TRI_TRACKED_CLOSE_FILE(fd); // remove empty file TRI_UnlinkFile(filename.c_str()); LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "cannot create datafile '" << filename << "': " << TRI_GET_ERRORBUF; return TRI_ERROR_SYS_ERROR; } // memory map the data int res = TRI_MMFile(nullptr, maximalSize, PROT_WRITE | PROT_READ, MAP_SHARED, fd, &mmHandle, 0, &data); if (res != TRI_ERROR_NO_ERROR) { TRI_SYSTEM_ERROR(); TRI_set_errno(res); TRI_TRACKED_CLOSE_FILE(fd); // remove empty file TRI_UnlinkFile(filename.c_str()); LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "cannot memory map file '" << filename << "': " << TRI_GET_ERRORBUF; LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "The database directory might reside on a shared folder " "(VirtualBox, VMWare) or an NFS " "mounted volume which does not allow memory mapped files."; return TRI_errno(); } // copy the data memcpy(data, _data, position); // patch the datafile structure res = TRI_UNMMFile(_data, _initSize, _fd, &_mmHandle); if (res < 0) { TRI_TRACKED_CLOSE_FILE(_fd); LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "munmap failed with: " << res; return res; } // ............................................................................................. // For windows: Mem mapped files use handles // the datafile->_mmHandle handle object has been closed in the underlying // TRI_UNMMFile(...) call above so we do not need to close it for the // associated file below // ............................................................................................. TRI_TRACKED_CLOSE_FILE(_fd); _data = static_cast<char*>(data); _next = (char*)(data) + position; _currentSize = position; TRI_ASSERT(_initSize == _maximalSize); TRI_ASSERT(maximalSize <= _initSize); _maximalSize = static_cast<uint32_t>(maximalSize); _initSize = static_cast<uint32_t>(maximalSize); _fd = fd; _mmHandle = mmHandle; _state = TRI_DF_STATE_WRITE; _full = false; _isSealed = false; _synced = static_cast<char*>(data); _written = _next; // rename files std::string oldname = _filename + ".corrupted"; res = TRI_RenameFile(_filename.c_str(), oldname.c_str()); if (res != TRI_ERROR_NO_ERROR) { LOG_TOPIC(ERR, Logger::FIXME) << "unable to rename file '" << filename << "' to '" << oldname << "': " << TRI_errno_string(res); return res; } res = TRI_RenameFile(filename.c_str(), _filename.c_str()); if (res != TRI_ERROR_NO_ERROR) { LOG_TOPIC(ERR, Logger::FIXME) << "unable to rename file '" << filename << "' to '" << _filename << "': " << TRI_errno_string(res); return res; } // need to reset the datafile state here to write, otherwise the following // call will return an error _state = TRI_DF_STATE_WRITE; return seal(); } /// @brief checks a datafile bool MMFilesDatafile::check(bool ignoreFailures, bool autoSeal) { // this function must not be called for non-physical datafiles TRI_ASSERT(isPhysical()); LOG_TOPIC(TRACE, arangodb::Logger::DATAFILES) << "checking markers in datafile '" << getName() << "', autoSeal: " << autoSeal; char const* ptr = _data; char const* end = ptr + _currentSize; char const* lastGood = nullptr; uint32_t currentSize = 0; if (_currentSize == 0) { LOG_TOPIC(WARN, arangodb::Logger::DATAFILES) << "current size is 0 in read-only datafile '" << getName() << "', trying to fix"; end = _data + _maximalSize; } TRI_voc_tick_t maxTick = 0; TRI_DEFER(TRI_UpdateTickServer(maxTick)); while (ptr < end) { bool const canRead = (ptr + sizeof(MMFilesMarker) <= end); MMFilesMarker const* marker = reinterpret_cast<MMFilesMarker const*>(ptr); uint32_t const size = marker->getSize(); TRI_voc_tick_t const tick = marker->getTick(); MMFilesMarkerType const type = marker->getType(); if (canRead) { if (size == 0) { LOG_TOPIC(DEBUG, arangodb::Logger::DATAFILES) << "reached end of datafile '" << getName() << "' data, current size " << currentSize << ", autoSeal: " << autoSeal; _currentSize = currentSize; _next = _data + _currentSize; if (autoSeal) { _isSealed = true; } return true; } } if (size < sizeof(MMFilesMarker)) { if (ignoreFailures) { return fix(currentSize); } _lastError = TRI_set_errno(TRI_ERROR_ARANGO_CORRUPTED_DATAFILE); _currentSize = currentSize; _next = _data + _currentSize; _state = TRI_DF_STATE_OPEN_ERROR; LOG_TOPIC(WARN, arangodb::Logger::DATAFILES) << "marker in datafile '" << getName() << "' too small, size " << size << ", should be at least " << sizeof(MMFilesMarker); return false; } // prevent reading over the end of the file if (ptr + size > end) { if (ignoreFailures) { return fix(currentSize); } _lastError = TRI_set_errno(TRI_ERROR_ARANGO_CORRUPTED_DATAFILE); _currentSize = currentSize; _next = _data + _currentSize; _state = TRI_DF_STATE_OPEN_ERROR; LOG_TOPIC(WARN, arangodb::Logger::DATAFILES) << "marker in datafile '" << getName() << "' points with size " << size << " beyond end of file"; if (lastGood != nullptr) { LOG_TOPIC(INFO, arangodb::Logger::DATAFILES) << "last good marker found at: " << hexValue(static_cast<uint64_t>(static_cast<uintptr_t>(lastGood - _data))); } printMarker(marker, static_cast<uint32_t>(end - ptr), _data, end); return false; } // the following sanity check offers some, but not 100% crash-protection // when reading totally corrupted datafiles if (!TRI_IsValidMarkerDatafile(marker)) { if (type == 0 && size < 128) { // ignore markers with type 0 and a small size LOG_TOPIC(WARN, arangodb::Logger::DATAFILES) << "ignoring suspicious marker in datafile '" << getName() << "': type: " << type << ", size: " << size; } else { if (ignoreFailures) { return fix(currentSize); } _lastError = TRI_set_errno(TRI_ERROR_ARANGO_CORRUPTED_DATAFILE); _currentSize = currentSize; _next = _data + _currentSize; _state = TRI_DF_STATE_OPEN_ERROR; LOG_TOPIC(WARN, arangodb::Logger::DATAFILES) << "marker in datafile '" << getName() << "' is corrupt: type: " << type << ", size: " << size; if (lastGood != nullptr) { LOG_TOPIC(INFO, arangodb::Logger::DATAFILES) << "last good marker found at: " << hexValue(static_cast<uint64_t>(static_cast<uintptr_t>(lastGood - _data))); } printMarker(marker, size, _data, end); return false; } } if (type != 0) { bool ok = CheckCrcMarker(marker, end); if (!ok) { // CRC mismatch! bool nextMarkerOk = false; if (size > 0) { auto next = reinterpret_cast<char const*>(marker) + encoding::alignedSize<size_t>(size); auto p = next; if (p < end) { // check if the rest of the datafile is only followed by NULL bytes bool isFollowedByNullBytes = true; while (p < end) { if (*p != '\0') { isFollowedByNullBytes = false; break; } ++p; } if (isFollowedByNullBytes) { // only last marker in datafile was corrupt. fix the datafile in // place LOG_TOPIC(WARN, arangodb::Logger::DATAFILES) << "datafile '" << getName() << "' automatically truncated at last marker"; ignoreFailures = true; } else { // there is some other stuff following. now inspect it... TRI_ASSERT(next <= end); if (next < end) { // there is a next marker auto nextMarker = reinterpret_cast<MMFilesMarker const*>(next); if (nextMarker->getType() != 0 && nextMarker->getSize() >= sizeof(MMFilesMarker) && next + nextMarker->getSize() <= end && TRI_IsValidMarkerDatafile(nextMarker) && CheckCrcMarker(nextMarker, end)) { // next marker looks good. nextMarkerOk = true; } } else { // EOF nextMarkerOk = true; } } } } if (!ignoreFailures) { _lastError = TRI_set_errno(TRI_ERROR_ARANGO_CORRUPTED_DATAFILE); _currentSize = currentSize; _next = _data + _currentSize; _state = TRI_DF_STATE_OPEN_ERROR; LOG_TOPIC(WARN, arangodb::Logger::DATAFILES) << "crc mismatch found in datafile '" << getName() << "' of size " << _maximalSize << ", at position " << currentSize; LOG_TOPIC(WARN, arangodb::Logger::DATAFILES) << "crc mismatch found inside marker of type '" << TRI_NameMarkerDatafile(marker) << "' and size " << size << ". expected crc: " << CalculateCrcValue(marker) << ", actual crc: " << marker->getCrc(); if (lastGood != nullptr) { LOG_TOPIC(INFO, arangodb::Logger::DATAFILES) << "last good marker found at: " << hexValue(static_cast<uint64_t>(static_cast<uintptr_t>(lastGood - _data))); } printMarker(marker, size, _data, end); if (nextMarkerOk) { LOG_TOPIC(INFO, arangodb::Logger::DATAFILES) << "data directly following this marker looks ok so repairing the marker manually may recover it..."; LOG_TOPIC(INFO, arangodb::Logger::DATAFILES) << "to truncate the file at this marker, please restart the server with the parameter '--wal.ignore-logfile-errors true' if the error happening during WAL recovery, or with parameter '--database.ignore-datafile-errors true' if it happened after WAL recovery"; } else { LOG_TOPIC(WARN, arangodb::Logger::DATAFILES) << "data directly following this marker cannot be analyzed"; } return false; } // ignore failures... // truncate return fix(currentSize); } } if (tick > maxTick) { maxTick = tick; } size_t alignedSize = MMFilesDatafileHelper::AlignedMarkerSize<size_t>(marker); currentSize += static_cast<uint32_t>(alignedSize); if (marker->getType() == TRI_DF_MARKER_FOOTER) { LOG_TOPIC(DEBUG, arangodb::Logger::DATAFILES) << "found footer, reached end of datafile '" << getName() << "', current size " << currentSize; _isSealed = true; _currentSize = currentSize; _next = _data + _currentSize; return true; } lastGood = ptr; ptr += alignedSize; } return true; } void MMFilesDatafile::printMarker(MMFilesMarker const* marker, uint32_t size, char const* begin, char const* end) { LOG_TOPIC(INFO, arangodb::Logger::DATAFILES) << "raw marker data following:"; LOG_TOPIC(INFO, arangodb::Logger::DATAFILES) << "type: " << TRI_NameMarkerDatafile(marker) << ", size: " << marker->getSize() << ", crc: " << marker->getCrc(); LOG_TOPIC(INFO, arangodb::Logger::DATAFILES) << "(expected layout: size (4 bytes), crc (4 bytes), type and tick (8 bytes), payload following)"; char const* p = reinterpret_cast<char const*>(marker); char const* e = reinterpret_cast<char const*>(marker) + encoding::alignedSize<size_t>(size); if (e + 16 < end) { // add some extra bytes for following data e += 16; } std::string line; std::string raw; size_t printed = 0; while (p < e) { // print offset line.append(hexValue(static_cast<uint64_t>(static_cast<uintptr_t>(p - begin)))); // print data line.append(": "); for (size_t i = 0; i < 16; ++i) { if (i == 8) { // separate groups of 8 bytes line.push_back(' '); raw.push_back(' '); } if (p >= e) { line.append(" "); } else { uint8_t c = static_cast<uint8_t>(*p++); uint8_t n1 = c >> 4; uint8_t n2 = c & 0x0F; line.push_back((n1 < 10) ? ('0' + n1) : 'A' + n1 - 10); line.push_back((n2 < 10) ? ('0' + n2) : 'A' + n2 - 10); line.push_back(' '); raw.push_back((c < 32 || c >= 127) ? '.' : static_cast<unsigned char>(c)); ++printed; } } LOG_TOPIC(INFO, arangodb::Logger::DATAFILES) << line << " " << raw; line.clear(); raw.clear(); if (printed >= 2048) { LOG_TOPIC(INFO, arangodb::Logger::DATAFILES) << "(output truncated due to excessive length)"; break; } } } /// @brief fixes a corrupted datafile bool MMFilesDatafile::fix(uint32_t currentSize) { LOG_TOPIC(WARN, arangodb::Logger::DATAFILES) << "datafile '" << getName() << "' is corrupted at position " << currentSize; LOG_TOPIC(WARN, arangodb::Logger::DATAFILES) << "setting datafile '" << getName() << "' to read-only and ignoring all data from this file beyond this position"; _currentSize = currentSize; TRI_ASSERT(_initSize == _maximalSize); TRI_ASSERT(currentSize <= _initSize); _maximalSize = static_cast<uint32_t>(currentSize); _next = _data + _currentSize; _full = true; _state = TRI_DF_STATE_READ; _isSealed = true; return true; } /// @brief scans a datafile DatafileScan MMFilesDatafile::scanHelper() { // this function must not be called for non-physical datafiles TRI_ASSERT(isPhysical()); char* ptr = _data; char* end = _data + _currentSize; uint32_t currentSize = 0; DatafileScan scan; scan.currentSize = _currentSize; scan.maximalSize = _maximalSize; if (_currentSize == 0) { end = _data + _maximalSize; } while (ptr < end) { MMFilesMarker* marker = reinterpret_cast<MMFilesMarker*>(ptr); DatafileScanEntry entry; entry.position = static_cast<uint32_t>(ptr - _data); entry.size = marker->getSize(); entry.realSize = static_cast<uint32_t>(MMFilesDatafileHelper::AlignedMarkerSize<size_t>(marker)); entry.tick = marker->getTick(); entry.type = marker->getType(); entry.status = 1; entry.typeName = TRI_NameMarkerDatafile(marker); if (marker->getSize() == 0 && marker->getCrc() == 0 && marker->getType() == 0 && marker->getTick() == 0) { entry.status = 2; scan.endPosition = currentSize; scan.entries.emplace_back(entry); return scan; } ++scan.numberMarkers; if (marker->getSize() == 0) { entry.status = 3; scan.status = 2; scan.endPosition = currentSize; scan.entries.emplace_back(entry); return scan; } if (marker->getSize() < sizeof(MMFilesMarker)) { entry.status = 4; entry.diagnosis = DiagnoseMarker(marker, end); scan.endPosition = currentSize; scan.status = 3; scan.entries.emplace_back(entry); return scan; } if (!TRI_IsValidMarkerDatafile(marker)) { entry.status = 4; entry.diagnosis = DiagnoseMarker(marker, end); scan.endPosition = currentSize; scan.status = 3; scan.entries.emplace_back(entry); return scan; } bool ok = CheckCrcMarker(marker, end); if (!ok) { entry.status = 5; entry.diagnosis = DiagnoseMarker(marker, end); scan.status = 4; } MMFilesMarkerType const type = marker->getType(); if (ok) { if (type == TRI_DF_MARKER_VPACK_DOCUMENT || type == TRI_DF_MARKER_VPACK_REMOVE) { VPackSlice const slice(reinterpret_cast<char const*>(marker) + MMFilesDatafileHelper::VPackOffset(type)); TRI_ASSERT(slice.isObject()); try { entry.key = slice.get(StaticStrings::KeyString).copyString(); } catch (...) { entry.key = "(unable to read value of _key)"; } } } scan.entries.emplace_back(entry); size_t size = MMFilesDatafileHelper::AlignedMarkerSize<size_t>(marker); currentSize += static_cast<uint32_t>(size); if (marker->getType() == TRI_DF_MARKER_FOOTER) { scan.endPosition = currentSize; scan.isSealed = true; return scan; } ptr += size; } return scan; } /// @brief create the initial datafile header marker int MMFilesDatafile::writeInitialHeaderMarker(TRI_voc_fid_t fid, uint32_t maximalSize) { // create the header MMFilesDatafileHeaderMarker header = MMFilesDatafileHelper::CreateHeaderMarker( maximalSize, static_cast<TRI_voc_tick_t>(fid)); // reserve space and write header to file MMFilesMarker* position; int res = reserveElement(header.base.getSize(), &position, 0); if (res == TRI_ERROR_NO_ERROR) { TRI_ASSERT(position != nullptr); res = writeCrcElement(position, &header.base); } return res; } /// @brief tries to repair a datafile bool MMFilesDatafile::tryRepair() { // this function must not be called for non-physical datafiles TRI_ASSERT(isPhysical()); char* ptr = _data; char* end = _data + _currentSize; if (_currentSize == 0) { end = _data + _maximalSize; } uint32_t currentSize = 0; while (ptr < end) { if (ptr + sizeof(MMFilesMarker) > end) { // remaining data chunk is too small return false; } MMFilesMarker* marker = reinterpret_cast<MMFilesMarker*>(ptr); uint32_t const size = marker->getSize(); if (size == 0) { // reached end return true; } if (size < sizeof(MMFilesMarker) || ptr + size > end) { // marker too small or too big return false; } if (!TRI_IsValidMarkerDatafile(marker)) { // unknown marker type return false; } if (marker->getType() != 0) { if (!CheckCrcMarker(marker, end)) { // CRC mismatch! auto next = reinterpret_cast<char const*>(marker) + size; auto p = next; if (p < end) { // check if the rest of the datafile is only followed by NULL bytes bool isFollowedByNullBytes = true; while (p < end) { if (*p != '\0') { isFollowedByNullBytes = false; break; } ++p; } if (isFollowedByNullBytes) { // only last marker in datafile was corrupt. fix the datafile in // place LOG_TOPIC(INFO, arangodb::Logger::DATAFILES) << "truncating datafile '" << getName() << "' at position " << currentSize; int res = truncateAndSeal(currentSize); return (res == TRI_ERROR_NO_ERROR); } // there is some other stuff following. now inspect it... TRI_ASSERT(next <= end); if (next < end) { // there is a next marker auto nextMarker = reinterpret_cast<MMFilesMarker const*>(next); if (nextMarker->getType() != 0 && nextMarker->getSize() >= sizeof(MMFilesMarker) && next + nextMarker->getSize() <= end && TRI_IsValidMarkerDatafile(nextMarker) && CheckCrcMarker(nextMarker, end)) { // next marker looks good. // create a temporary buffer auto buffer = std::unique_ptr<char[]>(new char[size]); // create a new marker in the temporary buffer auto temp = reinterpret_cast<MMFilesMarker*>(buffer.get()); MMFilesDatafileHelper::InitMarker( reinterpret_cast<MMFilesMarker*>(buffer.get()), TRI_DF_MARKER_BLANK, static_cast<uint32_t>(size)); temp->setCrc(CalculateCrcValue(temp)); // all done. now copy back the marker into the file memcpy(static_cast<void*>(ptr), buffer.get(), static_cast<size_t>(size)); buffer.reset(); // don't need the buffer anymore int res = this->sync(ptr, (ptr + size)); if (res == TRI_ERROR_NO_ERROR) { LOG_TOPIC(INFO, arangodb::Logger::DATAFILES) << "zeroed single invalid marker in datafile '" << getName() << "' at position " << currentSize; } else { LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "could not zero single invalid marker in datafile '" << getName() << "' at position " << currentSize; return false; } } else { // next marker looks broken, too. int res = truncateAndSeal(currentSize); return (res == TRI_ERROR_NO_ERROR); } } } } } size_t alignedSize = MMFilesDatafileHelper::AlignedMarkerSize<uint32_t>(marker); currentSize += static_cast<uint32_t>(alignedSize); if (marker->getType() == TRI_DF_MARKER_FOOTER) { return true; } ptr += alignedSize; } return true; } /// @brief opens an existing datafile /// The datafile will be opened read-only if a footer is found MMFilesDatafile* MMFilesDatafile::open(std::string const& filename, bool ignoreFailures, bool autoSeal) { // this function must not be called for non-physical datafiles TRI_ASSERT(!filename.empty()); std::unique_ptr<MMFilesDatafile> datafile(MMFilesDatafile::openHelper(filename, ignoreFailures)); if (datafile == nullptr) { return nullptr; } // check the datafile by scanning markers bool ok = datafile->check(ignoreFailures, autoSeal); if (!ok) { TRI_UNMMFile(const_cast<char*>(datafile->data()), datafile->initSize(), datafile->fd(), &datafile->_mmHandle); TRI_TRACKED_CLOSE_FILE(datafile->fd()); LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "datafile '" << datafile->getName() << "' is corrupt"; // must free datafile here return nullptr; } // change to read-write if no footer has been found if (!datafile->_isSealed) { if (!datafile->readWrite()) { LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "unable to change memory protection for memory backed by datafile '" << datafile->getName() << "'. please check file permissions and mount options."; return nullptr; } datafile->setState(TRI_DF_STATE_WRITE); } // Advise on sequential use: datafile->sequentialAccess(); datafile->willNeed(); return datafile.release(); } /// @brief opens a datafile MMFilesDatafile* MMFilesDatafile::openHelper(std::string const& filename, bool ignoreErrors) { TRI_ERRORBUF; // this function must not be called for non-physical datafiles TRI_ASSERT(!filename.empty()); TRI_voc_fid_t fid = GetNumericFilenamePart(filename.c_str()); // attempt to open a datafile file int fd = TRI_TRACKED_OPEN_FILE(filename.c_str(), O_RDWR | TRI_O_CLOEXEC); if (fd < 0) { TRI_SYSTEM_ERROR(); TRI_set_errno(TRI_ERROR_SYS_ERROR); LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "cannot open datafile '" << filename << "': '" << TRI_GET_ERRORBUF << "'"; return nullptr; } // compute the size of the file TRI_stat_t status; int res = TRI_FSTAT(fd, &status); if (res < 0) { TRI_SYSTEM_ERROR(); TRI_set_errno(TRI_ERROR_SYS_ERROR); TRI_TRACKED_CLOSE_FILE(fd); LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "cannot get status of datafile '" << filename << "': " << TRI_GET_ERRORBUF; return nullptr; } // check that file is not too small uint32_t size = static_cast<uint32_t>(status.st_size); if (size < sizeof(MMFilesDatafileHeaderMarker) + sizeof(MMFilesDatafileFooterMarker)) { TRI_set_errno(TRI_ERROR_ARANGO_CORRUPTED_DATAFILE); TRI_TRACKED_CLOSE_FILE(fd); LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "datafile '" << filename << "' is corrupt, size is only " << size; return nullptr; } // read header from file char buffer[128]; memset(&buffer[0], 0, sizeof(buffer)); size_t const len = sizeof(MMFilesDatafileHeaderMarker); ssize_t toRead = sizeof(buffer); if (toRead > static_cast<ssize_t>(status.st_size)) { toRead = static_cast<ssize_t>(status.st_size); } bool ok = TRI_ReadPointer(fd, &buffer[0], toRead); if (!ok) { LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "cannot read datafile header from '" << filename << "': " << TRI_last_error(); TRI_TRACKED_CLOSE_FILE(fd); return nullptr; } char const* ptr = reinterpret_cast<char*>(&buffer[0]); char const* end = static_cast<char const*>(ptr) + len; MMFilesDatafileHeaderMarker const* header = reinterpret_cast<MMFilesDatafileHeaderMarker const*>(&buffer[0]); // check CRC ok = CheckCrcMarker(reinterpret_cast<MMFilesMarker const*>(ptr), end); if (!ok) { if (IsMarker28(ptr, len)) { TRI_TRACKED_CLOSE_FILE(fd); LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "datafile found from older version of ArangoDB. " << "Please dump data from that version with arangodump " << "and reload it into this ArangoDB instance with arangorestore"; FATAL_ERROR_EXIT(); } TRI_set_errno(TRI_ERROR_ARANGO_CORRUPTED_DATAFILE); LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "corrupted datafile header read from '" << filename << "'"; printMarker(reinterpret_cast<MMFilesMarker const*>(ptr), len, &buffer[0], end); if (!ignoreErrors) { TRI_TRACKED_CLOSE_FILE(fd); return nullptr; } } // check the datafile version if (ok) { if (header->_version != TRI_DF_VERSION) { TRI_set_errno(TRI_ERROR_ARANGO_CORRUPTED_DATAFILE); LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "unknown datafile version '" << header->_version << "' in datafile '" << filename << "'"; if (!ignoreErrors) { TRI_TRACKED_CLOSE_FILE(fd); return nullptr; } } } // check the maximal size if (size > header->_maximalSize) { LOG_TOPIC(DEBUG, arangodb::Logger::DATAFILES) << "datafile '" << filename << "' has size " << size << ", but maximal size is " << header->_maximalSize; } // map datafile into memory void* data; void* mmHandle; res = TRI_MMFile(nullptr, size, PROT_READ, MAP_SHARED, fd, &mmHandle, 0, &data); if (res != TRI_ERROR_NO_ERROR) { TRI_set_errno(res); TRI_TRACKED_CLOSE_FILE(fd); LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "cannot memory map datafile '" << filename << "': " << TRI_errno_string(res); LOG_TOPIC(ERR, arangodb::Logger::DATAFILES) << "The database directory might reside on a shared folder " "(VirtualBox, VMWare) or an NFS-mounted volume which does not allow memory mapped files."; return nullptr; } // create datafile structure try { return new MMFilesDatafile(filename, fd, mmHandle, size, size, fid, static_cast<char*>(data)); } catch (...) { TRI_UNMMFile(data, size, fd, &mmHandle); TRI_TRACKED_CLOSE_FILE(fd); return nullptr; } } /// @brief returns information about the datafile DatafileScan MMFilesDatafile::scan(std::string const& path) { // this function must not be called for non-physical datafiles TRI_ASSERT(!path.empty()); std::unique_ptr<MMFilesDatafile> datafile(MMFilesDatafile::openHelper(path, true)); if (datafile != nullptr) { return datafile->scanHelper(); } DatafileScan scan; scan.currentSize = 0; scan.maximalSize = 0; scan.endPosition = 0; scan.numberMarkers = 0; scan.status = 5; scan.isSealed = false; return scan; }
#include<iostream> using namespace std; int main() { cout << "No. of rows: \n"; int row; cin >> row; cout << "No.of cols: \n"; int cols; cin >> cols; for(int i=0;i<row;i++) { for(int j=0;j<cols;j++) cout << "* " ; cout << "\n"; } return 0; }
#include <bits/stdc++.h> using namespace std; class YeuTo { protected: int GiaTri; public: YeuTo(); ~YeuTo(); int GetGiaTri(); virtual void DacDiem() = 0; virtual void ChiSoCao() = 0; virtual void ChiSoThap() = 0; }; YeuTo::YeuTo() { } YeuTo::~YeuTo() { } int YeuTo::GetGiaTri() { return GiaTri; } class O : public YeuTo { public: O(); ~O(); O(int); void DacDiem(); void ChiSoCao(); void ChiSoThap(); }; O::O() { } O::O(int nn) { GiaTri = nn; } void O::DacDiem() { cout << "San sang trai nghiem (0)"; } O::~O() { } void O::ChiSoCao() { cout << "Nguoi co chi so cao o yeu to nay thuong la nguoi thich nhung y tuong moi..."; } void O::ChiSoThap() { cout << "Nguoi co chi so thaps o yeu to nay thuong la nguoi kha bao thu ..."; } class C : public YeuTo { public: C(); ~C(); C(int); void DacDiem(); void ChiSoCao(); void ChiSoThap(); }; C::C() { } C::C(int nn) { GiaTri = nn; } void C::DacDiem() { cout << "Tu chu tan tam (C)"; } C::~C() { } void C::ChiSoCao() { cout << "Nguoi co chi so cao o yeu to nay thuong la nguoi cham chi ..."; } void C::ChiSoThap() { cout << "Nguoi co chi so thap o yeu to nay thuong la nguoi de bo cuoc ..."; } class E : public YeuTo { public: E(); ~E(); E(int); void DacDiem(); void ChiSoCao(); void ChiSoThap(); }; E::E() { } E::E(int nn) { GiaTri = nn; } void E::DacDiem() { cout << "Huong ngoai (E)"; } E::~E() { } void E::ChiSoCao() { cout << "Nguoi co chi so cao o yeu to nay thuong la nguoi nhiet tinh, nang dong..."; } void E::ChiSoThap() { cout << "Nguoi co chi so thap o yeu to nay thuong la ngai giao tieps ..."; } class A : public YeuTo { public: A(); ~A(); A(int); void DacDiem(); void ChiSoCao(); void ChiSoThap(); }; A::A() { } A::A(int nn) { GiaTri = nn; } void A::DacDiem() { cout << "Hoa dong de chiu (A)"; } A::~A() { } void A::ChiSoCao() { cout << "Nguoi co chi so cao o yeu to nay thuong than thien coi mo ..."; } void A::ChiSoThap() { cout << "Nguoi co chi so thap o yeu to nay thuong dat loi ich cua ban than len tren ..."; } class N : public YeuTo { public: N(); ~N(); N(int); void DacDiem(); void ChiSoCao(); void ChiSoThap(); }; N::N() { } N::N(int nn) { GiaTri = nn; } void N::DacDiem() { cout << "Bat on cam xuc (N)"; } N::~N() { } void N::ChiSoCao() { cout << "Nguoi co chi so cao o yeu to nay thuong co cac cam xuc tieu cuc ..."; } void N::ChiSoThap() { cout << "Nguoi co chi so thap o yeu to nay thuong kiem soat duoc cam xuc ..."; } class Nguoi { private: YeuTo *ds[5]; public: Nguoi(); ~Nguoi(); void Nhap(); void TinhCach(); bool NguyCo(); }; Nguoi::Nguoi() { } Nguoi::~Nguoi() { } void Nguoi::Nhap() { int temp; cout << "Nhap vao gia tri yeu to O"; cin >> temp; ds[0] = new O(temp); cout << "Nhap vao gia tri yeu to C"; cin >> temp; ds[1] = new C(temp); cout << "Nhap vao gia tri yeu to E"; cin >> temp; ds[2] = new E(temp); cout << "Nhap vao gia tri yeu to A"; cin >> temp; ds[3] = new A(temp); cout << "Nhap vao gia tri yeu to N"; cin >> temp; ds[4] = new N(temp); } void Nguoi::TinhCach() { for (int i = 0; i < 5; i++) { ds[i]->DacDiem(); if (ds[i]->GetGiaTri() >= 70) ds[i]->ChiSoCao(); else if (ds[i]->GetGiaTri() <= 30) ds[i]->ChiSoThap(); else cout << "Khong xac dinh ro"; } } bool Nguoi::NguyCo() { if ((ds[2]->GetGiaTri() <= 30) && (ds[3]->GetGiaTri() >= 70)) return true; if (ds[3]->GetGiaTri() >= 70) return true; if (ds[1]->GetGiaTri() <= 30) return true; return false; } int main() { Nguoi dsn[50]; int n; cout << "Nhap so luong nguoi"; cin >> n; for (int i = 0; i < n; i++) dsn[i].Nhap(); int x; cout << "Chon nguoi thu "; cin >> x; dsn[x].TinhCach(); for (int i = 0; i < n; i++) if (dsn[i].NguyCo() == true) cout << i << " "; system("pause"); }
// cmcstl2 - A concept-enabled C++ standard library // // Copyright Casey Carter 2015 // // 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/caseycarter/cmcstl2 // #ifndef STL2_DETAIL_ALGORITHM_REPLACE_COPY_HPP #define STL2_DETAIL_ALGORITHM_REPLACE_COPY_HPP #include <stl2/detail/algorithm/results.hpp> #include <stl2/detail/concepts/callable.hpp> #include <stl2/detail/range/primitives.hpp> /////////////////////////////////////////////////////////////////////////// // replace_copy [alg.replace] // STL2_OPEN_NAMESPACE { template<class I, class O> using replace_copy_result = __in_out_result<I, O>; struct __replace_copy_fn : private __niebloid { template<InputIterator I, Sentinel<I> S, class T1, class T2, OutputIterator<const T2&> O, class Proj = identity> requires IndirectlyCopyable<I, O> && IndirectRelation<equal_to, projected<I, Proj>, const T1*> constexpr replace_copy_result<I, O> operator()(I first, S last, O result, const T1& old_value, const T2& new_value, Proj proj = {}) const { for (; first != last; (void) ++first, (void) ++result) { iter_reference_t<I>&& v = *first; if (__stl2::invoke(proj, v) == old_value) { *result = new_value; } else { *result = std::forward<iter_reference_t<I>>(v); } } return {std::move(first), std::move(result)}; } template<InputRange R, class T1, class T2, OutputIterator<const T2&> O, class Proj = identity> requires IndirectlyCopyable<iterator_t<R>, O> && IndirectRelation<equal_to, projected<iterator_t<R>, Proj>, const T1*> constexpr replace_copy_result<safe_iterator_t<R>, O> operator()(R&& r, O result, const T1& old_value, const T2& new_value, Proj proj = {}) const { return (*this)(begin(r), end(r), std::move(result), old_value, new_value, __stl2::ref(proj)); } }; inline constexpr __replace_copy_fn replace_copy {}; } STL2_CLOSE_NAMESPACE #endif
#pragma once #include "./IOException.hpp" class JString; namespace java::io { class CharConversionException : public java::io::IOException { public: // Fields // QJniObject forward template<typename ...Ts> explicit CharConversionException(const char *className, const char *sig, Ts...agv) : java::io::IOException(className, sig, std::forward<Ts>(agv)...) {} CharConversionException(QJniObject obj); // Constructors CharConversionException(); CharConversionException(JString arg0); // Methods }; } // namespace java::io
#include "control.h" #include "util.h" Dfa::Dfa(Control *control_, Base *base_) : control(control_), option(control_ -> option), grammar(control_ -> grammar), node_pool(control_ -> node_pool), base(base_), num_states(0), num_shift_maps(0), num_shifts(0), num_shift_reduces(0), num_gotos(0), num_goto_reduces(0), shift_table(SHIFT_TABLE_SIZE, Util::NIL), conflict_table(CONFLICT_TABLE_SIZE, Util::NIL) { (void) shift.NextIndex(); (void) next_shift.Next(); conflicts.Next() = 0; assert(shift.Length() == 1 && next_shift.Length() == 1 && conflicts.Length() == 1); return; } void Dfa::Process(void) { MakeLr0(); BuildPredecessorsMap(); return; } // // This procedure constructs an LR(0) automaton. // void Dfa::MakeLr0(void) { (void) statset.Next(); // skip the zeroth element !!! // // Kernel of the first state consists of the first item of the // rule produced by the Accept non-terminal. // assert(base -> clitems[grammar -> accept_image].Length() == 1); Node *q = node_pool -> AllocateNode(); q -> value = base -> clitems[grammar -> accept_image][0]; q -> next = NULL; // // STATE_TABLE is the array used to hash the states. States are // identified by their Kernel set of items. Hash locations are // computed for the states. As states are inserted in the table, // they are threaded together via the QUEUE component of // STATE_ELEMENT. The variable STATE_ROOT points to the root of // the thread, and the variable STATE_TAIL points to the tail. // // After constructing a state, Shift and Goto actions are // defined on that state based on a partition of the set of items // in that state. The partitioning is based on the symbols // following the dot in the items. The array PARTITION is used // for that partitioning. LIST and ROOT are used to construct // temporary lists of symbols in a state on which Shift or Goto // actions are defined. // NT_LIST and NT_ROOT are used to build temporary lists of // non-terminals. // Array<int> state_table(STATE_TABLE_SIZE, Util::NIL), shift_action(grammar -> num_terminals + 1, Util::OMEGA); int goto_size = 0, nt_root = Util::NIL;; BoundedArray<int> nt_list(grammar -> num_terminals + 1, grammar -> num_symbols, Util::OMEGA); Array<Node *> partition(grammar -> num_symbols + 1); partition.MemReset(); Tuple<int> shift_list, list, next_state; (void) next_state.Next(); // // Insert first state in STATE_TABLE and keep constructing states // until we no longer can. // for (int state_index = lr0_state_map(state_table, next_state, q); // insert initial state state_index < statset.Length(); // and process next state until no more state_index++) { // // Now we construct a list of all non-terminals that can be // introduced in this state through closure. The CLOSURE of each // non-terminal has been previously computed in MKFIRST. // for (q = statset[state_index].kernel_items; q != NULL; // iterate over kernel set of items q = q -> next) { int item_no = q -> value, symbol = base -> item_table[item_no].symbol; // symbol after dot if (grammar -> IsNonTerminal(symbol)) // Dot symbol { if (nt_list[symbol] == Util::OMEGA) // not yet seen { nt_list[symbol] = nt_root; nt_root = symbol; for (int k = 0; k < base -> closure[symbol].Length(); k++) { int element = base -> closure[symbol][k]; if (nt_list[element] == Util::OMEGA) { nt_list[element] = nt_root; nt_root = element; } } } } } // // We now construct lists of all start items that the closure // non-terminals produce. A map from each non-terminal to its set // start items has previously been computed in MKFIRST. (CLITEMS) // Empty items are placed directly in the state, whereas non_empty // items are placed in a temporary list rooted at CLOSURE_ROOT. // Node *closure_root = NULL, // used to construct list of closure items *closure_tail = NULL; for (int symbol = nt_root; symbol != Util::NIL; nt_list[symbol] = Util::OMEGA, symbol = nt_root) { nt_root = nt_list[symbol]; for (int k = 0; k < base -> clitems[symbol].Length(); k++) { int item_no = base -> clitems[symbol][k]; Node *new_item = node_pool -> AllocateNode(); new_item -> value = item_no; if (base -> item_table[item_no].symbol == grammar -> empty) // complete item { new_item -> next = statset[state_index].complete_items; statset[state_index].complete_items = new_item; } else // closure item, add to closure list { if (closure_root == NULL) closure_root = new_item; else closure_tail -> next = new_item; closure_tail = new_item; } } } Node *item_ptr; if (closure_root != NULL) // any non-complete closure items? { closure_tail -> next = statset[state_index].kernel_items; item_ptr = closure_root; } else // else just consider kernel items item_ptr = statset[state_index].kernel_items; // // In this loop, the PARTITION map is constructed. At this point, // ITEM_PTR points to all the non_complete items in the closure of // the state, plus all the kernel items. We note that the kernel // items may still contain complete-items, and if any is found, the // COMPLETE_ITEMS list is updated. // list.Reset(); for (; item_ptr != NULL; item_ptr = item_ptr -> next) { int item_no = item_ptr -> value, symbol = base -> item_table[item_no].symbol; if (symbol != grammar -> empty) // incomplete item { int next_item_no = item_no + 1; if (partition[symbol] == NULL) // PARTITION not defined on symbol { list.Next() = symbol; // add to list if (grammar -> IsNonTerminal(symbol)) goto_size++; } Node *p, *tail = NULL; for (p = partition[symbol]; p != NULL; tail = p, p = p -> next) { if (p -> value > next_item_no) break; } Node *r = node_pool -> AllocateNode(); r -> value = next_item_no; r -> next = p; if (p == partition[symbol]) // Insert at beginning partition[symbol] = r; else tail -> next = r; } else // Update complete item set with item from kernel { Node *p = node_pool -> AllocateNode(); p -> value = item_no; p -> next = statset[state_index].complete_items; statset[state_index].complete_items = p; } } if (closure_root != NULL) node_pool -> FreeNodes(closure_root, closure_tail); // // We now iterate over the set of partitions and update the state // automaton and the transition maps: SHIFT and GOTO. Each // partition represents the kernel of a state. // for (int i = list.Length() - 1; i >= 0; i--) { int symbol = list[i], action = Util::OMEGA; // // If the partition contains only one item, and it is adequate // (i.e. the dot immediately follows the last symbol), and // READ-REDUCE is requested, a new state is not created, and the // action is marked as a Shift-reduce or a Goto-reduce. Otherwise // if a state with that kernel set does not yet exist, we create // it. // Node *q = partition[symbol]; // kernel of a new state if (option -> read_reduce && q -> next == NULL) { int item_no = q -> value; if (base -> item_table[item_no].symbol == grammar -> empty) { int rule_no = base -> item_table[item_no].rule_number; if (grammar -> rules[rule_no].lhs != grammar -> accept_image) { action = -rule_no; node_pool -> FreeNodes(q, q); } } } if (action == Util::OMEGA) // Not a Read-Reduce action action = lr0_state_map(state_table, next_state, q); // // At this stage, the partition list has been freed (for an old // state or an ADEQUATE item), or used (for a new state). The // PARTITION field involved should be reset. // partition[symbol] = NULL; // To be reused // // At this point, ACTION contains the value of the state to Shift // to, or rule to Read-Reduce on. If the symbol involved is a // terminal, we update the Shift map; else, it is a non-terminal // and we update the Goto map. // Shift maps are constructed temporarily in SHIFT_ACTION. // Later, they are inserted into a map of unique Shift maps, and // shared by states that contain identical shifts. // Since the lookahead set computation is based on the GOTO maps, // all these maps and their element maps should be kept as // separate entities. // if (grammar -> IsTerminal(symbol)) // terminal? add to SHIFT map { shift_action[symbol] = action; shift_list.Next() = symbol; if (action > 0) num_shifts++; else num_shift_reduces++; } // // NOTE that for Goto's we update the field LA_PTR of GOTO. This // field will be used later in the routine MKRDCTS to point to a // look-ahead set. // else { int index = statset[state_index].go_to.NextIndex(); statset[state_index].go_to[index].SetSymbol(symbol); // symbol field statset[state_index].go_to[index].SetAction(action); // state field statset[state_index].go_to[index].SetLaptr(Util::OMEGA); // la_ptr field if (action > 0) num_gotos++; else num_goto_reduces++; } } statset[state_index].shift_number = UpdateShiftMaps(shift_list, shift_action); // // Reset shift_list and shift_action for reuse later... // for (int j = 0; j < shift_list.Length(); j++) { int symbol = shift_list[j]; shift_action[symbol] = Util::OMEGA; } shift_list.Reset(); } // // Construct STATSET, a "compact" and final representation of // State table, and SHIFT which is a set of all shift maps needed. // NOTE that assignments to elements of SHIFT may occur more than // once, but that's ok. It is probably faster to do that than to // set up an elaborate scheme to avoid the multiple assignment which // may in fact cost more. Look at it this way: it is only a pointer // assignment, namely a Load and a Store. // Release all NODEs used by the maps CLITEMS and CLOSURE. // // If the grammar is LALR(k), k > 1, more states may be added and // the size of the shift map increased. // num_states = statset.Length() - 1; // recall that the 0th element is not used! assert(num_shift_maps == shift.Length() - 1); return; } // // LR0_STATE_MAP takes as an argument a pointer to a kernel set of items. If // no state based on that kernel set already exists, then a new one is // created and added to STATE_TABLE. In any case, a pointer to the STATE of // the KERNEL is returned. // int Dfa::lr0_state_map(Array<int> &state_table, Tuple<int> &next_state, Node *kernel) { unsigned hash_address = 0; // // Compute the hash address. // for (Node *p = kernel; p != NULL; p = p -> next) hash_address += p -> value; hash_address %= STATE_TABLE_SIZE; // // Check whether a state is already defined by the KERNEL set. // for (int i = state_table[hash_address]; i != Util::NIL; i = next_state[i]) { Node *p, *q, *tail = NULL; for (p = statset[i].kernel_items, q = kernel; p != NULL && q != NULL; p = p -> next, tail = q, q = q -> next) { if (p -> value != q -> value) break; } if (p == q) // Both P and Q are NULL? { node_pool -> FreeNodes(kernel, tail); return i; } } // // Add a new state based on the KERNEL set. // int state_index = statset.NextIndex(); assert(state_index == next_state.Length()); // sanity check !!! statset[state_index].kernel_items = kernel; statset[state_index].complete_items = NULL; statset[state_index].single_production_items = NULL; statset[state_index].transition_symbol = (base -> item_table[kernel -> value].dot == 0 ? grammar -> empty : base -> item_table[kernel -> value - 1].symbol); next_state.Next() = state_table[hash_address]; state_table[hash_address] = state_index; return state_index; } // // We are now going to update the set of Shift-maps. Ths idea is // to do a look-up in a hash table based on SHIFT_TABLE to see if // the Shift map associated with the current state has already been // computed. If it has, we simply update the SHIFT_NUMBER and the // SHIFT field of the current state. Otherwise, we allocate and // construct a SHIFT_ELEMENT map, update the current state, and // add it to the set of Shift maps in the hash table. // Note that the SHIFT_NUMBER field in the STATE_ELEMENTs could // have been factored out and associated instead with the // SHIFT_ELEMENTs. That would have saved some space, but only in // the short run. This field was purposely stored in the // STATE_ELEMENTs, because once the states have been constructed, // they are not kept, whereas the SHIFT_ELEMENTs are kept. // One could have also threaded through the states that contain // original shift maps so as to avoid duplicate assignments in // creating the SHIFT map later. However, this would have // increased the storage requirement, and would probably have saved // (at most) a totally insignificant amount of time. // int Dfa::UpdateShiftMaps(Tuple<int> &shift_list, Array<int> &shift_action) { if (shift_list.Length() == 0) return 0; unsigned hash_address = shift_list.Length(); for (int j = 0; j < shift_list.Length(); j++) { int symbol = shift_list[j]; hash_address += Util::Abs(shift_action[symbol]); } hash_address %= SHIFT_TABLE_SIZE; for (int k = shift_table[hash_address]; k != Util::NIL; // Search has table for shift map k = next_shift[k]) { ShiftHeader &sh = shift[k]; if (sh.Length() == shift_list.Length()) { int i; for (i = 0; i < shift_list.Length(); i++) // Compare shift maps { if (sh[i].Action() != shift_action[sh[i].Symbol()]) break; } if (i == shift_list.Length()) // Are they equal ? return k; } } num_shift_maps++; int shift_index = shift.NextIndex(); assert(shift_index == num_shift_maps); assert(shift_index == next_shift.Length()); next_shift.Next() = shift_table[hash_address]; shift_table[hash_address] = shift_index; ResetShiftMap(shift_index, shift_list, shift_action); return shift_index; } // // // void Dfa::ResetShiftMap(int shift_index, Tuple<int> &shift_list, Array<int> &shift_action) { ShiftHeader &sh = shift[shift_index]; sh.Reset(); for (int i = 0; i < shift_list.Length(); i++) { int symbol = shift_list[i], index = sh.NextIndex(); sh[index].SetSymbol(symbol); sh[index].SetAction(shift_action[symbol]); } assert(sh.Length() == shift_list.Length()); return; } // // // void Dfa::QuickSort(Tuple<ConflictCell> &array) { Stack<int> lostack, histack; int low = 0, high = array.Length() - 1; lostack.Push(low); histack.Push(high); while (! lostack.IsEmpty()) { int lower = lostack.Pop(), upper = histack.Pop(); while (upper > lower) { int i = lower; ConflictCell pivot = array[lower]; for (int j = lower + 1; j <= upper; j++) { if (array[j].priority < pivot.priority) { array[i] = array[j]; i++; array[j] = array[i]; } } array[i] = pivot; if (i - lower < upper - i) { lostack.Push(i + 1); histack.Push(upper); upper = i - 1; } else { histack.Push(i - 1); lostack.Push(lower); lower = i + 1; } } } return; } // // // int Dfa::MapConflict(Tuple<ConflictCell> &cell) { assert(cell.Length() > 1); QuickSort(cell); unsigned hash_address = 0; for (int j = 0; j < cell.Length(); j++) hash_address += ((unsigned) cell[j].action); hash_address %= CONFLICT_TABLE_SIZE; for (int k = conflict_table[hash_address]; k != Util::NIL; // Search has table for conflict map k = conflict_element[k].next) { int i = conflict_element[k].index, j; for (j = 0; j < cell.Length(); j++) // Compare action list { if (conflicts[i + j] != cell[j].action) break; } if ((i + j >= conflicts.Length() || conflicts[i + j] == 0) && (j == cell.Length())) // Are they equal ? return i; } int conflict_index = conflict_element.NextIndex(); conflict_element[conflict_index].next = conflict_table[hash_address]; conflict_table[hash_address] = conflict_index; conflict_element[conflict_index].index = conflicts.Length(); for (int i = 0; i < cell.Length(); i++) conflicts.Next() = cell[i].action; conflicts.Next() = 0; return conflict_element[conflict_index].index; } // // Replace a conflict list with new list. // void Dfa::RemapConflict(int index, Tuple<ConflictCell> &cell) { assert(conflicts[index + cell.Length()] == 0); for (int i = 0; i < cell.Length(); i++) conflicts[index + i] = cell[i].action; return; } // // We construct the IN_STAT map which is the inverse of the transition // map formed by GOTO and SHIFT maps. // This map is implemented as a table of pointers that can be indexed // by the states to a circular list of integers representing other // states that contain transitions to the state in question. // void Dfa::BuildPredecessorsMap(void) { // // // for (int k = 1; k <= num_states; k++) statset[k].predecessors.Reset(); // // Construct map. // for (int state_no = 1; state_no <= num_states; state_no++) { Dfa::ShiftHeader &sh = Shift(state_no); for (int i = 0; i < sh.Length(); ++i) { int action = sh[i].Action(); if (action > 0 && action <= num_states) // A shift action? AddPredecessor(action, state_no); } Dfa::GotoHeader &go_to = statset[state_no].go_to; for (int j = 0; j < go_to.Length(); j++) { int action = go_to[j].Action(); if (action > 0) // A goto action AddPredecessor(action, state_no); } } return; } // // Given a STATE_NO and an ITEM_NO, ACCESS computes the set of states where // the rule from which ITEM_NO is derived was introduced through closure. // void Dfa::Access(Tuple<int> &state_list, int state_no, int item_no) { // // Build a list pointed to by ACCESS_ROOT originally consisting // only of STATE_NO. // Tuple<int> temp_list; int first_index = temp_list.NextIndex(); temp_list[first_index] = state_no; for (int i = base -> item_table[item_no].dot; i > 0; i--) // distance to travel is DOT { int n = temp_list.Length(); for (int j = first_index; j < n; j++) { int state_number = temp_list[j]; // // Compute set of states with transition into p->value. // for (int k = 0; k < statset[state_number].predecessors.Length(); k++) temp_list.Next() = statset[state_number].predecessors[k]; } first_index = n; } state_list.Reset(); // clear the list out for (int k = first_index; k < temp_list.Length(); k++) state_list.Next() = temp_list[k]; return; } // // PrintItem takes as parameter an ITEM_NO which it prints. // void Dfa::PrintItem(int item_no) { // // We first print the left hand side of the rule, leaving at least // 5 spaces in the output line to accomodate the equivalence symbol // "::=" surrounded by blanks on both sides. Then, we print all the // terminal symbols in the right hand side up to but not including // the dot symbol. // int rule_no = base -> item_table[item_no].rule_number, symbol = grammar -> rules[rule_no].lhs; char tempstr[Control::PRINT_LINE_SIZE + 1], line[Control::PRINT_LINE_SIZE + 1], tok[Control::SYMBOL_SIZE + 1]; grammar -> RestoreSymbol(tok, grammar -> RetrieveString(symbol)); int len = Control::PRINT_LINE_SIZE - 5; grammar -> PrintLargeToken(line, tok, "", len); strcat(line, grammar -> rules[rule_no].IsArrowProduction() ? " -> " : " ::= "); int i = (Control::PRINT_LINE_SIZE / 2) - 1, offset = Util::Min(strlen(line)-1, i); len = Control::PRINT_LINE_SIZE - (offset + 4); i = grammar -> rules[rule_no].rhs_index; // symbols before dot int k = ((grammar -> rules[rule_no].rhs_index + base -> item_table[item_no].dot) - 1); for (; i <= k; i++) { int symbol = grammar -> rhs_sym[i]; grammar -> RestoreSymbol(tok, grammar -> RetrieveString(symbol)); if (strlen(tok) + strlen(line) > Control::PRINT_LINE_SIZE - 4) { fprintf(option -> syslis,"\n%s", line); FillIn(tempstr, offset, ' '); grammar -> PrintLargeToken(line, tok, tempstr, len); } else strcat(line, tok); strcat(line, " "); } // // We now add a DOT "." to the output line and print the remaining // symbols in the right hand side. If ITEM_NO is a complete item, // we also print the rule number. // if (base -> item_table[item_no].dot == 0 || base -> item_table[item_no].symbol == grammar -> empty) strcpy(tok, "."); else strcpy(tok, " ."); strcat(line, tok); len = Control::PRINT_LINE_SIZE - (offset + 1); { for (int i = grammar -> rules[rule_no].rhs_index + base -> item_table[item_no].dot;// symbols after dot i <= grammar -> rules[rule_no + 1].rhs_index - 1; i++) { int symbol = grammar -> rhs_sym[i]; grammar -> RestoreSymbol(tok, grammar -> RetrieveString(symbol)); if (strlen(tok) + strlen(line) > Control::PRINT_LINE_SIZE -1) { fprintf(option -> syslis, "\n%s", line); FillIn(tempstr, offset, ' '); grammar -> PrintLargeToken(line, tok, tempstr, len); } else strcat(line, tok); strcat(line, " "); } } if (base -> item_table[item_no].symbol == grammar -> empty) // complete item { IntToString num(rule_no); if (num.Length() + 3 + strlen(line) > Control::PRINT_LINE_SIZE - 1) { fprintf(option -> syslis, "\n%s", line); FillIn(line,offset, ' '); } strcat(line, " ("); strcat(line, num.String()); strcat(line, ")"); } fprintf(option -> syslis, "\n%s", line); return; }
/* * MIT License * * Copyright(c) 2018 Jimmie Bergmann * * 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. * */ #ifndef FLARE_PRIVATE_WIN32_WINDOW_HPP #define FLARE_PRIVATE_WIN32_WINDOW_HPP #include "flare/build.hpp" #if defined(FLARE_PLATFORM_WINDOWS) #include "windowBase.hpp" namespace Flare { namespace Priv { class FLARE_API Win32Window : public WindowBase { public: Win32Window(); Win32Window(const Vector2ui32 & size, const std::string & title); ~Win32Window(); virtual void open(const Vector2ui32 & size, const std::string & title); virtual void close(); virtual bool update(); virtual void show(); virtual void hide(); virtual void setWindowMode(const WindowMode mode); virtual void toggleWindowMode(); virtual bool isOpen() const; virtual bool isVisible() const; virtual bool isFullscreen() const; virtual WindowMode getWindowMode() const; virtual const Vector2ui32 & getSize() const; virtual const std::string & getTitle() const; virtual HWND getHWnd() const; virtual HINSTANCE getHInstance() const; private: /** * Window event functions. * */ static LRESULT windowProcStatic(HWND p_HWND, UINT p_Message, WPARAM p_WParam, LPARAM p_LParam); LRESULT windowProc(HWND p_HWND, UINT p_Message, WPARAM p_WParam, LPARAM p_LParam); bool m_open; bool m_closed; bool m_visible; WindowMode m_windowMode; HWND m_hWnd; HINSTANCE m_hInstance; HDC m_hDc; Vector2ui32 m_size; std::string m_title; DWORD m_style; ///< Win32 style of window. DWORD m_extendedStyle; ///< Win32 extended style of window. std::wstring m_windowClassName; }; } } #endif #endif
/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "condor_config.h" #include "string_list.h" #include "condorresource.h" #include "condorjob.h" #include "gridmanager.h" #define HASH_TABLE_SIZE 500 HashTable <HashKey, CondorResource *> CondorResource::ResourcesByName( HASH_TABLE_SIZE, hashFunction ); HashTable <HashKey, CondorResource::ScheddPollInfo *> CondorResource::PollInfoByName( 100, hashFunction ); const char *CondorResource::HashName( const char *resource_name, const char *pool_name, const char *proxy_subject ) { static std::string hash_name; formatstr( hash_name, "condor %s %s#%s", resource_name, pool_name ? pool_name : "NULL", proxy_subject ? proxy_subject : "NULL" ); return hash_name.c_str(); } CondorResource *CondorResource::FindOrCreateResource( const char * resource_name, const char *pool_name, const Proxy *proxy ) { int rc; CondorResource *resource = NULL; rc = ResourcesByName.lookup( HashKey( HashName( resource_name, pool_name, proxy ? proxy->subject->fqan : NULL ) ), resource ); if ( rc != 0 ) { resource = new CondorResource( resource_name, pool_name, proxy ); ASSERT(resource); resource->Reconfig(); ResourcesByName.insert( HashKey( HashName( resource_name, pool_name, proxy ? proxy->subject->fqan : NULL ) ), resource ); } else { ASSERT(resource); } return resource; } CondorResource::CondorResource( const char *resource_name, const char *pool_name, const Proxy *proxy ) : BaseResource( resource_name ) { hasLeases = true; if ( proxy != NULL ) { proxySubject = strdup( proxy->subject->subject_name ); proxyFQAN = strdup( proxy->subject->fqan ); } else { proxySubject = NULL; proxyFQAN = NULL; } scheddPollTid = TIMER_UNSET; scheddName = strdup( resource_name ); gahp = NULL; ping_gahp = NULL; scheddStatusActive = false; submitter_constraint = ""; if ( pool_name != NULL ) { poolName = strdup( pool_name ); } else { poolName = NULL; } scheddPollTid = daemonCore->Register_Timer( 0, (TimerHandlercpp)&CondorResource::DoScheddPoll, "CondorResource::DoScheddPoll", (Service*)this ); char *gahp_path = param("CONDOR_GAHP"); if ( gahp_path == NULL ) { EXCEPT( "CONDOR_GAHP not defined in condor config file" ); } else { // TODO remove scheddName from the gahp server key if/when // a gahp server can handle multiple schedds std::string buff; ArgList args; formatstr( buff, "CONDOR/%s/%s/%s", poolName ? poolName : "NULL", scheddName, proxyFQAN ? proxyFQAN : "NULL" ); args.AppendArg("-f"); args.AppendArg("-s"); args.AppendArg(scheddName); if ( poolName != NULL ) { args.AppendArg("-P"); args.AppendArg(poolName); } gahp = new GahpClient( buff.c_str(), gahp_path, &args ); gahp->setNotificationTimerId( scheddPollTid ); gahp->setMode( GahpClient::normal ); gahp->setTimeout( CondorJob::gahpCallTimeout ); ping_gahp = new GahpClient( buff.c_str(), gahp_path, &args ); ping_gahp->setNotificationTimerId( pingTimerId ); ping_gahp->setMode( GahpClient::normal ); ping_gahp->setTimeout( CondorJob::gahpCallTimeout ); lease_gahp = new GahpClient( buff.c_str(), gahp_path, &args ); lease_gahp->setNotificationTimerId( updateLeasesTimerId ); lease_gahp->setMode( GahpClient::normal ); lease_gahp->setTimeout( CondorJob::gahpCallTimeout ); free( gahp_path ); } } CondorResource::~CondorResource() { ResourcesByName.remove( HashKey( HashName( resourceName, poolName, proxyFQAN ) ) ); // Make sure we don't leak a ScheddPollInfo. If there are other // CondorResources that still want to use it, they'll recreate it. // Don't delete it if we know another CondorResource is doing a // poll of the remote schedd right now. // TODO Track how many CondorResources are still using this // ScheddPollInfo and delete it only if we're the last one. ScheddPollInfo *poll_info = NULL; PollInfoByName.lookup( HashKey( HashName( scheddName, poolName, NULL ) ), poll_info ); if ( poll_info && ( poll_info->m_pollActive == false || scheddStatusActive == true ) ) { PollInfoByName.remove( HashKey( HashName( scheddName, poolName, NULL ) ) ); delete poll_info; } if ( proxySubject != NULL ) { free( proxySubject ); } free( proxyFQAN ); if ( scheddPollTid != TIMER_UNSET ) { daemonCore->Cancel_Timer( scheddPollTid ); } if ( gahp != NULL ) { delete gahp; } if ( ping_gahp != NULL ) { delete ping_gahp; } if ( lease_gahp != NULL ) { delete lease_gahp; } if ( scheddName != NULL ) { free( scheddName ); } if ( poolName != NULL ) { free( poolName ); } } void CondorResource::Reconfig() { BaseResource::Reconfig(); } const char *CondorResource::ResourceType() { return "condor"; } const char *CondorResource::GetHashName() { return HashName( resourceName, poolName, proxyFQAN ); } void CondorResource::PublishResourceAd( ClassAd *resource_ad ) { BaseResource::PublishResourceAd( resource_ad ); std::string buff; formatstr( buff, "condor %s %s", resourceName, poolName ); resource_ad->Assign( ATTR_NAME, buff.c_str() ); if ( proxySubject ) { resource_ad->Assign( ATTR_X509_USER_PROXY_SUBJECT, proxySubject ); } if ( proxyFQAN ) { resource_ad->Assign( ATTR_X509_USER_PROXY_FQAN, proxyFQAN ); } gahp->PublishStats( resource_ad ); } void CondorResource::CondorRegisterJob( CondorJob *job, const char *submitter_id ) { BaseResource::RegisterJob( job ); if ( submitter_ids.contains( submitter_id ) == false ) { submitter_ids.append( submitter_id ); if ( submitter_constraint.empty() ) { formatstr( submitter_constraint, "(%s=?=\"%s\")", ATTR_SUBMITTER_ID, submitter_id ); } else { formatstr_cat( submitter_constraint, "||(%s=?=\"%s\")", ATTR_SUBMITTER_ID, submitter_id ); } } } void CondorResource::UnregisterJob( BaseJob *base_job ) { CondorJob *job = dynamic_cast<CondorJob*>( base_job ); ScheddPollInfo *poll_info = NULL; PollInfoByName.lookup( HashKey( HashName( scheddName, poolName, NULL ) ), poll_info ); if ( poll_info ) { poll_info->m_submittedJobs.Delete( job ); } // This may call delete, so don't put anything after it! BaseResource::UnregisterJob( job ); } // Return true if the given error message from the gahp indicates that // the remote schedd isn't working. Authentication or authorization // failures don't count. bool CondorResource::GahpErrorResourceDown( const char *errmsg ) { if ( errmsg == NULL ) { return false; } if ( strstr( errmsg, "Failed to connect to" ) || strstr( errmsg, "Error locating schedd" ) ) { return true; } else { return false; } } void CondorResource::DoScheddPoll() { int rc; ScheddPollInfo *poll_info = NULL; if ( ( registeredJobs.IsEmpty() || resourceDown ) && scheddStatusActive == false ) { // No jobs or we can't talk to the schedd, so no point // in polling daemonCore->Reset_Timer( scheddPollTid, BatchStatusInterval() ); return; } if ( gahp->isStarted() == false ) { // The gahp isn't started yet. Wait a few seconds for a CondorJob // object to start it (and possibly initialize x509 credentials). daemonCore->Reset_Timer( scheddPollTid, 5 ); return; } PollInfoByName.lookup( HashKey( HashName( scheddName, poolName, NULL ) ), poll_info ); daemonCore->Reset_Timer( scheddPollTid, TIMER_NEVER ); if ( scheddStatusActive == false ) { // We share polls across all CondorResource objects going to // the same schedd. If another object has done a poll // recently, then don't bother doing one ourselves. if ( poll_info == NULL ) { poll_info = new ScheddPollInfo; poll_info->m_lastPoll = 0; poll_info->m_pollActive = false; PollInfoByName.insert( HashKey( HashName( scheddName, poolName, NULL ) ), poll_info ); } if ( poll_info->m_pollActive == true || poll_info->m_lastPoll + BatchStatusInterval() > time(NULL) ) { daemonCore->Reset_Timer( scheddPollTid, BatchStatusInterval() ); return; } // start schedd status command dprintf( D_FULLDEBUG, "Starting collective poll: %s\n", scheddName ); std::string constraint; // create a list of jobs we expect to hear about in our // status command // Since we're sharing the results of this status command with // all CondorResource objects going to the same schedd, look // for their jobs as well. poll_info->m_submittedJobs.Rewind(); while ( poll_info->m_submittedJobs.Next() ) { poll_info->m_submittedJobs.DeleteCurrent(); } CondorResource *next_resource; BaseJob *job; std::string job_id; ResourcesByName.startIterations(); while ( ResourcesByName.iterate( next_resource ) != 0 ) { if ( strcmp( scheddName, next_resource->scheddName ) || strcmp( poolName ? poolName : "", next_resource->poolName ? next_resource->poolName : "" ) ) { continue; } next_resource->registeredJobs.Rewind(); while ( ( job = next_resource->registeredJobs.Next() ) ) { if ( job->jobAd->LookupString( ATTR_GRID_JOB_ID, job_id ) ) { poll_info->m_submittedJobs.Append( (CondorJob *)job ); } } } formatstr( constraint, "(%s)", submitter_constraint.c_str() ); rc = gahp->condor_job_status_constrained( scheddName, constraint.c_str(), NULL, NULL ); if ( rc != GAHPCLIENT_COMMAND_PENDING ) { dprintf( D_ALWAYS, "gahp->condor_job_status_constrained returned %d for remote schedd: %s\n", rc, scheddName ); EXCEPT( "condor_job_status_constrained failed!" ); } scheddStatusActive = true; poll_info->m_pollActive = true; } else { // finish schedd status command int num_status_ads; ClassAd **status_ads = NULL; ASSERT( poll_info ); rc = gahp->condor_job_status_constrained( NULL, NULL, &num_status_ads, &status_ads ); if ( rc == GAHPCLIENT_COMMAND_PENDING ) { return; } else if ( rc != 0 ) { dprintf( D_ALWAYS, "gahp->condor_job_status_constrained returned %d for remote schedd %s\n", rc, scheddName ); dprintf( D_ALWAYS, "Requesting ping of resource\n" ); RequestPing( NULL ); } if ( rc == 0 ) { for ( int i = 0; i < num_status_ads; i++ ) { int cluster, proc; int rc2; std::string job_id_string; BaseJob *base_job = NULL; CondorJob *job; if( status_ads[i] == NULL ) { dprintf(D_ALWAYS, "DoScheddPoll was given null pointer for classad #%d\n", i); continue; } status_ads[i]->LookupInteger( ATTR_CLUSTER_ID, cluster ); status_ads[i]->LookupInteger( ATTR_PROC_ID, proc ); formatstr( job_id_string, "condor %s %s %d.%d", scheddName, poolName, cluster, proc ); rc2 = BaseJob::JobsByRemoteId.lookup( HashKey( job_id_string.c_str() ), base_job ); job = dynamic_cast<CondorJob*>( base_job ); if ( rc2 == 0 ) { job->NotifyNewRemoteStatus( status_ads[i] ); poll_info->m_submittedJobs.Delete( job ); } else { delete status_ads[i]; } } poll_info->m_lastPoll = time(NULL); } poll_info->m_pollActive = false; if ( status_ads != NULL ) { free( status_ads ); } // Check if any jobs were missing from the status result if ( rc == 0 ) { CondorJob *job; std::string job_id; poll_info->m_submittedJobs.Rewind(); while ( ( job = poll_info->m_submittedJobs.Next() ) ) { if ( job->jobAd->LookupString( ATTR_GRID_JOB_ID, job_id ) ) { // We should have gotten a status ad for this job, // but didn't. Tell the job that there may be // something wrong by giving it a NULL status ad. job->NotifyNewRemoteStatus( NULL ); } poll_info->m_submittedJobs.DeleteCurrent(); } } scheddStatusActive = false; dprintf( D_FULLDEBUG, "Collective poll complete: %s\n", scheddName ); daemonCore->Reset_Timer( scheddPollTid, BatchStatusInterval() ); } } void CondorResource::DoPing( unsigned& ping_delay, bool& ping_complete, bool& ping_succeeded ) { int rc; int num_status_ads = 0; ClassAd **status_ads = NULL; dprintf(D_FULLDEBUG,"*** DoPing called\n"); if ( ping_gahp->isStarted() == false ) { dprintf( D_ALWAYS,"gahp server not up yet, delaying ping\n" ); ping_delay = 5; return; } ping_delay = 0; rc = ping_gahp->condor_job_status_constrained( scheddName, "False", &num_status_ads, &status_ads ); ASSERT( num_status_ads == 0 ); ASSERT( status_ads == NULL ); if ( rc == GAHPCLIENT_COMMAND_PENDING ) { ping_complete = false; } else if ( rc != 0 ) { ping_complete = true; if ( GahpErrorResourceDown( ping_gahp->getErrorString() ) ) { ping_succeeded = false; } else { ping_succeeded = true; } } else { ping_complete = true; ping_succeeded = true; } } void CondorResource::DoUpdateLeases( unsigned& update_delay, bool& update_complete, SimpleList<PROC_ID>& update_succeeded ) { int rc; BaseJob *curr_job; SimpleList<PROC_ID> jobs; SimpleList<int> expirations; SimpleList<PROC_ID> updated; dprintf(D_FULLDEBUG,"*** DoUpdateLeases called\n"); if ( lease_gahp->isStarted() == false ) { dprintf( D_ALWAYS,"gahp server not up yet, delaying lease update\n" ); update_delay = 5; return; } update_delay = 0; if ( leaseUpdates.IsEmpty() ) { dprintf( D_FULLDEBUG, "*** Job lease list empty, returning success immediately\n" ); update_complete = true; return; } if ( updateLeasesCmdActive == false ) { leaseUpdates.Rewind(); while ( leaseUpdates.Next( curr_job ) ) { // TODO When remote-job-id is homogenized and stored in // BaseJob, BaseResource can skip jobs that don't have a // a remote-job-id yet if ( ((CondorJob*)curr_job)->remoteJobId.cluster != 0 ) { jobs.Append( ((CondorJob*)curr_job)->remoteJobId ); expirations.Append( m_sharedLeaseExpiration ); } } } rc = lease_gahp->condor_job_update_lease( scheddName, jobs, expirations, updated ); if ( rc == GAHPCLIENT_COMMAND_PENDING ) { update_complete = false; } else if ( rc != 0 ) { dprintf( D_FULLDEBUG, "*** Lease update failed!\n" ); update_complete = true; } else { dprintf( D_FULLDEBUG, "*** Lease udpate succeeded!\n" ); update_complete = true; PROC_ID curr_id; std::string id_str; updated.Rewind(); while ( updated.Next( curr_id ) ) { formatstr( id_str, "condor %s %s %d.%d", scheddName, poolName, curr_id.cluster, curr_id.proc ); if ( BaseJob::JobsByRemoteId.lookup( HashKey( id_str.c_str() ), curr_job ) == 0 ) { update_succeeded.Append( curr_job->procID ); } } } }
// Copyright (c) 2018 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. // // --------------------------------------------------------------------------- // // This file was generated by the CEF translator tool. If making changes by // hand only do so within the body of existing method and function // implementations. See the translator.README.txt file in the tools directory // for more information. // // $hash=24f0d44c25fc3700e54ed2bdd692b0077e555c78$ // #include "libcef_dll/cpptoc/value_cpptoc.h" #include "libcef_dll/cpptoc/binary_value_cpptoc.h" #include "libcef_dll/cpptoc/dictionary_value_cpptoc.h" #include "libcef_dll/cpptoc/list_value_cpptoc.h" // GLOBAL FUNCTIONS - Body may be edited by hand. CEF_EXPORT cef_value_t* cef_value_create() { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute CefRefPtr<CefValue> _retval = CefValue::Create(); // Return type: refptr_same return CefValueCppToC::Wrap(_retval); } namespace { // MEMBER FUNCTIONS - Body may be edited by hand. int CEF_CALLBACK value_is_valid(struct _cef_value_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Execute bool _retval = CefValueCppToC::Get(self)->IsValid(); // Return type: bool return _retval; } int CEF_CALLBACK value_is_owned(struct _cef_value_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Execute bool _retval = CefValueCppToC::Get(self)->IsOwned(); // Return type: bool return _retval; } int CEF_CALLBACK value_is_read_only(struct _cef_value_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Execute bool _retval = CefValueCppToC::Get(self)->IsReadOnly(); // Return type: bool return _retval; } int CEF_CALLBACK value_is_same(struct _cef_value_t* self, struct _cef_value_t* that) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Verify param: that; type: refptr_same DCHECK(that); if (!that) return 0; // Execute bool _retval = CefValueCppToC::Get(self)->IsSame(CefValueCppToC::Unwrap(that)); // Return type: bool return _retval; } int CEF_CALLBACK value_is_equal(struct _cef_value_t* self, struct _cef_value_t* that) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Verify param: that; type: refptr_same DCHECK(that); if (!that) return 0; // Execute bool _retval = CefValueCppToC::Get(self)->IsEqual(CefValueCppToC::Unwrap(that)); // Return type: bool return _retval; } struct _cef_value_t* CEF_CALLBACK value_copy(struct _cef_value_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return NULL; // Execute CefRefPtr<CefValue> _retval = CefValueCppToC::Get(self)->Copy(); // Return type: refptr_same return CefValueCppToC::Wrap(_retval); } cef_value_type_t CEF_CALLBACK value_get_type(struct _cef_value_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return VTYPE_INVALID; // Execute cef_value_type_t _retval = CefValueCppToC::Get(self)->GetType(); // Return type: simple return _retval; } int CEF_CALLBACK value_get_bool(struct _cef_value_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Execute bool _retval = CefValueCppToC::Get(self)->GetBool(); // Return type: bool return _retval; } int CEF_CALLBACK value_get_int(struct _cef_value_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Execute int _retval = CefValueCppToC::Get(self)->GetInt(); // Return type: simple return _retval; } double CEF_CALLBACK value_get_double(struct _cef_value_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Execute double _retval = CefValueCppToC::Get(self)->GetDouble(); // Return type: simple return _retval; } cef_string_userfree_t CEF_CALLBACK value_get_string(struct _cef_value_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return NULL; // Execute CefString _retval = CefValueCppToC::Get(self)->GetString(); // Return type: string return _retval.DetachToUserFree(); } struct _cef_binary_value_t* CEF_CALLBACK value_get_binary(struct _cef_value_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return NULL; // Execute CefRefPtr<CefBinaryValue> _retval = CefValueCppToC::Get(self)->GetBinary(); // Return type: refptr_same return CefBinaryValueCppToC::Wrap(_retval); } struct _cef_dictionary_value_t* CEF_CALLBACK value_get_dictionary(struct _cef_value_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return NULL; // Execute CefRefPtr<CefDictionaryValue> _retval = CefValueCppToC::Get(self)->GetDictionary(); // Return type: refptr_same return CefDictionaryValueCppToC::Wrap(_retval); } struct _cef_list_value_t* CEF_CALLBACK value_get_list(struct _cef_value_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return NULL; // Execute CefRefPtr<CefListValue> _retval = CefValueCppToC::Get(self)->GetList(); // Return type: refptr_same return CefListValueCppToC::Wrap(_retval); } int CEF_CALLBACK value_set_null(struct _cef_value_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Execute bool _retval = CefValueCppToC::Get(self)->SetNull(); // Return type: bool return _retval; } int CEF_CALLBACK value_set_bool(struct _cef_value_t* self, int value) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Execute bool _retval = CefValueCppToC::Get(self)->SetBool(value ? true : false); // Return type: bool return _retval; } int CEF_CALLBACK value_set_int(struct _cef_value_t* self, int value) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Execute bool _retval = CefValueCppToC::Get(self)->SetInt(value); // Return type: bool return _retval; } int CEF_CALLBACK value_set_double(struct _cef_value_t* self, double value) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Execute bool _retval = CefValueCppToC::Get(self)->SetDouble(value); // Return type: bool return _retval; } int CEF_CALLBACK value_set_string(struct _cef_value_t* self, const cef_string_t* value) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Unverified params: value // Execute bool _retval = CefValueCppToC::Get(self)->SetString(CefString(value)); // Return type: bool return _retval; } int CEF_CALLBACK value_set_binary(struct _cef_value_t* self, struct _cef_binary_value_t* value) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Verify param: value; type: refptr_same DCHECK(value); if (!value) return 0; // Execute bool _retval = CefValueCppToC::Get(self)->SetBinary(CefBinaryValueCppToC::Unwrap(value)); // Return type: bool return _retval; } int CEF_CALLBACK value_set_dictionary(struct _cef_value_t* self, struct _cef_dictionary_value_t* value) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Verify param: value; type: refptr_same DCHECK(value); if (!value) return 0; // Execute bool _retval = CefValueCppToC::Get(self)->SetDictionary( CefDictionaryValueCppToC::Unwrap(value)); // Return type: bool return _retval; } int CEF_CALLBACK value_set_list(struct _cef_value_t* self, struct _cef_list_value_t* value) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Verify param: value; type: refptr_same DCHECK(value); if (!value) return 0; // Execute bool _retval = CefValueCppToC::Get(self)->SetList(CefListValueCppToC::Unwrap(value)); // Return type: bool return _retval; } } // namespace // CONSTRUCTOR - Do not edit by hand. CefValueCppToC::CefValueCppToC() { GetStruct()->is_valid = value_is_valid; GetStruct()->is_owned = value_is_owned; GetStruct()->is_read_only = value_is_read_only; GetStruct()->is_same = value_is_same; GetStruct()->is_equal = value_is_equal; GetStruct()->copy = value_copy; GetStruct()->get_type = value_get_type; GetStruct()->get_bool = value_get_bool; GetStruct()->get_int = value_get_int; GetStruct()->get_double = value_get_double; GetStruct()->get_string = value_get_string; GetStruct()->get_binary = value_get_binary; GetStruct()->get_dictionary = value_get_dictionary; GetStruct()->get_list = value_get_list; GetStruct()->set_null = value_set_null; GetStruct()->set_bool = value_set_bool; GetStruct()->set_int = value_set_int; GetStruct()->set_double = value_set_double; GetStruct()->set_string = value_set_string; GetStruct()->set_binary = value_set_binary; GetStruct()->set_dictionary = value_set_dictionary; GetStruct()->set_list = value_set_list; } template <> CefRefPtr<CefValue> CefCppToCRefCounted<CefValueCppToC, CefValue, cef_value_t>::UnwrapDerived( CefWrapperType type, cef_value_t* s) { NOTREACHED() << "Unexpected class type: " << type; return NULL; } #if DCHECK_IS_ON() template <> base::AtomicRefCount CefCppToCRefCounted<CefValueCppToC, CefValue, cef_value_t>::DebugObjCt ATOMIC_DECLARATION; #endif template <> CefWrapperType CefCppToCRefCounted<CefValueCppToC, CefValue, cef_value_t>::kWrapperType = WT_VALUE;
#include <game/entities/entities.h> #include <game/levels/lvl_1_creator.h> #include <lib/matlib/vec2.h> #include <whycpp/drawing.h> void Lvl1Creator::InitEntities() { auto platform_pos = Vec2((GetDisplayWidth(ctx) - 16.0) / 2, GetDisplayHeight(ctx) - 20.0); auto platform_size = Vec2(42, 7); CreatePlatform(engine->GetEntityManager(), platform_pos, platform_size); CreateBall(engine->GetEntityManager(), platform_pos, platform_size); CreateBricks(); CreateBorders(); CreateMusic(engine->GetEntityManager(), "music1"); } void Lvl1Creator::CreateBricks() { for (int i = 0; i < 13; i++) { for (int j = 1; j < 4; j++) { auto size = Vec2(15, 8); CreateBrick(engine->GetEntityManager(), Vec2(8 + i * (size.x + 1), 12 + j * (size.y + 1)), size); } } } void Lvl1Creator::CreateBorders() { CreateBorder(engine->GetEntityManager(), Vec2(GetDisplayWidth(ctx), 6), Vec2(0, 0)); // top // CreateBorder(engine, Vec2(GetDisplayWidth(ctx), 10), Vec2(0, GetDisplayHeight(ctx))); // bottom CreateBorder(engine->GetEntityManager(), Vec2(6, GetDisplayHeight(ctx)), Vec2(0, 0)); // left CreateBorder(engine->GetEntityManager(), Vec2(6, GetDisplayHeight(ctx)), Vec2(GetDisplayWidth(ctx) - 6, 0)); // right } Lvl1Creator::Lvl1Creator(Engine *engine, Context &ctx, SceneManager *scene_manager) : ILevelCreator(engine, ctx, scene_manager) {}
/********************************************************************************* * OKVIS - Open Keyframe-based Visual-Inertial SLAM * Copyright (c) 2015, Autonomous Systems Lab / ETH Zurich * * Copyright (c) 2011-2013, Paul Furgale and others. * All rights reserved. * * Unlike otherwise stated in source files, the code in this repository is * published under the Revised BSD (New BSD) license. * * 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 <organization> 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 <COPYRIGHT HOLDER> 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. *********************************************************************************/ /* * Modified: Stefan Leutenegger (s.leutenegger@imperial.ac.uk) * Modified: Andreas Forster (an.forster@gmail.com) */ #ifndef INCLUDE_OKVIS_TIMING_TIMER_HPP_ #define INCLUDE_OKVIS_TIMING_TIMER_HPP_ #ifndef BOOST_DATE_TIME_NO_LOCALE #define BOOST_DATE_TIME_NO_LOCALE #include <boost/date_time/posix_time/posix_time.hpp> #undef BOOST_DATE_TIME_NO_LOCALE #else #include <boost/date_time/posix_time/posix_time.hpp> #endif #include <mutex> #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics.hpp> #include <boost/accumulators/statistics/rolling_mean.hpp> #include <unordered_map> #include <vector> #include <okvis/assert_macros.hpp> #ifdef _WIN32 #define OKVIS_USE_HIGH_PERF_TIMER #include <windows.h> #endif namespace okvis { namespace timing { OKVIS_DEFINE_EXCEPTION(TimerException, std::runtime_error) struct TimerMapValue { // Initialize the window size for the rolling mean. TimerMapValue() : m_acc(boost::accumulators::tag::rolling_window::window_size = 50){} boost::accumulators::accumulator_set< double, boost::accumulators::features< boost::accumulators::tag::lazy_variance, boost::accumulators::tag::sum, boost::accumulators::tag::min, boost::accumulators::tag::max, boost::accumulators::tag::rolling_mean, boost::accumulators::tag::mean > > m_acc; }; // A class that has the timer interface but does nothing. // Swapping this in in place of the Timer class (say with a // typedef) should allow one to disable timing. Because all // of the functions are inline, they should just disappear. class DummyTimer { public: DummyTimer(size_t /* handle */, bool /* constructStopped */ ){} DummyTimer(size_t /* handle */){} DummyTimer(std::string const & /* tag */){} DummyTimer(std::string const & /* tag */, bool /* constructStopped */){} ~DummyTimer(){} void start(){} void stop(){} void discardTiming(){} bool isTiming(){ return false; } }; class Timer { public: Timer(size_t handle, bool constructStopped = false); Timer(std::string const & tag, bool constructStopped = false); ~Timer(); void start(); void stop(); bool isTiming(); void discardTiming(); private: #ifdef OKVIS_USE_HIGH_PERF_TIMER LARGE_INTEGER m_time; #else boost::posix_time::ptime m_time; #endif bool m_timing; size_t m_handle; }; class Timing{ public: friend class Timer; // Static funcitons to query the timers: static size_t getHandle(std::string const & tag); static std::string getTag(size_t handle); static double getTotalSeconds(size_t handle); static double getTotalSeconds(std::string const & tag); static double getMeanSeconds(size_t handle); static double getMeanSeconds(std::string const & tag); static size_t getNumSamples(size_t handle); static size_t getNumSamples(std::string const & tag); static double getVarianceSeconds(size_t handle); static double getVarianceSeconds(std::string const & tag); static double getMinSeconds(size_t handle); static double getMinSeconds(std::string const & tag); static double getMaxSeconds(size_t handle); static double getMaxSeconds(std::string const & tag); static double getHz(size_t handle); static double getHz(std::string const & tag); static void print(std::ostream & out); static void reset(size_t handle); static void reset(std::string const & tag); static std::string print(); static std::string secondsToTimeString(double seconds); private: void addTime(size_t handle, double seconds); static Timing & instance(); // Singleton design pattern Timing(); ~Timing(); typedef std::unordered_map<std::string,size_t> map_t; typedef std::vector<TimerMapValue> list_t; std::mutex addNewHandleMutex_; // Static members list_t m_timers; map_t m_tagMap; #ifdef OKVIS_USE_HIGH_PERF_TIMER double m_clockPeriod; #endif size_t m_maxTagLength; }; // end class timer #ifdef NDEBUG typedef DummyTimer DebugTimer; #else typedef Timer DebugTimer; #endif } // namespace timing } // end namespace sm #endif // INCLUDE_OKVIS_TIMING_TIMER_HPP_
// 4_move3.cpp // #include <iostream> using namespace std; // 1. 클래스 안에 포인터 변수가 있으면 얕은 복사 현상이 있다. // 2. 반드시 복사 생성자를 사용자가 만들어야 한다. class Buffer { int* resource; int size; public: Buffer(int sz) : size(sz) { resource = new int[sz]; } ~Buffer() { delete[] resource; } // lvalue, rvalue를 다 받음 // C++11 이전에는 복사생성만 있었다. // 이름 있는 객체와 임시 객체 모두에 대해서 동일한 알고리즘 사용 // C++11 이후 : 임시객체일때 복사하는 방법 // 이름 있는 객체 일때 복사하는 방법을 // 분리해서 최적화 하자. Buffer(const Buffer& b) : size (b.size) { cout << "copy 생성자" << endl; resource = new int[size]; memcpy(resource, b.resource, sizeof(int)*size); } // 인자가 임시객체가 올때, 메모리를 통째로 복사할 필요 없다. // 주소만 복사해오면 된다. // const는 빼야한다. 왜? pointer를 0으로 바꿔야해 // 임시 객체일떄는 밑에걸 사용함. // 성능향상 올라간다. Buffer(Buffer&& b) : size (b.size) { cout << "move 생성자" << endl; resource = b.resource; b.resource = 0; } }; Buffer foo() { Buffer buf(1024); return buf; } int main() { Buffer b1(1024); //Buffer b2 = b1; Buffer ret = foo(); // !! // 임시 객체 // 반환값 으로 온 것은 객체가 옴 // 깊은 복사 하지말고 얕은 복사 하자. // 얕은 복사하면 임시객체가 죽을 때.. 지우면 노답. 그래서 죽을 때 0번지를 넣어줌 // 0번지를 delete하는 건 아무 문제가 없음. // 포인터 복사로 가자. // 임시 객체 일때만 포인터를 빼가야함. }
// // // // MCStatistics.cpp // // #include <vector> #include <iterator> #include <algorithm> #include <cmath> #include<MCStatistics.h> #include <wrapper.h> using namespace std; StatisticsMean::StatisticsMean() : RunningSum(0.0), PathsDone(0UL) { } void StatisticsMean::DumpOneResult(double result) { PathsDone++; RunningSum += result; } vector<vector<double> > StatisticsMean::GetResultsSoFar() const { vector<vector<double> > Results(1); Results[0].resize(1); Results[0][0] = RunningSum / PathsDone; return Results; } StatisticsMC* StatisticsMean::clone() const { return new StatisticsMean(*this); } //Exercice 5.1 StatisticsMoments4::StatisticsMoments4() :RunningSum(0.0), RunningSum2(0.0),RunningSum3(0.0),RunningSum4(0.0),PathsDone(0UL) {} void StatisticsMoments4::DumpOneResult(double result) { PathsDone++; RunningSum += result; RunningSum2 += result* result; RunningSum3 += result * result * result; RunningSum4 += result * result * result * result; } vector<vector<double> > StatisticsMoments4::GetResultsSoFar() const { vector<vector<double> > Results(1); Results[0].resize(4); Results[0][0] = RunningSum / PathsDone; Results[0][1] = RunningSum2 / PathsDone; Results[0][2] = RunningSum3 / PathsDone; Results[0][3] = RunningSum4 / PathsDone; return Results; } StatisticsMC* StatisticsMoments4::clone() const { return new StatisticsMoments4(*this); } /* Compute historical VaR method Taken from quant finance books forum at www.markjoshi.com Re: Exercises - Chapter 5 Post by emza0114 Mon Jan 28, 2013 12:23 pm */ ValueAtRisk::ValueAtRisk(double alpha_) : alpha(alpha_) { PathsDone=0; } StatisticsMC* ValueAtRisk::clone() const { return new ValueAtRisk(*this); } void ValueAtRisk::DumpOneResult(double result) { PathData.push_back(result); ++PathsDone; } vector<vector<double> > ValueAtRisk::GetResultsSoFar() const { vector<vector<double> > Results(1); Results[0].resize(1); vector<double> tmp(PathData); sort(tmp.begin(), tmp.end()); int n(tmp.size()); int var_slot((int)(ceil(n*alpha))); Results[0][0] = tmp[var_slot]; return Results; } /* Taken from quant finance books forum at www.markjoshi.com Re: Exercise 5.3 Postby rer » Fri Apr 27, 2012 11:52 am */ StatsGatherer::StatsGatherer(const vector<Wrapper<StatisticsMC>>& GathererVector_) : GathererVector(GathererVector_),PathsDone(0UL) {} void StatsGatherer::DumpOneResult(double result) { for(unsigned long i=0;i <GathererVector.size();++i){ GathererVector[i]->DumpOneResult(result); } } vector<vector<double>> StatsGatherer::GetResultsSoFar() const { vector<vector<double> > Results(1); Results[0].resize(GathererVector.size()); for(unsigned long i = 0; i < GathererVector.size(); i++){ Results[0][i] = GathererVector[i]->GetResultsSoFar()[0][0]; } return Results; } StatisticsMC* StatsGatherer::clone() const { return new StatsGatherer(*this); } //Exercice 6.1 StatisticsSE::StatisticsSE() :RunningSum(0.0), RunningSum2(0.0),PathsDone(0UL) {} void StatisticsSE::DumpOneResult(double result) { PathsDone++; RunningSum += result; RunningSum2 += result* result; } vector<vector<double> > StatisticsSE::GetResultsSoFar() const { vector<vector<double> > Results(1); Results[0].resize(1); Results[0][0] = std::sqrt((double)((RunningSum2 - (RunningSum *RunningSum)/PathsDone)/(PathsDone - 1))/PathsDone); return Results; } StatisticsMC* StatisticsSE::clone() const { return new StatisticsSE(*this); } StatisticsVariance::StatisticsVariance() :RunningSum(0.0), RunningSum2(0.0),PathsDone(0UL) {} void StatisticsVariance::DumpOneResult(double result) { PathsDone++; RunningSum += result; RunningSum2 += result* result; } vector<vector<double> > StatisticsVariance::GetResultsSoFar() const { vector<vector<double> > Results(1); Results[0].resize(1); Results[0][0] = (RunningSum2 - (RunningSum *RunningSum) / PathsDone) / (PathsDone - 1); return Results; } StatisticsMC* StatisticsVariance::clone() const { return new StatisticsVariance(*this); } StatisticsStdDev::StatisticsStdDev() :RunningSum(0.0), RunningSum2(0.0),PathsDone(0UL) {} void StatisticsStdDev::DumpOneResult(double result) { PathsDone++; RunningSum += result; RunningSum2 += result* result; } vector<vector<double> > StatisticsStdDev::GetResultsSoFar() const { vector<vector<double> > Results(1); Results[0].resize(1); Results[0][0] = std::sqrt((double)((RunningSum2 - (RunningSum *RunningSum) / PathsDone) / (PathsDone - 1))); return Results; } StatisticsMC* StatisticsStdDev::clone() const { return new StatisticsStdDev(*this); } StatisticsRMS::StatisticsRMS() :RunningSum2(0.0),PathsDone(0UL) {} void StatisticsRMS::DumpOneResult(double result) { PathsDone++; RunningSum2 += result* result; } vector<vector<double> > StatisticsRMS::GetResultsSoFar() const { vector<vector<double> > Results(1); Results[0].resize(1); Results[0][0] = sqrt(RunningSum2/PathsDone); return Results; } StatisticsMC* StatisticsRMS::clone() const { return new StatisticsRMS(*this); } StatisticsKeepTrack::StatisticsKeepTrack() :LastNumber(0.0), PathsDone(0UL) {} void StatisticsKeepTrack::DumpOneResult(double result) { PathsDone++; LastNumber = result; } vector<vector<double> > StatisticsKeepTrack::GetResultsSoFar() const { vector<vector<double> > Results(1); Results[0].resize(1); Results[0][0] = LastNumber; return Results; } StatisticsMC* StatisticsKeepTrack::clone() const { return new StatisticsKeepTrack(*this); } /* * * Copyright (c) 2002 * Mark Joshi * * Permission to use, copy, modify, distribute and sell this * software for any purpose is hereby * granted without fee, provided that the above copyright notice * appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation. * Mark Joshi makes no representations about the * suitability of this software for any purpose. It is provided * "as is" without express or implied warranty. */
#include <iostream> #include <cmath> #include <limits> // для numeric_limits<float>::epsilon(), чтобы сравнивать результат дробных вычислений с 0 #include "command.h" // -- КОМАНДЫ ПЕРЕСЫЛКИ ДАННЫХ -- // void exchange::operator()(CPU &cpu) noexcept { const uint8_t r1_i = cpu.get_cmd_r1(); // -- получаю номера регистров -- // const uint8_t r2_i = cpu.get_cmd_r2(); std::swap(cpu.r[r1_i].u,cpu.r[r2_i].u); } void move::operator()(CPU &cpu) noexcept { const uint8_t r1_i = cpu.get_cmd_r1(); // -- получаю номера регистров -- // const uint8_t r2_i = cpu.get_cmd_r2(); cpu.r[r2_i].u = cpu.r[r1_i].u; // -- пересылка <регистр источник> -> <регистр назначения> -- // } void load::operator()(CPU &cpu) noexcept // -- пересылка память - регистр (в r2) -- // { enum load_mode { // -- значение во 1-м регистре команды является режимом загрузки, здесь перечислены все режимы -- // value_mode = 0, // -- пересылка: значение из памяти -> регистр (в r2) -- // // -- следующие два режима нужны для корректного расширения знака 16-битных операндов (в address) до 32-битных РОН -- // direct_mode = 1, // -- непосредственная загрузка целого числа со знаком вместо адреса в регистр (в r2) -- // address_mode = 2, // -- непосредственная загрузка константы-адреса (беззнаковое число) в регистр (в r2) -- // }; const uint8_t mode = cpu.get_cmd_r1(); const uint8_t r2_i = cpu.get_cmd_r2(); const uint16_t address = cpu.get_cmd_address(); switch (mode) { case value_mode: cpu.r[r2_i].u = cpu.ram.get_word(address).data.u; break; case direct_mode: cpu.r[r2_i].i = int16_t(address); // -- беру целочисленное значение из команды и помещаю его в регистр -- // break; case address_mode: cpu.r[r2_i].u = address; break; } } void save::operator()(CPU &cpu) noexcept // -- пересылка регистр (r1) - память [16][32], от длины команды зависит способ получения адреса -- // { const uint8_t t = cpu.get_cmd_t(); // -- получаю бит длины команды -- // const uint8_t r1_i = cpu.get_cmd_r1(); // -- получаю номер регистра с данными -- // const word data = {cpu.r[r1_i]}; // -- получаю данные из 1-го регистра -- // uint16_t address = 0; // -- адрес, по которому сохраняются данные из 1-го регистра -- // if (t == 0) // -- если команда короткая -- // { const uint8_t r2_i = cpu.get_cmd_r2(); // -- получаю номер регистра с адресом -- // address = uint16_t(cpu.r[r2_i].u); // -- получаю адрес из 2-го регистра -- // } else // -- если команда длинная -- // { address = cpu.get_cmd_address(); // -- получаю адрес из команды -- // } cpu.ram.push(data,address); } void dereference_ptr::operator()(CPU &cpu) noexcept { const uint8_t t = cpu.get_cmd_t(); // -- получаю бит длины команды -- // const uint8_t r1_i = cpu.get_cmd_r1(); // -- получаю номер регистра с адресом -- // const uint16_t ptr = uint16_t(cpu.r[r1_i].u); const word word = cpu.ram.get_word(ptr); if (t == 0) // -- если команда короткая, то сохраняю значение во 2-й регистр -- // { const uint8_t r2_i = cpu.get_cmd_r2(); cpu.r[r2_i] = word.data; } else // -- если команда длинная, то сохраняю значение по адресу команды -- // { const uint16_t address = cpu.get_cmd_address(); cpu.ram.push(word,address); } } // -- КОНЕЦ КОМАНДЫ ПЕРЕСЫЛКИ ДАННЫХ -- // // -- КОМАНДЫ ЦЕЛОЙ АРИФМЕТИКИ -- // void iMath::set_flags(CPU &cpu) noexcept { const uint8_t r_i = cpu.get_cmd_r2(); // -- результат помещается во 2-й операнд (регистр), поэтому получаю номер этого регистра -- // if (cpu.r[r_i].i == 0) cpu.PSW.FLAGS.ZF = 1; // -- если результат = 0, то флаг ZF = 1 -- // else cpu.PSW.FLAGS.ZF = 0; // -- иначе ZF = 0 -- // if (cpu.r[r_i].i < 0) cpu.PSW.FLAGS.SF = 1; // -- если результат < 0, то флаг SF = 1 -- // else cpu.PSW.FLAGS.SF = 0; // -- иначе SF = 0 -- // } void iMath::operator()(CPU &cpu) noexcept { const uint8_t t = cpu.get_cmd_t(); // -- получаю бит длины команды -- // const uint8_t r1_i = cpu.get_cmd_r1(); // -- получаю номера регистров -- // const uint8_t r2_i = cpu.get_cmd_r2(); if (t == 0) // -- если команда короткая (двухадресная арифметика) -- // { cpu.r[r2_i].i = calculate(cpu.r[r1_i].i, cpu.r[r2_i].i); // -- помещаю результат во второй операнд (регистр) -- // } else // -- если команда длинная (трехадресная арифметика) -- // { const uint16_t base_address = uint16_t(cpu.r[r1_i].u); // -- базовый адрес в первом регистре -- // const uint16_t offset = cpu.get_cmd_address(); // -- смещение в команде -- // const uint16_t address = base_address + offset; int32_t value = cpu.ram.get_word(address).data.i; cpu.r[r2_i].i = calculate(value, cpu.r[r2_i].i); } set_flags(cpu); // -- устанавливаю флаги -- // } // -- КОНЕЦ КОМАНДЫ ЦЕЛОЙ АРИФМЕТИКИ -- // // -- КОМАНДЫ ДРОБНОЙ АРИФМЕТИКИ -- // void fMath::set_flags(CPU &cpu) noexcept { const uint8_t r_i = cpu.get_cmd_r2(); // -- результат помещается во 2-й операнд (регистр), поэтому получаю номер этого регистра -- // if (fabsf(cpu.r[r_i].f) <= std::numeric_limits<float>::epsilon()) cpu.PSW.FLAGS.ZF = 1; // -- если результат = 0, то флаг ZF = 1 -- // else cpu.PSW.FLAGS.ZF = 0; // -- иначе ZF = 0 -- // if (cpu.r[r_i].f < 0) cpu.PSW.FLAGS.SF = 1; // -- если результат < 0, то флаг SF = 1 -- // else cpu.PSW.FLAGS.SF = 0; // -- иначе SF = 0 -- // } void fMath::operator()(CPU &cpu) noexcept { const uint8_t t = cpu.get_cmd_t(); // -- получаю бит длины команды -- // const uint8_t r1_i = cpu.get_cmd_r1(); // -- получаю номера регистров -- // const uint8_t r2_i = cpu.get_cmd_r2(); if (t == 0) // -- если команда короткая (двухадресная арифметика) -- // { cpu.r[r2_i].f = calculate(cpu.r[r1_i].f, cpu.r[r2_i].f); // -- помещаю результат во второй операнд (регистр) -- // } else // -- если команда длинная (трехадресная арифметика) -- // { const uint16_t base_address = uint16_t(cpu.r[r1_i].u); // -- базовый адрес в первом регистре -- // const uint16_t offset = cpu.get_cmd_address(); // -- смещение в команде -- // const uint16_t address = base_address + offset; float value = cpu.ram.get_word(address).data.f; cpu.r[r2_i].f = calculate(value, cpu.r[r2_i].f); } set_flags(cpu); // -- устанавливаю флаги -- // } // -- КОНЕЦ КОМАНДЫ ДРОБНОЙ АРИФМЕТИКИ -- // // -- КОМАНДЫ ВВОДА И ВЫВОДА -- // void io::operator()(CPU &cpu) noexcept { enum io_mode { // -- значение во 2-м регистре команды является режимом ввода-вывода, здесь перечислены все режимы -- // in_int = 0, // -- ввод целого числа -- // in_uint = 1, // -- ввод беззнакового числа -- // in_float = 2, // -- ввод дробного числа -- // out_int = 3, // -- вывод целого числа -- // out_uint = 4, // -- вывод беззнакового числа -- // out_float = 5 // -- вывод дробного числа -- // }; const uint8_t t = cpu.get_cmd_t(); // -- получаю бит длины команды -- // const uint8_t r1_i = cpu.get_cmd_r1(); // -- получаю номер регистра с результатом -- // const uint8_t mode = cpu.get_cmd_r2(); // -- получаю режим ввода-вывода -- // const uint16_t address = cpu.get_cmd_address(); // -- получаю адрес, находящийся в команде -- // switch (mode) { case in_int: std::cout << std::endl << "input int: "; if (t == 0) // -- если команда короткая -- // { std::cin >> cpu.r[r1_i].i; } else // -- если команда длинная -- // { word data; std::cin >> data.data.i; cpu.ram.push(data,address); } break; case in_uint: std::cout << std::endl << "input unsigned int: "; if (t == 0) // -- если команда короткая -- // { std::cin >> cpu.r[r1_i].u; } else // -- если команда длинная -- // { word data; std::cin >> data.data.u; cpu.ram.push(data,address); } break; case in_float: std::cout << std::endl << "input float: "; if (t == 0) // -- если команда короткая -- // { std::cin >> cpu.r[r1_i].f; } else // -- если команда длинная -- // { word data; std::cin >> data.data.f; cpu.ram.push(data,address); } break; case out_int: std::cout << std::endl << "int: "; if (t == 0) // -- если команда короткая -- // { std::cout << cpu.r[r1_i].i << std::endl; } else // -- если команда длинная -- // { std::cout << cpu.ram.get_word(address).data.i << std::endl; } break; case out_uint: std::cout << std::endl << "unsigned int: "; if (t == 0) // -- если команда короткая -- // { std::cout << cpu.r[r1_i].u << std::endl; } else // -- если команда длинная -- // { std::cout << cpu.ram.get_word(address).data.u << std::endl; } break; case out_float: std::cout << std::endl << "float: " << std::fixed; if (t == 0) // -- если команда короткая -- // { std::cout << cpu.r[r1_i].f << std::endl; } else // -- если команда длинная -- // { std::cout << cpu.ram.get_word(address).data.f << std::endl; } break; } } // -- КОНЕЦ КОМАНДЫ ВВОДА И ВЫВОДА -- // // -- КОМАНДЫ ПЕРЕХОДОВ -- // void Jump::operator()(CPU &cpu) noexcept { call_go_to(cpu); } void Jump::go_to(CPU &cpu) noexcept { enum jmp_mode { // -- значение во 1-м регистре команды является режимом перехода, здесь перечислены все режимы -- // direct_mode = 0, // -- прямой переход -- // offset_plus_mode = 1, // -- относительный переход вперед -- // offset_minus_mode = 2 // -- относительный переход назад -- // }; const uint8_t t = cpu.get_cmd_t(); // -- получаю бит длины команды -- // uint16_t address = cpu.PSW.IP; // -- адрес, для операции go_to, изначально пусть адрес равен IP -- // if (t == 0) // -- если команда короткая - значит косвенный переход -- // { const uint8_t r2_i = cpu.get_cmd_r2(); // -- получаю номер 2-ого регистра -- // address = uint16_t(cpu.r[r2_i].u); } else // -- если команда длинная -- // { const uint8_t mode = cpu.get_cmd_r1(); // -- получаю режим перехода -- // const uint16_t cmd_address = cpu.get_cmd_address(); // -- получаю адрес из команды -- // switch (mode) { case direct_mode: address = cmd_address; break; case offset_plus_mode: address += cmd_address; break; case offset_minus_mode: address -= cmd_address; break; } } cpu.PSW.IP = address; set_was_transition(cpu); } void jmp::call_go_to(CPU &cpu) noexcept { go_to(cpu); } void jzf::call_go_to(CPU &cpu) noexcept { if (cpu.PSW.FLAGS.ZF) go_to(cpu); } void jnzf::call_go_to(CPU &cpu) noexcept { if (!cpu.PSW.FLAGS.ZF) go_to(cpu); } void jsf::call_go_to(CPU &cpu) noexcept { if (cpu.PSW.FLAGS.SF) go_to(cpu); } void jnsf::call_go_to(CPU &cpu) noexcept { if (!cpu.PSW.FLAGS.SF) go_to(cpu); } void call::call_go_to(CPU &cpu) noexcept { cpu.r[15].u = cpu.PSW.IP; go_to(cpu); } void ret::call_go_to(CPU &cpu) noexcept { cpu.PSW.IP = uint16_t(cpu.r[15].u); } // -- КОНЕЦ КОМАНДЫ ПЕРЕХОДОВ -- //
#include "nod/nod.hpp" #include <cstdio> #include "nod/DiscBase.hpp" #include "nod/DiscGCN.hpp" #include "nod/DiscWii.hpp" namespace nod { logvisor::Module LogModule("nod"); std::unique_ptr<IDiscIO> NewDiscIOISO(std::string_view path); std::unique_ptr<IDiscIO> NewDiscIOWBFS(std::string_view path); std::unique_ptr<IDiscIO> NewDiscIONFS(std::string_view path); std::unique_ptr<DiscBase> OpenDiscFromImage(std::string_view path, bool& isWii) { /* Temporary file handle to determine image type */ std::unique_ptr<IFileIO> fio = NewFileIO(path); if (!fio->exists()) { LogModule.report(logvisor::Error, FMT_STRING("Unable to open '{}'"), path); return {}; } std::unique_ptr<IFileIO::IReadStream> rs = fio->beginReadStream(); if (!rs) return {}; isWii = false; std::unique_ptr<IDiscIO> discIO; uint32_t magic = 0; if (rs->read(&magic, 4) != 4) { LogModule.report(logvisor::Error, FMT_STRING("Unable to read magic from '{}'"), path); return {}; } using SignedSize = std::make_signed<std::string::size_type>::type; const auto dotPos = SignedSize(path.rfind('.')); const auto slashPos = SignedSize(path.find_last_of("/\\")); if (magic == nod::SBig((uint32_t)'WBFS')) { discIO = NewDiscIOWBFS(path); isWii = true; } else if (path.size() > 4 && dotPos != -1 && dotPos > slashPos && !path.compare(slashPos + 1, 4, "hif_") && !path.compare(dotPos, path.size() - dotPos, ".nfs")) { discIO = NewDiscIONFS(path); isWii = true; } else { rs->seek(0x18, SEEK_SET); rs->read(&magic, 4); magic = nod::SBig(magic); if (magic == 0x5D1C9EA3) { discIO = NewDiscIOISO(path); isWii = true; } else { rs->read(&magic, 4); magic = nod::SBig(magic); if (magic == 0xC2339F3D) discIO = NewDiscIOISO(path); } } if (!discIO) { LogModule.report(logvisor::Error, FMT_STRING("'{}' is not a valid image"), path); return {}; } bool err = false; std::unique_ptr<DiscBase> ret; if (isWii) { ret = std::make_unique<DiscWii>(std::move(discIO), err); if (err) return {}; return ret; } ret = std::make_unique<DiscGCN>(std::move(discIO), err); if (err) return {}; return ret; } std::unique_ptr<DiscBase> OpenDiscFromImage(std::string_view path) { bool isWii; return OpenDiscFromImage(path, isWii); } } // namespace nod
/* * See header file for a description of this class. * * \author G. Mila - INFN Torino * * threadsafe version (//-) oct/nov 2014 - WATWanAbdullah -ncpp-um-my * */ #include <DQM/DTMonitorClient/src/DTNoiseAnalysisTest.h> // Framework #include "FWCore/ServiceRegistry/interface/Service.h" #include <FWCore/Framework/interface/EventSetup.h> #include <FWCore/ParameterSet/interface/ParameterSet.h> // Geometry #include "Geometry/Records/interface/MuonGeometryRecord.h" #include "Geometry/DTGeometry/interface/DTGeometry.h" #include "Geometry/DTGeometry/interface/DTLayer.h" #include "Geometry/DTGeometry/interface/DTTopology.h" #include <DataFormats/MuonDetId/interface/DTLayerId.h> #include "DQMServices/Core/interface/DQMStore.h" #include "DQMServices/Core/interface/MonitorElement.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include <iostream> #include <sstream> using namespace edm; using namespace std; DTNoiseAnalysisTest::DTNoiseAnalysisTest(const edm::ParameterSet& ps) { LogTrace("DTDQM|DTMonitorClient|DTNoiseAnalysisTest") << "[DTNoiseAnalysisTest]: Constructor"; // get the cfi parameters noisyCellDef = ps.getUntrackedParameter<int>("noisyCellDef", 500); // switch on/off the summaries for the Synchronous noise doSynchNoise = ps.getUntrackedParameter<bool>("doSynchNoise", false); detailedAnalysis = ps.getUntrackedParameter<bool>("detailedAnalysis", false); maxSynchNoiseRate = ps.getUntrackedParameter<double>("maxSynchNoiseRate", 0.001); nMinEvts = ps.getUntrackedParameter<int>("nEventsCert", 5000); nevents = 0; bookingdone = false; } DTNoiseAnalysisTest::~DTNoiseAnalysisTest() { LogTrace("DTDQM|DTMonitorClient|DTNoiseAnalysisTest") << "DTNoiseAnalysisTest: analyzed " << nevents << " events"; } void DTNoiseAnalysisTest::beginRun(Run const& run, EventSetup const& context) { // Get the geometry context.get<MuonGeometryRecord>().get(muonGeom); } void DTNoiseAnalysisTest::dqmEndLuminosityBlock(DQMStore::IBooker& ibooker, DQMStore::IGetter& igetter, edm::LuminosityBlock const& lumiSeg, edm::EventSetup const& context) { float chRate; if (!bookingdone) { // book the histos bookHistos(ibooker); } bookingdone = true; LogVerbatim("DTDQM|DTMonitorClient|DTNoiseAnalysisTest") << "[DTNoiseAnalysisTest]: End of LS transition, performing the DQM client operation"; // Reset the summary plots for (map<int, MonitorElement*>::iterator plot = noiseHistos.begin(); plot != noiseHistos.end(); ++plot) { (*plot).second->Reset(); } for (map<int, MonitorElement*>::iterator plot = noisyCellHistos.begin(); plot != noisyCellHistos.end(); ++plot) { (*plot).second->Reset(); } summaryNoiseHisto->Reset(); vector<const DTChamber*>::const_iterator ch_it = muonGeom->chambers().begin(); vector<const DTChamber*>::const_iterator ch_end = muonGeom->chambers().end(); LogTrace("DTDQM|DTMonitorClient|DTNoiseAnalysisTest") << "[DTNoiseAnalysisTest]: Fill the summary histos"; for (; ch_it != ch_end; ++ch_it) { // loop over chambers DTChamberId chID = (*ch_it)->id(); MonitorElement* histo = igetter.get(getMEName(chID)); if (histo) { // check the pointer TH2F* histo_root = histo->getTH2F(); for (int sl = 1; sl != 4; ++sl) { // loop over SLs // skip theta SL in MB4 chambers if (chID.station() == 4 && sl == 2) continue; int binYlow = ((sl - 1) * 4) + 1; for (int layer = 1; layer <= 4; ++layer) { // loop over layers // Get the layer ID DTLayerId layID(chID, sl, layer); int nWires = muonGeom->layer(layID)->specificTopology().channels(); int firstWire = muonGeom->layer(layID)->specificTopology().firstChannel(); int binY = binYlow + (layer - 1); for (int wire = firstWire; wire != (nWires + firstWire); wire++) { // loop over wires double noise = histo_root->GetBinContent(wire, binY); // fill the histos noiseHistos[chID.wheel()]->Fill(noise); noiseHistos[3]->Fill(noise); int sector = chID.sector(); if (noise > noisyCellDef) { if (sector == 13) { sector = 4; } else if (sector == 14) { sector = 10; } noisyCellHistos[chID.wheel()]->Fill(sector, chID.station()); summaryNoiseHisto->Fill(sector, chID.wheel()); } } } } } } if (detailedAnalysis) { threshChannelsHisto->Reset(); TH1F* histo = noiseHistos[3]->getTH1F(); for (int step = 0; step != 15; step++) { int threshBin = step + 1; int minBin = 26 + step * 5; int nNoisyCh = histo->Integral(minBin, 101); threshChannelsHisto->setBinContent(threshBin, nNoisyCh); } } // build the summary of synch noise if (doSynchNoise) { LogTrace("DTDQM|DTMonitorClient|DTNoiseAnalysisTest") << "[DTNoiseAnalysisTest]: fill summaries for synch noise" << endl; summarySynchNoiseHisto->Reset(); glbSummarySynchNoiseHisto->Reset(); for (int wheel = -2; wheel != 3; ++wheel) { // Get the histo produced by DTDigiTask MonitorElement* histoNoiseSynch = igetter.get(getSynchNoiseMEName(wheel)); if (histoNoiseSynch != nullptr) { for (int sect = 1; sect != 13; ++sect) { // loop over sectors TH2F* histo = histoNoiseSynch->getTH2F(); float maxSectRate = 0; for (int sta = 1; sta != 5; ++sta) { if (nevents > 0) chRate = histo->GetBinContent(sect, sta) / (float)nevents; else chRate = -1.0; // in case nevents 0 e.g. counting not done LogTrace("DTDQM|DTMonitorClient|DTNoiseAnalysisTest") << " Wheel: " << wheel << " sect: " << sect << " station: " << sta << " rate is: " << chRate << endl; if (chRate > maxSectRate) maxSectRate = chRate; } summarySynchNoiseHisto->Fill(sect, wheel, maxSectRate > maxSynchNoiseRate ? 1 : 0); float glbBinValue = 1 - 0.15 * maxSectRate / maxSynchNoiseRate; glbSummarySynchNoiseHisto->Fill(sect, wheel, glbBinValue > 0 ? glbBinValue : 0); } } else { LogWarning("DTDQM|DTMonitorClient|DTNoiseAnalysisTest") << " Histo: " << getSynchNoiseMEName(wheel) << " not found!" << endl; } } } string nEvtsName = "DT/EventInfo/Counters/nProcessedEventsNoise"; MonitorElement* meProcEvts = igetter.get(nEvtsName); if (meProcEvts) { int nProcEvts = meProcEvts->getFloatValue(); glbSummarySynchNoiseHisto->setEntries(nProcEvts < nMinEvts ? 10. : nProcEvts); summarySynchNoiseHisto->setEntries(nProcEvts < nMinEvts ? 10. : nProcEvts); } else { glbSummarySynchNoiseHisto->setEntries(nMinEvts + 1); summarySynchNoiseHisto->setEntries(nMinEvts + 1); LogVerbatim("DTDQM|DTMonitorClient|DTnoiseAnalysisTest") << "[DTNoiseAnalysisTest] ME: " << nEvtsName << " not found!" << endl; } } string DTNoiseAnalysisTest::getMEName(const DTChamberId& chID) { stringstream wheel; wheel << chID.wheel(); stringstream station; station << chID.station(); stringstream sector; sector << chID.sector(); string folderName = "DT/05-Noise/Wheel" + wheel.str() + "/Sector" + sector.str() + "/"; string histoname = folderName + string("NoiseRate") + "_W" + wheel.str() + "_St" + station.str() + "_Sec" + sector.str(); return histoname; } void DTNoiseAnalysisTest::bookHistos(DQMStore::IBooker& ibooker) { ibooker.setCurrentFolder("DT/05-Noise"); string histoName; for (int wh = -2; wh <= 2; wh++) { stringstream wheel; wheel << wh; histoName = "NoiseRateSummary_W" + wheel.str(); noiseHistos[wh] = ibooker.book1D(histoName.c_str(), histoName.c_str(), 100, 0, 2000); noiseHistos[wh]->setAxisTitle("rate (Hz)", 1); noiseHistos[wh]->setAxisTitle("entries", 2); } histoName = "NoiseRateSummary"; noiseHistos[3] = ibooker.book1D(histoName.c_str(), histoName.c_str(), 100, 0, 2000); noiseHistos[3]->setAxisTitle("rate (Hz)", 1); noiseHistos[3]->setAxisTitle("entries", 2); for (int wh = -2; wh <= 2; wh++) { stringstream wheel; wheel << wh; histoName = "NoiseSummary_W" + wheel.str(); noisyCellHistos[wh] = ibooker.book2D(histoName.c_str(), "# of noisy channels", 12, 1, 13, 4, 1, 5); noisyCellHistos[wh]->setBinLabel(1, "MB1", 2); noisyCellHistos[wh]->setBinLabel(2, "MB2", 2); noisyCellHistos[wh]->setBinLabel(3, "MB3", 2); noisyCellHistos[wh]->setBinLabel(4, "MB4", 2); noisyCellHistos[wh]->setAxisTitle("Sector", 1); } histoName = "NoiseSummary"; summaryNoiseHisto = ibooker.book2D(histoName.c_str(), "# of noisy channels", 12, 1, 13, 5, -2, 3); summaryNoiseHisto->setAxisTitle("Sector", 1); summaryNoiseHisto->setAxisTitle("Wheel", 2); if (detailedAnalysis) { histoName = "NoisyChannels"; threshChannelsHisto = ibooker.book1D(histoName.c_str(), "# of noisy channels vs threshold", 15, 500, 2000); threshChannelsHisto->setAxisTitle("threshold", 1); threshChannelsHisto->setAxisTitle("# noisy channels", 2); } if (doSynchNoise) { ibooker.setCurrentFolder("DT/05-Noise/SynchNoise/"); histoName = "SynchNoiseSummary"; summarySynchNoiseHisto = ibooker.book2D(histoName.c_str(), "Summary Synch. Noise", 12, 1, 13, 5, -2, 3); summarySynchNoiseHisto->setAxisTitle("Sector", 1); summarySynchNoiseHisto->setAxisTitle("Wheel", 2); histoName = "SynchNoiseGlbSummary"; glbSummarySynchNoiseHisto = ibooker.book2D(histoName.c_str(), "Summary Synch. Noise", 12, 1, 13, 5, -2, 3); glbSummarySynchNoiseHisto->setAxisTitle("Sector", 1); glbSummarySynchNoiseHisto->setAxisTitle("Wheel", 2); } } string DTNoiseAnalysisTest::getSynchNoiseMEName(int wheelId) const { stringstream wheel; wheel << wheelId; string folderName = "DT/05-Noise/SynchNoise/"; string histoname = folderName + string("SyncNoiseEvents") + "_W" + wheel.str(); return histoname; } void DTNoiseAnalysisTest::dqmEndJob(DQMStore::IBooker& ibooker, DQMStore::IGetter& igetter) {}
/** @file main.cpp * @brief The main entry point. * * @author Hamdi Rakkez */ // Standard includes. #include <cstdlib> #include <limits> #include <ctype.h> // Other includes. #include "dict_utils.hpp" #include "string_utils.hpp" // For progress. #define PBSTR "||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||" #define PBWIDTH 60 using namespace std; /** * Prints the results along with the search criteria used. * * @param res The vector containing the results. * @param Ne The accepted number of errors in characters. 0 by default. * @param Ns The accepted number of missing characters. 0 by default. * @param Na The accepted number of extra characters. 0 by default. */ void printResults(const vector<string> res, const size_t Ne = 0, const size_t Ns = 0, const size_t Na = 0); /* * Main Entry point. */ int main() { // The tree structure. tree<char> tr; // The tree root node. //tr.insert(tr.begin(), '.'); tr.set_head('.'); // The choice to navigate through the program's Menu. char choice; do { cout << "___________ " << endl; cout << "\\__ ___/______ ____ ____ " << endl; cout << " | | \\_ __ \\_/ __ \\_/ __ \\ " << endl; cout << " | | | | \\/\\ ___/\\ ___/ " << endl; cout << " |____| |__| \\___ >\\___ >" << endl; cout << " \\/ \\/" << endl << endl; cout << " 1 - Load dictionary from file(Word/Line)." << endl; cout << " 2 - Search for a word in the dictionary." << endl; cout << " 3 - Add a word to the dictionary." << endl; cout << " 4 - Add list of words to the dictionary." << endl; cout << " 5 - Show/Print current dictionary." << endl; cout << " 6 - Clear the current dictionary." << endl; cout << " 7 - Exit." << endl << endl; cout << "[INPUT] Enter your choice and press Enter: "; cin >> choice; system("clear"); switch (choice) { // Loading dictionary. case '1': { string path = ""; cout << "[INPUT] Enter the name or the full path for the " "dictionary." << endl; cin >> path; system("clear"); size_t wordsNumber = 0; ifstream file(path); // When the file don't exist. if (!file.is_open()) { cout << "[LOG_WARNING] Invalid path for dictionary!" << endl; break; } /* The string which will be holding each word to insert into * the dictionary. */ string str; cout << "[LOG_INFO] Loading dictionary '" << path << "' in the tree..." << endl; cout << "[LOG_INFO] This can take some time depending on the " "dictionary" << endl; // Getting start clock. int start = clock(); while (getline(file, str)) { // Convert the word to lower case first. toLower(str); // Insert the word. Don't show log. insertWord(str, tr, false); wordsNumber++; } // Getting stop clock. int stop = clock(); // Printing execution time in ms. cout << endl << "[LOG_CHRONO] Inserting '" << wordsNumber << "' words in the dictionary took: " << (stop - start) / double(CLOCKS_PER_SEC) * 1000 << " ms" << endl; cout << "[LOG_INFO] The dictionary '" << path << "' was loaded into the tree !" << endl; cout << endl << "[LOG_INFO] " << wordsNumber << " word(s) added to " "the tree dictionary." << endl; cout << endl << "[LOG_INFO] " << "The dictionary's depth is : " << tr.max_depth() << endl; } break; case '2': { // We make sure the dictionary is not empty. if (tr.empty()) { cout << "[LOG_WARNING] The dictionary is empty!" << endl; cout << "[LOG_INFO] Load a dictionary or add words first." << endl; break; } string word = ""; cout << "[INPUT] Enter a word to search for." << endl; cin >> word; system("clear"); // Converts the word to lower case. toLower(word); char searchCriteria; do { cout << "[INPUT] Do you want to set a search criteria for '" << word << "' ? (y/n) "; cin >> searchCriteria; system("clear"); if (searchCriteria == 'n') { // Call searchForWords without any criteria. vector<string> res = searchForWords(word, tr); printResults(res); } else if (searchCriteria == 'y') { size_t wrongCharacters; size_t addedCharacters; size_t missingCharacters; cout << "[INPUT] Enter the N° of accepted wrong " "characters for '" << word << "' : "; cin >> wrongCharacters; cout << "[INPUT] Enter the N° of accepted added " "characters for '" << word << "' : "; cin >> addedCharacters; cout << "[INPUT] Enter the N° of accepted missing " "characters for '" << word << "' : "; cin >> missingCharacters; system("clear"); // Call searchForWords with the given criteria. vector<string> res = searchForWords(word, tr, wrongCharacters, missingCharacters, addedCharacters); printResults(res, wrongCharacters, missingCharacters, addedCharacters); } } while ((searchCriteria != 'y') && (searchCriteria != 'n')); } cout << endl << "[INPUT] Press [r] then [Enter] to return " "to the Menu ..." << endl; cin.ignore(numeric_limits<streamsize>::max(),'r'); system("clear"); break; case '3': { string word = ""; cout << "[LOG_INPUT] Enter a word to add to the dictionary." << endl; cin >> word; // Converts the word to lower case. toLower(word); // We add the word. insertWord(word, tr); cout << endl << "[INPUT] Press [r] then [Enter] to return " "to the Menu ..." << endl; cin.ignore(numeric_limits<streamsize>::max(),'r'); } system("clear"); break; case '4': { string word = ""; cout << "[LOG_INPUT] Enter the list of words to add to the " "dictionary." << endl; cout << "[LOG_INFO] Words should be separated by a comma ','" << endl << endl; cin >> word; // Converts the word to lower case. toLower(word); // We add the word. insertWords(word, tr); cout << endl << "[INPUT] Press [r] then [Enter] to return to " "the main Menu ..." << endl; cin.ignore(numeric_limits<streamsize>::max(),'r'); } system("clear"); break; case '5': { // We make sure the dictionary is not empty. if (tr.empty()) { cout << "[LOG_WARNING] The dictionary is empty!" << endl; cout << "[LOG_INFO] Load a dictionary or add words first." << endl; break; } cout << "[LOG_INFO] The loaded dictionary :" << endl; kptree::print_tree_bracketed(tr, cout); cout << endl; cout << endl << "[INPUT] Press [r] then [Enter] to return to " "the main Menu ..." << endl; cin.ignore(numeric_limits<streamsize>::max(),'r'); } system("clear"); break; case '6': { tr.clear(); cout << "[LOG_INFO] The dictionary is cleared." << endl; cout << endl; cout << endl << "[INPUT] Press [r] then [Enter] to return to " "the main Menu ..." << endl; cin.ignore(numeric_limits<streamsize>::max(),'r'); } system("clear"); break; case '7': // End of program. return EXIT_SUCCESS; default: cout << "[LOG_WARNING] You have entered an invalid choice!" << endl << "[INPUT] Please choose again !" << endl << endl; continue; } } while (1); return EXIT_SUCCESS; } void printResults(const vector<string> res, const size_t Ne, const size_t Ns, const size_t Na) { if (!res.empty()) { cout << "[LOG_INFO] We found " << res.size() << " result(s)." << endl; cout << "[LOG_INFO] Search criteria is : " << endl; cout << " - Accepted wrong characters : " << Ne << endl; cout << " - Accepted extra characters : " << Na << endl; cout << " - Accepted missing characters : " << Ns << endl; cout << "[LOG_INFO] Results : " << endl; // Print results. for (vector<string>::const_iterator it = res.begin(); it != res.end(); it++) { cout << " - " << (*it) << endl; } } else { cout << "[LOG_INFO] No results were found matching your search!" << endl; } }
/* * Copyright 2021 ServiceNow * 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 "bytesteady/model.hpp" #include "gtest/gtest.h" #include "thunder/linalg.hpp" #include "thunder/random.hpp" #include "thunder/serializer.hpp" namespace bytesteady { namespace { template < typename M > void forwardUpdateTest() { typedef typename M::byte_array byte_array; typedef typename M::field_array field_array; typedef typename M::index_array index_array; typedef typename M::size_type size_type; typedef typename M::tensor_type tensor_type; typedef typename M::tensor_array tensor_array; typedef typename M::value_type value_type; ::thunder::Random< tensor_type > random; // Create Model M model({16, 32}, 3, 10, {{},{1,2,3,4}}, 1946); model.initialize(0.0, 1.0); // Create input field_array input; input.push_back(index_array{ ::std::make_pair(size_type(4), value_type(0.6)), ::std::make_pair(size_type(3), value_type(0.88))}); input.push_back(byte_array({22, 0, 255, 4, 9, 88, 126, 30})); // Forward on the model const tensor_type &output = model.forward(input); EXPECT_EQ(1, output.dimension()); EXPECT_EQ(3, output.size(0)); // (TODO): check correctness of output // Create gradient with respect to the output tensor_type grad_output = random.normal( tensor_type(output.size(0)), 0.0, 1.0); // Update the parameters model.update(input, grad_output, 0.001, 0.00001); // TODO(Xiang): check correctness of updated parameters } TEST(ModelTest, forwardUpdateTest) { forwardUpdateTest< DoubleFNVModel >(); } template < typename M > void saveLoadTest() { typedef typename M::size_type size_type; typedef typename M::tensor_type tensor_type; typedef typename M::tensor_array tensor_array; ::thunder::StringBinarySerializer serializer; // Create Model M model1({16, 32}, 3, 10, {{1,2,3,4,5}}, 1948); // Save model to file serializer.save(model1); // Create another model M model2({2, 9}, 2, 7, {{3}}, 1999); // Load model serializer.load(&model2); EXPECT_EQ(model1.gram(), model2.gram()); EXPECT_EQ(model1.seed(), model2.seed()); EXPECT_EQ(model1.input_size(), model2.input_size()); EXPECT_EQ(model1.dimension(), model2.dimension()); for (size_type i = 0; i < model1.input_size(); ++i) { EXPECT_EQ(model1.input_embedding_size(i), model2.input_embedding_size(i)); } EXPECT_EQ(model1.output_embedding_size(), model2.output_embedding_size()); const tensor_array &input_embedding1 = model1.input_embedding(); const tensor_array &input_embedding2 = model2.input_embedding(); for (size_type i = 0; i < input_embedding1.size(); ++i) { for (size_type j = 0; j < input_embedding1[i].size(0); ++j) { for (size_type k = 0; k < input_embedding1[i].size(1); ++k) { EXPECT_FLOAT_EQ(input_embedding1[i](j, k), input_embedding2[i](j, k)); } } } const tensor_type &output_embedding1 = model1.output_embedding(); const tensor_type &output_embedding2 = model2.output_embedding(); for (size_type i = 0; i < output_embedding1.size(0); ++i) { for (size_type j = 0; j < output_embedding1.size(1); ++j) { EXPECT_FLOAT_EQ(output_embedding1(i, j), output_embedding2(i, j)); } } } TEST(ModelTest, saveLoadTest) { saveLoadTest< DoubleFNVModel >(); } template < typename M > void cloneTest() { typedef typename M::size_type size_type; typedef typename M::tensor_type tensor_type; typedef typename M::tensor_array tensor_array; // Create Model M model1({16, 32}, 3, 10, {{1,2,3,4,5}}, 1948); // Clone with sharing M model2 = model1.clone(); EXPECT_EQ(model1.gram(), model2.gram()); EXPECT_EQ(model1.seed(), model2.seed()); EXPECT_EQ(model1.input_size(), model2.input_size()); EXPECT_EQ(model1.dimension(), model2.dimension()); for (size_type i = 0; i < model1.input_size(); ++i) { EXPECT_EQ(model1.input_embedding_size(i), model2.input_embedding_size(i)); } EXPECT_EQ(model1.output_embedding_size(), model2.output_embedding_size()); const tensor_array &input_embedding1 = model1.input_embedding(); const tensor_array &input_embedding2 = model2.input_embedding(); for (size_type i = 0; i < input_embedding1.size(); ++i) { EXPECT_EQ(input_embedding1[i].storage(), input_embedding2[i].storage()); for (size_type j = 0; j < input_embedding1[i].size(0); ++j) { for (size_type k = 0; k < input_embedding1[i].size(1); ++k) { EXPECT_FLOAT_EQ(input_embedding1[i](j, k), input_embedding2[i](j, k)); } } } const tensor_type &output_embedding1 = model1.output_embedding(); const tensor_type &output_embedding2 = model2.output_embedding(); EXPECT_EQ(output_embedding1.storage(), output_embedding2.storage()); for (size_type i = 0; i < output_embedding1.size(0); ++i) { for (size_type j = 0; j < output_embedding1.size(1); ++j) { EXPECT_FLOAT_EQ(output_embedding1(i, j), output_embedding2(i, j)); } } EXPECT_NE(model1.feature().storage(), model2.feature().storage()); EXPECT_NE(model1.grad_feature().storage(), model2.grad_feature().storage()); EXPECT_NE(model1.output().storage(), model2.output().storage()); // Clone without sharing M model3 = model1.clone(false); EXPECT_EQ(model1.gram(), model3.gram()); EXPECT_EQ(model1.seed(), model3.seed()); EXPECT_EQ(model1.input_size(), model3.input_size()); EXPECT_EQ(model1.dimension(), model3.dimension()); for (size_type i = 0; i < model1.input_size(); ++i) { EXPECT_EQ(model1.input_embedding_size(i), model3.input_embedding_size(i)); } EXPECT_EQ(model1.output_embedding_size(), model3.output_embedding_size()); const tensor_array &input_embedding3 = model3.input_embedding(); for (size_type i = 0; i < input_embedding1.size(); ++i) { EXPECT_NE(input_embedding1[i].storage(), input_embedding3[i].storage()); for (size_type j = 0; j < input_embedding1[i].size(0); ++j) { for (size_type k = 0; k < input_embedding1[i].size(1); ++k) { EXPECT_FLOAT_EQ(input_embedding1[i](j, k), input_embedding3[i](j, k)); } } } const tensor_type &output_embedding3 = model3.output_embedding(); EXPECT_NE(output_embedding1.storage(), output_embedding3.storage()); for (size_type i = 0; i < output_embedding1.size(0); ++i) { for (size_type j = 0; j < output_embedding1.size(1); ++j) { EXPECT_FLOAT_EQ(output_embedding1(i, j), output_embedding3(i, j)); } } EXPECT_NE(model1.feature().storage(), model3.feature().storage()); EXPECT_NE(model1.grad_feature().storage(), model3.grad_feature().storage()); EXPECT_NE(model1.output().storage(), model3.output().storage()); } TEST(ModelTest, cloneTest) { cloneTest< DoubleFNVModel >(); } } // namespace } // namespace bytesteady
/* Copyright (c) 2010-2018, Delft University of Technology * All rigths reserved * * This file is part of the Tudat. Redistribution and use in source and * binary forms, with or without modification, are permitted exclusively * under the terms of the Modified BSD license. You should have received * a copy of the license with this file. If not, please or visit: * http://tudat.tudelft.nl/LICENSE. */ #define BOOST_TEST_MAIN #include "Tudat/JsonInterface/UnitTests/unitTestSupport.h" #include "Tudat/JsonInterface/Environment/aerodynamics.h" namespace tudat { namespace unit_tests { #define INPUT( filename ) \ ( json_interface::inputDirectory( ) / boost::filesystem::path( __FILE__ ).stem( ) / filename ).string( ) BOOST_AUTO_TEST_SUITE( test_json_aerodynamics ) // Test 1: aerodynamic coefficients types BOOST_AUTO_TEST_CASE( test_json_aerodynamics_coefficientsTypes ) { BOOST_CHECK_EQUAL_ENUM( INPUT( "coefficientsTypes" ), simulation_setup::aerodynamicCoefficientTypes, simulation_setup::unsupportedAerodynamicCoefficientTypes ); } // Test 2: aerodynamic variables BOOST_AUTO_TEST_CASE( test_json_aerodynamics_variables ) { BOOST_CHECK_EQUAL_ENUM( INPUT( "variables" ), aerodynamics::aerodynamicVariables, aerodynamics::unsupportedAerodynamicVariables ); } // Test 3: constant aerodynamics (only drag coefficient) BOOST_AUTO_TEST_CASE( test_json_aerodynamics_dragCoefficient ) { using namespace simulation_setup; using namespace json_interface; // Create AerodynamicCoefficientSettings from JSON file const std::shared_ptr< AerodynamicCoefficientSettings > fromFileSettings = parseJSONFile< std::shared_ptr< AerodynamicCoefficientSettings > >( INPUT( "dragCoefficient" ) ); // Create AerodynamicCoefficientSettings manually const double referenceArea = 10.5; const double dragCoefficient = 2.2; Eigen::Vector3d forceCoefficients = Eigen::Vector3d::Zero( ); forceCoefficients( 0 ) = dragCoefficient; const std::shared_ptr< AerodynamicCoefficientSettings > manualSettings = std::make_shared< ConstantAerodynamicCoefficientSettings >( referenceArea, forceCoefficients ); // Compare BOOST_CHECK_EQUAL_JSON( fromFileSettings, manualSettings ); } // Test 4: constant aerodynamics (full) BOOST_AUTO_TEST_CASE( test_json_aerodynamics_constant ) { using namespace simulation_setup; using namespace json_interface; // Create AerodynamicCoefficientSettings from JSON file const std::shared_ptr< AerodynamicCoefficientSettings > fromFileSettings = parseJSONFile< std::shared_ptr< AerodynamicCoefficientSettings > >( INPUT( "constant" ) ); // Create AerodynamicCoefficientSettings manually const double referenceLength = 5.0; const double referenceArea = 10.5; const double lateralReferenceLength = 4.0; const Eigen::Vector3d momentReferencePoint = ( Eigen::Vector3d( ) << 0.7, 0.8, 0.9 ).finished( ); const Eigen::Vector3d forceCoefficients = ( Eigen::Vector3d( ) << 1.0, 2.0, 3.0 ).finished( ); const Eigen::Vector3d momentCoefficients = ( Eigen::Vector3d( ) << 0.0, 1.0e-3, -0.1 ).finished( ); const bool areCoefficientsInAerodynamicFrame = true; const bool areCoefficientsInNegativeAxisDirection = false; const std::shared_ptr< AerodynamicCoefficientSettings > manualSettings = std::make_shared< ConstantAerodynamicCoefficientSettings >( referenceLength, referenceArea, lateralReferenceLength, momentReferencePoint, forceCoefficients, momentCoefficients, areCoefficientsInAerodynamicFrame, areCoefficientsInNegativeAxisDirection ); // Compare BOOST_CHECK_EQUAL_JSON( fromFileSettings, manualSettings ); } // Test 5: tabulated aerodynamics (1 dimension) BOOST_AUTO_TEST_CASE( test_json_aerodynamics_tabulated1 ) { using namespace aerodynamics; using namespace interpolators; using namespace simulation_setup; using namespace json_interface; // Create AerodynamicCoefficientSettings from JSON file const std::shared_ptr< AerodynamicCoefficientSettings > fromFileSettings = parseJSONFile< std::shared_ptr< AerodynamicCoefficientSettings > >( INPUT( "tabulated1" ) ); // Create AerodynamicCoefficientSettings manually const std::vector< double > independentVariables = { 0.0, 1.0, 2.0, 3.0 }; const std::vector< Eigen::Vector3d > forceCoefficients = { ( Eigen::Vector3d( ) << 0.7, 0.8, 0.9 ).finished( ), ( Eigen::Vector3d( ) << 1.7, 1.8, 1.9 ).finished( ), ( Eigen::Vector3d( ) << 2.7, 2.8, 2.9 ).finished( ), ( Eigen::Vector3d( ) << 3.7, 3.8, 3.9 ).finished( ) }; const std::vector< Eigen::Vector3d > momentCoefficients = { ( Eigen::Vector3d( ) << 1.0, 2.0, 3.0 ).finished( ), ( Eigen::Vector3d( ) << 1.0, 1.0, 1.0 ).finished( ), ( Eigen::Vector3d( ) << 2.0, 2.0, 2.0 ).finished( ), ( Eigen::Vector3d( ) << 3.0, 3.0, 3.0 ).finished( ) }; const double referenceLength = 5.0; const double referenceArea = 10.5; const double lateralReferenceLength = 4.0; const Eigen::Vector3d momentReferencePoint = ( Eigen::Vector3d( ) << 0.7, 0.8, 0.9 ).finished( ); const AerodynamicCoefficientsIndependentVariables independentVariableName = angle_of_sideslip_dependent; const std::shared_ptr< InterpolatorSettings > interpolatorSettings = std::make_shared< InterpolatorSettings >( cubic_spline_interpolator ); const bool areCoefficientsInAerodynamicFrame = false; const bool areCoefficientsInNegativeAxisDirection = false; const std::shared_ptr< AerodynamicCoefficientSettings > manualSettings = std::make_shared< TabulatedAerodynamicCoefficientSettings< 1 > >( independentVariables, forceCoefficients, momentCoefficients, referenceLength, referenceArea, lateralReferenceLength, momentReferencePoint, independentVariableName, areCoefficientsInAerodynamicFrame, areCoefficientsInNegativeAxisDirection, interpolatorSettings ); // Compare BOOST_CHECK_EQUAL_JSON( fromFileSettings, manualSettings ); } // Test 6: tabulated aerodynamics (N dimensions) BOOST_AUTO_TEST_CASE( test_json_aerodynamics_tabulatedN ) { using namespace aerodynamics; using namespace interpolators; using namespace simulation_setup; using namespace json_interface; // Create AerodynamicCoefficientSettings from JSON file const std::shared_ptr< AerodynamicCoefficientSettings > fromFileSettings = parseJSONFile< std::shared_ptr< AerodynamicCoefficientSettings > >( INPUT( "tabulatedN" ) ); // Create AerodynamicCoefficientSettings manually const std::map< int, std::string > forceCoefficientsFiles = { { 0, "aurora_CD.txt" }, { 2, "aurora_CL.txt" } }; const std::map< int, std::string > momentCoefficientsFiles = { { 1, "aurora_Cm.txt" } }; const double referenceLength = 5.0; const double referenceArea = 10.5; const double lateralReferenceLength = 4.0; const Eigen::Vector3d momentReferencePoint = ( Eigen::Vector3d( ) << 0.7, 0.8, 0.9 ).finished( ); const std::vector< AerodynamicCoefficientsIndependentVariables > independentVariableNames = { mach_number_dependent, angle_of_attack_dependent }; const bool areCoefficientsInAerodynamicFrame = true; const bool areCoefficientsInNegativeAxisDirection = true; const std::shared_ptr< AerodynamicCoefficientSettings > manualSettings = readTabulatedAerodynamicCoefficientsFromFiles( forceCoefficientsFiles, momentCoefficientsFiles, referenceLength, referenceArea, lateralReferenceLength, momentReferencePoint, independentVariableNames, areCoefficientsInAerodynamicFrame, areCoefficientsInNegativeAxisDirection ); // Compare BOOST_CHECK_EQUAL_JSON( fromFileSettings, manualSettings ); } BOOST_AUTO_TEST_SUITE_END( ) } // namespace unit_tests } // namespace tudat
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2016-2019 The ECODOLLAR 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/ecodollar-config.h" #endif #include "tinyformat.h" #include "utiltime.h" #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/thread.hpp> static int64_t nMockTime = 0; //! For unit testing int64_t GetTime() { if (nMockTime) return nMockTime; return time(NULL); } void SetMockTime(int64_t nMockTimeIn) { nMockTime = nMockTimeIn; } int64_t GetTimeMillis() { return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) - boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1))) .total_milliseconds(); } int64_t GetTimeMicros() { return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) - boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1))) .total_microseconds(); } void MilliSleep(int64_t n) { /** * Boost's sleep_for was uninterruptable when backed by nanosleep from 1.50 * until fixed in 1.52. Use the deprecated sleep method for the broken case. * See: https://svn.boost.org/trac/boost/ticket/7238 */ #if defined(HAVE_WORKING_BOOST_SLEEP_FOR) boost::this_thread::sleep_for(boost::chrono::milliseconds(n)); #elif defined(HAVE_WORKING_BOOST_SLEEP) boost::this_thread::sleep(boost::posix_time::milliseconds(n)); #else //should never get here #error missing boost sleep implementation #endif } std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime) { // std::locale takes ownership of the pointer std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat)); std::stringstream ss; ss.imbue(loc); ss << boost::posix_time::from_time_t(nTime); return ss.str(); } std::string DurationToDHMS(int64_t nDurationTime) { int seconds = nDurationTime % 60; nDurationTime /= 60; int minutes = nDurationTime % 60; nDurationTime /= 60; int hours = nDurationTime % 24; int days = nDurationTime / 24; if (days) return strprintf("%dd %02dh:%02dm:%02ds", days, hours, minutes, seconds); if (hours) return strprintf("%02dh:%02dm:%02ds", hours, minutes, seconds); return strprintf("%02dm:%02ds", minutes, seconds); }
extern "C" { extern int printf(const char *, ...); } double plus10(double arg) { double base = 10.0; return base + arg; } int main() { if (plus10(5.0) == 15.0) { printf("NORMAL\n"); return 0; } else { printf("MUTATED\n"); return 1; } } // clang-format off /** RUN: %clang_cxx %sysroot -fplugin=%mull_frontend_cxx -Xclang -plugin-arg-mull-cxx-frontend -Xclang mutators=cxx_init_const %s -o %s.exe RUN: %s.exe | %filecheck %s --dump-input=fail --strict-whitespace --match-full-lines --check-prefix=STANDALONE_WITHOUT_MUTATION RUN: (env "cxx_init_const:%s:6:17"=1 %s.exe || true) | %filecheck %s --dump-input=fail --strict-whitespace --match-full-lines --check-prefix=STANDALONE_WITH_MUTATION STANDALONE_WITHOUT_MUTATION:NORMAL STANDALONE_WITH_MUTATION:MUTATED RUN: %mull_runner %s.exe -ide-reporter-show-killed | %filecheck %s --dump-input=fail --strict-whitespace --match-full-lines --check-prefix=MULL_RUNNER MULL_RUNNER:[info] Killed mutants (1/1): MULL_RUNNER:{{.*}}sample.cpp:6:17: warning: Killed: Replaced 'T a = b' with 'T a = 42' [cxx_init_const] */
// written by bastiaan konings schuiling 2008 - 2014 // this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important. // i do not offer support, so don't ask. to be used for inspiration :) #include "scrollbar.hpp" #include "SDL/SDL_gfxBlitFunc.h" #include "../windowmanager.hpp" namespace blunted { Gui2Scrollbar::Gui2Scrollbar(Gui2WindowManager *windowManager, const std::string &name, float x_percent, float y_percent, float width_percent, float height_percent) : Gui2View(windowManager, name, x_percent, y_percent, width_percent, height_percent) { mode = e_Gui2ScrollbarMode_Vertical; int x, y, w, h; windowManager->GetCoordinates(x_percent, y_percent, width_percent, height_percent, x, y, w, h); image = windowManager->CreateImage2D(name, w, h, true); Redraw(); } Gui2Scrollbar::~Gui2Scrollbar() { } void Gui2Scrollbar::GetImages(std::vector < boost::intrusive_ptr<Image2D> > &target) { target.push_back(image); Gui2View::GetImages(target); } void Gui2Scrollbar::Process() { Gui2View::Process(); } void Gui2Scrollbar::Redraw() { int x, y, w, h; windowManager->GetCoordinates(x_percent, y_percent, width_percent, height_percent, x, y, w, h); Vector3 color1 = windowManager->GetStyle()->GetColor(e_DecorationType_Dark1); Vector3 color2 = windowManager->GetStyle()->GetColor(e_DecorationType_Bright1); // background image->DrawRectangle(0, 0, w, h, color1, 255); // bar if (mode == e_Gui2ScrollbarMode_Vertical) { int barSize = size_percent * 0.01 * h; int barStart = progress_percent * 0.01 * h; barStart -= barSize * progress_percent * 0.01; image->DrawRectangle(0, barStart, w, barSize, color2, 255); } else { int barSize = size_percent * 0.01 * w; int barStart = progress_percent * 0.01 * w; barStart -= barSize * progress_percent * 0.01; image->DrawRectangle(barStart, 0, barSize, h, color2, 255); } image->OnChange(); } }
// ============================= // SDL Programming // Name: ODOH KENNETH EMEKA // Student id: 0902024 // Task 18 // ============================= #include "CImageAlpha.h" #include <stdexcept> #include <SDL/SDL_image.h> #include <iostream> void DemoEngine::CImageAlpha::SetAlpha(Uint8 i_Alpha) { m_Alpha = i_Alpha; SDL_SetAlpha( m_pSurface, SDL_SRCALPHA, m_Alpha); } Uint8 DemoEngine::CImageAlpha::GetAlpha() { return m_Alpha; } bool DemoEngine::CImageAlpha::IsTransparent() { return (m_Alpha > 0 && m_Alpha < 255) ? true : false ; } void DemoEngine::CImageAlpha::Load( const char *szFileName ) { m_pSurface = IMG_Load(szFileName); if ( m_pSurface == NULL ) { throw std::runtime_error( "Cannot load image:" + std::string(szFileName)) ; } else { if (m_pSurface->format->BitsPerPixel == NO_OF_BITS_PER_PIXEL) { SetAlpha(m_pSurface->format->alpha); // set alpha value } SetSurface( m_pSurface); } }
/*********************************************************************************************//** * @file main.cpp * * Copyright (c) * Smart Robotic Systems * March 2015 * * 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. 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 HOLDER 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. ******************************************************************************/ /* Author: Jan Bacik */ #include <ros/ros.h> #include <image_transport/image_transport.h> #include <aruco_tracking.h> int main(int argc, char **argv) { ros::init(argc,argv,"aruco_tracking"); ros::NodeHandle nh; // Aruco mapping object aruco_tracking::ArucoTracking obj(&nh); // Image node and subscriber image_transport::ImageTransport it(nh); image_transport::Subscriber img_sub = it.subscribe("/image_raw", 1, &aruco_tracking::ArucoTracking::imageCallback, &obj); ros::spin(); return(EXIT_SUCCESS); }
#pragma once #include <exception> #include <string> namespace backing::domain::exception { struct InvalidUriException: public std::exception { public: explicit InvalidUriException(const std::string& uri): message("The uri '" + uri + "' is not a valid uri") {} [[nodiscard]] const char* what() const noexcept override { return message.c_str(); } private: std::string message; }; }
#ifndef CK_GRIDWISE_CONVOLUTION_IMPLICIT_GEMM_V4R4_FP16_BFP16_WRW_GNCHW_GKCYX_GNKHW_LDS_DOUBLE_BUFFER_HPP #define CK_GRIDWISE_CONVOLUTION_IMPLICIT_GEMM_V4R4_FP16_BFP16_WRW_GNCHW_GKCYX_GNKHW_LDS_DOUBLE_BUFFER_HPP #include "common_header.hpp" #include "tensor_descriptor.hpp" #include "tensor_descriptor_helper.hpp" #include "ConstantMatrixDescriptor.hpp" #include "gridwise_gemm_xdlops_fp16_bfp16.hpp" #include "convolution_common.hpp" #include "implicitgemm_params.hpp" namespace ck { // B = merge(N, Ho, Wo) template <index_t GridSize, index_t BlockSize, class ABFloat, class AccFloat, class CFloat, class InGlobalDesc, class WeiGlobalDesc, class OutGlobalDesc, class ConvStrides, class ConvDilations, class LeftPads, class RightPads, index_t GemmMPerBlock, index_t GemmNPerBlock, index_t GemmKPerBlock, index_t GemmKBlocks, index_t GemmKPACK, index_t GemmMPerWave, index_t GemmNPerWave, index_t GemmDataPerReadM, index_t GemmDataPerReadN, class GemmABlockCopyThreadSliceLengths_GemmG_GemmK_GemmM_GemmKPACK, class GemmABlockCopyThreadClusterLengths_GemmG_GemmK_GemmM_GemmKPACK, class GemmABlockCopyThreadClusterArrangeOrder, class GemmABlockCopySrcAccessOrder, class GemmABlockCopyDstAccessOrder, index_t GemmABlockCopySrcDataPerRead_GemmK, index_t GemmABlockCopyDstDataPerWrite_GemmKPACK, class GemmBBlockCopyThreadSliceLengths_GemmG_GemmK_GemmN_GemmKPACK, class GemmBBlockCopyThreadClusterLengths_GemmG_GemmK_GemmN_GemmKPACK, class GemmBBlockCopyThreadClusterArrangeOrder, class GemmBBlockCopySrcAccessOrder, class GemmBBlockCopyDstAccessOrder, index_t GemmBBlockCopySrcDataPerRead_GemmN, index_t GemmBBlockCopyDstDataPerWrite_GemmKPACK, ImplicitGemmDirection conv_dir> struct GridwiseConvolutionImplicitGemm_v4r4_gen_xdlops_fp16_bfp16_wrw_gnchw_gkcyx_gnkhw_lds_double_buffer { __device__ void Run(const ABFloat* const __restrict__ p_in_global, const ABFloat* const __restrict__ p_wei_global, CFloat* const __restrict__ p_out_global) const { constexpr auto I0 = Number<0>{}; constexpr auto I1 = Number<1>{}; constexpr auto I2 = Number<2>{}; constexpr auto I3 = Number<3>{}; constexpr auto I4 = Number<4>{}; constexpr auto in_g_n_c_hi_wi_global_desc = InGlobalDesc{}; constexpr auto wei_g_k_c_y_x_global_desc = WeiGlobalDesc{}; constexpr auto out_g_n_k_ho_wo_global_desc = OutGlobalDesc{}; constexpr index_t G = in_g_n_c_hi_wi_global_desc.GetLength(I0); constexpr index_t N = in_g_n_c_hi_wi_global_desc.GetLength(I1); constexpr index_t C = in_g_n_c_hi_wi_global_desc.GetLength(I2); constexpr index_t Hi = in_g_n_c_hi_wi_global_desc.GetLength(I3); constexpr index_t Wi = in_g_n_c_hi_wi_global_desc.GetLength(I4); constexpr index_t K = out_g_n_k_ho_wo_global_desc.GetLength(I2); constexpr index_t Ho = out_g_n_k_ho_wo_global_desc.GetLength(I3); constexpr index_t Wo = out_g_n_k_ho_wo_global_desc.GetLength(I4); constexpr index_t Y = wei_g_k_c_y_x_global_desc.GetLength(I3); constexpr index_t X = wei_g_k_c_y_x_global_desc.GetLength(I4); constexpr index_t ConvStrideH = ConvStrides{}[0]; constexpr index_t ConvStrideW = ConvStrides{}[1]; constexpr index_t ConvDilationH = ConvDilations{}[0]; constexpr index_t ConvDilationW = ConvDilations{}[1]; // GemmKPACK=1 for float32, =2 for bfloat16, =4 for float16 constexpr index_t GemmM = K; constexpr index_t GemmN = N * Ho * Wo; static_assert(C % GemmKPACK == 0, "C needs to be multiple of GemmKPACK"); constexpr index_t nonVectorizedC = C / GemmKPACK; constexpr index_t GemmK = nonVectorizedC * Y * X; static_assert(GemmM % GemmMPerBlock == 0 && GemmN % GemmNPerBlock == 0 && GemmK % (GemmKBlocks * GemmKPerBlock) == 0, "wrong! cannot divide work evenly among block"); constexpr index_t GemmKSub = GemmK / GemmKBlocks; // sanity-check for vectorized memory load static_assert((Wo == 1 || (ConvStrideW == 1 || GemmBBlockCopySrcDataPerRead_GemmN == 1)) && (X == 1 || ConvDilationW % GemmBBlockCopySrcDataPerRead_GemmN == 0), "wrong! aligment requirement for vectorized global load of input tensor will " "be violated"); constexpr auto in_g_n_c_hip_wip_global_desc = transform_tensor_descriptor( in_g_n_c_hi_wi_global_desc, make_tuple(PassThrough<G>{}, PassThrough<N>{}, PassThrough<C>{}, Pad<Sequence<Hi, Wi>, LeftPads, RightPads>{}), make_tuple(Sequence<0>{}, Sequence<1>{}, Sequence<2>{}, Sequence<3, 4>{}), make_tuple(Sequence<0>{}, Sequence<1>{}, Sequence<2>{}, Sequence<3, 4>{})); constexpr index_t Hip = in_g_n_c_hip_wip_global_desc.GetLengths()[3]; constexpr index_t Wip = in_g_n_c_hip_wip_global_desc.GetLengths()[4]; constexpr auto in_g_n_epack_c_y_ho_x_wo_global_desc = transform_tensor_descriptor( in_g_n_c_hip_wip_global_desc, make_tuple(PassThrough<G>{}, PassThrough<N>{}, UnMerge<Sequence<nonVectorizedC, GemmKPACK>>{}, Embed<Hip, Sequence<Y, Ho>, Sequence<ConvDilationH, ConvStrideH, 0>>{}, Embed<Wip, Sequence<X, Wo>, Sequence<ConvDilationW, ConvStrideW, 0>>{}), make_tuple(Sequence<0>{}, Sequence<1>{}, Sequence<2>{}, Sequence<3>{}, Sequence<4>{}), make_tuple(Sequence<0>{}, Sequence<1>{}, Sequence<2, 3>{}, Sequence<4, 5>{}, Sequence<6, 7>{})); constexpr auto in_gemmg_gemmk_gemmn_gemmkpack_global_desc_tmp = transform_tensor_descriptor( in_g_n_epack_c_y_ho_x_wo_global_desc, make_tuple(PassThrough<G>{}, Merge<Sequence<nonVectorizedC, Y, X>>{}, Merge<Sequence<N, Ho, Wo>>{}, PassThrough<GemmKPACK>{}), make_tuple(Sequence<0>{}, Sequence<2, 4, 6>{}, Sequence<1, 5, 7>{}, Sequence<3>{}), make_tuple(Sequence<0>{}, Sequence<1>{}, Sequence<2>{}, Sequence<3>{})); constexpr auto in_gemmg_gemmk0_gemmk1_gemmn_gemmkpack_global_desc = transform_tensor_descriptor( in_gemmg_gemmk_gemmn_gemmkpack_global_desc_tmp, make_tuple(PassThrough<G>{}, UnMerge<Sequence<GemmKBlocks, GemmKSub>>{}, PassThrough<GemmN>{}, PassThrough<GemmKPACK>{}), make_tuple(Sequence<0>{}, Sequence<1>{}, Sequence<2>{}, Sequence<3>{}), make_tuple(Sequence<0>{}, Sequence<1, 2>{}, Sequence<3>{}, Sequence<4>{})); constexpr auto in_gemmg_gemmk_gemmn_gemmkpack_global_desc = transform_tensor_descriptor( in_gemmg_gemmk0_gemmk1_gemmn_gemmkpack_global_desc, make_tuple(Merge<Sequence<G, GemmKBlocks>>{}, PassThrough<GemmKSub>{}, PassThrough<GemmN>{}, PassThrough<GemmKPACK>{}), make_tuple(Sequence<0, 1>{}, Sequence<2>{}, Sequence<3>{}, Sequence<4>{}), make_tuple(Sequence<0>{}, Sequence<1>{}, Sequence<2>{}, Sequence<3>{})); // weight tensor // global mem constexpr auto wei_g_k_epack_c_y_x_global_desc = transform_tensor_descriptor( wei_g_k_c_y_x_global_desc, make_tuple(PassThrough<G>{}, PassThrough<K>{}, UnMerge<Sequence<nonVectorizedC, GemmKPACK>>{}, PassThrough<Y>{}, PassThrough<X>{}), make_tuple(Sequence<0>{}, Sequence<1>{}, Sequence<2>{}, Sequence<3>{}, Sequence<4>{}), make_tuple( Sequence<0>{}, Sequence<1>{}, Sequence<2, 3>{}, Sequence<4>{}, Sequence<5>{})); constexpr auto wei_gemmg_gemmk_gemmm_gemmkpack_global_desc_tmp = transform_tensor_descriptor( wei_g_k_epack_c_y_x_global_desc, make_tuple(PassThrough<G>{}, Merge<Sequence<nonVectorizedC, Y, X>>{}, PassThrough<K>{}, PassThrough<GemmKPACK>{}), make_tuple(Sequence<0>{}, Sequence<2, 4, 5>{}, Sequence<1>{}, Sequence<3>{}), make_tuple(Sequence<0>{}, Sequence<1>{}, Sequence<2>{}, Sequence<3>{})); constexpr auto wei_gemmg_gemmk0_gemmk1_gemmm_gemmkpack_global_desc = transform_tensor_descriptor( wei_gemmg_gemmk_gemmm_gemmkpack_global_desc_tmp, make_tuple(PassThrough<G>{}, UnMerge<Sequence<GemmKBlocks, GemmKSub>>{}, PassThrough<GemmM>{}, PassThrough<GemmKPACK>{}), make_tuple(Sequence<0>{}, Sequence<1>{}, Sequence<2>{}, Sequence<3>{}), make_tuple(Sequence<0>{}, Sequence<1, 2>{}, Sequence<3>{}, Sequence<4>{})); constexpr auto wei_gemmg_gemmk_gemmm_gemmkpack_global_desc = transform_tensor_descriptor( wei_gemmg_gemmk0_gemmk1_gemmm_gemmkpack_global_desc, make_tuple(Merge<Sequence<G, GemmKBlocks>>{}, PassThrough<GemmKSub>{}, PassThrough<GemmM>{}, PassThrough<GemmKPACK>{}), make_tuple(Sequence<0, 1>{}, Sequence<2>{}, Sequence<3>{}, Sequence<4>{}), make_tuple(Sequence<0>{}, Sequence<1>{}, Sequence<2>{}, Sequence<3>{})); constexpr auto out_g_e0_n_k_ho_wo_global_desc = make_native_tensor_descriptor(Sequence<out_g_n_k_ho_wo_global_desc.GetLengths()[0], GemmKBlocks, out_g_n_k_ho_wo_global_desc.GetLengths()[1], out_g_n_k_ho_wo_global_desc.GetLengths()[2], out_g_n_k_ho_wo_global_desc.GetLengths()[3], out_g_n_k_ho_wo_global_desc.GetLengths()[4]>{}, Sequence<out_g_n_k_ho_wo_global_desc.GetStrides()[0], 0, out_g_n_k_ho_wo_global_desc.GetStrides()[1], out_g_n_k_ho_wo_global_desc.GetStrides()[2], out_g_n_k_ho_wo_global_desc.GetStrides()[3], out_g_n_k_ho_wo_global_desc.GetStrides()[4]>{}); constexpr auto out_gemmg_gemmm_gemmn_global_desc = transform_tensor_descriptor( out_g_e0_n_k_ho_wo_global_desc, make_tuple( Merge<Sequence<G, GemmKBlocks>>{}, PassThrough<K>{}, Merge<Sequence<N, Ho, Wo>>{}), make_tuple(Sequence<0, 1>{}, Sequence<3>{}, Sequence<2, 4, 5>{}), make_tuple(Sequence<0>{}, Sequence<1>{}, Sequence<2>{})); constexpr InMemoryDataOperation CGlobalMemoryDataOperation = GemmKBlocks > 1 ? InMemoryDataOperation::AtomicAdd : InMemoryDataOperation::Set; constexpr auto gridwise_batched_gemm = GridwiseBatchedGemmTransposedANormalBNormalCXdlopsFp16Bfp16_v1< GridSize, BlockSize, ABFloat, AccFloat, CFloat, decltype(wei_gemmg_gemmk_gemmm_gemmkpack_global_desc), decltype(in_gemmg_gemmk_gemmn_gemmkpack_global_desc), decltype(out_gemmg_gemmm_gemmn_global_desc), GemmMPerBlock, GemmNPerBlock, GemmKPerBlock, GemmMPerWave, GemmNPerWave, GemmDataPerReadM, GemmDataPerReadN, GemmABlockCopyThreadSliceLengths_GemmG_GemmK_GemmM_GemmKPACK, GemmABlockCopyThreadClusterLengths_GemmG_GemmK_GemmM_GemmKPACK, GemmABlockCopyThreadClusterArrangeOrder, GemmABlockCopySrcAccessOrder, GemmABlockCopyDstAccessOrder, 1, GemmABlockCopySrcDataPerRead_GemmK, GemmABlockCopyDstDataPerWrite_GemmKPACK, GemmBBlockCopyThreadSliceLengths_GemmG_GemmK_GemmN_GemmKPACK, GemmBBlockCopyThreadClusterLengths_GemmG_GemmK_GemmN_GemmKPACK, GemmBBlockCopyThreadClusterArrangeOrder, GemmBBlockCopySrcAccessOrder, GemmBBlockCopyDstAccessOrder, 2, GemmBBlockCopySrcDataPerRead_GemmN, GemmBBlockCopyDstDataPerWrite_GemmKPACK, CGlobalMemoryDataOperation, MBlock1NBlock0>{}; gridwise_batched_gemm.Run(p_wei_global, p_in_global, p_out_global); } }; } // namespace ck #endif
/*------------------------------------------------------------------------ * Index example * * Demonstrates using the `Index` node to retrieve indexed items * from a `std::vector`. Note that the first argument to Index is a * static property, not a node. *-----------------------------------------------------------------------*/ #include <signalflow/signalflow.h> #include <stdlib.h> #include <unistd.h> using namespace signalflow; int main() { AudioGraphRef graph = new AudioGraph(); /*------------------------------------------------------------------------ * Create a list of frequencies to iterate over *-----------------------------------------------------------------------*/ std::vector<float> freqs = { 60, 120, 180, 240, 300, 360, 420, 480 }; /*------------------------------------------------------------------------ * Create a pair of sawtooth waves, scaled between 0..8, used to index * over the array. The SawOscillator nodes are output over consecutive channels. * * Index casts the `index` inputs to an integer, used to select the * output frequency. Via automatic channel upmixing, this creates * two parallel counters, phasing gradually against each other. *-----------------------------------------------------------------------*/ NodeRef saw = new SawLFO({ 1, 0.97 }, 0, 8); NodeRef index = new Index(freqs, saw); /*------------------------------------------------------------------------ * Use the resultant values as frequency parameters of a SineOscillator node, * with a time-synced pair of TriangleOscillator waves to act as envelopes. *-----------------------------------------------------------------------*/ NodeRef sine = new SineOscillator(index); NodeRef envelope = new TriangleLFO({ 8.0, 7.76 }, 0, 1); sine = sine * envelope; /*------------------------------------------------------------------------ * Reduce the stereo width slightly to increase the interaction between * L / R channels. *-----------------------------------------------------------------------*/ NodeRef width = new StereoWidth(sine, 0.5); graph->play(width); graph->wait(); }
#include "led.h" void ledSet(uint16_t a,uint8_t k); void ARDUINO_ISR_ATTR timLEDISR(); static hw_timer_t *tim_LED_h = NULL; //ハンドラ static volatile SemaphoreHandle_t tim_LED_sem; //セマフォ static portMUX_TYPE tim_LED_mux = portMUX_INITIALIZER_UNLOCKED;//排他制御 static bool state_update_f = false; static bool bring_cnt_clear_f = false; static uint16_t bring_cnt = 0; static bool bright_read_f = false; static led_display_t internal_led; static led_display_t *next_led; static uint8_t led_bright = 100; static const uint16_t led_font[] = { 075557,//0 022222,//1 071747,//2 071717,//3 055711,//4 074717,//5 074757,//6 071111,//7 075757,//8 075717,//9 }; void ledUpdate(led_display_t *led){ next_led = led; state_update_f = true; } void bring_cnt_clear(){ bring_cnt_clear_f = true; } void ledInLoop(){ int bright_ad; if (xSemaphoreTake(tim_LED_sem, 0) == pdTRUE){ portENTER_CRITICAL_ISR(&tim_LED_mux); if(state_update_f){// メインループ側フラグ判定 state_update_f = false; memcpy(&internal_led,next_led,sizeof(led_display_t)); } if(bring_cnt_clear_f){// メインループ側フラグ判定 bring_cnt_clear_f = false; bring_cnt = 0; } if(bright_read_f){// 割り込み内部側のフラグ判定 bright_read_f = false; bright_ad = analogRead(PIN_BRIGHT); if(bright_ad >= 2500){ led_bright = 100; }else if(bright_ad >= 1500){ led_bright = 64; }else if(bright_ad >= 1000){ led_bright = 32; }else if(bright_ad >= 500){ led_bright = 16; }else if(bright_ad >= 250){ led_bright = 8; }else if(bright_ad >= 100){ led_bright = 4; }else if(bright_ad >= 50){ led_bright = 2; }else{ led_bright = 1; } } portEXIT_CRITICAL_ISR(&tim_LED_mux); } } void ledMakeDisplay(led_display_t *led,uint8_t h,uint8_t m,char dot){ for(int i=0; i<5; i++){ led->led[i] = 0; led->led[i] |= ((led_font[m%10]>>12-(3*i))&(0b111))<<0; led->led[i] |= ((led_font[m/10]>>12-(3*i))&(0b111))<<3; led->led[i] |= ((led_font[h%10]>>12-(3*i))&(0b111))<<7; led->led[i] |= ((led_font[h/10]>>12-(3*i))&(0b111))<<10; } switch(dot){ case ':': led->led[1] |= 0b0000001000000; led->led[3] |= 0b0000001000000; break; case ';': led->led[1] |= 0b0000001000000; led->led[3] |= 0b0000001000000; led->led[4] |= 0b0000001000000; break; case '.': led->led[4] |= 0b0000001000000; break; case ',': led->led[3] |= 0b0000001000000; led->led[4] |= 0b0000001000000; break; } } // --------------------------------------------------------------------- void ARDUINO_ISR_ATTR timLEDISR() {//割り込み static uint8_t cnt = 0; static uint8_t cnt_k = 0; static uint8_t cnt_ms = 0; portENTER_CRITICAL_ISR(&tim_LED_mux); cnt++; if (cnt >= led_bright) { ledSet(0, 0xff); } if (cnt > 100) { cnt = 0; if(bring_cnt >= 500){ internal_led.led[1] &= 0b1111110111111; internal_led.led[3] &= 0b1111110111111; internal_led.led[4] &= 0b1111110111111; }else{ bring_cnt ++; } ledSet(internal_led.led[cnt_k], cnt_k); if(cnt_k >= 4){ cnt_k = 0; }else{ cnt_k++; } if(cnt_ms > 100){//read bright bright_read_f = true; cnt_ms = 0; }else{ cnt_ms ++; } } portEXIT_CRITICAL_ISR(&tim_LED_mux); xSemaphoreGiveFromISR(tim_LED_sem, NULL); } void ledInit() { tim_LED_sem = xSemaphoreCreateBinary(); tim_LED_h = timerBegin(3, 80, true); //タイマー0-3 , プリスケーラー , インクリメント timerAttachInterrupt(tim_LED_h, &timLEDISR, true); //ハンドラ, 呼び出し関数, エッジタイプ timerAlarmWrite(tim_LED_h, 10, true); //ハンドラ, ポストスケーラ, 繰り返し有効 timerAlarmEnable(tim_LED_h); //開始 } void ledSet(uint16_t a, uint8_t k) { digitalWrite(PIN_K1, k == 0 ? HIGH : LOW); digitalWrite(PIN_K2, k == 1 ? HIGH : LOW); digitalWrite(PIN_K3, k == 2 ? HIGH : LOW); digitalWrite(PIN_K4, k == 3 ? HIGH : LOW); digitalWrite(PIN_K5, k == 4 ? HIGH : LOW); digitalWrite(PIN_A4_3, a & 0x0001 ? HIGH : LOW); digitalWrite(PIN_A4_2, a & 0x0002 ? HIGH : LOW); digitalWrite(PIN_A4_1, a & 0x0004 ? HIGH : LOW); digitalWrite(PIN_A3_3, a & 0x0008 ? HIGH : LOW); digitalWrite(PIN_A3_2, a & 0x0010 ? HIGH : LOW); digitalWrite(PIN_A3_1, a & 0x0020 ? HIGH : LOW); digitalWrite(PIN_AD_1, a & 0x0040 ? HIGH : LOW); digitalWrite(PIN_A2_3, a & 0x0080 ? HIGH : LOW); digitalWrite(PIN_A2_2, a & 0x0100 ? HIGH : LOW); digitalWrite(PIN_A2_1, a & 0x0200 ? HIGH : LOW); digitalWrite(PIN_A1_3, a & 0x0400 ? HIGH : LOW); digitalWrite(PIN_A1_2, a & 0x0800 ? HIGH : LOW); digitalWrite(PIN_A1_1, a & 0x1000 ? HIGH : LOW); }
/* Copyright (c) 2017-2020, Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC. See the top-level NOTICE for additional details. All rights reserved. SPDX-License-Identifier: BSD-3-Clause */ #pragma once #include "../core/ActionMessage.hpp" #include <json/forwards.h> #include <memory> namespace helics { class Broker; namespace apps { using portData = std::vector<std::tuple<int, bool, std::shared_ptr<Broker>>>; /** a virtual class to use as a base for broker servers of various types*/ class TypedBrokerServer { public: virtual ~TypedBrokerServer() = default; /** start the server*/ virtual void startServer(const Json::Value* val) = 0; /** stop the server*/ virtual void stopServer() = 0; protected: /** generate a reply to a message*/ static ActionMessage generateMessageResponse(const ActionMessage& rxcmd, portData& pdata, core_type ctype); /** get an open port for broker to start*/ static int getOpenPort(portData& pd); /* assign a port in the portData structure*/ static void assignPort(portData& pd, int pnumber, std::shared_ptr<Broker>& brk); /* log a message to the console */ static void logMessage(std::string message); }; } // namespace apps } // namespace helics
/******************************************************************************* * thrill/vfs/gzip_filter.cpp * * Part of Project Thrill - http://project-thrill.org * * Copyright (C) 2016 Timo Bingmann <tb@panthema.net> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #include <thrill/vfs/gzip_filter.hpp> #include <tlx/die.hpp> #if THRILL_HAVE_ZLIB #include <zlib.h> #endif #include <vector> namespace thrill { namespace vfs { #if THRILL_HAVE_ZLIB /******************************************************************************/ const char * Z_ERROR_to_string(int err) { switch (err) { case Z_OK: return "Z_OK"; case Z_STREAM_END: return "Z_STREAM_END"; case Z_NEED_DICT: return "Z_NEED_DICT"; case Z_ERRNO: return "Z_ERRNO"; case Z_STREAM_ERROR: return "Z_STREAM_ERROR"; case Z_DATA_ERROR: return "Z_DATA_ERROR"; case Z_MEM_ERROR: return "Z_MEM_ERROR"; case Z_BUF_ERROR: return "Z_BUF_ERROR"; case Z_VERSION_ERROR: return "Z_VERSION_ERROR"; default: return "UNKNOWN"; } } /******************************************************************************/ // GZipWriteFilter - on-the-fly gzip compressor class GZipWriteFilter final : public virtual WriteStream { public: explicit GZipWriteFilter(const WriteStreamPtr& output) : output_(output) { memset(&z_stream_, 0, sizeof(z_stream_)); // windowBits = 15 (largest allocation) + 16 (gzip header) int window_size = 15 + 16; int err = deflateInit2(&z_stream_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, window_size, /* memLevel */ 8, Z_DEFAULT_STRATEGY); die_unequal(err, Z_OK); // output buffer buffer_.resize(2 * 1024 * 1024); z_stream_.next_out = buffer_.data(); z_stream_.avail_out = static_cast<uInt>(buffer_.size()); initialized_ = true; } ~GZipWriteFilter() { close(); } ssize_t write(const void* data, const size_t size) final { int err; z_stream_.next_in = const_cast<Bytef*>( reinterpret_cast<const Bytef*>(data)); z_stream_.avail_in = size; do { err = deflate(&z_stream_, Z_NO_FLUSH); if (err == Z_OK && z_stream_.avail_in != 0) { uInt written_size = buffer_.size() - z_stream_.avail_out; // buffer is full, write to output output_->write(buffer_.data(), written_size); z_stream_.next_out = buffer_.data(); z_stream_.avail_out = buffer_.size(); } } while (z_stream_.avail_in != 0 && err == Z_OK); // NOLINT die_unequal(err, Z_OK); return size; } void close() final { if (!initialized_) return; int err; do { err = deflate(&z_stream_, Z_FINISH); if (err == Z_OK && z_stream_.avail_in != 0) { uInt written_size = buffer_.size() - z_stream_.avail_out; // buffer is full, write to output output_->write(buffer_.data(), written_size); z_stream_.next_out = buffer_.data(); z_stream_.avail_out = buffer_.size(); } } while (err == Z_OK); // NOLINT // write remaining data uInt written_size = buffer_.size() - z_stream_.avail_out; output_->write(buffer_.data(), written_size); output_->close(); deflateEnd(&z_stream_); initialized_ = false; } private: //! if z_stream_ is initialized bool initialized_; //! zlib context z_stream z_stream_; //! compression buffer, flushed to output when full std::vector<Bytef> buffer_; //! output stream for writing data somewhere WriteStreamPtr output_; }; WriteStreamPtr MakeGZipWriteFilter(const WriteStreamPtr& stream) { die_unless(stream); return tlx::make_counting<GZipWriteFilter>(stream); } /******************************************************************************/ // GZipReadFilter - on-the-fly gzip decompressor class GZipReadFilter : public virtual ReadStream { static constexpr bool debug = false; public: explicit GZipReadFilter(const ReadStreamPtr& input) : input_(input) { memset(&z_stream_, 0, sizeof(z_stream_)); /* windowBits = 15 (largest allocation) + 32 (autodetect headers) */ int window_size = 15 + 32; err_ = inflateInit2(&z_stream_, window_size); die_unequal(err_, Z_OK); // output buffer buffer_.resize(2 * 1024 * 1024); z_stream_.next_in = buffer_.data(); z_stream_.avail_in = 0; initialized_ = true; } ~GZipReadFilter() { close(); } ssize_t read(void* data, size_t size) final { z_stream_.next_out = const_cast<Bytef*>( reinterpret_cast<const Bytef*>(data)); z_stream_.avail_out = size; do { if (z_stream_.avail_in == 0) { // input buffer empty, so read from input_ z_stream_.avail_in = input_->read( buffer_.data(), buffer_.size()); z_stream_.next_in = buffer_.data(); if (z_stream_.avail_in == 0) { return size - z_stream_.avail_out; } } if (err_ == Z_STREAM_END) { LOG << "GZipReadFilter: inflateReset()"; inflateReset(&z_stream_); } err_ = inflate(&z_stream_, Z_SYNC_FLUSH); } while ((err_ == Z_OK || err_ == Z_STREAM_END) && // NOLINT z_stream_.avail_out != 0); // NOLINT if (err_ != Z_OK && err_ != Z_STREAM_END) { die("GZipReadFilter: " << Z_ERROR_to_string(err_) << " while inflating"); } die_unequal(z_stream_.avail_out, 0u); return size; } void close() final { if (!initialized_) return; inflateEnd(&z_stream_); input_->close(); initialized_ = false; } private: //! if z_stream_ is initialized bool initialized_; //! zlib context z_stream z_stream_; //! current error code int err_; //! decompression buffer, filled from the input when empty std::vector<Bytef> buffer_; //! input stream for reading data from somewhere ReadStreamPtr input_; }; ReadStreamPtr MakeGZipReadFilter(const ReadStreamPtr& stream) { die_unless(stream); return tlx::make_counting<GZipReadFilter>(stream); } /******************************************************************************/ #else // !THRILL_HAVE_ZLIB WriteStreamPtr MakeGZipWriteFilter(const WriteStreamPtr&) { die(".gz decompression is not available, " "because Thrill was built without zlib."); } ReadStreamPtr MakeGZipReadFilter(const ReadStreamPtr&) { die(".gz decompression is not available, " "because Thrill was built without zlib."); } #endif } // namespace vfs } // namespace thrill /******************************************************************************/
// // ruvi base // #pragma once // includes #include "sdk/memory/memory.hh" #include "sdk/vector/vector.hh" #include <functional> #include "sdk/indices.hh" struct player_info_t { int64_t __pad0; union { int64_t xuid; struct { int xuid_low; int xuid_high; }; }; char name[128]; int userid; char guid[33]; unsigned int steam3_id; char friendsname[128]; bool is_fake_player; bool ishltv; unsigned int customfiles[4]; unsigned char filesdownloaded; }; class i_engine_client { public: void get_screen_size(int &width, int &height) { return memory::vfunc<idx::ENGINE_GET_SCREEN_SIZE, void>(this, std::ref(width), std::ref(height)); } bool get_player_info(int ent_num, player_info_t *info) { return memory::vfunc<idx::GET_PLAYER_INFO, bool>(this, ent_num, info); } int get_player_for_user_id(int user_id) { return memory::vfunc<idx::GET_PLAYER_USER_ID, int>(this, user_id); } int get_local_player() { return memory::vfunc<idx::GET_LOCAL_PLAYER, int>(this); } void get_view_angles(qangle *angles) { return memory::vfunc<idx::GET_VIEW_ANGLES, void>(this, angles); } void set_view_angles(qangle *angles) { return memory::vfunc<idx::SET_VIEW_ANGLES, void>(this, angles); } int get_max_clients() { return memory::vfunc<idx::GET_MAX_CLIENTS, int>(this); } bool is_in_game() { return memory::vfunc<idx::IS_IN_GAME, bool>(this); } bool is_connected() { return memory::vfunc<idx::IS_CONNECTED, bool>(this); } char const *get_map_name() { return memory::vfunc<idx::GET_MAP_NAME, char const *>(this); } bool is_taking_screenshot() { return memory::vfunc<idx::IS_TAKING_SS, bool>(this); } void execute_client_cmd(char const *command) { return memory::vfunc<idx::EXEC_CLIENT_CMD, void>(this, command); } void client_cmd_unrestricted(char const *command) { return memory::vfunc<idx::EXEC_CMD_UNRESTRICTED, void>(this, command); } };
/******************************************************************************* * Copyright 2017-2022 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sstream> #include "dnnl_common.hpp" #include "utils/parser.hpp" #include "conv/conv.hpp" #include "conv/conv_dw_fusion.hpp" namespace conv { void check_correctness(const settings_t &s) { for_(const auto &i_dir : s.dir) for_(const auto &i_cfg : s.cfg) for_(const auto &i_stag : s.stag) for_(const auto &i_wtag : s.wtag) for_(const auto &i_dtag : s.dtag) for_(const auto &i_alg : s.alg) for_(const auto &i_oscale : s.oscale) for_(const auto &i_zero_points : s.zero_points) for_(const auto &i_post_ops : s.post_ops) for_(const auto &i_scratchpad_mode : s.scratchpad_mode) for (const auto &i_mb : s.mb) { attr_t attr; attr.insert(i_oscale); attr.insert(i_zero_points); attr.insert(i_post_ops); attr.insert(i_scratchpad_mode); handle_legacy_attr(attr, s.attr); const prb_t prb(s.desc, i_dir, i_cfg, i_stag, i_wtag, i_dtag, i_alg, attr, i_mb); std::stringstream ss; ss << prb; const std::string cpp_pstr = ss.str(); const char *pstr = cpp_pstr.c_str(); if (s.pattern && !match_regex(pstr, s.pattern)) return; BENCHDNN_PRINT(1, "run: %s\n", pstr); res_t res {}; if (attr.post_ops.convolution_index() != -1) conv_dw_fusion::doit(&prb, &res); else conv::doit(&prb, &res); parse_result(res, pstr); if (is_bench_mode(PERF)) { perf_report_t pr(&prb, s.perf_template); pr.report(&res, pstr); } benchdnn_stat.tests++; } } int bench(int argc, char **argv) { driver_name = "conv"; using namespace parser; static settings_t s; static const settings_t def {}; for (; argc > 0; --argc, ++argv) { const bool parsed_options = parse_bench_settings(argv[0]) || parse_batch(bench, argv[0]) || parse_dir(s.dir, def.dir, argv[0]) || parse_cfg(s.cfg, def.cfg, str2cfg, argv[0]) || parse_tag(s.stag, def.stag, argv[0], "stag") || parse_tag(s.wtag, def.wtag, argv[0], "wtag") || parse_tag(s.dtag, def.dtag, argv[0], "dtag") || parse_alg(s.alg, def.alg, str2alg, argv[0]) || parse_mb(s.mb, def.mb, argv[0]) || parse_attr(s.attr, argv[0]) || parse_attr_oscale(s.oscale, argv[0]) || parse_attr_zero_points(s.zero_points, argv[0]) || parse_attr_post_ops(s.post_ops, argv[0]) || parse_attr_scratchpad_mode( s.scratchpad_mode, def.scratchpad_mode, argv[0]) || parse_test_pattern_match(s.pattern, argv[0]) || parse_perf_template(s.perf_template, s.perf_template_def, s.perf_template_csv(), argv[0]) || parse_reset(s, argv[0]) || parse_help(argv[0]); if (!parsed_options) { catch_unknown_options(argv[0]); bool is_deconv = false; SAFE(str2desc(&s.desc, argv[0], is_deconv), CRIT); check_correctness(s); } } return parse_last_argument(); } } // namespace conv
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/elasticfilesystem/model/CreateMountTargetResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::EFS::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; CreateMountTargetResult::CreateMountTargetResult() : m_lifeCycleState(LifeCycleState::NOT_SET) { } CreateMountTargetResult::CreateMountTargetResult(const Aws::AmazonWebServiceResult<JsonValue>& result) : m_lifeCycleState(LifeCycleState::NOT_SET) { *this = result; } CreateMountTargetResult& CreateMountTargetResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("OwnerId")) { m_ownerId = jsonValue.GetString("OwnerId"); } if(jsonValue.ValueExists("MountTargetId")) { m_mountTargetId = jsonValue.GetString("MountTargetId"); } if(jsonValue.ValueExists("FileSystemId")) { m_fileSystemId = jsonValue.GetString("FileSystemId"); } if(jsonValue.ValueExists("SubnetId")) { m_subnetId = jsonValue.GetString("SubnetId"); } if(jsonValue.ValueExists("LifeCycleState")) { m_lifeCycleState = LifeCycleStateMapper::GetLifeCycleStateForName(jsonValue.GetString("LifeCycleState")); } if(jsonValue.ValueExists("IpAddress")) { m_ipAddress = jsonValue.GetString("IpAddress"); } if(jsonValue.ValueExists("NetworkInterfaceId")) { m_networkInterfaceId = jsonValue.GetString("NetworkInterfaceId"); } if(jsonValue.ValueExists("AvailabilityZoneId")) { m_availabilityZoneId = jsonValue.GetString("AvailabilityZoneId"); } if(jsonValue.ValueExists("AvailabilityZoneName")) { m_availabilityZoneName = jsonValue.GetString("AvailabilityZoneName"); } if(jsonValue.ValueExists("VpcId")) { m_vpcId = jsonValue.GetString("VpcId"); } return *this; }
/* Copyright 2019 Istio 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 "benchmark/benchmark.h" #include "common/stream_info/filter_state_impl.h" #include "extensions/common/context.h" #include "extensions/common/wasm/wasm_state.h" #include "google/protobuf/util/json_util.h" // WASM_PROLOG #ifdef NULL_PLUGIN namespace Wasm { #endif // NULL_PLUGIN // END WASM_PROLOG namespace Common { using namespace google::protobuf::util; constexpr absl::string_view node_metadata_json = R"###( { "NAME":"test_pod", "NAMESPACE":"test_namespace", "LABELS": { "app": "productpage", "version": "v1", "pod-template-hash": "84975bc778" }, "OWNER":"test_owner", "WORKLOAD_NAME":"test_workload", "PLATFORM_METADATA":{ "gcp_project":"test_project", "gcp_cluster_location":"test_location", "gcp_cluster_name":"test_cluster" }, "ISTIO_VERSION":"istio-1.4", "MESH_ID":"test-mesh" } )###"; constexpr absl::string_view metadata_id_key = "envoy.wasm.metadata_exchange.downstream_id"; constexpr absl::string_view metadata_key = "envoy.wasm.metadata_exchange.downstream"; constexpr absl::string_view node_id = "test_pod.test_namespace"; static void setData(Envoy::StreamInfo::FilterStateImpl& filter_state, absl::string_view key, absl::string_view value) { filter_state.setData( key, std::make_unique<Envoy::Extensions::Common::Wasm::WasmState>(value), Envoy::StreamInfo::FilterState::StateType::Mutable); } static const std::string& getData( Envoy::StreamInfo::FilterStateImpl& filter_state, absl::string_view key) { return filter_state .getDataReadOnly<Envoy::Extensions::Common::Wasm::WasmState>(key) .value(); } static void BM_ReadFlatBuffer(benchmark::State& state) { google::protobuf::Struct metadata_struct; JsonParseOptions json_parse_options; JsonStringToMessage(std::string(node_metadata_json), &metadata_struct, json_parse_options); flatbuffers::FlatBufferBuilder fbb(1024); extractNodeFlatBuffer(metadata_struct, fbb); Envoy::StreamInfo::FilterStateImpl filter_state{ Envoy::StreamInfo::FilterState::LifeSpan::TopSpan}; setData( filter_state, metadata_key, absl::string_view(reinterpret_cast<const char*>(fbb.GetBufferPointer()), fbb.GetSize())); size_t size = 0; for (auto _ : state) { auto buf = getData(filter_state, metadata_key); auto peer = flatbuffers::GetRoot<FlatNode>(buf.data()); size += peer->workload_name()->size() + peer->namespace_()->size() + peer->labels()->LookupByKey("app")->value()->size() + peer->labels()->LookupByKey("version")->value()->size(); benchmark::DoNotOptimize(size); } } BENCHMARK(BM_ReadFlatBuffer); static void BM_WriteRawBytes(benchmark::State& state) { google::protobuf::Struct metadata_struct; JsonParseOptions json_parse_options; JsonStringToMessage(std::string(node_metadata_json), &metadata_struct, json_parse_options); auto bytes = metadata_struct.SerializeAsString(); Envoy::StreamInfo::FilterStateImpl filter_state{ Envoy::StreamInfo::FilterState::LifeSpan::TopSpan}; for (auto _ : state) { setData(filter_state, metadata_id_key, node_id); setData(filter_state, metadata_key, bytes); } } BENCHMARK(BM_WriteRawBytes); static void BM_WriteFlatBufferWithCache(benchmark::State& state) { google::protobuf::Struct metadata_struct; JsonParseOptions json_parse_options; JsonStringToMessage(std::string(node_metadata_json), &metadata_struct, json_parse_options); auto bytes = metadata_struct.SerializeAsString(); Envoy::StreamInfo::FilterStateImpl filter_state{ Envoy::StreamInfo::FilterState::LifeSpan::TopSpan}; std::unordered_map<std::string, std::string> cache; for (auto _ : state) { // lookup cache by key auto nodeinfo_it = cache.find(std::string(node_id)); std::string node_info; if (nodeinfo_it == cache.end()) { google::protobuf::Struct test_struct; test_struct.ParseFromArray(bytes.data(), bytes.size()); benchmark::DoNotOptimize(test_struct); flatbuffers::FlatBufferBuilder fbb; extractNodeFlatBuffer(test_struct, fbb); node_info = cache .emplace(node_id, std::string(reinterpret_cast<const char*>( fbb.GetBufferPointer()), fbb.GetSize())) .first->second; } else { node_info = nodeinfo_it->second; } setData(filter_state, metadata_id_key, node_id); setData(filter_state, metadata_key, node_info); } } BENCHMARK(BM_WriteFlatBufferWithCache); } // namespace Common // WASM_EPILOG #ifdef NULL_PLUGIN } // namespace Wasm #endif // Boilerplate main(), which discovers benchmarks in the same file and runs // them. int main(int argc, char** argv) { benchmark::Initialize(&argc, argv); if (benchmark::ReportUnrecognizedArguments(argc, argv)) { return 1; } benchmark::RunSpecifiedBenchmarks(); }
// Chemfiles, a modern library for chemistry file reading and writing // Copyright (C) Guillaume Fraux and contributors -- BSD license #include <cassert> #include <cmath> #include <iosfwd> #include <string> #include <vector> #include <iterator> #include <algorithm> #include "chemfiles/Frame.hpp" #include "chemfiles/types.hpp" #include "chemfiles/Atom.hpp" #include "chemfiles/Connectivity.hpp" #include "chemfiles/error_fmt.hpp" #include "chemfiles/Topology.hpp" #include "chemfiles/UnitCell.hpp" #include "chemfiles/external/optional.hpp" using namespace chemfiles; Frame::Frame(UnitCell cell): cell_(std::move(cell)) {} // NOLINT: std::move for trivially copiable type size_t Frame::size() const { assert(positions_.size() == topology_.size()); if (velocities_) { assert(positions_.size() == velocities_->size()); } return positions_.size(); } void Frame::resize(size_t size) { topology_.resize(size); positions_.resize(size); if (velocities_) { velocities_->resize(size); } } void Frame::reserve(size_t size) { topology_.reserve(size); positions_.reserve(size); if (velocities_) { velocities_->reserve(size); } } void Frame::add_velocities() { if (!velocities_) { velocities_ = std::vector<Vector3D>(size()); } } void Frame::guess_bonds() { topology_.clear_bonds(); // This bond guessing algorithm comes from VMD auto cutoff = 0.833; for (size_t i = 0; i < size(); i++) { auto rad = topology_[i].vdw_radius().value_or(0); cutoff = std::max(cutoff, rad); } cutoff = 1.2 * cutoff; for (size_t i = 0; i < size(); i++) { auto i_radius = topology_[i].vdw_radius(); if (!i_radius) { throw error( "missing Van der Waals radius for '{}'", topology_[i].type() ); } for (size_t j = i + 1; j < size(); j++) { auto j_radius = topology_[j].vdw_radius(); if (!j_radius) { throw error( "missing Van der Waals radius for '{}'", topology_[j].type() ); } auto d = distance(i, j); auto radii = i_radius.value() + j_radius.value(); if (0.03 < d && d < 0.6 * radii && d < cutoff) { topology_.add_bond(i, j); } } } auto bonds = topology().bonds(); auto to_remove = std::vector<Bond>(); // We need to remove bonds between hydrogen atoms which are bonded more than // once for (auto& bond : bonds) { auto i = bond[0], j = bond[1]; if (topology_[i].type() != "H") { continue; } if (topology_[j].type() != "H") { continue; } auto nbonds = std::count_if( std::begin(bonds), std::end(bonds), [=](const Bond& b) { return b[0] == i || b[0] == j || b[1] == i || b[1] == j; }); assert(nbonds >= 1); if (nbonds != 1) { to_remove.push_back(bond); } } for (auto& bond : to_remove) { topology_.remove_bond(bond[0], bond[1]); } } void Frame::set_topology(Topology topology) { if (topology.size() != size()) { throw error( "the topology contains {} atoms, but the frame contains {} atoms", topology.size(), size() ); } topology_ = std::move(topology); } void Frame::add_atom(Atom atom, Vector3D position, Vector3D velocity) { topology_.add_atom(std::move(atom)); positions_.push_back(position); if (velocities_) { velocities_->push_back(velocity); } assert(size() == topology_.size()); } void Frame::remove(size_t i) { if (i >= size()) { throw out_of_bounds( "out of bounds atomic index in `Frame::remove`: we have {} atoms, " "but the index is {}", size(), i ); } topology_.remove(i); positions_.erase(positions_.begin() + static_cast<std::ptrdiff_t>(i)); if (velocities_) { velocities_->erase(velocities_->begin() + static_cast<std::ptrdiff_t>(i)); } assert(size() == topology_.size()); } double Frame::distance(size_t i, size_t j) const { if (i >= size() || j >= size()) { throw out_of_bounds( "out of bounds atomic index in `Frame::distance`: we have {} " "atoms, but the index are {} and {}", size(), i, j ); } auto rij = positions_[i] - positions_[j]; return cell_.wrap(rij).norm(); } double Frame::angle(size_t i, size_t j, size_t k) const { if (i >= size() || j >= size() || k >= size()) { throw out_of_bounds( "out of bounds atomic index in `Frame::angle`: we have {} atoms, " "but the index are {}, {}, and {}", size(), i, j, k ); } auto rij = cell_.wrap(positions_[i] - positions_[j]); auto rkj = cell_.wrap(positions_[k] - positions_[j]); auto cos = dot(rij, rkj) / (rij.norm() * rkj.norm()); cos = std::max(-1.0, std::min(1.0, cos)); return acos(cos); } double Frame::dihedral(size_t i, size_t j, size_t k, size_t m) const { if (i >= size() || j >= size() || k >= size() || m >= size()) { throw out_of_bounds( "out of bounds atomic index in `Frame::dihedral`: we have {} " "atoms, but the index are {}, {}, {}, and {}", size(), i, j, k, m ); } auto rij = cell_.wrap(positions_[i] - positions_[j]); auto rjk = cell_.wrap(positions_[j] - positions_[k]); auto rkm = cell_.wrap(positions_[k] - positions_[m]); auto a = cross(rij, rjk); auto b = cross(rjk, rkm); return atan2(rjk.norm() * dot(b, rij), dot(a, b)); } double Frame::out_of_plane(size_t i, size_t j, size_t k, size_t m) const { if (i >= size() || j >= size() || k >= size() || m >= size()) { throw out_of_bounds( "out of bounds atomic index in `Frame::out_of_plane`: we have {} " "atoms, but the index are {}, {}, {}, and {}", size(), i, j, k, m ); } auto rji = cell_.wrap(positions_[j] - positions_[i]); auto rik = cell_.wrap(positions_[i] - positions_[k]); auto rim = cell_.wrap(positions_[i] - positions_[m]); auto n = cross(rik, rim); return dot(rji, n) / n.norm(); }
// AcsVio.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <windows.h> int main(int argc, char* argv[]) { HINSTANCE hLib; int * ProcAdd; printf("Hi, every one. \nThis simple utility will simulate an access violation.\n--Raymond\n"); // Get a handle to the DLL module. hLib = LoadLibrary("Kernel32.dll"); // If the handle is valid, try to get the function address. if (hLib != NULL) { ProcAdd = (int *)GetProcAddress(hLib, "ReadFile"); // If the function address is valid, call the function. if (NULL != ProcAdd) { *ProcAdd = 0; } // Free the DLL module. FreeLibrary(hLib); } return 0; }
// Copyright 2013 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 "chromeos/settings/cros_settings_names.h" namespace chromeos { const char kCrosSettingsPrefix[] = "cros."; // All cros.accounts.* settings are stored in SignedSettings. const char kAccountsPrefAllowGuest[] = "cros.accounts.allowBWSI"; const char kAccountsPrefAllowNewUser[] = "cros.accounts.allowGuest"; const char kAccountsPrefShowUserNamesOnSignIn[] = "cros.accounts.showUserNamesOnSignIn"; const char kAccountsPrefUsers[] = "cros.accounts.users"; const char kAccountsPrefEphemeralUsersEnabled[] = "cros.accounts.ephemeralUsersEnabled"; const char kAccountsPrefDeviceLocalAccounts[] = "cros.accounts.deviceLocalAccounts"; const char kAccountsPrefDeviceLocalAccountsKeyId[] = "id"; const char kAccountsPrefDeviceLocalAccountsKeyType[] = "type"; const char kAccountsPrefDeviceLocalAccountsKeyKioskAppId[] = "kiosk_app_id"; const char kAccountsPrefDeviceLocalAccountAutoLoginId[] = "cros.accounts.deviceLocalAccountAutoLoginId"; const char kAccountsPrefDeviceLocalAccountAutoLoginDelay[] = "cros.accounts.deviceLocalAccountAutoLoginDelay"; const char kAccountsPrefDeviceLocalAccountAutoLoginBailoutEnabled[] = "cros.accounts.deviceLocalAccountAutoLoginBailoutEnabled"; const char kAccountsPrefDeviceLocalAccountPromptForNetworkWhenOffline[] = "cros.accounts.deviceLocalAccountPromptForNetworkWhenOffline"; const char kAccountsPrefSupervisedUsersEnabled[] = "cros.accounts.supervisedUsersEnabled"; // All cros.signed.* settings are stored in SignedSettings. const char kSignedDataRoamingEnabled[] = "cros.signed.data_roaming_enabled"; // True if auto-update was disabled by the system administrator. const char kUpdateDisabled[] = "cros.system.updateDisabled"; // A list of strings which specifies allowed connection types for // update. const char kAllowedConnectionTypesForUpdate[] = "cros.system.allowedConnectionTypesForUpdate"; // The first constant refers to the user setting editable in the UI. The second // refers to the timezone policy. This seperation is necessary to allow the user // to temporarily change the timezone for the current session and reset it to // the policy's value on logout. const char kSystemTimezone[] = "cros.system.timezone"; const char kSystemTimezonePolicy[] = "cros.system.timezone_policy"; // Value of kUse24HourClock user preference of device' owner. // ChromeOS device uses this setting on login screen. const char kSystemUse24HourClock[] = "cros.system.use_24hour_clock"; const char kDeviceOwner[] = "cros.device.owner"; const char kStatsReportingPref[] = "cros.metrics.reportingEnabled"; const char kReleaseChannel[] = "cros.system.releaseChannel"; const char kReleaseChannelDelegated[] = "cros.system.releaseChannelDelegated"; // A boolean pref that indicates whether OS & firmware version info should be // reported along with device policy requests. const char kReportDeviceVersionInfo[] = "cros.device_status.report_version_info"; // A boolean pref that indicates whether device activity times should be // recorded and reported along with device policy requests. const char kReportDeviceActivityTimes[] = "cros.device_status.report_activity_times"; // A boolean pref that indicates whether the state of the dev mode switch at // boot should be reported along with device policy requests. const char kReportDeviceBootMode[] = "cros.device_status.report_boot_mode"; // A boolean pref that indicates whether the current location should be reported // along with device policy requests. const char kReportDeviceLocation[] = "cros.device_status.report_location"; // Determines whether the device reports network interface types and addresses // in device status reports to the device management server. const char kReportDeviceNetworkInterfaces[] = "cros.device_status.report_network_interfaces"; // Determines whether the device reports recently logged in users in device // status reports to the device management server. const char kReportDeviceUsers[] = "cros.device_status.report_users"; // A list of dictionaries, each detailing one extension to install as part of // the AppPack and including the following fields: // "extension-id": ID of the extension to install // "update-url": URL to check the extension's version and download location // "key-checksum": checksum of the extension's CRX public key, encoded in hex. const char kAppPack[] = "cros.app_pack"; const char kAppPackKeyExtensionId[] = "extension-id"; const char kAppPackKeyUpdateUrl[] = "update-url"; // Values from the ScreenSaver proto. Defines the extension ID of the screen // saver extension and the timeout before the screen saver should be started. const char kScreenSaverExtensionId[] = "cros.screen_saver.extension_id"; const char kScreenSaverTimeout[] = "cros.screen_saver.timeout"; // Values from the ForcedLogoutTimeouts proto. Defines the timeouts before a // user is logged out after some period of inactivity as well as the duration of // a warning message informing the user about the pending logout. const char kIdleLogoutTimeout[] = "cros.idle_logout.timeout"; const char kIdleLogoutWarningDuration[] = "cros.idle_logout.warning_duration"; // Defines the set of URLs to be opened on login to the anonymous account used // if the device is in KIOSK mode. const char kStartUpUrls[] = "cros.start_up_urls"; // This policy should not appear in the protobuf ever but is used internally to // signal that we are running in a "safe-mode" for policy recovery. const char kPolicyMissingMitigationMode[] = "cros.internal.policy_mitigation_mode"; // A boolean pref that indicates whether users are allowed to redeem offers // through Chrome OS Registration. const char kAllowRedeemChromeOsRegistrationOffers[] = "cros.echo.allow_redeem_chrome_os_registration_offers"; // A list pref storing the flags that need to be applied to the browser upon // start-up. const char kStartUpFlags[] = "cros.startup_flags"; // A string pref for the restrict parameter to be appended to the Variations URL // when pinging the Variations server. const char kVariationsRestrictParameter[] = "cros.variations_restrict_parameter"; // A boolean pref that indicates whether enterprise attestation is enabled for // the device. const char kDeviceAttestationEnabled[] = "cros.device.attestation_enabled"; // A boolean pref that indicates whether attestation for content protection is // enabled for the device. const char kAttestationForContentProtectionEnabled[] = "cros.device.attestation_for_content_protection_enabled"; // The service account identity for device-level service accounts on // enterprise-enrolled devices. const char kServiceAccountIdentity[] = "cros.service_account_identity"; } // namespace chromeos
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // <functional> // class function<R(ArgTypes...)> // template<class F> // requires CopyConstructible<F> && Callable<F, ArgTypes..> // && Convertible<Callable<F, ArgTypes...>::result_type // operator=(F f); #include <functional> #include <cassert> #include "test_macros.h" #include "count_new.hpp" class A { int data_[10]; public: static int count; A() { ++count; for (int i = 0; i < 10; ++i) data_[i] = i; } A(const A&) {++count;} ~A() {--count;} int operator()(int i) const { for (int j = 0; j < 10; ++j) i += data_[j]; return i; } int foo(int) const {return 1;} }; int A::count = 0; int g(int) {return 0;} #if TEST_STD_VER >= 11 struct RValueCallable { template <class ...Args> void operator()(Args&&...) && {} }; struct LValueCallable { template <class ...Args> void operator()(Args&&...) & {} }; #endif int main(int, char**) { assert(globalMemCounter.checkOutstandingNewEq(0)); { std::function<int(int)> f; f = A(); assert(A::count == 1); assert(globalMemCounter.checkOutstandingNewEq(1)); assert(f.target<A>()); assert(f.target<int(*)(int)>() == 0); } assert(A::count == 0); assert(globalMemCounter.checkOutstandingNewEq(0)); { std::function<int(int)> f; f = g; assert(globalMemCounter.checkOutstandingNewEq(0)); assert(f.target<int(*)(int)>()); assert(f.target<A>() == 0); } assert(globalMemCounter.checkOutstandingNewEq(0)); { std::function<int(int)> f; f = (int (*)(int))0; assert(!f); assert(globalMemCounter.checkOutstandingNewEq(0)); assert(f.target<int(*)(int)>() == 0); assert(f.target<A>() == 0); } { std::function<int(const A*, int)> f; f = &A::foo; assert(f); assert(globalMemCounter.checkOutstandingNewEq(0)); assert(f.target<int (A::*)(int) const>() != 0); } { std::function<void(int)> f; f = &g; assert(f); assert(f.target<int(*)(int)>() != 0); f(1); } #if TEST_STD_VER >= 11 { using Fn = std::function<void(int, int, int)>; static_assert(std::is_assignable<Fn&, LValueCallable&>::value, ""); static_assert(std::is_assignable<Fn&, LValueCallable>::value, ""); static_assert(!std::is_assignable<Fn&, RValueCallable&>::value, ""); static_assert(!std::is_assignable<Fn&, RValueCallable>::value, ""); } #endif return 0; }
/* ************************************************************************ * Copyright 2016-2020 Advanced Micro Devices, Inc. * ************************************************************************ */ #include "rocblas_trmm.hpp" #include "handle.h" #include "logging.h" #include "rocblas.h" #include "utility.h" namespace { template <typename> constexpr char rocblas_trmm_name[] = "unknown"; template <> constexpr char rocblas_trmm_name<float>[] = "rocblas_strmm"; template <> constexpr char rocblas_trmm_name<double>[] = "rocblas_dtrmm"; template <typename T> rocblas_status rocblas_trmm_impl(rocblas_handle handle, rocblas_side side, rocblas_fill uplo, rocblas_operation transa, rocblas_diagonal diag, rocblas_int m, rocblas_int n, const T* alpha, const T* a, rocblas_int lda, T* c, rocblas_int ldc) { if(!handle) return rocblas_status_invalid_handle; auto layer_mode = handle->layer_mode; if(layer_mode & (rocblas_layer_mode_log_trace | rocblas_layer_mode_log_bench | rocblas_layer_mode_log_profile) && (!handle->is_device_memory_size_query())) { auto side_letter = rocblas_side_letter(side); auto uplo_letter = rocblas_fill_letter(uplo); auto transa_letter = rocblas_transpose_letter(transa); auto diag_letter = rocblas_diag_letter(diag); if(handle->pointer_mode == rocblas_pointer_mode_host) { if(layer_mode & rocblas_layer_mode_log_trace) log_trace(handle, rocblas_trmm_name<T>, side, uplo, transa, diag, m, n, log_trace_scalar_value(alpha), a, lda, c, ldc); if(layer_mode & rocblas_layer_mode_log_bench) { log_bench(handle, "./rocblas-bench -f trmm -r", rocblas_precision_string<T>, "--side", side_letter, "--uplo", uplo_letter, "--transposeA", transa_letter, "--diag", diag_letter, "-m", m, "-n", n, LOG_BENCH_SCALAR_VALUE(alpha), "--lda", lda, "--ldb", ldc); } } else { if(layer_mode & rocblas_layer_mode_log_trace) log_trace(handle, rocblas_trmm_name<T>, side, uplo, transa, diag, m, n, log_trace_scalar_value(alpha), a, lda, c, ldc); } if(layer_mode & rocblas_layer_mode_log_profile) { log_profile(handle, rocblas_trmm_name<T>, "side", side_letter, "uplo", uplo_letter, "transa", transa_letter, "diag", diag_letter, "m", m, "n", n, "lda", lda, "ldb", ldc); } } rocblas_int nrowa = rocblas_side_left == side ? m : n; if(m < 0 || n < 0 || lda < nrowa || ldc < m) return rocblas_status_invalid_size; if(m == 0 || n == 0) { if(handle->is_device_memory_size_query()) return rocblas_status_size_unchanged; else return rocblas_status_success; } if(!a || !c || !alpha) return rocblas_status_invalid_pointer; // gemm based trmm block sizes constexpr rocblas_int RB = 128; constexpr rocblas_int CB = 128; // work arrays dt1 and dt2 are used in trmm rocblas_int size_dt1 = RB * CB; rocblas_int size_dt2 = CB * CB; size_t dev_bytes = (size_dt1 + size_dt2) * sizeof(T); if(handle->is_device_memory_size_query()) return handle->set_optimal_device_memory_size(dev_bytes); auto mem = handle->device_malloc(dev_bytes); if(!mem) return rocblas_status_memory_error; rocblas_stride stride_a = 0; rocblas_stride stride_c = 0; rocblas_stride stride_mem = 0; rocblas_int batch_count = 1; return rocblas_trmm_template<false, false, RB, CB, T>(handle, side, uplo, transa, diag, m, n, alpha, a, lda, stride_a, c, ldc, stride_c, batch_count, (T*)mem, stride_mem); } } // namespace /* * =========================================================================== * C wrapper * =========================================================================== */ extern "C" { rocblas_status rocblas_strmm(rocblas_handle handle, rocblas_side side, rocblas_fill uplo, rocblas_operation transa, rocblas_diagonal diag, rocblas_int m, rocblas_int n, const float* alpha, const float* a, rocblas_int lda, float* c, rocblas_int ldc) try { return rocblas_trmm_impl(handle, side, uplo, transa, diag, m, n, alpha, a, lda, c, ldc); } catch(...) { return exception_to_rocblas_status(); } rocblas_status rocblas_dtrmm(rocblas_handle handle, rocblas_side side, rocblas_fill uplo, rocblas_operation transa, rocblas_diagonal diag, rocblas_int m, rocblas_int n, const double* alpha, const double* a, rocblas_int lda, double* c, rocblas_int ldc) try { return rocblas_trmm_impl(handle, side, uplo, transa, diag, m, n, alpha, a, lda, c, ldc); } catch(...) { return exception_to_rocblas_status(); } rocblas_status rocblas_ctrmm(rocblas_handle handle, rocblas_side side, rocblas_fill uplo, rocblas_operation transa, rocblas_diagonal diag, rocblas_int m, rocblas_int n, const rocblas_float_complex* alpha, const rocblas_float_complex* a, rocblas_int lda, rocblas_float_complex* c, rocblas_int ldc) try { return rocblas_trmm_impl(handle, side, uplo, transa, diag, m, n, alpha, a, lda, c, ldc); } catch(...) { return exception_to_rocblas_status(); } rocblas_status rocblas_ztrmm(rocblas_handle handle, rocblas_side side, rocblas_fill uplo, rocblas_operation transa, rocblas_diagonal diag, rocblas_int m, rocblas_int n, const rocblas_double_complex* alpha, const rocblas_double_complex* a, rocblas_int lda, rocblas_double_complex* c, rocblas_int ldc) try { return rocblas_trmm_impl(handle, side, uplo, transa, diag, m, n, alpha, a, lda, c, ldc); } catch(...) { return exception_to_rocblas_status(); } } // extern "C" /* ============================================================================================ */
// ======================================================================== // // Copyright 2019-2020 Ingo Wald // // // // 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 "InstanceGroup.h" #include "Context.h" #define LOG(message) \ if (Context::logging()) \ std::cout << "#owl(" << device->ID << "): " \ << message \ << std::endl #define LOG_OK(message) \ if (Context::logging()) \ std::cout << OWL_TERMINAL_GREEN \ << "#owl(" << device->ID << "): " \ << message << OWL_TERMINAL_DEFAULT << std::endl namespace owl { /*! constructor */ InstanceGroup::DeviceData::DeviceData(const DeviceContext::SP &device) : Group::DeviceData(device) {}; InstanceGroup::InstanceGroup(Context *const context, size_t numChildren, Group::SP *groups) : Group(context,context->groups), children(numChildren) { std::vector<uint32_t> childIDs; if (groups) { childIDs.resize(numChildren); for (size_t i=0;i<numChildren;i++) { assert(groups[i]); children[i] = groups[i]; childIDs[i] = groups[i]->ID; } } transforms[0].resize(children.size()); // do NOT automatically resize transforms[0] - need these only if // we use motion blur for this object } /*! pretty-printer, for printf-debugging */ std::string InstanceGroup::toString() const { return "InstanceGroup"; } /*! creates the device-specific data for this group */ RegisteredObject::DeviceData::SP InstanceGroup::createOn(const DeviceContext::SP &device) { return std::make_shared<DeviceData>(device); } /*! set transformation matrix of given child */ void InstanceGroup::setTransform(size_t childID, const affine3f &xfm) { assert(childID < children.size()); transforms[0][childID] = xfm; } void InstanceGroup::setTransforms(uint32_t timeStep, const float *floatsForThisStimeStep, OWLMatrixFormat matrixFormat) { switch(matrixFormat) { case OWL_MATRIX_FORMAT_OWL: { transforms[timeStep].resize(children.size()); memcpy((char*)transforms[timeStep].data(),floatsForThisStimeStep, children.size()*sizeof(affine3f)); } break; default: throw std::runtime_error("used matrix format not yet implmeneted for" " InstanceGroup::setTransforms"); }; } /* set instance IDs to use for the children - MUST be an array of children.size() items */ void InstanceGroup::setInstanceIDs(const uint32_t *_instanceIDs) { std::copy(_instanceIDs,_instanceIDs+instanceIDs.size(),instanceIDs.data()); } void InstanceGroup::setChild(size_t childID, Group::SP child) { assert(childID < children.size()); children[childID] = child; } void InstanceGroup::buildAccel() { for (auto device : context->getDevices()) if (transforms[1].empty()) staticBuildOn<true>(device); else motionBlurBuildOn<true>(device); } void InstanceGroup::refitAccel() { for (auto device : context->getDevices()) if (transforms[1].empty()) staticBuildOn<false>(device); else motionBlurBuildOn<false>(device); } template<bool FULL_REBUILD> void InstanceGroup::staticBuildOn(const DeviceContext::SP &device) { DeviceData &dd = getDD(device); auto optixContext = device->optixContext; SetActiveGPU forLifeTime(device); LOG("building instance accel over " << children.size() << " groups"); // ================================================================== // sanity check that that many instances are actualy allowed by optix: // ================================================================== uint32_t maxInstsPerIAS = 0; optixDeviceContextGetProperty (optixContext, OPTIX_DEVICE_PROPERTY_LIMIT_MAX_INSTANCES_PER_IAS, &maxInstsPerIAS, sizeof(maxInstsPerIAS)); if (children.size() > maxInstsPerIAS) throw std::runtime_error("number of children in instance group exceeds " "OptiX's MAX_INSTANCES_PER_IAS limit"); // ================================================================== // create instance build inputs // ================================================================== OptixBuildInput instanceInput {}; OptixAccelBuildOptions accelOptions {}; //! the N build inputs that go into the builder std::vector<OptixInstance> optixInstances(children.size()); // now go over all children to set up the buildinputs for (size_t childID=0;childID<children.size();childID++) { Group::SP child = children[childID]; assert(child); assert(transforms[1].empty()); const affine3f xfm = transforms[0][childID]; OptixInstance oi = {}; oi.transform[0*4+0] = xfm.l.vx.x; oi.transform[0*4+1] = xfm.l.vy.x; oi.transform[0*4+2] = xfm.l.vz.x; oi.transform[0*4+3] = xfm.p.x; oi.transform[1*4+0] = xfm.l.vx.y; oi.transform[1*4+1] = xfm.l.vy.y; oi.transform[1*4+2] = xfm.l.vz.y; oi.transform[1*4+3] = xfm.p.y; oi.transform[2*4+0] = xfm.l.vx.z; oi.transform[2*4+1] = xfm.l.vy.z; oi.transform[2*4+2] = xfm.l.vz.z; oi.transform[2*4+3] = xfm.p.z; oi.flags = OPTIX_INSTANCE_FLAG_NONE; oi.instanceId = (instanceIDs.empty())?uint32_t(childID):instanceIDs[childID]; oi.visibilityMask = 255; oi.sbtOffset = context->numRayTypes * child->getSBTOffset(); oi.visibilityMask = 255; oi.traversableHandle = child->getTraversable(device); assert(oi.traversableHandle); optixInstances[childID] = oi; } dd.optixInstanceBuffer.alloc(optixInstances.size()* sizeof(optixInstances[0])); dd.optixInstanceBuffer.upload(optixInstances.data(),"optixinstances"); // ================================================================== // set up build input // ================================================================== instanceInput.type = OPTIX_BUILD_INPUT_TYPE_INSTANCES; instanceInput.instanceArray.instances = (CUdeviceptr)dd.optixInstanceBuffer.get(); instanceInput.instanceArray.numInstances = (int)optixInstances.size(); // ================================================================== // set up accel uptions // ================================================================== accelOptions.buildFlags = OPTIX_BUILD_FLAG_PREFER_FAST_TRACE | OPTIX_BUILD_FLAG_ALLOW_UPDATE ; accelOptions.motionOptions.numKeys = 1; if (FULL_REBUILD) accelOptions.operation = OPTIX_BUILD_OPERATION_BUILD; else accelOptions.operation = OPTIX_BUILD_OPERATION_UPDATE; // ================================================================== // query build buffer sizes, and allocate those buffers // ================================================================== OptixAccelBufferSizes blasBufferSizes; OPTIX_CHECK(optixAccelComputeMemoryUsage(optixContext, &accelOptions, &instanceInput, 1, // num build inputs &blasBufferSizes )); // ================================================================== // trigger the build .... // ================================================================== const size_t tempSize = FULL_REBUILD ? blasBufferSizes.tempSizeInBytes : blasBufferSizes.tempUpdateSizeInBytes; LOG("starting to build/refit " << prettyNumber(optixInstances.size()) << " instances, " << prettyNumber(blasBufferSizes.outputSizeInBytes) << "B in output and " << prettyNumber(tempSize) << "B in temp data"); DeviceMemory tempBuffer; tempBuffer.alloc(tempSize); if (FULL_REBUILD) dd.bvhMemory.alloc(blasBufferSizes.outputSizeInBytes); OPTIX_CHECK(optixAccelBuild(optixContext, /* todo: stream */0, &accelOptions, // array of build inputs: &instanceInput,1, // buffer of temp memory: (CUdeviceptr)tempBuffer.get(), tempBuffer.size(), // where we store initial, uncomp bvh: (CUdeviceptr)dd.bvhMemory.get(), dd.bvhMemory.size(), /* the traversable we're building: */ &dd.traversable, /* no compaction for instances: */ nullptr,0u )); CUDA_SYNC_CHECK(); // ================================================================== // aaaaaand .... clean up // ================================================================== // TODO: move those free's to the destructor, so we can delay the // frees until all objects are done tempBuffer.free(); LOG_OK("successfully built instance group accel"); } template<bool FULL_REBUILD> void InstanceGroup::motionBlurBuildOn(const DeviceContext::SP &device) { DeviceData &dd = getDD(device); auto optixContext = device->optixContext; SetActiveGPU forLifeTime(device); LOG("building instance accel over " << children.size() << " groups"); // ================================================================== // sanity check that that many instances are actualy allowed by optix: // ================================================================== uint32_t maxInstsPerIAS = 0; optixDeviceContextGetProperty (optixContext, OPTIX_DEVICE_PROPERTY_LIMIT_MAX_INSTANCES_PER_IAS, &maxInstsPerIAS, sizeof(maxInstsPerIAS)); if (children.size() > maxInstsPerIAS) throw std::runtime_error("number of children in instnace group exceeds " "OptiX's MAX_INSTANCES_PER_IAS limit"); // ================================================================== // build motion transforms // ================================================================== assert(!transforms[1].empty()); std::vector<OptixMatrixMotionTransform> motionTransforms(children.size()); #if OPTIX_VERSION >= 70200 /* since 7.2, optix no longer requires those aabbs (and in fact, no longer supports specifying them */ #else std::vector<box3f> motionAABBs(children.size()); #endif for (size_t childID=0;childID<children.size();childID++) { Group::SP child = children[childID]; assert(child); OptixMatrixMotionTransform mt = {}; mt.child = child->getTraversable(device); mt.motionOptions.numKeys = 2; mt.motionOptions.timeBegin = 0.f; mt.motionOptions.timeEnd = 1.f; mt.motionOptions.flags = OPTIX_MOTION_FLAG_NONE; for (int timeStep = 0; timeStep < 2; timeStep ++ ) { const affine3f xfm = transforms[timeStep][childID]; mt.transform[timeStep][0*4+0] = xfm.l.vx.x; mt.transform[timeStep][0*4+1] = xfm.l.vy.x; mt.transform[timeStep][0*4+2] = xfm.l.vz.x; mt.transform[timeStep][0*4+3] = xfm.p.x; mt.transform[timeStep][1*4+0] = xfm.l.vx.y; mt.transform[timeStep][1*4+1] = xfm.l.vy.y; mt.transform[timeStep][1*4+2] = xfm.l.vz.y; mt.transform[timeStep][1*4+3] = xfm.p.y; mt.transform[timeStep][2*4+0] = xfm.l.vx.z; mt.transform[timeStep][2*4+1] = xfm.l.vy.z; mt.transform[timeStep][2*4+2] = xfm.l.vz.z; mt.transform[timeStep][2*4+3] = xfm.p.z; } motionTransforms[childID] = mt; #if OPTIX_VERSION >= 70200 /* since 7.2, optix no longer requires those aabbs (and in fact, no longer supports specifying them */ #else motionAABBs[childID] = xfmBounds(transforms[0][childID],child->bounds[0]); motionAABBs[childID].extend(xfmBounds(transforms[1][childID],child->bounds[1])); #endif } // and upload dd.motionTransformsBuffer.alloc(motionTransforms.size()* sizeof(motionTransforms[0])); dd.motionTransformsBuffer.upload(motionTransforms.data(),"motionTransforms"); #if OPTIX_VERSION >= 70200 /* since 7.2, optix no longer requires those aabbs (and in fact, no longer supports specifying them */ #else dd.motionAABBsBuffer.alloc(motionAABBs.size()*sizeof(box3f)); dd.motionAABBsBuffer.upload(motionAABBs.data(),"motionaabbs"); #endif // ================================================================== // create instance build inputs // ================================================================== OptixBuildInput instanceInput {}; OptixAccelBuildOptions accelOptions {}; //! the N build inputs that go into the builder std::vector<OptixInstance> optixInstances(children.size()); // now go over all children to set up the buildinputs for (size_t childID=0;childID<children.size();childID++) { Group::SP child = children[childID]; assert(child); OptixTraversableHandle childMotionHandle = 0; OPTIX_CHECK(optixConvertPointerToTraversableHandle (optixContext, (CUdeviceptr)(((const uint8_t*)dd.motionTransformsBuffer.get()) +childID*sizeof(motionTransforms[0]) ), OPTIX_TRAVERSABLE_TYPE_MATRIX_MOTION_TRANSFORM, &childMotionHandle)); OptixInstance oi = {}; oi.transform[0*4+0] = 1.f;//xfm.l.vx.x; oi.transform[0*4+1] = 0.f;//xfm.l.vy.x; oi.transform[0*4+2] = 0.f;//xfm.l.vz.x; oi.transform[0*4+3] = 0.f;//xfm.p.x; oi.transform[1*4+0] = 0.f;//xfm.l.vx.y; oi.transform[1*4+1] = 1.f;//xfm.l.vy.y; oi.transform[1*4+2] = 0.f;//xfm.l.vz.y; oi.transform[1*4+3] = 0.f;//xfm.p.y; oi.transform[2*4+0] = 0.f;//xfm.l.vx.z; oi.transform[2*4+1] = 0.f;//xfm.l.vy.z; oi.transform[2*4+2] = 1.f;//xfm.l.vz.z; oi.transform[2*4+3] = 0.f;//xfm.p.z; oi.flags = OPTIX_INSTANCE_FLAG_NONE; oi.instanceId = (instanceIDs.empty())?uint32_t(childID):instanceIDs[childID]; oi.sbtOffset = context->numRayTypes * child->getSBTOffset(); oi.visibilityMask = 1; //255; oi.traversableHandle = childMotionHandle; optixInstances[childID] = oi; } dd.optixInstanceBuffer.alloc(optixInstances.size()* sizeof(optixInstances[0])); dd.optixInstanceBuffer.upload(optixInstances.data(),"optixinstances"); // ================================================================== // set up build input // ================================================================== instanceInput.type = OPTIX_BUILD_INPUT_TYPE_INSTANCES; instanceInput.instanceArray.instances = dd.optixInstanceBuffer.d_pointer; instanceInput.instanceArray.numInstances = (int)optixInstances.size(); #if OPTIX_VERSION >= 70200 /* since 7.2, optix no longer requires those aabbs (and in fact, no longer supports specifying them */ #else instanceInput.instanceArray.aabbs = dd.motionAABBsBuffer.d_pointer; instanceInput.instanceArray.numAabbs = (int)motionAABBs.size(); #endif // ================================================================== // set up accel uption // ================================================================== accelOptions = {}; accelOptions.buildFlags = OPTIX_BUILD_FLAG_PREFER_FAST_TRACE | OPTIX_BUILD_FLAG_ALLOW_UPDATE ; if (FULL_REBUILD) accelOptions.operation = OPTIX_BUILD_OPERATION_BUILD; else { accelOptions.operation = OPTIX_BUILD_OPERATION_UPDATE; } // ================================================================== // query build buffer sizes, and allocate those buffers // ================================================================== OptixAccelBufferSizes blasBufferSizes; OPTIX_CHECK(optixAccelComputeMemoryUsage(optixContext, &accelOptions, &instanceInput, 1, // num build inputs &blasBufferSizes )); // ================================================================== // trigger the build .... // ================================================================== const size_t tempSize = FULL_REBUILD ? blasBufferSizes.tempSizeInBytes : blasBufferSizes.tempUpdateSizeInBytes; LOG("starting to build/refit " << prettyNumber(optixInstances.size()) << " instances, " << prettyNumber(blasBufferSizes.outputSizeInBytes) << "B in output and " << prettyNumber(tempSize) << "B in temp data"); DeviceMemory tempBuffer; tempBuffer.alloc(tempSize); if (FULL_REBUILD) dd.bvhMemory.alloc(blasBufferSizes.outputSizeInBytes); OPTIX_CHECK(optixAccelBuild(optixContext, /* todo: stream */0, &accelOptions, // array of build inputs: &instanceInput,1, // buffer of temp memory: (CUdeviceptr)tempBuffer.get(), tempBuffer.size(), // where we store initial, uncomp bvh: (CUdeviceptr)dd.bvhMemory.get(), dd.bvhMemory.size(), /* the traversable we're building: */ &dd.traversable, /* no compaction for instances: */ nullptr,0u )); CUDA_SYNC_CHECK(); // ================================================================== // aaaaaand .... clean up // ================================================================== // TODO: move those free's to the destructor, so we can delay the // frees until all objects are done tempBuffer.free(); LOG_OK("successfully built instance group accel"); } } // ::owl
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // <memory> // template <class X> // class auto_ptr; // // In C++17, auto_ptr has been removed. // However, for backwards compatibility, if _LIBCUDACXX_NO_REMOVE_AUTOPTR // is defined before including <memory>, then auto_ptr will be restored. // MODULES_DEFINES: _LIBCUDACXX_ENABLE_CXX17_REMOVED_AUTO_PTR // MODULES_DEFINES: _LIBCUDACXX_DISABLE_DEPRECATION_WARNINGS #define _LIBCUDACXX_ENABLE_CXX17_REMOVED_AUTO_PTR #define _LIBCUDACXX_DISABLE_DEPRECATION_WARNINGS #include <memory> #include <type_traits> #include "test_macros.h" int main(int, char**) { std::auto_ptr<int> p; return 0; }
#pragma once #include <sre/SpriteAtlas.hpp> #include <sre/SDLRenderer.hpp> #include "Level.hpp" #include "Snake.hpp" using namespace sre; class SnakeGUI { public: SnakeGUI(); private: void setupLevel(int width, int height); void update(float deltaTime); void keyEvent(SDL_Event &mouseEvent); void render(); void placeFood(); void restart(); std::shared_ptr<SpriteAtlas> atlas; SDLRenderer r; Camera camera; Level level; Snake snake; int foodX; int foodY; int score; bool playing = true; float tickRate = 0.25f; const int levelBlockSize = 100; const int snakeBlockSize = 25; std::shared_ptr<sre::SpriteBatch> levelSprites; };
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include "comms-precomp.h" // Precompiled headers
#include <doctest/doctest.h> #include <array> #include <chess/position.hpp> #include <cstdint> #include <string> TEST_SUITE_BEGIN("DeepPerft"); [[nodiscard]] static auto perft(chess::Position &pos, const std::size_t depth) noexcept -> std::uint64_t { if (depth == 0) { return 1ULL; } std::uint64_t nodes = 0ULL; const auto moves = pos.movegen(); REQUIRE(moves.size() <= moves.capacity()); for (const auto &move : moves) { pos.makemove<false>(move); if (pos.is_attacked(pos.get_king(!pos.turn()), pos.turn())) { pos.undomove(); continue; } nodes += perft(pos, depth - 1); pos.undomove(); } return nodes; } using pair_type = std::pair<std::string, std::array<std::uint64_t, 6>>; TEST_CASE("Perft960 - suite") { const std::array<pair_type, 960> tests = {{ {"bqnb1rkr/pp3ppp/3ppn2/2p5/5P2/P2P4/NPP1P1PP/BQ1BNRKR w HFhf - 2 9", {21, 528, 12189, 326672, 8146062, 227689589}}, {"2nnrbkr/p1qppppp/8/1ppb4/6PP/3PP3/PPP2P2/BQNNRBKR w HEhe - 1 9", {21, 807, 18002, 667366, 16253601, 590751109}}, {"b1q1rrkb/pppppppp/3nn3/8/P7/1PPP4/4PPPP/BQNNRKRB w GE - 1 9", {20, 479, 10471, 273318, 6417013, 177654692}}, {"qbbnnrkr/2pp2pp/p7/1p2pp2/8/P3PP2/1PPP1KPP/QBBNNR1R w hf - 0 9", {22, 593, 13440, 382958, 9183776, 274103539}}, {"1nbbnrkr/p1p1ppp1/3p4/1p3P1p/3Pq2P/8/PPP1P1P1/QNBBNRKR w HFhf - 0 9", {28, 1120, 31058, 1171749, 34030312, 1250970898}}, {"qnbnr1kr/ppp1b1pp/4p3/3p1p2/8/2NPP3/PPP1BPPP/QNB1R1KR w HEhe - 1 9", {29, 899, 26578, 824055, 24851983, 775718317}}, {"q1bnrkr1/ppppp2p/2n2p2/4b1p1/2NP4/8/PPP1PPPP/QNB1RRKB w ge - 1 9", {30, 860, 24566, 732757, 21093346, 649209803}}, {"qbn1brkr/ppp1p1p1/2n4p/3p1p2/P7/6PP/QPPPPP2/1BNNBRKR w HFhf - 0 9", {25, 635, 17054, 465806, 13203304, 377184252}}, {"qnnbbrkr/1p2ppp1/2pp3p/p7/1P5P/2NP4/P1P1PPP1/Q1NBBRKR w HFhf - 0 9", {24, 572, 15243, 384260, 11110203, 293989890}}, {"qn1rbbkr/ppp2p1p/1n1pp1p1/8/3P4/P6P/1PP1PPPK/QNNRBB1R w hd - 2 9", {28, 811, 23175, 679699, 19836606, 594527992}}, {"qnr1bkrb/pppp2pp/3np3/5p2/8/P2P2P1/NPP1PP1P/QN1RBKRB w GDg - 3 9", {33, 823, 26895, 713420, 23114629, 646390782}}, {"qb1nrkbr/1pppp1p1/1n3p2/p1B4p/8/3P1P1P/PPP1P1P1/QBNNRK1R w HEhe - 0 9", {31, 855, 25620, 735703, 21796206, 651054626}}, {"qnnbrk1r/1p1ppbpp/2p5/p4p2/2NP3P/8/PPP1PPP1/Q1NBRKBR w HEhe - 0 9", {26, 790, 21238, 642367, 17819770, 544866674}}, {"1qnrkbbr/1pppppp1/p1n4p/8/P7/1P1N1P2/2PPP1PP/QN1RKBBR w HDhd - 0 9", {37, 883, 32187, 815535, 29370838, 783201510}}, {"qn1rkrbb/pp1p1ppp/2p1p3/3n4/4P2P/2NP4/PPP2PP1/Q1NRKRBB w FDfd - 1 9", {24, 585, 14769, 356950, 9482310, 233468620}}, {"bb1qnrkr/pp1p1pp1/1np1p3/4N2p/8/1P4P1/P1PPPP1P/BBNQ1RKR w HFhf - 0 9", {29, 864, 25747, 799727, 24219627, 776836316}}, {"bnqbnr1r/p1p1ppkp/3p4/1p4p1/P7/3NP2P/1PPP1PP1/BNQB1RKR w HF - 0 9", {26, 889, 24353, 832956, 23701014, 809194268}}, {"bnqnrbkr/1pp2pp1/p7/3pP2p/4P1P1/8/PPPP3P/BNQNRBKR w HEhe d6 0 9", {31, 984, 28677, 962591, 29032175, 1008880643}}, {"b1qnrrkb/ppp1pp1p/n2p1Pp1/8/8/P7/1PPPP1PP/BNQNRKRB w GE - 0 9", {20, 484, 10532, 281606, 6718715, 193594729}}, {"n1bqnrkr/pp1ppp1p/2p5/6p1/2P2b2/PN6/1PNPPPPP/1BBQ1RKR w HFhf - 2 9", {23, 732, 17746, 558191, 14481581, 457140569}}, {"n1bb1rkr/qpnppppp/2p5/p7/P1P5/5P2/1P1PPRPP/NQBBN1KR w Hhf - 1 9", {27, 697, 18724, 505089, 14226907, 400942568}}, {"nqb1rbkr/pppppp1p/4n3/6p1/4P3/1NP4P/PP1P1PP1/1QBNRBKR w HEhe - 1 9", {28, 641, 18811, 456916, 13780398, 354122358}}, {"n1bnrrkb/pp1pp2p/2p2p2/6p1/5B2/3P4/PPP1PPPP/NQ1NRKRB w GE - 2 9", {28, 606, 16883, 381646, 10815324, 254026570}}, {"nbqnbrkr/2ppp1p1/pp3p1p/8/4N2P/1N6/PPPPPPP1/1BQ1BRKR w HFhf - 0 9", {26, 626, 17268, 437525, 12719546, 339132046}}, {"nq1bbrkr/pp2nppp/2pp4/4p3/1PP1P3/1B6/P2P1PPP/NQN1BRKR w HFhf - 2 9", {21, 504, 11812, 302230, 7697880, 207028745}}, {"nqnrb1kr/2pp1ppp/1p1bp3/p1B5/5P2/3N4/PPPPP1PP/NQ1R1BKR w HDhd - 0 9", {30, 672, 19307, 465317, 13454573, 345445468}}, {"nqn2krb/p1prpppp/1pbp4/7P/5P2/8/PPPPPKP1/NQNRB1RB w g - 3 9", {21, 461, 10608, 248069, 6194124, 152861936}}, {"nb1n1kbr/ppp1rppp/3pq3/P3p3/8/4P3/1PPPRPPP/NBQN1KBR w Hh - 1 9", {19, 566, 11786, 358337, 8047916, 249171636}}, {"nqnbrkbr/1ppppp1p/p7/6p1/6P1/P6P/1PPPPP2/NQNBRKBR w HEhe - 1 9", {20, 382, 8694, 187263, 4708975, 112278808}}, {"nq1rkb1r/pp1pp1pp/1n2bp1B/2p5/8/5P1P/PPPPP1P1/NQNRKB1R w HDhd - 2 9", {24, 809, 20090, 673811, 17647882, 593457788}}, {"nqnrkrb1/pppppp2/7p/4b1p1/8/PN1NP3/1PPP1PPP/1Q1RKRBB w FDfd - 1 9", {26, 683, 18102, 473911, 13055173, 352398011}}, {"bb1nqrkr/1pp1ppp1/pn5p/3p4/8/P2NNP2/1PPPP1PP/BB2QRKR w HFhf - 0 9", {29, 695, 21193, 552634, 17454857, 483785639}}, {"bnn1qrkr/pp1ppp1p/2p5/b3Q1p1/8/5P1P/PPPPP1P1/BNNB1RKR w HFhf - 2 9", {44, 920, 35830, 795317, 29742670, 702867204}}, {"bnnqrbkr/pp1p2p1/2p1p2p/5p2/1P5P/1R6/P1PPPPP1/BNNQRBK1 w Ehe - 0 9", {33, 1022, 32724, 1024721, 32898113, 1047360456}}, {"b1nqrkrb/2pppppp/p7/1P6/1n6/P4P2/1P1PP1PP/BNNQRKRB w GEge - 0 9", {23, 638, 15744, 446539, 11735969, 344211589}}, {"n1bnqrkr/3ppppp/1p6/pNp1b3/2P3P1/8/PP1PPP1P/NBB1QRKR w HFhf - 1 9", {29, 728, 20768, 532084, 15621236, 415766465}}, {"n2bqrkr/p1p1pppp/1pn5/3p1b2/P6P/1NP5/1P1PPPP1/1NBBQRKR w HFhf - 3 9", {20, 533, 12152, 325059, 8088751, 223068417}}, {"nnbqrbkr/1pp1p1p1/p2p4/5p1p/2P1P3/N7/PPQP1PPP/N1B1RBKR w HEhe - 0 9", {27, 619, 18098, 444421, 13755384, 357222394}}, {"nnbqrkr1/pp1pp2p/2p2b2/5pp1/1P5P/4P1P1/P1PP1P2/NNBQRKRB w GEge - 1 9", {32, 1046, 33721, 1111186, 36218182, 1202830851}}, {"nb1qbrkr/p1pppp2/1p1n2pp/8/1P6/2PN3P/P2PPPP1/NB1QBRKR w HFhf - 0 9", {25, 521, 14021, 306427, 8697700, 201455191}}, {"nnq1brkr/pp1pppp1/8/2p4P/8/5K2/PPPbPP1P/NNQBBR1R w hf - 0 9", {23, 724, 18263, 571072, 15338230, 484638597}}, {"nnqrbb1r/pppppk2/5pp1/7p/1P6/3P2PP/P1P1PP2/NNQRBBKR w HD - 0 9", {30, 717, 21945, 547145, 17166700, 450069742}}, {"nnqr1krb/p1p1pppp/2bp4/8/1p1P4/4P3/PPP2PPP/NNQRBKRB w GDgd - 0 9", {25, 873, 20796, 728628, 18162741, 641708630}}, {"nbnqrkbr/p2ppp2/1p4p1/2p4p/3P3P/3N4/PPP1PPPR/NB1QRKB1 w Ehe - 0 9", {24, 589, 15190, 382317, 10630667, 279474189}}, {"n1qbrkbr/p1ppp2p/2n2pp1/1p6/1P6/2P3P1/P2PPP1P/NNQBRKBR w HEhe - 0 9", {22, 592, 14269, 401976, 10356818, 301583306}}, {"2qrkbbr/ppn1pppp/n1p5/3p4/5P2/P1PP4/1P2P1PP/NNQRKBBR w HDhd - 1 9", {27, 750, 20584, 605458, 16819085, 516796736}}, {"1nqr1rbb/pppkp1pp/1n3p2/3p4/1P6/5P1P/P1PPPKP1/NNQR1RBB w - - 1 9", {24, 623, 15921, 429446, 11594634, 322745925}}, {"bbn1rqkr/pp1pp2p/4npp1/2p5/1P6/2BPP3/P1P2PPP/1BNNRQKR w HEhe - 0 9", {23, 730, 17743, 565340, 14496370, 468608864}}, {"bn1brqkr/pppp2p1/3npp2/7p/PPP5/8/3PPPPP/BNNBRQKR w HEhe - 0 9", {25, 673, 17835, 513696, 14284338, 434008567}}, {"bn1rqbkr/ppp1ppp1/1n6/2p4p/7P/3P4/PPP1PPP1/BN1RQBKR w HDhd - 0 9", {25, 776, 20562, 660217, 18486027, 616653869}}, {"bnnr1krb/ppp2ppp/3p4/3Bp3/q1P3PP/8/PP1PPP2/BNNRQKR1 w GDgd - 0 9", {29, 1040, 30772, 1053113, 31801525, 1075147725}}, {"1bbnrqkr/pp1ppppp/8/2p5/n7/3PNPP1/PPP1P2P/NBB1RQKR w HEhe - 1 9", {24, 598, 15673, 409766, 11394778, 310589129}}, {"nnbbrqkr/p2ppp1p/1pp5/8/6p1/N1P5/PPBPPPPP/N1B1RQKR w HEhe - 0 9", {26, 530, 14031, 326312, 8846766, 229270702}}, {"nnbrqbkr/2p1p1pp/p4p2/1p1p4/8/NP6/P1PPPPPP/N1BRQBKR w HDhd - 0 9", {17, 496, 10220, 303310, 7103549, 217108001}}, {"nnbrqk1b/pp2pprp/2pp2p1/8/3PP1P1/8/PPP2P1P/NNBRQRKB w d - 1 9", {33, 820, 27856, 706784, 24714401, 645835197}}, {"1bnrbqkr/ppnpp1p1/2p2p1p/8/1P6/4PPP1/P1PP3P/NBNRBQKR w HDhd - 0 9", {27, 705, 19760, 548680, 15964771, 464662032}}, {"n1rbbqkr/pp1pppp1/7p/P1p5/1n6/2PP4/1P2PPPP/NNRBBQKR w HChc - 0 9", {22, 631, 14978, 431801, 10911545, 320838556}}, {"n1rqb1kr/p1pppp1p/1pn4b/3P2p1/P7/1P6/2P1PPPP/NNRQBBKR w HChc - 0 9", {24, 477, 12506, 263189, 7419372, 165945904}}, {"nnrqbkrb/pppp1pp1/7p/4p3/6P1/2N2B2/PPPPPP1P/NR1QBKR1 w Ggc - 2 9", {29, 658, 19364, 476620, 14233587, 373744834}}, {"n1nrqkbr/ppb2ppp/3pp3/2p5/2P3P1/5P2/PP1PPB1P/NBNRQK1R w HDhd - 1 9", {32, 801, 25861, 681428, 22318948, 619857455}}, {"2rbqkbr/p1pppppp/1nn5/1p6/7P/P4P2/1PPPP1PB/NNRBQK1R w HChc - 2 9", {27, 647, 18030, 458057, 13189156, 354689323}}, {"nn1qkbbr/pp2ppp1/2rp4/2p4p/P2P4/1N5P/1PP1PPP1/1NRQKBBR w HCh - 1 9", {24, 738, 18916, 586009, 16420659, 519075930}}, {"nnrqk1bb/p1ppp2p/5rp1/1p3p2/1P4P1/5P1P/P1PPP3/NNRQKRBB w FCc - 1 9", {25, 795, 20510, 648945, 17342527, 556144017}}, {"bb1nrkqr/ppppn2p/4ppp1/8/1P4P1/4P3/P1PPKP1P/BBNNR1QR w he - 0 9", {29, 664, 20024, 498376, 15373803, 406016364}}, {"bnnbrkqr/1p1ppp2/8/p1p3pp/1P6/N4P2/PBPPP1PP/2NBRKQR w HEhe - 0 9", {31, 770, 24850, 677212, 22562080, 662029574}}, {"1nnrkbqr/p1pp1ppp/4p3/1p6/1Pb1P3/6PB/P1PP1P1P/BNNRK1QR w HDhd - 0 9", {27, 776, 22133, 641002, 19153245, 562738257}}, {"bnr1kqrb/pppp1pp1/1n5p/4p3/P3P3/3P2P1/1PP2P1P/BNNRKQRB w GDg - 0 9", {26, 624, 16411, 435426, 11906515, 338092952}}, {"nbbnrkqr/p1ppp1pp/1p3p2/8/2P5/4P3/PP1P1PPP/NBBNRKQR w HEhe - 1 9", {25, 624, 15561, 419635, 10817378, 311138112}}, {"nn1brkqr/pp1bpppp/8/2pp4/P4P2/1PN5/2PPP1PP/N1BBRKQR w HEhe - 1 9", {23, 659, 16958, 476567, 13242252, 373557073}}, {"n1brkbqr/ppp1pp1p/6pB/3p4/2Pn4/8/PP2PPPP/NN1RKBQR w HDhd - 0 9", {32, 1026, 30360, 978278, 29436320, 957904151}}, {"nnbrkqrb/p2ppp2/Q5pp/1pp5/4PP2/2N5/PPPP2PP/N1BRK1RB w GDgd - 0 9", {36, 843, 29017, 715537, 24321197, 630396940}}, {"nbnrbk1r/pppppppq/8/7p/8/1N2QPP1/PPPPP2P/NB1RBK1R w HDhd - 2 9", {36, 973, 35403, 1018054, 37143354, 1124883780}}, {"nnrbbkqr/2pppp1p/p7/6p1/1p2P3/4QPP1/PPPP3P/NNRBBK1R w HChc - 0 9", {36, 649, 22524, 489526, 16836636, 416139320}}, {"nnrkbbqr/1p2pppp/p2p4/2p5/8/1N2P1P1/PPPP1P1P/1NKRBBQR w hc - 0 9", {26, 672, 18136, 477801, 13342771, 363074681}}, {"n1rkbqrb/pp1ppp2/2n3p1/2p4p/P5PP/1P6/2PPPP2/NNRKBQRB w GCgc - 0 9", {24, 804, 20712, 684001, 18761475, 617932151}}, {"nbkr1qbr/1pp1pppp/pn1p4/8/3P2P1/5R2/PPP1PP1P/NBN1KQBR w H - 2 9", {30, 627, 18669, 423329, 12815016, 312798696}}, {"nnr1kqbr/pp1pp1p1/2p5/b4p1p/P7/1PNP4/2P1PPPP/N1RBKQBR w HChc - 1 9", {12, 421, 6530, 227044, 4266410, 149176979}}, {"n1rkqbbr/p1pp1pp1/np2p2p/8/8/N4PP1/PPPPP1BP/N1RKQ1BR w HChc - 0 9", {27, 670, 19119, 494690, 14708490, 397268628}}, {"nnr1qrbb/p2kpppp/1p1p4/2p5/6P1/PP1P4/2P1PP1P/NNRKQRBB w FC - 0 9", {27, 604, 17043, 409665, 11993332, 308518181}}, {"bbnnrkrq/ppp1pp2/6p1/3p4/7p/7P/PPPPPPP1/BBNNRRKQ w ge - 0 9", {20, 559, 12242, 355326, 8427161, 252274233}}, {"bnnbrkr1/ppp2p1p/5q2/3pp1p1/4P3/1N4P1/PPPPRP1P/BN1B1KRQ w Gge - 0 9", {26, 1036, 27228, 1028084, 28286576, 1042120495}}, {"bn1rkbrq/1pppppp1/p6p/1n6/3P4/6PP/PPPRPP2/BNN1KBRQ w Ggd - 2 9", {29, 633, 19278, 455476, 14333034, 361900466}}, {"b1nrkrqb/1p1npppp/p2p4/2p5/5P2/4P2P/PPPP1RP1/BNNRK1QB w Dfd - 1 9", {25, 475, 12603, 270909, 7545536, 179579818}}, {"1bbnrkrq/ppppppp1/8/7p/1n4P1/1PN5/P1PPPP1P/NBBR1KRQ w Gge - 0 9", {30, 803, 25473, 709716, 23443854, 686365049}}, {"nnbbrkrq/2pp1pp1/1p5p/pP2p3/7P/N7/P1PPPPP1/N1BBRKRQ w GEge - 0 9", {18, 432, 9638, 242350, 6131124, 160393505}}, {"nnbrkbrq/1pppp1p1/p7/7p/1P2Pp2/BN6/P1PP1PPP/1N1RKBRQ w GDgd - 0 9", {27, 482, 13441, 282259, 8084701, 193484216}}, {"n1brkrqb/pppp3p/n3pp2/6p1/3P1P2/N1P5/PP2P1PP/N1BRKRQB w FDfd - 0 9", {28, 642, 19005, 471729, 14529434, 384837696}}, {"nbnrbk2/p1pppp1p/1p3qr1/6p1/1B1P4/1N6/PPP1PPPP/1BNR1RKQ w d - 2 9", {30, 796, 22780, 687302, 20120565, 641832725}}, {"nnrbbrkq/1pp2ppp/3p4/p3p3/3P1P2/1P2P3/P1P3PP/NNRBBKRQ w GC - 1 9", {31, 827, 24538, 663082, 19979594, 549437308}}, {"nnrkbbrq/1pp2p1p/p2pp1p1/2P5/8/8/PP1PPPPP/NNRKBBRQ w Ggc - 0 9", {24, 762, 19283, 624598, 16838099, 555230555}}, {"nnr1brqb/1ppkp1pp/8/p2p1p2/1P1P4/N1P5/P3PPPP/N1RKBRQB w FC - 1 9", {23, 640, 15471, 444905, 11343507, 334123513}}, {"nbnrkrbq/2ppp2p/p4p2/1P4p1/4PP2/8/1PPP2PP/NBNRKRBQ w FDfd - 0 9", {31, 826, 26137, 732175, 23555139, 686250413}}, {"1nrbkr1q/1pppp1pp/1n6/p4p2/N1b4P/8/PPPPPPPB/N1RBKR1Q w FCfc - 2 9", {27, 862, 24141, 755171, 22027695, 696353497}}, {"nnrkrbbq/pppp2pp/8/4pp2/4P3/P7/1PPPBPPP/NNKRR1BQ w c - 0 9", {25, 792, 19883, 636041, 16473376, 532214177}}, {"n1rk1qbb/pppprpp1/2n4p/4p3/2PP3P/8/PP2PPP1/NNRKRQBB w ECc - 1 9", {25, 622, 16031, 425247, 11420973, 321855685}}, {"bbq1rnkr/pnp1pp1p/1p1p4/6p1/2P5/2Q1P2P/PP1P1PP1/BB1NRNKR w HEhe - 2 9", {36, 870, 30516, 811047, 28127620, 799738334}}, {"bq1brnkr/1p1ppp1p/1np5/p5p1/8/1N5P/PPPPPPP1/BQ1BRNKR w HEhe - 0 9", {22, 588, 13524, 380068, 9359618, 273795898}}, {"bq1rn1kr/1pppppbp/Nn4p1/8/8/P7/1PPPPPPP/BQ1RNBKR w HDhd - 1 9", {24, 711, 18197, 542570, 14692779, 445827351}}, {"bqnr1kr1/pppppp1p/6p1/5n2/4B3/3N2PP/PbPPPP2/BQNR1KR1 w GDgd - 2 9", {31, 1132, 36559, 1261476, 43256823, 1456721391}}, {"qbb1rnkr/ppp3pp/4n3/3ppp2/1P3PP1/8/P1PPPN1P/QBB1RNKR w HEhe - 0 9", {28, 696, 20502, 541886, 16492398, 456983120}}, {"qnbbr1kr/pp1ppp1p/4n3/6p1/2p3P1/2PP1P2/PP2P2P/QNBBRNKR w HEhe - 0 9", {25, 655, 16520, 450189, 11767038, 335414976}}, {"1nbrnbkr/p1ppp1pp/1p6/5p2/4q1PP/3P4/PPP1PP2/QNBRNBKR w HDhd - 1 9", {30, 1162, 33199, 1217278, 36048727, 1290346802}}, {"q1brnkrb/p1pppppp/n7/1p6/P7/3P1P2/QPP1P1PP/1NBRNKRB w GDgd - 0 9", {32, 827, 26106, 718243, 23143989, 673147648}}, {"qbnrb1kr/ppp1pp1p/3p4/2n3p1/1P6/6N1/P1PPPPPP/QBNRB1KR w HDhd - 2 9", {29, 751, 23132, 610397, 19555214, 530475036}}, {"q1rbbnkr/pppp1p2/2n3pp/2P1p3/3P4/8/PP1NPPPP/Q1RBBNKR w HChc - 2 9", {29, 806, 24540, 687251, 21694330, 619907316}}, {"q1r1bbkr/pnpp1ppp/2n1p3/1p6/2P2P2/2N1N3/PP1PP1PP/Q1R1BBKR w HChc - 2 9", {32, 1017, 32098, 986028, 31204371, 958455898}}, {"2rnbkrb/pqppppp1/1pn5/7p/2P5/P1R5/QP1PPPPP/1N1NBKRB w Ggc - 4 9", {26, 625, 16506, 434635, 11856964, 336672890}}, {"qbnr1kbr/p2ppppp/2p5/1p6/4n2P/P4N2/1PPP1PP1/QBNR1KBR w HDhd - 0 9", {27, 885, 23828, 767273, 21855658, 706272554}}, {"qnrbnk1r/pp1pp2p/5p2/2pbP1p1/3P4/1P6/P1P2PPP/QNRBNKBR w HChc - 0 9", {26, 954, 24832, 892456, 24415089, 866744329}}, {"qnrnk1br/p1p2ppp/8/1pbpp3/8/PP2N3/1QPPPPPP/1NR1KBBR w HChc - 0 9", {26, 783, 20828, 634267, 17477825, 539674275}}, {"qnrnkrbb/Bpppp2p/6p1/5p2/5P2/3PP3/PPP3PP/QNRNKR1B w FCfc - 1 9", {28, 908, 25730, 861240, 25251641, 869525254}}, {"bbnqrn1r/ppppp2k/5p2/6pp/7P/1QP5/PP1PPPP1/B1N1RNKR w HE - 0 9", {33, 643, 21790, 487109, 16693640, 410115900}}, {"b1qbrnkr/ppp1pp2/2np4/6pp/4P3/2N4P/PPPP1PP1/BQ1BRNKR w HEhe - 0 9", {28, 837, 24253, 745617, 22197063, 696399065}}, {"bnqr1bkr/pp1ppppp/2p5/4N3/5P2/P7/1PPPPnPP/BNQR1BKR w HDhd - 3 9", {25, 579, 13909, 341444, 8601011, 225530258}}, {"b1qr1krb/pp1ppppp/n2n4/8/2p5/2P3P1/PP1PPP1P/BNQRNKRB w GDgd - 0 9", {28, 707, 19721, 549506, 15583376, 468399900}}, {"nbbqr1kr/1pppp1pp/8/p1n2p2/4P3/PN6/1PPPQPPP/1BB1RNKR w HEhe - 0 9", {30, 745, 23416, 597858, 19478789, 515473678}}, {"nqbbrn1r/p1pppp1k/1p4p1/7p/4P3/1R3B2/PPPP1PPP/NQB2NKR w H - 0 9", {24, 504, 13512, 317355, 9002073, 228726497}}, {"nqbr1bkr/p1p1ppp1/1p1n4/3pN2p/1P6/8/P1PPPPPP/NQBR1BKR w HDhd - 0 9", {29, 898, 26532, 809605, 24703467, 757166494}}, {"nqbrn1rb/pppp1kp1/5p1p/4p3/P4B2/3P2P1/1PP1PP1P/NQ1RNKRB w GD - 0 9", {34, 671, 22332, 473110, 15556806, 353235120}}, {"nb1r1nkr/ppp1ppp1/2bp4/7p/3P2qP/P6R/1PP1PPP1/NBQRBNK1 w Dhd - 1 9", {38, 1691, 60060, 2526992, 88557078, 3589649998}}, {"n1rbbnkr/1p1pp1pp/p7/2p1qp2/1B3P2/3P4/PPP1P1PP/NQRB1NKR w HChc - 0 9", {24, 913, 21595, 807544, 19866918, 737239330}}, {"nqrnbbkr/p2p1p1p/1pp5/1B2p1p1/1P3P2/4P3/P1PP2PP/NQRNB1KR w HChc - 0 9", {33, 913, 30159, 843874, 28053260, 804687975}}, {"nqr1bkrb/ppp1pp2/2np2p1/P6p/8/2P4P/1P1PPPP1/NQRNBKRB w GCgc - 0 9", {24, 623, 16569, 442531, 12681936, 351623879}}, {"nb1rnkbr/pqppppp1/1p5p/8/1PP4P/8/P2PPPP1/NBQRNKBR w HDhd - 1 9", {31, 798, 24862, 694386, 22616076, 666227466}}, {"nqrbnkbr/2p1p1pp/3p4/pp3p2/6PP/3P1N2/PPP1PP2/NQRB1KBR w HChc - 0 9", {24, 590, 14409, 383690, 9698432, 274064911}}, {"nqrnkbbr/pp1p1p1p/4p1p1/1p6/8/5P1P/P1PPP1P1/NQRNKBBR w HChc - 0 9", {30, 1032, 31481, 1098116, 34914919, 1233362066}}, {"nqrnkrbb/p2ppppp/1p6/2p5/2P3P1/5P2/PP1PPN1P/NQR1KRBB w FCfc - 1 9", {30, 775, 23958, 668000, 21141738, 621142773}}, {"bbnrqrk1/pp2pppp/4n3/2pp4/P7/1N5P/BPPPPPP1/B2RQNKR w HD - 2 9", {23, 708, 17164, 554089, 14343443, 481405144}}, {"bnr1qnkr/p1pp1p1p/1p4p1/4p1b1/2P1P3/1P6/PB1P1PPP/1NRBQNKR w HChc - 1 9", {30, 931, 29249, 921746, 30026687, 968109774}}, {"b1rqnbkr/ppp1ppp1/3p3p/2n5/P3P3/2NP4/1PP2PPP/B1RQNBKR w HChc - 0 9", {24, 596, 15533, 396123, 11099382, 294180723}}, {"bnrqnr1b/pp1pkppp/2p1p3/P7/2P5/7P/1P1PPPP1/BNRQNKRB w GC - 0 9", {24, 572, 15293, 390903, 11208688, 302955778}}, {"n1brq1kr/bppppppp/p7/8/4P1Pn/8/PPPP1P2/NBBRQNKR w HDhd - 0 9", {20, 570, 13139, 371247, 9919113, 284592289}}, {"1rbbqnkr/ppn1ppp1/3p3p/2p5/3P4/1N4P1/PPPBPP1P/1R1BQNKR w HBhb - 0 9", {29, 1009, 29547, 1040816, 31059587, 1111986835}}, {"nrbq2kr/ppppppb1/5n1p/5Pp1/8/P5P1/1PPPP2P/NRBQNBKR w HBhb - 1 9", {20, 520, 11745, 316332, 7809837, 216997152}}, {"nrb1nkrb/pp3ppp/1qBpp3/2p5/8/P5P1/1PPPPP1P/NRBQNKR1 w GBgb - 2 9", {32, 850, 25642, 734088, 21981567, 664886187}}, {"1br1bnkr/ppqppp1p/1np3p1/8/1PP4P/4N3/P2PPPP1/NBRQB1KR w HChc - 1 9", {32, 798, 24765, 691488, 22076141, 670296871}}, {"nrqbb1kr/1p1pp1pp/2p3n1/p4p2/3PP3/P5N1/1PP2PPP/NRQBB1KR w HBhb - 0 9", {32, 791, 26213, 684890, 23239122, 634260266}}, {"nrqn1bkr/ppppp1pp/4b3/8/4P1p1/5P2/PPPP3P/NRQNBBKR w HBhb - 0 9", {29, 687, 20223, 506088, 15236287, 398759980}}, {"nrqnbrkb/pppp1p2/4p2p/3B2p1/8/1P4P1/PQPPPP1P/NR1NBKR1 w GB - 0 9", {37, 764, 27073, 610950, 21284835, 514864869}}, {"nbrq1kbr/Bp3ppp/2pnp3/3p4/5P2/2P4P/PP1PP1P1/NBRQNK1R w HChc - 0 9", {40, 1271, 48022, 1547741, 56588117, 1850696281}}, {"nrqbnkbr/1p2ppp1/p1p4p/3p4/1P6/8/PQPPPPPP/1RNBNKBR w HBhb - 0 9", {28, 757, 23135, 668025, 21427496, 650939962}}, {"nrqn1bbr/2ppkppp/4p3/pB6/8/2P1P3/PP1P1PPP/NRQNK1BR w HB - 1 9", {27, 642, 17096, 442653, 11872805, 327545120}}, {"nrqnkrb1/p1ppp2p/1p4p1/4bp2/4PP1P/4N3/PPPP2P1/NRQ1KRBB w FBfb - 1 9", {27, 958, 27397, 960350, 28520172, 995356563}}, {"1bnrnqkr/pbpp2pp/8/1p2pp2/P6P/3P1N2/1PP1PPP1/BBNR1QKR w HDhd - 0 9", {27, 859, 23475, 773232, 21581178, 732696327}}, {"b1rbnqkr/1pp1ppp1/2n4p/p2p4/5P2/1PBP4/P1P1P1PP/1NRBNQKR w HChc - 0 9", {26, 545, 14817, 336470, 9537260, 233549184}}, {"1nrnqbkr/p1pppppp/1p6/8/2b2P2/P1N5/1PP1P1PP/BNR1QBKR w HChc - 2 9", {24, 668, 17716, 494866, 14216070, 406225409}}, {"1nrnqkrb/2ppp1pp/p7/1p3p2/5P2/N5K1/PPPPP2P/B1RNQ1RB w gc - 0 9", {33, 725, 23572, 559823, 18547476, 471443091}}, {"nbbr1qkr/p1pppppp/8/1p1n4/3P4/1N3PP1/PPP1P2P/1BBRNQKR w HDhd - 1 9", {28, 698, 20527, 539625, 16555068, 458045505}}, {"1rbbnqkr/1pnppp1p/p5p1/2p5/2P4P/5P2/PP1PP1PR/NRBBNQK1 w Bhb - 1 9", {24, 554, 14221, 362516, 9863080, 269284081}}, {"nrb1qbkr/2pppppp/2n5/p7/2p5/4P3/PPNP1PPP/1RBNQBKR w HBhb - 0 9", {23, 618, 15572, 443718, 12044358, 360311412}}, {"nrb1qkrb/2ppppp1/p3n3/1p1B3p/2P5/6P1/PP1PPPRP/NRBNQK2 w Bgb - 2 9", {27, 593, 16770, 401967, 11806808, 303338935}}, {"nbrn1qkr/ppp1pp2/3p2p1/3Q3P/b7/8/PPPPPP1P/NBRNB1KR w HChc - 2 9", {39, 1056, 40157, 1133446, 42201531, 1239888683}}, {"nr1bbqkr/pp1pp2p/1n3pp1/2p5/8/1P4P1/P1PPPPQP/NRNBBK1R w hb - 0 9", {25, 585, 15719, 406544, 11582539, 320997679}}, {"nr2bbkr/ppp1pppp/1n1p4/8/6PP/1NP4q/PP1PPP2/1RNQBBKR w HBhb - 1 9", {22, 742, 15984, 545231, 13287051, 457010195}}, {"1rnqbkrb/ppp1p1p1/1n3p2/3p3p/P6P/4P3/1PPP1PP1/NRNQBRKB w gb - 0 9", {22, 574, 14044, 379648, 9968830, 281344367}}, {"nb1rqkbr/1pppp1pp/4n3/p4p2/6PP/5P2/PPPPPN2/NBR1QKBR w HCh - 0 9", {25, 621, 16789, 462600, 13378840, 396575613}}, {"nrnbqkbr/2pp2pp/4pp2/pp6/8/1P3P2/P1PPPBPP/NRNBQ1KR w hb - 0 9", {25, 656, 16951, 466493, 12525939, 358763789}}, {"nrnqkbbr/ppppp1p1/7p/5p2/8/P4PP1/NPPPP2P/NR1QKBBR w HBhb - 0 9", {28, 723, 20621, 547522, 15952533, 439046803}}, {"1rnqkr1b/ppppp2p/1n3pp1/8/2P3P1/Pb1N4/1P1PPP1P/NR1QKRBB w FBfb - 0 9", {26, 713, 19671, 548875, 15865528, 454532806}}, {"bbnrnkqr/1pppp1pp/5p2/p7/7P/1P6/PBPPPPPR/1BNRNKQ1 w D - 2 9", {26, 649, 17834, 502279, 14375839, 435585252}}, {"bnrbk1qr/1ppp1ppp/p2np3/8/P7/2N2P2/1PPPP1PP/B1RBNKQR w HC - 0 9", {26, 621, 17569, 451452, 13514201, 364421088}}, {"br1nkbqr/ppppppp1/8/n6p/8/N1P2PP1/PP1PP2P/B1RNKBQR w HCh - 1 9", {29, 664, 20182, 512316, 16125924, 442508159}}, {"bnr1kqrb/pp1pppp1/2n5/2p5/1P4Pp/4N3/P1PPPP1P/BNKR1QRB w gc - 0 9", {36, 888, 31630, 789863, 27792175, 719015345}}, {"1bbrnkqr/pp1p1ppp/2p1p3/1n6/5P2/3Q4/PPPPP1PP/NBBRNK1R w HDhd - 2 9", {36, 891, 31075, 781792, 26998966, 702903862}}, {"nrbbnk1r/pp2pppq/8/2pp3p/3P2P1/1N6/PPP1PP1P/1RBBNKQR w HBhb - 0 9", {29, 1036, 31344, 1139166, 35627310, 1310683359}}, {"nr1nkbqr/ppp3pp/5p2/3pp3/6b1/3PP3/PPP2PPP/NRBNKBQR w hb - 0 9", {18, 664, 13306, 483892, 10658989, 386307449}}, {"nrbnk1rb/ppp1pq1p/3p4/5pp1/2P1P3/1N6/PP1PKPPP/1RBN1QRB w gb - 2 9", {25, 966, 24026, 920345, 23957242, 913710194}}, {"1brnbkqr/pppppp2/6p1/7p/1Pn5/P1NP4/2P1PPPP/NBR1BKQR w HChc - 0 9", {22, 627, 13760, 395829, 9627826, 285900573}}, {"nrnbbk1r/p1pppppq/8/7p/1p6/P5PP/1PPPPPQ1/NRNBBK1R w HBhb - 2 9", {29, 888, 26742, 874270, 27229468, 930799376}}, {"n1nkb1qr/prppppbp/6p1/1p6/2P2P2/P7/1P1PP1PP/NRNKBBQR w HBh - 1 9", {29, 804, 24701, 688520, 21952444, 623156747}}, {"nr2bqrb/ppkpp1pp/1np5/5p1P/5P2/2P5/PP1PP1P1/NRNKBQRB w GB - 0 9", {22, 530, 13055, 347657, 9244693, 264088392}}, {"nbr1kqbr/p3pppp/2ppn3/1p4P1/4P3/1P6/P1PP1P1P/NBRNKQBR w HChc - 1 9", {23, 555, 14291, 350917, 9692630, 247479180}}, {"nr1bkqbr/1p1pp1pp/pnp2p2/8/6P1/P1PP4/1P2PP1P/NRNBKQBR w HBhb - 0 9", {22, 565, 13343, 365663, 9305533, 268612479}}, {"nr1kqbbr/np2pppp/p1p5/1B1p1P2/8/4P3/PPPP2PP/NRNKQ1BR w HBhb - 0 9", {32, 730, 23391, 556995, 18103280, 454569900}}, {"nrnk1rbb/p1p2ppp/3pq3/Qp2p3/1P1P4/8/P1P1PPPP/NRN1KRBB w fb - 2 9", {28, 873, 25683, 791823, 23868737, 747991356}}, {"bbnrnkrq/pp1ppp1p/6p1/2p5/6P1/P5RP/1PPPPP2/BBNRNK1Q w Dgd - 3 9", {37, 1260, 45060, 1542086, 54843403, 1898432768}}, {"bnrb1rkq/ppnpppp1/3Q4/2p4p/7P/N7/PPPPPPP1/B1RBNKR1 w GC - 2 9", {38, 878, 31944, 800440, 28784300, 784569826}}, {"bnrnkbrq/p1ppppp1/1p5p/8/P2PP3/5P2/1PP3PP/BNRNKBRQ w GCgc - 1 9", {26, 617, 16992, 419099, 11965544, 311309576}}, {"bnrnkrqb/pp2p2p/2pp1pp1/8/P7/2PP1P2/1P2P1PP/BNRNKRQB w FCfc - 0 9", {26, 721, 19726, 560824, 15966934, 467132503}}, {"nbbrnkr1/1pppp1p1/p6q/P4p1p/8/5P2/1PPPP1PP/NBBRNRKQ w gd - 2 9", {18, 556, 10484, 316634, 6629293, 202528241}}, {"nrb1nkrq/2pp1ppp/p4b2/1p2p3/P4B2/3P4/1PP1PPPP/NR1BNRKQ w gb - 0 9", {24, 562, 14017, 355433, 9227883, 247634489}}, {"nrbnkbrq/p3p1pp/1p6/2pp1P2/8/3PP3/PPP2P1P/NRBNKBRQ w GBgb - 0 9", {31, 746, 24819, 608523, 21019301, 542954168}}, {"nrbnkrqb/pppp1p1p/4p1p1/8/7P/2P1P3/PPNP1PP1/1RBNKRQB w FBfb - 0 9", {20, 459, 9998, 242762, 5760165, 146614723}}, {"nbrn1krq/ppp1p2p/6b1/3p1pp1/8/4N1PP/PPPPPP2/NBR1BRKQ w gc - 1 9", {27, 835, 23632, 766397, 22667987, 760795567}}, {"nrnbbkrq/p1pp2pp/5p2/1p6/2P1pP1B/1P6/P2PP1PP/NRNB1KRQ w GBgb - 0 9", {24, 646, 16102, 444472, 11489727, 324948755}}, {"nrn1bbrq/1ppkppp1/p2p3p/8/1P3N2/4P3/P1PP1PPP/NR1KBBRQ w GB - 2 9", {32, 591, 18722, 381683, 12069159, 269922838}}, {"n1krbrqb/1ppppppp/p7/8/4n3/P4P1P/1PPPPQP1/NRNKBR1B w FB - 2 9", {26, 639, 16988, 417190, 12167153, 312633873}}, {"n1rnkrbq/1p1ppp1p/8/p1p1b1p1/3PQ1P1/4N3/PPP1PP1P/NBR1KRB1 w FCfc - 0 9", {35, 1027, 35731, 1040417, 35738410, 1060661628}}, {"nrnbkrbq/2pp1pp1/pp6/4p2p/P7/5PPP/1PPPP3/NRNBKRBQ w FBfb - 0 9", {26, 628, 16731, 436075, 11920087, 331498921}}, {"1rnkrbbq/pp1p2pp/1n3p2/1Bp1p3/1P6/1N2P3/P1PP1PPP/1RNKR1BQ w EBeb - 0 9", {33, 992, 32244, 983481, 31703749, 980306735}}, {"nr1krqbb/p1ppppp1/8/1p5p/1Pn5/5P2/P1PPP1PP/NRNKRQBB w EBeb - 0 9", {24, 670, 15985, 445492, 11371067, 325556465}}, {"bbq1rkr1/1ppppppp/p1n2n2/8/2P2P2/1P6/PQ1PP1PP/BB1NRKNR w HEe - 3 9", {32, 794, 26846, 689334, 24085223, 645633370}}, {"b1nbrknr/1qppp1pp/p4p2/1p6/6P1/P2NP3/1PPP1P1P/BQ1BRKNR w HEhe - 1 9", {25, 663, 17138, 482994, 13157826, 389603029}}, {"bqnrk1nr/pp2ppbp/6p1/2pp4/2P5/5P2/PPQPP1PP/B1NRKBNR w HDhd - 0 9", {26, 850, 22876, 759768, 21341087, 719712622}}, {"bqnrknrb/1ppp1p1p/p7/6p1/1P2p3/P1PN4/3PPPPP/BQ1RKNRB w GDgd - 0 9", {25, 721, 19290, 581913, 16391601, 511725087}}, {"q1b1rknr/pp1pppp1/4n2p/2p1b3/1PP5/4P3/PQ1P1PPP/1BBNRKNR w HEhe - 1 9", {32, 975, 32566, 955493, 32649943, 962536105}}, {"qnbbrknr/1p1ppppp/8/p1p5/5P2/PP1P4/2P1P1PP/QNBBRKNR w HEhe - 0 9", {27, 573, 16331, 391656, 11562434, 301166330}}, {"q1brkb1r/p1pppppp/np3B2/8/6n1/1P5N/P1PPPPPP/QN1RKB1R w HDhd - 0 9", {32, 984, 31549, 1007217, 32597704, 1075429389}}, {"qn1rk1rb/p1pppppp/1p2n3/8/2b5/4NPP1/PPPPP1RP/QNBRK2B w Dgd - 4 9", {22, 802, 19156, 697722, 17761431, 650603534}}, {"qbnrbknr/ppp2p1p/8/3pp1p1/1PP1B3/5N2/P2PPPPP/Q1NRBK1R w HDhd - 0 9", {34, 943, 32506, 930619, 32523099, 955802240}}, {"qnrbb1nr/pp1p1ppp/2p2k2/4p3/4P3/5PPP/PPPP4/QNRBBKNR w HC - 0 9", {20, 460, 10287, 241640, 5846781, 140714047}}, {"qnr1bbnr/ppk1p1pp/3p4/2p2p2/8/2P5/PP1PPPPP/QNKRBBNR w - - 1 9", {19, 572, 11834, 357340, 7994547, 243724815}}, {"qnrkbnrb/1p1p1ppp/2p5/4p3/p7/N1BP4/PPP1PPPP/Q1R1KNRB w gc - 0 9", {27, 579, 16233, 375168, 10845146, 268229097}}, {"qbnrkn1r/1pppp1p1/p3bp2/2BN3p/8/5P2/PPPPP1PP/QBNRK2R w HDhd - 0 9", {40, 1027, 38728, 1059229, 38511307, 1104094381}}, {"qnrbknbr/1pp2ppp/4p3/p6N/2p5/8/PPPPPPPP/Q1RBK1BR w HChc - 0 9", {22, 510, 11844, 300180, 7403327, 200581103}}, {"1qkrnbbr/p1pppppp/2n5/1p6/8/5NP1/PPPPPP1P/QNRK1BBR w HC - 4 9", {24, 549, 13987, 352037, 9396521, 255676649}}, {"q1rknr1b/1ppppppb/2n5/p2B3p/8/1PN3P1/P1PPPP1P/Q1RKNRB1 w FCfc - 3 9", {31, 924, 28520, 861944, 27463479, 847726572}}, {"bbnqrk1r/pp1pppp1/2p4p/8/6n1/1N1P1P2/PPP1P1PP/BBQ1RKNR w HEhe - 4 9", {24, 804, 20147, 666341, 18024195, 595947631}}, {"bn1brknr/ppp1p1pp/5p2/3p4/6qQ/3P3P/PPP1PPP1/BN1BRKNR w HEhe - 4 9", {25, 854, 22991, 704173, 20290974, 600195008}}, {"1nqrkbnr/2pp1ppp/pp2p3/3b4/2P5/N7/PP1PPPPP/B1QRKBNR w HDhd - 0 9", {22, 651, 16173, 479152, 13133439, 390886040}}, {"bnqrk1rb/1pp1pppp/p2p4/4n3/2PPP3/8/PP3PPP/BNQRKNRB w GDgd - 1 9", {30, 950, 28169, 889687, 27610213, 880739164}}, {"nbb1rknr/1ppq1ppp/3p4/p3p3/4P3/1N2R3/PPPP1PPP/1BBQ1KNR w Hhe - 2 9", {33, 988, 31293, 967575, 30894863, 985384035}}, {"nqbbrknr/2ppp2p/pp4p1/5p2/7P/3P1P2/PPPBP1P1/NQ1BRKNR w HEhe - 0 9", {27, 492, 13266, 276569, 7583292, 175376176}}, {"1qbrkb1r/pppppppp/8/3n4/4P1n1/PN6/1PPP1P1P/1QBRKBNR w HDhd - 3 9", {28, 800, 21982, 630374, 17313279, 507140861}}, {"1qbrknrb/1p1ppppp/1np5/8/p4P1P/4P1N1/PPPP2P1/NQBRK1RB w GDgd - 0 9", {21, 482, 10581, 267935, 6218644, 168704845}}, {"nbqrbkr1/ppp1pppp/8/3p4/6n1/2P2PPN/PP1PP2P/NBQRBK1R w HDd - 1 9", {29, 921, 25748, 840262, 24138518, 806554650}}, {"nqrb1knr/1ppbpp1p/p7/3p2p1/2P3P1/5P1P/PP1PP3/NQRBBKNR w HChc - 1 9", {31, 803, 25857, 665799, 21998733, 583349773}}, {"1qrkbbr1/pppp1ppp/1n3n2/4p3/5P2/1N6/PPPPP1PP/1QRKBBNR w HCc - 0 9", {25, 715, 19118, 556325, 15514933, 459533767}}, {"nqrkb1rb/pp2pppp/2p1n3/3p4/3PP1N1/8/PPP2PPP/NQRKB1RB w GCgc - 0 9", {26, 795, 21752, 679387, 19185851, 616508881}}, {"nb1rknbr/pp2ppp1/8/2Bp3p/6P1/2P2P1q/PP1PP2P/NBQRKN1R w HDhd - 0 9", {35, 1391, 43025, 1726888, 53033675, 2139267832}}, {"nqrbkn1r/pp1pp1pp/8/2p2p2/5P2/P3B2P/1PbPP1P1/NQRBKN1R w HChc - 0 9", {23, 758, 19439, 653854, 18296195, 628403401}}, {"nqrknbbr/pp1pppp1/7p/2p5/7P/1P1N4/P1PPPPPB/NQRK1B1R w HChc - 2 9", {29, 824, 23137, 683686, 19429491, 595493802}}, {"1qrknrbb/B1p1pppp/8/1p1p4/2n2P2/1P6/P1PPP1PP/NQRKNR1B w FCfc - 0 9", {28, 771, 20237, 581721, 16065378, 483037840}}, {"bbnrqk1r/1ppppppp/8/7n/1p6/P6P/1BPPPPP1/1BNRQKNR w HDhd - 0 9", {25, 601, 15471, 396661, 10697065, 289472497}}, {"bnrbqknr/ppp3p1/3ppp1Q/7p/3P4/1P6/P1P1PPPP/BNRB1KNR w HChc - 0 9", {32, 845, 26876, 742888, 23717883, 682154649}}, {"bn1qkb1r/pprppppp/8/2p5/2PPP1n1/8/PPR2PPP/BN1QKBNR w Hh - 1 9", {32, 856, 27829, 768595, 25245957, 727424329}}, {"1nrqknrb/p1pp1ppp/1p2p3/3N4/5P1P/5b2/PPPPP3/B1RQKNRB w GCgc - 2 9", {33, 873, 27685, 779473, 25128076, 745401024}}, {"nbbrqrk1/pppppppp/8/2N1n3/P7/6P1/1PPPPP1P/1BBRQKNR w HD - 3 9", {25, 555, 14339, 342296, 9153089, 234841945}}, {"1rbbqknr/1ppp1pp1/1n2p3/p6p/4P1P1/P6N/1PPP1P1P/NRBBQK1R w HBhb - 0 9", {25, 693, 18652, 528070, 15133381, 439344945}}, {"nrq1kbnr/p1pbpppp/3p4/1p6/6P1/1N3N2/PPPPPP1P/1RBQKB1R w HBhb - 4 9", {24, 648, 16640, 471192, 12871967, 380436777}}, {"nr1qknr1/p1pppp1p/b5p1/1p6/8/P4PP1/1bPPP1RP/NRBQKN1B w Bgb - 0 9", {18, 533, 11215, 331243, 7777833, 234905172}}, {"nbrqbknr/1ppp2pp/8/4pp2/p2PP1P1/7N/PPP2P1P/NBRQBK1R w HChc - 0 9", {29, 803, 24416, 706648, 22305910, 672322762}}, {"nr1b1k1r/ppp1pppp/2bp1n2/6P1/2P3q1/5P2/PP1PP2P/NRQBBKNR w HBhb - 1 9", {27, 1199, 30908, 1296241, 35121759, 1418677099}}, {"nrqkbbnr/2pppp1p/p7/1p6/2P1Pp2/8/PPNP2PP/1RQKBBNR w HBhb - 0 9", {28, 613, 17874, 432750, 13097064, 345294379}}, {"1rqkbnrb/pp1ppp1p/1n4p1/B1p5/3PP3/4N3/PPP2PPP/NRQK2RB w GBgb - 0 9", {33, 723, 23991, 590970, 19715083, 535650233}}, {"nbrqkn1r/1pppp2p/5pp1/p2b4/5P2/P2PN3/1PP1P1PP/NBRQK1BR w HChc - 2 9", {23, 607, 15482, 400970, 11026383, 290708878}}, {"nrqbknbr/pp1pppp1/8/2p4p/P3PP2/8/1PPP2PP/NRQBKNBR w HBhb - 1 9", {26, 700, 19371, 556026, 16058815, 485460242}}, {"nrqknbbr/p2pppp1/1pp5/6Qp/3P4/1P3P2/P1P1P1PP/NR1KNBBR w HBhb - 0 9", {40, 905, 32932, 829746, 29263502, 791963709}}, {"nrqknrbb/1p3ppp/p2p4/2p1p3/1P6/3PP1P1/P1P2P1P/NRQKNRBB w FBfb - 0 9", {29, 780, 22643, 654495, 19532077, 593181101}}, {"1bnrkqnr/p1pppp2/7p/1p4p1/4b3/7N/PPPP1PPP/BBNRKQ1R w HDhd - 0 9", {25, 725, 19808, 565006, 16661676, 487354613}}, {"bnrbkq1r/pp2p1pp/5n2/2pp1p2/P7/N1PP4/1P2PPPP/B1RBKQNR w HChc - 1 9", {24, 745, 18494, 584015, 15079602, 488924040}}, {"2rkqbnr/p1pppppp/2b5/1pn5/1P3P1Q/2B5/P1PPP1PP/1NRK1BNR w HChc - 3 9", {33, 904, 30111, 840025, 28194726, 801757709}}, {"bnrkqnrb/2pppp2/8/pp4pp/1P5P/6P1/P1PPPPB1/BNRKQNR1 w GCgc - 0 9", {34, 1059, 34090, 1054311, 33195397, 1036498304}}, {"1bbrkq1r/pppp2pp/1n2pp1n/8/2PP4/1N4P1/PP2PP1P/1BBRKQNR w HDhd - 1 9", {33, 891, 28907, 814247, 26970098, 788040469}}, {"nrbbkqnr/1p2pp1p/p1p3p1/3p4/8/1PP5/P2PPPPP/NRBBKQNR w HBhb - 0 9", {21, 567, 13212, 376487, 9539687, 284426039}}, {"1rbkqbr1/ppp1pppp/1n5n/3p4/3P4/1PP3P1/P3PP1P/NRBKQBNR w HBb - 1 9", {27, 752, 20686, 606783, 16986290, 521817800}}, {"nrbkq1rb/1ppp1pp1/4p1n1/p6p/2PP4/5P2/PPK1P1PP/NRB1QNRB w gb - 0 9", {35, 697, 23678, 505836, 16906409, 390324794}}, {"nbrkbqnr/p2pp1p1/5p2/1pp4p/7P/3P2P1/PPP1PP2/NBKRBQNR w hc - 0 9", {25, 679, 17223, 484921, 12879258, 376652259}}, {"nrkb1qnr/ppppp1p1/6bp/5p2/1PP1P1P1/8/P2P1P1P/NRKBBQNR w HBhb - 1 9", {32, 761, 24586, 632916, 20671433, 568524724}}, {"nrk1bbnr/p1q1pppp/1ppp4/8/3P3P/4K3/PPP1PPP1/NR1QBBNR w hb - 0 9", {30, 719, 21683, 541389, 16278120, 423649784}}, {"nrkqbr1b/1pppp1pp/5pn1/p6N/1P3P2/8/P1PPP1PP/NRKQB1RB w GBb - 0 9", {26, 494, 13815, 296170, 8763742, 206993496}}, {"nbrkq2r/pppp1bpp/4p1n1/5p2/7P/2P3N1/PP1PPPP1/NBKRQ1BR w hc - 0 9", {27, 701, 19536, 535052, 15394667, 443506342}}, {"nrkbqnbr/2ppp2p/pp6/5pp1/P1P5/8/1P1PPPPP/NRKBQNBR w HBhb - 0 9", {21, 487, 11341, 285387, 7218486, 193586674}}, {"nr1qnbbr/pk1pppp1/1pp4p/8/3P4/5P1P/PPP1P1P1/NRKQNBBR w HB - 0 9", {22, 546, 13615, 352855, 9587439, 259830255}}, {"nrkq1rbb/pp1ppp1p/2pn4/8/PP3Pp1/7P/2PPP1P1/NRKQNRBB w FBfb - 0 9", {26, 839, 22075, 723845, 19867117, 658535326}}, {"b2rknqr/pp1ppppp/8/2P5/n7/P7/1PPNPPPb/BBNRK1QR w HDhd - 2 9", {24, 699, 19523, 575172, 17734818, 535094237}}, {"bnrbknqr/pp2p2p/2p3p1/3p1p2/8/3P4/PPPNPPPP/B1RBKNQR w HChc - 0 9", {23, 580, 14320, 385917, 10133092, 288041554}}, {"bnrknb1r/pppp2pp/8/4pp2/6P1/3P3P/qPP1PPQ1/BNRKNB1R w HChc - 0 9", {28, 1100, 31813, 1217514, 36142423, 1361341249}}, {"b1rknqrb/ppp1p1p1/2np1p1p/8/4N3/6PQ/PPPPPP1P/B1RKN1RB w GCgc - 0 9", {36, 629, 23082, 453064, 16897544, 367503974}}, {"nb1rknqr/pbppp2p/6p1/1p3p2/5P2/3KP3/PPPP2PP/NBBR1NQR w hd - 2 9", {18, 557, 9779, 300744, 5822387, 180936551}}, {"nr1bknqr/1ppb1ppp/p7/3pp3/B7/2P3NP/PP1PPPP1/NRB1K1QR w HBhb - 2 9", {28, 688, 19541, 519785, 15153092, 425149249}}, {"nrbkn2r/pppp1pqp/4p1p1/8/3P2P1/P3B3/P1P1PP1P/NR1KNBQR w HBhb - 1 9", {32, 808, 25578, 676525, 22094260, 609377239}}, {"nrbknqrb/2p1ppp1/1p6/p2p2Bp/1P6/3P1P2/P1P1P1PP/NR1KNQRB w GBgb - 0 9", {30, 625, 18288, 418895, 12225742, 301834282}}, {"nbr1knqr/1pp1p1pp/3p1pb1/8/7P/5P2/PPPPPQP1/NBRKBN1R w HC - 2 9", {29, 863, 25767, 800239, 24965592, 799182442}}, {"n1kbbnqr/prp2ppp/1p1p4/4p3/1P2P3/3P1B2/P1P2PPP/NRK1BNQR w HBh - 2 9", {26, 653, 17020, 449719, 12187583, 336872952}}, {"nrknbbqr/pp3p1p/B3p1p1/2pp4/4P3/2N3P1/PPPP1P1P/NRK1B1QR w HBhb - 0 9", {29, 683, 19755, 501807, 14684565, 394951291}}, {"n1knbqrb/pr1p1ppp/Qp6/2p1p3/4P3/6P1/PPPP1P1P/NRKNB1RB w GBg - 2 9", {31, 552, 17197, 371343, 11663330, 283583340}}, {"nbrknqbr/p3p1pp/1p1p1p2/2p5/2Q1PP2/8/PPPP2PP/NBRKN1BR w HChc - 0 9", {37, 913, 32470, 825748, 28899548, 759875563}}, {"nrkb1qbr/pp1pppp1/5n2/7p/2p5/1N1NPP2/PPPP2PP/1RKB1QBR w HBhb - 0 9", {25, 712, 18813, 543870, 15045589, 445074372}}, {"nrk2bbr/pppqpppp/3p4/8/1P3nP1/3P4/P1P1PP1P/NRKNQBBR w HBhb - 1 9", {24, 814, 19954, 670162, 17603960, 592121050}}, {"nrknqrbb/1p2ppp1/2pp4/Q6p/P2P3P/8/1PP1PPP1/NRKN1RBB w FBfb - 0 9", {34, 513, 16111, 303908, 9569590, 206509331}}, {"bbnrk1rq/pp2p1pp/2ppn3/5p2/8/3NNP1P/PPPPP1P1/BB1RK1RQ w GDgd - 1 9", {28, 697, 20141, 517917, 15301879, 410843713}}, {"bnrbknrq/ppppp2p/6p1/5p2/4QPP1/8/PPPPP2P/BNRBKNR1 w GCgc - 0 9", {37, 901, 32612, 877372, 31385912, 903831981}}, {"bnkrnbrq/ppppp1p1/B6p/5p2/8/4P3/PPPP1PPP/BNKRN1RQ w - - 0 9", {26, 417, 11124, 217095, 5980981, 133080499}}, {"bnrk1rqb/2pppp1p/3n4/pp4p1/3Q1P2/2N3P1/PPPPP2P/B1RKNR1B w FCfc - 0 9", {49, 1655, 74590, 2512003, 107234294, 3651608327}}, {"nbbrk1rq/pp2pppp/2pp4/8/2P2n2/6N1/PP1PP1PP/NBBRKR1Q w Dgd - 0 9", {28, 960, 26841, 884237, 26083252, 846682836}}, {"nrbb2rq/pppk1ppp/4p1n1/3p4/6P1/1BP5/PP1PPPQP/NRB1KNR1 w GB - 0 9", {28, 735, 22048, 593839, 18588316, 512048946}}, {"nrbk1brq/p1ppppp1/7p/1p6/4P1nP/P7/1PPP1PP1/NRBKNBRQ w GBgb - 0 9", {22, 572, 12739, 351494, 8525056, 247615348}}, {"nrbk1rqb/1pp2ppp/5n2/p2pp3/5B2/1N1P2P1/PPP1PP1P/1R1KNRQB w FBfb - 0 9", {35, 927, 31559, 849932, 28465693, 783048748}}, {"nbrkb1rq/p1pp1ppp/4n3/4p3/Pp6/6N1/1PPPPPPP/NBRKBRQ1 w Cgc - 0 9", {20, 456, 10271, 247733, 6124625, 154766108}}, {"nrkb1nrq/p2pp1pp/1pp2p2/7b/6PP/5P2/PPPPP2N/NRKBB1RQ w GBgb - 0 9", {21, 479, 11152, 264493, 6696458, 165253524}}, {"nr1nbbr1/pppkpp1p/6p1/3p4/P6P/1P6/1RPPPPP1/N1KNBBRQ w G - 1 9", {20, 498, 11304, 288813, 7197322, 188021682}}, {"nrknbrqb/3p1ppp/ppN1p3/8/6P1/8/PPPPPP1P/1RKNBRQB w FBfb - 0 9", {32, 526, 17267, 319836, 10755190, 220058991}}, {"nbrkn1bq/p1pppr1p/1p6/5pp1/8/1N2PP2/PPPP2PP/1BKRNRBQ w c - 1 9", {19, 491, 10090, 277313, 6230616, 180748649}}, {"nrkbnrbq/ppppppp1/8/8/7p/PP3P2/2PPPRPP/NRKBN1BQ w Bfb - 0 9", {16, 353, 6189, 156002, 3008668, 82706705}}, {"nrknrbbq/p4ppp/2p1p3/1p1p4/1P2P3/2P5/P1NP1PPP/1RKNRBBQ w EBeb - 0 9", {29, 728, 21915, 587668, 18231199, 511686397}}, {"nrknr1bb/pppp1p2/7p/2qPp1p1/8/1P5P/P1P1PPP1/NRKNRQBB w EBeb - 0 9", {20, 714, 14336, 500458, 11132758, 386064577}}, {"bbqnrrkn/ppp2p1p/3pp1p1/8/1PP5/2Q5/P1BPPPPP/B2NRKRN w GE - 0 9", {39, 593, 23446, 424799, 16764576, 346185058}}, {"bqn1rkrn/p1p2ppp/1p1p4/4p3/3PP2b/8/PPP2PPP/BQNBRKRN w GEge - 2 9", {25, 773, 20042, 616817, 16632403, 515838333}}, {"bqnrkb1n/p1p1pprp/3p4/1p2P1p1/2PP4/8/PP3PPP/BQNRKBRN w GDd - 1 9", {31, 860, 28102, 810379, 27233018, 813751250}}, {"bqr1krnb/ppppppp1/7p/3n4/1P4P1/P4N2/2PPPP1P/BQNRKR1B w FDf - 3 9", {31, 709, 22936, 559830, 18608857, 480498340}}, {"qbbn1krn/pp3ppp/4r3/2ppp3/P1P4P/8/1P1PPPP1/QBBNRKRN w GEg - 1 9", {26, 775, 21100, 649673, 18476807, 582542257}}, {"qnbbrkrn/1p1pp2p/p7/2p2pp1/8/4P2P/PPPP1PPK/QNBBRR1N w ge - 0 9", {25, 599, 15139, 389104, 10260500, 279222412}}, {"qnbrkbrn/1ppp2p1/p3p2p/5p2/P4P2/1P6/2PPP1PP/QNBRKBRN w GDgd - 0 9", {27, 588, 16735, 394829, 11640416, 293541380}}, {"1nbrkrnb/p1pppp1p/1pq3p1/8/4P3/P1P4N/1P1P1PPP/QNBRKR1B w FDfd - 1 9", {18, 609, 11789, 406831, 8604788, 299491047}}, {"qb1r1krn/pppp2pp/1n2ppb1/4P3/7P/8/PPPP1PP1/QBNRBKRN w GDgd - 0 9", {20, 578, 12205, 349453, 7939483, 229142178}}, {"qnr1bkrn/p3pppp/1bpp4/1p6/2P2PP1/8/PP1PPN1P/QNRBBKR1 w GCgc - 0 9", {30, 865, 26617, 771705, 24475596, 719842237}}, {"1nkrbbrn/qppppppp/8/8/p2P4/1P5P/P1P1PPP1/QNKRBBRN w - - 0 9", {27, 672, 18371, 505278, 14065717, 410130412}}, {"1qrkbrnb/ppp1p1pp/n2p4/5p2/4N3/8/PPPPPPPP/Q1RKBRNB w Ffc - 2 9", {25, 718, 18573, 536771, 14404324, 424279467}}, {"q1nrkrbn/pp1pppp1/2p4p/8/P7/5Pb1/BPPPPNPP/Q1NRKRB1 w FDfd - 0 9", {22, 558, 12911, 336042, 8516966, 228074630}}, {"qnrbkrbn/1p1p1pp1/p1p5/4p2p/8/3P1P2/PPP1P1PP/QNRBKRBN w FCfc - 0 9", {28, 669, 17713, 440930, 12055174, 313276304}}, {"qnrkr1bn/p1pp1ppp/8/1p2p3/3P1P2/bP4P1/P1P1P2P/QNRKRBBN w ECec - 1 9", {23, 845, 20973, 759778, 19939053, 718075943}}, {"q1krrnbb/p1p1pppp/2np4/1pB5/5P2/8/PPPPP1PP/QNRKRN1B w EC - 0 9", {29, 776, 21966, 631941, 18110831, 549019739}}, {"bbn1rkrn/pp1p1ppp/8/2p1p1q1/6P1/P7/BPPPPP1P/B1NQRKRN w GEge - 0 9", {26, 936, 25177, 906801, 24984621, 901444251}}, {"bn1brkrn/pp1qpp1p/2p3p1/3p4/1PPP4/P7/4PPPP/BNQBRKRN w GEge - 1 9", {29, 755, 22858, 645963, 20128587, 600207069}}, {"b2rkbrn/p1pppppp/qp6/8/1n6/2B2P2/P1PPP1PP/1NQRKBRN w GDgd - 0 9", {24, 878, 21440, 791007, 20840078, 775795187}}, {"b2rkrnb/pqp1pppp/n7/1p1p4/P7/N1P2N2/1P1PPPPP/B1QRKR1B w FDfd - 4 9", {26, 724, 19558, 571891, 16109522, 492933398}}, {"1bbqrkrn/ppppp1p1/8/5p1p/P1n3P1/3P4/1PP1PP1P/NBBQRRKN w ge - 1 9", {25, 678, 17351, 461211, 12173245, 329661421}}, {"nqb1rrkn/ppp1bppp/3pp3/8/3P4/1P6/PQP1PPPP/N1BBRRKN w - - 1 9", {23, 503, 12465, 290341, 7626054, 188215608}}, {"nqbrkbr1/p1pppppp/1p6/2N2n2/2P5/5P2/PP1PP1PP/1QBRKBRN w GDgd - 1 9", {29, 688, 20289, 506302, 15167248, 399015237}}, {"nqbrkrn1/1ppppp2/6pp/p7/1P6/2Q5/P1PPPPPP/N1BRKRNB w FDfd - 0 9", {36, 602, 20985, 397340, 13706856, 291708797}}, {"nbqrbrkn/pp1p1pp1/2p5/4p2p/2P3P1/1P3P2/P2PP2P/NBQRBKRN w GD - 0 9", {34, 655, 22581, 474396, 16613630, 379344541}}, {"nqrbbrkn/1p1pppp1/8/p1p4p/4P2P/1N4P1/PPPP1P2/1QRBBKRN w GC - 0 9", {23, 597, 14468, 400357, 10096863, 294900903}}, {"nqrkbbrn/2p1p1pp/pp1p1p2/8/P2N4/2P5/1P1PPPPP/1QRKBBRN w GCgc - 0 9", {32, 744, 23310, 550728, 17597164, 428786656}}, {"n1krbrnb/q1pppppp/p7/1p6/3Q4/2P2P2/PP1PP1PP/N1RKBRNB w FC - 1 9", {43, 1038, 41327, 1074450, 40918952, 1126603824}}, {"nb1rkrbn/p1pp1p1p/qp6/4p1p1/5PP1/P7/1PPPPB1P/NBQRKR1N w FDfd - 2 9", {26, 645, 16463, 445464, 11911314, 342563372}}, {"nqr1krbn/pppp1ppp/8/8/3pP3/5P2/PPPb1NPP/NQRBKRB1 w FCfc - 3 9", {2, 51, 1047, 27743, 612305, 17040200}}, {"n1rkrbbn/pqppppp1/7p/1p6/8/1NPP4/PP1KPPPP/1QR1RBBN w ec - 0 9", {25, 674, 17553, 505337, 13421727, 403551903}}, {"1qrkrnbb/1p1p1ppp/pnp1p3/8/3PP3/P6P/1PP2PP1/NQRKRNBB w ECec - 0 9", {24, 688, 17342, 511444, 13322502, 403441498}}, {"1bnrqkrn/2ppppp1/p7/1p1b3p/3PP1P1/8/PPPQ1P1P/BBNR1KRN w GDgd - 1 9", {35, 925, 32238, 857060, 30458921, 824344087}}, {"bnrbqkr1/ppp2pp1/6n1/3pp2p/1P6/2N3N1/P1PPPPPP/B1RBQRK1 w gc - 0 9", {23, 704, 17345, 539587, 14154852, 450893738}}, {"1nrqkbrn/p1pppppp/8/1p1b4/P6P/5P2/1PPPP1P1/BNRQKBRN w GCgc - 1 9", {19, 505, 10619, 281422, 6450025, 175593967}}, {"b1rqkrnb/ppppppp1/8/6p1/3n4/NP6/P1PPPP1P/B1RQKRNB w FCfc - 0 9", {25, 614, 15578, 377660, 10391021, 259629603}}, {"nbbrqkrn/ppp3p1/3pp3/5p1p/1P2P3/P7/2PPQPPP/NBBR1KRN w GDgd - 0 9", {30, 833, 25719, 717713, 22873901, 649556666}}, {"nr1bqrk1/ppp1pppp/6n1/3pP3/8/5PQb/PPPP2PP/NRBB1KRN w GB - 3 9", {26, 734, 20161, 582591, 17199594, 512134836}}, {"1rbqkbr1/ppppp1pp/1n6/4np2/3P1P2/6P1/PPPQP2P/NRB1KBRN w GBgb - 1 9", {27, 662, 17897, 447464, 13038519, 338365642}}, {"nr1qkr1b/ppp1pp1p/4bn2/3p2p1/4P3/1Q6/PPPP1PPP/NRB1KRNB w FBfb - 4 9", {33, 939, 30923, 942138, 30995969, 991509814}}, {"nb1qbkrn/pprp1pp1/7p/2p1pB2/Q1PP4/8/PP2PPPP/N1R1BKRN w GCg - 2 9", {47, 1128, 50723, 1306753, 56747878, 1560584212}}, {"nrqb1rkn/pp2pppp/2bp4/2p5/6P1/2P3N1/PP1PPP1P/NRQBBRK1 w - - 3 9", {24, 828, 21148, 723705, 19506135, 668969549}}, {"nrq1bbrn/ppkpp2p/2p3p1/P4p2/8/4P1N1/1PPP1PPP/NRQKBBR1 w GB - 0 9", {25, 525, 13533, 309994, 8250997, 201795680}}, {"Br1kbrn1/pqpppp2/8/6pp/3b2P1/1N6/PPPPPP1P/1RQKBRN1 w FBfb - 3 9", {20, 790, 18175, 695905, 17735648, 669854148}}, {"nbrqkrbn/2p1p1pp/p7/1p1p1p2/4P1P1/5P2/PPPP3P/NBRQKRBN w FCfc - 0 9", {29, 771, 22489, 647106, 19192982, 591335970}}, {"1rqbkrbn/1ppppp1p/1n6/p1N3p1/8/2P4P/PP1PPPP1/1RQBKRBN w FBfb - 0 9", {29, 502, 14569, 287739, 8652810, 191762235}}, {"1rqkrbbn/ppnpp1pp/8/2p5/6p1/3P4/PPP1PPPP/NRK1RBBN w eb - 0 9", {19, 531, 10812, 300384, 6506674, 184309316}}, {"nrqkrnbb/p1pp2pp/5p2/4P3/2p5/4N3/PP1PP1PP/NRQKR1BB w EBeb - 0 9", {26, 800, 23256, 756695, 23952941, 809841274}}, {"bbnrkqrn/pp3pp1/4p2p/2pp4/4P1P1/1PB5/P1PP1P1P/1BNRKQRN w GDgd - 0 9", {33, 915, 30536, 878648, 29602610, 881898159}}, {"bnrbkqr1/1p2pppp/6n1/p1pp4/7P/P3P3/1PPPKPP1/BNRB1QRN w gc - 0 9", {19, 457, 9332, 238944, 5356253, 144653627}}, {"b1rkqbrn/pp1p2pp/2n1p3/2p2p2/3P2PP/8/PPP1PP2/BNKRQBRN w gc - 0 9", {30, 985, 30831, 1011700, 32684185, 1080607773}}, {"b1rkqrnb/2ppppp1/np6/p6p/1P6/P2P3P/2P1PPP1/BNRKQRNB w FCfc - 0 9", {26, 692, 18732, 517703, 14561181, 413226841}}, {"nbbrkqrn/1ppp1p2/p6p/4p1p1/5P2/1P5P/P1PPPNP1/NBBRKQR1 w GDgd - 0 9", {22, 561, 13222, 367487, 9307003, 273928315}}, {"nrbbkqrn/p1pppppp/8/1p6/4P3/7Q/PPPP1PPP/NRBBK1RN w GBgb - 0 9", {38, 769, 28418, 632310, 23091070, 560139600}}, {"nrbkqbrn/1pppp2p/8/p4pp1/P4PQ1/8/1PPPP1PP/NRBK1BRN w GBgb - 0 9", {23, 507, 13067, 321423, 8887567, 237475184}}, {"nr1kqr1b/pp2pppp/5n2/2pp4/P5b1/5P2/1PPPPRPP/NRBK1QNB w Bfb - 2 9", {18, 626, 12386, 434138, 9465555, 335004239}}, {"nbkrbqrn/1pppppp1/8/4P2p/pP6/P7/2PP1PPP/NBRKBQRN w GC - 0 9", {22, 329, 8475, 148351, 4160034, 82875306}}, {"nrkb1qrn/pp1pp1pp/8/5p1b/P1p4P/6N1/1PPPPPP1/NRKBBQR1 w GBgb - 2 9", {16, 479, 9037, 275354, 5862341, 184959796}}, {"1rkq1brn/ppppp1pp/1n6/3b1p2/3N3P/5P2/PPPPP1P1/1RKQBBRN w GBgb - 3 9", {23, 614, 15324, 418395, 11090645, 313526088}}, {"nrk1brnb/pp1ppppp/2p5/3q4/5P2/PP6/1KPPP1PP/NR1QBRNB w fb - 1 9", {25, 942, 21765, 792179, 19318837, 685549171}}, {"nbrkqr1n/1pppp2p/p4pp1/2Bb4/5P2/6P1/PPPPP2P/NBRKQ1RN w Cfc - 2 9", {30, 841, 24775, 677876, 20145765, 557578726}}, {"n1kbqrbn/2p1pppp/1r6/pp1p4/P7/3P4/1PP1PPPP/NRKBQRBN w FBf - 2 9", {21, 591, 14101, 394289, 10295086, 292131422}}, {"nrkqrbb1/ppp1pppp/3p4/8/4P3/2Pn1P2/PP4PP/NRKQRBBN w EBeb - 0 9", {4, 88, 3090, 73414, 2640555, 66958031}}, {"nrkqrnbb/ppppp1p1/7p/1P3p2/3P4/2P5/P3PPPP/NRKQRNBB w EBeb - 0 9", {29, 689, 21091, 508789, 16226660, 408570219}}, {"bbnr1rqn/pp2pkpp/2pp1p2/8/4P1P1/8/PPPP1P1P/BBNRKRQN w FD - 0 9", {21, 463, 11135, 256244, 6826249, 165025370}}, {"bnrbk1qn/1pppprpp/8/p4p1P/6P1/3P4/PPP1PP2/BNRBKRQN w FCc - 0 9", {22, 459, 11447, 268157, 7371098, 190583454}}, {"1nrkrbqn/p1pp1ppp/4p3/1p6/1PP5/6PB/P2PPPbP/BNRKR1QN w ECec - 0 9", {30, 931, 29012, 887414, 28412902, 869228014}}, {"b1rkr1nb/pppppqp1/n4B2/7p/8/1P4P1/P1PPPP1P/1NKRRQNB w ec - 1 9", {36, 934, 31790, 930926, 30392925, 952871799}}, {"nbbrkrqn/p1ppp1p1/8/1p3p1p/2P3PP/8/PP1PPPQ1/NBBRKR1N w FDfd - 0 9", {34, 938, 31848, 921716, 31185844, 944483246}}, {"1rbbkrqn/ppp1pp2/1n1p2p1/7p/P3P1P1/3P4/1PP2P1P/NRBBKRQN w FBfb - 0 9", {26, 646, 18083, 472744, 14006203, 384101783}}, {"nrbkrbq1/Qpppp1pp/2n5/5p2/P4P2/6N1/1PPPP1PP/NRBKRB2 w EBeb - 1 9", {27, 619, 16713, 421845, 11718463, 313794027}}, {"1rbkr1nb/pppp1qpp/1n6/4pp2/1PP1P3/8/PB1P1PPP/NR1KRQNB w EBeb - 1 9", {32, 1029, 32970, 1080977, 35483796, 1181835398}}, {"nbrk1rqn/p1ppp2p/1p6/5ppb/8/1N2P2P/PPPP1PP1/1BKRBRQN w fc - 0 9", {18, 594, 12350, 408544, 9329122, 315021712}}, {"nrkbbrqn/3pppp1/7p/ppp5/P7/1N5P/1PPPPPP1/1RKBBRQN w FBfb - 0 9", {19, 417, 9026, 218513, 5236331, 137024458}}, {"nrkr1bqn/ppp1pppp/3p4/1b6/7P/P7/1PPPPPP1/NRKRBBQN w DBdb - 1 9", {17, 457, 9083, 243872, 5503579, 150091997}}, {"nrkrbqnb/p4ppp/1p2p3/2pp4/6P1/2P2N2/PPNPPP1P/1RKRBQ1B w DBdb - 0 9", {27, 755, 21012, 620093, 17883987, 547233320}}, {"nbkrr1bn/ppB2ppp/4p3/2qp4/4P3/5P2/PPPP2PP/NBRKRQ1N w EC - 1 9", {37, 1473, 51939, 1956521, 68070015, 2490912491}}, {"n1kbrqbn/p1pp1pp1/4p2p/2B5/1r3P2/8/PPPPP1PP/NRKBRQ1N w EBe - 2 9", {30, 1029, 30874, 1053163, 32318550, 1106487743}}, {"nrkrqbbn/2pppp1p/8/pp6/1P1P2p1/P5P1/2P1PP1P/NRKRQBBN w DBdb - 0 9", {22, 421, 10034, 221927, 5754555, 141245633}}, {"nrkr1nbb/1ppp2pp/p3q3/4pp2/2P5/P3P3/1PKP1PPP/NR1RQNBB w db - 0 9", {22, 619, 13953, 411392, 9905109, 301403003}}, {"bbnrkrnq/1pp1p2p/6p1/p2p1p2/8/1P2P3/P1PP1PPP/BBNRKRNQ w FDfd - 0 9", {27, 805, 21915, 688224, 19133881, 620749189}}, {"bnrbkrn1/pp1ppp2/2p3pp/8/2Pq4/P4PP1/1P1PP2P/BNRBKRNQ w FCfc - 1 9", {20, 770, 16593, 577980, 13581691, 456736500}}, {"b1rkrbnq/1pp1pppp/2np4/p5N1/8/1P2P3/P1PP1PPP/BNRKRB1Q w ECec - 0 9", {37, 740, 27073, 581744, 21156664, 485803600}}, {"b1krrnqb/pp1ppp1p/n1p3p1/2N5/6P1/8/PPPPPP1P/B1RKRNQB w EC - 0 9", {34, 850, 28494, 752350, 25360295, 698159474}}, {"1bbr1rnq/ppppkppp/8/3np3/4P3/3P4/PPP1KPPP/NBBRR1NQ w - - 1 9", {27, 704, 18290, 480474, 12817011, 341026662}}, {"nrbbk1nq/p1p1prpp/1p6/N2p1p2/P7/8/1PPPPPPP/R1BBKRNQ w Fb - 2 9", {23, 552, 13710, 348593, 9236564, 248469879}}, {"1rbkrb1q/1pppp1pp/1n5n/p4p2/P3P3/1P6/2PPNPPP/NRBKRB1Q w EBeb - 1 9", {22, 415, 10198, 217224, 5735644, 135295774}}, {"nrbkr1qb/1pp1pppp/6n1/p2p4/2P1P3/1N4N1/PP1P1PPP/1RBKR1QB w EBeb - 0 9", {27, 709, 19126, 506214, 14192779, 380516508}}, {"nbrkbrnq/p3p1pp/1pp2p2/3p4/1PP5/4P3/P1KP1PPP/NBR1BRNQ w fc - 0 9", {24, 715, 18009, 535054, 14322279, 427269976}}, {"nrk1brnq/pp1p1pp1/7p/b1p1p3/1P6/6P1/P1PPPPQP/NRKBBRN1 w FBfb - 2 9", {29, 675, 20352, 492124, 15316285, 389051744}}, {"nrkr1bnq/1p2pppp/p2p4/1bp5/PP6/1R5N/2PPPPPP/N1KRBB1Q w Ddb - 2 9", {27, 744, 20494, 571209, 16188945, 458900901}}, {"nrk1b1qb/pppn1ppp/3rp3/3p4/2P3P1/3P4/PPN1PP1P/1RKRBNQB w DBb - 3 9", {35, 941, 33203, 935791, 33150360, 968024386}}, {"nb1rrnbq/ppkp1ppp/8/2p1p3/P7/1N2P3/1PPP1PPP/1BKRRNBQ w - - 1 9", {19, 451, 9655, 235472, 5506897, 139436165}}, {"nrkbrnbq/4pppp/1ppp4/p7/2P1P3/3P2N1/PP3PPP/NRKBR1BQ w EBeb - 0 9", {29, 591, 17132, 384358, 11245508, 270967202}}, {"nrkrnbbq/3p1ppp/1p6/p1p1p3/3P2P1/P4Q2/1PP1PP1P/NRKRNBB1 w DBdb - 0 9", {38, 792, 28597, 640961, 22654797, 540864616}}, {"nr1rnqbb/ppp1pp1p/3k2p1/3p4/1P5P/3P1N2/P1P1PPP1/NRKR1QBB w DB - 1 9", {25, 758, 18547, 543643, 13890077, 402109399}}, {"bbqrnnkr/1ppp1p1p/5p2/p5p1/P7/1P4P1/2PPPP1P/1BQRNNKR w HDhd - 0 9", {20, 322, 7224, 145818, 3588435, 82754650}}, {"bqrb2k1/pppppppr/5nnp/8/3P1P2/4P1N1/PPP3PP/BQRBN1KR w HCc - 1 9", {25, 597, 15872, 397970, 11162476, 295682250}}, {"bqrnn1kr/1pppbppp/8/4p3/1p6/2P1N2P/P2PPPP1/BQR1NBKR w HChc - 1 9", {34, 921, 31695, 864023, 30126510, 850296236}}, {"bqr1nkr1/pppppp2/2n3p1/7p/1P1b1P2/8/PQP1P1PP/B1RNNKRB w GCgc - 0 9", {23, 788, 21539, 686795, 20849374, 645694580}}, {"qbbrnn1r/1pppp1pk/p7/5p1p/P2P3P/3N4/1PP1PPP1/QBBR1NKR w HD - 0 9", {34, 713, 24475, 562189, 19494094, 482645160}}, {"qrbb2kr/p1pppppp/1p1n4/8/1P3n2/P7/Q1PPP1PP/1RBBNNKR w HBhb - 0 9", {28, 977, 26955, 949925, 27802999, 992109168}}, {"qrb2bkr/1pp1pppp/2np1n2/pN6/3P4/4B3/PPP1PPPP/QR2NBKR w HBhb - 0 9", {27, 730, 20534, 585091, 17005916, 507008968}}, {"qrbnnkrb/pp2pp1p/8/2pp2p1/7P/P1P5/QP1PPPP1/1RBNNKRB w GBgb - 0 9", {24, 813, 21142, 707925, 19615756, 655850285}}, {"1brnb1kr/p1pppppp/1p6/8/4q2n/1P2P1P1/PNPP1P1P/QBR1BNKR w HChc - 3 9", {17, 734, 13462, 530809, 11032633, 416356876}}, {"1rnbbnkr/1pp1pppp/1q1p4/p7/4P3/5PN1/PPPP1BPP/QRNB2KR w HBhb - 1 9", {26, 809, 21764, 706677, 20292750, 675408811}}, {"qrnnbb1Q/ppp1pk1p/3p2p1/5p2/PP6/5P2/2PPP1PP/1RNNBBKR w HB - 0 9", {37, 751, 27902, 603931, 22443036, 515122176}}, {"qrnnbkrb/p3p1pp/3p1p2/1pp5/PP2P3/8/2PP1PPP/QRNNBRKB w gb - 0 9", {30, 906, 27955, 872526, 27658191, 890966633}}, {"qbrnnkbr/1p2pp1p/p1p3p1/3p4/6P1/P1N4P/1PPPPP2/QBR1NKBR w HChc - 0 9", {26, 701, 18930, 521377, 14733245, 416881799}}, {"qr1b1kbr/1p1ppppp/1n1n4/p1p5/4P3/5NPP/PPPP1P2/QRNB1KBR w HBhb - 1 9", {26, 649, 17235, 451997, 12367604, 342165821}}, {"qrnnkb1r/1pppppp1/7p/p4b2/4P3/5P1P/PPPP2PR/QRNNKBB1 w Bhb - 1 9", {34, 941, 31720, 901240, 30307554, 888709821}}, {"qr1nkrbb/p2ppppp/1pp5/8/3Pn3/1NP3P1/PP2PP1P/QR1NKRBB w FBfb - 1 9", {19, 505, 11107, 294251, 7046501, 190414579}}, {"bbrqn1kr/1pppp1pp/4n3/5p2/p5P1/3P4/PPP1PPKP/BBRQNN1R w hc - 0 9", {24, 573, 12963, 335845, 8191054, 227555387}}, {"brqb1nkr/pppppp1p/8/4N1pn/5P2/6P1/PPPPP2P/BRQB1NKR w HBhb - 0 9", {26, 550, 14338, 331666, 8903754, 223437427}}, {"brqnn1kr/pp3ppp/2pbp3/3p4/8/2NPP3/PPP1BPPP/BRQ1N1KR w HBhb - 0 9", {27, 780, 20760, 589328, 16243731, 463883447}}, {"brq1nkrb/ppp2ppp/8/n2pp2P/P7/4P3/1PPP1PP1/BRQNNKRB w GBgb - 1 9", {17, 426, 8295, 235162, 5048497, 153986034}}, {"rbbqn1kr/pp2p1pp/6n1/2pp1p2/2P4P/P7/BP1PPPP1/R1BQNNKR w HAha - 0 9", {27, 916, 25798, 890435, 26302461, 924181432}}, {"1qbbn1kr/1ppppppp/r3n3/8/p1P5/P7/1P1PPPPP/RQBBNNKR w HAh - 1 9", {29, 817, 24530, 720277, 22147642, 670707652}}, {"rqbnnbkr/ppp1ppp1/7p/3p4/PP6/7P/1NPPPPP1/RQB1NBKR w HAa - 1 9", {23, 572, 14509, 381474, 10416981, 288064942}}, {"r1bnnkrb/q1ppp1pp/p7/1p3pB1/2P1P3/3P4/PP3PPP/RQ1NNKRB w GAga - 2 9", {31, 925, 27776, 860969, 26316355, 843078864}}, {"rbqnb1kr/ppppp1pp/5p2/5N2/7P/1n3P2/PPPPP1P1/RBQNB1KR w HAha - 1 9", {32, 864, 27633, 766551, 24738875, 707188107}}, {"rqnbbn1r/ppppppp1/6k1/8/6Pp/2PN4/PP1PPPKP/RQ1BBN1R w - - 0 9", {27, 566, 15367, 347059, 9714509, 234622128}}, {"rqnnbbkr/p1p2pp1/1p1p3p/4p3/4NP2/6P1/PPPPP2P/RQN1BBKR w HAha - 0 9", {27, 631, 17923, 452734, 13307890, 356279813}}, {"1qnnbrkb/rppp1ppp/p3p3/8/4P3/2PP1P2/PP4PP/RQNNBKRB w GA - 1 9", {24, 479, 12135, 271469, 7204345, 175460841}}, {"rbqnn1br/p1pppk1p/1p4p1/5p2/8/P1P2P2/1PBPP1PP/R1QNNKBR w HA - 0 9", {31, 756, 23877, 625194, 20036784, 554292502}}, {"rqnbnkbr/1ppppp2/p5p1/8/1P4p1/4PP2/P1PP3P/RQNBNKBR w HAha - 0 9", {24, 715, 18536, 575589, 16013189, 515078271}}, {"rq1nkbbr/1p2pppp/p2n4/2pp4/1P4P1/P2N4/2PPPP1P/RQ1NKBBR w HAha - 1 9", {27, 694, 19840, 552904, 16685687, 494574415}}, {"r1nnkrbb/pp1pppp1/2p3q1/7p/8/1PPP3P/P3PPP1/RQNNKRBB w FAfa - 1 9", {18, 520, 10808, 329085, 7508201, 235103697}}, {"bbrnqk1r/pppp3p/6p1/4pp2/3P2P1/8/PPP1PP1P/BBRN1NKR w HC - 0 9", {22, 566, 12965, 362624, 8721079, 259069471}}, {"brnb1nkr/pppqpp2/3p2pp/8/3PP3/1P6/PBP2PPP/1RNBQNKR w HBhb - 0 9", {32, 859, 28517, 817464, 27734108, 829785474}}, {"brnq1b1r/ppp1ppkp/3p1np1/8/8/5P1P/PPPPPKPR/BRNQNB2 w - - 0 9", {21, 511, 10951, 273756, 6372681, 167139732}}, {"brnq1rkb/1pppppp1/3n3p/p7/8/P4NP1/1PPPPPRP/BRNQ1K1B w B - 0 9", {25, 548, 14049, 341208, 9015901, 235249649}}, {"rbb1qnkr/p1ppp1pp/1p3p2/6n1/8/1PN1P2P/P1PP1PP1/RBB1QNKR w HAha - 0 9", {25, 673, 16412, 467660, 12099119, 361714466}}, {"rnbb1nkr/1ppp1ppp/4p3/p5q1/6P1/1PP5/PB1PPP1P/RN1BQNKR w HAha - 1 9", {19, 663, 14149, 489653, 11491355, 399135495}}, {"rnbqnbkr/1pp1p2p/3p1p2/p5p1/5PP1/2P5/PPNPP2P/RNBQ1BKR w HAha - 0 9", {24, 647, 16679, 461931, 12649636, 361157611}}, {"rnb2krb/pppqppnp/8/3p2p1/1P4P1/7P/P1PPPPB1/RNBQNKR1 w GAga - 1 9", {24, 722, 18749, 605229, 16609220, 563558512}}, {"rbnqb1kr/pppn1pp1/3p3p/4p3/1P6/P7/R1PPPPPP/1BNQBNKR w Hha - 1 9", {20, 538, 12277, 345704, 8687621, 255304141}}, {"rnqb1nkr/p1pbp1pp/8/1pPp1p2/P2P4/8/1P2PPPP/RNQBBNKR w HAha - 1 9", {35, 764, 26952, 632796, 22592380, 564255328}}, {"rnq1bbkr/1p1ppp1p/4n3/p1p3p1/P1PP4/8/RP2PPPP/1NQNBBKR w Hha - 0 9", {29, 709, 21296, 570580, 17597398, 506140370}}, {"1nqnbkrb/1pppp2p/r7/p4pp1/3P4/8/PPPBPPPP/RNQNK1RB w g - 0 9", {27, 1028, 28534, 1050834, 30251988, 1096869832}}, {"rbnqnkbr/p1pp1p1p/8/1p2p3/3P2pP/2P5/PP2PPP1/RBNQNKBR w HAha - 0 9", {32, 832, 27120, 750336, 24945574, 724171581}}, {"rnq1nkbr/1p1p1ppp/2p1pb2/p7/7P/2P5/PPNPPPPB/RNQB1K1R w HAha - 2 9", {31, 779, 24010, 638640, 19919434, 551494771}}, {"rnqnk1br/p1ppp1bp/1p3p2/6p1/4N3/P5P1/1PPPPP1P/R1QNKBBR w HAha - 2 9", {25, 717, 19396, 576577, 16525239, 507175842}}, {"rnq1krbb/p1p1pppp/8/1p1p4/1n5B/2N2P2/PPPPP1PP/RNQ1KR1B w FAfa - 0 9", {28, 867, 24029, 735686, 21112751, 654808184}}, {"bbrnnqkr/1pp1pppp/3p4/p7/P3P3/7P/1PPP1PP1/BBRNNQKR w HChc - 0 9", {24, 405, 11025, 210557, 6196438, 131401224}}, {"brnbnqkr/p1ppp3/1p5p/5Pp1/5P2/3N4/PPPPP2P/BRNB1QKR w HBhb g6 0 9", {25, 785, 21402, 698331, 20687969, 695850727}}, {"br1nqbkr/1ppppp2/pn6/6pp/2PP4/1N4P1/PP2PP1P/BR1NQBKR w HBhb - 0 9", {25, 596, 16220, 421882, 12185361, 337805606}}, {"1rnnqkrb/p2ppp1p/1pp5/2N3p1/8/1P6/P1PPPPKP/BR1NQ1RB w gb - 0 9", {38, 960, 34831, 913665, 32490040, 880403591}}, {"rbbnnqkr/pp3pp1/2p1p3/3p3p/3P3P/1PP5/P3PPP1/RBBNNQKR w HAha - 0 9", {30, 785, 23079, 656618, 19885037, 599219582}}, {"rn1bnqkr/p1ppppp1/8/1p5p/P4P1P/3N4/1PPPP1b1/RNBB1QKR w HAha - 0 9", {27, 752, 21735, 613194, 18862234, 547415271}}, {"1nbnqbkr/1p1p1ppp/r3p3/p1p5/P3P3/3Q4/1PPP1PPP/RNBN1BKR w HAh - 2 9", {33, 721, 24278, 572535, 19648535, 496023732}}, {"rnbnqkrb/2pppppp/1p6/p7/1PP5/4N2P/P2PPPP1/RNB1QKRB w GAg - 0 9", {23, 570, 14225, 374196, 10022614, 279545007}}, {"rbnnbq1r/ppppppkp/6p1/N7/4P3/P7/1PPP1PPP/RB1NBQKR w HA - 5 9", {27, 620, 18371, 440594, 13909432, 349478320}}, {"r1nbbqkr/pppppp1p/8/8/1n3Pp1/3N1QP1/PPPPP2P/RN1BB1KR w HAha - 0 9", {31, 791, 25431, 682579, 22408813, 636779732}}, {"rnq1bbkr/pp1p1ppp/2pnp3/8/7P/1QP5/PP1PPPPR/RNN1BBK1 w Aha - 2 9", {28, 559, 16838, 390887, 12242780, 315431511}}, {"rnnqbrkb/2ppppp1/1p1N4/p6p/4P3/8/PPPP1PPP/R1NQBKRB w GA - 0 9", {32, 638, 20591, 438792, 14395828, 331782223}}, {"rbnnq1br/pppp1kp1/4pp2/7p/PP6/2PP4/4PPPP/RBNNQKBR w HA - 0 9", {21, 521, 12201, 320429, 8239159, 227346638}}, {"rnnbqkbr/p2ppp2/7p/1pp3p1/2P2N2/8/PP1PPPPP/RN1BQKBR w HAha - 0 9", {25, 528, 13896, 326094, 9079829, 232750602}}, {"rnn1kbbr/ppppqp2/6p1/2N1p2p/P7/2P5/1P1PPPPP/RN1QKBBR w HAha - 2 9", {27, 801, 22088, 707078, 20334071, 682580976}}, {"rnnqkrbb/p1p1p1pp/1p3p2/8/3p2Q1/P1P1P3/1P1P1PPP/RNN1KRBB w FAfa - 0 9", {37, 1014, 34735, 998999, 32921537, 988770109}}, {"bbrnk1qr/1pppppp1/p4n1p/8/P2P2N1/8/1PP1PPPP/BBR1NKQR w HC - 1 9", {21, 481, 11213, 279993, 7015419, 187564853}}, {"brnbnkqr/1pp1p1p1/p2p1p2/7p/1P4PP/8/PBPPPP2/1RNBNKQR w HBhb - 0 9", {31, 743, 24260, 660177, 22391185, 653721389}}, {"br2kbqr/ppppp1pp/3n1p2/3P4/3n3P/3N4/PPP1PPP1/BR1NKBQR w HBhb - 3 9", {25, 872, 22039, 748726, 20281962, 685749952}}, {"br1nkqrb/ppppppp1/8/7p/4P3/n1P2PP1/PP1P3P/BRNNKQRB w GBgb - 0 9", {28, 607, 16934, 396483, 11607818, 294181806}}, {"rbbn1kqr/pp1pp1p1/2pn3p/5p2/5P2/1P1N4/PNPPP1PP/RBB2KQR w HAha - 1 9", {27, 725, 21543, 616082, 19239812, 581716972}}, {"rnbbnk1r/pp1ppp1p/6q1/2p5/PP4p1/4P3/2PP1PPP/RNBBNKQR w HAha - 1 9", {25, 1072, 26898, 1088978, 28469879, 1122703887}}, {"rnbnkbqr/1pp3pp/3p4/p3pp2/3P2P1/2N1N3/PPP1PP1P/R1B1KBQR w HAha - 0 9", {31, 1028, 32907, 1095472, 36025223, 1211187800}}, {"r1bnkqrb/1ppppppp/p3n3/8/6P1/4N3/PPPPPPRP/RNB1KQ1B w Aga - 1 9", {23, 457, 11416, 250551, 6666787, 159759052}}, {"rbn1bkqr/p1pp1pp1/1pn5/4p2p/7P/1PBP4/P1P1PPP1/RBNN1KQR w HAha - 0 9", {23, 470, 11649, 264274, 6963287, 172833738}}, {"rnnbbkqr/3ppppp/p7/1pp5/P6P/6P1/1PPPPP2/RNNBBKQR w HAha - 0 9", {26, 569, 15733, 375556, 11008114, 284485303}}, {"r1nk1bqr/1pppp1pp/2n5/p4p1b/5P2/1N4B1/PPPPP1PP/RN1K1BQR w HAha - 2 9", {25, 824, 21983, 738366, 20904119, 716170771}}, {"r1nkbqrb/p2pppp1/npp4p/8/4PP2/2N4P/PPPP2P1/R1NKBQRB w GAga - 0 9", {31, 548, 17480, 349633, 11469548, 255067638}}, {"rbnnkqbr/ppppp2p/5p2/6p1/2P1B3/P6P/1P1PPPP1/R1NNKQBR w HAha - 1 9", {31, 809, 24956, 680747, 21247414, 606221516}}, {"1r1bkqbr/pppp1ppp/2nnp3/8/2P5/N4P2/PP1PP1PP/1RNBKQBR w Hh - 0 9", {28, 810, 22844, 694599, 20188622, 636748147}}, {"rn1kqbbr/p1pppp1p/1p4p1/1n6/1P2P3/4Q2P/P1PP1PP1/RNNK1BBR w HAha - 1 9", {39, 848, 30100, 724426, 25594662, 659615710}}, {"rn1kqrbb/pppppppp/8/8/2nP2P1/1P2P3/P1P2P1P/RNNKQRBB w FAfa - 1 9", {29, 766, 21701, 567971, 16944425, 456898648}}, {"b1rnnkrq/bpppppp1/7p/8/1p6/2B5/PNPPPPPP/1BR1NKRQ w GCgc - 2 9", {25, 667, 17253, 472678, 12865247, 365621294}}, {"brnb1krq/pppppppp/8/5P2/2P1n2P/8/PP1PP1P1/BRNBNKRQ w GBgb - 1 9", {23, 620, 14882, 402561, 10776855, 300125003}}, {"b1nnkbrq/pr1pppp1/1p5p/2p5/P2N1P2/8/1PPPP1PP/BR1NKBRQ w GBg - 0 9", {24, 472, 12181, 267398, 7370758, 178605165}}, {"br1nkrqb/p1p1p1pp/3n4/1p1p1p2/5N1P/4P3/PPPP1PP1/BR1NKRQB w FBfb - 0 9", {24, 775, 19398, 624309, 16429837, 539767605}}, {"rbbnnkrq/p2pp1pp/2p5/5p2/1pPP1B2/P7/1P2PPPP/RB1NNKRQ w GAga - 0 9", {34, 921, 30474, 849933, 28095833, 806446436}}, {"rnbbnkr1/1p1ppp1p/2p3p1/p7/2Pq4/1P1P4/P2BPPPP/RN1BNKRQ w GAga - 2 9", {26, 1139, 29847, 1204863, 32825932, 1281760240}}, {"1rbnkbrq/pppppp2/n5pp/2P5/P7/4N3/1P1PPPPP/RNB1KBRQ w GAg - 2 9", {23, 574, 14146, 391413, 10203438, 301874034}}, {"1nbnkr1b/rppppppq/p7/7p/1P5P/3P2P1/P1P1PP2/RNBNKRQB w FAf - 1 9", {33, 823, 26696, 724828, 23266182, 672294132}}, {"rbn1bkrq/ppppp3/4n2p/5pp1/1PN5/2P5/P2PPPPP/RBN1BKRQ w GAga - 0 9", {27, 859, 24090, 796482, 23075785, 789152120}}, {"r1nbbkrq/1ppp2pp/2n2p2/p3p3/5P2/1N4BP/PPPPP1P1/RN1B1KRQ w GAga - 0 9", {25, 774, 20141, 618805, 16718577, 515864053}}, {"rnnkbbrq/1pppp1p1/5p2/7p/p6P/3N1P2/PPPPP1PQ/RN1KBBR1 w GAga - 0 9", {29, 673, 20098, 504715, 15545590, 416359581}}, {"r1nkbrqb/pppp1p2/n3p1p1/7p/2P2P2/1P6/P2PPQPP/RNNKBR1B w FAfa - 0 9", {27, 722, 21397, 593762, 18742426, 537750982}}, {"rbnnkr1q/1ppp2pp/p4p2/P2bp3/4P2P/8/1PPP1PP1/RBNNKRBQ w FAfa - 1 9", {26, 848, 23387, 741674, 21591790, 675163653}}, {"rn1bkrb1/1ppppp1p/pn4p1/8/P2q3P/3P4/NPP1PPP1/RN1BKRBQ w FAfa - 1 9", {22, 803, 18322, 632920, 15847763, 536419559}}, {"rn1krbbq/pppp1npp/4pp2/8/4P2P/3P2P1/PPP2P2/RNNKRBBQ w EAea - 1 9", {29, 810, 23968, 670500, 20361517, 575069358}}, {"rnn1rqbb/ppkp1pp1/2p1p2p/2P5/8/3P1P2/PP2P1PP/RNNKRQBB w EA - 0 9", {22, 506, 11973, 292344, 7287368, 189865944}}, {"bbqr1knr/pppppp1p/8/4n1p1/2P1P3/6P1/PPQP1P1P/BB1RNKNR w HDhd - 0 9", {26, 650, 18253, 481200, 14301029, 394943978}}, {"bq1bnknr/pprppp1p/8/2p3p1/4PPP1/8/PPPP3P/BQRBNKNR w HCh - 0 9", {24, 548, 14021, 347611, 9374021, 250988458}}, {"bqrnkb1r/1p2pppp/p1pp3n/5Q2/2P4P/5N2/PP1PPPP1/B1RNKB1R w HChc - 0 9", {46, 823, 33347, 673905, 26130444, 582880996}}, {"bq1rknrb/pppppp1p/4n3/6p1/4P1P1/3P1P2/PPP4P/BQRNKNRB w GCg - 0 9", {23, 618, 14815, 419474, 10606831, 315124518}}, {"q1brnknr/pp1pp1p1/8/2p2p1p/5b2/P4N2/1PPPP1PP/QBBRK1NR w hd - 0 9", {22, 675, 15778, 473994, 12077228, 368479752}}, {"qrbbnknr/1p1ppp1p/p1p5/8/1P2P1p1/3P1B2/P1P2PPP/QRB1NKNR w HBhb - 0 9", {32, 722, 24049, 569905, 19584539, 484814878}}, {"qrb1kbnr/p3pppp/2n5/1ppp4/7P/3P1P2/PPP1P1PR/QRBNKBN1 w Bhb - 0 9", {26, 831, 22606, 724505, 20500804, 662608969}}, {"qrbnknrb/ppp1pp2/6p1/7p/PPNp4/8/2PPPPPP/QRB1KNRB w GBgb - 0 9", {31, 840, 26762, 742772, 24422614, 701363800}}, {"qbrnbknr/pp1pp1pp/8/2p2p2/3Q4/PP6/2PPPPPP/1BRNBKNR w HChc - 0 9", {38, 1121, 39472, 1198438, 41108769, 1285503872}}, {"qr1bbk1r/pppppp1p/1n6/5np1/4B3/1PP5/P2PPPPP/QRN1BKNR w HBhb - 0 9", {25, 694, 16938, 472950, 12164609, 345122090}}, {"qrnkbbnr/1p1pp2p/p7/2p1Npp1/6P1/7P/PPPPPP2/QR1KBBNR w HBhb - 0 9", {27, 586, 16348, 393391, 11409633, 298054792}}, {"qrnkbnrb/pp1p1p2/2p1p1pp/4N3/P4P2/8/1PPPP1PP/QR1KBNRB w GBgb - 0 9", {32, 645, 20737, 460319, 15037464, 358531599}}, {"qbrnknbr/1pppppp1/p6p/8/1P6/3PP3/PQP2PPP/1BRNKNBR w HChc - 3 9", {26, 595, 16755, 415022, 12214768, 323518628}}, {"qrnbk1br/1ppppp1p/p5p1/8/4Pn2/4K1P1/PPPP1P1P/QRNB1NBR w hb - 0 9", {24, 609, 13776, 359415, 8538539, 230364479}}, {"qrnk1bbr/1pnp1ppp/p1p1p3/8/3Q4/1P1N3P/P1PPPPP1/1RNK1BBR w HBhb - 0 9", {43, 1106, 42898, 1123080, 41695761, 1113836402}}, {"qrnknrb1/pppppp2/8/6pp/4P2P/3P1P2/PbP3P1/QRNKNRBB w FBfb - 0 9", {24, 658, 17965, 488373, 14457245, 400971226}}, {"bbrqnrk1/ppp2ppp/7n/3pp3/8/P4N1N/1PPPPPPP/BBRQ1RK1 w - - 1 9", {22, 503, 12078, 310760, 8080951, 224960353}}, {"brqbnk1r/1ppp1ppp/8/p3pn2/8/2PP1P2/PP2PKPP/BRQBN1NR w hb - 1 9", {25, 745, 19387, 570459, 15520298, 460840861}}, {"brqnkbnr/pp2pp1p/3p4/2p5/5p2/3P3P/PPP1PPP1/B1RNKBNR w Hhb - 0 9", {19, 516, 10755, 312996, 6995034, 214340699}}, {"brq1kn1b/1ppppprp/2n3p1/p7/P1N5/6P1/1PPPPP1P/BRQNK1RB w GBb - 2 9", {29, 557, 16739, 352277, 10840256, 249999654}}, {"rbbq1k1r/ppp1pppp/7n/1n1p4/5P2/P2P4/1PPBP1PP/RB1QNKNR w HAha - 1 9", {25, 769, 20110, 638340, 17438715, 570893953}}, {"r1bbnk1r/qpp1pppp/p6n/3p4/1P6/5N1P/P1PPPPP1/RQBBK1NR w ha - 0 9", {23, 728, 18209, 587364, 16053564, 529082811}}, {"rqbnkbnr/1pp2p1p/3p4/p3p1p1/8/2P2P2/PP1PPNPP/RQBNKB1R w HAha - 0 9", {26, 772, 21903, 653704, 19571559, 593915677}}, {"r1bnknrb/pqppp1p1/1p5p/5p2/7P/3P2N1/PPP1PPP1/RQBNK1RB w GAga - 2 9", {27, 748, 20291, 597105, 16324542, 506453626}}, {"rbqnbknr/pp1pppp1/8/2p5/3P3p/5N1P/PPP1PPPR/RBQNBK2 w Aha - 0 9", {30, 859, 26785, 819631, 26363334, 842796987}}, {"rqnbbrk1/ppppppp1/8/5n1p/3P3P/2B3P1/PPP1PP2/RQNB1KNR w HA - 0 9", {22, 505, 11452, 283464, 7055215, 186760784}}, {"rqnkbbnr/pp2p1p1/8/2pp1p1p/3PPP2/8/PPP1N1PP/RQNKBB1R w HAha - 0 9", {28, 832, 23142, 722857, 20429246, 663183060}}, {"rqnkbnr1/pppp2bp/6p1/4pp2/1P2P3/3NN3/P1PP1PPP/RQ1KB1RB w GAga - 0 9", {28, 641, 18835, 459993, 14038570, 364210162}}, {"rbq2kbr/pppppppp/2n5/P7/3P1n2/2P5/1P2PPPP/RBQNKNBR w HA - 1 9", {31, 889, 27028, 766181, 24299415, 692180754}}, {"rq1bkn1r/ppppp2p/3n4/5pp1/2b3P1/1N1P1P2/PPP1P2P/RQ1BKNBR w HAha - 1 9", {28, 810, 22667, 657520, 18719949, 556282676}}, {"r1nknbbr/p2ppp1p/1pp3p1/8/1P6/4P3/P1PPNPPq/R1QKNBBR w HAha - 0 9", {24, 797, 22144, 719069, 21862776, 716521139}}, {"rqnknrbb/ppp1p3/5ppp/2Np4/2P5/4P3/PP1P1PPP/RQNK1RBB w FAfa - 0 9", {34, 686, 23277, 515541, 17664543, 423574794}}, {"1brnqknr/2p1pppp/p2p4/1P6/6P1/4Nb2/PP1PPP1P/BBR1QKNR w HChc - 1 9", {34, 1019, 32982, 1003103, 33322477, 1043293394}}, {"brn1qknr/1p1pppp1/pb5p/Q1p5/3P3P/8/PPP1PPPR/BRNB1KN1 w Bhb - 2 9", {32, 642, 20952, 464895, 15454749, 371861782}}, {"brnqkbnr/pppppp2/8/6pp/6P1/P2P1P2/1PP1P2P/BRNQKBNR w HBhb - 0 9", {20, 441, 9782, 240220, 5770284, 153051835}}, {"2nqknrb/1rpppppp/5B2/pp6/1PP1b3/3P4/P3PPPP/1RNQKNRB w GBg - 1 9", {35, 1042, 36238, 1101159, 38505058, 1202668717}}, {"rb1nqknr/1pp1pppp/8/3p4/p2P4/6PN/PPPQPP1P/RBBN1K1R w HAha - 0 9", {29, 692, 21237, 555018, 17820605, 497251206}}, {"rnbbqknr/pppp4/5p2/4p1pp/P7/2N2PP1/1PPPP2P/R1BBQKNR w HAha - 0 9", {23, 595, 14651, 415772, 10881112, 329010121}}, {"rn1qkbnr/p1p1pp1p/bp4p1/3p4/1P6/4P3/P1PP1PPP/RNBQKBNR w HAha - 0 9", {30, 794, 24319, 690811, 21657601, 647745807}}, {"r1bqk1rb/pppnpppp/5n2/3p4/2P3PP/2N5/PP1PPP2/R1BQKNRB w GAga - 1 9", {32, 821, 27121, 733155, 24923473, 710765657}}, {"rbnqbknr/1p1ppp1p/6p1/p1p5/7P/3P4/PPP1PPP1/RBNQBKNR w HAha - 0 9", {24, 720, 18842, 575027, 15992882, 501093456}}, {"r1qbbk1r/pp1ppppp/n1p5/5n2/B1P3P1/8/PP1PPP1P/RNQ1BKNR w HAha - 0 9", {27, 831, 22293, 698986, 19948650, 637973209}}, {"rnqkbb1r/p1pppppp/8/8/1p4n1/PP4PP/2PPPP2/RNQKBBNR w HAha - 0 9", {18, 463, 9519, 256152, 6065231, 172734380}}, {"rnqk1nrb/pppbpp2/7p/3p2p1/4B3/2N1N1P1/PPPPPP1P/R1QKB1R1 w GAga - 0 9", {34, 1171, 38128, 1318217, 42109356, 1465473753}}, {"rbnqknbr/1pp1ppp1/3p4/7p/p2P2PP/2P5/PP2PP2/RBNQKNBR w HAha - 0 9", {32, 867, 28342, 798722, 26632459, 781067145}}, {"rn1bknbr/pq2pppp/1p6/2pp4/P7/1P1P4/2PNPPPP/RNQBK1BR w HAha - 0 9", {24, 627, 16652, 462942, 13200921, 385193532}}, {"r1qk1bbr/ppp1pp1p/2np1n2/6p1/2PP4/3BP3/PP3PPP/RNQKN1BR w HAha - 2 9", {31, 992, 30213, 986631, 30397368, 1011631987}}, {"r1qknrbb/pppp1p2/2n3p1/4p2p/8/QPP5/P1NPPPPP/RN1K1RBB w FAfa - 2 9", {30, 702, 21563, 532939, 16813114, 438096194}}, {"bbkr1qnr/2pppppp/2n5/pp6/8/PPN5/1BPPPPPP/1BR1KQNR w HC - 2 9", {25, 573, 15183, 380910, 10554668, 283975400}}, {"1rnbkqnr/1bpppppp/1p6/7P/p2P4/5P2/PPP1P1P1/BRNBKQNR w HBhb - 0 9", {21, 503, 11790, 301084, 7679979, 207799378}}, {"brnkqbnr/2p1pppp/1p6/3p4/1pP5/P6P/3PPPP1/BRNKQBNR w HBhb - 0 9", {28, 743, 21054, 587192, 17354516, 507176753}}, {"br1kqnrb/npp1pppp/8/3p4/p4N2/PP6/2PPPPPP/BR1KQNRB w GBgb - 0 9", {31, 808, 25585, 698475, 22376575, 640362920}}, {"rbbnkq1r/pppppp1p/7n/6p1/P5P1/2P2N2/1P1PPP1P/RBBNKQ1R w HAha - 1 9", {29, 580, 17585, 404831, 12730970, 325226128}}, {"rnbbk1nr/pp2qppp/2ppp3/8/3P4/P1N4N/1PP1PPPP/R1BBKQ1R w HAha - 0 9", {29, 838, 24197, 721884, 21100580, 646624429}}, {"rnbk1b1r/ppppn1pp/4pp2/7q/7P/P5PB/1PPPPP2/RNBKQ1NR w HAha - 3 9", {20, 729, 16633, 576199, 14507076, 498621813}}, {"r2kqnrb/pbppppp1/np5p/8/4Q1P1/3P4/PPP1PP1P/RNBK1NRB w GAga - 2 9", {47, 1219, 55009, 1486353, 65239153, 1834391369}}, {"rbnkbq1r/p1p2ppp/1p2pn2/3p4/P3P3/3P4/1PP1KPPP/RBN1BQNR w ha - 2 9", {29, 923, 27179, 883866, 26202752, 868565895}}, {"rk1bb1nr/ppppqppp/n7/1N2p3/6P1/7N/PPPPPP1P/R1KBBQ1R w HA - 6 9", {27, 703, 19478, 559525, 16049807, 492966455}}, {"rnkqbbnr/p1ppp2p/1p4p1/8/1B3p1P/2NP4/PPP1PPP1/R1KQ1BNR w HAha - 0 9", {29, 610, 18855, 438277, 14020041, 355083962}}, {"rnkqb1rb/pp1p1ppp/4p3/2P3n1/8/1PP5/P3PPPP/RNKQBNRB w GAga - 0 9", {29, 675, 20699, 535821, 17000613, 476598337}}, {"rb1kqnbr/pp1pp1p1/1np2p2/7p/P1P3PP/8/1P1PPP2/RBNKQNBR w HAha - 0 9", {31, 1077, 33661, 1183381, 37415304, 1328374620}}, {"rnkbq1br/ppp2ppp/3p4/Q3p1n1/5P2/3P2P1/PPP1P2P/RNKB1NBR w HAha - 0 9", {41, 1201, 46472, 1420367, 52991625, 1675608008}}, {"rn1qnbbr/pp2pppp/2ppk3/8/2PP4/3Q1N2/PP2PPPP/RNK2BBR w HA - 1 9", {34, 666, 22474, 472299, 15860369, 353831792}}, {"rnkqnr1b/ppppp1pp/5p2/8/Q1P2P2/8/PP1P2PP/RbK1NRBB w FAfa - 0 9", {36, 876, 31987, 788580, 29022529, 736717252}}, {"bbrn1nqr/ppp1k1pp/5p2/3pp3/7P/3PN3/PPP1PPP1/BBRK1NQR w - - 1 9", {24, 583, 15063, 383532, 10522064, 280707118}}, {"brnbkn1r/1pppp1p1/4q3/p4p1p/7P/1N3P2/PPPPP1PQ/BR1BKN1R w HBhb - 2 9", {27, 935, 26120, 885699, 26000648, 873063158}}, {"br1knbqr/pp2p1pp/1n6/2pp1p2/6P1/2P4B/PP1PPPQP/BRNKN2R w HBhb - 0 9", {27, 681, 19202, 510687, 14954779, 415624943}}, {"brnk1qrb/p1ppppp1/1p5p/8/P3n3/1N4P1/1PPPPPRP/BR1KNQ1B w Bgb - 0 9", {22, 638, 13991, 412346, 9760752, 293499724}}, {"rbbnknqr/pppp3p/5pp1/8/1P1pP3/7P/P1P2PP1/RBBNKNQR w HAha - 0 9", {29, 756, 21616, 614074, 17602252, 528140595}}, {"1nbbknqr/rpp1ppp1/1Q1p3p/p7/2P2PP1/8/PP1PP2P/RNBBKN1R w HAh - 2 9", {37, 977, 34977, 944867, 33695089, 940198007}}, {"rnb2bqr/ppkpppp1/3n3p/2p5/6PP/2N2P2/PPPPP3/R1BKNBQR w HA - 2 9", {30, 647, 20365, 467780, 15115531, 369257622}}, {"rn1k1qrb/p1pppppp/bp6/8/4n3/P4BPP/1PPPPP2/RNBKNQR1 w GAga - 2 9", {22, 670, 14998, 451517, 11199653, 339919682}}, {"rb2bnqr/nppkpppp/3p4/p7/1P6/P2N2P1/2PPPP1P/RB1KBNQR w HA - 3 9", {22, 479, 11475, 264739, 6831555, 167329117}}, {"r1kbb1qr/2pppppp/np2n3/p7/2P3P1/8/PP1PPPQP/RNKBBN1R w HAha - 1 9", {32, 723, 23953, 581832, 19472074, 504622114}}, {"rnknbb1r/p1ppp1pp/8/1p1P1p1q/8/P1P5/1P2PPPP/RNKNBBQR w HAha - 1 9", {19, 607, 12733, 417451, 9753617, 325177085}}, {"rnkn1qrb/pp1bp1pp/2p5/1N1p1p2/8/2P5/PPKPPPPP/R2NBQRB w ga - 2 9", {27, 533, 14549, 330747, 9206957, 232664675}}, {"r1nknqbr/pp2p1pp/2p2p2/3p4/6P1/PP1P4/2P1PP1b/RBNKNQBR w HAha - 0 9", {20, 582, 13777, 409166, 10708639, 326565393}}, {"rnkb1qbr/p1pp1p1p/1p2pn2/1Q4p1/4P3/N4P2/PPPP2PP/R1KBN1BR w HAha - 0 9", {40, 1038, 39356, 1051441, 39145902, 1079612614}}, {"rn2qbbr/1pkppp1p/p3n1p1/8/8/2P2P2/PP1PP1PP/RNKN1BBR w HA - 0 9", {24, 605, 14888, 385964, 9687507, 260874068}}, {"rn1nqrbb/p1kppp1p/8/1pp3p1/1P6/2N1P3/P1PP1PPP/RK1NQRBB w - - 0 9", {21, 540, 12489, 337997, 8436136, 237525904}}, {"bbrnknrq/1pp3pp/p2p1p2/4p3/P7/1P2N3/2PPPPPP/BBRN1RKQ w gc - 0 9", {24, 527, 13900, 326175, 9139962, 226253685}}, {"brnb1nrq/pppp1kpp/4p3/8/5p1P/P1P3P1/1P1PPP2/BRNBKNRQ w GB - 1 9", {29, 773, 23904, 638768, 20503775, 560338709}}, {"br1k1brq/ppppp2p/1n1n1pp1/8/P1P5/3P2P1/1P2PP1P/BRNKNBRQ w GBgb - 0 9", {28, 811, 23550, 664880, 19913758, 565143976}}, {"1r1knrqb/n1pppppp/p1b5/1p6/8/3N1P2/PPPPP1PP/BRNK1RQB w fb - 3 9", {29, 753, 23210, 620019, 20044474, 558383603}}, {"rbbnk1rq/pppppppp/8/3Pn3/8/4P1P1/PPP2P1P/RBBNKNRQ w GAga - 1 9", {22, 551, 12619, 324608, 8204171, 217689974}}, {"rnbbk1rq/2pppp1p/p3n1p1/1p6/P3N3/8/1PPPPPPP/RNBB1KRQ w ga - 0 9", {26, 742, 20061, 599527, 16787080, 525678162}}, {"rnbkn1rq/ppppppb1/6p1/7p/2B2P2/1P2P3/P1PP2PP/RNBKN1RQ w GAga - 1 9", {28, 799, 23210, 689436, 20755098, 639632905}}, {"rn1knrqb/p2pppp1/b1p5/1p5p/2P2P2/1P6/P2PP1PP/RNBKNRQB w FAfa - 1 9", {30, 579, 18481, 397545, 13257198, 311282465}}, {"rbnkbnrq/pp2p1Np/2p2p2/8/3p4/8/PPPPPPPP/RBNKBR1Q w Aga - 0 9", {23, 670, 16435, 501883, 13012378, 411860744}}, {"rk1bbnrq/ppp1pppp/n7/3p4/5P2/3P2NP/PPP1P1P1/RNKBB1RQ w GA - 0 9", {26, 597, 16238, 402506, 11269462, 296701249}}, {"r1knbbrq/pppp2p1/2n1p2p/5p2/4P3/P1PP4/1P3PPP/RNKNBBRQ w GAga - 1 9", {20, 596, 13091, 399069, 9416862, 293659781}}, {"rnknbrqb/p1p1pp1p/3p4/1p1N2p1/8/N7/PPPPPPPP/1RK1BRQB w Ffa - 0 9", {26, 724, 18942, 552040, 15257204, 461293885}}, {"rbnknrb1/1p1ppp1p/p1p3p1/8/1P3P2/1R6/PqPPP1PP/RBNKN1BQ w Afa - 0 9", {31, 1183, 34723, 1289502, 38722152, 1421492227}}, {"rnkbnrbq/2p1ppp1/p7/1p1p3p/3P4/1P4P1/P1P1PP1P/RNKBNRBQ w FAfa - 0 9", {24, 506, 12748, 301464, 8086100, 207129256}}, {"r1knrbbq/pp1ppppp/2p1n3/8/2P3P1/P7/1PKPPP1P/RN1NRBBQ w ea - 0 9", {28, 570, 16037, 352471, 10278695, 242592363}}, {"rnknrq1b/ppp1p1p1/4b3/3p1p1p/6P1/P4P2/1PPPPQ1P/RNKNR1BB w EAea - 2 9", {30, 739, 23124, 594962, 19252739, 521629794}}, {"bbqr1krn/pppp1p1p/5n2/4p1p1/3P4/P3QP2/1PP1P1PP/BB1RNKRN w GDgd - 0 9", {31, 799, 25627, 674913, 22172123, 609277274}}, {"bq1b1krn/pp1ppppp/3n4/2r5/3p3N/6N1/PPP1PPPP/BQRB1KR1 w GCg - 2 9", {21, 798, 18571, 688429, 17546069, 647165916}}, {"bqrnkbrn/2pp1pp1/p7/1p2p2p/1P6/4N3/P1PPPPPP/BQR1KBRN w GCgc - 0 9", {27, 783, 22327, 670798, 20059741, 624462073}}, {"bqr1krnb/1np1pppp/8/pp1p4/8/2P2N2/PP1PPPPP/BQRNKR1B w FCfc - 0 9", {28, 636, 18874, 461104, 14237097, 372181570}}, {"qbb1rkrn/1ppppppp/p7/7n/8/P2P4/1PP1PPPP/QBBRNKRN w Gg - 0 9", {25, 547, 13837, 332918, 8849383, 229112926}}, {"1rbbnkrn/p1p1pp1p/2q5/1p1p2p1/8/2P3P1/PP1PPP1P/QRBBNKRN w GBgb - 2 9", {24, 1010, 24370, 983770, 24328258, 961371180}}, {"qrb1kbrn/ppp1p2p/4npp1/3p4/8/1PP4P/PR1PPPP1/Q1BNKBRN w Ggb - 1 9", {18, 451, 9291, 247310, 5568106, 155744022}}, {"qr2krnb/p1p1pppp/b1np4/1p6/3NP3/7P/PPPP1PP1/QRBNKR1B w FBfb - 2 9", {25, 667, 17081, 476030, 12458875, 361495148}}, {"qbrnbkrn/ppp3pp/3p4/5p2/2P1pP2/6PP/PP1PP3/QBRNBKRN w GCgc - 0 9", {24, 650, 16835, 445263, 12187382, 326834539}}, {"qrnb1krn/ppp1p1pp/5p2/2Np4/b2P4/2P5/PP2PPPP/QR1BBKRN w GBgb - 0 9", {27, 641, 17490, 432041, 12103076, 310695797}}, {"qrnkbbrn/pp2pp2/8/2pp2pp/6PP/3P4/PPPKPP2/QRN1BBRN w gb - 0 9", {22, 554, 13116, 357404, 9014737, 258925091}}, {"qrnkbrnb/p1p1ppp1/1p6/3p4/3P3p/5N1P/PPP1PPP1/QRNKBR1B w FBfb - 0 9", {24, 529, 13205, 318722, 8295874, 213856651}}, {"qbr1krbn/1pppp1pp/p7/5pn1/2PP4/8/PPB1PPPP/Q1RNKRBN w FCfc - 0 9", {26, 831, 21651, 696830, 18961456, 621884383}}, {"1rnbkrbn/1qp1pppp/3p4/pp6/4P3/1NP4P/PP1P1PP1/QR1BKRBN w FBfb - 0 9", {24, 597, 15089, 404761, 10832084, 307793179}}, {"q1rkrbbn/ppp1pppp/8/3p4/1PnP4/P7/1RP1PPPP/Q1NKRBBN w Ee - 1 9", {20, 520, 10769, 278067, 6452205, 170268300}}, {"qrnkrn1b/ppppp1pp/4b3/7P/6p1/P7/1PPPPP2/QRNKRNBB w EBeb - 0 9", {26, 566, 15623, 381312, 10940750, 287987207}}, {"bbr1nkrn/ppp1pppp/3q4/3p4/8/P7/1PPPPPPP/BBRQNRKN w gc - 5 9", {19, 661, 13895, 460396, 10870247, 356399665}}, {"brqbnkrn/pp1pp2p/5pp1/2p5/4P3/P2P1N2/1PP2PPP/BRQB1KRN w GBgb - 0 9", {27, 679, 19916, 527306, 16391730, 455940859}}, {"2qnkbrn/p1pppppp/8/1r6/1p2bP2/7N/PPPPP1PP/BR1QKBRN w GBg - 4 9", {18, 774, 15713, 635461, 14371755, 559579332}}, {"r1qnkr1b/p1pppppp/7n/1p6/8/1P3b1N/PRPPPPPP/B1QNK1RB w f - 5 9", {21, 677, 15437, 501520, 12463801, 410795298}}, {"rbbqn1rn/pppp1pp1/3k4/4p2Q/2PPP3/8/PP3PPP/RBB1NKRN w GA - 1 9", {40, 742, 28757, 579833, 21852196, 471452088}}, {"rqbbnkrn/3pppp1/p1p4p/1p6/5P2/P2N4/1PPPP1PP/RQBBK1RN w ga - 0 9", {23, 665, 16400, 492544, 12794736, 396640086}}, {"r2nkbrn/pp2pppp/8/2ppqb2/2P3P1/5P2/PP1PPN1P/RQB1KBRN w GAga - 3 9", {28, 1108, 31164, 1194581, 34780853, 1292405738}}, {"rqbnk1nb/p1pppr1p/5p2/1p4p1/1PP1P3/8/P2P1PPP/RQBNKRNB w FAa - 1 9", {26, 650, 18208, 491403, 14565370, 416833400}}, {"rbqnb1rn/p1pp1kpp/1p2pp2/8/4P2P/P5P1/1PPP1P2/RBQNBKRN w GA - 0 9", {20, 437, 9423, 222154, 5282124, 132309824}}, {"rqnbbkrn/p1p1pppp/3p4/1p5B/8/1P1NP3/P1PP1PPP/RQ2BKRN w GAga - 0 9", {30, 606, 18382, 422491, 12989786, 326601372}}, {"rqnkbbr1/ppppp1pp/5p2/7n/8/2PNP2P/PP1P1PP1/RQ1KBBRN w GAga - 1 9", {23, 482, 12506, 297869, 8430874, 217797292}}, {"r1nkbrnb/2ppppp1/1q6/pp5p/1P6/P3P3/2PPKPPP/RQN1BRNB w fa - 2 9", {25, 827, 21518, 701071, 19290675, 632892337}}, {"rbqnkrbn/p1ppppp1/7p/1p6/7P/2N1P3/PPPP1PPB/RBQ1KR1N w FAfa - 1 9", {30, 627, 18566, 440217, 12976682, 337377291}}, {"r1nbkrbn/p1qp1ppp/8/1pp1p3/2P1P3/6P1/PP1PBP1P/RQN1KRBN w FAfa - 2 9", {22, 616, 14503, 431199, 10850952, 335943324}}, {"rqnkr1bn/ppp1ppb1/3p2pp/8/P7/2P2P2/1PKPP1PP/RQN1RBBN w ea - 1 9", {31, 679, 21365, 493500, 15661072, 379844460}}, {"r2krnbb/qppp1ppp/1n6/p3p3/PP6/4N3/N1PPPPPP/RQ1KR1BB w EAea - 4 9", {24, 645, 17054, 487028, 13837270, 416239106}}, {"bbr1qk1n/1ppppp1p/2n5/p7/P7/1P2P3/2PP1PrP/1BRNQKRN w GCc - 0 9", {18, 520, 10680, 304462, 7215306, 207612575}}, {"brnbq1rn/2ppppkp/p5p1/1p6/8/1BP3P1/PP1PPP1P/BRN1QRKN w - - 0 9", {21, 625, 13989, 419667, 9929336, 300902534}}, {"brn1kbrn/pp2p1pp/3p4/q1p2p2/2P4P/6P1/PP1PPP2/BRNQKBRN w GBgb - 1 9", {18, 477, 10205, 273925, 6720181, 187205941}}, {"brn1krnb/p3pppp/1qpp4/1p6/2P3P1/1P6/P2PPP1P/BRNQKRNB w FBfb - 1 9", {30, 835, 24761, 716151, 21806428, 654487872}}, {"r1b1qkrn/1p1ppppp/p1p1n3/8/4P3/1PN5/P1PPQPPb/RBB2KRN w GAga - 0 9", {28, 825, 24536, 716585, 22079005, 647939781}}, {"r1bbqk1n/p1pppprp/n7/1p4p1/5P2/2N3N1/PPPPP1PP/1RBBQKR1 w Ga - 4 9", {25, 545, 14657, 358854, 10271111, 273864588}}, {"rnbqkbrn/p1pp1pp1/4p3/7p/2p4P/2P5/PP1PPPP1/R1BQKBRN w GAga - 0 9", {17, 445, 9076, 255098, 5918310, 174733195}}, {"rnbqkrnb/1p1pp1p1/2p4p/p4p2/3P2P1/7N/PPPBPP1P/RN1QKR1B w FAfa - 0 9", {34, 746, 25319, 623133, 21285553, 569141201}}, {"rbnqbkr1/1ppppp2/p5n1/6pp/4P3/1N6/PPPP1PPP/RBQ1BRKN w ga - 2 9", {18, 466, 9683, 260864, 6051500, 170135726}}, {"rnqb1krn/ppppp1p1/7p/7b/P1P2pPP/8/1P1PPP2/RNQBBKRN w GAga - 0 9", {24, 575, 15400, 385825, 11039042, 291243811}}, {"rnqkbbr1/p1pp1ppp/4p3/1p6/P3P2n/5P2/1PPP1NPP/RNQKBBR1 w GAga - 2 9", {27, 803, 22883, 694449, 20666099, 638696065}}, {"rn1kbrnb/1qppp1pp/1p6/p4p2/1B1P4/1P5N/P1P1PPPP/RNQK1R1B w FAfa - 0 9", {37, 1209, 43015, 1425600, 49748034, 1671593862}}, {"rbnqkrbn/Bppp1p2/p5pp/4p3/5P2/6PP/PPPPP3/RBNQKR1N w FAfa - 0 9", {29, 720, 20434, 534148, 15384362, 421343249}}, {"rnqbkr1n/1p1ppbpp/3p1p2/p7/8/1P6/P1PPPPPP/R1QBKRBN w FAfa - 0 9", {20, 657, 14424, 492678, 11843134, 413965054}}, {"rnqkrb1n/ppppp3/6p1/5p1p/2b2P2/P1N5/1PPPP1PP/RQ1KRBBN w EAea - 1 9", {28, 749, 20684, 543151, 15379233, 417191461}}, {"rnqk1nbb/1pp2ppp/3pr3/p3p3/3P1P2/2N3N1/PPP1P1PP/R1QKR1BB w EAa - 1 9", {29, 883, 26412, 815098, 25144295, 789705382}}, {"bbr1kqrn/p1p1ppp1/1p2n2p/3p4/1P1P4/2N5/P1P1PPPP/BBR1KQRN w GCgc - 0 9", {22, 485, 11475, 271271, 6825123, 171793012}}, {"brnbkq1n/ppp1ppr1/7p/3p2p1/2P3PP/8/PPBPPP2/BRN1KQRN w GBb - 2 9", {30, 634, 19017, 442537, 13674310, 345386924}}, {"brnkqbr1/1pppp1pp/5p2/p7/P1P1P2n/8/1P1P1PP1/BRNKQBRN w GBgb - 0 9", {21, 504, 11672, 305184, 7778289, 217596497}}, {"b1rkqrnb/p1ppp1pp/1p1n4/5p2/5P2/PN5P/1PPPP1P1/BR1KQRNB w FBf - 0 9", {23, 688, 17259, 531592, 14228372, 451842354}}, {"1bbnkqrn/rppppp2/p5p1/7p/7P/P1P1P3/1P1P1PP1/RBBNKQRN w GAg - 1 9", {25, 450, 12391, 263946, 7752404, 185393913}}, {"rnbbkqr1/1pppppp1/7p/p3n3/PP5P/8/1BPPPPP1/RN1BKQRN w GAga - 0 9", {23, 543, 12224, 305812, 7549008, 199883770}}, {"r1bkqbrn/ppppp1pp/8/5p2/3nPP2/1P4N1/P1PP2PP/RNBKQBR1 w GAga - 1 9", {27, 751, 21158, 600417, 17989920, 527273615}}, {"rnbkqr1b/1p1pp1pp/p4p1n/2p5/1P5P/N4P2/P1PPP1P1/R1BKQRNB w FAfa - 0 9", {21, 498, 11738, 302278, 7808375, 216224115}}, {"rbnkbqrn/p1p3pp/1p1p4/B3pp2/3P2P1/6N1/PPP1PP1P/RBNK1QR1 w GAga - 0 9", {34, 977, 33464, 961128, 33318567, 978991050}}, {"r1kbbqrn/ppp3pp/2np1p2/1P2p3/3P1P2/8/P1P1P1PP/RNKBBQRN w GAga - 0 9", {32, 920, 28916, 844881, 26763259, 797524786}}, {"rk1qbbrn/p2npppp/1p6/2p4Q/8/4P3/PPPP1PPP/RNK1B1RN w GA - 2 9", {35, 657, 22359, 495406, 16662477, 419496845}}, {"rnk1brnb/pp1p1pp1/8/q1p1p2p/5P2/NP6/P1PPP1PP/R1KQBRNB w FAfa - 1 9", {26, 774, 20215, 610661, 16987110, 523437649}}, {"rb1kqrbn/npp1ppp1/p7/3P3p/2PP4/8/PP3PPP/RBNKQRBN w FAfa - 0 9", {35, 775, 27395, 661118, 23983464, 625669222}}, {"rnkb1rbn/pp1p2pp/8/2p1pp1q/P6P/1PN5/2PPPPP1/R1KBQRBN w FAfa - 1 9", {22, 899, 21188, 850597, 21518343, 857951339}}, {"rnkqrbbn/1pppp1p1/8/p2N1p1p/2P4P/8/PP1PPPP1/R1KQRBBN w EAea - 0 9", {29, 585, 17571, 393221, 12238776, 299752383}}, {"rnk1r1bb/pp1ppppp/1q4n1/2p5/5P1P/3PP3/PPP3P1/RNKQRNBB w EAea - 1 9", {27, 884, 24613, 811915, 23698701, 790239502}}, {"bbrnkrqn/1ppp1p2/6pp/p3p3/5PP1/2PB4/PP1PP2P/B1RNKRQN w FCfc - 0 9", {37, 693, 25425, 550527, 20138432, 481498664}}, {"b1rbkrqn/ppp2ppp/1n2p3/3p4/6P1/2PP4/PP2PP1P/BRNBKRQN w FBf - 1 9", {21, 463, 10610, 253204, 6307276, 159025909}}, {"brnkrb1n/1pp1p1pp/3p4/p1Nq1p2/2P5/8/PP1PPPPP/BRK1RBQN w eb - 2 9", {27, 725, 17842, 496072, 12604078, 362747791}}, {"brn1r1nb/ppppkppp/4p3/8/2PP1P2/8/PP1KP1PP/BRN1RQNB w - - 1 9", {25, 623, 16874, 426659, 12290985, 317097424}}, {"rbb1krqn/1pp1pp1p/p3n1p1/3pP3/8/1PN5/P1PP1PPP/RBB1KRQN w FAfa d6 0 9", {23, 529, 12641, 310277, 7861413, 202594556}}, {"r1bbkrqn/p1pppppp/8/4n3/1p5P/P2P2P1/1PP1PP2/RNBBKRQN w FAfa - 0 9", {23, 571, 13133, 346793, 8699448, 243460643}}, {"rnbkrbqn/p1pp1ppp/4p3/1p6/8/BPN3P1/P1PPPP1P/R2KRBQN w EAea - 2 9", {29, 692, 20014, 500375, 14904192, 386694739}}, {"rnbkrqn1/pppppp2/8/1Q2b1pp/P3P3/5P2/1PPP2PP/RNBKR1NB w EAea - 0 9", {37, 1001, 36440, 987842, 35626426, 993747544}}, {"rbnkbrqn/p1pppp2/7p/1p4pP/3P1P2/8/PPP1P1P1/RBNKBRQN w FAfa - 0 9", {30, 564, 17143, 381364, 11859538, 293703269}}, {"1nkbbrqn/3ppppp/r1p5/pp6/8/4PP2/PPPPN1PP/RNKBBRQ1 w FAf - 2 9", {26, 546, 14641, 344592, 9556962, 245137199}}, {"rnkrbbq1/pppppnp1/7p/8/1B1Q1p2/3P1P2/PPP1P1PP/RNKR1B1N w DAda - 2 9", {43, 887, 36240, 846858, 33185346, 851927292}}, {"1rkrbqnb/pppppp2/2n3p1/7p/3P3P/P4N2/1PP1PPP1/RNKRBQ1B w DAd - 0 9", {26, 622, 16049, 403921, 10786140, 285233838}}, {"rbnkr1bn/pp1pqp1p/2p1p3/6p1/3P4/7P/PPP1PPP1/RBNKRQBN w EAea - 0 9", {19, 566, 12257, 381197, 9107175, 293397389}}, {"r1kbrqb1/pppp2pp/2n1p1n1/5p1B/4PP2/P7/1PPP2PP/RNK1RQBN w EAea - 2 9", {39, 1359, 53626, 1876028, 73871486, 2633945690}}, {"rnkrqbbn/p1p3pp/1p1ppp2/8/1P6/3P2P1/PKP1PP1P/RN1RQBBN w da - 0 9", {26, 776, 20735, 611907, 16884013, 503561996}}, {"rnkrqnbb/ppp2p1p/3p4/4p1p1/3P3P/N1Q5/PPP1PPP1/R1KR1NBB w DAda - 0 9", {40, 1175, 45637, 1375884, 52620163, 1633655838}}, {"bbrnkrn1/p1pppp2/1p6/6pp/3q4/1P3QP1/P1PPPP1P/BBRNKRN1 w FCfc - 0 9", {34, 1398, 45749, 1712950, 57268492, 2059942014}}, {"br1bkrnq/1p2pppp/pnp5/3p4/P1P5/5P2/1P1PPKPP/BRNB1RNQ w fb - 2 9", {24, 501, 12237, 284936, 7049659, 177940764}}, {"brnkrbn1/pppppp1q/B6p/6p1/8/1P2PP2/P1PP2PP/BRNKR1NQ w EBeb - 0 9", {34, 815, 25868, 700970, 22006883, 639803952}}, {"br1krnqb/pppppp1p/1n4p1/8/8/P2NN3/2PPPPPP/BR1K1RQB w Beb - 2 9", {37, 1029, 36748, 1025712, 36214583, 1026195877}}, {"rbbnkr1q/p1p2ppp/1p1ppn2/8/1PP4P/8/P2PPPP1/RBBNKRNQ w FAfa - 0 9", {28, 755, 22623, 605106, 18972778, 513486101}}, {"r1b1krnq/pp2pppp/1bn5/2pp4/4N3/5P2/PPPPPRPP/R1BBK1NQ w Afa - 0 9", {24, 705, 17427, 532521, 13532966, 426443376}}, {"1nbkrbn1/rpppppqp/p7/6p1/4P3/3P2P1/PPP1KP1P/RNB1RBNQ w e - 1 9", {31, 800, 24748, 693366, 21193292, 625757852}}, {"r1bkrnqb/pp3ppp/n1ppp3/8/1P5P/P7/R1PPPPP1/1NBKRNQB w Eea - 0 9", {21, 482, 11417, 275339, 7112890, 180378139}}, {"rbnkbrnq/ppp1p2p/5p2/3p2p1/1B1P4/1N4P1/PPP1PP1P/RB1K1RNQ w FAfa - 0 9", {33, 780, 25532, 628945, 20756770, 535497008}}, {"rnk1brnq/pp1ppppp/2p5/b7/8/1P2P2P/P1PP1PPQ/RNKBBRN1 w FAfa - 3 9", {29, 648, 19043, 449637, 13722785, 341389148}}, {"rnkrbbnq/p1p3pp/5p2/1p1pp3/P7/1PN2P2/2PPP1PP/R1KRBBNQ w DAda - 0 9", {26, 827, 21865, 683167, 18916370, 589161126}}, {"r1krbnqb/p1pp1ppp/2n1p3/8/1p4P1/PPP5/3PPP1P/RNKRBNQB w DAda - 1 9", {25, 540, 14709, 331332, 9491817, 225389422}}, {"rbnkrnbq/ppp1pp2/3p2p1/2N5/P6p/2P5/1P1PPPPP/RB1KRNBQ w EAea - 0 9", {32, 790, 25107, 661207, 20906017, 578332225}}, {"rnkbrn1q/1ppppppb/8/p4N1p/8/P1N5/1PPPPPPP/R1KBR1BQ w EAea - 0 9", {31, 691, 20813, 510665, 15308408, 404129987}}, {"rnkrnbbq/p1p2ppp/3pp3/1p6/6P1/4PQ1B/PPPP1P1P/RNKRN1B1 w DAda - 0 9", {29, 558, 16800, 352887, 10825379, 246965507}}, {"rnkrnqbb/pp2p1p1/3p3p/2p2p2/5P2/1P1N4/P1PPPQPP/RNKR2BB w DAda - 0 9", {29, 762, 23210, 644936, 20522675, 596067005}}, {"bb1rknnr/ppqppppp/8/2p5/3P1N2/1P6/P1P1PPPP/BBQRKN1R w HDhd - 1 9", {33, 963, 32279, 1000890, 34552118, 1124738493}}, {"bqrbknnr/ppp1p2p/8/3p1p2/5p2/P3N2P/1PPPP1P1/BQRBK1NR w HChc - 0 9", {20, 398, 9009, 194859, 4834319, 113660536}}, {"b1rk1bnr/qpp1pppp/p4n2/3p4/3PPP2/7N/PPP3PP/BQRKNB1R w HChc - 1 9", {25, 648, 16587, 455720, 12200870, 351766307}}, {"bqkrnnrb/pppp2p1/4pp2/4P2p/6P1/7P/PPPP1P2/BQRKNNRB w GC - 1 9", {30, 493, 15118, 280726, 8786998, 181492621}}, {"q1brknnr/1p1ppppp/p7/2p5/8/1PPP4/P2RPPPP/QBB1KNNR w Hhd - 0 9", {25, 501, 13206, 290463, 7982978, 192717198}}, {"qrb1k1nr/ppppb1pp/6n1/4ppN1/3P4/4N3/PPP1PPPP/QRBBK2R w HBhb - 2 9", {31, 872, 26191, 739276, 22493014, 646855304}}, {"1rbknbnr/1ppp1pp1/q6p/p3p3/5P2/2PPB3/PP2P1PP/QR1KNBNR w HBhb - 0 9", {28, 1020, 28147, 984000, 27484692, 947786800}}, {"qrbk2rb/1ppp1ppp/5nn1/p3p3/1N6/P7/1PPPPPPP/QRB1KNRB w gb - 0 9", {23, 592, 14398, 395716, 10098215, 293988585}}, {"qbrk1nnr/1pp1pppp/2b5/p2p4/P2P2P1/8/1PP1PP1P/QBKRBNNR w hc - 1 9", {26, 654, 18103, 471653, 13740891, 373081138}}, {"qrkbbnnr/ppp2p1p/4p3/3p2p1/P7/2PP4/1P2PPPP/QRKBBNNR w HBhb - 0 9", {25, 626, 16616, 431634, 12079406, 324006164}}, {"qr1kbbnr/ppp1pp1p/4n1p1/2Pp4/6P1/4N3/PP1PPP1P/QRK1BBNR w HB d6 0 9", {26, 699, 18068, 497152, 13353359, 375702908}}, {"qrk1b1rb/p1pppppp/3nnQ2/1p6/1P3P2/3P4/P1P1P1PP/1RKNBNRB w GBgb - 3 9", {43, 1369, 55463, 1831200, 71514365, 2427477375}}, {"qbrk1nbr/pppp3p/5n2/4ppp1/3P1P2/4N3/PPP1P1PP/QBKRN1BR w hc - 0 9", {25, 752, 20165, 615263, 17493373, 543180234}}, {"qrkb1nbr/1pppppQp/3n4/p7/5p2/1P1N4/P1PPP1PP/1RKB1NBR w HBhb - 0 9", {45, 946, 40100, 966903, 39736157, 1051910977}}, {"qrk1nbbr/ppp1p1p1/4n2p/3p1p2/1P5P/3P2P1/P1P1PP2/QRKNNBBR w HBhb - 1 9", {32, 770, 25367, 646977, 21717615, 577979364}}, {"qrkn1rbb/pp2pppp/2p5/3p4/P2Qn1P1/1P6/2PPPP1P/1RKNNRBB w FBfb - 0 9", {38, 943, 35335, 868165, 31909835, 798405123}}, {"bbrqknnr/ppp4p/3pp3/5pp1/4PP2/5Q2/PPPP2PP/BBR1KNNR w HChc - 0 9", {36, 843, 29974, 758528, 26828059, 723306114}}, {"1rqbkn1r/p1p1pppp/1p5n/P2p4/3Pb1P1/8/1PP1PP1P/BRQBKNNR w HBhb - 0 9", {23, 778, 19482, 649789, 17337683, 579112676}}, {"br1knbnr/1qp1pppp/pp1p4/8/8/PP6/2PPPPPP/BRQKNBNR w HBhb - 2 9", {26, 697, 18835, 546622, 15280079, 473071890}}, {"brqk2rb/ppppp1pp/4np2/8/2n5/3P1Q2/PP2PPPP/BR1KNNRB w GBgb - 0 9", {32, 948, 30434, 885713, 29821322, 874251866}}, {"r1bqknnr/pp1pp1p1/5p1p/2p1b2N/2P5/8/PPQPPPPP/RBB1K1NR w HAha - 0 9", {31, 785, 25549, 659952, 22244193, 592797491}}, {"rqbbknnr/ppppp2p/5pp1/8/8/1P3PP1/PQPPP2P/R1BBKNNR w HAha - 0 9", {23, 391, 10163, 198450, 5576671, 121267576}}, {"rqbknbnr/1pp1p2p/p7/3p1pp1/7N/1PP5/P2PPPPP/RQBK1BNR w HAha - 0 9", {27, 676, 19606, 522428, 15955388, 448477218}}, {"rqb1nnrb/2ppkppp/1p2p3/p7/2PPP3/1P6/P4PPP/RQBKNNRB w GA - 1 9", {31, 727, 22895, 570647, 18361051, 483248153}}, {"rb1kbn1r/p1ppppp1/qp5n/7p/P7/RPP5/3PPPPP/1BQKBNNR w Hha - 2 9", {29, 837, 23815, 730083, 21279560, 682863811}}, {"rqkbb1nr/p1p2ppp/1p1p2n1/3Np3/4P3/5N2/PPPP1PPP/RQKBB2R w HAha - 0 9", {28, 717, 20663, 550987, 16347343, 453153783}}, {"rqknbbr1/p1pppp1p/1p3np1/8/4P3/2P2P1P/PP1P2P1/RQKNBBNR w HAa - 0 9", {27, 650, 18231, 475303, 13847463, 383256006}}, {"r1k1bnrb/1qpppppp/1p2n3/p7/1P5P/6P1/P1PPPP2/RQKNBNR1 w GAga - 1 9", {24, 806, 20693, 713220, 19382263, 686009788}}, {"rb1knnbr/1pp1ppp1/p2p3p/5q2/3B2P1/3P1P2/PPP1P2P/RBQKNN1R w HAha - 0 9", {34, 1360, 44096, 1605706, 51973672, 1837704407}}, {"rqkb1nbr/p1p1ppp1/1p3n1p/2Qp4/8/2P5/PP1PPPPP/R1KBNNBR w HAha - 2 9", {39, 983, 38218, 940989, 36347815, 918801645}}, {"rqknnbbr/2pppp2/pp5p/6p1/1P1P4/4PP2/P1P3PP/RQKNNBBR w HAha - 0 9", {26, 628, 17638, 464924, 13787303, 386125234}}, {"rqkn1rbb/1pp1pppp/p7/3p4/3Pn3/2P1PP2/PP4PP/RQKNNRBB w FAfa - 1 9", {20, 527, 12216, 321533, 8082183, 219311659}}, {"bbrkqn1r/1pppppp1/5n2/p7/1PP2P1p/7N/P2PP1PP/BBRKQN1R w HChc - 1 9", {36, 963, 35291, 973839, 35907489, 1034223364}}, {"brkbqn1r/p2ppppp/7n/1p6/P1p3PP/8/1PPPPP1N/BRKBQ1NR w HBhb - 0 9", {18, 583, 11790, 394603, 8858385, 304339862}}, {"brkq1bnr/pp1ppp1p/8/2p2np1/P7/8/1PPPPPPP/BRKQNBNR w HBhb - 0 9", {19, 552, 11811, 354260, 8432183, 262293169}}, {"brkqnnrb/1ppppppp/8/8/p3P3/5N2/PPPP1PPP/BRKQ1NRB w GBgb - 3 9", {21, 397, 9653, 204350, 5489836, 128389738}}, {"rbbkq1nr/1p2pppp/p1p3nB/3p4/1Q1P4/6N1/PPP1PPPP/RB1K2NR w HAha - 0 9", {40, 1132, 43404, 1260470, 47425783, 1415578783}}, {"rkbbq1nr/1pppp1p1/4np2/p6p/8/PP3P2/1KPPP1PP/R1BBQNNR w ha - 0 9", {24, 596, 15220, 402121, 10822049, 302056813}}, {"r1bqn1nr/pkpppp1p/1p4pb/8/PN6/R7/1PPPPPPP/1KBQ1BNR w H - 2 9", {33, 794, 25450, 649150, 20919309, 561073410}}, {"rkb1nnrb/1pppq1pp/p4p2/4p3/5P2/1P1PB3/P1P1P1PP/RK1QNNRB w GAga - 0 9", {26, 625, 17050, 442036, 12515042, 342967558}}, {"rbkqbn1r/pppp1p1p/2n1p1p1/8/8/1P1PP1N1/P1P2PPP/RBKQB1NR w HAha - 1 9", {30, 660, 20308, 492714, 15348335, 403323883}}, {"rkqbb1n1/pppppppr/8/6np/5P2/8/PPPPP1PP/RKQBBNNR w HAa - 6 9", {23, 500, 12154, 292936, 7519117, 196524441}}, {"rkqnbbnr/ppppppp1/8/7p/3N4/6PP/PPPPPP2/RKQNBB1R w HAa - 0 9", {24, 484, 12495, 284570, 7775173, 193947530}}, {"rkqnb1rb/p1p1pppp/1p1p4/2n5/3P4/2P1N1N1/PP2PPPP/RKQ1B1RB w GAga - 0 9", {28, 1020, 29124, 1027904, 30515456, 1073711823}}, {"rbk1nnbr/1ppq1ppp/p2p4/4p3/P3B2P/2P5/1P1PPPP1/R1KQNNBR w HAha - 2 9", {38, 998, 37265, 1047592, 38552638, 1139322479}}, {"r1qbn1br/k1pppppp/6n1/pp6/5P1P/P7/1PPPP1PB/RKQBNN1R w HA - 1 9", {22, 549, 12867, 348574, 8725809, 251613569}}, {"rkqnn1br/pppp3p/4p1pb/5p2/P2P4/7P/1PP1PPPB/RKQNNB1R w HAha - 1 9", {32, 659, 21249, 469701, 15434721, 365761521}}, {"rk1nnrbb/p1p1pppp/1p6/3p1q2/P3P3/2NN4/1PPP1PPP/RKQ2RBB w FAfa - 3 9", {29, 989, 29087, 980477, 29643404, 998848556}}, {"bbrk1q1r/ppppppp1/3n4/7p/3Pn3/6PN/PPP1PPNP/BBRK1Q1R w HChc - 2 9", {23, 712, 16551, 516177, 12995202, 411077508}}, {"brkbnq1r/p1ppp2p/5ppn/1p6/5P2/1P1P2P1/P1P1P2P/BRKBNQNR w HBhb - 0 9", {28, 856, 24984, 780503, 23529352, 754501112}}, {"br1k1bnr/ppppp1pp/4np2/1B2P2q/3P4/8/PPP2PPP/BRKNQ1NR w HB - 3 9", {36, 1214, 40615, 1328331, 45096834, 1470987023}}, {"brk1qnrb/pnppp1p1/1p6/5p1p/8/5PPP/PPPPP1R1/BRKNQN1B w Bgb - 0 9", {22, 551, 13111, 353317, 9040545, 259643605}}, {"rbbkn1nr/1ppp2pp/p3p3/2q2p2/3P4/6P1/PPPBPP1P/RB1KNQNR w HAha - 0 9", {31, 1060, 31332, 1015099, 30314172, 976268967}}, {"rkbbn1nr/ppppp1pp/8/6N1/5p2/1q6/P1PPPPPP/RKBBN1QR w HAha - 0 9", {3, 72, 1919, 50827, 1400832, 39654253}}, {"rkb2bnr/pp2pppp/2p1n3/3p4/q2P4/5NP1/PPP1PP1P/RKBNQBR1 w Aha - 0 9", {29, 861, 24504, 763454, 22763215, 731511256}}, {"rkbq1nrb/ppppppp1/7p/8/1P1n4/P4P1P/2PPP1P1/RKBNQNRB w GAga - 0 9", {25, 672, 17631, 473864, 12954224, 361237536}}, {"rbknb1nr/ppp1qp1p/6p1/3pp3/3P3P/2B1P3/PPP2PP1/RBKN1QNR w HAha - 1 9", {27, 857, 24688, 792538, 23790033, 768247869}}, {"rknbbq1r/p1pppppp/1p2N3/8/3n4/2P5/PP1PPPPP/RK1BBQNR w HAha - 4 9", {29, 763, 22138, 574054, 16926075, 447896703}}, {"r1nqbbnr/1pppp1pp/1k6/p4p2/8/4P3/PPPP1PPP/RKN1BBNR w HA - 0 9", {26, 658, 17302, 464039, 12380488, 349047256}}, {"rkn2qrb/ppp1pppp/6n1/1b1p4/1P6/4PPB1/P1PP2PP/RKNQ1NRB w GAga - 3 9", {23, 574, 14070, 370324, 9501401, 263870337}}, {"rbkn2br/ppppp1p1/4np1p/1P5q/8/2P1N3/P2PPPPP/RBK1QNBR w HAha - 1 9", {29, 992, 29506, 999564, 30148787, 1045942540}}, {"1knbqnbr/1ppppp1p/r5p1/p7/7P/2PN2P1/PP1PPP2/RK1BQNBR w HAh - 2 9", {26, 698, 19395, 512023, 14848229, 402599313}}, {"rk1qnbbr/pnpppp1p/6p1/1p6/3P4/1P6/P1P1PPPP/RKNQNBBR w HAha - 1 9", {20, 480, 11159, 287539, 7425917, 203194521}}, {"rknqnrbb/pp1p2p1/5p1p/2p1p3/2P1P3/P2P4/1P3PPP/RKNQNRBB w FAfa - 0 9", {26, 679, 18116, 494953, 13790137, 392629571}}, {"bbrk2qr/pp1p1ppp/3n2n1/2p1p3/3P1P2/6N1/PPP1P1PP/BBRKN1QR w HChc - 0 9", {26, 790, 21521, 673269, 19259490, 617563700}}, {"b1krnnqr/1p1ppppp/p1p5/b6B/P7/4P1N1/1PPP1PPP/BRK1N1QR w HB - 2 9", {26, 625, 16451, 415452, 11490615, 304805107}}, {"1rknnbqr/3ppppp/p7/1pp5/4b2P/P4P2/1PPPP1PR/BRKNNBQ1 w Bhb - 1 9", {24, 757, 19746, 618777, 17275100, 544309489}}, {"br1nn1rb/pppkpqpp/3p1p2/8/PP6/4N3/1KPPPPPP/BR2NQRB w - - 3 9", {24, 682, 17129, 482711, 13057308, 375033550}}, {"rbbkn1qr/pppp2p1/6np/4pp2/7N/7P/PPPPPPPR/RBBK1NQ1 w Aha - 0 9", {22, 586, 14158, 409891, 10607781, 324452612}}, {"rk1bn1qr/pppbpppp/4n3/4p3/4P3/5P2/PPPP2PP/RKBB1NQR w HAha - 1 9", {22, 530, 13440, 348004, 9514787, 259898748}}, {"rkbnnbqr/1ppp1ppp/p7/4p3/8/QP3P2/P1PPP1PP/RKBNNB1R w HAha - 0 9", {29, 705, 21511, 551042, 17524731, 472356665}}, {"1kbnnqrb/1pp1p1pp/r4p2/p2p4/N4P2/3P4/PPP1P1PP/RKB1NQRB w GAg - 2 9", {21, 623, 14979, 437554, 11601134, 343214006}}, {"rbknbn1r/pppp1p1p/4p1q1/8/P1P3Pp/8/1P1PPP2/RBKNBNQR w HAha - 0 9", {30, 813, 24959, 708454, 23379040, 692576573}}, {"rk1bb1qr/2pppppp/p2nn3/1p4P1/6QP/8/PPPPPP2/RKNBBN1R w HAha - 2 9", {36, 857, 30124, 757524, 26485812, 696999449}}, {"rkn1bbqr/p2ppppp/2p1n3/1p6/4PP2/6PP/PPPP4/RKNNBBQR w HAha - 0 9", {33, 687, 22744, 511018, 17101732, 412778368}}, {"rkn1bqrb/pnp1pppp/3p4/8/Pp6/1N2NP2/1PPPP1PP/RK2BQRB w GAga - 0 9", {28, 591, 17174, 406025, 12182448, 312575205}}, {"rbk1n1br/ppp1ppqp/2n5/2Np2p1/8/2P5/PPBPPPPP/R1KN1QBR w HAha - 4 9", {35, 930, 30663, 844433, 27160490, 780616047}}, {"rknbn1br/1ppp1ppp/p3p3/8/1q6/2P2N1P/P2PPPP1/RKNB1QBR w HAha - 0 9", {4, 157, 3697, 138102, 3454704, 125373395}}, {"rkn1qbbr/pp3ppp/4n3/2ppp3/4P1P1/P2P4/1PP2P1P/RKNNQBBR w HAha - 0 9", {28, 840, 24437, 771328, 23200961, 756489357}}, {"rkn1qrbb/pp1ppp2/2p1n1p1/7p/2P2P1P/6P1/PP1PP3/RKNNQRBB w FAfa - 1 9", {32, 867, 27595, 757836, 24485663, 688115847}}, {"b1rknnrq/bpppp1p1/p6p/5p1P/6P1/4N3/PPPPPP2/BBRKN1RQ w GCgc - 1 9", {33, 851, 28888, 763967, 26686205, 731944177}}, {"brkb1nr1/pppppp2/3n2pp/3B4/1P6/4P3/PqPP1PPP/BRK1NNRQ w GBgb - 2 9", {4, 98, 2965, 76143, 2352530, 64251468}}, {"brk1nbrq/1ppppn1p/6p1/p4p2/P5P1/5R2/1PPPPP1P/BRKNNB1Q w Bgb - 0 9", {29, 922, 27709, 879527, 27463717, 888881062}}, {"brkn1rqb/1p1ppppp/3n4/p1p5/1P3P2/8/PNPPP1PP/BR1KNRQB w fb - 1 9", {29, 633, 19399, 469818, 15076198, 396737074}}, {"rb1k1nrq/pbp1pppp/1p1p1n2/8/5P2/4NN1P/PPPPP1P1/RBBK2RQ w GAga - 2 9", {28, 841, 24056, 710751, 20772996, 613798447}}, {"rkbbnnrq/p1pp3p/4p1p1/1p3p2/P6P/1P6/1BPPPPP1/RK1BNNRQ w GAga - 0 9", {33, 957, 30668, 907217, 29735654, 903933626}}, {"rk2nbrq/p1ppppp1/bpn5/7p/6P1/2N2P2/PPPPP1QP/RKB1NBR1 w GAga - 2 9", {24, 687, 18206, 544627, 15518417, 484217179}}, {"rkbn1r1b/pp1pppnp/6q1/2p3p1/5P1P/4N3/PPPPP1P1/RKB1NRQB w FAfa - 1 9", {23, 831, 21254, 754622, 21126103, 744755212}}, {"rbknb1rq/ppp1p1p1/3pnp1p/8/6PP/2PP4/PP2PP2/RBKNBNRQ w GAga - 0 9", {31, 838, 26800, 736910, 24008129, 677776408}}, {"rknbb1rq/p1pn1ppp/4p3/1p1p4/2P5/1P2N1P1/P2PPP1P/RKNBB1RQ w GAga - 1 9", {29, 830, 24798, 721630, 22243832, 660040360}}, {"rk1nbbrq/pp1p1ppp/3n4/P3p3/2p4P/8/1PPPPPP1/RKNNBBRQ w GAga - 1 9", {24, 484, 12776, 297419, 8379748, 214004367}}, {"rknnbr1b/ppp2pqp/3p4/4p1p1/7P/3P1P2/PPP1P1P1/RKNNBRQB w FAfa - 0 9", {32, 838, 26408, 740701, 23472124, 699211365}}, {"rb1k1rbq/ppppN1pp/2nn4/5p2/7P/8/PPPPPPP1/RBK1NRBQ w FA - 1 9", {27, 800, 22785, 701742, 20804424, 660917073}}, {"r1nbnrbq/kppppp1p/6p1/8/p1PP1P2/4P3/PP4PP/RKNBNRBQ w FA - 1 9", {28, 757, 21198, 602699, 17180857, 507618340}}, {"rkn1rbbq/p1pppppp/2n5/1pP5/8/1N2P3/PP1P1PPP/RK1NRBBQ w EAea - 1 9", {22, 483, 11890, 283679, 7497674, 191130942}}, {"rknnrqbb/2pppppp/8/p7/Np3P2/3P4/PPP1P1PP/RKN1RQBB w EAea - 0 9", {25, 536, 14456, 339180, 9694947, 245669668}}, {"bb1rknrn/1qppppp1/1p4B1/p6N/8/2P5/PP1PPPPP/B1QRK1RN w GDgd - 1 9", {32, 715, 22421, 575008, 17860156, 502410909}}, {"b1rbknrn/qpp1ppp1/p6p/3p4/2P5/1P1P1P2/P3P1PP/BQRBKNRN w GCgc - 0 9", {30, 818, 24421, 688711, 20981488, 611986786}}, {"bqkrnbrn/1pp1pp1p/p7/1B1p2p1/4P3/7P/PPPP1PP1/BQKRN1RN w - - 0 9", {28, 676, 18366, 478054, 13126287, 363765666}}, {"bqrknrnb/1p2ppp1/p1pp3p/8/3P1P2/1PP5/P3P1PP/BQRKNRNB w FCfc - 0 9", {31, 646, 20686, 455607, 14984618, 349082278}}, {"qbbrkn1r/pppppp1p/8/6p1/2P1Pn1P/6N1/PP1P1PP1/QBBRKNR1 w GDd - 3 9", {20, 532, 11581, 303586, 7512432, 202967948}}, {"1rbbknr1/p1ppp1pp/1pq2pn1/8/3P4/P3P3/QPP2PPP/1RBBKNRN w GBgb - 3 9", {31, 1002, 30581, 999607, 30642468, 1009228283}}, {"qrbkn1rn/pppp1ppp/8/6b1/P1P1Pp2/8/1P1P2PP/QRBKNBRN w GBgb - 0 9", {22, 505, 12447, 304863, 8192621, 214730959}}, {"qrbk1rnb/p2ppp1p/5n2/1pp3p1/8/7P/PPPPPPPN/QRBKR1NB w Bfb - 0 9", {20, 619, 13448, 449630, 10571176, 369603424}}, {"qbrkb1r1/ppp2ppp/3pn1n1/P3p3/4P3/3P4/1PP2PPP/QBRKBNRN w GCgc - 1 9", {26, 755, 20596, 604483, 17164382, 510878835}}, {"qrkbb1r1/ppp1pnpp/3p2n1/5p2/1P3P2/2Q3N1/P1PPP1PP/1RKBB1RN w GBgb - 0 9", {35, 918, 32244, 870888, 30933394, 867833733}}, {"qrknbbrn/ppp1ppp1/8/7p/2Bp4/4PPP1/PPPP3P/QRKNB1RN w GBgb - 0 9", {27, 593, 16168, 376808, 10422676, 258348640}}, {"qrk1brnb/ppppp3/4n2p/5pp1/2PP4/2N4P/PP2PPP1/QRK1BRNB w FBfb - 2 9", {24, 672, 17447, 506189, 13765777, 414930519}}, {"qbrknrb1/p2ppppp/2p3n1/8/p4P2/6PP/1PPPP3/QBRKNRBN w FCfc - 0 9", {29, 759, 23235, 634493, 20416668, 584870558}}, {"1rkb1rbn/p1pp1ppp/3np3/1p6/4qP2/3NB3/PPPPPRPP/QRKB3N w Bfb - 0 9", {22, 923, 22585, 914106, 24049880, 957218571}}, {"1rknrbbn/p1pp1p1p/8/1p2p1p1/4qPP1/2P5/PP1PP1BP/QRKNR1BN w EBeb - 0 9", {28, 1309, 36355, 1568968, 44576409, 1846382333}}, {"qrk1rn1b/ppppp2p/4n3/3b1pp1/4P2P/5BP1/PPPP1P2/QRKNRNB1 w EBeb - 3 9", {26, 839, 22189, 726354, 19978260, 661207281}}, {"bbrqk1rn/pp1ppppp/8/2p5/2P1P3/5n1P/PPBP1PP1/B1RQKNRN w GCgc - 1 9", {3, 95, 2690, 85038, 2518864, 80775549}}, {"brqbk2n/pppppprp/8/6p1/1P3n2/5P2/P1PPP1PP/R1QBKNRN w Gb - 2 9", {22, 593, 13255, 362760, 8922397, 253271592}}, {"brqknbr1/pp3ppp/3p2n1/2p1p3/2P5/5P2/PPKPP1PP/BRQ1NBRN w gb - 0 9", {21, 590, 13190, 397355, 9581695, 304103516}}, {"1rqknrnb/2pp1ppp/p3p3/1p6/P2P4/5bP1/1PP1PP1P/BRQKNRNB w FBfb - 0 9", {24, 737, 20052, 598439, 17948681, 536330341}}, {"rbb1k1rn/p1pqpppp/6n1/1p1p4/5P2/3PP3/PPP1K1PP/RBBQ1NRN w ga - 3 9", {24, 694, 16773, 513782, 13094823, 419402704}}, {"rqbbknr1/1ppp2pp/p5n1/4pp2/P7/1PP5/1Q1PPPPP/R1BBKNRN w GAga - 0 9", {24, 600, 15347, 408207, 11029596, 308553169}}, {"rqbknbrn/2pppppp/6Q1/pp6/8/2P5/PP1PPPPP/R1BKNBRN w GAga - 2 9", {40, 949, 34100, 889887, 31296485, 881529007}}, {"rqbknr1b/pp1ppp2/2p2n1p/6p1/8/3P1PPP/PPP1P3/RQBKNRNB w FAfa - 0 9", {20, 560, 12275, 373921, 8687544, 277906201}}, {"rbqkbnrn/p3pppp/1p6/3p4/P1p3P1/1P6/1QPPPP1P/RB1KBNRN w GAga - 0 9", {30, 1155, 35865, 1351455, 43092716, 1614019629}}, {"rqkbb1rn/p1p1pppn/1p1p4/7p/4PP2/7P/PPPPB1P1/RQK1BNRN w GAga - 1 9", {30, 701, 20804, 515942, 15450970, 401499189}}, {"rqknbbrn/1p2pp1p/3p2p1/p1p5/P2P4/1P6/1KP1PPPP/RQ1NBBRN w ga - 0 9", {28, 756, 21655, 610320, 17989811, 525585996}}, {"rqknbrnb/1pp3pp/5p2/p2pp3/P7/3PPN2/1PP2PPP/RQKNBR1B w FAfa - 0 9", {26, 731, 19509, 550395, 15209404, 439767476}}, {"rbqkr1bn/p1pppp1p/1p1n4/6p1/7P/3P1PP1/PPP1P3/RBQKNRBN w FAa - 0 9", {27, 586, 16282, 381604, 10905865, 274364342}}, {"rqk1nrb1/ppbp1ppp/4p1n1/2p5/7P/1PP5/P2PPPP1/RQKBNRBN w FAfa - 1 9", {27, 749, 21480, 602318, 18084787, 520547029}}, {"rqknrbbn/pp1p1ppp/4p3/2p5/3P2P1/7P/PPP1PP2/RQKNRBBN w EAa - 0 9", {20, 533, 11829, 336248, 8230417, 245871540}}, {"rqknrnbb/pp1ppp1p/2p3p1/8/8/1P2P1NP/P1PP1PP1/RQKNR1BB w EAea - 0 9", {22, 633, 14480, 441877, 10827868, 343525739}}, {"1brkq1rn/2pppppp/1p2n3/p2bN3/8/7P/PPPPPPP1/BBRKQ1RN w GCgc - 2 9", {27, 748, 20134, 580054, 16010135, 475206624}}, {"brkbqnrn/2pp1ppp/8/1p2p3/Pp2N3/8/2PPPPPP/BRKBQNR1 w GBgb - 0 9", {30, 827, 25308, 757837, 23746165, 751690068}}, {"brk1nbrn/pp1ppppp/2p5/7P/5P2/q2P4/PPP1P1P1/BRKQNBRN w GBgb - 1 9", {15, 471, 8716, 276424, 5960901, 190316951}}, {"brkqnrnb/1p1pp1p1/p4p2/2p4p/8/P2PP3/1PP1QPPP/BRK1NRNB w FBfb - 0 9", {24, 479, 12584, 280081, 7830230, 190419716}}, {"rbbkqnrn/2ppp2p/pp3p2/6p1/P6P/8/RPPPPPP1/1BBKQNRN w Gga - 0 9", {21, 523, 12125, 328733, 8322614, 242240658}}, {"rkbbqr1n/1ppppppn/7p/p7/4P3/2P2P2/PP1PB1PP/RKB1QNRN w GAa - 3 9", {27, 563, 16026, 372148, 11105151, 283211800}}, {"rkbqnbrn/ppppp3/8/5ppp/2P3P1/7P/PPQPPP2/RKB1NBRN w GAga - 0 9", {28, 639, 19250, 469250, 14872172, 384663405}}, {"rkb1nrnb/pppp1pp1/5q1p/8/P3p3/4R1P1/1PPPPP1P/1KBQNRNB w Ffa - 0 9", {28, 873, 23690, 720814, 20209424, 625281937}}, {"rbkqb1rn/1p1ppppp/4n3/p1p5/8/3PBP2/PPP1P1PP/RBKQ1NRN w GAga - 0 9", {26, 798, 21416, 667496, 18475618, 591681956}}, {"rk1qbnrn/1p1ppppp/1b6/p1p5/P7/2P3NP/1P1PPPP1/RKQBB1RN w GAga - 0 9", {22, 506, 12313, 301029, 7891676, 205739580}}, {"rk1nbbrn/ppp1ppp1/8/3p3p/1P1P2q1/5PB1/P1P1P1PP/RKQN1BRN w GAga - 1 9", {31, 956, 29219, 903799, 27827461, 876341492}}, {"rkqnbr1b/pp1pppp1/7p/2p2n2/P2P4/7N/RPP1PPPP/1KQNBR1B w Ffa - 0 9", {31, 750, 24267, 646252, 21639104, 617064197}}, {"rbkq1rbn/2p1pppp/pp3n2/3p4/5P2/3N2N1/PPPPP1PP/RBKQR1B1 w Afa - 2 9", {26, 647, 18027, 465119, 13643783, 369702807}}, {"rkqbr1bn/p2ppppp/1pp2n2/8/5P2/3P1N2/PPP1PRPP/RKQB2BN w Aa - 3 9", {24, 574, 14593, 371597, 10066892, 271121237}}, {"rk1qrbbn/p1ppp1pp/1p2n3/5p2/1P6/K3N3/P1PPPPPP/R1Q1RBBN w ea - 0 9", {25, 548, 14069, 340734, 9043111, 235545764}}, {"rkqnrnbb/pp1pp3/2p5/5ppp/8/PP4NP/2PPPPP1/RKQNR1BB w EAea - 0 9", {23, 727, 18228, 566572, 15078056, 471296844}}, {"bbrknq1r/ppppppp1/8/7p/5n2/3P4/PPP1PNPP/BBKRNQR1 w c - 0 9", {21, 610, 13300, 394705, 9605845, 293532398}}, {"brkbnqr1/2pppnpp/pp3p2/8/4PPPP/8/PPPP4/BRKBNQRN w GBgb - 1 9", {30, 757, 23908, 621332, 20360394, 548380577}}, {"brk1qb1n/ppppppr1/2n3pp/8/2P3P1/2N5/PP1PPP1P/BR1KQBRN w b - 1 9", {26, 570, 15537, 352883, 10081351, 242864559}}, {"brknq1nb/pp2prpp/8/2pP1p2/6P1/2N5/PPPP1P1P/BRK1QRNB w FBb - 1 9", {33, 830, 27897, 764915, 26262884, 765831403}}, {"rbbk1qrn/ppp1p1pp/5p2/3p1n2/7N/P7/1PPPPPPP/RBB1KQRN w ga - 0 9", {21, 562, 13060, 378883, 9520963, 290579255}}, {"rk1b1qrn/ppp1pppp/5n2/3pN3/P6P/7b/1PPPPPP1/RKBB1QRN w GAga - 4 9", {28, 677, 19235, 488740, 14354779, 383207197}}, {"rkbnqbrn/pp1ppp1p/2p5/6p1/P7/4P3/KPPPQPPP/R1BN1BRN w - - 3 9", {28, 585, 17443, 401483, 12574541, 310495538}}, {"rk1nqrnb/pbpppp2/1p4p1/7p/P7/5NP1/1PPPPPBP/RKBNQR2 w FAfa - 2 9", {26, 774, 21626, 645200, 19093408, 576325868}}, {"rbknb1rn/p1pp2pp/1p6/4pp2/1q3P1B/2N5/PPPPPNPP/RBK2QR1 w GAga - 2 9", {31, 1206, 36940, 1374158, 42849564, 1555711209}}, {"rk1bbqrn/pp1pp1pp/3n4/5p2/3p4/1PP5/PK2PPPP/R1NBBQRN w ga - 0 9", {21, 629, 14059, 429667, 10587910, 332632033}}, {"rknqbbr1/p1pp1pp1/1p4n1/4p2p/4P1P1/6RB/PPPP1P1P/RKNQB2N w Aga - 0 9", {27, 753, 20918, 593155, 17318772, 507563675}}, {"rknqbr1b/pppp1ppp/4p2n/8/1P3P2/4P3/P1PPN1PP/RKNQBR1B w FAfa - 2 9", {26, 623, 17177, 460663, 13389799, 383508368}}, {"r2kqrbn/bppppppp/2n5/p4B2/5P2/2P5/PP1PP1PP/1RKNQRBN w F - 2 9", {39, 1026, 37800, 1011922, 35946987, 992756232}}, {"rk1bqrb1/ppppppp1/1n6/7p/2P2P1n/4P1Q1/PP1P2PP/RKNB1RBN w FAfa - 0 9", {35, 760, 25817, 610557, 21014787, 536852043}}, {"rkq1rb1n/ppppp1pp/1n6/5p2/PPb2P2/8/1KPPP1PP/R1NQRBBN w ea - 1 9", {27, 754, 21009, 568788, 16461795, 448313956}}, {"rknqr2b/pppnp1pp/3p4/3b1p2/8/1N1P2N1/PPP1PPPP/RKQ1R1BB w EAea - 1 9", {27, 803, 23708, 700453, 21875031, 654754840}}, {"bbrknrqn/ppppp1pB/8/2P2p1p/8/5N2/PP1PPPPP/B1RK1RQN w FCfc - 0 9", {30, 799, 23923, 671112, 20532790, 603059376}}, {"brkbnrq1/1pppp1p1/6np/p4p2/4P3/1PP5/P1KP1PPP/BR1BNRQN w fb - 1 9", {27, 726, 19329, 555622, 15156662, 457601127}}, {"brknrbq1/1p1p1ppp/p3p1n1/2p5/8/1P1BPP2/P1PP2PP/BRKNR1QN w EBeb - 0 9", {36, 786, 27868, 655019, 22852433, 577223409}}, {"brknrqnb/p2ppp1p/2p5/1p6/3P2p1/P1P1N3/1P2PPPP/BRK1RQNB w EBeb - 0 9", {23, 649, 15169, 440504, 10687843, 320881984}}, {"rbbk1rqn/1ppppppp/3n4/p7/2P5/3N4/PP1PPPPP/RBB1KRQN w fa - 1 9", {20, 478, 11094, 275250, 7094988, 185488058}}, {"rkbbnrqn/p2p1ppp/1p2p3/8/P1p1P3/1BP5/1P1P1PPP/RKB1NRQN w FAfa - 0 9", {22, 570, 13295, 346811, 8671852, 229898448}}, {"rkb1rb1n/ppppppqp/8/2n3p1/2P1P1P1/8/PP1P1P1P/RKBNRBQN w EAea - 1 9", {23, 663, 16212, 490748, 12900485, 404944553}}, {"rkb1rqnb/pppp3p/2n3p1/4pp2/P2P3P/2P5/1P2PPP1/RKBNRQNB w EAea - 0 9", {25, 845, 22188, 741972, 20276176, 683290790}}, {"rbk1brqn/ppp1pppp/8/3p4/7P/1P4P1/2PPPP2/RBKNBRQN w FAfa - 0 9", {24, 526, 13862, 322175, 9054028, 222704171}}, {"rknbbrqn/pp3pp1/4p3/2pp3p/2P5/8/PPBPPPPP/RKN1BRQN w FAfa - 0 9", {26, 756, 19280, 559186, 14697705, 433719427}}, {"1knrbbqn/rp1p1ppp/p3p3/2p5/8/5P1P/PPPPP1P1/RKNRBBQN w DAd - 0 9", {26, 539, 15194, 345070, 10223443, 248715580}}, {"rknr1qnb/ppp1p1pp/3p2b1/8/4p3/1P3P1P/P1PP2P1/RKNRBQNB w DAda - 0 9", {25, 701, 18969, 561369, 16047041, 496340789}}, {"rbk1r1bn/ppppp1pp/4n3/5p2/1P3P2/4N2P/PqPPP1P1/RBK1RQBN w EAea - 1 9", {2, 60, 1319, 41765, 1017864, 33183408}}, {"r1nbrqbn/k1ppp1pp/1p6/p4p2/2P5/6PQ/PP1PPP1P/RKNBR1BN w EA - 0 9", {27, 699, 20436, 561765, 17192121, 499247248}}, {"rknrqbbn/1pp1pp2/p5p1/3p3p/6P1/PN5P/1PPPPP2/RK1RQBBN w DAda - 0 9", {23, 611, 15515, 435927, 11917036, 352885930}}, {"rknrqn1b/p1pp1ppb/8/1p2p1Qp/3P4/3N4/PPP1PPPP/RK1R1NBB w DAda - 0 9", {45, 1170, 48283, 1320341, 52213677, 1500007485}}, {"bbkrnrnq/p2p1ppp/2p1p3/1p6/1P2Q3/6P1/P1PPPP1P/BBKRNRN1 w - - 0 9", {41, 1035, 39895, 1035610, 38555608, 1037686769}}, {"brkbnr2/1ppppp1p/7n/p5N1/P2q4/8/1PPPPPPP/BRKBNRQ1 w FBfb - 1 9", {22, 869, 19234, 679754, 16453359, 567287944}}, {"brknrbnq/p1ppppp1/1p6/7p/2PP4/5P2/PPK1P1PP/BR1NRBNQ w eb - 1 9", {23, 641, 14748, 422240, 10192718, 302864305}}, {"brk1r1qb/pp1ppnpp/2p2pn1/8/6N1/2N3P1/PPPPPP1P/BRK1R1QB w EBeb - 3 9", {32, 863, 28379, 773191, 25848794, 720443112}}, {"rbbk1rnq/pppp1pp1/4p2p/8/3P2n1/4BN1P/PPP1PPP1/RB1K1RNQ w FAfa - 3 9", {26, 628, 16151, 411995, 11237919, 300314373}}, {"rkbbnr1q/p1pppppp/5n2/1p5B/PP6/4P3/2PP1PPP/RKB1NRNQ w FAfa - 0 9", {30, 692, 21036, 519283, 16025428, 420887328}}, {"rkb1rbnq/1pppp1pp/5p2/p7/5n1P/1PN3P1/P1PPPP2/RKB1RBNQ w EAea - 0 9", {32, 825, 27130, 697251, 23593363, 622249676}}, {"rkbnrnqb/1ppp1p1p/p5p1/4p3/4P3/2N2P2/PPPP2PP/RKBR1NQB w Aea - 0 9", {24, 487, 13300, 301989, 8782713, 215787079}}, {"rbknbr1q/pppp2pp/4p3/5p1n/1P2P2N/8/P1PP1PPP/RBKNBR1Q w FAfa - 0 9", {23, 571, 13799, 365272, 9224232, 257288920}}, {"rknbb1nq/pppppr2/5pp1/7p/8/1N4P1/PPPPPP1P/RK1BBRNQ w FAa - 2 9", {26, 548, 15618, 350173, 10587626, 253006082}}, {"rknr1bnq/p2pp1pp/1p3p2/2p4b/6PP/2P2N2/PP1PPP2/RKNRBB1Q w DAda - 1 9", {25, 502, 13150, 279098, 7824941, 175766730}}, {"rknrb1qb/ppp1pppp/3p4/8/4P1nP/2P5/PPKP1PP1/R1NRBNQB w da - 1 9", {23, 643, 14849, 426616, 10507328, 312096061}}, {"rbk1rnbq/pppp1npp/4p3/5p2/4P1P1/7P/PPPP1P1N/RBKNR1BQ w EAea - 1 9", {24, 591, 15178, 376988, 10251465, 263574861}}, {"rknbrnb1/p1pppp1p/1p6/3N2p1/P3q1P1/8/1PPPPP1P/RKNBR1BQ w EAea - 1 9", {28, 948, 27343, 864588, 26241141, 812343987}}, {"rknrn1b1/ppppppqp/8/6p1/2P5/2P1BP2/PP2P1PP/RKNRNB1Q w DAda - 1 9", {31, 807, 24360, 672973, 20455205, 588518645}}, {"1k1rnqbb/npppppp1/r7/p2B3p/5P2/1N4P1/PPPPP2P/RK1RNQB1 w DAd - 0 9", {40, 1122, 44297, 1249989, 48711073, 1412437357}}, {"bbqr1rkn/pp1ppppp/8/2p5/1P2P1n1/7N/P1PP1P1P/BBQRKR1N w FD - 0 9", {26, 841, 22986, 746711, 21328001, 705170410}}, {"bqkr1rnn/1ppp1ppp/p4b2/4p3/P7/3PP2N/1PP2PPP/BQRBKR1N w FC - 3 9", {24, 500, 12802, 293824, 7928916, 197806842}}, {"bqrkrbnn/1pp1ppp1/8/p6p/3p4/P3P2P/QPPP1PP1/B1RKRBNN w ECec - 0 9", {31, 592, 18585, 396423, 12607528, 298629240}}, {"bqkrrnnb/2p1pppp/p7/1P1p4/8/2R3P1/PP1PPP1P/BQ1KRNNB w E - 0 9", {42, 1124, 45187, 1276664, 50052573, 1483524894}}, {"qbbrkrn1/p1pppn1p/8/1p3Pp1/2P5/8/PP1PPP1P/QBBRKRNN w FDfd - 0 9", {21, 577, 13244, 392131, 9683808, 300294295}}, {"qrbbkrnn/pp1p2pp/4p3/5p2/2p2P1P/2P5/PP1PP1P1/QRBBKRNN w FBfb - 0 9", {21, 571, 12736, 345681, 8239872, 228837930}}, {"qrbkrbn1/1pp1pppp/p2p4/8/5PPn/2P5/PP1PP3/QRBKRBNN w EBeb - 0 9", {18, 466, 9443, 257776, 5679073, 162883949}}, {"qrb1rnnb/pp1p1ppp/2pk4/4p3/1P2P3/1R6/P1PP1PPP/Q1BKRNNB w E - 4 9", {37, 760, 26863, 562201, 19486022, 421740856}}, {"qbrkbrn1/p1pppp1p/6n1/1p4p1/1P6/5P2/P1PPPBPP/QBRK1RNN w FCfc - 1 9", {33, 824, 27385, 750924, 25176664, 734656217}}, {"qrkbbr2/2pppppp/5nn1/pp1Q4/P7/3P4/1PP1PPPP/1RKBBRNN w FBfb - 0 9", {42, 1147, 44012, 1311247, 48216013, 1522548864}}, {"qrkrbbnn/pp2pp2/2pp2pp/1B6/P7/4P3/1PPP1PPP/QRKRB1NN w DBdb - 0 9", {26, 464, 12653, 242892, 6928220, 142507795}}, {"qrkrbnnb/p1pp1pp1/1p5p/4p3/1P6/6PN/PKPPPP1P/QR1RBN1B w db - 0 9", {29, 705, 20000, 529810, 15055365, 419552571}}, {"qbrkr1bn/p1p1pp1p/1p1p2n1/6p1/3P1P2/4P3/PPP3PP/QBKRRNBN w ec - 2 9", {23, 613, 14835, 426484, 10747407, 323905533}}, {"qrk1rnb1/p1pp1ppp/1p2Bbn1/8/4P3/6P1/PPPP1P1P/QRK1RNBN w EBeb - 1 9", {28, 927, 24887, 846839, 23063284, 807913585}}, {"1qkrnbbn/1rpppppp/pp6/5N2/P4P2/8/1PPPP1PP/QRKRNBB1 w DBd - 3 9", {30, 542, 16646, 345172, 10976745, 251694423}}, {"qrkr2bb/pppppppp/8/1n2n3/1N5P/1P6/P1PPPPP1/QRKR1NBB w DBdb - 1 9", {28, 719, 21048, 562015, 17351761, 479400272}}, {"bbrqkrnn/3ppppp/8/ppp5/6P1/4P2N/PPPPKP1P/BBRQ1R1N w fc - 0 9", {21, 704, 16119, 546215, 13676371, 470796854}}, {"brqbkrnn/1pp2p1p/3pp1p1/p5N1/8/1P6/P1PPPPPP/BRQBK1RN w Bfb - 0 9", {34, 688, 22827, 505618, 16639723, 402140795}}, {"br1krb1n/2qppppp/pp3n2/8/1P4P1/8/P1PPPP1P/1RQKRBNN w EBeb - 0 9", {24, 945, 23943, 926427, 25019636, 959651619}}, {"brqkr1nb/2ppp1pp/1p2np2/p7/2P1PN2/8/PP1P1PPP/BRQKRN1B w EBeb - 0 9", {28, 675, 19728, 504128, 15516491, 417396563}}, {"rbbqkrnn/3pppp1/p7/1pp4p/2P1P2P/8/PP1P1PP1/RBBQKRNN w FAfa - 0 9", {26, 671, 18164, 496806, 14072641, 404960259}}, {"rqbbkr1n/pp1p1p1p/4pn2/2p3p1/4P1P1/3P3P/PPP2P2/RQBBKRNN w FAfa - 0 9", {22, 633, 14629, 441809, 10776416, 335689685}}, {"rqbkrbnn/p1ppp3/1p3pp1/7p/3P4/P1P5/1PQ1PPPP/R1BKRBNN w EAea - 0 9", {32, 607, 20339, 454319, 15586203, 383515709}}, {"rqbkrnn1/pp2ppbp/3p4/2p3p1/2P5/1P3N1P/P2PPPP1/RQBKRN1B w EAea - 1 9", {29, 943, 28732, 908740, 28761841, 907579129}}, {"rbqkb1nn/1ppppr1p/p5p1/5p2/1P6/2P4P/P1KPPPP1/RBQ1BRNN w a - 1 9", {22, 441, 10403, 231273, 5784206, 140934555}}, {"rqkb1rnn/1pp1pp1p/p5p1/1b1p4/3P4/P5P1/RPP1PP1P/1QKBBRNN w Ffa - 1 9", {21, 505, 11592, 290897, 7147063, 188559137}}, {"rq1rbbnn/pkp1ppp1/3p3p/1p2N1P1/8/8/PPPPPP1P/RQKRBB1N w DA - 0 9", {27, 608, 16419, 387751, 10808908, 268393274}}, {"rqkrb2b/p2ppppp/2p3nn/1p6/5P2/PP1P4/2P1P1PP/RQKRBNNB w DAda - 1 9", {30, 749, 21563, 581531, 16916813, 485406712}}, {"rbqkr1bn/pp1ppp2/2p1n2p/6p1/8/4BPNP/PPPPP1P1/RBQKRN2 w EAea - 0 9", {23, 600, 15082, 410057, 11041820, 314327867}}, {"rqkbrnb1/2ppp1pp/pp3pn1/8/5P2/B2P4/PPP1P1PP/RQKBRN1N w EAea - 2 9", {22, 569, 13541, 371471, 9395816, 269460607}}, {"rqkrnbb1/p1p1pppp/1p4n1/3p4/7P/P3P3/1PPPBPP1/RQKRN1BN w DAda - 0 9", {27, 579, 15565, 373079, 10238486, 266047417}}, {"rqkrn1bb/p1ppp1pp/4n3/1p6/6p1/4N3/PPPPPPPP/RQKR2BB w DAda - 0 9", {20, 462, 10234, 274162, 6563859, 193376359}}, {"bbrkqr2/pppp1ppp/6nn/8/2P1p3/3PP2N/PP3PPP/BBRKQR1N w FCfc - 0 9", {28, 724, 21688, 619064, 19318355, 593204629}}, {"brk1qrnn/1pppbppp/4p3/8/1p6/P1P4P/3PPPP1/BRKBQRNN w FBfb - 1 9", {24, 662, 16920, 468215, 12610387, 355969349}}, {"1r1qrbnn/p1pkpppp/1p1p4/8/3P1PP1/P4b2/1PP1P2P/BRKQRBNN w EB - 1 9", {22, 696, 17021, 510247, 13697382, 401903030}}, {"1rkqrnnb/p1p1p1pp/1p1p4/3b1p1N/4P3/5N2/PPPP1PPP/BRKQR2B w EBeb - 1 9", {29, 887, 27035, 816176, 26051242, 791718847}}, {"rbbkq1rn/pppppppp/7n/8/P7/3P3P/1PPKPPP1/RBB1QRNN w a - 3 9", {22, 417, 9900, 216855, 5505063, 134818483}}, {"rkbbqr1n/1p1pppp1/2p2n2/p4NBp/8/3P4/PPP1PPPP/RK1BQRN1 w FAfa - 0 9", {37, 832, 30533, 728154, 26676373, 673756141}}, {"rkbqrb1n/3pBppp/ppp2n2/8/8/P2P4/1PP1PPPP/RK1QRBNN w EAea - 0 9", {28, 685, 19718, 543069, 16033316, 482288814}}, {"rkb1rn1b/ppppqppp/4p3/8/1P2n1P1/5Q2/P1PP1P1P/RKB1RNNB w EAea - 2 9", {37, 1158, 40114, 1234768, 44672979, 1389312729}}, {"r1kqbrnn/pp1pp1p1/7p/2P2p2/5b2/3P4/P1P1P1PP/RBKQBRNN w FAfa - 0 9", {5, 161, 4745, 154885, 4734999, 157499039}}, {"rkqbbr1n/ppp1ppp1/8/Q2p3p/4n3/3P1P2/PPP1P1PP/RK1BBRNN w FAfa - 2 9", {38, 1144, 40433, 1236877, 43832975, 1366087771}}, {"rkqrbbn1/p1ppppp1/Bp5p/8/P6n/2P1P3/1P1P1PPP/RKQRB1NN w DAda - 0 9", {28, 551, 15488, 350861, 9944107, 251179183}}, {"rkqrb1nb/1ppp1ppp/p7/4p3/5n2/3P2N1/PPPQPPPP/RK1RB1NB w DAda - 0 9", {26, 690, 19877, 513628, 15965907, 418191735}}, {"rbkqrnbn/pppp1p2/4p1p1/7p/7P/P2P4/BPP1PPP1/R1KQRNBN w EAea - 0 9", {27, 515, 13992, 309727, 8792550, 218658292}}, {"rkqbrnbn/pp1ppp2/8/2p3p1/P1P4p/5P2/1PKPP1PP/R1QBRNBN w ea - 0 9", {27, 627, 16843, 431101, 11978698, 328434174}}, {"rkqrnbbn/1p2pp1p/3p2p1/p1p5/P5PP/3N4/1PPPPP2/RKQR1BBN w DAda - 0 9", {23, 624, 15512, 451860, 11960861, 367311176}}, {"rk2rnbb/ppqppppp/2pn4/8/1P3P2/6P1/P1PPP1NP/RKQR1NBB w DAa - 1 9", {27, 727, 20206, 581003, 16633696, 505212747}}, {"b1krrqnn/pp1ppp1p/2p3p1/8/P3Pb1P/1P6/2PP1PP1/BBRKRQNN w EC - 0 9", {32, 943, 30759, 865229, 28672582, 800922511}}, {"1rkbrqnn/p1pp1ppp/1p6/8/P2Pp3/8/1PPKPPQP/BR1BR1NN w eb - 0 9", {28, 916, 24892, 817624, 22840279, 759318058}}, {"brkrqb1n/1pppp1pp/p7/3n1p2/P5P1/3PP3/1PP2P1P/BRKRQBNN w DBdb - 0 9", {27, 669, 18682, 484259, 13956472, 380267099}}, {"brkrqnnb/3pppp1/1p6/p1p4p/2P3P1/6N1/PP1PPP1P/BRKRQ1NB w DBdb - 0 9", {29, 699, 20042, 512639, 15093909, 406594531}}, {"r1bkrq1n/pp2pppp/3b1n2/2pp2B1/6P1/3P1P2/PPP1P2P/RB1KRQNN w EAea - 2 9", {27, 835, 22848, 713550, 19867800, 631209313}}, {"rk1brq1n/p1p1pppp/3p1n2/1p3b2/4P3/2NQ4/PPPP1PPP/RKBBR2N w EAea - 4 9", {36, 1004, 35774, 979608, 35143142, 966310885}}, {"rkbrqbnn/1p2ppp1/B1p5/p2p3p/4P2P/8/PPPP1PP1/RKBRQ1NN w DAda - 0 9", {27, 748, 21005, 597819, 17597073, 515304215}}, {"rkbrqn1b/pp1pp1pp/2p2p2/5n2/8/2P2P2/PP1PP1PP/RKBRQ1NB w DAda - 0 9", {20, 479, 10485, 266446, 6253775, 167767913}}, {"rbkrbnn1/ppppp1pp/5q2/5p2/5P2/P3P2N/1PPP2PP/RBKRBQ1N w DAda - 3 9", {28, 947, 26900, 876068, 26007841, 838704143}}, {"rkr1bqnn/1ppp1p1p/p5p1/4p3/3PP2b/2P2P2/PP4PP/RKRBBQNN w CAca - 0 9", {31, 1004, 32006, 1006830, 32688124, 1024529879}}, {"rkrqbbnn/pppp3p/8/4ppp1/1PP4P/8/P2PPPP1/RKRQBBNN w CAca - 0 9", {24, 717, 18834, 564137, 15844525, 484884485}}, {"rkrqbn1b/pppp2pp/8/4pp2/1P1P2n1/5N2/P1P1PP1P/RKRQBN1B w CAca - 0 9", {25, 718, 19654, 587666, 17257753, 537354146}}, {"rbkrqnbn/p1p1ppp1/1p1p4/8/3PP2p/2PB4/PP3PPP/R1KRQNBN w DAda - 0 9", {30, 754, 23298, 611322, 19338246, 532603566}}, {"1krbqnbn/1p2pppp/r1pp4/p7/8/1P1P2PP/P1P1PP2/RKRBQNBN w CAc - 0 9", {21, 566, 13519, 375128, 9700847, 279864836}}, {"rkrq1b2/pppppppb/3n2np/2N5/4P3/7P/PPPP1PP1/RKRQ1BBN w CAca - 1 9", {33, 654, 21708, 479678, 15990307, 382218272}}, {"rkr1nnbb/ppp2p1p/3p1qp1/4p3/P5P1/3PN3/1PP1PP1P/RKRQN1BB w CAca - 1 9", {28, 715, 20361, 555328, 16303092, 468666425}}, {"bbrkrnqn/1p1ppppp/8/8/p2pP3/PP6/2P2PPP/BBRKRNQN w ECec - 0 9", {24, 757, 19067, 603231, 15957628, 509307623}}, {"brkbrnqn/ppp2p2/4p3/P2p2pp/6P1/5P2/1PPPP2P/BRKBRNQN w EBeb - 0 9", {25, 548, 14563, 348259, 9688526, 247750144}}, {"brkr1bqn/1pppppp1/3n3p/1p6/P7/4P1P1/1PPP1P1P/BRKRN1QN w DBdb - 0 9", {19, 359, 7430, 157099, 3521652, 81787718}}, {"brkr1qnb/pppp2pp/2B1p3/5p2/2n5/6PP/PPPPPPN1/BRKR1QN1 w DBdb - 1 9", {27, 854, 23303, 741626, 20558538, 667089231}}, {"rbbkrnqn/p1p1p1pp/8/1p1p4/1P1Pp3/6N1/P1P2PPP/RBBKRNQ1 w EAea - 0 9", {28, 723, 19844, 514440, 14621108, 397454100}}, {"rkbbrn1n/pppppp2/5q1p/6p1/3P3P/4P3/PPP2PP1/RKBBRNQN w EAea - 1 9", {25, 741, 19224, 585198, 15605840, 485037906}}, {"rkbr1bq1/ppnppppp/6n1/2p5/2P1N2P/8/PP1PPPP1/RKBRNBQ1 w DAda - 3 9", {24, 547, 14359, 339497, 9410221, 234041078}}, {"1kbrnqnb/r1ppppp1/8/pp5p/8/1P1NP3/P1PP1PPP/RKB1RQNB w Ad - 2 9", {26, 618, 17305, 442643, 13112297, 357030697}}, {"rbkrb1qn/1pp1ppp1/3pn2p/pP6/8/4N1P1/P1PPPP1P/RBKRB1QN w DAda - 0 9", {21, 544, 12492, 338832, 8381483, 236013157}}, {"rkrbbnqn/ppppp3/5p2/6pp/5PBP/4P3/PPPP2P1/RKR1BNQN w CAca - 0 9", {30, 891, 25435, 764356, 21894752, 669256602}}, {"rkr1bb1n/ppppp1pp/5p2/4n3/3QP3/5P2/RPPP2PP/1KRNBB1N w Cca - 1 9", {45, 1172, 51766, 1332060, 57856784, 1501852662}}, {"rkr1bqnb/pp1ppppp/8/2pN4/1P6/5N2/P1PPnPPP/RKR1BQ1B w CAca - 0 9", {28, 730, 20511, 559167, 16323242, 463032124}}, {"rbkrnqb1/2ppppp1/p5np/1p6/8/3N4/PPPPPPPP/RBKRQNB1 w DAda - 2 9", {20, 417, 9159, 217390, 5180716, 133936564}}, {"rkrbnqb1/p1pppnpp/5p2/1p6/2P5/1P1P1N2/P3PPPP/RKRB1QBN w CAca - 0 9", {25, 546, 14039, 330316, 8813781, 222026485}}, {"rkr1qbbn/ppppppp1/4n3/7p/8/P7/KPPPPPPP/R1RNQBBN w ca - 0 9", {22, 484, 11458, 267495, 6633319, 163291279}}, {"rkrnqnb1/1ppppp2/p5p1/7p/8/P1bPP3/1PP1QPPP/RKRN1NBB w CAca - 0 9", {22, 636, 15526, 441001, 11614241, 331083405}}, {"b2krn1q/p1rppppp/1Q3n2/2p1b3/1P4P1/8/P1PPPP1P/BBRKRNN1 w ECe - 3 9", {36, 1192, 42945, 1406795, 50382104, 1650202838}}, {"brkbrnn1/pp1pppp1/7q/2p5/6Pp/4P1NP/PPPP1P2/BRKBR1NQ w EBeb - 2 9", {30, 978, 29593, 942398, 29205057, 936568065}}, {"brkrnb1q/pp1p1ppp/2p1p3/5n2/1P6/5N1N/P1PPPPPP/BRKR1B1Q w DBdb - 1 9", {31, 897, 27830, 810187, 25423729, 755334868}}, {"brkr1nqb/pp1p1pp1/2pn3p/P3p3/4P3/6P1/1PPP1P1P/BRKRNNQB w DBdb - 0 9", {19, 382, 8052, 182292, 4232274, 103537333}}, {"r1bkrn1q/ppbppppp/5n2/2p5/3P4/P6N/1PP1PPPP/RBBKRNQ1 w EAea - 3 9", {27, 822, 22551, 678880, 19115128, 578210135}}, {"rkbbrnnq/pp2pppp/8/2pp4/P1P5/1P3P2/3PP1PP/RKBBRNNQ w EAea - 1 9", {23, 643, 15410, 442070, 11170489, 329615708}}, {"rkbr1b1q/p1pppppp/1p1n4/7n/5QP1/3N4/PPPPPP1P/RKBR1BN1 w DAda - 4 9", {37, 943, 34382, 880474, 31568111, 842265141}}, {"rkbr1nqb/pppp2np/8/4ppp1/1P6/6N1/P1PPPPPP/RKBRN1QB w DAda - 1 9", {23, 574, 13260, 362306, 9020291, 261247606}}, {"rbkr1nnq/p1p1pp1p/1p4p1/3p4/b3P3/4N3/PPPPNPPP/RBKRB1Q1 w DAda - 0 9", {26, 900, 23414, 805006, 21653203, 745802405}}, {"rkrbb1nq/p2pppp1/1p4n1/2p4p/3N4/4P1P1/PPPP1P1P/RKRBBN1Q w CAca - 0 9", {32, 697, 22231, 531121, 17150175, 441578567}}, {"rkrnbb1q/pp2pp1p/6pn/2pp4/2B1P2P/8/PPPP1PP1/RKRNB1NQ w CAca - 0 9", {28, 854, 23853, 755990, 21823412, 712787248}}, {"rk2bnqb/pprpppp1/4n2p/2p5/P7/3P2NP/1PP1PPP1/RKRNB1QB w CAa - 1 9", {26, 596, 16251, 414862, 11758184, 323043654}}, {"r1krnnbq/pp1ppp1p/6p1/2p5/2P5/P3P3/Rb1P1PPP/1BKRNNBQ w Dda - 0 9", {2, 61, 1312, 40072, 937188, 28753562}}, {"1krbnnbq/1pp1p1pp/r7/p2p1p2/3PP3/2P3P1/PP3P1P/RKRBNNBQ w CAc - 0 9", {30, 953, 28033, 860530, 25531358, 787205262}}, {"rkr1nbbq/2ppp1pp/1pn5/p4p2/P6P/3P4/1PP1PPPB/RKRNNB1Q w CAca - 1 9", {24, 645, 15689, 446423, 11484012, 341262639}}, {"rkrnnqbb/p1ppp2p/Qp6/4Pp2/5p2/8/PPPP2PP/RKRNN1BB w CAca - 0 9", {35, 929, 32020, 896130, 31272517, 915268405}}, {"bbq1nr1r/pppppk1p/2n2p2/6p1/P4P2/4P1P1/1PPP3P/BBQNNRKR w HF - 1 9", {23, 589, 14744, 387556, 10316716, 280056112}}, }}; for (std::size_t i = 0; i < 6; ++i) { int test_num = 1; for (const auto &[fen, nodes] : tests) { if (nodes.size() > i) { INFO("FEN: ", fen); INFO("Depth: ", i + 1); INFO("Position ", test_num, "/", tests.size()); auto pos = chess::Position(fen); REQUIRE(perft(pos, i + 1) == nodes.at(i)); } test_num++; } } } TEST_SUITE_END();