text
stringlengths 5
1.04M
|
|---|
// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "optionsdialog.h"
#include "ui_optionsdialog.h"
#include "bitcoinunits.h"
#include "monitoreddatamapper.h"
#include "netbase.h"
#include "optionsmodel.h"
#include <QDir>
#include <QIntValidator>
#include <QLocale>
#include <QMessageBox>
OptionsDialog::OptionsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::OptionsDialog),
model(0),
mapper(0),
fRestartWarningDisplayed_Proxy(false),
fRestartWarningDisplayed_Lang(false),
fProxyIpValid(true)
{
ui->setupUi(this);
/* Network elements init */
#ifndef USE_UPNP
ui->mapPortUpnp->setEnabled(false);
#endif
ui->proxyIp->setEnabled(false);
ui->proxyPort->setEnabled(false);
ui->proxyPort->setValidator(new QIntValidator(1, 65535, this));
ui->socksVersion->setEnabled(false);
ui->socksVersion->addItem("5", 5);
ui->socksVersion->addItem("4", 4);
ui->socksVersion->setCurrentIndex(0);
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy()));
ui->proxyIp->installEventFilter(this);
/* Window elements init */
#ifdef Q_OS_MAC
/* remove Window tab on Mac */
ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow));
#endif
/* Display elements init */
QDir translations(":translations");
ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
foreach(const QString &langStr, translations.entryList())
{
QLocale locale(langStr);
/** check if the locale name consists of 2 parts (language_country) */
if(langStr.contains("_"))
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
else
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language (locale name)", e.g. "German (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
}
ui->unit->setModel(new BitcoinUnits(this));
/* Widget-to-option mapper */
mapper = new MonitoredDataMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
mapper->setOrientation(Qt::Vertical);
/* enable apply button when data modified */
connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton()));
/* disable apply button when new data loaded */
connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton()));
/* setup/change UI elements when proxy IP is invalid/valid */
connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool)));
}
OptionsDialog::~OptionsDialog()
{
delete ui;
}
void OptionsDialog::setModel(OptionsModel *model)
{
this->model = model;
if(model)
{
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
mapper->setModel(model);
setMapper();
mapper->toFirst();
}
/* update the display unit, to not use the default ("BTC") */
updateDisplayUnit();
/* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */
connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang()));
/* disable apply button after settings are loaded as there is nothing to save */
disableApplyButton();
}
void OptionsDialog::setMapper()
{
/* Main */
mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup);
/* Wallet */
mapper->addMapping(ui->transactionFee, OptionsModel::Fee);
mapper->addMapping(ui->spendZeroConfChange, OptionsModel::SpendZeroConfChange);
/* Network */
mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP);
mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse);
mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP);
mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort);
mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion);
/* Window */
#ifndef Q_OS_MAC
mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray);
mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose);
#endif
/* Display */
mapper->addMapping(ui->lang, OptionsModel::Language);
mapper->addMapping(ui->unit, OptionsModel::DisplayUnit);
mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses);
mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures);
}
void OptionsDialog::enableApplyButton()
{
ui->applyButton->setEnabled(true);
}
void OptionsDialog::disableApplyButton()
{
ui->applyButton->setEnabled(false);
}
void OptionsDialog::enableSaveButtons()
{
/* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */
if(fProxyIpValid)
setSaveButtonState(true);
}
void OptionsDialog::disableSaveButtons()
{
setSaveButtonState(false);
}
void OptionsDialog::setSaveButtonState(bool fState)
{
ui->applyButton->setEnabled(fState);
ui->okButton->setEnabled(fState);
}
void OptionsDialog::on_resetButton_clicked()
{
if(model)
{
// confirmation dialog
QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm options reset"),
tr("Some settings may require a client restart to take effect.") + "<br><br>" + tr("Do you want to proceed?"),
QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
if(btnRetVal == QMessageBox::Cancel)
return;
disableApplyButton();
/* disable restart warning messages display */
fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = true;
/* reset all options and save the default values (QSettings) */
model->Reset();
mapper->toFirst();
mapper->submit();
/* re-enable restart warning messages display */
fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = false;
}
}
void OptionsDialog::on_okButton_clicked()
{
mapper->submit();
accept();
}
void OptionsDialog::on_cancelButton_clicked()
{
reject();
}
void OptionsDialog::on_applyButton_clicked()
{
mapper->submit();
disableApplyButton();
}
void OptionsDialog::showRestartWarning_Proxy()
{
if(!fRestartWarningDisplayed_Proxy)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Kaori."), QMessageBox::Ok);
fRestartWarningDisplayed_Proxy = true;
}
}
void OptionsDialog::showRestartWarning_Lang()
{
if(!fRestartWarningDisplayed_Lang)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Kaori."), QMessageBox::Ok);
fRestartWarningDisplayed_Lang = true;
}
}
void OptionsDialog::updateDisplayUnit()
{
if(model)
{
/* Update transactionFee with the current unit */
ui->transactionFee->setDisplayUnit(model->getDisplayUnit());
}
}
void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState)
{
// this is used in a check before re-enabling the save buttons
fProxyIpValid = fState;
if(fProxyIpValid)
{
enableSaveButtons();
ui->statusLabel->clear();
}
else
{
disableSaveButtons();
object->setValid(fProxyIpValid);
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
ui->statusLabel->setText(tr("The supplied proxy address is invalid."));
}
}
bool OptionsDialog::eventFilter(QObject *object, QEvent *event)
{
if(event->type() == QEvent::FocusOut)
{
if(object == ui->proxyIp)
{
CService addr;
/* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */
emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr));
}
}
return QDialog::eventFilter(object, event);
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "amount.h"
#include "tinyformat.h"
CFeeRate::CFeeRate(const CAmount& nFeePaid, size_t nSize)
{
if (nSize > 0)
nSatoshisPerK = nFeePaid * 1000 / nSize;
else
nSatoshisPerK = 0;
}
CAmount CFeeRate::GetFee(size_t nSize) const
{
CAmount nFee = nSatoshisPerK * nSize / 1000;
if (nFee == 0 && nSatoshisPerK > 0)
nFee = nSatoshisPerK;
return nFee;
}
std::string CFeeRate::ToString() const
{
return strprintf("%d.%08d VN/kB", nSatoshisPerK / COIN, nSatoshisPerK % COIN);
}
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#ifdef __GNUC__
# pragma GCC diagnostic ignored "-Wmissing-declarations"
# if defined __clang__ || defined __APPLE__
# pragma GCC diagnostic ignored "-Wmissing-prototypes"
# pragma GCC diagnostic ignored "-Wextra"
# endif
#endif
#ifndef __OPENCV_TEST_PRECOMP_HPP__
#define __OPENCV_TEST_PRECOMP_HPP__
#include "opencv2/ts.hpp"
#include "opencv2/ts/cuda_test.hpp"
#include "opencv2/cudacodec.hpp"
#include BLIK_OPENCV_U_opencv2__highgui_hpp //original-code:"opencv2/highgui.hpp"
#include BLIK_OPENCV_U_cvconfig_h //original-code:"cvconfig.h"
#endif
|
//=================================================================================================
/*!
// \file src/mathtest/dmatdmatadd/D3x3aD3x3b.cpp
// \brief Source file for the D3x3aD3x3b dense matrix/dense matrix addition math test
//
// Copyright (C) 2012-2017 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. 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 names of the Blaze development group 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 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/DiagonalMatrix.h>
#include <blaze/math/StaticMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatdmatadd/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'D3x3aD3x3b'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
typedef blaze::DiagonalMatrix< blaze::StaticMatrix<TypeA,3UL,3UL> > D3x3a;
typedef blaze::DiagonalMatrix< blaze::StaticMatrix<TypeB,3UL,3UL> > D3x3b;
// Creator type definitions
typedef blazetest::Creator<D3x3a> CD3x3a;
typedef blazetest::Creator<D3x3b> CD3x3b;
// Running the tests
RUN_DMATDMATADD_OPERATION_TEST( CD3x3a(), CD3x3b() );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix addition:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
/*
Copyright 2018 Oscar Sebio Cajaraville
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 "mesh.h"
#include <tinyply.h>
#include <algorithm>
#include <cctype>
#include <cerrno>
#include <cstdint>
#include <iterator>
#include <fstream>
#include <functional>
#include <map>
#include <string>
#include <tuple>
#include <vector>
#include <cassert>
bool operator <(const Vector3 &lhs, const Vector3 &rhs)
{
return std::tie(lhs.x, lhs.y, lhs.z) < std::tie(rhs.x, rhs.y, rhs.z);
}
namespace
{
enum class WavefrontWarning
{
UnknownToken = (1 << 0),
NotImplemented = (1 << 1),
};
enum class WavefrontError
{
Syntax = (1 << 0),
InvalidStatement = (1 << 1),
};
enum class WavefrontToken
{
Unknown,
Comment,
Vertex,
VertexTexture,
VertexNormal,
VertexParameter,
PolygonPoint,
PolygonLine,
PolygonFace,
};
WavefrontToken str2token(const std::string::const_iterator begin, const std::string::const_iterator end)
{
const auto length = std::distance(begin, end);
if (*begin == '#')
{
return WavefrontToken::Comment;
}
if (*begin == 'v')
{
if (length == 1)
{
return WavefrontToken::Vertex;
}
if (length == 2)
{
const char secondChar = *(begin + 1);
if (secondChar == 't') return WavefrontToken::VertexTexture;
if (secondChar == 'n') return WavefrontToken::VertexNormal;
if (secondChar == 'p') return WavefrontToken::VertexParameter;
}
}
if (*begin == 'p')
{
if (length == 1) return WavefrontToken::PolygonPoint;
}
if (*begin == 'l')
{
if (length == 1) return WavefrontToken::PolygonLine;
}
if (*begin == 'f')
{
if (length == 1) return WavefrontToken::PolygonFace;
}
return WavefrontToken::Unknown;
}
std::string::const_iterator findFirstNoEmpty(const std::string::const_iterator &begin, const std::string::const_iterator &end)
{
return std::find_if(begin, end, std::not1(std::ptr_fun<int, int>(std::isspace)));
}
std::string::const_iterator findFirstEmpty(const std::string::const_iterator &begin, const std::string::const_iterator &end)
{
return std::find_if(begin, end, std::isspace);
}
bool readFloat(const char *&strPtr, float &value, bool required = true)
{
char *end;
errno = 0;
value = static_cast<float>(std::strtod(strPtr, &end));
if (required && strPtr == end) return false;
strPtr = end;
return errno == 0;
}
bool readInt(const char *&strPtr, int &value, bool required = true)
{
char *end;
errno = 0;
value = static_cast<int>(std::strtol(strPtr, &end, 10));
if (required && strPtr == end) return false;
strPtr = end;
return errno == 0;
}
bool consumeCharacter(const char *&strPtr, char c)
{
if (*strPtr == c)
{
++strPtr;
return true;
}
return false;
}
void consumeSpaces(const char *&strPtr)
{
while (std::isspace(*strPtr))
{
++strPtr;
}
}
bool isEndOfLine(const char *strPtr)
{
while (*strPtr)
{
if (!std::isspace(*strPtr)) return false;
++strPtr;
}
return true;
}
struct WavefrontVertex
{
float x, y, z, w;
};
struct WavefrontTexcoord
{
float u, v, w;
};
struct WavefrontNormal
{
float i, j, k;
};
struct WavefrontFaceVertex
{
int vertexIndex;
int texcoordIndex;
int normalIndex;
};
struct WavefrontFaceEntryPoint
{
size_t start;
size_t vertexCount;
};
enum class WavefrontFaceOptions
{
HasTexcoord = (1 << 0),
HasNormal = (1 << 1),
};
bool operator <(const WavefrontFaceVertex &lhs, const WavefrontFaceVertex &rhs)
{
return std::tie(lhs.vertexIndex, lhs.texcoordIndex, lhs.normalIndex) < std::tie(rhs.vertexIndex, rhs.texcoordIndex, rhs.normalIndex);
}
template <typename T, typename E>
class Bitmask
{
public:
Bitmask() : mask(0) {}
Bitmask(T m) : mask(m) {}
Bitmask(E e) : mask(static_cast<T>(e)) {}
Bitmask operator|(Bitmask b) { return Bitmask(mask | b.mask); }
Bitmask& operator|=(E e) { mask |= static_cast<T>(e); return *this; }
Bitmask& operator|=(Bitmask rhs) { mask |= rhs.mask; return *this; }
bool has(E e) { return mask & static_cast<T>(e); }
private:
T mask;
};
#define DeclareBitmask(T,E) \
Bitmask<T,E> operator|(E a, E b) { return Bitmask<T,E>(a) | Bitmask<T,E>(b); } \
using Bitmask_ ## E = Bitmask<T, E>;
DeclareBitmask(uint32_t, WavefrontFaceOptions)
}
#if DEBUG
#define exit_on_fail(x) if (!(x)) { errors |= static_cast<uint32_t>(WavefrontError::Syntax); return nullptr; }
#else
#define exit_on_fail(x) if (!(x)) { return nullptr; }
#endif
Mesh* Mesh::loadWavefrontObj(const char *path)
{
#if DEBUG
uint32_t warnings = 0u;
uint32_t errors = 0u;
#endif
Bitmask_WavefrontFaceOptions faceOptions;
bool faceOptionsInitialzed = false;
std::vector<WavefrontVertex> vertices;
std::vector<WavefrontTexcoord> texcoords;
std::vector<WavefrontNormal> normals;
std::vector<WavefrontFaceEntryPoint> faces;
std::vector<WavefrontFaceVertex> faceVertices;
std::ifstream ifs;
ifs.open(path, std::ifstream::in);
std::string line;
while (std::getline(ifs, line))
{
if (line.size() == 0) continue; // Empty line
const auto firstTokenBegin = findFirstNoEmpty(line.begin(), line.end());
const auto firstTokenEnd = findFirstEmpty(firstTokenBegin, line.end());
if (firstTokenBegin == line.end()) continue; // Empty line
const WavefrontToken token = str2token(firstTokenBegin, firstTokenEnd);
switch (token)
{
case WavefrontToken::Comment:
{
continue;
} break;
case WavefrontToken::Vertex:
{
float x, y, z, w;
const char *ptr = &(*firstTokenEnd);
exit_on_fail(readFloat(ptr, x));
exit_on_fail(readFloat(ptr, y));
exit_on_fail(readFloat(ptr, z));
exit_on_fail(readFloat(ptr, w, false));
exit_on_fail(isEndOfLine(ptr));
vertices.emplace_back(WavefrontVertex{ x, y, z, w });
} break;
case WavefrontToken::VertexTexture:
{
float u, v, w;
const char *ptr = &(*firstTokenEnd);
exit_on_fail(readFloat(ptr, u));
exit_on_fail(readFloat(ptr, v));
exit_on_fail(readFloat(ptr, w, false));
exit_on_fail(isEndOfLine(ptr));
texcoords.emplace_back(WavefrontTexcoord{ u, v, w });
} break;
case WavefrontToken::VertexNormal:
{
float i, j, k;
const char *ptr = &(*firstTokenEnd);
exit_on_fail(readFloat(ptr, i));
exit_on_fail(readFloat(ptr, j));
exit_on_fail(readFloat(ptr, k));
exit_on_fail(isEndOfLine(ptr));
normals.emplace_back(WavefrontNormal{ i, j, k });
} break;
case WavefrontToken::PolygonFace:
{
WavefrontFaceEntryPoint entryPoint;
entryPoint.start = faceVertices.size();
entryPoint.vertexCount = 0;
const char *ptr = &(*firstTokenEnd);
while (!isEndOfLine(ptr))
{
WavefrontFaceVertex v;
v.texcoordIndex = 0;
v.normalIndex = 0;
exit_on_fail(readInt(ptr, v.vertexIndex));
if (consumeCharacter(ptr, '/')) exit_on_fail(readInt(ptr, v.texcoordIndex, false));
if (consumeCharacter(ptr, '/')) exit_on_fail(readInt(ptr, v.normalIndex));
if (!faceOptionsInitialzed)
{
if (v.texcoordIndex != 0) faceOptions |= WavefrontFaceOptions::HasTexcoord;
if (v.normalIndex != 0) faceOptions |= WavefrontFaceOptions::HasNormal;
faceOptionsInitialzed = true;
}
else
{
exit_on_fail((v.texcoordIndex != 0) == faceOptions.has(WavefrontFaceOptions::HasTexcoord));
exit_on_fail((v.normalIndex != 0) == faceOptions.has(WavefrontFaceOptions::HasNormal));
}
++entryPoint.vertexCount;
faceVertices.emplace_back(v);
consumeSpaces(ptr);
}
if (entryPoint.vertexCount < 3)
{
#if DEBUG
errors |= static_cast<uint32_t>(WavefrontError::InvalidStatement);
return nullptr;
#endif
}
faces.emplace_back(entryPoint);
} break;
case WavefrontToken::VertexParameter:
case WavefrontToken::PolygonPoint:
case WavefrontToken::PolygonLine:
{
#if DEBUG
warnings |= static_cast<uint32_t>(WavefrontWarning::NotImplemented);
#endif
}
case WavefrontToken::Unknown:
default:
{
#if DEBUG
warnings |= static_cast<uint32_t>(WavefrontWarning::UnknownToken);
#endif
}
}
}
ifs.close();
Mesh *mesh = new Mesh();
mesh->positions.reserve(vertices.size());
for (const auto &v : vertices) mesh->positions.push_back(Vector3(v.x, v.y, v.z));
mesh->texcoords.reserve(texcoords.size());
for (const auto &t : texcoords) mesh->texcoords.push_back(Vector2(t.u, t.v));
mesh->normals.reserve(normals.size());
for (const auto &n : normals) mesh->normals.push_back(Vector3(n.i, n.j, n.k));
#if 0
std::map<WavefrontFaceVertex, uint32_t> vertexIndices; // Shared vertices map
for (const auto &face : faces)
{
uint32_t firstVertexIdx = UINT32_MAX;
uint32_t previousVertexIdx = UINT32_MAX;
for (size_t i = 0; i < face.vertexCount; ++i)
{
uint32_t vertexIdx = UINT32_MAX;
{
const auto &v = faceVertices[face.start + i];
auto it = vertexIndices.find(v);
if (it == vertexIndices.end())
{
const uint32_t pidx = (uint32_t)(v.vertexIndex - 1);
const uint32_t tidx = v.texcoordIndex != 0 ? (uint32_t)(v.texcoordIndex - 1) : UINT32_MAX;
const uint32_t nidx = v.normalIndex != 0 ? (uint32_t)(v.normalIndex - 1) : UINT32_MAX;
vertexIdx = (uint32_t)mesh->vertices.size();
vertexIndices[v] = vertexIdx;
mesh->vertices.emplace_back(Mesh::Vertex{ pidx, tidx, nidx });
}
else
{
vertexIdx = it->second;
}
}
if (firstVertexIdx == UINT32_MAX)
{
firstVertexIdx = vertexIdx;
}
else if (previousVertexIdx == UINT32_MAX)
{
previousVertexIdx = vertexIdx;
}
else
{
mesh->triangles.emplace_back(Mesh::Triangle{ firstVertexIdx, previousVertexIdx, vertexIdx });
previousVertexIdx = vertexIdx;
}
}
}
#else
for (const auto &face : faces)
{
uint32_t firstVertexIdx = UINT32_MAX;
uint32_t previousVertexIdx = UINT32_MAX;
for (size_t i = 0; i < face.vertexCount; ++i)
{
uint32_t vertexIdx = UINT32_MAX;
{
const auto &v = faceVertices[face.start + i];
const uint32_t pidx = (uint32_t)(v.vertexIndex - 1);
const uint32_t tidx = v.texcoordIndex != 0 ? (uint32_t)(v.texcoordIndex - 1) : UINT32_MAX;
const uint32_t nidx = v.normalIndex != 0 ? (uint32_t)(v.normalIndex - 1) : UINT32_MAX;
vertexIdx = (uint32_t)mesh->vertices.size();
mesh->vertices.emplace_back(Mesh::Vertex{ pidx, tidx, nidx });
}
if (firstVertexIdx == UINT32_MAX)
{
firstVertexIdx = vertexIdx;
}
else if (previousVertexIdx == UINT32_MAX)
{
previousVertexIdx = vertexIdx;
}
else
{
mesh->triangles.emplace_back(Mesh::Triangle{ firstVertexIdx, previousVertexIdx, vertexIdx });
previousVertexIdx = vertexIdx;
}
}
}
#endif
return mesh;
}
namespace
{
void copyPlyData(std::shared_ptr<tinyply::PlyData> src, std::vector<Vector3> &dst)
{
dst.clear();
dst.reserve(src->count);
switch (src->t)
{
case tinyply::Type::FLOAT32:
{
const Vector3 *data = reinterpret_cast<const Vector3 *>(src->buffer.get());
for (size_t i = 0; i < src->count; ++i)
{
dst.push_back(data[i]);
}
} break;
case tinyply::Type::FLOAT64:
{
struct Vector3d { double x, y, z; };
const Vector3d *data = reinterpret_cast<const Vector3d *>(src->buffer.get());
for (size_t i = 0; i < src->count; ++i)
{
dst.push_back(Vector3(float(data[i].x), float(data[i].y), float(data[i].z)));
}
} break;
}
}
void copyPlyData(std::shared_ptr<tinyply::PlyData> src, std::vector<Vector2> &dst)
{
dst.clear();
dst.reserve(src->count);
switch (src->t)
{
case tinyply::Type::FLOAT32:
{
const Vector2 *data = reinterpret_cast<const Vector2 *>(src->buffer.get());
for (size_t i = 0; i < src->count; ++i)
{
dst.push_back(data[i]);
}
} break;
case tinyply::Type::FLOAT64:
{
struct Vector2d { double x, y; };
const Vector2d *data = reinterpret_cast<const Vector2d *>(src->buffer.get());
for (size_t i = 0; i < src->count; ++i)
{
dst.push_back(Vector2(float(data[i].x), float(data[i].y)));
}
} break;
}
}
}
Mesh* Mesh::loadPly(const char *path)
{
enum class NormalsFrom { Nowhere, Face, Vertex };
try
{
std::ifstream ss(path, std::ios::binary);
tinyply::PlyFile file;
file.parse_header(ss);
std::shared_ptr<tinyply::PlyData> verts;
std::shared_ptr<tinyply::PlyData> norms;
std::shared_ptr<tinyply::PlyData> uvs;
std::shared_ptr<tinyply::PlyData> faces;
verts = file.request_properties_from_element("vertex", { "x", "y", "z" });
faces = file.request_properties_from_element("face", { "vertex_indices" });
try { uvs = file.request_properties_from_element("vertex", { "s", "t" }); }
catch (const std::exception &e) {}
NormalsFrom normalsFrom = NormalsFrom::Nowhere;
if (!norms)
{
try
{
norms = file.request_properties_from_element("vertex", { "nx", "ny", "nz" });
normalsFrom = NormalsFrom::Vertex;
}
catch (const std::exception &e) {}
}
if (!norms)
{
try
{
norms = file.request_properties_from_element("face", { "nx", "ny", "nz" });
normalsFrom = NormalsFrom::Face;
}
catch (const std::exception &e) {}
}
file.read(ss);
Mesh *mesh = new Mesh();
copyPlyData(verts, mesh->positions);
copyPlyData(uvs, mesh->texcoords);
copyPlyData(norms, mesh->normals);
const size_t tricount = faces->count;
mesh->triangles.reserve(tricount);
uint32_t normal_idx = UINT32_MAX;
auto &get_face_vertex_idx = [&](const size_t i)
{
switch (faces->t)
{
case tinyply::Type::UINT32: return reinterpret_cast<const uint32_t*>(faces->buffer.get())[i];
case tinyply::Type::UINT16: return uint32_t(reinterpret_cast<const uint16_t*>(faces->buffer.get())[i]);
}
return UINT32_MAX;
};
for (size_t i = 0; i < tricount; ++i)
{
const uint32_t vstart = mesh->vertices.size();
if (normalsFrom == NormalsFrom::Face) { normal_idx = i * 3; }
for (size_t j = 0; j < 3; ++j)
{
const uint32_t vidx = get_face_vertex_idx(i * 3 + j);
if (normalsFrom == NormalsFrom::Vertex) { normal_idx = vidx; }
mesh->vertices.emplace_back(Mesh::Vertex{ vidx, (!uvs) ? UINT32_MAX : vidx, normal_idx });
}
mesh->triangles.emplace_back(Mesh::Triangle{ vstart, vstart + 1, vstart + 2 });
}
return mesh;
}
catch (const std::exception &e)
{
return nullptr;
}
}
namespace
{
bool endsWith(const std::string &str, const std::string &ending)
{
if (ending.size() > str.size()) return false;
return std::equal(ending.rbegin(), ending.rend(), str.rbegin());
}
}
Mesh * Mesh::loadFile(const char * path)
{
if (endsWith(path, ".obj")) return loadWavefrontObj(path);
if (endsWith(path, ".ply")) return loadPly(path);
return nullptr;
}
Mesh* Mesh::createCopy(const Mesh *mesh)
{
assert(mesh);
Mesh* r = new Mesh();
*r = *mesh;
return r;
}
void Mesh::computeFaceNormals()
{
normals.clear();
for (const auto &tri : triangles)
{
auto &v0 = vertices[tri.vertexIndex0];
auto &v1 = vertices[tri.vertexIndex1];
auto &v2 = vertices[tri.vertexIndex2];
const Vector3 p0 = positions[v0.positionIndex];
const Vector3 p1 = positions[v1.positionIndex];
const Vector3 p2 = positions[v2.positionIndex];
const Vector3 n = normalize(cross(p1 - p0, p2 - p0));
const uint32_t nidx = (uint32_t)normals.size();
normals.emplace_back(n);
v0.normalIndex = nidx;
v1.normalIndex = nidx;
v2.normalIndex = nidx;
}
}
// TODO: Improve algorithm
// Face weighting?
void Mesh::computeVertexNormals()
{
normals.clear();
normals.resize(positions.size());
for (const auto &tri : triangles)
{
auto &v0 = vertices[tri.vertexIndex0];
auto &v1 = vertices[tri.vertexIndex1];
auto &v2 = vertices[tri.vertexIndex2];
const Vector3 p0 = positions[v0.positionIndex];
const Vector3 p1 = positions[v1.positionIndex];
const Vector3 p2 = positions[v2.positionIndex];
const Vector3 n = normalize(cross(p1 - p0, p2 - p0));
normals[v0.positionIndex] += n;
normals[v1.positionIndex] += n;
normals[v2.positionIndex] += n;
}
for (auto &n : normals)
{
n = normalize(n);
}
for (auto &v : vertices)
{
v.normalIndex = v.positionIndex;
}
}
void Mesh::computeVertexNormalsAggressive()
{
struct NormalData { Vector3 normal = Vector3(); uint32_t index = 0; };
std::map<Vector3, NormalData> normalsMap;
auto addNormal = [&](const Vector3 &p, const Vector3 &n)
{
auto it = normalsMap.find(p);
if (it != normalsMap.end())
{
it->second.normal += n;
return it->second.index;
}
else
{
const uint32_t index = uint32_t(normalsMap.size());
normalsMap[p] = NormalData{ n, index };
return index;
}
};
for (const auto &tri : triangles)
{
auto &v0 = vertices[tri.vertexIndex0];
auto &v1 = vertices[tri.vertexIndex1];
auto &v2 = vertices[tri.vertexIndex2];
const Vector3 p0 = positions[v0.positionIndex];
const Vector3 p1 = positions[v1.positionIndex];
const Vector3 p2 = positions[v2.positionIndex];
const Vector3 n = normalize(cross(p1 - p0, p2 - p0));
v0.normalIndex = addNormal(p0, n);
v1.normalIndex = addNormal(p1, n);
v2.normalIndex = addNormal(p2, n);
}
normals.clear();
normals.resize(normalsMap.size());
for (auto &n : normalsMap)
{
normals[n.second.index] = normalize(n.second.normal);
}
}
// TODO: Improve algorithm
void Mesh::computeTangentSpace()
{
tangents.clear();
bitangents.clear();
tangents.resize(vertices.size());
bitangents.resize(vertices.size());
for (const auto &tri : triangles)
{
const auto &v0 = vertices[tri.vertexIndex0];
const auto &v1 = vertices[tri.vertexIndex1];
const auto &v2 = vertices[tri.vertexIndex2];
const Vector3 p0 = positions[v0.positionIndex];
const Vector3 p1 = positions[v1.positionIndex];
const Vector3 p2 = positions[v2.positionIndex];
const Vector2 u0 = texcoords[v0.texcoordIndex];
const Vector2 u1 = texcoords[v1.texcoordIndex];
const Vector2 u2 = texcoords[v2.texcoordIndex];
const Vector3 e0 = p1 - p0;
const Vector3 e1 = p2 - p0;
const Vector2 t0 = u1 - u0;
const Vector2 t1 = u2 - u0;
const float r = 1.0f / (t0.x * t1.y - t1.x * t0.y);
const Vector3 sdir = (e0 * t1.y - e1 * t0.y) * r;
const Vector3 tdir = (e1 * t0.x - e0 * t1.x) * r;
tangents[tri.vertexIndex0] += sdir;
tangents[tri.vertexIndex1] += sdir;
tangents[tri.vertexIndex2] += sdir;
bitangents[tri.vertexIndex0] += tdir;
bitangents[tri.vertexIndex1] += tdir;
bitangents[tri.vertexIndex2] += tdir;
}
for (size_t i = 0; i < tangents.size(); ++i)
{
const Vector3 n = normals[vertices[i].normalIndex];
const Vector3 t1 = tangents[i];
const Vector3 t2 = bitangents[i];
tangents[i] = normalize(t1 - n * dot(n, t1));
bitangents[i] = cross(n, tangents[i]);
if (dot(cross(n, t1), t2) < 0.0f) bitangents[i] = -bitangents[i];
}
}
bool Mesh::intersect(const Vector3 &o, const Vector3 &d, IntersectResult &o_result) const
{
bool intersected = false;
for (size_t tidx = 0; tidx < triangles.size(); ++tidx)
{
IntersectResult r;
if (intersect(o, d, (uint32_t)tidx, r))
{
if (!intersected || o_result.distance > r.distance)
{
o_result = r;
intersected = true;
}
}
}
return intersected;
}
bool Mesh::intersect(const Vector3 &o, const Vector3 &d, const uint32_t tidx, IntersectResult &o_result) const
{
const float epsilon = 1e-6f;
const Triangle &tri = triangles[tidx];
const Vector3 v0 = positions[vertices[tri.vertexIndex0].positionIndex];
const Vector3 v1 = positions[vertices[tri.vertexIndex1].positionIndex];
const Vector3 v2 = positions[vertices[tri.vertexIndex2].positionIndex];
// Moller-Trumbore algorithm
const Vector3 e0 = v1 - v0;
const Vector3 e1 = v2 - v0;
const Vector3 h = cross(d, e1);
const float a = dot(e0, h);
if (a > -epsilon && a < epsilon) return false;
const float f = 1.0f / a;
const Vector3 s = o - v0;
const float u = f * dot(s, h);
if (u < 0.0f || u > 1.0f) return false;
const Vector3 q = cross(s, e0);
const float v = f * dot(d, q);
if (v < 0.0f || (u + v) > 1.0f) return false;
const float t = f * dot(e1, q);
if (t < epsilon) return false;
o_result.tidx = tidx;
o_result.distance = t;
return true;
}
void Mesh::intersectAll(const Vector3 *origins, const Vector3 *directions, IntersectResult *o_results, size_t count) const
{
const float epsilon = 1e-6f;
for (size_t tidx = 0; tidx < triangles.size(); ++tidx)
{
const Triangle &tri = triangles[tidx];
const Vector3 v0 = positions[vertices[tri.vertexIndex0].positionIndex];
const Vector3 v1 = positions[vertices[tri.vertexIndex1].positionIndex];
const Vector3 v2 = positions[vertices[tri.vertexIndex2].positionIndex];
// Moller-Trumbore algorithm
const Vector3 e0 = v1 - v0;
const Vector3 e1 = v2 - v0;
for (size_t i = 0; i < count; ++i)
{
const Vector3 d = directions[i];
const Vector3 o = origins[i];
const Vector3 h = cross(d, e1);
const float a = dot(e0, h);
if (a < -epsilon || a > epsilon)
{
const float f = 1.0f / a;
const Vector3 s = o - v0;
const float u = f * dot(s, h);
if (u >= 0.0f && u <= 1.0f)
{
const Vector3 q = cross(s, e0);
const float v = f * dot(d, q);
if (v >= 0.0f && (u + v) <= 1.0f)
{
const float t = f * dot(e1, q);
if (t >= epsilon)
{
o_results[i].tidx = (uint32_t)tidx;
o_results[i].distance = t;
}
}
}
}
}
}
}
|
// Copyright (c) 2009-2014 The Polcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcserver.h"
#include "chainparams.h"
#include "clientversion.h"
#include "main.h"
#include "net.h"
#include "netbase.h"
#include "protocol.h"
#include "sync.h"
#include "timedata.h"
#include "ui_interface.h"
#include "util.h"
#include "utilstrencodings.h"
#include "version.h"
#include <boost/foreach.hpp>
#include <univalue.h>
using namespace std;
UniValue getconnectioncount(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getconnectioncount\n"
"\nReturns the number of connections to other nodes.\n"
"\nbResult:\n"
"n (numeric) The connection count\n"
"\nExamples:\n"
+ HelpExampleCli("getconnectioncount", "")
+ HelpExampleRpc("getconnectioncount", "")
);
LOCK2(cs_main, cs_vNodes);
return (int)vNodes.size();
}
UniValue ping(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"ping\n"
"\nRequests that a ping be sent to all other nodes, to measure ping time.\n"
"Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n"
"Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.\n"
"\nExamples:\n"
+ HelpExampleCli("ping", "")
+ HelpExampleRpc("ping", "")
);
// Request that each node send a ping during next message processing pass
LOCK2(cs_main, cs_vNodes);
BOOST_FOREACH(CNode* pNode, vNodes) {
pNode->fPingQueued = true;
}
return NullUniValue;
}
static void CopyNodeStats(std::vector<CNodeStats>& vstats)
{
vstats.clear();
LOCK(cs_vNodes);
vstats.reserve(vNodes.size());
BOOST_FOREACH(CNode* pnode, vNodes) {
CNodeStats stats;
pnode->copyStats(stats);
vstats.push_back(stats);
}
}
UniValue getpeerinfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getpeerinfo\n"
"\nReturns data about each connected network node as a json array of objects.\n"
"\nbResult:\n"
"[\n"
" {\n"
" \"id\": n, (numeric) Peer index\n"
" \"addr\":\"host:port\", (string) The ip address and port of the peer\n"
" \"addrlocal\":\"ip:port\", (string) local address\n"
" \"services\":\"xxxxxxxxxxxxxxxx\", (string) The services offered\n"
" \"lastsend\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last send\n"
" \"lastrecv\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last receive\n"
" \"bytessent\": n, (numeric) The total bytes sent\n"
" \"bytesrecv\": n, (numeric) The total bytes received\n"
" \"conntime\": ttt, (numeric) The connection time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"timeoffset\": ttt, (numeric) The time offset in seconds\n"
" \"pingtime\": n, (numeric) ping time\n"
" \"minping\": n, (numeric) minimum observed ping time\n"
" \"pingwait\": n, (numeric) ping wait\n"
" \"version\": v, (numeric) The peer version, such as 7001\n"
" \"subver\": \"/Satoshi:0.8.5/\", (string) The string version\n"
" \"inbound\": true|false, (boolean) Inbound (true) or Outbound (false)\n"
" \"startingheight\": n, (numeric) The starting height (block) of the peer\n"
" \"banscore\": n, (numeric) The ban score\n"
" \"synced_headers\": n, (numeric) The last header we have in common with this peer\n"
" \"synced_blocks\": n, (numeric) The last block we have in common with this peer\n"
" \"inflight\": [\n"
" n, (numeric) The heights of blocks we're currently asking from this peer\n"
" ...\n"
" ]\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getpeerinfo", "")
+ HelpExampleRpc("getpeerinfo", "")
);
LOCK(cs_main);
vector<CNodeStats> vstats;
CopyNodeStats(vstats);
UniValue ret(UniValue::VARR);
BOOST_FOREACH(const CNodeStats& stats, vstats) {
UniValue obj(UniValue::VOBJ);
CNodeStateStats statestats;
bool fStateStats = GetNodeStateStats(stats.nodeid, statestats);
obj.push_back(Pair("id", stats.nodeid));
obj.push_back(Pair("addr", stats.addrName));
if (!(stats.addrLocal.empty()))
obj.push_back(Pair("addrlocal", stats.addrLocal));
obj.push_back(Pair("services", strprintf("%016x", stats.nServices)));
obj.push_back(Pair("lastsend", stats.nLastSend));
obj.push_back(Pair("lastrecv", stats.nLastRecv));
obj.push_back(Pair("bytessent", stats.nSendBytes));
obj.push_back(Pair("bytesrecv", stats.nRecvBytes));
obj.push_back(Pair("blocksrequested", stats.nBlocksRequested));
obj.push_back(Pair("conntime", stats.nTimeConnected));
obj.push_back(Pair("timeoffset", stats.nTimeOffset));
obj.push_back(Pair("pingtime", stats.dPingTime));
obj.push_back(Pair("minping", stats.dPingMin));
if (stats.dPingWait > 0.0)
obj.push_back(Pair("pingwait", stats.dPingWait));
obj.push_back(Pair("version", stats.nVersion));
// Use the sanitized form of subver here, to avoid tricksy remote peers from
// corrupting or modifiying the JSON output by putting special characters in
// their ver message.
obj.push_back(Pair("subver", stats.cleanSubVer));
obj.push_back(Pair("inbound", stats.fInbound));
obj.push_back(Pair("startingheight", stats.nStartingHeight));
if (fStateStats) {
obj.push_back(Pair("banscore", statestats.nMisbehavior));
obj.push_back(Pair("synced_headers", statestats.nSyncHeight));
obj.push_back(Pair("synced_blocks", statestats.nCommonHeight));
UniValue heights(UniValue::VARR);
BOOST_FOREACH(int height, statestats.vHeightInFlight) {
heights.push_back(height);
}
obj.push_back(Pair("inflight", heights));
}
obj.push_back(Pair("whitelisted", stats.fWhitelisted));
ret.push_back(obj);
}
return ret;
}
UniValue addnode(const UniValue& params, bool fHelp)
{
string strCommand;
if (params.size() == 2)
strCommand = params[1].get_str();
if (fHelp || params.size() != 2 ||
(strCommand != "onetry" && strCommand != "add" && strCommand != "remove"))
throw runtime_error(
"addnode \"node\" \"add|remove|onetry\"\n"
"\nAttempts add or remove a node from the addnode list.\n"
"Or try a connection to a node once.\n"
"\nArguments:\n"
"1. \"node\" (string, required) The node (see getpeerinfo for nodes)\n"
"2. \"command\" (string, required) 'add' to add a node to the list, 'remove' to remove a node from the list, 'onetry' to try a connection to the node once\n"
"\nExamples:\n"
+ HelpExampleCli("addnode", "\"192.168.0.6:9338\" \"onetry\"")
+ HelpExampleRpc("addnode", "\"192.168.0.6:9338\", \"onetry\"")
);
string strNode = params[0].get_str();
if (strCommand == "onetry")
{
CAddress addr;
OpenNetworkConnection(addr, NULL, strNode.c_str());
return NullUniValue;
}
LOCK(cs_vAddedNodes);
vector<string>::iterator it = vAddedNodes.begin();
for(; it != vAddedNodes.end(); it++)
if (strNode == *it)
break;
if (strCommand == "add")
{
if (it != vAddedNodes.end())
throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: Node already added");
vAddedNodes.push_back(strNode);
}
else if(strCommand == "remove")
{
if (it == vAddedNodes.end())
throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added.");
vAddedNodes.erase(it);
}
return NullUniValue;
}
UniValue disconnectnode(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"disconnectnode \"node\" \n"
"\nImmediately disconnects from the specified node.\n"
"\nArguments:\n"
"1. \"node\" (string, required) The node (see getpeerinfo for nodes)\n"
"\nExamples:\n"
+ HelpExampleCli("disconnectnode", "\"192.168.0.6:9338\"")
+ HelpExampleRpc("disconnectnode", "\"192.168.0.6:9338\"")
);
CNode* pNode = FindNode(params[0].get_str());
if (pNode == NULL)
throw JSONRPCError(RPC_CLIENT_NODE_NOT_CONNECTED, "Node not found in connected nodes");
pNode->fDisconnect = true;
return NullUniValue;
}
UniValue getaddednodeinfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getaddednodeinfo dns ( \"node\" )\n"
"\nReturns information about the given added node, or all added nodes\n"
"(note that onetry addnodes are not listed here)\n"
"If dns is false, only a list of added nodes will be provided,\n"
"otherwise connected information will also be available.\n"
"\nArguments:\n"
"1. dns (boolean, required) If false, only a list of added nodes will be provided, otherwise connected information will also be available.\n"
"2. \"node\" (string, optional) If provided, return information about this specific node, otherwise all nodes are returned.\n"
"\nResult:\n"
"[\n"
" {\n"
" \"addednode\" : \"192.168.0.201\", (string) The node ip address\n"
" \"connected\" : true|false, (boolean) If connected\n"
" \"addresses\" : [\n"
" {\n"
" \"address\" : \"192.168.0.201:9338\", (string) The Polcoin server host and port\n"
" \"connected\" : \"outbound\" (string) connection, inbound or outbound\n"
" }\n"
" ,...\n"
" ]\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getaddednodeinfo", "true")
+ HelpExampleCli("getaddednodeinfo", "true \"192.168.0.201\"")
+ HelpExampleRpc("getaddednodeinfo", "true, \"192.168.0.201\"")
);
bool fDns = params[0].get_bool();
list<string> laddedNodes(0);
if (params.size() == 1)
{
LOCK(cs_vAddedNodes);
BOOST_FOREACH(const std::string& strAddNode, vAddedNodes)
laddedNodes.push_back(strAddNode);
}
else
{
string strNode = params[1].get_str();
LOCK(cs_vAddedNodes);
BOOST_FOREACH(const std::string& strAddNode, vAddedNodes) {
if (strAddNode == strNode)
{
laddedNodes.push_back(strAddNode);
break;
}
}
if (laddedNodes.size() == 0)
throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added.");
}
UniValue ret(UniValue::VARR);
if (!fDns)
{
BOOST_FOREACH (const std::string& strAddNode, laddedNodes) {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("addednode", strAddNode));
ret.push_back(obj);
}
return ret;
}
list<pair<string, vector<CService> > > laddedAddreses(0);
BOOST_FOREACH(const std::string& strAddNode, laddedNodes) {
vector<CService> vservNode(0);
if(Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0))
laddedAddreses.push_back(make_pair(strAddNode, vservNode));
else
{
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("addednode", strAddNode));
obj.push_back(Pair("connected", false));
UniValue addresses(UniValue::VARR);
obj.push_back(Pair("addresses", addresses));
}
}
LOCK(cs_vNodes);
for (list<pair<string, vector<CService> > >::iterator it = laddedAddreses.begin(); it != laddedAddreses.end(); it++)
{
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("addednode", it->first));
UniValue addresses(UniValue::VARR);
bool fConnected = false;
BOOST_FOREACH(const CService& addrNode, it->second) {
bool fFound = false;
UniValue node(UniValue::VOBJ);
node.push_back(Pair("address", addrNode.ToString()));
BOOST_FOREACH(CNode* pnode, vNodes) {
if (pnode->addr == addrNode)
{
fFound = true;
fConnected = true;
node.push_back(Pair("connected", pnode->fInbound ? "inbound" : "outbound"));
break;
}
}
if (!fFound)
node.push_back(Pair("connected", "false"));
addresses.push_back(node);
}
obj.push_back(Pair("connected", fConnected));
obj.push_back(Pair("addresses", addresses));
ret.push_back(obj);
}
return ret;
}
UniValue getnettotals(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"getnettotals\n"
"\nReturns information about network traffic, including bytes in, bytes out,\n"
"and current time.\n"
"\nResult:\n"
"{\n"
" \"totalbytesrecv\": n, (numeric) Total bytes received\n"
" \"totalbytessent\": n, (numeric) Total bytes sent\n"
" \"timemillis\": t (numeric) Total cpu time\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getnettotals", "")
+ HelpExampleRpc("getnettotals", "")
);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("totalbytesrecv", CNode::GetTotalBytesRecv()));
obj.push_back(Pair("totalbytessent", CNode::GetTotalBytesSent()));
obj.push_back(Pair("timemillis", GetTimeMillis()));
return obj;
}
static UniValue GetNetworksInfo()
{
UniValue networks(UniValue::VARR);
for(int n=0; n<NET_MAX; ++n)
{
enum Network network = static_cast<enum Network>(n);
if(network == NET_UNROUTABLE)
continue;
proxyType proxy;
UniValue obj(UniValue::VOBJ);
GetProxy(network, proxy);
obj.push_back(Pair("name", GetNetworkName(network)));
obj.push_back(Pair("limited", IsLimited(network)));
obj.push_back(Pair("reachable", IsReachable(network)));
obj.push_back(Pair("proxy", proxy.IsValid() ? proxy.proxy.ToStringIPPort() : string()));
obj.push_back(Pair("proxy_randomize_credentials", proxy.randomize_credentials));
networks.push_back(obj);
}
return networks;
}
UniValue getnetworkinfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getnetworkinfo\n"
"Returns an object containing various state info regarding P2P networking.\n"
"\nResult:\n"
"{\n"
" \"version\": xxxxx, (numeric) the server version\n"
" \"subversion\": \"/Satoshi:x.x.x/\", (string) the server subversion string\n"
" \"protocolversion\": xxxxx, (numeric) the protocol version\n"
" \"localservices\": \"xxxxxxxxxxxxxxxx\", (string) the services we offer to the network\n"
" \"timeoffset\": xxxxx, (numeric) the time offset\n"
" \"connections\": xxxxx, (numeric) the number of connections\n"
" \"networks\": [ (array) information per network\n"
" {\n"
" \"name\": \"xxx\", (string) network (ipv4, ipv6 or onion)\n"
" \"limited\": true|false, (boolean) is the network limited using -onlynet?\n"
" \"reachable\": true|false, (boolean) is the network reachable?\n"
" \"proxy\": \"host:port\" (string) the proxy that is used for this network, or empty if none\n"
" }\n"
" ,...\n"
" ],\n"
" \"relayfee\": x.xxxxxxxx, (numeric) minimum relay fee for non-free transactions in " + CURRENCY_UNIT + "/kB\n"
" \"localaddresses\": [ (array) list of local addresses\n"
" {\n"
" \"address\": \"xxxx\", (string) network address\n"
" \"port\": xxx, (numeric) network port\n"
" \"score\": xxx (numeric) relative score\n"
" }\n"
" ,...\n"
" ]\n"
" \"warnings\": \"...\" (string) any network warnings (such as alert messages) \n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getnetworkinfo", "")
+ HelpExampleRpc("getnetworkinfo", "")
);
LOCK(cs_main);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("version", CLIENT_VERSION));
obj.push_back(Pair("subversion", strSubVersion));
obj.push_back(Pair("protocolversion",PROTOCOL_VERSION));
obj.push_back(Pair("localservices", strprintf("%016x", nLocalServices)));
obj.push_back(Pair("timeoffset", GetTimeOffset()));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("networks", GetNetworksInfo()));
obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())));
UniValue localAddresses(UniValue::VARR);
{
LOCK(cs_mapLocalHost);
BOOST_FOREACH(const PAIRTYPE(CNetAddr, LocalServiceInfo) &item, mapLocalHost)
{
UniValue rec(UniValue::VOBJ);
rec.push_back(Pair("address", item.first.ToString()));
rec.push_back(Pair("port", item.second.nPort));
rec.push_back(Pair("score", item.second.nScore));
localAddresses.push_back(rec);
}
}
obj.push_back(Pair("localaddresses", localAddresses));
obj.push_back(Pair("warnings", GetWarnings("statusbar")));
return obj;
}
UniValue setban(const UniValue& params, bool fHelp)
{
string strCommand;
if (params.size() >= 2)
strCommand = params[1].get_str();
if (fHelp || params.size() < 2 ||
(strCommand != "add" && strCommand != "remove"))
throw runtime_error(
"setban \"ip(/netmask)\" \"add|remove\" (bantime) (absolute)\n"
"\nAttempts add or remove a IP/Subnet from the banned list.\n"
"\nArguments:\n"
"1. \"ip(/netmask)\" (string, required) The IP/Subnet (see getpeerinfo for nodes ip) with a optional netmask (default is /32 = single ip)\n"
"2. \"command\" (string, required) 'add' to add a IP/Subnet to the list, 'remove' to remove a IP/Subnet from the list\n"
"3. \"bantime\" (numeric, optional) time in seconds how long (or until when if [absolute] is set) the ip is banned (0 or empty means using the default time of 24h which can also be overwritten by the -bantime startup argument)\n"
"4. \"absolute\" (boolean, optional) If set, the bantime must be a absolute timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
"\nExamples:\n"
+ HelpExampleCli("setban", "\"192.168.0.6\" \"add\" 86400")
+ HelpExampleCli("setban", "\"192.168.0.0/24\" \"add\"")
+ HelpExampleRpc("setban", "\"192.168.0.6\", \"add\" 86400")
);
CSubNet subNet;
CNetAddr netAddr;
bool isSubnet = false;
if (params[0].get_str().find("/") != string::npos)
isSubnet = true;
if (!isSubnet)
netAddr = CNetAddr(params[0].get_str());
else
subNet = CSubNet(params[0].get_str());
if (! (isSubnet ? subNet.IsValid() : netAddr.IsValid()) )
throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: Invalid IP/Subnet");
if (strCommand == "add")
{
if (isSubnet ? CNode::IsBanned(subNet) : CNode::IsBanned(netAddr))
throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: IP/Subnet already banned");
int64_t banTime = 0; //use standard bantime if not specified
if (params.size() >= 3 && !params[2].isNull())
banTime = params[2].get_int64();
bool absolute = false;
if (params.size() == 4 && params[3].isTrue())
absolute = true;
isSubnet ? CNode::Ban(subNet, BanReasonManuallyAdded, banTime, absolute) : CNode::Ban(netAddr, BanReasonManuallyAdded, banTime, absolute);
//disconnect possible nodes
while(CNode *bannedNode = (isSubnet ? FindNode(subNet) : FindNode(netAddr)))
bannedNode->fDisconnect = true;
}
else if(strCommand == "remove")
{
if (!( isSubnet ? CNode::Unban(subNet) : CNode::Unban(netAddr) ))
throw JSONRPCError(RPC_MISC_ERROR, "Error: Unban failed");
}
DumpBanlist(); //store banlist to disk
uiInterface.BannedListChanged();
return NullUniValue;
}
UniValue listbanned(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"listbanned\n"
"\nList all banned IPs/Subnets.\n"
"\nExamples:\n"
+ HelpExampleCli("listbanned", "")
+ HelpExampleRpc("listbanned", "")
);
banmap_t banMap;
CNode::GetBanned(banMap);
UniValue bannedAddresses(UniValue::VARR);
for (banmap_t::iterator it = banMap.begin(); it != banMap.end(); it++)
{
CBanEntry banEntry = (*it).second;
UniValue rec(UniValue::VOBJ);
rec.push_back(Pair("address", (*it).first.ToString()));
rec.push_back(Pair("banned_until", banEntry.nBanUntil));
rec.push_back(Pair("ban_created", banEntry.nCreateTime));
rec.push_back(Pair("ban_reason", banEntry.banReasonToString()));
bannedAddresses.push_back(rec);
}
return bannedAddresses;
}
UniValue clearbanned(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"clearbanned\n"
"\nClear all banned IPs.\n"
"\nExamples:\n"
+ HelpExampleCli("clearbanned", "")
+ HelpExampleRpc("clearbanned", "")
);
CNode::ClearBanned();
DumpBanlist(); //store banlist to disk
uiInterface.BannedListChanged();
return NullUniValue;
}
|
//==================================================================================================
/*!
@file
@Copyright 2016 Numscale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_X86_SSE2_SIMD_FUNCTION_IS_GREATER_EQUAL_HPP_INCLUDED
#define BOOST_SIMD_ARCH_X86_SSE2_SIMD_FUNCTION_IS_GREATER_EQUAL_HPP_INCLUDED
#include <boost/simd/detail/overload.hpp>
#include <boost/simd/meta/as_logical.hpp>
#include <boost/simd/function/logical_not.hpp>
#include <boost/simd/function/is_less.hpp>
namespace boost { namespace simd { namespace ext
{
namespace bd = boost::dispatch;
namespace bs = boost::simd;
BOOST_DISPATCH_OVERLOAD ( is_greater_equal_
, (typename A0)
, bs::sse2_
, bs::pack_<bd::double_<A0>, bs::sse_>
, bs::pack_<bd::double_<A0>, bs::sse_>
)
{
BOOST_FORCEINLINE bs::as_logical_t<A0> operator() ( const A0 & a0
, const A0 & a1 ) const BOOST_NOEXCEPT
{
return _mm_cmpge_pd(a0,a1);
}
};
BOOST_DISPATCH_OVERLOAD ( is_greater_equal_
, (typename A0)
, bs::sse2_
, bs::pack_<bd::integer_<A0>, bs::sse_>
, bs::pack_<bd::integer_<A0>, bs::sse_>
)
{
BOOST_FORCEINLINE bs::as_logical_t<A0> operator() ( const A0 & a0
, const A0 & a1 ) const BOOST_NOEXCEPT
{
return bs::logical_not(bs::is_less(a0,a1));
}
};
} } }
#endif
|
version https://git-lfs.github.com/spec/v1
oid sha256:bcf06371b0513acdb8241c31768045904180dcaf8d7d114d75c7b9167ecb15f3
size 5231
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Copyright (c) 2020 The SmartUSD Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include <map>
#include "smartusd_curve25519.h"
#include "script/script.h"
#include "wallet/wallet.h"
#define KOMODO_ASSETCHAIN_MAXLEN 65
std::string ASSETCHAINS_SELFIMPORT;
std::string ASSETCHAINS_CCLIB = "";
std::map <std::int8_t, int32_t> mapHeightEvalActivate;
uint8_t ASSETCHAINS_CCDISABLES[256];
uint32_t ASSETCHAINS_CC = 2;
extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN]; // validation.cpp
uint16_t ASSETCHAINS_CODAPORT,ASSETCHAINS_BEAMPORT;
uint8_t ASSETCHAINS_OVERRIDE_PUBKEY33[33];
uint64_t ASSETCHAINS_PEGSCCPARAMS[3];
uint8_t ASSETCHAINS_MARMARA;
CScript SMARTUSD_EARLYTXID_SCRIPTPUB;
//int32_t CCActivationHeight = Params().GetConsensus().nCCActivationHeight;
//int32_t SMARTUSD_CONNECTING = -1;
int32_t ASSETCHAINS_BLOCKTIME = 60;
uint64_t ASSETCHAINS_CBOPRET=0;
uint8_t NOTARY_PUBKEY33[33];
uint256 SMARTUSD_EARLYTXID;
pthread_mutex_t KOMODO_CC_mutex;
int32_t SMARTUSD_INSYNC;
int32_t lastSnapShotHeight;
pthread_mutex_t staked_mutex;
#ifdef ENABLE_WALLET
CWallet* pwalletMain = NULL;
#endif
#define SMARTUSD_MAXPRICES 2048 // must be power of 2 and less than 8192
struct priceinfo
{
FILE *fp;
char symbol[64];
} PRICES[SMARTUSD_MAXPRICES];
extern char *bitcoin_base58encode(char *coinaddr,uint8_t *data,int32_t datalen);
//struct sha256_vstate { uint64_t length; uint32_t state[8],curlen; uint8_t buf[64]; };
//struct rmd160_vstate { uint64_t length; uint8_t buf[64]; uint32_t curlen, state[5]; };
// following is ported from libtom
#define STORE32L(x, y) \
{ (y)[3] = (uint8_t)(((x)>>24)&255); (y)[2] = (uint8_t)(((x)>>16)&255); \
(y)[1] = (uint8_t)(((x)>>8)&255); (y)[0] = (uint8_t)((x)&255); }
#define LOAD32L(x, y) \
{ x = (uint32_t)(((uint64_t)((y)[3] & 255)<<24) | \
((uint32_t)((y)[2] & 255)<<16) | \
((uint32_t)((y)[1] & 255)<<8) | \
((uint32_t)((y)[0] & 255))); }
#define STORE64L(x, y) \
{ (y)[7] = (uint8_t)(((x)>>56)&255); (y)[6] = (uint8_t)(((x)>>48)&255); \
(y)[5] = (uint8_t)(((x)>>40)&255); (y)[4] = (uint8_t)(((x)>>32)&255); \
(y)[3] = (uint8_t)(((x)>>24)&255); (y)[2] = (uint8_t)(((x)>>16)&255); \
(y)[1] = (uint8_t)(((x)>>8)&255); (y)[0] = (uint8_t)((x)&255); }
#define LOAD64L(x, y) \
{ x = (((uint64_t)((y)[7] & 255))<<56)|(((uint64_t)((y)[6] & 255))<<48)| \
(((uint64_t)((y)[5] & 255))<<40)|(((uint64_t)((y)[4] & 255))<<32)| \
(((uint64_t)((y)[3] & 255))<<24)|(((uint64_t)((y)[2] & 255))<<16)| \
(((uint64_t)((y)[1] & 255))<<8)|(((uint64_t)((y)[0] & 255))); }
#define STORE32H(x, y) \
{ (y)[0] = (uint8_t)(((x)>>24)&255); (y)[1] = (uint8_t)(((x)>>16)&255); \
(y)[2] = (uint8_t)(((x)>>8)&255); (y)[3] = (uint8_t)((x)&255); }
#define LOAD32H(x, y) \
{ x = (uint32_t)(((uint64_t)((y)[0] & 255)<<24) | \
((uint32_t)((y)[1] & 255)<<16) | \
((uint32_t)((y)[2] & 255)<<8) | \
((uint32_t)((y)[3] & 255))); }
#define STORE64H(x, y) \
{ (y)[0] = (uint8_t)(((x)>>56)&255); (y)[1] = (uint8_t)(((x)>>48)&255); \
(y)[2] = (uint8_t)(((x)>>40)&255); (y)[3] = (uint8_t)(((x)>>32)&255); \
(y)[4] = (uint8_t)(((x)>>24)&255); (y)[5] = (uint8_t)(((x)>>16)&255); \
(y)[6] = (uint8_t)(((x)>>8)&255); (y)[7] = (uint8_t)((x)&255); }
#define LOAD64H(x, y) \
{ x = (((uint64_t)((y)[0] & 255))<<56)|(((uint64_t)((y)[1] & 255))<<48) | \
(((uint64_t)((y)[2] & 255))<<40)|(((uint64_t)((y)[3] & 255))<<32) | \
(((uint64_t)((y)[4] & 255))<<24)|(((uint64_t)((y)[5] & 255))<<16) | \
(((uint64_t)((y)[6] & 255))<<8)|(((uint64_t)((y)[7] & 255))); }
// Various logical functions
#define RORc(x, y) ( ((((uint32_t)(x)&0xFFFFFFFFUL)>>(uint32_t)((y)&31)) | ((uint32_t)(x)<<(uint32_t)(32-((y)&31)))) & 0xFFFFFFFFUL)
#define Ch(x,y,z) (z ^ (x & (y ^ z)))
#define Maj(x,y,z) (((x | y) & z) | (x & y))
#define S(x, n) RORc((x),(n))
#define R(x, n) (((x)&0xFFFFFFFFUL)>>(n))
#define Sigma0(x) (S(x, 2) ^ S(x, 13) ^ S(x, 22))
#define Sigma1(x) (S(x, 6) ^ S(x, 11) ^ S(x, 25))
#define Gamma0(x) (S(x, 7) ^ S(x, 18) ^ R(x, 3))
#define Gamma1(x) (S(x, 17) ^ S(x, 19) ^ R(x, 10))
#define MIN(x, y) ( ((x)<(y))?(x):(y) )
static inline int32_t sha256_vcompress(struct sha256_vstate * md,uint8_t *buf)
{
uint32_t S[8],W[64],t0,t1,i;
for (i=0; i<8; i++) // copy state into S
S[i] = md->state[i];
for (i=0; i<16; i++) // copy the state into 512-bits into W[0..15]
LOAD32H(W[i],buf + (4*i));
for (i=16; i<64; i++) // fill W[16..63]
W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
#define RND(a,b,c,d,e,f,g,h,i,ki) \
t0 = h + Sigma1(e) + Ch(e, f, g) + ki + W[i]; \
t1 = Sigma0(a) + Maj(a, b, c); \
d += t0; \
h = t0 + t1;
RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],0,0x428a2f98);
RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],1,0x71374491);
RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],2,0xb5c0fbcf);
RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],3,0xe9b5dba5);
RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],4,0x3956c25b);
RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],5,0x59f111f1);
RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],6,0x923f82a4);
RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],7,0xab1c5ed5);
RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],8,0xd807aa98);
RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],9,0x12835b01);
RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],10,0x243185be);
RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],11,0x550c7dc3);
RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],12,0x72be5d74);
RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],13,0x80deb1fe);
RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],14,0x9bdc06a7);
RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],15,0xc19bf174);
RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],16,0xe49b69c1);
RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],17,0xefbe4786);
RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],18,0x0fc19dc6);
RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],19,0x240ca1cc);
RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],20,0x2de92c6f);
RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],21,0x4a7484aa);
RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],22,0x5cb0a9dc);
RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],23,0x76f988da);
RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],24,0x983e5152);
RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],25,0xa831c66d);
RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],26,0xb00327c8);
RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],27,0xbf597fc7);
RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],28,0xc6e00bf3);
RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],29,0xd5a79147);
RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],30,0x06ca6351);
RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],31,0x14292967);
RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],32,0x27b70a85);
RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],33,0x2e1b2138);
RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],34,0x4d2c6dfc);
RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],35,0x53380d13);
RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],36,0x650a7354);
RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],37,0x766a0abb);
RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],38,0x81c2c92e);
RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],39,0x92722c85);
RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],40,0xa2bfe8a1);
RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],41,0xa81a664b);
RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],42,0xc24b8b70);
RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],43,0xc76c51a3);
RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],44,0xd192e819);
RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],45,0xd6990624);
RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],46,0xf40e3585);
RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],47,0x106aa070);
RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],48,0x19a4c116);
RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],49,0x1e376c08);
RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],50,0x2748774c);
RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],51,0x34b0bcb5);
RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],52,0x391c0cb3);
RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],53,0x4ed8aa4a);
RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],54,0x5b9cca4f);
RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],55,0x682e6ff3);
RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],56,0x748f82ee);
RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],57,0x78a5636f);
RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],58,0x84c87814);
RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],59,0x8cc70208);
RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],60,0x90befffa);
RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],61,0xa4506ceb);
RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],62,0xbef9a3f7);
RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],63,0xc67178f2);
#undef RND
for (i=0; i<8; i++) // feedback
md->state[i] = md->state[i] + S[i];
return(0);
}
#undef RORc
#undef Ch
#undef Maj
#undef S
#undef R
#undef Sigma0
#undef Sigma1
#undef Gamma0
#undef Gamma1
static inline void sha256_vinit(struct sha256_vstate * md)
{
md->curlen = 0;
md->length = 0;
md->state[0] = 0x6A09E667UL;
md->state[1] = 0xBB67AE85UL;
md->state[2] = 0x3C6EF372UL;
md->state[3] = 0xA54FF53AUL;
md->state[4] = 0x510E527FUL;
md->state[5] = 0x9B05688CUL;
md->state[6] = 0x1F83D9ABUL;
md->state[7] = 0x5BE0CD19UL;
}
static inline int32_t sha256_vprocess(struct sha256_vstate *md,const uint8_t *in,uint64_t inlen)
{
uint64_t n; int32_t err;
if ( md->curlen > sizeof(md->buf) )
return(-1);
while ( inlen > 0 )
{
if ( md->curlen == 0 && inlen >= 64 )
{
if ( (err= sha256_vcompress(md,(uint8_t *)in)) != 0 )
return(err);
md->length += 64 * 8, in += 64, inlen -= 64;
}
else
{
n = MIN(inlen,64 - md->curlen);
memcpy(md->buf + md->curlen,in,(size_t)n);
md->curlen += n, in += n, inlen -= n;
if ( md->curlen == 64 )
{
if ( (err= sha256_vcompress(md,md->buf)) != 0 )
return(err);
md->length += 8*64;
md->curlen = 0;
}
}
}
return(0);
}
static inline int32_t sha256_vdone(struct sha256_vstate *md,uint8_t *out)
{
int32_t i;
if ( md->curlen >= sizeof(md->buf) )
return(-1);
md->length += md->curlen * 8; // increase the length of the message
md->buf[md->curlen++] = (uint8_t)0x80; // append the '1' bit
// if len > 56 bytes we append zeros then compress. Then we can fall back to padding zeros and length encoding like normal.
if ( md->curlen > 56 )
{
while ( md->curlen < 64 )
md->buf[md->curlen++] = (uint8_t)0;
sha256_vcompress(md,md->buf);
md->curlen = 0;
}
while ( md->curlen < 56 ) // pad upto 56 bytes of zeroes
md->buf[md->curlen++] = (uint8_t)0;
STORE64H(md->length,md->buf+56); // store length
sha256_vcompress(md,md->buf);
for (i=0; i<8; i++) // copy output
STORE32H(md->state[i],out+(4*i));
return(0);
}
void vcalc_sha256(char deprecated[(256 >> 3) * 2 + 1],uint8_t hash[256 >> 3],uint8_t *src,int32_t len)
{
struct sha256_vstate md;
sha256_vinit(&md);
sha256_vprocess(&md,src,len);
sha256_vdone(&md,hash);
// we will use CSHA256 class instead of above implementation,
// in case if daemon compiled with USE_ASM enabled it will use
// hardware (SSE4) implementation, otherwise standart
// CSHA256().Write((const unsigned char *)src, len).Finalize(hash);
}
bits256 bits256_doublesha256(char *deprecated,uint8_t *data,int32_t datalen)
{
bits256 hash,hash2; int32_t i;
vcalc_sha256(0,hash.bytes,data,datalen);
vcalc_sha256(0,hash2.bytes,hash.bytes,sizeof(hash));
for (i=0; i<sizeof(hash); i++)
hash.bytes[i] = hash2.bytes[sizeof(hash) - 1 - i];
return(hash);
}
// rmd160: the five basic functions F(), G() and H()
#define F(x, y, z) ((x) ^ (y) ^ (z))
#define G(x, y, z) (((x) & (y)) | (~(x) & (z)))
#define H(x, y, z) (((x) | ~(y)) ^ (z))
#define I(x, y, z) (((x) & (z)) | ((y) & ~(z)))
#define J(x, y, z) ((x) ^ ((y) | ~(z)))
#define ROLc(x, y) ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
/* the ten basic operations FF() through III() */
#define FF(a, b, c, d, e, x, s) \
(a) += F((b), (c), (d)) + (x);\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define GG(a, b, c, d, e, x, s) \
(a) += G((b), (c), (d)) + (x) + 0x5a827999UL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define HH(a, b, c, d, e, x, s) \
(a) += H((b), (c), (d)) + (x) + 0x6ed9eba1UL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define II(a, b, c, d, e, x, s) \
(a) += I((b), (c), (d)) + (x) + 0x8f1bbcdcUL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define JJ(a, b, c, d, e, x, s) \
(a) += J((b), (c), (d)) + (x) + 0xa953fd4eUL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define FFF(a, b, c, d, e, x, s) \
(a) += F((b), (c), (d)) + (x);\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define GGG(a, b, c, d, e, x, s) \
(a) += G((b), (c), (d)) + (x) + 0x7a6d76e9UL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define HHH(a, b, c, d, e, x, s) \
(a) += H((b), (c), (d)) + (x) + 0x6d703ef3UL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define III(a, b, c, d, e, x, s) \
(a) += I((b), (c), (d)) + (x) + 0x5c4dd124UL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define JJJ(a, b, c, d, e, x, s) \
(a) += J((b), (c), (d)) + (x) + 0x50a28be6UL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
static int32_t rmd160_vcompress(struct rmd160_vstate *md,uint8_t *buf)
{
uint32_t aa,bb,cc,dd,ee,aaa,bbb,ccc,ddd,eee,X[16];
int i;
/* load words X */
for (i = 0; i < 16; i++){
LOAD32L(X[i], buf + (4 * i));
}
/* load state */
aa = aaa = md->state[0];
bb = bbb = md->state[1];
cc = ccc = md->state[2];
dd = ddd = md->state[3];
ee = eee = md->state[4];
/* round 1 */
FF(aa, bb, cc, dd, ee, X[ 0], 11);
FF(ee, aa, bb, cc, dd, X[ 1], 14);
FF(dd, ee, aa, bb, cc, X[ 2], 15);
FF(cc, dd, ee, aa, bb, X[ 3], 12);
FF(bb, cc, dd, ee, aa, X[ 4], 5);
FF(aa, bb, cc, dd, ee, X[ 5], 8);
FF(ee, aa, bb, cc, dd, X[ 6], 7);
FF(dd, ee, aa, bb, cc, X[ 7], 9);
FF(cc, dd, ee, aa, bb, X[ 8], 11);
FF(bb, cc, dd, ee, aa, X[ 9], 13);
FF(aa, bb, cc, dd, ee, X[10], 14);
FF(ee, aa, bb, cc, dd, X[11], 15);
FF(dd, ee, aa, bb, cc, X[12], 6);
FF(cc, dd, ee, aa, bb, X[13], 7);
FF(bb, cc, dd, ee, aa, X[14], 9);
FF(aa, bb, cc, dd, ee, X[15], 8);
/* round 2 */
GG(ee, aa, bb, cc, dd, X[ 7], 7);
GG(dd, ee, aa, bb, cc, X[ 4], 6);
GG(cc, dd, ee, aa, bb, X[13], 8);
GG(bb, cc, dd, ee, aa, X[ 1], 13);
GG(aa, bb, cc, dd, ee, X[10], 11);
GG(ee, aa, bb, cc, dd, X[ 6], 9);
GG(dd, ee, aa, bb, cc, X[15], 7);
GG(cc, dd, ee, aa, bb, X[ 3], 15);
GG(bb, cc, dd, ee, aa, X[12], 7);
GG(aa, bb, cc, dd, ee, X[ 0], 12);
GG(ee, aa, bb, cc, dd, X[ 9], 15);
GG(dd, ee, aa, bb, cc, X[ 5], 9);
GG(cc, dd, ee, aa, bb, X[ 2], 11);
GG(bb, cc, dd, ee, aa, X[14], 7);
GG(aa, bb, cc, dd, ee, X[11], 13);
GG(ee, aa, bb, cc, dd, X[ 8], 12);
/* round 3 */
HH(dd, ee, aa, bb, cc, X[ 3], 11);
HH(cc, dd, ee, aa, bb, X[10], 13);
HH(bb, cc, dd, ee, aa, X[14], 6);
HH(aa, bb, cc, dd, ee, X[ 4], 7);
HH(ee, aa, bb, cc, dd, X[ 9], 14);
HH(dd, ee, aa, bb, cc, X[15], 9);
HH(cc, dd, ee, aa, bb, X[ 8], 13);
HH(bb, cc, dd, ee, aa, X[ 1], 15);
HH(aa, bb, cc, dd, ee, X[ 2], 14);
HH(ee, aa, bb, cc, dd, X[ 7], 8);
HH(dd, ee, aa, bb, cc, X[ 0], 13);
HH(cc, dd, ee, aa, bb, X[ 6], 6);
HH(bb, cc, dd, ee, aa, X[13], 5);
HH(aa, bb, cc, dd, ee, X[11], 12);
HH(ee, aa, bb, cc, dd, X[ 5], 7);
HH(dd, ee, aa, bb, cc, X[12], 5);
/* round 4 */
II(cc, dd, ee, aa, bb, X[ 1], 11);
II(bb, cc, dd, ee, aa, X[ 9], 12);
II(aa, bb, cc, dd, ee, X[11], 14);
II(ee, aa, bb, cc, dd, X[10], 15);
II(dd, ee, aa, bb, cc, X[ 0], 14);
II(cc, dd, ee, aa, bb, X[ 8], 15);
II(bb, cc, dd, ee, aa, X[12], 9);
II(aa, bb, cc, dd, ee, X[ 4], 8);
II(ee, aa, bb, cc, dd, X[13], 9);
II(dd, ee, aa, bb, cc, X[ 3], 14);
II(cc, dd, ee, aa, bb, X[ 7], 5);
II(bb, cc, dd, ee, aa, X[15], 6);
II(aa, bb, cc, dd, ee, X[14], 8);
II(ee, aa, bb, cc, dd, X[ 5], 6);
II(dd, ee, aa, bb, cc, X[ 6], 5);
II(cc, dd, ee, aa, bb, X[ 2], 12);
/* round 5 */
JJ(bb, cc, dd, ee, aa, X[ 4], 9);
JJ(aa, bb, cc, dd, ee, X[ 0], 15);
JJ(ee, aa, bb, cc, dd, X[ 5], 5);
JJ(dd, ee, aa, bb, cc, X[ 9], 11);
JJ(cc, dd, ee, aa, bb, X[ 7], 6);
JJ(bb, cc, dd, ee, aa, X[12], 8);
JJ(aa, bb, cc, dd, ee, X[ 2], 13);
JJ(ee, aa, bb, cc, dd, X[10], 12);
JJ(dd, ee, aa, bb, cc, X[14], 5);
JJ(cc, dd, ee, aa, bb, X[ 1], 12);
JJ(bb, cc, dd, ee, aa, X[ 3], 13);
JJ(aa, bb, cc, dd, ee, X[ 8], 14);
JJ(ee, aa, bb, cc, dd, X[11], 11);
JJ(dd, ee, aa, bb, cc, X[ 6], 8);
JJ(cc, dd, ee, aa, bb, X[15], 5);
JJ(bb, cc, dd, ee, aa, X[13], 6);
/* parallel round 1 */
JJJ(aaa, bbb, ccc, ddd, eee, X[ 5], 8);
JJJ(eee, aaa, bbb, ccc, ddd, X[14], 9);
JJJ(ddd, eee, aaa, bbb, ccc, X[ 7], 9);
JJJ(ccc, ddd, eee, aaa, bbb, X[ 0], 11);
JJJ(bbb, ccc, ddd, eee, aaa, X[ 9], 13);
JJJ(aaa, bbb, ccc, ddd, eee, X[ 2], 15);
JJJ(eee, aaa, bbb, ccc, ddd, X[11], 15);
JJJ(ddd, eee, aaa, bbb, ccc, X[ 4], 5);
JJJ(ccc, ddd, eee, aaa, bbb, X[13], 7);
JJJ(bbb, ccc, ddd, eee, aaa, X[ 6], 7);
JJJ(aaa, bbb, ccc, ddd, eee, X[15], 8);
JJJ(eee, aaa, bbb, ccc, ddd, X[ 8], 11);
JJJ(ddd, eee, aaa, bbb, ccc, X[ 1], 14);
JJJ(ccc, ddd, eee, aaa, bbb, X[10], 14);
JJJ(bbb, ccc, ddd, eee, aaa, X[ 3], 12);
JJJ(aaa, bbb, ccc, ddd, eee, X[12], 6);
/* parallel round 2 */
III(eee, aaa, bbb, ccc, ddd, X[ 6], 9);
III(ddd, eee, aaa, bbb, ccc, X[11], 13);
III(ccc, ddd, eee, aaa, bbb, X[ 3], 15);
III(bbb, ccc, ddd, eee, aaa, X[ 7], 7);
III(aaa, bbb, ccc, ddd, eee, X[ 0], 12);
III(eee, aaa, bbb, ccc, ddd, X[13], 8);
III(ddd, eee, aaa, bbb, ccc, X[ 5], 9);
III(ccc, ddd, eee, aaa, bbb, X[10], 11);
III(bbb, ccc, ddd, eee, aaa, X[14], 7);
III(aaa, bbb, ccc, ddd, eee, X[15], 7);
III(eee, aaa, bbb, ccc, ddd, X[ 8], 12);
III(ddd, eee, aaa, bbb, ccc, X[12], 7);
III(ccc, ddd, eee, aaa, bbb, X[ 4], 6);
III(bbb, ccc, ddd, eee, aaa, X[ 9], 15);
III(aaa, bbb, ccc, ddd, eee, X[ 1], 13);
III(eee, aaa, bbb, ccc, ddd, X[ 2], 11);
/* parallel round 3 */
HHH(ddd, eee, aaa, bbb, ccc, X[15], 9);
HHH(ccc, ddd, eee, aaa, bbb, X[ 5], 7);
HHH(bbb, ccc, ddd, eee, aaa, X[ 1], 15);
HHH(aaa, bbb, ccc, ddd, eee, X[ 3], 11);
HHH(eee, aaa, bbb, ccc, ddd, X[ 7], 8);
HHH(ddd, eee, aaa, bbb, ccc, X[14], 6);
HHH(ccc, ddd, eee, aaa, bbb, X[ 6], 6);
HHH(bbb, ccc, ddd, eee, aaa, X[ 9], 14);
HHH(aaa, bbb, ccc, ddd, eee, X[11], 12);
HHH(eee, aaa, bbb, ccc, ddd, X[ 8], 13);
HHH(ddd, eee, aaa, bbb, ccc, X[12], 5);
HHH(ccc, ddd, eee, aaa, bbb, X[ 2], 14);
HHH(bbb, ccc, ddd, eee, aaa, X[10], 13);
HHH(aaa, bbb, ccc, ddd, eee, X[ 0], 13);
HHH(eee, aaa, bbb, ccc, ddd, X[ 4], 7);
HHH(ddd, eee, aaa, bbb, ccc, X[13], 5);
/* parallel round 4 */
GGG(ccc, ddd, eee, aaa, bbb, X[ 8], 15);
GGG(bbb, ccc, ddd, eee, aaa, X[ 6], 5);
GGG(aaa, bbb, ccc, ddd, eee, X[ 4], 8);
GGG(eee, aaa, bbb, ccc, ddd, X[ 1], 11);
GGG(ddd, eee, aaa, bbb, ccc, X[ 3], 14);
GGG(ccc, ddd, eee, aaa, bbb, X[11], 14);
GGG(bbb, ccc, ddd, eee, aaa, X[15], 6);
GGG(aaa, bbb, ccc, ddd, eee, X[ 0], 14);
GGG(eee, aaa, bbb, ccc, ddd, X[ 5], 6);
GGG(ddd, eee, aaa, bbb, ccc, X[12], 9);
GGG(ccc, ddd, eee, aaa, bbb, X[ 2], 12);
GGG(bbb, ccc, ddd, eee, aaa, X[13], 9);
GGG(aaa, bbb, ccc, ddd, eee, X[ 9], 12);
GGG(eee, aaa, bbb, ccc, ddd, X[ 7], 5);
GGG(ddd, eee, aaa, bbb, ccc, X[10], 15);
GGG(ccc, ddd, eee, aaa, bbb, X[14], 8);
/* parallel round 5 */
FFF(bbb, ccc, ddd, eee, aaa, X[12] , 8);
FFF(aaa, bbb, ccc, ddd, eee, X[15] , 5);
FFF(eee, aaa, bbb, ccc, ddd, X[10] , 12);
FFF(ddd, eee, aaa, bbb, ccc, X[ 4] , 9);
FFF(ccc, ddd, eee, aaa, bbb, X[ 1] , 12);
FFF(bbb, ccc, ddd, eee, aaa, X[ 5] , 5);
FFF(aaa, bbb, ccc, ddd, eee, X[ 8] , 14);
FFF(eee, aaa, bbb, ccc, ddd, X[ 7] , 6);
FFF(ddd, eee, aaa, bbb, ccc, X[ 6] , 8);
FFF(ccc, ddd, eee, aaa, bbb, X[ 2] , 13);
FFF(bbb, ccc, ddd, eee, aaa, X[13] , 6);
FFF(aaa, bbb, ccc, ddd, eee, X[14] , 5);
FFF(eee, aaa, bbb, ccc, ddd, X[ 0] , 15);
FFF(ddd, eee, aaa, bbb, ccc, X[ 3] , 13);
FFF(ccc, ddd, eee, aaa, bbb, X[ 9] , 11);
FFF(bbb, ccc, ddd, eee, aaa, X[11] , 11);
/* combine results */
ddd += cc + md->state[1]; /* final result for md->state[0] */
md->state[1] = md->state[2] + dd + eee;
md->state[2] = md->state[3] + ee + aaa;
md->state[3] = md->state[4] + aa + bbb;
md->state[4] = md->state[0] + bb + ccc;
md->state[0] = ddd;
return 0;
}
/**
Initialize the hash state
@param md The hash state you wish to initialize
@return 0 if successful
*/
int rmd160_vinit(struct rmd160_vstate * md)
{
md->state[0] = 0x67452301UL;
md->state[1] = 0xefcdab89UL;
md->state[2] = 0x98badcfeUL;
md->state[3] = 0x10325476UL;
md->state[4] = 0xc3d2e1f0UL;
md->curlen = 0;
md->length = 0;
return 0;
}
#define HASH_PROCESS(func_name, compress_name, state_var, block_size) \
int func_name (struct rmd160_vstate * md, const unsigned char *in, unsigned long inlen) \
{ \
unsigned long n; \
int err; \
if (md->curlen > sizeof(md->buf)) { \
return -1; \
} \
while (inlen > 0) { \
if (md->curlen == 0 && inlen >= block_size) { \
if ((err = compress_name (md, (unsigned char *)in)) != 0) { \
return err; \
} \
md->length += block_size * 8; \
in += block_size; \
inlen -= block_size; \
} else { \
n = MIN(inlen, (block_size - md->curlen)); \
memcpy(md->buf + md->curlen, in, (size_t)n); \
md->curlen += n; \
in += n; \
inlen -= n; \
if (md->curlen == block_size) { \
if ((err = compress_name (md, md->buf)) != 0) { \
return err; \
} \
md->length += 8*block_size; \
md->curlen = 0; \
} \
} \
} \
return 0; \
}
/**
Process a block of memory though the hash
@param md The hash state
@param in The data to hash
@param inlen The length of the data (octets)
@return 0 if successful
*/
HASH_PROCESS(rmd160_vprocess, rmd160_vcompress, rmd160, 64)
/**
Terminate the hash to get the digest
@param md The hash state
@param out [out] The destination of the hash (20 bytes)
@return 0 if successful
*/
int rmd160_vdone(struct rmd160_vstate * md, unsigned char *out)
{
int i;
if (md->curlen >= sizeof(md->buf)) {
return -1;
}
/* increase the length of the message */
md->length += md->curlen * 8;
/* append the '1' bit */
md->buf[md->curlen++] = (unsigned char)0x80;
/* if the length is currently above 56 bytes we append zeros
* then compress. Then we can fall back to padding zeros and length
* encoding like normal.
*/
if (md->curlen > 56) {
while (md->curlen < 64) {
md->buf[md->curlen++] = (unsigned char)0;
}
rmd160_vcompress(md, md->buf);
md->curlen = 0;
}
/* pad upto 56 bytes of zeroes */
while (md->curlen < 56) {
md->buf[md->curlen++] = (unsigned char)0;
}
/* store length */
STORE64L(md->length, md->buf+56);
rmd160_vcompress(md, md->buf);
/* copy output */
for (i = 0; i < 5; i++) {
STORE32L(md->state[i], out+(4*i));
}
return 0;
}
void calc_rmd160(char deprecated[41],uint8_t buf[20],uint8_t *msg,int32_t len)
{
struct rmd160_vstate md;
rmd160_vinit(&md);
rmd160_vprocess(&md,msg,len);
rmd160_vdone(&md, buf);
}
#undef F
#undef G
#undef H
#undef I
#undef J
#undef ROLc
#undef FF
#undef GG
#undef HH
#undef II
#undef JJ
#undef FFF
#undef GGG
#undef HHH
#undef III
#undef JJJ
void calc_rmd160_sha256(uint8_t rmd160[20],uint8_t *data,int32_t datalen)
{
bits256 hash;
vcalc_sha256(0,hash.bytes,data,datalen);
calc_rmd160(0,rmd160,hash.bytes,sizeof(hash));
}
char *nonportable_path(char *str)
{
int32_t i;
for (i=0; str[i]!=0; i++)
if ( str[i] == '/' )
str[i] = '\\';
return(str);
}
char *portable_path(char *str)
{
#ifdef _WIN32
return(nonportable_path(str));
#else
#ifdef __PNACL
/*int32_t i,n;
if ( str[0] == '/' )
return(str);
else
{
n = (int32_t)strlen(str);
for (i=n; i>0; i--)
str[i] = str[i-1];
str[0] = '/';
str[n+1] = 0;
}*/
#endif
return(str);
#endif
}
void *loadfile(char *fname,uint8_t **bufp,long *lenp,long *allocsizep)
{
FILE *fp;
long filesize,buflen = *allocsizep;
uint8_t *buf = *bufp;
*lenp = 0;
if ( (fp= fopen(portable_path(fname),"rb")) != 0 )
{
fseek(fp,0,SEEK_END);
filesize = ftell(fp);
if ( filesize == 0 )
{
fclose(fp);
*lenp = 0;
//LogPrintf("loadfile null size.(%s)\n",fname);
return(0);
}
if ( filesize > buflen )
{
*allocsizep = filesize;
*bufp = buf = (uint8_t *)realloc(buf,(long)*allocsizep+64);
}
rewind(fp);
if ( buf == 0 )
LogPrintf("Null buf ???\n");
else
{
if ( fread(buf,1,(long)filesize,fp) != (unsigned long)filesize )
LogPrintf("error reading filesize.%ld\n",(long)filesize);
buf[filesize] = 0;
}
fclose(fp);
*lenp = filesize;
//LogPrintf("loaded.(%s)\n",buf);
} //else LogPrintf("OS_loadfile couldnt load.(%s)\n",fname);
return(buf);
}
void *filestr(long *allocsizep,char *_fname)
{
long filesize = 0; char *fname,*buf = 0; void *retptr;
*allocsizep = 0;
fname = (char *)malloc(strlen(_fname)+1);
strcpy(fname,_fname);
retptr = loadfile(fname,(uint8_t **)&buf,&filesize,allocsizep);
free(fname);
return(retptr);
}
char *bitcoin_address(char *coinaddr,uint8_t addrtype,uint8_t *pubkey_or_rmd160,int32_t len)
{
int32_t i; uint8_t data[25]; bits256 hash;// char checkaddr[65];
if ( len != 20 )
calc_rmd160_sha256(data+1,pubkey_or_rmd160,len);
else memcpy(data+1,pubkey_or_rmd160,20);
//btc_convrmd160(checkaddr,addrtype,data+1);
data[0] = addrtype;
hash = bits256_doublesha256(0,data,21);
for (i=0; i<4; i++)
data[21+i] = hash.bytes[31-i];
if ( (coinaddr= bitcoin_base58encode(coinaddr,data,25)) != 0 )
{
//uint8_t checktype,rmd160[20];
//bitcoin_addr2rmd160(&checktype,rmd160,coinaddr);
//if ( strcmp(checkaddr,coinaddr) != 0 )
// LogPrintf("checkaddr.(%s) vs coinaddr.(%s) %02x vs [%02x] memcmp.%d\n",checkaddr,coinaddr,addrtype,checktype,memcmp(rmd160,data+1,20));
}
return(coinaddr);
}
void InitKomodoInternalVariables() {
// used for init internal variables, called from bitcoind.cpp and qt/bitcoin.cpp after
// gArgs.ParseParameters(...), mean when params already parsed into mapArgs and mapMultiArgs.
// this function is analog of komodo_args in komodod ...
std::string NOTARY_PUBKEY = gArgs.GetArg("-pubkey", "");
if (IsHex(NOTARY_PUBKEY) && NOTARY_PUBKEY.size() == 2 * CPubKey::COMPRESSED_PUBLIC_KEY_SIZE) {
std::vector<unsigned char> vch_pubkey = ParseHex(NOTARY_PUBKEY);
std::copy(vch_pubkey.begin(), vch_pubkey.end(), NOTARY_PUBKEY33);
}
}
|
#include <future>
#include <gmock/gmock.h>
#include <grpc++/grpc++.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <memory>
#include <vector>
#include "core_service_impl.h"
#include "mocks/mavsdk_mock.h"
namespace {
using testing::_;
using testing::NiceMock;
using MockMavsdk = NiceMock<mavsdk::testing::MockMavsdk>;
using CoreServiceImpl = mavsdk::mavsdk_server::CoreServiceImpl<MockMavsdk>;
using CoreService = mavsdk::rpc::core::CoreService;
using ConnectionStateResponse = mavsdk::rpc::core::ConnectionStateResponse;
class CoreServiceImplTest : public ::testing::Test {
protected:
virtual void SetUp()
{
_mavsdk = std::make_unique<MockMavsdk>();
_core_service = std::make_unique<CoreServiceImpl>(*_mavsdk);
grpc::ServerBuilder builder;
builder.RegisterService(_core_service.get());
_server = builder.BuildAndStart();
grpc::ChannelArguments channel_args;
auto channel = _server->InProcessChannel(channel_args);
_stub = CoreService::NewStub(channel);
}
virtual void TearDown() { _server->Shutdown(); }
std::future<void> subscribeConnectionStateAsync(std::vector<bool>& events);
std::unique_ptr<CoreServiceImpl> _core_service{};
std::unique_ptr<MockMavsdk> _mavsdk{};
std::unique_ptr<grpc::Server> _server{};
std::unique_ptr<CoreService::Stub> _stub{};
};
ACTION_P2(SaveCallback, callback, callback_promise)
{
*callback = arg0;
callback_promise->set_value();
}
TEST_F(CoreServiceImplTest, subscribeConnectionStateSubscribesToChange)
{
EXPECT_CALL(*_mavsdk, subscribe_on_new_system(_)).Times(1);
grpc::ClientContext context;
mavsdk::rpc::core::SubscribeConnectionStateRequest request;
_stub->SubscribeConnectionState(&context, request);
_core_service->stop();
}
TEST_F(CoreServiceImplTest, connectionStateStreamEmptyIfCallbackNotCalled)
{
std::vector<bool> events;
auto events_stream_future = subscribeConnectionStateAsync(events);
_core_service->stop();
events_stream_future.wait();
EXPECT_EQ(0, events.size());
}
std::future<void> CoreServiceImplTest::subscribeConnectionStateAsync(std::vector<bool>& events)
{
return std::async(std::launch::async, [&]() {
grpc::ClientContext context;
mavsdk::rpc::core::SubscribeConnectionStateRequest request;
auto response_reader = _stub->SubscribeConnectionState(&context, request);
mavsdk::rpc::core::ConnectionStateResponse response;
while (response_reader->Read(&response)) {
events.push_back(response.connection_state().is_connected());
}
});
}
} // namespace
|
#include <iostream>
#include <fstream>
#include <vector>
#include <sys/stat.h>
using namespace std;
#define KMERLONGS (MAX_KMER_SIZE/32) // 32 = numbits(uint64_t)/2- with 2 being the number of bits needed per nucleotide
#define KMER_LENGTH 15
#include "Kmer.hpp"
#include "common.h"
#include "ParallelFASTQ.h"
struct filedata
{
char filename[MAX_FILE_PATH];
size_t filesize;
};
vector< filedata > GetFiles(char * filename)
{
int64_t totalsize = 0;
int numfiles = 0;
vector< filedata > filesview;
filedata fdata;
ifstream allfiles(filename);
if(!allfiles.is_open()) {
cerr << "Could not open " << filename << endl;
exit(1);
}
allfiles.getline(fdata.filename,MAX_FILE_PATH);
while(!allfiles.eof())
{
struct stat st;
stat(fdata.filename, &st);
fdata.filesize = st.st_size;
filesview.push_back(fdata);
std::cout << "inputFile: " << filesview.back().filename << std::endl;
std::cout << "inputSize: " << filesview.back().filesize / (1024*1024) << " MB" << endl;
allfiles.getline(fdata.filename,MAX_FILE_PATH);
totalsize += fdata.filesize;
numfiles++;
}
return filesview;
}
int main(int argc, char* argv[])
{
Kmer::set_k(KMER_LENGTH);
vector<filedata> allfiles = GetFiles(argv[1]);
size_t upperlimit = 1000; // a thousand reads at a time
vector<string> seqs;
vector<string> quals;
for(auto itr= allfiles.begin(); itr != allfiles.end(); itr++)
{
ParallelFASTQ *pfq = new ParallelFASTQ();
pfq->open(itr->filename, false, itr->filesize);
size_t fillstatus = 1;
while(fillstatus)
{
fillstatus = pfq->fill_block(seqs, quals, upperlimit);
size_t nreads = seqs.size();
for(size_t i=0; i< nreads; ++i)
{
size_t found;
found = seqs[i].length();
// skip this sequence if the length is too short
if (seqs[i].length() <= KMER_LENGTH) {
continue;
}
int nkmers = (seqs[i].length()-KMER_LENGTH+1);
std::vector<Kmer> kmers = Kmer::getKmers(seqs[i]); // calculate all the kmers
assert(kmers.size() == nkmers);
// Aydin: the following lines are just for debugging, comment out after you get a feeling of how it works
cout << "printing the first k-mer and its reverse complement from this read: ";
cout << kmers[0].toString() << " " << kmers[0].twin().toString() << endl;
}
}
}
}
|
// Copyright 2017-2020 The Verible Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 "common/text/tree_utils.h"
#include <algorithm>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/str_cat.h"
#include "common/text/concrete_syntax_leaf.h"
#include "common/text/concrete_syntax_tree.h"
#include "common/text/symbol.h"
#include "common/text/token_info.h"
#include "common/text/visitors.h"
#include "common/util/iterator_adaptors.h"
#include "common/util/logging.h"
#include "common/util/spacer.h"
#include "common/util/value_saver.h"
namespace verible {
const Symbol* DescendThroughSingletons(const Symbol& symbol) {
if (symbol.Kind() == SymbolKind::kLeaf) {
return &symbol;
}
// else is a kNode
const auto& node = down_cast<const SyntaxTreeNode&>(symbol);
const auto& children = node.children();
if (children.size() == 1 && children.front() != nullptr) {
// If only child is non-null, descend.
return DescendThroughSingletons(*children.front());
}
return &symbol;
}
const SyntaxTreeLeaf* GetRightmostLeaf(const Symbol& symbol) {
if (symbol.Kind() == SymbolKind::kLeaf) {
const auto* leaf = down_cast<const SyntaxTreeLeaf*>(&symbol);
return leaf;
}
if (symbol.Kind() == SymbolKind::kNode) {
const auto& node = down_cast<const SyntaxTreeNode&>(symbol);
for (const auto& child : reversed_view(node.children())) {
if (child != nullptr) {
const auto* leaf = GetRightmostLeaf(*child);
if (leaf != nullptr) {
return leaf;
}
}
}
}
return nullptr;
}
const SyntaxTreeLeaf* GetLeftmostLeaf(const Symbol& symbol) {
if (symbol.Kind() == SymbolKind::kLeaf) {
const auto* leaf = down_cast<const SyntaxTreeLeaf*>(&symbol);
return leaf;
}
if (symbol.Kind() == SymbolKind::kNode) {
const auto& node = down_cast<const SyntaxTreeNode&>(symbol);
for (const auto& child : node.children()) {
if (child != nullptr) {
const auto* leaf = GetLeftmostLeaf(*child);
if (leaf != nullptr) {
return leaf;
}
}
}
}
return nullptr;
}
absl::string_view StringSpanOfSymbol(const Symbol& symbol) {
return StringSpanOfSymbol(symbol, symbol);
}
absl::string_view StringSpanOfSymbol(const Symbol& lsym, const Symbol& rsym) {
const auto* left = GetLeftmostLeaf(lsym);
const auto* right = GetRightmostLeaf(rsym);
if (left != nullptr && right != nullptr) {
const auto range_begin = left->get().text.begin();
const auto range_end = right->get().text.end();
return absl::string_view(range_begin,
std::distance(range_begin, range_end));
} else {
return "";
}
}
const SyntaxTreeNode& SymbolCastToNode(const Symbol& symbol) {
// Assert the symbol is a node.
CHECK_EQ(symbol.Kind(), SymbolKind::kNode)
<< "got: " << RawTreePrinter(symbol);
return down_cast<const SyntaxTreeNode&>(symbol);
}
const SyntaxTreeLeaf& SymbolCastToLeaf(const Symbol& symbol) {
// Assert the symbol is a leaf.
CHECK_EQ(symbol.Kind(), SymbolKind::kLeaf)
<< "got: " << RawTreePrinter(symbol);
return down_cast<const SyntaxTreeLeaf&>(symbol);
}
namespace {
// FirstSubtreeFinderMutable is a visitor class that supports the implementation
// of FindFirstSubtreeMutable(). It is derived from
// MutableTreeVisitorRecursive because it is intended for use with pruning and
// modifying syntax trees.
class FirstSubtreeFinderMutable : public MutableTreeVisitorRecursive {
public:
explicit FirstSubtreeFinderMutable(const TreePredicate& predicate)
: predicate_(predicate) {}
void Visit(const SyntaxTreeNode& node, SymbolPtr* symbol_ptr) override {
CHECK_EQ(symbol_ptr->get(), &node); // symbol_ptr owns node.
if (result_ == nullptr) {
// If this node matches, return it, and skip evaluating children.
if (predicate_(node)) {
result_ = symbol_ptr;
} else {
// Cast the mutable copy of the node pointer (same object as &node).
auto* const mutable_node =
down_cast<SyntaxTreeNode*>(symbol_ptr->get());
for (SymbolPtr& child : mutable_node->mutable_children()) {
if (child != nullptr) {
child->Accept(this, &child);
}
// Stop as soon as first result is found.
if (result_ != nullptr) return;
}
}
}
}
void Visit(const SyntaxTreeLeaf& leaf, SymbolPtr* symbol_ptr) override {
CHECK_EQ(symbol_ptr->get(), &leaf); // symbol_ptr owns leaf.
// If already have a result, stop checking and return right away.
if (result_ == nullptr) {
if (predicate_(leaf)) {
result_ = symbol_ptr;
}
}
}
ConcreteSyntaxTree* result() const { return result_; }
private:
// Matching criterion.
TreePredicate predicate_;
// Contains first matching result found or nullptr if no match is found.
ConcreteSyntaxTree* result_ = nullptr;
};
// FirstSubtreeFinder is a visitor class that supports the implementation of
// FindFirstSubtree(). It is derived from TreeVisitorRecursive because it is
// only intended for searching a tree given a predicate.
class FirstSubtreeFinder : public TreeVisitorRecursive {
public:
explicit FirstSubtreeFinder(const TreePredicate& predicate)
: predicate_(predicate) {}
void Visit(const SyntaxTreeNode& node) override {
if (result_ == nullptr) {
// If this node matches, return it, and skip evaluating children.
if (predicate_(node)) {
result_ = &node;
} else {
for (const SymbolPtr& child : node.children()) {
if (child != nullptr) {
child->Accept(this);
}
// Stop as soon as first result is found.
if (result_ != nullptr) return;
}
}
}
}
void Visit(const SyntaxTreeLeaf& leaf) override {
// If already have a result, stop checking and return right away.
if (result_ == nullptr) {
if (predicate_(leaf)) {
result_ = &leaf;
}
}
}
const Symbol* result() const { return result_; }
private:
// Matching criterion.
TreePredicate predicate_;
// Contains first matching result found or nullptr if no match is found.
const Symbol* result_ = nullptr;
};
} // namespace
ConcreteSyntaxTree* FindFirstSubtreeMutable(ConcreteSyntaxTree* tree,
const TreePredicate& pred) {
if (*ABSL_DIE_IF_NULL(tree) == nullptr) return nullptr;
FirstSubtreeFinderMutable finder(pred);
(*tree)->Accept(&finder, tree);
return finder.result();
}
const Symbol* FindFirstSubtree(const Symbol* tree, const TreePredicate& pred) {
if (tree == nullptr) return nullptr;
FirstSubtreeFinder finder(pred);
tree->Accept(&finder);
return finder.result();
}
ConcreteSyntaxTree* FindSubtreeStartingAtOffset(
ConcreteSyntaxTree* tree, const char* first_token_offset) {
auto predicate = [=](const Symbol& s) {
const SyntaxTreeLeaf* leftmost = GetLeftmostLeaf(s);
if (leftmost != nullptr) {
if (std::distance(first_token_offset, leftmost->get().text.begin()) >=
0) {
return true;
}
}
return false;
};
ConcreteSyntaxTree* result =
FindFirstSubtreeMutable(ABSL_DIE_IF_NULL(tree), predicate);
// This cannot return a null tree node because it would have been skipped
// by FirstSubtreeFinderMutable.
if (result != nullptr) CHECK(*result != nullptr);
return result;
}
// Helper function for PruneSyntaxTreeAfterOffset
namespace {
// Returns true if this node should be deleted by parent (pop_back).
bool PruneTreeFromRight(ConcreteSyntaxTree* tree, const char* offset) {
const auto kind = (*ABSL_DIE_IF_NULL(tree))->Kind();
switch (kind) {
case SymbolKind::kLeaf: {
auto* leaf = down_cast<SyntaxTreeLeaf*>(tree->get());
return std::distance(offset, leaf->get().text.end()) > 0;
}
case SymbolKind::kNode: {
auto& node = down_cast<SyntaxTreeNode&>(*tree->get());
auto& children = node.mutable_children();
for (auto& child : reversed_view(children)) {
if (child == nullptr) {
children.pop_back(); // pop_back() guaranteed to not realloc
} else {
if (PruneTreeFromRight(&child, offset)) {
children.pop_back();
} else {
// Since token locations are monotonic, we can stop checking
// as soon as the above function returns false.
break;
}
}
}
// If no children remain, tell caller to delete this node.
return children.empty();
}
}
std::cerr << "Unhandled SymbolKind: " << static_cast<int>(kind);
abort();
}
} // namespace
void PruneSyntaxTreeAfterOffset(ConcreteSyntaxTree* tree, const char* offset) {
PruneTreeFromRight(tree, offset);
}
// Helper functions for ZoomSyntaxTree
namespace {
// Return the upper bound offset of the rightmost token in the tree.
const char* RightmostOffset(const Symbol& symbol) {
const SyntaxTreeLeaf* leaf_ptr = verible::GetRightmostLeaf(symbol);
return ABSL_DIE_IF_NULL(leaf_ptr)->get().text.end();
}
// Return the first non-null child node/leaf of the immediate subtree.
ConcreteSyntaxTree* LeftSubtree(ConcreteSyntaxTree* tree) {
if ((ABSL_DIE_IF_NULL(*tree))->Kind() == verible::SymbolKind::kLeaf) {
// Leaves don't have subtrees.
return nullptr;
}
auto& children = down_cast<SyntaxTreeNode&>(*tree->get()).mutable_children();
for (auto& child : children) {
if (child != nullptr) return &child;
}
return nullptr;
}
} // namespace
ConcreteSyntaxTree* ZoomSyntaxTree(ConcreteSyntaxTree* tree,
absl::string_view trim_range) {
if (*tree == nullptr) return nullptr;
const auto left_offset = trim_range.begin();
// Find shallowest syntax tree node that starts at the given byte offset.
ConcreteSyntaxTree* match =
FindSubtreeStartingAtOffset(ABSL_DIE_IF_NULL(tree), left_offset);
// Take leftmost subtree until its right bound falls within offset.
const auto right_offset = trim_range.end();
while (match != nullptr && *match != nullptr &&
RightmostOffset(*ABSL_DIE_IF_NULL(*match)) > right_offset) {
match = LeftSubtree(match);
}
return match;
}
void TrimSyntaxTree(ConcreteSyntaxTree* tree, absl::string_view trim_range) {
auto* replacement = ZoomSyntaxTree(tree, trim_range);
if (replacement == nullptr || *replacement == nullptr) {
*tree = nullptr;
} else {
*tree = std::move(*replacement);
}
}
namespace {
// Applies one transformation to every leaf (token) in the syntax tree.
class LeafMutatorVisitor : public MutableTreeVisitorRecursive {
public:
// Maintains a reference but not ownership of the mutator, so the
// mutator must outlive this object.
explicit LeafMutatorVisitor(const LeafMutator* mutator)
: leaf_mutator_(*mutator) {}
void Visit(const SyntaxTreeNode&, SymbolPtr*) override {}
// Transforms a single leaf.
void Visit(const SyntaxTreeLeaf& leaf, SymbolPtr* leaf_owner) override {
CHECK_EQ(leaf_owner->get(), &leaf);
auto* const mutable_leaf = down_cast<SyntaxTreeLeaf*>(leaf_owner->get());
leaf_mutator_(ABSL_DIE_IF_NULL(mutable_leaf)->get_mutable());
}
private:
// Mutation to apply to every leaf token.
const LeafMutator& leaf_mutator_;
};
} // namespace
void MutateLeaves(ConcreteSyntaxTree* tree, const LeafMutator& mutator) {
if (*ABSL_DIE_IF_NULL(tree) != nullptr) {
LeafMutatorVisitor visitor(&mutator);
(*tree)->Accept(&visitor, tree);
}
}
//
// Implementation of printing functions
//
std::ostream& RawSymbolPrinter::auto_indent() {
return *stream_ << Spacer(indent_, ' ');
}
void RawSymbolPrinter::Visit(const SyntaxTreeLeaf& leaf) {
leaf.get().ToStream(auto_indent()) << std::endl;
}
void PrettyPrinter::Visit(const SyntaxTreeLeaf& leaf) {
leaf.get().ToStream(auto_indent(), context_) << std::endl;
}
void RawSymbolPrinter::Visit(const SyntaxTreeNode& node) {
std::string tag_info = "";
const int tag = node.Tag().tag;
if (tag != 0) tag_info = absl::StrCat("(tag: ", tag, ") ");
auto_indent() << "Node " << tag_info << "{" << std::endl;
{
ValueSaver<int> value_saver(&indent_, indent_ + 2);
for (const auto& child : node.children()) {
if (child) child->Accept(this);
}
}
auto_indent() << "}" << std::endl;
}
std::ostream& RawTreePrinter::Print(std::ostream& stream) const {
RawSymbolPrinter printer(&stream);
root_.Accept(&printer);
return stream;
}
std::ostream& operator<<(std::ostream& stream, const RawTreePrinter& printer) {
return printer.Print(stream);
}
void PrettyPrintTree(const Symbol& root, const TokenInfo::Context& context,
std::ostream* stream) {
PrettyPrinter printer(stream, context);
root.Accept(&printer);
}
std::ostream& TreePrettyPrinter::Print(std::ostream& stream) const {
PrettyPrintTree(root_, context_, &stream);
return stream;
}
std::ostream& operator<<(std::ostream& stream,
const TreePrettyPrinter& printer) {
return printer.Print(stream);
}
} // namespace verible
|
#include "geom2graph/geometry-flattener.h"
#include "geom2graph/io/wkt.h"
#include <geos/io/ParseException.h>
#include <geos/io/WKTReader.h>
#include <gtest/gtest.h>
using geom2graph::io::from_wkt;
TEST(GeometryFlattenerTests, TestPoint)
{
const auto geometry = from_wkt("POINT(1 2)");
auto flattener = geom2graph::GeometryFlattener(*geometry);
auto iter = flattener.cbegin();
ASSERT_NE(iter, flattener.cend());
ASSERT_TRUE(iter);
ASSERT_EQ(iter->getGeometryTypeId(), geos::geom::GeometryTypeId::GEOS_POINT);
++iter;
EXPECT_EQ(iter, flattener.cend());
EXPECT_FALSE(iter);
}
TEST(GeometryFlattenerTests, TestMultiPoint)
{
const auto geometry = from_wkt("MULTIPOINT((1 1), (2 2))");
auto flattener = geom2graph::GeometryFlattener(*geometry);
auto iter = flattener.cbegin();
ASSERT_NE(iter, flattener.cend());
ASSERT_TRUE(iter);
ASSERT_EQ(iter->getGeometryTypeId(), geos::geom::GeometryTypeId::GEOS_POINT);
EXPECT_TRUE(iter->equals(from_wkt("POINT(1 1)").get()));
++iter;
ASSERT_NE(iter, flattener.cend());
ASSERT_TRUE(iter);
ASSERT_EQ(iter->getGeometryTypeId(), geos::geom::GeometryTypeId::GEOS_POINT);
EXPECT_TRUE(iter->equals(from_wkt("POINT(2 2)").get()));
++iter;
ASSERT_EQ(iter, flattener.cend());
ASSERT_FALSE(iter);
}
TEST(GeometryFlattenerTests, TestSingleMultiPoint)
{
const auto geometry = from_wkt("MULTIPOINT((1 1))");
auto flattener = geom2graph::GeometryFlattener(*geometry);
auto iter = flattener.cbegin();
ASSERT_NE(iter, flattener.cend());
ASSERT_TRUE(iter);
ASSERT_EQ(iter->getGeometryTypeId(), geos::geom::GeometryTypeId::GEOS_POINT);
EXPECT_TRUE(iter->equals(from_wkt("POINT(1 1)").get()));
++iter;
ASSERT_EQ(iter, flattener.cend());
ASSERT_FALSE(iter);
}
TEST(GeometryFlattenerTests, TestSingleCollection)
{
const auto geometry = from_wkt("GEOMETRYCOLLECTION(POINT(1 1))");
auto flattener = geom2graph::GeometryFlattener(*geometry);
auto iter = flattener.cbegin();
ASSERT_NE(iter, flattener.cend());
ASSERT_TRUE(iter);
ASSERT_EQ(iter->getGeometryTypeId(), geos::geom::GeometryTypeId::GEOS_POINT);
EXPECT_TRUE(iter->equals(from_wkt("POINT(1 1)").get()));
++iter;
ASSERT_EQ(iter, flattener.cend());
ASSERT_FALSE(iter);
}
TEST(GeometryFlattenerTests, TestCollection)
{
const auto geometry = from_wkt("GEOMETRYCOLLECTION(POINT(1 1), POINT(2 2), POINT(3 3))");
auto flattener = geom2graph::GeometryFlattener(*geometry);
auto iter = flattener.cbegin();
ASSERT_NE(iter, flattener.cend());
ASSERT_TRUE(iter);
ASSERT_EQ(iter->getGeometryTypeId(), geos::geom::GeometryTypeId::GEOS_POINT);
EXPECT_TRUE(iter->equals(from_wkt("POINT(1 1)").get()));
++iter;
ASSERT_NE(iter, flattener.cend());
ASSERT_TRUE(iter);
ASSERT_EQ(iter->getGeometryTypeId(), geos::geom::GeometryTypeId::GEOS_POINT);
EXPECT_TRUE(iter->equals(from_wkt("POINT(2 2)").get()));
++iter;
ASSERT_NE(iter, flattener.cend());
ASSERT_TRUE(iter);
ASSERT_EQ(iter->getGeometryTypeId(), geos::geom::GeometryTypeId::GEOS_POINT);
EXPECT_TRUE(iter->equals(from_wkt("POINT(3 3)").get()));
++iter;
ASSERT_EQ(iter, flattener.cend());
ASSERT_FALSE(iter);
}
// End the collection with a multi-geometry to test the edge case where you can't mark the root as
// exhausted until you exhaust _all_ of the child.
TEST(GeometryFlattenerTests, TestCollectionWithMultiGeometry)
{
const auto geometry = from_wkt("GEOMETRYCOLLECTION(POINT(1 1), MULTIPOINT((2 2), (3 3)))");
auto flattener = geom2graph::GeometryFlattener(*geometry);
auto iter = flattener.cbegin();
ASSERT_NE(iter, flattener.cend());
ASSERT_TRUE(iter);
ASSERT_EQ(iter->getGeometryTypeId(), geos::geom::GeometryTypeId::GEOS_POINT);
EXPECT_TRUE(iter->equals(from_wkt("POINT(1 1)").get()));
++iter;
ASSERT_NE(iter, flattener.cend());
ASSERT_TRUE(iter);
ASSERT_EQ(iter->getGeometryTypeId(), geos::geom::GeometryTypeId::GEOS_POINT);
EXPECT_TRUE(iter->equals(from_wkt("POINT(2 2)").get()));
++iter;
ASSERT_NE(iter, flattener.cend());
ASSERT_TRUE(iter);
ASSERT_EQ(iter->getGeometryTypeId(), geos::geom::GeometryTypeId::GEOS_POINT);
EXPECT_TRUE(iter->equals(from_wkt("POINT(3 3)").get()));
++iter;
ASSERT_EQ(iter, flattener.cend());
ASSERT_FALSE(iter);
}
TEST(GeometryFlattenerTests, TestNestedCollection)
{
const auto geometry =
from_wkt("GEOMETRYCOLLECTION(GEOMETRYCOLLECTION(POINT(1 1), POINT(2 2)), POINT(3 3))");
auto flattener = geom2graph::GeometryFlattener(*geometry);
auto iter = flattener.cbegin();
ASSERT_NE(iter, flattener.cend());
ASSERT_TRUE(iter);
ASSERT_EQ(iter->getGeometryTypeId(), geos::geom::GeometryTypeId::GEOS_POINT);
EXPECT_TRUE(iter->equals(from_wkt("POINT(1 1)").get()));
++iter;
ASSERT_NE(iter, flattener.cend());
ASSERT_TRUE(iter);
ASSERT_EQ(iter->getGeometryTypeId(), geos::geom::GeometryTypeId::GEOS_POINT);
EXPECT_TRUE(iter->equals(from_wkt("POINT(2 2)").get()));
++iter;
ASSERT_NE(iter, flattener.cend());
ASSERT_TRUE(iter);
ASSERT_EQ(iter->getGeometryTypeId(), geos::geom::GeometryTypeId::GEOS_POINT);
EXPECT_TRUE(iter->equals(from_wkt("POINT(3 3)").get()));
++iter;
ASSERT_EQ(iter, flattener.cend());
ASSERT_FALSE(iter);
}
TEST(GeometryFlattenerTests, TestDeeplyNestedCollection)
{
const auto geometry = from_wkt(
// clang-format off
"GEOMETRYCOLLECTION("
"GEOMETRYCOLLECTION("
"POINT(1 1),"
"GEOMETRYCOLLECTION("
"MULTIPOINT((2 2), (3 3)),"
"POINT(4 4)"
"),"
"MULTIPOINT((5 5))"
"),"
"POINT(6 6),"
"MULTILINESTRING((7 7, 8 8, 9 9))"
")"
// clang-format on
);
const std::array<std::string, 7> expected_wkt = {
"POINT(1 1)",
"POINT(2 2)",
"POINT(3 3)",
"POINT(4 4)",
"POINT(5 5)",
"POINT(6 6)",
"LINESTRING(7 7, 8 8, 9 9)",
};
auto flattener = geom2graph::GeometryFlattener(*geometry);
size_t e = 0;
for (const auto& actual : flattener)
{
SCOPED_TRACE("Iteration: " + std::to_string(e));
const auto expected = from_wkt(expected_wkt.at(e));
ASSERT_EQ(expected->getGeometryType(), actual.getGeometryType());
ASSERT_TRUE(actual.equals(expected.get()));
e++;
}
}
TEST(GeometryFlattenerTests, RecursiveIteratorEquality)
{
// The multipoint will have a child iterator.
const auto geometry = from_wkt("GEOMETRYCOLLECTION(MULTIPOINT(1 1, 2 2), POINT(3 3))");
ASSERT_TRUE(geometry);
auto flattener = geom2graph::GeometryFlattener(*geometry);
const auto end = flattener.end();
auto iter1 = flattener.begin();
auto iter2 = flattener.begin();
ASSERT_NE(iter1, end);
ASSERT_EQ(iter1, iter2);
++iter1;
EXPECT_NE(iter1, iter2);
++iter2;
EXPECT_EQ(iter1, iter2);
++iter1;
++iter2;
EXPECT_EQ(iter1, iter2);
++iter1;
++iter2;
EXPECT_EQ(iter1, iter2);
EXPECT_EQ(iter1, end);
}
TEST(GeometryFlattenerTests, DeeplyRecursiveIteratorEquality)
{
const auto geometry = from_wkt(
// clang-format off
"GEOMETRYCOLLECTION("
"GEOMETRYCOLLECTION("
"POINT(1 1)," // 0
"GEOMETRYCOLLECTION("
"MULTIPOINT((2 2), (3 3))," // 1, 2
"POINT(4 4)" // 3
"),"
"MULTIPOINT((5 5))" // 4
"),"
"POINT(6 6)," // 5
"MULTILINESTRING((7 7, 8 8, 9 9))" // 6, 7, 8
")"
// clang-format on
);
ASSERT_TRUE(geometry);
auto flattener = geom2graph::GeometryFlattener(*geometry);
const auto end = flattener.end();
auto iter1 = flattener.begin();
auto iter2 = flattener.begin();
ASSERT_NE(iter1, end);
ASSERT_EQ(iter1, iter2);
++iter1;
ASSERT_NE(iter1, end);
EXPECT_NE(iter1, iter2);
++iter1;
ASSERT_NE(iter1, end);
EXPECT_NE(iter1, iter2);
++iter1;
ASSERT_NE(iter1, end);
EXPECT_NE(iter1, iter2);
std::advance(iter2, 3);
ASSERT_NE(iter2, end);
EXPECT_EQ(iter1, iter2);
std::advance(iter2, 3);
ASSERT_NE(iter2, end);
EXPECT_NE(iter1, iter2);
std::advance(iter1, 3);
ASSERT_NE(iter1, end);
EXPECT_EQ(iter1, iter2);
std::advance(iter1, 1);
std::advance(iter2, 1);
EXPECT_EQ(iter1, end);
EXPECT_EQ(iter1, iter2);
}
|
// Copyright (C) 2019 by Pedro Mendes, Rector and Visitors of the
// University of Virginia, University of Heidelberg, and University
// of Connecticut School of Medicine.
// All rights reserved.
// Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.
// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
// Copyright (C) 2005 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
// hoojee.cpp : optimization by the method of Hooke and Jeeves
//
/* Nonlinear Optimization using the algorithm of Hooke and Jeeves */
/* 12 February 1994 author: Mark G. Johnson */
/* Adapted for Gepasi by Pedro Mendes, 18 August 1997 */
#include <cmath>
#include "copasi/copasi.h"
#include "COptMethodHookeJeeves.h"
#include "COptProblem.h"
#include "COptItem.h"
#include "COptTask.h"
#include "copasi/core/CDataObjectReference.h"
COptMethodHookeJeeves::COptMethodHookeJeeves(const CDataContainer * pParent,
const CTaskEnum::Method & methodType,
const CTaskEnum::Task & taskType):
COptMethod(pParent, methodType, taskType)
{
assertParameter("Iteration Limit", CCopasiParameter::Type::UINT, (unsigned C_INT32) 50);
assertParameter("Tolerance", CCopasiParameter::Type::DOUBLE, (C_FLOAT64) 1.e-005);
assertParameter("Rho", CCopasiParameter::Type::DOUBLE, (C_FLOAT64) 0.2);
initObjects();
}
COptMethodHookeJeeves::COptMethodHookeJeeves(const COptMethodHookeJeeves & src,
const CDataContainer * pParent):
COptMethod(src, pParent)
{
initObjects();
}
COptMethodHookeJeeves::~COptMethodHookeJeeves()
{cleanup();}
bool COptMethodHookeJeeves::optimise()
{
mContinue = true;
if (!initialize())
{
if (mpCallBack)
mpCallBack->finishItem(mhIteration);
return false;
}
if (mLogVerbosity > 0)
mMethodLog.enterLogEntry(
COptLogEntry(
"Algorithm started",
"For more information about this method see: http://copasi.org/Support/User_Manual/Methods/Optimization_Methods/Hooke___Jeeves/"
)
);
C_FLOAT64 newf, steplength, tmp;
bool Keep;
size_t iadj;
// initial point is first guess
size_t i;
// initialise the guess vector
bool pointInParameterDomain = true;
for (i = 0; i < mVariableSize; i++)
{
C_FLOAT64 & mut = mIndividual[i];
COptItem & OptItem = *(*mpOptItem)[i];
mut = OptItem.getStartValue();
// force it to be within the bounds
switch (OptItem.checkConstraint(mut))
{
case - 1:
mut = *OptItem.getLowerBoundValue();
pointInParameterDomain = false;
break;
case 1:
mut = *OptItem.getUpperBoundValue();
pointInParameterDomain = false;
break;
}
// We need to set the value here so that further checks take
// account of the value.
*mContainerVariables[i] = mut;
}
if (!pointInParameterDomain && (mLogVerbosity > 0))
mMethodLog.enterLogEntry(COptLogEntry("Initial point outside parameter domain."));
mContinue &= evaluate();
// The first value is also the best
mBestValue = mEvaluationValue;
mpOptProblem->setSolution(mBestValue, mIndividual);
mpParentTask->output(COutputInterface::DURING);
if (!mContinue)
{
if (mLogVerbosity > 0)
mMethodLog.enterLogEntry(COptLogEntry("Algorithm was terminated by user."));
if (mpCallBack)
mpCallBack->finishItem(mhIteration);
cleanup();
return true;
}
for (i = 0; i < mVariableSize; i++)
{
mNew[i] = mBefore[i] = mIndividual[i];
mDelta[i] = fabs(mIndividual[i] * mRho);
if (mDelta[i] == 0.0) mDelta[i] = mRho;
}
iadj = 0;
steplength = mRho;
newf = mBestValue;
while ((mIteration < mIterationLimit) && (steplength > mTolerance) && mContinue)
{
// signal another iteration to Gepasi
if (mpCallBack)
mContinue &= mpCallBack->progressItem(mhIteration);
mIteration++;
iadj++;
/* find best new point, one coord at a time */
mNew = mBefore;
newf = bestNearby();
/* if we made some improvements, pursue that direction */
Keep = true;
while ((newf < mBestValue) && Keep && mContinue)
{
// We found a better value
mBestValue = newf;
mpOptProblem->setSolution(mBestValue, mNew);
mpParentTask->output(COutputInterface::DURING);
iadj = 0;
for (i = 0; i < mVariableSize; i++)
{
C_FLOAT64 & mut = mNew[i];
COptItem & OptItem = *(*mpOptItem)[i];
/* firstly, arrange the sign of mDelta[] */
if (mut <= mBefore[i])
mDelta[i] = - fabs(mDelta[i]);
else
mDelta[i] = fabs(mDelta[i]);
/* now, move further in this direction */
tmp = mBefore[i];
mBefore[i] = mut;
mut = mut + mut - tmp;
// force it to be within the bounds
switch (OptItem.checkConstraint(mut))
{
case - 1:
mut = *OptItem.getLowerBoundValue();
break;
case 1:
mut = *OptItem.getUpperBoundValue();
break;
}
// We need to set the value here so that further checks take
// account of the value.
*mContainerVariables[i] = mut;
}
newf = bestNearby();
/* if the further (optimistic) move was bad.... */
if (newf >= mBestValue) break;
/* make sure that the differences between the new */
/* and the old points are due to actual */
/* displacements; beware of roundoff errors that */
/* might cause newf < mBestValue */
Keep = false;
for (i = 0; i < mVariableSize; i++)
if (fabs(mNew[i] - mBefore[i]) > (0.5 * fabs(mDelta[i])))
{
Keep = true;
break;
}
}
if ((steplength >= mTolerance) && (newf >= mBestValue))
{
steplength = steplength * mRho;
for (i = 0; i < mVariableSize; i++)
mDelta[i] *= mRho;
}
}
if (mLogVerbosity > 0)
{
if (steplength < mTolerance)
mMethodLog.enterLogEntry(
COptLogEntry(
"Iteration " + std::to_string(mIteration) + ": Step length lower than tolerance. Terminating."));
mMethodLog.enterLogEntry(
COptLogEntry("Algorithm finished.",
"Terminated after " + std::to_string(mIteration) + " of " +
std::to_string(mIterationLimit) + " iterations."));
}
if (mpCallBack)
mpCallBack->finishItem(mhIteration);
cleanup();
return true;
}
void COptMethodHookeJeeves::initObjects()
{
addObjectReference("Current Iteration", mIteration, CDataObject::ValueInt);
}
bool COptMethodHookeJeeves::initialize()
{
cleanup();
if (!COptMethod::initialize()) return false;
mIterationLimit = getValue< unsigned C_INT32 >("Iteration Limit");
mTolerance = getValue< C_FLOAT64 >("Tolerance");
mRho = getValue< C_FLOAT64 >("Rho");
mIteration = 0;
if (mpCallBack)
mhIteration =
mpCallBack->addItem("Current Iteration",
mIteration,
& mIterationLimit);
mVariableSize = mpOptItem->size();
mIndividual.resize(mVariableSize);
mBefore.resize(mVariableSize);
mNew.resize(mVariableSize);
mDelta.resize(mVariableSize);
mBestValue = std::numeric_limits<C_FLOAT64>::infinity();
return true;
}
bool COptMethodHookeJeeves::cleanup()
{
return true;
}
bool COptMethodHookeJeeves::evaluate()
{
// We do not need to check whether the parametric constraints are fulfilled
// since the parameters are created within the bounds.
// evaluate the fitness
if (!mpOptProblem->checkParametricConstraints())
{
mEvaluationValue = std::numeric_limits< C_FLOAT64 >::max();
return mContinue;
}
mContinue &= mpOptProblem->calculate();
// check whether the functional constraints are fulfilled
if (!mpOptProblem->checkFunctionalConstraints())
mEvaluationValue = std::numeric_limits<C_FLOAT64>::infinity();
else
// get the value of the objective function
mEvaluationValue = mpOptProblem->getCalculateValue();
return mContinue;
}
// given a point, look for a better one nearby, one coord at a time
C_FLOAT64 COptMethodHookeJeeves::bestNearby()
{
C_FLOAT64 minf = mBestValue;
size_t i;
mIndividual = mNew;
for (i = 0; i < mVariableSize; i++)
*mContainerVariables[i] = mIndividual[i];
for (i = 0; i < mVariableSize; i++)
{
C_FLOAT64 & mut = mIndividual[i];
COptItem & OptItem = *(*mpOptItem)[i];
mut = mNew[i] + mDelta[i];
// force it to be within the bounds
switch (OptItem.checkConstraint(mut))
{
case - 1:
mut = *OptItem.getLowerBoundValue();
break;
case 1:
mut = *OptItem.getUpperBoundValue();
break;
}
// We need to set the value here so that further checks take
// account of the value.
*mContainerVariables[i] = mut;
if (!evaluate()) break;
if (mEvaluationValue < minf)
minf = mEvaluationValue;
else
{
mDelta[i] = - mDelta[i];
mut = mNew[i] + mDelta[i];
// force it to be within the bounds
switch (OptItem.checkConstraint(mut))
{
case - 1:
mut = *OptItem.getLowerBoundValue();
break;
case 1:
mut = *OptItem.getUpperBoundValue();
break;
}
// We need to set the value here so that further checks take
// account of the value.
*mContainerVariables[i] = mut;
if (!evaluate()) break;
if (mEvaluationValue < minf)
minf = mEvaluationValue;
else
{
mut = mNew[i];
*mContainerVariables[i] = mut;
}
}
}
mNew = mIndividual;
return (minf);
}
unsigned C_INT32 COptMethodHookeJeeves::getMaxLogVerbosity() const
{
return 0;
}
/* Find a point X where the nonlinear function f(X) has a local */
/* minimum. X is an n-vector and f(X) is a scalar. In mathe- */
/* matical notation f: R^n -> R^1. The objective function f() */
/* is not required to be continuous. Nor does f() need to be */
/* differentiable. The program does not use or require */
/* derivatives of f(). */
/* The software user supplies three things: a subroutine that */
/* computes f(X), an initial "starting guess" of the minimum point */
/* X, and values for the algorithm convergence parameters. Then */
/* the program searches for a local minimum, beginning from the */
/* starting guess, using the Direct Search algorithm of Hooke and */
/* Jeeves. */
/* This C program is adapted from the Algol pseudocode found in */
/* "Algorithm 178: Direct Search" by Arthur F. Kaupe Jr., Commun- */
/* ications of the ACM, Vol 6. p.313 (June 1963). It includes the */
/* improvements suggested by Bell and Pike (CACM v.9, p. 684, Sept */
/* 1966) and those of Tomlin and Smith, "Remark on Algorithm 178" */
/* (CACM v.12). The original paper, which I don't recommend as */
/* highly as the one by A. Kaupe, is: R. Hooke and T. A. Jeeves, */
/* "Direct Search Solution of Numerical and Statistical Problems", */
/* Journal of the ACM, Vol. 8, April 1961, pp. 212-229. */
/* Calling sequence: */
/* int hooke(mVariableSize, startpt, endpt, mRho, epsilon, mIterationLimit) */
/* */
/* mVariableSize {an integer} This is the number of dimensions */
/* in the domain of f(). It is the number of */
/* coordinates of the starting point (and the */
/* minimum point.) */
/* startpt {an array of C_FLOAT64s} This is the user- */
/* supplied guess at the minimum. */
/* endpt {an array of C_FLOAT64s} This is the location of */
/* the local minimum, calculated by the program */
/* mRho {a C_FLOAT64} This is a user-supplied convergence */
/* parameter (more detail below), which should be */
/* set to a value between 0.0 and 1.0. Larger */
/* values of mRho give greater probability of */
/* convergence on highly nonlinear functions, at a */
/* cost of more function evaluations. Smaller */
/* values of mRho reduces the number of evaluations */
/* (and the program running time), but increases */
/* the risk of nonconvergence. See below. */
/* epsilon {a C_FLOAT64} This is the criterion for halting */
/* the search for a minimum. When the algorithm */
/* begins to make less and less progress on each */
/* iteration, it checks the halting criterion: if */
/* the stepsize is below epsilon, terminate the */
/* iteration and return the current best estimate */
/* of the minimum. Larger values of epsilon (such */
/* as 1.0e-4) give quicker running time, but a */
/* less accurate estimate of the minimum. Smaller */
/* values of epsilon (such as 1.0e-7) give longer */
/* running time, but a more accurate estimate of */
/* the minimum. */
/* mIterationLimit {an integer} A second, rarely used, halting */
/* criterion. If the algorithm uses >= mIterationLimit */
/* iterations, halt. */
/* The user-supplied objective function f(x,n) should return a C */
/* "C_FLOAT64". Its arguments are x -- an array of C_FLOAT64s, and */
/* n -- an integer. x is the point at which f(x) should be */
/* evaluated, and n is the number of coordinates of x. That is, */
/* n is the number of coefficients being fitted. */
/* mRho, the algorithm convergence control */
/* The algorithm works by taking "steps" from one estimate of */
/* a minimum, to another (hopefully better) estimate. Taking */
/* big steps gets to the minimum more quickly, at the risk of */
/* "stepping right over" an excellent point. The stepsize is */
/* controlled by a user supplied parameter called mRho. At each */
/* iteration, the stepsize is multiplied by mRho (0 < mRho < 1), */
/* so the stepsize is successively reduced. */
/* Small values of mRho correspond to big stepsize changes, */
/* which make the algorithm run more quickly. However, there */
/* is a chance (especially with highly nonlinear functions) */
/* that these big changes will accidentally overlook a */
/* promising search vector, leading to nonconvergence. */
/* Large values of mRho correspond to small stepsize changes, */
/* which force the algorithm to carefully examine nearby points */
/* instead of optimistically forging ahead. This improves the */
/* probability of convergence. */
/* The stepsize is reduced until it is equal to (or smaller */
/* than) epsilon. So the number of iterations performed by */
/* Hooke-Jeeves is determined by mRho and epsilon: */
/* mRho**(number_of_iterations) = epsilon */
/* In general it is a good idea to set mRho to an aggressively */
/* small value like 0.5 (hoping for fast convergence). Then, */
/* if the user suspects that the reported minimum is incorrect */
/* (or perhaps not accurate enough), the program can be run */
/* again with a larger value of mRho such as 0.85, using the */
/* result of the first minimization as the starting guess to */
/* begin the second minimization. */
/* Normal use: (1) Code your function f() in the C language */
/* (2) Install your starting guess {or read it in} */
/* (3) Run the program */
/* (4) {for the skeptical}: Use the computed minimum */
/* as the starting point for another run */
/* Data Fitting: */
/* Code your function f() to be the sum of the squares of the */
/* errors (differences) between the computed values and the */
/* measured values. Then minimize f() using Hooke-Jeeves. */
/* EXAMPLE: you have 20 datapoints (ti, yi) and you want to */
/* find A,B,C such that (A*t*t) + (B*exp(t)) + (C*tan(t)) */
/* fits the data as closely as possible. Then f() is just */
/* f(x) = SUM (measured_y[i] - ((A*t[i]*t[i]) + (B*exp(t[i])) */
/* + (C*tan(t[i]))))^2 */
/* where x[] is a 3-vector consisting of {A, B, C}. */
/* */
/* The author of this software is M.G. Johnson. */
/* Permission to use, copy, modify, and distribute this software */
/* for any purpose without fee is hereby granted, provided that */
/* this entire notice is included in all copies of any software */
/* which is or includes a copy or modification of this software */
/* and in all copies of the supporting documentation for such */
/* software. THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT */
/* ANY EXPRESS OR IMPLIED WARRANTY. IN PARTICULAR, NEITHER THE */
/* AUTHOR NOR AT&T MAKE ANY REPRESENTATION OR WARRANTY OF ANY */
/* KIND CONCERNING THE MERCHANTABILITY OF THIS SOFTWARE OR ITS */
/* FITNESS FOR ANY PARTICULAR PURPOSE. */
/* */
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "addresstablemodel.h"
#include "guiutil.h"
#include "walletmodel.h"
#include "base58.h"
#include "wallet.h"
#include <QDebug>
#include <QFont>
const QString AddressTableModel::Send = "S";
const QString AddressTableModel::Receive = "R";
const QString AddressTableModel::Zerocoin = "X";
struct AddressTableEntry {
enum Type {
Sending,
Receiving,
Zerocoin,
Hidden /* QSortFilterProxyModel will filter these out */
};
Type type;
QString label;
QString address;
QString pubcoin;
AddressTableEntry() {}
AddressTableEntry(Type type, const QString &pubcoin): type(type), pubcoin(pubcoin) {}
AddressTableEntry(Type type, const QString& label, const QString& address) : type(type), label(label), address(address) {}
};
struct AddressTableEntryLessThan {
bool operator()(const AddressTableEntry& a, const AddressTableEntry& b) const
{
return a.address < b.address;
}
bool operator()(const AddressTableEntry& a, const QString& b) const
{
return a.address < b;
}
bool operator()(const QString& a, const AddressTableEntry& b) const
{
return a < b.address;
}
};
/* Determine address type from address purpose */
static AddressTableEntry::Type translateTransactionType(const QString& strPurpose, bool isMine)
{
AddressTableEntry::Type addressType = AddressTableEntry::Hidden;
// "refund" addresses aren't shown, and change addresses aren't in mapAddressBook at all.
if (strPurpose == "send")
addressType = AddressTableEntry::Sending;
else if (strPurpose == "receive")
addressType = AddressTableEntry::Receiving;
else if (strPurpose == "unknown" || strPurpose == "") // if purpose not set, guess
addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending);
return addressType;
}
// Private implementation
class AddressTablePriv
{
public:
CWallet* wallet;
QList<AddressTableEntry> cachedAddressTable;
AddressTableModel* parent;
AddressTablePriv(CWallet* wallet, AddressTableModel* parent) : wallet(wallet), parent(parent) {}
void refreshAddressTable()
{
cachedAddressTable.clear();
{
LOCK(wallet->cs_wallet);
BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & item, wallet->mapAddressBook) {
const CBitcoinAddress& address = item.first;
bool fMine = IsMine(*wallet, address.Get());
AddressTableEntry::Type addressType = translateTransactionType(
QString::fromStdString(item.second.purpose), fMine);
const std::string& strName = item.second.name;
cachedAddressTable.append(AddressTableEntry(addressType,
QString::fromStdString(strName),
QString::fromStdString(address.ToString())));
}
}
// qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order
// Even though the map is already sorted this re-sorting step is needed because the originating map
// is sorted by binary address, not by base58() address.
qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan());
}
void updateEntry(const QString& address, const QString& label, bool isMine, const QString& purpose, int status)
{
// Find address / label in model
QList<AddressTableEntry>::iterator lower = qLowerBound(
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
QList<AddressTableEntry>::iterator upper = qUpperBound(
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
int lowerIndex = (lower - cachedAddressTable.begin());
int upperIndex = (upper - cachedAddressTable.begin());
bool inModel = (lower != upper);
AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine);
switch (status) {
case CT_NEW:
if (inModel) {
qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_NEW, but entry is already in model";
break;
}
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address));
parent->endInsertRows();
break;
case CT_UPDATED:
if (!inModel) {
qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_UPDATED, but entry is not in model";
break;
}
lower->type = newEntryType;
lower->label = label;
parent->emitDataChanged(lowerIndex);
break;
case CT_DELETED:
if (!inModel) {
qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_DELETED, but entry is not in model";
break;
}
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex - 1);
cachedAddressTable.erase(lower, upper);
parent->endRemoveRows();
break;
}
}
void updateEntry(const QString &pubCoin, const QString &isUsed, int status)
{
// Find address / label in model
QList<AddressTableEntry>::iterator lower = qLowerBound(
cachedAddressTable.begin(), cachedAddressTable.end(), pubCoin, AddressTableEntryLessThan());
QList<AddressTableEntry>::iterator upper = qUpperBound(
cachedAddressTable.begin(), cachedAddressTable.end(), pubCoin, AddressTableEntryLessThan());
int lowerIndex = (lower - cachedAddressTable.begin());
bool inModel = (lower != upper);
AddressTableEntry::Type newEntryType = AddressTableEntry::Zerocoin;
switch(status)
{
case CT_NEW:
if(inModel)
{
qWarning() << "AddressTablePriv_ZC::updateEntry : Warning: Got CT_NEW, but entry is already in model";
}
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, isUsed, pubCoin));
parent->endInsertRows();
break;
case CT_UPDATED:
if(!inModel)
{
qWarning() << "AddressTablePriv_ZC::updateEntry : Warning: Got CT_UPDATED, but entry is not in model";
break;
}
lower->type = newEntryType;
lower->label = isUsed;
parent->emitDataChanged(lowerIndex);
break;
}
}
int size()
{
return cachedAddressTable.size();
}
AddressTableEntry* index(int idx)
{
if (idx >= 0 && idx < cachedAddressTable.size()) {
return &cachedAddressTable[idx];
} else {
return 0;
}
}
};
AddressTableModel::AddressTableModel(CWallet* wallet, WalletModel* parent) : QAbstractTableModel(parent), walletModel(parent), wallet(wallet), priv(0)
{
columns << tr("Label") << tr("Address");
priv = new AddressTablePriv(wallet, this);
priv->refreshAddressTable();
}
AddressTableModel::~AddressTableModel()
{
delete priv;
}
int AddressTableModel::rowCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int AddressTableModel::columnCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant AddressTableModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer());
if (role == Qt::DisplayRole || role == Qt::EditRole) {
switch (index.column()) {
case Label:
if (rec->label.isEmpty() && role == Qt::DisplayRole) {
return tr("(no label)");
} else {
return rec->label;
}
case Address:
return rec->address;
}
} else if (role == Qt::FontRole) {
QFont font;
if (index.column() == Address) {
font = GUIUtil::bitcoinAddressFont();
}
return font;
} else if (role == TypeRole) {
switch (rec->type) {
case AddressTableEntry::Sending:
return Send;
case AddressTableEntry::Receiving:
return Receive;
default:
break;
}
}
return QVariant();
}
bool AddressTableModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
if (!index.isValid())
return false;
AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer());
std::string strPurpose = (rec->type == AddressTableEntry::Sending ? "send" : "receive");
editStatus = OK;
if (role == Qt::EditRole) {
LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */
CTxDestination curAddress = CBitcoinAddress(rec->address.toStdString()).Get();
if (index.column() == Label) {
// Do nothing, if old label == new label
if (rec->label == value.toString()) {
editStatus = NO_CHANGES;
return false;
}
wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose);
} else if (index.column() == Address) {
CTxDestination newAddress = CBitcoinAddress(value.toString().toStdString()).Get();
// Refuse to set invalid address, set error status and return false
if (boost::get<CNoDestination>(&newAddress)) {
editStatus = INVALID_ADDRESS;
return false;
}
// Do nothing, if old address == new address
else if (newAddress == curAddress) {
editStatus = NO_CHANGES;
return false;
}
// Check for duplicate addresses to prevent accidental deletion of addresses, if you try
// to paste an existing address over another address (with a different label)
else if (wallet->mapAddressBook.count(newAddress)) {
editStatus = DUPLICATE_ADDRESS;
return false;
}
// Double-check that we're not overwriting a receiving address
else if (rec->type == AddressTableEntry::Sending) {
// Remove old entry
wallet->DelAddressBook(curAddress);
// Add new entry with new address
wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose);
}
}
return true;
}
return false;
}
QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal) {
if (role == Qt::DisplayRole && section < columns.size()) {
return columns[section];
}
}
return QVariant();
}
Qt::ItemFlags AddressTableModel::flags(const QModelIndex& index) const
{
if (!index.isValid())
return 0;
AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer());
Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
// Can edit address and label for sending addresses,
// and only label for receiving addresses.
if (rec->type == AddressTableEntry::Sending ||
(rec->type == AddressTableEntry::Receiving && index.column() == Label)) {
retval |= Qt::ItemIsEditable;
}
return retval;
}
QModelIndex AddressTableModel::index(int row, int column, const QModelIndex& parent) const
{
Q_UNUSED(parent);
AddressTableEntry* data = priv->index(row);
if (data) {
return createIndex(row, column, priv->index(row));
} else {
return QModelIndex();
}
}
void AddressTableModel::updateEntry(const QString& address,
const QString& label,
bool isMine,
const QString& purpose,
int status)
{
// Update address book model from NPay core
priv->updateEntry(address, label, isMine, purpose, status);
}
void AddressTableModel::updateEntry(const QString &pubCoin, const QString &isUsed, int status)
{
// Update stealth address book model from Bitcoin core
priv->updateEntry(pubCoin, isUsed, status);
}
QString AddressTableModel::addRow(const QString& type, const QString& label, const QString& address)
{
std::string strLabel = label.toStdString();
std::string strAddress = address.toStdString();
editStatus = OK;
if (type == Send) {
if (!walletModel->validateAddress(address)) {
editStatus = INVALID_ADDRESS;
return QString();
}
// Check for duplicate addresses
{
LOCK(wallet->cs_wallet);
if (wallet->mapAddressBook.count(CBitcoinAddress(strAddress).Get())) {
editStatus = DUPLICATE_ADDRESS;
return QString();
}
}
} else if (type == Receive) {
// Generate a new address to associate with given label
CPubKey newKey;
if (!wallet->GetKeyFromPool(newKey)) {
WalletModel::UnlockContext ctx(walletModel->requestUnlock(true));
if (!ctx.isValid()) {
// Unlock wallet failed or was cancelled
editStatus = WALLET_UNLOCK_FAILURE;
return QString();
}
if (!wallet->GetKeyFromPool(newKey)) {
editStatus = KEY_GENERATION_FAILURE;
return QString();
}
}
strAddress = CBitcoinAddress(newKey.GetID()).ToString();
} else {
return QString();
}
// Add entry
{
LOCK(wallet->cs_wallet);
wallet->SetAddressBook(CBitcoinAddress(strAddress).Get(), strLabel,
(type == Send ? "send" : "receive"));
}
return QString::fromStdString(strAddress);
}
bool AddressTableModel::removeRows(int row, int count, const QModelIndex& parent)
{
Q_UNUSED(parent);
AddressTableEntry* rec = priv->index(row);
if (count != 1 || !rec || rec->type == AddressTableEntry::Receiving) {
// Can only remove one row at a time, and cannot remove rows not in model.
// Also refuse to remove receiving addresses.
return false;
}
{
LOCK(wallet->cs_wallet);
wallet->DelAddressBook(CBitcoinAddress(rec->address.toStdString()).Get());
}
return true;
}
/* Look up label for address in address book, if not found return empty string.
*/
QString AddressTableModel::labelForAddress(const QString& address) const
{
{
LOCK(wallet->cs_wallet);
CBitcoinAddress address_parsed(address.toStdString());
std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(address_parsed.Get());
if (mi != wallet->mapAddressBook.end()) {
return QString::fromStdString(mi->second.name);
}
}
return QString();
}
int AddressTableModel::lookupAddress(const QString& address) const
{
QModelIndexList lst = match(index(0, Address, QModelIndex()),
Qt::EditRole, address, 1, Qt::MatchExactly);
if (lst.isEmpty()) {
return -1;
} else {
return lst.at(0).row();
}
}
void AddressTableModel::emitDataChanged(int idx)
{
emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length() - 1, QModelIndex()));
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
//===----------------------------------------------------------------------===//
/// \file
/// ES6.0 23.1 Initialize the Map constructor.
//===----------------------------------------------------------------------===//
#include "JSLibInternal.h"
#include "hermes/VM/StringPrimitive.h"
namespace hermes {
namespace vm {
Handle<JSObject> createMapConstructor(Runtime *runtime) {
auto mapPrototype = Handle<JSObject>::vmcast(&runtime->mapPrototype);
// Map.prototype.xxx methods.
defineMethod(
runtime,
mapPrototype,
Predefined::getSymbolID(Predefined::clear),
nullptr,
mapPrototypeClear,
0);
defineMethod(
runtime,
mapPrototype,
Predefined::getSymbolID(Predefined::deleteStr),
nullptr,
mapPrototypeDelete,
1);
defineMethod(
runtime,
mapPrototype,
Predefined::getSymbolID(Predefined::entries),
nullptr,
mapPrototypeEntries,
0);
defineMethod(
runtime,
mapPrototype,
Predefined::getSymbolID(Predefined::forEach),
nullptr,
mapPrototypeForEach,
1);
defineMethod(
runtime,
mapPrototype,
Predefined::getSymbolID(Predefined::get),
nullptr,
mapPrototypeGet,
1);
defineMethod(
runtime,
mapPrototype,
Predefined::getSymbolID(Predefined::has),
nullptr,
mapPrototypeHas,
1);
defineMethod(
runtime,
mapPrototype,
Predefined::getSymbolID(Predefined::keys),
nullptr,
mapPrototypeKeys,
0);
defineMethod(
runtime,
mapPrototype,
Predefined::getSymbolID(Predefined::set),
nullptr,
mapPrototypeSet,
2);
defineAccessor(
runtime,
mapPrototype,
Predefined::getSymbolID(Predefined::size),
nullptr,
mapPrototypeSizeGetter,
nullptr,
false,
true);
defineMethod(
runtime,
mapPrototype,
Predefined::getSymbolID(Predefined::values),
nullptr,
mapPrototypeValues,
0);
DefinePropertyFlags dpf = DefinePropertyFlags::getNewNonEnumerableFlags();
PseudoHandle<> propValue =
runtime->ignoreAllocationFailure(JSObject::getNamed_RJS(
mapPrototype, runtime, Predefined::getSymbolID(Predefined::entries)));
runtime->ignoreAllocationFailure(JSObject::defineOwnProperty(
mapPrototype,
runtime,
Predefined::getSymbolID(Predefined::SymbolIterator),
dpf,
runtime->makeHandle<NativeFunction>(propValue.get())));
dpf = DefinePropertyFlags::getDefaultNewPropertyFlags();
dpf.writable = 0;
dpf.enumerable = 0;
defineProperty(
runtime,
mapPrototype,
Predefined::getSymbolID(Predefined::SymbolToStringTag),
runtime->getPredefinedStringHandle(Predefined::Map),
dpf);
auto cons = defineSystemConstructor<JSMap>(
runtime,
Predefined::getSymbolID(Predefined::Map),
mapConstructor,
mapPrototype,
0,
CellKind::JSMapKind);
return cons;
}
CallResult<HermesValue>
mapConstructor(void *, Runtime *runtime, NativeArgs args) {
GCScope gcScope{runtime};
if (LLVM_UNLIKELY(!args.isConstructorCall())) {
return runtime->raiseTypeError("Constructor Map requires 'new'");
}
auto selfHandle = args.dyncastThis<JSMap>();
if (LLVM_UNLIKELY(!selfHandle)) {
return runtime->raiseTypeError(
"Map Constructor only applies to Map object");
}
JSMap::initializeStorage(selfHandle, runtime);
if (args.getArgCount() == 0 || args.getArg(0).isUndefined() ||
args.getArg(0).isNull()) {
return selfHandle.getHermesValue();
}
auto propRes = JSObject::getNamed_RJS(
selfHandle, runtime, Predefined::getSymbolID(Predefined::set));
if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
// ES6.0 23.1.1.1.7: Cache adder across all iterations of the loop.
auto adder =
Handle<Callable>::dyn_vmcast(runtime->makeHandle(std::move(*propRes)));
if (!adder) {
return runtime->raiseTypeError("Property 'set' for Map is not callable");
}
return addEntriesFromIterable(
runtime,
selfHandle,
args.getArgHandle(0),
[runtime, selfHandle, adder](Runtime *, Handle<> key, Handle<> value) {
return Callable::executeCall2(
adder,
runtime,
selfHandle,
key.getHermesValue(),
value.getHermesValue())
.getStatus();
});
}
CallResult<HermesValue>
mapPrototypeClear(void *, Runtime *runtime, NativeArgs args) {
auto selfHandle = args.dyncastThis<JSMap>();
if (LLVM_UNLIKELY(!selfHandle)) {
return runtime->raiseTypeError(
"Non-Map object called on Map.prototype.clear");
}
if (LLVM_UNLIKELY(!selfHandle->isInitialized())) {
return runtime->raiseTypeError(
"Method Map.prototype.clear called on incompatible receiver");
}
JSMap::clear(selfHandle, runtime);
return HermesValue::encodeUndefinedValue();
}
CallResult<HermesValue>
mapPrototypeDelete(void *, Runtime *runtime, NativeArgs args) {
auto selfHandle = args.dyncastThis<JSMap>();
if (LLVM_UNLIKELY(!selfHandle)) {
return runtime->raiseTypeError(
"Non-Map object called on Map.prototype.delete");
}
if (LLVM_UNLIKELY(!selfHandle->isInitialized())) {
return runtime->raiseTypeError(
"Method Map.prototype.delete called on incompatible receiver");
}
return HermesValue::encodeBoolValue(
JSMap::deleteKey(selfHandle, runtime, args.getArgHandle(0)));
}
CallResult<HermesValue>
mapPrototypeEntries(void *, Runtime *runtime, NativeArgs args) {
auto selfHandle = args.dyncastThis<JSMap>();
if (LLVM_UNLIKELY(!selfHandle)) {
return runtime->raiseTypeError(
"Non-Map object called on Map.prototype.entries");
}
if (LLVM_UNLIKELY(!selfHandle->isInitialized())) {
return runtime->raiseTypeError(
"Method Map.prototype.entries called on incompatible receiver");
}
auto iterator = runtime->makeHandle(JSMapIterator::create(
runtime, Handle<JSObject>::vmcast(&runtime->mapIteratorPrototype)));
iterator->initializeIterator(runtime, selfHandle, IterationKind::Entry);
return iterator.getHermesValue();
}
CallResult<HermesValue>
mapPrototypeForEach(void *, Runtime *runtime, NativeArgs args) {
auto selfHandle = args.dyncastThis<JSMap>();
if (LLVM_UNLIKELY(!selfHandle)) {
return runtime->raiseTypeError(
"Non-Map object called on Map.prototype.forEach");
}
if (LLVM_UNLIKELY(!selfHandle->isInitialized())) {
return runtime->raiseTypeError(
"Method Map.prototype.forEach called on incompatible receiver");
}
auto callbackfn = args.dyncastArg<Callable>(0);
if (LLVM_UNLIKELY(!callbackfn)) {
return runtime->raiseTypeError(
"callbackfn must be Callable in Map.prototype.forEach");
}
auto thisArg = args.getArgHandle(1);
if (JSMap::forEach(selfHandle, runtime, callbackfn, thisArg) ==
ExecutionStatus::EXCEPTION)
return ExecutionStatus::EXCEPTION;
return HermesValue::encodeUndefinedValue();
}
CallResult<HermesValue>
mapPrototypeGet(void *, Runtime *runtime, NativeArgs args) {
auto selfHandle = args.dyncastThis<JSMap>();
if (LLVM_UNLIKELY(!selfHandle)) {
return runtime->raiseTypeError(
"Non-Map object called on Map.prototype.get");
}
if (LLVM_UNLIKELY(!selfHandle->isInitialized())) {
return runtime->raiseTypeError(
"Method Map.prototype.get called on incompatible receiver");
}
return JSMap::getValue(selfHandle, runtime, args.getArgHandle(0));
}
CallResult<HermesValue>
mapPrototypeHas(void *, Runtime *runtime, NativeArgs args) {
auto selfHandle = args.dyncastThis<JSMap>();
if (LLVM_UNLIKELY(!selfHandle)) {
return runtime->raiseTypeError(
"Non-Map object called on Map.prototype.has");
}
if (LLVM_UNLIKELY(!selfHandle->isInitialized())) {
return runtime->raiseTypeError(
"Method Map.prototype.has called on incompatible receiver");
}
return HermesValue::encodeBoolValue(
JSMap::hasKey(selfHandle, runtime, args.getArgHandle(0)));
}
CallResult<HermesValue>
mapPrototypeKeys(void *, Runtime *runtime, NativeArgs args) {
auto selfHandle = args.dyncastThis<JSMap>();
if (LLVM_UNLIKELY(!selfHandle)) {
return runtime->raiseTypeError(
"Non-Map object called on Map.prototype.keys");
}
if (LLVM_UNLIKELY(!selfHandle->isInitialized())) {
return runtime->raiseTypeError(
"Method Map.prototype.keys called on incompatible receiver");
}
auto iterator = runtime->makeHandle(JSMapIterator::create(
runtime, Handle<JSObject>::vmcast(&runtime->mapIteratorPrototype)));
iterator->initializeIterator(runtime, selfHandle, IterationKind::Key);
return iterator.getHermesValue();
}
// ES12 23.1.3.9 Map.prototype.set ( key, value )
CallResult<HermesValue>
mapPrototypeSet(void *, Runtime *runtime, NativeArgs args) {
auto selfHandle = args.dyncastThis<JSMap>();
if (LLVM_UNLIKELY(!selfHandle)) {
return runtime->raiseTypeError(
"Non-Map object called on Map.prototype.set");
}
if (LLVM_UNLIKELY(!selfHandle->isInitialized())) {
return runtime->raiseTypeError(
"Method Map.prototype.set called on incompatible receiver");
}
auto keyHandle = args.getArgHandle(0);
// 5. If key is -0, set key to +0.
// N.B. in the case of Map, only key should be normalized but not the value.
auto key = keyHandle->isNumber() && keyHandle->getNumber() == 0
? HandleRootOwner::getZeroValue()
: keyHandle;
JSMap::addValue(selfHandle, runtime, key, args.getArgHandle(1));
return selfHandle.getHermesValue();
}
CallResult<HermesValue>
mapPrototypeSizeGetter(void *, Runtime *runtime, NativeArgs args) {
auto self = dyn_vmcast<JSMap>(args.getThisArg());
if (LLVM_UNLIKELY(!self)) {
return runtime->raiseTypeError(
"Non-Map object called on Map.prototype.size");
}
if (LLVM_UNLIKELY(!self->isInitialized())) {
return runtime->raiseTypeError(
"Method Map.prototype.size called on incompatible receiver");
}
return HermesValue::encodeNumberValue(JSMap::getSize(self, runtime));
}
CallResult<HermesValue>
mapPrototypeValues(void *, Runtime *runtime, NativeArgs args) {
auto selfHandle = args.dyncastThis<JSMap>();
if (LLVM_UNLIKELY(!selfHandle)) {
return runtime->raiseTypeError(
"Non-Map object called on Map.prototype.values");
}
if (LLVM_UNLIKELY(!selfHandle->isInitialized())) {
return runtime->raiseTypeError(
"Method Map.prototype.values called on incompatible receiver");
}
auto iterator = runtime->makeHandle(JSMapIterator::create(
runtime, Handle<JSObject>::vmcast(&runtime->mapIteratorPrototype)));
iterator->initializeIterator(runtime, selfHandle, IterationKind::Value);
return iterator.getHermesValue();
}
Handle<JSObject> createMapIteratorPrototype(Runtime *runtime) {
auto parentHandle = runtime->makeHandle(JSObject::create(
runtime, Handle<JSObject>::vmcast(&runtime->iteratorPrototype)));
defineMethod(
runtime,
parentHandle,
Predefined::getSymbolID(Predefined::next),
nullptr,
mapIteratorPrototypeNext,
0);
auto dpf = DefinePropertyFlags::getDefaultNewPropertyFlags();
dpf.writable = 0;
dpf.enumerable = 0;
defineProperty(
runtime,
parentHandle,
Predefined::getSymbolID(Predefined::SymbolToStringTag),
runtime->getPredefinedStringHandle(Predefined::MapIterator),
dpf);
return parentHandle;
}
CallResult<HermesValue>
mapIteratorPrototypeNext(void *, Runtime *runtime, NativeArgs args) {
auto selfHandle = args.dyncastThis<JSMapIterator>();
if (LLVM_UNLIKELY(!selfHandle)) {
return runtime->raiseTypeError(
"Non-MapIterator object called on MapIterator.prototype.next");
}
if (LLVM_UNLIKELY(!selfHandle->isInitialized())) {
return runtime->raiseTypeError(
"Method MapIterator.prototype.next called on incompatible receiver");
}
auto cr = JSMapIterator::nextElement(selfHandle, runtime);
if (LLVM_UNLIKELY(cr == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
return *cr;
}
} // namespace vm
} // namespace hermes
|
// Given an array of integers, return indices of the two numbers such that they add up to a specific target.
//
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
//
// Example:
//
// Given nums = [2, 7, 11, 15], target = 9,
//
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
std::vector<int> res;
std::unordered_map<int, int> m;
for (std::size_t i = 0; i < nums.size(); i++) {
auto iter = m.find(nums[i]);
if (iter == m.end()) {
m[target-nums[i]] = i;
} else {
res.push_back(iter->second);
res.push_back(i);
return res;
}
}
}
};
|
// Copyright (c) 2006-2008 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.
// Test of Histogram class
#include "base/histogram.h"
#include "base/string_util.h"
#include "base/time.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::TimeDelta;
namespace {
class HistogramTest : public testing::Test {
};
// Check for basic syntax and use.
TEST(HistogramTest, StartupShutdownTest) {
// Try basic construction
scoped_refptr<Histogram> histogram = Histogram::FactoryGet(
"TestHistogram", 1, 1000, 10, Histogram::kNoFlags);
scoped_refptr<Histogram> histogram1 = Histogram::FactoryGet(
"Test1Histogram", 1, 1000, 10, Histogram::kNoFlags);
scoped_refptr<Histogram> linear_histogram = LinearHistogram::FactoryGet(
"TestLinearHistogram", 1, 1000, 10, Histogram::kNoFlags);
scoped_refptr<Histogram> linear_histogram1 = LinearHistogram::FactoryGet(
"Test1LinearHistogram", 1, 1000, 10, Histogram::kNoFlags);
// Use standard macros (but with fixed samples)
HISTOGRAM_TIMES("Test2Histogram", TimeDelta::FromDays(1));
HISTOGRAM_COUNTS("Test3Histogram", 30);
DHISTOGRAM_TIMES("Test4Histogram", TimeDelta::FromDays(1));
DHISTOGRAM_COUNTS("Test5Histogram", 30);
HISTOGRAM_ENUMERATION("Test6Histogram", 129, 130);
// Try to construct samples.
Histogram::SampleSet sample1;
Histogram::SampleSet sample2;
// Use copy constructor of SampleSet
sample1 = sample2;
Histogram::SampleSet sample3(sample1);
// Finally test a statistics recorder, without really using it.
StatisticsRecorder recorder;
}
// Repeat with a recorder present to register with.
TEST(HistogramTest, RecordedStartupTest) {
// Test a statistics recorder, by letting histograms register.
StatisticsRecorder recorder; // This initializes the global state.
StatisticsRecorder::Histograms histograms;
EXPECT_EQ(0U, histograms.size());
StatisticsRecorder::GetHistograms(&histograms); // Load up lists
EXPECT_EQ(0U, histograms.size());
// Try basic construction
scoped_refptr<Histogram> histogram = Histogram::FactoryGet(
"TestHistogram", 1, 1000, 10, Histogram::kNoFlags);
histograms.clear();
StatisticsRecorder::GetHistograms(&histograms); // Load up lists
EXPECT_EQ(1U, histograms.size());
scoped_refptr<Histogram> histogram1 = Histogram::FactoryGet(
"Test1Histogram", 1, 1000, 10, Histogram::kNoFlags);
histograms.clear();
StatisticsRecorder::GetHistograms(&histograms); // Load up lists
EXPECT_EQ(2U, histograms.size());
scoped_refptr<Histogram> linear_histogram = LinearHistogram::FactoryGet(
"TestLinearHistogram", 1, 1000, 10, Histogram::kNoFlags);
scoped_refptr<Histogram> linear_histogram1 = LinearHistogram::FactoryGet(
"Test1LinearHistogram", 1, 1000, 10, Histogram::kNoFlags);
histograms.clear();
StatisticsRecorder::GetHistograms(&histograms); // Load up lists
EXPECT_EQ(4U, histograms.size());
// Use standard macros (but with fixed samples)
HISTOGRAM_TIMES("Test2Histogram", TimeDelta::FromDays(1));
HISTOGRAM_COUNTS("Test3Histogram", 30);
histograms.clear();
StatisticsRecorder::GetHistograms(&histograms); // Load up lists
EXPECT_EQ(6U, histograms.size());
HISTOGRAM_ENUMERATION("TestEnumerationHistogram", 20, 200);
histograms.clear();
StatisticsRecorder::GetHistograms(&histograms); // Load up lists
EXPECT_EQ(7U, histograms.size());
DHISTOGRAM_TIMES("Test4Histogram", TimeDelta::FromDays(1));
DHISTOGRAM_COUNTS("Test5Histogram", 30);
histograms.clear();
StatisticsRecorder::GetHistograms(&histograms); // Load up lists
#ifndef NDEBUG
EXPECT_EQ(9U, histograms.size());
#else
EXPECT_EQ(7U, histograms.size());
#endif
}
TEST(HistogramTest, RangeTest) {
StatisticsRecorder recorder;
StatisticsRecorder::Histograms histograms;
recorder.GetHistograms(&histograms);
EXPECT_EQ(0U, histograms.size());
scoped_refptr<Histogram> histogram = Histogram::FactoryGet(
"Histogram", 1, 64, 8, Histogram::kNoFlags); // As per header file.
// Check that we got a nice exponential when there was enough rooom.
EXPECT_EQ(0, histogram->ranges(0));
int power_of_2 = 1;
for (int i = 1; i < 8; i++) {
EXPECT_EQ(power_of_2, histogram->ranges(i));
power_of_2 *= 2;
}
EXPECT_EQ(INT_MAX, histogram->ranges(8));
scoped_refptr<Histogram> short_histogram = Histogram::FactoryGet(
"Histogram Shortened", 1, 7, 8, Histogram::kNoFlags);
// Check that when the number of buckets is short, we get a linear histogram
// for lack of space to do otherwise.
for (int i = 0; i < 8; i++)
EXPECT_EQ(i, short_histogram->ranges(i));
EXPECT_EQ(INT_MAX, short_histogram->ranges(8));
scoped_refptr<Histogram> linear_histogram = LinearHistogram::FactoryGet(
"Linear", 1, 7, 8, Histogram::kNoFlags);
// We also get a nice linear set of bucket ranges when we ask for it
for (int i = 0; i < 8; i++)
EXPECT_EQ(i, linear_histogram->ranges(i));
EXPECT_EQ(INT_MAX, linear_histogram->ranges(8));
scoped_refptr<Histogram> linear_broad_histogram = LinearHistogram::FactoryGet(
"Linear widened", 2, 14, 8, Histogram::kNoFlags);
// ...but when the list has more space, then the ranges naturally spread out.
for (int i = 0; i < 8; i++)
EXPECT_EQ(2 * i, linear_broad_histogram->ranges(i));
EXPECT_EQ(INT_MAX, linear_broad_histogram->ranges(8));
scoped_refptr<Histogram> transitioning_histogram =
Histogram::FactoryGet("LinearAndExponential", 1, 32, 15,
Histogram::kNoFlags);
// When space is a little tight, we transition from linear to exponential.
EXPECT_EQ(0, transitioning_histogram->ranges(0));
EXPECT_EQ(1, transitioning_histogram->ranges(1));
EXPECT_EQ(2, transitioning_histogram->ranges(2));
EXPECT_EQ(3, transitioning_histogram->ranges(3));
EXPECT_EQ(4, transitioning_histogram->ranges(4));
EXPECT_EQ(5, transitioning_histogram->ranges(5));
EXPECT_EQ(6, transitioning_histogram->ranges(6));
EXPECT_EQ(7, transitioning_histogram->ranges(7));
EXPECT_EQ(9, transitioning_histogram->ranges(8));
EXPECT_EQ(11, transitioning_histogram->ranges(9));
EXPECT_EQ(14, transitioning_histogram->ranges(10));
EXPECT_EQ(17, transitioning_histogram->ranges(11));
EXPECT_EQ(21, transitioning_histogram->ranges(12));
EXPECT_EQ(26, transitioning_histogram->ranges(13));
EXPECT_EQ(32, transitioning_histogram->ranges(14));
EXPECT_EQ(INT_MAX, transitioning_histogram->ranges(15));
recorder.GetHistograms(&histograms);
EXPECT_EQ(5U, histograms.size());
}
// Make sure histogram handles out-of-bounds data gracefully.
TEST(HistogramTest, BoundsTest) {
const size_t kBucketCount = 50;
scoped_refptr<Histogram> histogram = Histogram::FactoryGet(
"Bounded", 10, 100, kBucketCount, Histogram::kNoFlags);
// Put two samples "out of bounds" above and below.
histogram->Add(5);
histogram->Add(-50);
histogram->Add(100);
histogram->Add(10000);
// Verify they landed in the underflow, and overflow buckets.
Histogram::SampleSet sample;
histogram->SnapshotSample(&sample);
EXPECT_EQ(2, sample.counts(0));
EXPECT_EQ(0, sample.counts(1));
size_t array_size = histogram->bucket_count();
EXPECT_EQ(kBucketCount, array_size);
EXPECT_EQ(0, sample.counts(array_size - 2));
EXPECT_EQ(2, sample.counts(array_size - 1));
}
// Check to be sure samples land as expected is "correct" buckets.
TEST(HistogramTest, BucketPlacementTest) {
scoped_refptr<Histogram> histogram = Histogram::FactoryGet(
"Histogram", 1, 64, 8, Histogram::kNoFlags); // As per header file.
// Check that we got a nice exponential since there was enough rooom.
EXPECT_EQ(0, histogram->ranges(0));
int power_of_2 = 1;
for (int i = 1; i < 8; i++) {
EXPECT_EQ(power_of_2, histogram->ranges(i));
power_of_2 *= 2;
}
EXPECT_EQ(INT_MAX, histogram->ranges(8));
// Add i+1 samples to the i'th bucket.
histogram->Add(0);
power_of_2 = 1;
for (int i = 1; i < 8; i++) {
for (int j = 0; j <= i; j++)
histogram->Add(power_of_2);
power_of_2 *= 2;
}
// Leave overflow bucket empty.
// Check to see that the bucket counts reflect our additions.
Histogram::SampleSet sample;
histogram->SnapshotSample(&sample);
EXPECT_EQ(INT_MAX, histogram->ranges(8));
for (int i = 0; i < 8; i++)
EXPECT_EQ(i + 1, sample.counts(i));
}
} // namespace
|
// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "oldisim/FanoutManager.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "ConnectionUtil.h"
#include "FanoutManagerImpl.h"
#include "oldisim/ChildConnection.h"
#include "oldisim/ResponseContext.h"
#include "oldisim/Util.h"
namespace oldisim {
/**
* Implementation details for FanoutManager
*/
FanoutManager::FanoutManager(std::unique_ptr<FanoutManagerImpl> impl)
: impl_(move(impl)) {}
void FanoutManager::MakeChildConnection(uint32_t child_node_id) {
assert(child_node_id < impl_->child_nodes.size());
std::unique_ptr<ChildConnection> conn(ConnectionUtil::MakeChildConnection(
std::bind(FanoutManager::FanoutManagerImpl::ResponseCallback,
std::ref(*this), std::placeholders::_1),
std::bind(FanoutManager::FanoutManagerImpl::ChildConnectionClosedHandler,
std::ref(*this), std::placeholders::_1),
impl_->node_thread, impl_->child_node_addr[child_node_id],
*impl_->child_nodes[child_node_id].stats, false, true));
impl_->child_nodes[child_node_id].connections.emplace_back(std::move(conn));
}
void FanoutManager::MakeChildConnections(uint32_t child_node_id, int num) {
for (int i = 0; i < num; i++) {
MakeChildConnection(child_node_id);
}
}
void FanoutManager::Fanout(QueryContext&& originating_query,
const FanoutRequest* requests, int num_requests,
const FanoutDoneCallback& callback,
double timeout_ms) {
// Allocate new internal tracker
auto tracker = std::make_shared<FanoutReplyTrackerInternal>(
impl_->next_request_id, num_requests, callback,
std::move(originating_query));
// Send the request out on the child connections, round-robin between
// connections to the same child node
for (int i = 0; i < num_requests; i++) {
const FanoutRequest& request = requests[i];
ChildConnection& conn = impl_->GetConnection(request.child_node_id);
// Check if request type has been registered
if (impl_->request_types.count(request.request_type) == 0) {
DIE("Request type %d has not been registered\n", request.request_type);
}
conn.IssueRequest(request.request_type, impl_->next_request_id++,
request.request_data, request.request_data_length);
// Fill in tracking data
tracker->user_tracker.replies[i].child_node_id = request.child_node_id;
tracker->user_tracker.replies[i].request_type = request.request_type;
}
// Register the tracker
impl_->RegisterReplyTracker(tracker);
tracker->user_tracker.start_time = GetTimeAccurateNano();
// Activate timeout timer if specified
if (timeout_ms > 0) {
impl_->RegisterTrackerTimeout(tracker, timeout_ms);
}
}
void FanoutManager::FanoutAll(QueryContext&& originating_query,
const FanoutRequest& request,
const FanoutDoneCallback& callback,
double timeout_ms) {
// Check if request type has been registered
if (impl_->request_types.count(request.request_type) == 0) {
DIE("Request type %d has not been registered\n", request.request_type);
}
// Allocate new internal tracker
auto tracker = std::make_shared<FanoutReplyTrackerInternal>(
impl_->next_request_id, impl_->child_nodes.size(), callback,
std::move(originating_query));
// Send the request out on the child connections, round-robin between
// connections to the same child node
for (int i = 0; i < impl_->child_nodes.size(); i++) {
ChildConnection& conn = impl_->GetConnection(i);
conn.IssueRequest(request.request_type, impl_->next_request_id++,
request.request_data, request.request_data_length);
// Fill in tracking data
tracker->user_tracker.replies[i].child_node_id = i;
tracker->user_tracker.replies[i].request_type = request.request_type;
}
// Register the tracker
impl_->RegisterReplyTracker(tracker);
tracker->user_tracker.start_time = GetTimeAccurateNano();
// Activate timeout timer if specified
if (timeout_ms > 0) {
impl_->RegisterTrackerTimeout(tracker, timeout_ms);
}
}
/**
* Implementation details for FanoutManagerImpl
*/
FanoutManager::FanoutManagerImpl::FanoutManagerImpl(
const std::vector<addrinfo*>& _child_node_addr,
const std::set<uint32_t>& _request_types, const NodeThread& _node_thread)
: child_node_addr(_child_node_addr),
next_request_id(0),
request_types(_request_types),
node_thread(_node_thread) {
child_nodes.resize(child_node_addr.size());
// Create connection stats objects for each node
for (int i = 0; i < child_nodes.size(); i++) {
child_nodes[i].stats.reset(new ChildConnectionStats(request_types));
}
}
ChildConnection& FanoutManager::FanoutManagerImpl::GetConnection(
uint32_t child_node_id) {
assert(child_node_id < child_nodes.size());
assert(child_nodes[child_node_id].connections.size() > 0);
const auto& connection_ptr =
child_nodes[child_node_id]
.connections[child_nodes[child_node_id].next_connection_index];
child_nodes[child_node_id].next_connection_index =
(child_nodes[child_node_id].next_connection_index + 1) %
child_nodes[child_node_id].connections.size();
return *connection_ptr;
}
void FanoutManager::FanoutManagerImpl::RegisterReplyTracker(
std::shared_ptr<FanoutReplyTrackerInternal> tracker) {
for (int i = 0; i < tracker->user_tracker.num_requests; i++) {
uint64_t request_id = tracker->user_tracker.starting_request_id + i;
assert(tracker_by_id.count(request_id) == 0);
tracker_by_id[request_id] = tracker;
}
}
void FanoutManager::FanoutManagerImpl::UnregisterReplyTracker(
const FanoutReplyTrackerInternal& tracker) {
const uint32_t num_requests = tracker.user_tracker.num_requests;
const uint64_t starting_request_id = tracker.user_tracker.starting_request_id;
for (int i = 0; i < num_requests; i++) {
uint64_t request_id = starting_request_id + i;
assert(tracker_by_id.count(request_id) == 1);
assert(tracker_by_id.at(request_id).get() == &tracker);
tracker_by_id.erase(request_id);
}
}
void FanoutManager::FanoutManagerImpl::RegisterTrackerTimeout(
const std::shared_ptr<FanoutReplyTrackerInternal>& tracker,
double timeout_ms) {
// Make a heap-allocated shared_ptr to not leak the tracker
auto timeout_args = new TimeoutArgs(*this, tracker);
tracker->timeout_event = evtimer_new(
node_thread.get_event_base(),
FanoutManager::FanoutManagerImpl::TimeoutCallback, timeout_args);
timeval tv;
DoubleToTv(timeout_ms / 1000, &tv);
evtimer_add(tracker->timeout_event, &tv);
}
void FanoutManager::FanoutManagerImpl::CloseTracker(
FanoutManager& manager, FanoutReplyTrackerInternal& tracker) {
CloseTracker(*manager.impl_, tracker);
}
void FanoutManager::FanoutManagerImpl::CloseTracker(
FanoutManagerImpl& manager_impl, FanoutReplyTrackerInternal& tracker) {
tracker.user_tracker.closed = true; // Close the tracker
tracker.done_callback(tracker.originating_query,
tracker.user_tracker); // Call user-callback
if (tracker.timeout_event != nullptr) {
// Deregister timeout event
auto timeout_args = reinterpret_cast<TimeoutArgs*>(
event_get_callback_arg(tracker.timeout_event));
delete timeout_args;
event_free(tracker.timeout_event);
tracker.timeout_event = nullptr;
}
// Have to do this last, because when the last one is deleted the
// reference becomes no-good (shared-ptr) will clean it up from under you
manager_impl.UnregisterReplyTracker(tracker); // remove from tracker table
}
void FanoutManager::FanoutManagerImpl::ResponseCallback(
FanoutManager& manager, ResponseContext& context) {
// Get the tracking data structure in the map
const auto& tracker_it =
manager.impl_->tracker_by_id.find(context.request_id);
if (tracker_it == manager.impl_->tracker_by_id.end()) {
return;
} else {
FanoutReplyTrackerInternal& tracker = *tracker_it->second;
// Debug checking
assert(context.request_id >= tracker.user_tracker.starting_request_id);
assert(context.request_id < tracker.user_tracker.starting_request_id +
tracker.user_tracker.num_requests);
// Find the index in the tracker holding the reply struct
int index = context.request_id - tracker.user_tracker.starting_request_id;
FanoutReply& reply = tracker.user_tracker.replies[index];
assert(reply.request_type == context.type);
assert(reply.reply_data == nullptr);
// Fill in the fields of the reply object
reply.timed_out = false;
// Allocate memory to copy the payload data
uint8_t* payload_copy = new uint8_t[context.payload_length];
memcpy(payload_copy, context.payload, context.payload_length);
reply.reply_data = std::unique_ptr<uint8_t[]>(payload_copy);
reply.reply_data_length = context.payload_length;
reply.latency_ms =
(context.response_timestamp - context.request_timestamp) / 1000000.0;
// Update tracker, check to see if all responses received
tracker.user_tracker.num_replies_received++;
if (tracker.user_tracker.num_replies_received ==
tracker.user_tracker.num_requests) {
CloseTracker(manager, tracker);
}
}
}
void FanoutManager::FanoutManagerImpl::ChildConnectionClosedHandler(
const FanoutManager& manager, const ChildConnection& conn) {}
void FanoutManager::FanoutManagerImpl::TimeoutCallback(evutil_socket_t listener,
int16_t event,
void* arg) {
auto args = reinterpret_cast<TimeoutArgs*>(arg);
FanoutManager::FanoutManagerImpl& manager_impl = std::get<0>(*args);
auto tracker = std::get<1>(*args);
// Log timed out requests
for (const auto& reply_tracker : tracker->user_tracker.replies) {
if (reply_tracker.timed_out) {
manager_impl.child_nodes[reply_tracker.child_node_id]
.stats->LogDroppedRequest(reply_tracker.request_type);
}
}
CloseTracker(manager_impl, *tracker);
}
/**
* Implementation details of FanoutReplyTrackerInternal
*/
static FanoutReply EmptyFanoutReply() {
FanoutReply empty;
empty.timed_out = true;
empty.child_node_id = 0;
empty.request_type = 0;
empty.reply_data = nullptr;
empty.reply_data_length = 0;
empty.latency_ms = 0.0f;
return empty;
}
FanoutReplyTrackerInternal::FanoutReplyTrackerInternal(
uint64_t starting_request_id, int num_requests,
const FanoutManager::FanoutDoneCallback& _done_callback,
QueryContext&& _originating_query)
: done_callback(_done_callback),
timeout_event(nullptr),
originating_query(std::move(_originating_query)) {
// Initialize user_tracker
user_tracker.starting_request_id = starting_request_id;
user_tracker.num_requests = num_requests;
user_tracker.num_replies_received = 0;
user_tracker.closed = false;
// Fill up FanoutReply vector
user_tracker.replies.reserve(num_requests);
for (int i = 0; i < num_requests; i++) {
user_tracker.replies.emplace_back(EmptyFanoutReply());
}
}
FanoutReplyTrackerInternal::~FanoutReplyTrackerInternal() {
if (timeout_event != nullptr) {
event_free(timeout_event);
timeout_event = nullptr;
}
}
} // namespace oldisim
|
//
// detail/posix_static_mutex.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2014 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 BOOST_ASIO_DETAIL_POSIX_STATIC_MUTEX_HPP
#define BOOST_ASIO_DETAIL_POSIX_STATIC_MUTEX_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#if defined(BOOST_ASIO_HAS_PTHREADS)
#include <pthread.h>
#include <boost/asio/detail/scoped_lock.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
namespace detail {
struct posix_static_mutex
{
typedef boost::asio::detail::scoped_lock<posix_static_mutex> scoped_lock;
// Initialise the mutex.
void init()
{
// Nothing to do.
}
// Lock the mutex.
void lock()
{
(void)::pthread_mutex_lock(&mutex_); // Ignore EINVAL.
}
// Unlock the mutex.
void unlock()
{
(void)::pthread_mutex_unlock(&mutex_); // Ignore EINVAL.
}
::pthread_mutex_t mutex_;
};
#define BOOST_ASIO_POSIX_STATIC_MUTEX_INIT { PTHREAD_MUTEX_INITIALIZER }
} // namespace detail
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#endif // defined(BOOST_ASIO_HAS_PTHREADS)
#endif // BOOST_ASIO_DETAIL_POSIX_STATIC_MUTEX_HPP
|
/**
* WriteACodeTemplate!
*/
#include <fstream>
using namespace std;
/**
* File Management
*/
ifstream fin("input.txt");
ofstream fout("output.txt");
/**
* Constants
*/
struct Keyboard {
int width;
int height;
};
/**
* Main
*/
int main(void)
{
// Parse template
Keyboard keyboard = initializeKeyboard(fin);
// Match on Logic
// Build Output
fout << "out\n";
return EXIT_SUCCESS;
}
|
#include "../test_helpers.hxx"
namespace
{
void test_result_iteration()
{
pqxx::connection conn;
pqxx::work tx{conn};
pqxx::result r = tx.exec("SELECT generate_series(1, 3)");
PQXX_CHECK(r.end() != r.begin(), "Broken begin/end.");
PQXX_CHECK(r.rend() != r.rbegin(), "Broken rbegin/rend.");
PQXX_CHECK(r.cbegin() == r.begin(), "Wrong cbegin.");
PQXX_CHECK(r.cend() == r.end(), "Wrong cend.");
PQXX_CHECK(r.crbegin() == r.rbegin(), "Wrong crbegin.");
PQXX_CHECK(r.crend() == r.rend(), "Wrong crend.");
PQXX_CHECK_EQUAL(r.front().front().as<int>(), 1, "Unexpected front().");
PQXX_CHECK_EQUAL(r.back().front().as<int>(), 3, "Unexpected back().");
}
PQXX_REGISTER_TEST(test_result_iteration);
} // namespace
|
/*
* 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/inspector/model/RulesPackage.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Inspector
{
namespace Model
{
RulesPackage::RulesPackage() :
m_rulesPackageArnHasBeenSet(false),
m_rulesPackageNameHasBeenSet(false),
m_versionHasBeenSet(false),
m_providerHasBeenSet(false),
m_descriptionHasBeenSet(false)
{
}
RulesPackage::RulesPackage(const JsonValue& jsonValue) :
m_rulesPackageArnHasBeenSet(false),
m_rulesPackageNameHasBeenSet(false),
m_versionHasBeenSet(false),
m_providerHasBeenSet(false),
m_descriptionHasBeenSet(false)
{
*this = jsonValue;
}
RulesPackage& RulesPackage::operator =(const JsonValue& jsonValue)
{
if(jsonValue.ValueExists("rulesPackageArn"))
{
m_rulesPackageArn = jsonValue.GetString("rulesPackageArn");
m_rulesPackageArnHasBeenSet = true;
}
if(jsonValue.ValueExists("rulesPackageName"))
{
m_rulesPackageName = jsonValue.GetString("rulesPackageName");
m_rulesPackageNameHasBeenSet = true;
}
if(jsonValue.ValueExists("version"))
{
m_version = jsonValue.GetString("version");
m_versionHasBeenSet = true;
}
if(jsonValue.ValueExists("provider"))
{
m_provider = jsonValue.GetString("provider");
m_providerHasBeenSet = true;
}
if(jsonValue.ValueExists("description"))
{
m_description = jsonValue.GetObject("description");
m_descriptionHasBeenSet = true;
}
return *this;
}
JsonValue RulesPackage::Jsonize() const
{
JsonValue payload;
if(m_rulesPackageArnHasBeenSet)
{
payload.WithString("rulesPackageArn", m_rulesPackageArn);
}
if(m_rulesPackageNameHasBeenSet)
{
payload.WithString("rulesPackageName", m_rulesPackageName);
}
if(m_versionHasBeenSet)
{
payload.WithString("version", m_version);
}
if(m_providerHasBeenSet)
{
payload.WithString("provider", m_provider);
}
if(m_descriptionHasBeenSet)
{
payload.WithObject("description", m_description.Jsonize());
}
return payload;
}
} // namespace Model
} // namespace Inspector
} // namespace Aws
|
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Christian Schulte <schulte@gecode.org>
*
* Contributing authors:
* Guido Tack <tack@gecode.org>
*
* Copyright:
* Christian Schulte, 2004
* Guido Tack, 2004
*
* Last modified:
* $Date: 2016-04-20 01:19:45 +1000 (Wed, 20 Apr 2016) $ by $Author: schulte $
* $Revision: 14967 $
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* 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 __GECODE_SEARCH_SEQUENTIAL_BAB_HH__
#define __GECODE_SEARCH_SEQUENTIAL_BAB_HH__
#include <gecode/search.hh>
#include <gecode/search/support.hh>
#include <gecode/search/worker.hh>
#include <gecode/search/sequential/path.hh>
namespace Gecode { namespace Search { namespace Sequential {
/// Implementation of depth-first branch-and-bound search engine
class BAB : public Worker {
private:
/// Search options
Options opt;
/// Current path in search tree
Path path;
/// Current space being explored
Space* cur;
/// Distance until next clone
unsigned int d;
/// Number of entries not yet constrained to be better
int mark;
/// Best solution found so far
Space* best;
public:
/// Initialize with space \a s and search options \a o
BAB(Space* s, const Options& o);
/// %Search for next better solution
Space* next(void);
/// Return statistics
Statistics statistics(void) const;
/// Constrain future solutions to be better than \a b
void constrain(const Space& b);
/// Reset engine to restart at space \a s
void reset(Space* s);
/// Return no-goods
NoGoods& nogoods(void);
/// Destructor
~BAB(void);
};
forceinline
BAB::BAB(Space* s, const Options& o)
: opt(o), path(opt.nogoods_limit), d(0), mark(0), best(NULL) {
if ((s == NULL) || (s->status(*this) == SS_FAILED)) {
fail++;
cur = NULL;
if (!o.clone)
delete s;
} else {
cur = snapshot(s,opt);
}
}
forceinline Space*
BAB::next(void) {
/*
* The engine maintains the following invariant:
* - If the current space (cur) is not NULL, the path always points
* to exactly that space.
* - If the current space (cur) is NULL, the path always points
* to the next space (if there is any).
*
* This invariant is needed so that no-goods can be extracted properly
* when the engine is stopped or has found a solution.
*
* An additional invariant maintained by the engine is:
* For all nodes stored at a depth less than mark, there
* is no guarantee of betterness. For those above the mark,
* betterness is guaranteed.
*
*/
start();
while (true) {
if (stop(opt))
return NULL;
// Recompute and add constraint if necessary
while (cur == NULL) {
if (path.empty())
return NULL;
cur = path.recompute(d,opt.a_d,*this,*best,mark);
if (cur != NULL)
break;
path.next();
}
node++;
switch (cur->status(*this)) {
case SS_FAILED:
fail++;
delete cur;
cur = NULL;
path.next();
break;
case SS_SOLVED:
// Deletes all pending branchers
(void) cur->choice();
delete best;
best = cur;
cur = NULL;
path.next();
mark = path.entries();
return best->clone();
case SS_BRANCH:
{
Space* c;
if ((d == 0) || (d >= opt.c_d)) {
c = cur->clone();
d = 1;
} else {
c = NULL;
d++;
}
const Choice* ch = path.push(*this,cur,c);
cur->commit(*ch,0);
break;
}
default:
GECODE_NEVER;
}
}
GECODE_NEVER;
return NULL;
}
forceinline Statistics
BAB::statistics(void) const {
return *this;
}
forceinline void
BAB::constrain(const Space& b) {
if (best != NULL) {
// Check whether b is in fact better than best
best->constrain(b);
if (best->status(*this) != SS_FAILED)
return;
else
delete best;
}
best = b.clone();
if (cur != NULL)
cur->constrain(b);
mark = path.entries();
}
forceinline void
BAB::reset(Space* s) {
delete best;
best = NULL;
path.reset();
d = 0;
mark = 0;
delete cur;
if ((s == NULL) || (s->status(*this) == SS_FAILED)) {
delete s;
cur = NULL;
} else {
cur = s;
}
Worker::reset();
}
forceinline NoGoods&
BAB::nogoods(void) {
return path;
}
forceinline
BAB::~BAB(void) {
path.reset();
delete best;
delete cur;
}
}}}
#endif
// STATISTICS: search-sequential
|
#include "ComputeEulerRHS.H"
#include "FFTW1D.H"
#include "WriteRectMDArray.H"
void ComputeEulerRHS::operator() (DeltaVelocity& a_newDv,
const double& a_time,
const double& a_dt,
const FieldData& a_velocity,
DeltaVelocity& a_oldDv) {
double a_scalar = 1.0;
//std::shared_ptr<FFT1D> fft1dptr(a_velocity.m_N); std::shared_ptr<FFT1D> fft1dptr(new FFTW1D(a_velocity.m_M));
//create dummy variables
FieldData velTemp;
a_velocity.copyTo(velTemp);
DeltaVelocity deltaV;
//int index[DIM];
Projection projVel(a_velocity.m_fft1dptr);
DBox bx = a_velocity.m_grid;
//increment veltemp by a_oldDv
velTemp.increment(a_scalar,a_oldDv);
//apply advection on veltemp (what is uu?) advectionOperator(DeltaVelocity& a_divuu,const FieldData& a_velocity,const Box m_grid, const double& a_h);
advectionOperator(deltaV,velTemp, a_velocity.m_grid,a_dt);
velTemp.increment(-a_dt,deltaV);
velTemp.setBoundaries();
projVel.applyProjection(velTemp);
//assigning a_newDv :: veltemp2 - a_velocity
for(Point pt = bx.getLowCorner(); bx.notDone(pt); bx.increment(pt)) {
/* for(int i = 0; i <a_velocity.m_M; i++) {
for(int j = 0; j <a_velocity.m_N; j++) {
index[0]= i;
index[1] = j;
a_newDv[0][index]= (velTemp2[0])[index] - (a_velocity[0])[index];
a_newDv[1][index]= (velTemp2[1])[index] - (a_velocity[1])[index];
}
}*/
a_newDv.m_data(pt, 0) = velTemp.m_data(pt, 0) - a_velocity.m_data(pt, 0);
a_newDv.m_data(pt, 1) = velTemp.m_data(pt, 1) - a_velocity.m_data(pt, 1);
}
// MDWrite(a_newDv[1]);
}
|
#ifndef CK_GRIDWISE_GROUP_CONVOLUTION_FORWARD_IMPLICIT_GEMM_V4R5_XDLOPS_GNCHW_GKCYX_GNKHW_HPP
#define CK_GRIDWISE_GROUP_CONVOLUTION_FORWARD_IMPLICIT_GEMM_V4R5_XDLOPS_GNCHW_GKCYX_GNKHW_HPP
#include "common_header.hpp"
#include "tensor_descriptor.hpp"
#include "tensor_descriptor_helper.hpp"
#include "ConstantMatrixDescriptor.hpp"
#include "gridwise_gemm_xdlops_fp16_bfp16.hpp"
namespace ck {
template <index_t GridSize,
index_t BlockSize,
class ABFloat,
class AccFloat,
class CFloat,
class InGlobalDesc,
class WeiGlobalDesc,
class OutGlobalDesc,
index_t G,
class ConvStrides,
class ConvDilations,
class InLeftPads,
class InRightPads,
index_t GemmMPerBlock,
index_t BPerBlock,
index_t GemmKPerBlock,
index_t GemmMPerWave,
index_t BPerWave,
index_t NWaves,
index_t GemmKPack,
class GemmABlockCopyThreadSliceLengths_GemmG_GemmK_GemmM_GemmKPack,
class GemmABlockCopyThreadClusterLengths_GemmG_GemmK_GemmM_GemmKPack,
class GemmABlockCopyThreadClusterArrangeOrder,
class GemmABlockCopySrcAccessOrder,
class GemmABlockCopyDstAccessOrder,
index_t GemmABlockCopySrcDataPerRead_GemmKPack,
index_t GemmABlockCopyDstDataPerWrite_GemmKPack,
class GemmBBlockCopyThreadSliceLengths_GemmG_GemmK_NWaves_B_GemmKPack,
class GemmBBlockCopyThreadClusterLengths_GemmG_GemmK_NWaves_B_GemmKPack,
class GemmBBlockCopyThreadClusterArrangeOrder,
class GemmBBlockCopySrcAccessOrder,
class GemmBBlockCopyDstAccessOrder,
index_t GemmBBlockCopySrcDataPerRead_B,
index_t GemmBBlockCopyDstDataPerWrite_GemmKPack,
WorkgroupScheduleOrder WorkgroupSchdOrder>
struct GridwiseConvolutionForwardImplicitGemm_v4r5_xdlops_nchw_kcyx_nkhw
{
__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 in_n_c_hi_wi_global_desc = InGlobalDesc{};
constexpr auto wei_k_cpergroup_y_x_global_desc = WeiGlobalDesc{};
constexpr auto out_n_k_ho_wo_global_desc = OutGlobalDesc{};
constexpr index_t N = in_n_c_hi_wi_global_desc.GetLengths()[0];
constexpr index_t C = in_n_c_hi_wi_global_desc.GetLengths()[1];
constexpr index_t Hi = in_n_c_hi_wi_global_desc.GetLengths()[2];
constexpr index_t Wi = in_n_c_hi_wi_global_desc.GetLengths()[3];
constexpr index_t K = out_n_k_ho_wo_global_desc.GetLengths()[1];
constexpr index_t Ho = out_n_k_ho_wo_global_desc.GetLengths()[2];
constexpr index_t Wo = out_n_k_ho_wo_global_desc.GetLengths()[3];
constexpr index_t Y = wei_k_cpergroup_y_x_global_desc.GetLengths()[2];
constexpr index_t X = wei_k_cpergroup_y_x_global_desc.GetLengths()[3];
constexpr index_t CPerGroup = C / G;
constexpr index_t KPerGroup = K / G;
static_assert(CPerGroup == wei_k_cpergroup_y_x_global_desc.GetLengths()[1], "wrong!");
constexpr index_t ConvStrideH = ConvStrides{}[0];
constexpr index_t ConvStrideW = ConvStrides{}[1];
constexpr index_t ConvDilationH = ConvDilations{}[0];
constexpr index_t ConvDilationW = ConvDilations{}[1];
constexpr index_t N1 = N / NWaves;
constexpr index_t GemmG = G;
constexpr index_t GemmM = KPerGroup;
constexpr index_t B = N1 * Ho * Wo;
constexpr index_t GemmKTotal = CPerGroup * Y * X;
static_assert(GemmKTotal % GemmKPack == 0,
"wrong! GemmKTotal should be multiple of GemmKPack");
constexpr index_t GemmK = GemmKTotal / GemmKPack;
static_assert(GemmM % GemmMPerBlock == 0 && B % BPerBlock == 0 &&
GemmK % GemmKPerBlock == 0,
"wrong! cannot divide work evenly among block");
// construct tensor descriptor for group convolution
constexpr auto in_g_n_cpergroup_hi_wi_global_desc = make_native_tensor_descriptor(
Sequence<G, N, CPerGroup, Hi, Wi>{},
Sequence<CPerGroup * Hi * Wi, C * Hi * Wi, Hi * Wi, Wi, 1>{});
constexpr auto wei_g_kpergroup_cpergroup_y_x_global_desc =
make_native_tensor_descriptor_packed(Sequence<G, KPerGroup, CPerGroup, Y, X>{});
constexpr auto out_g_n_kpergroup_ho_wo_global_desc = make_native_tensor_descriptor(
Sequence<G, N, KPerGroup, Ho, Wo>{},
Sequence<KPerGroup * Ho * Wo, K * Ho * Wo, Ho * Wo, Wo, 1>{});
// input tensor
constexpr auto in_g_n_cpergroup_hip_wip_global_desc = transform_tensor_descriptor(
in_g_n_cpergroup_hi_wi_global_desc,
make_tuple(PassThrough<G>{},
PassThrough<N>{},
PassThrough<CPerGroup>{},
Pad<Sequence<Hi, Wi>, InLeftPads, InRightPads>{}),
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_cpergroup_hip_wip_global_desc.GetLengths()[3];
constexpr index_t Wip = in_g_n_cpergroup_hip_wip_global_desc.GetLengths()[4];
constexpr auto in_g_n0_n1_cpergroup_y_ho_x_wo_global_desc = transform_tensor_descriptor(
in_g_n_cpergroup_hip_wip_global_desc,
make_tuple(PassThrough<G>{},
UnMerge<Sequence<NWaves, N1>>{},
PassThrough<CPerGroup>{},
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, 2>{},
Sequence<3>{},
Sequence<4, 5>{},
Sequence<6, 7>{}));
constexpr auto in_gemmg_gemmktotal_n0_b_global_desc = transform_tensor_descriptor(
in_g_n0_n1_cpergroup_y_ho_x_wo_global_desc,
make_tuple(PassThrough<G>{},
Merge<Sequence<CPerGroup, Y, X>>{},
PassThrough<NWaves>{},
Merge<Sequence<N1, Ho, Wo>>{}),
make_tuple(Sequence<0>{}, Sequence<3, 4, 6>{}, Sequence<1>{}, Sequence<2, 5, 7>{}),
make_tuple(Sequence<0>{}, Sequence<1>{}, Sequence<2>{}, Sequence<3>{}));
constexpr auto in_gemmg_gemmk_n0_b_gemmkpack_global_desc = transform_tensor_descriptor(
in_gemmg_gemmktotal_n0_b_global_desc,
make_tuple(PassThrough<GemmG>{},
UnMerge<Sequence<GemmK, GemmKPack>>{},
PassThrough<NWaves>{},
PassThrough<B>{}),
make_tuple(Sequence<0>{}, Sequence<1>{}, Sequence<2>{}, Sequence<3>{}),
make_tuple(Sequence<0>{}, Sequence<1, 4>{}, Sequence<2>{}, Sequence<3>{}));
// weight tensor
constexpr auto wei_gemmg_gemmm_gemmktotal_global_desc = unfold_tensor_descriptor(
wei_g_kpergroup_cpergroup_y_x_global_desc, Number<2>{}, Number<4>{});
constexpr auto wei_gemmg_gemmk_gemmm_gemmkpack_global_desc = transform_tensor_descriptor(
wei_gemmg_gemmm_gemmktotal_global_desc,
make_tuple(
PassThrough<GemmG>{}, PassThrough<GemmM>{}, UnMerge<Sequence<GemmK, GemmKPack>>{}),
make_tuple(Sequence<0>{}, Sequence<1>{}, Sequence<2>{}),
make_tuple(Sequence<0>{}, Sequence<2>{}, Sequence<1, 3>{}));
// output tensor
constexpr auto out_gemmg_gemmm_gemmn_global_desc = transform_tensor_descriptor(
out_g_n_kpergroup_ho_wo_global_desc,
make_tuple(PassThrough<G>{}, PassThrough<KPerGroup>{}, Merge<Sequence<N, Ho, Wo>>{}),
make_tuple(Sequence<0>{}, Sequence<2>{}, Sequence<1, 3, 4>{}),
make_tuple(Sequence<0>{}, Sequence<1>{}, Sequence<2>{}));
// gridwise batch-GEMM
constexpr auto gridwise_gemm = GridwiseBatchGemmXdlops_gkmkpack_gkn1bkpack_gmn_v2<
GridSize,
BlockSize,
ABFloat,
AccFloat,
CFloat,
decltype(wei_gemmg_gemmk_gemmm_gemmkpack_global_desc),
decltype(in_gemmg_gemmk_n0_b_gemmkpack_global_desc),
decltype(out_gemmg_gemmm_gemmn_global_desc),
GemmMPerBlock,
BPerBlock,
GemmKPerBlock,
GemmMPerWave,
BPerWave,
GemmABlockCopyThreadSliceLengths_GemmG_GemmK_GemmM_GemmKPack,
GemmABlockCopyThreadClusterLengths_GemmG_GemmK_GemmM_GemmKPack,
GemmABlockCopyThreadClusterArrangeOrder,
GemmABlockCopySrcAccessOrder,
GemmABlockCopyDstAccessOrder,
3, // src vector read dimension of A matrix is GemmKPack
GemmABlockCopySrcDataPerRead_GemmKPack,
GemmABlockCopyDstDataPerWrite_GemmKPack,
GemmBBlockCopyThreadSliceLengths_GemmG_GemmK_NWaves_B_GemmKPack,
GemmBBlockCopyThreadClusterLengths_GemmG_GemmK_NWaves_B_GemmKPack,
GemmBBlockCopyThreadClusterArrangeOrder,
GemmBBlockCopySrcAccessOrder,
GemmBBlockCopyDstAccessOrder,
3, // Src vetor read diemsnion of B matrix is B
GemmBBlockCopySrcDataPerRead_B,
GemmBBlockCopyDstDataPerWrite_GemmKPack,
InMemoryDataOperation::Set,
WorkgroupSchdOrder>{};
gridwise_gemm.Run(p_wei_global, p_in_global, p_out_global);
}
};
} // namespace ck
#endif
|
/*=========================================================================
Program: Robarts Visualization Toolkit
Copyright (c) Adam Rankin, Robarts Research Institute
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "QVTKWidget.h"
#include "qDeviceManagementWidget.h"
#include "qFileManagementWidget.h"
#include "qSegmentationWidget.h"
#include "qShadingWidget.h"
#include "qStereoRenderingWidget.h"
#include "qTransferFunctionDefinitionWidget.h"
#include "qTransferFunctionWindowWidget.h"
#include "qVirtualToolWidget.h"
#include "vtkCuda2DTransferFunction.h"
#include "vtkCuda2DVolumeMapper.h"
#include "vtkInteractorStyleTrackballActor.h"
#include "vtkInteractorStyleTrackballCamera.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderer.h"
#include "vtkStringArray.h"
#include <QAction>
#include <QCheckBox>
#include <QColorDialog>
#include <QFileDialog>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QInputDialog>
#include <QKeyEvent>
#include <QMenu>
#include <QMenuBar>
#include <QString>
#include <QStringList>
#include <QTabWidget>
#include <QThread>
#include <QVBoxLayout>
#include <QWidget>
#include <fstream>
qTransferFunctionWindowWidget::qTransferFunctionWindowWidget(QWidget *parent) :
qTransferFunctionWindowWidgetInterface(parent)
{
//initialize communal elements
window = vtkRenderWindow::New();
renderer = vtkRenderer::New();
mapper = vtkCuda2DVolumeMapper::New();
mapper->UseFullVTKCompatibility();
//assemble the communal pipeline
renderer->SetBackground(0,0,0);
window->AddRenderer(renderer);
window->SetStereoCapableWindow(1);
//initialize overall layout
menuLayout = new QVBoxLayout();
setLayout(menuLayout);
mainLayout = new QHBoxLayout();
tabbar = new QTabWidget(this);
tabbar->setMinimumWidth(100);
tabbar->setMaximumWidth(250);
connect(tabbar, SIGNAL(currentChanged(int)), this, SLOT(changeTab()) );
mainLayout->addWidget(tabbar);
//set up the file widget and menu
fmWidget = new qFileManagementWidget( (qTransferFunctionWindowWidgetInterface*) this );
fmWidget->setStandardWidgets( window, renderer, mapper );
fileMenu = fmWidget->getMenuOptions();
tabbar->addTab(fmWidget,"Files");
//set up the widgets GUI
vtWidget = new qVirtualToolWidget( (qTransferFunctionWindowWidgetInterface*) this );
vtWidget->setStandardWidgets( window, renderer, mapper );
widgetMenu = vtWidget->getMenuOptions();
widgetMenu->setEnabled( false );
//set up the transfer function widgets
vtkCuda2DTransferFunction* function = vtkCuda2DTransferFunction::New();
mapper->SetFunction( function );
function->Delete();
tfWidget = new qTransferFunctionDefinitionWidget( this, mapper->GetFunction() );
tfWidget->setStandardWidgets( window, renderer, mapper );
transferFunctionMenu = tfWidget->getMenuOptions();
transferFunctionMenu->setEnabled(false);
tabbar->addTab(tfWidget,"Histogram");
function = vtkCuda2DTransferFunction::New();
mapper->SetKeyholeFunction( function );
function->Delete();
ktfWidget = new qTransferFunctionDefinitionWidget( this, mapper->GetKeyholeFunction() );
ktfWidget->setStandardWidgets( window, renderer, mapper );
ktransferFunctionMenu = ktfWidget->getMenuOptions();
ktransferFunctionMenu->setEnabled(false);
tabbar->addTab(ktfWidget,"Histogram x2");
//set up the shading widget
shWidget = new qShadingWidget( (qTransferFunctionWindowWidgetInterface*) this);
shWidget->setStandardWidgets( window, renderer, mapper );
tabbar->addTab(shWidget,"Shading");
//set up the device management widget
devWidget = new qDeviceManagementWidget(this);
devWidget->setStandardWidgets( window, renderer, mapper );
tabbar->addTab(devWidget,"Device");
//set up the stereo rendering menu
srWidget = new qStereoRenderingWidget( (qTransferFunctionWindowWidgetInterface*) this );
srWidget->setStandardWidgets( window, renderer, mapper );
stereoRenderingMenu = srWidget->getMenuOptions();
//set up the segmentation menu
segWidget = new qSegmentationWidget(this);
segWidget->setStandardWidgets( window, renderer, mapper );
segmentationMenu = segWidget->getMenuOptions();
segmentationMenu->setEnabled(false);
//create the menu from the submenus
menubar = new QMenuBar(this);
menubar->addMenu(fileMenu);
menubar->addMenu(stereoRenderingMenu);
menubar->addMenu(transferFunctionMenu);
menubar->addMenu(ktransferFunctionMenu);
menubar->addMenu(segmentationMenu);
menubar->addMenu( widgetMenu );
menubar->show();
//set up the screen
screenMainLayout = new QVBoxLayout();
screen = new QVTKWidget(this);
actorManipulationStyle = vtkInteractorStyleTrackballActor::New();
cameraManipulationStyle = vtkInteractorStyleTrackballCamera::New();
screen->SetRenderWindow(window);
screen->GetInteractor()->SetInteractorStyle( cameraManipulationStyle );
usingCamera = true;
screen->setMinimumSize(512,512);
screenMainLayout->addWidget(screen);
mainLayout->addLayout(screenMainLayout);
//set up the plane screens
planeXScreen = new QVTKWidget(this);
planeYScreen = new QVTKWidget(this);
planeZScreen = new QVTKWidget(this);
planeXScreen->setMinimumSize(128,128);
planeYScreen->setMinimumSize(128,128);
planeZScreen->setMinimumSize(128,128);
planeXScreen->setMaximumSize(128,128);
planeYScreen->setMaximumSize(128,128);
planeZScreen->setMaximumSize(128,128);
screenPlanesLayout = new QHBoxLayout();
screenPlanesLayout->addWidget(planeXScreen);
screenPlanesLayout->addWidget(planeYScreen);
screenPlanesLayout->addWidget(planeZScreen);
screenMainLayout->addLayout(screenPlanesLayout);
planeXScreen->SetRenderWindow(vtWidget->GetXPlaneRenderWindow());
planeYScreen->SetRenderWindow(vtWidget->GetYPlaneRenderWindow());
planeZScreen->SetRenderWindow(vtWidget->GetZPlaneRenderWindow());
this->grabKeyboard();
//main Layout manages the entire screen
menuLayout->addWidget(menubar);
menuLayout->addLayout(mainLayout);
fmWidget->addMHDFile();
}
qTransferFunctionWindowWidget::~qTransferFunctionWindowWidget()
{
//remove interaction components
actorManipulationStyle->Delete();
cameraManipulationStyle->Delete();
//remove the screen components
delete screen;
delete planeXScreen;
delete planeYScreen;
delete planeZScreen;
//delete associated widgets
delete vtWidget;
delete srWidget;
delete shWidget;
delete segWidget;
delete tfWidget;
delete ktfWidget;
delete fmWidget;
//remove the menu system
delete menubar;
//delete the tab bar
delete tabbar;
//remove the layout managers
delete screenPlanesLayout;
delete screenMainLayout;
delete mainLayout;
delete menuLayout;
//clear the pipeline
window->Delete();
renderer->Delete();
mapper->Delete();
}
void qTransferFunctionWindowWidget::UpdateScreen()
{
this->screen->repaint();
this->planeXScreen->repaint();
this->planeYScreen->repaint();
this->planeZScreen->repaint();
}
void qTransferFunctionWindowWidget::LoadedImageData()
{
tfWidget->selectImage( fmWidget->getCurrentImage() );
ktfWidget->selectImage( fmWidget->getCurrentImage() );
vtWidget->selectImage( fmWidget->getCurrentImage() );
//if this is the first image, compute the histogram and enable the menu bars
if( fmWidget->getNumFrames() == 1 )
{
tfWidget->computeHistogram( );
ktfWidget->computeHistogram( );
transferFunctionMenu->setEnabled(true);
ktransferFunctionMenu->setEnabled(true);
segmentationMenu->setEnabled(true);
widgetMenu->setEnabled(true);
renderer->ResetCamera();
}
this->UpdateScreen();
}
void qTransferFunctionWindowWidget::changeTab()
{
QWidget* currTab = tabbar->currentWidget();
//change the width of the tab bar according to which tab is selected
//if no valid tab is found, don't change the size
if(currTab == fmWidget)
{
tabbar->setMinimumWidth(100);
tabbar->setMaximumWidth(250);
}
else if(currTab == tfWidget)
{
tabbar->setMinimumWidth(tfWidget->getHistoSize() + 80 );
tabbar->setMaximumWidth(tfWidget->getHistoSize() + 80 );
}
else if(currTab == ktfWidget)
{
tabbar->setMinimumWidth(ktfWidget->getHistoSize() + 80 );
tabbar->setMaximumWidth(ktfWidget->getHistoSize() + 80 );
}
else if(currTab == shWidget)
{
tabbar->setMinimumWidth(100);
tabbar->setMaximumWidth(250);
}
else
{
std::cerr << "Tab error: cannot find tab." << std::endl;
return;
}
//if the window is still visible, redraw all the screens (just in case)
if( this->isVisible() )
{
this->UpdateScreen();
}
}
void qTransferFunctionWindowWidget::keyPressEvent(QKeyEvent* e)
{
if( e->key() == Qt::Key::Key_Alt )
{
screen->GetInteractor()->SetInteractorStyle( actorManipulationStyle );
screen->GetInteractor()->ReInitialize();
}
tfWidget->keyPressEvent(e);
ktfWidget->keyPressEvent(e);
}
void qTransferFunctionWindowWidget::keyReleaseEvent(QKeyEvent* e)
{
if( e->key() == Qt::Key::Key_Alt )
{
screen->GetInteractor()->SetInteractorStyle( cameraManipulationStyle );
screen->GetInteractor()->ReInitialize();
}
tfWidget->keyReleaseEvent(e);
ktfWidget->keyReleaseEvent(e);
}
|
#include "order.h"
#include "constants.h"
#include "coord.h"
#include <fstream>
#include <stdexcept>
#include <utility>
#include <vector>
#include <stack>
using namespace std;
// compile with -O3 -DNDEBUG
NodeOrdering compute_real_dfs_order(const ListGraph&g){
std::vector<int>out_begin, out_dest;
auto source_node = [&](int x){
return g.arc[x].source;
};
auto target_node = [&](int x){
return g.arc[x].target;
};
build_adj_array(
out_begin, out_dest,
g.node_count(), g.arc.size(),
source_node, target_node
);
NodeOrdering order(g.node_count());
std::vector<bool>was_pushed(g.node_count(), false);
std::vector<bool>was_popped(g.node_count(), false);
std::vector<int>next_out = out_begin;
std::stack<int>to_visit;
int next_id = 0;
for(int source_node=0; source_node<g.node_count(); ++source_node){
if(!was_pushed[source_node]){
to_visit.push(source_node);
was_pushed[source_node] = true;
while(!to_visit.empty()){
int x = to_visit.top();
to_visit.pop();
if(!was_popped[x]){
order.map(x, next_id++);
was_popped[x] = true;
}
while(next_out[x] != out_begin[x+1]){
int y = out_dest[next_out[x]];
if(was_pushed[y])
++next_out[x];
else{
was_pushed[y] = true;
to_visit.push(x);
to_visit.push(y);
++next_out[x];
break;
}
}
}
}
}
assert(order.is_complete());
return order;
}
NodeOrdering compute_split_dfs_order(const ListGraph&g){
vector<int>out_begin, out_dest;
vector<int> mask(g.node_count());
auto source_node = [&](int x){
return g.arc[x].source;
};
auto target_node = [&](int x){
return g.arc[x].target;
};
auto is_normal_tile = [&](int x) {
return mask[x] == (warthog::STRAIGHTs | warthog::DIAGs);
};
build_adj_array(
out_begin, out_dest,
g.node_count(), g.arc.size(),
source_node, target_node
);
for (auto i: g.arc) {
mask[i.source] |= 1<<i.direction;
}
NodeOrdering order(g.node_count());
vector<bool>was_pushed(g.node_count(), false);
vector<bool>was_popped(g.node_count(), false);
vector<int>next_out = vector<int>(out_begin.begin(), out_begin.end());
stack<int>to_visit;
int next_id = 0;
for(int source_node=0; source_node<g.node_count(); ++source_node){
if(!was_pushed[source_node]){
to_visit.push(source_node);
was_pushed[source_node] = true;
while(!to_visit.empty()){
int x = to_visit.top();
to_visit.pop();
if(!was_popped[x] && is_normal_tile(x)){
order.map(x, next_id++);
was_popped[x] = true;
}
while(next_out[x] != out_begin[x+1]){
int y = out_dest[next_out[x]];
if(was_pushed[y])
++next_out[x];
else{
was_pushed[y] = true;
to_visit.push(x);
to_visit.push(y);
++next_out[x];
break;
}
}
}
}
}
fill(was_pushed.begin(), was_pushed.end(), false);
fill(was_popped.begin(), was_popped.end(), false);
next_out = vector<int>(out_begin.begin(), out_begin.end());
for (int source_node=0; source_node<g.node_count(); ++source_node) {
if (!was_pushed[source_node]){
to_visit.push(source_node);
was_pushed[source_node] = true;
while (!to_visit.empty()) {
int x = to_visit.top();
to_visit.pop();
if (!was_popped[x] && !is_normal_tile(x)) {
order.map(x, next_id++);
was_popped[x] = true;
}
while (next_out[x] != out_begin[x+1]) {
int y = out_dest[next_out[x]];
if (was_pushed[y])
++next_out[x];
else {
was_pushed[y] = true;
to_visit.push(x);
to_visit.push(y);
++next_out[x];
break;
}
}
}
}
}
assert(order.validate());
return order;
}
void fractal_sort(
int l, int r,
std::vector<xyLoc>& nodes,
std::vector<int>& ids)
{
if (l >= r) return;
int16_t xmin, xmax, ymin, ymax;
xmin = xmax = nodes[l].x;
ymin = ymax = nodes[l].y;
for (int i=l; i<=r; i++) {
xmin = min(xmin, nodes[i].x);
xmax = max(xmax, nodes[i].x);
ymin = min(ymin, nodes[i].y);
ymax = max(ymax, nodes[i].y);
}
long long xmid = (xmax + xmin) / 2;
long long ymid = (ymax + ymin) / 2;
auto quat = [&](xyLoc node) {
if (node.x <= xmid & node.y <= ymid) return 0;
if (node.x > xmid & node.y <= ymid) return 1;
if (node.x > xmid & node.y > ymid) return 2;
if (node.x <= xmid & node.y > ymid) return 3;
assert(false);
return -1;
};
int idx = l;
for (int i=l; i<=r; i++) {
if (quat(nodes[i]) == 0) {
if (idx != i) {
swap(nodes[i], nodes[idx]);
swap(ids[i], ids[idx]);
}
idx++;
}
}
if (l < idx-1)
fractal_sort(l, idx-1, nodes, ids);
l = idx;
for (int i=idx; i<=r; i++) {
if (quat(nodes[i]) == 1) {
if (idx != i) {
swap(nodes[i], nodes[idx]);
swap(ids[i], ids[idx]);
}
idx++;
}
}
if (l < idx-1)
fractal_sort(l, idx-1, nodes, ids);
l = idx;
for (int i=idx; i<=r; i++) {
if (quat(nodes[i]) == 2) {
if (i != idx) {
swap(nodes[i], nodes[idx]);
swap(ids[i], ids[idx]);
}
idx++;
}
}
if (l < idx-1)
fractal_sort(l, idx-1, nodes, ids);
l = idx;
for (int i=idx; i<=r; i++) {
if (quat(nodes[i]) == 3) {
if (i != idx) {
swap(nodes[i], nodes[idx]);
swap(ids[i], ids[idx]);
}
idx++;
}
}
if (l < idx-1)
fractal_sort(l, idx-1, nodes, ids);
}
NodeOrdering compute_fractal_order(const std::vector<xyLoc> nodes) {
std::vector<xyLoc> cur_nodes;
std::vector<int> cur_ids;
int16_t xmin = nodes[0].x, ymin = nodes[0].y;
for (int i=0; i<(int)nodes.size(); i++) {
cur_nodes.push_back(nodes[i]);
cur_ids.push_back(i);
xmin = min(xmin, nodes[i].x);
ymin = min(ymin , nodes[i].y);
}
for (int i=0; i<(int)nodes.size(); i++) {
cur_nodes[i].x -= xmin;
cur_nodes[i].y -= ymin;
}
NodeOrdering order(nodes.size());
fractal_sort(0, nodes.size()-1, cur_nodes, cur_ids);
for (int i=0; i<(int)nodes.size(); i++) {
order.map(cur_ids[i], i);
}
return order;
}
|
////////////////////////////////////////////////////////////////////////////////
//
// CopyRight (c) 2017 Kyungkun Ko
//
// Author : KyungKun Ko
//
// Description : Basic IOS application
//
//
////////////////////////////////////////////////////////////////////////////////
#include "SFEnginePCH.h"
#if SF_PLATFORM == SF_PLATFORM_IOS
#include "SFAssert.h"
#include "Util/SFUtility.h"
#include "Application/IOS/IOSApp.h"
#include "Application/IOS/IOSAppTasks.h"
#include "Service/SFEngineService.h"
#include "SFEngine.h"
#include "Graphics/SFGraphicDeviceGLES.h"
namespace SF
{
IOSAppTask::IOSAppTask(ApplicationBase* app)
: m_pApp((IOSApp*)app)
{
}
/////////////////////////////////////////////////////////////////
//
// App EngineTask
//
IOSAppTask_InitWindow::IOSAppTask_InitWindow(ApplicationBase* app, NativeWindow pWindow)
: IOSAppTask(app)
, m_Window(pWindow)
{
}
IOSAppTask_InitWindow::~IOSAppTask_InitWindow()
{
//if (m_Window != nullptr)
// ANativeWindow_release(m_Window);
}
void IOSAppTask_InitWindow::Run()
{
if (m_Window != nullptr)
{
Service::GraphicDevice->InitDisplay(m_Window);
m_Window = nullptr;
}
Finished();
}
IOSAppTask_DestroyWindow::IOSAppTask_DestroyWindow(ApplicationBase* app)
: IOSAppTask(app)
{
}
void IOSAppTask_DestroyWindow::Run()
{
Service::GraphicDevice->DeinitDisplay();
Finished();
}
IOSAppTask_WindowResized::IOSAppTask_WindowResized(ApplicationBase* app)
: IOSAppTask(app)
{
}
void IOSAppTask_WindowResized::Run()
{
Finished();
}
IOSAppTask_GainFocus::IOSAppTask_GainFocus(ApplicationBase* app)
: IOSAppTask(app)
{
}
void IOSAppTask_GainFocus::Run()
{
GetApp()->SetPaused(false);
Finished();
}
IOSAppTask_LostFocus::IOSAppTask_LostFocus(ApplicationBase* app)
: IOSAppTask(app)
{
}
void IOSAppTask_LostFocus::Run()
{
GetApp()->SetPaused(true);
Finished();
}
IOSAppTask_LowMemory::IOSAppTask_LowMemory(ApplicationBase* app)
: IOSAppTask(app)
{
}
void IOSAppTask_LowMemory::Run()
{
Finished();
}
IOSAppTask_AppStart::IOSAppTask_AppStart(ApplicationBase* app)
: IOSAppTask(app)
{
}
void IOSAppTask_AppStart::Run()
{
Finished();
}
IOSAppTask_AppStop::IOSAppTask_AppStop(ApplicationBase* app)
: IOSAppTask(app)
{
}
void IOSAppTask_AppStop::Run()
{
Finished();
}
IOSAppTask_Pause::IOSAppTask_Pause(ApplicationBase* app)
: IOSAppTask(app)
{
}
void IOSAppTask_Pause::Run()
{
GetApp()->SetPaused(true);
Finished();
}
IOSAppTask_Resume::IOSAppTask_Resume(ApplicationBase* app)
: IOSAppTask(app)
{
}
void IOSAppTask_Resume::Run()
{
GetApp()->SetPaused(false);
Finished();
}
IOSAppTask_ConfigChanged::IOSAppTask_ConfigChanged(ApplicationBase* app)
: IOSAppTask(app)
{
}
void IOSAppTask_ConfigChanged::Run()
{
Finished();
}
IOSAppTask_SaveState::IOSAppTask_SaveState(ApplicationBase* app)
: IOSAppTask(app)
{
}
void IOSAppTask_SaveState::Run()
{
// TODO::
Finished();
}
}
#else
void IOSAppTasks_Dummy() {}
#endif
|
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2020 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <openspace/rendering/transferfunction.h>
#include <ghoul/filesystem/cachemanager.h>
#include <ghoul/filesystem/file.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/filesystem/file.h>
#include <ghoul/io/texture/texturereader.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/opengl/texture.h>
#include <iterator>
#include <fstream>
#include <string>
namespace {
constexpr const char* _loggerCat = "TransferFunction";
// @TODO Replace with Filesystem::File extension
bool hasExtension(const std::string& filepath, const std::string& extension) {
std::string ending = "." + extension;
if (filepath.length() > ending.length()) {
return (0 == filepath.compare(
filepath.length() - ending.length(),
ending.length(), ending));
}
else {
return false;
}
}
} // namespace
namespace openspace {
TransferFunction::TransferFunction(const std::string& filepath,
TfChangedCallback tfChangedCallback)
: _filepath(filepath)
{
setPath(filepath);
setCallback(std::move(tfChangedCallback));
}
TransferFunction::~TransferFunction() {} // NOLINT
void TransferFunction::setPath(const std::string& filepath) {
if (_file) {
_file = nullptr;
}
std::string f = absPath(filepath);
if (!FileSys.fileExists(f)) {
LERROR("Could not find transfer function file.");
_file = nullptr;
return;
}
_filepath = f;
_file = std::make_unique<ghoul::filesystem::File>(
_filepath,
ghoul::filesystem::File::RawPath::Yes
);
_needsUpdate = true;
_file->setCallback([this](const ghoul::filesystem::File&) {
_needsUpdate = true;
});
}
ghoul::opengl::Texture& TransferFunction::texture() {
ghoul_assert(_texture != nullptr, "Transfer function is null");
update();
return *_texture.get();
}
void TransferFunction::update() {
if (_needsUpdate) {
if (hasExtension(_filepath, "txt")) {
setTextureFromTxt();
}
else {
setTextureFromImage();
}
_texture->uploadTexture();
_needsUpdate = false;
if (_tfChangedCallback) {
_tfChangedCallback(*this);
}
}
}
void TransferFunction::setCallback(TfChangedCallback callback) {
_tfChangedCallback = std::move(callback);
}
void TransferFunction::setTextureFromTxt(std::shared_ptr<ghoul::opengl::Texture> ptr) {
std::ifstream in;
in.open(_filepath.c_str());
if (!in.is_open()) {
throw ghoul::FileNotFoundError(_filepath);
}
int width = 512;
float lower = 0.f;
float upper = 1.f;
std::vector<MappingKey> mappingKeys;
std::string line;
while (std::getline(in, line)) {
std::istringstream iss(line);
std::string key;
iss >> key;
if (key == "width") {
iss >> width;
}
else if (key == "lower") {
iss >> lower;
lower = glm::clamp(lower, 0.f, 1.f);
}
else if (key == "upper") {
iss >> upper;
upper = glm::clamp(upper, lower, 1.f);
}
else if (key == "mappingkey") {
float intensity;
glm::vec4 rgba = glm::vec4(0.f);
iss >> intensity;
for(int i = 0; i < 4; ++i) {
iss >> rgba[i];
}
mappingKeys.emplace_back(intensity, rgba);
}
}
in.close();
if (mappingKeys.empty()) {
return;
}
if (mappingKeys.front().position > lower) {
mappingKeys.insert(mappingKeys.begin(), {lower, mappingKeys.front().color});
}
if (mappingKeys.back().position < upper) {
mappingKeys.emplace_back(upper, mappingKeys.back().color);
}
// allocate new float array with zeros
float* transferFunction = new float[width * 4];
for (int i = 0; i < 4 * width; ++i) {
transferFunction[i] = 0.f;
}
size_t lowerIndex = static_cast<size_t>(floorf(lower * static_cast<float>(width-1)));
size_t upperIndex = static_cast<size_t>(floorf(upper * static_cast<float>(width-1)));
auto prevKey = mappingKeys.begin();
auto currentKey = prevKey + 1;
auto lastKey = mappingKeys.end() -1;
for (size_t i = lowerIndex; i <= upperIndex; ++i) {
const float fpos = static_cast<float>(i) / static_cast<float>(width-1);
if (fpos > currentKey->position) {
prevKey = currentKey;
currentKey++;
if (currentKey == mappingKeys.end()) {
currentKey = lastKey;
}
}
const float dist = fpos - prevKey->position;
const float weight = dist / (currentKey->position - prevKey->position);
for (int channel = 0; channel < 4; ++channel) {
const size_t position = 4 * i + channel;
// Interpolate linearly between prev and next mapping key
float value = (prevKey->color[channel] * (1.f - weight) +
currentKey->color[channel] * weight) / 255.f;
if (channel < 3) {
// Premultiply with alpha
value *= (prevKey->color[3] * (1.f - weight) +
currentKey->color[3] * weight) / 255.f;
}
transferFunction[position] = value;
}
}
// no need to deallocate transferFunction. Ownership is transferred to the Texture.
_texture = std::make_unique<ghoul::opengl::Texture>(
transferFunction,
glm::size3_t(width, 1, 1),
ghoul::opengl::Texture::Format::RGBA,
GL_RGBA,
GL_FLOAT,
ghoul::opengl::Texture::FilterMode::Linear,
ghoul::opengl::Texture::WrappingMode::ClampToEdge
);
}
void TransferFunction::setTextureFromImage() {
_texture = ghoul::io::TextureReader::ref().loadTexture(_filepath);
_texture->setWrapping(ghoul::opengl::Texture::WrappingMode::ClampToEdge);
}
glm::vec4 TransferFunction::sample(size_t offset) {
if (!_texture) {
return glm::vec4(0.f);
}
const int nPixels = _texture->width();
// Clamp to range.
if (offset >= static_cast<size_t>(nPixels)) {
offset = nPixels - 1;
}
return _texture->texelAsFloat(static_cast<unsigned int>(offset));
}
size_t TransferFunction::width() {
update();
return _texture->width();
}
void TransferFunction::bind() {
update();
_texture->bind();
}
} // namespace openspace
|
#include <cppurses/system/focus.hpp>
#include <cppurses/system/system.hpp>
#include "main_menu.hpp"
using namespace cppurses;
int main() {
System sys;
demos::Main_menu demo_menu;
Focus::set_focus_to(&demo_menu.main_menu.menu());
return sys.run(demo_menu);
}
|
#include "uml/impl/ExtensionPointImpl.hpp"
#ifdef NDEBUG
#define DEBUG_MESSAGE(a) /**/
#else
#define DEBUG_MESSAGE(a) a
#endif
#ifdef ACTIVITY_DEBUG_ON
#define ACT_DEBUG(a) a
#else
#define ACT_DEBUG(a) /**/
#endif
//#include "util/ProfileCallCount.hpp"
#include <cassert>
#include <iostream>
#include <sstream>
#include "abstractDataTypes/Bag.hpp"
#include "abstractDataTypes/Subset.hpp"
#include "abstractDataTypes/SubsetUnion.hpp"
#include "abstractDataTypes/Union.hpp"
#include "abstractDataTypes/Any.hpp"
#include "abstractDataTypes/SubsetUnion.hpp"
#include "ecore/EAnnotation.hpp"
#include "ecore/EClass.hpp"
#include "uml/impl/UmlPackageImpl.hpp"
//Forward declaration includes
#include "persistence/interfaces/XLoadHandler.hpp" // used for Persistence
#include "persistence/interfaces/XSaveHandler.hpp" // used for Persistence
#include "uml/UmlFactory.hpp"
#include "uml/UmlPackage.hpp"
#include <exception> // used in Persistence
#include "uml/Classifier.hpp"
#include "uml/Comment.hpp"
#include "uml/Dependency.hpp"
#include "ecore/EAnnotation.hpp"
#include "uml/Element.hpp"
#include "uml/Namespace.hpp"
#include "uml/RedefinableElement.hpp"
#include "uml/StringExpression.hpp"
#include "uml/UseCase.hpp"
#include "ecore/EcorePackage.hpp"
#include "ecore/EcoreFactory.hpp"
#include "uml/UmlPackage.hpp"
#include "uml/UmlFactory.hpp"
#include "ecore/EAttribute.hpp"
#include "ecore/EStructuralFeature.hpp"
using namespace uml;
//*********************************
// Constructor / Destructor
//*********************************
ExtensionPointImpl::ExtensionPointImpl()
{
//*********************************
// Attribute Members
//*********************************
//*********************************
// Reference Members
//*********************************
//References
//Init references
}
ExtensionPointImpl::~ExtensionPointImpl()
{
#ifdef SHOW_DELETION
std::cout << "-------------------------------------------------------------------------------------------------\r\ndelete ExtensionPoint "<< this << "\r\n------------------------------------------------------------------------ " << std::endl;
#endif
}
//Additional constructor for the containments back reference
ExtensionPointImpl::ExtensionPointImpl(std::weak_ptr<uml::Namespace > par_namespace)
:ExtensionPointImpl()
{
m_namespace = par_namespace;
m_owner = par_namespace;
}
//Additional constructor for the containments back reference
ExtensionPointImpl::ExtensionPointImpl(std::weak_ptr<uml::Element > par_owner)
:ExtensionPointImpl()
{
m_owner = par_owner;
}
//Additional constructor for the containments back reference
ExtensionPointImpl::ExtensionPointImpl(std::weak_ptr<uml::UseCase > par_useCase)
:ExtensionPointImpl()
{
m_useCase = par_useCase;
m_namespace = par_useCase;
}
ExtensionPointImpl::ExtensionPointImpl(const ExtensionPointImpl & obj):ExtensionPointImpl()
{
//create copy of all Attributes
#ifdef SHOW_COPIES
std::cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\ncopy ExtensionPoint "<< this << "\r\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ " << std::endl;
#endif
m_isLeaf = obj.getIsLeaf();
m_name = obj.getName();
m_qualifiedName = obj.getQualifiedName();
m_visibility = obj.getVisibility();
//copy references with no containment (soft copy)
std::shared_ptr<Bag<uml::Dependency>> _clientDependency = obj.getClientDependency();
m_clientDependency.reset(new Bag<uml::Dependency>(*(obj.getClientDependency().get())));
m_namespace = obj.getNamespace();
m_owner = obj.getOwner();
std::shared_ptr<Union<uml::RedefinableElement>> _redefinedElement = obj.getRedefinedElement();
m_redefinedElement.reset(new Union<uml::RedefinableElement>(*(obj.getRedefinedElement().get())));
std::shared_ptr<Union<uml::Classifier>> _redefinitionContext = obj.getRedefinitionContext();
m_redefinitionContext.reset(new Union<uml::Classifier>(*(obj.getRedefinitionContext().get())));
m_useCase = obj.getUseCase();
//Clone references with containment (deep copy)
std::shared_ptr<Bag<ecore::EAnnotation>> _eAnnotationsList = obj.getEAnnotations();
for(std::shared_ptr<ecore::EAnnotation> _eAnnotations : *_eAnnotationsList)
{
this->getEAnnotations()->add(std::shared_ptr<ecore::EAnnotation>(std::dynamic_pointer_cast<ecore::EAnnotation>(_eAnnotations->copy())));
}
#ifdef SHOW_SUBSET_UNION
std::cout << "Copying the Subset: " << "m_eAnnotations" << std::endl;
#endif
if(obj.getNameExpression()!=nullptr)
{
m_nameExpression = std::dynamic_pointer_cast<uml::StringExpression>(obj.getNameExpression()->copy());
}
#ifdef SHOW_SUBSET_UNION
std::cout << "Copying the Subset: " << "m_nameExpression" << std::endl;
#endif
std::shared_ptr<Bag<uml::Comment>> _ownedCommentList = obj.getOwnedComment();
for(std::shared_ptr<uml::Comment> _ownedComment : *_ownedCommentList)
{
this->getOwnedComment()->add(std::shared_ptr<uml::Comment>(std::dynamic_pointer_cast<uml::Comment>(_ownedComment->copy())));
}
#ifdef SHOW_SUBSET_UNION
std::cout << "Copying the Subset: " << "m_ownedComment" << std::endl;
#endif
}
std::shared_ptr<ecore::EObject> ExtensionPointImpl::copy() const
{
std::shared_ptr<ExtensionPointImpl> element(new ExtensionPointImpl(*this));
element->setThisExtensionPointPtr(element);
return element;
}
std::shared_ptr<ecore::EClass> ExtensionPointImpl::eStaticClass() const
{
return UmlPackageImpl::eInstance()->getExtensionPoint_EClass();
}
//*********************************
// Attribute Setter Getter
//*********************************
//*********************************
// Operations
//*********************************
bool ExtensionPointImpl::must_have_name(Any diagnostics,std::map < Any, Any > context)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
throw "UnsupportedOperationException";
}
//*********************************
// References
//*********************************
std::weak_ptr<uml::UseCase > ExtensionPointImpl::getUseCase() const
{
//assert(m_useCase);
return m_useCase;
}
void ExtensionPointImpl::setUseCase(std::shared_ptr<uml::UseCase> _useCase)
{
m_useCase = _useCase;
}
//*********************************
// Union Getter
//*********************************
std::weak_ptr<uml::Namespace > ExtensionPointImpl::getNamespace() const
{
return m_namespace;
}
std::shared_ptr<Union<uml::Element>> ExtensionPointImpl::getOwnedElement() const
{
return m_ownedElement;
}
std::weak_ptr<uml::Element > ExtensionPointImpl::getOwner() const
{
return m_owner;
}
std::shared_ptr<ExtensionPoint> ExtensionPointImpl::getThisExtensionPointPtr() const
{
return m_thisExtensionPointPtr.lock();
}
void ExtensionPointImpl::setThisExtensionPointPtr(std::weak_ptr<ExtensionPoint> thisExtensionPointPtr)
{
m_thisExtensionPointPtr = thisExtensionPointPtr;
setThisRedefinableElementPtr(thisExtensionPointPtr);
}
std::shared_ptr<ecore::EObject> ExtensionPointImpl::eContainer() const
{
if(auto wp = m_namespace.lock())
{
return wp;
}
if(auto wp = m_owner.lock())
{
return wp;
}
if(auto wp = m_useCase.lock())
{
return wp;
}
return nullptr;
}
//*********************************
// Structural Feature Getter/Setter
//*********************************
Any ExtensionPointImpl::eGet(int featureID, bool resolve, bool coreType) const
{
switch(featureID)
{
case UmlPackage::EXTENSIONPOINT_EREFERENCE_USECASE:
return eAny(getUseCase()); //10013
}
return RedefinableElementImpl::eGet(featureID, resolve, coreType);
}
bool ExtensionPointImpl::internalEIsSet(int featureID) const
{
switch(featureID)
{
case UmlPackage::EXTENSIONPOINT_EREFERENCE_USECASE:
return getUseCase().lock() != nullptr; //10013
}
return RedefinableElementImpl::internalEIsSet(featureID);
}
bool ExtensionPointImpl::eSet(int featureID, Any newValue)
{
switch(featureID)
{
case UmlPackage::EXTENSIONPOINT_EREFERENCE_USECASE:
{
// BOOST CAST
std::shared_ptr<uml::UseCase> _useCase = newValue->get<std::shared_ptr<uml::UseCase>>();
setUseCase(_useCase); //10013
return true;
}
}
return RedefinableElementImpl::eSet(featureID, newValue);
}
//*********************************
// Persistence Functions
//*********************************
void ExtensionPointImpl::load(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler)
{
std::map<std::string, std::string> attr_list = loadHandler->getAttributeList();
loadAttributes(loadHandler, attr_list);
//
// Create new objects (from references (containment == true))
//
// get UmlFactory
std::shared_ptr<uml::UmlFactory> modelFactory = uml::UmlFactory::eInstance();
int numNodes = loadHandler->getNumOfChildNodes();
for(int ii = 0; ii < numNodes; ii++)
{
loadNode(loadHandler->getNextNodeName(), loadHandler, modelFactory);
}
}
void ExtensionPointImpl::loadAttributes(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler, std::map<std::string, std::string> attr_list)
{
RedefinableElementImpl::loadAttributes(loadHandler, attr_list);
}
void ExtensionPointImpl::loadNode(std::string nodeName, std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler, std::shared_ptr<uml::UmlFactory> modelFactory)
{
RedefinableElementImpl::loadNode(nodeName, loadHandler, modelFactory);
}
void ExtensionPointImpl::resolveReferences(const int featureID, std::list<std::shared_ptr<ecore::EObject> > references)
{
switch(featureID)
{
case UmlPackage::EXTENSIONPOINT_EREFERENCE_USECASE:
{
if (references.size() == 1)
{
// Cast object to correct type
std::shared_ptr<uml::UseCase> _useCase = std::dynamic_pointer_cast<uml::UseCase>( references.front() );
setUseCase(_useCase);
}
return;
}
}
RedefinableElementImpl::resolveReferences(featureID, references);
}
void ExtensionPointImpl::save(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const
{
saveContent(saveHandler);
RedefinableElementImpl::saveContent(saveHandler);
NamedElementImpl::saveContent(saveHandler);
ElementImpl::saveContent(saveHandler);
ecore::EModelElementImpl::saveContent(saveHandler);
ObjectImpl::saveContent(saveHandler);
ecore::EObjectImpl::saveContent(saveHandler);
}
void ExtensionPointImpl::saveContent(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const
{
try
{
std::shared_ptr<uml::UmlPackage> package = uml::UmlPackage::eInstance();
}
catch (std::exception& e)
{
std::cout << "| ERROR | " << e.what() << std::endl;
}
}
|
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "core/components_v2/inspector/row_composed_element.h"
#include "base/log/dump_log.h"
#include "core/components/common/layout/constants.h"
#include "core/components/flex/render_flex.h"
#include "core/components_v2/inspector/utils.h"
namespace OHOS::Ace::V2 {
namespace {
const std::unordered_map<std::string, std::function<std::string(const RowComposedElement&)>> CREATE_JSON_MAP {
{ "alignItems", [](const RowComposedElement& inspector) { return inspector.GetAlignItems(); } },
{ "space", [](const RowComposedElement& inspector) { return inspector.GetSpace(); } },
{ "selfAlign", [](const RowComposedElement& inspector) { return inspector.GetVerticalAlign(); } },
};
}
void RowComposedElement::Dump()
{
InspectorComposedElement::Dump();
DumpLog::GetInstance().AddDesc(
std::string("alignItems: ").append(GetAlignItems()));
DumpLog::GetInstance().AddDesc(
std::string("space: ").append(GetSpace()));
}
std::unique_ptr<JsonValue> RowComposedElement::ToJsonObject() const
{
auto resultJson = InspectorComposedElement::ToJsonObject();
for (const auto& value : CREATE_JSON_MAP) {
resultJson->Put(value.first.c_str(), value.second(*this).c_str());
}
return resultJson;
}
std::string RowComposedElement::GetAlignItems() const
{
auto node = GetInspectorNode(RowElement::TypeId());
if (!node) {
return "VerticalAlign.Center";
}
auto renderRow = AceType::DynamicCast<RenderFlex>(node);
if (renderRow) {
auto alignItems = renderRow->GetAlignItems();
if (alignItems == FlexAlign::FLEX_START) {
return "VerticalAlign.Top";
} else if (alignItems == FlexAlign::CENTER) {
return "VerticalAlign.Center";
} else if (alignItems == FlexAlign::FLEX_END) {
return "VerticalAlign.Bottom";
}
}
return "VerticalAlign.Center";
}
std::string RowComposedElement::GetSpace() const
{
auto node = GetInspectorNode(RowElement::TypeId());
if (!node) {
return Dimension(0.0).ToString();
}
auto renderRow = AceType::DynamicCast<RenderFlex>(node);
if (renderRow) {
auto dimension = Dimension(renderRow->GetSpace());
return dimension.ToString();
}
return Dimension(0.0).ToString();
}
std::string RowComposedElement::GetVerticalAlign() const
{
auto node = GetInspectorNode(RowElement::TypeId());
if (!node) {
return "VerticalAlign::Center";
}
auto renderRow = AceType::DynamicCast<RenderFlex>(node);
if (renderRow) {
auto alignPtr = renderRow->GetAlignPtr();
if (alignPtr) {
auto verticalAlign = alignPtr->GetVerticalAlign();
switch (verticalAlign) {
case VerticalAlign::TOP:
return "VerticalAlign::Top";
case VerticalAlign::CENTER:
return "VerticalAlign::Center";
case VerticalAlign::BOTTOM:
return "VerticalAlign::Bottom";
default:
return "verticalAlign::Center";
}
}
}
return "verticalAlign::Center";
}
} // namespace OHOS::Ace::V2
|
/*
* Copyright 2018 Vladimir Balun
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cstdint>
#include <cstdlib>
#include <Winsock2.h>
#include <WS2tcpip.h>
#include "../Utils/Debug.hpp"
namespace Network {
class UDPConnection
{
public:
explicit UDPConnection(LPCSTR ipAddress, std::uint16_t port) noexcept;
void sendBuffer(char* buffer, std::size_t size) noexcept;
void receiveBuffer(char* buffer) noexcept;
~UDPConnection();
private:
int mSocketHandle;
struct sockaddr_in mSocketAddress;
static const std::uint16_t MAX_PACKET_SIZE = 1024;
};
}
|
/*
Copyright (c) 2011 Daniel Bakkelund.
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 of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CPUNIT_FIXTUREREGISTRAR_HPP
#define CPUNIT_FIXTUREREGISTRAR_HPP
#include <string>
namespace cpunit {
class FixtureRegistrar {
public:
enum FixType {
SET_UP,
TEAR_DOWN
};
FixtureRegistrar(const std::string &path, const std::string &name,
const std::string &file, const int line, void (*func)(), const FixType t);
virtual ~FixtureRegistrar();
};
}
#endif // CPUNIT_FIXTUREREGISTRAR_HPP
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <chainparams.h>
#include <clientversion.h>
#include <compat.h>
#include <fs.h>
#include <interfaces/chain.h>
#include <rpc/server.h>
#include <init.h>
#include <noui.h>
#include <shutdown.h>
#include <util/system.h>
#include <httpserver.h>
#include <httprpc.h>
#include <util/strencodings.h>
#include <walletinitinterface.h>
#include <stdio.h>
const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
/* Introduction text for doxygen: */
/*! \mainpage Developer documentation
*
* \section intro_sec Introduction
*
* This is the developer documentation of the reference client for an experimental new digital currency called Bitcoin,
* which enables instant payments to anyone, anywhere in the world. Bitcoin uses peer-to-peer technology to operate
* with no central authority: managing transactions and issuing money are carried out collectively by the network.
*
* The software is a community-driven open source project, released under the MIT license.
*
* See https://github.com/bitcoin/bitcoin and https://bitcoincore.org/ for further information about the project.
*
* \section Navigation
* Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code.
*/
static void WaitForShutdown()
{
while (!ShutdownRequested())
{
MilliSleep(200);
}
Interrupt();
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
static bool AppInit(int argc, char* argv[])
{
InitInterfaces interfaces;
interfaces.chain = interfaces::MakeChain();
bool fRet = false;
//
// Parameters
//
// If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
SetupServerArgs();
std::string error;
if (!gArgs.ParseParameters(argc, argv, error)) {
tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error.c_str());
return false;
}
// Process help and version before taking care about datadir
if (HelpRequested(gArgs) || gArgs.IsArgSet("-version")) {
std::string strUsage = PACKAGE_NAME " Daemon version " + FormatFullVersion() + "\n";
if (gArgs.IsArgSet("-version"))
{
strUsage += FormatParagraph(LicenseInfo()) + "\n";
}
else
{
strUsage += "\nUsage: litecoind [options] Start " PACKAGE_NAME " Daemon\n";
strUsage += "\n" + gArgs.GetHelpMessage();
}
tfm::format(std::cout, "%s", strUsage.c_str());
return true;
}
try
{
if (!fs::is_directory(GetDataDir(false)))
{
tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "").c_str());
return false;
}
if (!gArgs.ReadConfigFiles(error, true)) {
tfm::format(std::cerr, "Error reading configuration file: %s\n", error.c_str());
return false;
}
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
try {
SelectParams(gArgs.GetChainName());
} catch (const std::exception& e) {
tfm::format(std::cerr, "Error: %s\n", e.what());
return false;
}
// Error out when loose non-argument tokens are encountered on command line
for (int i = 1; i < argc; i++) {
if (!IsSwitchChar(argv[i][0])) {
tfm::format(std::cerr, "Error: Command line contains unexpected token '%s', see litecoind -h for a list of options.\n", argv[i]);
return false;
}
}
// -server defaults to true for bitcoind but not for the GUI so do this here
gArgs.SoftSetBoolArg("-server", true);
// Set this early so that parameter interactions go to console
InitLogging();
InitParameterInteraction();
if (!AppInitBasicSetup())
{
// InitError will have been called with detailed error, which ends up on console
return false;
}
if (!AppInitParameterInteraction())
{
// InitError will have been called with detailed error, which ends up on console
return false;
}
if (!AppInitSanityChecks())
{
// InitError will have been called with detailed error, which ends up on console
return false;
}
if (gArgs.GetBoolArg("-daemon", false))
{
#if HAVE_DECL_DAEMON
#if defined(MAC_OSX)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
tfm::format(std::cout, "Litecoin server starting\n");
// Daemonize
if (daemon(1, 0)) { // don't chdir (1), do close FDs (0)
tfm::format(std::cerr, "Error: daemon() failed: %s\n", strerror(errno));
return false;
}
#if defined(MAC_OSX)
#pragma GCC diagnostic pop
#endif
#else
tfm::format(std::cerr, "Error: -daemon is not supported on this operating system\n");
return false;
#endif // HAVE_DECL_DAEMON
}
// Lock data directory after daemonization
if (!AppInitLockDataDirectory())
{
// If locking the data directory failed, exit immediately
return false;
}
fRet = AppInitMain(interfaces);
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "AppInit()");
} catch (...) {
PrintExceptionContinue(nullptr, "AppInit()");
}
if (!fRet)
{
Interrupt();
} else {
WaitForShutdown();
}
Shutdown(interfaces);
return fRet;
}
int main(int argc, char* argv[])
{
#ifdef WIN32
util::WinCmdLineArgs winArgs;
std::tie(argc, argv) = winArgs.get();
#endif
SetupEnvironment();
// Connect bitcoind signal handlers
noui_connect();
return (AppInit(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE);
}
|
// Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <memory>
#include <ngraph/ngraph.hpp>
#include "low_precision/layer_transformation.hpp"
namespace ngraph {
namespace pass {
namespace low_precision {
/**
* @ingroup ie_transformation_common_api
* @brief TransposeTransformation propagates dequantization operations through Transpose operation.
*
* For more details about the transformation, refer to
* [TransposeTransformation](@ref openvino_docs_OV_UG_lpt_TransposeTransformation) page
* in the Inference Engine Developer Guide.
*/
class LP_TRANSFORMATIONS_API TransposeTransformation : public LayerTransformation {
public:
OPENVINO_RTTI("TransposeTransformation", "0");
TransposeTransformation(const Params& params = Params());
bool transform(TransformationContext& context, ngraph::pattern::Matcher &m) override;
bool isPrecisionPreserved(std::shared_ptr<Node> layer) const noexcept override;
bool canBeTransformed(const TransformationContext& context, std::shared_ptr<Node> op) const override;
};
} // namespace low_precision
} // namespace pass
} // namespace ngraph
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: NUnit.Framework.ResultStateException
#include "NUnit/Framework/ResultStateException.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: NUnit::Framework::Interfaces
namespace NUnit::Framework::Interfaces {
// Forward declaring type: ResultState
class ResultState;
}
// Completed forward declares
// Type namespace: UnityEngine.TestTools.TestRunner
namespace UnityEngine::TestTools::TestRunner {
// Size: 0x88
#pragma pack(push, 1)
// Autogenerated type: UnityEngine.TestTools.TestRunner.InvalidSignatureException
// [TokenAttribute] Offset: FFFFFFFF
class InvalidSignatureException : public NUnit::Framework::ResultStateException {
public:
// Creating value type constructor for type: InvalidSignatureException
InvalidSignatureException() noexcept {}
// public override NUnit.Framework.Interfaces.ResultState get_ResultState()
// Offset: 0x14CFE98
// Implemented from: NUnit.Framework.ResultStateException
// Base method: NUnit.Framework.Interfaces.ResultState ResultStateException::get_ResultState()
NUnit::Framework::Interfaces::ResultState* get_ResultState();
// public System.Void .ctor(System.String message)
// Offset: 0x14CFE90
// Implemented from: NUnit.Framework.ResultStateException
// Base method: System.Void ResultStateException::.ctor(System.String message)
// Base method: System.Void Exception::.ctor(System.String message)
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static InvalidSignatureException* New_ctor(::Il2CppString* message) {
static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::TestTools::TestRunner::InvalidSignatureException::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<InvalidSignatureException*, creationType>(message)));
}
}; // UnityEngine.TestTools.TestRunner.InvalidSignatureException
#pragma pack(pop)
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::TestTools::TestRunner::InvalidSignatureException*, "UnityEngine.TestTools.TestRunner", "InvalidSignatureException");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: UnityEngine::TestTools::TestRunner::InvalidSignatureException::get_ResultState
// Il2CppName: get_ResultState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<NUnit::Framework::Interfaces::ResultState* (UnityEngine::TestTools::TestRunner::InvalidSignatureException::*)()>(&UnityEngine::TestTools::TestRunner::InvalidSignatureException::get_ResultState)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TestTools::TestRunner::InvalidSignatureException*), "get_ResultState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TestTools::TestRunner::InvalidSignatureException::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
|
/* ScopedNodes.cpp --
*
* Copyright (c) 2014, Lex Chou <lex at chou dot it>
* 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 Swallow 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 "semantics/ScopedNodes.h"
#include "semantics/SymbolScope.h"
#include "semantics/SemanticAnalyzer.h"
#include "semantics/SemanticContext.h"
#include "semantics/SymbolRegistry.h"
#include "ast/TypeIdentifier.h"
#include <cassert>
#include "ast/Identifier.h"
#include "semantics/ScopeGuard.h"
#include "ast/NodeVisitor.h"
USE_SWALLOW_NS
void ScopedProgram::accept(NodeVisitor* visitor)
{
ScopeGuard scope(this, visitor);
if(scope.symbolRegistry)
scope.symbolRegistry->setFileScope(this->getScope());
accept2(visitor, &NodeVisitor::visitProgram);
if(scope.symbolRegistry)
scope.symbolRegistry->setFileScope(nullptr);
}
void ScopedProgram::setScope(SymbolScope* scope)
{
this->symbolScope = scope;
}
const std::wstring& ScopedClass::getName()const
{
return identifier->getName();
}
const std::wstring& ScopedProtocol::getName()const
{
return identifier->getName();
}
const std::wstring& ScopedStruct::getName()const
{
return identifier->getName();
}
const std::wstring& ScopedEnum::getName()const
{
return identifier->getName();
}
void ScopedCodeBlock::accept(NodeVisitor* visitor)
{
ScopeGuard scope(this, visitor);
SemanticAnalyzer* sa = dynamic_cast<SemanticAnalyzer*>(visitor);
SemanticContext* ctx = sa ? sa->getContext() : nullptr;
ScopedCodeBlock* old = ctx ? ctx->currentCodeBlock : nullptr;
if(ctx)
ctx->currentCodeBlock = this;
try
{
accept2(visitor, &NodeVisitor::visitCodeBlock);
if(ctx)
ctx->currentCodeBlock = old;
}
catch(...)
{
if(ctx)
ctx->currentCodeBlock = old;
throw;
}
}
void ScopedClosure::accept(NodeVisitor* visitor)
{
ScopeGuard scope(this, visitor);
accept2(visitor, &NodeVisitor::visitClosure);
}
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2016 The Dash developers
// Copyright (c) 2016-2018 The PIVX developers
// Copyright (c) 2018 The Zest Foundation developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "transactiontablemodel.h"
#include "addresstablemodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "transactiondesc.h"
#include "transactionrecord.h"
#include "walletmodel.h"
#include "main.h"
#include "sync.h"
#include "uint256.h"
#include "util.h"
#include "wallet.h"
#include <QColor>
#include <QDateTime>
#include <QDebug>
#include <QIcon>
#include <QList>
// Amount column is right-aligned it contains numbers
static int column_alignments[] = {
Qt::AlignLeft | Qt::AlignVCenter, /* status */
Qt::AlignLeft | Qt::AlignVCenter, /* watchonly */
Qt::AlignLeft | Qt::AlignVCenter, /* date */
Qt::AlignLeft | Qt::AlignVCenter, /* type */
Qt::AlignLeft | Qt::AlignVCenter, /* address */
Qt::AlignLeft | Qt::AlignVCenter /* amount */
};
// Comparison operator for sort/binary search of model tx list
struct TxLessThan {
bool operator()(const TransactionRecord& a, const TransactionRecord& b) const
{
return a.hash < b.hash;
}
bool operator()(const TransactionRecord& a, const uint256& b) const
{
return a.hash < b;
}
bool operator()(const uint256& a, const TransactionRecord& b) const
{
return a < b.hash;
}
};
// Private implementation
class TransactionTablePriv
{
public:
TransactionTablePriv(CWallet* wallet, TransactionTableModel* parent) : wallet(wallet),
parent(parent)
{
}
CWallet* wallet;
TransactionTableModel* parent;
/* Local cache of wallet.
* As it is in the same order as the CWallet, by definition
* this is sorted by sha256.
*/
QList<TransactionRecord> cachedWallet;
/* Query entire wallet anew from core.
*/
void refreshWallet()
{
qDebug() << "TransactionTablePriv::refreshWallet";
cachedWallet.clear();
{
LOCK2(cs_main, wallet->cs_wallet);
for (std::map<uint256, CWalletTx>::iterator it = wallet->mapWallet.begin(); it != wallet->mapWallet.end(); ++it) {
if (TransactionRecord::showTransaction(it->second))
cachedWallet.append(TransactionRecord::decomposeTransaction(wallet, it->second));
}
}
}
/* Update our model of the wallet incrementally, to synchronize our model of the wallet
with that of the core.
Call with transaction that was added, removed or changed.
*/
void updateWallet(const uint256& hash, int status, bool showTransaction)
{
qDebug() << "TransactionTablePriv::updateWallet : " + QString::fromStdString(hash.ToString()) + " " + QString::number(status);
// Find bounds of this transaction in model
QList<TransactionRecord>::iterator lower = qLowerBound(
cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());
QList<TransactionRecord>::iterator upper = qUpperBound(
cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());
int lowerIndex = (lower - cachedWallet.begin());
int upperIndex = (upper - cachedWallet.begin());
bool inModel = (lower != upper);
if (status == CT_UPDATED) {
if (showTransaction && !inModel)
status = CT_NEW; /* Not in model, but want to show, treat as new */
if (!showTransaction && inModel)
status = CT_DELETED; /* In model, but want to hide, treat as deleted */
}
qDebug() << " inModel=" + QString::number(inModel) +
" Index=" + QString::number(lowerIndex) + "-" + QString::number(upperIndex) +
" showTransaction=" + QString::number(showTransaction) + " derivedStatus=" + QString::number(status);
switch (status) {
case CT_NEW:
if (inModel) {
qWarning() << "TransactionTablePriv::updateWallet : Warning: Got CT_NEW, but transaction is already in model";
break;
}
if (showTransaction) {
LOCK2(cs_main, wallet->cs_wallet);
// Find transaction in wallet
std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash);
if (mi == wallet->mapWallet.end()) {
qWarning() << "TransactionTablePriv::updateWallet : Warning: Got CT_NEW, but transaction is not in wallet";
break;
}
// Added -- insert at the right position
QList<TransactionRecord> toInsert =
TransactionRecord::decomposeTransaction(wallet, mi->second);
if (!toInsert.isEmpty()) /* only if something to insert */
{
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex + toInsert.size() - 1);
int insert_idx = lowerIndex;
foreach (const TransactionRecord& rec, toInsert) {
cachedWallet.insert(insert_idx, rec);
insert_idx += 1;
}
parent->endInsertRows();
}
}
break;
case CT_DELETED:
if (!inModel) {
qWarning() << "TransactionTablePriv::updateWallet : Warning: Got CT_DELETED, but transaction is not in model";
break;
}
// Removed -- remove entire transaction from table
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex - 1);
cachedWallet.erase(lower, upper);
parent->endRemoveRows();
break;
case CT_UPDATED:
// Miscellaneous updates -- nothing to do, status update will take care of this, and is only computed for
// visible transactions.
break;
}
}
int size()
{
return cachedWallet.size();
}
TransactionRecord* index(int idx)
{
if (idx >= 0 && idx < cachedWallet.size()) {
TransactionRecord* rec = &cachedWallet[idx];
// Get required locks upfront. This avoids the GUI from getting
// stuck if the core is holding the locks for a longer time - for
// example, during a wallet rescan.
//
// If a status update is needed (blocks came in since last check),
// update the status of this transaction from the wallet. Otherwise,
// simply re-use the cached status.
TRY_LOCK(cs_main, lockMain);
if (lockMain) {
TRY_LOCK(wallet->cs_wallet, lockWallet);
if (lockWallet && rec->statusUpdateNeeded()) {
std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash);
if (mi != wallet->mapWallet.end()) {
rec->updateStatus(mi->second);
}
}
}
return rec;
}
return 0;
}
QString describe(TransactionRecord* rec, int unit)
{
{
LOCK2(cs_main, wallet->cs_wallet);
std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash);
if (mi != wallet->mapWallet.end()) {
return TransactionDesc::toHTML(wallet, mi->second, rec, unit);
}
}
return QString();
}
};
TransactionTableModel::TransactionTableModel(CWallet* wallet, WalletModel* parent) : QAbstractTableModel(parent),
wallet(wallet),
walletModel(parent),
priv(new TransactionTablePriv(wallet, this)),
fProcessingQueuedTransactions(false)
{
columns << QString() << QString() << tr("Date") << tr("Type") << tr("Address") << BitcoinUnits::getAmountColumnTitle(walletModel->getOptionsModel()->getDisplayUnit());
priv->refreshWallet();
connect(walletModel->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
subscribeToCoreSignals();
}
TransactionTableModel::~TransactionTableModel()
{
unsubscribeFromCoreSignals();
delete priv;
}
/** Updates the column title to "Amount (DisplayUnit)" and emits headerDataChanged() signal for table headers to react. */
void TransactionTableModel::updateAmountColumnTitle()
{
columns[Amount] = BitcoinUnits::getAmountColumnTitle(walletModel->getOptionsModel()->getDisplayUnit());
emit headerDataChanged(Qt::Horizontal, Amount, Amount);
}
void TransactionTableModel::updateTransaction(const QString& hash, int status, bool showTransaction)
{
uint256 updated;
updated.SetHex(hash.toStdString());
priv->updateWallet(updated, status, showTransaction);
}
void TransactionTableModel::updateConfirmations()
{
// Blocks came in since last poll.
// Invalidate status (number of confirmations) and (possibly) description
// for all rows. Qt is smart enough to only actually request the data for the
// visible rows.
emit dataChanged(index(0, Status), index(priv->size() - 1, Status));
emit dataChanged(index(0, ToAddress), index(priv->size() - 1, ToAddress));
}
int TransactionTableModel::rowCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int TransactionTableModel::columnCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QString TransactionTableModel::formatTxStatus(const TransactionRecord* wtx) const
{
QString status;
switch (wtx->status.status) {
case TransactionStatus::OpenUntilBlock:
status = tr("Open for %n more block(s)", "", wtx->status.open_for);
break;
case TransactionStatus::OpenUntilDate:
status = tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx->status.open_for));
break;
case TransactionStatus::Offline:
status = tr("Offline");
break;
case TransactionStatus::Unconfirmed:
status = tr("Unconfirmed");
break;
case TransactionStatus::Confirming:
status = tr("Confirming (%1 of %2 recommended confirmations)").arg(wtx->status.depth).arg(TransactionRecord::RecommendedNumConfirmations);
break;
case TransactionStatus::Confirmed:
status = tr("Confirmed (%1 confirmations)").arg(wtx->status.depth);
break;
case TransactionStatus::Conflicted:
status = tr("Conflicted");
break;
case TransactionStatus::Immature:
status = tr("Immature (%1 confirmations, will be available after %2)").arg(wtx->status.depth).arg(wtx->status.depth + wtx->status.matures_in);
break;
case TransactionStatus::MaturesWarning:
status = tr("This block was not received by any other nodes and will probably not be accepted!");
break;
case TransactionStatus::NotAccepted:
status = tr("Orphan Block - Generated but not accepted. This does not impact your holdings.");
break;
}
return status;
}
QString TransactionTableModel::formatTxDate(const TransactionRecord* wtx) const
{
if (wtx->time) {
return GUIUtil::dateTimeStr(wtx->time);
}
return QString();
}
/* Look up address in address book, if found return label (address)
otherwise just return (address)
*/
QString TransactionTableModel::lookupAddress(const std::string& address, bool tooltip) const
{
QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(address));
QString description;
if (!label.isEmpty()) {
description += label;
}
if (label.isEmpty() || tooltip) {
description += QString(" (") + QString::fromStdString(address) + QString(")");
}
return description;
}
QString TransactionTableModel::formatTxType(const TransactionRecord* wtx) const
{
switch (wtx->type) {
case TransactionRecord::RecvWithAddress:
return tr("Received with");
case TransactionRecord::MNReward:
return tr("Masternode Reward");
case TransactionRecord::RecvFromOther:
return tr("Received from");
case TransactionRecord::SendToAddress:
case TransactionRecord::SendToOther:
return tr("Sent to");
case TransactionRecord::SendToSelf:
return tr("Payment to yourself");
case TransactionRecord::StakeMint:
return tr("Minted");
case TransactionRecord::Generated:
return tr("Mined");
default:
return QString();
}
}
QVariant TransactionTableModel::txAddressDecoration(const TransactionRecord* wtx) const
{
switch (wtx->type) {
case TransactionRecord::Generated:
case TransactionRecord::StakeMint:
case TransactionRecord::MNReward:
return QIcon(":/icons/tx_mined");
case TransactionRecord::RecvWithAddress:
case TransactionRecord::RecvFromOther:
return QIcon(":/icons/tx_input");
case TransactionRecord::SendToAddress:
case TransactionRecord::SendToOther:
return QIcon(":/icons/tx_output");
default:
return QIcon(":/icons/tx_inout");
}
}
QString TransactionTableModel::formatTxToAddress(const TransactionRecord* wtx, bool tooltip) const
{
QString watchAddress;
if (tooltip) {
// Mark transactions involving watch-only addresses by adding " (watch-only)"
watchAddress = wtx->involvesWatchAddress ? QString(" (") + tr("watch-only") + QString(")") : "";
}
switch (wtx->type) {
case TransactionRecord::RecvFromOther:
return QString::fromStdString(wtx->address) + watchAddress;
case TransactionRecord::RecvWithAddress:
case TransactionRecord::MNReward:
case TransactionRecord::SendToAddress:
case TransactionRecord::Generated:
case TransactionRecord::StakeMint:
return lookupAddress(wtx->address, tooltip);
case TransactionRecord::SendToOther:
return QString::fromStdString(wtx->address) + watchAddress;
case TransactionRecord::SendToSelf:
default:
return tr("(n/a)") + watchAddress;
}
}
QVariant TransactionTableModel::addressColor(const TransactionRecord* wtx) const
{
switch (wtx->type) {
// Show addresses without label in a less visible color
case TransactionRecord::RecvWithAddress:
case TransactionRecord::SendToAddress:
case TransactionRecord::Generated:
case TransactionRecord::MNReward: {
QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(wtx->address));
if (label.isEmpty())
return COLOR_BAREADDRESS;
}
case TransactionRecord::SendToSelf:
default:
// To avoid overriding above conditional formats a default text color for this QTableView is not defined in stylesheet,
// so we must always return a color here
return COLOR_BLACK;
}
}
QString TransactionTableModel::formatTxAmount(const TransactionRecord* wtx, bool showUnconfirmed, BitcoinUnits::SeparatorStyle separators) const
{
QString str = BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), wtx->credit + wtx->debit, false, separators);
if (showUnconfirmed) {
if (!wtx->status.countsForBalance) {
str = QString("[") + str + QString("]");
}
}
return QString(str);
}
QVariant TransactionTableModel::txStatusDecoration(const TransactionRecord* wtx) const
{
switch (wtx->status.status) {
case TransactionStatus::OpenUntilBlock:
case TransactionStatus::OpenUntilDate:
return COLOR_TX_STATUS_OPENUNTILDATE;
case TransactionStatus::Offline:
return COLOR_TX_STATUS_OFFLINE;
case TransactionStatus::Unconfirmed:
return QIcon(":/icons/transaction_0");
case TransactionStatus::Confirming:
switch (wtx->status.depth) {
case 1:
return QIcon(":/icons/transaction_1");
case 2:
return QIcon(":/icons/transaction_2");
case 3:
return QIcon(":/icons/transaction_3");
case 4:
return QIcon(":/icons/transaction_4");
default:
return QIcon(":/icons/transaction_5");
};
case TransactionStatus::Confirmed:
return QIcon(":/icons/transaction_confirmed");
case TransactionStatus::Conflicted:
return QIcon(":/icons/transaction_conflicted");
case TransactionStatus::Immature: {
int total = wtx->status.depth + wtx->status.matures_in;
int part = (wtx->status.depth * 4 / total) + 1;
return QIcon(QString(":/icons/transaction_%1").arg(part));
}
case TransactionStatus::MaturesWarning:
case TransactionStatus::NotAccepted:
return QIcon(":/icons/transaction_0");
default:
return COLOR_BLACK;
}
}
QVariant TransactionTableModel::txWatchonlyDecoration(const TransactionRecord* wtx) const
{
if (wtx->involvesWatchAddress)
return QIcon(":/icons/eye");
else
return QVariant();
}
QString TransactionTableModel::formatTooltip(const TransactionRecord* rec) const
{
QString tooltip = formatTxStatus(rec) + QString("\n") + formatTxType(rec);
if (rec->type == TransactionRecord::RecvFromOther || rec->type == TransactionRecord::SendToOther ||
rec->type == TransactionRecord::SendToAddress || rec->type == TransactionRecord::RecvWithAddress || rec->type == TransactionRecord::MNReward) {
tooltip += QString(" ") + formatTxToAddress(rec, true);
}
return tooltip;
}
QVariant TransactionTableModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
TransactionRecord* rec = static_cast<TransactionRecord*>(index.internalPointer());
switch (role) {
case Qt::DecorationRole:
switch (index.column()) {
case Status:
return txStatusDecoration(rec);
case Watchonly:
return txWatchonlyDecoration(rec);
case ToAddress:
return txAddressDecoration(rec);
}
break;
case Qt::DisplayRole:
switch (index.column()) {
case Date:
return formatTxDate(rec);
case Type:
return formatTxType(rec);
case ToAddress:
return formatTxToAddress(rec, false);
case Amount:
return formatTxAmount(rec, true, BitcoinUnits::separatorNever);
}
break;
case Qt::EditRole:
// Edit role is used for sorting, so return the unformatted values
switch (index.column()) {
case Status:
return QString::fromStdString(rec->status.sortKey);
case Date:
return rec->time;
case Type:
return formatTxType(rec);
case Watchonly:
return (rec->involvesWatchAddress ? 1 : 0);
case ToAddress:
return formatTxToAddress(rec, true);
case Amount:
return qint64(rec->credit + rec->debit);
}
break;
case Qt::ToolTipRole:
return formatTooltip(rec);
case Qt::TextAlignmentRole:
return column_alignments[index.column()];
case Qt::ForegroundRole:
// Minted
if (rec->type == TransactionRecord::Generated || rec->type == TransactionRecord::StakeMint ||
rec->type == TransactionRecord::MNReward) {
if (rec->status.status == TransactionStatus::Conflicted || rec->status.status == TransactionStatus::NotAccepted)
return COLOR_ORPHAN;
else
return COLOR_STAKE;
}
// Conflicted tx
if (rec->status.status == TransactionStatus::Conflicted || rec->status.status == TransactionStatus::NotAccepted) {
return COLOR_CONFLICTED;
}
// Unconfimed or immature
if ((rec->status.status == TransactionStatus::Unconfirmed) || (rec->status.status == TransactionStatus::Immature)) {
return COLOR_UNCONFIRMED;
}
if (index.column() == Amount && (rec->credit + rec->debit) < 0) {
return COLOR_NEGATIVE;
}
if (index.column() == ToAddress) {
return addressColor(rec);
}
// To avoid overriding above conditional formats a default text color for this QTableView is not defined in stylesheet,
// so we must always return a color here
return COLOR_BLACK;
case TypeRole:
return rec->type;
case DateRole:
return QDateTime::fromTime_t(static_cast<uint>(rec->time));
case WatchonlyRole:
return rec->involvesWatchAddress;
case WatchonlyDecorationRole:
return txWatchonlyDecoration(rec);
case LongDescriptionRole:
return priv->describe(rec, walletModel->getOptionsModel()->getDisplayUnit());
case AddressRole:
return QString::fromStdString(rec->address);
case LabelRole:
return walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(rec->address));
case AmountRole:
return qint64(rec->credit + rec->debit);
case TxIDRole:
return rec->getTxID();
case TxHashRole:
return QString::fromStdString(rec->hash.ToString());
case ConfirmedRole:
return rec->status.countsForBalance;
case FormattedAmountRole:
// Used for copy/export, so don't include separators
return formatTxAmount(rec, false, BitcoinUnits::separatorNever);
case StatusRole:
return rec->status.status;
}
return QVariant();
}
QVariant TransactionTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal) {
if (role == Qt::DisplayRole) {
return columns[section];
} else if (role == Qt::TextAlignmentRole) {
return column_alignments[section];
} else if (role == Qt::ToolTipRole) {
switch (section) {
case Status:
return tr("Transaction status. Hover over this field to show number of confirmations.");
case Date:
return tr("Date and time that the transaction was received.");
case Type:
return tr("Type of transaction.");
case Watchonly:
return tr("Whether or not a watch-only address is involved in this transaction.");
case ToAddress:
return tr("Destination address of transaction.");
case Amount:
return tr("Amount removed from or added to balance.");
}
}
}
return QVariant();
}
QModelIndex TransactionTableModel::index(int row, int column, const QModelIndex& parent) const
{
Q_UNUSED(parent);
TransactionRecord* data = priv->index(row);
if (data) {
return createIndex(row, column, priv->index(row));
}
return QModelIndex();
}
void TransactionTableModel::updateDisplayUnit()
{
// emit dataChanged to update Amount column with the current unit
updateAmountColumnTitle();
emit dataChanged(index(0, Amount), index(priv->size() - 1, Amount));
}
// queue notifications to show a non freezing progress dialog e.g. for rescan
struct TransactionNotification {
public:
TransactionNotification() {}
TransactionNotification(uint256 hash, ChangeType status, bool showTransaction) : hash(hash), status(status), showTransaction(showTransaction) {}
void invoke(QObject* ttm)
{
QString strHash = QString::fromStdString(hash.GetHex());
qDebug() << "NotifyTransactionChanged : " + strHash + " status= " + QString::number(status);
QMetaObject::invokeMethod(ttm, "updateTransaction", Qt::QueuedConnection,
Q_ARG(QString, strHash),
Q_ARG(int, status),
Q_ARG(bool, showTransaction));
}
private:
uint256 hash;
ChangeType status;
bool showTransaction;
};
static bool fQueueNotifications = false;
static std::vector<TransactionNotification> vQueueNotifications;
static void NotifyTransactionChanged(TransactionTableModel* ttm, CWallet* wallet, const uint256& hash, ChangeType status)
{
// Find transaction in wallet
std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash);
// Determine whether to show transaction or not (determine this here so that no relocking is needed in GUI thread)
bool inWallet = mi != wallet->mapWallet.end();
bool showTransaction = (inWallet && TransactionRecord::showTransaction(mi->second));
TransactionNotification notification(hash, status, showTransaction);
if (fQueueNotifications) {
vQueueNotifications.push_back(notification);
return;
}
notification.invoke(ttm);
}
static void ShowProgress(TransactionTableModel* ttm, const std::string& title, int nProgress)
{
if (nProgress == 0)
fQueueNotifications = true;
if (nProgress == 100) {
fQueueNotifications = false;
if (vQueueNotifications.size() > 10) // prevent balloon spam, show maximum 10 balloons
QMetaObject::invokeMethod(ttm, "setProcessingQueuedTransactions", Qt::QueuedConnection, Q_ARG(bool, true));
for (unsigned int i = 0; i < vQueueNotifications.size(); ++i) {
if (vQueueNotifications.size() - i <= 10)
QMetaObject::invokeMethod(ttm, "setProcessingQueuedTransactions", Qt::QueuedConnection, Q_ARG(bool, false));
vQueueNotifications[i].invoke(ttm);
}
std::vector<TransactionNotification>().swap(vQueueNotifications); // clear
}
}
void TransactionTableModel::subscribeToCoreSignals()
{
// Connect signals to wallet
wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
wallet->ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2));
}
void TransactionTableModel::unsubscribeFromCoreSignals()
{
// Disconnect signals from wallet
wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
wallet->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
}
|
/*
*
* Copyright 2019 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 <grpc/support/port_platform.h>
#include "src/core/ext/filters/client_channel/config_selector.h"
#include "src/core/ext/filters/client_channel/resolver_registry.h"
#include "src/core/ext/filters/client_channel/xds/xds_client.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/transport/timeout_encoding.h"
namespace grpc_core {
TraceFlag grpc_xds_resolver_trace(false, "xds_resolver");
const char* kCallAttributeDeadline = "deadline";
namespace {
//
// XdsResolver
//
class XdsResolver : public Resolver {
public:
explicit XdsResolver(ResolverArgs args)
: Resolver(std::move(args.work_serializer),
std::move(args.result_handler)),
args_(grpc_channel_args_copy(args.args)),
interested_parties_(args.pollset_set),
config_selector_(MakeRefCounted<XdsConfigSelector>()) {
char* path = args.uri->path;
if (path[0] == '/') ++path;
server_name_ = path;
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_resolver_trace)) {
gpr_log(GPR_INFO, "[xds_resolver %p] created for server name %s", this,
server_name_.c_str());
}
}
~XdsResolver() override {
grpc_channel_args_destroy(args_);
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_resolver_trace)) {
gpr_log(GPR_INFO, "[xds_resolver %p] destroyed", this);
}
}
void StartLocked() override;
void ShutdownLocked() override {
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_resolver_trace)) {
gpr_log(GPR_INFO, "[xds_resolver %p] shutting down", this);
}
xds_client_.reset();
}
private:
class ServiceConfigWatcher : public XdsClient::ServiceConfigWatcherInterface {
public:
explicit ServiceConfigWatcher(RefCountedPtr<XdsResolver> resolver)
: resolver_(std::move(resolver)) {}
void OnServiceConfigChanged(
RefCountedPtr<ServiceConfig> service_config) override;
void OnError(grpc_error* error) override;
void OnResourceDoesNotExist() override;
private:
RefCountedPtr<XdsResolver> resolver_;
};
class XdsConfigSelector : public ConfigSelector {
public:
CallConfig GetCallConfig(GetCallConfigArgs args) override {
char* deadline_str = static_cast<char*>(
args.arena->Alloc(GRPC_HTTP2_TIMEOUT_ENCODE_MIN_BUFSIZE));
grpc_http2_encode_timeout(
args.initial_metadata->deadline - grpc_core::ExecCtx::Get()->Now(),
deadline_str);
CallConfig call_config;
call_config.call_attributes[kCallAttributeDeadline] =
absl::string_view(deadline_str);
return call_config;
}
};
std::string server_name_;
const grpc_channel_args* args_;
grpc_pollset_set* interested_parties_;
OrphanablePtr<XdsClient> xds_client_;
RefCountedPtr<XdsConfigSelector> config_selector_;
};
void XdsResolver::ServiceConfigWatcher::OnServiceConfigChanged(
RefCountedPtr<ServiceConfig> service_config) {
if (resolver_->xds_client_ == nullptr) return;
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_resolver_trace)) {
gpr_log(GPR_INFO, "[xds_resolver %p] received updated service config: %s",
resolver_.get(), service_config->json_string().c_str());
}
grpc_arg new_args[] = {
resolver_->xds_client_->MakeChannelArg(),
resolver_->config_selector_->MakeChannelArg(),
};
Result result;
result.args = grpc_channel_args_copy_and_add(resolver_->args_, new_args,
GPR_ARRAY_SIZE(new_args));
result.service_config = std::move(service_config);
resolver_->result_handler()->ReturnResult(std::move(result));
}
void XdsResolver::ServiceConfigWatcher::OnError(grpc_error* error) {
if (resolver_->xds_client_ == nullptr) return;
gpr_log(GPR_ERROR, "[xds_resolver %p] received error: %s", resolver_.get(),
grpc_error_string(error));
grpc_arg xds_client_arg = resolver_->xds_client_->MakeChannelArg();
Result result;
result.args =
grpc_channel_args_copy_and_add(resolver_->args_, &xds_client_arg, 1);
result.service_config_error = error;
resolver_->result_handler()->ReturnResult(std::move(result));
}
void XdsResolver::ServiceConfigWatcher::OnResourceDoesNotExist() {
if (resolver_->xds_client_ == nullptr) return;
gpr_log(GPR_ERROR,
"[xds_resolver %p] LDS/RDS resource does not exist -- returning "
"empty service config",
resolver_.get());
Result result;
result.service_config =
ServiceConfig::Create("{}", &result.service_config_error);
GPR_ASSERT(result.service_config != nullptr);
result.args = grpc_channel_args_copy(resolver_->args_);
resolver_->result_handler()->ReturnResult(std::move(result));
}
void XdsResolver::StartLocked() {
grpc_error* error = GRPC_ERROR_NONE;
xds_client_ = MakeOrphanable<XdsClient>(
work_serializer(), interested_parties_, server_name_,
absl::make_unique<ServiceConfigWatcher>(Ref()), *args_, &error);
if (error != GRPC_ERROR_NONE) {
gpr_log(GPR_ERROR,
"Failed to create xds client -- channel will remain in "
"TRANSIENT_FAILURE: %s",
grpc_error_string(error));
result_handler()->ReturnError(error);
}
}
//
// Factory
//
class XdsResolverFactory : public ResolverFactory {
public:
bool IsValidUri(const grpc_uri* uri) const override {
if (GPR_UNLIKELY(0 != strcmp(uri->authority, ""))) {
gpr_log(GPR_ERROR, "URI authority not supported");
return false;
}
return true;
}
OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const override {
if (!IsValidUri(args.uri)) return nullptr;
return MakeOrphanable<XdsResolver>(std::move(args));
}
const char* scheme() const override { return "xds"; }
};
} // namespace
} // namespace grpc_core
void grpc_resolver_xds_init() {
grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
absl::make_unique<grpc_core::XdsResolverFactory>());
}
void grpc_resolver_xds_shutdown() {}
|
#include "Common.h"
#include "BuildingManager.h"
#include "CCBot.h"
#include "Util.h"
BuildingManager::BuildingManager(CCBot & bot)
: m_bot(bot)
, m_buildingPlacer(bot)
, m_debugMode(true)
, m_reservedMinerals(0)
, m_reservedGas(0)
{
}
void BuildingManager::onStart()
{
m_buildingPlacer.onStart();
}
// gets called every frame from GameCommander
void BuildingManager::onFrame()
{
for (auto unit : m_bot.UnitInfo().getUnits(Players::Self))
{
// filter out units which aren't buildings under construction
if (m_bot.Data(unit).isBuilding)
{
std::stringstream ss;
ss << unit.getID();
m_bot.Map().drawText(unit.getPosition(), ss.str());
}
}
validateWorkersAndBuildings(); // check to see if assigned workers have died en route or while constructing
assignWorkersToUnassignedBuildings(); // assign workers to the unassigned buildings and label them 'planned'
constructAssignedBuildings(); // for each planned building, if the worker isn't constructing, send the command
checkForStartedConstruction(); // check to see if any buildings have started construction and update data structures
checkForDeadTerranBuilders(); // if we are terran and a building is under construction without a worker, assign a new one
checkForCompletedBuildings(); // check to see if any buildings have completed and update data structures
drawBuildingInformation();
}
bool BuildingManager::isBeingBuilt(UnitType type)
{
for (auto & b : m_buildings)
{
if (b.type == type)
{
return true;
}
}
return false;
}
// STEP 1: DO BOOK KEEPING ON WORKERS WHICH MAY HAVE DIED
void BuildingManager::validateWorkersAndBuildings()
{
// TODO: if a terran worker dies while constructing and its building
// is under construction, place unit back into buildingsNeedingBuilders
std::vector<Building> toRemove;
// find any buildings which have become obsolete
for (auto & b : m_buildings)
{
if (b.status != BuildingStatus::UnderConstruction)
{
continue;
}
auto buildingUnit = b.buildingUnit;
// TODO: || !b.buildingUnit->getType().isBuilding()
if (!buildingUnit.isValid())
{
toRemove.push_back(b);
}
}
removeBuildings(toRemove);
}
// STEP 2: FIND A SUITABLE LOCATION TO BUILD THE REQUESTED BUILDING
void BuildingManager::assignWorkersToUnassignedBuildings()
{
// for each building that doesn't have a builder, assign one
for (Building & b : m_buildings)
{
if (b.status != BuildingStatus::Unassigned)
{
continue;
}
BOT_ASSERT(!b.builderUnit.isValid(), "Error: Tried to assign a builder to a building that already had one ");
if (m_debugMode) { printf("Assigning Worker To: %s\n", b.type.getName().c_str()); }
// If the building does not yet have a worker assigned to it, go assign one.
if (b.finalPosition != sc2::Point2DI{ 0,0 }) continue;
b.finalPosition = m_buildingPlacer.getBuildLocationForType(b.type.getAPIUnitType(), b.desiredPosition);
std::cout << "final_position:" << b.finalPosition.x << " + " << b.finalPosition.y << std::endl;
// reserve this building's space
m_buildingPlacer.reserveTiles(b.type.getAPIUnitType(), b.finalPosition);
// grab the worker unit from WorkerManager which is closest to this final position
Unit builderUnit = m_bot.Workers().getBuilder(b);
b.builderUnit = builderUnit;
b.status = BuildingStatus::Assigned;
}
}
// STEP 3: ISSUE CONSTRUCTION ORDERS TO ASSIGN BUILDINGS AS NEEDED
void BuildingManager::constructAssignedBuildings()
{
for (auto & b : m_buildings)
{
if (b.status != BuildingStatus::Assigned)
{
continue;
}
if (!b.builderUnit.isValid())
{
continue;
}
bool isConstructing = false;
// if we're zerg and the builder unit is null, we assume it morphed into the building
if (Util::IsZerg(m_bot.GetPlayerRace(Players::Self)))
{
if (!b.builderUnit.isValid())
{
isConstructing = true;
}
}
else
{
BOT_ASSERT(b.builderUnit.isValid(), "null builder unit");
isConstructing = b.builderUnit.isConstructing(b.type);
}
// if that worker is not currently constructing
if (!isConstructing)
{
// if we haven't explored the build position, go there
if (!isBuildingPositionExplored(b))
{
b.builderUnit.move(b.finalPosition);
}
// if this is not the first time we've sent this guy to build this
// it must be the case that something was in the way of building
else if (b.buildCommandGiven)
{
// TODO: in here is where we would check to see if the builder died on the way
// or if things are taking too long, or the build location is no longer valid
}
else
{
// if it's a refinery, the build command has to be on the geyser unit tag
if (b.type.isRefinery())
{
// first we find the geyser at the desired location
Unit geyser;
for (auto unit : m_bot.GetUnits())
{
if (unit.getType().isGeyser() && Util::Dist(Util::GetPosition(b.finalPosition), unit.getPosition()) < 3)
{
geyser = unit;
break;
}
}
if (geyser.isValid())
{
b.builderUnit.buildTarget(b.type, geyser);
}
else
{
std::cout << "WARNING: NO VALID GEYSER UNIT FOUND TO BUILD ON, SKIPPING REFINERY\n";
}
}
// if it's not a refinery, we build right on the position
else
{
b.builderUnit.build(b.type, b.finalPosition);
}
// set the flag to true
b.buildCommandGiven = true;
}
}
}
}
// STEP 4: UPDATE DATA STRUCTURES FOR BUILDINGS STARTING CONSTRUCTION
void BuildingManager::checkForStartedConstruction()
{
// for each building unit which is being constructed
for (auto buildingStarted : m_bot.UnitInfo().getUnits(Players::Self))
{
// filter out units which aren't buildings under construction
if (!buildingStarted.getType().isBuilding() || !buildingStarted.isBeingConstructed())
{
continue;
}
// check all our building status objects to see if we have a match and if we do, update it
for (auto & b : m_buildings)
{
if (b.status != BuildingStatus::Assigned)
{
continue;
}
// check if the positions match
int dx = b.finalPosition.x - buildingStarted.getTilePosition().x;
int dy = b.finalPosition.y - buildingStarted.getTilePosition().y;
if (dx*dx + dy*dy < Util::TileToPosition(1.0f))
{
if (b.buildingUnit.isValid())
{
std::cout << "Building mis-match somehow\n";
}
// the resources should now be spent, so unreserve them
m_reservedMinerals -= buildingStarted.getType().mineralPrice();
m_reservedGas -= buildingStarted.getType().gasPrice();
// flag it as started and set the buildingUnit
b.underConstruction = true;
b.buildingUnit = buildingStarted;
// if we are zerg, the buildingUnit now becomes nullptr since it's destroyed
if (Util::IsZerg(m_bot.GetPlayerRace(Players::Self)))
{
b.builderUnit = Unit();
}
else if (Util::IsProtoss(m_bot.GetPlayerRace(Players::Self)))
{
m_bot.Workers().finishedWithWorker(b.builderUnit);
b.builderUnit = Unit();
}
// put it in the under construction vector
b.status = BuildingStatus::UnderConstruction;
// free this space
m_buildingPlacer.freeTiles((int)b.finalPosition.x, (int)b.finalPosition.y, b.type.tileWidth(), b.type.tileHeight());
// only one building will match
break;
}
}
}
}
// STEP 5: IF WE ARE TERRAN, THIS MATTERS, SO: LOL
void BuildingManager::checkForDeadTerranBuilders() {}
// STEP 6: CHECK FOR COMPLETED BUILDINGS
void BuildingManager::checkForCompletedBuildings()
{
std::vector<Building> toRemove;
// for each of our buildings under construction
for (auto & b : m_buildings)
{
if (b.status != BuildingStatus::UnderConstruction)
{
continue;
}
// if the unit has completed
if (b.buildingUnit.isCompleted())
{
// if we are terran, give the worker back to worker manager
if (Util::IsTerran(m_bot.GetPlayerRace(Players::Self)))
{
if (Util::IsTownHallType(b.type.getAPIUnitType()))
{
m_bot.resetExpandState();
}
m_bot.Workers().finishedWithWorker(b.builderUnit);
}
// remove this unit from the under construction vector
toRemove.push_back(b);
}
}
removeBuildings(toRemove);
}
// add a new building to be constructed
void BuildingManager::addBuildingTask(const UnitType & type, const CCTilePosition & desiredPosition)
{
m_reservedMinerals += m_bot.Data(type).mineralCost;
m_reservedGas += m_bot.Data(type).gasCost;
Building b(type, desiredPosition);
b.status = BuildingStatus::Unassigned;
m_buildings.push_back(b);
}
// TODO: may need to iterate over all tiles of the building footprint
bool BuildingManager::isBuildingPositionExplored(const Building & b) const
{
return m_bot.Map().isExplored(b.finalPosition);
}
char BuildingManager::getBuildingWorkerCode(const Building & b) const
{
return b.builderUnit.isValid() ? 'W' : 'X';
}
int BuildingManager::getReservedMinerals()
{
return m_reservedMinerals;
}
int BuildingManager::getReservedGas()
{
return m_reservedGas;
}
BuildingPlacer BuildingManager::getBuildPlacer()
{
return m_buildingPlacer;
}
void BuildingManager::drawBuildingInformation()
{
m_buildingPlacer.drawReservedTiles();
if (!m_bot.Config().DrawBuildingInfo)
{
return;
}
std::stringstream ss;
ss << "Building Information " << m_buildings.size() << "\n\n\n";
int yspace = 0;
for (const auto & b : m_buildings)
{
std::stringstream dss;
if (b.builderUnit.isValid())
{
dss << "\n\nBuilder: " << b.builderUnit.getID() << "\n";
}
if (b.buildingUnit.isValid())
{
dss << "Building: " << b.buildingUnit.getID() << "\n" << b.buildingUnit.getBuildPercentage();
m_bot.Map().drawText(b.buildingUnit.getPosition(), dss.str());
}
if (b.status == BuildingStatus::Unassigned)
{
ss << "Unassigned " << b.type.getName() << " " << getBuildingWorkerCode(b) << "\n";
}
else if (b.status == BuildingStatus::Assigned)
{
ss << "Assigned " << b.type.getName() << " " << b.builderUnit.getID() << " " << getBuildingWorkerCode(b) << " (" << b.finalPosition.x << "," << b.finalPosition.y << ")\n";
int x1 = b.finalPosition.x - b.type.tileWidth() / 2;
int y1 = b.finalPosition.y - b.type.tileHeight() / 2;
int x2 = b.finalPosition.x + b.type.tileWidth() / 2;
int y2 = b.finalPosition.y + b.type.tileHeight() / 2;
m_bot.Map().drawBox((CCPositionType)x1, (CCPositionType)y1, (CCPositionType)x2, (CCPositionType)y2, CCColor(255, 0, 0));
//m_bot.Map().drawLine(b.finalPosition, m_bot.GetUnit(b.builderUnitTag)->pos, CCColors::Yellow);
}
else if (b.status == BuildingStatus::UnderConstruction)
{
ss << "Constructing " << b.type.getName() << " " << getBuildingWorkerCode(b) << "\n";
}
}
m_bot.Map().drawTextScreen(0.3f, 0.05f, ss.str());
}
std::vector<UnitType> BuildingManager::buildingsQueued() const
{
std::vector<UnitType> buildingsQueued;
for (const auto & b : m_buildings)
{
if (b.status == BuildingStatus::Unassigned || b.status == BuildingStatus::Assigned)
{
buildingsQueued.push_back(b.type);
}
}
return buildingsQueued;
}
CCTilePosition BuildingManager::getBuildingLocation(const Building & b)
{
size_t numPylons = m_bot.UnitInfo().getUnitTypeCount(Players::Self, Util::GetSupplyProvider(m_bot.GetPlayerRace(Players::Self), m_bot), true);
// TODO: if requires psi and we have no pylons return 0
if (b.type.isRefinery())
{
return m_buildingPlacer.getRefineryPosition();
}
if (b.type.isResourceDepot())
{
return m_bot.Bases().getNextExpansion(Players::Self);
}
// get a position within our region
// TODO: put back in special pylon / cannon spacing
return m_buildingPlacer.getBuildLocationNear(b, m_bot.Config().BuildingSpacing);
}
void BuildingManager::removeBuildings(const std::vector<Building> & toRemove)
{
for (auto & b : toRemove)
{
const auto & it = std::find(m_buildings.begin(), m_buildings.end(), b);
if (it != m_buildings.end())
{
m_buildings.erase(it);
}
}
}
|
#include <inspurcloud/oss/model/Tagging.h>
#include "../utils/Utils.h"
#include <sstream>
using namespace InspurCloud::OSS;
std::string Tagging::toQueryParameters()
{
std::string sep;
std::stringstream ss;
for (const auto& tag : tagSet_)
{
if (tag.Key().empty())
continue;
if (tag.Value().empty())
ss << sep << UrlEncode(tag.Key());
else
ss << sep << UrlEncode(tag.Key()) << "=" << UrlEncode(tag.Value());
sep = "&";
}
return ss.str();
}
|
#pragma once
#include <algorithm> // reverse
#include <array> // array
#include <cmath> // isnan, isinf
#include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
#include <cstring> // memcpy
#include <limits> // numeric_limits
#include <string> // string
#include <utility> // move
#include VTK_NLOHMANN_JSON(detail/input/binary_reader.hpp)
#include VTK_NLOHMANN_JSON(detail/macro_scope.hpp)
#include VTK_NLOHMANN_JSON(detail/output/output_adapters.hpp)
namespace nlohmann
{
namespace detail
{
///////////////////
// binary writer //
///////////////////
/*!
@brief serialization to CBOR and MessagePack values
*/
template<typename BasicJsonType, typename CharType>
class binary_writer
{
using string_t = typename BasicJsonType::string_t;
using binary_t = typename BasicJsonType::binary_t;
using number_float_t = typename BasicJsonType::number_float_t;
public:
/*!
@brief create a binary writer
@param[in] adapter output adapter to write to
*/
explicit binary_writer(output_adapter_t<CharType> adapter) : oa(std::move(adapter))
{
JSON_ASSERT(oa);
}
/*!
@param[in] j JSON value to serialize
@pre j.type() == value_t::object
*/
void write_bson(const BasicJsonType& j)
{
switch (j.type())
{
case value_t::object:
{
write_bson_object(*j.m_value.object);
break;
}
case value_t::null:
case value_t::array:
case value_t::string:
case value_t::boolean:
case value_t::number_integer:
case value_t::number_unsigned:
case value_t::number_float:
case value_t::binary:
case value_t::discarded:
default:
{
JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name()), j));
}
}
}
/*!
@param[in] j JSON value to serialize
*/
void write_cbor(const BasicJsonType& j)
{
switch (j.type())
{
case value_t::null:
{
oa->write_character(to_char_type(0xF6));
break;
}
case value_t::boolean:
{
oa->write_character(j.m_value.boolean
? to_char_type(0xF5)
: to_char_type(0xF4));
break;
}
case value_t::number_integer:
{
if (j.m_value.number_integer >= 0)
{
// CBOR does not differentiate between positive signed
// integers and unsigned integers. Therefore, we used the
// code from the value_t::number_unsigned case here.
if (j.m_value.number_integer <= 0x17)
{
write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
}
else if (j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
{
oa->write_character(to_char_type(0x18));
write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
}
else if (j.m_value.number_integer <= (std::numeric_limits<std::uint16_t>::max)())
{
oa->write_character(to_char_type(0x19));
write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
}
else if (j.m_value.number_integer <= (std::numeric_limits<std::uint32_t>::max)())
{
oa->write_character(to_char_type(0x1A));
write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
}
else
{
oa->write_character(to_char_type(0x1B));
write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
}
}
else
{
// The conversions below encode the sign in the first
// byte, and the value is converted to a positive number.
const auto positive_number = -1 - j.m_value.number_integer;
if (j.m_value.number_integer >= -24)
{
write_number(static_cast<std::uint8_t>(0x20 + positive_number));
}
else if (positive_number <= (std::numeric_limits<std::uint8_t>::max)())
{
oa->write_character(to_char_type(0x38));
write_number(static_cast<std::uint8_t>(positive_number));
}
else if (positive_number <= (std::numeric_limits<std::uint16_t>::max)())
{
oa->write_character(to_char_type(0x39));
write_number(static_cast<std::uint16_t>(positive_number));
}
else if (positive_number <= (std::numeric_limits<std::uint32_t>::max)())
{
oa->write_character(to_char_type(0x3A));
write_number(static_cast<std::uint32_t>(positive_number));
}
else
{
oa->write_character(to_char_type(0x3B));
write_number(static_cast<std::uint64_t>(positive_number));
}
}
break;
}
case value_t::number_unsigned:
{
if (j.m_value.number_unsigned <= 0x17)
{
write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
}
else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
{
oa->write_character(to_char_type(0x18));
write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
}
else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
{
oa->write_character(to_char_type(0x19));
write_number(static_cast<std::uint16_t>(j.m_value.number_unsigned));
}
else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
{
oa->write_character(to_char_type(0x1A));
write_number(static_cast<std::uint32_t>(j.m_value.number_unsigned));
}
else
{
oa->write_character(to_char_type(0x1B));
write_number(static_cast<std::uint64_t>(j.m_value.number_unsigned));
}
break;
}
case value_t::number_float:
{
if (std::isnan(j.m_value.number_float))
{
// NaN is 0xf97e00 in CBOR
oa->write_character(to_char_type(0xF9));
oa->write_character(to_char_type(0x7E));
oa->write_character(to_char_type(0x00));
}
else if (std::isinf(j.m_value.number_float))
{
// Infinity is 0xf97c00, -Infinity is 0xf9fc00
oa->write_character(to_char_type(0xf9));
oa->write_character(j.m_value.number_float > 0 ? to_char_type(0x7C) : to_char_type(0xFC));
oa->write_character(to_char_type(0x00));
}
else
{
write_compact_float(j.m_value.number_float, detail::input_format_t::cbor);
}
break;
}
case value_t::string:
{
// step 1: write control byte and the string length
const auto N = j.m_value.string->size();
if (N <= 0x17)
{
write_number(static_cast<std::uint8_t>(0x60 + N));
}
else if (N <= (std::numeric_limits<std::uint8_t>::max)())
{
oa->write_character(to_char_type(0x78));
write_number(static_cast<std::uint8_t>(N));
}
else if (N <= (std::numeric_limits<std::uint16_t>::max)())
{
oa->write_character(to_char_type(0x79));
write_number(static_cast<std::uint16_t>(N));
}
else if (N <= (std::numeric_limits<std::uint32_t>::max)())
{
oa->write_character(to_char_type(0x7A));
write_number(static_cast<std::uint32_t>(N));
}
// LCOV_EXCL_START
else if (N <= (std::numeric_limits<std::uint64_t>::max)())
{
oa->write_character(to_char_type(0x7B));
write_number(static_cast<std::uint64_t>(N));
}
// LCOV_EXCL_STOP
// step 2: write the string
oa->write_characters(
reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
j.m_value.string->size());
break;
}
case value_t::array:
{
// step 1: write control byte and the array size
const auto N = j.m_value.array->size();
if (N <= 0x17)
{
write_number(static_cast<std::uint8_t>(0x80 + N));
}
else if (N <= (std::numeric_limits<std::uint8_t>::max)())
{
oa->write_character(to_char_type(0x98));
write_number(static_cast<std::uint8_t>(N));
}
else if (N <= (std::numeric_limits<std::uint16_t>::max)())
{
oa->write_character(to_char_type(0x99));
write_number(static_cast<std::uint16_t>(N));
}
else if (N <= (std::numeric_limits<std::uint32_t>::max)())
{
oa->write_character(to_char_type(0x9A));
write_number(static_cast<std::uint32_t>(N));
}
// LCOV_EXCL_START
else if (N <= (std::numeric_limits<std::uint64_t>::max)())
{
oa->write_character(to_char_type(0x9B));
write_number(static_cast<std::uint64_t>(N));
}
// LCOV_EXCL_STOP
// step 2: write each element
for (const auto& el : *j.m_value.array)
{
write_cbor(el);
}
break;
}
case value_t::binary:
{
if (j.m_value.binary->has_subtype())
{
if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint8_t>::max)())
{
write_number(static_cast<std::uint8_t>(0xd8));
write_number(static_cast<std::uint8_t>(j.m_value.binary->subtype()));
}
else if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint16_t>::max)())
{
write_number(static_cast<std::uint8_t>(0xd9));
write_number(static_cast<std::uint16_t>(j.m_value.binary->subtype()));
}
else if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint32_t>::max)())
{
write_number(static_cast<std::uint8_t>(0xda));
write_number(static_cast<std::uint32_t>(j.m_value.binary->subtype()));
}
else if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint64_t>::max)())
{
write_number(static_cast<std::uint8_t>(0xdb));
write_number(static_cast<std::uint64_t>(j.m_value.binary->subtype()));
}
}
// step 1: write control byte and the binary array size
const auto N = j.m_value.binary->size();
if (N <= 0x17)
{
write_number(static_cast<std::uint8_t>(0x40 + N));
}
else if (N <= (std::numeric_limits<std::uint8_t>::max)())
{
oa->write_character(to_char_type(0x58));
write_number(static_cast<std::uint8_t>(N));
}
else if (N <= (std::numeric_limits<std::uint16_t>::max)())
{
oa->write_character(to_char_type(0x59));
write_number(static_cast<std::uint16_t>(N));
}
else if (N <= (std::numeric_limits<std::uint32_t>::max)())
{
oa->write_character(to_char_type(0x5A));
write_number(static_cast<std::uint32_t>(N));
}
// LCOV_EXCL_START
else if (N <= (std::numeric_limits<std::uint64_t>::max)())
{
oa->write_character(to_char_type(0x5B));
write_number(static_cast<std::uint64_t>(N));
}
// LCOV_EXCL_STOP
// step 2: write each element
oa->write_characters(
reinterpret_cast<const CharType*>(j.m_value.binary->data()),
N);
break;
}
case value_t::object:
{
// step 1: write control byte and the object size
const auto N = j.m_value.object->size();
if (N <= 0x17)
{
write_number(static_cast<std::uint8_t>(0xA0 + N));
}
else if (N <= (std::numeric_limits<std::uint8_t>::max)())
{
oa->write_character(to_char_type(0xB8));
write_number(static_cast<std::uint8_t>(N));
}
else if (N <= (std::numeric_limits<std::uint16_t>::max)())
{
oa->write_character(to_char_type(0xB9));
write_number(static_cast<std::uint16_t>(N));
}
else if (N <= (std::numeric_limits<std::uint32_t>::max)())
{
oa->write_character(to_char_type(0xBA));
write_number(static_cast<std::uint32_t>(N));
}
// LCOV_EXCL_START
else if (N <= (std::numeric_limits<std::uint64_t>::max)())
{
oa->write_character(to_char_type(0xBB));
write_number(static_cast<std::uint64_t>(N));
}
// LCOV_EXCL_STOP
// step 2: write each element
for (const auto& el : *j.m_value.object)
{
write_cbor(el.first);
write_cbor(el.second);
}
break;
}
case value_t::discarded:
default:
break;
}
}
/*!
@param[in] j JSON value to serialize
*/
void write_msgpack(const BasicJsonType& j)
{
switch (j.type())
{
case value_t::null: // nil
{
oa->write_character(to_char_type(0xC0));
break;
}
case value_t::boolean: // true and false
{
oa->write_character(j.m_value.boolean
? to_char_type(0xC3)
: to_char_type(0xC2));
break;
}
case value_t::number_integer:
{
if (j.m_value.number_integer >= 0)
{
// MessagePack does not differentiate between positive
// signed integers and unsigned integers. Therefore, we used
// the code from the value_t::number_unsigned case here.
if (j.m_value.number_unsigned < 128)
{
// positive fixnum
write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
}
else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
{
// uint 8
oa->write_character(to_char_type(0xCC));
write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
}
else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
{
// uint 16
oa->write_character(to_char_type(0xCD));
write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
}
else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
{
// uint 32
oa->write_character(to_char_type(0xCE));
write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
}
else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
{
// uint 64
oa->write_character(to_char_type(0xCF));
write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
}
}
else
{
if (j.m_value.number_integer >= -32)
{
// negative fixnum
write_number(static_cast<std::int8_t>(j.m_value.number_integer));
}
else if (j.m_value.number_integer >= (std::numeric_limits<std::int8_t>::min)() &&
j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
{
// int 8
oa->write_character(to_char_type(0xD0));
write_number(static_cast<std::int8_t>(j.m_value.number_integer));
}
else if (j.m_value.number_integer >= (std::numeric_limits<std::int16_t>::min)() &&
j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
{
// int 16
oa->write_character(to_char_type(0xD1));
write_number(static_cast<std::int16_t>(j.m_value.number_integer));
}
else if (j.m_value.number_integer >= (std::numeric_limits<std::int32_t>::min)() &&
j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
{
// int 32
oa->write_character(to_char_type(0xD2));
write_number(static_cast<std::int32_t>(j.m_value.number_integer));
}
else if (j.m_value.number_integer >= (std::numeric_limits<std::int64_t>::min)() &&
j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
{
// int 64
oa->write_character(to_char_type(0xD3));
write_number(static_cast<std::int64_t>(j.m_value.number_integer));
}
}
break;
}
case value_t::number_unsigned:
{
if (j.m_value.number_unsigned < 128)
{
// positive fixnum
write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
}
else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
{
// uint 8
oa->write_character(to_char_type(0xCC));
write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
}
else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
{
// uint 16
oa->write_character(to_char_type(0xCD));
write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
}
else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
{
// uint 32
oa->write_character(to_char_type(0xCE));
write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
}
else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
{
// uint 64
oa->write_character(to_char_type(0xCF));
write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
}
break;
}
case value_t::number_float:
{
write_compact_float(j.m_value.number_float, detail::input_format_t::msgpack);
break;
}
case value_t::string:
{
// step 1: write control byte and the string length
const auto N = j.m_value.string->size();
if (N <= 31)
{
// fixstr
write_number(static_cast<std::uint8_t>(0xA0 | N));
}
else if (N <= (std::numeric_limits<std::uint8_t>::max)())
{
// str 8
oa->write_character(to_char_type(0xD9));
write_number(static_cast<std::uint8_t>(N));
}
else if (N <= (std::numeric_limits<std::uint16_t>::max)())
{
// str 16
oa->write_character(to_char_type(0xDA));
write_number(static_cast<std::uint16_t>(N));
}
else if (N <= (std::numeric_limits<std::uint32_t>::max)())
{
// str 32
oa->write_character(to_char_type(0xDB));
write_number(static_cast<std::uint32_t>(N));
}
// step 2: write the string
oa->write_characters(
reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
j.m_value.string->size());
break;
}
case value_t::array:
{
// step 1: write control byte and the array size
const auto N = j.m_value.array->size();
if (N <= 15)
{
// fixarray
write_number(static_cast<std::uint8_t>(0x90 | N));
}
else if (N <= (std::numeric_limits<std::uint16_t>::max)())
{
// array 16
oa->write_character(to_char_type(0xDC));
write_number(static_cast<std::uint16_t>(N));
}
else if (N <= (std::numeric_limits<std::uint32_t>::max)())
{
// array 32
oa->write_character(to_char_type(0xDD));
write_number(static_cast<std::uint32_t>(N));
}
// step 2: write each element
for (const auto& el : *j.m_value.array)
{
write_msgpack(el);
}
break;
}
case value_t::binary:
{
// step 0: determine if the binary type has a set subtype to
// determine whether or not to use the ext or fixext types
const bool use_ext = j.m_value.binary->has_subtype();
// step 1: write control byte and the byte string length
const auto N = j.m_value.binary->size();
if (N <= (std::numeric_limits<std::uint8_t>::max)())
{
std::uint8_t output_type{};
bool fixed = true;
if (use_ext)
{
switch (N)
{
case 1:
output_type = 0xD4; // fixext 1
break;
case 2:
output_type = 0xD5; // fixext 2
break;
case 4:
output_type = 0xD6; // fixext 4
break;
case 8:
output_type = 0xD7; // fixext 8
break;
case 16:
output_type = 0xD8; // fixext 16
break;
default:
output_type = 0xC7; // ext 8
fixed = false;
break;
}
}
else
{
output_type = 0xC4; // bin 8
fixed = false;
}
oa->write_character(to_char_type(output_type));
if (!fixed)
{
write_number(static_cast<std::uint8_t>(N));
}
}
else if (N <= (std::numeric_limits<std::uint16_t>::max)())
{
std::uint8_t output_type = use_ext
? 0xC8 // ext 16
: 0xC5; // bin 16
oa->write_character(to_char_type(output_type));
write_number(static_cast<std::uint16_t>(N));
}
else if (N <= (std::numeric_limits<std::uint32_t>::max)())
{
std::uint8_t output_type = use_ext
? 0xC9 // ext 32
: 0xC6; // bin 32
oa->write_character(to_char_type(output_type));
write_number(static_cast<std::uint32_t>(N));
}
// step 1.5: if this is an ext type, write the subtype
if (use_ext)
{
write_number(static_cast<std::int8_t>(j.m_value.binary->subtype()));
}
// step 2: write the byte string
oa->write_characters(
reinterpret_cast<const CharType*>(j.m_value.binary->data()),
N);
break;
}
case value_t::object:
{
// step 1: write control byte and the object size
const auto N = j.m_value.object->size();
if (N <= 15)
{
// fixmap
write_number(static_cast<std::uint8_t>(0x80 | (N & 0xF)));
}
else if (N <= (std::numeric_limits<std::uint16_t>::max)())
{
// map 16
oa->write_character(to_char_type(0xDE));
write_number(static_cast<std::uint16_t>(N));
}
else if (N <= (std::numeric_limits<std::uint32_t>::max)())
{
// map 32
oa->write_character(to_char_type(0xDF));
write_number(static_cast<std::uint32_t>(N));
}
// step 2: write each element
for (const auto& el : *j.m_value.object)
{
write_msgpack(el.first);
write_msgpack(el.second);
}
break;
}
case value_t::discarded:
default:
break;
}
}
/*!
@param[in] j JSON value to serialize
@param[in] use_count whether to use '#' prefixes (optimized format)
@param[in] use_type whether to use '$' prefixes (optimized format)
@param[in] add_prefix whether prefixes need to be used for this value
*/
void write_ubjson(const BasicJsonType& j, const bool use_count,
const bool use_type, const bool add_prefix = true)
{
switch (j.type())
{
case value_t::null:
{
if (add_prefix)
{
oa->write_character(to_char_type('Z'));
}
break;
}
case value_t::boolean:
{
if (add_prefix)
{
oa->write_character(j.m_value.boolean
? to_char_type('T')
: to_char_type('F'));
}
break;
}
case value_t::number_integer:
{
write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
break;
}
case value_t::number_unsigned:
{
write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
break;
}
case value_t::number_float:
{
write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
break;
}
case value_t::string:
{
if (add_prefix)
{
oa->write_character(to_char_type('S'));
}
write_number_with_ubjson_prefix(j.m_value.string->size(), true);
oa->write_characters(
reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
j.m_value.string->size());
break;
}
case value_t::array:
{
if (add_prefix)
{
oa->write_character(to_char_type('['));
}
bool prefix_required = true;
if (use_type && !j.m_value.array->empty())
{
JSON_ASSERT(use_count);
const CharType first_prefix = ubjson_prefix(j.front());
const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
[this, first_prefix](const BasicJsonType & v)
{
return ubjson_prefix(v) == first_prefix;
});
if (same_prefix)
{
prefix_required = false;
oa->write_character(to_char_type('$'));
oa->write_character(first_prefix);
}
}
if (use_count)
{
oa->write_character(to_char_type('#'));
write_number_with_ubjson_prefix(j.m_value.array->size(), true);
}
for (const auto& el : *j.m_value.array)
{
write_ubjson(el, use_count, use_type, prefix_required);
}
if (!use_count)
{
oa->write_character(to_char_type(']'));
}
break;
}
case value_t::binary:
{
if (add_prefix)
{
oa->write_character(to_char_type('['));
}
if (use_type && !j.m_value.binary->empty())
{
JSON_ASSERT(use_count);
oa->write_character(to_char_type('$'));
oa->write_character('U');
}
if (use_count)
{
oa->write_character(to_char_type('#'));
write_number_with_ubjson_prefix(j.m_value.binary->size(), true);
}
if (use_type)
{
oa->write_characters(
reinterpret_cast<const CharType*>(j.m_value.binary->data()),
j.m_value.binary->size());
}
else
{
for (size_t i = 0; i < j.m_value.binary->size(); ++i)
{
oa->write_character(to_char_type('U'));
oa->write_character(j.m_value.binary->data()[i]);
}
}
if (!use_count)
{
oa->write_character(to_char_type(']'));
}
break;
}
case value_t::object:
{
if (add_prefix)
{
oa->write_character(to_char_type('{'));
}
bool prefix_required = true;
if (use_type && !j.m_value.object->empty())
{
JSON_ASSERT(use_count);
const CharType first_prefix = ubjson_prefix(j.front());
const bool same_prefix = std::all_of(j.begin(), j.end(),
[this, first_prefix](const BasicJsonType & v)
{
return ubjson_prefix(v) == first_prefix;
});
if (same_prefix)
{
prefix_required = false;
oa->write_character(to_char_type('$'));
oa->write_character(first_prefix);
}
}
if (use_count)
{
oa->write_character(to_char_type('#'));
write_number_with_ubjson_prefix(j.m_value.object->size(), true);
}
for (const auto& el : *j.m_value.object)
{
write_number_with_ubjson_prefix(el.first.size(), true);
oa->write_characters(
reinterpret_cast<const CharType*>(el.first.c_str()),
el.first.size());
write_ubjson(el.second, use_count, use_type, prefix_required);
}
if (!use_count)
{
oa->write_character(to_char_type('}'));
}
break;
}
case value_t::discarded:
default:
break;
}
}
private:
//////////
// BSON //
//////////
/*!
@return The size of a BSON document entry header, including the id marker
and the entry name size (and its null-terminator).
*/
static std::size_t calc_bson_entry_header_size(const string_t& name, const BasicJsonType& j)
{
const auto it = name.find(static_cast<typename string_t::value_type>(0));
if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos))
{
JSON_THROW(out_of_range::create(409, "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")", j));
static_cast<void>(j);
}
return /*id*/ 1ul + name.size() + /*zero-terminator*/1u;
}
/*!
@brief Writes the given @a element_type and @a name to the output adapter
*/
void write_bson_entry_header(const string_t& name,
const std::uint8_t element_type)
{
oa->write_character(to_char_type(element_type)); // boolean
oa->write_characters(
reinterpret_cast<const CharType*>(name.c_str()),
name.size() + 1u);
}
/*!
@brief Writes a BSON element with key @a name and boolean value @a value
*/
void write_bson_boolean(const string_t& name,
const bool value)
{
write_bson_entry_header(name, 0x08);
oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00));
}
/*!
@brief Writes a BSON element with key @a name and double value @a value
*/
void write_bson_double(const string_t& name,
const double value)
{
write_bson_entry_header(name, 0x01);
write_number<double, true>(value);
}
/*!
@return The size of the BSON-encoded string in @a value
*/
static std::size_t calc_bson_string_size(const string_t& value)
{
return sizeof(std::int32_t) + value.size() + 1ul;
}
/*!
@brief Writes a BSON element with key @a name and string value @a value
*/
void write_bson_string(const string_t& name,
const string_t& value)
{
write_bson_entry_header(name, 0x02);
write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size() + 1ul));
oa->write_characters(
reinterpret_cast<const CharType*>(value.c_str()),
value.size() + 1);
}
/*!
@brief Writes a BSON element with key @a name and null value
*/
void write_bson_null(const string_t& name)
{
write_bson_entry_header(name, 0x0A);
}
/*!
@return The size of the BSON-encoded integer @a value
*/
static std::size_t calc_bson_integer_size(const std::int64_t value)
{
return (std::numeric_limits<std::int32_t>::min)() <= value && value <= (std::numeric_limits<std::int32_t>::max)()
? sizeof(std::int32_t)
: sizeof(std::int64_t);
}
/*!
@brief Writes a BSON element with key @a name and integer @a value
*/
void write_bson_integer(const string_t& name,
const std::int64_t value)
{
if ((std::numeric_limits<std::int32_t>::min)() <= value && value <= (std::numeric_limits<std::int32_t>::max)())
{
write_bson_entry_header(name, 0x10); // int32
write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
}
else
{
write_bson_entry_header(name, 0x12); // int64
write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
}
}
/*!
@return The size of the BSON-encoded unsigned integer in @a j
*/
static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept
{
return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
? sizeof(std::int32_t)
: sizeof(std::int64_t);
}
/*!
@brief Writes a BSON element with key @a name and unsigned @a value
*/
void write_bson_unsigned(const string_t& name,
const BasicJsonType& j)
{
if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
{
write_bson_entry_header(name, 0x10 /* int32 */);
write_number<std::int32_t, true>(static_cast<std::int32_t>(j.m_value.number_unsigned));
}
else if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
{
write_bson_entry_header(name, 0x12 /* int64 */);
write_number<std::int64_t, true>(static_cast<std::int64_t>(j.m_value.number_unsigned));
}
else
{
JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(j.m_value.number_unsigned) + " cannot be represented by BSON as it does not fit int64", j));
}
}
/*!
@brief Writes a BSON element with key @a name and object @a value
*/
void write_bson_object_entry(const string_t& name,
const typename BasicJsonType::object_t& value)
{
write_bson_entry_header(name, 0x03); // object
write_bson_object(value);
}
/*!
@return The size of the BSON-encoded array @a value
*/
static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value)
{
std::size_t array_index = 0ul;
const std::size_t embedded_document_size = std::accumulate(std::begin(value), std::end(value), std::size_t(0), [&array_index](std::size_t result, const typename BasicJsonType::array_t::value_type & el)
{
return result + calc_bson_element_size(std::to_string(array_index++), el);
});
return sizeof(std::int32_t) + embedded_document_size + 1ul;
}
/*!
@return The size of the BSON-encoded binary array @a value
*/
static std::size_t calc_bson_binary_size(const typename BasicJsonType::binary_t& value)
{
return sizeof(std::int32_t) + value.size() + 1ul;
}
/*!
@brief Writes a BSON element with key @a name and array @a value
*/
void write_bson_array(const string_t& name,
const typename BasicJsonType::array_t& value)
{
write_bson_entry_header(name, 0x04); // array
write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_array_size(value)));
std::size_t array_index = 0ul;
for (const auto& el : value)
{
write_bson_element(std::to_string(array_index++), el);
}
oa->write_character(to_char_type(0x00));
}
/*!
@brief Writes a BSON element with key @a name and binary value @a value
*/
void write_bson_binary(const string_t& name,
const binary_t& value)
{
write_bson_entry_header(name, 0x05);
write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size()));
write_number(value.has_subtype() ? static_cast<std::uint8_t>(value.subtype()) : std::uint8_t(0x00));
oa->write_characters(reinterpret_cast<const CharType*>(value.data()), value.size());
}
/*!
@brief Calculates the size necessary to serialize the JSON value @a j with its @a name
@return The calculated size for the BSON document entry for @a j with the given @a name.
*/
static std::size_t calc_bson_element_size(const string_t& name,
const BasicJsonType& j)
{
const auto header_size = calc_bson_entry_header_size(name, j);
switch (j.type())
{
case value_t::object:
return header_size + calc_bson_object_size(*j.m_value.object);
case value_t::array:
return header_size + calc_bson_array_size(*j.m_value.array);
case value_t::binary:
return header_size + calc_bson_binary_size(*j.m_value.binary);
case value_t::boolean:
return header_size + 1ul;
case value_t::number_float:
return header_size + 8ul;
case value_t::number_integer:
return header_size + calc_bson_integer_size(j.m_value.number_integer);
case value_t::number_unsigned:
return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned);
case value_t::string:
return header_size + calc_bson_string_size(*j.m_value.string);
case value_t::null:
return header_size + 0ul;
// LCOV_EXCL_START
case value_t::discarded:
default:
JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert)
return 0ul;
// LCOV_EXCL_STOP
}
}
/*!
@brief Serializes the JSON value @a j to BSON and associates it with the
key @a name.
@param name The name to associate with the JSON entity @a j within the
current BSON document
*/
void write_bson_element(const string_t& name,
const BasicJsonType& j)
{
switch (j.type())
{
case value_t::object:
return write_bson_object_entry(name, *j.m_value.object);
case value_t::array:
return write_bson_array(name, *j.m_value.array);
case value_t::binary:
return write_bson_binary(name, *j.m_value.binary);
case value_t::boolean:
return write_bson_boolean(name, j.m_value.boolean);
case value_t::number_float:
return write_bson_double(name, j.m_value.number_float);
case value_t::number_integer:
return write_bson_integer(name, j.m_value.number_integer);
case value_t::number_unsigned:
return write_bson_unsigned(name, j);
case value_t::string:
return write_bson_string(name, *j.m_value.string);
case value_t::null:
return write_bson_null(name);
// LCOV_EXCL_START
case value_t::discarded:
default:
JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert)
return;
// LCOV_EXCL_STOP
}
}
/*!
@brief Calculates the size of the BSON serialization of the given
JSON-object @a j.
@param[in] value JSON value to serialize
@pre value.type() == value_t::object
*/
static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value)
{
std::size_t document_size = std::accumulate(value.begin(), value.end(), std::size_t(0),
[](size_t result, const typename BasicJsonType::object_t::value_type & el)
{
return result += calc_bson_element_size(el.first, el.second);
});
return sizeof(std::int32_t) + document_size + 1ul;
}
/*!
@param[in] value JSON value to serialize
@pre value.type() == value_t::object
*/
void write_bson_object(const typename BasicJsonType::object_t& value)
{
write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value)));
for (const auto& el : value)
{
write_bson_element(el.first, el.second);
}
oa->write_character(to_char_type(0x00));
}
//////////
// CBOR //
//////////
static constexpr CharType get_cbor_float_prefix(float /*unused*/)
{
return to_char_type(0xFA); // Single-Precision Float
}
static constexpr CharType get_cbor_float_prefix(double /*unused*/)
{
return to_char_type(0xFB); // Double-Precision Float
}
/////////////
// MsgPack //
/////////////
static constexpr CharType get_msgpack_float_prefix(float /*unused*/)
{
return to_char_type(0xCA); // float 32
}
static constexpr CharType get_msgpack_float_prefix(double /*unused*/)
{
return to_char_type(0xCB); // float 64
}
////////////
// UBJSON //
////////////
// UBJSON: write number (floating point)
template<typename NumberType, typename std::enable_if<
std::is_floating_point<NumberType>::value, int>::type = 0>
void write_number_with_ubjson_prefix(const NumberType n,
const bool add_prefix)
{
if (add_prefix)
{
oa->write_character(get_ubjson_float_prefix(n));
}
write_number(n);
}
// UBJSON: write number (unsigned integer)
template<typename NumberType, typename std::enable_if<
std::is_unsigned<NumberType>::value, int>::type = 0>
void write_number_with_ubjson_prefix(const NumberType n,
const bool add_prefix)
{
if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
{
if (add_prefix)
{
oa->write_character(to_char_type('i')); // int8
}
write_number(static_cast<std::uint8_t>(n));
}
else if (n <= (std::numeric_limits<std::uint8_t>::max)())
{
if (add_prefix)
{
oa->write_character(to_char_type('U')); // uint8
}
write_number(static_cast<std::uint8_t>(n));
}
else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
{
if (add_prefix)
{
oa->write_character(to_char_type('I')); // int16
}
write_number(static_cast<std::int16_t>(n));
}
else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
{
if (add_prefix)
{
oa->write_character(to_char_type('l')); // int32
}
write_number(static_cast<std::int32_t>(n));
}
else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
{
if (add_prefix)
{
oa->write_character(to_char_type('L')); // int64
}
write_number(static_cast<std::int64_t>(n));
}
else
{
if (add_prefix)
{
oa->write_character(to_char_type('H')); // high-precision number
}
const auto number = BasicJsonType(n).dump();
write_number_with_ubjson_prefix(number.size(), true);
for (std::size_t i = 0; i < number.size(); ++i)
{
oa->write_character(to_char_type(static_cast<std::uint8_t>(number[i])));
}
}
}
// UBJSON: write number (signed integer)
template < typename NumberType, typename std::enable_if <
std::is_signed<NumberType>::value&&
!std::is_floating_point<NumberType>::value, int >::type = 0 >
void write_number_with_ubjson_prefix(const NumberType n,
const bool add_prefix)
{
if ((std::numeric_limits<std::int8_t>::min)() <= n && n <= (std::numeric_limits<std::int8_t>::max)())
{
if (add_prefix)
{
oa->write_character(to_char_type('i')); // int8
}
write_number(static_cast<std::int8_t>(n));
}
else if (static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::min)()) <= n && n <= static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::max)()))
{
if (add_prefix)
{
oa->write_character(to_char_type('U')); // uint8
}
write_number(static_cast<std::uint8_t>(n));
}
else if ((std::numeric_limits<std::int16_t>::min)() <= n && n <= (std::numeric_limits<std::int16_t>::max)())
{
if (add_prefix)
{
oa->write_character(to_char_type('I')); // int16
}
write_number(static_cast<std::int16_t>(n));
}
else if ((std::numeric_limits<std::int32_t>::min)() <= n && n <= (std::numeric_limits<std::int32_t>::max)())
{
if (add_prefix)
{
oa->write_character(to_char_type('l')); // int32
}
write_number(static_cast<std::int32_t>(n));
}
else if ((std::numeric_limits<std::int64_t>::min)() <= n && n <= (std::numeric_limits<std::int64_t>::max)())
{
if (add_prefix)
{
oa->write_character(to_char_type('L')); // int64
}
write_number(static_cast<std::int64_t>(n));
}
// LCOV_EXCL_START
else
{
if (add_prefix)
{
oa->write_character(to_char_type('H')); // high-precision number
}
const auto number = BasicJsonType(n).dump();
write_number_with_ubjson_prefix(number.size(), true);
for (std::size_t i = 0; i < number.size(); ++i)
{
oa->write_character(to_char_type(static_cast<std::uint8_t>(number[i])));
}
}
// LCOV_EXCL_STOP
}
/*!
@brief determine the type prefix of container values
*/
CharType ubjson_prefix(const BasicJsonType& j) const noexcept
{
switch (j.type())
{
case value_t::null:
return 'Z';
case value_t::boolean:
return j.m_value.boolean ? 'T' : 'F';
case value_t::number_integer:
{
if ((std::numeric_limits<std::int8_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
{
return 'i';
}
if ((std::numeric_limits<std::uint8_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
{
return 'U';
}
if ((std::numeric_limits<std::int16_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
{
return 'I';
}
if ((std::numeric_limits<std::int32_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
{
return 'l';
}
if ((std::numeric_limits<std::int64_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
{
return 'L';
}
// anything else is treated as high-precision number
return 'H'; // LCOV_EXCL_LINE
}
case value_t::number_unsigned:
{
if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
{
return 'i';
}
if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::uint8_t>::max)()))
{
return 'U';
}
if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
{
return 'I';
}
if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
{
return 'l';
}
if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
{
return 'L';
}
// anything else is treated as high-precision number
return 'H'; // LCOV_EXCL_LINE
}
case value_t::number_float:
return get_ubjson_float_prefix(j.m_value.number_float);
case value_t::string:
return 'S';
case value_t::array: // fallthrough
case value_t::binary:
return '[';
case value_t::object:
return '{';
case value_t::discarded:
default: // discarded values
return 'N';
}
}
static constexpr CharType get_ubjson_float_prefix(float /*unused*/)
{
return 'd'; // float 32
}
static constexpr CharType get_ubjson_float_prefix(double /*unused*/)
{
return 'D'; // float 64
}
///////////////////////
// Utility functions //
///////////////////////
/*
@brief write a number to output input
@param[in] n number of type @a NumberType
@tparam NumberType the type of the number
@tparam OutputIsLittleEndian Set to true if output data is
required to be little endian
@note This function needs to respect the system's endianess, because bytes
in CBOR, MessagePack, and UBJSON are stored in network order (big
endian) and therefore need reordering on little endian systems.
*/
template<typename NumberType, bool OutputIsLittleEndian = false>
void write_number(const NumberType n)
{
// step 1: write number to array of length NumberType
std::array<CharType, sizeof(NumberType)> vec{};
std::memcpy(vec.data(), &n, sizeof(NumberType));
// step 2: write array to output (with possible reordering)
if (is_little_endian != OutputIsLittleEndian)
{
// reverse byte order prior to conversion if necessary
std::reverse(vec.begin(), vec.end());
}
oa->write_characters(vec.data(), sizeof(NumberType));
}
void write_compact_float(const number_float_t n, detail::input_format_t format)
{
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
#endif
if (static_cast<double>(n) >= static_cast<double>(std::numeric_limits<float>::lowest()) &&
static_cast<double>(n) <= static_cast<double>((std::numeric_limits<float>::max)()) &&
static_cast<double>(static_cast<float>(n)) == static_cast<double>(n))
{
oa->write_character(format == detail::input_format_t::cbor
? get_cbor_float_prefix(static_cast<float>(n))
: get_msgpack_float_prefix(static_cast<float>(n)));
write_number(static_cast<float>(n));
}
else
{
oa->write_character(format == detail::input_format_t::cbor
? get_cbor_float_prefix(n)
: get_msgpack_float_prefix(n));
write_number(n);
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
}
public:
// The following to_char_type functions are implement the conversion
// between uint8_t and CharType. In case CharType is not unsigned,
// such a conversion is required to allow values greater than 128.
// See <https://github.com/nlohmann/json/issues/1286> for a discussion.
template < typename C = CharType,
enable_if_t < std::is_signed<C>::value && std::is_signed<char>::value > * = nullptr >
static constexpr CharType to_char_type(std::uint8_t x) noexcept
{
return *reinterpret_cast<char*>(&x);
}
template < typename C = CharType,
enable_if_t < std::is_signed<C>::value && std::is_unsigned<char>::value > * = nullptr >
static CharType to_char_type(std::uint8_t x) noexcept
{
static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t");
static_assert(std::is_trivial<CharType>::value, "CharType must be trivial");
CharType result;
std::memcpy(&result, &x, sizeof(x));
return result;
}
template<typename C = CharType,
enable_if_t<std::is_unsigned<C>::value>* = nullptr>
static constexpr CharType to_char_type(std::uint8_t x) noexcept
{
return x;
}
template < typename InputCharType, typename C = CharType,
enable_if_t <
std::is_signed<C>::value &&
std::is_signed<char>::value &&
std::is_same<char, typename std::remove_cv<InputCharType>::type>::value
> * = nullptr >
static constexpr CharType to_char_type(InputCharType x) noexcept
{
return x;
}
private:
/// whether we can assume little endianess
const bool is_little_endian = little_endianess();
/// the output
output_adapter_t<CharType> oa = nullptr;
};
} // namespace detail
} // namespace nlohmann
|
#include <AnalyzerChannelData.h>
#include "SDMMCAnalyzer.h"
#include "SDMMCAnalyzerResults.h"
#include "SDMMCHelpers.h"
SDMMCAnalyzer::SDMMCAnalyzer()
: mSimulationInitialized(false)
{
SetAnalyzerSettings(&mSettings);
}
SDMMCAnalyzer::~SDMMCAnalyzer()
{
KillThread();
}
const char* SDMMCAnalyzer::GetAnalyzerName() const
{
return ::GetAnalyzerName();
}
const char* GetAnalyzerName()
{
return "SDMMC";
}
void SDMMCAnalyzer::WorkerThread()
{
mClock = GetAnalyzerChannelData(mSettings.mClockChannel);
mCommand = GetAnalyzerChannelData(mSettings.mCommandChannel);
mData0 = GetAnalyzerChannelData(mSettings.mDataChannel0);
mData1 = GetAnalyzerChannelData(mSettings.mDataChannel1);
mData2 = GetAnalyzerChannelData(mSettings.mDataChannel2);
mData3 = GetAnalyzerChannelData(mSettings.mDataChannel3);
mData4 = GetAnalyzerChannelData(mSettings.mDataChannel4);
mData5 = GetAnalyzerChannelData(mSettings.mDataChannel5);
mData6 = GetAnalyzerChannelData(mSettings.mDataChannel6);
mData7 = GetAnalyzerChannelData(mSettings.mDataChannel7);
while (true) {
ReportProgress(mClock->GetSampleNumber());
CheckIfThreadShouldExit();
// Skip to next command
AdvanceToNextCommand();
AdvanceToNextClock();
// Frame objects used by state machine functions - can't be created
// there (lifetime)
Frame respFrame;
Frame dataFrame;
// Init CMD & DATA state machines
CommandReadState cmdState = {
CMD_INIT, 0, 0, 0, // CMD counters & state
// RESP counters & state (will be set after CMD has been read)
MMC_RSP_NONE, 0, 0, 0, 0, 0, 0};
DataReadState dataState = {DATA_NOTSTARTED, 0, 0, 0, 0, false};
while (cmdState.phase != CMD_ERROR && dataState.phase != DATA_ERROR &&
cmdState.phase != CMD_INTERRUPT &&
!(cmdState.phase == CMD_END &&
(dataState.phase == DATA_END ||
dataState.phase == DATA_NOTSTARTED))) {
// CMD state machine may start DATA state machine => ref needed
ReadCommandBit(&cmdState, &dataState, &respFrame);
ReadDataBit(&dataState, &dataFrame);
AdvanceToNextClock();
}
mResults->CommitResults();
}
}
bool SDMMCAnalyzer::NeedsRerun()
{
return false;
}
U32 SDMMCAnalyzer::GenerateSimulationData(U64 newest_sample_requested, U32 sample_rate, SimulationChannelDescriptor** simulation_channels)
{
if (!mSimulationInitialized) {
mDataGenerator.Initialize(GetSimulationSampleRate(), &mSettings);
mSimulationInitialized = true;
}
return mDataGenerator.GenerateSimulationData(newest_sample_requested, sample_rate, simulation_channels);
}
U32 SDMMCAnalyzer::GetMinimumSampleRateHz()
{
return 400000 * 4;
}
void SDMMCAnalyzer::SetupResults()
{
mResults.reset(new SDMMCAnalyzerResults(this, &mSettings));
SetAnalyzerResults(mResults.get());
// set which channels will carry bubbles
mResults->AddChannelBubblesWillAppearOn(mSettings.mCommandChannel);
if (mSettings.mBusWidth != BUS_WIDTH_0)
mResults->AddChannelBubblesWillAppearOn(mSettings.mDataChannel0);
}
void SDMMCAnalyzer::AdvanceToNextClock()
{
enum BitState search = mSettings.mSampleEdge == SAMPLE_EDGE_RISING ? BIT_HIGH : BIT_LOW;
do {
mClock->AdvanceToNextEdge();
} while (mClock->GetBitState() != search);
mCommand->AdvanceToAbsPosition(mClock->GetSampleNumber());
if (mSettings.mBusWidth != BUS_WIDTH_0)
mData0->AdvanceToAbsPosition(mClock->GetSampleNumber());
if (mSettings.mBusWidth == BUS_WIDTH_4 ||
mSettings.mBusWidth == BUS_WIDTH_8) {
mData1->AdvanceToAbsPosition(mClock->GetSampleNumber());
mData2->AdvanceToAbsPosition(mClock->GetSampleNumber());
mData3->AdvanceToAbsPosition(mClock->GetSampleNumber());
}
if (mSettings.mBusWidth == BUS_WIDTH_8) {
mData4->AdvanceToAbsPosition(mClock->GetSampleNumber());
mData5->AdvanceToAbsPosition(mClock->GetSampleNumber());
mData6->AdvanceToAbsPosition(mClock->GetSampleNumber());
mData7->AdvanceToAbsPosition(mClock->GetSampleNumber());
}
}
void SDMMCAnalyzer::AdvanceToNextCommand() {
mCommand->AdvanceToNextEdge();
mClock->AdvanceToAbsPosition(mCommand->GetSampleNumber());
if (mSettings.mBusWidth != BUS_WIDTH_0)
mData0->AdvanceToAbsPosition(mCommand->GetSampleNumber());
if (mSettings.mBusWidth == BUS_WIDTH_4 ||
mSettings.mBusWidth == BUS_WIDTH_8) {
mData1->AdvanceToAbsPosition(mCommand->GetSampleNumber());
mData2->AdvanceToAbsPosition(mCommand->GetSampleNumber());
mData3->AdvanceToAbsPosition(mCommand->GetSampleNumber());
}
if (mSettings.mBusWidth == BUS_WIDTH_8) {
mData4->AdvanceToAbsPosition(mCommand->GetSampleNumber());
mData5->AdvanceToAbsPosition(mCommand->GetSampleNumber());
mData6->AdvanceToAbsPosition(mCommand->GetSampleNumber());
mData7->AdvanceToAbsPosition(mCommand->GetSampleNumber());
}
return;
}
void SDMMCAnalyzer::ReadCommandBit(CommandReadState *state, DataReadState
*dataState, struct Frame *frame) {
switch(state->phase) {
case CMD_INIT:
if (mCommand->GetBitState() == BIT_LOW) {
mResults->AddMarker(mClock->GetSampleNumber(),
AnalyzerResults::Start, mSettings.mCommandChannel);
state->phase = CMD_DIR;
}
return;
case CMD_DIR:
if (mCommand->GetBitState() != BIT_HIGH) {
mResults->AddMarker(mClock->GetSampleNumber(),
AnalyzerResults::X, mSettings.mCommandChannel);
state->phase = CMD_ERROR;
} else {
state->phase = CMD_IDX;
}
return;
case CMD_IDX:
if (state->cmd_idx_cnt == 0) {
frame->mStartingSampleInclusive = mClock->GetSampleNumber();
frame->mData1 = 0;
frame->mData2 = 0;
frame->mType = SDMMCAnalyzerResults::FRAMETYPE_COMMAND;
frame->mFlags = 0;
}
frame->mData1 = (frame->mData1 << 1) | mCommand->GetBitState();
if (state->cmd_idx_cnt == 5)
state->phase = CMD_ARG;
state->cmd_idx_cnt++;
return;
case CMD_ARG:
frame->mData2 = (frame->mData2 << 1) | mCommand->GetBitState();
if (state->cmd_arg_cnt == 31) {
state->phase = CMD_CRC;
frame->mEndingSampleInclusive = mClock->GetSampleNumber();
mResults->AddFrame(*frame);
mResults->CommitResults();
state->cmdindex = (int)frame->mData1;
dataState->cmdindex = (int)frame->mData1;
}
state->cmd_arg_cnt++;
return;
case CMD_CRC:
if (state->cmd_crc_cnt == 0) {
frame->mStartingSampleInclusive = mClock->GetSampleNumber();
frame->mData1 = 0;
frame->mData2 = 0;
frame->mType = SDMMCAnalyzerResults::FRAMETYPE_CRC;
frame->mFlags = 0;
}
frame->mData1 = (frame->mData1 << 1) | mCommand->GetBitState();
if (state->cmd_crc_cnt == 6) {
state->phase = CMD_STOP;
frame->mEndingSampleInclusive = mClock->GetSampleNumber();
mResults->AddFrame(*frame);
mResults->CommitResults();
}
state->cmd_crc_cnt++;
return;
case CMD_STOP:
mResults->AddMarker(mClock->GetSampleNumber(),
AnalyzerResults::Stop, mSettings.mCommandChannel);
if (mSettings.mProtocol == PROTOCOL_MMC) {
struct MMCResponse response = SDMMCHelpers::MMCCommandResponse(state->cmdindex);
if (response.mType != MMC_RSP_NONE) {
state->phase = RESP_INIT;
// prepare RESP parsing
state->timeout = response.mTimeout + 3; // add some slack time
state->resp_data_bits = response.mBits;
state->responseType = response.mType;
if (response.hasDataBlock &&
mSettings.mBusWidth != BUS_WIDTH_0) {
// init DATA state machine
dataState->phase = DATA_INIT;
dataState->hasSeveralDataBlocks = response.hasSeveralDataBlocks;
}
} else {
state->phase = CMD_END;
}
} else {
/* FIXME: implement SD response handling */
state->phase = CMD_END;
}
return;
case RESP_INIT:
if (mCommand->GetBitState() != BIT_LOW) {
// Waiting for init
if (state->timeout == 0) {
state->phase = CMD_ERROR;
mResults->AddMarker(mClock->GetSampleNumber(),
AnalyzerResults::X, mSettings.mCommandChannel);
} else {
state->timeout--;
}
} else {
mResults->AddMarker(mClock->GetSampleNumber(),
AnalyzerResults::Start, mSettings.mCommandChannel);
state->phase = RESP_DIR;
}
return;
case RESP_DIR:
if (mCommand->GetBitState() != BIT_LOW) {
/* if card is not transferring this is no response */
mResults->AddMarker(mClock->GetSampleNumber(),
AnalyzerResults::X, mSettings.mCommandChannel);
state->phase = CMD_ERROR;
} else {
state->phase = RESP_IGNORED;
}
return;
case RESP_IGNORED:
if (state->resp_ignore_cnt == 0) {
frame->mStartingSampleInclusive = mClock->GetSampleNumber();
frame->mData1 = 0;
frame->mData2 = 0;
frame->mType = SDMMCAnalyzerResults::FRAMETYPE_RESPONSE;
frame->mFlags = state->responseType;
}
if (state->resp_ignore_cnt == 5)
state->phase = RESP_DATA;
state->resp_ignore_cnt++;
return;
case RESP_DATA:
if (state->resp_data_cnt < 64) {
frame->mData1 = (frame->mData1 << 1) | mCommand->GetBitState();
/* bits 0 to 63 */
} else {
frame->mData2 = (frame->mData2 << 1) | mCommand->GetBitState();
/* bits 64 to 127 */
}
/* last data bit only */
if (state->resp_data_cnt == state->resp_data_bits) {
// observed: no data block following CMD8 R1 response,
// EXCEPTION_EVENT bit (6), RESERVED (4) and APP-specific (2)
// bits set - why?
if (state->responseType == MMC_RSP_R1 &&
((frame->mData1 & (1 << 6)) != 0)) {
dataState->phase = DATA_NOTSTARTED;
}
frame->mEndingSampleInclusive = mClock->GetSampleNumber();
mResults->AddFrame(*frame);
mResults->CommitResults();
if (state->responseType != MMC_RSP_R2_CID &&
state->responseType != MMC_RSP_R2_CSD) {
state->phase = RESP_CRC;
state->resp_crc_cnt = 0;
} else {
state->phase = RESP_STOP;
}
}
state->resp_data_cnt++;
return;
case RESP_CRC:
/* first crc bit only */
if (state->resp_crc_cnt == 0) {
frame->mStartingSampleInclusive = mClock->GetSampleNumber();
frame->mData1 = 0;
frame->mData2 = 0;
frame->mType = SDMMCAnalyzerResults::FRAMETYPE_CRC;
}
frame->mData1 = (frame->mData1 << 1) | mCommand->GetBitState();
/* last crc bit only */
if (state->resp_crc_cnt == 6) {
frame->mEndingSampleInclusive = mClock->GetSampleNumber();
mResults->AddFrame(*frame);
mResults->CommitResults();
ReportProgress(frame->mEndingSampleInclusive);
state->phase = RESP_STOP;
}
state->resp_crc_cnt++;
return;
case RESP_STOP:
/* stop bit */
mResults->AddMarker(mClock->GetSampleNumber(), AnalyzerResults::Stop, mSettings.mCommandChannel);
if (state->cmdindex == 12) { // STOP_TRANSMISSION
state->phase = CMD_INTERRUPT;
return;
}
if (dataState->hasSeveralDataBlocks) {
// READ MULTIPLE BLOCK / WRITE MULTIPLE BLOCK: wait for another
// command while data is being transmitted
state->phase = CMD_INIT;
// Reset state
state->cmd_idx_cnt = 0;
state->cmd_arg_cnt = 0;
state->cmd_crc_cnt = 0;
state->responseType = MMC_RSP_NONE;
state->timeout = 0;
state->cmdindex = 0;
state->resp_data_bits = 0;
state->resp_ignore_cnt = 0;
state->resp_data_cnt = 0;
} else {
state->phase = CMD_END;
}
return;
/* this method does not gets called for END and ERROR phases */
case CMD_ERROR:
case CMD_END:
return;
}
}
void SDMMCAnalyzer::ReadDataBit(DataReadState *state, struct Frame *frame) {
switch(state->phase) {
case DATA_INIT:
if (mData0->GetBitState() == BIT_LOW) {
/* other data lines must be at 0, too
* (depending on bus width (?)) */
if ( /* BusWidth=4 or 8 */
mSettings.mBusWidth != BUS_WIDTH_1 &&
(mData1->GetBitState() != BIT_LOW ||
mData2->GetBitState() != BIT_LOW ||
mData3->GetBitState() != BIT_LOW) ||
/* BusWidth=8 */
mSettings.mBusWidth == BUS_WIDTH_8 &&
(mData4->GetBitState() != BIT_LOW ||
mData5->GetBitState() != BIT_LOW ||
mData6->GetBitState() != BIT_LOW ||
mData7->GetBitState() != BIT_LOW)) {
mResults->AddMarker(mClock->GetSampleNumber(),
AnalyzerResults::X, mSettings.mDataChannel0);
state->phase = DATA_ERROR;
} else {
mResults->AddMarker(mClock->GetSampleNumber(),
AnalyzerResults::Start, mSettings.mDataChannel0);
state->phase = DATA_DATA;
}
}
return;
case DATA_DATA:
/* Start frames if necessary*/
if (mSettings.mBusWidth == BUS_WIDTH_8 ||
(mSettings.mBusWidth == BUS_WIDTH_4 && state->data_cnt % 2 == 0) ||
(mSettings.mBusWidth == BUS_WIDTH_1 && state->data_cnt % 8 == 0)) {
frame->mType = SDMMCAnalyzerResults::FRAMETYPE_DATA_CONTENTS;
frame->mStartingSampleInclusive = mClock->GetSampleNumber();
frame->mData1 = 0;
frame->mData2 = 0;
frame->mFlags = 0;
}
/* Store data */
if (mSettings.mBusWidth == BUS_WIDTH_8) {
frame->mData1 = (frame->mData1 << 1) | mData7->GetBitState();
frame->mData1 = (frame->mData1 << 1) | mData6->GetBitState();
frame->mData1 = (frame->mData1 << 1) | mData5->GetBitState();
frame->mData1 = (frame->mData1 << 1) | mData4->GetBitState();
}
if (mSettings.mBusWidth == BUS_WIDTH_8 ||
mSettings.mBusWidth == BUS_WIDTH_4) {
frame->mData1 = (frame->mData1 << 1) | mData3->GetBitState();
frame->mData1 = (frame->mData1 << 1) | mData2->GetBitState();
frame->mData1 = (frame->mData1 << 1) | mData1->GetBitState();
}
frame->mData1 = (frame->mData1 << 1) | mData0->GetBitState();
/* Commit results if necessary */
if (mSettings.mBusWidth == BUS_WIDTH_8 ||
(mSettings.mBusWidth == BUS_WIDTH_4 && state->data_cnt % 2 == 1) ||
(mSettings.mBusWidth == BUS_WIDTH_1 && state->data_cnt % 8 == 7)
) {
frame->mEndingSampleInclusive = mClock->GetSampleNumber();
mResults->AddFrame(*frame);
mResults->CommitResults();
}
/* last data bit only - change state */
if (state->data_cnt == 1023) {
/* FIXME do not used fixed block width */
state->phase = DATA_CRC;
}
state->data_cnt++;
return;
case DATA_CRC:
if (state->crc_cnt == 0) {
frame->mType = SDMMCAnalyzerResults::FRAMETYPE_DATA_CRC;
frame->mStartingSampleInclusive = mClock->GetSampleNumber();
frame->mData1 = 0;
frame->mData2 = 0;
frame->mFlags = 0;
}
frame->mData1 <<= 1;
frame->mData1 |= (mData0->GetBitState());
if (mSettings.mBusWidth != BUS_WIDTH_1) { /* BusWidth=4 or 8 */
frame->mData1 |= (mData1->GetBitState() << 16);
frame->mData1 |= (mData2->GetBitState() << 32);
frame->mData1 |= (mData3->GetBitState() << 48);
}
if (mSettings.mBusWidth == BUS_WIDTH_8) { /* BusWidth=8 */
frame->mData2 |= (mData4->GetBitState() << 16);
frame->mData2 |= (mData5->GetBitState() << 16);
frame->mData2 |= (mData6->GetBitState() << 32);
frame->mData2 |= (mData7->GetBitState() << 48);
}
if (state->crc_cnt == 15) {
frame->mEndingSampleInclusive = mClock->GetSampleNumber();
mResults->AddFrame(*frame);
mResults->CommitResults();
state->phase = DATA_STOP;
}
state->crc_cnt++;
return;
case DATA_STOP:
if ( /* BusWidth=4 or 8 */
mSettings.mBusWidth != BUS_WIDTH_1 &&
(mData0->GetBitState() == BIT_LOW ||
mData1->GetBitState() == BIT_LOW ||
mData2->GetBitState() == BIT_LOW ||
mData3->GetBitState() == BIT_LOW) ||
/* BusWidth=8 */
mSettings.mBusWidth == BUS_WIDTH_8 &&
(mData4->GetBitState() == BIT_LOW ||
mData5->GetBitState() == BIT_LOW ||
mData6->GetBitState() == BIT_LOW ||
mData7->GetBitState() == BIT_LOW)) {
mResults->AddMarker(mClock->GetSampleNumber(),
AnalyzerResults::X, mSettings.mDataChannel0);
state->phase = DATA_ERROR;
} else {
mResults->AddMarker(mClock->GetSampleNumber(),
AnalyzerResults::Stop, mSettings.mDataChannel0);
if (state->cmdindex == 24 || state->cmdindex == 25) {
// Write commands
state->phase = DATA_CHECKCRC_INIT;
} else {
if (state->hasSeveralDataBlocks) {
// FIXME take CMD23 (SET BLOCK COUNT) into account, stop if
// necessary
state->data_cnt = 0;
state->crc_cnt = 0;
state->checkcrc_cnt = 0;
state->phase = DATA_INIT;
} else {
state->phase = DATA_END;
}
}
}
case DATA_CHECKCRC_INIT:
if (mData0->GetBitState() == BIT_LOW) {
state->phase = DATA_CHECKCRC_CRC;
mResults->AddMarker(mClock->GetSampleNumber(),
AnalyzerResults::Start, mSettings.mDataChannel0);
}
return;
case DATA_CHECKCRC_CRC:
// 010 -> OK; 101 -> NOK
if (state->checkcrc_cnt == 0) {
frame->mStartingSampleInclusive = mClock->GetSampleNumber();
frame->mData1 = 0;
frame->mData2 = 0;
frame->mType = SDMMCAnalyzerResults::FRAMETYPE_DATA_CRC_CHECK;
}
frame->mData1 = (frame->mData1 << 1) | mData0->GetBitState();
if (state->checkcrc_cnt == 2) {
state->phase = DATA_CHECKCRC_STOP;
frame->mEndingSampleInclusive = mClock->GetSampleNumber();
mResults->AddFrame(*frame);
mResults->CommitResults();
ReportProgress(frame->mEndingSampleInclusive);
}
state->checkcrc_cnt++;
return;
case DATA_CHECKCRC_STOP:
mResults->AddMarker(mClock->GetSampleNumber(),
AnalyzerResults::Stop, mSettings.mDataChannel0);
state->phase = DATA_BUSY;
return;
case DATA_BUSY:
if (mData0->GetBitState() == BIT_HIGH) {
state->phase = DATA_BUSY_END;
}
return;
case DATA_BUSY_END:
if (state->hasSeveralDataBlocks) {
state->phase = DATA_INIT;
} else {
state->phase = DATA_END;
}
return;
/* this method does not gets called for NOTSTARTED, END and ERROR
* phases */
case DATA_NOTSTARTED:
case DATA_ERROR:
case DATA_END:
return;
}
}
/*
* loader hooks
*/
Analyzer* CreateAnalyzer()
{
return new SDMMCAnalyzer();
}
void DestroyAnalyzer(Analyzer* analyzer)
{
delete analyzer;
}
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/sms/webotp_service.h"
#include <string>
#include "base/android/jni_string.h"
#include "base/android/scoped_java_ref.h"
#include "base/test/scoped_feature_list.h"
#include "content/browser/sms/sms_provider.h"
#include "content/browser/sms/sms_provider_gms.h"
#include "content/public/browser/sms_fetcher.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/test_renderer_host.h"
#include "content/test/content_unittests_jni_headers/SmsProviderFakes_jni.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/android/window_android.h"
using base::android::AttachCurrentThread;
using ::testing::_;
using ::testing::InvokeWithoutArgs;
using ::testing::Mock;
using ::testing::NiceMock;
using url::Origin;
namespace content {
namespace {
class MockObserver : public SmsProvider::Observer {
public:
MockObserver() = default;
~MockObserver() override = default;
MOCK_METHOD3(OnReceive,
bool(const OriginList&,
const std::string& one_time_code,
SmsFetcher::UserConsent));
MOCK_METHOD1(OnFailure, bool(SmsFetcher::FailureType));
private:
DISALLOW_COPY_AND_ASSIGN(MockObserver);
};
// SmsProviderGmsBaseTest tests the JNI bindings to the android provider, the
// handling of the SMS upon retrieval, and various failure scenarios.
// It creates and injects a fake sms retriver client to trigger various actions
// for testing purposes.
class SmsProviderGmsBaseTest : public RenderViewHostTestHarness {
protected:
SmsProviderGmsBaseTest() = default;
virtual ~SmsProviderGmsBaseTest() override = default;
void SetUp() {
RenderViewHostTestHarness::SetUp();
base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kWebOtpBackend, GetSwitch());
test_window_ = ui::WindowAndroid::CreateForTesting();
provider_ = std::make_unique<SmsProviderGms>();
j_fake_sms_retriever_client_.Reset(
Java_FakeSmsRetrieverClient_create(AttachCurrentThread()));
provider_->SetClientAndWindowForTesting(j_fake_sms_retriever_client_,
test_window_->GetJavaObject());
provider_->AddObserver(&observer_);
}
void TearDown() {
RenderViewHostTestHarness::TearDown();
test_window_->Destroy(nullptr, nullptr);
}
void TriggerSms(const std::string& sms) {
if (GetSwitch() == switches::kWebOtpBackendUserConsent) {
TriggerSmsForUserConsent(sms);
} else {
TriggerSmsForVerification(sms);
}
}
void TriggerSmsForUserConsent(const std::string& sms) {
JNIEnv* env = base::android::AttachCurrentThread();
Java_FakeSmsRetrieverClient_triggerUserConsentSms(
env, j_fake_sms_retriever_client_,
base::android::ConvertUTF8ToJavaString(env, sms));
}
void TriggerSmsForVerification(const std::string& sms) {
JNIEnv* env = base::android::AttachCurrentThread();
Java_FakeSmsRetrieverClient_triggerVerificationSms(
env, j_fake_sms_retriever_client_,
base::android::ConvertUTF8ToJavaString(env, sms));
}
void TriggerTimeout() {
JNIEnv* env = base::android::AttachCurrentThread();
if (GetSwitch() == switches::kWebOtpBackendUserConsent) {
Java_FakeSmsRetrieverClient_triggerUserConsentTimeout(
env, j_fake_sms_retriever_client_);
} else {
Java_FakeSmsRetrieverClient_triggerVerificationTimeout(
env, j_fake_sms_retriever_client_);
}
}
void TriggerUserDeniesPermission() {
JNIEnv* env = base::android::AttachCurrentThread();
Java_FakeSmsRetrieverClient_triggerUserDeniesPermission(
env, j_fake_sms_retriever_client_, test_window_->GetJavaObject());
}
void TriggerUserGrantsPermission() {
JNIEnv* env = base::android::AttachCurrentThread();
Java_FakeSmsRetrieverClient_triggerUserGrantsPermission(
env, j_fake_sms_retriever_client_, test_window_->GetJavaObject());
}
void TriggerAPIFailure(const std::string& failure_type) {
JNIEnv* env = base::android::AttachCurrentThread();
Java_FakeSmsRetrieverClient_triggerFailure(
env, j_fake_sms_retriever_client_,
base::android::ConvertUTF8ToJavaString(env, failure_type));
}
SmsProviderGms* provider() { return provider_.get(); }
NiceMock<MockObserver>* observer() { return &observer_; }
virtual std::string GetSwitch() const = 0;
private:
std::unique_ptr<SmsProviderGms> provider_;
NiceMock<MockObserver> observer_;
base::android::ScopedJavaGlobalRef<jobject> j_fake_sms_retriever_client_;
base::test::ScopedFeatureList feature_list_;
ui::WindowAndroid* test_window_;
DISALLOW_COPY_AND_ASSIGN(SmsProviderGmsBaseTest);
};
class SmsProviderGmsTest : public ::testing::WithParamInterface<std::string>,
public SmsProviderGmsBaseTest {
std::string GetSwitch() const override { return GetParam(); }
};
// Fixture to be used with tests that are only applicable to the auto backend.
class SmsProviderGmsAutoTest : public SmsProviderGmsBaseTest {
std::string GetSwitch() const override {
return switches::kWebOtpBackendAuto;
}
};
// Fixture to be used with tests that are only applicable to the verification
// backend.
class SmsProviderGmsVerificationTest : public SmsProviderGmsBaseTest {
std::string GetSwitch() const override {
return switches::kWebOtpBackendSmsVerification;
}
};
} // namespace
TEST_P(SmsProviderGmsTest, Retrieve) {
std::string test_url = "https://google.com";
EXPECT_CALL(*observer(), OnReceive(OriginList{Origin::Create(GURL(test_url))},
"ABC123", _));
provider()->Retrieve(main_rfh());
TriggerSms("Hi\n@google.com #ABC123");
}
TEST_P(SmsProviderGmsTest, IgnoreBadSms) {
std::string test_url = "https://google.com";
std::string good_sms = "Hi\n@google.com #ABC123";
std::string bad_sms = "Hi\n@b.com";
EXPECT_CALL(*observer(), OnReceive(OriginList{Origin::Create(GURL(test_url))},
"ABC123", _));
provider()->Retrieve(main_rfh());
TriggerSms(bad_sms);
TriggerSms(good_sms);
}
TEST_P(SmsProviderGmsTest, TaskTimedOut) {
EXPECT_CALL(*observer(), OnReceive(_, _, _)).Times(0);
provider()->Retrieve(main_rfh());
TriggerTimeout();
}
TEST_P(SmsProviderGmsTest, OneObserverTwoTasks) {
std::string test_url = "https://google.com";
EXPECT_CALL(*observer(), OnReceive(OriginList{Origin::Create(GURL(test_url))},
"ABC123", _));
// Two tasks for when 1 request gets aborted but the task is still triggered.
provider()->Retrieve(main_rfh());
provider()->Retrieve(main_rfh());
// First timeout should be ignored.
TriggerTimeout();
TriggerSms("Hi\n@google.com #ABC123");
}
// For common tests, instantiate the parametric tests three times:
// with user consent backend, with verification backend, and with auto.
INSTANTIATE_TEST_SUITE_P(
AllBackends,
SmsProviderGmsTest,
testing::Values(switches::kWebOtpBackendAuto,
switches::kWebOtpBackendSmsVerification,
switches::kWebOtpBackendUserConsent));
// These tests are only valid with auto backend.
TEST_F(SmsProviderGmsAutoTest, OneTimePermissionDeniedByUser) {
EXPECT_CALL(*observer(), OnFailure(_)).Times(1);
provider()->Retrieve(main_rfh());
TriggerUserDeniesPermission();
}
TEST_F(SmsProviderGmsAutoTest, OneTimePermissionGrantedByUser) {
std::string test_url = "https://example.com";
EXPECT_CALL(*observer(), OnFailure(_)).Times(0);
EXPECT_CALL(*observer(), OnReceive(OriginList{Origin::Create(GURL(test_url))},
"ABC123", _));
provider()->Retrieve(main_rfh());
TriggerUserGrantsPermission();
TriggerSms("@example.com #ABC123 $50");
}
TEST_F(SmsProviderGmsAutoTest, OneTimePermissionNotGranted) {
EXPECT_CALL(*observer(), OnFailure(_)).Times(1);
provider()->Retrieve(main_rfh());
TriggerAPIFailure("USER_PERMISSION_REQUIRED");
}
TEST_F(SmsProviderGmsAutoTest, ExpectedFailuresShouldFallback) {
// These failures should not cancel the retrieve but should cause us to
// fallback to the user consensus method.
std::string test_url = "https://example.com";
std::string good_sms = "Hi\n@example.com #ABC123";
{
EXPECT_CALL(*observer(), OnFailure(_)).Times(0);
EXPECT_CALL(
*observer(),
OnReceive(OriginList{Origin::Create(GURL(test_url))}, "ABC123", _));
TriggerAPIFailure("API_NOT_CONNECTED");
TriggerSmsForUserConsent("Hi\n@example.com #ABC123");
Mock::VerifyAndClearExpectations(observer());
}
{
EXPECT_CALL(*observer(), OnFailure(_)).Times(0);
EXPECT_CALL(
*observer(),
OnReceive(OriginList{Origin::Create(GURL(test_url))}, "ABC123", _));
provider()->Retrieve(main_rfh());
TriggerAPIFailure("PLATFORM_NOT_SUPPORTED");
TriggerSmsForUserConsent("Hi\n@example.com #ABC123");
Mock::VerifyAndClearExpectations(observer());
}
{
EXPECT_CALL(*observer(), OnFailure(_)).Times(0);
EXPECT_CALL(
*observer(),
OnReceive(OriginList{Origin::Create(GURL(test_url))}, "ABC123", _));
provider()->Retrieve(main_rfh());
TriggerAPIFailure("API_NOT_AVAILABLE");
TriggerSmsForUserConsent("Hi\n@example.com #ABC123");
Mock::VerifyAndClearExpectations(observer());
}
}
// These tests are only valid with verification backend.
TEST_F(SmsProviderGmsVerificationTest, ExpectedFailuresShouldCancel) {
{
EXPECT_CALL(*observer(),
OnFailure(SmsFetcher::FailureType::kBackendNotAvailable))
.Times(1);
provider()->Retrieve(main_rfh());
TriggerAPIFailure("API_NOT_CONNECTED");
Mock::VerifyAndClearExpectations(observer());
}
{
EXPECT_CALL(*observer(),
OnFailure(SmsFetcher::FailureType::kBackendNotAvailable))
.Times(1);
provider()->Retrieve(main_rfh());
TriggerAPIFailure("PLATFORM_NOT_SUPPORTED");
Mock::VerifyAndClearExpectations(observer());
}
{
EXPECT_CALL(*observer(),
OnFailure(SmsFetcher::FailureType::kBackendNotAvailable))
.Times(1);
provider()->Retrieve(main_rfh());
TriggerAPIFailure("API_NOT_AVAILABLE");
Mock::VerifyAndClearExpectations(observer());
}
}
} // namespace content
|
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/Scripting/Natives/Generated/game/data/TweakDBRecord.hpp>
namespace RED4ext
{
namespace game::data {
struct LifePath_Record : game::data::TweakDBRecord
{
static constexpr const char* NAME = "gamedataLifePath_Record";
static constexpr const char* ALIAS = "LifePath_Record";
uint8_t unk48[0x60 - 0x48]; // 48
};
RED4EXT_ASSERT_SIZE(LifePath_Record, 0x60);
} // namespace game::data
using LifePath_Record = game::data::LifePath_Record;
} // namespace RED4ext
|
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
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 "renderer/CCTextureCache.h"
#include <errno.h>
#include <stack>
#include <cctype>
#include <list>
#include "renderer/CCTexture2D.h"
#include "base/ccMacros.h"
#include "base/ccUTF8.h"
#include "base/CCDirector.h"
#include "base/CCScheduler.h"
#include "platform/CCFileUtils.h"
#include "base/ccUtils.h"
#include "base/CCNinePatchImageParser.h"
using namespace std;
NS_CC_BEGIN
std::string TextureCache::s_etc1AlphaFileSuffix = "@alpha";
// implementation TextureCache
void TextureCache::setETC1AlphaFileSuffix(const std::string& suffix)
{
s_etc1AlphaFileSuffix = suffix;
}
TextureCache * TextureCache::getInstance()
{
return Director::getInstance()->getTextureCache();
}
TextureCache::TextureCache()
: _loadingThread(nullptr)
, _needQuit(false)
, _asyncRefCount(0)
{
}
TextureCache::~TextureCache()
{
CCLOGINFO("deallocing TextureCache: %p", this);
for (auto& texture : _textures)
texture.second->release();
CC_SAFE_DELETE(_loadingThread);
}
void TextureCache::destroyInstance()
{
}
TextureCache * TextureCache::sharedTextureCache()
{
return Director::getInstance()->getTextureCache();
}
void TextureCache::purgeSharedTextureCache()
{
}
std::string TextureCache::getDescription() const
{
return StringUtils::format("<TextureCache | Number of textures = %d>", static_cast<int>(_textures.size()));
}
struct TextureCache::AsyncStruct
{
public:
AsyncStruct(const std::string& fn,const std::function<void(Texture2D*)>& f) : filename(fn), callback(f), pixelFormat(Texture2D::getDefaultAlphaPixelFormat()), loadSuccess(false) {}
std::string filename;
std::function<void(Texture2D*)> callback;
Image image;
Image imageAlpha;
Texture2D::PixelFormat pixelFormat;
bool loadSuccess;
};
/**
The addImageAsync logic follow the steps:
- find the image has been add or not, if not add an AsyncStruct to _requestQueue (GL thread)
- get AsyncStruct from _requestQueue, load res and fill image data to AsyncStruct.image, then add AsyncStruct to _responseQueue (Load thread)
- on schedule callback, get AsyncStruct from _responseQueue, convert image to texture, then delete AsyncStruct (GL thread)
the Critical Area include these members:
- _requestQueue: locked by _requestMutex
- _responseQueue: locked by _responseMutex
the object's life time:
- AsyncStruct: construct and destruct in GL thread
- image data: new in Load thread, delete in GL thread(by Image instance)
Note:
- all AsyncStruct referenced in _asyncStructQueue, for unbind function use.
How to deal add image many times?
- At first, this situation is abnormal, we only ensure the logic is correct.
- If the image has been loaded, the after load image call will return immediately.
- If the image request is in queue already, there will be more than one request in queue,
- In addImageAsyncCallback, will deduplicate the request to ensure only create one texture.
Does process all response in addImageAsyncCallback consume more time?
- Convert image to texture faster than load image from disk, so this isn't a problem.
*/
void TextureCache::addImageAsync(const std::string &path, const std::function<void(Texture2D*)>& callback)
{
Texture2D *texture = nullptr;
std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path);
auto it = _textures.find(fullpath);
if (it != _textures.end())
texture = it->second;
if (texture != nullptr)
{
if (callback) callback(texture);
return;
}
// check if file exists
if (fullpath.empty() || !FileUtils::getInstance()->isFileExist(fullpath)) {
if (callback) callback(nullptr);
return;
}
// lazy init
if (_loadingThread == nullptr)
{
// create a new thread to load images
_loadingThread = new (std::nothrow) std::thread(&TextureCache::loadImage, this);
_needQuit = false;
}
if (0 == _asyncRefCount)
{
Director::getInstance()->getScheduler()->schedule(CC_SCHEDULE_SELECTOR(TextureCache::addImageAsyncCallBack), this, 0, false);
}
++_asyncRefCount;
// generate async struct
AsyncStruct *data = new (std::nothrow) AsyncStruct(fullpath, callback);
// add async struct into queue
_asyncStructQueue.push_back(data);
_requestMutex.lock();
_requestQueue.push_back(data);
_requestMutex.unlock();
_sleepCondition.notify_one();
}
void TextureCache::unbindImageAsync(const std::string& filename)
{
if (_asyncStructQueue.empty())
{
return;
}
std::string fullpath = FileUtils::getInstance()->fullPathForFilename(filename);
for (auto& asyncStruct : _asyncStructQueue)
{
if (asyncStruct->filename == fullpath)
{
asyncStruct->callback = nullptr;
}
}
}
void TextureCache::unbindAllImageAsync()
{
if (_asyncStructQueue.empty())
{
return;
}
for (auto& asyncStruct : _asyncStructQueue)
{
asyncStruct->callback = nullptr;
}
}
void TextureCache::loadImage()
{
AsyncStruct *asyncStruct = nullptr;
std::mutex signalMutex;
std::unique_lock<std::mutex> signal(signalMutex);
while (!_needQuit)
{
// pop an AsyncStruct from request queue
_requestMutex.lock();
if (_requestQueue.empty())
{
asyncStruct = nullptr;
}
else
{
asyncStruct = _requestQueue.front();
_requestQueue.pop_front();
}
_requestMutex.unlock();
if (nullptr == asyncStruct) {
_sleepCondition.wait(signal);
continue;
}
// load image
asyncStruct->loadSuccess = asyncStruct->image.initWithImageFileThreadSafe(asyncStruct->filename);
// ETC1 ALPHA supports.
if (asyncStruct->loadSuccess && asyncStruct->image.getFileType() == Image::Format::ETC && !s_etc1AlphaFileSuffix.empty())
{ // check whether alpha texture exists & load it
auto alphaFile = asyncStruct->filename + s_etc1AlphaFileSuffix;
if (FileUtils::getInstance()->isFileExist(alphaFile))
asyncStruct->imageAlpha.initWithImageFileThreadSafe(alphaFile);
}
// push the asyncStruct to response queue
_responseMutex.lock();
_responseQueue.push_back(asyncStruct);
_responseMutex.unlock();
}
}
void TextureCache::addImageAsyncCallBack(float /*dt*/)
{
Texture2D *texture = nullptr;
AsyncStruct *asyncStruct = nullptr;
while (true)
{
// pop an AsyncStruct from response queue
_responseMutex.lock();
if (_responseQueue.empty())
{
asyncStruct = nullptr;
}
else
{
asyncStruct = _responseQueue.front();
_responseQueue.pop_front();
// the asyncStruct's sequence order in _asyncStructQueue must equal to the order in _responseQueue
CC_ASSERT(asyncStruct == _asyncStructQueue.front());
_asyncStructQueue.pop_front();
}
_responseMutex.unlock();
if (nullptr == asyncStruct) {
break;
}
// check the image has been convert to texture or not
auto it = _textures.find(asyncStruct->filename);
if (it != _textures.end())
{
texture = it->second;
}
else
{
// convert image to texture
if (asyncStruct->loadSuccess)
{
Image* image = &(asyncStruct->image);
// generate texture in render thread
texture = new (std::nothrow) Texture2D();
texture->initWithImage(image, asyncStruct->pixelFormat);
//parse 9-patch info
this->parseNinePatchImage(image, texture, asyncStruct->filename);
#if CC_ENABLE_CACHE_TEXTURE_DATA
// cache the texture file name
VolatileTextureMgr::addImageTexture(texture, asyncStruct->filename);
#endif
// cache the texture. retain it, since it is added in the map
_textures.emplace(asyncStruct->filename, texture);
texture->retain();
texture->autorelease();
// ETC1 ALPHA supports.
if (asyncStruct->imageAlpha.getFileType() == Image::Format::ETC) {
auto alphaTexture = new(std::nothrow) Texture2D();
if(alphaTexture != nullptr && alphaTexture->initWithImage(&asyncStruct->imageAlpha, asyncStruct->pixelFormat)) {
texture->setAlphaTexture(alphaTexture);
}
CC_SAFE_RELEASE(alphaTexture);
}
}
else {
texture = nullptr;
CCLOG("cocos2d: failed to call TextureCache::addImageAsync(%s)", asyncStruct->filename.c_str());
}
}
// call callback function
if (asyncStruct->callback)
{
(asyncStruct->callback)(texture);
}
// release the asyncStruct
delete asyncStruct;
--_asyncRefCount;
}
if (0 == _asyncRefCount)
{
Director::getInstance()->getScheduler()->unschedule(CC_SCHEDULE_SELECTOR(TextureCache::addImageAsyncCallBack), this);
}
}
Texture2D * TextureCache::addImage(const std::string &path)
{
Texture2D * texture = nullptr;
Image* image = nullptr;
// Split up directory and filename
// MUTEX:
// Needed since addImageAsync calls this method from a different thread
std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path);
if (fullpath.size() == 0)
{
return nullptr;
}
auto it = _textures.find(fullpath);
if (it != _textures.end())
texture = it->second;
if (!texture)
{
// all images are handled by UIImage except PVR extension that is handled by our own handler
do
{
image = new (std::nothrow) Image();
CC_BREAK_IF(nullptr == image);
bool bRet = image->initWithImageFile(fullpath);
CC_BREAK_IF(!bRet);
texture = new (std::nothrow) Texture2D();
if (texture && texture->initWithImage(image))
{
#if CC_ENABLE_CACHE_TEXTURE_DATA
// cache the texture file name
VolatileTextureMgr::addImageTexture(texture, fullpath);
#endif
// texture already retained, no need to re-retain it
_textures.emplace(fullpath, texture);
//-- ANDROID ETC1 ALPHA SUPPORTS.
std::string alphaFullPath = path + s_etc1AlphaFileSuffix;
if (image->getFileType() == Image::Format::ETC && !s_etc1AlphaFileSuffix.empty() && FileUtils::getInstance()->isFileExist(alphaFullPath))
{
Image alphaImage;
if (alphaImage.initWithImageFile(alphaFullPath))
{
Texture2D *pAlphaTexture = new(std::nothrow) Texture2D;
if(pAlphaTexture != nullptr && pAlphaTexture->initWithImage(&alphaImage)) {
texture->setAlphaTexture(pAlphaTexture);
}
CC_SAFE_RELEASE(pAlphaTexture);
}
}
//parse 9-patch info
this->parseNinePatchImage(image, texture, path);
}
else
{
CCLOG("cocos2d: Couldn't create texture for file:%s in TextureCache", path.c_str());
CC_SAFE_RELEASE(texture);
texture = nullptr;
}
} while (0);
}
CC_SAFE_RELEASE(image);
return texture;
}
void TextureCache::parseNinePatchImage(cocos2d::Image *image, cocos2d::Texture2D *texture, const std::string& path)
{
if (NinePatchImageParser::isNinePatchImage(path))
{
Rect frameRect = Rect(0, 0, image->getWidth(), image->getHeight());
NinePatchImageParser parser(image, frameRect, false);
texture->addSpriteFrameCapInset(nullptr, parser.parseCapInset());
}
}
Texture2D* TextureCache::addImage(Image *image, const std::string &key)
{
CCASSERT(image != nullptr, "TextureCache: image MUST not be nil");
CCASSERT(image->getData() != nullptr, "TextureCache: image MUST not be nil");
Texture2D * texture = nullptr;
do
{
auto it = _textures.find(key);
if (it != _textures.end()) {
texture = it->second;
break;
}
texture = new (std::nothrow) Texture2D();
if (texture)
{
if (texture->initWithImage(image))
{
_textures.emplace(key, texture);
}
else
{
CC_SAFE_RELEASE(texture);
texture = nullptr;
CCLOG("cocos2d: initWithImage failed!");
}
}
else
{
CCLOG("cocos2d: Allocating memory for Texture2D failed!");
}
} while (0);
#if CC_ENABLE_CACHE_TEXTURE_DATA
VolatileTextureMgr::addImage(texture, image);
#endif
return texture;
}
bool TextureCache::reloadTexture(const std::string& fileName)
{
Texture2D * texture = nullptr;
Image * image = nullptr;
std::string fullpath = FileUtils::getInstance()->fullPathForFilename(fileName);
if (fullpath.size() == 0)
{
return false;
}
auto it = _textures.find(fullpath);
if (it != _textures.end()) {
texture = it->second;
}
bool ret = false;
if (!texture) {
texture = this->addImage(fullpath);
ret = (texture != nullptr);
}
else
{
do {
image = new (std::nothrow) Image();
CC_BREAK_IF(nullptr == image);
bool bRet = image->initWithImageFile(fullpath);
CC_BREAK_IF(!bRet);
ret = texture->initWithImage(image);
} while (0);
}
CC_SAFE_RELEASE(image);
return ret;
}
// TextureCache - Remove
void TextureCache::removeAllTextures()
{
for (auto& texture : _textures) {
texture.second->release();
}
_textures.clear();
}
void TextureCache::removeUnusedTextures()
{
for (auto it = _textures.cbegin(); it != _textures.cend(); /* nothing */) {
Texture2D *tex = it->second;
if (tex->getReferenceCount() == 1) {
CCLOG("cocos2d: TextureCache: removing unused texture: %s", it->first.c_str());
tex->release();
it = _textures.erase(it);
}
else {
++it;
}
}
}
void TextureCache::removeTexture(Texture2D* texture)
{
if (!texture)
{
return;
}
for (auto it = _textures.cbegin(); it != _textures.cend(); /* nothing */) {
if (it->second == texture) {
it->second->release();
it = _textures.erase(it);
break;
}
else
++it;
}
}
void TextureCache::removeTextureForKey(const std::string &textureKeyName)
{
std::string key = textureKeyName;
auto it = _textures.find(key);
if (it == _textures.end()) {
key = FileUtils::getInstance()->fullPathForFilename(textureKeyName);
it = _textures.find(key);
}
if (it != _textures.end()) {
it->second->release();
_textures.erase(it);
}
}
Texture2D* TextureCache::getTextureForKey(const std::string &textureKeyName) const
{
std::string key = textureKeyName;
auto it = _textures.find(key);
if (it == _textures.end()) {
key = FileUtils::getInstance()->fullPathForFilename(textureKeyName);
it = _textures.find(key);
}
if (it != _textures.end())
return it->second;
return nullptr;
}
void TextureCache::reloadAllTextures()
{
//will do nothing
// #if CC_ENABLE_CACHE_TEXTURE_DATA
// VolatileTextureMgr::reloadAllTextures();
// #endif
}
std::string TextureCache::getTextureFilePath(cocos2d::Texture2D* texture) const
{
for (auto& item : _textures)
{
if (item.second == texture)
{
return item.first;
break;
}
}
return "";
}
void TextureCache::waitForQuit()
{
// notify sub thread to quick
_needQuit = true;
_sleepCondition.notify_one();
if (_loadingThread) _loadingThread->join();
}
std::string TextureCache::getCachedTextureInfo() const
{
std::string buffer;
char buftmp[4096];
unsigned int count = 0;
unsigned int totalBytes = 0;
for (auto& texture : _textures) {
memset(buftmp, 0, sizeof(buftmp));
Texture2D* tex = texture.second;
unsigned int bpp = tex->getBitsPerPixelForFormat();
// Each texture takes up width * height * bytesPerPixel bytes.
auto bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8;
totalBytes += bytes;
count++;
snprintf(buftmp, sizeof(buftmp) - 1, "\"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB\n",
texture.first.c_str(),
(long)tex->getReferenceCount(),
(long)tex->getName(),
(long)tex->getPixelsWide(),
(long)tex->getPixelsHigh(),
(long)bpp,
(long)bytes / 1024);
buffer += buftmp;
}
snprintf(buftmp, sizeof(buftmp) - 1, "TextureCache dumpDebugInfo: %ld textures, for %lu KB (%.2f MB)\n", (long)count, (long)totalBytes / 1024, totalBytes / (1024.0f*1024.0f));
buffer += buftmp;
return buffer;
}
void TextureCache::renameTextureWithKey(const std::string& srcName, const std::string& dstName)
{
std::string key = srcName;
auto it = _textures.find(key);
if (it == _textures.end()) {
key = FileUtils::getInstance()->fullPathForFilename(srcName);
it = _textures.find(key);
}
if (it != _textures.end()) {
std::string fullpath = FileUtils::getInstance()->fullPathForFilename(dstName);
Texture2D* tex = it->second;
Image* image = new (std::nothrow) Image();
if (image)
{
bool ret = image->initWithImageFile(dstName);
if (ret)
{
tex->initWithImage(image);
_textures.emplace(fullpath, tex);
_textures.erase(it);
}
CC_SAFE_DELETE(image);
}
}
}
#if CC_ENABLE_CACHE_TEXTURE_DATA
std::list<VolatileTexture*> VolatileTextureMgr::_textures;
bool VolatileTextureMgr::_isReloading = false;
VolatileTexture::VolatileTexture(Texture2D *t)
: _texture(t)
, _cashedImageType(kInvalid)
, _textureData(nullptr)
, _pixelFormat(Texture2D::PixelFormat::RGBA8888)
, _fileName("")
, _text("")
, _uiImage(nullptr)
, _hasMipmaps(false)
{
_texParams.minFilter = GL_LINEAR;
_texParams.magFilter = GL_LINEAR;
_texParams.wrapS = GL_CLAMP_TO_EDGE;
_texParams.wrapT = GL_CLAMP_TO_EDGE;
}
VolatileTexture::~VolatileTexture()
{
CC_SAFE_RELEASE(_uiImage);
}
void VolatileTextureMgr::addImageTexture(Texture2D *tt, const std::string& imageFileName)
{
if (_isReloading)
{
return;
}
VolatileTexture *vt = findVolotileTexture(tt);
vt->_cashedImageType = VolatileTexture::kImageFile;
vt->_fileName = imageFileName;
vt->_pixelFormat = tt->getPixelFormat();
}
void VolatileTextureMgr::addImage(Texture2D *tt, Image *image)
{
if (tt == nullptr || image == nullptr)
return;
VolatileTexture *vt = findVolotileTexture(tt);
image->retain();
vt->_uiImage = image;
vt->_cashedImageType = VolatileTexture::kImage;
}
VolatileTexture* VolatileTextureMgr::findVolotileTexture(Texture2D *tt)
{
VolatileTexture *vt = nullptr;
for (const auto& texture : _textures)
{
VolatileTexture *v = texture;
if (v->_texture == tt)
{
vt = v;
break;
}
}
if (!vt)
{
vt = new (std::nothrow) VolatileTexture(tt);
_textures.push_back(vt);
}
return vt;
}
void VolatileTextureMgr::addDataTexture(Texture2D *tt, void* data, int dataLen, Texture2D::PixelFormat pixelFormat, const Size& contentSize)
{
if (_isReloading)
{
return;
}
VolatileTexture *vt = findVolotileTexture(tt);
vt->_cashedImageType = VolatileTexture::kImageData;
vt->_textureData = data;
vt->_dataLen = dataLen;
vt->_pixelFormat = pixelFormat;
vt->_textureSize = contentSize;
}
void VolatileTextureMgr::addStringTexture(Texture2D *tt, const char* text, const FontDefinition& fontDefinition)
{
if (_isReloading)
{
return;
}
VolatileTexture *vt = findVolotileTexture(tt);
vt->_cashedImageType = VolatileTexture::kString;
vt->_text = text;
vt->_fontDefinition = fontDefinition;
}
void VolatileTextureMgr::setHasMipmaps(Texture2D *t, bool hasMipmaps)
{
VolatileTexture *vt = findVolotileTexture(t);
vt->_hasMipmaps = hasMipmaps;
}
void VolatileTextureMgr::setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams)
{
VolatileTexture *vt = findVolotileTexture(t);
if (texParams.minFilter != GL_NONE)
vt->_texParams.minFilter = texParams.minFilter;
if (texParams.magFilter != GL_NONE)
vt->_texParams.magFilter = texParams.magFilter;
if (texParams.wrapS != GL_NONE)
vt->_texParams.wrapS = texParams.wrapS;
if (texParams.wrapT != GL_NONE)
vt->_texParams.wrapT = texParams.wrapT;
}
void VolatileTextureMgr::removeTexture(Texture2D *t)
{
for (auto& item : _textures)
{
VolatileTexture *vt = item;
if (vt->_texture == t)
{
_textures.remove(vt);
delete vt;
break;
}
}
}
void VolatileTextureMgr::reloadAllTextures()
{
_isReloading = true;
// we need to release all of the glTextures to avoid collisions of texture id's when reloading the textures onto the GPU
for (auto& item : _textures)
{
item->_texture->releaseGLTexture();
}
CCLOG("reload all texture");
for (auto& texture : _textures)
{
VolatileTexture *vt = texture;
switch (vt->_cashedImageType)
{
case VolatileTexture::kImageFile:
{
Image* image = new (std::nothrow) Image();
Data data = FileUtils::getInstance()->getDataFromFile(vt->_fileName);
if (image && image->initWithImageData(data.getBytes(), data.getSize()))
{
Texture2D::PixelFormat oldPixelFormat = Texture2D::getDefaultAlphaPixelFormat();
Texture2D::setDefaultAlphaPixelFormat(vt->_pixelFormat);
vt->_texture->initWithImage(image);
Texture2D::setDefaultAlphaPixelFormat(oldPixelFormat);
}
CC_SAFE_RELEASE(image);
}
break;
case VolatileTexture::kImageData:
{
vt->_texture->initWithData(vt->_textureData,
vt->_dataLen,
vt->_pixelFormat,
vt->_textureSize.width,
vt->_textureSize.height,
vt->_textureSize);
}
break;
case VolatileTexture::kString:
{
vt->_texture->initWithString(vt->_text.c_str(), vt->_fontDefinition);
}
break;
case VolatileTexture::kImage:
{
vt->_texture->initWithImage(vt->_uiImage);
}
break;
default:
break;
}
if (vt->_hasMipmaps) {
vt->_texture->generateMipmap();
}
vt->_texture->setTexParameters(vt->_texParams);
}
_isReloading = false;
}
#endif // CC_ENABLE_CACHE_TEXTURE_DATA
NS_CC_END
|
#ifndef __DEBUG_UTILITY_H__
#define __DEBUG_UTILITY_H__
#ifdef _DEBUG_CONSOLE
#include <iostream>
#include <stdio.h>
#ifdef _DEBUG_TIME
#include <chrono>
#define speed_test_begin() speed_test_start_begin_time = std::chrono::system_clock::now()
#define speed_test_end(info, unit) std::cout << info << std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now() - speed_test_start_begin_time).count() / 1000.0 << " " << unit << std::endl;
#ifdef _DEBUG_PART_TIME
#define speed_test_reset() speed_test_start_begin_time = std::chrono::system_clock::now()
#else // _DEBUG_PART_TIME
#define speed_test_reset()
#endif // _DEBUG_PART_TIME
#else // _DEBUG_TIME
#define speed_test_begin()
#define speed_test_reset()
#define speed_test_end(...)
#endif // _DEBUG_TIME
#define console_log(args...) printf(args)
#else // _DEBUG_CONSOLE
#define speed_test_begin()
#define speed_test_reset()
#define speed_test_end(...)
#define console_log(...)
#endif // _DEBUG_CONSOLE
#endif // !__DEBUG_UTILITY_H__
|
#include "stdafx.h"
/*
This file is a part of KMC software distributed under GNU GPL 3 licence.
The homepage of the KMC project is http://sun.aei.polsl.pl/kmc
Authors: Sebastian Deorowicz, Agnieszka Debudaj-Grabysz, Marek Kokot
Version: 3.0.0
Date : 2017-01-28
*/
#include "mem_disk_file.h"
#include "asmlib_wrapper.h"
#include <iostream>
using namespace std;
//----------------------------------------------------------------------------------
// Constructor
CMemDiskFile::CMemDiskFile(bool _memory_mode)
{
memory_mode = _memory_mode;
file = NULL;
}
//----------------------------------------------------------------------------------
void CMemDiskFile::Open(const string& f_name)
{
if(memory_mode)
{
}
else
{
file = fopen(f_name.c_str(), "wb+");
if (!file)
{
cout << "Error: Cannot open temporary file " << f_name << "\n";
exit(1);
}
setbuf(file, nullptr);
}
name = f_name;
}
//----------------------------------------------------------------------------------
void CMemDiskFile::Rewind()
{
if(memory_mode)
{
}
else
{
rewind(file);
}
}
//----------------------------------------------------------------------------------
int CMemDiskFile::Close()
{
if(memory_mode)
{
for(auto& p : container)
{
delete[] p.first;
}
container.clear();
return 0;
}
else
{
return fclose(file);
}
}
//----------------------------------------------------------------------------------
void CMemDiskFile::Remove()
{
if (!memory_mode)
remove(name.c_str());
}
//----------------------------------------------------------------------------------
size_t CMemDiskFile::Read(uchar * ptr, size_t size, size_t count)
{
if(memory_mode)
{
uint64 pos = 0;
for(auto& p : container)
{
A_memcpy(ptr + pos, p.first, p.second);
pos += p.second;
delete[] p.first;
}
container.clear();
return pos;
}
else
{
return fread(ptr, size, count, file);
}
}
//----------------------------------------------------------------------------------
size_t CMemDiskFile::Write(const uchar * ptr, size_t size, size_t count)
{
if(memory_mode)
{
uchar *buf = new uchar[size * count];
A_memcpy(buf, ptr, size * count);
container.push_back(make_pair(buf, size * count));
return size * count;
}
else
{
return fwrite(ptr, size, count, file);
}
}
|
/*
Author: Luis Manuel D?az Bar?n (LUISMO)
Problem: F - LCS
Online Judge:
Idea: Classic LCS with string reconstruction
*/
#include<bits/stdc++.h>
// Types
#define ll long long
#define ull unsigned long long
// IO
#define sf scanf
#define pf printf
#define mkp make_pair
#define fi first
#define se second
#define endl "\n"
using namespace std;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const ll inf = 1e16 + 3;
const int mod = 1e9 + 7;
const int lim = 3e3 + 2;
string s, t;
int dp[lim][lim];
bool mark[lim][lim];
pii stat[lim][lim];
int DynamicProgramming(int ls, int rs)
{
if(ls == 0 || rs == 0)
return 0;
if(mark[ls][rs])
return dp[ls][rs];
mark[ls][rs] = true;
int idxs = ls - 1;
int idxr = rs - 1;
int s1 = DynamicProgramming(ls, rs - 1);
int s2 = DynamicProgramming(ls - 1, rs);
int s3 = 0;
if(s[ls-1] == t[rs-1])
s3 = 1 + DynamicProgramming(ls - 1, rs - 1);
int mx = max(max(s1, s2), s3);
if(s1 >= s2 && s1 >= s3)
stat[ls][rs] = mkp(ls, rs - 1);
if(s2 >= s1 && s2 >= s3)
stat[ls][rs] = mkp(ls - 1, rs);
if(s3 >= s1 && s3 >= s2)
stat[ls][rs] = mkp(ls - 1, rs - 1);
dp[ls][rs] = mx;
return mx;
}
void solve()
{
cin >> s >> t;
int cnt = DynamicProgramming(s.size(), t.size());
string answ = "";
int l = s.size();
int r = t.size();
while(l > 0 && r > 0)
{
if(s[l-1] == t[r-1])
{
answ = s[l-1] + answ;
}
int xl = stat[l][r].first;
int xr = stat[l][r].second;
l = xl;
r = xr;
}
// print answer
cout << answ << endl;
}
void fastIO()
{
cin.sync_with_stdio(false);
cin.tie(0);
}
void IO()
{
if(fopen("d:\\lmo.in","r") != NULL)
{
freopen("d:\\lmo.in","r",stdin);
}
else if(fopen("/media/Beijing/lmo.in","r") != NULL)
{
freopen("/media/Beijing/lmo.in", "r", stdin);
}
}
int main()
{
IO();
fastIO();
solve();
}
|
// Copyright 2020-2021 Herald Project Contributors
// SPDX-License-Identifier: Apache-2.0
//
#include "herald/ble/bluetooth_state_manager.h"
namespace herald {
namespace ble {
}
}
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <NvCloth_precompiled.h>
#include <AzTest/AzTest.h>
#include <AzCore/UnitTest/TestTypes.h>
#include <AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.h>
#include <Components/ClothComponent.h>
#include <Components/EditorClothComponent.h>
#include <Utils/Allocators.h>
namespace NvCloth
{
namespace
{
using EntityPtr = AZStd::unique_ptr<AZ::Entity>;
const AZ::Uuid EditorMeshComponentTypeId = "{FC315B86-3280-4D03-B4F0-5553D7D08432}";
const AZ::Uuid MeshComponentTypeId = "{2F4BAD46-C857-4DCB-A454-C412DE67852A}";
const AZ::Uuid EditorActorComponentTypeId = "{A863EE1B-8CFD-4EDD-BA0D-1CEC2879AD44}";
const AZ::Uuid ActorComponentTypeId = "{BDC97E7F-A054-448B-A26F-EA2B5D78E377}";
}
class NvClothEditorTest
: public ::testing::Test
{
protected:
static void SetUpTestCase()
{
if (s_app == nullptr)
{
AZ::AllocatorInstance<AZ::SystemAllocator>::Create();
AZ::AllocatorInstance<AzClothAllocator>::Create();
s_app = aznew AzToolsFramework::ToolsApplication;
AzToolsFramework::ToolsApplication::Descriptor appDescriptor;
appDescriptor.m_useExistingAllocator = true;
appDescriptor.m_modules.emplace_back(AZ::DynamicModuleDescriptor());
appDescriptor.m_modules.back().m_dynamicLibraryPath = "Gem.LmbrCentral.Editor.ff06785f7145416b9d46fde39098cb0c.v0.1.0";
appDescriptor.m_modules.emplace_back(AZ::DynamicModuleDescriptor());
appDescriptor.m_modules.back().m_dynamicLibraryPath = "Gem.EMotionFX.Editor.044a63ea67d04479aa5daf62ded9d9ca.v0.1.0";
s_app->Start(appDescriptor);
s_app->RegisterComponentDescriptor(ClothComponent::CreateDescriptor());
s_app->RegisterComponentDescriptor(EditorClothComponent::CreateDescriptor());
}
}
static void TearDownTestCase()
{
if (s_app)
{
s_app->Stop();
delete s_app;
s_app = nullptr;
AZ::AllocatorInstance<AzClothAllocator>::Destroy();
AZ::AllocatorInstance<AZ::SystemAllocator>::Destroy();
}
}
static AzToolsFramework::ToolsApplication* s_app;
};
AzToolsFramework::ToolsApplication* NvClothEditorTest::s_app = nullptr;
EntityPtr CreateInactiveEditorEntity(const char* entityName)
{
AZ::Entity* entity = nullptr;
UnitTest::CreateDefaultEditorEntity(entityName, &entity);
entity->Deactivate();
return AZStd::unique_ptr<AZ::Entity>(entity);
}
EntityPtr CreateActiveGameEntityFromEditorEntity(AZ::Entity* editorEntity)
{
EntityPtr gameEntity = AZStd::make_unique<AZ::Entity>();
AzToolsFramework::ToolsApplicationRequestBus::Broadcast(
&AzToolsFramework::ToolsApplicationRequests::PreExportEntity, *editorEntity, *gameEntity);
gameEntity->Init();
gameEntity->Activate();
return gameEntity;
}
TEST_F(NvClothEditorTest, EditorClothComponent_DependencyMissing_EntityIsInvalid)
{
EntityPtr entity = CreateInactiveEditorEntity("ClothComponentEditorEntity");
entity->CreateComponent<EditorClothComponent>();
// the entity should not be in a valid state because the cloth component requires a mesh or an actor component
AZ::Entity::DependencySortOutcome sortOutcome = entity->EvaluateDependenciesGetDetails();
EXPECT_FALSE(sortOutcome.IsSuccess());
EXPECT_TRUE(sortOutcome.GetError().m_code == AZ::Entity::DependencySortResult::MissingRequiredService);
}
TEST_F(NvClothEditorTest, EditorClothComponent_MeshDependencySatisfied_EntityIsValid)
{
EntityPtr entity = CreateInactiveEditorEntity("ClothComponentEditorEntity");
entity->CreateComponent<EditorClothComponent>();
entity->CreateComponent(EditorMeshComponentTypeId);
// the entity should be in a valid state because the cloth component requirement is satisfied
AZ::Entity::DependencySortOutcome sortOutcome = entity->EvaluateDependenciesGetDetails();
EXPECT_TRUE(sortOutcome.IsSuccess());
}
TEST_F(NvClothEditorTest, EditorClothComponent_ActorDependencySatisfied_EntityIsValid)
{
EntityPtr entity = CreateInactiveEditorEntity("ClothComponentEditorEntity");
entity->CreateComponent<EditorClothComponent>();
entity->CreateComponent(EditorActorComponentTypeId);
// the entity should be in a valid state because the cloth component requirement is satisfied
AZ::Entity::DependencySortOutcome sortOutcome = entity->EvaluateDependenciesGetDetails();
EXPECT_TRUE(sortOutcome.IsSuccess());
}
TEST_F(NvClothEditorTest, EditorClothComponent_MultipleClothComponents_EntityIsValid)
{
EntityPtr entity = CreateInactiveEditorEntity("ClothComponentEditorEntity");
entity->CreateComponent<EditorClothComponent>();
entity->CreateComponent(EditorMeshComponentTypeId);
// the cloth component should be compatible with multiple cloth components
entity->CreateComponent<EditorClothComponent>();
entity->CreateComponent<EditorClothComponent>();
// the entity should be in a valid state because the cloth component requirement is satisfied
AZ::Entity::DependencySortOutcome sortOutcome = entity->EvaluateDependenciesGetDetails();
EXPECT_TRUE(sortOutcome.IsSuccess());
}
TEST_F(NvClothEditorTest, EditorClothComponent_ClothWithMesh_CorrectRuntimeComponents)
{
// create an editor entity with a cloth component and a mesh component
EntityPtr editorEntity = CreateInactiveEditorEntity("ClothComponentEditorEntity");
editorEntity->CreateComponent<EditorClothComponent>();
editorEntity->CreateComponent(EditorMeshComponentTypeId);
editorEntity->Activate();
EntityPtr gameEntity = CreateActiveGameEntityFromEditorEntity(editorEntity.get());
// check that the runtime entity has the expected components
EXPECT_TRUE(gameEntity->FindComponent<ClothComponent>() != nullptr);
EXPECT_TRUE(gameEntity->FindComponent(MeshComponentTypeId) != nullptr);
}
TEST_F(NvClothEditorTest, EditorClothComponent_ClothWithActor_CorrectRuntimeComponents)
{
// create an editor entity with a cloth component and an actor component
EntityPtr editorEntity = CreateInactiveEditorEntity("ClothComponentEditorEntity");
editorEntity->CreateComponent<EditorClothComponent>();
editorEntity->CreateComponent(EditorActorComponentTypeId);
editorEntity->Activate();
EntityPtr gameEntity = CreateActiveGameEntityFromEditorEntity(editorEntity.get());
// check that the runtime entity has the expected components
EXPECT_TRUE(gameEntity->FindComponent<ClothComponent>() != nullptr);
EXPECT_TRUE(gameEntity->FindComponent(ActorComponentTypeId) != nullptr);
}
AZ_UNIT_TEST_HOOK();
} // namespace NvCloth
|
#ifndef __SHOW_H__
#define __SHOW_H__
#include "recipe.hpp"
#include <list>
// 화면지우기
void clear();
//메인 메뉴
int show_main();
// 선택한 메뉴
void show_1(list<Ingredient> &ingredient_list); // 재료 추가
void show_2(list<Ingredient> &ingredient_list); // 재료 삭제
void show_3(list<Recipe> &recipe_list); // 레시피 추가
void show_4(list<Recipe> &recipe_list); // 레시피 삭제
void show_5(list<Ingredient> &ingredient_list); // 재료 목록
void show_6(list<Recipe> &recipe_list); // 레시피 목록
void show_7(list<Ingredient> &ingredient_list,
const list<Recipe> &recipe_list); // 요리하기
#endif
|
//
// mime_types.hpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2016 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_SERVER4_MIME_TYPES_HPP
#define HTTP_SERVER4_MIME_TYPES_HPP
#include <string>
namespace http {
namespace server4 {
namespace mime_types {
/// Convert a file extension into a MIME type.
std::string extension_to_type(const std::string& extension);
} // namespace mime_types
} // namespace server4
} // namespace http
#endif // HTTP_SERVER4_MIME_TYPES_HPP
|
/******************************************************************************
* Copyright 2017 The Apollo 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 "modules/dreamview/backend/hmi/vehicle_manager.h"
#include "absl/strings/str_cat.h"
#include "cyber/common/file.h"
#include "cyber/common/log.h"
#include "gflags/gflags.h"
#include "modules/common/configs/vehicle_config_helper.h"
DEFINE_string(vehicle_data_config_filename,
"/apollo/modules/dreamview/conf/vehicle_data.pb.txt",
"Vehicle data config file.");
namespace apollo {
namespace dreamview {
using cyber::common::GetProtoFromFile;
VehicleManager::VehicleManager() {
ACHECK(GetProtoFromFile(FLAGS_vehicle_data_config_filename, &vehicle_data_))
<< "Unable to parse VehicleData config file "
<< FLAGS_vehicle_data_config_filename;
}
const std::string &VehicleManager::GetVehicleDataPath() const {
return vehicle_data_path_;
}
bool VehicleManager::UseVehicle(const std::string &vehicle_data_path) {
if (!cyber::common::DirectoryExists(vehicle_data_path)) {
AERROR << "Cannot find vehicle data: " << vehicle_data_path;
return false;
}
vehicle_data_path_ = vehicle_data_path;
for (const auto &data_file : vehicle_data_.data_files()) {
const auto source_path =
absl::StrCat(vehicle_data_path, "/", data_file.source_path());
const auto &dest_path = data_file.dest_path();
const bool ret = cyber::common::Copy(source_path, dest_path);
AINFO_IF(ret) << "Copied " << source_path << " to " << dest_path;
}
// Reload vehicle config for current process.
apollo::common::VehicleConfigHelper::Init();
// Broadcast new extrinsics.
static const std::string kBroadcastExtrinsicsCmd =
"bash /apollo/scripts/broadcast_extrinsics.sh";
const int ret = std::system(kBroadcastExtrinsicsCmd.c_str());
AERROR_IF(ret != 0) << "Command returns " << ret << ": "
<< kBroadcastExtrinsicsCmd;
return true;
}
} // namespace dreamview
} // namespace apollo
|
/*
* Copyright (c) 2012-2021 Daniele Bartolini et al.
* License: https://github.com/dbartolini/crown/blob/master/LICENSE
*/
#include "config.h"
#if CROWN_SOUND_OPENAL
#include "core/containers/array.inl"
#include "core/math/constants.h"
#include "core/math/matrix4x4.inl"
#include "core/math/vector3.inl"
#include "core/memory/temp_allocator.inl"
#include "device/log.h"
#include "resource/sound_resource.h"
#include "world/audio.h"
#include "world/sound_world.h"
#include <AL/al.h>
#include <AL/alc.h>
LOG_SYSTEM(SOUND, "sound")
namespace crown
{
#if CROWN_DEBUG
static const char* al_error_to_string(ALenum error)
{
switch (error)
{
case AL_INVALID_ENUM: return "AL_INVALID_ENUM";
case AL_INVALID_VALUE: return "AL_INVALID_VALUE";
case AL_INVALID_OPERATION: return "AL_INVALID_OPERATION";
case AL_OUT_OF_MEMORY: return "AL_OUT_OF_MEMORY";
default: return "UNKNOWN_AL_ERROR";
}
}
#define AL_CHECK(function) \
function; \
do \
{ \
ALenum error; \
CE_ASSERT((error = alGetError()) == AL_NO_ERROR \
, "alGetError: %s" \
, al_error_to_string(error) \
); \
} while (0)
#else
#define AL_CHECK(function) function
#endif // CROWN_DEBUG
/// Global audio-related functions
namespace audio_globals
{
static ALCdevice* s_al_device;
static ALCcontext* s_al_context;
void init()
{
s_al_device = alcOpenDevice(NULL);
CE_ASSERT(s_al_device, "alcOpenDevice: error");
s_al_context = alcCreateContext(s_al_device, NULL);
CE_ASSERT(s_al_context, "alcCreateContext: error");
AL_CHECK(alcMakeContextCurrent(s_al_context));
#if CROWN_DEBUG && !CROWN_DEVELOPMENT
logi(SOUND, "OpenAL Vendor : %s", alGetString(AL_VENDOR));
logi(SOUND, "OpenAL Version : %s", alGetString(AL_VERSION));
logi(SOUND, "OpenAL Renderer : %s", alGetString(AL_RENDERER));
#endif
AL_CHECK(alDistanceModel(AL_LINEAR_DISTANCE_CLAMPED));
AL_CHECK(alDopplerFactor(1.0f));
AL_CHECK(alDopplerVelocity(343.0f));
}
void shutdown()
{
alcDestroyContext(s_al_context);
alcCloseDevice(s_al_device);
}
} // namespace audio_globals
struct SoundInstance
{
const SoundResource* _resource;
SoundInstanceId _id;
ALuint _buffer;
ALuint _source;
void create(const SoundResource& sr, const Vector3& pos, f32 range)
{
using namespace sound_resource;
AL_CHECK(alGenSources(1, &_source));
CE_ASSERT(alIsSource(_source), "alGenSources: error");
AL_CHECK(alSourcef(_source, AL_REFERENCE_DISTANCE, 0.01f));
AL_CHECK(alSourcef(_source, AL_MAX_DISTANCE, range));
AL_CHECK(alSourcef(_source, AL_PITCH, 1.0f));
// Generates AL buffers
AL_CHECK(alGenBuffers(1, &_buffer));
CE_ASSERT(alIsBuffer(_buffer), "alGenBuffers: error");
ALenum fmt = AL_INVALID_ENUM;
switch (sr.bits_ps)
{
case 8: fmt = sr.channels > 1 ? AL_FORMAT_STEREO8 : AL_FORMAT_MONO8; break;
case 16: fmt = sr.channels > 1 ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16; break;
default: CE_FATAL("Number of bits per sample not supported."); break;
}
AL_CHECK(alBufferData(_buffer, fmt, data(&sr), sr.size, sr.sample_rate));
_resource = &sr;
set_position(pos);
}
void destroy()
{
stop();
AL_CHECK(alSourcei(_source, AL_BUFFER, 0));
AL_CHECK(alDeleteBuffers(1, &_buffer));
AL_CHECK(alDeleteSources(1, &_source));
}
void reload(const SoundResource& new_sr)
{
destroy();
create(new_sr, position(), range());
}
void play(bool loop, f32 volume)
{
set_volume(volume);
AL_CHECK(alSourcei(_source, AL_LOOPING, (loop ? AL_TRUE : AL_FALSE)));
AL_CHECK(alSourceQueueBuffers(_source, 1, &_buffer));
AL_CHECK(alSourcePlay(_source));
}
void pause()
{
AL_CHECK(alSourcePause(_source));
}
void resume()
{
AL_CHECK(alSourcePlay(_source));
}
void stop()
{
AL_CHECK(alSourceStop(_source));
AL_CHECK(alSourceRewind(_source)); // Workaround
ALint processed;
AL_CHECK(alGetSourcei(_source, AL_BUFFERS_PROCESSED, &processed));
if (processed > 0)
{
ALuint removed;
AL_CHECK(alSourceUnqueueBuffers(_source, 1, &removed));
}
}
bool is_playing()
{
ALint state;
AL_CHECK(alGetSourcei(_source, AL_SOURCE_STATE, &state));
return state == AL_PLAYING;
}
bool finished()
{
ALint state;
AL_CHECK(alGetSourcei(_source, AL_SOURCE_STATE, &state));
return (state != AL_PLAYING && state != AL_PAUSED);
}
Vector3 position()
{
ALfloat pos[3];
AL_CHECK(alGetSourcefv(_source, AL_POSITION, pos));
return vector3(pos[0], pos[1], pos[2]);
}
float range()
{
ALfloat range;
AL_CHECK(alGetSourcefv(_source, AL_MAX_DISTANCE, &range));
return range;
}
void set_position(const Vector3& pos)
{
AL_CHECK(alSourcefv(_source, AL_POSITION, to_float_ptr(pos)));
}
void set_range(f32 range)
{
AL_CHECK(alSourcef(_source, AL_MAX_DISTANCE, range));
}
void set_volume(f32 volume)
{
AL_CHECK(alSourcef(_source, AL_GAIN, volume));
}
};
#define MAX_OBJECTS 1024
#define INDEX_MASK 0xffff
#define NEW_OBJECT_ID_ADD 0x10000
struct SoundWorldImpl
{
struct Index
{
SoundInstanceId id;
u16 index;
u16 next;
};
u32 _num_objects;
SoundInstance _playing_sounds[MAX_OBJECTS];
Index _indices[MAX_OBJECTS];
u16 _freelist_enqueue;
u16 _freelist_dequeue;
Matrix4x4 _listener_pose;
bool has(SoundInstanceId id)
{
Index& in = _indices[id & INDEX_MASK];
return in.id == id && in.index != UINT16_MAX;
}
SoundInstance& lookup(SoundInstanceId id)
{
return _playing_sounds[_indices[id & INDEX_MASK].index];
}
SoundInstanceId add()
{
Index& in = _indices[_freelist_dequeue];
_freelist_dequeue = in.next;
in.id += NEW_OBJECT_ID_ADD;
in.index = _num_objects++;
SoundInstance& o = _playing_sounds[in.index];
o._id = in.id;
return o._id;
}
void remove(SoundInstanceId id)
{
Index& in = _indices[id & INDEX_MASK];
SoundInstance& o = _playing_sounds[in.index];
o = _playing_sounds[--_num_objects];
_indices[o._id & INDEX_MASK].index = in.index;
in.index = UINT16_MAX;
_indices[_freelist_enqueue].next = id & INDEX_MASK;
_freelist_enqueue = id & INDEX_MASK;
}
SoundWorldImpl()
{
_num_objects = 0;
for (u32 i = 0; i < MAX_OBJECTS; ++i)
{
_indices[i].id = i;
_indices[i].next = i + 1;
}
_freelist_dequeue = 0;
_freelist_enqueue = MAX_OBJECTS - 1;
set_listener_pose(MATRIX4X4_IDENTITY);
}
SoundInstanceId play(const SoundResource& sr, bool loop, f32 volume, f32 range, const Vector3& pos)
{
SoundInstanceId id = add();
SoundInstance& si = lookup(id);
si.create(sr, pos, range);
si.play(loop, volume);
return id;
}
void stop(SoundInstanceId id)
{
SoundInstance& si = lookup(id);
si.destroy();
remove(id);
}
bool is_playing(SoundInstanceId id)
{
return has(id) && lookup(id).is_playing();
}
void stop_all()
{
for (u32 i = 0; i < _num_objects; ++i)
{
_playing_sounds[i].stop();
}
}
void pause_all()
{
for (u32 i = 0; i < _num_objects; ++i)
{
_playing_sounds[i].pause();
}
}
void resume_all()
{
for (u32 i = 0; i < _num_objects; ++i)
{
_playing_sounds[i].resume();
}
}
void set_sound_positions(u32 num, const SoundInstanceId* ids, const Vector3* positions)
{
for (u32 i = 0; i < num; ++i)
{
lookup(ids[i]).set_position(positions[i]);
}
}
void set_sound_ranges(u32 num, const SoundInstanceId* ids, const f32* ranges)
{
for (u32 i = 0; i < num; ++i)
{
lookup(ids[i]).set_range(ranges[i]);
}
}
void set_sound_volumes(u32 num, const SoundInstanceId* ids, const f32* volumes)
{
for (u32 i = 0; i < num; i++)
{
lookup(ids[i]).set_volume(volumes[i]);
}
}
void reload_sounds(const SoundResource& old_sr, const SoundResource& new_sr)
{
for (u32 i = 0; i < _num_objects; ++i)
{
if (_playing_sounds[i]._resource == &old_sr)
{
_playing_sounds[i].reload(new_sr);
}
}
}
void set_listener_pose(const Matrix4x4& pose)
{
const Vector3 pos = translation(pose);
const Vector3 up = y(pose);
const Vector3 at = z(pose);
AL_CHECK(alListener3f(AL_POSITION, pos.x, pos.y, pos.z));
//AL_CHECK(alListener3f(AL_VELOCITY, vel.x, vel.y, vel.z));
const ALfloat orientation[] = { up.x, up.y, up.z, at.x, at.y, at.z };
AL_CHECK(alListenerfv(AL_ORIENTATION, orientation));
_listener_pose = pose;
}
void update()
{
TempAllocator256 alloc;
Array<SoundInstanceId> to_delete(alloc);
// Check what sounds finished playing
for (u32 i = 0; i < _num_objects; ++i)
{
SoundInstance& instance = _playing_sounds[i];
if (instance.finished())
{
array::push_back(to_delete, instance._id);
}
}
// Destroy instances which finished playing
for (u32 i = 0; i < array::size(to_delete); ++i)
{
stop(to_delete[i]);
}
}
};
SoundWorld::SoundWorld(Allocator& a)
: _marker(SOUND_WORLD_MARKER)
, _allocator(&a)
, _impl(NULL)
{
_impl = CE_NEW(*_allocator, SoundWorldImpl)();
}
SoundWorld::~SoundWorld()
{
CE_DELETE(*_allocator, _impl);
_marker = 0;
}
SoundInstanceId SoundWorld::play(const SoundResource& sr, bool loop, f32 volume, f32 range, const Vector3& pos)
{
return _impl->play(sr, loop, volume, range, pos);
}
void SoundWorld::stop(SoundInstanceId id)
{
_impl->stop(id);
}
bool SoundWorld::is_playing(SoundInstanceId id)
{
return _impl->is_playing(id);
}
void SoundWorld::stop_all()
{
_impl->stop_all();
}
void SoundWorld::pause_all()
{
_impl->pause_all();
}
void SoundWorld::resume_all()
{
_impl->resume_all();
}
void SoundWorld::set_sound_positions(u32 num, const SoundInstanceId* ids, const Vector3* positions)
{
_impl->set_sound_positions(num, ids, positions);
}
void SoundWorld::set_sound_ranges(u32 num, const SoundInstanceId* ids, const f32* ranges)
{
_impl->set_sound_ranges(num, ids, ranges);
}
void SoundWorld::set_sound_volumes(u32 num, const SoundInstanceId* ids, const f32* volumes)
{
_impl->set_sound_volumes(num, ids, volumes);
}
void SoundWorld::reload_sounds(const SoundResource& old_sr, const SoundResource& new_sr)
{
_impl->reload_sounds(old_sr, new_sr);
}
void SoundWorld::set_listener_pose(const Matrix4x4& pose)
{
_impl->set_listener_pose(pose);
}
void SoundWorld::update()
{
_impl->update();
}
} // namespace crown
#endif // CROWN_SOUND_OPENAL
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef MavLinkCom_MavLinkComImpl_hpp
#define MavLinkCom_MavLinkComImpl_hpp
#include <memory>
#include <string>
#include <vector>
#include <mutex>
#include <chrono>
#include "MavLinkNode.hpp"
#include "MavLinkNodeImpl.hpp"
#include "MavLinkFtpClient.hpp"
#include <stdio.h>
#include <string>
namespace mavlinkcom_impl {
class MavLinkFtpClientImpl : public MavLinkNodeImpl
{
public:
MavLinkFtpClientImpl(int localSystemId, int localComponentId);
~MavLinkFtpClientImpl();
bool isSupported();
void list(MavLinkFtpProgress& progress, const std::string& remotePath, std::vector<MavLinkFileInfo>& files);
void get(MavLinkFtpProgress& progress, const std::string& remotePath, const std::string& localPath);
void put(MavLinkFtpProgress& progress, const std::string& remotePath, const std::string& localPath);
void remove(MavLinkFtpProgress& progress, const std::string& remotePath);
void mkdir(MavLinkFtpProgress& progress, const std::string& remotePath);
void rmdir(MavLinkFtpProgress& progress, const std::string& remotePath);
void cancel();
private:
void nextStep();
void listDirectory();
void removeFile();
void readFile();
void writeFile();
void mkdir();
void rmdir();
void handleListResponse();
void handleReadResponse();
void handleWriteResponse();
void handleRemoveResponse();
void handleRmdirResponse();
void handleMkdirResponse();
void reset();
void handleResponse(const MavLinkMessage& msg);
bool createLocalFile();
bool openSourceFile();
void subscribe();
void close();
void recordMessageSent();
void recordMessageReceived();
void runStateMachine();
void retry();
std::string replaceAll(std::string s, char toFind, char toReplace);
std::string normalize(std::string arg);
std::string toPX4Path(std::string arg);
// the following state is needed to implement a restartable state machine for each command
// with a watchdog
enum FtpCommandEnum {
FtpCommandNone, FtpCommandList, FtpCommandGet, FtpCommandPut, FtpCommandRemove, FtpCommandMkdir, FtpCommandRmdir
};
FtpCommandEnum command_ = FtpCommandNone;
std::string local_file_;
std::string remote_file_;
FILE* file_ptr_ = nullptr;
int bytes_read_ = 0;
bool remote_file_open_ = false;
int bytes_written_ = 0;
uint64_t file_size_ = 0;
uint32_t file_index_ = 0;
int sequence_ = 0;
int subscription_ = 0;
bool waiting_ = false;
bool success_ = false;
int errorCode_ = 0;
std::chrono::milliseconds start_time_;
std::chrono::milliseconds total_time_;
int messages_ = 0;
int retries_ = 0;
MavLinkFileTransferProtocol last_message_;
bool watch_dog_running_ = false;
std::mutex mutex_;
std::vector<mavlinkcom::MavLinkFileInfo>* files_ = nullptr;
MavLinkFtpProgress* progress_ = nullptr;
};
}
#endif
|
#include "network.h"
Octree::Octree()
{
m_ABC[0] = Vector(1,0,0);
m_ABC[1] = Vector(0,1,0);
m_ABC[2] = Vector(0,0,1);
pm_Head = new Node();
InitializeOctree();
}
Node::Node()
{
p_Parent = NULL;
pm_Children = NULL;
pm_Objects = NULL;
pm_Neighbors = NULL;
m_Length = 0.0;
m_Depth = 0;
}
Node::~Node()
{
if (pm_Children != NULL)
{
for (unsigned int i=0;i<8; i++)
{
delete *pm_Children[i];
}
}
delete Node;
}
void Node::Print()
{
if (pm_Children != NULL)
{
for (unsigned int i=0;i<8; i++)
{
pm_Children[i]->Print();
}
}
else
{
std::cout << "\nDepth " << m_Depth << std::endl;
for (unsigned int i=0; i<pm_objects->size(); i++)
{
std::cout << "Element " << i << ": " << pm_objects->at(i) << std::endl;
}
}
}
bool Node::Threshold(vector<Point>& objects)
{
if ((object.size() < MAXOBJECTSPERNODE) || m_Depth > MAXOCTREEDEPTH || m_Length > MINBOXSIZE)
{
return true;
}
return false;
}
Node* Node::OctreeConstruct(vector<Point>& objects)
{
if (Threshold(objects) == true)
{
pm_Children = NULL;
m_Objects = new vector<Point>(objects.begin(),objects.end());
}
else //Threshold condition is not satisfied
{
InitializeChildren();
for (unsigned int i=0; i<8; i++) //For each octant reinvoke octree
{
vector<Point> subset_Objects;
for (unsigned int j=0; j<objects.size(); j++)
{
if (Subset(objects[j]) == true)
{
subset_Objects.push_back(objects[j]);
}
}
pm_Children[i]->OctreeConstruct(subset_Objects);
}
}
}
Node* Node::InitializeChildren()
{
pm_Children = new Node* [8];
pm_Neighbors = new Node* [26];
for (unsigned int i=0; i<8; i++)
{
pm_Children[i] = new Node();
pm_Children[i]->p_Parent = this;
pm_Children[i]->m_Depth = m_Depth + 1;
pm_Children[i]->m_Length = 0.5 * m_Length;
}
//Now I will add all node specific information Eg. Location, and pointers which will significantly speed up the code
double delta_h = 0.5 * m_Length;
for (unsinged int i=0; i<8; i++)
{
switch(i)
{
case 0:
pm_Children[i]->m_ABC = m_ABC + Point(delta_h,-delta_h,delta_h);
pm_Children[i]->pm_Neighbors[0] = pm_Neighbors[0]; //U
pm_Children[i]->pm_Neighbors[1] = pm_Children[4]; //D
pm_Children[i]->pm_Neighbors[2] = pm_Neighbors[2]; //L
pm_Children[i]->pm_Neighbors[3] = pm_Children[2]; //R
pm_Children[i]->pm_Neighbors[4] = pm_Neighbors[4]; //F
pm_Children[i]->pm_Neighbors[5] = pm_Children[1]; //B
pm_Children[i]->pm_Neighbors[6] = pm_Neighbors[6]; //UL
pm_Children[i]->pm_Neighbors[7] = pm_Neighbors[0]; //UR
pm_Children[i]->pm_Neighbors[8] = pm_Neighbors[8]; //UF
pm_Children[i]->pm_Neighbors[9] = pm_Neighbors[0]; //UB
pm_Children[i]->pm_Neighbors[10] = pm_Neighbors[2]; //DL
pm_Children[i]->pm_Neighbors[11] = pm_Children[6]; //DR
pm_Children[i]->pm_Neighbors[12] = pm_Neighbors[4]; //DF
pm_Children[i]->pm_Neighbors[13] = pm_Children[5]; //DB
pm_Children[i]->pm_Neighbors[14] = pm_Neighbors[14]; //LF
pm_Children[i]->pm_Neighbors[15] = pm_Neighbors[2]; //LB
pm_Children[i]->pm_Neighbors[16] = pm_Neighbors[4]; //RF
pm_Children[i]->pm_Neighbors[17] = pm_Children[3]; //RB
pm_Children[i]->pm_Neighbors[18] = pm_Neighbors[18]; //ULF
pm_Children[i]->pm_Neighbors[19] = pm_Neighbors[6]; //ULB
pm_Children[i]->pm_Neighbors[20] = pm_Neighbors[8]; //URF
pm_Children[i]->pm_Neighbors[21] = pm_Neighbors[0]; //URB
pm_Children[i]->pm_Neighbors[22] = pm_Neighbors[14]; //DLF
pm_Children[i]->pm_Neighbors[23] = pm_Neighbors[2]; //DLB
pm_Children[i]->pm_Neighbors[24] = pm_Neighbors[4]; //DRF
pm_Children[i]->pm_Neighbors[25] = pm_Children[7]; //DRB
break;
case 1:
pm_Children[i]->m_ABC = m_ABC + Point-(delta_h,-delta_h,delta_h);
pm_Children[i]->pm_Neighbors[0] = pm_Neighbors[0]; //U
pm_Children[i]->pm_Neighbors[1] = pm_Children[5]; //D
pm_Children[i]->pm_Neighbors[2] = pm_Neighbors[2]; //L
pm_Children[i]->pm_Neighbors[3] = pm_Children[3]; //R
pm_Children[i]->pm_Neighbors[4] = pm_Children[0]; //F
pm_Children[i]->pm_Neighbors[5] = pm_Neighbors[5]; //B
pm_Children[i]->pm_Neighbors[6] = pm_Neighbors[6]; //UL
pm_Children[i]->pm_Neighbors[7] = pm_Neighbors[0]; //UR
pm_Children[i]->pm_Neighbors[8] = pm_Neighbors[0]; //UF
pm_Children[i]->pm_Neighbors[9] = pm_Neighbors[9]; //UB
pm_Children[i]->pm_Neighbors[10] = pm_Neighbors[2]; //DL
pm_Children[i]->pm_Neighbors[11] = pm_Children[7]; //DR
pm_Children[i]->pm_Neighbors[12] = pm_Children[4]; //DF
pm_Children[i]->pm_Neighbors[13] = pm_Neighbors[5]; //DB
pm_Children[i]->pm_Neighbors[14] = pm_Neighbors[2]; //LF
pm_Children[i]->pm_Neighbors[15] = pm_Neighbors[15]; //LB
pm_Children[i]->pm_Neighbors[16] = pm_Children[2]; //RF
pm_Children[i]->pm_Neighbors[17] = pm_Neighbors[5]; //RB
pm_Children[i]->pm_Neighbors[18] = pm_Neighbors[6]; //ULF
pm_Children[i]->pm_Neighbors[19] = pm_Neighbors[19]; //ULB
pm_Children[i]->pm_Neighbors[20] = pm_Neighbors[0]; //URF
pm_Children[i]->pm_Neighbors[21] = pm_Neighbors[9]; //URB
pm_Children[i]->pm_Neighbors[22] = pm_Neighbors[2]; //DLF
pm_Children[i]->pm_Neighbors[23] = pm_Neighbors[15]; //DLB
pm_Children[i]->pm_Neighbors[24] = pm_Children[6]; //DRF
pm_Children[i]->pm_Neighbors[25] = pm_Neighbors[5]; //DRB
break;
case 2:
pm_Children[i]->m_ABC = m_ABC + Point(delta_h,delta_h,delta_h);
pm_Children[i]->pm_Neighbors[0] = pm_Neighbors[0]; //U
pm_Children[i]->pm_Neighbors[1] = pm_Children[6]; //D
pm_Children[i]->pm_Neighbors[2] = pm_Children[0]; //L
pm_Children[i]->pm_Neighbors[3] = pm_Neighbors[3]; //R
pm_Children[i]->pm_Neighbors[4] = pm_Neighbors[4]; //F
pm_Children[i]->pm_Neighbors[5] = pm_Children[3]; //B
pm_Children[i]->pm_Neighbors[6] = pm_Neighbors[0]; //UL
pm_Children[i]->pm_Neighbors[7] = pm_Neighbors[7]; //UR
pm_Children[i]->pm_Neighbors[8] = pm_Neighbors[8]; //UF
pm_Children[i]->pm_Neighbors[9] = pm_Neighbors[0]; //UB
pm_Children[i]->pm_Neighbors[10] = pm_Children[4]; //DL
pm_Children[i]->pm_Neighbors[11] = pm_Neighbors[3]; //DR
pm_Children[i]->pm_Neighbors[12] = pm_Neighbors[4]; //DF
pm_Children[i]->pm_Neighbors[13] = pm_Children[7]; //DB
pm_Children[i]->pm_Neighbors[14] = pm_Neighbors[4]; //LF
pm_Children[i]->pm_Neighbors[15] = pm_Children[1]; //LB
pm_Children[i]->pm_Neighbors[16] = pm_Neighbors[16]; //RF
pm_Children[i]->pm_Neighbors[17] = pm_Neighbors[3]; //RB
pm_Children[i]->pm_Neighbors[18] = pm_Neighbors[8]; //ULF
pm_Children[i]->pm_Neighbors[19] = pm_Neighbors[0]; //ULB
pm_Children[i]->pm_Neighbors[20] = pm_Neighbors[20]; //URF
pm_Children[i]->pm_Neighbors[21] = pm_Neighbors[7]; //URB
pm_Children[i]->pm_Neighbors[22] = pm_Neighbors[4]; //DLF
pm_Children[i]->pm_Neighbors[23] =pm_Children[5]; //DLB
pm_Children[i]->pm_Neighbors[24] = pm_Neighbors[16]; //DRF
pm_Children[i]->pm_Neighbors[25] = pm_Neighbors[3]; //DRB
break;
case 3:
pm_Children[i]->m_ABC = m_ABC + Point(-delta_h,delta_h,delta_h);
pm_Children[i]->pm_Neighbors[0] = pm_Neighbors[0]; //U
pm_Children[i]->pm_Neighbors[1] = pm_Children[7]; //D
pm_Children[i]->pm_Neighbors[2] = pm_Children[1]; //L
pm_Children[i]->pm_Neighbors[3] = pm_Neighbors[3]; //R
pm_Children[i]->pm_Neighbors[4] = pm_Children[2]; //F
pm_Children[i]->pm_Neighbors[5] = pm_Neighbors[5]; //B
pm_Children[i]->pm_Neighbors[6] = pm_Neighbors[0]; //UL
pm_Children[i]->pm_Neighbors[7] = pm_Neighbors[7]; //UR
pm_Children[i]->pm_Neighbors[8] = pm_Neighbors[0]; //UF
pm_Children[i]->pm_Neighbors[9] = pm_Neighbors[9]; //UB
pm_Children[i]->pm_Neighbors[10] = pm_Children[5]; //DL
pm_Children[i]->pm_Neighbors[11] = pm_Neighbors[3]; //DR
pm_Children[i]->pm_Neighbors[12] = pm_Children[6]; //DF
pm_Children[i]->pm_Neighbors[13] = pm_Neighbors[5]; //DB
pm_Children[i]->pm_Neighbors[14] = pm_Children[0]; //LF
pm_Children[i]->pm_Neighbors[15] = pm_Neighbors[5]; //LB
pm_Children[i]->pm_Neighbors[16] = pm_Neighbors[3]; //RF
pm_Children[i]->pm_Neighbors[17] = pm_Neighbors[17]; //RB
pm_Children[i]->pm_Neighbors[18] = pm_Neighbors[0]; //ULF
pm_Children[i]->pm_Neighbors[19] = pm_Neighbors[9]; //ULB
pm_Children[i]->pm_Neighbors[20] = pm_Neighbors[7]; //URF
pm_Children[i]->pm_Neighbors[21] = pm_Neighbors[21]; //URB
pm_Children[i]->pm_Neighbors[22] = pm_Children[4]; //DLF
pm_Children[i]->pm_Neighbors[23] = pm_Neighbors[5]; //DLB
pm_Children[i]->pm_Neighbors[24] = pm_Neighbors[3]; //DRF
pm_Children[i]->pm_Neighbors[25] = pm_Neighbors[17]; //DRB
break;
case 4:
pm_Children[i]->m_ABC = m_ABC + Point(delta_h,-delta_h,delta_h);
pm_Children[i]->pm_Neighbors[0] = pm_Children[0]; //U
pm_Children[i]->pm_Neighbors[1] = pm_Neighbors[1]; //D
pm_Children[i]->pm_Neighbors[2] = pm_Neighbors[2]; //L
pm_Children[i]->pm_Neighbors[3] = pm_Children[6]; //R
pm_Children[i]->pm_Neighbors[4] = pm_Neighbors[4]; //F
pm_Children[i]->pm_Neighbors[5] = pm_Children[5]; //B
pm_Children[i]->pm_Neighbors[6] = pm_Neighbors[2]; //UL
pm_Children[i]->pm_Neighbors[7] = pm_Children[2]; //UR
pm_Children[i]->pm_Neighbors[8] = pm_Neighbors[4]; //UF
pm_Children[i]->pm_Neighbors[9] = pm_Children[1]; //UB
pm_Children[i]->pm_Neighbors[10] = pm_Neighbors[10]; //DL
pm_Children[i]->pm_Neighbors[11] = pm_Neighbors[1]; //DR
pm_Children[i]->pm_Neighbors[12] = pm_Neighbors[12]; //DF
pm_Children[i]->pm_Neighbors[13] = pm_Neighbors[1]; //DB
pm_Children[i]->pm_Neighbors[14] = pm_Neighbors[14]; //LF
pm_Children[i]->pm_Neighbors[15] = pm_Neighbors[2]; //LB
pm_Children[i]->pm_Neighbors[16] = pm_Neighbors[4]; //RF
pm_Children[i]->pm_Neighbors[17] = pm_Children[7]; //RB
pm_Children[i]->pm_Neighbors[18] = pm_Neighbors[14]; //ULF
pm_Children[i]->pm_Neighbors[19] = pm_Neighbors[2]; //ULB
pm_Children[i]->pm_Neighbors[20] = pm_Neighbors[4]; //URF
pm_Children[i]->pm_Neighbors[21] = pm_Children[3]; //URB
pm_Children[i]->pm_Neighbors[22] = pm_Neighbors[22]; //DLF
pm_Children[i]->pm_Neighbors[23] = pm_Neighbors[10]; //DLB
pm_Children[i]->pm_Neighbors[24] = pm_Neighbors[12]; //DRF
pm_Children[i]->pm_Neighbors[25] = pm_Neighbors[1]; //DRB
break;
case 5:
pm_Children[i]->m_ABC = m_ABC + Point(-delta_h,-delta_h,delta_h);
pm_Children[i]->pm_Neighbors[0] = pm_Children[1]; //U
pm_Children[i]->pm_Neighbors[1] = pm_Neighbors[1]; //D
pm_Children[i]->pm_Neighbors[2] = pm_Neighbors[2]; //L
pm_Children[i]->pm_Neighbors[3] = pm_Children[7]; //R
pm_Children[i]->pm_Neighbors[4] = pm_Children[4]; //F
pm_Children[i]->pm_Neighbors[5] = pm_Neighbors[5]; //B
pm_Children[i]->pm_Neighbors[6] = pm_Neighbors[2]; //UL
pm_Children[i]->pm_Neighbors[7] = pm_Children[3]; //UR
pm_Children[i]->pm_Neighbors[8] = pm_Children[0]; //UF
pm_Children[i]->pm_Neighbors[9] = pm_Neighbors[5]; //UB
pm_Children[i]->pm_Neighbors[10] = pm_Neighbors[10]; //DL
pm_Children[i]->pm_Neighbors[11] = pm_Neighbors[1]; //DR
pm_Children[i]->pm_Neighbors[12] = pm_Neighbors[1]; //DF
pm_Children[i]->pm_Neighbors[13] = pm_Neighbors[13]; //DB
pm_Children[i]->pm_Neighbors[14] = pm_Neighbors[2]; //LF
pm_Children[i]->pm_Neighbors[15] = pm_Neighbors[15]; //LB
pm_Children[i]->pm_Neighbors[16] = pm_Children[6]; //RF
pm_Children[i]->pm_Neighbors[17] = pm_Neighbors[5]; //RB
pm_Children[i]->pm_Neighbors[18] = pm_Neighbors[2]; //ULF
pm_Children[i]->pm_Neighbors[19] = pm_Neighbors[15]; //ULB
pm_Children[i]->pm_Neighbors[20] = pm_Children[2]; //URF
pm_Children[i]->pm_Neighbors[21] = pm_Neighbors[5]; //URB
pm_Children[i]->pm_Neighbors[22] = pm_Neighbors[10]; //DLF
pm_Children[i]->pm_Neighbors[23] = pm_Neighbors[23]; //DLB
pm_Children[i]->pm_Neighbors[24] = pm_Neighbors[1]; //DRF
pm_Children[i]->pm_Neighbors[25] = pm_Neighbors[13]; //DRB
break;
case 6:
pm_Children[i]->m_ABC = m_ABC + Point(delta_h,delta_h,delta_h);
pm_Children[i]->pm_Neighbors[0] = pm_Children[2]; //U
pm_Children[i]->pm_Neighbors[1] = pm_Neighbors[1]; //D
pm_Children[i]->pm_Neighbors[2] = pm_Children[4]; //L
pm_Children[i]->pm_Neighbors[3] = pm_Neighbors[3]; //R
pm_Children[i]->pm_Neighbors[4] = pm_Neighbors[4]; //F
pm_Children[i]->pm_Neighbors[5] = pm_Children[7]; //B
pm_Children[i]->pm_Neighbors[6] = pm_Children[0]; //UL
pm_Children[i]->pm_Neighbors[7] = pm_Neighbors[3]; //UR
pm_Children[i]->pm_Neighbors[8] = pm_Neighbors[4]; //UF
pm_Children[i]->pm_Neighbors[9] = pm_Children[3]; //UB
pm_Children[i]->pm_Neighbors[10] = pm_Neighbors[1]; //DL
pm_Children[i]->pm_Neighbors[11] = pm_Neighbors[11]; //DR
pm_Children[i]->pm_Neighbors[12] = pm_Neighbors[12]; //DF
pm_Children[i]->pm_Neighbors[13] = pm_Neighbors[1]; //DB
pm_Children[i]->pm_Neighbors[14] = pm_Neighbors[4]; //LF
pm_Children[i]->pm_Neighbors[15] = pm_Children[5]; //LB
pm_Children[i]->pm_Neighbors[16] = pm_Neighbors[16]; //RF
pm_Children[i]->pm_Neighbors[17] = pm_Neighbors[3]; //RB
pm_Children[i]->pm_Neighbors[18] = pm_Neighbors[4]; //ULF
pm_Children[i]->pm_Neighbors[19] = pm_Children[1]; //ULB
pm_Children[i]->pm_Neighbors[20] = pm_Neighbors[16]; //URF
pm_Children[i]->pm_Neighbors[21] = pm_Neighbors[3]; //URB
pm_Children[i]->pm_Neighbors[22] = pm_Neighbors[12]; //DLF
pm_Children[i]->pm_Neighbors[23] = pm_Neighbors[1]; //DLB
pm_Children[i]->pm_Neighbors[24] = pm_Neighbors[24]; //DRF
pm_Children[i]->pm_Neighbors[25] = pm_Neighbors[11]; //DRB
break;
case 7:
pm_Children[i]->m_ABC = m_ABC + Point(-delta_h,delta_h,delta_h);
pm_Children[i]->pm_Neighbors[0] = pm_Children[3]; //U
pm_Children[i]->pm_Neighbors[1] = pm_Neighbors[1]; //D
pm_Children[i]->pm_Neighbors[2] = pm_Children[5]; //L
pm_Children[i]->pm_Neighbors[3] = pm_Neighbors[3]; //R
pm_Children[i]->pm_Neighbors[4] = pm_Children[6]; //F
pm_Children[i]->pm_Neighbors[5] = pm_Neighbors[5]; //B
pm_Children[i]->pm_Neighbors[6] = pm_Children[1]; //UL
pm_Children[i]->pm_Neighbors[7] = pm_Neighbors[3]; //UR
pm_Children[i]->pm_Neighbors[8] = pm_Children[2]; //UF
pm_Children[i]->pm_Neighbors[9] = pm_Neighbors[5]; //UB
pm_Children[i]->pm_Neighbors[10] = pm_Neighbors[1]; //DL
pm_Children[i]->pm_Neighbors[11] = pm_Neighbors[11]; //DR
pm_Children[i]->pm_Neighbors[12] = pm_Neighbors[1]; //DF
pm_Children[i]->pm_Neighbors[13] = pm_Neighbors[13]; //DB
pm_Children[i]->pm_Neighbors[14] = pm_Children[4]; //LF
pm_Children[i]->pm_Neighbors[15] = pm_Neighbors[5]; //LB
pm_Children[i]->pm_Neighbors[16] = pm_Neighbors[3]; //RF
pm_Children[i]->pm_Neighbors[17] = pm_Neighbors[17]; //RB
pm_Children[i]->pm_Neighbors[18] = pm_Children[0]; //ULF
pm_Children[i]->pm_Neighbors[19] = pm_Neighbors[5]; //ULB
pm_Children[i]->pm_Neighbors[20] = pm_Neighbors[3]; //URF
pm_Children[i]->pm_Neighbors[21] = pm_Neighbors[17]; //URB
pm_Children[i]->pm_Neighbors[22] = pm_Neighbors[1]; //DLF
pm_Children[i]->pm_Neighbors[23] = pm_Neighbors[13]; //DLB
pm_Children[i]->pm_Neighbors[24] = pm_Neighbors[11]; //DRF
pm_Children[i]->pm_Neighbors[25] = pm_Neighbors[25]; //DRB
break;
}
}
}
bool Node::Subset(Point object)
{
//If the center lies within the cube then it is a member
if ( m_ABC[0]+m_Length > object[0] && m_ABC[0]-m_Length < object[0])
{
if ( m_ABC[1]+m_Length > object[1] && m_ABC[1]-m_Length < object[1])
{
if ( m_ABC[2]+m_Length > object[2] && m_ABC[2]-m_Length < object[2])
{
return true;
}
}
}
return false;
}
bool Node::Subset(Sphere object)
{
//If the center lies within the cube then it is a member (Of course this needs to be Extended
if ( m_ABC[0]+m_Length > object.center[0] && m_ABC[0]-m_Length < object.center[0])
{
if ( m_ABC[1]+m_Length > object.center[1] && m_ABC[1]-m_Length < object.center[1])
{
if ( m_ABC[2]+m_Length > object.center[2] && m_ABC[2]-m_Length < object.center[2])
{
return true;
}
}
}
return false;
}
|
#include "ICamera.h"
namespace trview
{
ICamera::~ICamera()
{
}
}
|
#include <string>
#include "envoy/extensions/filters/http/set_metadata/v3/set_metadata.pb.h"
#include "envoy/extensions/filters/http/set_metadata/v3/set_metadata.pb.validate.h"
#include "extensions/filters/http/set_metadata/config.h"
#include "extensions/filters/http/set_metadata/set_metadata_filter.h"
#include "test/mocks/server/factory_context.h"
#include "test/mocks/server/instance.h"
#include "test/test_common/utility.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace SetMetadataFilter {
using SetMetadataProtoConfig = envoy::extensions::filters::http::set_metadata::v3::Config;
TEST(SetMetadataFilterConfigTest, SimpleConfig) {
const std::string yaml = R"EOF(
metadata_namespace: thenamespace
value:
mynumber: 20
mylist: ["b"]
tags:
mytag1: 1
)EOF";
SetMetadataProtoConfig proto_config;
TestUtility::loadFromYamlAndValidate(yaml, proto_config);
testing::NiceMock<Server::Configuration::MockFactoryContext> context;
SetMetadataConfig factory;
Http::FilterFactoryCb cb = factory.createFilterFactoryFromProto(proto_config, "stats", context);
Http::MockFilterChainFactoryCallbacks filter_callbacks;
EXPECT_CALL(filter_callbacks, addStreamDecoderFilter(_));
cb(filter_callbacks);
}
} // namespace SetMetadataFilter
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy
|
/*
* 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/codebuild/model/DeleteWebhookResult.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::CodeBuild::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
DeleteWebhookResult::DeleteWebhookResult()
{
}
DeleteWebhookResult::DeleteWebhookResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
DeleteWebhookResult& DeleteWebhookResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
AWS_UNREFERENCED_PARAM(result);
return *this;
}
|
/*This file is part of the FEBio Studio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio-Studio.txt for details.
Copyright (c) 2020 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
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 "stdafx.h"
#include "DlgDetachSelection.h"
#include <QLineEdit>
#include <QFormLayout>
#include <QBoxLayout>
#include <QDialogButtonBox>
#include <QMessageBox>
class Ui::CDlgDetachSelection
{
public:
QLineEdit *name;
public:
void setup(QWidget* w)
{
QFormLayout* form = new QFormLayout;
form->addRow("Name:", name = new QLineEdit);
QVBoxLayout* l = new QVBoxLayout;
l->addLayout(form);
QDialogButtonBox* bb = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
l->addWidget(bb);
w->setLayout(l);
QObject::connect(bb, SIGNAL(accepted()), w, SLOT(accept()));
QObject::connect(bb, SIGNAL(rejected()), w, SLOT(reject()));
}
};
CDlgDetachSelection::CDlgDetachSelection(QWidget* parent) : QDialog(parent), ui(new Ui::CDlgDetachSelection)
{
ui->setup(this);
static int n = 1;
QString newName = QString("Detached%1").arg(n++);
ui->name->setText(newName);
}
void CDlgDetachSelection::accept()
{
QString name = getName();
if (name.isEmpty())
{
QMessageBox::critical(this, "Detach Selection", "Please enter a valid name.");
}
else QDialog::accept();
}
QString CDlgDetachSelection::getName()
{
return ui->name->text();
}
class Ui::CDlgExtractSelection
{
public:
QLineEdit *name;
public:
void setup(QWidget* w)
{
QFormLayout* form = new QFormLayout;
form->addRow("Name:", name = new QLineEdit);
QVBoxLayout* l = new QVBoxLayout;
l->addLayout(form);
QDialogButtonBox* bb = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
l->addWidget(bb);
w->setLayout(l);
QObject::connect(bb, SIGNAL(accepted()), w, SLOT(accept()));
QObject::connect(bb, SIGNAL(rejected()), w, SLOT(reject()));
}
};
CDlgExtractSelection::CDlgExtractSelection(QWidget* parent) : QDialog(parent), ui(new Ui::CDlgExtractSelection)
{
ui->setup(this);
static int n = 1;
QString newName = QString("Extracted%1").arg(n++);
ui->name->setText(newName);
}
void CDlgExtractSelection::accept()
{
QString name = getName();
if (name.isEmpty())
{
QMessageBox::critical(this, "Extract Selection", "Please enter a valid name.");
}
else QDialog::accept();
}
QString CDlgExtractSelection::getName()
{
return ui->name->text();
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2020 The Samcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <logging.h>
#include <util/threadnames.h>
#include <util/string.h>
#include <util/time.h>
#include <mutex>
const char * const DEFAULT_DEBUGLOGFILE = "debug.log";
BCLog::Logger& LogInstance()
{
/**
* NOTE: the logger instances is leaked on exit. This is ugly, but will be
* cleaned up by the OS/libc. Defining a logger as a global object doesn't work
* since the order of destruction of static/global objects is undefined.
* Consider if the logger gets destroyed, and then some later destructor calls
* LogPrintf, maybe indirectly, and you get a core dump at shutdown trying to
* access the logger. When the shutdown sequence is fully audited and tested,
* explicit destruction of these objects can be implemented by changing this
* from a raw pointer to a std::unique_ptr.
* Since the ~Logger() destructor is never called, the Logger class and all
* its subclasses must have implicitly-defined destructors.
*
* This method of initialization was originally introduced in
* ee3374234c60aba2cc4c5cd5cac1c0aefc2d817c.
*/
static BCLog::Logger* g_logger{new BCLog::Logger()};
return *g_logger;
}
bool fLogIPs = DEFAULT_LOGIPS;
static int FileWriteStr(const std::string &str, FILE *fp)
{
return fwrite(str.data(), 1, str.size(), fp);
}
bool BCLog::Logger::StartLogging()
{
StdLockGuard scoped_lock(m_cs);
assert(m_buffering);
assert(m_fileout == nullptr);
if (m_print_to_file) {
assert(!m_file_path.empty());
m_fileout = fsbridge::fopen(m_file_path, "a");
if (!m_fileout) {
return false;
}
setbuf(m_fileout, nullptr); // unbuffered
// Add newlines to the logfile to distinguish this execution from the
// last one.
FileWriteStr("\n\n\n\n\n", m_fileout);
}
// dump buffered messages from before we opened the log
m_buffering = false;
while (!m_msgs_before_open.empty()) {
const std::string& s = m_msgs_before_open.front();
if (m_print_to_file) FileWriteStr(s, m_fileout);
if (m_print_to_console) fwrite(s.data(), 1, s.size(), stdout);
for (const auto& cb : m_print_callbacks) {
cb(s);
}
m_msgs_before_open.pop_front();
}
if (m_print_to_console) fflush(stdout);
return true;
}
void BCLog::Logger::DisconnectTestLogger()
{
StdLockGuard scoped_lock(m_cs);
m_buffering = true;
if (m_fileout != nullptr) fclose(m_fileout);
m_fileout = nullptr;
m_print_callbacks.clear();
}
void BCLog::Logger::EnableCategory(BCLog::LogFlags flag)
{
m_categories |= flag;
}
bool BCLog::Logger::EnableCategory(const std::string& str)
{
BCLog::LogFlags flag;
if (!GetLogCategory(flag, str)) return false;
EnableCategory(flag);
return true;
}
void BCLog::Logger::DisableCategory(BCLog::LogFlags flag)
{
m_categories &= ~flag;
}
bool BCLog::Logger::DisableCategory(const std::string& str)
{
BCLog::LogFlags flag;
if (!GetLogCategory(flag, str)) return false;
DisableCategory(flag);
return true;
}
bool BCLog::Logger::WillLogCategory(BCLog::LogFlags category) const
{
return (m_categories.load(std::memory_order_relaxed) & category) != 0;
}
bool BCLog::Logger::DefaultShrinkDebugFile() const
{
return m_categories == BCLog::NONE;
}
struct CLogCategoryDesc
{
BCLog::LogFlags flag;
std::string category;
};
const CLogCategoryDesc LogCategories[] =
{
{BCLog::NONE, "0"},
{BCLog::NONE, "none"},
{BCLog::NET, "net"},
{BCLog::TOR, "tor"},
{BCLog::MEMPOOL, "mempool"},
{BCLog::HTTP, "http"},
{BCLog::BENCH, "bench"},
{BCLog::ZMQ, "zmq"},
{BCLog::WALLETDB, "walletdb"},
{BCLog::RPC, "rpc"},
{BCLog::ESTIMATEFEE, "estimatefee"},
{BCLog::ADDRMAN, "addrman"},
{BCLog::SELECTCOINS, "selectcoins"},
{BCLog::REINDEX, "reindex"},
{BCLog::CMPCTBLOCK, "cmpctblock"},
{BCLog::RAND, "rand"},
{BCLog::PRUNE, "prune"},
{BCLog::PROXY, "proxy"},
{BCLog::MEMPOOLREJ, "mempoolrej"},
{BCLog::LIBEVENT, "libevent"},
{BCLog::COINDB, "coindb"},
{BCLog::QT, "qt"},
{BCLog::LEVELDB, "leveldb"},
{BCLog::VALIDATION, "validation"},
{BCLog::I2P, "i2p"},
{BCLog::IPC, "ipc"},
{BCLog::ALL, "1"},
{BCLog::ALL, "all"},
};
bool GetLogCategory(BCLog::LogFlags& flag, const std::string& str)
{
if (str == "") {
flag = BCLog::ALL;
return true;
}
for (const CLogCategoryDesc& category_desc : LogCategories) {
if (category_desc.category == str) {
flag = category_desc.flag;
return true;
}
}
return false;
}
std::vector<LogCategory> BCLog::Logger::LogCategoriesList() const
{
std::vector<LogCategory> ret;
for (const CLogCategoryDesc& category_desc : LogCategories) {
// Omit the special cases.
if (category_desc.flag != BCLog::NONE && category_desc.flag != BCLog::ALL) {
LogCategory catActive;
catActive.category = category_desc.category;
catActive.active = WillLogCategory(category_desc.flag);
ret.push_back(catActive);
}
}
return ret;
}
std::string BCLog::Logger::LogTimestampStr(const std::string& str)
{
std::string strStamped;
if (!m_log_timestamps)
return str;
if (m_started_new_line) {
int64_t nTimeMicros = GetTimeMicros();
strStamped = FormatISO8601DateTime(nTimeMicros/1000000);
if (m_log_time_micros) {
strStamped.pop_back();
strStamped += strprintf(".%06dZ", nTimeMicros%1000000);
}
std::chrono::seconds mocktime = GetMockTime();
if (mocktime > 0s) {
strStamped += " (mocktime: " + FormatISO8601DateTime(count_seconds(mocktime)) + ")";
}
strStamped += ' ' + str;
} else
strStamped = str;
return strStamped;
}
namespace BCLog {
/** Belts and suspenders: make sure outgoing log messages don't contain
* potentially suspicious characters, such as terminal control codes.
*
* This escapes control characters except newline ('\n') in C syntax.
* It escapes instead of removes them to still allow for troubleshooting
* issues where they accidentally end up in strings.
*/
std::string LogEscapeMessage(const std::string& str) {
std::string ret;
for (char ch_in : str) {
uint8_t ch = (uint8_t)ch_in;
if ((ch >= 32 || ch == '\n') && ch != '\x7f') {
ret += ch_in;
} else {
ret += strprintf("\\x%02x", ch);
}
}
return ret;
}
}
void BCLog::Logger::LogPrintStr(const std::string& str, const std::string& logging_function, const std::string& source_file, const int source_line)
{
StdLockGuard scoped_lock(m_cs);
std::string str_prefixed = LogEscapeMessage(str);
if (m_log_sourcelocations && m_started_new_line) {
str_prefixed.insert(0, "[" + RemovePrefix(source_file, "./") + ":" + ToString(source_line) + "] [" + logging_function + "] ");
}
if (m_log_threadnames && m_started_new_line) {
str_prefixed.insert(0, "[" + util::ThreadGetInternalName() + "] ");
}
str_prefixed = LogTimestampStr(str_prefixed);
m_started_new_line = !str.empty() && str[str.size()-1] == '\n';
if (m_buffering) {
// buffer if we haven't started logging yet
m_msgs_before_open.push_back(str_prefixed);
return;
}
if (m_print_to_console) {
// print to console
fwrite(str_prefixed.data(), 1, str_prefixed.size(), stdout);
fflush(stdout);
}
for (const auto& cb : m_print_callbacks) {
cb(str_prefixed);
}
if (m_print_to_file) {
assert(m_fileout != nullptr);
// reopen the log file, if requested
if (m_reopen_file) {
m_reopen_file = false;
FILE* new_fileout = fsbridge::fopen(m_file_path, "a");
if (new_fileout) {
setbuf(new_fileout, nullptr); // unbuffered
fclose(m_fileout);
m_fileout = new_fileout;
}
}
FileWriteStr(str_prefixed, m_fileout);
}
}
void BCLog::Logger::ShrinkDebugFile()
{
// Amount of debug.log to save at end when shrinking (must fit in memory)
constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000;
assert(!m_file_path.empty());
// Scroll debug.log if it's getting too big
FILE* file = fsbridge::fopen(m_file_path, "r");
// Special files (e.g. device nodes) may not have a size.
size_t log_size = 0;
try {
log_size = fs::file_size(m_file_path);
} catch (const fs::filesystem_error&) {}
// If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
// trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
if (file && log_size > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10))
{
// Restart the file with some of the end
std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0);
if (fseek(file, -((long)vch.size()), SEEK_END)) {
LogPrintf("Failed to shrink debug log file: fseek(...) failed\n");
fclose(file);
return;
}
int nBytes = fread(vch.data(), 1, vch.size(), file);
fclose(file);
file = fsbridge::fopen(m_file_path, "w");
if (file)
{
fwrite(vch.data(), 1, nBytes, file);
fclose(file);
}
}
else if (file != nullptr)
fclose(file);
}
|
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#include "QueryMultimediaFilesAdd.hpp"
namespace db::multimedia_files::query
{
Add::Add(const MultimediaFilesRecord &record) : Query(Query::Type::Create), record(record)
{}
auto Add::getRecord() const -> MultimediaFilesRecord
{
return record;
}
auto Add::debugInfo() const -> std::string
{
return std::string{"Add"};
}
AddResult::AddResult(bool ret) : ret(ret)
{}
auto AddResult::getResult() const -> bool
{
return ret;
}
auto AddResult::debugInfo() const -> std::string
{
return std::string{"AddResult"};
}
AddOrEdit::AddOrEdit(const MultimediaFilesRecord &record, std::string oldPath)
: Query(Query::Type::Create), record(record), oldPath(oldPath)
{}
auto AddOrEdit::getRecord() const -> MultimediaFilesRecord
{
return record;
}
auto AddOrEdit::getOldPath() const -> std::string
{
return oldPath;
}
auto AddOrEdit::debugInfo() const -> std::string
{
return std::string{"AddOrEdit"};
}
AddOrEditResult::AddOrEditResult(bool ret) : ret(ret)
{}
auto AddOrEditResult::getResult() const -> bool
{
return ret;
}
auto AddOrEditResult::debugInfo() const -> std::string
{
return std::string{"AddResult"};
}
} // namespace db::multimedia_files::query
|
#include "ModuleWindow.h"
#include "ModuleResources.h"
#include "imgui.h"
#include "imgui_impl_sdl.h"
#include "imgui_impl_opengl3.h"
#include "Application.h"
using namespace std;
ModuleWindow::ModuleWindow() {}
ModuleWindow::~ModuleWindow()
{
//Destroy window
SDL_DestroyWindow(window);
}
bool ModuleWindow::Init()
{
cout << "Initializing Module Window..." << endl;
//Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) < 0)
{
cout << "SDL could not initialize! SDL_Error: " << SDL_GetError() << endl;
return false;
}
else //Create window
{
SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
window = SDL_CreateWindow("Pixel Ape Engine", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags);
if (window == NULL)
{
cout << "Window could not be created! SDL_Error: " << SDL_GetError() << endl;
return false;
}
else
{
//Get window surface
//window_surface = SDL_GetWindowSurface(window);
//Fill the surface white
//SDL_FillRect(window_surface, NULL, SDL_MapRGB(window_surface->format, 0xFF, 0xFF, 0xFF));
//Update the surface
//SDL_BlitSurface(App->resources->GetPNG("png_test"), NULL, window_surface, NULL);
//SDL_UpdateWindowSurface(window);
}
}
cout << "Module Window Initialized" << endl;
return true;
}
update_status ModuleWindow::PreUpdate() {
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL2_NewFrame(window);
return update_status::UPDATE_CONTINUE;
}
update_status ModuleWindow::Update() {
return update_status::UPDATE_CONTINUE;
}
update_status ModuleWindow::PostUpdate() {
//Update the surface
//SDL_UpdateWindowSurface(window);
return update_status::UPDATE_CONTINUE;
}
bool ModuleWindow::CleanUp() {
//Destroy window
if (window != NULL)
{
SDL_DestroyWindow(window);
SDL_FreeSurface(window_surface);
}
//Quit SDL subsystems
SDL_Quit();
return true;
}
SDL_Window* ModuleWindow::GetWindow()
{
return window;
}
|
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdint.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netlink/genl/genl.h>
#include <netlink/genl/family.h>
#include <netlink/genl/ctrl.h>
#include <linux/rtnetlink.h>
#include <netpacket/packet.h>
#include <linux/filter.h>
#include <linux/errqueue.h>
#include <linux/pkt_sched.h>
#include <netlink/object-api.h>
#include <netlink/netlink.h>
#include <netlink/socket.h>
#include <netlink-types.h>
#include <net/if.h>
#include "nl80211_copy.h"
#include <ctype.h>
#include "wifi_hal.h"
#include "common.h"
#include "cpp_bindings.h"
#include "qca-vendor.h"
void appendFmt(char *buf, size_t buf_len, int &offset, const char *fmt, ...)
{
va_list params;
va_start(params, fmt);
offset += vsnprintf(buf + offset, buf_len - offset, fmt, params);
va_end(params);
}
#define C2S(x) case x: return #x;
static const char *cmdToString(int cmd)
{
switch (cmd) {
C2S(NL80211_CMD_UNSPEC)
C2S(NL80211_CMD_GET_WIPHY)
C2S(NL80211_CMD_SET_WIPHY)
C2S(NL80211_CMD_NEW_WIPHY)
C2S(NL80211_CMD_DEL_WIPHY)
C2S(NL80211_CMD_GET_INTERFACE)
C2S(NL80211_CMD_SET_INTERFACE)
C2S(NL80211_CMD_NEW_INTERFACE)
C2S(NL80211_CMD_DEL_INTERFACE)
C2S(NL80211_CMD_GET_KEY)
C2S(NL80211_CMD_SET_KEY)
C2S(NL80211_CMD_NEW_KEY)
C2S(NL80211_CMD_DEL_KEY)
C2S(NL80211_CMD_GET_BEACON)
C2S(NL80211_CMD_SET_BEACON)
C2S(NL80211_CMD_START_AP)
C2S(NL80211_CMD_STOP_AP)
C2S(NL80211_CMD_GET_STATION)
C2S(NL80211_CMD_SET_STATION)
C2S(NL80211_CMD_NEW_STATION)
C2S(NL80211_CMD_DEL_STATION)
C2S(NL80211_CMD_GET_MPATH)
C2S(NL80211_CMD_SET_MPATH)
C2S(NL80211_CMD_NEW_MPATH)
C2S(NL80211_CMD_DEL_MPATH)
C2S(NL80211_CMD_SET_BSS)
C2S(NL80211_CMD_SET_REG)
C2S(NL80211_CMD_REQ_SET_REG)
C2S(NL80211_CMD_GET_MESH_CONFIG)
C2S(NL80211_CMD_SET_MESH_CONFIG)
C2S(NL80211_CMD_SET_MGMT_EXTRA_IE)
C2S(NL80211_CMD_GET_REG)
C2S(NL80211_CMD_GET_SCAN)
C2S(NL80211_CMD_TRIGGER_SCAN)
C2S(NL80211_CMD_NEW_SCAN_RESULTS)
C2S(NL80211_CMD_SCAN_ABORTED)
C2S(NL80211_CMD_REG_CHANGE)
C2S(NL80211_CMD_AUTHENTICATE)
C2S(NL80211_CMD_ASSOCIATE)
C2S(NL80211_CMD_DEAUTHENTICATE)
C2S(NL80211_CMD_DISASSOCIATE)
C2S(NL80211_CMD_MICHAEL_MIC_FAILURE)
C2S(NL80211_CMD_REG_BEACON_HINT)
C2S(NL80211_CMD_JOIN_IBSS)
C2S(NL80211_CMD_LEAVE_IBSS)
C2S(NL80211_CMD_TESTMODE)
C2S(NL80211_CMD_CONNECT)
C2S(NL80211_CMD_ROAM)
C2S(NL80211_CMD_DISCONNECT)
C2S(NL80211_CMD_SET_WIPHY_NETNS)
C2S(NL80211_CMD_GET_SURVEY)
C2S(NL80211_CMD_NEW_SURVEY_RESULTS)
C2S(NL80211_CMD_SET_PMKSA)
C2S(NL80211_CMD_DEL_PMKSA)
C2S(NL80211_CMD_FLUSH_PMKSA)
C2S(NL80211_CMD_REMAIN_ON_CHANNEL)
C2S(NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL)
C2S(NL80211_CMD_SET_TX_BITRATE_MASK)
C2S(NL80211_CMD_REGISTER_FRAME)
C2S(NL80211_CMD_FRAME)
C2S(NL80211_CMD_FRAME_TX_STATUS)
C2S(NL80211_CMD_SET_POWER_SAVE)
C2S(NL80211_CMD_GET_POWER_SAVE)
C2S(NL80211_CMD_SET_CQM)
C2S(NL80211_CMD_NOTIFY_CQM)
C2S(NL80211_CMD_SET_CHANNEL)
C2S(NL80211_CMD_SET_WDS_PEER)
C2S(NL80211_CMD_FRAME_WAIT_CANCEL)
C2S(NL80211_CMD_JOIN_MESH)
C2S(NL80211_CMD_LEAVE_MESH)
C2S(NL80211_CMD_UNPROT_DEAUTHENTICATE)
C2S(NL80211_CMD_UNPROT_DISASSOCIATE)
C2S(NL80211_CMD_NEW_PEER_CANDIDATE)
C2S(NL80211_CMD_GET_WOWLAN)
C2S(NL80211_CMD_SET_WOWLAN)
C2S(NL80211_CMD_START_SCHED_SCAN)
C2S(NL80211_CMD_STOP_SCHED_SCAN)
C2S(NL80211_CMD_SCHED_SCAN_RESULTS)
C2S(NL80211_CMD_SCHED_SCAN_STOPPED)
C2S(NL80211_CMD_SET_REKEY_OFFLOAD)
C2S(NL80211_CMD_PMKSA_CANDIDATE)
C2S(NL80211_CMD_TDLS_OPER)
C2S(NL80211_CMD_TDLS_MGMT)
C2S(NL80211_CMD_UNEXPECTED_FRAME)
C2S(NL80211_CMD_PROBE_CLIENT)
C2S(NL80211_CMD_REGISTER_BEACONS)
C2S(NL80211_CMD_UNEXPECTED_4ADDR_FRAME)
C2S(NL80211_CMD_SET_NOACK_MAP)
C2S(NL80211_CMD_CH_SWITCH_NOTIFY)
C2S(NL80211_CMD_START_P2P_DEVICE)
C2S(NL80211_CMD_STOP_P2P_DEVICE)
C2S(NL80211_CMD_CONN_FAILED)
C2S(NL80211_CMD_SET_MCAST_RATE)
C2S(NL80211_CMD_SET_MAC_ACL)
C2S(NL80211_CMD_RADAR_DETECT)
C2S(NL80211_CMD_GET_PROTOCOL_FEATURES)
C2S(NL80211_CMD_UPDATE_FT_IES)
C2S(NL80211_CMD_FT_EVENT)
C2S(NL80211_CMD_CRIT_PROTOCOL_START)
C2S(NL80211_CMD_CRIT_PROTOCOL_STOP)
C2S(NL80211_CMD_GET_COALESCE)
C2S(NL80211_CMD_SET_COALESCE)
C2S(NL80211_CMD_CHANNEL_SWITCH)
C2S(NL80211_CMD_VENDOR)
C2S(NL80211_CMD_SET_QOS_MAP)
default:
return "NL80211_CMD_UNKNOWN";
}
}
const char *attributeToString(int attribute)
{
switch (attribute) {
C2S(NL80211_ATTR_UNSPEC)
C2S(NL80211_ATTR_WIPHY)
C2S(NL80211_ATTR_WIPHY_NAME)
C2S(NL80211_ATTR_IFINDEX)
C2S(NL80211_ATTR_IFNAME)
C2S(NL80211_ATTR_IFTYPE)
C2S(NL80211_ATTR_MAC)
C2S(NL80211_ATTR_KEY_DATA)
C2S(NL80211_ATTR_KEY_IDX)
C2S(NL80211_ATTR_KEY_CIPHER)
C2S(NL80211_ATTR_KEY_SEQ)
C2S(NL80211_ATTR_KEY_DEFAULT)
C2S(NL80211_ATTR_BEACON_INTERVAL)
C2S(NL80211_ATTR_DTIM_PERIOD)
C2S(NL80211_ATTR_BEACON_HEAD)
C2S(NL80211_ATTR_BEACON_TAIL)
C2S(NL80211_ATTR_STA_AID)
C2S(NL80211_ATTR_STA_FLAGS)
C2S(NL80211_ATTR_STA_LISTEN_INTERVAL)
C2S(NL80211_ATTR_STA_SUPPORTED_RATES)
C2S(NL80211_ATTR_STA_VLAN)
C2S(NL80211_ATTR_STA_INFO)
C2S(NL80211_ATTR_WIPHY_BANDS)
C2S(NL80211_ATTR_MNTR_FLAGS)
C2S(NL80211_ATTR_MESH_ID)
C2S(NL80211_ATTR_STA_PLINK_ACTION)
C2S(NL80211_ATTR_MPATH_NEXT_HOP)
C2S(NL80211_ATTR_MPATH_INFO)
C2S(NL80211_ATTR_BSS_CTS_PROT)
C2S(NL80211_ATTR_BSS_SHORT_PREAMBLE)
C2S(NL80211_ATTR_BSS_SHORT_SLOT_TIME)
C2S(NL80211_ATTR_HT_CAPABILITY)
C2S(NL80211_ATTR_SUPPORTED_IFTYPES)
C2S(NL80211_ATTR_REG_ALPHA2)
C2S(NL80211_ATTR_REG_RULES)
C2S(NL80211_ATTR_MESH_CONFIG)
C2S(NL80211_ATTR_BSS_BASIC_RATES)
C2S(NL80211_ATTR_WIPHY_TXQ_PARAMS)
C2S(NL80211_ATTR_WIPHY_FREQ)
C2S(NL80211_ATTR_WIPHY_CHANNEL_TYPE)
C2S(NL80211_ATTR_KEY_DEFAULT_MGMT)
C2S(NL80211_ATTR_MGMT_SUBTYPE)
C2S(NL80211_ATTR_IE)
C2S(NL80211_ATTR_MAX_NUM_SCAN_SSIDS)
C2S(NL80211_ATTR_SCAN_FREQUENCIES)
C2S(NL80211_ATTR_SCAN_SSIDS)
C2S(NL80211_ATTR_GENERATION) /* replaces old SCAN_GENERATION */
C2S(NL80211_ATTR_BSS)
C2S(NL80211_ATTR_REG_INITIATOR)
C2S(NL80211_ATTR_REG_TYPE)
C2S(NL80211_ATTR_SUPPORTED_COMMANDS)
C2S(NL80211_ATTR_FRAME)
C2S(NL80211_ATTR_SSID)
C2S(NL80211_ATTR_AUTH_TYPE)
C2S(NL80211_ATTR_REASON_CODE)
C2S(NL80211_ATTR_KEY_TYPE)
C2S(NL80211_ATTR_MAX_SCAN_IE_LEN)
C2S(NL80211_ATTR_CIPHER_SUITES)
C2S(NL80211_ATTR_FREQ_BEFORE)
C2S(NL80211_ATTR_FREQ_AFTER)
C2S(NL80211_ATTR_FREQ_FIXED)
C2S(NL80211_ATTR_WIPHY_RETRY_SHORT)
C2S(NL80211_ATTR_WIPHY_RETRY_LONG)
C2S(NL80211_ATTR_WIPHY_FRAG_THRESHOLD)
C2S(NL80211_ATTR_WIPHY_RTS_THRESHOLD)
C2S(NL80211_ATTR_TIMED_OUT)
C2S(NL80211_ATTR_USE_MFP)
C2S(NL80211_ATTR_STA_FLAGS2)
C2S(NL80211_ATTR_CONTROL_PORT)
C2S(NL80211_ATTR_TESTDATA)
C2S(NL80211_ATTR_PRIVACY)
C2S(NL80211_ATTR_DISCONNECTED_BY_AP)
C2S(NL80211_ATTR_STATUS_CODE)
C2S(NL80211_ATTR_CIPHER_SUITES_PAIRWISE)
C2S(NL80211_ATTR_CIPHER_SUITE_GROUP)
C2S(NL80211_ATTR_WPA_VERSIONS)
C2S(NL80211_ATTR_AKM_SUITES)
C2S(NL80211_ATTR_REQ_IE)
C2S(NL80211_ATTR_RESP_IE)
C2S(NL80211_ATTR_PREV_BSSID)
C2S(NL80211_ATTR_KEY)
C2S(NL80211_ATTR_KEYS)
C2S(NL80211_ATTR_PID)
C2S(NL80211_ATTR_4ADDR)
C2S(NL80211_ATTR_SURVEY_INFO)
C2S(NL80211_ATTR_PMKID)
C2S(NL80211_ATTR_MAX_NUM_PMKIDS)
C2S(NL80211_ATTR_DURATION)
C2S(NL80211_ATTR_COOKIE)
C2S(NL80211_ATTR_WIPHY_COVERAGE_CLASS)
C2S(NL80211_ATTR_TX_RATES)
C2S(NL80211_ATTR_FRAME_MATCH)
C2S(NL80211_ATTR_ACK)
C2S(NL80211_ATTR_PS_STATE)
C2S(NL80211_ATTR_CQM)
C2S(NL80211_ATTR_LOCAL_STATE_CHANGE)
C2S(NL80211_ATTR_AP_ISOLATE)
C2S(NL80211_ATTR_WIPHY_TX_POWER_SETTING)
C2S(NL80211_ATTR_WIPHY_TX_POWER_LEVEL)
C2S(NL80211_ATTR_TX_FRAME_TYPES)
C2S(NL80211_ATTR_RX_FRAME_TYPES)
C2S(NL80211_ATTR_FRAME_TYPE)
C2S(NL80211_ATTR_CONTROL_PORT_ETHERTYPE)
C2S(NL80211_ATTR_CONTROL_PORT_NO_ENCRYPT)
C2S(NL80211_ATTR_SUPPORT_IBSS_RSN)
C2S(NL80211_ATTR_WIPHY_ANTENNA_TX)
C2S(NL80211_ATTR_WIPHY_ANTENNA_RX)
C2S(NL80211_ATTR_MCAST_RATE)
C2S(NL80211_ATTR_OFFCHANNEL_TX_OK)
C2S(NL80211_ATTR_BSS_HT_OPMODE)
C2S(NL80211_ATTR_KEY_DEFAULT_TYPES)
C2S(NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION)
C2S(NL80211_ATTR_MESH_SETUP)
C2S(NL80211_ATTR_WIPHY_ANTENNA_AVAIL_TX)
C2S(NL80211_ATTR_WIPHY_ANTENNA_AVAIL_RX)
C2S(NL80211_ATTR_SUPPORT_MESH_AUTH)
C2S(NL80211_ATTR_STA_PLINK_STATE)
C2S(NL80211_ATTR_WOWLAN_TRIGGERS)
C2S(NL80211_ATTR_WOWLAN_TRIGGERS_SUPPORTED)
C2S(NL80211_ATTR_SCHED_SCAN_INTERVAL)
C2S(NL80211_ATTR_INTERFACE_COMBINATIONS)
C2S(NL80211_ATTR_SOFTWARE_IFTYPES)
C2S(NL80211_ATTR_REKEY_DATA)
C2S(NL80211_ATTR_MAX_NUM_SCHED_SCAN_SSIDS)
C2S(NL80211_ATTR_MAX_SCHED_SCAN_IE_LEN)
C2S(NL80211_ATTR_SCAN_SUPP_RATES)
C2S(NL80211_ATTR_HIDDEN_SSID)
C2S(NL80211_ATTR_IE_PROBE_RESP)
C2S(NL80211_ATTR_IE_ASSOC_RESP)
C2S(NL80211_ATTR_STA_WME)
C2S(NL80211_ATTR_SUPPORT_AP_UAPSD)
C2S(NL80211_ATTR_ROAM_SUPPORT)
C2S(NL80211_ATTR_SCHED_SCAN_MATCH)
C2S(NL80211_ATTR_MAX_MATCH_SETS)
C2S(NL80211_ATTR_PMKSA_CANDIDATE)
C2S(NL80211_ATTR_TX_NO_CCK_RATE)
C2S(NL80211_ATTR_TDLS_ACTION)
C2S(NL80211_ATTR_TDLS_DIALOG_TOKEN)
C2S(NL80211_ATTR_TDLS_OPERATION)
C2S(NL80211_ATTR_TDLS_SUPPORT)
C2S(NL80211_ATTR_TDLS_EXTERNAL_SETUP)
C2S(NL80211_ATTR_DEVICE_AP_SME)
C2S(NL80211_ATTR_DONT_WAIT_FOR_ACK)
C2S(NL80211_ATTR_FEATURE_FLAGS)
C2S(NL80211_ATTR_PROBE_RESP_OFFLOAD)
C2S(NL80211_ATTR_PROBE_RESP)
C2S(NL80211_ATTR_DFS_REGION)
C2S(NL80211_ATTR_DISABLE_HT)
C2S(NL80211_ATTR_HT_CAPABILITY_MASK)
C2S(NL80211_ATTR_NOACK_MAP)
C2S(NL80211_ATTR_INACTIVITY_TIMEOUT)
C2S(NL80211_ATTR_RX_SIGNAL_DBM)
C2S(NL80211_ATTR_BG_SCAN_PERIOD)
C2S(NL80211_ATTR_WDEV)
C2S(NL80211_ATTR_USER_REG_HINT_TYPE)
C2S(NL80211_ATTR_CONN_FAILED_REASON)
C2S(NL80211_ATTR_SAE_DATA)
C2S(NL80211_ATTR_VHT_CAPABILITY)
C2S(NL80211_ATTR_SCAN_FLAGS)
C2S(NL80211_ATTR_CHANNEL_WIDTH)
C2S(NL80211_ATTR_CENTER_FREQ1)
C2S(NL80211_ATTR_CENTER_FREQ2)
C2S(NL80211_ATTR_P2P_CTWINDOW)
C2S(NL80211_ATTR_P2P_OPPPS)
C2S(NL80211_ATTR_LOCAL_MESH_POWER_MODE)
C2S(NL80211_ATTR_ACL_POLICY)
C2S(NL80211_ATTR_MAC_ADDRS)
C2S(NL80211_ATTR_MAC_ACL_MAX)
C2S(NL80211_ATTR_RADAR_EVENT)
C2S(NL80211_ATTR_EXT_CAPA)
C2S(NL80211_ATTR_EXT_CAPA_MASK)
C2S(NL80211_ATTR_STA_CAPABILITY)
C2S(NL80211_ATTR_STA_EXT_CAPABILITY)
C2S(NL80211_ATTR_PROTOCOL_FEATURES)
C2S(NL80211_ATTR_SPLIT_WIPHY_DUMP)
C2S(NL80211_ATTR_DISABLE_VHT)
C2S(NL80211_ATTR_VHT_CAPABILITY_MASK)
C2S(NL80211_ATTR_MDID)
C2S(NL80211_ATTR_IE_RIC)
C2S(NL80211_ATTR_CRIT_PROT_ID)
C2S(NL80211_ATTR_MAX_CRIT_PROT_DURATION)
C2S(NL80211_ATTR_PEER_AID)
C2S(NL80211_ATTR_COALESCE_RULE)
C2S(NL80211_ATTR_CH_SWITCH_COUNT)
C2S(NL80211_ATTR_CH_SWITCH_BLOCK_TX)
C2S(NL80211_ATTR_CSA_IES)
C2S(NL80211_ATTR_CSA_C_OFF_BEACON)
C2S(NL80211_ATTR_CSA_C_OFF_PRESP)
C2S(NL80211_ATTR_RXMGMT_FLAGS)
C2S(NL80211_ATTR_STA_SUPPORTED_CHANNELS)
C2S(NL80211_ATTR_STA_SUPPORTED_OPER_CLASSES)
C2S(NL80211_ATTR_HANDLE_DFS)
C2S(NL80211_ATTR_SUPPORT_5_MHZ)
C2S(NL80211_ATTR_SUPPORT_10_MHZ)
C2S(NL80211_ATTR_OPMODE_NOTIF)
C2S(NL80211_ATTR_VENDOR_ID)
C2S(NL80211_ATTR_VENDOR_SUBCMD)
C2S(NL80211_ATTR_VENDOR_DATA)
C2S(NL80211_ATTR_VENDOR_EVENTS)
C2S(NL80211_ATTR_QOS_MAP)
default:
return "NL80211_ATTR_UNKNOWN";
}
}
void WifiEvent::log() {
parse();
byte *data = (byte *)genlmsg_attrdata(mHeader, 0);
int len = genlmsg_attrlen(mHeader, 0);
for (int i = 0; i < len; i += 16) {
char line[81];
int linelen = min(16, len - i);
int offset = 0;
appendFmt(line, sizeof(line), offset, "%02x", data[i]);
for (int j = 1; j < linelen; j++) {
appendFmt(line, sizeof(line), offset, " %02x", data[i+j]);
}
for (int j = linelen; j < 16; j++) {
appendFmt(line, sizeof(line), offset, " ");
}
line[23] = '-';
appendFmt(line, sizeof(line), offset, " ");
for (int j = 0; j < linelen; j++) {
if (isprint(data[i+j])) {
appendFmt(line, sizeof(line), offset, "%c", data[i+j]);
} else {
appendFmt(line, sizeof(line), offset, "-");
}
}
}
}
const char *WifiEvent::get_cmdString() {
return cmdToString(get_cmd());
}
int WifiEvent::parse() {
if (mHeader != NULL) {
return WIFI_SUCCESS;
}
mHeader = (genlmsghdr *)nlmsg_data(nlmsg_hdr(mMsg));
int result = nla_parse(mAttributes, NL80211_ATTR_MAX_INTERNAL, genlmsg_attrdata(mHeader, 0),
genlmsg_attrlen(mHeader, 0), NULL);
return result;
}
int WifiRequest::create(int family, uint8_t cmd, int flags, int hdrlen) {
destroy();
mMsg = nlmsg_alloc();
if (mMsg != NULL) {
genlmsg_put(mMsg, /* pid = */ 0, /* seq = */ 0, family,
hdrlen, flags, cmd, /* version = */ 0);
return WIFI_SUCCESS;
} else {
return WIFI_ERROR_OUT_OF_MEMORY;
}
}
int WifiRequest::create(uint32_t id, int subcmd) {
int res = create(NL80211_CMD_VENDOR);
if (res < 0) {
return res;
}
res = put_u32(NL80211_ATTR_VENDOR_ID, id);
if (res < 0) {
return res;
}
res = put_u32(NL80211_ATTR_VENDOR_SUBCMD, subcmd);
if (res < 0) {
return res;
}
if (mIface != -1) {
res = set_iface_id(mIface);
}
return res;
}
static int no_seq_check(struct nl_msg *msg, void *arg)
{
return NL_OK;
}
int WifiCommand::requestResponse() {
int err = create(); /* create the message */
if (err < 0) {
return err;
}
return requestResponse(mMsg);
}
int WifiCommand::requestResponse(WifiRequest& request) {
int err = 0;
struct nl_cb *cb = nl_cb_alloc(NL_CB_DEFAULT);
if (!cb)
goto out;
err = nl_send_auto_complete(mInfo->cmd_sock, request.getMessage()); /* send message */
if (err < 0)
goto out;
err = 1;
nl_cb_set(cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM, no_seq_check, NULL);
nl_cb_err(cb, NL_CB_CUSTOM, error_handler, &err);
nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, finish_handler, &err);
nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ack_handler, &err);
nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, response_handler, this);
while (err > 0) { /* wait for reply */
int res = nl_recvmsgs(mInfo->cmd_sock, cb);
if (res) {
ALOGE("nl80211: %s->nl_recvmsgs failed: %d", __FUNCTION__, res);
}
}
out:
nl_cb_put(cb);
mMsg.destroy();
return err;
}
int WifiCommand::requestEvent(int cmd) {
int res = wifi_register_handler(wifiHandle(), cmd, event_handler, this);
if (res < 0) {
return res;
}
res = create(); /* create the message */
if (res < 0)
goto out;
res = nl_send_auto_complete(mInfo->cmd_sock, mMsg.getMessage()); /* send message */
if (res < 0)
goto out;
res = mCondition.wait();
if (res < 0)
goto out;
out:
wifi_unregister_handler(wifiHandle(), cmd);
return res;
}
int WifiCommand::requestVendorEvent(uint32_t id, int subcmd) {
int res = wifi_register_vendor_handler(wifiHandle(), id, subcmd, event_handler, this);
if (res < 0) {
return res;
}
res = create(); /* create the message */
if (res < 0)
goto out;
res = nl_send_auto_complete(mInfo->cmd_sock, mMsg.getMessage()); /* send message */
if (res < 0)
goto out;
res = mCondition.wait();
if (res < 0)
goto out;
out:
wifi_unregister_vendor_handler(wifiHandle(), id, subcmd);
return res;
}
/* Event handlers */
int WifiCommand::response_handler(struct nl_msg *msg, void *arg) {
WifiCommand *cmd = (WifiCommand *)arg;
WifiEvent reply(msg);
int res = reply.parse();
if (res < 0) {
ALOGE("Failed to parse reply message = %d", res);
return NL_SKIP;
} else {
// reply.log(); /* Don't call log() to avoid excess WiFi HAL logging */
return cmd->handleResponse(reply);
}
}
int WifiCommand::event_handler(struct nl_msg *msg, void *arg) {
WifiCommand *cmd = (WifiCommand *)arg;
WifiEvent event(msg);
int res = event.parse();
if (res < 0) {
ALOGE("Failed to parse event = %d", res);
res = NL_SKIP;
} else {
res = cmd->handleEvent(event);
}
cmd->mCondition.signal();
return res;
}
/* Other event handlers */
int WifiCommand::valid_handler(struct nl_msg *msg, void *arg) {
int *err = (int *)arg;
*err = 0;
return NL_SKIP;
}
int WifiCommand::ack_handler(struct nl_msg *msg, void *arg) {
int *err = (int *)arg;
*err = 0;
return NL_STOP;
}
int WifiCommand::finish_handler(struct nl_msg *msg, void *arg) {
int *ret = (int *)arg;
*ret = 0;
return NL_SKIP;
}
int WifiCommand::error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err, void *arg) {
int *ret = (int *)arg;
*ret = err->error;
return NL_SKIP;
}
WifiVendorCommand::WifiVendorCommand(wifi_handle handle,
wifi_request_id id,
u32 vendor_id,
u32 subcmd)
: WifiCommand(handle, id), mVendor_id(vendor_id), mSubcmd(subcmd),
mVendorData(NULL), mDataLen(0)
{
ALOGV("WifiVendorCommand %p created vendor_id:0x%x subcmd:%u",
this, mVendor_id, mSubcmd);
}
WifiVendorCommand::~WifiVendorCommand()
{
//ALOGV("~WifiVendorCommand %p destroyed", this);
//mVendorData is not destroyed here. Assumption
//is that VendorData is specific to each Vendor and they
//are responsible for owning the same.
}
// Override this method to parse reply and dig out data; save it
// in the corresponding object
int WifiVendorCommand::handleResponse(WifiEvent &reply)
{
struct nlattr **tb = reply.attributes();
struct nlattr *attr = NULL;
struct genlmsghdr *gnlh = reply.header();
if (gnlh->cmd == NL80211_CMD_VENDOR) {
if (tb[NL80211_ATTR_VENDOR_DATA]) {
mVendorData = (char *)nla_data(tb[NL80211_ATTR_VENDOR_DATA]);
mDataLen = nla_len(tb[NL80211_ATTR_VENDOR_DATA]);
}
}
return NL_SKIP;
}
// Override this method to parse event and dig out data;
// save it in the object
int WifiVendorCommand::handleEvent(WifiEvent &event)
{
struct nlattr **tb = event.attributes();
struct nlattr *attr = NULL;
struct genlmsghdr *gnlh = event.header();
if (gnlh->cmd == NL80211_CMD_VENDOR) {
/* Vendor Event */
if (!tb[NL80211_ATTR_VENDOR_ID] ||
!tb[NL80211_ATTR_VENDOR_SUBCMD])
return NL_SKIP;
mVendor_id = nla_get_u32(tb[NL80211_ATTR_VENDOR_ID]);
mSubcmd = nla_get_u32(tb[NL80211_ATTR_VENDOR_SUBCMD]);
ALOGV("%s: Vendor event: vendor_id=0x%x subcmd=%u",
__FUNCTION__, mVendor_id, mSubcmd);
if (tb[NL80211_ATTR_VENDOR_DATA]) {
mVendorData = (char *)nla_data(tb[NL80211_ATTR_VENDOR_DATA]);
mDataLen = nla_len(tb[NL80211_ATTR_VENDOR_DATA]);
ALOGV("%s: Vendor data len received:%d", __FUNCTION__, mDataLen);
hexdump(mVendorData, mDataLen);
}
}
return NL_SKIP;
}
int WifiVendorCommand::create() {
int ifindex;
int ret = mMsg.create(NL80211_CMD_VENDOR, 0, 0);
if (ret < 0) {
return ret;
}
// insert the oui in the msg
ret = mMsg.put_u32(NL80211_ATTR_VENDOR_ID, mVendor_id);
if (ret < 0)
goto out;
// insert the subcmd in the msg
ret = mMsg.put_u32(NL80211_ATTR_VENDOR_SUBCMD, mSubcmd);
if (ret < 0)
goto out;
//Insert the vendor specific data
ret = mMsg.put_bytes(NL80211_ATTR_VENDOR_DATA, mVendorData, mDataLen);
hexdump(mVendorData, mDataLen);
//insert the iface id to be "wlan0"
ifindex = if_nametoindex("wlan0");
mMsg.set_iface_id(ifindex);
out:
return ret;
}
int WifiVendorCommand::requestResponse()
{
return WifiCommand::requestResponse(mMsg);
}
int WifiVendorCommand::requestEvent()
{
int res = requestVendorEvent(mVendor_id, mSubcmd);
return res;
}
int WifiVendorCommand::put_u8(int attribute, uint8_t value)
{
return mMsg.put_u8(attribute, value);
}
int WifiVendorCommand::put_u16(int attribute, uint16_t value)
{
return mMsg.put_u16(attribute, value);
}
int WifiVendorCommand::put_u32(int attribute, uint32_t value)
{
return mMsg.put_u32(attribute, value);
}
int WifiVendorCommand::put_u64(int attribute, uint64_t value)
{
return mMsg.put_u64(attribute, value);
}
int WifiVendorCommand::put_s8(int attribute, s8 value)
{
return mMsg.put_s8(attribute, value);
}
int WifiVendorCommand::put_s16(int attribute, s16 value)
{
return mMsg.put_s16(attribute, value);
}
int WifiVendorCommand::put_s32(int attribute, s32 value) {
return mMsg.put_s32(attribute, value);
}
int WifiVendorCommand::put_s64(int attribute, s64 value)
{
return mMsg.put_s64(attribute, value);
}
u8 WifiVendorCommand::get_u8(const struct nlattr *nla)
{
return mMsg.get_u8(nla);
}
u16 WifiVendorCommand::get_u16(const struct nlattr *nla)
{
return mMsg.get_u16(nla);
}
u32 WifiVendorCommand::get_u32(const struct nlattr *nla)
{
return mMsg.get_u32(nla);
}
u64 WifiVendorCommand::get_u64(const struct nlattr *nla)
{
return mMsg.get_u64(nla);
}
s8 WifiVendorCommand::get_s8(const struct nlattr *nla)
{
return mMsg.get_s8(nla);
}
s16 WifiVendorCommand::get_s16(const struct nlattr *nla)
{
return mMsg.get_s16(nla);
}
s32 WifiVendorCommand::get_s32(const struct nlattr *nla)
{
return mMsg.get_s32(nla);
}
s64 WifiVendorCommand::get_s64(const struct nlattr *nla)
{
return mMsg.get_s64(nla);
}
int WifiVendorCommand::put_string(int attribute, const char *value)
{
return mMsg.put_string(attribute, value);
}
int WifiVendorCommand::put_addr(int attribute, mac_addr value)
{
return mMsg.put_addr(attribute, value);
}
struct nlattr * WifiVendorCommand::attr_start(int attribute)
{
return mMsg.attr_start(attribute);
}
void WifiVendorCommand::attr_end(struct nlattr *attribute)
{
return mMsg.attr_end(attribute);
}
int WifiVendorCommand::set_iface_id(const char* name)
{
unsigned ifindex = if_nametoindex(name);
return mMsg.set_iface_id(ifindex);
}
int WifiVendorCommand::put_bytes(int attribute, const char *data, int len)
{
return mMsg.put_bytes(attribute, data, len);
}
wifi_error WifiVendorCommand::get_mac_addr(struct nlattr **tb_vendor,
int attribute,
mac_addr addr)
{
if (!tb_vendor[attribute]) {
ALOGE("Failed to get attribute : %d", attribute);
return WIFI_ERROR_INVALID_ARGS;
}
if (!addr) {
ALOGE("addr is NULL");
return WIFI_ERROR_INVALID_ARGS;
}
if (nla_len(tb_vendor[attribute]) != sizeof(mac_addr)) {
ALOGE("Invalid mac addr lenght\n");
return WIFI_ERROR_INVALID_ARGS;
}
memcpy(addr, (u8 *)nla_data(tb_vendor[attribute]),
nla_len(tb_vendor[attribute]));
return WIFI_SUCCESS;
}
wifi_error initialize_vendor_cmd(wifi_interface_handle iface,
wifi_request_id id,
u32 subcmd,
WifiVendorCommand **vCommand)
{
int ret = 0;
interface_info *ifaceInfo = getIfaceInfo(iface);
wifi_handle wifiHandle = getWifiHandle(iface);
if (vCommand == NULL) {
ALOGE("%s: Error vCommand NULL", __FUNCTION__);
return WIFI_ERROR_INVALID_ARGS;
}
*vCommand = new WifiVendorCommand(wifiHandle, id,
OUI_QCA,
subcmd);
if (*vCommand == NULL) {
ALOGE("%s: Object creation failed", __FUNCTION__);
return WIFI_ERROR_OUT_OF_MEMORY;
}
/* Create the message */
ret = (*vCommand)->create();
if (ret < 0)
goto cleanup;
ret = (*vCommand)->set_iface_id(ifaceInfo->name);
if (ret < 0)
goto cleanup;
return WIFI_SUCCESS;
cleanup:
delete *vCommand;
return (wifi_error)ret;
}
|
//
// Copyright (c) 2017-2019 the rbfx project.
//
// 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 <EASTL/sort.h>
#include <Urho3D/SystemUI/SystemUI.h>
#include <Urho3D/Core/Context.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Resource/ResourceEvents.h>
#include <Urho3D/IO/FileSystem.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/IO/Log.h>
#include <IconFontCppHeaders/IconsFontAwesome5.h>
#include <ImGui/imgui_stdlib.h>
#include <ImGui/imgui_internal.h>
#include "ResourceBrowser.h"
#include "Widgets.h"
#include "IO/ContentUtilities.h"
namespace Urho3D
{
ResourceBrowserResult ResourceBrowserWidget(const ea::string& resourcePath, const ea::string& cacheDir,
ea::string& path, ea::string& selected, ResourceBrowserFlags flags)
{
struct State
{
bool rescanDirs = true;
bool isEditing = false;
bool wasEditing = false;
bool deletionPending = false;
ea::string editBuffer;
ea::string editStartItem;
ea::vector<ea::string> directories;
ea::vector<ea::string> files;
Timer updateTimer;
std::function<void()> singleClickPending;
};
auto result = RBR_NOOP;
auto systemUI = (SystemUI*)ui::GetIO().UserData;
auto fs = systemUI->GetContext()->GetFileSystem();
auto& state = *ui::GetUIState<State>();
if (!selected.empty() && !ui::IsAnyItemActive() && ui::IsWindowFocused())
{
if (flags & RBF_RENAME_CURRENT)
{
state.isEditing = true;
state.deletionPending = false;
state.editStartItem = selected;
state.editBuffer = RemoveTrailingSlash(selected);
}
if (flags & RBF_DELETE_CURRENT)
{
state.isEditing = false;
state.deletionPending = true;
state.editStartItem = selected;
}
}
if (state.isEditing || state.deletionPending)
{
if (ui::IsKeyReleased(SCANCODE_ESCAPE) || state.editStartItem != selected)
{
state.isEditing = false;
state.deletionPending = false;
}
}
if (state.deletionPending)
{
if (ui::Begin("Delete?", &state.deletionPending))
{
ui::Text("Would you like to delete '%s%s'?", path.c_str(), selected.c_str());
ui::TextUnformatted(ICON_FA_EXCLAMATION_TRIANGLE " This action can not be undone!");
ui::NewLine();
if (ui::Button("Delete Permanently"))
{
using namespace ResourceBrowserDelete;
fs->SendEvent(E_RESOURCEBROWSERDELETE, P_NAME, path + selected);
state.deletionPending = false;
}
}
ui::End();
}
auto moveFileDropTarget = [&](const ea::string& destination) {
if (ui::BeginDragDropTarget())
{
const Variant& dropped = ui::AcceptDragDropVariant("path");
if (dropped.GetType() == VAR_STRING)
{
const ea::string& source = dropped.GetString();
bool isDir = source.ends_with("/");
ea::string destinationName;
if (destination == "..")
destinationName = GetParentPath(path);
else
destinationName = path + destination;
destinationName += GetFileNameAndExtension(RemoveTrailingSlash(source));
if (isDir)
destinationName = AddTrailingSlash(destinationName);
if (source != destinationName)
{
fs->GetContext()->GetCache()->RenameResource(resourcePath + source, resourcePath + destinationName);
state.rescanDirs = true;
}
}
ui::EndDragDropTarget();
}
};
if (!path.empty())
{
switch (ui::DoubleClickSelectable("..", selected == ".."))
{
case 1:
state.singleClickPending = [&]()
{
selected = "..";
};
break;
case 2:
state.singleClickPending = nullptr;
path = GetParentPath(path);
state.rescanDirs = true;
break;
default:
break;
}
moveFileDropTarget("..");
}
auto renameWidget = [&](const ea::string& item, const ea::string& icon) {
if (selected == item && state.isEditing)
{
ui::IdScope idScope("Rename");
ui::TextUnformatted(icon.c_str());
ui::SameLine();
ui::PushStyleVar(ImGuiStyleVar_FramePadding, {0, 0});
ui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0);
if (ui::InputText("", &state.editBuffer, ImGuiInputTextFlags_EnterReturnsTrue))
{
if (selected.ends_with("/"))
state.editBuffer = AddTrailingSlash(state.editBuffer);
if (selected != state.editBuffer)
{
fs->GetContext()->GetCache()->RenameResource(resourcePath + path + selected, resourcePath + path + state.editBuffer);
selected = state.editBuffer;
state.isEditing = false;
state.rescanDirs = true;
}
}
if (!state.wasEditing)
ui::GetCurrentContext()->FocusRequestNextCounterTab = ui::GetCurrentContext()->ActiveId;
ui::PopStyleVar(2);
return true;
}
return false;
};
if (state.updateTimer.GetMSec(false) >= 1000 || state.rescanDirs)
{
state.rescanDirs = false;
state.updateTimer.Reset();
// Find resource files
fs->ScanDir(state.files, resourcePath + path, "", SCAN_FILES, false);
// Remove internal files
for (auto it = state.files.begin(); it != state.files.end();)
{
// Internal files
const ea::string& name = *it;
if (name.ends_with(".asset"))
it = state.files.erase(it);
else
++it;
}
ea::quick_sort(state.files.begin(), state.files.end());
// Find resource dirs
fs->ScanDir(state.directories, resourcePath + path, "", SCAN_DIRS, false);
state.directories.erase_first(".");
state.directories.erase_first("..");
ea::quick_sort(state.directories.begin(), state.directories.end());
for (ea::string& dir : state.directories)
dir = AddTrailingSlash(dir);
}
// Render dirs first
for (const ea::string& item: state.directories)
{
if (!renameWidget(item, ICON_FA_FOLDER))
{
bool isSelected = selected == item;
if (flags & RBF_SCROLL_TO_CURRENT && isSelected)
ui::SetScrollHereY();
switch (ui::DoubleClickSelectable((ICON_FA_FOLDER " " + RemoveTrailingSlash(item)).c_str(), isSelected))
{
case 1:
state.singleClickPending = [&]()
{
selected = item;
result = RBR_ITEM_SELECTED;
};
break;
case 2:
state.singleClickPending = nullptr;
path += AddTrailingSlash(item);
selected.clear();
state.rescanDirs = true;
break;
default:
break;
}
if (ui::IsItemActive())
{
if (ui::BeginDragDropSource())
{
ui::SetDragDropVariant("path", path + item);
// TODO: show actual preview of a resource.
ui::Text("%s%s", path.c_str(), item.c_str());
ui::EndDragDropSource();
}
}
moveFileDropTarget(path + item);
}
}
// Render files after dirs
for (const auto& item: state.files)
{
auto icon = GetFileIcon(item);
if (!renameWidget(item, icon))
{
auto isSelected = selected == item;
if (flags & RBF_SCROLL_TO_CURRENT && isSelected)
ui::SetScrollHereY();
switch (ui::DoubleClickSelectable((icon + " " + item).c_str(), isSelected))
{
case 1:
selected = item;
result = RBR_ITEM_SELECTED;
using namespace ResourceBrowserSelect;
fs->SendEvent(E_RESOURCEBROWSERSELECT, P_NAME, path + selected);
break;
case 2:
result = RBR_ITEM_OPEN;
break;
default:
break;
}
if (ui::IsItemActive())
{
if (ui::BeginDragDropSource())
{
ui::SetDragDropVariant("path", path + item);
// TODO: show actual preview of a resource.
ui::Text("%s%s", path.c_str(), item.c_str());
ui::EndDragDropSource();
}
}
// Render cache items
ea::string cacheItem = GetFileName(item);
ea::string resourceCachePath = cacheDir + path + cacheItem;
if (fs->DirExists(resourceCachePath))
{
StringVector cacheFiles;
fs->ScanDir(cacheFiles, resourceCachePath, "", SCAN_FILES, true);
if (!cacheFiles.empty())
{
ui::PushID(resourceCachePath.c_str());
ui::Indent();
for (const ea::string& cachedFile : cacheFiles)
{
icon = GetFileIcon(resourceCachePath + cachedFile);
isSelected = selected == cacheItem + "/" + cachedFile;
if (flags & RBF_SCROLL_TO_CURRENT && isSelected)
ui::SetScrollHereY();
switch (ui::DoubleClickSelectable((icon + " " + cachedFile).c_str(), isSelected))
{
case 1:
state.singleClickPending = [&]()
{
selected = cacheItem + "/" + cachedFile;
result = RBR_ITEM_SELECTED;
using namespace ResourceBrowserSelect;
fs->SendEvent(E_RESOURCEBROWSERSELECT, P_NAME, path + selected);
};
break;
case 2:
state.singleClickPending = nullptr;
selected = cacheItem + "/" + cachedFile;
result = RBR_ITEM_OPEN;
break;
default:
break;
}
if (ui::IsItemActive())
{
if (ui::BeginDragDropSource())
{
ui::SetDragDropVariant("path", path + cacheItem + "/" + cachedFile);
// TODO: show actual preview of a resource.
ui::Text("%s%s/%s", path.c_str(), cacheItem.c_str(), cachedFile.c_str());
ui::EndDragDropSource();
}
}
}
ui::Unindent();
ui::PopID();
}
}
}
}
if (ui::IsWindowHovered())
{
if (ui::IsMouseClicked(MOUSEB_RIGHT))
result = RBR_ITEM_CONTEXT_MENU;
if ((ui::IsMouseClicked(MOUSEB_LEFT) || ui::IsMouseClicked(MOUSEB_RIGHT)) && !ui::IsAnyItemHovered())
// Clicking empty area unselects item.
selected.clear();
}
state.wasEditing = state.isEditing;
if (state.singleClickPending)
{
auto& g = *ui::GetCurrentContext();
if ((float)(g.Time - g.IO.MouseClickedTime[0]) > g.IO.MouseDoubleClickTime)
{
state.singleClickPending();
state.singleClickPending = nullptr;
}
}
return result;
}
}
|
/*
Created by Fabrizio Di Vittorio (fdivitto2013@gmail.com) - <http://www.fabgl.com>
Copyright (c) 2019-2020 Fabrizio Di Vittorio.
All rights reserved.
This file is part of FabGL Library.
FabGL is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
FabGL 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 FabGL. If not, see <http://www.gnu.org/licenses/>.
*/
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "fabutils.h"
#include "scene.h"
namespace fabgl {
Scene::Scene(int maxSpritesCount, int updateTimeMS, int width, int height, int stackSize)
: m_width(width),
m_height(height),
m_updateTimeMS(updateTimeMS),
m_collisionDetector(maxSpritesCount, width, height),
m_suspendedTask(nullptr),
m_running(false)
{
m_mutex = xSemaphoreCreateMutex();
xSemaphoreTake(m_mutex, portMAX_DELAY); // suspend update task
xTaskCreate(updateTask, "", FABGL_DEFAULT_SCENETASK_STACKSIZE, this, 5, &m_updateTaskHandle);
}
Scene::~Scene()
{
stop();
xSemaphoreTake(m_mutex, portMAX_DELAY); // suspend update task
vTaskDelete(m_updateTaskHandle);
vSemaphoreDelete(m_mutex);
}
void Scene::start(bool suspendTask)
{
if (!m_running) {
m_running = true;
m_updateCount = 0;
init();
xSemaphoreGive(m_mutex); // resume update task
if (suspendTask) {
m_suspendedTask = xTaskGetCurrentTaskHandle();
vTaskSuspend(m_suspendedTask);
} else
m_suspendedTask = nullptr;
}
}
void Scene::stop()
{
if (m_running) {
// are we inside update task?
if (xTaskGetCurrentTaskHandle() != m_updateTaskHandle)
xSemaphoreTake(m_mutex, portMAX_DELAY); // no, suspend update task
m_running = false;
if (m_suspendedTask)
vTaskResume(m_suspendedTask);
}
}
void Scene::updateTask(void * pvParameters)
{
Scene * scene = (Scene*) pvParameters;
while (true) {
xSemaphoreTake(scene->m_mutex, portMAX_DELAY);
int64_t t0 = esp_timer_get_time(); // us
if (scene->m_running) {
scene->m_updateCount += 1;
scene->update(scene->m_updateCount);
}
xSemaphoreGive(scene->m_mutex);
int64_t t1 = esp_timer_get_time(); // us
int delayMS = (scene->m_updateTimeMS - (t1 - t0) / 1000);
if (delayMS > 0)
vTaskDelay(delayMS / portTICK_PERIOD_MS);
}
}
void collisionDetectionCallback(void * callbackObj, Sprite * spriteA, Sprite * spriteB, Point collisionPoint)
{
((Scene*)callbackObj)->collisionDetected(spriteA, spriteB, collisionPoint);
}
void Scene::updateSpriteAndDetectCollisions(Sprite * sprite)
{
m_collisionDetector.updateAndDetectCollision(sprite, collisionDetectionCallback, this);
}
} // end of namespace
|
/*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
Sample showing how to correct the positions inside the returned tokens in
a way that these appear to be consecutive (ignoring positions from macro
definitions).
http://www.boost.org/
Copyright (c) 2001-2009 Hartmut Kaiser. 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 <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
///////////////////////////////////////////////////////////////////////////////
// Include Wave itself
#include <boost/wave.hpp>
///////////////////////////////////////////////////////////////////////////////
// Include the lexer stuff
#include "real_position_token.hpp" // token class
#include <boost/wave/cpplexer/cpp_lex_iterator.hpp> // lexer type
#include "correct_token_positions.hpp"
///////////////////////////////////////////////////////////////////////////////
//
// Special output operator for a lex_token.
//
// Note: this doesn't compile if BOOST_SPIRIT_DEBUG is defined.
//
///////////////////////////////////////////////////////////////////////////////
template <typename PositionT>
inline std::ostream &
operator<< (std::ostream &stream, lex_token<PositionT> const &t)
{
using namespace std;
using namespace boost::wave;
token_id id = token_id(t);
stream << setw(16)
<< left << boost::wave::get_token_name(id) << " ("
<< "#" << setw(3) << BASEID_FROM_TOKEN(id);
if (ExtTokenTypeMask & id) {
// this is an extended token id
if (AltTokenType == (id & ExtTokenOnlyMask)) {
stream << ", AltTokenType";
}
else if (TriGraphTokenType == (id & ExtTokenOnlyMask)) {
stream << ", TriGraphTokenType";
}
else if (AltExtTokenType == (id & ExtTokenOnlyMask)){
stream << ", AltExtTokenType";
}
}
stream << "): >";
typedef typename lex_token<PositionT>::string_type string_type;
string_type const& value = t.get_value();
for (std::size_t i = 0; i < value.size(); ++i) {
switch (value[i]) {
case '\r': stream << "\\r"; break;
case '\n': stream << "\\n"; break;
case '\t': stream << "\\t"; break;
default:
stream << value[i];
break;
}
}
stream << "<" << std::endl;
stream << " at: " << t.get_position().get_file() << " ("
<< setw(3) << right << t.get_position().get_line() << "/"
<< setw(2) << right << t.get_position().get_column()
<< ")" << std::endl;
stream << " and: " << t.get_corrected_position().get_file() << " ("
<< setw(3) << right << t.get_corrected_position().get_line() << "/"
<< setw(2) << right << t.get_corrected_position().get_column()
<< ")";
return stream;
}
///////////////////////////////////////////////////////////////////////////////
// main entry point
int main(int argc, char *argv[])
{
if (2 != argc) {
std::cerr << "Usage: real_positions infile" << std::endl;
return -1;
}
// current file position is saved for exception handling
boost::wave::util::file_position_type current_position;
try {
// Open and read in the specified input file.
std::ifstream instream(argv[1]);
std::string instring;
if (!instream.is_open()) {
std::cerr << "Could not open input file: " << argv[1] << std::endl;
return -2;
}
instream.unsetf(std::ios::skipws);
instring = std::string(std::istreambuf_iterator<char>(instream.rdbuf()),
std::istreambuf_iterator<char>());
// The template real_positions::lex_token<> is the token type to be
// used by the Wave library.
typedef lex_token<> token_type;
// The template boost::wave::cpplexer::lex_iterator<> is the lexer type to
// be used by the Wave library.
typedef boost::wave::cpplexer::lex_iterator<token_type>
lex_iterator_type;
// This is the resulting context type to use. The first template parameter
// should match the iterator type to be used during construction of the
// corresponding context object (see below).
typedef boost::wave::context<
std::string::iterator, lex_iterator_type,
boost::wave::iteration_context_policies::load_file_to_string,
correct_token_position<token_type> >
context_type;
// This preprocessor hooks are used to correct the file positions inside
// the tokens returned from the library
correct_token_position<token_type> hooks(argv[1]);
// The preprocessor iterator shouldn't be constructed directly. It is
// to be generated through a wave::context<> object. This wave:context<>
// object is to be used additionally to initialize and define different
// parameters of the actual preprocessing (not done here).
//
// The preprocessing of the input stream is done on the fly behind the
// scenes during iteration over the context_type::iterator_type stream.
context_type ctx (instring.begin(), instring.end(), argv[1], hooks);
// analyze the input file
context_type::iterator_type first = ctx.begin();
context_type::iterator_type last = ctx.end();
while (first != last) {
current_position = (*first).get_position();
std::cout << *first << std::endl;
++first;
}
}
catch (boost::wave::cpp_exception const& e) {
// some preprocessing error
std::cerr
<< e.file_name() << "(" << e.line_no() << "): "
<< e.description() << std::endl;
return 2;
}
catch (std::exception const& e) {
// use last recognized token to retrieve the error position
std::cerr
<< current_position.get_file()
<< "(" << current_position.get_line() << "): "
<< "exception caught: " << e.what()
<< std::endl;
return 3;
}
catch (...) {
// use last recognized token to retrieve the error position
std::cerr
<< current_position.get_file()
<< "(" << current_position.get_line() << "): "
<< "unexpected exception caught." << std::endl;
return 4;
}
return 0;
}
|
/**
* Autogenerated by Thrift for src/include1.thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated @nocommit
*/
#include <thrift/lib/cpp2/gen/module_metadata_cpp.h>
#include "thrift/compiler/test/fixtures/frozen-struct/gen-cpp2/include1_metadata.h"
namespace apache {
namespace thrift {
namespace detail {
namespace md {
using ThriftMetadata = ::apache::thrift::metadata::ThriftMetadata;
using ThriftPrimitiveType = ::apache::thrift::metadata::ThriftPrimitiveType;
using ThriftType = ::apache::thrift::metadata::ThriftType;
using ThriftService = ::apache::thrift::metadata::ThriftService;
using ThriftServiceContext = ::apache::thrift::metadata::ThriftServiceContext;
using ThriftFunctionGenerator = void (*)(ThriftMetadata&, ThriftService&);
const ::apache::thrift::metadata::ThriftStruct&
StructMetadata<::some::ns::IncludedA>::gen(ThriftMetadata& metadata) {
auto res = metadata.structs_ref()->emplace("include1.IncludedA", ::apache::thrift::metadata::ThriftStruct{});
if (!res.second) {
return res.first->second;
}
::apache::thrift::metadata::ThriftStruct& include1_IncludedA = res.first->second;
include1_IncludedA.name_ref() = "include1.IncludedA";
include1_IncludedA.is_union_ref() = false;
static const EncodedThriftField
include1_IncludedA_fields[] = {
{1, "i32Field", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE), std::vector<ThriftConstStruct>{}},
{2, "strField", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE), std::vector<ThriftConstStruct>{}},
};
for (const auto& f : include1_IncludedA_fields) {
::apache::thrift::metadata::ThriftField field;
field.id_ref() = f.id;
field.name_ref() = f.name;
field.is_optional_ref() = f.is_optional;
f.metadata_type_interface->writeAndGenType(*field.type_ref(), metadata);
field.structured_annotations_ref() = f.structured_annotations;
include1_IncludedA.fields_ref()->push_back(std::move(field));
}
return res.first->second;
}
} // namespace md
} // namespace detail
} // namespace thrift
} // namespace apache
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE121_Stack_Based_Buffer_Overflow__CWE805_struct_declare_memcpy_74a.cpp
Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE805.label.xml
Template File: sources-sink-74a.tmpl.cpp
*/
/*
* @description
* CWE: 121 Stack Based Buffer Overflow
* BadSource: Set data pointer to the bad buffer
* GoodSource: Set data pointer to the good buffer
* Sinks: memcpy
* BadSink : Copy twoIntsStruct array to data using memcpy
* Flow Variant: 74 Data flow: data passed in a map from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <map>
using namespace std;
namespace CWE121_Stack_Based_Buffer_Overflow__CWE805_struct_declare_memcpy_74
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(map<int, twoIntsStruct *> dataMap);
void bad()
{
twoIntsStruct * data;
map<int, twoIntsStruct *> dataMap;
twoIntsStruct dataBadBuffer[50];
twoIntsStruct dataGoodBuffer[100];
/* FLAW: Set a pointer to a "small" buffer. This buffer will be used in the sinks as a destination
* buffer in various memory copying functions using a "large" source buffer. */
data = dataBadBuffer;
/* Put data in a map */
dataMap[0] = data;
dataMap[1] = data;
dataMap[2] = data;
badSink(dataMap);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declarations */
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(map<int, twoIntsStruct *> dataMap);
static void goodG2B()
{
twoIntsStruct * data;
map<int, twoIntsStruct *> dataMap;
twoIntsStruct dataBadBuffer[50];
twoIntsStruct dataGoodBuffer[100];
/* FIX: Set a pointer to a "large" buffer, thus avoiding buffer overflows in the sinks. */
data = dataGoodBuffer;
/* Put data in a map */
dataMap[0] = data;
dataMap[1] = data;
dataMap[2] = data;
goodG2BSink(dataMap);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
using namespace CWE121_Stack_Based_Buffer_Overflow__CWE805_struct_declare_memcpy_74; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
// Problem # : 112
// Created on : 2018-07-30 19:02:38
#include <algorithm>
#include <assert.h>
#include <bitset>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <limits>
#include <list>
#include <map>
#include <math.h>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <time.h>
#include <utility>
#include <vector>
using namespace std;
typedef pair<int, int> ii; // pair of ints
typedef vector<int> vi; // 1d vector of ints
typedef vector<ii> vii; // 1d vector of pairs
typedef vector<vi> vvi; // 2d vector of ints
typedef vector<vii> vvii; // 2d vector of pairs
typedef vector<bool> vb; // 1d vector of bools
typedef long long ll;
int ans;
int soln(int s, int t, char *c) {
int f = 0, l = 0, x, n;
while (isspace(*c)) {
*c = getchar();
}
if (*c == '(') {
x = f = 0, n = 1;
while (*c = getchar()) {
if (isdigit(*c)) {
x = x * 10 + *c - '0', f = 1;
} else {
if (*c == '-') {
n = -1;
} else {
break;
}
}
}
while (isspace(*c))
*c = getchar();
x *= n;
if (f == 0) {
return 0;
}
int L = soln(s + x, t, c);
while ((*c = getchar()) != '(')
;
int R = soln(s + x, t, c);
while ((*c = getchar()) != ')')
;
if (L == 0 && R == 0) {
if (s + x == t) {
ans = 1;
}
}
return 1;
}
}
int main() {
char c;
int t;
while (scanf("%d", &t) == 1) {
ans = 0;
c = getchar();
soln(0, t, &c);
if (ans) {
printf("yes\n");
} else {
printf("no\n");
}
}
return 0;
}
|
#include "sim/init.hh"
namespace {
const uint8_t data_m5_objects_GarnetNetwork[] = {
120,156,189,85,219,110,219,70,16,29,234,126,241,45,118,96,
180,41,218,236,67,139,170,105,44,198,106,253,98,20,69,107,
59,41,2,164,110,192,36,104,162,23,130,34,87,34,149,37,
87,224,174,20,171,175,233,83,63,168,63,208,15,107,103,150,
164,36,75,69,234,135,194,162,52,218,57,92,238,238,156,57,
51,244,33,255,148,241,247,3,3,80,127,224,32,192,175,5,
2,224,101,62,178,178,81,9,68,9,226,50,244,203,96,145,
95,6,81,129,184,2,253,74,230,87,64,84,33,174,66,191,
138,126,21,120,25,134,22,4,53,248,29,224,61,192,155,126,
13,130,58,240,170,65,27,11,180,14,65,19,120,197,160,173,
5,218,128,160,13,47,58,91,120,156,232,111,252,116,44,28,
105,50,15,178,97,27,141,51,29,204,47,185,126,39,211,183,
75,240,204,83,145,239,200,169,230,105,6,110,163,57,23,210,
127,203,131,95,6,99,238,107,131,252,228,165,9,215,249,211,
254,42,15,103,196,195,159,56,224,0,125,139,216,232,151,136,
6,12,27,143,57,174,18,17,24,251,251,18,96,68,132,212,
41,116,12,152,144,70,129,152,96,9,105,174,32,13,131,180,
10,164,73,17,19,210,94,89,185,109,144,45,131,108,3,223,
129,96,203,32,187,6,217,3,126,7,130,109,131,236,23,235,
224,156,93,131,28,128,243,162,179,71,204,84,208,168,175,209,
196,60,182,83,228,201,78,178,80,237,145,9,188,215,125,100,
95,163,160,27,134,17,49,160,142,208,36,211,120,192,83,38,
135,44,149,239,20,139,134,172,119,193,58,49,87,161,173,101,
58,85,118,183,251,21,211,114,34,133,28,205,35,218,80,125,
78,143,101,75,177,40,65,242,135,158,207,217,80,68,154,169,
232,55,142,24,27,204,53,87,81,165,152,61,139,82,61,245,
4,243,67,47,73,184,80,108,130,91,22,96,190,148,194,92,
192,96,58,28,242,52,187,31,120,218,99,107,79,70,148,230,
141,153,190,78,197,250,76,245,37,78,122,116,202,126,229,209,
40,212,71,3,79,241,128,189,244,6,130,63,100,199,167,236,
245,155,135,172,119,202,206,167,74,203,88,221,35,9,36,116,
179,56,13,27,122,83,161,89,44,3,92,234,96,37,224,21,
60,122,254,87,126,152,252,230,145,224,51,46,88,192,189,128,
68,200,116,152,34,143,82,4,157,187,164,206,6,26,215,77,
188,152,187,174,110,25,7,215,153,10,114,137,42,61,159,112,
131,251,87,87,110,136,139,240,84,87,209,125,238,165,94,172,
73,175,79,19,109,86,193,164,185,148,46,93,67,231,21,162,
223,244,52,213,79,18,185,148,6,151,210,96,128,153,175,92,
100,200,157,225,9,245,193,146,54,3,18,193,238,204,223,192,
137,78,194,239,32,158,98,117,69,201,200,245,196,72,166,145,
14,99,115,210,51,41,133,57,218,19,79,40,174,247,23,244,
185,134,30,215,208,99,66,121,66,254,207,198,165,7,47,95,
61,123,102,74,119,117,222,199,232,103,82,117,11,234,220,37,
117,164,212,165,81,175,209,216,161,140,185,61,83,113,207,246,
229,52,85,220,168,253,241,249,227,147,227,99,123,196,227,19,
55,246,20,234,210,86,169,111,223,184,42,38,115,83,74,95,
208,46,36,136,154,69,215,254,226,106,226,149,253,235,195,245,
174,242,180,40,131,205,246,18,254,107,123,193,242,199,94,138,
29,114,92,51,29,6,193,122,238,242,6,140,155,212,103,242,
150,178,0,91,69,231,105,175,128,91,212,109,178,54,130,13,
161,78,13,129,248,212,84,169,235,135,83,221,15,119,137,245,
249,216,40,212,3,146,221,5,213,116,202,133,167,35,153,96,
55,96,82,135,88,119,27,77,64,221,188,218,239,93,235,61,
235,119,111,86,85,212,220,29,146,161,67,117,224,80,240,186,
153,215,143,47,60,165,28,42,22,135,32,135,170,65,151,232,
29,19,152,170,193,162,226,137,118,118,8,94,158,197,149,67,
55,63,139,91,156,197,44,73,32,33,202,249,232,154,30,111,
65,148,148,206,111,105,151,187,11,81,214,74,187,214,22,10,
49,251,153,74,207,30,203,94,134,155,34,188,248,79,17,242,
58,140,27,197,203,174,177,2,46,164,216,34,129,25,182,41,
57,134,196,108,59,147,244,15,68,148,205,34,49,253,79,234,
232,180,55,19,239,124,66,230,122,190,157,79,201,80,138,157,
207,200,220,191,237,212,17,81,63,210,46,59,203,212,229,73,
187,236,52,11,185,198,39,221,9,181,120,101,122,59,121,169,
188,154,235,250,178,130,29,122,237,57,164,94,135,82,106,250,
148,209,133,217,225,54,67,50,71,252,46,123,109,125,127,191,
8,173,101,181,172,61,186,74,135,187,135,219,255,0,19,241,
150,232,
};
EmbeddedPython embedded_m5_objects_GarnetNetwork(
"m5/objects/GarnetNetwork.py",
"/home/vsm2/coursework/ECE511/gem5_master/src/mem/ruby/network/garnet2.0/GarnetNetwork.py",
"m5.objects.GarnetNetwork",
data_m5_objects_GarnetNetwork,
1074,
2667);
} // anonymous namespace
|
/*
* Copyright (c) 2018-2019 Confetti Interactive Inc.
*
* This file is part of The-Forge
* (see https://github.com/ConfettiFX/The-Forge).
*
* 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 "../../Middleware_3/Text/Fontstash.h"
#include "../../Common_3/ThirdParty/OpenSource/imgui/imgui.h"
#include "../../Common_3/ThirdParty/OpenSource/imgui/imgui_internal.h"
#include "AppUI.h"
#include "../../Common_3/OS/Interfaces/IOperatingSystem.h"
#include "../../Common_3/OS/Interfaces/ILog.h"
#include "../../Common_3/Renderer/IRenderer.h"
#include "../../Common_3/Renderer/ResourceLoader.h"
#include "../../Common_3/OS/Input/InputSystem.h"
#include "../../Common_3/OS/Input/InputMappings.h"
#include "../../Common_3/OS/Interfaces/IMemory.h" //NOTE: this should be the last include in a .cpp
#define LABELID(prop) eastl::string().sprintf("##%llu", (uint64_t)(prop.pData)).c_str()
#define LABELID1(prop) eastl::string().sprintf("##%llu", (uint64_t)(prop)).c_str()
namespace ImGui {
bool SliderFloatWithSteps(const char* label, float* v, float v_min, float v_max, float v_step, const char* display_format)
{
eastl::string text_buf;
bool value_changed = false;
if (!display_format)
display_format = "%.1f";
text_buf.sprintf(display_format, *v);
if (ImGui::GetIO().WantTextInput)
{
value_changed = ImGui::SliderFloat(label, v, v_min, v_max, text_buf.c_str());
int v_i = int(((*v - v_min) / v_step) + 0.5f);
*v = v_min + float(v_i) * v_step;
}
else
{
// Map from [v_min,v_max] to [0,N]
const int countValues = int((v_max - v_min) / v_step);
int v_i = int(((*v - v_min) / v_step) + 0.5f);
value_changed = ImGui::SliderInt(label, &v_i, 0, countValues, text_buf.c_str());
// Remap from [0,N] to [v_min,v_max]
*v = v_min + float(v_i) * v_step;
}
if (*v < v_min)
*v = v_min;
if (*v > v_max)
*v = v_max;
return value_changed;
}
bool SliderIntWithSteps(const char* label, int32_t* v, int32_t v_min, int32_t v_max, int32_t v_step, const char* display_format)
{
eastl::string text_buf;
bool value_changed = false;
if (!display_format)
display_format = "%d";
text_buf.sprintf(display_format, *v);
if (ImGui::GetIO().WantTextInput)
{
value_changed = ImGui::SliderInt(label, v, v_min, v_max, text_buf.c_str());
int32_t v_i = int((*v - v_min) / v_step);
*v = v_min + int32_t(v_i) * v_step;
}
else
{
// Map from [v_min,v_max] to [0,N]
const int countValues = int((v_max - v_min) / v_step);
int32_t v_i = int((*v - v_min) / v_step);
value_changed = ImGui::SliderInt(label, &v_i, 0, countValues, text_buf.c_str());
// Remap from [0,N] to [v_min,v_max]
*v = v_min + int32_t(v_i) * v_step;
}
if (*v < v_min)
*v = v_min;
if (*v > v_max)
*v = v_max;
return value_changed;
}
} // namespace ImGui
class ImguiGUIDriver: public GUIDriver
{
public:
// Declare virtual destructor
virtual ~ImguiGUIDriver() {}
bool init(Renderer* pRenderer, uint32_t const maxDynamicUIUpdatesPerBatch);
void exit();
bool load(RenderTarget** ppRts, uint32_t count);
void unload();
bool addGui(Fontstash* fontID, float fontSize, Texture* cursorTexture = 0, float uiwidth = 600, float uiheight = 400);
void* getContext();
bool update(GUIUpdate* pGuiUpdate);
void draw(Cmd* q);
void onInput(const ButtonData* data);
bool isHovering(const float4& windowRect);
int needsTextInput() const;
static void* alloc_func(size_t size, void* user_data) { return conf_malloc(size); }
static void dealloc_func(void* ptr, void* user_data) { conf_free(ptr); }
protected:
static const uint32_t MAX_FRAMES = 3;
ImGuiContext* context;
Texture* pFontTexture;
float2 dpiScale;
bool loaded;
uint32_t frameIdx;
Renderer* pRenderer;
Shader* pShaderTextured;
RootSignature* pRootSignatureTextured;
DescriptorBinder* pDescriptorBinderTextured;
Pipeline* pPipelineTextured;
Buffer* pVertexBuffer;
Buffer* pIndexBuffer;
Buffer* pUniformBuffer;
uint64_t mUniformSize;
/// Default states
BlendState* pBlendAlpha;
DepthState* pDepthState;
RasterizerState* pRasterizerState;
Sampler* pDefaultSampler;
VertexLayout mVertexLayoutTextured = {};
};
static const uint64_t VERTEX_BUFFER_SIZE = 1024 * 64 * sizeof(ImDrawVert);
static const uint64_t INDEX_BUFFER_SIZE = 128 * 1024 * sizeof(ImDrawIdx);
void initGUIDriver(Renderer* pRenderer, GUIDriver** ppDriver)
{
ImguiGUIDriver* pDriver = conf_placement_new<ImguiGUIDriver>(conf_calloc(1, sizeof(ImguiGUIDriver)));
*ppDriver = pDriver;
}
void removeGUIDriver(GUIDriver* pDriver)
{
(reinterpret_cast<ImguiGUIDriver*>(pDriver))->~ImguiGUIDriver();
conf_free(pDriver);
}
static float4 ToFloat4Color(uint color)
{
float4 col; // Translate colours back by bit shifting
col.x = (float)((color & 0xFF000000) >> 24);
col.y = (float)((color & 0x00FF0000) >> 16);
col.z = (float)((color & 0x0000FF00) >> 8);
col.w = (float)(color & 0x000000FF);
return col;
}
static uint ToUintColor(float4 color)
{
uint c = (((uint)color.x << 24) & 0xFF000000) | (((uint)color.y << 16) & 0x00FF0000) | (((uint)color.z << 8) & 0x0000FF00) |
(((uint)color.w) & 0x000000FF);
return c;
}
void IWidget::ProcessCallbacks()
{
if (pOnHover && ImGui::IsItemHovered())
pOnHover();
if (pOnActive && ImGui::IsItemActive())
pOnActive();
if (pOnFocus && ImGui::IsItemFocused())
pOnFocus();
if (pOnEdited && ImGui::IsItemEdited())
pOnEdited();
if (pOnDeactivated && ImGui::IsItemDeactivated())
pOnDeactivated();
if (pOnDeactivatedAfterEdit && ImGui::IsItemDeactivatedAfterEdit())
pOnDeactivatedAfterEdit();
}
void CollapsingHeaderWidget::Draw()
{
if (mPreviousCollapsed != mCollapsed)
{
ImGui::SetNextTreeNodeOpen(!mCollapsed);
mPreviousCollapsed = mCollapsed;
}
ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_CollapsingHeader;
if (mDefaultOpen)
flags |= ImGuiTreeNodeFlags_DefaultOpen;
if (!mHeaderIsVisible || ImGui::CollapsingHeader(mLabel.c_str(), flags))
{
for (IWidget* widget : mGroupedWidgets)
widget->Draw();
}
ProcessCallbacks();
}
void DebugTexturesWidget::Draw()
{
for (Texture* tex : mTextures)
{
ImGui::Image(tex, mTextureDisplaySize);
ImGui::SameLine();
}
ProcessCallbacks();
}
void LabelWidget::Draw()
{
ImGui::Text("%s", mLabel.c_str());
ProcessCallbacks();
}
void SeparatorWidget::Draw()
{
ImGui::Separator();
ProcessCallbacks();
}
void ButtonWidget::Draw()
{
ImGui::Button(mLabel.c_str());
ProcessCallbacks();
}
void SliderFloatWidget::Draw()
{
ImGui::Text("%s", mLabel.c_str());
ImGui::SliderFloatWithSteps(LABELID1(pData), pData, mMin, mMax, mStep, mFormat.c_str());
ProcessCallbacks();
}
void SliderFloat2Widget::Draw()
{
ImGui::Text("%s", mLabel.c_str());
for (uint32_t i = 0; i < 2; ++i)
{
ImGui::SliderFloatWithSteps(LABELID1(&pData->operator[](i)), &pData->operator[](i), mMin[i], mMax[i], mStep[i], mFormat.c_str());
ProcessCallbacks();
}
}
void SliderFloat3Widget::Draw()
{
ImGui::Text("%s", mLabel.c_str());
for (uint32_t i = 0; i < 3; ++i)
{
ImGui::SliderFloatWithSteps(LABELID1(&pData->operator[](i)), &pData->operator[](i), mMin[i], mMax[i], mStep[i], mFormat.c_str());
ProcessCallbacks();
}
}
void SliderFloat4Widget::Draw()
{
ImGui::Text("%s", mLabel.c_str());
for (uint32_t i = 0; i < 4; ++i)
{
ImGui::SliderFloatWithSteps(LABELID1(&pData->operator[](i)), &pData->operator[](i), mMin[i], mMax[i], mStep[i], mFormat.c_str());
ProcessCallbacks();
}
}
void SliderIntWidget::Draw()
{
ImGui::Text("%s", mLabel.c_str());
ImGui::SliderIntWithSteps(LABELID1(pData), pData, mMin, mMax, mStep, mFormat.c_str());
ProcessCallbacks();
}
void SliderUintWidget::Draw()
{
ImGui::Text("%s", mLabel.c_str());
ImGui::SliderIntWithSteps(LABELID1(pData), (int32_t*)pData, (int32_t)mMin, (int32_t)mMax, (int32_t)mStep, mFormat.c_str());
ProcessCallbacks();
}
void RadioButtonWidget::Draw()
{
ImGui::RadioButton(mLabel.c_str(), pData, mRadioId);
ProcessCallbacks();
}
void CheckboxWidget::Draw()
{
ImGui::Text("%s", mLabel.c_str());
ImGui::Checkbox(LABELID1(pData), pData);
ProcessCallbacks();
}
void DropdownWidget::Draw()
{
uint32_t& current = *pData;
ImGui::Text("%s", mLabel.c_str());
if (ImGui::BeginCombo(LABELID1(pData), mNames[current].c_str()))
{
for (uint32_t i = 0; i < (uint32_t)mNames.size(); ++i)
{
if (ImGui::Selectable(mNames[i].c_str()))
{
uint32_t prevVal = current;
current = i;
// Note that callbacks are sketchy with BeginCombo/EndCombo, so we manually process them here
if (pOnEdited)
pOnEdited();
if (current != prevVal)
{
if (pOnDeactivatedAfterEdit)
pOnDeactivatedAfterEdit();
}
}
}
ImGui::EndCombo();
}
}
void ProgressBarWidget::Draw()
{
size_t currProgress = *pData;
ImGui::Text("%s", mLabel.c_str());
ImGui::ProgressBar((float)currProgress / mMaxProgress);
ProcessCallbacks();
}
void ColorSliderWidget::Draw()
{
uint& colorPick = *(uint*)pData;
float4 combo_color = ToFloat4Color(colorPick) / 255.0f;
float col[4] = { combo_color.x, combo_color.y, combo_color.z, combo_color.w };
ImGui::Text("%s", mLabel.c_str());
if (ImGui::ColorEdit4(LABELID1(pData), col, ImGuiColorEditFlags_AlphaPreview))
{
if (col[0] != combo_color.x || col[1] != combo_color.y || col[2] != combo_color.z || col[3] != combo_color.w)
{
combo_color = col;
colorPick = ToUintColor(combo_color * 255.0f);
}
}
ProcessCallbacks();
}
void ColorPickerWidget::Draw()
{
uint& colorPick = *(uint*)pData;
float4 combo_color = ToFloat4Color(colorPick) / 255.0f;
float col[4] = { combo_color.x, combo_color.y, combo_color.z, combo_color.w };
ImGui::Text("%s", mLabel.c_str());
if (ImGui::ColorPicker4(LABELID1(pData), col, ImGuiColorEditFlags_AlphaPreview))
{
if (col[0] != combo_color.x || col[1] != combo_color.y || col[2] != combo_color.z || col[3] != combo_color.w)
{
combo_color = col;
colorPick = ToUintColor(combo_color * 255.0f);
}
}
ProcessCallbacks();
}
void TextboxWidget::Draw()
{
ImGui::InputText(LABELID1(pData), (char*)pData, mLength, mAutoSelectAll ? ImGuiInputTextFlags_AutoSelectAll : 0);
ProcessCallbacks();
}
static void SetDefaultStyle()
{
ImGuiStyle& style = ImGui::GetStyle();
style.WindowRounding = 0.4f;
float4* colors = style.Colors;
colors[ImGuiCol_Text] = float4(1.00f, 1.00f, 1.00f, 1.00f);
colors[ImGuiCol_TextDisabled] = float4(0.50f, 0.50f, 0.50f, 1.00f);
colors[ImGuiCol_WindowBg] = float4(0.06f, 0.06f, 0.06f, 1.0f);
colors[ImGuiCol_ChildBg] = float4(1.00f, 1.00f, 1.00f, 0.00f);
colors[ImGuiCol_PopupBg] = float4(0.08f, 0.08f, 0.08f, 0.94f);
colors[ImGuiCol_Border] = float4(0.43f, 0.43f, 0.50f, 0.50f);
colors[ImGuiCol_BorderShadow] = float4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_FrameBg] = float4(0.20f, 0.21f, 0.22f, 0.54f);
colors[ImGuiCol_FrameBgHovered] = float4(0.40f, 0.40f, 0.40f, 0.40f);
colors[ImGuiCol_FrameBgActive] = float4(0.18f, 0.18f, 0.18f, 0.67f);
colors[ImGuiCol_TitleBg] = float4(0.04f, 0.04f, 0.04f, 1.00f);
colors[ImGuiCol_TitleBgActive] = float4(0.29f, 0.29f, 0.29f, 1.00f);
colors[ImGuiCol_TitleBgCollapsed] = float4(0.00f, 0.00f, 0.00f, 0.51f);
colors[ImGuiCol_MenuBarBg] = float4(0.14f, 0.14f, 0.14f, 1.00f);
colors[ImGuiCol_ScrollbarBg] = float4(0.02f, 0.02f, 0.02f, 0.53f);
colors[ImGuiCol_ScrollbarGrab] = float4(0.31f, 0.31f, 0.31f, 1.00f);
colors[ImGuiCol_ScrollbarGrabHovered] = float4(0.41f, 0.41f, 0.41f, 1.00f);
colors[ImGuiCol_ScrollbarGrabActive] = float4(0.51f, 0.51f, 0.51f, 1.00f);
colors[ImGuiCol_CheckMark] = float4(0.94f, 0.94f, 0.94f, 1.00f);
colors[ImGuiCol_SliderGrab] = float4(0.51f, 0.51f, 0.51f, 1.00f);
colors[ImGuiCol_SliderGrabActive] = float4(0.86f, 0.86f, 0.86f, 1.00f);
colors[ImGuiCol_Button] = float4(0.44f, 0.44f, 0.44f, 0.40f);
colors[ImGuiCol_ButtonHovered] = float4(0.46f, 0.47f, 0.48f, 1.00f);
colors[ImGuiCol_ButtonActive] = float4(0.42f, 0.42f, 0.42f, 1.00f);
colors[ImGuiCol_Header] = float4(0.70f, 0.70f, 0.70f, 0.31f);
colors[ImGuiCol_HeaderHovered] = float4(0.70f, 0.70f, 0.70f, 0.80f);
colors[ImGuiCol_HeaderActive] = float4(0.48f, 0.50f, 0.52f, 1.00f);
colors[ImGuiCol_Separator] = float4(0.43f, 0.43f, 0.50f, 0.50f);
colors[ImGuiCol_SeparatorHovered] = float4(0.72f, 0.72f, 0.72f, 0.78f);
colors[ImGuiCol_SeparatorActive] = float4(0.51f, 0.51f, 0.51f, 1.00f);
colors[ImGuiCol_ResizeGrip] = float4(0.91f, 0.91f, 0.91f, 0.25f);
colors[ImGuiCol_ResizeGripHovered] = float4(0.81f, 0.81f, 0.81f, 0.67f);
colors[ImGuiCol_ResizeGripActive] = float4(0.46f, 0.46f, 0.46f, 0.95f);
colors[ImGuiCol_PlotLines] = float4(0.61f, 0.61f, 0.61f, 1.00f);
colors[ImGuiCol_PlotLinesHovered] = float4(1.00f, 0.43f, 0.35f, 1.00f);
colors[ImGuiCol_PlotHistogram] = float4(0.73f, 0.60f, 0.15f, 1.00f);
colors[ImGuiCol_PlotHistogramHovered] = float4(1.00f, 0.60f, 0.00f, 1.00f);
colors[ImGuiCol_TextSelectedBg] = float4(0.87f, 0.87f, 0.87f, 0.35f);
colors[ImGuiCol_ModalWindowDarkening] = float4(0.80f, 0.80f, 0.80f, 0.35f);
colors[ImGuiCol_DragDropTarget] = float4(1.00f, 1.00f, 0.00f, 0.90f);
colors[ImGuiCol_NavHighlight] = float4(0.60f, 0.60f, 0.60f, 1.00f);
colors[ImGuiCol_NavWindowingHighlight] = float4(1.00f, 1.00f, 1.00f, 0.70f);
}
bool ImguiGUIDriver::init(Renderer* renderer, uint32_t const maxDynamicUIUpdatesPerBatch)
{
mHandledGestures = false;
pRenderer = renderer;
loaded = false;
/************************************************************************/
// Rendering resources
/************************************************************************/
SamplerDesc samplerDesc = { FILTER_LINEAR,
FILTER_LINEAR,
MIPMAP_MODE_NEAREST,
ADDRESS_MODE_CLAMP_TO_EDGE,
ADDRESS_MODE_CLAMP_TO_EDGE,
ADDRESS_MODE_CLAMP_TO_EDGE };
addSampler(pRenderer, &samplerDesc, &pDefaultSampler);
BlendStateDesc blendStateDesc = {};
blendStateDesc.mSrcFactors[0] = BC_SRC_ALPHA;
blendStateDesc.mDstFactors[0] = BC_ONE_MINUS_SRC_ALPHA;
blendStateDesc.mSrcAlphaFactors[0] = BC_SRC_ALPHA;
blendStateDesc.mDstAlphaFactors[0] = BC_ONE_MINUS_SRC_ALPHA;
blendStateDesc.mMasks[0] = ALL;
blendStateDesc.mRenderTargetMask = BLEND_STATE_TARGET_ALL;
blendStateDesc.mIndependentBlend = false;
addBlendState(pRenderer, &blendStateDesc, &pBlendAlpha);
DepthStateDesc depthStateDesc = {};
depthStateDesc.mDepthTest = false;
depthStateDesc.mDepthWrite = false;
addDepthState(pRenderer, &depthStateDesc, &pDepthState);
RasterizerStateDesc rasterizerStateDesc = {};
rasterizerStateDesc.mCullMode = CULL_MODE_NONE;
rasterizerStateDesc.mScissor = true;
addRasterizerState(pRenderer, &rasterizerStateDesc, &pRasterizerState);
ShaderLoadDesc texturedShaderDesc = {};
texturedShaderDesc.mStages[0] = { "imgui.vert", NULL, 0, FSR_MIDDLEWARE_UI };
texturedShaderDesc.mStages[1] = { "imgui.frag", NULL, 0, FSR_MIDDLEWARE_UI };
addShader(pRenderer, &texturedShaderDesc, &pShaderTextured);
const char* pStaticSamplerNames[] = { "uSampler" };
RootSignatureDesc textureRootDesc = { &pShaderTextured, 1 };
textureRootDesc.mStaticSamplerCount = 1;
textureRootDesc.ppStaticSamplerNames = pStaticSamplerNames;
textureRootDesc.ppStaticSamplers = &pDefaultSampler;
addRootSignature(pRenderer, &textureRootDesc, &pRootSignatureTextured);
DescriptorBinderDesc descriptorBinderDesc = { pRootSignatureTextured, maxDynamicUIUpdatesPerBatch };
addDescriptorBinder(pRenderer, 0, 1, &descriptorBinderDesc, &pDescriptorBinderTextured);
BufferLoadDesc vbDesc = {};
vbDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_VERTEX_BUFFER;
vbDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU;
vbDesc.mDesc.mVertexStride = sizeof(ImDrawVert);
vbDesc.mDesc.mSize = VERTEX_BUFFER_SIZE * MAX_FRAMES;
vbDesc.mDesc.mFlags = BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT | BUFFER_CREATION_FLAG_OWN_MEMORY_BIT;
vbDesc.ppBuffer = &pVertexBuffer;
addResource(&vbDesc);
BufferLoadDesc ibDesc = vbDesc;
ibDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_INDEX_BUFFER;
ibDesc.mDesc.mIndexType = INDEX_TYPE_UINT16;
ibDesc.mDesc.mSize = INDEX_BUFFER_SIZE * MAX_FRAMES;
ibDesc.ppBuffer = &pIndexBuffer;
addResource(&ibDesc);
BufferLoadDesc ubDesc = {};
mUniformSize = round_up_64(256, pRenderer->mGpuSettings->mUniformBufferAlignment);
#if defined(DIRECT3D11)
ubDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_ONLY;
#else
ubDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_UNIFORM_BUFFER;
ubDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU;
#endif
ubDesc.mDesc.mFlags =
BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT | BUFFER_CREATION_FLAG_NO_DESCRIPTOR_VIEW_CREATION | BUFFER_CREATION_FLAG_OWN_MEMORY_BIT;
ubDesc.mDesc.mSize = mUniformSize * MAX_FRAMES;
ubDesc.ppBuffer = &pUniformBuffer;
addResource(&ubDesc);
mVertexLayoutTextured.mAttribCount = 3;
mVertexLayoutTextured.mAttribs[0].mSemantic = SEMANTIC_POSITION;
mVertexLayoutTextured.mAttribs[0].mFormat = ImageFormat::RG32F;
mVertexLayoutTextured.mAttribs[0].mBinding = 0;
mVertexLayoutTextured.mAttribs[0].mLocation = 0;
mVertexLayoutTextured.mAttribs[0].mOffset = 0;
mVertexLayoutTextured.mAttribs[1].mSemantic = SEMANTIC_TEXCOORD0;
mVertexLayoutTextured.mAttribs[1].mFormat = ImageFormat::RG32F;
mVertexLayoutTextured.mAttribs[1].mBinding = 0;
mVertexLayoutTextured.mAttribs[1].mLocation = 1;
mVertexLayoutTextured.mAttribs[1].mOffset = ImageFormat::GetImageFormatStride(mVertexLayoutTextured.mAttribs[0].mFormat);
mVertexLayoutTextured.mAttribs[2].mSemantic = SEMANTIC_COLOR;
mVertexLayoutTextured.mAttribs[2].mFormat = ImageFormat::RGBA8;
mVertexLayoutTextured.mAttribs[2].mBinding = 0;
mVertexLayoutTextured.mAttribs[2].mLocation = 2;
mVertexLayoutTextured.mAttribs[2].mOffset =
mVertexLayoutTextured.mAttribs[1].mOffset + ImageFormat::GetImageFormatStride(mVertexLayoutTextured.mAttribs[1].mFormat);
/************************************************************************/
/************************************************************************/
dpiScale = getDpiScale();
//// init UI (input)
ImGui::SetAllocatorFunctions(alloc_func, dealloc_func);
context = ImGui::CreateContext();
ImGui::SetCurrentContext(context);
return true;
}
void ImguiGUIDriver::exit()
{
removeSampler(pRenderer, pDefaultSampler);
removeBlendState(pBlendAlpha);
removeDepthState(pDepthState);
removeRasterizerState(pRasterizerState);
removeShader(pRenderer, pShaderTextured);
removeDescriptorBinder(pRenderer, pDescriptorBinderTextured);
removeRootSignature(pRenderer, pRootSignatureTextured);
removeResource(pVertexBuffer);
removeResource(pIndexBuffer);
removeResource(pUniformBuffer);
if (pFontTexture)
{
removeResource(pFontTexture);
}
ImGui::DestroyContext(context);
}
bool ImguiGUIDriver::addGui(Fontstash* fontstash, float fontSize, Texture* cursorTexture, float uiwidth, float uiheight)
{
if (!loaded)
{
// Build and load the texture atlas into a texture
// (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
int width, height;
unsigned char* pixels = NULL;
ImFontConfig config = {};
config.FontDataOwnedByAtlas = false;
ImFont* font = ImGui::GetIO().Fonts->AddFontFromMemoryTTF(
fontstash->getFontBuffer("default"), fontstash->getFontBufferSize("default"), fontSize * min(dpiScale.x, dpiScale.y), &config);
if (font != NULL)
{
ImGui::GetIO().FontDefault = font;
}
else
{
ImGui::GetIO().Fonts->AddFontDefault();
}
ImGui::GetIO().Fonts->Build();
ImGui::GetIO().Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
// At this point you've got the texture data and you need to upload that your your graphic system:
// After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
// This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ below for details about ImTextureID.
RawImageData rawData{ pixels, ImageFormat::RGBA8, (uint32_t)width, (uint32_t)height, 1, 1, 1 };
TextureLoadDesc loadDesc = {};
loadDesc.pRawImageData = &rawData;
loadDesc.ppTexture = &pFontTexture;
loadDesc.mCreationFlag = TEXTURE_CREATION_FLAG_OWN_MEMORY_BIT;
addResource(&loadDesc);
ImGui::GetIO().Fonts->TexID = (void*)pFontTexture;
SetDefaultStyle();
ImGuiIO& io = ImGui::GetIO();
//io.KeyMap[ImGuiKey_Tab] = VK_TAB;
//io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR;
//io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
//io.KeyMap[ImGuiKey_Home] = VK_HOME;
//io.KeyMap[ImGuiKey_End] = VK_END;
//io.KeyMap[ImGuiKey_Insert] = VK_INSERT;
//io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
io.KeyMap[ImGuiKey_LeftArrow] = KEY_PAD_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = KEY_PAD_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = KEY_PAD_UP;
io.KeyMap[ImGuiKey_DownArrow] = KEY_PAD_DOWN;
io.KeyMap[ImGuiKey_Backspace] = KEY_RIGHT_STICK_BUTTON;
io.KeyMap[ImGuiKey_Delete] = KEY_DELETE;
io.KeyMap[ImGuiKey_Space] = KEY_LEFT_TRIGGER;
io.KeyMap[ImGuiKey_Enter] = KEY_MENU;
io.KeyMap[ImGuiKey_Escape] = KEY_CANCEL;
io.KeyMap[ImGuiKey_A] = 'A';
io.KeyMap[ImGuiKey_C] = 'C';
io.KeyMap[ImGuiKey_V] = 'V';
io.KeyMap[ImGuiKey_X] = 'X';
io.KeyMap[ImGuiKey_Y] = 'Y';
io.KeyMap[ImGuiKey_Z] = 'Z';
loaded = true;
}
return true;
}
bool ImguiGUIDriver::load(RenderTarget** ppRts, uint32_t count)
{
UNREF_PARAM(count);
PipelineDesc desc = {};
desc.mType = PIPELINE_TYPE_GRAPHICS;
GraphicsPipelineDesc& pipelineDesc = desc.mGraphicsDesc;
pipelineDesc.mDepthStencilFormat = ImageFormat::NONE;
pipelineDesc.mRenderTargetCount = 1;
pipelineDesc.mSampleCount = ppRts[0]->mDesc.mSampleCount;
pipelineDesc.pBlendState = pBlendAlpha;
pipelineDesc.mSampleQuality = ppRts[0]->mDesc.mSampleQuality;
pipelineDesc.pColorFormats = &ppRts[0]->mDesc.mFormat;
pipelineDesc.pDepthState = pDepthState;
pipelineDesc.pRasterizerState = pRasterizerState;
pipelineDesc.pSrgbValues = &ppRts[0]->mDesc.mSrgb;
pipelineDesc.pRootSignature = pRootSignatureTextured;
pipelineDesc.pShaderProgram = pShaderTextured;
pipelineDesc.pVertexLayout = &mVertexLayoutTextured;
pipelineDesc.mPrimitiveTopo = PRIMITIVE_TOPO_TRI_LIST;
addPipeline(pRenderer, &desc, &pPipelineTextured);
return true;
}
void ImguiGUIDriver::unload()
{
removePipeline(pRenderer, pPipelineTextured);
}
void* ImguiGUIDriver::getContext() { return context; }
void ImguiGUIDriver::onInput(const ButtonData* data)
{
ImGui::SetCurrentContext(context);
ImGuiIO& io = ImGui::GetIO();
if (GAINPUT_GAMEPAD & data->mActiveDevicesMask)
{
io.NavActive = true;
io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;
io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
return;
}
io.NavActive = false;
// Always handle gestures first
if (GESTURE_SWIPE_2 == data->mUserId)
{
// Divide by extra multiple that ImGUI applies when using the MouseWheel values
// We do that because swiping is different than mousewheel and matches exactly pixels
// Removing this division will cause the scroll to not match the fingers movement.
float scroll_amount = 1.0f;
if (context->HoveredWindow)
scroll_amount = 5.f * context->HoveredWindow->CalcFontSize();
io.MouseWheel += data->mValue[INPUT_Y_AXIS] * getDpiScale().y / scroll_amount;
mHandledGestures = true;
for (int i = 0; i < 5; i++)
{
io.MouseDown[0] = false;
}
}
if (mHandledGestures)
return;
if (data->mUserId == KEY_UI_MOVE)
{
io.MousePos = float2((float)data->mValue[0], (float)data->mValue[1]);
}
else if (data->mUserId == KEY_CONFIRM || data->mUserId == KEY_RIGHT_BUMPER || data->mUserId == KEY_MOUSE_WHEEL_BUTTON)
{
uint32_t index = data->mUserId == KEY_CONFIRM ? 0 : (data->mUserId == KEY_RIGHT_BUMPER ? 1 : 2);
io.MouseDown[index] = data->mIsPressed;
io.MousePos = float2((float)data->mValue[0], (float)data->mValue[1]);
}
else if (KEY_MOUSE_WHEEL == data->mUserId)
{
io.MouseWheel += data->mValue[0];
}
else if (KEY_CHAR == data->mUserId)
{
if (data->mIsPressed && needsTextInput())
io.AddInputCharacter(data->mCharacter);
}
else if (KEY_LEFT_STICK == data->mUserId)
{
io.KeysDown[(int)'A'] = data->mIsPressed;
}
else if (KEY_RIGHT_STICK_BUTTON == data->mUserId || KEY_DELETE == data->mUserId)
{
io.KeysDown[data->mUserId] = data->mIsPressed;
}
else if (KEY_RIGHT_CTRL == data->mUserId || KEY_LEFT_CTRL == data->mUserId)
{
io.KeysDown[data->mUserId] = data->mIsPressed;
io.KeyCtrl = data->mIsPressed;
}
else if (KEY_RIGHT_SHIFT == data->mUserId || KEY_LEFT_BUMPER == data->mUserId)
{
io.KeysDown[data->mUserId] = data->mIsPressed;
io.KeyShift = data->mIsPressed;
}
else if (KEY_RIGHT_SUPER == data->mUserId || KEY_LEFT_SUPER == data->mUserId)
{
io.KeysDown[data->mUserId] = data->mIsPressed;
io.KeySuper = data->mIsPressed;
}
else if (
KEY_PAD_LEFT == data->mUserId || KEY_PAD_RIGHT == data->mUserId || KEY_PAD_UP == data->mUserId || KEY_PAD_DOWN == data->mUserId)
{
io.KeysDown[data->mUserId] = data->mIsPressed;
}
else if (KEY_MENU == data->mUserId)
{
io.KeysDown[data->mUserId] = data->mIsPressed;
}
}
bool ImguiGUIDriver::isHovering(const float4& windowRect)
{
return ImGui::IsMouseHoveringRect(
float2(windowRect.x, windowRect.y), float2(windowRect.x + windowRect.z, windowRect.y + windowRect.w), false);
}
bool ImguiGUIDriver::update(GUIUpdate* pGuiUpdate)
{
ImGui::SetCurrentContext(context);
// #TODO: Use window size as render-target size cannot be trusted to be the same as window size
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize.x = pGuiUpdate->width;
io.DisplaySize.y = pGuiUpdate->height;
io.DeltaTime = pGuiUpdate->deltaTime;
if (io.NavActive)
{
io.NavInputs[ImGuiNavInput_Activate] = InputSystem::GetFloatInput(IMGUI_NAVINPUT_ACTIVATE);
io.NavInputs[ImGuiNavInput_Cancel] = InputSystem::GetFloatInput(IMGUI_NAVINPUT_CANCEL);
io.NavInputs[ImGuiNavInput_Menu] = InputSystem::GetFloatInput(IMGUI_NAVINPUT_MENU);
io.NavInputs[ImGuiNavInput_Input] = InputSystem::GetFloatInput(IMGUI_NAVINPUT_INPUT);
io.NavInputs[ImGuiNavInput_DpadLeft] = InputSystem::GetFloatInput(IMGUI_NAVINPUT_DPADLEFT);
io.NavInputs[ImGuiNavInput_DpadRight] = InputSystem::GetFloatInput(IMGUI_NAVINPUT_DPADRIGHT);
io.NavInputs[ImGuiNavInput_DpadUp] = InputSystem::GetFloatInput(IMGUI_NAVINPUT_DPADUP);
io.NavInputs[ImGuiNavInput_DpadDown] = InputSystem::GetFloatInput(IMGUI_NAVINPUT_DPADDOWN);
io.NavInputs[ImGuiNavInput_FocusNext] = InputSystem::GetFloatInput(IMGUI_NAVINPUT_FOCUSNEXT);
io.NavInputs[ImGuiNavInput_FocusPrev] = InputSystem::GetFloatInput(IMGUI_NAVINPUT_FOCUSPREV);
io.NavInputs[ImGuiNavInput_TweakFast] = InputSystem::GetFloatInput(IMGUI_NAVINPUT_TWEAKFAST);
io.NavInputs[ImGuiNavInput_TweakSlow] = InputSystem::GetFloatInput(IMGUI_NAVINPUT_TWEAKSLOW);
}
ImGui::NewFrame();
if (pGuiUpdate->showDemoWindow)
ImGui::ShowDemoWindow();
bool ret = false;
for (uint32_t compIndex = 0; compIndex < pGuiUpdate->componentCount; ++compIndex)
{
GuiComponent* pComponent = pGuiUpdate->pGuiComponents[compIndex];
eastl::string title = pComponent->mTitle;
int32_t guiComponentFlags = pComponent->mFlags;
bool* pCloseButtonActiveValue = pComponent->mHasCloseButton ? &pComponent->mHasCloseButton : NULL;
const eastl::vector<eastl::string>& contextualMenuLabels = pComponent->mContextualMenuLabels;
const eastl::vector<WidgetCallback>& contextualMenuCallbacks = pComponent->mContextualMenuCallbacks;
const float4& windowRect = pComponent->mInitialWindowRect;
float4& currentWindowRect = pComponent->mCurrentWindowRect;
IWidget** pProps = pComponent->mWidgets.data();
uint32_t propCount = (uint32_t)pComponent->mWidgets.size();
if (title == "")
title.sprintf("##%llu", (uint64_t)pComponent);
// Setup the ImGuiWindowFlags
ImGuiWindowFlags guiWinFlags = GUI_COMPONENT_FLAGS_NONE;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_TITLE_BAR)
guiWinFlags |= ImGuiWindowFlags_NoTitleBar;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_RESIZE)
guiWinFlags |= ImGuiWindowFlags_NoResize;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_MOVE)
guiWinFlags |= ImGuiWindowFlags_NoMove;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_SCROLLBAR)
guiWinFlags |= ImGuiWindowFlags_NoScrollbar;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_COLLAPSE)
guiWinFlags |= ImGuiWindowFlags_NoCollapse;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_ALWAYS_AUTO_RESIZE)
guiWinFlags |= ImGuiWindowFlags_AlwaysAutoResize;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_INPUTS)
guiWinFlags |= ImGuiWindowFlags_NoInputs;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_MEMU_BAR)
guiWinFlags |= ImGuiWindowFlags_MenuBar;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_HORIZONTAL_SCROLLBAR)
guiWinFlags |= ImGuiWindowFlags_HorizontalScrollbar;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_FOCUS_ON_APPEARING)
guiWinFlags |= ImGuiWindowFlags_NoFocusOnAppearing;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_BRING_TO_FRONT_ON_FOCUS)
guiWinFlags |= ImGuiWindowFlags_NoBringToFrontOnFocus;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_ALWAYS_VERTICAL_SCROLLBAR)
guiWinFlags |= ImGuiWindowFlags_AlwaysVerticalScrollbar;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_ALWAYS_HORIZONTAL_SCROLLBAR)
guiWinFlags |= ImGuiWindowFlags_AlwaysHorizontalScrollbar;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_ALWAYS_USE_WINDOW_PADDING)
guiWinFlags |= ImGuiWindowFlags_AlwaysUseWindowPadding;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_NAV_INPUT)
guiWinFlags |= ImGuiWindowFlags_NoNavInputs;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_NAV_FOCUS)
guiWinFlags |= ImGuiWindowFlags_NoNavFocus;
bool result = ImGui::Begin(title.c_str(), pCloseButtonActiveValue, guiWinFlags);
if (result)
{
// Setup the contextual menus
if (!contextualMenuLabels.empty() && ImGui::BeginPopupContextItem()) // <-- This is using IsItemHovered()
{
for (size_t i = 0; i < contextualMenuLabels.size(); i++)
{
if (ImGui::MenuItem(contextualMenuLabels[i].c_str()))
{
if (i < contextualMenuCallbacks.size())
contextualMenuCallbacks[i]();
}
}
ImGui::EndPopup();
}
bool overrideSize = false;
bool overridePos = false;
if ((guiComponentFlags & GUI_COMPONENT_FLAGS_NO_RESIZE) && !(guiComponentFlags & GUI_COMPONENT_FLAGS_ALWAYS_AUTO_RESIZE))
overrideSize = true;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_MOVE)
overridePos = true;
ImGui::SetWindowSize(
float2(windowRect.z * dpiScale.x, windowRect.w * dpiScale.y), overrideSize ? ImGuiCond_Always : ImGuiCond_Once);
ImGui::SetWindowPos(
float2(windowRect.x * dpiScale.x, windowRect.y * dpiScale.y), overridePos ? ImGuiCond_Always : ImGuiCond_Once);
float2 min = ImGui::GetWindowPos();
float2 max = ImGui::GetWindowSize();
currentWindowRect.x = min.x;
currentWindowRect.y = min.y;
currentWindowRect.z = max.x;
currentWindowRect.w = max.y;
for (uint32_t i = 0; i < propCount; ++i)
if (pProps[i])
pProps[i]->Draw();
if (!ret)
ret = ImGui::GetIO().WantCaptureMouse;
}
// Need to call ImGui::End event if result is false since we called ImGui::Begin
ImGui::End();
}
ImGui::EndFrame();
// Flush key down array since onInput will apply the right states again next frame
for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++)
io.KeysDown[i] = 0;
mHandledGestures = false;
return ret;
}
void ImguiGUIDriver::draw(Cmd* pCmd)
{
/************************************************************************/
/************************************************************************/
ImGui::Render();
frameIdx = (frameIdx + 1) % MAX_FRAMES;
ImDrawData* draw_data = ImGui::GetDrawData();
Pipeline* pPipeline = pPipelineTextured;
uint32_t vSize = 0;
uint32_t iSize = 0;
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
vSize += (int)(cmd_list->VtxBuffer.size() * sizeof(ImDrawVert));
iSize += (int)(cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx));
}
vSize = min<uint32_t>(vSize, VERTEX_BUFFER_SIZE);
iSize = min<uint32_t>(iSize, INDEX_BUFFER_SIZE);
// Copy and convert all vertices into a single contiguous buffer
uint64_t vOffset = frameIdx * VERTEX_BUFFER_SIZE;
uint64_t iOffset = frameIdx * INDEX_BUFFER_SIZE;
uint64_t vtx_dst = vOffset;
uint64_t idx_dst = iOffset;
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
BufferUpdateDesc update = { pVertexBuffer, cmd_list->VtxBuffer.data(), 0, vtx_dst,
cmd_list->VtxBuffer.size() * sizeof(ImDrawVert) };
updateResource(&update);
update = { pIndexBuffer, cmd_list->IdxBuffer.data(), 0, idx_dst, cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx) };
updateResource(&update);
vtx_dst += (cmd_list->VtxBuffer.size() * sizeof(ImDrawVert));
idx_dst += (cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx));
}
float L = draw_data->DisplayPos.x;
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
float T = draw_data->DisplayPos.y;
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
float mvp[4][4] = {
{ 2.0f / (R - L), 0.0f, 0.0f, 0.0f },
{ 0.0f, 2.0f / (T - B), 0.0f, 0.0f },
{ 0.0f, 0.0f, 0.5f, 0.0f },
{ (R + L) / (L - R), (T + B) / (B - T), 0.5f, 1.0f },
};
uint64_t uOffset = frameIdx * mUniformSize;
BufferUpdateDesc update = { pUniformBuffer, mvp, 0, uOffset, sizeof(mvp) };
updateResource(&update);
cmdSetViewport(pCmd, 0.0f, 0.0f, draw_data->DisplaySize.x, draw_data->DisplaySize.y, 0.0f, 1.0f);
cmdSetScissor(
pCmd, (uint32_t)draw_data->DisplayPos.x, (uint32_t)draw_data->DisplayPos.y, (uint32_t)draw_data->DisplaySize.x,
(uint32_t)draw_data->DisplaySize.y);
cmdBindPipeline(pCmd, pPipeline);
cmdBindIndexBuffer(pCmd, pIndexBuffer, iOffset);
cmdBindVertexBuffer(pCmd, 1, &pVertexBuffer, &vOffset);
DescriptorData params[1] = {};
params[0].pName = "uniformBlockVS";
params[0].pOffsets = &uOffset;
params[0].ppBuffers = &pUniformBuffer;
cmdBindDescriptors(pCmd, pDescriptorBinderTextured, pRootSignatureTextured, 1, params);
// Render command lists
int vtx_offset = 0;
int idx_offset = 0;
float2 pos = draw_data->DisplayPos;
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback)
{
// User callback (registered via ImDrawList::AddCallback)
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
// Apply scissor/clipping rectangle
//const D3D12_RECT r = { (LONG)(pcmd->ClipRect.x - pos.x), (LONG)(pcmd->ClipRect.y - pos.y), (LONG)(pcmd->ClipRect.z - pos.x), (LONG)(pcmd->ClipRect.w - pos.y) };
//pCmd->pDxCmdList->RSSetScissorRects(1, &r);
cmdSetScissor(
pCmd, (uint32_t)(pcmd->ClipRect.x - pos.x), (uint32_t)(pcmd->ClipRect.y - pos.y),
(uint32_t)(pcmd->ClipRect.z - pcmd->ClipRect.x), (uint32_t)(pcmd->ClipRect.w - pcmd->ClipRect.y));
DescriptorData params[1] = {};
params[0].pName = "uTex";
params[0].ppTextures = (Texture**)&pcmd->TextureId;
cmdBindDescriptors(pCmd, pDescriptorBinderTextured, pRootSignatureTextured, 1, params);
cmdDrawIndexed(pCmd, pcmd->ElemCount, idx_offset, vtx_offset);
}
idx_offset += pcmd->ElemCount;
}
vtx_offset += (int)cmd_list->VtxBuffer.size();
}
}
int ImguiGUIDriver::needsTextInput() const
{
//The User flags are not what I expect them to be.
//We need access to Per-Component InputFlags
ImGuiContext* guiContext = (ImGuiContext*)this->context;
ImGuiInputTextFlags currentInputFlags = guiContext->InputTextState.UserFlags;
//0 -> Not pressed
//1 -> Digits Only keyboard
//2 -> Full Keyboard (Chars + Digits)
int inputState = ImGui::GetIO().WantTextInput ? 2 : 0;
//keyboard only Numbers
if (inputState > 0 && (currentInputFlags & ImGuiInputTextFlags_CharsDecimal))
{
inputState = 1;
}
return inputState;
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile: TestHandleWidget.cxx,v $
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
//
// This example tests the vtkSliderWidget.
#include "vtkConeSource.h"
#include "vtkGlyph3D.h"
#include "vtkSphereSource.h"
#include "vtkAppendPolyData.h"
#include "vtkHandleWidget.h"
#include "vtkPointHandleRepresentation3D.h"
#include "vtkCoordinate.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkCommand.h"
#include "vtkInteractorEventRecorder.h"
#include "vtkDebugLeaks.h"
#include "vtkOutlineFilter.h"
#include "vtkImplicitPlaneWidget2.h"
#include "vtkImplicitPlaneRepresentation.h"
#include "vtkBoundedPlanePointPlacer.h"
#include "vtkCutter.h"
#include "vtkLODActor.h"
#include "vtkPlane.h"
#include "vtkProperty.h"
#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"
// -----------------------------------------------------------------------
// This does the actual work: updates the vtkPline implicit function.
// This in turn causes the pipeline to update and clip the object.
// Callback for the interaction
class vtkTIPW3Callback : public vtkCommand
{
public:
static vtkTIPW3Callback *New()
{ return new vtkTIPW3Callback; }
virtual void Execute(vtkObject *caller, unsigned long, void*)
{
vtkImplicitPlaneWidget2 *planeWidget =
reinterpret_cast<vtkImplicitPlaneWidget2*>(caller);
vtkImplicitPlaneRepresentation *rep =
reinterpret_cast<vtkImplicitPlaneRepresentation*>(planeWidget->GetRepresentation());
rep->GetPlane(this->Plane);
this->Actor->VisibilityOn();
}
vtkTIPW3Callback() : Actor(0) { this->Plane = vtkPlane::New(); }
~vtkTIPW3Callback() { this->Plane->Delete(); }
vtkPlane *Plane;
vtkActor *Actor;
};
// -----------------------------------------------------------------------
char HandleWidgetLog[] =
"# StreamVersion 1\n"
"ConfigureEvent 600 -1 0 0 0 0 0 i\n"
"ExposeEvent 300 299 0 0 0 0 0 i\n"
"EnterEvent 598 197 0 0 0 0 0 i\n"
"MouseMoveEvent 586 197 0 0 0 0 0 i\n"
"MouseMoveEvent 585 197 0 0 0 0 0 i\n"
"MouseMoveEvent 585 196 0 0 0 0 0 i\n"
"MouseMoveEvent 585 195 0 0 0 0 0 i\n"
"MouseMoveEvent 585 194 0 0 0 0 0 i\n"
"MouseMoveEvent 581 188 0 0 0 0 0 i\n"
"MouseMoveEvent 571 184 0 0 0 0 0 i\n"
"MouseMoveEvent 559 180 0 0 0 0 0 i\n"
"MouseMoveEvent 549 178 0 0 0 0 0 i\n"
"MouseMoveEvent 547 177 0 0 0 0 0 i\n"
"MouseMoveEvent 548 177 0 0 0 0 0 i\n"
"MouseMoveEvent 550 177 0 0 0 0 0 i\n"
"MouseMoveEvent 551 176 0 0 0 0 0 i\n"
"MouseMoveEvent 551 175 0 0 0 0 0 i\n"
"MouseMoveEvent 552 175 0 0 0 0 0 i\n"
"MouseMoveEvent 552 174 0 0 0 0 0 i\n"
"KeyPressEvent 552 174 0 0 116 1 t i\n"
"CharEvent 552 174 0 0 116 1 t i\n"
"KeyReleaseEvent 552 174 0 0 116 1 t i\n"
"MouseMoveEvent 546 176 0 0 0 0 t i\n"
"MouseMoveEvent 530 188 0 0 0 0 t i\n"
"MouseMoveEvent 504 218 0 0 0 0 t i\n"
"MouseMoveEvent 504 226 0 0 0 0 t i\n"
"MouseMoveEvent 518 214 0 0 0 0 t i\n"
"MouseMoveEvent 528 208 0 0 0 0 t i\n"
"MouseMoveEvent 534 206 0 0 0 0 t i\n"
"MouseMoveEvent 540 200 0 0 0 0 t i\n"
"MouseMoveEvent 548 194 0 0 0 0 t i\n"
"MouseMoveEvent 556 186 0 0 0 0 t i\n"
"MouseMoveEvent 566 178 0 0 0 0 t i\n"
"MouseMoveEvent 567 178 0 0 0 0 t i\n"
"MouseMoveEvent 568 179 0 0 0 0 t i\n"
"MouseMoveEvent 569 179 0 0 0 0 t i\n"
"MouseMoveEvent 569 180 0 0 0 0 t i\n"
"MouseMoveEvent 569 181 0 0 0 0 t i\n"
"MouseMoveEvent 570 181 0 0 0 0 t i\n"
"MouseMoveEvent 570 182 0 0 0 0 t i\n"
"LeftButtonPressEvent 570 182 0 0 0 0 t i\n"
"MouseMoveEvent 345 96 0 0 0 0 t i\n"
"MouseMoveEvent 347 106 0 0 0 0 t i\n"
"MouseMoveEvent 347 124 0 0 0 0 t i\n"
"MouseMoveEvent 349 148 0 0 0 0 t i\n"
"MouseMoveEvent 349 172 0 0 0 0 t i\n"
"MouseMoveEvent 349 198 0 0 0 0 t i\n"
"MouseMoveEvent 349 222 0 0 0 0 t i\n"
"MouseMoveEvent 347 244 0 0 0 0 t i\n"
"MouseMoveEvent 343 264 0 0 0 0 t i\n"
"MouseMoveEvent 341 276 0 0 0 0 t i\n"
"MouseMoveEvent 335 286 0 0 0 0 t i\n"
"MouseMoveEvent 333 292 0 0 0 0 t i\n"
"MouseMoveEvent 332 294 0 0 0 0 t i\n"
"MouseMoveEvent 331 295 0 0 0 0 t i\n"
"MouseMoveEvent 330 297 0 0 0 0 t i\n"
"MouseMoveEvent 329 299 0 0 0 0 t i\n"
"MouseMoveEvent 327 305 0 0 0 0 t i\n"
"MouseMoveEvent 321 313 0 0 0 0 t i\n"
"MouseMoveEvent 320 315 0 0 0 0 t i\n"
"MouseMoveEvent 314 319 0 0 0 0 t i\n"
"MouseMoveEvent 308 325 0 0 0 0 t i\n"
"MouseMoveEvent 304 329 0 0 0 0 t i\n"
"MouseMoveEvent 298 335 0 0 0 0 t i\n"
"MouseMoveEvent 292 339 0 0 0 0 t i\n"
"MouseMoveEvent 288 343 0 0 0 0 t i\n"
"MouseMoveEvent 282 345 0 0 0 0 t i\n"
"MouseMoveEvent 281 346 0 0 0 0 t i\n"
"MouseMoveEvent 279 346 0 0 0 0 t i\n"
"MouseMoveEvent 278 346 0 0 0 0 t i\n"
"MouseMoveEvent 278 348 0 0 0 0 t i\n"
"MouseMoveEvent 279 350 0 0 0 0 t i\n"
"MouseMoveEvent 279 352 0 0 0 0 t i\n"
"MouseMoveEvent 279 353 0 0 0 0 t i\n"
"MouseMoveEvent 279 355 0 0 0 0 t i\n"
"MouseMoveEvent 279 354 0 0 0 0 t i\n"
"MouseMoveEvent 279 353 0 0 0 0 t i\n"
"MouseMoveEvent 279 352 0 0 0 0 t i\n"
"MouseMoveEvent 279 350 0 0 0 0 t i\n"
"MouseMoveEvent 279 349 0 0 0 0 t i\n"
"MouseMoveEvent 280 348 0 0 0 0 t i\n"
"MouseMoveEvent 281 347 0 0 0 0 t i\n"
"MouseMoveEvent 281 346 0 0 0 0 t i\n"
"MouseMoveEvent 282 346 0 0 0 0 t i\n"
"LeftButtonPressEvent 282 346 0 0 0 0 t i\n"
"MouseMoveEvent 375 323 0 0 0 0 t i\n"
"MouseMoveEvent 369 321 0 0 0 0 t i\n"
"MouseMoveEvent 361 319 0 0 0 0 t i\n"
"MouseMoveEvent 351 317 0 0 0 0 t i\n"
"MouseMoveEvent 333 315 0 0 0 0 t i\n"
"MouseMoveEvent 317 315 0 0 0 0 t i\n"
"MouseMoveEvent 301 315 0 0 0 0 t i\n"
"MouseMoveEvent 287 317 0 0 0 0 t i\n"
"MouseMoveEvent 273 319 0 0 0 0 t i\n"
"MouseMoveEvent 265 319 0 0 0 0 t i\n"
"MouseMoveEvent 264 319 0 0 0 0 t i\n"
"MouseMoveEvent 263 319 0 0 0 0 t i\n"
"MouseMoveEvent 263 318 0 0 0 0 t i\n"
"MouseMoveEvent 264 318 0 0 0 0 t i\n"
"MouseMoveEvent 265 318 0 0 0 0 t i\n"
"MouseMoveEvent 266 318 0 0 0 0 t i\n"
"MouseMoveEvent 267 317 0 0 0 0 t i\n"
"MouseMoveEvent 275 315 0 0 0 0 t i\n"
"MouseMoveEvent 281 311 0 0 0 0 t i\n"
"MouseMoveEvent 287 309 0 0 0 0 t i\n"
"MouseMoveEvent 290 309 0 0 0 0 t i\n"
"MouseMoveEvent 291 309 0 0 0 0 t i\n"
"MouseMoveEvent 292 309 0 0 0 0 t i\n"
"LeftButtonPressEvent 292 309 0 0 0 0 t i\n"
"MouseMoveEvent 358 228 0 0 0 0 t i\n"
"MouseMoveEvent 358 238 0 0 0 0 t i\n"
"MouseMoveEvent 358 250 0 0 0 0 t i\n"
"MouseMoveEvent 358 258 0 0 0 0 t i\n"
"MouseMoveEvent 358 268 0 0 0 0 t i\n"
"MouseMoveEvent 358 271 0 0 0 0 t i\n"
"MouseMoveEvent 356 279 0 0 0 0 t i\n"
"MouseMoveEvent 354 285 0 0 0 0 t i\n"
"MouseMoveEvent 354 287 0 0 0 0 t i\n"
"MouseMoveEvent 352 293 0 0 0 0 t i\n"
"MouseMoveEvent 351 295 0 0 0 0 t i\n"
"MouseMoveEvent 350 297 0 0 0 0 t i\n"
"MouseMoveEvent 350 298 0 0 0 0 t i\n"
"MouseMoveEvent 350 299 0 0 0 0 t i\n"
"MouseMoveEvent 350 300 0 0 0 0 t i\n"
"MouseMoveEvent 350 301 0 0 0 0 t i\n"
"MouseMoveEvent 350 302 0 0 0 0 t i\n"
"MouseMoveEvent 350 303 0 0 0 0 t i\n"
"MouseMoveEvent 350 304 0 0 0 0 t i\n"
"MouseMoveEvent 351 305 0 0 0 0 t i\n"
"MouseMoveEvent 351 306 0 0 0 0 t i\n"
"MouseMoveEvent 351 307 0 0 0 0 t i\n"
"MouseMoveEvent 352 308 0 0 0 0 t i\n"
"MouseMoveEvent 352 309 0 0 0 0 t i\n"
"MouseMoveEvent 353 309 0 0 0 0 t i\n"
"MouseMoveEvent 353 310 0 0 0 0 t i\n"
"MouseMoveEvent 353 311 0 0 0 0 t i\n"
"MouseMoveEvent 353 312 0 0 0 0 t i\n"
"MouseMoveEvent 353 313 0 0 0 0 t i\n"
"MouseMoveEvent 353 314 0 0 0 0 t i\n"
"LeftButtonPressEvent 353 314 0 0 0 0 t i\n"
"MouseMoveEvent 338 439 0 0 0 0 t i\n"
"MouseMoveEvent 338 429 0 0 0 0 t i\n"
"MouseMoveEvent 344 413 0 0 0 0 t i\n"
"MouseMoveEvent 356 395 0 0 0 0 t i\n"
"MouseMoveEvent 378 381 0 0 0 0 t i\n"
"MouseMoveEvent 406 373 0 0 0 0 t i\n"
"MouseMoveEvent 440 365 0 0 0 0 t i\n"
"MouseMoveEvent 470 365 0 0 0 0 t i\n"
"MouseMoveEvent 490 365 0 0 0 0 t i\n"
"MouseMoveEvent 498 369 0 0 0 0 t i\n"
"MouseMoveEvent 499 371 0 0 0 0 t i\n"
"MouseMoveEvent 500 373 0 0 0 0 t i\n"
"MouseMoveEvent 500 374 0 0 0 0 t i\n"
"MouseMoveEvent 500 376 0 0 0 0 t i\n"
"MouseMoveEvent 500 378 0 0 0 0 t i\n"
"MouseMoveEvent 500 386 0 0 0 0 t i\n"
"MouseMoveEvent 500 394 0 0 0 0 t i\n"
"MouseMoveEvent 498 402 0 0 0 0 t i\n"
"MouseMoveEvent 498 412 0 0 0 0 t i\n"
"MouseMoveEvent 494 418 0 0 0 0 t i\n"
"MouseMoveEvent 492 426 0 0 0 0 t i\n"
"MouseMoveEvent 488 434 0 0 0 0 t i\n"
"MouseMoveEvent 482 440 0 0 0 0 t i\n"
"MouseMoveEvent 474 448 0 0 0 0 t i\n"
"MouseMoveEvent 472 454 0 0 0 0 t i\n"
"MouseMoveEvent 471 456 0 0 0 0 t i\n"
"MouseMoveEvent 470 456 0 0 0 0 t i\n"
"MouseMoveEvent 470 457 0 0 0 0 t i\n"
"MouseMoveEvent 470 459 0 0 0 0 t i\n"
"MouseMoveEvent 470 460 0 0 0 0 t i\n"
"LeftButtonPressEvent 470 460 0 0 0 0 t i\n"
"MouseMoveEvent 536 235 0 0 0 0 t i\n"
"MouseMoveEvent 530 241 0 0 0 0 t i\n"
"MouseMoveEvent 516 247 0 0 0 0 t i\n"
"MouseMoveEvent 500 255 0 0 0 0 t i\n"
"MouseMoveEvent 484 263 0 0 0 0 t i\n"
"MouseMoveEvent 472 269 0 0 0 0 t i\n"
"MouseMoveEvent 460 273 0 0 0 0 t i\n"
"MouseMoveEvent 452 279 0 0 0 0 t i\n"
"MouseMoveEvent 444 281 0 0 0 0 t i\n"
"MouseMoveEvent 443 281 0 0 0 0 t i\n"
"MouseMoveEvent 443 282 0 0 0 0 t i\n"
"MouseMoveEvent 441 282 0 0 0 0 t i\n"
"MouseMoveEvent 439 283 0 0 0 0 t i\n"
"MouseMoveEvent 433 285 0 0 0 0 t i\n"
"MouseMoveEvent 423 285 0 0 0 0 t i\n"
"MouseMoveEvent 413 287 0 0 0 0 t i\n"
"MouseMoveEvent 410 287 0 0 0 0 t i\n"
"MouseMoveEvent 408 287 0 0 0 0 t i\n"
"MouseMoveEvent 407 287 0 0 0 0 t i\n"
"MouseMoveEvent 407 288 0 0 0 0 t i\n"
"MouseMoveEvent 407 289 0 0 0 0 t i\n"
"MouseMoveEvent 406 289 0 0 0 0 t i\n"
"MouseMoveEvent 406 290 0 0 0 0 t i\n"
"LeftButtonPressEvent 406 290 0 0 0 0 t i\n"
"MouseMoveEvent 403 413 0 0 0 0 t i\n"
"MouseMoveEvent 395 409 0 0 0 0 t i\n"
"MouseMoveEvent 387 401 0 0 0 0 t i\n"
"MouseMoveEvent 377 393 0 0 0 0 t i\n"
"MouseMoveEvent 369 385 0 0 0 0 t i\n"
"MouseMoveEvent 363 381 0 0 0 0 t i\n"
"MouseMoveEvent 362 379 0 0 0 0 t i\n"
"MouseMoveEvent 361 378 0 0 0 0 t i\n"
"MouseMoveEvent 361 377 0 0 0 0 t i\n"
"MouseMoveEvent 362 377 0 0 0 0 t i\n"
"MouseMoveEvent 366 381 0 0 0 0 t i\n"
"MouseMoveEvent 367 381 0 0 0 0 t i\n"
"MouseMoveEvent 368 382 0 0 0 0 t i\n"
"MouseMoveEvent 368 383 0 0 0 0 t i\n"
"MouseMoveEvent 369 383 0 0 0 0 t i\n"
"LeftButtonPressEvent 369 383 0 0 0 0 t i\n"
"MouseMoveEvent 455 388 0 0 0 0 t i\n"
"MouseMoveEvent 447 388 0 0 0 0 t i\n"
"MouseMoveEvent 439 386 0 0 0 0 t i\n"
"MouseMoveEvent 431 386 0 0 0 0 t i\n"
"MouseMoveEvent 428 386 0 0 0 0 t i\n"
"MouseMoveEvent 426 386 0 0 0 0 t i\n"
"MouseMoveEvent 425 386 0 0 0 0 t i\n"
"MouseMoveEvent 424 386 0 0 0 0 t i\n"
"MouseMoveEvent 423 386 0 0 0 0 t i\n"
"MouseMoveEvent 423 387 0 0 0 0 t i\n"
"MouseMoveEvent 423 388 0 0 0 0 t i\n"
"MouseMoveEvent 422 389 0 0 0 0 t i\n"
"MouseMoveEvent 422 390 0 0 0 0 t i\n"
"MouseMoveEvent 421 390 0 0 0 0 t i\n"
"MouseMoveEvent 421 391 0 0 0 0 t i\n"
"MouseMoveEvent 420 392 0 0 0 0 t i\n"
"MouseMoveEvent 420 393 0 0 0 0 t i\n"
"MouseMoveEvent 420 394 0 0 0 0 t i\n"
"MouseMoveEvent 419 394 0 0 0 0 t i\n"
"LeftButtonPressEvent 419 394 0 0 0 0 t i\n"
"MouseMoveEvent 395 280 0 0 0 0 t i\n"
"MouseMoveEvent 395 279 0 0 0 0 t i\n"
"MouseMoveEvent 397 273 0 0 0 0 t i\n"
"MouseMoveEvent 401 267 0 0 0 0 t i\n"
"MouseMoveEvent 405 261 0 0 0 0 t i\n"
"MouseMoveEvent 411 253 0 0 0 0 t i\n"
"MouseMoveEvent 415 245 0 0 0 0 t i\n"
"MouseMoveEvent 421 237 0 0 0 0 t i\n"
"MouseMoveEvent 429 229 0 0 0 0 t i\n"
"MouseMoveEvent 437 219 0 0 0 0 t i\n"
"MouseMoveEvent 445 211 0 0 0 0 t i\n"
"MouseMoveEvent 451 205 0 0 0 0 t i\n"
"MouseMoveEvent 452 203 0 0 0 0 t i\n"
"MouseMoveEvent 453 202 0 0 0 0 t i\n"
"MouseMoveEvent 454 202 0 0 0 0 t i\n"
"MouseMoveEvent 454 201 0 0 0 0 t i\n"
"MouseMoveEvent 454 199 0 0 0 0 t i\n"
"MouseMoveEvent 454 198 0 0 0 0 t i\n"
"MouseMoveEvent 454 195 0 0 0 0 t i\n"
"MouseMoveEvent 454 194 0 0 0 0 t i\n"
"MouseMoveEvent 454 193 0 0 0 0 t i\n"
"MouseMoveEvent 454 190 0 0 0 0 t i\n"
"MouseMoveEvent 454 187 0 0 0 0 t i\n"
"MouseMoveEvent 456 181 0 0 0 0 t i\n"
"MouseMoveEvent 456 179 0 0 0 0 t i\n"
"MouseMoveEvent 456 178 0 0 0 0 t i\n"
"MouseMoveEvent 456 177 0 0 0 0 t i\n"
"MouseMoveEvent 457 176 0 0 0 0 t i\n"
"KeyPressEvent 457 176 0 0 113 1 q i\n"
"CharEvent 457 176 0 0 113 1 q i\n"
"ExitEvent 457 176 0 0 113 1 q i\n"
;
// -----------------------------------------------------------------------
int TestHandleWidget( int argc, char *argv[] )
{
// Create a mace out of filters.
//
vtkSphereSource *sphere = vtkSphereSource::New();
vtkConeSource *cone = vtkConeSource::New();
vtkGlyph3D *glyph = vtkGlyph3D::New();
glyph->SetInputConnection(sphere->GetOutputPort());
glyph->SetSource(cone->GetOutput());
glyph->SetVectorModeToUseNormal();
glyph->SetScaleModeToScaleByVector();
glyph->SetScaleFactor(0.25);
// The sphere and spikes are appended into a single polydata.
// This just makes things simpler to manage.
vtkAppendPolyData *apd = vtkAppendPolyData::New();
apd->AddInput(glyph->GetOutput());
apd->AddInput(sphere->GetOutput());
// This portion of the code clips the mace with the vtkPlanes
// implicit function. The cut region is colored green.
vtkTIPW3Callback *myCallback = vtkTIPW3Callback::New();
vtkCutter *cutter = vtkCutter::New();
cutter->SetInputConnection(apd->GetOutputPort());
cutter->SetCutFunction( myCallback->Plane );
vtkPolyDataMapper *selectMapper = vtkPolyDataMapper::New();
selectMapper->SetInputConnection(cutter->GetOutputPort());
vtkLODActor *selectActor = vtkLODActor::New();
selectActor->SetMapper(selectMapper);
selectActor->GetProperty()->SetColor(0,1,0);
selectActor->VisibilityOff();
selectActor->SetScale(1.01, 1.01, 1.01);
vtkOutlineFilter* outline = vtkOutlineFilter::New();
outline->SetInputConnection(apd->GetOutputPort());
vtkPolyDataMapper* outlineMapper = vtkPolyDataMapper::New();
outlineMapper->SetInputConnection(outline->GetOutputPort());
vtkActor* outlineActor = vtkActor::New();
outlineActor->SetMapper( outlineMapper);
vtkImplicitPlaneRepresentation *rep = vtkImplicitPlaneRepresentation::New();
rep->SetPlaceFactor(0.7);
rep->GetPlaneProperty()->SetAmbientColor(0.0, 0.5, 0.5);
rep->GetPlaneProperty()->SetOpacity(0.3);
rep->PlaceWidget(outline->GetOutput()->GetBounds());
vtkImplicitPlaneWidget2 *planeWidget = vtkImplicitPlaneWidget2::New();
planeWidget->SetRepresentation(rep);
myCallback->Actor = selectActor;
planeWidget->AddObserver(vtkCommand::InteractionEvent,myCallback);
// Create the RenderWindow, Renderer and both Actors
//
vtkRenderer *ren1 = vtkRenderer::New();
vtkRenderWindow *renWin = vtkRenderWindow::New();
renWin->AddRenderer(ren1);
vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow(renWin);
// VTK widgets consist of two parts: the widget part that handles event processing;
// and the widget representation that defines how the widget appears in the scene
// (i.e., matters pertaining to geometry).
vtkPointHandleRepresentation3D *handleRep
= vtkPointHandleRepresentation3D::New();
handleRep->SetPlaceFactor(2.5);
handleRep->PlaceWidget(outlineActor->GetBounds());
handleRep->SetHandleSize(10);
vtkHandleWidget *handleWidget = vtkHandleWidget::New();
handleWidget->SetInteractor(iren);
planeWidget->SetInteractor(iren);
handleWidget->SetRepresentation(handleRep);
ren1->AddActor(selectActor);
ren1->AddActor(outlineActor);
// Add the actors to the renderer, set the background and size
//
// record events
vtkInteractorEventRecorder *recorder = vtkInteractorEventRecorder::New();
recorder->SetInteractor(iren);
//recorder->SetFileName("/tmp/record.log");
recorder->ReadFromInputStringOn();
recorder->SetInputString(HandleWidgetLog);
recorder->EnabledOn();
// Should we constrain the handles to the oblique plane ?
bool constrainHandlesToObliquePlane = false;
for (int i = 0; i < argc; i++)
{
if (strcmp("-ConstrainHandlesToPlane", argv[i]) == 0)
{
constrainHandlesToObliquePlane = true;
break;
}
}
// Set some defaults.
//
rep->SetNormal(0.942174, 0.25322, 0.219519);
double worldPos[3] = {-0.0417953, 0.202206, -0.0538641};
handleRep->SetWorldPosition(worldPos);
rep->GetPlane(myCallback->Plane);
if (constrainHandlesToObliquePlane)
{
vtkBoundedPlanePointPlacer *placer = vtkBoundedPlanePointPlacer::New();
// Define the the plane as the image plane widget's plane
placer->SetProjectionNormalToOblique();
placer->SetObliquePlane(myCallback->Plane);
// Also add bounding planes for the bounds of the dataset.
double bounds[6];
outline->GetOutput()->GetBounds(bounds);
vtkPlane *plane;
plane = vtkPlane::New();
plane->SetOrigin( bounds[0], bounds[2], bounds[4] );
plane->SetNormal( 1.0, 0.0, 0.0 );
placer->AddBoundingPlane( plane );
plane->Delete();
plane = vtkPlane::New();
plane->SetOrigin( bounds[1], bounds[3], bounds[5] );
plane->SetNormal( -1.0, 0.0, 0.0 );
placer->AddBoundingPlane( plane );
plane->Delete();
plane = vtkPlane::New();
plane->SetOrigin( bounds[0], bounds[2], bounds[4] );
plane->SetNormal( 0.0, 1.0, 0.0 );
placer->AddBoundingPlane( plane );
plane->Delete();
plane = vtkPlane::New();
plane->SetOrigin( bounds[1], bounds[3], bounds[5] );
plane->SetNormal( 0.0, -1.0, 0.0 );
placer->AddBoundingPlane( plane );
plane->Delete();
plane = vtkPlane::New();
plane->SetOrigin( bounds[0], bounds[2], bounds[4] );
plane->SetNormal( 0.0, 0.0, 1.0 );
placer->AddBoundingPlane( plane );
plane->Delete();
plane = vtkPlane::New();
plane->SetOrigin( bounds[1], bounds[3], bounds[5] );
plane->SetNormal( 0.0, 0.0, -1.0 );
placer->AddBoundingPlane( plane );
plane->Delete();
handleRep->SetPointPlacer(placer);
placer->Delete();
}
iren->Initialize();
handleWidget->EnabledOn();
planeWidget->EnabledOn();
ren1->SetBackground(0.1, 0.2, 0.4);
renWin->SetSize(600, 600);
ren1->ResetCamera();
ren1->ResetCameraClippingRange();
renWin->Render();
recorder->Play();
int retVal = vtkRegressionTestImage( renWin );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
recorder->Off();
recorder->Delete();
apd->Delete();
planeWidget->Delete();
glyph->Delete();
sphere->Delete();
cone->Delete();
rep->Delete();
myCallback->Delete();
selectMapper->Delete();
selectActor->Delete();
cutter->Delete();
outline->Delete();
outlineMapper->Delete();
outlineActor->Delete();
handleWidget->Delete();
handleRep->Delete();
iren->Delete();
renWin->Delete();
ren1->Delete();
return !retVal;
}
|
/******************************************************************************
*
* Project: GDAL
* Purpose: ECW (ERDAS Wavelet Compression Format) Driver
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 2001, Frank Warmerdam <warmerdam@pobox.com>
* Copyright (c) 2007-2013, Even Rouault <even dot rouault at spatialys.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
// ncsjpcbuffer.h needs the min and max macros.
#undef NOMINMAX
#include "cpl_minixml.h"
#include "gdal_ecw.h"
#include "gdal_frmts.h"
#include "ogr_spatialref.h"
#include "ogr_api.h"
#include "../mem/memdataset.h"
CPL_CVSID("$Id$")
#undef NOISY_DEBUG
#ifdef FRMT_ecw
constexpr unsigned char jpc_header[] = {0xff,0x4f,0xff,0x51}; // SOC + RSIZ markers
constexpr unsigned char jp2_header[] =
{0x00,0x00,0x00,0x0c,0x6a,0x50,0x20,0x20,0x0d,0x0a,0x87,0x0a};
static CPLMutex *hECWDatasetMutex = nullptr;
static int bNCSInitialized = FALSE;
void ECWInitialize( void );
extern "C" int CPL_DLL GDALIsInGlobalDestructor(void);
#define BLOCK_SIZE 256
GDALDataset* ECWDatasetOpenJPEG2000(GDALOpenInfo* poOpenInfo);
/************************************************************************/
/* ECWReportError() */
/************************************************************************/
void ECWReportError(CNCSError& oErr, const char* pszMsg)
{
#if ECWSDK_VERSION<50
char* pszErrorMessage = oErr.GetErrorMessage();
CPLError( CE_Failure, CPLE_AppDefined,
"%s%s", pszMsg, pszErrorMessage );
NCSFree(pszErrorMessage);
#else
CPLError( CE_Failure, CPLE_AppDefined,
"%s%s", pszMsg, NCSGetLastErrorText(oErr) );
#endif
}
/************************************************************************/
/* ECWRasterBand() */
/************************************************************************/
ECWRasterBand::ECWRasterBand( ECWDataset *poDSIn, int nBandIn, int iOverviewIn,
char** papszOpenOptions )
{
this->poDS = poDSIn;
poGDS = poDSIn;
this->iOverview = iOverviewIn;
this->nBand = nBandIn;
eDataType = poDSIn->eRasterDataType;
nRasterXSize = poDS->GetRasterXSize() / ( 1 << (iOverview+1));
nRasterYSize = poDS->GetRasterYSize() / ( 1 << (iOverview+1));
nBlockXSize = BLOCK_SIZE;
nBlockYSize = BLOCK_SIZE;
/* -------------------------------------------------------------------- */
/* Work out band color interpretation. */
/* -------------------------------------------------------------------- */
if( poDSIn->psFileInfo->eColorSpace == NCSCS_NONE )
eBandInterp = GCI_Undefined;
else if( poDSIn->psFileInfo->eColorSpace == NCSCS_GREYSCALE )
{
eBandInterp = GCI_GrayIndex;
//we could also have alpha band.
if ( strcmp(poDSIn->psFileInfo->pBands[nBand-1].szDesc, NCS_BANDDESC_AllOpacity) == 0 ||
strcmp(poDSIn->psFileInfo->pBands[nBand-1].szDesc, NCS_BANDDESC_GreyscaleOpacity) ==0 ){
eBandInterp = GCI_AlphaBand;
}
}else if (poDSIn->psFileInfo->eColorSpace == NCSCS_MULTIBAND ){
eBandInterp = ECWGetColorInterpretationByName(poDSIn->psFileInfo->pBands[nBand-1].szDesc);
}else if (poDSIn->psFileInfo->eColorSpace == NCSCS_sRGB){
eBandInterp = ECWGetColorInterpretationByName(poDSIn->psFileInfo->pBands[nBand-1].szDesc);
if( eBandInterp == GCI_Undefined )
{
if( nBand == 1 )
eBandInterp = GCI_RedBand;
else if( nBand == 2 )
eBandInterp = GCI_GreenBand;
else if( nBand == 3 )
eBandInterp = GCI_BlueBand;
else if (nBand == 4 )
{
if (strcmp(poDSIn->psFileInfo->pBands[nBand-1].szDesc, NCS_BANDDESC_AllOpacity) == 0)
eBandInterp = GCI_AlphaBand;
else
eBandInterp = GCI_Undefined;
}
else
{
eBandInterp = GCI_Undefined;
}
}
}
else if( poDSIn->psFileInfo->eColorSpace == NCSCS_YCbCr )
{
if( CPLTestBool( CPLGetConfigOption("CONVERT_YCBCR_TO_RGB","YES") ))
{
if( nBand == 1 )
eBandInterp = GCI_RedBand;
else if( nBand == 2 )
eBandInterp = GCI_GreenBand;
else if( nBand == 3 )
eBandInterp = GCI_BlueBand;
else
eBandInterp = GCI_Undefined;
}
else
{
if( nBand == 1 )
eBandInterp = GCI_YCbCr_YBand;
else if( nBand == 2 )
eBandInterp = GCI_YCbCr_CbBand;
else if( nBand == 3 )
eBandInterp = GCI_YCbCr_CrBand;
else
eBandInterp = GCI_Undefined;
}
}
else
eBandInterp = GCI_Undefined;
/* -------------------------------------------------------------------- */
/* If this is the base level, create a set of overviews. */
/* -------------------------------------------------------------------- */
if( iOverview == -1 )
{
int i;
for( i = 0;
nRasterXSize / (1 << (i+1)) > 128
&& nRasterYSize / (1 << (i+1)) > 128;
i++ )
{
apoOverviews.push_back( new ECWRasterBand( poDSIn, nBandIn, i, papszOpenOptions ) );
}
}
bPromoteTo8Bit =
poDSIn->psFileInfo->nBands == 4 && nBand == 4 &&
poDSIn->psFileInfo->pBands[0].nBits == 8 &&
poDSIn->psFileInfo->pBands[1].nBits == 8 &&
poDSIn->psFileInfo->pBands[2].nBits == 8 &&
poDSIn->psFileInfo->pBands[3].nBits == 1 &&
eBandInterp == GCI_AlphaBand &&
CPLFetchBool(papszOpenOptions, "1BIT_ALPHA_PROMOTION",
CPLTestBool(
CPLGetConfigOption("GDAL_ECW_PROMOTE_1BIT_ALPHA_AS_8BIT",
"YES")));
if( bPromoteTo8Bit )
CPLDebug("ECW", "Fourth (alpha) band is promoted from 1 bit to 8 bit");
if( (poDSIn->psFileInfo->pBands[nBand-1].nBits % 8) != 0 && !bPromoteTo8Bit )
GDALPamRasterBand::SetMetadataItem("NBITS",
CPLString().Printf("%d",poDSIn->psFileInfo->pBands[nBand-1].nBits),
"IMAGE_STRUCTURE" );
GDALPamRasterBand::SetDescription(poDSIn->psFileInfo->pBands[nBand-1].szDesc);
}
/************************************************************************/
/* ~ECWRasterBand() */
/************************************************************************/
ECWRasterBand::~ECWRasterBand()
{
GDALRasterBand::FlushCache();
while( !apoOverviews.empty() )
{
delete apoOverviews.back();
apoOverviews.pop_back();
}
}
/************************************************************************/
/* GetOverview() */
/************************************************************************/
GDALRasterBand *ECWRasterBand::GetOverview( int iOverviewIn )
{
if( iOverviewIn >= 0 && iOverviewIn < (int) apoOverviews.size() )
return apoOverviews[iOverviewIn];
else
return nullptr;
}
/************************************************************************/
/* GetColorInterpretation() */
/************************************************************************/
GDALColorInterp ECWRasterBand::GetColorInterpretation()
{
return eBandInterp;
}
/************************************************************************/
/* SetColorInterpretation() */
/* */
/* This would normally just be used by folks using the ECW code */
/* to read JP2 streams in other formats (such as NITF) and */
/* providing their own color interpretation regardless of what */
/* ECW might think the stream itself says. */
/************************************************************************/
CPLErr ECWRasterBand::SetColorInterpretation( GDALColorInterp eNewInterp )
{
eBandInterp = eNewInterp;
return CE_None;
}
/************************************************************************/
/* AdviseRead() */
/************************************************************************/
CPLErr ECWRasterBand::AdviseRead( int nXOff, int nYOff, int nXSize, int nYSize,
int nBufXSize, int nBufYSize,
GDALDataType eDT,
char **papszOptions )
{
const int nResFactor = 1 << (iOverview+1);
return poGDS->AdviseRead( nXOff * nResFactor,
nYOff * nResFactor,
nXSize * nResFactor,
nYSize * nResFactor,
nBufXSize, nBufYSize, eDT,
1, &nBand, papszOptions );
}
//statistics support:
#if ECWSDK_VERSION >= 50
/************************************************************************/
/* GetDefaultHistogram() */
/************************************************************************/
CPLErr ECWRasterBand::GetDefaultHistogram( double *pdfMin, double *pdfMax,
int *pnBuckets, GUIntBig ** ppanHistogram,
int bForce,
GDALProgressFunc f, void *pProgressData)
{
int bForceCoalesced = bForce;
// If file version is smaller than 3, there will be no statistics in the file. But if it is version 3 or higher we don't want underlying implementation to compute histogram
// so we set bForceCoalesced to FALSE.
if (poGDS->psFileInfo->nFormatVersion >= 3){
bForceCoalesced = FALSE;
}
// We check if we have PAM histogram. If we have them we return them. This will allow to override statistics stored in the file.
CPLErr pamError = GDALPamRasterBand::GetDefaultHistogram(pdfMin, pdfMax, pnBuckets, ppanHistogram, bForceCoalesced, f, pProgressData);
if ( pamError == CE_None || poGDS->psFileInfo->nFormatVersion<3 || eBandInterp == GCI_AlphaBand){
return pamError;
}
NCS::CError error = poGDS->StatisticsEnsureInitialized();
if (!error.Success()){
CPLError( CE_Warning, CPLE_AppDefined,
"ECWRDataset::StatisticsEnsureInitialized failed in ECWRasterBand::GetDefaultHistogram. " );
return CE_Failure;
}
GetBandIndexAndCountForStatistics(nStatsBandIndex, nStatsBandCount);
bool bHistogramFromFile = false;
if (poGDS->pStatistics != nullptr) {
NCSBandStats& bandStats = poGDS->pStatistics->BandsStats[nStatsBandIndex];
if ( bandStats.Histogram != nullptr && bandStats.nHistBucketCount > 0 ){
*pnBuckets = bandStats.nHistBucketCount;
*ppanHistogram = static_cast<GUIntBig *>(VSIMalloc(bandStats.nHistBucketCount * sizeof(GUIntBig)));
for (size_t i = 0; i < bandStats.nHistBucketCount; i++){
(*ppanHistogram)[i] = static_cast<GUIntBig>(bandStats.Histogram[i]);
}
//JTO: this is not perfect as You can't tell who wrote the histogram !!!
//It will offset it unnecessarily for files with hists not modified by GDAL.
const double dfHalfBucket = (bandStats.fMaxHist - bandStats.fMinHist) / (2 * (*pnBuckets - 1));
if ( pdfMin != nullptr ){
*pdfMin = bandStats.fMinHist - dfHalfBucket;
}
if ( pdfMax != nullptr ){
*pdfMax = bandStats.fMaxHist + dfHalfBucket;
}
bHistogramFromFile = true;
}
}
if (!bHistogramFromFile) {
if (bForce == TRUE){
//compute. Save.
pamError = GDALPamRasterBand::GetDefaultHistogram(pdfMin, pdfMax, pnBuckets, ppanHistogram, TRUE, f,pProgressData);
if (pamError == CE_None){
const CPLErr error2 = SetDefaultHistogram(*pdfMin, *pdfMax, *pnBuckets, *ppanHistogram);
if (error2 != CE_None){
//Histogram is there but we failed to save it back to file.
CPLError (CE_Warning, CPLE_AppDefined,
"SetDefaultHistogram failed in ECWRasterBand::GetDefaultHistogram. Histogram might not be saved in .ecw file." );
}
return CE_None;
}
return pamError;
}
// No histogram, no forced computation.
return CE_Warning;
}
// Statistics were already there and were used.
return CE_None;
}
/************************************************************************/
/* SetDefaultHistogram() */
/************************************************************************/
CPLErr ECWRasterBand::SetDefaultHistogram( double dfMin, double dfMax,
int nBuckets,
GUIntBig *panHistogram )
{
//Only version 3 supports saving statistics.
if (poGDS->psFileInfo->nFormatVersion < 3 || eBandInterp == GCI_AlphaBand){
return GDALPamRasterBand::SetDefaultHistogram(dfMin, dfMax, nBuckets, panHistogram);
}
//determine if there are statistics in PAM file.
double dummy;
int dummy_i;
GUIntBig *dummy_histogram = nullptr;
bool hasPAMDefaultHistogram =
GDALPamRasterBand::GetDefaultHistogram(
&dummy, &dummy, &dummy_i, &dummy_histogram,
FALSE, nullptr, nullptr) == CE_None;
if( hasPAMDefaultHistogram ) {
VSIFree(dummy_histogram);
}
// ECW SDK ignores statistics for opacity bands. So we need to compute
// number of bands without opacity.
GetBandIndexAndCountForStatistics(nStatsBandIndex, nStatsBandCount);
UINT32 bucketCounts[256];
std::fill_n(bucketCounts, nStatsBandCount, 0);
bucketCounts[nStatsBandIndex] = nBuckets;
NCS::CError error = poGDS->StatisticsEnsureInitialized();
if (!error.Success()){
CPLError( CE_Warning, CPLE_AppDefined,
"ECWRDataset::StatisticsEnsureInitialized failed in ECWRasterBand::SetDefaultHistogram. Default histogram will be written to PAM. " );
return GDALPamRasterBand::SetDefaultHistogram(dfMin, dfMax, nBuckets, panHistogram);
}
NCSFileStatistics *pStatistics = poGDS->pStatistics;
if (pStatistics == nullptr){
error = NCSEcwInitStatistics(&pStatistics, nStatsBandCount, bucketCounts);
poGDS->bStatisticsDirty = TRUE;
poGDS->pStatistics = pStatistics;
if (!error.Success()){
CPLError( CE_Warning, CPLE_AppDefined,
"NCSEcwInitStatistics failed in ECWRasterBand::SetDefaultHistogram." );
return GDALPamRasterBand::SetDefaultHistogram(dfMin, dfMax, nBuckets, panHistogram);
}
//no error statistics properly initialized but there were no statistics previously.
}else{
//is there a room for our band already?
//This should account for following cases:
//1. Existing histogram (for this or different band) has smaller bucket count.
//2. There is no existing histogram but statistics are set for one or more bands (pStatistics->nHistBucketCounts is zero).
if ((int)pStatistics->BandsStats[nStatsBandIndex].nHistBucketCount != nBuckets){
//no. There is no room. We need more!
NCSFileStatistics *pNewStatistics = nullptr;
for (size_t i=0;i<pStatistics->nNumberOfBands;i++){
bucketCounts[i] = pStatistics->BandsStats[i].nHistBucketCount;
}
bucketCounts[nStatsBandIndex] = nBuckets;
if (nBuckets < static_cast<int>(pStatistics->BandsStats[nStatsBandIndex].nHistBucketCount)){
pStatistics->BandsStats[nStatsBandIndex].nHistBucketCount = nBuckets;
}
error = NCSEcwInitStatistics(&pNewStatistics, nStatsBandCount, bucketCounts);
if (!error.Success()){
CPLError( CE_Warning, CPLE_AppDefined,
"NCSEcwInitStatistics failed in "
"ECWRasterBand::SetDefaultHistogram (reallocate)." );
return GDALPamRasterBand::SetDefaultHistogram(dfMin, dfMax, nBuckets, panHistogram);
}
//we need to copy existing statistics.
error = NCSEcwCopyStatistics(&pNewStatistics, pStatistics);
if (!error.Success()){
CPLError( CE_Warning, CPLE_AppDefined,
"NCSEcwCopyStatistics failed in ECWRasterBand::SetDefaultHistogram." );
NCSEcwFreeStatistics(pNewStatistics);
return GDALPamRasterBand::SetDefaultHistogram(dfMin, dfMax, nBuckets, panHistogram);
}
pNewStatistics->nNumberOfBands = nStatsBandCount;
NCSEcwFreeStatistics(pStatistics);
pStatistics = pNewStatistics;
poGDS->pStatistics = pStatistics;
poGDS->bStatisticsDirty = TRUE;
}
}
//at this point we have allocated statistics structure.
double dfHalfBucket = (dfMax - dfMin) / (2 * nBuckets);
pStatistics->BandsStats[nStatsBandIndex].fMinHist = static_cast<IEEE4>(dfMin + dfHalfBucket);
pStatistics->BandsStats[nStatsBandIndex].fMaxHist = static_cast<IEEE4>(dfMax - dfHalfBucket);
for (int i=0;i<nBuckets;i++){
pStatistics->BandsStats[nStatsBandIndex].Histogram[i] = static_cast<UINT64>(panHistogram[i]);
}
if (hasPAMDefaultHistogram){
CPLError( CE_Debug, CPLE_AppDefined,
"PAM default histogram will be overwritten." );
return GDALPamRasterBand::SetDefaultHistogram(dfMin, dfMax, nBuckets, panHistogram);
}
return CE_None;
}
/************************************************************************/
/* GetBandIndexAndCountForStatistics() */
/************************************************************************/
void ECWRasterBand::GetBandIndexAndCountForStatistics(int &bandIndex, int &bandCount) const
{
bandIndex = nBand-1;
bandCount = poGDS->nBands;
for (int i=0;i<poGDS->nBands;i++){
if (poDS->GetRasterBand(i+1)->GetColorInterpretation() == GCI_AlphaBand){
bandCount--;
if ( i < nBand-1 ){
bandIndex--;
}
}
}
}
/************************************************************************/
/* GetMinimum() */
/************************************************************************/
double ECWRasterBand::GetMinimum(int* pbSuccess)
{
if( poGDS->psFileInfo->nFormatVersion >= 3 )
{
NCS::CError error = poGDS->StatisticsEnsureInitialized();
if ( error.Success() )
{
GetBandIndexAndCountForStatistics(nStatsBandIndex, nStatsBandCount);
if ( poGDS->pStatistics != nullptr )
{
NCSBandStats& bandStats = poGDS->pStatistics->BandsStats[nStatsBandIndex];
if (!std::isnan(bandStats.fMinVal))
{
if( pbSuccess )
*pbSuccess = TRUE;
return bandStats.fMinVal;
}
}
}
}
return GDALPamRasterBand::GetMinimum(pbSuccess);
}
/************************************************************************/
/* GetMaximum() */
/************************************************************************/
double ECWRasterBand::GetMaximum(int* pbSuccess)
{
if( poGDS->psFileInfo->nFormatVersion >= 3 )
{
NCS::CError error = poGDS->StatisticsEnsureInitialized();
if ( error.Success() )
{
GetBandIndexAndCountForStatistics(nStatsBandIndex, nStatsBandCount);
if ( poGDS->pStatistics != nullptr )
{
NCSBandStats& bandStats = poGDS->pStatistics->BandsStats[nStatsBandIndex];
if (!std::isnan(bandStats.fMaxVal))
{
if( pbSuccess )
*pbSuccess = TRUE;
return bandStats.fMaxVal;
}
}
}
}
return GDALPamRasterBand::GetMaximum(pbSuccess);
}
/************************************************************************/
/* GetStatistics() */
/************************************************************************/
CPLErr ECWRasterBand::GetStatistics( int bApproxOK, int bForce,
double *pdfMin, double *pdfMax,
double *pdfMean, double *padfStdDev )
{
int bForceCoalesced = bForce;
// If file version is smaller than 3, there will be no statistics in the file. But if it is version 3 or higher we don't want underlying implementation to compute histogram
// so we set bForceCoalesced to FALSE.
if (poGDS->psFileInfo->nFormatVersion >= 3) {
bForceCoalesced = FALSE;
}
// We check if we have PAM histogram. If we have them we return them. This will allow to override statistics stored in the file.
CPLErr pamError = GDALPamRasterBand::GetStatistics(bApproxOK, bForceCoalesced, pdfMin, pdfMax, pdfMean, padfStdDev);
if ( pamError == CE_None || poGDS->psFileInfo->nFormatVersion<3 || eBandInterp == GCI_AlphaBand){
return pamError;
}
NCS::CError error = poGDS->StatisticsEnsureInitialized();
if (!error.Success()){
CPLError( CE_Failure, CPLE_AppDefined,
"ECWRDataset::StatisticsEnsureInitialized failed in ECWRasterBand::GetStatistic. " );
return CE_Failure;
}
GetBandIndexAndCountForStatistics(nStatsBandIndex, nStatsBandCount);
bool bStatisticsFromFile = false;
if ( poGDS->pStatistics != nullptr )
{
bStatisticsFromFile = true;
NCSBandStats& bandStats = poGDS->pStatistics->BandsStats[nStatsBandIndex];
if ( pdfMin != nullptr && !std::isnan(bandStats.fMinVal)) {
*pdfMin = bandStats.fMinVal;
}else{
bStatisticsFromFile = false;
}
if ( pdfMax != nullptr && !std::isnan(bandStats.fMaxVal)) {
*pdfMax = bandStats.fMaxVal;
}else{
bStatisticsFromFile = false;
}
if ( pdfMean != nullptr && !std::isnan(bandStats.fMeanVal)) {
*pdfMean = bandStats.fMeanVal;
}else{
bStatisticsFromFile = false;
}
if ( padfStdDev != nullptr && !std::isnan(bandStats.fStandardDev)) {
*padfStdDev = bandStats.fStandardDev;
}else{
bStatisticsFromFile = false;
}
if (bStatisticsFromFile) return CE_None;
}
//no required statistics.
if (!bStatisticsFromFile && bForce == TRUE){
double dfMin, dfMax, dfMean,dfStdDev;
pamError = GDALPamRasterBand::GetStatistics(bApproxOK, TRUE,
&dfMin,
&dfMax,
&dfMean,
&dfStdDev);
if (pdfMin!=nullptr) {
*pdfMin = dfMin;
}
if (pdfMax !=nullptr){
*pdfMax = dfMax;
}
if (pdfMean !=nullptr){
*pdfMean = dfMean;
}
if (padfStdDev!=nullptr){
*padfStdDev = dfStdDev;
}
if ( pamError == CE_None){
const CPLErr err = SetStatistics(dfMin,dfMax,dfMean,dfStdDev);
if (err !=CE_None){
CPLError (CE_Warning, CPLE_AppDefined,
"SetStatistics failed in ECWRasterBand::GetDefaultHistogram. Statistics might not be saved in .ecw file." );
}
return CE_None;
}
//whatever happened we return.
return pamError;
}
//no statistics and we are not forced to return.
return CE_Warning;
}
/************************************************************************/
/* SetStatistics() */
/************************************************************************/
CPLErr ECWRasterBand::SetStatistics( double dfMin, double dfMax,
double dfMean, double dfStdDev ){
if (poGDS->psFileInfo->nFormatVersion < 3 || eBandInterp == GCI_AlphaBand){
return GDALPamRasterBand::SetStatistics(dfMin, dfMax, dfMean, dfStdDev);
}
double dummy;
bool hasPAMStatistics = GDALPamRasterBand::GetStatistics(TRUE, FALSE, &dummy, &dummy, &dummy, &dummy) == CE_None;
NCS::CError error = poGDS->StatisticsEnsureInitialized();
if (!error.Success()){
CPLError( CE_Warning, CPLE_AppDefined,
"ECWRDataset::StatisticsEnsureInitialized failed in ECWRasterBand::SetStatistic. Statistics will be written to PAM. " );
return GDALPamRasterBand::SetStatistics(dfMin, dfMax, dfMean, dfStdDev);
}
GetBandIndexAndCountForStatistics(nStatsBandIndex, nStatsBandCount);
if (poGDS->pStatistics == nullptr){
error = NCSEcwInitStatistics(&poGDS->pStatistics, nStatsBandCount, nullptr);
if (!error.Success()){
CPLError( CE_Warning, CPLE_AppDefined,
"NCSEcwInitStatistics failed in ECWRasterBand::SetStatistic. Statistics will be written to PAM." );
return GDALPamRasterBand::SetStatistics(dfMin, dfMax, dfMean, dfStdDev);
}
}
poGDS->pStatistics->BandsStats[nStatsBandIndex].fMinVal = static_cast<IEEE4>(dfMin);
poGDS->pStatistics->BandsStats[nStatsBandIndex].fMaxVal = static_cast<IEEE4>(dfMax);
poGDS->pStatistics->BandsStats[nStatsBandIndex].fMeanVal = static_cast<IEEE4>(dfMean);
poGDS->pStatistics->BandsStats[nStatsBandIndex].fStandardDev = static_cast<IEEE4>(dfStdDev);
poGDS->bStatisticsDirty = TRUE;
//if we have PAM statistics we need to save them as well. Better option would be to remove them from PAM file but I don't know how to do that without messing in PAM internals.
if ( hasPAMStatistics ){
CPLError( CE_Debug, CPLE_AppDefined,
"PAM statistics will be overwritten." );
return GDALPamRasterBand::SetStatistics(dfMin, dfMax, dfMean, dfStdDev);
}
return CE_None;
}
#endif
//#if !defined(SDK_CAN_DO_SUPERSAMPLING)
/************************************************************************/
/* OldIRasterIO() */
/************************************************************************/
/* This implementation of IRasterIO(), derived from the one of GDAL 1.9 */
/* and older versions, is meant at making over-sampling */
/* work with ECW SDK 3.3. Newer versions of the SDK can do super-sampling in their */
/* SetView() call. */
CPLErr ECWRasterBand::OldIRasterIO( GDALRWFlag eRWFlag,
int nXOff, int nYOff, int nXSize, int nYSize,
void * pData, int nBufXSize, int nBufYSize,
GDALDataType eBufType,
GSpacing nPixelSpace, GSpacing nLineSpace,
GDALRasterIOExtraArg* psExtraArg )
{
int iBand;
GByte *pabyWorkBuffer = nullptr;
const int nResFactor = 1 << (iOverview+1);
nXOff *= nResFactor;
nYOff *= nResFactor;
nXSize *= nResFactor;
nYSize *= nResFactor;
/* -------------------------------------------------------------------- */
/* Try to do it based on existing "advised" access. */
/* -------------------------------------------------------------------- */
int nRet = poGDS->TryWinRasterIO( eRWFlag,
nXOff, nYOff,
nXSize, nYSize,
static_cast<GByte *>(pData), nBufXSize, nBufYSize,
eBufType, 1, &nBand,
nPixelSpace, nLineSpace, 0 , psExtraArg);
if( nRet == TRUE )
return CE_None;
if( nRet < 0 )
return CE_Failure;
/* -------------------------------------------------------------------- */
/* The ECW SDK doesn't supersample, so adjust for this case. */
/* -------------------------------------------------------------------- */
int nNewXSize = nBufXSize;
int nNewYSize = nBufYSize;
if ( nXSize < nBufXSize )
nNewXSize = nXSize;
if ( nYSize < nBufYSize )
nNewYSize = nYSize;
/* -------------------------------------------------------------------- */
/* Can we perform direct loads, or must we load into a working */
/* buffer, and transform? */
/* -------------------------------------------------------------------- */
const int nRawPixelSize = GDALGetDataTypeSize(poGDS->eRasterDataType) / 8;
int bDirect = nPixelSpace == 1 && eBufType == GDT_Byte
&& nNewXSize == nBufXSize && nNewYSize == nBufYSize;
if( !bDirect )
pabyWorkBuffer = static_cast<GByte *>(CPLMalloc(nNewXSize * nRawPixelSize));
/* -------------------------------------------------------------------- */
/* Establish access at the desired resolution. */
/* -------------------------------------------------------------------- */
poGDS->CleanupWindow();
iBand = nBand-1;
poGDS->nBandIndexToPromoteTo8Bit = ( bPromoteTo8Bit ) ? 0 : -1;
// TODO: Fix writable strings issue.
CNCSError oErr = poGDS->poFileView->SetView( 1, reinterpret_cast<unsigned int *>(&iBand),
nXOff, nYOff,
nXOff + nXSize - 1,
nYOff + nYSize - 1,
nNewXSize, nNewYSize );
if( oErr.GetErrorNumber() != NCS_SUCCESS )
{
CPLFree( pabyWorkBuffer );
ECWReportError(oErr);
return CE_Failure;
}
/* -------------------------------------------------------------------- */
/* Read back one scanline at a time, till request is satisfied. */
/* Supersampling is not supported by the ECW API, so we will do */
/* it ourselves. */
/* -------------------------------------------------------------------- */
double dfSrcYInc = static_cast<double>(nNewYSize) / nBufYSize;
double dfSrcXInc = static_cast<double>(nNewXSize) / nBufXSize;
int iSrcLine, iDstLine;
CPLErr eErr = CE_None;
for( iSrcLine = 0, iDstLine = 0; iDstLine < nBufYSize; iDstLine++ )
{
NCSEcwReadStatus eRStatus;
GPtrDiff_t iDstLineOff = iDstLine * (GPtrDiff_t)nLineSpace;
unsigned char *pabySrcBuf;
if( bDirect )
pabySrcBuf = ((GByte *)pData) + iDstLineOff;
else
pabySrcBuf = pabyWorkBuffer;
if ( nNewYSize == nBufYSize || iSrcLine == (int)(iDstLine * dfSrcYInc) )
{
eRStatus = poGDS->poFileView->ReadLineBIL(
poGDS->eNCSRequestDataType, 1, (void **) &pabySrcBuf );
if( eRStatus != NCSECW_READ_OK )
{
CPLDebug( "ECW", "ReadLineBIL status=%d", (int) eRStatus );
CPLError( CE_Failure, CPLE_AppDefined,
"NCScbmReadViewLineBIL failed." );
eErr = CE_Failure;
break;
}
if( bPromoteTo8Bit )
{
for ( int iX = 0; iX < nNewXSize; iX++ )
{
pabySrcBuf[iX] *= 255;
}
}
if( !bDirect )
{
if ( nNewXSize == nBufXSize )
{
GDALCopyWords( pabyWorkBuffer, poGDS->eRasterDataType,
nRawPixelSize,
((GByte *)pData) + iDstLine * nLineSpace,
eBufType, (int)nPixelSpace, nBufXSize );
}
else
{
int iPixel;
for ( iPixel = 0; iPixel < nBufXSize; iPixel++ )
{
GDALCopyWords( pabyWorkBuffer
+ nRawPixelSize*((int)(iPixel*dfSrcXInc)),
poGDS->eRasterDataType, nRawPixelSize,
(GByte *)pData + iDstLineOff
+ iPixel * nPixelSpace,
eBufType, (int)nPixelSpace, 1 );
}
}
}
iSrcLine++;
}
else
{
// Just copy the previous line in this case
GDALCopyWords( (GByte *)pData + (iDstLineOff - nLineSpace),
eBufType, (int)nPixelSpace,
(GByte *)pData + iDstLineOff,
eBufType, (int)nPixelSpace, nBufXSize );
}
if( psExtraArg->pfnProgress != nullptr &&
!psExtraArg->pfnProgress(1.0 * (iDstLine + 1) / nBufYSize, "",
psExtraArg->pProgressData) )
{
eErr = CE_Failure;
break;
}
}
CPLFree( pabyWorkBuffer );
return eErr;
}
//#endif !defined(SDK_CAN_DO_SUPERSAMPLING)
/************************************************************************/
/* IRasterIO() */
/************************************************************************/
CPLErr ECWRasterBand::IRasterIO( GDALRWFlag eRWFlag,
int nXOff, int nYOff, int nXSize, int nYSize,
void * pData, int nBufXSize, int nBufYSize,
GDALDataType eBufType,
GSpacing nPixelSpace, GSpacing nLineSpace,
GDALRasterIOExtraArg* psExtraArg )
{
if( eRWFlag == GF_Write )
return CE_Failure;
/* -------------------------------------------------------------------- */
/* Default line and pixel spacing if needed. */
/* -------------------------------------------------------------------- */
if ( nPixelSpace == 0 )
nPixelSpace = GDALGetDataTypeSize( eBufType ) / 8;
if ( nLineSpace == 0 )
nLineSpace = nPixelSpace * nBufXSize;
CPLDebug( "ECWRasterBand",
"RasterIO(nBand=%d,iOverview=%d,nXOff=%d,nYOff=%d,nXSize=%d,nYSize=%d -> %dx%d)",
nBand, iOverview, nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize );
#if !defined(SDK_CAN_DO_SUPERSAMPLING)
if( poGDS->bUseOldBandRasterIOImplementation )
{
return OldIRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
pData, nBufXSize, nBufYSize,
eBufType,
nPixelSpace, nLineSpace, psExtraArg );
}
#endif
int nResFactor = 1 << (iOverview+1);
return poGDS->IRasterIO(eRWFlag,
nXOff * nResFactor,
nYOff * nResFactor,
(nXSize == nRasterXSize) ? poGDS->nRasterXSize : nXSize * nResFactor,
(nYSize == nRasterYSize) ? poGDS->nRasterYSize : nYSize * nResFactor,
pData, nBufXSize, nBufYSize,
eBufType, 1, &nBand,
nPixelSpace, nLineSpace, nLineSpace*nBufYSize, psExtraArg);
}
/************************************************************************/
/* IReadBlock() */
/************************************************************************/
CPLErr ECWRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff, void * pImage )
{
int nXOff = nBlockXOff * nBlockXSize,
nYOff = nBlockYOff * nBlockYSize,
nXSize = nBlockXSize,
nYSize = nBlockYSize;
if( nXOff + nXSize > nRasterXSize )
nXSize = nRasterXSize - nXOff;
if( nYOff + nYSize > nRasterYSize )
nYSize = nRasterYSize - nYOff;
int nPixelSpace = GDALGetDataTypeSize(eDataType) / 8;
int nLineSpace = nPixelSpace * nBlockXSize;
GDALRasterIOExtraArg sExtraArg;
INIT_RASTERIO_EXTRA_ARG(sExtraArg);
return IRasterIO( GF_Read,
nXOff, nYOff, nXSize, nYSize,
pImage, nXSize, nYSize,
eDataType, nPixelSpace, nLineSpace, &sExtraArg );
}
/************************************************************************/
/* ==================================================================== */
/* ECWDataset */
/* ==================================================================== */
/************************************************************************/
/************************************************************************/
/* ECWDataset() */
/************************************************************************/
ECWDataset::ECWDataset(int bIsJPEG2000In)
{
this->bIsJPEG2000 = bIsJPEG2000In;
bUsingCustomStream = FALSE;
poFileView = nullptr;
bWinActive = FALSE;
panWinBandList = nullptr;
eRasterDataType = GDT_Byte;
papszGMLMetadata = nullptr;
bHdrDirty = FALSE;
bGeoTransformChanged = FALSE;
bProjectionChanged = FALSE;
bProjCodeChanged = FALSE;
bDatumCodeChanged = FALSE;
bUnitsCodeChanged = FALSE;
bUseOldBandRasterIOImplementation = FALSE;
#if ECWSDK_VERSION>=50
pStatistics = nullptr;
bStatisticsDirty = FALSE;
bStatisticsInitialized = FALSE;
bFileMetaDataDirty = FALSE;
#endif
sCachedMultiBandIO.bEnabled = FALSE;
sCachedMultiBandIO.nBandsTried = 0;
sCachedMultiBandIO.nXOff = 0;
sCachedMultiBandIO.nYOff = 0;
sCachedMultiBandIO.nXSize = 0;
sCachedMultiBandIO.nYSize = 0;
sCachedMultiBandIO.nBufXSize = 0;
sCachedMultiBandIO.nBufYSize = 0;
sCachedMultiBandIO.eBufType = GDT_Unknown;
sCachedMultiBandIO.pabyData = nullptr;
bPreventCopyingSomeMetadata = FALSE;
nBandIndexToPromoteTo8Bit = -1;
poDriver = (GDALDriver*) GDALGetDriverByName( bIsJPEG2000 ? "JP2ECW" : "ECW" );
psFileInfo = nullptr;
eNCSRequestDataType = NCSCT_UINT8;
nWinXOff = 0;
nWinYOff = 0;
nWinXSize = 0;
nWinYSize = 0;
nWinBufXSize = 0;
nWinBufYSize = 0;
nWinBandCount = 0;
nWinBufLoaded = FALSE;
papCurLineBuf = nullptr;
m_nAdviseReadXOff = -1;
m_nAdviseReadYOff = -1;
m_nAdviseReadXSize = -1;
m_nAdviseReadYSize = -1;
m_nAdviseReadBufXSize = -1;
m_nAdviseReadBufYSize = -1;
m_nAdviseReadBandCount = -1;
m_panAdviseReadBandList = nullptr;
}
/************************************************************************/
/* ~ECWDataset() */
/************************************************************************/
ECWDataset::~ECWDataset()
{
GDALPamDataset::FlushCache();
CleanupWindow();
#if ECWSDK_VERSION>=50
NCSFileMetaData* pFileMetaDataCopy = nullptr;
if( bFileMetaDataDirty )
{
NCSCopyMetaData(&pFileMetaDataCopy, psFileInfo->pFileMetaData);
}
#endif
/* -------------------------------------------------------------------- */
/* Release / dereference iostream. */
/* -------------------------------------------------------------------- */
// The underlying iostream of the CNCSJP2FileView (poFileView) object may
// also be the underlying iostream of other CNCSJP2FileView (poFileView)
// objects. Consequently, when we delete the CNCSJP2FileView (poFileView)
// object, we must decrement the nFileViewCount attribute of the underlying
// VSIIOStream object, and only delete the VSIIOStream object when
// nFileViewCount is equal to zero.
CPLMutexHolder oHolder( &hECWDatasetMutex );
// bInGDALGlobalDestructor is set to TRUE by gdaldllmain.cpp/GDALDestroy() so as
// to avoid an issue with the ECW SDK 3.3 where the destructor of CNCSJP2File::CNCSJP2FileVector CNCSJP2File::sm_Files;
// static resource allocated in NCJP2File.cpp can be called before GDALDestroy(), causing
// ECW SDK resources ( CNCSJP2File files ) to be closed before we get here.
//
// We also have an issue with ECW SDK 5.0 and ECW files on Linux when
// running a multi-threaded test under Java if there's still an ECW dataset
// not explicitly closed at process termination.
/* #0 0x00007fffb26e7a80 in NCSAtomicAdd64 () from /home/even/ecwjp2_sdk/redistributable/x64/libNCSEcw.so
#1 0x00007fffb2aa7684 in NCS::SDK::CBuffer2D::Free() () from /home/even/ecwjp2_sdk/redistributable/x64/libNCSEcw.so
#2 0x00007fffb2aa7727 in NCS::SDK::CBuffer2D::~CBuffer2D() () from /home/even/ecwjp2_sdk/redistributable/x64/libNCSEcw.so
#3 0x00007fffb29aa7be in NCS::ECW::CReader::~CReader() () from /home/even/ecwjp2_sdk/redistributable/x64/libNCSEcw.so
#4 0x00007fffb29aa819 in NCS::ECW::CReader::~CReader() () from /home/even/ecwjp2_sdk/redistributable/x64/libNCSEcw.so
#5 0x00007fffb291fd3a in NCS::CView::Close(bool) () from /home/even/ecwjp2_sdk/redistributable/x64/libNCSEcw.so
#6 0x00007fffb2927529 in NCS::CView::~CView() () from /home/even/ecwjp2_sdk/redistributable/x64/libNCSEcw.so
#7 0x00007fffb29277f9 in NCS::CView::~CView() () from /home/even/ecwjp2_sdk/redistributable/x64/libNCSEcw.so
#8 0x00007fffb71a9a53 in ECWDataset::~ECWDataset (this=0x7fff942cce10, __in_chrg=<optimized out>) at ecwdataset.cpp:1003
#9 0x00007fffb71a9cca in ECWDataset::~ECWDataset (this=0x7fff942cce10, __in_chrg=<optimized out>) at ecwdataset.cpp:1039
#10 0x00007fffb7551f98 in GDALDriverManager::~GDALDriverManager (this=0x7ffff01981a0, __in_chrg=<optimized out>) at gdaldrivermanager.cpp:196
#11 0x00007fffb7552140 in GDALDriverManager::~GDALDriverManager (this=0x7ffff01981a0, __in_chrg=<optimized out>) at gdaldrivermanager.cpp:288
#12 0x00007fffb7552e18 in GDALDestroyDriverManager () at gdaldrivermanager.cpp:824
#13 0x00007fffb7551c61 in GDALDestroy () at gdaldllmain.cpp:80
#14 0x00007ffff7de990e in _dl_fini () at dl-fini.c:254
*/
// Not reproducible with similar test in C++, but this might be
// just a matter of luck related to the order in which the
// libraries are unloaded, so just don't try to delete poFileView
// from the GDAL destructor.
if( poFileView != nullptr && !GDALIsInGlobalDestructor() )
{
#if ECWSDK_VERSION >= 55
delete poFileView;
#else
VSIIOStream *poUnderlyingIOStream = (VSIIOStream *)nullptr;
if( bUsingCustomStream )
{
poUnderlyingIOStream = ((VSIIOStream *)(poFileView->GetStream()));
}
delete poFileView;
if( bUsingCustomStream )
{
if( --poUnderlyingIOStream->nFileViewCount == 0 )
delete poUnderlyingIOStream;
}
#endif
poFileView = nullptr;
}
/* WriteHeader() must be called after closing the file handle to work */
/* on Windows */
if( bHdrDirty )
WriteHeader();
#if ECWSDK_VERSION>=50
if (bStatisticsDirty){
StatisticsWrite();
}
CleanupStatistics();
if( bFileMetaDataDirty )
{
WriteFileMetaData(pFileMetaDataCopy);
NCSFreeMetaData(pFileMetaDataCopy);
}
#endif
CSLDestroy( papszGMLMetadata );
CPLFree(sCachedMultiBandIO.pabyData);
CPLFree(m_panAdviseReadBandList);
}
#if ECWSDK_VERSION>=50
/************************************************************************/
/* StatisticsEnsureInitialized() */
/************************************************************************/
NCS::CError ECWDataset::StatisticsEnsureInitialized(){
if (bStatisticsInitialized == TRUE){
return NCS_SUCCESS;
}
NCS::CError error = poFileView->GetClientStatistics(&pStatistics);
if (error.Success()){
bStatisticsInitialized = TRUE;
}
return error;
}
/************************************************************************/
/* StatisticsWrite() */
/************************************************************************/
NCS::CError ECWDataset::StatisticsWrite()
{
CPLDebug("ECW", "In StatisticsWrite()");
NCSFileView* view = NCSEcwEditOpen( GetDescription() );
NCS::CError error;
if ( view != nullptr ){
error = NCSEcwEditSetStatistics(view, pStatistics);
if (error.Success()){
error = NCSEcwEditFlushAll(view);
if (error.Success()){
error = NCSEcwEditClose(view);
}
}
}
bStatisticsDirty = FALSE;
return error;
}
/************************************************************************/
/* CleanupStatistics() */
/************************************************************************/
void ECWDataset::CleanupStatistics(){
if (bStatisticsInitialized == TRUE && pStatistics !=nullptr){
NCSEcwFreeStatistics(pStatistics);
}
}
#endif // #if ECWSDK_VERSION>=50
/************************************************************************/
/* SetGeoTransform() */
/************************************************************************/
CPLErr ECWDataset::SetGeoTransform( double * padfGeoTransform )
{
if ( bIsJPEG2000 || eAccess == GA_ReadOnly )
return GDALPamDataset::SetGeoTransform(padfGeoTransform);
if ( !bGeoTransformValid ||
adfGeoTransform[0] != padfGeoTransform[0] ||
adfGeoTransform[1] != padfGeoTransform[1] ||
adfGeoTransform[2] != padfGeoTransform[2] ||
adfGeoTransform[3] != padfGeoTransform[3] ||
adfGeoTransform[4] != padfGeoTransform[4] ||
adfGeoTransform[5] != padfGeoTransform[5] )
{
memcpy(adfGeoTransform, padfGeoTransform, 6 * sizeof(double));
bGeoTransformValid = TRUE;
bHdrDirty = TRUE;
bGeoTransformChanged = TRUE;
}
return CE_None;
}
/************************************************************************/
/* SetProjection() */
/************************************************************************/
CPLErr ECWDataset::_SetProjection( const char* pszProjectionIn )
{
if ( bIsJPEG2000 || eAccess == GA_ReadOnly )
return GDALPamDataset::_SetProjection(pszProjectionIn);
if ( !( (pszProjection == nullptr && pszProjectionIn == nullptr) ||
(pszProjection != nullptr && pszProjectionIn != nullptr &&
strcmp(pszProjection, pszProjectionIn) == 0) ) )
{
CPLFree(pszProjection);
pszProjection = pszProjectionIn ? CPLStrdup(pszProjectionIn) : nullptr;
bHdrDirty = TRUE;
bProjectionChanged = TRUE;
}
return CE_None;
}
/************************************************************************/
/* SetMetadataItem() */
/************************************************************************/
CPLErr ECWDataset::SetMetadataItem( const char * pszName,
const char * pszValue,
const char * pszDomain )
{
if ( !bIsJPEG2000 && eAccess == GA_Update &&
(pszDomain == nullptr || EQUAL(pszDomain, "") ||
(pszDomain != nullptr && EQUAL(pszDomain, "ECW"))) &&
pszName != nullptr &&
(strcmp(pszName, "PROJ") == 0 || strcmp( pszName, "DATUM") == 0 ||
strcmp( pszName, "UNITS") == 0 ) )
{
CPLString osNewVal = pszValue ? pszValue : "";
if (osNewVal.size() > 31)
osNewVal.resize(31);
if (strcmp(pszName, "PROJ") == 0)
{
bProjCodeChanged = (osNewVal != m_osProjCode);
m_osProjCode = osNewVal;
bHdrDirty |= bProjCodeChanged;
}
else if (strcmp( pszName, "DATUM") == 0)
{
bDatumCodeChanged |= (osNewVal != m_osDatumCode)? TRUE:FALSE ;
m_osDatumCode = osNewVal;
bHdrDirty |= bDatumCodeChanged;
}
else
{
bUnitsCodeChanged |= (osNewVal != m_osUnitsCode)?TRUE:FALSE;
m_osUnitsCode = osNewVal;
bHdrDirty |= bUnitsCodeChanged;
}
return CE_None;
}
#if ECWSDK_VERSION >=50
else if ( psFileInfo != nullptr &&
psFileInfo->nFormatVersion >= 3 &&
eAccess == GA_Update &&
(pszDomain == nullptr || EQUAL(pszDomain, "")) &&
pszName != nullptr &&
STARTS_WITH(pszName, "FILE_METADATA_") )
{
bFileMetaDataDirty = TRUE;
if( psFileInfo->pFileMetaData == nullptr )
NCSInitMetaData(&(psFileInfo->pFileMetaData));
if( strcmp(pszName, "FILE_METADATA_CLASSIFICATION") == 0 )
{
NCSFree(psFileInfo->pFileMetaData->sClassification);
psFileInfo->pFileMetaData->sClassification = pszValue ? NCSStrDupT(NCS::CString(pszValue).c_str()) : nullptr;
return GDALDataset::SetMetadataItem( pszName, pszValue, pszDomain );
}
else if( strcmp(pszName, "FILE_METADATA_ACQUISITION_DATE") == 0 )
{
NCSFree(psFileInfo->pFileMetaData->sAcquisitionDate);
psFileInfo->pFileMetaData->sAcquisitionDate = pszValue ? NCSStrDupT(NCS::CString(pszValue).c_str()) : nullptr;
return GDALDataset::SetMetadataItem( pszName, pszValue, pszDomain );
}
else if( strcmp(pszName, "FILE_METADATA_ACQUISITION_SENSOR_NAME") == 0 )
{
NCSFree(psFileInfo->pFileMetaData->sAcquisitionSensorName);
psFileInfo->pFileMetaData->sAcquisitionSensorName = pszValue ? NCSStrDupT(NCS::CString(pszValue).c_str()) : nullptr;
return GDALDataset::SetMetadataItem( pszName, pszValue, pszDomain );
}
else if( strcmp(pszName, "FILE_METADATA_COMPRESSION_SOFTWARE") == 0 )
{
NCSFree(psFileInfo->pFileMetaData->sCompressionSoftware);
psFileInfo->pFileMetaData->sCompressionSoftware = pszValue ? NCSStrDupT(NCS::CString(pszValue).c_str()) : nullptr;
return GDALDataset::SetMetadataItem( pszName, pszValue, pszDomain );
}
else if( strcmp(pszName, "FILE_METADATA_AUTHOR") == 0 )
{
NCSFree(psFileInfo->pFileMetaData->sAuthor);
psFileInfo->pFileMetaData->sAuthor = pszValue ? NCSStrDupT(NCS::CString(pszValue).c_str()) : nullptr;
return GDALDataset::SetMetadataItem( pszName, pszValue, pszDomain );
}
else if( strcmp(pszName, "FILE_METADATA_COPYRIGHT") == 0 )
{
NCSFree(psFileInfo->pFileMetaData->sCopyright);
psFileInfo->pFileMetaData->sCopyright = pszValue ? NCSStrDupT(NCS::CString(pszValue).c_str()) : nullptr;
return GDALDataset::SetMetadataItem( pszName, pszValue, pszDomain );
}
else if( strcmp(pszName, "FILE_METADATA_COMPANY") == 0 )
{
NCSFree(psFileInfo->pFileMetaData->sCompany);
psFileInfo->pFileMetaData->sCompany = pszValue ? NCSStrDupT(NCS::CString(pszValue).c_str()) : nullptr;
return GDALDataset::SetMetadataItem( pszName, pszValue, pszDomain );
}
else if( strcmp(pszName, "FILE_METADATA_EMAIL") == 0 )
{
NCSFree(psFileInfo->pFileMetaData->sEmail);
psFileInfo->pFileMetaData->sEmail = pszValue ? NCSStrDupT(NCS::CString(pszValue).c_str()) : nullptr;
return GDALDataset::SetMetadataItem( pszName, pszValue, pszDomain );
}
else if( strcmp(pszName, "FILE_METADATA_ADDRESS") == 0 )
{
NCSFree(psFileInfo->pFileMetaData->sAddress);
psFileInfo->pFileMetaData->sAddress = pszValue ? NCSStrDupT(NCS::CString(pszValue).c_str()) : nullptr;
return GDALDataset::SetMetadataItem( pszName, pszValue, pszDomain );
}
else if( strcmp(pszName, "FILE_METADATA_TELEPHONE") == 0 )
{
NCSFree(psFileInfo->pFileMetaData->sTelephone);
psFileInfo->pFileMetaData->sTelephone = pszValue ? NCSStrDupT(NCS::CString(pszValue).c_str()) : nullptr;
return GDALDataset::SetMetadataItem( pszName, pszValue, pszDomain );
}
else
{
return GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain);
}
}
#endif
else
return GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain);
}
/************************************************************************/
/* SetMetadata() */
/************************************************************************/
CPLErr ECWDataset::SetMetadata( char ** papszMetadata,
const char * pszDomain )
{
/* The bPreventCopyingSomeMetadata is set by ECWCreateCopy() */
/* just before calling poDS->CloneInfo( poSrcDS, GCIF_PAM_DEFAULT ); */
if( bPreventCopyingSomeMetadata && (pszDomain == nullptr || EQUAL(pszDomain, "")) )
{
char** papszMetadataDup = nullptr;
char** papszIter = papszMetadata;
while( *papszIter )
{
char* pszKey = nullptr;
CPLParseNameValue(*papszIter, &pszKey);
/* Remove a few metadata item from the source that we don't want in */
/* the target metadata */
if( pszKey != nullptr && (
EQUAL(pszKey, "VERSION") ||
EQUAL(pszKey, "COMPRESSION_RATE_TARGET") ||
EQUAL(pszKey, "COMPRESSION_RATE_ACTUAL") ||
EQUAL(pszKey, "CLOCKWISE_ROTATION_DEG") ||
EQUAL(pszKey, "COLORSPACE") ||
EQUAL(pszKey, "COMPRESSION_DATE") ||
STARTS_WITH_CI(pszKey, "FILE_METADATA_") ) )
{
/* do nothing */
}
else
{
papszMetadataDup = CSLAddString(papszMetadataDup, *papszIter);
}
CPLFree(pszKey);
papszIter ++;
}
bPreventCopyingSomeMetadata = FALSE;
CPLErr eErr = SetMetadata(papszMetadataDup, pszDomain);
bPreventCopyingSomeMetadata = TRUE;
CSLDestroy(papszMetadataDup);
return eErr;
}
if ( ((pszDomain == nullptr || EQUAL(pszDomain, "") || EQUAL(pszDomain, "ECW")) &&
(CSLFetchNameValue(papszMetadata, "PROJ") != nullptr ||
CSLFetchNameValue(papszMetadata, "DATUM") != nullptr ||
CSLFetchNameValue(papszMetadata, "UNITS") != nullptr))
#if ECWSDK_VERSION >=50
|| (psFileInfo != nullptr &&
psFileInfo->nFormatVersion >= 3 &&
eAccess == GA_Update &&
(pszDomain == nullptr || EQUAL(pszDomain, "")) &&
(CSLFetchNameValue(papszMetadata, "FILE_METADATA_CLASSIFICATION") != nullptr ||
CSLFetchNameValue(papszMetadata, "FILE_METADATA_ACQUISITION_DATE") != nullptr ||
CSLFetchNameValue(papszMetadata, "FILE_METADATA_ACQUISITION_SENSOR_NAME") != nullptr ||
CSLFetchNameValue(papszMetadata, "FILE_METADATA_COMPRESSION_SOFTWARE") != nullptr ||
CSLFetchNameValue(papszMetadata, "FILE_METADATA_AUTHOR") != nullptr ||
CSLFetchNameValue(papszMetadata, "FILE_METADATA_COPYRIGHT") != nullptr ||
CSLFetchNameValue(papszMetadata, "FILE_METADATA_COMPANY") != nullptr ||
CSLFetchNameValue(papszMetadata, "FILE_METADATA_EMAIL") != nullptr ||
CSLFetchNameValue(papszMetadata, "FILE_METADATA_ADDRESS") != nullptr ||
CSLFetchNameValue(papszMetadata, "FILE_METADATA_TELEPHONE") != nullptr))
#endif
)
{
CPLStringList osNewMetadata;
char** papszIter = papszMetadata;
while(papszIter && *papszIter)
{
if (STARTS_WITH(*papszIter, "PROJ=") ||
STARTS_WITH(*papszIter, "DATUM=") ||
STARTS_WITH(*papszIter, "UNITS=") ||
(STARTS_WITH(*papszIter, "FILE_METADATA_") && strchr(*papszIter, '=') != nullptr) )
{
char* pszKey = nullptr;
const char* pszValue = CPLParseNameValue(*papszIter, &pszKey );
SetMetadataItem(pszKey, pszValue, pszDomain);
CPLFree(pszKey);
}
else
osNewMetadata.AddString(*papszIter);
papszIter ++;
}
if (!osNewMetadata.empty())
return GDALPamDataset::SetMetadata(osNewMetadata.List(), pszDomain);
else
return CE_None;
}
else
return GDALPamDataset::SetMetadata(papszMetadata, pszDomain);
}
/************************************************************************/
/* WriteHeader() */
/************************************************************************/
void ECWDataset::WriteHeader()
{
if (!bHdrDirty)
return;
CPLAssert(eAccess == GA_Update);
CPLAssert(!bIsJPEG2000);
bHdrDirty = FALSE;
NCSEcwEditInfo *psEditInfo = nullptr;
NCSError eErr;
/* Load original header info */
#if ECWSDK_VERSION<50
eErr = NCSEcwEditReadInfo((char*) GetDescription(), &psEditInfo);
#else
eErr = NCSEcwEditReadInfo( NCS::CString::Utf8Decode(GetDescription()).c_str(), &psEditInfo);
#endif
if (eErr != NCS_SUCCESS)
{
CPLError(CE_Failure, CPLE_AppDefined, "NCSEcwEditReadInfo() failed");
return;
}
/* To avoid potential cross-heap issues, we keep the original */
/* strings, and restore them before freeing the structure */
char* pszOriginalCode = psEditInfo->szDatum;
char* pszOriginalProj = psEditInfo->szProjection;
/* Alter the structure with user modified information */
char szProjCode[32], szDatumCode[32], szUnits[32];
if (bProjectionChanged)
{
if (ECWTranslateFromWKT( pszProjection, szProjCode, sizeof(szProjCode),
szDatumCode, sizeof(szDatumCode), szUnits ) )
{
psEditInfo->szDatum = szDatumCode;
psEditInfo->szProjection = szProjCode;
psEditInfo->eCellSizeUnits = ECWTranslateToCellSizeUnits(szUnits);
CPLDebug("ECW", "Rewrite DATUM : %s", psEditInfo->szDatum);
CPLDebug("ECW", "Rewrite PROJ : %s", psEditInfo->szProjection);
CPLDebug("ECW", "Rewrite UNITS : %s",
ECWTranslateFromCellSizeUnits(psEditInfo->eCellSizeUnits));
}
}
if (bDatumCodeChanged)
{
psEditInfo->szDatum = (char*) ((m_osDatumCode.size()) ? m_osDatumCode.c_str() : "RAW");
CPLDebug("ECW", "Rewrite DATUM : %s", psEditInfo->szDatum);
}
if (bProjCodeChanged)
{
psEditInfo->szProjection = (char*) ((m_osProjCode.size()) ? m_osProjCode.c_str() : "RAW");
CPLDebug("ECW", "Rewrite PROJ : %s", psEditInfo->szProjection);
}
if (bUnitsCodeChanged)
{
psEditInfo->eCellSizeUnits = ECWTranslateToCellSizeUnits(m_osUnitsCode.c_str());
CPLDebug("ECW", "Rewrite UNITS : %s",
ECWTranslateFromCellSizeUnits(psEditInfo->eCellSizeUnits));
}
if (bGeoTransformChanged)
{
psEditInfo->fOriginX = adfGeoTransform[0];
psEditInfo->fCellIncrementX = adfGeoTransform[1];
psEditInfo->fOriginY = adfGeoTransform[3];
psEditInfo->fCellIncrementY = adfGeoTransform[5];
CPLDebug("ECW", "Rewrite Geotransform");
}
/* Write modified header info */
#if ECWSDK_VERSION<50
eErr = NCSEcwEditWriteInfo((char*) GetDescription(), psEditInfo, nullptr, nullptr, nullptr);
#else
eErr = NCSEcwEditWriteInfo( NCS::CString::Utf8Decode(GetDescription()).c_str(), psEditInfo, nullptr, nullptr, nullptr);
#endif
if (eErr != NCS_SUCCESS)
{
CPLError(CE_Failure, CPLE_AppDefined, "NCSEcwEditWriteInfo() failed");
}
/* Restore original pointers before free'ing */
psEditInfo->szDatum = pszOriginalCode;
psEditInfo->szProjection = pszOriginalProj;
NCSEcwEditFreeInfo(psEditInfo);
}
/************************************************************************/
/* AdviseRead() */
/************************************************************************/
CPLErr ECWDataset::AdviseRead( int nXOff, int nYOff, int nXSize, int nYSize,
int nBufXSize, int nBufYSize,
CPL_UNUSED GDALDataType eDT,
int nBandCount, int *panBandList,
CPL_UNUSED char **papszOptions )
{
CPLDebug( "ECW",
"ECWDataset::AdviseRead(%d,%d,%d,%d->%d,%d)",
nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize );
#if !defined(SDK_CAN_DO_SUPERSAMPLING)
if( nBufXSize > nXSize || nBufYSize > nYSize )
{
CPLError( CE_Warning, CPLE_AppDefined,
"Supersampling not directly supported by ECW toolkit,\n"
"ignoring AdviseRead() request." );
return CE_Warning;
}
#endif
/* -------------------------------------------------------------------- */
/* Do some validation of parameters. */
/* -------------------------------------------------------------------- */
CPLErr eErr;
int bStopProcessing = FALSE;
eErr = ValidateRasterIOOrAdviseReadParameters( "AdviseRead()", &bStopProcessing,
nXOff, nYOff, nXSize, nYSize,
nBufXSize, nBufYSize,
nBandCount, panBandList);
if( eErr != CE_None || bStopProcessing )
return eErr;
if( nBandCount > 100 )
{
ReportError( CE_Failure, CPLE_IllegalArg,
"AdviseRead(): Too many bands : %d", nBandCount);
return CE_Failure;
}
if( nBufXSize != nXSize || nBufYSize != nYSize )
{
// This early exit is because experimentally we found that
// performance of requesting at 50% is much slower with
// AdviseRead()...
// At least on JPEG2000 images with SDK 3.3
CPLDebug("ECW", "Ignoring AdviseRead() for non full resolution request");
return CE_None;
}
// We don't setup the reading window right away, in case the actual read
// pattern wouldn't be compatible of it. Which might be the case for
// example if AdviseRead() requests a full image, but we don't read by
// chunks of the full width of one or several lines
m_nAdviseReadXOff = nXOff;
m_nAdviseReadYOff = nYOff;
m_nAdviseReadXSize = nXSize;
m_nAdviseReadYSize = nYSize;
m_nAdviseReadBufXSize = nBufXSize;
m_nAdviseReadBufYSize = nBufYSize;
m_nAdviseReadBandCount = nBandCount;
CPLFree(m_panAdviseReadBandList);
if( panBandList )
{
m_panAdviseReadBandList =
static_cast<int*>(CPLMalloc(sizeof(int) * nBandCount));
memcpy(m_panAdviseReadBandList, panBandList, sizeof(int) * nBandCount);
}
else
{
m_panAdviseReadBandList = nullptr;
}
return CE_None;
}
/************************************************************************/
/* RunDeferredAdviseRead() */
/************************************************************************/
CPLErr ECWDataset::RunDeferredAdviseRead()
{
CPLAssert(m_nAdviseReadXOff >= 0);
const int nXOff = m_nAdviseReadXOff;
const int nYOff = m_nAdviseReadYOff;
const int nXSize = m_nAdviseReadXSize;
const int nYSize = m_nAdviseReadYSize;
const int nBufXSize = m_nAdviseReadBufXSize;
const int nBufYSize = m_nAdviseReadBufYSize;
const int nBandCount = m_nAdviseReadBandCount;
int* panBandList = m_panAdviseReadBandList;
m_nAdviseReadXOff = -1;
m_nAdviseReadYOff = -1;
m_nAdviseReadXSize = -1;
m_nAdviseReadYSize = -1;
m_nAdviseReadBufXSize = -1;
m_nAdviseReadBufYSize = -1;
m_nAdviseReadBandCount = -1;
m_panAdviseReadBandList = nullptr;
/* -------------------------------------------------------------------- */
/* Adjust band numbers to be zero based. */
/* -------------------------------------------------------------------- */
int* panAdjustedBandList = (int *)
CPLMalloc(sizeof(int) * nBandCount );
nBandIndexToPromoteTo8Bit = -1;
for( int ii= 0; ii < nBandCount; ii++ )
{
panAdjustedBandList[ii] = (panBandList != nullptr) ? panBandList[ii] - 1 : ii;
if( ((ECWRasterBand*)GetRasterBand(panAdjustedBandList[ii] + 1))->bPromoteTo8Bit )
nBandIndexToPromoteTo8Bit = ii;
}
/* -------------------------------------------------------------------- */
/* Cleanup old window cache information. */
/* -------------------------------------------------------------------- */
CleanupWindow();
/* -------------------------------------------------------------------- */
/* Set the new requested window. */
/* -------------------------------------------------------------------- */
CNCSError oErr = poFileView->SetView( nBandCount, (UINT32 *) panAdjustedBandList,
nXOff, nYOff,
nXOff + nXSize-1, nYOff + nYSize-1,
nBufXSize, nBufYSize );
CPLFree( panAdjustedBandList );
if( oErr.GetErrorNumber() != NCS_SUCCESS )
{
ECWReportError(oErr);
bWinActive = FALSE;
CPLFree( panBandList );
return CE_Failure;
}
bWinActive = TRUE;
/* -------------------------------------------------------------------- */
/* Record selected window. */
/* -------------------------------------------------------------------- */
nWinXOff = nXOff;
nWinYOff = nYOff;
nWinXSize = nXSize;
nWinYSize = nYSize;
nWinBufXSize = nBufXSize;
nWinBufYSize = nBufYSize;
panWinBandList = (int *) CPLMalloc(sizeof(int)*nBandCount);
if( panBandList != nullptr )
memcpy( panWinBandList, panBandList, sizeof(int)* nBandCount);
else
{
for( int ii= 0; ii < nBandCount; ii++ )
{
panWinBandList[ii] = ii + 1;
}
}
nWinBandCount = nBandCount;
nWinBufLoaded = -1;
/* -------------------------------------------------------------------- */
/* Allocate current scanline buffer. */
/* -------------------------------------------------------------------- */
papCurLineBuf = (void **) CPLMalloc(sizeof(void*) * nWinBandCount );
for( int iBand = 0; iBand < nWinBandCount; iBand++ )
papCurLineBuf[iBand] =
CPLMalloc(nBufXSize * (GDALGetDataTypeSize(eRasterDataType)/8) );
CPLFree( panBandList );
return CE_None;
}
/************************************************************************/
/* TryWinRasterIO() */
/* */
/* Try to satisfy the given request based on the currently */
/* defined window. Return TRUE on success or FALSE on */
/* failure. On failure, the caller should satisfy the request */
/* another way (not report an error). */
/************************************************************************/
int ECWDataset::TryWinRasterIO( CPL_UNUSED GDALRWFlag eFlag,
int nXOff, int nYOff, int nXSize, int nYSize,
GByte *pabyData, int nBufXSize, int nBufYSize,
GDALDataType eDT,
int nBandCount, int *panBandList,
GSpacing nPixelSpace, GSpacing nLineSpace,
GSpacing nBandSpace,
GDALRasterIOExtraArg* psExtraArg )
{
int iBand, i;
/* -------------------------------------------------------------------- */
/* Provide default buffer organization. */
/* -------------------------------------------------------------------- */
if( nPixelSpace == 0 )
nPixelSpace = GDALGetDataTypeSize( eDT ) / 8;
if( nLineSpace == 0 )
nLineSpace = nPixelSpace * nBufXSize;
if( nBandSpace == 0 )
nBandSpace = nLineSpace * nBufYSize;
/* -------------------------------------------------------------------- */
/* Do some simple tests to see if the current window can */
/* satisfy our requirement. */
/* -------------------------------------------------------------------- */
#ifdef NOISY_DEBUG
CPLDebug( "ECW", "TryWinRasterIO(%d,%d,%d,%d,%d,%d)",
nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize );
#endif
if( !bWinActive )
{
if( nXOff == m_nAdviseReadXOff && nXSize == m_nAdviseReadXSize &&
nBufXSize == m_nAdviseReadBufXSize )
{
if( RunDeferredAdviseRead() != CE_None )
return FALSE;
}
if( !bWinActive )
{
return FALSE;
}
}
if( nXOff != nWinXOff || nXSize != nWinXSize )
return FALSE;
if( nBufXSize != nWinBufXSize )
return FALSE;
for( iBand = 0; iBand < nBandCount; iBand++ )
{
for( i = 0; i < nWinBandCount; i++ )
{
if( panWinBandList[i] == panBandList[iBand] )
break;
}
if( i == nWinBandCount )
return FALSE;
}
if( nYOff < nWinYOff || nYOff + nYSize > nWinYOff + nWinYSize )
return FALSE;
/* -------------------------------------------------------------------- */
/* Now we try more subtle tests. */
/* -------------------------------------------------------------------- */
{
static int nDebugCount = 0;
if( nDebugCount < 30 )
CPLDebug( "ECW",
"TryWinRasterIO(%d,%d,%d,%d -> %dx%d) - doing advised read.",
nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize );
if( nDebugCount == 29 )
CPLDebug( "ECW", "No more TryWinRasterIO messages will be reported" );
nDebugCount++;
}
/* -------------------------------------------------------------------- */
/* Actually load data one buffer line at a time. */
/* -------------------------------------------------------------------- */
int iBufLine;
for( iBufLine = 0; iBufLine < nBufYSize; iBufLine++ )
{
double fFileLine = ((iBufLine+0.5) / nBufYSize) * nYSize + nYOff;
int iWinLine =
(int) (((fFileLine - nWinYOff) / nWinYSize) * nWinBufYSize);
if( iWinLine == nWinBufLoaded + 1 )
LoadNextLine();
if( iWinLine != nWinBufLoaded )
return FALSE;
/* -------------------------------------------------------------------- */
/* Copy out all our target bands. */
/* -------------------------------------------------------------------- */
int iWinBand;
for( iBand = 0; iBand < nBandCount; iBand++ )
{
for( iWinBand = 0; iWinBand < nWinBandCount; iWinBand++ )
{
if( panWinBandList[iWinBand] == panBandList[iBand] )
break;
}
GDALCopyWords( papCurLineBuf[iWinBand], eRasterDataType,
GDALGetDataTypeSize( eRasterDataType ) / 8,
pabyData + nBandSpace * iBand
+ iBufLine * nLineSpace, eDT, (int)nPixelSpace,
nBufXSize );
}
if( psExtraArg->pfnProgress != nullptr &&
!psExtraArg->pfnProgress(1.0 * (iBufLine + 1) / nBufYSize, "",
psExtraArg->pProgressData) )
{
return -1;
}
}
return TRUE;
}
/************************************************************************/
/* LoadNextLine() */
/************************************************************************/
CPLErr ECWDataset::LoadNextLine()
{
if( !bWinActive )
return CE_Failure;
if( nWinBufLoaded == nWinBufYSize-1 )
{
CleanupWindow();
return CE_Failure;
}
NCSEcwReadStatus eRStatus;
eRStatus = poFileView->ReadLineBIL( eNCSRequestDataType,
(UINT16) nWinBandCount,
papCurLineBuf );
if( eRStatus != NCSECW_READ_OK )
return CE_Failure;
if( nBandIndexToPromoteTo8Bit >= 0 )
{
for(int iX = 0; iX < nWinBufXSize; iX ++ )
{
((GByte*)papCurLineBuf[nBandIndexToPromoteTo8Bit])[iX] *= 255;
}
}
nWinBufLoaded++;
return CE_None;
}
/************************************************************************/
/* CleanupWindow() */
/************************************************************************/
void ECWDataset::CleanupWindow()
{
if( !bWinActive )
return;
bWinActive = FALSE;
CPLFree( panWinBandList );
panWinBandList = nullptr;
for( int iBand = 0; iBand < nWinBandCount; iBand++ )
CPLFree( papCurLineBuf[iBand] );
CPLFree( papCurLineBuf );
papCurLineBuf = nullptr;
}
/************************************************************************/
/* IRasterIO() */
/************************************************************************/
CPLErr ECWDataset::IRasterIO( GDALRWFlag eRWFlag,
int nXOff, int nYOff, int nXSize, int nYSize,
void * pData, int nBufXSize, int nBufYSize,
GDALDataType eBufType,
int nBandCount, int *panBandMap,
GSpacing nPixelSpace, GSpacing nLineSpace,
GSpacing nBandSpace,
GDALRasterIOExtraArg* psExtraArg)
{
if( eRWFlag == GF_Write )
return CE_Failure;
if( nBandCount > 100 )
return CE_Failure;
if( bUseOldBandRasterIOImplementation )
/* Sanity check. Should not happen */
return CE_Failure;
int nDataTypeSize = (GDALGetDataTypeSize(eRasterDataType) / 8);
if ( nPixelSpace == 0 ){
nPixelSpace = nDataTypeSize;
}
if (nLineSpace == 0 ) {
nLineSpace = nPixelSpace*nBufXSize;
}
if ( nBandSpace == 0 ){
nBandSpace = static_cast<GSpacing>(nDataTypeSize)*nBufXSize*nBufYSize;
}
// Use GDAL upsampling if non nearest
if( (nBufXSize > nXSize || nBufYSize > nYSize) &&
psExtraArg->eResampleAlg != GRIORA_NearestNeighbour )
{
int nBufDataTypeSize = (GDALGetDataTypeSize(eBufType) / 8);
GByte* pabyTemp = (GByte*)VSI_MALLOC3_VERBOSE(nXSize, nYSize, nBufDataTypeSize * nBandCount);
if( pabyTemp == nullptr )
{
return CE_Failure;
}
CPLErr eErr = IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
pabyTemp, nXSize, nYSize,
eBufType, nBandCount, panBandMap,
nBufDataTypeSize,
(GIntBig)nBufDataTypeSize* nXSize,
(GIntBig)nBufDataTypeSize*nXSize*nYSize,
psExtraArg);
if( eErr == CE_None )
{
/* Create a MEM dataset that wraps the input buffer */
GDALDataset* poMEMDS = MEMDataset::Create("", nXSize, nYSize, 0,
eBufType, nullptr);
char szBuffer[64];
int nRet;
for( int i = 0; i < nBandCount; i++ )
{
nRet = CPLPrintPointer(szBuffer, pabyTemp + i * nBufDataTypeSize, sizeof(szBuffer));
szBuffer[nRet] = 0;
char** papszOptions = CSLSetNameValue(nullptr, "DATAPOINTER", szBuffer);
papszOptions = CSLSetNameValue(papszOptions, "PIXELOFFSET",
CPLSPrintf(CPL_FRMT_GIB, (GIntBig)nBufDataTypeSize * nBandCount));
papszOptions = CSLSetNameValue(papszOptions, "LINEOFFSET",
CPLSPrintf(CPL_FRMT_GIB, (GIntBig)nBufDataTypeSize * nBandCount * nXSize));
poMEMDS->AddBand(eBufType, papszOptions);
CSLDestroy(papszOptions);
const char* pszNBITS = GetRasterBand(i+1)->GetMetadataItem("NBITS", "IMAGE_STRUCTURE");
if( pszNBITS )
poMEMDS->GetRasterBand(i+1)->SetMetadataItem("NBITS", pszNBITS, "IMAGE_STRUCTURE");
}
GDALRasterIOExtraArg sExtraArgTmp;
INIT_RASTERIO_EXTRA_ARG(sExtraArgTmp);
sExtraArgTmp.eResampleAlg = psExtraArg->eResampleAlg;
CPL_IGNORE_RET_VAL(poMEMDS->RasterIO(GF_Read, 0, 0, nXSize, nYSize,
pData, nBufXSize, nBufYSize,
eBufType,
nBandCount, nullptr,
nPixelSpace, nLineSpace, nBandSpace,
&sExtraArgTmp));
GDALClose(poMEMDS);
}
VSIFree(pabyTemp);
return eErr;
}
/* -------------------------------------------------------------------- */
/* ECW SDK 3.3 has a bug with the ECW format when we query the */
/* number of bands of the dataset, but not in the "natural order". */
/* It ignores the content of panBandMap. (#4234) */
/* -------------------------------------------------------------------- */
#if ECWSDK_VERSION < 40
if( !bIsJPEG2000 && nBandCount == nBands )
{
int i;
int bDoBandIRasterIO = FALSE;
for( i = 0; i < nBandCount; i++ )
{
if( panBandMap[i] != i + 1 )
{
bDoBandIRasterIO = TRUE;
}
}
if( bDoBandIRasterIO )
{
return GDALDataset::IRasterIO(
eRWFlag, nXOff, nYOff, nXSize, nYSize,
pData, nBufXSize, nBufYSize,
eBufType,
nBandCount, panBandMap,
nPixelSpace, nLineSpace, nBandSpace, psExtraArg);
}
}
#endif
/* -------------------------------------------------------------------- */
/* Check if we can directly return the data in case we have cached */
/* it from a previous call in a multi-band reading pattern. */
/* -------------------------------------------------------------------- */
if( nBandCount == 1 && *panBandMap > 1 && *panBandMap <= nBands &&
sCachedMultiBandIO.nXOff == nXOff &&
sCachedMultiBandIO.nYOff == nYOff &&
sCachedMultiBandIO.nXSize == nXSize &&
sCachedMultiBandIO.nYSize == nYSize &&
sCachedMultiBandIO.nBufXSize == nBufXSize &&
sCachedMultiBandIO.nBufYSize == nBufYSize &&
sCachedMultiBandIO.eBufType == eBufType )
{
sCachedMultiBandIO.nBandsTried ++;
if( sCachedMultiBandIO.bEnabled &&
sCachedMultiBandIO.pabyData != nullptr )
{
int j;
int nBufTypeSize = GDALGetDataTypeSize(eBufType) / 8;
for(j = 0; j < nBufYSize; j++)
{
GDALCopyWords(sCachedMultiBandIO.pabyData +
(*panBandMap - 1) * nBufXSize * nBufYSize * nBufTypeSize +
j * nBufXSize * nBufTypeSize,
eBufType, nBufTypeSize,
((GByte*)pData) + j * nLineSpace, eBufType, (int)nPixelSpace,
nBufXSize);
}
return CE_None;
}
if( !(sCachedMultiBandIO.bEnabled) &&
sCachedMultiBandIO.nBandsTried == nBands &&
CPLTestBool(CPLGetConfigOption("ECW_CLEVER", "YES")) )
{
sCachedMultiBandIO.bEnabled = TRUE;
CPLDebug("ECW", "Detecting successive band reading pattern (for next time)");
}
}
/* -------------------------------------------------------------------- */
/* Try to do it based on existing "advised" access. */
/* -------------------------------------------------------------------- */
int nRet = TryWinRasterIO( eRWFlag, nXOff, nYOff, nXSize, nYSize,
(GByte *) pData, nBufXSize, nBufYSize,
eBufType, nBandCount, panBandMap,
nPixelSpace, nLineSpace, nBandSpace, psExtraArg );
if( nRet == TRUE )
return CE_None;
else if( nRet < 0 )
return CE_Failure;
/* -------------------------------------------------------------------- */
/* If we are requesting a single line at 1:1, we do a multi-band */
/* AdviseRead() and then TryWinRasterIO() again. */
/* */
/* Except for reading a 1x1 window when reading a scanline might */
/* be longer. */
/* -------------------------------------------------------------------- */
if( nXSize == 1 && nYSize == 1 && nBufXSize == 1 && nBufYSize == 1 )
{
/* do nothing */
}
#if !defined(SDK_CAN_DO_SUPERSAMPLING)
/* -------------------------------------------------------------------- */
/* If we are supersampling we need to fall into the general */
/* purpose logic. */
/* -------------------------------------------------------------------- */
else if( nXSize < nBufXSize || nYSize < nBufYSize )
{
bUseOldBandRasterIOImplementation = TRUE;
CPLErr eErr =
GDALDataset::IRasterIO( eRWFlag, nXOff, nYOff, nXSize, nYSize,
pData, nBufXSize, nBufYSize,
eBufType,
nBandCount, panBandMap,
nPixelSpace, nLineSpace, nBandSpace, psExtraArg);
bUseOldBandRasterIOImplementation = FALSE;
return eErr;
}
#endif
else if( nBufYSize == 1 )
{
// This is tricky, because it expects the rest of the image
// with this buffer width to be read. The preferred way to
// achieve this behaviour would be to call AdviseRead before
// call IRasterIO. The logic could be improved to detect
// successive pattern of single line reading before doing an
// AdviseRead.
CPLErr eErr;
eErr = AdviseRead( nXOff, nYOff, nXSize, GetRasterYSize() - nYOff,
nBufXSize, (nRasterYSize - nYOff) / nYSize, eBufType,
nBandCount, panBandMap, nullptr );
if( eErr == CE_None
&& TryWinRasterIO( eRWFlag, nXOff, nYOff, nXSize, nYSize,
(GByte *) pData, nBufXSize, nBufYSize,
eBufType, nBandCount, panBandMap,
nPixelSpace, nLineSpace, nBandSpace, psExtraArg ) )
return CE_None;
}
CPLDebug( "ECW",
"RasterIO(%d,%d,%d,%d -> %dx%d) - doing interleaved read.",
nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize );
/* -------------------------------------------------------------------- */
/* Setup view. */
/* -------------------------------------------------------------------- */
UINT32 anBandIndices[100];
int i;
NCSError eNCSErr;
CNCSError oErr(GetCNCSError(NCS_SUCCESS));
for( i = 0; i < nBandCount; i++ )
anBandIndices[i] = panBandMap[i] - 1;
CleanupWindow();
/* -------------------------------------------------------------------- */
/* Cache data in the context of a multi-band reading pattern. */
/* -------------------------------------------------------------------- */
if( nBandCount == 1 && *panBandMap == 1 && (nBands == 3 || nBands == 4) )
{
if( sCachedMultiBandIO.bEnabled && sCachedMultiBandIO.nBandsTried != nBands )
{
sCachedMultiBandIO.bEnabled = FALSE;
CPLDebug("ECW", "Disabling successive band reading pattern");
}
sCachedMultiBandIO.nXOff = nXOff;
sCachedMultiBandIO.nYOff = nYOff;
sCachedMultiBandIO.nXSize = nXSize;
sCachedMultiBandIO.nYSize = nYSize;
sCachedMultiBandIO.nBufXSize = nBufXSize;
sCachedMultiBandIO.nBufYSize = nBufYSize;
sCachedMultiBandIO.eBufType = eBufType;
sCachedMultiBandIO.nBandsTried = 1;
int nBufTypeSize = GDALGetDataTypeSize(eBufType) / 8;
if( sCachedMultiBandIO.bEnabled )
{
GByte* pNew = (GByte*)VSIRealloc(
sCachedMultiBandIO.pabyData,
nBufXSize * nBufYSize * nBands * nBufTypeSize);
if( pNew == nullptr )
CPLFree(sCachedMultiBandIO.pabyData);
sCachedMultiBandIO.pabyData = pNew;
}
if( sCachedMultiBandIO.bEnabled &&
sCachedMultiBandIO.pabyData != nullptr )
{
nBandIndexToPromoteTo8Bit = -1;
for( i = 0; i < nBands; i++ )
{
if( ((ECWRasterBand*)GetRasterBand(i+1))->bPromoteTo8Bit )
nBandIndexToPromoteTo8Bit = i;
anBandIndices[i] = i;
}
oErr = poFileView->SetView( nBands, anBandIndices,
nXOff, nYOff,
nXOff + nXSize - 1,
nYOff + nYSize - 1,
nBufXSize, nBufYSize );
eNCSErr = oErr.GetErrorNumber();
if( eNCSErr != NCS_SUCCESS )
{
CPLError( CE_Failure, CPLE_AppDefined,
"%s", NCSGetErrorText(eNCSErr) );
return CE_Failure;
}
CPLErr eErr = ReadBands(sCachedMultiBandIO.pabyData,
nBufXSize, nBufYSize, eBufType,
nBands,
nBufTypeSize,
nBufXSize * nBufTypeSize,
nBufXSize * nBufYSize * nBufTypeSize,
psExtraArg);
if( eErr != CE_None )
return eErr;
int j;
for(j = 0; j < nBufYSize; j++)
{
GDALCopyWords(sCachedMultiBandIO.pabyData +
j * nBufXSize * nBufTypeSize,
eBufType, nBufTypeSize,
((GByte*)pData) + j * nLineSpace, eBufType, (int)nPixelSpace,
nBufXSize);
}
return CE_None;
}
}
nBandIndexToPromoteTo8Bit = -1;
for( i = 0; i < nBandCount; i++ )
{
if( ((ECWRasterBand*)GetRasterBand(anBandIndices[i]+1))->bPromoteTo8Bit )
nBandIndexToPromoteTo8Bit = i;
}
oErr = poFileView->SetView( nBandCount, anBandIndices,
nXOff, nYOff,
nXOff + nXSize - 1,
nYOff + nYSize - 1,
nBufXSize, nBufYSize );
eNCSErr = oErr.GetErrorNumber();
if( eNCSErr != NCS_SUCCESS )
{
CPLError( CE_Failure, CPLE_AppDefined,
"%s", NCSGetErrorText(eNCSErr) );
return CE_Failure;
}
return ReadBands(pData, nBufXSize, nBufYSize, eBufType,
nBandCount, nPixelSpace, nLineSpace, nBandSpace,
psExtraArg);
}
/************************************************************************/
/* ReadBandsDirectly() */
/************************************************************************/
CPLErr ECWDataset::ReadBandsDirectly(void * pData, int nBufXSize, int nBufYSize,
CPL_UNUSED GDALDataType eBufType,
int nBandCount,
CPL_UNUSED GSpacing nPixelSpace,
GSpacing nLineSpace,
GSpacing nBandSpace,
GDALRasterIOExtraArg* psExtraArg)
{
CPLDebug( "ECW",
"ReadBandsDirectly(-> %dx%d) - reading lines directly.",
nBufXSize, nBufYSize);
UINT8 **pBIL = (UINT8**)NCSMalloc(nBandCount * sizeof(UINT8*), FALSE);
for(int nB = 0; nB < nBandCount; nB++)
{
pBIL[nB] = ((UINT8*)pData) + (nBandSpace*nB);//for any bit depth
}
CPLErr eErr = CE_None;
for(int nR = 0; nR < nBufYSize; nR++)
{
if (poFileView->ReadLineBIL(eNCSRequestDataType,(UINT16) nBandCount, (void**)pBIL) != NCSECW_READ_OK)
{
eErr = CE_Failure;
break;
}
for(int nB = 0; nB < nBandCount; nB++)
{
if( nB == nBandIndexToPromoteTo8Bit )
{
for(int iX = 0; iX < nBufXSize; iX ++ )
{
pBIL[nB][iX] *= 255;
}
}
pBIL[nB] += nLineSpace;
}
if( psExtraArg->pfnProgress != nullptr &&
!psExtraArg->pfnProgress(1.0 * (nR + 1) / nBufYSize, "",
psExtraArg->pProgressData) )
{
eErr = CE_Failure;
break;
}
}
if(pBIL)
{
NCSFree(pBIL);
}
return eErr;
}
/************************************************************************/
/* ReadBands() */
/************************************************************************/
CPLErr ECWDataset::ReadBands(void * pData, int nBufXSize, int nBufYSize,
GDALDataType eBufType,
int nBandCount,
GSpacing nPixelSpace, GSpacing nLineSpace, GSpacing nBandSpace,
GDALRasterIOExtraArg* psExtraArg)
{
int i;
/* -------------------------------------------------------------------- */
/* Setup working scanline, and the pointers into it. */
/* -------------------------------------------------------------------- */
int nDataTypeSize = (GDALGetDataTypeSize(eRasterDataType) / 8);
bool bDirect = (eBufType == eRasterDataType) && nDataTypeSize == nPixelSpace &&
nLineSpace == (nPixelSpace*nBufXSize) && nBandSpace == (static_cast<GSpacing>(nDataTypeSize)*nBufXSize*nBufYSize) ;
if (bDirect)
{
return ReadBandsDirectly(pData, nBufXSize, nBufYSize,eBufType,
nBandCount, nPixelSpace, nLineSpace, nBandSpace, psExtraArg);
}
CPLDebug( "ECW",
"ReadBands(-> %dx%d) - reading lines using GDALCopyWords.",
nBufXSize, nBufYSize);
CPLErr eErr = CE_None;
GByte *pabyBILScanline = (GByte *) CPLMalloc(nBufXSize * nDataTypeSize *
nBandCount);
GByte **papabyBIL = (GByte **) CPLMalloc(nBandCount * sizeof(void*));
for( i = 0; i < nBandCount; i++ )
papabyBIL[i] = pabyBILScanline + i * nBufXSize * nDataTypeSize;
/* -------------------------------------------------------------------- */
/* Read back all the data for the requested view. */
/* -------------------------------------------------------------------- */
for( int iScanline = 0; iScanline < nBufYSize; iScanline++ )
{
NCSEcwReadStatus eRStatus;
eRStatus = poFileView->ReadLineBIL( eNCSRequestDataType,
(UINT16) nBandCount,
(void **) papabyBIL );
if( eRStatus != NCSECW_READ_OK )
{
eErr = CE_Failure;
CPLError( CE_Failure, CPLE_AppDefined,
"NCScbmReadViewLineBIL failed." );
break;
}
for( i = 0; i < nBandCount; i++ )
{
if( i == nBandIndexToPromoteTo8Bit )
{
for(int iX = 0; iX < nBufXSize; iX ++ )
{
papabyBIL[i][iX] *= 255;
}
}
GDALCopyWords(
pabyBILScanline + i * nDataTypeSize * nBufXSize,
eRasterDataType, nDataTypeSize,
((GByte *) pData) + nLineSpace * iScanline + nBandSpace * i,
eBufType, (int)nPixelSpace,
nBufXSize );
}
if( psExtraArg->pfnProgress != nullptr &&
!psExtraArg->pfnProgress(1.0 * (iScanline + 1) / nBufYSize, "",
psExtraArg->pProgressData) )
{
eErr = CE_Failure;
break;
}
}
CPLFree( pabyBILScanline );
CPLFree( papabyBIL );
return eErr;
}
/************************************************************************/
/* IdentifyJPEG2000() */
/* */
/* Identify method that only supports JPEG2000 files. */
/************************************************************************/
int ECWDataset::IdentifyJPEG2000( GDALOpenInfo * poOpenInfo )
{
if( STARTS_WITH_CI(poOpenInfo->pszFilename, "J2K_SUBFILE:") )
return TRUE;
else if( poOpenInfo->nHeaderBytes >= 16
&& (memcmp( poOpenInfo->pabyHeader, jpc_header,
sizeof(jpc_header) ) == 0
|| memcmp( poOpenInfo->pabyHeader, jp2_header,
sizeof(jp2_header) ) == 0) )
return TRUE;
else
return FALSE;
}
/************************************************************************/
/* OpenJPEG2000() */
/* */
/* Open method that only supports JPEG2000 files. */
/************************************************************************/
GDALDataset *ECWDataset::OpenJPEG2000( GDALOpenInfo * poOpenInfo )
{
if (!IdentifyJPEG2000(poOpenInfo))
return nullptr;
return Open( poOpenInfo, TRUE );
}
/************************************************************************/
/* IdentifyECW() */
/* */
/* Identify method that only supports ECW files. */
/************************************************************************/
int ECWDataset::IdentifyECW( GDALOpenInfo * poOpenInfo )
{
/* -------------------------------------------------------------------- */
/* This has to either be a file on disk ending in .ecw or a */
/* ecwp: protocol url. */
/* -------------------------------------------------------------------- */
if( (!EQUAL(CPLGetExtension(poOpenInfo->pszFilename),"ecw")
|| poOpenInfo->nHeaderBytes == 0)
&& !STARTS_WITH_CI(poOpenInfo->pszFilename, "ecwp:")
&& !STARTS_WITH_CI(poOpenInfo->pszFilename,"ecwps:") )
return FALSE;
return TRUE;
}
/************************************************************************/
/* OpenECW() */
/* */
/* Open method that only supports ECW files. */
/************************************************************************/
GDALDataset *ECWDataset::OpenECW( GDALOpenInfo * poOpenInfo )
{
if (!IdentifyECW(poOpenInfo))
return nullptr;
return Open( poOpenInfo, FALSE );
}
/************************************************************************/
/* OpenFileView() */
/************************************************************************/
CNCSJP2FileView *ECWDataset::OpenFileView( const char *pszDatasetName,
bool bProgressive,
int &bUsingCustomStream,
CPL_UNUSED bool bWrite )
{
/* -------------------------------------------------------------------- */
/* First we try to open it as a normal CNCSFile, letting the */
/* ECW SDK manage the IO itself. This will only work for real */
/* files, and ecwp: or ecwps: sources. */
/* -------------------------------------------------------------------- */
CNCSJP2FileView *poFileView = nullptr;
NCSError eErr;
CNCSError oErr(GetCNCSError(NCS_SUCCESS));
bUsingCustomStream = FALSE;
poFileView = new CNCSFile();
//we always open in read only mode. This should be improved in the future.
try
{
#ifdef WIN32
if( CPLTestBool( CPLGetConfigOption( "GDAL_FILENAME_IS_UTF8", "YES" ) ) )
{
wchar_t *pwszDatasetName = CPLRecodeToWChar( pszDatasetName, CPL_ENC_UTF8, CPL_ENC_UCS2 );
oErr = poFileView->Open( pwszDatasetName, bProgressive, false );
CPLFree( pwszDatasetName );
}
else
#endif
{
oErr = poFileView->Open( (char *) pszDatasetName, bProgressive, false );
}
}
catch(...)
{
CPLError( CE_Failure, CPLE_AppDefined,
"Unexpected exception occurred in ECW SDK");
delete poFileView;
return nullptr;
}
eErr = oErr.GetErrorNumber();
/* -------------------------------------------------------------------- */
/* If that did not work, trying opening as a virtual file. */
/* -------------------------------------------------------------------- */
if( eErr != NCS_SUCCESS )
{
CPLDebug( "ECW",
"NCScbmOpenFileView(%s): eErr=%d, will try VSIL stream.",
pszDatasetName, (int) eErr );
delete poFileView;
VSILFILE *fpVSIL = VSIFOpenL( pszDatasetName, "rb" );
if( fpVSIL == nullptr )
{
CPLError( CE_Failure, CPLE_OpenFailed,
"Failed to open %s.", pszDatasetName );
return nullptr;
}
if( hECWDatasetMutex == nullptr )
{
hECWDatasetMutex = CPLCreateMutex();
}
else if( !CPLAcquireMutex( hECWDatasetMutex, 60.0 ) )
{
CPLDebug( "ECW", "Failed to acquire mutex in 60s." );
}
else
{
CPLDebug( "ECW", "Got mutex." );
}
poFileView = new CNCSJP2FileView();
#if ECWSDK_VERSION >= 55
NCS::CString streamName(pszDatasetName);
auto vsiIoStream = NCS::CView::FindSteamByStreamNameFromOpenDatasets(streamName);
if (!vsiIoStream) {
vsiIoStream = std::make_shared<VSIIOStream>();
std::static_pointer_cast<VSIIOStream>(vsiIoStream)->Access(fpVSIL, FALSE, TRUE, pszDatasetName, 0, -1);
bUsingCustomStream = TRUE;
}
oErr = poFileView->Open(vsiIoStream, bProgressive);
#else
auto vsiIoStream = new VSIIOStream();
vsiIoStream->Access(fpVSIL, FALSE, TRUE, pszDatasetName, 0, -1);
oErr = poFileView->Open(vsiIoStream, bProgressive);
// The CNCSJP2FileView (poFileView) object may not use the iostream
// (poIOStream) passed to the CNCSJP2FileView::Open() method if an
// iostream is already available to the ECW JPEG 2000 SDK for a given
// file. Consequently, if the iostream passed to
// CNCSJP2FileView::Open() does not become the underlying iostream
// of the CNCSJP2FileView object, then it should be deleted.
//
// In addition, the underlying iostream of the CNCSJP2FileView object
// should not be deleted until all CNCSJP2FileView objects using the
// underlying iostream are deleted. Consequently, each time a
// CNCSJP2FileView object is created, the nFileViewCount attribute
// of the underlying VSIIOStream object must be incremented for use
// in the ECWDataset destructor.
VSIIOStream * poUnderlyingIOStream =
((VSIIOStream *)(poFileView->GetStream()));
if (poUnderlyingIOStream)
poUnderlyingIOStream->nFileViewCount++;
if ( vsiIoStream != poUnderlyingIOStream )
{
delete vsiIoStream;
}
else
{
bUsingCustomStream = TRUE;
}
#endif
CPLReleaseMutex( hECWDatasetMutex );
if( oErr.GetErrorNumber() != NCS_SUCCESS )
{
delete poFileView;
ECWReportError(oErr);
return nullptr;
}
}
return poFileView;
}
/************************************************************************/
/* Open() */
/************************************************************************/
GDALDataset *ECWDataset::Open( GDALOpenInfo * poOpenInfo, int bIsJPEG2000 )
{
CNCSJP2FileView *poFileView = nullptr;
int i;
int bUsingCustomStream = FALSE;
CPLString osFilename = poOpenInfo->pszFilename;
ECWInitialize();
/* Note: J2K_SUBFILE is somehow an obsolete concept that predates /vsisubfile/ */
/* syntax and was used mainly(only?) by the NITF driver before its switch */
/* to /vsisubfile */
/* -------------------------------------------------------------------- */
/* If we get a J2K_SUBFILE style name, convert it into the */
/* corresponding /vsisubfile/ path. */
/* */
/* From: J2K_SUBFILE:offset,size,filename */
/* To: /vsisubfile/offset_size,filename */
/* -------------------------------------------------------------------- */
if (STARTS_WITH_CI(osFilename, "J2K_SUBFILE:"))
{
char** papszTokens = CSLTokenizeString2(osFilename.c_str()+12, ",", 0);
if (CSLCount(papszTokens) >= 3)
{
osFilename.Printf( "/vsisubfile/%s_%s,%s",
papszTokens[0], papszTokens[1], papszTokens[2]);
}
else
{
CPLError( CE_Failure, CPLE_OpenFailed,
"Failed to parse J2K_SUBFILE specification." );
CSLDestroy(papszTokens);
return nullptr;
}
CSLDestroy(papszTokens);
}
/* -------------------------------------------------------------------- */
/* Open the client interface. */
/* -------------------------------------------------------------------- */
poFileView = OpenFileView( osFilename.c_str(), false, bUsingCustomStream, poOpenInfo->eAccess == GA_Update );
if( poFileView == nullptr )
{
#if ECWSDK_VERSION < 50
/* Detect what is apparently the ECW v3 file format signature */
if( EQUAL(CPLGetExtension(osFilename), "ECW") &&
poOpenInfo->nHeaderBytes > 0x30 &&
STARTS_WITH_CI((const char*)(poOpenInfo->pabyHeader + 0x20), "ecw ECW3") )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot open %s which looks like a ECW format v3 file, that requires ECW SDK 5.0 or later",
osFilename.c_str());
}
#endif
return nullptr;
}
/* -------------------------------------------------------------------- */
/* Create a corresponding GDALDataset. */
/* -------------------------------------------------------------------- */
ECWDataset *poDS = new ECWDataset(bIsJPEG2000);
poDS->poFileView = poFileView;
poDS->eAccess = poOpenInfo->eAccess;
// Disable .aux.xml writing for subfiles and such. Unfortunately
// this will also disable it in some cases where it might be
// applicable.
if( bUsingCustomStream )
poDS->nPamFlags |= GPF_DISABLED;
poDS->bUsingCustomStream = bUsingCustomStream;
/* -------------------------------------------------------------------- */
/* Fetch general file information. */
/* -------------------------------------------------------------------- */
poDS->psFileInfo = poFileView->GetFileInfo();
CPLDebug( "ECW", "FileInfo: SizeXY=%d,%d Bands=%d\n"
" OriginXY=%g,%g CellIncrementXY=%g,%g\n"
" ColorSpace=%d, eCellType=%d\n",
poDS->psFileInfo->nSizeX,
poDS->psFileInfo->nSizeY,
poDS->psFileInfo->nBands,
poDS->psFileInfo->fOriginX,
poDS->psFileInfo->fOriginY,
poDS->psFileInfo->fCellIncrementX,
poDS->psFileInfo->fCellIncrementY,
(int) poDS->psFileInfo->eColorSpace,
(int) poDS->psFileInfo->eCellType );
/* -------------------------------------------------------------------- */
/* Establish raster info. */
/* -------------------------------------------------------------------- */
poDS->nRasterXSize = poDS->psFileInfo->nSizeX;
poDS->nRasterYSize = poDS->psFileInfo->nSizeY;
/* -------------------------------------------------------------------- */
/* Establish the GDAL data type that corresponds. A few NCS */
/* data types have no direct corresponding value in GDAL so we */
/* will coerce to something sufficiently similar. */
/* -------------------------------------------------------------------- */
poDS->eNCSRequestDataType = poDS->psFileInfo->eCellType;
switch( poDS->psFileInfo->eCellType )
{
case NCSCT_UINT8:
poDS->eRasterDataType = GDT_Byte;
break;
case NCSCT_UINT16:
poDS->eRasterDataType = GDT_UInt16;
break;
case NCSCT_UINT32:
case NCSCT_UINT64:
poDS->eRasterDataType = GDT_UInt32;
poDS->eNCSRequestDataType = NCSCT_UINT32;
break;
case NCSCT_INT8:
case NCSCT_INT16:
poDS->eRasterDataType = GDT_Int16;
poDS->eNCSRequestDataType = NCSCT_INT16;
break;
case NCSCT_INT32:
case NCSCT_INT64:
poDS->eRasterDataType = GDT_Int32;
poDS->eNCSRequestDataType = NCSCT_INT32;
break;
case NCSCT_IEEE4:
poDS->eRasterDataType = GDT_Float32;
break;
case NCSCT_IEEE8:
poDS->eRasterDataType = GDT_Float64;
break;
default:
CPLDebug("ECW", "Unhandled case : eCellType = %d",
(int)poDS->psFileInfo->eCellType );
break;
}
/* -------------------------------------------------------------------- */
/* Create band information objects. */
/* -------------------------------------------------------------------- */
for( i=0; i < poDS->psFileInfo->nBands; i++ )
poDS->SetBand( i+1, new ECWRasterBand( poDS, i+1, -1, poOpenInfo->papszOpenOptions ) );
/* -------------------------------------------------------------------- */
/* Look for supporting coordinate system information. */
/* -------------------------------------------------------------------- */
if( bIsJPEG2000 )
{
poDS->LoadJP2Metadata(poOpenInfo, osFilename);
}
else
{
poDS->ECW2WKTProjection();
/* -------------------------------------------------------------------- */
/* Check for world file. */
/* -------------------------------------------------------------------- */
if( !poDS->bGeoTransformValid )
{
poDS->bGeoTransformValid |=
GDALReadWorldFile2( osFilename, nullptr,
poDS->adfGeoTransform,
poOpenInfo->GetSiblingFiles(), nullptr )
|| GDALReadWorldFile2( osFilename, ".wld",
poDS->adfGeoTransform,
poOpenInfo->GetSiblingFiles(), nullptr );
}
}
poDS->SetMetadataItem("COMPRESSION_RATE_TARGET", CPLString().Printf("%d", poDS->psFileInfo->nCompressionRate));
poDS->SetMetadataItem("COLORSPACE", ECWGetColorSpaceName(poDS->psFileInfo->eColorSpace));
#if ECWSDK_VERSION>=50
if( !bIsJPEG2000 )
poDS->SetMetadataItem("VERSION", CPLString().Printf("%d", poDS->psFileInfo->nFormatVersion));
#if ECWSDK_VERSION>=51
// output jp2 header info
if( bIsJPEG2000 && poDS->poFileView ) {
// comments
char *csComments = nullptr;
poDS->poFileView->GetParameter((char*)"JPC:DECOMPRESS:COMMENTS", &csComments);
if (csComments) {
poDS->SetMetadataItem("ALL_COMMENTS", CPLString().Printf("%s", csComments));
NCSFree(csComments);
}
// Profile
UINT32 nProfile = 2;
UINT32 nRsiz = 0;
poDS->poFileView->GetParameter((char*)"JP2:COMPLIANCE:PROFILE:TYPE", &nRsiz);
if (nRsiz == 0)
nProfile = 2; // Profile 2 (no restrictions)
else if (nRsiz == 1)
nProfile = 0; // Profile 0
else if (nRsiz == 2)
nProfile = 1; // Profile 1, NITF_BIIF_NPJE, NITF_BIIF_EPJE
poDS->SetMetadataItem("PROFILE", CPLString().Printf("%d", nProfile), JPEG2000_DOMAIN_NAME);
// number of tiles on X axis
UINT32 nTileNrX = 1;
poDS->poFileView->GetParameter((char*)"JPC:DECOMPRESS:TILENR:X", &nTileNrX);
poDS->SetMetadataItem("TILES_X", CPLString().Printf("%d", nTileNrX), JPEG2000_DOMAIN_NAME);
// number of tiles on X axis
UINT32 nTileNrY = 1;
poDS->poFileView->GetParameter((char*)"JPC:DECOMPRESS:TILENR:Y", &nTileNrY);
poDS->SetMetadataItem("TILES_Y", CPLString().Printf("%d", nTileNrY), JPEG2000_DOMAIN_NAME);
// Tile Width
UINT32 nTileSizeX = 0;
poDS->poFileView->GetParameter((char*)"JPC:DECOMPRESS:TILESIZE:X", &nTileSizeX);
poDS->SetMetadataItem("TILE_WIDTH", CPLString().Printf("%d", nTileSizeX), JPEG2000_DOMAIN_NAME);
// Tile Height
UINT32 nTileSizeY = 0;
poDS->poFileView->GetParameter((char*)"JPC:DECOMPRESS:TILESIZE:Y", &nTileSizeY);
poDS->SetMetadataItem("TILE_HEIGHT", CPLString().Printf("%d", nTileSizeY), JPEG2000_DOMAIN_NAME);
// Precinct Sizes on X axis
char *csPreSizeX = nullptr;
poDS->poFileView->GetParameter((char*)"JPC:DECOMPRESS:PRECINCTSIZE:X", &csPreSizeX);
if (csPreSizeX) {
poDS->SetMetadataItem("PRECINCT_SIZE_X", csPreSizeX, JPEG2000_DOMAIN_NAME);
NCSFree(csPreSizeX);
}
// Precinct Sizes on Y axis
char *csPreSizeY = nullptr;
poDS->poFileView->GetParameter((char*)"JPC:DECOMPRESS:PRECINCTSIZE:Y", &csPreSizeY);
if (csPreSizeY) {
poDS->SetMetadataItem("PRECINCT_SIZE_Y", csPreSizeY, JPEG2000_DOMAIN_NAME);
NCSFree(csPreSizeY);
}
// Code Block Size on X axis
UINT32 nCodeBlockSizeX = 0;
poDS->poFileView->GetParameter((char*)"JPC:DECOMPRESS:CODEBLOCK:X", &nCodeBlockSizeX);
poDS->SetMetadataItem("CODE_BLOCK_SIZE_X", CPLString().Printf("%d", nCodeBlockSizeX), JPEG2000_DOMAIN_NAME);
// Code Block Size on Y axis
UINT32 nCodeBlockSizeY = 0;
poDS->poFileView->GetParameter((char*)"JPC:DECOMPRESS:CODEBLOCK:Y", &nCodeBlockSizeY);
poDS->SetMetadataItem("CODE_BLOCK_SIZE_Y", CPLString().Printf("%d", nCodeBlockSizeY), JPEG2000_DOMAIN_NAME);
// Bitdepth
char *csBitdepth = nullptr;
poDS->poFileView->GetParameter((char*)"JPC:DECOMPRESS:BITDEPTH", &csBitdepth);
if (csBitdepth) {
poDS->SetMetadataItem("PRECISION", csBitdepth, JPEG2000_DOMAIN_NAME);
NCSFree(csBitdepth);
}
// Resolution Levels
UINT32 nLevels = 0;
poDS->poFileView->GetParameter((char*)"JPC:DECOMPRESS:RESOLUTION:LEVELS", &nLevels);
poDS->SetMetadataItem("RESOLUTION_LEVELS", CPLString().Printf("%d", nLevels), JPEG2000_DOMAIN_NAME);
// Qualaity Layers
UINT32 nLayers = 0;
poDS->poFileView->GetParameter((char*)"JP2:DECOMPRESS:LAYERS", &nLayers);
poDS->SetMetadataItem("QUALITY_LAYERS", CPLString().Printf("%d", nLayers), JPEG2000_DOMAIN_NAME);
// Progression Order
char *csOrder = nullptr;
poDS->poFileView->GetParameter((char*)"JPC:DECOMPRESS:PROGRESSION:ORDER", &csOrder);
if (csOrder) {
poDS->SetMetadataItem("PROGRESSION_ORDER", csOrder, JPEG2000_DOMAIN_NAME);
NCSFree(csOrder);
}
// DWT Filter
const char *csFilter = nullptr;
UINT32 nFilter;
poDS->poFileView->GetParameter((char*)"JP2:TRANSFORMATION:TYPE", &nFilter);
if (nFilter)
csFilter = "5x3";
else
csFilter = "9x7";
poDS->SetMetadataItem("TRANSFORMATION_TYPE", csFilter, JPEG2000_DOMAIN_NAME);
// SOP used?
bool bSOP = 0;
poDS->poFileView->GetParameter((char*)"JP2:DECOMPRESS:SOP:EXISTS", &bSOP);
poDS->SetMetadataItem("USE_SOP", (bSOP) ? "TRUE" : "FALSE", JPEG2000_DOMAIN_NAME);
// EPH used?
bool bEPH = 0;
poDS->poFileView->GetParameter((char*)"JP2:DECOMPRESS:EPH:EXISTS", &bEPH);
poDS->SetMetadataItem("USE_EPH", (bEPH) ? "TRUE" : "FALSE", JPEG2000_DOMAIN_NAME);
// GML JP2 data contained?
bool bGML = 0;
poDS->poFileView->GetParameter((char*)"JP2:GML:JP2:BOX:EXISTS", &bGML);
poDS->SetMetadataItem("GML_JP2_DATA", (bGML) ? "TRUE" : "FALSE", JPEG2000_DOMAIN_NAME);
}
#endif //ECWSDK_VERSION>=51
if ( !bIsJPEG2000 && poDS->psFileInfo->nFormatVersion >=3 ){
poDS->SetMetadataItem("COMPRESSION_RATE_ACTUAL", CPLString().Printf("%f", poDS->psFileInfo->fActualCompressionRate));
poDS->SetMetadataItem("CLOCKWISE_ROTATION_DEG", CPLString().Printf("%f", poDS->psFileInfo->fCWRotationDegrees));
poDS->SetMetadataItem("COMPRESSION_DATE", poDS->psFileInfo->sCompressionDate);
//Get file metadata.
poDS->ReadFileMetaDataFromFile();
}
#else
poDS->SetMetadataItem("VERSION", CPLString().Printf("%d",bIsJPEG2000?1:2));
#endif
/* -------------------------------------------------------------------- */
/* Initialize any PAM information. */
/* -------------------------------------------------------------------- */
poDS->SetDescription( osFilename );
poDS->TryLoadXML();
/* -------------------------------------------------------------------- */
/* Vector layers */
/* -------------------------------------------------------------------- */
if( bIsJPEG2000 && poOpenInfo->nOpenFlags & GDAL_OF_VECTOR )
{
poDS->LoadVectorLayers(
CPLFetchBool(poOpenInfo->papszOpenOptions, "OPEN_REMOTE_GML",
false));
// If file opened in vector-only mode and there's no vector,
// return
if( (poOpenInfo->nOpenFlags & GDAL_OF_RASTER) == 0 &&
poDS->GetLayerCount() == 0 )
{
delete poDS;
return nullptr;
}
}
return poDS;
}
/************************************************************************/
/* GetMetadataDomainList() */
/************************************************************************/
char **ECWDataset::GetMetadataDomainList()
{
return BuildMetadataDomainList(GDALPamDataset::GetMetadataDomainList(),
TRUE,
"ECW", "GML", nullptr);
}
/************************************************************************/
/* GetMetadataItem() */
/************************************************************************/
const char *ECWDataset::GetMetadataItem( const char * pszName,
const char * pszDomain )
{
if (!bIsJPEG2000 && pszDomain != nullptr && EQUAL(pszDomain, "ECW") && pszName != nullptr)
{
if (EQUAL(pszName, "PROJ"))
return m_osProjCode.size() ? m_osProjCode.c_str() : "RAW";
if (EQUAL(pszName, "DATUM"))
return m_osDatumCode.size() ? m_osDatumCode.c_str() : "RAW";
if (EQUAL(pszName, "UNITS"))
return m_osUnitsCode.size() ? m_osUnitsCode.c_str() : "METERS";
}
return GDALPamDataset::GetMetadataItem(pszName, pszDomain);
}
/************************************************************************/
/* GetMetadata() */
/************************************************************************/
char **ECWDataset::GetMetadata( const char *pszDomain )
{
if( !bIsJPEG2000 && pszDomain != nullptr && EQUAL(pszDomain, "ECW") )
{
oECWMetadataList.Clear();
oECWMetadataList.AddString(CPLSPrintf("%s=%s", "PROJ", GetMetadataItem("PROJ", "ECW")));
oECWMetadataList.AddString(CPLSPrintf("%s=%s", "DATUM", GetMetadataItem("DATUM", "ECW")));
oECWMetadataList.AddString(CPLSPrintf("%s=%s", "UNITS", GetMetadataItem("UNITS", "ECW")));
return oECWMetadataList.List();
}
else if( pszDomain == nullptr || !EQUAL(pszDomain,"GML") )
return GDALPamDataset::GetMetadata( pszDomain );
else
return papszGMLMetadata;
}
/************************************************************************/
/* ReadFileMetaDataFromFile() */
/* */
/* Gets relevant information from NCSFileMetadata and populates */
/* GDAL metadata. */
/* */
/************************************************************************/
#if ECWSDK_VERSION >= 50
void ECWDataset::ReadFileMetaDataFromFile()
{
if (psFileInfo->pFileMetaData == nullptr) return;
if (psFileInfo->pFileMetaData->sClassification != nullptr )
GDALDataset::SetMetadataItem("FILE_METADATA_CLASSIFICATION", NCS::CString(psFileInfo->pFileMetaData->sClassification));
if (psFileInfo->pFileMetaData->sAcquisitionDate != nullptr )
GDALDataset::SetMetadataItem("FILE_METADATA_ACQUISITION_DATE", NCS::CString(psFileInfo->pFileMetaData->sAcquisitionDate));
if (psFileInfo->pFileMetaData->sAcquisitionSensorName != nullptr )
GDALDataset::SetMetadataItem("FILE_METADATA_ACQUISITION_SENSOR_NAME", NCS::CString(psFileInfo->pFileMetaData->sAcquisitionSensorName));
if (psFileInfo->pFileMetaData->sCompressionSoftware != nullptr )
GDALDataset::SetMetadataItem("FILE_METADATA_COMPRESSION_SOFTWARE", NCS::CString(psFileInfo->pFileMetaData->sCompressionSoftware));
if (psFileInfo->pFileMetaData->sAuthor != nullptr )
GDALDataset::SetMetadataItem("FILE_METADATA_AUTHOR", NCS::CString(psFileInfo->pFileMetaData->sAuthor));
if (psFileInfo->pFileMetaData->sCopyright != nullptr )
GDALDataset::SetMetadataItem("FILE_METADATA_COPYRIGHT", NCS::CString(psFileInfo->pFileMetaData->sCopyright));
if (psFileInfo->pFileMetaData->sCompany != nullptr )
GDALDataset::SetMetadataItem("FILE_METADATA_COMPANY", NCS::CString(psFileInfo->pFileMetaData->sCompany));
if (psFileInfo->pFileMetaData->sEmail != nullptr )
GDALDataset::SetMetadataItem("FILE_METADATA_EMAIL", NCS::CString(psFileInfo->pFileMetaData->sEmail));
if (psFileInfo->pFileMetaData->sAddress != nullptr )
GDALDataset::SetMetadataItem("FILE_METADATA_ADDRESS", NCS::CString(psFileInfo->pFileMetaData->sAddress));
if (psFileInfo->pFileMetaData->sTelephone != nullptr )
GDALDataset::SetMetadataItem("FILE_METADATA_TELEPHONE", NCS::CString(psFileInfo->pFileMetaData->sTelephone));
}
/************************************************************************/
/* WriteFileMetaData() */
/************************************************************************/
void ECWDataset::WriteFileMetaData(NCSFileMetaData* pFileMetaDataCopy)
{
if (!bFileMetaDataDirty )
return;
CPLAssert(eAccess == GA_Update);
CPLAssert(!bIsJPEG2000);
bFileMetaDataDirty = FALSE;
NCSFileView *psFileView = nullptr;
NCSError eErr;
psFileView = NCSEditOpen( GetDescription() );
if (psFileView == nullptr)
{
CPLError(CE_Failure, CPLE_AppDefined,
"NCSEditOpen() failed");
return;
}
eErr = NCSEditSetFileMetaData(psFileView, pFileMetaDataCopy);
if( eErr != NCS_SUCCESS )
{
CPLError(CE_Failure, CPLE_AppDefined,
"NCSEditSetFileMetaData() failed : %s",
NCSGetLastErrorText(eErr));
}
NCSEditFlushAll(psFileView);
NCSEditClose(psFileView);
}
#endif
/************************************************************************/
/* ECW2WKTProjection() */
/* */
/* Set the dataset pszProjection string in OGC WKT format by */
/* looking up the ECW (GDT) coordinate system info in */
/* ecw_cs.wkt support data file. */
/* */
/* This code is likely still broken in some circumstances. For */
/* instance, I haven't been careful about changing the linear */
/* projection parameters (false easting/northing) if the units */
/* is feet. Lots of cases missing here, and in ecw_cs.wkt. */
/************************************************************************/
void ECWDataset::ECW2WKTProjection()
{
if( psFileInfo == nullptr )
return;
/* -------------------------------------------------------------------- */
/* Capture Geotransform. */
/* */
/* We will try to ignore the provided file information if it is */
/* origin (0,0) and pixel size (1,1). I think sometimes I have */
/* also seen pixel increments of 0 on invalid datasets. */
/* -------------------------------------------------------------------- */
if( psFileInfo->fOriginX != 0.0
|| psFileInfo->fOriginY != 0.0
|| (psFileInfo->fCellIncrementX != 0.0
&& psFileInfo->fCellIncrementX != 1.0)
|| (psFileInfo->fCellIncrementY != 0.0
&& psFileInfo->fCellIncrementY != 1.0) )
{
bGeoTransformValid = TRUE;
adfGeoTransform[0] = psFileInfo->fOriginX;
adfGeoTransform[1] = psFileInfo->fCellIncrementX;
adfGeoTransform[2] = 0.0;
adfGeoTransform[3] = psFileInfo->fOriginY;
adfGeoTransform[4] = 0.0;
/* By default, set Y-resolution negative assuming images always */
/* have "Upward" orientation (Y coordinates increase "Upward"). */
/* Setting ECW_ALWAYS_UPWARD=FALSE option relexes that policy */
/* and makes the driver rely on the actual Y-resolution */
/* value (sign) of an image. This allows to correctly process */
/* rare images with "Downward" orientation, where Y coordinates */
/* increase "Downward" and Y-resolution is positive. */
if( CPLTestBool( CPLGetConfigOption("ECW_ALWAYS_UPWARD","TRUE") ) )
adfGeoTransform[5] = -fabs(psFileInfo->fCellIncrementY);
else
adfGeoTransform[5] = psFileInfo->fCellIncrementY;
}
/* -------------------------------------------------------------------- */
/* do we have projection and datum? */
/* -------------------------------------------------------------------- */
CPLString osUnits = ECWTranslateFromCellSizeUnits(psFileInfo->eCellSizeUnits);
CPLDebug( "ECW", "projection=%s, datum=%s, units=%s",
psFileInfo->szProjection, psFileInfo->szDatum,
osUnits.c_str());
if( EQUAL(psFileInfo->szProjection,"RAW") )
return;
/* -------------------------------------------------------------------- */
/* Set projection if we have it. */
/* -------------------------------------------------------------------- */
OGRSpatialReference oSRS;
/* For backward-compatible with previous behaviour. Should we only */
/* restrict to those 2 values ? */
if (psFileInfo->eCellSizeUnits != ECW_CELL_UNITS_METERS &&
psFileInfo->eCellSizeUnits != ECW_CELL_UNITS_FEET)
osUnits = ECWTranslateFromCellSizeUnits(ECW_CELL_UNITS_METERS);
m_osDatumCode = psFileInfo->szDatum;
m_osProjCode = psFileInfo->szProjection;
m_osUnitsCode = osUnits;
if( oSRS.importFromERM( psFileInfo->szProjection,
psFileInfo->szDatum,
osUnits ) == OGRERR_NONE )
{
oSRS.exportToWkt( &pszProjection );
}
CPLErrorReset(); /* see #4187 */
}
/************************************************************************/
/* ECWTranslateFromWKT() */
/************************************************************************/
int ECWTranslateFromWKT( const char *pszWKT,
char *pszProjection,
int nProjectionLen,
char *pszDatum,
int nDatumLen,
char *pszUnits)
{
OGRSpatialReference oSRS;
strcpy( pszProjection, "RAW" );
strcpy( pszDatum, "RAW" );
strcpy( pszUnits, "METERS" );
if( pszWKT == nullptr || strlen(pszWKT) == 0 )
return FALSE;
oSRS.importFromWkt( pszWKT );
if( oSRS.IsLocal() )
return TRUE;
/* -------------------------------------------------------------------- */
/* Do we have an overall EPSG number for this coordinate system? */
/* -------------------------------------------------------------------- */
const char *pszAuthorityCode = nullptr;
const char *pszAuthorityName = nullptr;
UINT32 nEPSGCode = 0;
if( oSRS.IsProjected() )
{
pszAuthorityCode = oSRS.GetAuthorityCode( "PROJCS" );
pszAuthorityName = oSRS.GetAuthorityName( "PROJCS" );
}
else if( oSRS.IsGeographic() )
{
pszAuthorityCode = oSRS.GetAuthorityCode( "GEOGCS" );
pszAuthorityName = oSRS.GetAuthorityName( "GEOGCS" );
}
if( pszAuthorityName != nullptr && EQUAL(pszAuthorityName,"EPSG")
&& pszAuthorityCode != nullptr && atoi(pszAuthorityCode) > 0 )
nEPSGCode = (UINT32) atoi(pszAuthorityCode);
if( nEPSGCode != 0 )
{
char *pszEPSGProj = nullptr, *pszEPSGDatum = nullptr;
CNCSError oErr =
CNCSJP2FileView::GetProjectionAndDatum( atoi(pszAuthorityCode),
&pszEPSGProj, &pszEPSGDatum );
CPLDebug( "ECW", "GetGDTProjDat(%d) = %s/%s",
atoi(pszAuthorityCode),
pszEPSGProj ? pszEPSGProj : "(null)",
pszEPSGDatum ? pszEPSGDatum : "(null)");
if( oErr.GetErrorNumber() == NCS_SUCCESS
&& pszEPSGProj != nullptr && pszEPSGDatum != nullptr )
{
strncpy( pszProjection, pszEPSGProj, nProjectionLen );
strncpy( pszDatum, pszEPSGDatum, nDatumLen );
pszProjection[nProjectionLen - 1] = 0;
pszDatum[nDatumLen - 1] = 0;
NCSFree( pszEPSGProj );
NCSFree( pszEPSGDatum );
return TRUE;
}
NCSFree( pszEPSGProj );
NCSFree( pszEPSGDatum );
}
/* -------------------------------------------------------------------- */
/* Fallback to translating based on the ecw_cs.wkt file, and */
/* various jiffy rules. */
/* -------------------------------------------------------------------- */
return oSRS.exportToERM( pszProjection, pszDatum, pszUnits ) == OGRERR_NONE;
}
/************************************************************************/
/* ECWTranslateToCellSizeUnits() */
/************************************************************************/
CellSizeUnits ECWTranslateToCellSizeUnits(const char* pszUnits)
{
if (EQUAL(pszUnits, "METERS"))
return ECW_CELL_UNITS_METERS;
else if (EQUAL(pszUnits, "DEGREES"))
return ECW_CELL_UNITS_DEGREES;
else if (EQUAL(pszUnits, "FEET"))
return ECW_CELL_UNITS_FEET;
else if (EQUAL(pszUnits, "UNKNOWN"))
return ECW_CELL_UNITS_UNKNOWN;
else if (EQUAL(pszUnits, "INVALID"))
return ECW_CELL_UNITS_INVALID;
else
{
CPLError(CE_Warning, CPLE_AppDefined, "Unrecognized value for UNITS : %s", pszUnits);
return ECW_CELL_UNITS_INVALID;
}
}
/************************************************************************/
/* ECWGetColorInterpretationByName() */
/************************************************************************/
GDALColorInterp ECWGetColorInterpretationByName(const char *pszName)
{
if (EQUAL(pszName, NCS_BANDDESC_AllOpacity))
return GCI_AlphaBand;
else if (EQUAL(pszName, NCS_BANDDESC_Blue))
return GCI_BlueBand;
else if (EQUAL(pszName, NCS_BANDDESC_Green))
return GCI_GreenBand;
else if (EQUAL(pszName, NCS_BANDDESC_Red))
return GCI_RedBand;
else if (EQUAL(pszName, NCS_BANDDESC_Greyscale))
return GCI_GrayIndex;
else if (EQUAL(pszName, NCS_BANDDESC_GreyscaleOpacity))
return GCI_AlphaBand;
return GCI_Undefined;
}
/************************************************************************/
/* ECWGetColorInterpretationName() */
/************************************************************************/
const char* ECWGetColorInterpretationName(GDALColorInterp eColorInterpretation, int nBandNumber)
{
const char *pszResult = nullptr;
switch (eColorInterpretation){
case GCI_AlphaBand:
pszResult = NCS_BANDDESC_AllOpacity;
break;
case GCI_GrayIndex:
pszResult = NCS_BANDDESC_Greyscale;
break;
case GCI_RedBand:
case GCI_GreenBand:
case GCI_BlueBand:
pszResult = GDALGetColorInterpretationName(eColorInterpretation);
break;
case GCI_Undefined:
if (nBandNumber == 0 ) {
pszResult = "Red";
}else if (nBandNumber == 1) {
pszResult = "Green";
}else if (nBandNumber == 2) {
pszResult = "Blue";
}
else
{
pszResult = CPLSPrintf(NCS_BANDDESC_Band,nBandNumber + 1);
}
break;
default:
pszResult = CPLSPrintf(NCS_BANDDESC_Band,nBandNumber + 1);
break;
}
return pszResult;
}
/************************************************************************/
/* ECWGetColorSpaceName() */
/************************************************************************/
const char* ECWGetColorSpaceName(NCSFileColorSpace colorSpace)
{
switch (colorSpace)
{
case NCSCS_NONE:
return "NONE"; break;
case NCSCS_GREYSCALE:
return "GREYSCALE"; break;
case NCSCS_YUV:
return "YUV"; break;
case NCSCS_MULTIBAND:
return "MULTIBAND"; break;
case NCSCS_sRGB:
return "RGB"; break;
case NCSCS_YCbCr:
return "YCbCr"; break;
default:
return "unrecognized";
}
}
/************************************************************************/
/* ECWTranslateFromCellSizeUnits() */
/************************************************************************/
const char* ECWTranslateFromCellSizeUnits(CellSizeUnits eUnits)
{
if (eUnits == ECW_CELL_UNITS_METERS)
return "METERS";
else if (eUnits == ECW_CELL_UNITS_DEGREES)
return "DEGREES";
else if (eUnits == ECW_CELL_UNITS_FEET)
return "FEET";
else if (eUnits == ECW_CELL_UNITS_UNKNOWN)
return "UNKNOWN";
else
return "INVALID";
}
#endif /* def FRMT_ecw */
/************************************************************************/
/* ECWInitialize() */
/* */
/* Initialize NCS library. We try to defer this as late as */
/* possible since de-initializing it seems to be expensive/slow */
/* on some system. */
/************************************************************************/
void ECWInitialize()
{
CPLMutexHolder oHolder( &hECWDatasetMutex );
if( bNCSInitialized )
return;
#ifndef WIN32
NCSecwInit();
#endif
bNCSInitialized = TRUE;
/* -------------------------------------------------------------------- */
/* This will disable automatic conversion of YCbCr to RGB by */
/* the toolkit. */
/* -------------------------------------------------------------------- */
if( !CPLTestBool( CPLGetConfigOption("CONVERT_YCBCR_TO_RGB","YES") ) )
NCSecwSetConfig(NCSCFG_JP2_MANAGE_ICC, FALSE);
#if ECWSDK_VERSION>= 50
NCSecwSetConfig(NCSCFG_ECWP_CLIENT_HTTP_USER_AGENT,
"ECW GDAL Driver/" NCS_ECWJP2_FULL_VERSION_STRING_DOT_DEL);
#endif
/* -------------------------------------------------------------------- */
/* Initialize cache memory limit. Default is apparently 1/4 RAM. */
/* -------------------------------------------------------------------- */
const char *pszEcwCacheSize =
CPLGetConfigOption("GDAL_ECW_CACHE_MAXMEM",nullptr);
if( pszEcwCacheSize == nullptr )
pszEcwCacheSize = CPLGetConfigOption("ECW_CACHE_MAXMEM",nullptr);
if( pszEcwCacheSize != nullptr )
NCSecwSetConfig(NCSCFG_CACHE_MAXMEM, (UINT32) atoi(pszEcwCacheSize) );
/* -------------------------------------------------------------------- */
/* Version 3.x and 4.x of the ECWJP2 SDK did not resolve datum and */
/* projection to EPSG code using internal mapping. */
/* Version 5.x do so we provide means to achieve old */
/* behaviour. */
/* -------------------------------------------------------------------- */
#if ECWSDK_VERSION >= 50
if( CPLTestBool( CPLGetConfigOption("ECW_DO_NOT_RESOLVE_DATUM_PROJECTION","NO") ) == TRUE)
NCSecwSetConfig(NCSCFG_PROJECTION_FORMAT, NCS_PROJECTION_ERMAPPER_FORMAT);
#endif
/* -------------------------------------------------------------------- */
/* Allow configuration of a local cache based on configuration */
/* options. Setting the location turns things on. */
/* -------------------------------------------------------------------- */
const char *pszOpt = nullptr;
CPL_IGNORE_RET_VAL(pszOpt);
#if ECWSDK_VERSION >= 40
pszOpt = CPLGetConfigOption( "ECWP_CACHE_SIZE_MB", nullptr );
if( pszOpt )
NCSecwSetConfig( NCSCFG_ECWP_CACHE_SIZE_MB, (INT32) atoi( pszOpt ) );
pszOpt = CPLGetConfigOption( "ECWP_CACHE_LOCATION", nullptr );
if( pszOpt )
{
NCSecwSetConfig( NCSCFG_ECWP_CACHE_LOCATION, pszOpt );
NCSecwSetConfig( NCSCFG_ECWP_CACHE_ENABLED, (BOOLEAN) TRUE );
}
#endif
/* -------------------------------------------------------------------- */
/* Various other configuration items. */
/* -------------------------------------------------------------------- */
pszOpt = CPLGetConfigOption( "ECWP_BLOCKING_TIME_MS", nullptr );
if( pszOpt )
NCSecwSetConfig( NCSCFG_BLOCKING_TIME_MS,
(NCSTimeStampMs) atoi(pszOpt) );
// I believe 10s means we wait for complete data back from
// ECWP almost all the time which is good for our blocking model.
pszOpt = CPLGetConfigOption( "ECWP_REFRESH_TIME_MS", "10000" );
if( pszOpt )
NCSecwSetConfig( NCSCFG_REFRESH_TIME_MS,
(NCSTimeStampMs) atoi(pszOpt) );
pszOpt = CPLGetConfigOption( "ECW_TEXTURE_DITHER", nullptr );
if( pszOpt )
NCSecwSetConfig( NCSCFG_TEXTURE_DITHER,
(BOOLEAN) CPLTestBool( pszOpt ) );
pszOpt = CPLGetConfigOption( "ECW_FORCE_FILE_REOPEN", nullptr );
if( pszOpt )
NCSecwSetConfig( NCSCFG_FORCE_FILE_REOPEN,
(BOOLEAN) CPLTestBool( pszOpt ) );
pszOpt = CPLGetConfigOption( "ECW_CACHE_MAXOPEN", nullptr );
if( pszOpt )
NCSecwSetConfig( NCSCFG_CACHE_MAXOPEN, (UINT32) atoi(pszOpt) );
#if ECWSDK_VERSION >= 40
pszOpt = CPLGetConfigOption( "ECW_AUTOGEN_J2I", nullptr );
if( pszOpt )
NCSecwSetConfig( NCSCFG_JP2_AUTOGEN_J2I,
(BOOLEAN) CPLTestBool( pszOpt ) );
pszOpt = CPLGetConfigOption( "ECW_OPTIMIZE_USE_NEAREST_NEIGHBOUR", nullptr );
if( pszOpt )
NCSecwSetConfig( NCSCFG_OPTIMIZE_USE_NEAREST_NEIGHBOUR,
(BOOLEAN) CPLTestBool( pszOpt ) );
pszOpt = CPLGetConfigOption( "ECW_RESILIENT_DECODING", nullptr );
if( pszOpt )
NCSecwSetConfig( NCSCFG_RESILIENT_DECODING,
(BOOLEAN) CPLTestBool( pszOpt ) );
#endif
}
/************************************************************************/
/* GDALDeregister_ECW() */
/************************************************************************/
static void GDALDeregister_ECW( GDALDriver * )
{
/* For unknown reason, this cleanup can take up to 3 seconds (see #3134) for SDK 3.3. */
/* Not worth it */
#if ECWSDK_VERSION >= 50
#ifndef WIN32
if( bNCSInitialized )
{
bNCSInitialized = FALSE;
if( !GDALIsInGlobalDestructor() )
{
NCSecwShutdown();
}
}
#endif
#endif
if( hECWDatasetMutex != nullptr )
{
CPLDestroyMutex( hECWDatasetMutex );
hECWDatasetMutex = nullptr;
}
}
/************************************************************************/
/* GDALRegister_ECW() */
/************************************************************************/
/* Needed for v4.3 and v5.0 */
#if !defined(NCS_ECWSDK_VERSION_STRING) && defined(NCS_ECWJP2_VERSION_STRING)
#define NCS_ECWSDK_VERSION_STRING NCS_ECWJP2_VERSION_STRING
#endif
void GDALRegister_ECW()
{
#ifdef FRMT_ecw
if( !GDAL_CHECK_VERSION( "ECW driver" ) )
return;
if( GDALGetDriverByName( "ECW" ) != nullptr )
return;
GDALDriver *poDriver = new GDALDriver();
poDriver->SetDescription( "ECW" );
poDriver->SetMetadataItem( GDAL_DCAP_RASTER, "YES" );
CPLString osLongName = "ERDAS Compressed Wavelets (SDK ";
#ifdef NCS_ECWSDK_VERSION_STRING
osLongName += NCS_ECWSDK_VERSION_STRING;
#else
osLongName += "3.x";
#endif
osLongName += ")";
poDriver->SetMetadataItem( GDAL_DMD_LONGNAME, osLongName );
poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, "drivers/raster/ecw.html" );
poDriver->SetMetadataItem( GDAL_DMD_EXTENSION, "ecw" );
poDriver->pfnIdentify = ECWDataset::IdentifyECW;
poDriver->pfnOpen = ECWDataset::OpenECW;
poDriver->pfnUnloadDriver = GDALDeregister_ECW;
#ifdef HAVE_COMPRESS
// The create method does not work with SDK 3.3 ( crash in
// CNCSJP2FileView::WriteLineBIL() due to m_pFile being nullptr ).
#if ECWSDK_VERSION >= 50
poDriver->pfnCreate = ECWCreateECW;
#endif
poDriver->pfnCreateCopy = ECWCreateCopyECW;
#if ECWSDK_VERSION >= 50
poDriver->SetMetadataItem( GDAL_DMD_CREATIONDATATYPES, "Byte UInt16" );
#else
poDriver->SetMetadataItem( GDAL_DMD_CREATIONDATATYPES, "Byte" );
#endif
poDriver->SetMetadataItem( GDAL_DMD_CREATIONOPTIONLIST,
"<CreationOptionList>"
" <Option name='TARGET' type='float' description='Compression Percentage' />"
" <Option name='PROJ' type='string' description='ECW Projection Name'/>"
" <Option name='DATUM' type='string' description='ECW Datum Name' />"
#if ECWSDK_VERSION < 40
" <Option name='LARGE_OK' type='boolean' description='Enable compressing 500+MB files'/>"
#else
" <Option name='ECW_ENCODE_KEY' type='string' description='OEM Compress Key from ERDAS.'/>"
" <Option name='ECW_ENCODE_COMPANY' type='string' description='OEM Company Name.'/>"
#endif
#if ECWSDK_VERSION >= 50
" <Option name='ECW_FORMAT_VERSION' type='integer' description='ECW format version (2 or 3).' default='2'/>"
#endif
"</CreationOptionList>" );
#else
// In read-only mode, we support VirtualIO. This is not the case
// for ECWCreateCopyECW().
poDriver->SetMetadataItem( GDAL_DCAP_VIRTUALIO, "YES" );
#endif
GetGDALDriverManager()->RegisterDriver( poDriver );
#endif /* def FRMT_ecw */
}
/************************************************************************/
/* GDALRegister_ECW_JP2ECW() */
/* */
/* This function exists so that when built as a plugin, there */
/* is a function that will register both drivers. */
/************************************************************************/
void GDALRegister_ECW_JP2ECW()
{
GDALRegister_ECW();
GDALRegister_JP2ECW();
}
/************************************************************************/
/* ECWDatasetOpenJPEG2000() */
/************************************************************************/
GDALDataset* ECWDatasetOpenJPEG2000(GDALOpenInfo* poOpenInfo)
{
return ECWDataset::OpenJPEG2000(poOpenInfo);
}
/************************************************************************/
/* GDALRegister_JP2ECW() */
/************************************************************************/
void GDALRegister_JP2ECW()
{
#ifdef FRMT_ecw
if( !GDAL_CHECK_VERSION( "JP2ECW driver" ) )
return;
if( GDALGetDriverByName( "JP2ECW" ) != nullptr )
return;
GDALDriver *poDriver = new GDALDriver();
poDriver->SetDescription( "JP2ECW" );
poDriver->SetMetadataItem( GDAL_DCAP_RASTER, "YES" );
poDriver->SetMetadataItem( GDAL_DCAP_VECTOR, "YES" );
CPLString osLongName = "ERDAS JPEG2000 (SDK ";
#ifdef NCS_ECWSDK_VERSION_STRING
osLongName += NCS_ECWSDK_VERSION_STRING;
#else
osLongName += "3.x";
#endif
osLongName += ")";
poDriver->SetMetadataItem( GDAL_DMD_LONGNAME, osLongName );
poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, "drivers/raster/jp2ecw.html" );
poDriver->SetMetadataItem( GDAL_DMD_EXTENSION, "jp2" );
poDriver->SetMetadataItem( GDAL_DCAP_VIRTUALIO, "YES" );
poDriver->pfnIdentify = ECWDataset::IdentifyJPEG2000;
poDriver->pfnOpen = ECWDataset::OpenJPEG2000;
poDriver->SetMetadataItem( GDAL_DMD_OPENOPTIONLIST,
"<OpenOptionList>"
" <Option name='1BIT_ALPHA_PROMOTION' type='boolean' description='Whether a 1-bit alpha channel should be promoted to 8-bit' default='YES'/>"
" <Option name='OPEN_REMOTE_GML' type='boolean' description='Whether to load remote vector layers referenced by a link in a GMLJP2 v2 box' default='NO'/>"
" <Option name='GEOREF_SOURCES' type='string' description='Comma separated list made with values INTERNAL/GMLJP2/GEOJP2/WORLDFILE/PAM/NONE that describe the priority order for georeferencing' default='PAM,GEOJP2,GMLJP2,WORLDFILE'/>"
"</OpenOptionList>" );
#ifdef HAVE_COMPRESS
poDriver->pfnCreate = ECWCreateJPEG2000;
poDriver->pfnCreateCopy = ECWCreateCopyJPEG2000;
poDriver->SetMetadataItem( GDAL_DMD_CREATIONDATATYPES,
"Byte UInt16 Int16 UInt32 Int32 "
"Float32 "
#if ECWSDK_VERSION >= 40
// Crashes for sure with 3.3. Didn't try other versions
"Float64"
#endif
);
poDriver->SetMetadataItem( GDAL_DMD_CREATIONOPTIONLIST,
"<CreationOptionList>"
" <Option name='TARGET' type='float' description='Compression Percentage' />"
" <Option name='PROJ' type='string' description='ECW Projection Name'/>"
" <Option name='DATUM' type='string' description='ECW Datum Name' />"
" <Option name='UNITS' type='string-select' description='ECW Projection Units'>"
" <Value>METERS</Value>"
" <Value>FEET</Value>"
" </Option>"
#if ECWSDK_VERSION < 40
" <Option name='LARGE_OK' type='boolean' description='Enable compressing 500+MB files'/>"
#else
" <Option name='ECW_ENCODE_KEY' type='string' description='OEM Compress Key from ERDAS.'/>"
" <Option name='ECW_ENCODE_COMPANY' type='string' description='OEM Company Name.'/>"
#endif
" <Option name='GeoJP2' type='boolean' description='defaults to ON'/>"
" <Option name='GMLJP2' type='boolean' description='defaults to ON'/>"
" <Option name='GMLJP2V2_DEF' type='string' description='Definition file to describe how a GMLJP2 v2 box should be generated. If set to YES, a minimal instance will be created'/>"
" <Option name='PROFILE' type='string-select'>"
" <Value>BASELINE_0</Value>"
" <Value>BASELINE_1</Value>"
" <Value>BASELINE_2</Value>"
" <Value>NPJE</Value>"
" <Value>EPJE</Value>"
" </Option>"
" <Option name='PROGRESSION' type='string-select'>"
" <Value>LRCP</Value>"
" <Value>RLCP</Value>"
" <Value>RPCL</Value>"
" </Option>"
" <Option name='CODESTREAM_ONLY' type='boolean' description='No JP2 wrapper'/>"
" <Option name='NBITS' type='int' description='Bits (precision) for sub-byte files (1-7), sub-uint16 (9-15)'/>"
" <Option name='LEVELS' type='int'/>"
" <Option name='LAYERS' type='int'/>"
" <Option name='PRECINCT_WIDTH' type='int'/>"
" <Option name='PRECINCT_HEIGHT' type='int'/>"
" <Option name='TILE_WIDTH' type='int'/>"
" <Option name='TILE_HEIGHT' type='int'/>"
" <Option name='INCLUDE_SOP' type='boolean'/>"
" <Option name='INCLUDE_EPH' type='boolean'/>"
" <Option name='DECOMPRESS_LAYERS' type='int'/>"
" <Option name='DECOMPRESS_RECONSTRUCTION_PARAMETER' type='float'/>"
" <Option name='WRITE_METADATA' type='boolean' description='Whether metadata should be written, in a dedicated JP2 XML box' default='NO'/>"
" <Option name='MAIN_MD_DOMAIN_ONLY' type='boolean' description='(Only if WRITE_METADATA=YES) Whether only metadata from the main domain should be written' default='NO'/>"
"</CreationOptionList>" );
#endif
GetGDALDriverManager()->RegisterDriver( poDriver );
#endif /* def FRMT_ecw */
}
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDateTime>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
label = new QLabel(this);
label->setGeometry(QRect(50, 50, 200, 25));
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateTime()));
timer->start(1000);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::updateTime()
{
QDateTime sysTime = QDateTime::currentDateTime();
label->setText(sysTime.toString());
}
|
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif
#include "util.h"
#include "uritests.h"
#include "compattests.h"
#ifdef ENABLE_WALLET
#include "paymentservertests.h"
#endif
#include <QCoreApplication>
#include <QObject>
#include <QTest>
#include <openssl/ssl.h>
#if defined(QT_STATICPLUGIN) && QT_VERSION < 0x050000
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
#endif
// This is all you need to run all the tests
int main(int argc, char *argv[])
{
SetupEnvironment();
bool fInvalid = false;
// Don't remove this, it's needed to access
// QCoreApplication:: in the tests
QCoreApplication app(argc, argv);
app.setApplicationName("FakeCoin-Qt-test");
SSL_library_init();
URITests test1;
if (QTest::qExec(&test1) != 0)
fInvalid = true;
#ifdef ENABLE_WALLET
PaymentServerTests test2;
if (QTest::qExec(&test2) != 0)
fInvalid = true;
#endif
CompatTests test4;
if (QTest::qExec(&test4) != 0)
fInvalid = true;
return fInvalid;
}
|
/*
* Copyright (c) 2020-2021 Samsung Electronics Co., Ltd. All rights reserved.
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "tvgLoaderMgr.h"
#include "tvgPngLoader.h"
PngLoader::PngLoader()
{
image = static_cast<png_imagep>(calloc(1, sizeof(png_image)));
image->version = PNG_IMAGE_VERSION;
image->opaque = NULL;
}
PngLoader::~PngLoader()
{
if (content) {
free((void*)content);
content = nullptr;
}
free(image);
}
bool PngLoader::open(const string& path)
{
image->opaque = NULL;
if (!png_image_begin_read_from_file(image, path.c_str())) return false;
vw = w = image->width;
vh = h = image->height;
return true;
}
bool PngLoader::read()
{
png_bytep buffer;
image->format = PNG_FORMAT_BGRA;
buffer = static_cast<png_bytep>(malloc(PNG_IMAGE_SIZE((*image))));
if (!buffer) {
// out of memory, only time when libpng doesnt free its data
png_image_free(image);
return false;
}
if (!png_image_finish_read(image, NULL, buffer, 0, NULL)) return false;
content = reinterpret_cast<uint32_t*>(buffer);
return true;
}
bool PngLoader::close()
{
png_image_free(image);
return true;
}
const uint32_t* PngLoader::pixels()
{
return this->content;
}
|
#include <phi/core/NonCopyable.hpp>
class A : phi::NonCopyable
{};
int main()
{
A a;
A b(a);
}
|
/*
Part of the TBMod ( https://github.com/TacticalBaconDevs/TBMod )
Developed by http://tacticalbacon.de
*/
class Extended_InitPost_EventHandlers
{
#define STAIYIN(CLASSE) class CLASSE { \
init = "(_this # 0) allowCrewInImmobile true";\
}
STAIYIN(Wheeled_APC_F);
STAIYIN(Tank);
};
|
/**
* Copyright (C) 2015 Dato, Inc.
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
#include <cross_platform/windows_wrapper.hpp>
#include <tlhelp32.h>
#include <process/process_util.hpp>
namespace graphlab {
//TODO: This has a race condition that I'm ignoring as I don't think it will
//happen much, if at all. The parent could crash before the child gets a
//chance to run this, and the PID reassigned to an unrelated process. Since
//stakes are not high (the child processes just won't get reaped for awhile
//but won't be doing much of anything), I'm ignoring it.
size_t get_parent_pid() {
HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pe;
ZeroMemory(&pe, sizeof(PROCESSENTRY32));
pe.dwSize = sizeof(PROCESSENTRY32);
auto my_pid = get_my_pid();
size_t parent_pid = size_t(-1);
// Iterate through all processes to find myself
if(Process32First(h, &pe)) {
do {
if(pe.th32ProcessID == my_pid) {
parent_pid = pe.th32ParentProcessID;
}
} while(Process32Next(h, &pe));
}
CloseHandle(h);
return parent_pid;
}
size_t get_my_pid() {
return (size_t)GetCurrentProcessId();
}
void wait_for_parent_exit(size_t parent_pid) {
HANDLE parent_handle = OpenProcess(SYNCHRONIZE, FALSE, (DWORD)parent_pid);
DWORD wait_ret = WAIT_TIMEOUT;
while(wait_ret == WAIT_TIMEOUT) {
// Wait 5 seconds for the parent to be signaled
wait_ret = WaitForSingleObject(parent_handle, 5000);
}
}
bool is_process_running(size_t pid) {
// Strategy taken from
// http://stackoverflow.com/questions/1591342/c-how-to-determine-if-a-windows-process-is-running
HANDLE proc = OpenProcess(SYNCHRONIZE, FALSE, (DWORD)pid);
if(proc != NULL) {
DWORD ret = WaitForSingleObject(proc, 0);
if(proc != NULL)
CloseHandle(proc);
return (ret == WAIT_TIMEOUT);
}
return false;
}
} // namespace graphlab
|
#if !defined(MANDELWIN_HPP_)
#define MANDELWIN_HPP
#include "utils.hpp"
#include <gtkmm/applicationwindow.h>
#include <string>
class MandelWin : public Gtk::ApplicationWindow {
public:
MandelWin(CLIOptions clopts);
virtual ~MandelWin();
protected:
// Signal handler
void on_button_quit_clicked();
CLIOptions clopts_;
std::string _get_sample_value();
};
#endif
|
#include "common.h"
#include "Draw.h"
#include "Frontend.h"
#include "Camera.h"
#include "CutsceneMgr.h"
#ifdef ASPECT_RATIO_SCALE
float CDraw::ms_fAspectRatio = DEFAULT_ASPECT_RATIO;
float CDraw::ms_fScaledFOV = 45.0f;
#endif
float CDraw::ms_fNearClipZ;
float CDraw::ms_fFarClipZ;
float CDraw::ms_fFOV = 45.0f;
float CDraw::ms_fLODDistance;
uint8 CDraw::FadeValue;
uint8 CDraw::FadeRed;
uint8 CDraw::FadeGreen;
uint8 CDraw::FadeBlue;
#ifdef PROPER_SCALING
bool CDraw::ms_bProperScaling = true;
#endif
#ifdef FIX_RADAR
bool CDraw::ms_bFixRadar = true;
#endif
#ifdef FIX_SPRITES
bool CDraw::ms_bFixSprites = true;
#endif
float
CDraw::FindAspectRatio(void)
{
#ifndef ASPECT_RATIO_SCALE
if(FrontEndMenuManager.m_PrefsUseWideScreen)
return 16.0f/9.0f;
else
return 4.0f/3.0f;
#else
switch (FrontEndMenuManager.m_PrefsUseWideScreen) {
case AR_AUTO:
return SCREEN_WIDTH / SCREEN_HEIGHT;
default:
case AR_4_3:
return 4.0f / 3.0f;
case AR_5_4:
return 5.0f / 4.0f;
case AR_16_10:
return 16.0f / 10.0f;
case AR_16_9:
return 16.0f / 9.0f;
case AR_21_9:
return 21.0f / 9.0f;
};
#endif
}
#ifdef ASPECT_RATIO_SCALE
// convert a 4:3 hFOV to vFOV,
// then convert that vFOV to hFOV for our aspect ratio,
// i.e. HOR+
float
CDraw::ConvertFOV(float hfov)
{
// => tan(hFOV/2) = tan(vFOV/2)*aspectRatio
// => tan(vFOV/2) = tan(hFOV/2)/aspectRatio
float ar1 = DEFAULT_ASPECT_RATIO;
float ar2 = GetAspectRatio();
hfov = DEGTORAD(hfov);
float vfov = Atan(tan(hfov/2) / ar1) *2;
hfov = Atan(tan(vfov/2) * ar2) *2;
return RADTODEG(hfov);
}
#endif
void
CDraw::SetFOV(float fov)
{
#ifdef ASPECT_RATIO_SCALE
if (!CCutsceneMgr::IsRunning())
ms_fScaledFOV = ConvertFOV(fov);
else
ms_fScaledFOV = fov;
#endif
ms_fFOV = fov;
}
#ifdef PROPER_SCALING
float CDraw::ScaleY(float y)
{
return ms_bProperScaling ? y : y * ((float)DEFAULT_SCREEN_HEIGHT/SCREEN_HEIGHT_NTSC);
}
#endif
|
// Boost::locale (convert utf encoding) test for Conan package
// Dmitriy Vetutnev, ODANT, 2018
#include <boost/locale.hpp>
#include <string>
#include <iostream>
#include <cstdlib>
int main(int, char**) {
std::locale defaultLocale{boost::locale::generator().generate("")};
std::locale::global(defaultLocale);
std::cout.imbue(defaultLocale);
std::wcout.imbue(defaultLocale);
{
std::cout << "-- char(UTF-8) to wchar_t --" << std::endl;
const std::string in = {(char)0xd0, (char)0xaf, 'Z', (char)0xd0, (char)0x90}; // Cyrillic capital letter ya, Z, cyrillic capital letter a (ЯZА in UTF-8)
std::cout << "in: " << in << " , in.length(): " << in.length() << std::endl;
const std::wstring normalOut = L"\u042f" L"Z" L"\u0410";
std::wcout << L"normalOut: " << normalOut << L" , normalOut.length(): " << normalOut.length() << std::endl;
const std::wstring out = boost::locale::conv::utf_to_utf<wchar_t>(in);
if (out != normalOut) {
std::wcout << L"Failed! out not equal normalOut, out: " << out << L" , out.length(): " << out.length() << std::endl;
std::exit(EXIT_FAILURE);
}
std::cout << "Ok" << std::endl;
}
{
std::cout << "-- wchar_t to char(UTF-8) --" << std::endl;
const std::wstring in = L"\u042f" L"Z" L"\u0410"; // Cyrillic capital letter ya, Z, cyrillic capital letter a (ЯZА in UTF-8)
std::wcout << L"in: " << in << L" , in.length(): " << in.length() << std::endl;
const std::string normalOut = {(char)0xd0, (char)0xaf, 'Z', (char)0xd0, (char)0x90};
std::cout << "normalOut: " << normalOut << " , normalOut.length(): " << normalOut.length() << std::endl;
const std::string out = boost::locale::conv::utf_to_utf<char>(in);
if (out != normalOut) {
std::cout << "Failed! out not equal normalOut, out: " << out << " , out.length(): " << out.length() << std::endl;
std::exit(EXIT_FAILURE);
}
std::cout << "Ok" << std::endl;
}
{
std::cout << "-- char(UTF-8) to char16_t(UTF-16) --" << std::endl;
const std::string in = {(char)0xd0, (char)0xaf, 'Z', (char)0xd0, (char)0x90}; // Cyrillic capital letter ya, Z, cyrillic capital letter a (ЯZА in UTF-8)
std::cout << "in.length(): " << in.length() << std::endl;
const std::u16string normalOut = u"\u042f" u"Z" u"\u0410";
std::cout << "normalOut.length(): " << normalOut.length() << std::endl;
const std::u16string out = boost::locale::conv::utf_to_utf<char16_t>(in);
if (out != normalOut) {
std::cout << "Failed! out not equal normalOut, out.length(): " << out.length() << std::endl;
std::exit(EXIT_FAILURE);
}
std::cout << "Ok" << std::endl;
}
{
std::cout << "-- char16_t(UTF-16) to char(UTF-8) --" << std::endl;
const std::u16string in = u"\u042f" u"Z" u"\u0410"; // Cyrillic capital letter ya, Z, cyrillic capital letter a (ЯZА in UTF-8)
std::cout << "in.length(): " << in.length() << std::endl;
const std::string normalOut = {(char)0xd0, (char)0xaf, 'Z', (char)0xd0, (char)0x90};
std::cout << "normalOut.length(): " << normalOut.length() << std::endl;
const std::string out = boost::locale::conv::utf_to_utf<char>(in);
if (out != normalOut) {
std::cout << "Failed! out not equal normalOut, out.length(): " << out.length() << std::endl;
std::exit(EXIT_FAILURE);
}
std::cout << "Ok" << std::endl;
}
{
std::cout << "-- char(UTF-8) to char32_t(UTF-32) --" << std::endl;
const std::string in = {(char)0xd0, (char)0xaf, 'Z', (char)0xd0, (char)0x90}; // Cyrillic capital letter ya, Z, cyrillic capital letter a (ЯZА in UTF-8)
std::cout << "in.length(): " << in.length() << std::endl;
const std::u32string normalOut = U"\u042f" U"Z" U"\u0410";
std::cout << "normalOut.length(): " << normalOut.length() << std::endl;
const std::u32string out = boost::locale::conv::utf_to_utf<char32_t>(in);
if (out != normalOut) {
std::cout << "Failed! out not equal normalOut, out.length(): " << out.length() << std::endl;
std::exit(EXIT_FAILURE);
}
std::cout << "Ok" << std::endl;
}
{
std::cout << "-- char32_t(UTF-32) to char(UTF-8) --" << std::endl;
const std::u32string in = U"\u042f" U"Z" U"\u0410"; // Cyrillic capital letter ya, Z, cyrillic capital letter a (ЯZА in UTF-8)
std::cout << "in.length(): " << in.length() << std::endl;
const std::string normalOut = {(char)0xd0, (char)0xaf, 'Z', (char)0xd0, (char)0x90};
std::cout << "normalOut.length(): " << normalOut.length() << std::endl;
const std::string out = boost::locale::conv::utf_to_utf<char>(in);
if (out != normalOut) {
std::cout << "Failed! out not equal normalOut, out.length(): " << out.length() << std::endl;
std::exit(EXIT_FAILURE);
}
std::cout << "Ok" << std::endl;
}
{
std::cout << "-- char16_t(UTF-16) to char32_t(UTF-32) --" << std::endl;
const std::u16string in = u"\u042f" u"Z" u"\u0410"; // Cyrillic capital letter ya, Z, cyrillic capital letter a (ЯZА in UTF-8)
std::cout << "in.length(): " << in.length() << std::endl;
const std::u32string normalOut = U"\u042f" U"Z" U"\u0410";
std::cout << "normalOut.length(): " << normalOut.length() << std::endl;
const std::u32string out = boost::locale::conv::utf_to_utf<char32_t>(in);
if (out != normalOut) {
std::cout << "Failed! out not equal normalOut, out.length(): " << out.length() << std::endl;
std::exit(EXIT_FAILURE);
}
std::cout << "Ok" << std::endl;
}
{
std::cout << "-- char32_t(UTF-32) to char16_t(UTF-16) --" << std::endl;
const std::u32string in = U"\u042f" U"Z" U"\u0410"; // Cyrillic capital letter ya, Z, cyrillic capital letter a (ЯZА in UTF-8)
std::cout << "in.length(): " << in.length() << std::endl;
const std::u16string normalOut = u"\u042f" u"Z" u"\u0410";
std::cout << "normalOut.length(): " << normalOut.length() << std::endl;
const std::u16string out = boost::locale::conv::utf_to_utf<char16_t>(in);
if (out != normalOut) {
std::cout << "Failed! out not equal normalOut, out.length(): " << out.length() << std::endl;
std::exit(EXIT_FAILURE);
}
std::cout << "Ok" << std::endl;
}
return EXIT_SUCCESS;
}
|
#pragma once
#include <mbgl/util/geo.hpp>
#include <mbgl/util/geometry.hpp>
#include <mbgl/util/range.hpp>
#include <mbgl/util/optional.hpp>
#include <mbgl/util/variant.hpp>
#include <mbgl/style/types.hpp>
#include <mbgl/storage/response.hpp>
#include <string>
#include <vector>
#include <functional>
namespace mbgl {
class TileID;
/*
* An offline region defined by a style URL, geographic bounding box, zoom range, and
* device pixel ratio.
*
* Both minZoom and maxZoom must be ≥ 0, and maxZoom must be ≥ minZoom.
*
* maxZoom may be ∞, in which case for each tile source, the region will include
* tiles from minZoom up to the maximum zoom level provided by that source.
*
* pixelRatio must be ≥ 0 and should typically be 1.0 or 2.0.
*/
class OfflineTilePyramidRegionDefinition {
public:
OfflineTilePyramidRegionDefinition(std::string, LatLngBounds, double, double, float, bool);
/* Private */
const std::string styleURL;
const LatLngBounds bounds;
const double minZoom;
const double maxZoom;
const float pixelRatio;
const bool includeIdeographs;
};
/*
* An offline region defined by a style URL, geometry, zoom range, and
* device pixel ratio.
*
* Both minZoom and maxZoom must be ≥ 0, and maxZoom must be ≥ minZoom.
*
* maxZoom may be ∞, in which case for each tile source, the region will include
* tiles from minZoom up to the maximum zoom level provided by that source.
*
* pixelRatio must be ≥ 0 and should typically be 1.0 or 2.0.
*/
class OfflineGeometryRegionDefinition {
public:
OfflineGeometryRegionDefinition(std::string styleURL, Geometry<double>, double minZoom, double maxZoom, float pixelRatio, bool includeIdeographs);
/* Private */
const std::string styleURL;
const Geometry<double> geometry;
const double minZoom;
const double maxZoom;
const float pixelRatio;
const bool includeIdeographs;
};
/*
* The offline region definition types supported
*/
using OfflineRegionDefinition = variant<OfflineTilePyramidRegionDefinition, OfflineGeometryRegionDefinition>;
/*
* The encoded format is private.
*/
std::string encodeOfflineRegionDefinition(const OfflineRegionDefinition&);
OfflineRegionDefinition decodeOfflineRegionDefinition(const std::string&);
/*
* Arbitrary binary region metadata. The contents are opaque to the mbgl implementation;
* it just stores and retrieves a BLOB. SDK bindings should leave the interpretation of
* this data up to the application; they _should not_ enforce a higher-level data format.
* In the future we want offline database to be portable across target platforms, and a
* platform-specific metadata format would prevent that.
*/
using OfflineRegionMetadata = std::vector<uint8_t>;
/*
* A region is either inactive (not downloading, but previously-downloaded
* resources are available for use), or active (resources are being downloaded
* or will be downloaded, if necessary, when network access is available).
*
* This state is independent of whether or not the complete set of resources
* is currently available for offline use. To check if that is the case, use
* `OfflineRegionStatus::complete()`.
*/
enum class OfflineRegionDownloadState {
Inactive,
Active
};
/*
* A region's status includes its active/inactive state as well as counts
* of the number of resources that have completed downloading, their total
* size in bytes, and the total number of resources that are required.
*
* Note that the total required size in bytes is not currently available. A
* future API release may provide an estimate of this number.
*/
class OfflineRegionStatus {
public:
OfflineRegionDownloadState downloadState = OfflineRegionDownloadState::Inactive;
/**
* The number of resources that have been fully downloaded and are ready for
* offline access.
*/
uint64_t completedResourceCount = 0;
/**
* The cumulative size, in bytes, of all resources (inclusive of tiles) that have
* been fully downloaded.
*/
uint64_t completedResourceSize = 0;
/**
* The number of tiles that are known to be required for this region. This is a
* subset of `completedResourceCount`.
*/
uint64_t completedTileCount = 0;
/**
* The cumulative size, in bytes, of all tiles that have been fully downloaded.
* This is a subset of `completedResourceSize`.
*/
uint64_t completedTileSize = 0;
/**
* The number of resources that are known to be required for this region. See the
* documentation for `requiredResourceCountIsPrecise` for an important caveat
* about this number.
*/
uint64_t requiredResourceCount = 0;
/**
* This property is true when the value of requiredResourceCount is a precise
* count of the number of required resources, and false when it is merely a lower
* bound.
*
* Specifically, it is false during early phases of an offline download. Once
* style and tile sources have been downloaded, it is possible to calculate the
* precise number of required resources, at which point it is set to true.
*/
bool requiredResourceCountIsPrecise = false;
bool complete() const {
return completedResourceCount >= requiredResourceCount;
}
};
/*
* A region can have a single observer, which gets notified whenever a change
* to the region's status occurs.
*/
class OfflineRegionObserver {
public:
virtual ~OfflineRegionObserver() = default;
/*
* Implement this method to be notified of a change in the status of an
* offline region. Status changes include any change in state of the members
* of OfflineRegionStatus.
*
* Note that this method will be executed on the database thread; it is the
* responsibility of the SDK bindings to wrap this object in an interface that
* re-executes the user-provided implementation on the main thread.
*/
virtual void statusChanged(OfflineRegionStatus) {}
/*
* Implement this method to be notified of errors encountered while downloading
* regional resources. Such errors may be recoverable; for example the implementation
* will attempt to re-request failed resources based on an exponential backoff
* algorithm, or when it detects that network access has been restored.
*
* Note that this method will be executed on the database thread; it is the
* responsibility of the SDK bindings to wrap this object in an interface that
* re-executes the user-provided implementation on the main thread.
*/
virtual void responseError(Response::Error) {}
/*
* Implement this method to be notified when the limit on the number of Mapbox
* tiles stored for offline regions has been reached.
*
* Once the limit has been reached, the SDK will not download further offline
* tiles from Mapbox APIs until existing tiles have been removed.
*
* This limit does not apply to non-Mapbox tile sources.
*
* Note that this method will be executed on the database thread; it is the
* responsibility of the SDK bindings to wrap this object in an interface that
* re-executes the user-provided implementation on the main thread.
*/
virtual void mapboxTileCountLimitExceeded(uint64_t /* limit */) {}
};
class OfflineRegion {
public:
// Move-only; not publicly constructible.
OfflineRegion(OfflineRegion&&);
~OfflineRegion();
OfflineRegion() = delete;
OfflineRegion(const OfflineRegion&) = delete;
OfflineRegion& operator=(OfflineRegion&&) = delete;
OfflineRegion& operator=(const OfflineRegion&) = delete;
int64_t getID() const;
const OfflineRegionDefinition& getDefinition() const;
const OfflineRegionMetadata& getMetadata() const;
private:
friend class OfflineDatabase;
OfflineRegion(int64_t id,
OfflineRegionDefinition,
OfflineRegionMetadata);
const int64_t id;
const OfflineRegionDefinition definition;
const OfflineRegionMetadata metadata;
};
using OfflineRegions = std::vector<OfflineRegion>;
} // namespace mbgl
|
//=================================================================================================
/*!
// \file src/mathtest/dmatdmatadd/SHaSHa.cpp
// \brief Source file for the SHaSHa dense matrix/dense matrix addition math test
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. 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 names of the Blaze development group 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 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/HybridMatrix.h>
#include <blaze/math/SymmetricMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatdmatadd/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'SHaSHa'..." << std::endl;
using blazetest::mathtest::TypeA;
try
{
// Matrix type definitions
using SHa = blaze::SymmetricMatrix< blaze::HybridMatrix<TypeA,128UL,128UL> >;
// Creator type definitions
using CSHa = blazetest::Creator<SHa>;
// Running tests with small matrices
for( size_t i=0UL; i<=9UL; ++i ) {
RUN_DMATDMATADD_OPERATION_TEST( CSHa( i ), CSHa( i ) );
}
// Running tests with large matrices
RUN_DMATDMATADD_OPERATION_TEST( CSHa( 67UL ), CSHa( 67UL ) );
RUN_DMATDMATADD_OPERATION_TEST( CSHa( 128UL ), CSHa( 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix addition:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
/*!
* @file
* Basic tests for `Reduce.hpp`
*
* This file is a part of easyLambda(ezl) project for parallel data
* processing with modern C++ and MPI.
*
* @copyright Utkarsh Bhardwaj <haptork@gmail.com> 2015-2016
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying LICENSE.md or copy at * http://boost.org/LICENSE_1_0.txt)
* */
#include <tuple>
#include <type_traits>
#include <assert.h>
#include <ezl/units/Filter.hpp>
#include <ezl/units/Zip.hpp>
namespace ezl {
namespace detail {
using namespace ezl::detail;
void ZipBasicCallTest();
void ZipTest(int argc, char* argv[]) {
ZipBasicCallTest();
}
void ZipBasicCallTest() {
using std::make_tuple;
using meta::slct;
using std::tuple;
auto t1 = make_tuple(3, 'c', 4.);
auto t2 = make_tuple(4, 'c');
char ch;
auto f1 = [&ch](char c, int i) {
ch = c;
return i+1;
};
auto r1 = std::make_shared<
Filter<tuple<const int&, const char&>, slct<2,1>, decltype(f1), slct<1,2>>>(f1);
auto z1 = std::make_shared<
Zip<decltype(t1), decltype(t2), slct<1>, slct<1>, slct<1,2>>>();
z1->next(r1, z1);
z1->dataEvent(t1);
z1->dataEvent(t2);
std::get<0>(t2) = 3;
z1->dataEvent(t2);
assert(ch == 'c');
}
int main(int argc, char* argv[]) {
ZipTest(argc, argv);
return 0;
}
}
}
|
#include "common/common/cleanup.h"
#include "test/test_common/test_base.h"
namespace Envoy {
TEST(CleanupTest, ScopeExitCallback) {
bool callback_fired = false;
{
Cleanup cleanup([&callback_fired] { callback_fired = true; });
EXPECT_FALSE(callback_fired);
}
EXPECT_TRUE(callback_fired);
}
} // namespace Envoy
|
#include <fstream>
#include <iostream>
#include <iterator>
#include <numeric>
#include <string>
int main() {
const auto filename = std::string{"directions.txt"};
auto file = std::fstream{filename};
if(file.is_open()) {
using iterator = std::istreambuf_iterator<char>;
const auto begin = iterator{file};
const auto end = iterator{};
const auto accumulator = [UP = '('] (auto floor, const auto direction) {
return floor += (direction == UP) ? 1 : -1;
};
const auto result = std::accumulate(begin, end, 0, accumulator);
std::cout << result << std::endl;
} else {
std::cerr << "Error! Could not open \"" << filename << "\"!" << std::endl;
}
return 0;
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "db.h"
#include "net.h"
#include "init.h"
#include "addrman.h"
#include "ui_interface.h"
#include "script.h"
#ifdef WIN32
#include <string.h>
#endif
#ifdef USE_UPNP
#include <miniupnpc/miniwget.h>
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
#endif
// Dump addresses to peers.dat every 15 minutes (900s)
#define DUMP_ADDRESSES_INTERVAL 900
using namespace std;
using namespace boost;
static const int MAX_OUTBOUND_CONNECTIONS = 8;
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
struct LocalServiceInfo {
int nScore;
int nPort;
};
//
// Global state variables
//
bool fDiscover = true;
uint64 nLocalServices = NODE_NETWORK;
static CCriticalSection cs_mapLocalHost;
static map<CNetAddr, LocalServiceInfo> mapLocalHost;
static bool vfReachable[NET_MAX] = {};
static bool vfLimited[NET_MAX] = {};
static CNode* pnodeLocalHost = NULL;
static CNode* pnodeSync = NULL;
uint64 nLocalHostNonce = 0;
static std::vector<SOCKET> vhListenSocket;
CAddrMan addrman;
int nMaxConnections = 125;
vector<CNode*> vNodes;
CCriticalSection cs_vNodes;
map<CInv, CDataStream> mapRelay;
deque<pair<int64, CInv> > vRelayExpiration;
CCriticalSection cs_mapRelay;
limitedmap<CInv, int64> mapAlreadyAskedFor(MAX_INV_SZ);
static deque<string> vOneShots;
CCriticalSection cs_vOneShots;
set<CNetAddr> setservAddNodeAddresses;
CCriticalSection cs_setservAddNodeAddresses;
vector<std::string> vAddedNodes;
CCriticalSection cs_vAddedNodes;
static CSemaphore *semOutbound = NULL;
void AddOneShot(string strDest)
{
LOCK(cs_vOneShots);
vOneShots.push_back(strDest);
}
unsigned short GetListenPort()
{
return (unsigned short)(GetArg("-port", GetDefaultPort()));
}
void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)
{
// Filter out duplicate requests
if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd)
return;
pindexLastGetBlocksBegin = pindexBegin;
hashLastGetBlocksEnd = hashEnd;
PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);
}
// find 'best' local address for a particular peer
bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
{
if (fNoListen)
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
CAddress GetLocalAddress(const CNetAddr *paddrPeer)
{
CAddress ret(CService("0.0.0.0",0),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 = "";
loop
{
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
printf("socket closed\n");
return false;
}
else
{
// socket error
int nErr = WSAGetLastError();
printf("recv failed: %d\n", nErr);
return false;
}
}
}
}
// used when scores of local addresses may have changed
// pushes better local address to peers
void static AdvertizeLocal()
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->fSuccessfullyConnected)
{
CAddress addrLocal = GetLocalAddress(&pnode->addr);
if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal)
{
pnode->PushAddress(addrLocal);
pnode->addrLocal = 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;
printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), 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());
}
AdvertizeLocal();
return true;
}
bool AddLocal(const CNetAddr &addr, int nScore)
{
return AddLocal(CService(addr, GetListenPort()), nScore);
}
/** 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++;
}
AdvertizeLocal();
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 address is in a network we can probably connect to */
bool IsReachable(const CNetAddr& addr)
{
LOCK(cs_mapLocalHost);
enum Network net = addr.GetNetwork();
return vfReachable[net] && !vfLimited[net];
}
bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
{
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());
send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
string strLine;
while (RecvLine(hSocket, strLine))
{
if (strLine.empty()) // HTTP response is separated from headers by blank line
{
loop
{
if (!RecvLine(hSocket, strLine))
{
closesocket(hSocket);
return false;
}
if (pszKeyword == NULL)
break;
if (strLine.find(pszKeyword) != string::npos)
{
strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
break;
}
}
closesocket(hSocket);
if (strLine.find("<") != string::npos)
strLine = strLine.substr(0, strLine.find("<"));
strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
strLine.resize(strLine.size()-1);
CService addr(strLine,0,true);
printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
if (!addr.IsValid() || !addr.IsRoutable())
return false;
ipRet.SetIP(addr);
return true;
}
}
closesocket(hSocket);
return error("GetMyExternalIP() : connection closed");
}
bool GetMyExternalIP(CNetAddr& ipRet)
{
CService addrConnect;
const char* pszGet;
const char* pszKeyword;
for (int nLookup = 0; nLookup <= 1; nLookup++)
for (int nHost = 1; nHost <= 1; nHost++)
{
// We should be phasing out our use of sites like these. If we need
// replacements, we should ask for volunteers to put this simple
// php file on their web server that prints the client IP:
// <?php echo $_SERVER["REMOTE_ADDR"]; ?>
if (nHost == 1)
{
addrConnect = CService("216.146.43.70", 80); // checkip.dyndns.org
if (nLookup == 1)
{
CService addrIP("checkip.dyndns.org", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET / HTTP/1.1\r\n"
"Host: checkip.dyndns.org\r\n"
"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = "Address:";
}
if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
return true;
}
return false;
}
void ThreadGetMyExternalIP(void* parg)
{
// Make this thread recognisable as the external IP detection thread
RenameThread("bitcoin-ext-ip");
CNetAddr addrLocalHost;
if (GetMyExternalIP(addrLocalHost))
{
printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
AddLocal(addrLocalHost, LOCAL_HTTP);
}
}
void AddressCurrentlyConnected(const CService& addr)
{
addrman.Connected(addr);
}
CNode* FindNode(const CNetAddr& ip)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CNetAddr)pnode->addr == ip)
return (pnode);
return NULL;
}
CNode* FindNode(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 ((CService)pnode->addr == addr)
return (pnode);
return NULL;
}
CNode* ConnectNode(CAddress addrConnect, const char *pszDest)
{
if (pszDest == NULL) {
if (IsLocal(addrConnect))
return NULL;
// Look for an existing connection
CNode* pnode = FindNode((CService)addrConnect);
if (pnode)
{
pnode->AddRef();
return pnode;
}
}
/// debug print
printf("trying connection %s lastseen=%.1fhrs\n",
pszDest ? pszDest : addrConnect.ToString().c_str(),
pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
// Connect
SOCKET hSocket;
if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
{
addrman.Attempt(addrConnect);
/// debug print
printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str());
// Set to non-blocking
#ifdef WIN32
u_long nOne = 1;
if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError());
#else
if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno);
#endif
// Add node
CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
pnode->nTimeConnected = GetTime();
return pnode;
}
else
{
return NULL;
}
}
void CNode::CloseSocketDisconnect()
{
fDisconnect = true;
if (hSocket != INVALID_SOCKET)
{
printf("disconnecting node %s\n", addrName.c_str());
closesocket(hSocket);
hSocket = INVALID_SOCKET;
}
// in case this fails, we'll empty the recv buffer when the CNode is deleted
TRY_LOCK(cs_vRecvMsg, lockRecv);
if (lockRecv)
vRecvMsg.clear();
// if this was the sync node, we'll need a new one
if (this == pnodeSync)
pnodeSync = NULL;
}
void CNode::Cleanup()
{
}
void CNode::PushVersion()
{
/// when NTP implemented, change to just nTime = GetAdjustedTime()
int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
CAddress addrMe = GetLocalAddress(&addr);
RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str());
PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight);
}
std::map<CNetAddr, int64> 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>::iterator i = setBanned.find(ip);
if (i != setBanned.end())
{
int64 t = (*i).second;
if (GetTime() < t)
fResult = true;
}
}
return fResult;
}
bool CNode::Misbehaving(int howmuch)
{
if (addr.IsLocal())
{
printf("Warning: Local node %s misbehaving (delta: %d)!\n", addrName.c_str(), howmuch);
return false;
}
nMisbehavior += howmuch;
if (nMisbehavior >= GetArg("-banscore", 100))
{
int64 banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban
printf("Misbehaving: %s (%d -> %d) DISCONNECTING\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
{
LOCK(cs_setBanned);
if (setBanned[addr] < banTime)
setBanned[addr] = banTime;
}
CloseSocketDisconnect();
return true;
} else
printf("Misbehaving: %s (%d -> %d)\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
return false;
}
#undef X
#define X(name) stats.name = name
void CNode::copyStats(CNodeStats &stats)
{
X(nServices);
X(nLastSend);
X(nLastRecv);
X(nTimeConnected);
X(addrName);
X(nVersion);
X(cleanSubVer);
X(fInbound);
X(nStartingHeight);
X(nMisbehavior);
X(nSendBytes);
X(nRecvBytes);
X(nBlocksRequested);
stats.fSyncNode = (this == pnodeSync);
}
#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;
pch += handled;
nBytes -= handled;
}
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 (std::exception &e) {
return -1;
}
// reject messages larger than MAX_SIZE
if (hdr.nMessageSize > MAX_SIZE)
return -1;
// switch state to reading message data
in_data = true;
vRecv.resize(hdr.nMessageSize);
return nCopy;
}
int CNetMessage::readData(const char *pch, unsigned int nBytes)
{
unsigned int nRemaining = hdr.nMessageSize - nDataPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
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;
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)
{
printf("socket send error %d\n", 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;
loop
{
//
// 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();
pnode->Cleanup();
// 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;
}
}
}
}
if (vNodes.size() != nPrevNodeCount)
{
nPrevNodeCount = vNodes.size();
uiInterface.NotifyNumConnectionsChanged(vNodes.size());
}
//
// 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(SOCKET hListenSocket, vhListenSocket) {
FD_SET(hListenSocket, &fdsetRecv);
hSocketMax = max(hSocketMax, hListenSocket);
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();
printf("socket select error %d\n", 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(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
{
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
CAddress addr;
int nInbound = 0;
if (hSocket != INVALID_SOCKET)
if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
printf("Warning: Unknown socket family\n");
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->fInbound)
nInbound++;
}
if (hSocket == INVALID_SOCKET)
{
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK)
printf("socket error accept failed: %d\n", nErr);
}
else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS)
{
{
LOCK(cs_setservAddNodeAddresses);
if (!setservAddNodeAddresses.count(addr))
closesocket(hSocket);
}
}
else if (CNode::IsBanned(addr))
{
printf("connection from %s dropped (banned)\n", addr.ToString().c_str());
closesocket(hSocket);
}
else
{
printf("accepted connection %s\n", addr.ToString().c_str());
CNode* pnode = new CNode(hSocket, addr, "", true);
pnode->AddRef();
{
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;
}
else if (nBytes == 0)
{
// socket closed gracefully
if (!pnode->fDisconnect)
printf("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)
printf("socket recv error %d\n", 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
//
if (pnode->vSendMsg.empty())
pnode->nLastSendEmpty = GetTime();
if (GetTime() - pnode->nTimeConnected > 60)
{
if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
{
printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
{
printf("socket not sending\n");
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastRecv > 90*60)
{
printf("socket inactivity timeout\n");
pnode->fDisconnect = true;
}
}
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
MilliSleep(10);
}
}
#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);
#else
/* miniupnpc 1.6 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &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)
printf("UPnP: GetExternalIPAddress() returned %d\n", r);
else
{
if(externalIPAddress[0])
{
printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
}
else
printf("UPnP: GetExternalIPAddress failed.\n");
}
}
string strDesc = "ctlcoin " + FormatFullVersion();
try {
loop {
#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)
printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
else
printf("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);
printf("UPNP_DeletePortMapping() returned : %d\n", r);
freeUPNPDevlist(devlist); devlist = 0;
FreeUPNPUrls(&urls);
throw;
}
} else {
printf("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<boost::function<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
// DNS seeds
// Each pair gives a source name and a seed name.
// The first name is used as information source for addrman.
// The second name should resolve to a list of seed addresses.
static const char *strMainNetDNSSeed[][2] = {
{"walletbuilders.com", "node.walletbuilders.com"},
{NULL, NULL}
};
static const char *strTestNetDNSSeed[][2] = {
{NULL, NULL}
};
void ThreadDNSAddressSeed()
{
static const char *(*strDNSSeed)[2] = fTestNet ? strTestNetDNSSeed : strMainNetDNSSeed;
int found = 0;
printf("Loading addresses from DNS seeds (could take a while)\n");
for (unsigned int seed_idx = 0; strDNSSeed[seed_idx][0] != NULL; seed_idx++) {
if (HaveNameProxy()) {
AddOneShot(strDNSSeed[seed_idx][1]);
} else {
vector<CNetAddr> vaddr;
vector<CAddress> vAdd;
if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
{
BOOST_FOREACH(CNetAddr& ip, vaddr)
{
int nOneDay = 24*3600;
CAddress addr = CAddress(CService(ip, 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(strDNSSeed[seed_idx][0], true));
}
}
printf("%d addresses found from DNS seeds\n", found);
}
unsigned int pnSeed[] =
{};
void DumpAddresses()
{
int64 nStart = GetTimeMillis();
CAddrDB adb;
adb.Write(addrman);
printf("Flushed %d addresses to peers.dat %"PRI64d"ms\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 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 nStart = GetTime();
loop
{
ProcessOneShot();
MilliSleep(500);
CSemaphoreGrant grant(*semOutbound);
boost::this_thread::interruption_point();
// Add seed nodes if IRC isn't working
if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet)
{
std::vector<CAddress> vAdd;
for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64 nOneWeek = 7*24*60*60;
struct in_addr ip;
memcpy(&ip, &pnSeed[i], sizeof(ip));
CAddress addr(CService(ip, GetDefaultPort()));
addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
vAdd.push_back(addr);
}
addrman.Add(vAdd, CNetAddr("127.0.0.1"));
}
//
// 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 nANow = GetAdjustedTime();
int nTries = 0;
loop
{
// use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
// 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() != 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, 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 *strDest, bool fOneShot)
{
//
// Initiate outbound network connection
//
boost::this_thread::interruption_point();
if (!strDest)
if (IsLocal(addrConnect) ||
FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
FindNode(addrConnect.ToStringIPPort().c_str()))
return false;
if (strDest && FindNode(strDest))
return false;
CNode* pnode = ConnectNode(addrConnect, strDest);
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;
}
// for now, use a very simple selection metric: the node from which we received
// most recently
double static NodeSyncScore(const CNode *pnode) {
return -pnode->nLastRecv;
}
void static StartSync(const vector<CNode*> &vNodes) {
CNode *pnodeNewSync = NULL;
double dBestScore = 0;
// fImporting and fReindex are accessed out of cs_main here, but only
// as an optimization - they are checked again in SendMessages.
if (fImporting || fReindex)
return;
// Iterate over all nodes
BOOST_FOREACH(CNode* pnode, vNodes) {
// check preconditions for allowing a sync
if (!pnode->fClient && !pnode->fOneShot &&
!pnode->fDisconnect && pnode->fSuccessfullyConnected &&
(pnode->nStartingHeight > (nBestHeight - 144)) &&
(pnode->nVersion < NOBLKS_VERSION_START || pnode->nVersion >= NOBLKS_VERSION_END)) {
// if ok, compare node's score with the best so far
double dScore = NodeSyncScore(pnode);
if (pnodeNewSync == NULL || dScore > dBestScore) {
pnodeNewSync = pnode;
dBestScore = dScore;
}
}
}
// if a new sync candidate was found, start sync!
if (pnodeNewSync) {
pnodeNewSync->fStartSync = true;
pnodeSync = pnodeNewSync;
}
}
void ThreadMessageHandler()
{
SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
while (true)
{
bool fHaveSyncNode = false;
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy) {
pnode->AddRef();
if (pnode == pnodeSync)
fHaveSyncNode = true;
}
}
if (!fHaveSyncNode)
StartSync(vNodesCopy);
// Poll the connected nodes for messages
CNode* pnodeTrickle = NULL;
if (!vNodesCopy.empty())
pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
bool fSleep = true;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (pnode->fDisconnect)
continue;
// Receive messages
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv)
{
if (!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)
SendMessages(pnode, pnode == pnodeTrickle);
}
boost::this_thread::interruption_point();
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
if (fSleep)
MilliSleep(100);
}
}
bool BindListenPort(const CService &addrBind, string& strError)
{
strError = "";
int nOne = 1;
// Create socket for listening for incoming connections
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
{
strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
printf("%s\n", strError.c_str());
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 %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
#ifdef SO_NOSIGPIPE
// Different way of disabling SIGPIPE on BSD
setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
#endif
#ifndef WIN32
// 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
#ifdef WIN32
// Set to non-blocking, incoming connections will also inherit this
if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
#else
if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
#endif
{
strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
#ifdef USE_IPV6
// 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 = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
// this call is allowed to fail
setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
#endif
}
#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. ctlcoin is probably already running."), addrBind.ToString().c_str());
else
strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
printf("%s\n", strError.c_str());
return false;
}
printf("Bound to %s\n", addrBind.ToString().c_str());
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
{
strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
vhListenSocket.push_back(hListenSocket);
if (addrBind.IsRoutable() && fDiscover)
AddLocal(addrBind, LOCAL_BIND);
return true;
}
void static Discover()
{
if (!fDiscover)
return;
#ifdef WIN32
// Get local host IP
char pszHostName[1000] = "";
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
{
vector<CNetAddr> vaddr;
if (LookupHost(pszHostName, vaddr))
{
BOOST_FOREACH (const CNetAddr &addr, vaddr)
{
AddLocal(addr, LOCAL_IF);
}
}
}
#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))
printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
#ifdef USE_IPV6
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))
printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
#endif
}
freeifaddrs(myaddrs);
}
#endif
// Don't use external IPv4 discovery, when -onlynet="IPv6"
if (!IsLimited(NET_IPV4))
NewThread(ThreadGetMyExternalIP, NULL);
}
void StartNode(boost::thread_group& threadGroup)
{
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();
//
// Start threads
//
if (!GetBoolArg("-dnsseed", true))
printf("DNS seeding disabled\n");
else
threadGroup.create_thread(boost::bind(&TraceThread<boost::function<void()> >, "dnsseed", &ThreadDNSAddressSeed));
#ifdef USE_UPNP
// Map ports with UPnP
MapPort(GetBoolArg("-upnp", USE_UPNP));
#endif
// 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));
}
bool StopNode()
{
printf("StopNode()\n");
GenerateBitcoins(false, NULL);
MapPort(false);
nTransactionsUpdated++;
if (semOutbound)
for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
semOutbound->post();
MilliSleep(50);
DumpAddresses();
return true;
}
class CNetCleanup
{
public:
CNetCleanup()
{
}
~CNetCleanup()
{
// Close sockets
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->hSocket != INVALID_SOCKET)
closesocket(pnode->hSocket);
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET)
if (closesocket(hListenSocket) == SOCKET_ERROR)
printf("closesocket(hListenSocket) failed with error %d\n", 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();
delete semOutbound;
semOutbound = NULL;
delete pnodeLocalHost;
pnodeLocalHost = NULL;
#ifdef WIN32
// Shutdown Windows Sockets
WSACleanup();
#endif
}
}
instance_of_cnetcleanup;
void RelayTransaction(const CTransaction& tx, const uint256& hash)
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(10000);
ss << tx;
RelayTransaction(tx, hash, ss);
}
void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss)
{
CInv inv(MSG_TX, hash);
{
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, hash))
pnode->PushInventory(inv);
} else
pnode->PushInventory(inv);
}
}
|
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/vm/jit/check.h"
#include "hphp/runtime/vm/jit/analysis.h"
#include "hphp/runtime/vm/jit/block.h"
#include "hphp/runtime/vm/jit/cfg.h"
#include "hphp/runtime/vm/jit/id-set.h"
#include "hphp/runtime/vm/jit/ir-instruction.h"
#include "hphp/runtime/vm/jit/ir-opcode.h"
#include "hphp/runtime/vm/jit/ir-unit.h"
#include "hphp/runtime/vm/jit/state-vector.h"
#include "hphp/runtime/vm/jit/phys-reg.h"
#include "hphp/runtime/vm/jit/reg-alloc.h"
#include "hphp/runtime/vm/jit/type.h"
#include "hphp/runtime/base/perf-warning.h"
#include "hphp/runtime/ext/std/ext_std_closure.h"
#include <folly/Format.h>
#include <bitset>
#include <iostream>
#include <string>
#include <boost/dynamic_bitset.hpp>
namespace HPHP { namespace jit {
//////////////////////////////////////////////////////////////////////
namespace {
//////////////////////////////////////////////////////////////////////
TRACE_SET_MOD(hhir);
/*
* Return the number of parameters required for this block.
*/
DEBUG_ONLY static int numBlockParams(Block* b) {
return b->empty() || b->front().op() != DefLabel ? 0 :
b->front().numDsts();
}
/*
* Check one block for being well formed. Invariants verified:
* 1. The block begins with an optional DefLabel, followed by an optional
* BeginCatch.
* 2. DefLabel and BeginCatch may not appear anywhere in a block other than
* where specified in #1.
* 3. If this block is a catch block, it must have at most one predecessor.
* 4. The last instruction must be isBlockEnd() and the middle instructions
* must not be isBlockEnd(). Therefore, blocks cannot be empty.
* 5. block->next() must be null iff the last instruction isTerminal().
* 6. Every instruction must have a catch block attached to it if and only if it
* has the MayRaiseError flag.
* 7. Any path from this block to a Block that expects values must be
* from a Jmp instruciton.
* 8. Every instruction's BCMarker must point to a valid bytecode instruction.
*/
bool checkBlock(Block* b) {
SCOPE_ASSERT_DETAIL("checkBlock") { return folly::sformat("B{}", b->id()); };
auto it = b->begin();
auto end = b->end();
always_assert(!b->empty());
// Invariant #1
if (it->op() == DefLabel) {
++it;
}
// Invariant #1
if (it != end && it->op() == BeginCatch) {
++it;
}
// Invariants #2, #4
always_assert(it != end && b->back().isBlockEnd());
--end;
for (IRInstruction& inst : folly::range(it, end)) {
always_assert(inst.op() != DefLabel);
always_assert(inst.op() != BeginCatch);
always_assert(!inst.isBlockEnd());
}
for (IRInstruction& inst : *b) {
// Invariant #8
always_assert(inst.marker().valid());
always_assert(inst.block() == b);
// Invariant #6
always_assert_flog(
inst.mayRaiseError() == (inst.taken() && inst.taken()->isCatch()),
"{}", inst
);
}
// Invariant #5
always_assert(b->back().isTerminal() == (b->next() == nullptr));
// Invariant #7
if (b->taken()) {
// only Jmp can branch to a join block expecting values.
IRInstruction* branch = &b->back();
auto numArgs = branch->op() == Jmp ? branch->numSrcs() : 0;
always_assert(numBlockParams(b->taken()) == numArgs);
}
// Invariant #3
if (b->isCatch()) {
// keyed off a tca, so there needs to be exactly one
always_assert(b->preds().size() <= 1);
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
}
///////////////////////////////////////////////////////////////////////////////
/*
* Build the CFG, then the dominator tree, then use it to validate SSA.
* 1. Each src must be defined by some other instruction, and each dst must
* be defined by the current instruction.
* 2. Each src must be defined earlier in the same block or in a dominator.
* 3. Each dst must not be previously defined.
* 4. Treat tmps defined by DefConst as always defined.
* 5. Each predecessor of a reachable block must be reachable (deleted
* blocks must not have out-edges to reachable blocks).
* 6. The entry block must not have any predecessors.
* 7. The entry block starts with a DefFP instruction.
*/
bool checkCfg(const IRUnit& unit) {
auto const blocks = rpoSortCfg(unit);
auto const rpoIDs = numberBlocks(unit, blocks);
auto reachable = boost::dynamic_bitset<>(unit.numBlocks());
// Entry block can't have predecessors.
always_assert(unit.entry()->numPreds() == 0);
// Entry block starts with DefFP.
always_assert(!unit.entry()->empty() &&
unit.entry()->begin()->op() == DefFP);
// Check valid successor/predecessor edges, and identify reachable blocks.
for (Block* b : blocks) {
reachable.set(b->id());
auto checkEdge = [&] (const Edge* e) {
always_assert(e->from() == b);
for (auto& p : e->to()->preds()) if (&p == e) return;
always_assert(false); // did not find edge.
};
checkBlock(b);
if (auto e = b->nextEdge()) checkEdge(e);
if (auto e = b->takenEdge()) checkEdge(e);
}
for (Block* b : blocks) {
for (auto const& e : b->preds()) {
always_assert(&e == e.inst()->takenEdge() || &e == e.inst()->nextEdge());
always_assert(e.to() == b);
// Invariant #5
always_assert_flog(reachable.test(e.from()->id()),
"unreachable: B{}\n", e.from()->id());
}
}
auto defined_set = jit::sparse_idptr_set<SSATmp>{unit.numTmps()};
/*
* Visit every instruction and make sure their sources are either defined in
* a block that strictly dominates the block containing the instruction, or
* defined earlier in the same block as the instruction.
*/
auto const idoms = findDominators(unit, blocks, rpoIDs);
for (auto& blk : blocks) {
for (auto& inst : blk->instrs()) {
for (auto src : inst.srcs()) {
if (src->inst()->is(DefConst)) continue;
if (src->type() <= TBottom) continue;
always_assert_flog(
src->inst()->dsts().contains(src),
"src '{}' has '{}' as its instruction, "
"but the instruction does not have '{}' as a dst",
src->toString(),
src->inst()->toString(),
src->toString()
);
auto const dom = findDefiningBlock(src, idoms);
auto const locally_defined =
src->inst()->block() == inst.block() && defined_set.contains(src);
auto const strictly_dominates =
src->inst()->block() != inst.block() &&
dom && dominates(dom, inst.block(), idoms);
always_assert_flog(
locally_defined || strictly_dominates,
"src '{}' in '{}' came from '{}', which is not a "
"DefConst and is not defined at this use site",
src->toString(), inst.toString(),
src->inst()->toString()
);
}
for (auto dst : inst.dsts()) defined_set.insert(dst);
}
defined_set.clear();
}
/*
* Check that each dst is defined only once.
*/
defined_set.clear();
for (auto& blk : blocks) {
for (auto& inst : blk->instrs()) {
for (auto dst : inst.dsts()) {
always_assert_flog(
!defined_set.contains(dst),
"SSATmp ({}) was defined multiple times",
dst->toString()
);
defined_set.insert(dst);
}
}
}
return true;
}
bool checkTmpsSpanningCalls(const IRUnit& unit) {
auto ignoreSrc = [&](IRInstruction& /*inst*/, SSATmp* src) {
/*
* FramePtr/StkPtr-typed tmps may live across calls.
*
* Tmps defined by DefConst are always available and may be assigned to
* registers if needed by the instructions using the const.
*/
return src->isA(TStkPtr) ||
src->isA(TFramePtr) ||
src->inst()->is(DefConst);
};
StateVector<Block,IdSet<SSATmp>> livein(unit, IdSet<SSATmp>());
bool isValid = true;
std::string failures;
postorderWalk(unit, [&](Block* block) {
auto& live = livein[block];
if (auto taken = block->taken()) live = livein[taken];
if (auto next = block->next()) live |= livein[next];
for (auto it = block->end(); it != block->begin();) {
auto& inst = *--it;
for (auto dst : inst.dsts()) {
live.erase(dst);
}
if (isCallOp(inst.op())) {
live.forEach([&](uint32_t tmp) {
folly::format(&failures, "t{} is live across `{}`\n", tmp, inst);
isValid = false;
});
}
for (auto* src : inst.srcs()) {
if (!ignoreSrc(inst, src)) live.add(src);
}
}
});
if (!isValid) {
logLowPriPerfWarning(
"checkTmpsSpanningCalls",
[&](StructuredLogEntry& cols) {
cols.setStr("live_tmps", failures);
cols.setStr("hhir_unit", show(unit));
}
);
}
return isValid;
}
///////////////////////////////////////////////////////////////////////////////
// checkOperandTypes().
namespace {
/*
* Return a union type containing all the types in the argument list.
*/
Type buildUnion() {
return TBottom;
}
template<class... Args>
Type buildUnion(Type t, Args... ts) {
return t | buildUnion(ts...);
}
template <uint32_t...> struct IdxSeq {};
template <typename F>
inline void forEachSrcIdx(F /*f*/, IdxSeq<>) {}
template <typename F, uint32_t Idx, uint32_t... Rest>
inline void forEachSrcIdx(F f, IdxSeq<Idx, Rest...>) {
f(Idx); forEachSrcIdx(f, IdxSeq<Rest...>{});
}
}
/*
* Runtime typechecking for IRInstruction operands.
*
* This is generated using the table in ir-opcode.h. We instantiate
* IR_OPCODES after defining all the various source forms to do type
* assertions according to their form (see ir-opcode.h for documentation on
* the notation). The checkers appear in argument order, so each one
* increments curSrc, and at the end we can check that the argument
* count was also correct.
*/
bool checkOperandTypes(const IRInstruction* inst, const IRUnit* /*unit*/) {
int curSrc = 0;
auto bail = [&] (const std::string& msg) {
FTRACE(1, "{}", msg);
fprintf(stderr, "%s\n", msg.c_str());
always_assert_log(false, [&] { return msg; });
};
if (opHasExtraData(inst->op()) != (bool)inst->rawExtra()) {
bail(folly::format("opcode {} should{} have an ExtraData struct "
"but instruction {} does{}",
inst->op(),
opHasExtraData(inst->op()) ? "" : "n't",
*inst,
inst->rawExtra() ? "" : "n't").str());
}
auto src = [&]() -> SSATmp* {
if (curSrc < inst->numSrcs()) {
return inst->src(curSrc);
}
bail(folly::format(
"Error: instruction had too few operands\n"
" instruction: {}\n",
inst->toString()
).str()
);
not_reached();
};
// If expected is not nullptr, it will be used. Otherwise, t.toString() will
// be used as the expected string.
auto check = [&] (bool cond, const Type t, const char* expected) {
if (cond) return true;
std::string expectStr = expected ? expected : t.toString();
bail(folly::format(
"Error: failed type check on operand {}\n"
" instruction: {}\n"
" was expecting: {}\n"
" received: {}\n"
" from: {}\n",
curSrc,
*inst,
expectStr,
inst->src(curSrc)->type(),
*inst->src(curSrc)->inst()
).str()
);
return true;
};
auto checkNoArgs = [&]{
if (inst->numSrcs() == 0) return true;
bail(folly::format(
"Error: instruction expected no operands\n"
" instruction: {}\n",
inst->toString()
).str()
);
return true;
};
auto countCheck = [&]{
if (inst->numSrcs() == curSrc) return true;
bail(folly::format(
"Error: instruction had too many operands\n"
" instruction: {}\n"
" expected {} arguments\n",
inst->toString(),
curSrc
).str()
);
return true;
};
auto checkArr = [&] (bool is_kv,
bool is_const) {
auto t = src()->type();
auto cond_type = RuntimeOption::EvalHackArrDVArrs
? (is_kv ? TDict : TVec) : TArr;
if (is_const) {
auto expected = folly::sformat("constant {}", t.toString());
check(src()->hasConstVal(cond_type), t, expected.c_str());
} else {
check(src()->isA(cond_type), t, nullptr);
}
++curSrc;
};
auto checkDst = [&] (bool cond, const std::string& errorMessage) {
if (cond) return true;
bail(folly::format("Error: failed type check on dest operand\n"
" instruction: {}\n"
" message: {}\n",
inst->toString(),
errorMessage).str());
return true;
};
auto requireTypeParam = [&] (Type ty) {
checkDst(inst->hasTypeParam() || inst->is(DefConst),
"Missing paramType for DParam instruction");
if (inst->hasTypeParam()) {
checkDst(inst->typeParam() <= ty,
"Invalid paramType for DParam instruction");
}
};
auto checkVariadic = [&] (Type super) {
for (; curSrc < inst->numSrcs(); ++curSrc) {
auto const valid = (inst->src(curSrc)->type() <= super);
check(valid, Type(), nullptr);
}
};
#define IRT(name, ...) UNUSED static constexpr Type name = T##name;
#define IRTP(name, ...) IRT(name)
#define IRTL(name, ...) IRT(name)
#define IRTM(name, ...) IRT(name)
#define IRTX(name, ...) IRT(name)
IR_TYPES
#undef IRT
#undef IRTP
#undef IRTL
#undef IRTM
#undef IRTX
#define NA return checkNoArgs();
#define S(...) { \
Type t = buildUnion(__VA_ARGS__); \
check(src()->isA(t), t, nullptr); \
++curSrc; \
}
#define AK(kind) Type::Array(ArrayData::k##kind##Kind)
#define C(T) check(src()->hasConstVal(T) || \
src()->isA(TBottom), \
Type(), \
"constant " #T); \
++curSrc;
#define CStr C(StaticStr)
#define SVar(...) checkVariadic(buildUnion(__VA_ARGS__));
#define SVArr checkArr(false /* is_kv */, false /* is_const */);
#define SDArr checkArr(true /* is_kv */, false /* is_const */);
#define CDArr checkArr(true /* is_kv */, true /* is_const */);
#define ND
#define DMulti
#define DSetElem
#define D(...)
#define DBuiltin
#define DCall
#define DGenIter
#define DSubtract(src, t)checkDst(src < inst->numSrcs(), \
"invalid src num");
#define DofS(src) checkDst(src < inst->numSrcs(), \
"invalid src num");
#define DRefineS(src) checkDst(src < inst->numSrcs(), \
"invalid src num"); \
requireTypeParam(Top);
#define DParamMayRelax(t) requireTypeParam(t);
#define DParam(t) requireTypeParam(t);
#define DUnion(...) forEachSrcIdx( \
[&](uint32_t idx) { \
checkDst(idx < inst->numSrcs(), "invalid src num"); \
}, \
IdxSeq<__VA_ARGS__>{} \
);
#define DLdObjCls
#define DAllocObj
#define DArrElem
#define DVecElem
#define DDictElem
#define DKeysetElem
#define DVecFirstElem
#define DVecLastElem
#define DVecKey
#define DDictFirstElem
#define DDictLastElem
#define DDictFirstKey
#define DDictLastKey
#define DKeysetFirstElem
#define DKeysetLastElem
#define DArrPacked
#define DArrMixed
#define DArrRecord
#define DVArr
#define DVArrOrNull
#define DDArr
#define DStaticDArr
#define DCol
#define DCns
#define DMemoKey
#define DLvalOfPtr
#define DPtrIter
#define DPtrIterVal
#define O(opcode, dstinfo, srcinfo, flags) \
case opcode: dstinfo srcinfo countCheck(); return true;
switch (inst->op()) {
IR_OPCODES
default: always_assert(false);
}
#undef O
#undef NA
#undef S
#undef AK
#undef C
#undef CStr
#undef SVar
#undef SVArr
#undef SVArrOrNull
#undef SDArr
#undef CDArr
#undef ND
#undef D
#undef DBuiltin
#undef DCall
#undef DGenIter
#undef DSubtract
#undef DMulti
#undef DSetElem
#undef DofS
#undef DRefineS
#undef DParamMayRelax
#undef DParam
#undef DLdObjCls
#undef DAllocObj
#undef DArrElem
#undef DVecElem
#undef DDictElem
#undef DKeysetElem
#undef DVecFirstElem
#undef DVecLastElem
#undef DVecKey
#undef DDictFirstElem
#undef DDictLastElem
#undef DDictFirstKey
#undef DDictLastKey
#undef DKeysetFirstElem
#undef DKeysetLastElem
#undef DArrPacked
#undef DArrMixed
#undef DArrRecord
#undef DVArr
#undef DVArrOrNull
#undef DDArr
#undef DStaticDArr
#undef DCol
#undef DCns
#undef DUnion
#undef DMemoKey
#undef DLvalOfPtr
return true;
}
bool checkEverything(const IRUnit& unit) {
assertx(checkCfg(unit));
if (debug) {
checkTmpsSpanningCalls(unit);
forEachInst(rpoSortCfg(unit), [&](IRInstruction* inst) {
assertx(checkOperandTypes(inst, &unit));
});
}
return true;
}
//////////////////////////////////////////////////////////////////////
}}
|
#include "IPlugFaustDSP.h"
#include "IPlug_include_in_plug_src.h"
IPlugFaustDSP::IPlugFaustDSP(const InstanceInfo& info)
: Plugin(info, MakeConfig(kNumParams, 1))
{
InitParamRange(0, kNumParams-1, 0, "Param %i", 0., 0., 1., 0.01, "", IParam::kFlagsNone);
#if IPLUG_DSP
mFaustProcessor.SetMaxChannelCount(MaxNChannels(ERoute::kInput), MaxNChannels(ERoute::kOutput));
mFaustProcessor.Init();
mFaustProcessor.CompileCPP();
mFaustProcessor.SetAutoRecompile(true);
mFaustProcessor.SetCompileFunc([&](){
OnParamReset(EParamSource::kRecompile);
});
#endif
#if IPLUG_EDITOR
mMakeGraphicsFunc = [&]() {
return MakeGraphics(*this, PLUG_WIDTH, PLUG_HEIGHT, PLUG_FPS, 1.);
};
mLayoutFunc = [&](IGraphics* pGraphics) {
IRECT b = pGraphics->GetBounds().GetPadded(-20);
IRECT knobs = b.GetFromTop(100.);
IRECT viz = b.GetReducedFromTop(100);
pGraphics->AttachCornerResizer(EUIResizerMode::Scale);
pGraphics->LoadFont("Roboto-Regular", ROBOTO_FN);
for (int i = 0; i < kNumParams; i++) {
pGraphics->AttachControl(new IVKnobControl(knobs.GetGridCell(i, 1, kNumParams), i));
}
pGraphics->AttachPanelBackground(COLOR_GRAY);
pGraphics->AttachControl(new IVScopeControl<2>(viz, "", DEFAULT_STYLE.WithColor(kBG, COLOR_BLACK).WithColor(kFG, COLOR_GREEN)), kCtrlTagScope);
};
#endif
}
#if IPLUG_DSP
void IPlugFaustDSP::ProcessBlock(sample** inputs, sample** outputs, int nFrames)
{
mFaustProcessor.ProcessBlock(inputs, outputs, nFrames);
mScopeSender.ProcessBlock(outputs, nFrames);
}
void IPlugFaustDSP::OnReset()
{
mFaustProcessor.SetSampleRate(GetSampleRate());
}
void IPlugFaustDSP::OnParamChange(int paramIdx)
{
mFaustProcessor.SetParameterValueNormalised(paramIdx, GetParam(paramIdx)->Value());
}
void IPlugFaustDSP::OnIdle()
{
mScopeSender.TransmitData(*this);
}
#endif
|
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/compiler/frontend/bytecode_reader.h"
#include "vm/bit_vector.h"
#include "vm/bootstrap.h"
#include "vm/class_finalizer.h"
#include "vm/code_descriptors.h"
#include "vm/compiler/aot/precompiler.h" // For Obfuscator
#include "vm/compiler/assembler/disassembler_kbc.h"
#include "vm/compiler/frontend/bytecode_scope_builder.h"
#include "vm/constants_kbc.h"
#include "vm/dart_api_impl.h" // For Api::IsFfiEnabled().
#include "vm/dart_entry.h"
#include "vm/debugger.h"
#include "vm/hash.h"
#include "vm/longjump.h"
#include "vm/object_store.h"
#include "vm/reusable_handles.h"
#include "vm/scopes.h"
#include "vm/stack_frame_kbc.h"
#include "vm/timeline.h"
#if !defined(DART_PRECOMPILED_RUNTIME)
#define Z (zone_)
#define H (translation_helper_)
#define I (translation_helper_.isolate())
namespace dart {
DEFINE_FLAG(bool, dump_kernel_bytecode, false, "Dump kernel bytecode");
namespace kernel {
BytecodeMetadataHelper::BytecodeMetadataHelper(KernelReaderHelper* helper,
ActiveClass* active_class)
: MetadataHelper(helper, tag(), /* precompiler_only = */ false),
active_class_(active_class) {}
void BytecodeMetadataHelper::ParseBytecodeFunction(
ParsedFunction* parsed_function) {
TIMELINE_DURATION(Thread::Current(), CompilerVerbose,
"BytecodeMetadataHelper::ParseBytecodeFunction");
const Function& function = parsed_function->function();
ASSERT(function.is_declared_in_bytecode());
BytecodeComponentData bytecode_component(
&Array::Handle(helper_->zone_, GetBytecodeComponent()));
BytecodeReaderHelper bytecode_reader(&H, active_class_, &bytecode_component);
bytecode_reader.ParseBytecodeFunction(parsed_function, function);
}
bool BytecodeMetadataHelper::ReadLibraries() {
TIMELINE_DURATION(Thread::Current(), Compiler,
"BytecodeMetadataHelper::ReadLibraries");
ASSERT(Thread::Current()->IsMutatorThread());
if (translation_helper_.GetBytecodeComponent() == Array::null()) {
return false;
}
BytecodeComponentData bytecode_component(
&Array::Handle(helper_->zone_, GetBytecodeComponent()));
BytecodeReaderHelper bytecode_reader(&H, active_class_, &bytecode_component);
AlternativeReadingScope alt(&bytecode_reader.reader(),
bytecode_component.GetLibraryIndexOffset());
bytecode_reader.ReadLibraryDeclarations(bytecode_component.GetNumLibraries());
return true;
}
void BytecodeMetadataHelper::ReadLibrary(const Library& library) {
TIMELINE_DURATION(Thread::Current(), Compiler,
"BytecodeMetadataHelper::ReadLibrary");
ASSERT(Thread::Current()->IsMutatorThread());
ASSERT(!library.Loaded());
if (translation_helper_.GetBytecodeComponent() == Array::null()) {
return;
}
BytecodeComponentData bytecode_component(
&Array::Handle(helper_->zone_, GetBytecodeComponent()));
BytecodeReaderHelper bytecode_reader(&H, active_class_, &bytecode_component);
AlternativeReadingScope alt(&bytecode_reader.reader(),
bytecode_component.GetLibraryIndexOffset());
bytecode_reader.FindAndReadSpecificLibrary(
library, bytecode_component.GetNumLibraries());
}
bool BytecodeMetadataHelper::FindModifiedLibrariesForHotReload(
BitVector* modified_libs,
bool* is_empty_program,
intptr_t* p_num_classes,
intptr_t* p_num_procedures) {
ASSERT(Thread::Current()->IsMutatorThread());
if (translation_helper_.GetBytecodeComponent() == Array::null()) {
return false;
}
BytecodeComponentData bytecode_component(
&Array::Handle(helper_->zone_, GetBytecodeComponent()));
BytecodeReaderHelper bytecode_reader(&H, active_class_, &bytecode_component);
AlternativeReadingScope alt(&bytecode_reader.reader(),
bytecode_component.GetLibraryIndexOffset());
bytecode_reader.FindModifiedLibrariesForHotReload(
modified_libs, bytecode_component.GetNumLibraries());
if (is_empty_program != nullptr) {
*is_empty_program = (bytecode_component.GetNumLibraries() == 0);
}
if (p_num_classes != nullptr) {
*p_num_classes = bytecode_component.GetNumClasses();
}
if (p_num_procedures != nullptr) {
*p_num_procedures = bytecode_component.GetNumCodes();
}
return true;
}
RawLibrary* BytecodeMetadataHelper::GetMainLibrary() {
const intptr_t md_offset = GetComponentMetadataPayloadOffset();
if (md_offset < 0) {
return Library::null();
}
BytecodeComponentData bytecode_component(
&Array::Handle(helper_->zone_, GetBytecodeComponent()));
const intptr_t main_offset = bytecode_component.GetMainOffset();
if (main_offset == 0) {
return Library::null();
}
BytecodeReaderHelper bytecode_reader(&H, active_class_, &bytecode_component);
AlternativeReadingScope alt(&bytecode_reader.reader(), main_offset);
return bytecode_reader.ReadMain();
}
RawArray* BytecodeMetadataHelper::GetBytecodeComponent() {
RawArray* array = translation_helper_.GetBytecodeComponent();
if (array == Array::null()) {
array = ReadBytecodeComponent();
ASSERT(array != Array::null());
}
return array;
}
RawArray* BytecodeMetadataHelper::ReadBytecodeComponent() {
const intptr_t md_offset = GetComponentMetadataPayloadOffset();
if (md_offset < 0) {
return Array::null();
}
BytecodeReaderHelper component_reader(&H, nullptr, nullptr);
return component_reader.ReadBytecodeComponent(md_offset);
}
BytecodeReaderHelper::BytecodeReaderHelper(
TranslationHelper* translation_helper,
ActiveClass* active_class,
BytecodeComponentData* bytecode_component)
: reader_(translation_helper->metadata_payloads()),
translation_helper_(*translation_helper),
active_class_(active_class),
thread_(translation_helper->thread()),
zone_(translation_helper->zone()),
bytecode_component_(bytecode_component),
scoped_function_(Function::Handle(translation_helper->zone())),
scoped_function_name_(String::Handle(translation_helper->zone())),
scoped_function_class_(Class::Handle(translation_helper->zone())) {}
void BytecodeReaderHelper::ReadCode(const Function& function,
intptr_t code_offset) {
ASSERT(Thread::Current()->IsMutatorThread());
ASSERT(!function.IsImplicitGetterFunction() &&
!function.IsImplicitSetterFunction());
if (code_offset == 0) {
FATAL2("Function %s (kind %s) doesn't have bytecode",
function.ToFullyQualifiedCString(),
Function::KindToCString(function.kind()));
}
AlternativeReadingScope alt(&reader_, code_offset);
// This scope is needed to set active_class_->enclosing_ which is used to
// assign parent function for function types.
ActiveEnclosingFunctionScope active_enclosing_function(active_class_,
&function);
const intptr_t flags = reader_.ReadUInt();
const bool has_exceptions_table =
(flags & Code::kHasExceptionsTableFlag) != 0;
const bool has_source_positions =
(flags & Code::kHasSourcePositionsFlag) != 0;
const bool has_local_variables = (flags & Code::kHasLocalVariablesFlag) != 0;
const bool has_nullable_fields = (flags & Code::kHasNullableFieldsFlag) != 0;
const bool has_closures = (flags & Code::kHasClosuresFlag) != 0;
const bool has_parameters_flags = (flags & Code::kHasParameterFlagsFlag) != 0;
const bool has_forwarding_stub_target =
(flags & Code::kHasForwardingStubTargetFlag) != 0;
const bool has_default_function_type_args =
(flags & Code::kHasDefaultFunctionTypeArgsFlag) != 0;
if (has_parameters_flags) {
intptr_t num_params = reader_.ReadUInt();
ASSERT(num_params ==
function.NumParameters() - function.NumImplicitParameters());
for (intptr_t i = 0; i < num_params; ++i) {
reader_.ReadUInt();
}
}
if (has_forwarding_stub_target) {
reader_.ReadUInt();
}
if (has_default_function_type_args) {
reader_.ReadUInt();
}
intptr_t num_closures = 0;
if (has_closures) {
num_closures = reader_.ReadListLength();
closures_ = &Array::Handle(Z, Array::New(num_closures));
for (intptr_t i = 0; i < num_closures; i++) {
ReadClosureDeclaration(function, i);
}
}
// Create object pool and read pool entries.
const intptr_t obj_count = reader_.ReadListLength();
const ObjectPool& pool = ObjectPool::Handle(Z, ObjectPool::New(obj_count));
ReadConstantPool(function, pool, 0);
// Read bytecode and attach to function.
const Bytecode& bytecode = Bytecode::Handle(Z, ReadBytecode(pool));
function.AttachBytecode(bytecode);
ASSERT(bytecode.GetBinary(Z) == reader_.typed_data()->raw());
ReadExceptionsTable(bytecode, has_exceptions_table);
ReadSourcePositions(bytecode, has_source_positions);
ReadLocalVariables(bytecode, has_local_variables);
if (FLAG_dump_kernel_bytecode) {
KernelBytecodeDisassembler::Disassemble(function);
}
// Initialization of fields with null literal is elided from bytecode.
// Record the corresponding stores if field guards are enabled.
if (has_nullable_fields) {
ASSERT(function.IsGenerativeConstructor());
const intptr_t num_fields = reader_.ReadListLength();
if (I->use_field_guards()) {
Field& field = Field::Handle(Z);
for (intptr_t i = 0; i < num_fields; i++) {
field ^= ReadObject();
field.RecordStore(Object::null_object());
}
} else {
for (intptr_t i = 0; i < num_fields; i++) {
ReadObject();
}
}
}
// Read closures.
if (has_closures) {
Function& closure = Function::Handle(Z);
Bytecode& closure_bytecode = Bytecode::Handle(Z);
for (intptr_t i = 0; i < num_closures; i++) {
closure ^= closures_->At(i);
const intptr_t flags = reader_.ReadUInt();
const bool has_exceptions_table =
(flags & ClosureCode::kHasExceptionsTableFlag) != 0;
const bool has_source_positions =
(flags & ClosureCode::kHasSourcePositionsFlag) != 0;
const bool has_local_variables =
(flags & ClosureCode::kHasLocalVariablesFlag) != 0;
// Read closure bytecode and attach to closure function.
closure_bytecode = ReadBytecode(pool);
closure.AttachBytecode(closure_bytecode);
ASSERT(bytecode.GetBinary(Z) == reader_.typed_data()->raw());
ReadExceptionsTable(closure_bytecode, has_exceptions_table);
ReadSourcePositions(closure_bytecode, has_source_positions);
ReadLocalVariables(closure_bytecode, has_local_variables);
if (FLAG_dump_kernel_bytecode) {
KernelBytecodeDisassembler::Disassemble(closure);
}
#if !defined(PRODUCT)
thread_->isolate()->debugger()->NotifyBytecodeLoaded(closure);
#endif
}
}
#if !defined(PRODUCT)
thread_->isolate()->debugger()->NotifyBytecodeLoaded(function);
#endif
}
static intptr_t IndexFor(Zone* zone,
const Function& function,
const String& name) {
const Bytecode& bc = Bytecode::Handle(zone, function.bytecode());
const ObjectPool& pool = ObjectPool::Handle(zone, bc.object_pool());
const KBCInstr* pc = reinterpret_cast<const KBCInstr*>(bc.PayloadStart());
ASSERT(KernelBytecode::IsEntryOptionalOpcode(pc));
ASSERT(KernelBytecode::DecodeB(pc) ==
function.NumOptionalPositionalParameters());
ASSERT(KernelBytecode::DecodeC(pc) == function.NumOptionalNamedParameters());
pc = KernelBytecode::Next(pc);
const intptr_t num_opt_params = function.NumOptionalParameters();
const intptr_t num_fixed_params = function.num_fixed_parameters();
for (intptr_t i = 0; i < num_opt_params; i++) {
const KBCInstr* load_name = pc;
const KBCInstr* load_value = KernelBytecode::Next(load_name);
pc = KernelBytecode::Next(load_value);
ASSERT(KernelBytecode::IsLoadConstantOpcode(load_name));
ASSERT(KernelBytecode::IsLoadConstantOpcode(load_value));
if (pool.ObjectAt(KernelBytecode::DecodeE(load_name)) == name.raw()) {
return num_fixed_params + i;
}
}
UNREACHABLE();
return -1;
}
RawArray* BytecodeReaderHelper::CreateForwarderChecks(
const Function& function) {
ASSERT(function.kind() != RawFunction::kDynamicInvocationForwarder);
ASSERT(function.is_declared_in_bytecode());
TypeArguments& default_args = TypeArguments::Handle(Z);
if (function.bytecode_offset() != 0) {
AlternativeReadingScope alt(&reader_, function.bytecode_offset());
const intptr_t flags = reader_.ReadUInt();
const bool has_parameters_flags =
(flags & Code::kHasParameterFlagsFlag) != 0;
const bool has_forwarding_stub_target =
(flags & Code::kHasForwardingStubTargetFlag) != 0;
const bool has_default_function_type_args =
(flags & Code::kHasDefaultFunctionTypeArgsFlag) != 0;
if (has_parameters_flags) {
intptr_t num_params = reader_.ReadUInt();
ASSERT(num_params ==
function.NumParameters() - function.NumImplicitParameters());
for (intptr_t i = 0; i < num_params; ++i) {
reader_.ReadUInt();
}
}
if (has_forwarding_stub_target) {
reader_.ReadUInt();
}
if (has_default_function_type_args) {
const intptr_t index = reader_.ReadUInt();
const Bytecode& code = Bytecode::Handle(Z, function.bytecode());
const ObjectPool& pool = ObjectPool::Handle(Z, code.object_pool());
default_args ^= pool.ObjectAt(index);
}
}
auto& name = String::Handle(Z);
auto& check = ParameterTypeCheck::Handle(Z);
auto& checks = GrowableObjectArray::Handle(Z, GrowableObjectArray::New());
checks.Add(function);
checks.Add(default_args);
const auto& type_params =
TypeArguments::Handle(Z, function.type_parameters());
if (!type_params.IsNull()) {
auto& type_param = TypeParameter::Handle(Z);
auto& bound = AbstractType::Handle(Z);
for (intptr_t i = 0, n = type_params.Length(); i < n; ++i) {
type_param ^= type_params.TypeAt(i);
bound = type_param.bound();
if (!bound.IsTopType() && !type_param.IsGenericCovariantImpl()) {
name = type_param.name();
ASSERT(type_param.IsFinalized());
check = ParameterTypeCheck::New();
check.set_param(type_param);
check.set_type_or_bound(bound);
check.set_name(name);
checks.Add(check);
}
}
}
const intptr_t num_params = function.NumParameters();
const intptr_t num_pos_params = function.HasOptionalNamedParameters()
? function.num_fixed_parameters()
: num_params;
BitVector is_covariant(Z, num_params);
BitVector is_generic_covariant_impl(Z, num_params);
ReadParameterCovariance(function, &is_covariant, &is_generic_covariant_impl);
auto& type = AbstractType::Handle(Z);
auto& cache = SubtypeTestCache::Handle(Z);
const bool has_optional_parameters = function.HasOptionalParameters();
for (intptr_t i = function.NumImplicitParameters(); i < num_params; ++i) {
type = function.ParameterTypeAt(i);
if (!type.IsTopType() && !is_generic_covariant_impl.Contains(i) &&
!is_covariant.Contains(i)) {
name = function.ParameterNameAt(i);
intptr_t index;
if (i >= num_pos_params) {
// Named parameter.
index = IndexFor(Z, function, name);
} else if (has_optional_parameters) {
// Fixed or optional parameter.
index = i;
} else {
// Fixed parameter.
index = -kKBCParamEndSlotFromFp - num_params + i;
}
check = ParameterTypeCheck::New();
check.set_index(index);
check.set_type_or_bound(type);
check.set_name(name);
cache = SubtypeTestCache::New();
check.set_cache(cache);
checks.Add(check);
}
}
return Array::MakeFixedLength(checks);
}
void BytecodeReaderHelper::ReadClosureDeclaration(const Function& function,
intptr_t closureIndex) {
// Closure flags, must be in sync with ClosureDeclaration constants in
// pkg/vm/lib/bytecode/declarations.dart.
const int kHasOptionalPositionalParamsFlag = 1 << 0;
const int kHasOptionalNamedParamsFlag = 1 << 1;
const int kHasTypeParamsFlag = 1 << 2;
const int kHasSourcePositionsFlag = 1 << 3;
const int kIsAsyncFlag = 1 << 4;
const int kIsAsyncStarFlag = 1 << 5;
const int kIsSyncStarFlag = 1 << 6;
const int kIsDebuggableFlag = 1 << 7;
const int kHasAttributesFlag = 1 << 8;
const intptr_t flags = reader_.ReadUInt();
Object& parent = Object::Handle(Z, ReadObject());
if (!parent.IsFunction()) {
ASSERT(parent.IsField());
ASSERT(function.kind() == RawFunction::kFieldInitializer);
// Closure in a static field initializer, so use current function as parent.
parent = function.raw();
}
String& name = String::CheckedHandle(Z, ReadObject());
ASSERT(name.IsSymbol());
TokenPosition position = TokenPosition::kNoSource;
TokenPosition end_position = TokenPosition::kNoSource;
if ((flags & kHasSourcePositionsFlag) != 0) {
position = reader_.ReadPosition();
end_position = reader_.ReadPosition();
}
const Function& closure = Function::Handle(
Z, Function::NewClosureFunction(name, Function::Cast(parent), position));
closure.set_is_declared_in_bytecode(true);
closure.set_end_token_pos(end_position);
if ((flags & kIsSyncStarFlag) != 0) {
closure.set_modifier(RawFunction::kSyncGen);
} else if ((flags & kIsAsyncFlag) != 0) {
closure.set_modifier(RawFunction::kAsync);
closure.set_is_inlinable(!FLAG_causal_async_stacks);
} else if ((flags & kIsAsyncStarFlag) != 0) {
closure.set_modifier(RawFunction::kAsyncGen);
closure.set_is_inlinable(!FLAG_causal_async_stacks);
}
if (Function::Cast(parent).IsAsyncOrGenerator()) {
closure.set_is_generated_body(true);
}
closure.set_is_debuggable((flags & kIsDebuggableFlag) != 0);
closures_->SetAt(closureIndex, closure);
Type& signature_type = Type::Handle(
Z, ReadFunctionSignature(closure,
(flags & kHasOptionalPositionalParamsFlag) != 0,
(flags & kHasOptionalNamedParamsFlag) != 0,
(flags & kHasTypeParamsFlag) != 0,
/* has_positional_param_names = */ true,
Nullability::kNonNullable));
closure.SetSignatureType(signature_type);
if ((flags & kHasAttributesFlag) != 0) {
ReadAttributes(closure);
}
I->AddClosureFunction(closure);
}
static bool IsNonCanonical(const AbstractType& type) {
return type.IsTypeRef() || (type.IsType() && !type.IsCanonical());
}
static bool HasNonCanonicalTypes(Zone* zone, const Function& func) {
auto& type = AbstractType::Handle(zone);
for (intptr_t i = 0; i < func.NumParameters(); ++i) {
type = func.ParameterTypeAt(i);
if (IsNonCanonical(type)) {
return true;
}
}
type = func.result_type();
if (IsNonCanonical(type)) {
return true;
}
const auto& type_params = TypeArguments::Handle(zone, func.type_parameters());
if (!type_params.IsNull()) {
for (intptr_t i = 0; i < type_params.Length(); ++i) {
type = type_params.TypeAt(i);
type = TypeParameter::Cast(type).bound();
if (IsNonCanonical(type)) {
return true;
}
}
}
return false;
}
RawType* BytecodeReaderHelper::ReadFunctionSignature(
const Function& func,
bool has_optional_positional_params,
bool has_optional_named_params,
bool has_type_params,
bool has_positional_param_names,
Nullability nullability) {
FunctionTypeScope function_type_scope(this);
if (has_type_params) {
ReadTypeParametersDeclaration(Class::Handle(Z), func);
}
const intptr_t kImplicitClosureParam = 1;
const intptr_t num_params = kImplicitClosureParam + reader_.ReadUInt();
intptr_t num_required_params = num_params;
if (has_optional_positional_params || has_optional_named_params) {
num_required_params = kImplicitClosureParam + reader_.ReadUInt();
}
func.set_num_fixed_parameters(num_required_params);
func.SetNumOptionalParameters(num_params - num_required_params,
!has_optional_named_params);
const Array& parameter_types =
Array::Handle(Z, Array::New(num_params, Heap::kOld));
func.set_parameter_types(parameter_types);
const Array& parameter_names =
Array::Handle(Z, Array::New(num_params, Heap::kOld));
func.set_parameter_names(parameter_names);
intptr_t i = 0;
parameter_types.SetAt(i, AbstractType::dynamic_type());
parameter_names.SetAt(i, Symbols::ClosureParameter());
++i;
AbstractType& type = AbstractType::Handle(Z);
String& name = String::Handle(Z);
for (; i < num_params; ++i) {
if (has_positional_param_names ||
(has_optional_named_params && (i >= num_required_params))) {
name ^= ReadObject();
} else {
name = Symbols::NotNamed().raw();
}
parameter_names.SetAt(i, name);
type ^= ReadObject();
parameter_types.SetAt(i, type);
}
type ^= ReadObject();
func.set_result_type(type);
// Finalize function type.
type = func.SignatureType(nullability);
ClassFinalizer::FinalizationKind finalization = ClassFinalizer::kCanonicalize;
if (pending_recursive_types_ != nullptr && HasNonCanonicalTypes(Z, func)) {
// This function type is a part of recursive type. Avoid canonicalization
// as not all TypeRef objects are filled up at this point.
finalization = ClassFinalizer::kFinalize;
}
type =
ClassFinalizer::FinalizeType(*(active_class_->klass), type, finalization);
return Type::Cast(type).raw();
}
void BytecodeReaderHelper::ReadTypeParametersDeclaration(
const Class& parameterized_class,
const Function& parameterized_function) {
ASSERT(parameterized_class.IsNull() != parameterized_function.IsNull());
const intptr_t num_type_params = reader_.ReadUInt();
ASSERT(num_type_params > 0);
intptr_t offset;
if (!parameterized_class.IsNull()) {
offset = parameterized_class.NumTypeArguments() - num_type_params;
} else {
offset = parameterized_function.NumParentTypeParameters();
}
// First setup the type parameters, so if any of the following code uses it
// (in a recursive way) we're fine.
//
// Step a) Create array of [TypeParameter] objects (without bound).
const TypeArguments& type_parameters =
TypeArguments::Handle(Z, TypeArguments::New(num_type_params));
String& name = String::Handle(Z);
TypeParameter& parameter = TypeParameter::Handle(Z);
AbstractType& bound = AbstractType::Handle(Z);
for (intptr_t i = 0; i < num_type_params; ++i) {
name ^= ReadObject();
ASSERT(name.IsSymbol());
parameter = TypeParameter::New(
parameterized_class, parameterized_function, i, name, bound,
/* is_generic_covariant_impl = */ false, TokenPosition::kNoSource);
parameter.set_index(offset + i);
parameter.SetIsFinalized();
type_parameters.SetTypeAt(i, parameter);
}
if (!parameterized_class.IsNull()) {
parameterized_class.set_type_parameters(type_parameters);
} else if (!parameterized_function.IsFactory()) {
// Do not set type parameters for factories, as VM uses class type
// parameters instead.
parameterized_function.set_type_parameters(type_parameters);
if (parameterized_function.IsSignatureFunction()) {
if (function_type_type_parameters_ == nullptr) {
function_type_type_parameters_ = &type_parameters;
} else {
function_type_type_parameters_ = &TypeArguments::Handle(
Z, function_type_type_parameters_->ConcatenateTypeParameters(
Z, type_parameters));
}
} else {
ASSERT(function_type_type_parameters_ == nullptr);
}
}
// Step b) Fill in the bounds of all [TypeParameter]s.
for (intptr_t i = 0; i < num_type_params; ++i) {
parameter ^= type_parameters.TypeAt(i);
bound ^= ReadObject();
// Convert dynamic to Object in bounds of type parameters so
// they are equivalent when doing subtype checks for function types.
// TODO(https://github.com/dart-lang/language/issues/495): revise this
// when function subtyping is fixed.
if (bound.IsDynamicType()) {
bound = I->object_store()->object_type();
}
parameter.set_bound(bound);
}
}
intptr_t BytecodeReaderHelper::ReadConstantPool(const Function& function,
const ObjectPool& pool,
intptr_t start_index) {
TIMELINE_DURATION(Thread::Current(), CompilerVerbose,
"BytecodeReaderHelper::ReadConstantPool");
// These enums and the code below reading the constant pool from kernel must
// be kept in sync with pkg/vm/lib/bytecode/constant_pool.dart.
enum ConstantPoolTag {
kInvalid,
kUnused1,
kUnused2,
kUnused3,
kUnused4,
kUnused5,
kUnused6,
kUnused6a,
kUnused7,
kStaticField,
kInstanceField,
kClass,
kTypeArgumentsField,
kUnused8,
kType,
kUnused9,
kUnused10,
kUnused11,
kUnused12,
kClosureFunction,
kEndClosureFunctionScope,
kNativeEntry,
kSubtypeTestCache,
kUnused13,
kEmptyTypeArguments,
kUnused14,
kUnused15,
kObjectRef,
kDirectCall,
kInterfaceCall,
kInstantiatedInterfaceCall,
kDynamicCall,
kDirectCallViaDynamicForwarder,
};
Object& obj = Object::Handle(Z);
Object& elem = Object::Handle(Z);
Field& field = Field::Handle(Z);
Class& cls = Class::Handle(Z);
String& name = String::Handle(Z);
const intptr_t obj_count = pool.Length();
for (intptr_t i = start_index; i < obj_count; ++i) {
const intptr_t tag = reader_.ReadTag();
switch (tag) {
case ConstantPoolTag::kInvalid:
UNREACHABLE();
case ConstantPoolTag::kStaticField:
obj = ReadObject();
ASSERT(obj.IsField());
break;
case ConstantPoolTag::kInstanceField:
field ^= ReadObject();
// InstanceField constant occupies 2 entries.
// The first entry is used for field offset.
obj = Smi::New(field.Offset() / kWordSize);
pool.SetTypeAt(i, ObjectPool::EntryType::kTaggedObject,
ObjectPool::Patchability::kNotPatchable);
pool.SetObjectAt(i, obj);
++i;
ASSERT(i < obj_count);
// The second entry is used for field object.
obj = field.raw();
break;
case ConstantPoolTag::kClass:
obj = ReadObject();
ASSERT(obj.IsClass());
break;
case ConstantPoolTag::kTypeArgumentsField:
cls ^= ReadObject();
obj = Smi::New(cls.type_arguments_field_offset() / kWordSize);
break;
case ConstantPoolTag::kType:
obj = ReadObject();
ASSERT(obj.IsAbstractType());
break;
case ConstantPoolTag::kClosureFunction: {
intptr_t closure_index = reader_.ReadUInt();
obj = closures_->At(closure_index);
ASSERT(obj.IsFunction());
// Set current entry.
pool.SetTypeAt(i, ObjectPool::EntryType::kTaggedObject,
ObjectPool::Patchability::kNotPatchable);
pool.SetObjectAt(i, obj);
// This scope is needed to set active_class_->enclosing_ which is used
// to assign parent function for function types.
ActiveEnclosingFunctionScope active_enclosing_function(
active_class_, &Function::Cast(obj));
// Read constant pool until corresponding EndClosureFunctionScope.
i = ReadConstantPool(function, pool, i + 1);
// Proceed with the rest of entries.
continue;
}
case ConstantPoolTag::kEndClosureFunctionScope: {
// EndClosureFunctionScope entry is not used and set to null.
obj = Object::null();
pool.SetTypeAt(i, ObjectPool::EntryType::kTaggedObject,
ObjectPool::Patchability::kNotPatchable);
pool.SetObjectAt(i, obj);
return i;
}
case ConstantPoolTag::kNativeEntry: {
name = ReadString();
obj = NativeEntry(function, name);
pool.SetTypeAt(i, ObjectPool::EntryType::kNativeEntryData,
ObjectPool::Patchability::kNotPatchable);
pool.SetObjectAt(i, obj);
continue;
}
case ConstantPoolTag::kSubtypeTestCache: {
obj = SubtypeTestCache::New();
} break;
case ConstantPoolTag::kEmptyTypeArguments:
obj = Object::empty_type_arguments().raw();
break;
case ConstantPoolTag::kObjectRef:
obj = ReadObject();
break;
case ConstantPoolTag::kDirectCall: {
// DirectCall constant occupies 2 entries.
// The first entry is used for target function.
obj = ReadObject();
ASSERT(obj.IsFunction());
pool.SetTypeAt(i, ObjectPool::EntryType::kTaggedObject,
ObjectPool::Patchability::kNotPatchable);
pool.SetObjectAt(i, obj);
++i;
ASSERT(i < obj_count);
// The second entry is used for arguments descriptor.
obj = ReadObject();
} break;
case ConstantPoolTag::kInterfaceCall: {
elem = ReadObject();
ASSERT(elem.IsFunction());
// InterfaceCall constant occupies 2 entries.
// The first entry is used for interface target.
pool.SetTypeAt(i, ObjectPool::EntryType::kTaggedObject,
ObjectPool::Patchability::kNotPatchable);
pool.SetObjectAt(i, elem);
++i;
ASSERT(i < obj_count);
// The second entry is used for arguments descriptor.
obj = ReadObject();
} break;
case ConstantPoolTag::kInstantiatedInterfaceCall: {
elem = ReadObject();
ASSERT(elem.IsFunction());
// InstantiatedInterfaceCall constant occupies 3 entries:
// 1) Interface target.
pool.SetTypeAt(i, ObjectPool::EntryType::kTaggedObject,
ObjectPool::Patchability::kNotPatchable);
pool.SetObjectAt(i, elem);
++i;
ASSERT(i < obj_count);
// 2) Arguments descriptor.
obj = ReadObject();
pool.SetTypeAt(i, ObjectPool::EntryType::kTaggedObject,
ObjectPool::Patchability::kNotPatchable);
pool.SetObjectAt(i, obj);
++i;
ASSERT(i < obj_count);
// 3) Static receiver type.
obj = ReadObject();
} break;
case ConstantPoolTag::kDynamicCall: {
name ^= ReadObject();
ASSERT(name.IsSymbol());
// Do not mangle == or call:
// * operator == takes an Object so it is either not checked or
// checked at the entry because the parameter is marked covariant,
// neither of those cases require a dynamic invocation forwarder;
// * we assume that all closures are entered in a checked way.
if (!Field::IsGetterName(name) && I->should_emit_strong_mode_checks() &&
(name.raw() != Symbols::EqualOperator().raw()) &&
(name.raw() != Symbols::Call().raw())) {
name = Function::CreateDynamicInvocationForwarderName(name);
}
// DynamicCall constant occupies 2 entries: selector and arguments
// descriptor.
pool.SetTypeAt(i, ObjectPool::EntryType::kTaggedObject,
ObjectPool::Patchability::kNotPatchable);
pool.SetObjectAt(i, name);
++i;
ASSERT(i < obj_count);
// The second entry is used for arguments descriptor.
obj = ReadObject();
} break;
case ConstantPoolTag::kDirectCallViaDynamicForwarder: {
// DirectCallViaDynamicForwarder constant occupies 2 entries.
// The first entry is used for target function.
obj = ReadObject();
ASSERT(obj.IsFunction());
name = Function::Cast(obj).name();
name = Function::CreateDynamicInvocationForwarderName(name);
obj = Function::Cast(obj).GetDynamicInvocationForwarder(name);
pool.SetTypeAt(i, ObjectPool::EntryType::kTaggedObject,
ObjectPool::Patchability::kNotPatchable);
pool.SetObjectAt(i, obj);
++i;
ASSERT(i < obj_count);
// The second entry is used for arguments descriptor.
obj = ReadObject();
} break;
default:
UNREACHABLE();
}
pool.SetTypeAt(i, ObjectPool::EntryType::kTaggedObject,
ObjectPool::Patchability::kNotPatchable);
pool.SetObjectAt(i, obj);
}
return obj_count - 1;
}
RawBytecode* BytecodeReaderHelper::ReadBytecode(const ObjectPool& pool) {
#if defined(SUPPORT_TIMELINE)
TIMELINE_DURATION(Thread::Current(), CompilerVerbose,
"BytecodeReaderHelper::ReadBytecode");
#endif // defined(SUPPORT_TIMELINE)
const intptr_t size = reader_.ReadUInt();
const intptr_t offset = reader_.offset();
const uint8_t* data = reader_.BufferAt(offset);
reader_.set_offset(offset + size);
// Create and return bytecode object.
return Bytecode::New(reinterpret_cast<uword>(data), size, offset, pool);
}
void BytecodeReaderHelper::ReadExceptionsTable(const Bytecode& bytecode,
bool has_exceptions_table) {
#if defined(SUPPORT_TIMELINE)
TIMELINE_DURATION(Thread::Current(), CompilerVerbose,
"BytecodeReaderHelper::ReadExceptionsTable");
#endif
const intptr_t try_block_count =
has_exceptions_table ? reader_.ReadListLength() : 0;
if (try_block_count > 0) {
const ObjectPool& pool = ObjectPool::Handle(Z, bytecode.object_pool());
AbstractType& handler_type = AbstractType::Handle(Z);
Array& handler_types = Array::Handle(Z);
DescriptorList* pc_descriptors_list = new (Z) DescriptorList(64);
ExceptionHandlerList* exception_handlers_list =
new (Z) ExceptionHandlerList();
// Encoding of ExceptionsTable is described in
// pkg/vm/lib/bytecode/exceptions.dart.
for (intptr_t try_index = 0; try_index < try_block_count; try_index++) {
intptr_t outer_try_index_plus1 = reader_.ReadUInt();
intptr_t outer_try_index = outer_try_index_plus1 - 1;
// PcDescriptors are expressed in terms of return addresses.
intptr_t start_pc =
KernelBytecode::BytecodePcToOffset(reader_.ReadUInt(),
/* is_return_address = */ true);
intptr_t end_pc =
KernelBytecode::BytecodePcToOffset(reader_.ReadUInt(),
/* is_return_address = */ true);
intptr_t handler_pc =
KernelBytecode::BytecodePcToOffset(reader_.ReadUInt(),
/* is_return_address = */ false);
uint8_t flags = reader_.ReadByte();
const uint8_t kFlagNeedsStackTrace = 1 << 0;
const uint8_t kFlagIsSynthetic = 1 << 1;
const bool needs_stacktrace = (flags & kFlagNeedsStackTrace) != 0;
const bool is_generated = (flags & kFlagIsSynthetic) != 0;
intptr_t type_count = reader_.ReadListLength();
ASSERT(type_count > 0);
handler_types = Array::New(type_count, Heap::kOld);
for (intptr_t i = 0; i < type_count; i++) {
intptr_t type_index = reader_.ReadUInt();
ASSERT(type_index < pool.Length());
handler_type ^= pool.ObjectAt(type_index);
handler_types.SetAt(i, handler_type);
}
pc_descriptors_list->AddDescriptor(RawPcDescriptors::kOther, start_pc,
DeoptId::kNone,
TokenPosition::kNoSource, try_index,
RawPcDescriptors::kInvalidYieldIndex);
pc_descriptors_list->AddDescriptor(RawPcDescriptors::kOther, end_pc,
DeoptId::kNone,
TokenPosition::kNoSource, try_index,
RawPcDescriptors::kInvalidYieldIndex);
// The exception handler keeps a zone handle of the types array, rather
// than a raw pointer. Do not share the handle across iterations to avoid
// clobbering the array.
exception_handlers_list->AddHandler(
try_index, outer_try_index, handler_pc, is_generated,
Array::ZoneHandle(Z, handler_types.raw()), needs_stacktrace);
}
const PcDescriptors& descriptors = PcDescriptors::Handle(
Z, pc_descriptors_list->FinalizePcDescriptors(bytecode.PayloadStart()));
bytecode.set_pc_descriptors(descriptors);
const ExceptionHandlers& handlers = ExceptionHandlers::Handle(
Z, exception_handlers_list->FinalizeExceptionHandlers(
bytecode.PayloadStart()));
bytecode.set_exception_handlers(handlers);
} else {
bytecode.set_pc_descriptors(Object::empty_descriptors());
bytecode.set_exception_handlers(Object::empty_exception_handlers());
}
}
void BytecodeReaderHelper::ReadSourcePositions(const Bytecode& bytecode,
bool has_source_positions) {
if (!has_source_positions) {
return;
}
intptr_t offset = reader_.ReadUInt();
bytecode.set_source_positions_binary_offset(
bytecode_component_->GetSourcePositionsOffset() + offset);
}
void BytecodeReaderHelper::ReadLocalVariables(const Bytecode& bytecode,
bool has_local_variables) {
if (!has_local_variables) {
return;
}
const intptr_t offset = reader_.ReadUInt();
bytecode.set_local_variables_binary_offset(
bytecode_component_->GetLocalVariablesOffset() + offset);
}
RawTypedData* BytecodeReaderHelper::NativeEntry(const Function& function,
const String& external_name) {
MethodRecognizer::Kind kind = function.recognized_kind();
// This list of recognized methods must be kept in sync with the list of
// methods handled specially by the NativeCall bytecode in the interpreter.
switch (kind) {
case MethodRecognizer::kObjectEquals:
case MethodRecognizer::kStringBaseLength:
case MethodRecognizer::kStringBaseIsEmpty:
case MethodRecognizer::kGrowableArrayLength:
case MethodRecognizer::kObjectArrayLength:
case MethodRecognizer::kImmutableArrayLength:
case MethodRecognizer::kTypedListLength:
case MethodRecognizer::kTypedListViewLength:
case MethodRecognizer::kByteDataViewLength:
case MethodRecognizer::kByteDataViewOffsetInBytes:
case MethodRecognizer::kTypedDataViewOffsetInBytes:
case MethodRecognizer::kByteDataViewTypedData:
case MethodRecognizer::kTypedDataViewTypedData:
case MethodRecognizer::kClassIDgetID:
case MethodRecognizer::kGrowableArrayCapacity:
case MethodRecognizer::kListFactory:
case MethodRecognizer::kObjectArrayAllocate:
case MethodRecognizer::kLinkedHashMap_getIndex:
case MethodRecognizer::kLinkedHashMap_setIndex:
case MethodRecognizer::kLinkedHashMap_getData:
case MethodRecognizer::kLinkedHashMap_setData:
case MethodRecognizer::kLinkedHashMap_getHashMask:
case MethodRecognizer::kLinkedHashMap_setHashMask:
case MethodRecognizer::kLinkedHashMap_getUsedData:
case MethodRecognizer::kLinkedHashMap_setUsedData:
case MethodRecognizer::kLinkedHashMap_getDeletedKeys:
case MethodRecognizer::kLinkedHashMap_setDeletedKeys:
case MethodRecognizer::kFfiAbi:
break;
case MethodRecognizer::kAsyncStackTraceHelper:
// If causal async stacks are disabled the interpreter.cc will handle this
// native call specially.
if (!FLAG_causal_async_stacks) {
break;
}
FALL_THROUGH;
default:
kind = MethodRecognizer::kUnknown;
}
NativeFunctionWrapper trampoline = NULL;
NativeFunction native_function = NULL;
intptr_t argc_tag = 0;
if (kind == MethodRecognizer::kUnknown) {
if (!FLAG_link_natives_lazily) {
const Class& cls = Class::Handle(Z, function.Owner());
const Library& library = Library::Handle(Z, cls.library());
Dart_NativeEntryResolver resolver = library.native_entry_resolver();
const bool is_bootstrap_native = Bootstrap::IsBootstrapResolver(resolver);
const int num_params =
NativeArguments::ParameterCountForResolution(function);
bool is_auto_scope = true;
native_function = NativeEntry::ResolveNative(library, external_name,
num_params, &is_auto_scope);
if (native_function == nullptr) {
Report::MessageF(Report::kError, Script::Handle(function.script()),
function.token_pos(), Report::AtLocation,
"native function '%s' (%" Pd
" arguments) cannot be found",
external_name.ToCString(), function.NumParameters());
}
if (is_bootstrap_native) {
trampoline = &NativeEntry::BootstrapNativeCallWrapper;
} else if (is_auto_scope) {
trampoline = &NativeEntry::AutoScopeNativeCallWrapper;
} else {
trampoline = &NativeEntry::NoScopeNativeCallWrapper;
}
}
argc_tag = NativeArguments::ComputeArgcTag(function);
}
return NativeEntryData::New(kind, trampoline, native_function, argc_tag);
}
RawArray* BytecodeReaderHelper::ReadBytecodeComponent(intptr_t md_offset) {
ASSERT(Thread::Current()->IsMutatorThread());
AlternativeReadingScope alt(&reader_, md_offset);
const intptr_t start_offset = reader_.offset();
intptr_t magic = reader_.ReadUInt32();
if (magic != KernelBytecode::kMagicValue) {
FATAL1("Unexpected Dart bytecode magic %" Px, magic);
}
const intptr_t version = reader_.ReadUInt32();
if ((version < KernelBytecode::kMinSupportedBytecodeFormatVersion) ||
(version > KernelBytecode::kMaxSupportedBytecodeFormatVersion)) {
FATAL3("Unsupported Dart bytecode format version %" Pd
". "
"This version of Dart VM supports bytecode format versions from %" Pd
" to %" Pd ".",
version, KernelBytecode::kMinSupportedBytecodeFormatVersion,
KernelBytecode::kMaxSupportedBytecodeFormatVersion);
}
reader_.ReadUInt32(); // Skip stringTable.numItems
const intptr_t string_table_offset = start_offset + reader_.ReadUInt32();
reader_.ReadUInt32(); // Skip objectTable.numItems
const intptr_t object_table_offset = start_offset + reader_.ReadUInt32();
reader_.ReadUInt32(); // Skip main.numItems
const intptr_t main_offset = start_offset + reader_.ReadUInt32();
const intptr_t num_libraries = reader_.ReadUInt32();
const intptr_t library_index_offset = start_offset + reader_.ReadUInt32();
reader_.ReadUInt32(); // Skip libraries.numItems
const intptr_t libraries_offset = start_offset + reader_.ReadUInt32();
const intptr_t num_classes = reader_.ReadUInt32();
const intptr_t classes_offset = start_offset + reader_.ReadUInt32();
reader_.ReadUInt32(); // Skip members.numItems
const intptr_t members_offset = start_offset + reader_.ReadUInt32();
const intptr_t num_codes = reader_.ReadUInt32();
const intptr_t codes_offset = start_offset + reader_.ReadUInt32();
reader_.ReadUInt32(); // Skip sourcePositions.numItems
const intptr_t source_positions_offset = start_offset + reader_.ReadUInt32();
reader_.ReadUInt32(); // Skip sourceFiles.numItems
const intptr_t source_files_offset = start_offset + reader_.ReadUInt32();
reader_.ReadUInt32(); // Skip lineStarts.numItems
const intptr_t line_starts_offset = start_offset + reader_.ReadUInt32();
reader_.ReadUInt32(); // Skip localVariables.numItems
const intptr_t local_variables_offset = start_offset + reader_.ReadUInt32();
reader_.ReadUInt32(); // Skip annotations.numItems
const intptr_t annotations_offset = start_offset + reader_.ReadUInt32();
intptr_t num_protected_names = 0;
intptr_t protected_names_offset = 0;
static_assert(KernelBytecode::kMinSupportedBytecodeFormatVersion < 23,
"Cleanup condition");
if (version >= 23) {
num_protected_names = reader_.ReadUInt32();
protected_names_offset = start_offset + reader_.ReadUInt32();
}
// Read header of string table.
reader_.set_offset(string_table_offset);
const intptr_t num_one_byte_strings = reader_.ReadUInt32();
const intptr_t num_two_byte_strings = reader_.ReadUInt32();
const intptr_t strings_contents_offset =
reader_.offset() + (num_one_byte_strings + num_two_byte_strings) * 4;
// Read header of object table.
reader_.set_offset(object_table_offset);
const intptr_t num_objects = reader_.ReadUInt();
const intptr_t objects_size = reader_.ReadUInt();
// Skip over contents of objects.
const intptr_t objects_contents_offset = reader_.offset();
const intptr_t object_offsets_offset = objects_contents_offset + objects_size;
reader_.set_offset(object_offsets_offset);
auto& bytecode_component_array = Array::Handle(
Z,
BytecodeComponentData::New(
Z, version, num_objects, string_table_offset, strings_contents_offset,
object_offsets_offset, objects_contents_offset, main_offset,
num_libraries, library_index_offset, libraries_offset, num_classes,
classes_offset, members_offset, num_codes, codes_offset,
source_positions_offset, source_files_offset, line_starts_offset,
local_variables_offset, annotations_offset, Heap::kOld));
BytecodeComponentData bytecode_component(&bytecode_component_array);
// Read object offsets.
Smi& offs = Smi::Handle(Z);
for (intptr_t i = 0; i < num_objects; ++i) {
offs = Smi::New(reader_.ReadUInt());
bytecode_component.SetObject(i, offs);
}
// Read protected names.
if (I->obfuscate() && (num_protected_names > 0)) {
bytecode_component_ = &bytecode_component;
reader_.set_offset(protected_names_offset);
Obfuscator obfuscator(thread_, Object::null_string());
auto& name = String::Handle(Z);
for (intptr_t i = 0; i < num_protected_names; ++i) {
name = ReadString();
obfuscator.PreventRenaming(name);
}
bytecode_component_ = nullptr;
}
H.SetBytecodeComponent(bytecode_component_array);
return bytecode_component_array.raw();
}
void BytecodeReaderHelper::ResetObjects() {
reader_.set_offset(bytecode_component_->GetObjectOffsetsOffset());
const intptr_t num_objects = bytecode_component_->GetNumObjects();
// Read object offsets.
Smi& offs = Smi::Handle(Z);
for (intptr_t i = 0; i < num_objects; ++i) {
offs = Smi::New(reader_.ReadUInt());
bytecode_component_->SetObject(i, offs);
}
}
RawObject* BytecodeReaderHelper::ReadObject() {
uint32_t header = reader_.ReadUInt();
if ((header & kReferenceBit) != 0) {
intptr_t index = header >> kIndexShift;
if (index == 0) {
return Object::null();
}
RawObject* obj = bytecode_component_->GetObject(index);
if (obj->IsHeapObject()) {
return obj;
}
// Object is not loaded yet.
intptr_t offset = bytecode_component_->GetObjectsContentsOffset() +
Smi::Value(Smi::RawCast(obj));
AlternativeReadingScope alt(&reader_, offset);
header = reader_.ReadUInt();
obj = ReadObjectContents(header);
ASSERT(obj->IsHeapObject());
{
REUSABLE_OBJECT_HANDLESCOPE(thread_);
Object& obj_handle = thread_->ObjectHandle();
obj_handle = obj;
bytecode_component_->SetObject(index, obj_handle);
}
return obj;
}
return ReadObjectContents(header);
}
RawString* BytecodeReaderHelper::ConstructorName(const Class& cls,
const String& name) {
GrowableHandlePtrArray<const String> pieces(Z, 3);
pieces.Add(String::Handle(Z, cls.Name()));
pieces.Add(Symbols::Dot());
pieces.Add(name);
return Symbols::FromConcatAll(thread_, pieces);
}
RawObject* BytecodeReaderHelper::ReadObjectContents(uint32_t header) {
ASSERT(((header & kReferenceBit) == 0));
// Must be in sync with enum ObjectKind in
// pkg/vm/lib/bytecode/object_table.dart.
enum ObjectKind {
kInvalid,
kLibrary,
kClass,
kMember,
kClosure,
kUnused1,
kUnused2,
kUnused3,
kUnused4,
kName,
kTypeArguments,
kUnused5,
kConstObject,
kArgDesc,
kScript,
kType,
};
// Member flags, must be in sync with _MemberHandle constants in
// pkg/vm/lib/bytecode/object_table.dart.
const intptr_t kFlagIsField = kFlagBit0;
const intptr_t kFlagIsConstructor = kFlagBit1;
// ArgDesc flags, must be in sync with _ArgDescHandle constants in
// pkg/vm/lib/bytecode/object_table.dart.
const int kFlagHasNamedArgs = kFlagBit0;
const int kFlagHasTypeArgs = kFlagBit1;
// Script flags, must be in sync with _ScriptHandle constants in
// pkg/vm/lib/bytecode/object_table.dart.
const int kFlagHasSourceFile = kFlagBit0;
// Name flags, must be in sync with _NameHandle constants in
// pkg/vm/lib/bytecode/object_table.dart.
const intptr_t kFlagIsPublic = kFlagBit0;
const intptr_t kind = (header >> kKindShift) & kKindMask;
const intptr_t flags = header & kFlagsMask;
switch (kind) {
case kInvalid:
UNREACHABLE();
break;
case kLibrary: {
String& uri = String::CheckedHandle(Z, ReadObject());
RawLibrary* library = Library::LookupLibrary(thread_, uri);
if (library == Library::null()) {
// We do not register expression evaluation libraries with the VM:
// The expression evaluation functions should be GC-able as soon as
// they are not reachable anymore and we never look them up by name.
if (uri.raw() == Symbols::EvalSourceUri().raw()) {
ASSERT(expression_evaluation_library_ != nullptr);
return expression_evaluation_library_->raw();
}
#if !defined(PRODUCT)
ASSERT(Isolate::Current()->HasAttemptedReload());
const String& msg = String::Handle(
Z,
String::NewFormatted("Unable to find library %s", uri.ToCString()));
Report::LongJump(LanguageError::Handle(Z, LanguageError::New(msg)));
#else
FATAL1("Unable to find library %s", uri.ToCString());
#endif
}
return library;
}
case kClass: {
const Library& library = Library::CheckedHandle(Z, ReadObject());
const String& class_name = String::CheckedHandle(Z, ReadObject());
if (class_name.raw() == Symbols::Empty().raw()) {
NoSafepointScope no_safepoint_scope(thread_);
RawClass* cls = library.toplevel_class();
if (cls == Class::null()) {
FATAL1("Unable to find toplevel class %s", library.ToCString());
}
return cls;
}
RawClass* cls = library.LookupLocalClass(class_name);
if (cls == Class::null()) {
if (IsExpressionEvaluationLibrary(library)) {
return H.GetExpressionEvaluationRealClass();
}
#if !defined(PRODUCT)
ASSERT(Isolate::Current()->HasAttemptedReload());
const String& msg = String::Handle(
Z,
String::NewFormatted("Unable to find class %s in %s",
class_name.ToCString(), library.ToCString()));
Report::LongJump(LanguageError::Handle(Z, LanguageError::New(msg)));
#else
FATAL2("Unable to find class %s in %s", class_name.ToCString(),
library.ToCString());
#endif
}
return cls;
}
case kMember: {
const Class& cls = Class::CheckedHandle(Z, ReadObject());
String& name = String::CheckedHandle(Z, ReadObject());
if ((flags & kFlagIsField) != 0) {
RawField* field = cls.LookupField(name);
if (field == Field::null()) {
#if !defined(PRODUCT)
ASSERT(Isolate::Current()->HasAttemptedReload());
const String& msg = String::Handle(
Z, String::NewFormatted("Unable to find field %s in %s",
name.ToCString(), cls.ToCString()));
Report::LongJump(LanguageError::Handle(Z, LanguageError::New(msg)));
#else
FATAL2("Unable to find field %s in %s", name.ToCString(),
cls.ToCString());
#endif
}
return field;
} else {
if ((flags & kFlagIsConstructor) != 0) {
name = ConstructorName(cls, name);
}
ASSERT(!name.IsNull() && name.IsSymbol());
if (name.raw() == scoped_function_name_.raw() &&
cls.raw() == scoped_function_class_.raw()) {
return scoped_function_.raw();
}
RawFunction* function = cls.LookupFunction(name);
if (function == Function::null()) {
// When requesting a getter, also return method extractors.
if (Field::IsGetterName(name)) {
String& method_name =
String::Handle(Z, Field::NameFromGetter(name));
function = cls.LookupFunction(method_name);
if (function != Function::null()) {
function =
Function::Handle(Z, function).CreateMethodExtractor(name);
if (function != Function::null()) {
return function;
}
}
}
#if !defined(PRODUCT)
ASSERT(Isolate::Current()->HasAttemptedReload());
const String& msg = String::Handle(
Z, String::NewFormatted("Unable to find function %s in %s",
name.ToCString(), cls.ToCString()));
Report::LongJump(LanguageError::Handle(Z, LanguageError::New(msg)));
#else
FATAL2("Unable to find function %s in %s", name.ToCString(),
cls.ToCString());
#endif
}
return function;
}
}
case kClosure: {
ReadObject(); // Skip enclosing member.
const intptr_t closure_index = reader_.ReadUInt();
return closures_->At(closure_index);
}
case kName: {
if ((flags & kFlagIsPublic) == 0) {
const Library& library = Library::CheckedHandle(Z, ReadObject());
static_assert(KernelBytecode::kMinSupportedBytecodeFormatVersion < 23,
"Cleanup library.IsNull() condition");
if (!library.IsNull()) {
auto& name =
String::Handle(Z, ReadString(/* is_canonical = */ false));
name = library.PrivateName(name);
if (I->obfuscate()) {
const auto& library_key = String::Handle(Z, library.private_key());
Obfuscator obfuscator(thread_, library_key);
return obfuscator.Rename(name);
}
return name.raw();
}
}
if (I->obfuscate()) {
Obfuscator obfuscator(thread_, Object::null_string());
const auto& name = String::Handle(Z, ReadString());
return obfuscator.Rename(name);
} else {
return ReadString();
}
}
case kTypeArguments: {
return ReadTypeArguments();
}
case kConstObject: {
const intptr_t tag = flags / kFlagBit0;
return ReadConstObject(tag);
}
case kArgDesc: {
const intptr_t num_arguments = reader_.ReadUInt();
const intptr_t num_type_args =
((flags & kFlagHasTypeArgs) != 0) ? reader_.ReadUInt() : 0;
if ((flags & kFlagHasNamedArgs) == 0) {
return ArgumentsDescriptor::New(num_type_args, num_arguments);
} else {
const intptr_t num_arg_names = reader_.ReadListLength();
const Array& array = Array::Handle(Z, Array::New(num_arg_names));
String& name = String::Handle(Z);
for (intptr_t i = 0; i < num_arg_names; ++i) {
name ^= ReadObject();
array.SetAt(i, name);
}
return ArgumentsDescriptor::New(num_type_args, num_arguments, array);
}
}
case kScript: {
const String& uri = String::CheckedHandle(Z, ReadObject());
Script& script = Script::Handle(Z);
if ((flags & kFlagHasSourceFile) != 0) {
// TODO(alexmarkov): read source and line starts only when needed.
script =
ReadSourceFile(uri, bytecode_component_->GetSourceFilesOffset() +
reader_.ReadUInt());
} else {
script = Script::New(uri, Object::null_string());
}
script.set_kernel_program_info(H.GetKernelProgramInfo());
return script.raw();
}
case kType: {
const intptr_t tag = (flags & kTagMask) / kFlagBit0;
static_assert(KernelBytecode::kMinSupportedBytecodeFormatVersion < 24,
"Cleanup condition");
const Nullability nullability =
bytecode_component_->GetVersion() >= 24
? static_cast<Nullability>((flags & kNullabilityMask) / kFlagBit4)
: Nullability::kLegacy;
return ReadType(tag, nullability);
}
default:
UNREACHABLE();
}
return Object::null();
}
RawObject* BytecodeReaderHelper::ReadConstObject(intptr_t tag) {
// Must be in sync with enum ConstTag in
// pkg/vm/lib/bytecode/object_table.dart.
enum ConstTag {
kInvalid,
kInstance,
kInt,
kDouble,
kList,
kTearOff,
kBool,
kSymbol,
kTearOffInstantiation,
kString,
};
switch (tag) {
case kInvalid:
UNREACHABLE();
break;
case kInstance: {
const Type& type = Type::CheckedHandle(Z, ReadObject());
const Class& cls = Class::Handle(Z, type.type_class());
const Instance& obj = Instance::Handle(Z, Instance::New(cls, Heap::kOld));
if (type.arguments() != TypeArguments::null()) {
const TypeArguments& type_args =
TypeArguments::Handle(Z, type.arguments());
obj.SetTypeArguments(type_args);
}
const intptr_t num_fields = reader_.ReadUInt();
Field& field = Field::Handle(Z);
Object& value = Object::Handle(Z);
for (intptr_t i = 0; i < num_fields; ++i) {
field ^= ReadObject();
value = ReadObject();
obj.SetField(field, value);
}
return H.Canonicalize(obj);
}
case kInt: {
const int64_t value = reader_.ReadSLEB128AsInt64();
if (Smi::IsValid(value)) {
return Smi::New(static_cast<intptr_t>(value));
}
const Integer& obj = Integer::Handle(Z, Integer::New(value, Heap::kOld));
return H.Canonicalize(obj);
}
case kDouble: {
const int64_t bits = reader_.ReadSLEB128AsInt64();
double value = bit_cast<double, int64_t>(bits);
const Double& obj = Double::Handle(Z, Double::New(value, Heap::kOld));
return H.Canonicalize(obj);
}
case kList: {
const AbstractType& elem_type =
AbstractType::CheckedHandle(Z, ReadObject());
const intptr_t length = reader_.ReadUInt();
const Array& array = Array::Handle(Z, Array::New(length, elem_type));
Object& value = Object::Handle(Z);
for (intptr_t i = 0; i < length; ++i) {
value = ReadObject();
array.SetAt(i, value);
}
array.MakeImmutable();
return H.Canonicalize(array);
}
case kTearOff: {
Object& obj = Object::Handle(Z, ReadObject());
ASSERT(obj.IsFunction());
obj = Function::Cast(obj).ImplicitClosureFunction();
ASSERT(obj.IsFunction());
obj = Function::Cast(obj).ImplicitStaticClosure();
ASSERT(obj.IsInstance());
return H.Canonicalize(Instance::Cast(obj));
}
case kBool: {
bool is_true = reader_.ReadByte() != 0;
return is_true ? Bool::True().raw() : Bool::False().raw();
}
case kSymbol: {
const String& name = String::CheckedHandle(Z, ReadObject());
ASSERT(name.IsSymbol());
const Library& library = Library::Handle(Z, Library::InternalLibrary());
ASSERT(!library.IsNull());
const Class& cls =
Class::Handle(Z, library.LookupClass(Symbols::Symbol()));
ASSERT(!cls.IsNull());
const Field& field = Field::Handle(
Z, cls.LookupInstanceFieldAllowPrivate(Symbols::_name()));
ASSERT(!field.IsNull());
const Instance& obj = Instance::Handle(Z, Instance::New(cls, Heap::kOld));
obj.SetField(field, name);
return H.Canonicalize(obj);
}
case kTearOffInstantiation: {
Closure& closure = Closure::CheckedHandle(Z, ReadObject());
const TypeArguments& type_args =
TypeArguments::CheckedHandle(Z, ReadObject());
closure = Closure::New(
TypeArguments::Handle(Z, closure.instantiator_type_arguments()),
TypeArguments::Handle(Z, closure.function_type_arguments()),
type_args, Function::Handle(Z, closure.function()),
Context::Handle(Z, closure.context()), Heap::kOld);
return H.Canonicalize(closure);
}
case kString:
return ReadString();
default:
UNREACHABLE();
}
return Object::null();
}
RawObject* BytecodeReaderHelper::ReadType(intptr_t tag,
Nullability nullability) {
// Must be in sync with enum TypeTag in
// pkg/vm/lib/bytecode/object_table.dart.
enum TypeTag {
kInvalid,
kDynamic,
kVoid,
kSimpleType,
kTypeParameter,
kGenericType,
kRecursiveGenericType,
kRecursiveTypeRef,
kFunctionType,
kNever,
};
// FunctionType flags, must be in sync with _FunctionTypeHandle constants in
// pkg/vm/lib/bytecode/object_table.dart.
const int kFlagHasOptionalPositionalParams = 1 << 0;
const int kFlagHasOptionalNamedParams = 1 << 1;
const int kFlagHasTypeParams = 1 << 2;
switch (tag) {
case kInvalid:
UNREACHABLE();
break;
case kDynamic:
return AbstractType::dynamic_type().raw();
case kVoid:
return AbstractType::void_type().raw();
case kNever:
return AbstractType::never_type().raw();
case kSimpleType: {
const Class& cls = Class::CheckedHandle(Z, ReadObject());
if (!cls.is_declaration_loaded()) {
LoadReferencedClass(cls);
}
return cls.DeclarationType(nullability);
}
case kTypeParameter: {
Object& parent = Object::Handle(Z, ReadObject());
const intptr_t index_in_parent = reader_.ReadUInt();
TypeArguments& type_parameters = TypeArguments::Handle(Z);
if (parent.IsClass()) {
type_parameters = Class::Cast(parent).type_parameters();
} else if (parent.IsFunction()) {
if (Function::Cast(parent).IsFactory()) {
// For factory constructors VM uses type parameters of a class
// instead of constructor's type parameters.
parent = Function::Cast(parent).Owner();
type_parameters = Class::Cast(parent).type_parameters();
} else {
type_parameters = Function::Cast(parent).type_parameters();
}
} else if (parent.IsNull()) {
ASSERT(function_type_type_parameters_ != nullptr);
type_parameters = function_type_type_parameters_->raw();
} else {
UNREACHABLE();
}
TypeParameter& type_parameter = TypeParameter::Handle(Z);
type_parameter ^= type_parameters.TypeAt(index_in_parent);
return type_parameter.ToNullability(nullability, Heap::kOld);
}
case kGenericType: {
const Class& cls = Class::CheckedHandle(Z, ReadObject());
if (!cls.is_declaration_loaded()) {
LoadReferencedClass(cls);
}
const TypeArguments& type_arguments =
TypeArguments::CheckedHandle(Z, ReadObject());
const Type& type =
Type::Handle(Z, Type::New(cls, type_arguments,
TokenPosition::kNoSource, nullability));
type.SetIsFinalized();
return type.Canonicalize();
}
case kRecursiveGenericType: {
const intptr_t id = reader_.ReadUInt();
const Class& cls = Class::CheckedHandle(Z, ReadObject());
if (!cls.is_declaration_loaded()) {
LoadReferencedClass(cls);
}
const auto saved_pending_recursive_types = pending_recursive_types_;
if (id == 0) {
pending_recursive_types_ = &GrowableObjectArray::Handle(
Z, GrowableObjectArray::New(Heap::kOld));
}
ASSERT(id == pending_recursive_types_->Length());
const auto& type_ref =
TypeRef::Handle(Z, TypeRef::New(AbstractType::null_abstract_type()));
pending_recursive_types_->Add(type_ref);
reading_type_arguments_of_recursive_type_ = true;
const TypeArguments& type_arguments =
TypeArguments::CheckedHandle(Z, ReadObject());
reading_type_arguments_of_recursive_type_ = false;
ASSERT(id == pending_recursive_types_->Length() - 1);
ASSERT(pending_recursive_types_->At(id) == type_ref.raw());
pending_recursive_types_->SetLength(id);
pending_recursive_types_ = saved_pending_recursive_types;
Type& type =
Type::Handle(Z, Type::New(cls, type_arguments,
TokenPosition::kNoSource, nullability));
type_ref.set_type(type);
type.SetIsFinalized();
if (id != 0) {
// Do not canonicalize non-root recursive types
// as not all TypeRef objects are filled up at this point.
return type.raw();
}
return type.Canonicalize();
}
case kRecursiveTypeRef: {
const intptr_t id = reader_.ReadUInt();
ASSERT(pending_recursive_types_ != nullptr);
ASSERT(pending_recursive_types_->Length() >= id);
return pending_recursive_types_->At(id);
}
case kFunctionType: {
const intptr_t flags = reader_.ReadUInt();
Function& signature_function = Function::ZoneHandle(
Z, Function::NewSignatureFunction(*active_class_->klass,
active_class_->enclosing != NULL
? *active_class_->enclosing
: Function::null_function(),
TokenPosition::kNoSource));
// This scope is needed to set active_class_->enclosing_ which is used to
// assign parent function for function types.
ActiveEnclosingFunctionScope active_enclosing_function(
active_class_, &signature_function);
// TODO(alexmarkov): skip type finalization
return ReadFunctionSignature(
signature_function, (flags & kFlagHasOptionalPositionalParams) != 0,
(flags & kFlagHasOptionalNamedParams) != 0,
(flags & kFlagHasTypeParams) != 0,
/* has_positional_param_names = */ false, nullability);
}
default:
UNREACHABLE();
}
return Object::null();
}
RawString* BytecodeReaderHelper::ReadString(bool is_canonical) {
const int kFlagTwoByteString = 1;
const int kHeaderFields = 2;
const int kUInt32Size = 4;
uint32_t ref = reader_.ReadUInt();
const bool isOneByteString = (ref & kFlagTwoByteString) == 0;
intptr_t index = ref >> 1;
if (!isOneByteString) {
const uint32_t num_one_byte_strings =
reader_.ReadUInt32At(bytecode_component_->GetStringsHeaderOffset());
index += num_one_byte_strings;
}
AlternativeReadingScope alt(&reader_,
bytecode_component_->GetStringsHeaderOffset() +
(kHeaderFields + index - 1) * kUInt32Size);
intptr_t start_offs = reader_.ReadUInt32();
intptr_t end_offs = reader_.ReadUInt32();
if (index == 0) {
// For the 0-th string we read a header field instead of end offset of
// the previous string.
start_offs = 0;
}
// Bytecode strings reside in ExternalTypedData which is not movable by GC,
// so it is OK to take a direct pointer to string characters even if
// symbol allocation triggers GC.
const uint8_t* data = reader_.BufferAt(
bytecode_component_->GetStringsContentsOffset() + start_offs);
if (is_canonical) {
if (isOneByteString) {
return Symbols::FromLatin1(thread_, data, end_offs - start_offs);
} else {
return Symbols::FromUTF16(thread_,
reinterpret_cast<const uint16_t*>(data),
(end_offs - start_offs) >> 1);
}
} else {
if (isOneByteString) {
return String::FromLatin1(data, end_offs - start_offs, Heap::kOld);
} else {
return String::FromUTF16(reinterpret_cast<const uint16_t*>(data),
(end_offs - start_offs) >> 1, Heap::kOld);
}
}
}
RawScript* BytecodeReaderHelper::ReadSourceFile(const String& uri,
intptr_t offset) {
// SourceFile flags, must be in sync with SourceFile constants in
// pkg/vm/lib/bytecode/declarations.dart.
const int kHasLineStartsFlag = 1 << 0;
const int kHasSourceFlag = 1 << 1;
AlternativeReadingScope alt(&reader_, offset);
const intptr_t flags = reader_.ReadUInt();
const String& import_uri = String::CheckedHandle(Z, ReadObject());
TypedData& line_starts = TypedData::Handle(Z);
if ((flags & kHasLineStartsFlag) != 0) {
// TODO(alexmarkov): read line starts only when needed.
const intptr_t line_starts_offset =
bytecode_component_->GetLineStartsOffset() + reader_.ReadUInt();
AlternativeReadingScope alt(&reader_, line_starts_offset);
const intptr_t num_line_starts = reader_.ReadUInt();
line_starts = reader_.ReadLineStartsData(num_line_starts);
}
String& source = String::Handle(Z);
if ((flags & kHasSourceFlag) != 0) {
source = ReadString(/* is_canonical = */ false);
}
const Script& script =
Script::Handle(Z, Script::New(import_uri, uri, source));
script.set_line_starts(line_starts);
if (source.IsNull() && line_starts.IsNull()) {
// This script provides a uri only, but no source or line_starts array.
// This could be a reference to a Script in another kernel binary.
// Make an attempt to find source and line starts when needed.
script.SetLazyLookupSourceAndLineStarts(true);
}
return script.raw();
}
RawTypeArguments* BytecodeReaderHelper::ReadTypeArguments() {
const bool is_recursive = reading_type_arguments_of_recursive_type_;
reading_type_arguments_of_recursive_type_ = false;
const intptr_t length = reader_.ReadUInt();
TypeArguments& type_arguments =
TypeArguments::ZoneHandle(Z, TypeArguments::New(length));
AbstractType& type = AbstractType::Handle(Z);
for (intptr_t i = 0; i < length; ++i) {
type ^= ReadObject();
type_arguments.SetTypeAt(i, type);
}
if (is_recursive) {
// Avoid canonicalization of type arguments of recursive type
// as not all TypeRef objects are filled up at this point.
// Type arguments will be canoncialized when the root recursive
// type is canonicalized.
ASSERT(pending_recursive_types_ != nullptr);
return type_arguments.raw();
}
return type_arguments.Canonicalize();
}
void BytecodeReaderHelper::ReadAttributes(const Object& key) {
ASSERT(key.IsFunction() || key.IsField());
const auto& value = Object::Handle(Z, ReadObject());
Array& attributes =
Array::Handle(Z, I->object_store()->bytecode_attributes());
if (attributes.IsNull()) {
attributes = HashTables::New<BytecodeAttributesMap>(16, Heap::kOld);
}
BytecodeAttributesMap map(attributes.raw());
bool present = map.UpdateOrInsert(key, value);
ASSERT(!present);
I->object_store()->set_bytecode_attributes(map.Release());
if (key.IsField()) {
const Field& field = Field::Cast(key);
const auto& inferred_type_attr =
Array::CheckedHandle(Z, BytecodeReader::GetBytecodeAttribute(
key, Symbols::vm_inferred_type_metadata()));
if (!inferred_type_attr.IsNull() &&
(InferredTypeBytecodeAttribute::GetPCAt(inferred_type_attr, 0) ==
InferredTypeBytecodeAttribute::kFieldTypePC)) {
const InferredTypeMetadata type =
InferredTypeBytecodeAttribute::GetInferredTypeAt(
Z, inferred_type_attr, 0);
if (!type.IsTrivial()) {
field.set_guarded_cid(type.cid);
field.set_is_nullable(type.IsNullable());
field.set_guarded_list_length(Field::kNoFixedLength);
}
}
}
}
void BytecodeReaderHelper::ReadMembers(const Class& cls, bool discard_fields) {
ASSERT(Thread::Current()->IsMutatorThread());
ASSERT(cls.is_type_finalized());
ASSERT(!cls.is_loaded());
const intptr_t num_functions = reader_.ReadUInt();
functions_ = &Array::Handle(Z, Array::New(num_functions, Heap::kOld));
function_index_ = 0;
ReadFieldDeclarations(cls, discard_fields);
ReadFunctionDeclarations(cls);
cls.set_is_loaded(true);
}
void BytecodeReaderHelper::ReadFieldDeclarations(const Class& cls,
bool discard_fields) {
// Field flags, must be in sync with FieldDeclaration constants in
// pkg/vm/lib/bytecode/declarations.dart.
const int kHasNontrivialInitializerFlag = 1 << 0;
const int kHasGetterFlag = 1 << 1;
const int kHasSetterFlag = 1 << 2;
const int kIsReflectableFlag = 1 << 3;
const int kIsStaticFlag = 1 << 4;
const int kIsConstFlag = 1 << 5;
const int kIsFinalFlag = 1 << 6;
const int kIsCovariantFlag = 1 << 7;
const int kIsGenericCovariantImplFlag = 1 << 8;
const int kHasSourcePositionsFlag = 1 << 9;
const int kHasAnnotationsFlag = 1 << 10;
const int kHasPragmaFlag = 1 << 11;
const int kHasCustomScriptFlag = 1 << 12;
const int kHasInitializerCodeFlag = 1 << 13;
const int kHasAttributesFlag = 1 << 14;
const int kIsLateFlag = 1 << 15;
const int kIsExtensionMemberFlag = 1 << 16;
const int kHasInitializerFlag = 1 << 17;
const int num_fields = reader_.ReadListLength();
if ((num_fields == 0) && !cls.is_enum_class()) {
return;
}
const Array& fields = Array::Handle(
Z, Array::New(num_fields + (cls.is_enum_class() ? 1 : 0), Heap::kOld));
String& name = String::Handle(Z);
Object& script_class = Object::Handle(Z);
AbstractType& type = AbstractType::Handle(Z);
Field& field = Field::Handle(Z);
Instance& value = Instance::Handle(Z);
Function& function = Function::Handle(Z);
for (intptr_t i = 0; i < num_fields; ++i) {
intptr_t flags = reader_.ReadUInt();
const bool is_static = (flags & kIsStaticFlag) != 0;
const bool is_final = (flags & kIsFinalFlag) != 0;
const bool is_const = (flags & kIsConstFlag) != 0;
const bool is_late = (flags & kIsLateFlag) != 0;
const bool has_nontrivial_initializer =
(flags & kHasNontrivialInitializerFlag) != 0;
const bool has_pragma = (flags & kHasPragmaFlag) != 0;
const bool is_extension_member = (flags & kIsExtensionMemberFlag) != 0;
const bool has_initializer = (flags & kHasInitializerFlag) != 0;
name ^= ReadObject();
type ^= ReadObject();
if ((flags & kHasCustomScriptFlag) != 0) {
Script& script = Script::CheckedHandle(Z, ReadObject());
script_class = GetPatchClass(cls, script);
} else {
script_class = cls.raw();
}
TokenPosition position = TokenPosition::kNoSource;
TokenPosition end_position = TokenPosition::kNoSource;
if ((flags & kHasSourcePositionsFlag) != 0) {
position = reader_.ReadPosition();
end_position = reader_.ReadPosition();
}
field = Field::New(name, is_static, is_final, is_const,
(flags & kIsReflectableFlag) != 0, script_class, type,
position, end_position);
field.set_is_declared_in_bytecode(true);
field.set_has_pragma(has_pragma);
field.set_is_covariant((flags & kIsCovariantFlag) != 0);
field.set_is_generic_covariant_impl((flags & kIsGenericCovariantImplFlag) !=
0);
field.set_has_nontrivial_initializer(has_nontrivial_initializer);
field.set_is_late((flags & kIsLateFlag) != 0);
field.set_is_extension_member(is_extension_member);
field.set_has_initializer(has_initializer);
if (!has_nontrivial_initializer) {
value ^= ReadObject();
if (is_static) {
if (field.is_late() && !has_initializer) {
field.SetStaticValue(Object::sentinel(), true);
} else {
field.SetStaticValue(value, true);
}
} else {
field.set_saved_initial_value(value);
// Null-initialized instance fields are tracked separately for each
// constructor (see handling of kHasNullableFieldsFlag).
if (!value.IsNull()) {
// Note: optimizer relies on DoubleInitialized bit in its
// field-unboxing heuristics.
// See JitCallSpecializer::VisitStoreInstanceField for more details.
field.RecordStore(value);
if (value.IsDouble()) {
field.set_is_double_initialized(true);
}
}
}
}
if ((flags & kHasInitializerCodeFlag) != 0) {
const intptr_t code_offset = reader_.ReadUInt();
field.set_bytecode_offset(code_offset +
bytecode_component_->GetCodesOffset());
if (is_static) {
field.SetStaticValue(Object::sentinel(), true);
}
}
if ((flags & kHasGetterFlag) != 0) {
name ^= ReadObject();
function = Function::New(name,
is_static ? RawFunction::kImplicitStaticGetter
: RawFunction::kImplicitGetter,
is_static, is_const,
false, // is_abstract
false, // is_external
false, // is_native
script_class, position);
function.set_end_token_pos(end_position);
function.set_result_type(type);
function.set_is_debuggable(false);
function.set_accessor_field(field);
function.set_is_declared_in_bytecode(true);
function.set_is_extension_member(is_extension_member);
if (is_const && has_nontrivial_initializer) {
function.set_bytecode_offset(field.bytecode_offset());
}
H.SetupFieldAccessorFunction(cls, function, type);
functions_->SetAt(function_index_++, function);
}
if ((flags & kHasSetterFlag) != 0) {
ASSERT(is_late || ((!is_static) && (!is_final)));
ASSERT(!is_const);
name ^= ReadObject();
function = Function::New(name, RawFunction::kImplicitSetter, is_static,
false, // is_const
false, // is_abstract
false, // is_external
false, // is_native
script_class, position);
function.set_end_token_pos(end_position);
function.set_result_type(Object::void_type());
function.set_is_debuggable(false);
function.set_accessor_field(field);
function.set_is_declared_in_bytecode(true);
function.set_is_extension_member(is_extension_member);
H.SetupFieldAccessorFunction(cls, function, type);
functions_->SetAt(function_index_++, function);
}
if ((flags & kHasAnnotationsFlag) != 0) {
intptr_t annotations_offset =
reader_.ReadUInt() + bytecode_component_->GetAnnotationsOffset();
ASSERT(annotations_offset > 0);
if (FLAG_enable_mirrors || has_pragma) {
Library& library = Library::Handle(Z, cls.library());
library.AddFieldMetadata(field, TokenPosition::kNoSource, 0,
annotations_offset);
if (has_pragma) {
// TODO(alexmarkov): read annotations right away using
// annotations_offset.
NoOOBMessageScope no_msg_scope(thread_);
NoReloadScope no_reload_scope(thread_->isolate(), thread_);
library.GetMetadata(field);
}
}
}
if ((flags & kHasAttributesFlag) != 0) {
ReadAttributes(field);
}
fields.SetAt(i, field);
}
if (cls.is_enum_class()) {
// Add static field 'const _deleted_enum_sentinel'.
field =
Field::New(Symbols::_DeletedEnumSentinel(),
/* is_static = */ true,
/* is_final = */ true,
/* is_const = */ true,
/* is_reflectable = */ false, cls, Object::dynamic_type(),
TokenPosition::kNoSource, TokenPosition::kNoSource);
fields.SetAt(num_fields, field);
}
if (!discard_fields) {
cls.SetFields(fields);
}
if (cls.IsTopLevel()) {
const Library& library = Library::Handle(Z, cls.library());
for (intptr_t i = 0, n = fields.Length(); i < n; ++i) {
field ^= fields.At(i);
name = field.name();
library.AddObject(field, name);
}
}
}
RawPatchClass* BytecodeReaderHelper::GetPatchClass(const Class& cls,
const Script& script) {
if (patch_class_ != nullptr && patch_class_->patched_class() == cls.raw() &&
patch_class_->script() == script.raw()) {
return patch_class_->raw();
}
if (patch_class_ == nullptr) {
patch_class_ = &PatchClass::Handle(Z);
}
*patch_class_ = PatchClass::New(cls, script);
return patch_class_->raw();
}
void BytecodeReaderHelper::ReadFunctionDeclarations(const Class& cls) {
// Function flags, must be in sync with FunctionDeclaration constants in
// pkg/vm/lib/bytecode/declarations.dart.
const int kIsConstructorFlag = 1 << 0;
const int kIsGetterFlag = 1 << 1;
const int kIsSetterFlag = 1 << 2;
const int kIsFactoryFlag = 1 << 3;
const int kIsStaticFlag = 1 << 4;
const int kIsAbstractFlag = 1 << 5;
const int kIsConstFlag = 1 << 6;
const int kHasOptionalPositionalParamsFlag = 1 << 7;
const int kHasOptionalNamedParamsFlag = 1 << 8;
const int kHasTypeParamsFlag = 1 << 9;
const int kIsReflectableFlag = 1 << 10;
const int kIsDebuggableFlag = 1 << 11;
const int kIsAsyncFlag = 1 << 12;
const int kIsAsyncStarFlag = 1 << 13;
const int kIsSyncStarFlag = 1 << 14;
// const int kIsForwardingStubFlag = 1 << 15;
const int kIsNoSuchMethodForwarderFlag = 1 << 16;
const int kIsNativeFlag = 1 << 17;
const int kIsExternalFlag = 1 << 18;
const int kHasSourcePositionsFlag = 1 << 19;
const int kHasAnnotationsFlag = 1 << 20;
const int kHasPragmaFlag = 1 << 21;
const int kHasCustomScriptFlag = 1 << 22;
const int kHasAttributesFlag = 1 << 23;
const int kIsExtensionMemberFlag = 1 << 24;
const intptr_t num_functions = reader_.ReadListLength();
ASSERT(function_index_ + num_functions == functions_->Length());
if (function_index_ + num_functions == 0) {
return;
}
String& name = String::Handle(Z);
Object& script_class = Object::Handle(Z);
Function& function = Function::Handle(Z);
Array& parameter_types = Array::Handle(Z);
Array& parameter_names = Array::Handle(Z);
AbstractType& type = AbstractType::Handle(Z);
for (intptr_t i = 0; i < num_functions; ++i) {
intptr_t flags = reader_.ReadUInt();
const bool is_static = (flags & kIsStaticFlag) != 0;
const bool is_factory = (flags & kIsFactoryFlag) != 0;
const bool is_native = (flags & kIsNativeFlag) != 0;
const bool has_pragma = (flags & kHasPragmaFlag) != 0;
const bool is_extension_member = (flags & kIsExtensionMemberFlag) != 0;
name ^= ReadObject();
if ((flags & kHasCustomScriptFlag) != 0) {
Script& script = Script::CheckedHandle(Z, ReadObject());
script_class = GetPatchClass(cls, script);
} else {
script_class = cls.raw();
}
TokenPosition position = TokenPosition::kNoSource;
TokenPosition end_position = TokenPosition::kNoSource;
if ((flags & kHasSourcePositionsFlag) != 0) {
position = reader_.ReadPosition();
end_position = reader_.ReadPosition();
}
RawFunction::Kind kind = RawFunction::kRegularFunction;
if ((flags & kIsGetterFlag) != 0) {
kind = RawFunction::kGetterFunction;
} else if ((flags & kIsSetterFlag) != 0) {
kind = RawFunction::kSetterFunction;
} else if ((flags & (kIsConstructorFlag | kIsFactoryFlag)) != 0) {
kind = RawFunction::kConstructor;
name = ConstructorName(cls, name);
}
function = Function::New(name, kind, is_static, (flags & kIsConstFlag) != 0,
(flags & kIsAbstractFlag) != 0,
(flags & kIsExternalFlag) != 0, is_native,
script_class, position);
const bool is_expression_evaluation =
(name.raw() == Symbols::DebugProcedureName().raw());
// Declare function scope as types (type parameters) in function
// signature may back-reference to the function being declared.
// At this moment, owner class is not fully loaded yet and it won't be
// able to serve function lookup requests.
FunctionScope function_scope(this, function, name, cls);
function.set_is_declared_in_bytecode(true);
function.set_has_pragma(has_pragma);
function.set_end_token_pos(end_position);
function.set_is_no_such_method_forwarder(
(flags & kIsNoSuchMethodForwarderFlag) != 0);
function.set_is_reflectable((flags & kIsReflectableFlag) != 0);
function.set_is_debuggable((flags & kIsDebuggableFlag) != 0);
function.set_is_extension_member(is_extension_member);
if ((flags & kIsSyncStarFlag) != 0) {
function.set_modifier(RawFunction::kSyncGen);
} else if ((flags & kIsAsyncFlag) != 0) {
function.set_modifier(RawFunction::kAsync);
function.set_is_inlinable(!FLAG_causal_async_stacks);
} else if ((flags & kIsAsyncStarFlag) != 0) {
function.set_modifier(RawFunction::kAsyncGen);
function.set_is_inlinable(!FLAG_causal_async_stacks);
}
if ((flags & kHasTypeParamsFlag) != 0) {
ReadTypeParametersDeclaration(Class::Handle(Z), function);
}
const intptr_t num_implicit_params = (!is_static || is_factory) ? 1 : 0;
const intptr_t num_params = num_implicit_params + reader_.ReadUInt();
intptr_t num_required_params = num_params;
if ((flags & (kHasOptionalPositionalParamsFlag |
kHasOptionalNamedParamsFlag)) != 0) {
num_required_params = num_implicit_params + reader_.ReadUInt();
}
function.set_num_fixed_parameters(num_required_params);
function.SetNumOptionalParameters(
num_params - num_required_params,
(flags & kHasOptionalNamedParamsFlag) == 0);
parameter_types = Array::New(num_params, Heap::kOld);
function.set_parameter_types(parameter_types);
parameter_names = Array::New(num_params, Heap::kOld);
function.set_parameter_names(parameter_names);
intptr_t param_index = 0;
if (!is_static) {
if (is_expression_evaluation) {
// Do not reference enclosing class as expression evaluation
// method logically belongs to another (real) class.
// Enclosing class is not registered and doesn't have
// a valid cid, so it can't be used in a type.
function.SetParameterTypeAt(param_index, AbstractType::dynamic_type());
} else {
function.SetParameterTypeAt(param_index, H.GetDeclarationType(cls));
}
function.SetParameterNameAt(param_index, Symbols::This());
++param_index;
} else if (is_factory) {
function.SetParameterTypeAt(param_index, AbstractType::dynamic_type());
function.SetParameterNameAt(param_index,
Symbols::TypeArgumentsParameter());
++param_index;
}
for (; param_index < num_params; ++param_index) {
name ^= ReadObject();
parameter_names.SetAt(param_index, name);
type ^= ReadObject();
parameter_types.SetAt(param_index, type);
}
type ^= ReadObject();
function.set_result_type(type);
if (is_native) {
name ^= ReadObject();
function.set_native_name(name);
}
if ((flags & kIsAbstractFlag) == 0) {
const intptr_t code_offset = reader_.ReadUInt();
function.set_bytecode_offset(code_offset +
bytecode_component_->GetCodesOffset());
}
if ((flags & kHasAnnotationsFlag) != 0) {
const intptr_t annotations_offset =
reader_.ReadUInt() + bytecode_component_->GetAnnotationsOffset();
ASSERT(annotations_offset > 0);
if (FLAG_enable_mirrors || has_pragma) {
Library& library = Library::Handle(Z, cls.library());
library.AddFunctionMetadata(function, TokenPosition::kNoSource, 0,
annotations_offset);
if (has_pragma) {
if (H.constants().IsNull() &&
library.raw() == Library::CoreLibrary()) {
// Bootstrapping, need to postpone evaluation of pragma annotations
// as classes are not fully loaded/finalized yet.
const auto& pragma_funcs = GrowableObjectArray::Handle(
Z, H.EnsurePotentialPragmaFunctions());
pragma_funcs.Add(function);
} else {
// TODO(alexmarkov): read annotations right away using
// annotations_offset.
Thread* thread = H.thread();
NoOOBMessageScope no_msg_scope(thread);
NoReloadScope no_reload_scope(thread->isolate(), thread);
library.GetMetadata(function);
}
}
}
}
if ((flags & kHasAttributesFlag) != 0) {
ASSERT(!is_expression_evaluation);
ReadAttributes(function);
}
if (is_expression_evaluation) {
H.SetExpressionEvaluationFunction(function);
// Read bytecode of expression evaluation function eagerly,
// while expression_evaluation_library_ and FunctionScope
// are still set, as its constant pool may reference back to a library
// or a function which are not registered and cannot be looked up.
ASSERT(!function.is_abstract());
ASSERT(function.bytecode_offset() != 0);
// Replace class of the function in scope as we're going to look for
// expression evaluation function in a real class.
if (!cls.IsTopLevel()) {
scoped_function_class_ = H.GetExpressionEvaluationRealClass();
}
CompilerState compiler_state(thread_);
ReadCode(function, function.bytecode_offset());
}
functions_->SetAt(function_index_++, function);
}
cls.SetFunctions(*functions_);
if (cls.IsTopLevel()) {
const Library& library = Library::Handle(Z, cls.library());
for (intptr_t i = 0, n = functions_->Length(); i < n; ++i) {
function ^= functions_->At(i);
name = function.name();
library.AddObject(function, name);
}
}
functions_ = nullptr;
}
void BytecodeReaderHelper::LoadReferencedClass(const Class& cls) {
ASSERT(!cls.is_declaration_loaded());
if (!cls.is_declared_in_bytecode()) {
cls.EnsureDeclarationLoaded();
return;
}
const auto& script = Script::Handle(Z, cls.script());
if (H.GetKernelProgramInfo().raw() != script.kernel_program_info()) {
// Class comes from a different binary.
cls.EnsureDeclarationLoaded();
return;
}
// We can reuse current BytecodeReaderHelper.
ActiveClassScope active_class_scope(active_class_, &cls);
AlternativeReadingScope alt(&reader_, cls.bytecode_offset());
ReadClassDeclaration(cls);
}
void BytecodeReaderHelper::ReadClassDeclaration(const Class& cls) {
// Class flags, must be in sync with ClassDeclaration constants in
// pkg/vm/lib/bytecode/declarations.dart.
const int kIsAbstractFlag = 1 << 0;
const int kIsEnumFlag = 1 << 1;
const int kHasTypeParamsFlag = 1 << 2;
const int kHasTypeArgumentsFlag = 1 << 3;
const int kIsTransformedMixinApplicationFlag = 1 << 4;
const int kHasSourcePositionsFlag = 1 << 5;
const int kHasAnnotationsFlag = 1 << 6;
const int kHasPragmaFlag = 1 << 7;
// Class is allocated when reading library declaration in
// BytecodeReaderHelper::ReadLibraryDeclaration.
// Its cid is set in Class::New / Isolate::RegisterClass /
// ClassTable::Register, unless it was loaded for expression evaluation.
ASSERT(cls.is_declared_in_bytecode());
ASSERT(!cls.is_declaration_loaded() || loading_native_wrappers_library_);
const intptr_t flags = reader_.ReadUInt();
const bool has_pragma = (flags & kHasPragmaFlag) != 0;
// Set early to enable access to type_parameters().
// TODO(alexmarkov): revise early stamping of native wrapper classes
// as loaded.
if (!cls.is_declaration_loaded()) {
cls.set_is_declaration_loaded();
}
const auto& script = Script::CheckedHandle(Z, ReadObject());
cls.set_script(script);
TokenPosition position = TokenPosition::kNoSource;
TokenPosition end_position = TokenPosition::kNoSource;
if ((flags & kHasSourcePositionsFlag) != 0) {
position = reader_.ReadPosition();
end_position = reader_.ReadPosition();
cls.set_token_pos(position);
cls.set_end_token_pos(end_position);
}
cls.set_has_pragma(has_pragma);
if ((flags & kIsAbstractFlag) != 0) {
cls.set_is_abstract();
}
if ((flags & kIsEnumFlag) != 0) {
cls.set_is_enum_class();
}
if ((flags & kIsTransformedMixinApplicationFlag) != 0) {
cls.set_is_transformed_mixin_application();
}
intptr_t num_type_arguments = 0;
if ((flags & kHasTypeArgumentsFlag) != 0) {
num_type_arguments = reader_.ReadUInt();
}
cls.set_num_type_arguments(num_type_arguments);
if ((flags & kHasTypeParamsFlag) != 0) {
ReadTypeParametersDeclaration(cls, Function::null_function());
}
auto& type = AbstractType::CheckedHandle(Z, ReadObject());
cls.set_super_type(type);
const intptr_t num_interfaces = reader_.ReadUInt();
if (num_interfaces > 0) {
const auto& interfaces =
Array::Handle(Z, Array::New(num_interfaces, Heap::kOld));
for (intptr_t i = 0; i < num_interfaces; ++i) {
type ^= ReadObject();
interfaces.SetAt(i, type);
}
cls.set_interfaces(interfaces);
}
if ((flags & kHasAnnotationsFlag) != 0) {
intptr_t annotations_offset =
reader_.ReadUInt() + bytecode_component_->GetAnnotationsOffset();
ASSERT(annotations_offset > 0);
if (FLAG_enable_mirrors || has_pragma) {
const auto& library = Library::Handle(Z, cls.library());
if (cls.IsTopLevel()) {
ASSERT(!has_pragma);
library.AddLibraryMetadata(cls, TokenPosition::kNoSource, 0,
annotations_offset);
} else {
const auto& top_level_class =
Class::Handle(Z, library.toplevel_class());
library.AddClassMetadata(cls, top_level_class, TokenPosition::kNoSource,
0, annotations_offset);
}
}
}
const intptr_t members_offset = reader_.ReadUInt();
cls.set_bytecode_offset(members_offset +
bytecode_component_->GetMembersOffset());
// All types are finalized if loading from bytecode.
// TODO(alexmarkov): revise early stamping of native wrapper classes
// as type-finalized.
if (!cls.is_type_finalized()) {
cls.set_is_type_finalized();
}
// Avoid registering expression evaluation class in a hierarchy, as
// it doesn't have cid and shouldn't be found when enumerating subclasses.
if (expression_evaluation_library_ == nullptr) {
// TODO(alexmarkov): move this to class finalization.
ClassFinalizer::RegisterClassInHierarchy(Z, cls);
}
}
void BytecodeReaderHelper::ReadLibraryDeclaration(const Library& library,
bool lookup_classes) {
// Library flags, must be in sync with LibraryDeclaration constants in
// pkg/vm/lib/bytecode/declarations.dart.
const int kUsesDartMirrorsFlag = 1 << 0;
const int kUsesDartFfiFlag = 1 << 1;
const int kHasExtensionsFlag = 1 << 2;
const int kIsNonNullableByDefaultFlag = 1 << 3;
ASSERT(library.is_declared_in_bytecode());
ASSERT(!library.Loaded());
ASSERT(library.toplevel_class() == Object::null());
// TODO(alexmarkov): fill in library.owned_scripts.
const intptr_t flags = reader_.ReadUInt();
if (((flags & kUsesDartMirrorsFlag) != 0) && !FLAG_enable_mirrors) {
H.ReportError(
"import of dart:mirrors is not supported in the current Dart runtime");
}
if (((flags & kUsesDartFfiFlag) != 0) && !Api::IsFfiEnabled()) {
H.ReportError(
"import of dart:ffi is not supported in the current Dart runtime");
}
auto& name = String::CheckedHandle(Z, ReadObject());
library.SetName(name);
const auto& script = Script::CheckedHandle(Z, ReadObject());
if ((flags & kHasExtensionsFlag) != 0) {
const intptr_t num_extensions = reader_.ReadUInt();
auto& import_namespace = Namespace::Handle(Z);
auto& native_library = Library::Handle(Z);
for (intptr_t i = 0; i < num_extensions; ++i) {
name ^= ReadObject();
ASSERT(name.StartsWith(Symbols::DartExtensionScheme()));
// Create a dummy library and add it as an import to the current library.
// Actual loading occurs in KernelLoader::LoadNativeExtensionLibraries().
// This also allows later to discover and reload this native extension,
// e.g. when running from an app-jit snapshot.
// See Loader::ReloadNativeExtensions(...) which relies on
// Dart_GetImportsOfScheme('dart-ext').
native_library = Library::New(name);
import_namespace = Namespace::New(native_library, Array::null_array(),
Array::null_array());
library.AddImport(import_namespace);
}
H.AddPotentialExtensionLibrary(library);
}
if ((flags & kIsNonNullableByDefaultFlag) != 0) {
library.set_is_nnbd(true);
}
// The bootstrapper will take care of creating the native wrapper classes,
// but we will add the synthetic constructors to them here.
if (name.raw() ==
Symbols::Symbol(Symbols::kDartNativeWrappersLibNameId).raw()) {
ASSERT(library.LoadInProgress());
loading_native_wrappers_library_ = true;
} else {
loading_native_wrappers_library_ = false;
library.SetLoadInProgress();
}
const bool register_class = !IsExpressionEvaluationLibrary(library);
const intptr_t num_classes = reader_.ReadUInt();
ASSERT(num_classes > 0);
auto& cls = Class::Handle(Z);
for (intptr_t i = 0; i < num_classes; ++i) {
name ^= ReadObject();
const intptr_t class_offset =
bytecode_component_->GetClassesOffset() + reader_.ReadUInt();
if (i == 0) {
ASSERT(name.raw() == Symbols::Empty().raw());
cls = Class::New(library, Symbols::TopLevel(), script,
TokenPosition::kNoSource, register_class);
library.set_toplevel_class(cls);
} else {
if (lookup_classes) {
cls = library.LookupLocalClass(name);
}
if (lookup_classes && !cls.IsNull()) {
ASSERT(!cls.is_declaration_loaded() ||
loading_native_wrappers_library_);
cls.set_script(script);
} else {
cls = Class::New(library, name, script, TokenPosition::kNoSource,
register_class);
if (register_class) {
library.AddClass(cls);
}
}
}
cls.set_is_declared_in_bytecode(true);
cls.set_bytecode_offset(class_offset);
if (loading_native_wrappers_library_ || !register_class) {
AlternativeReadingScope alt(&reader_, class_offset);
ReadClassDeclaration(cls);
ActiveClassScope active_class_scope(active_class_, &cls);
AlternativeReadingScope alt2(&reader_, cls.bytecode_offset());
ReadMembers(cls, /* discard_fields = */ false);
}
}
ASSERT(!library.Loaded());
library.SetLoaded();
loading_native_wrappers_library_ = false;
}
void BytecodeReaderHelper::ReadLibraryDeclarations(intptr_t num_libraries) {
auto& library = Library::Handle(Z);
auto& uri = String::Handle(Z);
for (intptr_t i = 0; i < num_libraries; ++i) {
uri ^= ReadObject();
const intptr_t library_offset =
bytecode_component_->GetLibrariesOffset() + reader_.ReadUInt();
if (!FLAG_precompiled_mode && !I->should_load_vmservice()) {
if (uri.raw() == Symbols::DartVMServiceIO().raw()) {
continue;
}
}
bool lookup_classes = true;
library = Library::LookupLibrary(thread_, uri);
if (library.IsNull()) {
lookup_classes = false;
library = Library::New(uri);
if (uri.raw() == Symbols::EvalSourceUri().raw()) {
ASSERT(expression_evaluation_library_ == nullptr);
expression_evaluation_library_ = &Library::Handle(Z, library.raw());
} else {
library.Register(thread_);
}
}
if (library.Loaded()) {
continue;
}
library.set_is_declared_in_bytecode(true);
library.set_bytecode_offset(library_offset);
AlternativeReadingScope alt(&reader_, library_offset);
ReadLibraryDeclaration(library, lookup_classes);
}
}
void BytecodeReaderHelper::FindAndReadSpecificLibrary(const Library& library,
intptr_t num_libraries) {
auto& uri = String::Handle(Z);
for (intptr_t i = 0; i < num_libraries; ++i) {
uri ^= ReadObject();
const intptr_t library_offset =
bytecode_component_->GetLibrariesOffset() + reader_.ReadUInt();
if (uri.raw() == library.url()) {
library.set_is_declared_in_bytecode(true);
library.set_bytecode_offset(library_offset);
AlternativeReadingScope alt(&reader_, library_offset);
ReadLibraryDeclaration(library, /* lookup_classes = */ true);
return;
}
}
}
void BytecodeReaderHelper::FindModifiedLibrariesForHotReload(
BitVector* modified_libs,
intptr_t num_libraries) {
auto& uri = String::Handle(Z);
auto& lib = Library::Handle(Z);
for (intptr_t i = 0; i < num_libraries; ++i) {
uri ^= ReadObject();
reader_.ReadUInt(); // Skip offset.
lib = Library::LookupLibrary(thread_, uri);
if (!lib.IsNull() && !lib.is_dart_scheme()) {
// This is a library that already exists so mark it as being modified.
modified_libs->Add(lib.index());
}
}
}
void BytecodeReaderHelper::ReadParameterCovariance(
const Function& function,
BitVector* is_covariant,
BitVector* is_generic_covariant_impl) {
ASSERT(function.is_declared_in_bytecode());
const intptr_t num_params = function.NumParameters();
ASSERT(is_covariant->length() == num_params);
ASSERT(is_generic_covariant_impl->length() == num_params);
AlternativeReadingScope alt(&reader_, function.bytecode_offset());
const intptr_t code_flags = reader_.ReadUInt();
if ((code_flags & Code::kHasParameterFlagsFlag) != 0) {
const intptr_t num_explicit_params = reader_.ReadUInt();
ASSERT(num_params ==
function.NumImplicitParameters() + num_explicit_params);
for (intptr_t i = function.NumImplicitParameters(); i < num_params; ++i) {
const intptr_t flags = reader_.ReadUInt();
if ((flags & Parameter::kIsCovariantFlag) != 0) {
is_covariant->Add(i);
}
if ((flags & Parameter::kIsGenericCovariantImplFlag) != 0) {
is_generic_covariant_impl->Add(i);
}
}
}
}
RawObject* BytecodeReaderHelper::BuildParameterDescriptor(
const Function& function) {
ASSERT(function.is_declared_in_bytecode());
Object& result = Object::Handle(Z);
if (!function.HasBytecode()) {
result = BytecodeReader::ReadFunctionBytecode(Thread::Current(), function);
if (result.IsError()) {
return result.raw();
}
}
const intptr_t num_params = function.NumParameters();
const intptr_t num_implicit_params = function.NumImplicitParameters();
const intptr_t num_explicit_params = num_params - num_implicit_params;
const Array& descriptor = Array::Handle(
Z, Array::New(num_explicit_params * Parser::kParameterEntrySize));
// 1. Find isFinal in the Code declaration.
bool found_final = false;
if (!function.is_abstract()) {
AlternativeReadingScope alt(&reader_, function.bytecode_offset());
const intptr_t code_flags = reader_.ReadUInt();
if ((code_flags & Code::kHasParameterFlagsFlag) != 0) {
const intptr_t num_explicit_params_written = reader_.ReadUInt();
ASSERT(num_explicit_params == num_explicit_params_written);
for (intptr_t i = 0; i < num_explicit_params; ++i) {
const intptr_t flags = reader_.ReadUInt();
descriptor.SetAt(
i * Parser::kParameterEntrySize + Parser::kParameterIsFinalOffset,
Bool::Get((flags & Parameter::kIsFinalFlag) != 0));
}
found_final = true;
}
}
if (!found_final) {
for (intptr_t i = 0; i < num_explicit_params; ++i) {
descriptor.SetAt(
i * Parser::kParameterEntrySize + Parser::kParameterIsFinalOffset,
Bool::Get(false));
}
}
// 2. Find metadata implicitly after the function declaration's metadata.
const Class& klass = Class::Handle(Z, function.Owner());
const Library& library = Library::Handle(Z, klass.library());
const Object& metadata = Object::Handle(
Z, library.GetExtendedMetadata(function, num_explicit_params));
if (metadata.IsError()) {
return metadata.raw();
}
if (Array::Cast(metadata).Length() != 0) {
for (intptr_t i = 0; i < num_explicit_params; i++) {
result = Array::Cast(metadata).At(i);
descriptor.SetAt(
i * Parser::kParameterEntrySize + Parser::kParameterMetadataOffset,
result);
}
}
// 3. Find the defaultValues in the EntryOptional sequence.
if (!function.is_abstract()) {
const Bytecode& bytecode = Bytecode::Handle(Z, function.bytecode());
ASSERT(!bytecode.IsNull());
const ObjectPool& constants = ObjectPool::Handle(Z, bytecode.object_pool());
ASSERT(!constants.IsNull());
const KBCInstr* instr =
reinterpret_cast<const KBCInstr*>(bytecode.PayloadStart());
if (KernelBytecode::IsEntryOptionalOpcode(instr)) {
// Note that number of fixed parameters may not match 'A' operand of
// EntryOptional bytecode as [function] could be an implicit closure
// function with an extra implicit argument, while bytecode corresponds
// to a static function without any implicit arguments.
const intptr_t num_fixed_params = function.num_fixed_parameters();
const intptr_t num_opt_pos_params = KernelBytecode::DecodeB(instr);
const intptr_t num_opt_named_params = KernelBytecode::DecodeC(instr);
instr = KernelBytecode::Next(instr);
ASSERT(num_opt_pos_params == function.NumOptionalPositionalParameters());
ASSERT(num_opt_named_params == function.NumOptionalNamedParameters());
ASSERT((num_opt_pos_params == 0) || (num_opt_named_params == 0));
for (intptr_t i = 0; i < num_opt_pos_params; i++) {
const KBCInstr* load_value_instr = instr;
instr = KernelBytecode::Next(instr);
ASSERT(KernelBytecode::IsLoadConstantOpcode(load_value_instr));
result = constants.ObjectAt(KernelBytecode::DecodeE(load_value_instr));
descriptor.SetAt((num_fixed_params - num_implicit_params + i) *
Parser::kParameterEntrySize +
Parser::kParameterDefaultValueOffset,
result);
}
for (intptr_t i = 0; i < num_opt_named_params; i++) {
const KBCInstr* load_name_instr = instr;
const KBCInstr* load_value_instr =
KernelBytecode::Next(load_name_instr);
instr = KernelBytecode::Next(load_value_instr);
ASSERT(KernelBytecode::IsLoadConstantOpcode(load_name_instr));
result = constants.ObjectAt(KernelBytecode::DecodeE(load_name_instr));
intptr_t param_index;
for (param_index = num_fixed_params; param_index < num_params;
param_index++) {
if (function.ParameterNameAt(param_index) == result.raw()) {
break;
}
}
ASSERT(param_index < num_params);
ASSERT(KernelBytecode::IsLoadConstantOpcode(load_value_instr));
result = constants.ObjectAt(KernelBytecode::DecodeE(load_value_instr));
descriptor.SetAt(
(param_index - num_implicit_params) * Parser::kParameterEntrySize +
Parser::kParameterDefaultValueOffset,
result);
}
}
}
return descriptor.raw();
}
void BytecodeReaderHelper::ParseBytecodeFunction(
ParsedFunction* parsed_function,
const Function& function) {
// Handle function kinds which don't have a user-defined body first.
switch (function.kind()) {
case RawFunction::kImplicitClosureFunction:
ParseForwarderFunction(parsed_function, function,
Function::Handle(Z, function.parent_function()));
return;
case RawFunction::kDynamicInvocationForwarder:
ParseForwarderFunction(parsed_function, function,
Function::Handle(Z, function.ForwardingTarget()));
return;
case RawFunction::kImplicitGetter:
case RawFunction::kImplicitSetter:
case RawFunction::kMethodExtractor:
BytecodeScopeBuilder(parsed_function).BuildScopes();
return;
case RawFunction::kImplicitStaticGetter: {
if (IsStaticFieldGetterGeneratedAsInitializer(function, Z)) {
break;
} else {
BytecodeScopeBuilder(parsed_function).BuildScopes();
return;
}
}
case RawFunction::kRegularFunction:
case RawFunction::kGetterFunction:
case RawFunction::kSetterFunction:
case RawFunction::kClosureFunction:
case RawFunction::kConstructor:
case RawFunction::kFieldInitializer:
break;
case RawFunction::kNoSuchMethodDispatcher:
case RawFunction::kInvokeFieldDispatcher:
case RawFunction::kSignatureFunction:
case RawFunction::kIrregexpFunction:
case RawFunction::kFfiTrampoline:
UNREACHABLE();
break;
}
// We only reach here if function has a bytecode body. Make sure it is
// loaded and collect information about covariant parameters.
if (!function.HasBytecode()) {
ReadCode(function, function.bytecode_offset());
ASSERT(function.HasBytecode());
}
// TODO(alexmarkov): simplify access to covariant / generic_covariant_impl
// flags of parameters so we won't need to read them separately.
if (!parsed_function->HasCovariantParametersInfo()) {
const intptr_t num_params = function.NumParameters();
BitVector* covariant_parameters = new (Z) BitVector(Z, num_params);
BitVector* generic_covariant_impl_parameters =
new (Z) BitVector(Z, num_params);
ReadParameterCovariance(function, covariant_parameters,
generic_covariant_impl_parameters);
parsed_function->SetCovariantParameters(covariant_parameters);
parsed_function->SetGenericCovariantImplParameters(
generic_covariant_impl_parameters);
}
}
void BytecodeReaderHelper::ParseForwarderFunction(
ParsedFunction* parsed_function,
const Function& function,
const Function& target) {
ASSERT(function.IsImplicitClosureFunction() ||
function.IsDynamicInvocationForwarder());
ASSERT(target.is_declared_in_bytecode());
if (function.IsDynamicInvocationForwarder() &&
target.IsImplicitSetterFunction()) {
BytecodeScopeBuilder(parsed_function).BuildScopes();
return;
}
if (!target.HasBytecode()) {
ReadCode(target, target.bytecode_offset());
}
BytecodeScopeBuilder(parsed_function).BuildScopes();
const auto& target_bytecode = Bytecode::Handle(Z, target.bytecode());
const auto& obj_pool = ObjectPool::Handle(Z, target_bytecode.object_pool());
AlternativeReadingScope alt(&reader_, target.bytecode_offset());
const intptr_t flags = reader_.ReadUInt();
const bool has_parameters_flags = (flags & Code::kHasParameterFlagsFlag) != 0;
const bool has_forwarding_stub_target =
(flags & Code::kHasForwardingStubTargetFlag) != 0;
const bool has_default_function_type_args =
(flags & Code::kHasDefaultFunctionTypeArgsFlag) != 0;
const auto proc_attrs = kernel::ProcedureAttributesOf(target, Z);
// TODO(alexmarkov): fix building of flow graph for implicit closures so
// it would include missing checks and remove 'proc_attrs.has_tearoff_uses'
// from this condition.
const bool body_has_generic_covariant_impl_type_checks =
proc_attrs.has_non_this_uses || proc_attrs.has_tearoff_uses;
if (has_parameters_flags) {
const intptr_t num_params = reader_.ReadUInt();
const intptr_t num_implicit_params = function.NumImplicitParameters();
for (intptr_t i = 0; i < num_params; ++i) {
const intptr_t flags = reader_.ReadUInt();
bool is_covariant = (flags & Parameter::kIsCovariantFlag) != 0;
bool is_generic_covariant_impl =
(flags & Parameter::kIsGenericCovariantImplFlag) != 0;
LocalVariable* variable =
parsed_function->ParameterVariable(num_implicit_params + i);
if (is_covariant) {
variable->set_is_explicit_covariant_parameter();
}
const bool checked_in_method_body =
is_covariant || (is_generic_covariant_impl &&
body_has_generic_covariant_impl_type_checks);
if (checked_in_method_body) {
variable->set_type_check_mode(LocalVariable::kSkipTypeCheck);
} else {
ASSERT(variable->type_check_mode() == LocalVariable::kDoTypeCheck);
}
}
}
if (has_forwarding_stub_target) {
const intptr_t cp_index = reader_.ReadUInt();
const auto& forwarding_stub_target =
Function::CheckedZoneHandle(Z, obj_pool.ObjectAt(cp_index));
parsed_function->MarkForwardingStub(&forwarding_stub_target);
}
if (has_default_function_type_args) {
ASSERT(function.IsGeneric());
const intptr_t cp_index = reader_.ReadUInt();
const auto& type_args =
TypeArguments::CheckedHandle(Z, obj_pool.ObjectAt(cp_index));
parsed_function->SetDefaultFunctionTypeArguments(type_args);
}
if (function.HasOptionalParameters()) {
const KBCInstr* raw_bytecode =
reinterpret_cast<const KBCInstr*>(target_bytecode.PayloadStart());
const KBCInstr* entry = raw_bytecode;
raw_bytecode = KernelBytecode::Next(raw_bytecode);
ASSERT(KernelBytecode::IsEntryOptionalOpcode(entry));
ASSERT(KernelBytecode::DecodeB(entry) ==
function.NumOptionalPositionalParameters());
ASSERT(KernelBytecode::DecodeC(entry) ==
function.NumOptionalNamedParameters());
const intptr_t num_opt_params = function.NumOptionalParameters();
ZoneGrowableArray<const Instance*>* default_values =
new (Z) ZoneGrowableArray<const Instance*>(Z, num_opt_params);
if (function.HasOptionalPositionalParameters()) {
for (intptr_t i = 0, n = function.NumOptionalPositionalParameters();
i < n; ++i) {
const KBCInstr* load = raw_bytecode;
raw_bytecode = KernelBytecode::Next(raw_bytecode);
ASSERT(KernelBytecode::IsLoadConstantOpcode(load));
const auto& value = Instance::CheckedZoneHandle(
Z, obj_pool.ObjectAt(KernelBytecode::DecodeE(load)));
default_values->Add(&value);
}
} else {
const intptr_t num_fixed_params = function.num_fixed_parameters();
auto& param_name = String::Handle(Z);
default_values->EnsureLength(num_opt_params, nullptr);
for (intptr_t i = 0; i < num_opt_params; ++i) {
const KBCInstr* load_name = raw_bytecode;
const KBCInstr* load_value = KernelBytecode::Next(load_name);
raw_bytecode = KernelBytecode::Next(load_value);
ASSERT(KernelBytecode::IsLoadConstantOpcode(load_name));
ASSERT(KernelBytecode::IsLoadConstantOpcode(load_value));
param_name ^= obj_pool.ObjectAt(KernelBytecode::DecodeE(load_name));
const auto& value = Instance::CheckedZoneHandle(
Z, obj_pool.ObjectAt(KernelBytecode::DecodeE(load_value)));
const intptr_t num_params = function.NumParameters();
intptr_t param_index = num_fixed_params;
for (; param_index < num_params; ++param_index) {
if (function.ParameterNameAt(param_index) == param_name.raw()) {
break;
}
}
ASSERT(param_index < num_params);
ASSERT(default_values->At(param_index - num_fixed_params) == nullptr);
(*default_values)[param_index - num_fixed_params] = &value;
}
}
parsed_function->set_default_parameter_values(default_values);
}
}
RawLibrary* BytecodeReaderHelper::ReadMain() {
return Library::RawCast(ReadObject());
}
intptr_t BytecodeComponentData::GetVersion() const {
return Smi::Value(Smi::RawCast(data_.At(kVersion)));
}
intptr_t BytecodeComponentData::GetStringsHeaderOffset() const {
return Smi::Value(Smi::RawCast(data_.At(kStringsHeaderOffset)));
}
intptr_t BytecodeComponentData::GetStringsContentsOffset() const {
return Smi::Value(Smi::RawCast(data_.At(kStringsContentsOffset)));
}
intptr_t BytecodeComponentData::GetObjectOffsetsOffset() const {
return Smi::Value(Smi::RawCast(data_.At(kObjectOffsetsOffset)));
}
intptr_t BytecodeComponentData::GetNumObjects() const {
return Smi::Value(Smi::RawCast(data_.At(kNumObjects)));
}
intptr_t BytecodeComponentData::GetObjectsContentsOffset() const {
return Smi::Value(Smi::RawCast(data_.At(kObjectsContentsOffset)));
}
intptr_t BytecodeComponentData::GetMainOffset() const {
return Smi::Value(Smi::RawCast(data_.At(kMainOffset)));
}
intptr_t BytecodeComponentData::GetNumLibraries() const {
return Smi::Value(Smi::RawCast(data_.At(kNumLibraries)));
}
intptr_t BytecodeComponentData::GetLibraryIndexOffset() const {
return Smi::Value(Smi::RawCast(data_.At(kLibraryIndexOffset)));
}
intptr_t BytecodeComponentData::GetLibrariesOffset() const {
return Smi::Value(Smi::RawCast(data_.At(kLibrariesOffset)));
}
intptr_t BytecodeComponentData::GetNumClasses() const {
return Smi::Value(Smi::RawCast(data_.At(kNumClasses)));
}
intptr_t BytecodeComponentData::GetClassesOffset() const {
return Smi::Value(Smi::RawCast(data_.At(kClassesOffset)));
}
intptr_t BytecodeComponentData::GetMembersOffset() const {
return Smi::Value(Smi::RawCast(data_.At(kMembersOffset)));
}
intptr_t BytecodeComponentData::GetNumCodes() const {
return Smi::Value(Smi::RawCast(data_.At(kNumCodes)));
}
intptr_t BytecodeComponentData::GetCodesOffset() const {
return Smi::Value(Smi::RawCast(data_.At(kCodesOffset)));
}
intptr_t BytecodeComponentData::GetSourcePositionsOffset() const {
return Smi::Value(Smi::RawCast(data_.At(kSourcePositionsOffset)));
}
intptr_t BytecodeComponentData::GetSourceFilesOffset() const {
return Smi::Value(Smi::RawCast(data_.At(kSourceFilesOffset)));
}
intptr_t BytecodeComponentData::GetLineStartsOffset() const {
return Smi::Value(Smi::RawCast(data_.At(kLineStartsOffset)));
}
intptr_t BytecodeComponentData::GetLocalVariablesOffset() const {
return Smi::Value(Smi::RawCast(data_.At(kLocalVariablesOffset)));
}
intptr_t BytecodeComponentData::GetAnnotationsOffset() const {
return Smi::Value(Smi::RawCast(data_.At(kAnnotationsOffset)));
}
void BytecodeComponentData::SetObject(intptr_t index, const Object& obj) const {
data_.SetAt(kNumFields + index, obj);
}
RawObject* BytecodeComponentData::GetObject(intptr_t index) const {
return data_.At(kNumFields + index);
}
RawArray* BytecodeComponentData::New(Zone* zone,
intptr_t version,
intptr_t num_objects,
intptr_t strings_header_offset,
intptr_t strings_contents_offset,
intptr_t object_offsets_offset,
intptr_t objects_contents_offset,
intptr_t main_offset,
intptr_t num_libraries,
intptr_t library_index_offset,
intptr_t libraries_offset,
intptr_t num_classes,
intptr_t classes_offset,
intptr_t members_offset,
intptr_t num_codes,
intptr_t codes_offset,
intptr_t source_positions_offset,
intptr_t source_files_offset,
intptr_t line_starts_offset,
intptr_t local_variables_offset,
intptr_t annotations_offset,
Heap::Space space) {
const Array& data =
Array::Handle(zone, Array::New(kNumFields + num_objects, space));
Smi& smi_handle = Smi::Handle(zone);
smi_handle = Smi::New(version);
data.SetAt(kVersion, smi_handle);
smi_handle = Smi::New(strings_header_offset);
data.SetAt(kStringsHeaderOffset, smi_handle);
smi_handle = Smi::New(strings_contents_offset);
data.SetAt(kStringsContentsOffset, smi_handle);
smi_handle = Smi::New(object_offsets_offset);
data.SetAt(kObjectOffsetsOffset, smi_handle);
smi_handle = Smi::New(num_objects);
data.SetAt(kNumObjects, smi_handle);
smi_handle = Smi::New(objects_contents_offset);
data.SetAt(kObjectsContentsOffset, smi_handle);
smi_handle = Smi::New(main_offset);
data.SetAt(kMainOffset, smi_handle);
smi_handle = Smi::New(num_libraries);
data.SetAt(kNumLibraries, smi_handle);
smi_handle = Smi::New(library_index_offset);
data.SetAt(kLibraryIndexOffset, smi_handle);
smi_handle = Smi::New(libraries_offset);
data.SetAt(kLibrariesOffset, smi_handle);
smi_handle = Smi::New(num_classes);
data.SetAt(kNumClasses, smi_handle);
smi_handle = Smi::New(classes_offset);
data.SetAt(kClassesOffset, smi_handle);
smi_handle = Smi::New(members_offset);
data.SetAt(kMembersOffset, smi_handle);
smi_handle = Smi::New(num_codes);
data.SetAt(kNumCodes, smi_handle);
smi_handle = Smi::New(codes_offset);
data.SetAt(kCodesOffset, smi_handle);
smi_handle = Smi::New(source_positions_offset);
data.SetAt(kSourcePositionsOffset, smi_handle);
smi_handle = Smi::New(source_files_offset);
data.SetAt(kSourceFilesOffset, smi_handle);
smi_handle = Smi::New(line_starts_offset);
data.SetAt(kLineStartsOffset, smi_handle);
smi_handle = Smi::New(local_variables_offset);
data.SetAt(kLocalVariablesOffset, smi_handle);
smi_handle = Smi::New(annotations_offset);
data.SetAt(kAnnotationsOffset, smi_handle);
return data.raw();
}
RawError* BytecodeReader::ReadFunctionBytecode(Thread* thread,
const Function& function) {
ASSERT(!FLAG_precompiled_mode);
ASSERT(!function.HasBytecode());
ASSERT(thread->sticky_error() == Error::null());
ASSERT(Thread::Current()->IsMutatorThread());
VMTagScope tagScope(thread, VMTag::kLoadBytecodeTagId);
#if defined(SUPPORT_TIMELINE)
TimelineDurationScope tds(thread, Timeline::GetCompilerStream(),
"BytecodeReader::ReadFunctionBytecode");
// This increases bytecode reading time by ~7%, so only keep it around for
// debugging.
#if defined(DEBUG)
tds.SetNumArguments(1);
tds.CopyArgument(0, "Function", function.ToQualifiedCString());
#endif // defined(DEBUG)
#endif // !defined(SUPPORT_TIMELINE)
LongJumpScope jump;
if (setjmp(*jump.Set()) == 0) {
StackZone stack_zone(thread);
Zone* const zone = stack_zone.GetZone();
HANDLESCOPE(thread);
auto& bytecode = Bytecode::Handle(zone);
switch (function.kind()) {
case RawFunction::kImplicitGetter:
bytecode = Object::implicit_getter_bytecode().raw();
break;
case RawFunction::kImplicitSetter:
bytecode = Object::implicit_setter_bytecode().raw();
break;
case RawFunction::kImplicitStaticGetter:
if (!IsStaticFieldGetterGeneratedAsInitializer(function, zone)) {
bytecode = Object::implicit_static_getter_bytecode().raw();
}
break;
case RawFunction::kMethodExtractor:
bytecode = Object::method_extractor_bytecode().raw();
break;
case RawFunction::kInvokeFieldDispatcher:
if (Class::Handle(zone, function.Owner()).id() == kClosureCid) {
bytecode = Object::invoke_closure_bytecode().raw();
} else {
bytecode = Object::invoke_field_bytecode().raw();
}
break;
case RawFunction::kNoSuchMethodDispatcher:
bytecode = Object::nsm_dispatcher_bytecode().raw();
break;
case RawFunction::kDynamicInvocationForwarder: {
const Function& target =
Function::Handle(zone, function.ForwardingTarget());
if (!target.HasBytecode()) {
// The forwarder will use the target's bytecode to handle optional
// parameters.
const Error& error =
Error::Handle(zone, ReadFunctionBytecode(thread, target));
if (!error.IsNull()) {
return error.raw();
}
}
{
const Script& script = Script::Handle(zone, target.script());
TranslationHelper translation_helper(thread);
translation_helper.InitFromScript(script);
ActiveClass active_class;
BytecodeComponentData bytecode_component(
&Array::Handle(zone, translation_helper.GetBytecodeComponent()));
ASSERT(!bytecode_component.IsNull());
BytecodeReaderHelper bytecode_reader(
&translation_helper, &active_class, &bytecode_component);
const Array& checks = Array::Handle(
zone, bytecode_reader.CreateForwarderChecks(target));
function.SetForwardingChecks(checks);
}
bytecode = Object::dynamic_invocation_forwarder_bytecode().raw();
} break;
default:
break;
}
if (!bytecode.IsNull()) {
function.AttachBytecode(bytecode);
} else if (function.is_declared_in_bytecode()) {
const intptr_t code_offset = function.bytecode_offset();
if (code_offset != 0) {
CompilerState compiler_state(thread);
const Script& script = Script::Handle(zone, function.script());
TranslationHelper translation_helper(thread);
translation_helper.InitFromScript(script);
ActiveClass active_class;
// Setup a [ActiveClassScope] and a [ActiveMemberScope] which will be
// used e.g. for type translation.
const Class& klass = Class::Handle(zone, function.Owner());
Function& outermost_function =
Function::Handle(zone, function.GetOutermostFunction());
ActiveClassScope active_class_scope(&active_class, &klass);
ActiveMemberScope active_member(&active_class, &outermost_function);
BytecodeComponentData bytecode_component(
&Array::Handle(zone, translation_helper.GetBytecodeComponent()));
ASSERT(!bytecode_component.IsNull());
BytecodeReaderHelper bytecode_reader(&translation_helper, &active_class,
&bytecode_component);
bytecode_reader.ReadCode(function, code_offset);
}
}
return Error::null();
} else {
return thread->StealStickyError();
}
}
RawObject* BytecodeReader::ReadAnnotation(const Field& annotation_field) {
ASSERT(annotation_field.is_declared_in_bytecode());
Thread* thread = Thread::Current();
Zone* zone = thread->zone();
ASSERT(thread->IsMutatorThread());
const Script& script = Script::Handle(zone, annotation_field.Script());
TranslationHelper translation_helper(thread);
translation_helper.InitFromScript(script);
ActiveClass active_class;
BytecodeComponentData bytecode_component(
&Array::Handle(zone, translation_helper.GetBytecodeComponent()));
ASSERT(!bytecode_component.IsNull());
BytecodeReaderHelper bytecode_reader(&translation_helper, &active_class,
&bytecode_component);
AlternativeReadingScope alt(&bytecode_reader.reader(),
annotation_field.bytecode_offset());
return bytecode_reader.ReadObject();
}
RawArray* BytecodeReader::ReadExtendedAnnotations(const Field& annotation_field,
intptr_t count) {
ASSERT(annotation_field.is_declared_in_bytecode());
Thread* thread = Thread::Current();
Zone* zone = thread->zone();
ASSERT(thread->IsMutatorThread());
const Script& script = Script::Handle(zone, annotation_field.Script());
TranslationHelper translation_helper(thread);
translation_helper.InitFromScript(script);
ActiveClass active_class;
BytecodeComponentData bytecode_component(
&Array::Handle(zone, translation_helper.GetBytecodeComponent()));
ASSERT(!bytecode_component.IsNull());
BytecodeReaderHelper bytecode_reader(&translation_helper, &active_class,
&bytecode_component);
AlternativeReadingScope alt(&bytecode_reader.reader(),
annotation_field.bytecode_offset());
bytecode_reader.ReadObject(); // Discard main annotation.
Array& result = Array::Handle(zone, Array::New(count));
Object& element = Object::Handle(zone);
for (intptr_t i = 0; i < count; i++) {
element = bytecode_reader.ReadObject();
result.SetAt(i, element);
}
return result.raw();
}
void BytecodeReader::ResetObjectTable(const KernelProgramInfo& info) {
Thread* thread = Thread::Current();
TranslationHelper translation_helper(thread);
translation_helper.InitFromKernelProgramInfo(info);
ActiveClass active_class;
BytecodeComponentData bytecode_component(&Array::Handle(
thread->zone(), translation_helper.GetBytecodeComponent()));
ASSERT(!bytecode_component.IsNull());
BytecodeReaderHelper bytecode_reader(&translation_helper, &active_class,
&bytecode_component);
bytecode_reader.ResetObjects();
}
void BytecodeReader::LoadClassDeclaration(const Class& cls) {
TIMELINE_DURATION(Thread::Current(), Compiler,
"BytecodeReader::LoadClassDeclaration");
ASSERT(cls.is_declared_in_bytecode());
ASSERT(!cls.is_declaration_loaded());
Thread* thread = Thread::Current();
Zone* zone = thread->zone();
ASSERT(thread->IsMutatorThread());
const Script& script = Script::Handle(zone, cls.script());
TranslationHelper translation_helper(thread);
translation_helper.InitFromScript(script);
ActiveClass active_class;
ActiveClassScope active_class_scope(&active_class, &cls);
BytecodeComponentData bytecode_component(
&Array::Handle(zone, translation_helper.GetBytecodeComponent()));
ASSERT(!bytecode_component.IsNull());
BytecodeReaderHelper bytecode_reader(&translation_helper, &active_class,
&bytecode_component);
AlternativeReadingScope alt(&bytecode_reader.reader(), cls.bytecode_offset());
bytecode_reader.ReadClassDeclaration(cls);
}
void BytecodeReader::FinishClassLoading(const Class& cls) {
ASSERT(cls.is_declared_in_bytecode());
Thread* thread = Thread::Current();
Zone* zone = thread->zone();
ASSERT(thread->IsMutatorThread());
const Script& script = Script::Handle(zone, cls.script());
TranslationHelper translation_helper(thread);
translation_helper.InitFromScript(script);
ActiveClass active_class;
ActiveClassScope active_class_scope(&active_class, &cls);
BytecodeComponentData bytecode_component(
&Array::Handle(zone, translation_helper.GetBytecodeComponent()));
ASSERT(!bytecode_component.IsNull());
BytecodeReaderHelper bytecode_reader(&translation_helper, &active_class,
&bytecode_component);
AlternativeReadingScope alt(&bytecode_reader.reader(), cls.bytecode_offset());
// If this is a dart:internal.ClassID class ignore field declarations
// contained in the Kernel file and instead inject our own const
// fields.
const bool discard_fields = cls.InjectCIDFields();
bytecode_reader.ReadMembers(cls, discard_fields);
}
RawObject* BytecodeReader::GetBytecodeAttribute(const Object& key,
const String& name) {
Thread* thread = Thread::Current();
Zone* zone = thread->zone();
const auto* object_store = thread->isolate()->object_store();
if (object_store->bytecode_attributes() == Object::null()) {
return Object::null();
}
BytecodeAttributesMap map(object_store->bytecode_attributes());
const auto& attrs = Array::CheckedHandle(zone, map.GetOrNull(key));
ASSERT(map.Release().raw() == object_store->bytecode_attributes());
if (attrs.IsNull()) {
return Object::null();
}
auto& obj = Object::Handle(zone);
for (intptr_t i = 0, n = attrs.Length(); i + 1 < n; i += 2) {
obj = attrs.At(i);
if (obj.raw() == name.raw()) {
return attrs.At(i + 1);
}
}
return Object::null();
}
InferredTypeMetadata InferredTypeBytecodeAttribute::GetInferredTypeAt(
Zone* zone,
const Array& attr,
intptr_t index) {
ASSERT(index + kNumElements <= attr.Length());
const auto& type = AbstractType::CheckedHandle(zone, attr.At(index + 1));
const intptr_t flags = Smi::Value(Smi::RawCast(attr.At(index + 2)));
if (!type.IsNull()) {
intptr_t cid = Type::Cast(type).type_class_id();
return InferredTypeMetadata(cid, flags);
} else {
return InferredTypeMetadata(kDynamicCid, flags);
}
}
#if !defined(PRODUCT)
RawLocalVarDescriptors* BytecodeReader::ComputeLocalVarDescriptors(
Zone* zone,
const Function& function,
const Bytecode& bytecode) {
ASSERT(function.is_declared_in_bytecode());
ASSERT(function.HasBytecode());
ASSERT(!bytecode.IsNull());
ASSERT(function.bytecode() == bytecode.raw());
LocalVarDescriptorsBuilder vars;
if (function.IsLocalFunction()) {
const auto& parent = Function::Handle(zone, function.parent_function());
ASSERT(parent.is_declared_in_bytecode() && parent.HasBytecode());
const auto& parent_bytecode = Bytecode::Handle(zone, parent.bytecode());
const auto& parent_vars = LocalVarDescriptors::Handle(
zone, parent_bytecode.GetLocalVarDescriptors());
for (intptr_t i = 0; i < parent_vars.Length(); ++i) {
RawLocalVarDescriptors::VarInfo var_info;
parent_vars.GetInfo(i, &var_info);
// Include parent's context variable if variable's scope
// intersects with the local function range.
// It is not enough to check if local function is declared within the
// scope of variable, because in case of async functions closure has
// the same range as original function.
if (var_info.kind() == RawLocalVarDescriptors::kContextVar &&
((var_info.begin_pos <= function.token_pos() &&
function.token_pos() <= var_info.end_pos) ||
(function.token_pos() <= var_info.begin_pos &&
var_info.begin_pos <= function.end_token_pos()))) {
vars.Add(LocalVarDescriptorsBuilder::VarDesc{
&String::Handle(zone, parent_vars.GetName(i)), var_info});
}
}
}
if (bytecode.HasLocalVariablesInfo()) {
intptr_t scope_id = 0;
intptr_t context_level = -1;
BytecodeLocalVariablesIterator local_vars(zone, bytecode);
while (local_vars.MoveNext()) {
switch (local_vars.Kind()) {
case BytecodeLocalVariablesIterator::kScope: {
++scope_id;
context_level = local_vars.ContextLevel();
} break;
case BytecodeLocalVariablesIterator::kVariableDeclaration: {
LocalVarDescriptorsBuilder::VarDesc desc;
desc.name = &String::Handle(zone, local_vars.Name());
if (local_vars.IsCaptured()) {
desc.info.set_kind(RawLocalVarDescriptors::kContextVar);
desc.info.scope_id = context_level;
desc.info.set_index(local_vars.Index());
} else {
desc.info.set_kind(RawLocalVarDescriptors::kStackVar);
desc.info.scope_id = scope_id;
if (local_vars.Index() < 0) {
// Parameter
ASSERT(local_vars.Index() < -kKBCParamEndSlotFromFp);
desc.info.set_index(-local_vars.Index() - kKBCParamEndSlotFromFp);
} else {
desc.info.set_index(-local_vars.Index());
}
}
desc.info.declaration_pos = local_vars.DeclarationTokenPos();
desc.info.begin_pos = local_vars.StartTokenPos();
desc.info.end_pos = local_vars.EndTokenPos();
vars.Add(desc);
} break;
case BytecodeLocalVariablesIterator::kContextVariable: {
ASSERT(local_vars.Index() >= 0);
const intptr_t context_variable_index = -local_vars.Index();
LocalVarDescriptorsBuilder::VarDesc desc;
desc.name = &Symbols::CurrentContextVar();
desc.info.set_kind(RawLocalVarDescriptors::kSavedCurrentContext);
desc.info.scope_id = 0;
desc.info.declaration_pos = TokenPosition::kMinSource;
desc.info.begin_pos = TokenPosition::kMinSource;
desc.info.end_pos = TokenPosition::kMinSource;
desc.info.set_index(context_variable_index);
vars.Add(desc);
} break;
}
}
}
return vars.Done();
}
#endif // !defined(PRODUCT)
bool IsStaticFieldGetterGeneratedAsInitializer(const Function& function,
Zone* zone) {
ASSERT(function.kind() == RawFunction::kImplicitStaticGetter);
const auto& field = Field::Handle(zone, function.accessor_field());
return field.is_declared_in_bytecode() && field.is_const() &&
field.has_nontrivial_initializer();
}
} // namespace kernel
} // namespace dart
#endif // !defined(DART_PRECOMPILED_RUNTIME)
|
#pragma once
struct RenderBatchParam
{
glm::mat4 modelMatrix;
};
struct RenderEntityParams
{
glm::vec3 position;
glm::mat4 orientation; // and scale
RenderModelHandle model;
int renderMask{ 0 }; // if 0, it gets rendered everywhere
// Must point to valid, living memory! The renderer doesn't copy the renderbatch
// data, it just references it
RenderBatchParam* batch{ nullptr };
uint32_t batchSize{ 0 };
};
/*
Copyright (c) 2021 Admer456
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.
*/
|
//--------------------------------------------------------------------------------------
// File: SpriteBatch.cpp
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkID=615561
//--------------------------------------------------------------------------------------
#include "pch.h"
#include "SpriteBatch.h"
#include "CommonStates.h"
#include "VertexTypes.h"
#include "SharedResourcePool.h"
#include "AlignedNew.h"
#include "ResourceUploadBatch.h"
#include "GraphicsMemory.h"
#include "DirectXHelpers.h"
using namespace DirectX;
using Microsoft::WRL::ComPtr;
namespace
{
// Include the precompiled shader code.
#ifdef _GAMING_XBOX_SCARLETT
#include "Shaders/Compiled/XboxGamingScarlettSpriteEffect_SpriteVertexShader.inc"
#include "Shaders/Compiled/XboxGamingScarlettSpriteEffect_SpritePixelShader.inc"
#include "Shaders/Compiled/XboxGamingScarlettSpriteEffect_SpriteVertexShaderHeap.inc"
#include "Shaders/Compiled/XboxGamingScarlettSpriteEffect_SpritePixelShaderHeap.inc"
#elif defined(_GAMING_XBOX)
#include "Shaders/Compiled/XboxGamingXboxOneSpriteEffect_SpriteVertexShader.inc"
#include "Shaders/Compiled/XboxGamingXboxOneSpriteEffect_SpritePixelShader.inc"
#include "Shaders/Compiled/XboxGamingXboxOneSpriteEffect_SpriteVertexShaderHeap.inc"
#include "Shaders/Compiled/XboxGamingXboxOneSpriteEffect_SpritePixelShaderHeap.inc"
#elif defined(_XBOX_ONE) && defined(_TITLE)
#include "Shaders/Compiled/XboxOneSpriteEffect_SpriteVertexShader.inc"
#include "Shaders/Compiled/XboxOneSpriteEffect_SpritePixelShader.inc"
#include "Shaders/Compiled/XboxOneSpriteEffect_SpriteVertexShaderHeap.inc"
#include "Shaders/Compiled/XboxOneSpriteEffect_SpritePixelShaderHeap.inc"
#else
#include "Shaders/Compiled/SpriteEffect_SpriteVertexShader.inc"
#include "Shaders/Compiled/SpriteEffect_SpritePixelShader.inc"
#include "Shaders/Compiled/SpriteEffect_SpriteVertexShaderHeap.inc"
#include "Shaders/Compiled/SpriteEffect_SpritePixelShaderHeap.inc"
#endif
inline bool operator != (D3D12_GPU_DESCRIPTOR_HANDLE a, D3D12_GPU_DESCRIPTOR_HANDLE b) noexcept
{
return a.ptr != b.ptr;
}
inline bool operator < (D3D12_GPU_DESCRIPTOR_HANDLE a, D3D12_GPU_DESCRIPTOR_HANDLE b) noexcept
{
return a.ptr < b.ptr;
}
// Helper converts a RECT to XMVECTOR.
inline XMVECTOR LoadRect(_In_ RECT const* rect) noexcept
{
XMVECTOR v = XMLoadInt4(reinterpret_cast<uint32_t const*>(rect));
v = XMConvertVectorIntToFloat(v, 0);
// Convert right/bottom to width/height.
v = XMVectorSubtract(v, XMVectorPermute<0, 1, 4, 5>(g_XMZero, v));
return v;
}
}
// Internal SpriteBatch implementation class.
__declspec(align(16)) class SpriteBatch::Impl : public AlignedNew<SpriteBatch::Impl>
{
public:
Impl(_In_ ID3D12Device* device,
ResourceUploadBatch& upload,
const SpriteBatchPipelineStateDescription& psoDesc,
const D3D12_VIEWPORT* viewport);
void XM_CALLCONV Begin(
_In_ ID3D12GraphicsCommandList* commandList,
SpriteSortMode sortMode = SpriteSortMode_Deferred,
FXMMATRIX transformMatrix = MatrixIdentity);
void End();
void XM_CALLCONV Draw(
D3D12_GPU_DESCRIPTOR_HANDLE texture,
XMUINT2 const& textureSize,
FXMVECTOR destination,
_In_opt_ RECT const* sourceRectangle,
FXMVECTOR color,
FXMVECTOR originRotationDepth,
unsigned int flags);
// Info about a single sprite that is waiting to be drawn.
__declspec(align(16)) struct SpriteInfo : public AlignedNew<SpriteInfo>
{
XMFLOAT4A source;
XMFLOAT4A destination;
XMFLOAT4A color;
XMFLOAT4A originRotationDepth;
D3D12_GPU_DESCRIPTOR_HANDLE texture;
XMVECTOR textureSize;
unsigned int flags;
// Combine values from the public SpriteEffects enum with these internal-only flags.
static const unsigned int SourceInTexels = 4;
static const unsigned int DestSizeInPixels = 8;
static_assert((SpriteEffects_FlipBoth & (SourceInTexels | DestSizeInPixels)) == 0, "Flag bits must not overlap");
};
DXGI_MODE_ROTATION mRotation;
bool mSetViewport;
D3D12_VIEWPORT mViewPort;
D3D12_GPU_DESCRIPTOR_HANDLE mSampler;
private:
// Implementation helper methods.
void GrowSpriteQueue();
void PrepareForRendering();
void FlushBatch();
void SortSprites();
void GrowSortedSprites();
void RenderBatch(
D3D12_GPU_DESCRIPTOR_HANDLE texture,
XMVECTOR textureSize,
_In_reads_(count) SpriteInfo const* const* sprites,
size_t count);
static void XM_CALLCONV RenderSprite(_In_ SpriteInfo const* sprite,
_Out_writes_(VerticesPerSprite) VertexPositionColorTexture* vertices,
FXMVECTOR textureSize,
FXMVECTOR inverseTextureSize) noexcept;
XMMATRIX GetViewportTransform(_In_ DXGI_MODE_ROTATION rotation);
// Constants.
static const size_t MaxBatchSize = 2048;
static const size_t MinBatchSize = 128;
static const size_t InitialQueueSize = 64;
static const size_t VerticesPerSprite = 4;
static const size_t IndicesPerSprite = 6;
//
// The following functions and members are used to create the default pipeline state objects.
//
static const D3D12_SHADER_BYTECODE s_DefaultVertexShaderByteCodeStatic;
static const D3D12_SHADER_BYTECODE s_DefaultPixelShaderByteCodeStatic;
static const D3D12_SHADER_BYTECODE s_DefaultVertexShaderByteCodeHeap;
static const D3D12_SHADER_BYTECODE s_DefaultPixelShaderByteCodeHeap;
static const D3D12_INPUT_LAYOUT_DESC s_DefaultInputLayoutDesc;
// Queue of sprites waiting to be drawn.
std::unique_ptr<SpriteInfo[]> mSpriteQueue;
size_t mSpriteQueueCount;
size_t mSpriteQueueArraySize;
// To avoid needlessly copying around bulky SpriteInfo structures, we leave that
// actual data alone and just sort this array of pointers instead. But we want contiguous
// memory for cache efficiency, so these pointers are just shortcuts into the single
// mSpriteQueue array, and we take care to keep them in order when sorting is disabled.
std::vector<SpriteInfo const*> mSortedSprites;
// Mode settings from the last Begin call.
bool mInBeginEndPair;
SpriteSortMode mSortMode;
ComPtr<ID3D12PipelineState> mPSO;
ComPtr<ID3D12RootSignature> mRootSignature;
XMMATRIX mTransformMatrix;
ComPtr<ID3D12GraphicsCommandList> mCommandList;
// Batched data
GraphicsResource mVertexSegment;
size_t mVertexPageSize;
size_t mSpriteCount;
GraphicsResource mConstantBuffer;
enum RootParameterIndex
{
TextureSRV,
ConstantBuffer,
TextureSampler,
RootParameterCount
};
// Only one of these helpers is allocated per D3D device, even if there are multiple SpriteBatch instances.
struct DeviceResources
{
DeviceResources(_In_ ID3D12Device* device, ResourceUploadBatch& upload);
ComPtr<ID3D12Resource> indexBuffer;
D3D12_INDEX_BUFFER_VIEW indexBufferView;
ComPtr<ID3D12RootSignature> rootSignatureStatic;
ComPtr<ID3D12RootSignature> rootSignatureHeap;
ID3D12Device* mDevice;
private:
void CreateIndexBuffer(_In_ ID3D12Device* device, ResourceUploadBatch& upload);
void CreateRootSignatures(_In_ ID3D12Device* device);
static std::vector<short> CreateIndexValues();
};
// Per-device data.
std::shared_ptr<DeviceResources> mDeviceResources;
static SharedResourcePool<ID3D12Device*, DeviceResources, ResourceUploadBatch&> deviceResourcesPool;
};
// Global pools of per-device and per-context SpriteBatch resources.
SharedResourcePool<ID3D12Device*, SpriteBatch::Impl::DeviceResources, ResourceUploadBatch&> SpriteBatch::Impl::deviceResourcesPool;
// Constants.
const XMMATRIX SpriteBatch::MatrixIdentity = XMMatrixIdentity();
const XMFLOAT2 SpriteBatch::Float2Zero(0, 0);
const D3D12_SHADER_BYTECODE SpriteBatch::Impl::s_DefaultVertexShaderByteCodeStatic = {SpriteEffect_SpriteVertexShader, sizeof(SpriteEffect_SpriteVertexShader)};
const D3D12_SHADER_BYTECODE SpriteBatch::Impl::s_DefaultPixelShaderByteCodeStatic = {SpriteEffect_SpritePixelShader, sizeof(SpriteEffect_SpritePixelShader)};
const D3D12_SHADER_BYTECODE SpriteBatch::Impl::s_DefaultVertexShaderByteCodeHeap = { SpriteEffect_SpriteVertexShaderHeap, sizeof(SpriteEffect_SpriteVertexShaderHeap) };
const D3D12_SHADER_BYTECODE SpriteBatch::Impl::s_DefaultPixelShaderByteCodeHeap = { SpriteEffect_SpritePixelShaderHeap, sizeof(SpriteEffect_SpritePixelShaderHeap) };
const D3D12_INPUT_LAYOUT_DESC SpriteBatch::Impl::s_DefaultInputLayoutDesc = VertexPositionColorTexture::InputLayout;
// Matches CommonStates::AlphaBlend
const D3D12_BLEND_DESC SpriteBatchPipelineStateDescription::s_DefaultBlendDesc =
{
FALSE, // AlphaToCoverageEnable
FALSE, // IndependentBlendEnable
{ {
TRUE, // BlendEnable
FALSE, // LogicOpEnable
D3D12_BLEND_ONE, // SrcBlend
D3D12_BLEND_INV_SRC_ALPHA, // DestBlend
D3D12_BLEND_OP_ADD, // BlendOp
D3D12_BLEND_ONE, // SrcBlendAlpha
D3D12_BLEND_INV_SRC_ALPHA, // DestBlendAlpha
D3D12_BLEND_OP_ADD, // BlendOpAlpha
D3D12_LOGIC_OP_NOOP,
D3D12_COLOR_WRITE_ENABLE_ALL
} }
};
// Same to CommonStates::CullCounterClockwise
const D3D12_RASTERIZER_DESC SpriteBatchPipelineStateDescription::s_DefaultRasterizerDesc =
{
D3D12_FILL_MODE_SOLID,
D3D12_CULL_MODE_BACK,
FALSE, // FrontCounterClockwise
D3D12_DEFAULT_DEPTH_BIAS,
D3D12_DEFAULT_DEPTH_BIAS_CLAMP,
D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS,
TRUE, // DepthClipEnable
TRUE, // MultisampleEnable
FALSE, // AntialiasedLineEnable
0, // ForcedSampleCount
D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF
};
// Same as CommonStates::DepthNone
const D3D12_DEPTH_STENCIL_DESC SpriteBatchPipelineStateDescription::s_DefaultDepthStencilDesc =
{
FALSE, // DepthEnable
D3D12_DEPTH_WRITE_MASK_ZERO,
D3D12_COMPARISON_FUNC_LESS_EQUAL, // DepthFunc
FALSE, // StencilEnable
D3D12_DEFAULT_STENCIL_READ_MASK,
D3D12_DEFAULT_STENCIL_WRITE_MASK,
{
D3D12_STENCIL_OP_KEEP, // StencilFailOp
D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp
D3D12_STENCIL_OP_KEEP, // StencilPassOp
D3D12_COMPARISON_FUNC_ALWAYS // StencilFunc
}, // FrontFace
{
D3D12_STENCIL_OP_KEEP, // StencilFailOp
D3D12_STENCIL_OP_KEEP, // StencilDepthFailOp
D3D12_STENCIL_OP_KEEP, // StencilPassOp
D3D12_COMPARISON_FUNC_ALWAYS // StencilFunc
} // BackFace
};
// Per-device constructor.
SpriteBatch::Impl::DeviceResources::DeviceResources(_In_ ID3D12Device* device, ResourceUploadBatch& upload) :
indexBufferView{},
mDevice(device)
{
CreateIndexBuffer(device, upload);
CreateRootSignatures(device);
}
// Creates the SpriteBatch index buffer.
void SpriteBatch::Impl::DeviceResources::CreateIndexBuffer(_In_ ID3D12Device* device, ResourceUploadBatch& upload)
{
static_assert((MaxBatchSize * VerticesPerSprite) < USHRT_MAX, "MaxBatchSize too large for 16-bit indices");
CD3DX12_HEAP_PROPERTIES heapProps(D3D12_HEAP_TYPE_DEFAULT);
CD3DX12_RESOURCE_DESC bufferDesc = CD3DX12_RESOURCE_DESC::Buffer(sizeof(short) * MaxBatchSize * IndicesPerSprite);
// Create the constant buffer.
ThrowIfFailed(device->CreateCommittedResource(
&heapProps,
D3D12_HEAP_FLAG_NONE,
&bufferDesc,
D3D12_RESOURCE_STATE_COPY_DEST,
nullptr,
IID_GRAPHICS_PPV_ARGS(indexBuffer.ReleaseAndGetAddressOf())));
SetDebugObjectName(indexBuffer.Get(), L"SpriteBatch");
auto indexValues = CreateIndexValues();
D3D12_SUBRESOURCE_DATA indexDataDesc = {};
indexDataDesc.pData = indexValues.data();
indexDataDesc.RowPitch = static_cast<LONG_PTR>(bufferDesc.Width);
indexDataDesc.SlicePitch = indexDataDesc.RowPitch;
// Upload the resource
upload.Upload(indexBuffer.Get(), 0, &indexDataDesc, 1);
upload.Transition(indexBuffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDEX_BUFFER);
SetDebugObjectName(indexBuffer.Get(), L"DirectXTK:SpriteBatch Index Buffer");
// Create the index buffer view
indexBufferView.BufferLocation = indexBuffer->GetGPUVirtualAddress();
indexBufferView.Format = DXGI_FORMAT_R16_UINT;
indexBufferView.SizeInBytes = static_cast<UINT>(bufferDesc.Width);
}
void SpriteBatch::Impl::DeviceResources::CreateRootSignatures(_In_ ID3D12Device* device)
{
D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags =
D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS |
D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS;
CD3DX12_DESCRIPTOR_RANGE textureSRV(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0);
{
// Same as CommonStates::StaticLinearClamp
CD3DX12_STATIC_SAMPLER_DESC sampler(
0, // register
D3D12_FILTER_MIN_MAG_MIP_LINEAR,
D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
0.f,
16,
D3D12_COMPARISON_FUNC_LESS_EQUAL,
D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE,
0.f,
D3D12_FLOAT32_MAX,
D3D12_SHADER_VISIBILITY_PIXEL);
CD3DX12_ROOT_PARAMETER rootParameters[RootParameterIndex::RootParameterCount - 1] = {};
rootParameters[RootParameterIndex::TextureSRV].InitAsDescriptorTable(1, &textureSRV, D3D12_SHADER_VISIBILITY_PIXEL);
rootParameters[RootParameterIndex::ConstantBuffer].InitAsConstantBufferView(0, 0, D3D12_SHADER_VISIBILITY_ALL);
CD3DX12_ROOT_SIGNATURE_DESC rsigDesc;
rsigDesc.Init(_countof(rootParameters), rootParameters, 1, &sampler, rootSignatureFlags);
ThrowIfFailed(::CreateRootSignature(device, &rsigDesc, rootSignatureStatic.ReleaseAndGetAddressOf()));
SetDebugObjectName(rootSignatureStatic.Get(), L"SpriteBatch");
}
{
CD3DX12_DESCRIPTOR_RANGE textureSampler(D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0);
CD3DX12_ROOT_PARAMETER rootParameters[RootParameterIndex::RootParameterCount] = {};
rootParameters[RootParameterIndex::TextureSRV].InitAsDescriptorTable(1, &textureSRV, D3D12_SHADER_VISIBILITY_PIXEL);
rootParameters[RootParameterIndex::ConstantBuffer].InitAsConstantBufferView(0, 0, D3D12_SHADER_VISIBILITY_ALL);
rootParameters[RootParameterIndex::TextureSampler].InitAsDescriptorTable(1, &textureSampler, D3D12_SHADER_VISIBILITY_PIXEL);
CD3DX12_ROOT_SIGNATURE_DESC rsigDesc;
rsigDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, rootSignatureFlags);
ThrowIfFailed(::CreateRootSignature(device, &rsigDesc, rootSignatureHeap.ReleaseAndGetAddressOf()));
SetDebugObjectName(rootSignatureHeap.Get(), L"SpriteBatch");
}
}
// Helper for populating the SpriteBatch index buffer.
std::vector<short> SpriteBatch::Impl::DeviceResources::CreateIndexValues()
{
std::vector<short> indices;
indices.reserve(MaxBatchSize * IndicesPerSprite);
for (size_t j = 0; j < MaxBatchSize * VerticesPerSprite; j += VerticesPerSprite)
{
short i = static_cast<short>(j);
indices.push_back(i);
indices.push_back(i + 1);
indices.push_back(i + 2);
indices.push_back(i + 1);
indices.push_back(i + 3);
indices.push_back(i + 2);
}
return indices;
}
// Per-SpriteBatch constructor.
_Use_decl_annotations_
SpriteBatch::Impl::Impl(ID3D12Device* device, ResourceUploadBatch& upload, const SpriteBatchPipelineStateDescription& psoDesc, const D3D12_VIEWPORT* viewport)
: mRotation(DXGI_MODE_ROTATION_IDENTITY),
mSetViewport(false),
mViewPort{},
mSampler{},
mSpriteQueueCount(0),
mSpriteQueueArraySize(0),
mInBeginEndPair(false),
mSortMode(SpriteSortMode_Deferred),
mTransformMatrix(MatrixIdentity),
mVertexSegment{},
mVertexPageSize(sizeof(VertexPositionColorTexture) * MaxBatchSize * VerticesPerSprite),
mSpriteCount(0),
mDeviceResources(deviceResourcesPool.DemandCreate(device, upload))
{
if (viewport != nullptr)
{
mViewPort = *viewport;
mSetViewport = true;
}
D3D12_GRAPHICS_PIPELINE_STATE_DESC d3dDesc = {};
d3dDesc.InputLayout = s_DefaultInputLayoutDesc;
d3dDesc.BlendState = psoDesc.blendDesc;
d3dDesc.DepthStencilState = psoDesc.depthStencilDesc;
d3dDesc.RasterizerState = psoDesc.rasterizerDesc;
d3dDesc.DSVFormat = psoDesc.renderTargetState.dsvFormat;
d3dDesc.NodeMask = psoDesc.renderTargetState.nodeMask;
d3dDesc.NumRenderTargets = psoDesc.renderTargetState.numRenderTargets;
memcpy_s(d3dDesc.RTVFormats, sizeof(d3dDesc.RTVFormats), psoDesc.renderTargetState.rtvFormats, sizeof(DXGI_FORMAT) * D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT);
d3dDesc.SampleDesc = psoDesc.renderTargetState.sampleDesc;
d3dDesc.SampleMask = psoDesc.renderTargetState.sampleMask;
d3dDesc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED;
d3dDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
// Three choices: (1) static sampler, (2) heap sampler, or (3) custom signature & shaders
if (psoDesc.customRootSignature)
{
mRootSignature = psoDesc.customRootSignature;
}
else
{
mRootSignature = (psoDesc.samplerDescriptor.ptr) ? mDeviceResources->rootSignatureHeap.Get() : mDeviceResources->rootSignatureStatic.Get();
}
d3dDesc.pRootSignature = mRootSignature.Get();
if (psoDesc.customVertexShader.pShaderBytecode)
{
d3dDesc.VS = psoDesc.customVertexShader;
}
else
{
d3dDesc.VS = (psoDesc.samplerDescriptor.ptr) ? s_DefaultVertexShaderByteCodeHeap : s_DefaultVertexShaderByteCodeStatic;
}
if (psoDesc.customPixelShader.pShaderBytecode)
{
d3dDesc.PS = psoDesc.customPixelShader;
}
else
{
d3dDesc.PS = (psoDesc.samplerDescriptor.ptr) ? s_DefaultPixelShaderByteCodeHeap : s_DefaultPixelShaderByteCodeStatic;
}
if (psoDesc.samplerDescriptor.ptr)
{
mSampler = psoDesc.samplerDescriptor;
}
ThrowIfFailed(device->CreateGraphicsPipelineState(
&d3dDesc,
IID_GRAPHICS_PPV_ARGS(mPSO.GetAddressOf())));
SetDebugObjectName(mPSO.Get(), L"SpriteBatch");
}
// Begins a batch of sprite drawing operations.
_Use_decl_annotations_
void XM_CALLCONV SpriteBatch::Impl::Begin(
ID3D12GraphicsCommandList* commandList,
SpriteSortMode sortMode,
FXMMATRIX transformMatrix)
{
if (mInBeginEndPair)
{
DebugTrace("ERROR: Cannot nest Begin calls on a single SpriteBatch\n");
throw std::exception("SpriteBatch::Begin");
}
mSortMode = sortMode;
mTransformMatrix = transformMatrix;
mCommandList = commandList;
mSpriteCount = 0;
if (sortMode == SpriteSortMode_Immediate)
{
PrepareForRendering();
}
mInBeginEndPair = true;
}
// Ends a batch of sprite drawing operations.
void SpriteBatch::Impl::End()
{
if (!mInBeginEndPair)
{
DebugTrace("ERROR: Begin must be called before End\n");
throw std::exception("SpriteBatch::End");
}
if (mSortMode != SpriteSortMode_Immediate)
{
PrepareForRendering();
FlushBatch();
}
// Release this memory
mVertexSegment.Reset();
// Break circular reference chains, in case the state lambda closed
// over an object that holds a reference to this SpriteBatch.
mCommandList = nullptr;
mInBeginEndPair = false;
}
// Adds a single sprite to the queue.
_Use_decl_annotations_
void XM_CALLCONV SpriteBatch::Impl::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture,
XMUINT2 const& textureSize,
FXMVECTOR destination,
RECT const* sourceRectangle,
FXMVECTOR color,
FXMVECTOR originRotationDepth,
unsigned int flags)
{
if (!mInBeginEndPair)
{
DebugTrace("ERROR: Begin must be called before Draw\n");
throw std::exception("SpriteBatch::Draw");
}
if (!texture.ptr)
throw std::exception("Invalid texture for Draw");
// Get a pointer to the output sprite.
if (mSpriteQueueCount >= mSpriteQueueArraySize)
{
GrowSpriteQueue();
}
SpriteInfo* sprite = &mSpriteQueue[mSpriteQueueCount];
XMVECTOR dest = destination;
if (sourceRectangle)
{
// User specified an explicit source region.
XMVECTOR source = LoadRect(sourceRectangle);
XMStoreFloat4A(&sprite->source, source);
// If the destination size is relative to the source region, convert it to pixels.
if (!(flags & SpriteInfo::DestSizeInPixels))
{
dest = XMVectorPermute<0, 1, 6, 7>(dest, XMVectorMultiply(dest, source)); // dest.zw *= source.zw
}
flags |= SpriteInfo::SourceInTexels | SpriteInfo::DestSizeInPixels;
}
else
{
// No explicit source region, so use the entire texture.
static const XMVECTORF32 wholeTexture = { { {0, 0, 1, 1} } };
XMStoreFloat4A(&sprite->source, wholeTexture);
}
// Convert texture size
XMVECTOR textureSizeV = XMLoadUInt2(&textureSize);
// Store sprite parameters.
XMStoreFloat4A(&sprite->destination, dest);
XMStoreFloat4A(&sprite->color, color);
XMStoreFloat4A(&sprite->originRotationDepth, originRotationDepth);
sprite->texture = texture;
sprite->textureSize = textureSizeV;
sprite->flags = flags;
if (mSortMode == SpriteSortMode_Immediate)
{
// If we are in immediate mode, draw this sprite straight away.
RenderBatch(texture, textureSizeV, &sprite, 1);
}
else
{
// Queue this sprite for later sorting and batched rendering.
mSpriteQueueCount++;
}
}
// Dynamically expands the array used to store pending sprite information.
void SpriteBatch::Impl::GrowSpriteQueue()
{
// Grow by a factor of 2.
size_t newSize = std::max(InitialQueueSize, mSpriteQueueArraySize * 2);
// Allocate the new array.
auto newArray = std::make_unique<SpriteInfo[]>(newSize);
// Copy over any existing sprites.
for (size_t i = 0; i < mSpriteQueueCount; i++)
{
newArray[i] = mSpriteQueue[i];
}
// Replace the previous array with the new one.
mSpriteQueue = std::move(newArray);
mSpriteQueueArraySize = newSize;
// Clear any dangling SpriteInfo pointers left over from previous rendering.
mSortedSprites.clear();
}
// Sets up D3D device state ready for drawing sprites.
void SpriteBatch::Impl::PrepareForRendering()
{
auto commandList = mCommandList.Get();
// Set root signature
commandList->SetGraphicsRootSignature(mRootSignature.Get());
// Set render state
commandList->SetPipelineState(mPSO.Get());
commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
// Set the index buffer.
commandList->IASetIndexBuffer(&mDeviceResources->indexBufferView);
// Set the transform matrix.
XMMATRIX transformMatrix = (mRotation == DXGI_MODE_ROTATION_UNSPECIFIED)
? mTransformMatrix
: (mTransformMatrix * GetViewportTransform(mRotation));
mConstantBuffer = GraphicsMemory::Get(mDeviceResources->mDevice).AllocateConstant(transformMatrix);
commandList->SetGraphicsRootConstantBufferView(RootParameterIndex::ConstantBuffer, mConstantBuffer.GpuAddress());
}
// Sends queued sprites to the graphics device.
void SpriteBatch::Impl::FlushBatch()
{
if (!mSpriteQueueCount)
return;
SortSprites();
// Walk through the sorted sprite list, looking for adjacent entries that share a texture.
D3D12_GPU_DESCRIPTOR_HANDLE batchTexture = {};
XMVECTOR batchTextureSize = {};
size_t batchStart = 0;
for (size_t pos = 0; pos < mSpriteQueueCount; pos++)
{
D3D12_GPU_DESCRIPTOR_HANDLE texture = mSortedSprites[pos]->texture;
assert(texture.ptr != 0);
XMVECTOR textureSize = mSortedSprites[pos]->textureSize;
// Flush whenever the texture changes.
if (texture != batchTexture)
{
if (pos > batchStart)
{
RenderBatch(batchTexture, batchTextureSize, &mSortedSprites[batchStart], pos - batchStart);
}
batchTexture = texture;
batchTextureSize = textureSize;
batchStart = pos;
}
}
// Flush the final batch.
RenderBatch(batchTexture, batchTextureSize, &mSortedSprites[batchStart], mSpriteQueueCount - batchStart);
// Reset the queue.
mSpriteQueueCount = 0;
// When sorting is disabled, we persist mSortedSprites data from one batch to the next, to avoid
// uneccessary work in GrowSortedSprites. But we never reuse these when sorting, because re-sorting
// previously sorted items gives unstable ordering if some sprites have identical sort keys.
if (mSortMode != SpriteSortMode_Deferred)
{
mSortedSprites.clear();
}
}
// Sorts the array of queued sprites.
void SpriteBatch::Impl::SortSprites()
{
// Fill the mSortedSprites vector.
if (mSortedSprites.size() < mSpriteQueueCount)
{
GrowSortedSprites();
}
switch (mSortMode)
{
case SpriteSortMode_Texture:
// Sort by texture.
std::sort(mSortedSprites.begin(),
mSortedSprites.begin() + static_cast<int>(mSpriteQueueCount),
[](SpriteInfo const* x, SpriteInfo const* y) noexcept -> bool
{
return x->texture < y->texture;
});
break;
case SpriteSortMode_BackToFront:
// Sort back to front.
std::sort(mSortedSprites.begin(),
mSortedSprites.begin() + static_cast<int>(mSpriteQueueCount),
[](SpriteInfo const* x, SpriteInfo const* y) noexcept -> bool
{
return x->originRotationDepth.w > y->originRotationDepth.w;
});
break;
case SpriteSortMode_FrontToBack:
// Sort front to back.
std::sort(mSortedSprites.begin(),
mSortedSprites.begin() + static_cast<int>(mSpriteQueueCount),
[](SpriteInfo const* x, SpriteInfo const* y) noexcept -> bool
{
return x->originRotationDepth.w < y->originRotationDepth.w;
});
break;
default:
break;
}
}
// Populates the mSortedSprites vector with pointers to individual elements of the mSpriteQueue array.
void SpriteBatch::Impl::GrowSortedSprites()
{
size_t previousSize = mSortedSprites.size();
mSortedSprites.resize(mSpriteQueueCount);
for (size_t i = previousSize; i < mSpriteQueueCount; i++)
{
mSortedSprites[i] = &mSpriteQueue[i];
}
}
// Submits a batch of sprites to the GPU.
_Use_decl_annotations_
void SpriteBatch::Impl::RenderBatch(D3D12_GPU_DESCRIPTOR_HANDLE texture, XMVECTOR textureSize, SpriteInfo const* const* sprites, size_t count)
{
auto commandList = mCommandList.Get();
// Draw using the specified texture.
// **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor heap(s)
commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::TextureSRV, texture);
if (mSampler.ptr)
{
commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::TextureSampler, mSampler);
}
// Convert to vector format.
XMVECTOR inverseTextureSize = XMVectorReciprocal(textureSize);
while (count > 0)
{
// How many sprites do we want to draw?
size_t batchSize = count;
// How many sprites does the D3D vertex buffer have room for?
size_t remainingSpace = MaxBatchSize - mSpriteCount;
if (batchSize > remainingSpace)
{
if (remainingSpace < MinBatchSize)
{
// If we are out of room, or about to submit an excessively small batch, wrap back to the start of the vertex buffer.
mSpriteCount = 0;
batchSize = std::min(count, MaxBatchSize);
}
else
{
// Take however many sprites fit in what's left of the vertex buffer.
batchSize = remainingSpace;
}
}
// Allocate a new page of vertex memory if we're starting the batch
if (mSpriteCount == 0)
{
mVertexSegment = GraphicsMemory::Get(mDeviceResources->mDevice).Allocate(mVertexPageSize);
}
auto vertices = static_cast<VertexPositionColorTexture*>(mVertexSegment.Memory()) + mSpriteCount * VerticesPerSprite;
// Generate sprite vertex data.
for (size_t i = 0; i < batchSize; i++)
{
assert(i < count);
_Analysis_assume_(i < count);
RenderSprite(sprites[i], vertices, textureSize, inverseTextureSize);
vertices += VerticesPerSprite;
}
// Set the vertex buffer view
D3D12_VERTEX_BUFFER_VIEW vbv;
size_t spriteVertexTotalSize = sizeof(VertexPositionColorTexture) * VerticesPerSprite;
vbv.BufferLocation = mVertexSegment.GpuAddress() + (UINT64(mSpriteCount) * UINT64(spriteVertexTotalSize));
vbv.StrideInBytes = sizeof(VertexPositionColorTexture);
vbv.SizeInBytes = static_cast<UINT>(batchSize * spriteVertexTotalSize);
commandList->IASetVertexBuffers(0, 1, &vbv);
// Ok lads, the time has come for us draw ourselves some sprites!
UINT indexCount = static_cast<UINT>(batchSize * IndicesPerSprite);
commandList->DrawIndexedInstanced(indexCount, 1, 0, 0, 0);
// Advance the buffer position.
mSpriteCount += batchSize;
sprites += batchSize;
count -= batchSize;
}
}
// Generates vertex data for drawing a single sprite.
_Use_decl_annotations_
void XM_CALLCONV SpriteBatch::Impl::RenderSprite(SpriteInfo const* sprite, VertexPositionColorTexture* vertices, FXMVECTOR textureSize, FXMVECTOR inverseTextureSize) noexcept
{
// Load sprite parameters into SIMD registers.
XMVECTOR source = XMLoadFloat4A(&sprite->source);
XMVECTOR destination = XMLoadFloat4A(&sprite->destination);
XMVECTOR color = XMLoadFloat4A(&sprite->color);
XMVECTOR originRotationDepth = XMLoadFloat4A(&sprite->originRotationDepth);
float rotation = sprite->originRotationDepth.z;
unsigned int flags = sprite->flags;
// Extract the source and destination sizes into separate vectors.
XMVECTOR sourceSize = XMVectorSwizzle<2, 3, 2, 3>(source);
XMVECTOR destinationSize = XMVectorSwizzle<2, 3, 2, 3>(destination);
// Scale the origin offset by source size, taking care to avoid overflow if the source region is zero.
XMVECTOR isZeroMask = XMVectorEqual(sourceSize, XMVectorZero());
XMVECTOR nonZeroSourceSize = XMVectorSelect(sourceSize, g_XMEpsilon, isZeroMask);
XMVECTOR origin = XMVectorDivide(originRotationDepth, nonZeroSourceSize);
// Convert the source region from texels to mod-1 texture coordinate format.
if (flags & SpriteInfo::SourceInTexels)
{
source = XMVectorMultiply(source, inverseTextureSize);
sourceSize = XMVectorMultiply(sourceSize, inverseTextureSize);
}
else
{
origin = XMVectorMultiply(origin, inverseTextureSize);
}
// If the destination size is relative to the source region, convert it to pixels.
if (!(flags & SpriteInfo::DestSizeInPixels))
{
destinationSize = XMVectorMultiply(destinationSize, textureSize);
}
// Compute a 2x2 rotation matrix.
XMVECTOR rotationMatrix1;
XMVECTOR rotationMatrix2;
if (rotation != 0)
{
float sin, cos;
XMScalarSinCos(&sin, &cos, rotation);
XMVECTOR sinV = XMLoadFloat(&sin);
XMVECTOR cosV = XMLoadFloat(&cos);
rotationMatrix1 = XMVectorMergeXY(cosV, sinV);
rotationMatrix2 = XMVectorMergeXY(XMVectorNegate(sinV), cosV);
}
else
{
rotationMatrix1 = g_XMIdentityR0;
rotationMatrix2 = g_XMIdentityR1;
}
// The four corner vertices are computed by transforming these unit-square positions.
static XMVECTORF32 cornerOffsets[VerticesPerSprite] =
{
{ { { 0, 0, 0, 0 } } },
{ { { 1, 0, 0, 0 } } },
{ { { 0, 1, 0, 0 } } },
{ { { 1, 1, 0, 0 } } },
};
// Tricksy alert! Texture coordinates are computed from the same cornerOffsets
// table as vertex positions, but if the sprite is mirrored, this table
// must be indexed in a different order. This is done as follows:
//
// position = cornerOffsets[i]
// texcoord = cornerOffsets[i ^ SpriteEffects]
static_assert(SpriteEffects_FlipHorizontally == 1 &&
SpriteEffects_FlipVertically == 2, "If you change these enum values, the mirroring implementation must be updated to match");
const unsigned int mirrorBits = flags & 3u;
// Generate the four output vertices.
for (size_t i = 0; i < VerticesPerSprite; i++)
{
// Calculate position.
XMVECTOR cornerOffset = XMVectorMultiply(XMVectorSubtract(cornerOffsets[i], origin), destinationSize);
// Apply 2x2 rotation matrix.
XMVECTOR position1 = XMVectorMultiplyAdd(XMVectorSplatX(cornerOffset), rotationMatrix1, destination);
XMVECTOR position2 = XMVectorMultiplyAdd(XMVectorSplatY(cornerOffset), rotationMatrix2, position1);
// Set z = depth.
XMVECTOR position = XMVectorPermute<0, 1, 7, 6>(position2, originRotationDepth);
// Write position as a Float4, even though VertexPositionColor::position is an XMFLOAT3.
// This is faster, and harmless as we are just clobbering the first element of the
// following color field, which will immediately be overwritten with its correct value.
XMStoreFloat4(reinterpret_cast<XMFLOAT4*>(&vertices[i].position), position);
// Write the color.
XMStoreFloat4(&vertices[i].color, color);
// Compute and write the texture coordinate.
XMVECTOR textureCoordinate = XMVectorMultiplyAdd(cornerOffsets[static_cast<unsigned int>(i) ^ mirrorBits], sourceSize, source);
XMStoreFloat2(&vertices[i].textureCoordinate, textureCoordinate);
}
}
// Generates a viewport transform matrix for rendering sprites using x-right y-down screen pixel coordinates.
XMMATRIX SpriteBatch::Impl::GetViewportTransform(_In_ DXGI_MODE_ROTATION rotation)
{
if (!mSetViewport)
{
DebugTrace("ERROR: SpriteBatch requires viewport information via SetViewport\n");
throw std::exception("Viewport not set.");
}
// Compute the matrix.
float xScale = (mViewPort.Width > 0) ? 2.0f / mViewPort.Width : 0.0f;
float yScale = (mViewPort.Height > 0) ? 2.0f / mViewPort.Height : 0.0f;
switch (rotation)
{
case DXGI_MODE_ROTATION_ROTATE90:
return XMMATRIX
(
0, -yScale, 0, 0,
-xScale, 0, 0, 0,
0, 0, 1, 0,
1, 1, 0, 1
);
case DXGI_MODE_ROTATION_ROTATE270:
return XMMATRIX
(
0, yScale, 0, 0,
xScale, 0, 0, 0,
0, 0, 1, 0,
-1, -1, 0, 1
);
case DXGI_MODE_ROTATION_ROTATE180:
return XMMATRIX
(
-xScale, 0, 0, 0,
0, yScale, 0, 0,
0, 0, 1, 0,
1, -1, 0, 1
);
default:
return XMMATRIX
(
xScale, 0, 0, 0,
0, -yScale, 0, 0,
0, 0, 1, 0,
-1, 1, 0, 1
);
}
}
// Public constructor.
_Use_decl_annotations_
SpriteBatch::SpriteBatch(ID3D12Device* device,
ResourceUploadBatch& upload,
const SpriteBatchPipelineStateDescription& psoDesc,
const D3D12_VIEWPORT* viewport)
: pImpl(std::make_unique<Impl>(device, upload, psoDesc, viewport))
{
}
// Move constructor.
SpriteBatch::SpriteBatch(SpriteBatch&& moveFrom) noexcept
: pImpl(std::move(moveFrom.pImpl))
{
}
// Move assignment.
SpriteBatch& SpriteBatch::operator= (SpriteBatch&& moveFrom) noexcept
{
pImpl = std::move(moveFrom.pImpl);
return *this;
}
// Public destructor.
SpriteBatch::~SpriteBatch()
{
}
_Use_decl_annotations_
void XM_CALLCONV SpriteBatch::Begin(
ID3D12GraphicsCommandList* commandList,
SpriteSortMode sortMode,
FXMMATRIX transformMatrix)
{
pImpl->Begin(commandList, sortMode, transformMatrix);
}
_Use_decl_annotations_
void XM_CALLCONV SpriteBatch::Begin(
ID3D12GraphicsCommandList* commandList,
D3D12_GPU_DESCRIPTOR_HANDLE sampler,
SpriteSortMode sortMode,
FXMMATRIX transformMatrix)
{
if (!sampler.ptr)
throw std::exception("Invalid heap-based sampler for Begin");
if (!pImpl->mSampler.ptr)
{
DebugTrace("ERROR: sampler version of Begin requires SpriteBatch was created with a heap-based sampler\n");
throw std::exception("SpriteBatch::Begin");
}
pImpl->mSampler = sampler;
pImpl->Begin(commandList, sortMode, transformMatrix);
}
void SpriteBatch::End()
{
pImpl->End();
}
void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture,
XMUINT2 const& textureSize,
XMFLOAT2 const& position,
FXMVECTOR color)
{
XMVECTOR destination = XMVectorPermute<0, 1, 4, 5>(XMLoadFloat2(&position), g_XMOne); // x, y, 1, 1
pImpl->Draw(texture, textureSize, destination, nullptr, color, g_XMZero, 0);
}
_Use_decl_annotations_
void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture,
XMUINT2 const& textureSize,
XMFLOAT2 const& position,
RECT const* sourceRectangle,
FXMVECTOR color,
float rotation,
XMFLOAT2 const& origin,
float scale,
SpriteEffects effects,
float layerDepth)
{
XMVECTOR destination = XMVectorPermute<0, 1, 4, 4>(XMLoadFloat2(&position), XMLoadFloat(&scale)); // x, y, scale, scale
XMVECTOR originRotationDepth = XMVectorSet(origin.x, origin.y, rotation, layerDepth);
pImpl->Draw(texture, textureSize, destination, sourceRectangle, color, originRotationDepth, static_cast<unsigned int>(effects));
}
_Use_decl_annotations_
void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture,
XMUINT2 const& textureSize,
XMFLOAT2 const& position,
RECT const* sourceRectangle,
FXMVECTOR color,
float rotation,
XMFLOAT2 const& origin,
XMFLOAT2 const& scale,
SpriteEffects effects,
float layerDepth)
{
XMVECTOR destination = XMVectorPermute<0, 1, 4, 5>(XMLoadFloat2(&position), XMLoadFloat2(&scale)); // x, y, scale.x, scale.y
XMVECTOR originRotationDepth = XMVectorSet(origin.x, origin.y, rotation, layerDepth);
pImpl->Draw(texture, textureSize, destination, sourceRectangle, color, originRotationDepth, static_cast<unsigned int>(effects));
}
void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, XMUINT2 const& textureSize, FXMVECTOR position, FXMVECTOR color)
{
XMVECTOR destination = XMVectorPermute<0, 1, 4, 5>(position, g_XMOne); // x, y, 1, 1
pImpl->Draw(texture, textureSize, destination, nullptr, color, g_XMZero, 0);
}
_Use_decl_annotations_
void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture,
XMUINT2 const& textureSize,
FXMVECTOR position,
RECT const* sourceRectangle,
FXMVECTOR color,
float rotation,
FXMVECTOR origin,
float scale,
SpriteEffects effects,
float layerDepth)
{
XMVECTOR destination = XMVectorPermute<0, 1, 4, 4>(position, XMLoadFloat(&scale)); // x, y, scale, scale
XMVECTOR rotationDepth = XMVectorMergeXY(XMVectorReplicate(rotation), XMVectorReplicate(layerDepth));
XMVECTOR originRotationDepth = XMVectorPermute<0, 1, 4, 5>(origin, rotationDepth);
pImpl->Draw(texture, textureSize, destination, sourceRectangle, color, originRotationDepth, static_cast<unsigned int>(effects));
}
_Use_decl_annotations_
void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture,
XMUINT2 const& textureSize,
FXMVECTOR position,
RECT const* sourceRectangle,
FXMVECTOR color,
float rotation,
FXMVECTOR origin,
GXMVECTOR scale,
SpriteEffects effects,
float layerDepth)
{
XMVECTOR destination = XMVectorPermute<0, 1, 4, 5>(position, scale); // x, y, scale.x, scale.y
XMVECTOR rotationDepth = XMVectorMergeXY(XMVectorReplicate(rotation), XMVectorReplicate(layerDepth));
XMVECTOR originRotationDepth = XMVectorPermute<0, 1, 4, 5>(origin, rotationDepth);
pImpl->Draw(texture, textureSize, destination, sourceRectangle, color, originRotationDepth, static_cast<unsigned int>(effects));
}
void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture,
XMUINT2 const& textureSize,
RECT const& destinationRectangle,
FXMVECTOR color)
{
XMVECTOR destination = LoadRect(&destinationRectangle); // x, y, w, h
pImpl->Draw(texture, textureSize, destination, nullptr, color, g_XMZero, Impl::SpriteInfo::DestSizeInPixels);
}
_Use_decl_annotations_
void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture,
XMUINT2 const& textureSize,
RECT const& destinationRectangle,
RECT const* sourceRectangle,
FXMVECTOR color,
float rotation,
XMFLOAT2 const& origin,
SpriteEffects effects,
float layerDepth)
{
XMVECTOR destination = LoadRect(&destinationRectangle); // x, y, w, h
XMVECTOR originRotationDepth = XMVectorSet(origin.x, origin.y, rotation, layerDepth);
pImpl->Draw(texture, textureSize, destination, sourceRectangle, color, originRotationDepth, static_cast<unsigned int>(effects) | Impl::SpriteInfo::DestSizeInPixels);
}
void SpriteBatch::SetRotation(DXGI_MODE_ROTATION mode)
{
pImpl->mRotation = mode;
}
DXGI_MODE_ROTATION SpriteBatch::GetRotation() const noexcept
{
return pImpl->mRotation;
}
void SpriteBatch::SetViewport(const D3D12_VIEWPORT& viewPort)
{
pImpl->mSetViewport = true;
pImpl->mViewPort = viewPort;
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bitcoinrpc.h"
#include "db.h"
#include "init.h"
#include "main.h"
#include "miner.h"
#include "script.h"
#include "txdb.h"
#include "txmempool.h"
#include "work.h"
#include <random>
using namespace json_spirit;
using namespace std;
Value getsubsidy(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error("getsubsidy [nTarget]\n"
"Returns proof-of-work subsidy value for the specified value of target.");
return (uint64_t)GetProofOfWorkReward(0);
}
Value getmininginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error("getmininginfo\n"
"Returns an object containing mining-related information.");
uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
Object obj, diff, weight;
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
diff.push_back(Pair("proof-of-work", GetDifficulty()));
diff.push_back(Pair("proof-of-stake",
GetDifficulty(GetLastBlockIndex(boost::atomic_load(&pindexBest).get(), true))));
diff.push_back(Pair("search-interval", (int)stakeMaker.getLastCoinStakeSearchInterval()));
obj.push_back(Pair("difficulty", diff));
obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(0)));
obj.push_back(Pair("netmhashps", GetPoWMHashPS()));
obj.push_back(Pair("netstakeweight", GetPoSKernelPS()));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
weight.push_back(Pair("minimum", (uint64_t)nMinWeight));
weight.push_back(Pair("maximum", (uint64_t)nMaxWeight));
weight.push_back(Pair("combined", (uint64_t)nWeight));
obj.push_back(Pair("stakeweight", weight));
obj.push_back(Pair("stakeinterest", (uint64_t)COIN_YEAR_REWARD));
obj.push_back(Pair("testnet", Params().NetType() != Mainnet));
return obj;
}
Value getstakinginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error("getstakinginfo\n"
"Returns an object containing staking-related information.");
uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
const uint64_t nNetworkWeight = GetPoSKernelPS();
const bool staking = stakeMaker.getLastCoinStakeSearchInterval() && nWeight;
const unsigned int nTS = Params().TargetSpacing();
const int nExpectedTime = staking ? (nTS * nNetworkWeight / nWeight) : -1;
Object stakingCriteria;
const bool matureCoins = !!nWeight;
bool activeConnection = []() {
LOCK(cs_vNodes);
return !vNodes.empty();
}();
const bool unlocked = !(pwalletMain && pwalletMain->IsLocked());
const bool synced = !IsInitialBlockDownload();
const std::size_t stakableCoinsCount = []() {
std::vector<COutput> vCoins;
bool fIncludeColdStaking = Params().IsColdStakingEnabled() && GetBoolArg("-coldstaking", true);
pwalletMain->AvailableCoinsForStaking(vCoins, GetAdjustedTime(), fIncludeColdStaking, false);
return vCoins.size();
}();
stakingCriteria.push_back(Pair("mature-coins", matureCoins));
stakingCriteria.push_back(Pair("wallet-unlocked", unlocked));
stakingCriteria.push_back(Pair("online", activeConnection));
stakingCriteria.push_back(Pair("synced", synced));
Object obj;
obj.push_back(Pair("enabled", GetBoolArg("-staking", true)));
obj.push_back(Pair("staking", staking));
obj.push_back(Pair("staking-criteria", stakingCriteria));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("stakableoutputs", (int)stakableCoinsCount));
obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("difficulty",
GetDifficulty(GetLastBlockIndex(boost::atomic_load(&pindexBest).get(), true))));
obj.push_back(Pair("search-interval", (int)stakeMaker.getLastCoinStakeSearchInterval()));
obj.push_back(Pair("weight", (uint64_t)nWeight));
obj.push_back(Pair("netstakeweight", (uint64_t)nNetworkWeight));
obj.push_back(Pair("expectedtime", nExpectedTime));
return obj;
}
Value getworkex(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error("getworkex [data, coinbase]\n"
"If [data, coinbase] is not specified, returns extended work data.\n");
if (vNodes.empty())
throw JSONRPCError(-9, "neblio is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "neblio is downloading blocks...");
if (boost::atomic_load(&pindexBest)->nHeight >= Params().LastPoWBlock())
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
typedef map<uint256, pair<CBlock*, CScript>> mapNewBlock_t;
static mapNewBlock_t mapNewBlock;
static vector<CBlock*> vNewBlock;
static CReserveKey reservekey(std::atomic_load(&pwalletMain).get());
if (params.size() == 0) {
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndexSmartPtr pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) {
if (pindexPrev != pindexBest) {
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH (CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
nTransactionsUpdatedLast = nTransactionsUpdated;
pindexPrev = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(pwalletMain.get()).release();
if (!pblock)
throw JSONRPCError(-7, "Out of memory");
vNewBlock.push_back(pblock);
}
// Update nTime
pblock->nTime = max(pindexPrev->GetPastTimeLimit() + 1, GetAdjustedTime());
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev.get(), nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Prebuild hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
CTransaction coinbaseTx = pblock->vtx[0];
std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
Object result;
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << coinbaseTx;
result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
Array merkle_arr;
BOOST_FOREACH (uint256 merkleh, merkle) {
merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
}
result.push_back(Pair("merkle", merkle_arr));
return result;
} else {
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
vector<unsigned char> coinbase;
if (params.size() == 2)
coinbase = ParseHex(params[1].get_str());
if (vchData.size() != 128)
throw JSONRPCError(-8, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128 / 4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
if (coinbase.size() == 0)
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
else
CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
pblock->hashMerkleRoot = pblock->GetMerkleRoot();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
Value getwork(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getwork [data]\n"
"If [data] is not specified, returns formatted hash data to work on:\n"
" \"midstate\" : precomputed hash state after hashing the first half of the data "
"(DEPRECATED)\n" // deprecated
" \"data\" : block data\n"
" \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
" \"target\" : little endian hash target\n"
"If [data] is specified, tries to solve the block and returns true if it was successful.");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "neblio is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "neblio is downloading blocks...");
if (boost::atomic_load(&pindexBest)->nHeight >= Params().LastPoWBlock())
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
typedef map<uint256, pair<CBlock*, CScript>> mapNewBlock_t;
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
static vector<CBlock*> vNewBlock;
static CReserveKey reservekey(pwalletMain.get());
if (params.size() == 0) {
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndexSmartPtr pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != boost::atomic_load(&pindexBest) ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) {
if (pindexPrev != pindexBest) {
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
for (CBlock* pblock : vNewBlock)
delete pblock;
vNewBlock.clear();
}
// Clear pindexPrev so future getworks make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndexSmartPtr pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(pwalletMain.get()).release();
if (!pblock)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
vNewBlock.push_back(pblock);
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
// Update nTime
pblock->UpdateTime(pindexPrev.get());
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev.get(), nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Pre-build hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
return result;
} else {
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
if (vchData.size() != 128)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128 / 4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
pblock->hashMerkleRoot = pblock->GetMerkleRoot();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
Value getblocktemplate(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error("getblocktemplate [params]\n"
"Returns data needed to construct a block to work on:\n"
" \"version\" : block version\n"
" \"previousblockhash\" : hash of current highest block\n"
" \"transactions\" : contents of non-coinbase transactions that should be "
"included in the next block\n"
" \"coinbaseaux\" : data that should be included in coinbase\n"
" \"coinbasevalue\" : maximum allowable input to coinbase transaction, "
"including the generation award and transaction fees\n"
" \"target\" : hash target\n"
" \"mintime\" : minimum timestamp appropriate for next block\n"
" \"curtime\" : current timestamp\n"
" \"mutable\" : list of ways the block template may be changed\n"
" \"noncerange\" : range of valid nonces\n"
" \"sigoplimit\" : limit of sigops in blocks\n"
" \"sizelimit\" : limit of block size\n"
" \"bits\" : compressed target of next block\n"
" \"height\" : height of the next block\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
std::string strMode = "template";
if (params.size() > 0) {
const Object& oparam = params[0].get_obj();
const Value& modeval = find_value(oparam, "mode");
if (modeval.type() == str_type)
strMode = modeval.get_str();
else if (modeval.type() == null_type) {
/* Do nothing */
} else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
}
if (strMode != "template")
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "neblio is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "neblio is downloading blocks...");
if (boost::atomic_load(&pindexBest)->nHeight >= Params().LastPoWBlock())
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
static CReserveKey reservekey(pwalletMain.get());
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndexSmartPtr pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5)) {
// Clear pindexPrev so future calls make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndexSmartPtr pindexPrevNew = boost::atomic_load(&pindexBest);
nStart = GetTime();
// Create new block
if (pblock) {
delete pblock;
pblock = NULL;
}
pblock = CreateNewBlock(pwalletMain.get()).release();
if (!pblock)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
// Update nTime
pblock->UpdateTime(pindexPrev.get());
pblock->nNonce = 0;
Array transactions;
map<uint256, int64_t> setTxIndex;
int i = 0;
CTxDB txdb("r");
BOOST_FOREACH (CTransaction& tx, pblock->vtx) {
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase() || tx.IsCoinStake())
continue;
Object entry;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
entry.push_back(Pair("hash", txHash.GetHex()));
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) {
entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
Array deps;
BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs) {
if (setTxIndex.count(inp.first))
deps.push_back(setTxIndex[inp.first]);
}
entry.push_back(Pair("depends", deps));
int64_t nSigOps = tx.GetLegacySigOpCount();
nSigOps += tx.GetP2SHSigOpCount(mapInputs);
entry.push_back(Pair("sigops", nSigOps));
}
transactions.push_back(entry);
}
Object aux;
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
static Array aMutable;
if (aMutable.empty()) {
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
}
Object result;
result.push_back(Pair("version", pblock->nVersion));
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(Pair("transactions", transactions));
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetPastTimeLimit() + 1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
result.push_back(Pair("sizelimit", (int64_t)MaxBlockSize()));
result.push_back(Pair("curtime", (int64_t)pblock->nTime));
result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight + 1)));
return result;
}
Value submitblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error("submitblock <hex data> [optional-params-obj]\n"
"[optional-params-obj] parameter is currently ignored.\n"
"Attempts to submit new block to network.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
vector<unsigned char> blockData(ParseHex(params[0].get_str()));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
CBlock block;
try {
ssBlock >> block;
} catch (std::exception& e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
}
bool fAccepted = ProcessBlock(NULL, &block);
if (!fAccepted)
return "rejected";
return Value::null;
}
boost::optional<unsigned> MineBlock(CBlock block, uint64_t nMaxTries)
{
using NonceType = unsigned;
static_assert(std::is_same<NonceType, decltype(block.nNonce)>::value,
"Nonce type is expected to be unsigned");
auto seed = std::random_device{}();
std::mt19937 gen(seed);
std::uniform_int_distribution<NonceType> dis;
while (nMaxTries > 0) {
--nMaxTries;
block.nNonce = dis(gen);
if (!CheckProofOfWork(block.GetHash(), block.nBits, true)) {
continue;
} else {
return block.nNonce;
}
}
return boost::none;
}
Value generateBlocks(int nGenerate, uint64_t nMaxTries, CWallet* const pwallet,
const boost::optional<CBitcoinAddress>& destinationAddress = boost::none)
{
static const int nInnerLoopCount = 0x10000;
int nHeightEnd = 0;
int nHeight = nBestHeight.load();
nHeightEnd = nBestHeight.load() + nGenerate;
unsigned int nExtraNonce = 0;
json_spirit::Array blockHashes;
// generate a new address
const CBitcoinAddress destination = [&destinationAddress]() {
if (destinationAddress) {
return *destinationAddress;
}
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT,
"Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBookEntry(keyID, "");
return CBitcoinAddress(keyID);
}();
while (nHeight < nHeightEnd) {
std::unique_ptr<CBlock> pblock = CreateNewBlock(pwallet, false, 0, destination);
if (!pblock)
throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
{
LOCK(cs_main);
IncrementExtraNonce(pblock.get(), pindexBest.get(), nExtraNonce);
}
boost::optional<unsigned int> nonce = MineBlock(*pblock, nMaxTries);
if (nonce) {
pblock->nNonce = *nonce;
} else {
// failed to mine
break;
}
if (pblock->nNonce == nInnerLoopCount) {
continue;
}
// peercoin: sign block
// rfc6: we sign proof of work blocks only before 0.8 fork
// if (!pblock->SignBlock(*pwallet, 0))
// throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
if (!ProcessBlock(nullptr, pblock.get()))
throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
++nHeight;
blockHashes.push_back(pblock->GetHash().GetHex());
// mark script as important because it was used at least for one coinbase output if the script
// came from the wallet
// if (keepScript) {
// coinbaseScript->KeepScript();
// }
}
return Value(blockHashes);
}
Value generatePOSBlocks(
int nGenerate, CWallet* const pwallet, bool submitBlock = true,
const boost::optional<std::set<std::pair<uint256, unsigned>>>& customInputs = boost::none,
CAmount extraPayoutForTests = 0)
{
if (!Params().MineBlocksOnDemand())
throw JSONRPCError(RPC_INVALID_REQUEST, "This method can only be used on regtest");
int nHeightEnd = 0;
int nHeight = nBestHeight.load();
nHeightEnd = nBestHeight.load() + nGenerate;
json_spirit::Array blockHashesOrSerializedData;
const auto BlockMaker = [&]() {
std::unique_ptr<CBlock> block = CreateNewBlock(pwallet, true, 0);
if (!block)
throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
if (block->SignBlock(*pwallet, 0, customInputs, extraPayoutForTests)) {
if (submitBlock) {
if (!CheckStake(block.get(), *pwallet))
throw JSONRPCError(RPC_INTERNAL_ERROR, "CheckStake, CheckStake failed");
}
} else {
block.reset();
}
return block;
};
while (nHeight < nHeightEnd) {
const std::unique_ptr<CBlock> pblock = BlockMaker();
if (!pblock) {
// staking failed
break;
}
++nHeight;
if (submitBlock) {
blockHashesOrSerializedData.push_back(pblock->GetHash().GetHex());
} else {
// if block is not submitted, return the serialized format
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << *pblock;
std::string blockRaw = ss.str();
blockHashesOrSerializedData.push_back(HexStr(std::make_move_iterator(blockRaw.begin()),
std::make_move_iterator(blockRaw.end())));
}
}
return Value(blockHashesOrSerializedData);
}
Value generate(const Array& params, bool fHelp)
{
CWallet* const pwallet = pwalletMain.get();
if (fHelp || params.size() < 1 || params.size() > 2) {
throw std::runtime_error(
"generate nblocks ( maxtries )\n"
"\nMine up to nblocks blocks immediately (before the RPC call returns) to an address in the "
"wallet.\n"
"\nArguments:\n"
"1. nblocks (numeric, required) How many blocks are generated immediately.\n"
"2. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n"
"\nResult:\n"
"[ blockhashes ] (array) hashes of blocks generated\n"
"\nExamples:\n"
"\nGenerate 11 blocks\n"
"generate 11");
}
if (!Params().MineBlocksOnDemand())
throw JSONRPCError(RPC_INVALID_REQUEST, "This method can only be used on regtest");
EnsureWalletIsUnlocked();
int num_generate = params[0].get_int();
uint64_t max_tries = 1000000;
if (params.size() > 1 && params[1].type() != null_type) {
max_tries = params[1].get_int();
}
// std::shared_ptr<CReserveScript> coinbase_script;
// pwallet->GetScriptForMining(coinbase_script);
// // If the keypool is exhausted, no script is returned at all. Catch this.
// if (!coinbase_script) {
// throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT,
// "Error: Keypool ran out, please call keypoolrefill first");
// }
// // throw an error if no script was provided
// if (coinbase_script->reserveScript.empty()) {
// throw JSONRPCError(RPC_INTERNAL_ERROR, "No coinbase script available");
// }
return generateBlocks(num_generate, max_tries, pwallet);
}
std::set<std::pair<uint256, unsigned>> ParseCustomInputs(const Value& inputsArray)
{
std::set<std::pair<uint256, unsigned>> result;
if (inputsArray.type() == Value_type::array_type) {
Array inputs = inputsArray.get_array();
for (const Value& el : inputs) {
if (el.type() != Value_type::array_type) {
throw JSONRPCError(RPC_TYPE_ERROR,
"Error: Second parameter's elements must be arrays, each are a "
"pair of string (hash) and output index (int) (error A)");
}
Array p = el.get_array();
if (p.size() != 2) {
throw JSONRPCError(RPC_TYPE_ERROR,
"Error: Second parameter's elements must be arrays, each are a "
"pair of string (hash) and output index (int) (error B)");
}
if (p[0].type() != Value_type::str_type) {
throw JSONRPCError(RPC_TYPE_ERROR,
"Error: Second parameter's elements must be arrays, each are a "
"pair of string (hash) and output index (int) (first element of "
"a pair is not a string)");
}
if (p[1].type() != Value_type::int_type) {
throw JSONRPCError(RPC_TYPE_ERROR,
"Error: Second parameter's elements must be arrays, each are a "
"pair of string (hash) and output index (int) (second element of "
"a pair is not an int)");
}
int outIndexS = p[1].get_int();
if (outIndexS < 0) {
throw JSONRPCError(RPC_TYPE_ERROR,
"Error: Second parameter's elements must be arrays, each are a "
"pair of string (hash) and output index (int) (second element of "
"a pair is < 0)");
}
unsigned outIndex = static_cast<unsigned>(outIndexS);
result.insert(std::make_pair(uint256(p[0].get_str()), outIndex));
}
return result;
} else {
throw JSONRPCError(RPC_TYPE_ERROR, "Error: Second parameter must be an array of pairs");
}
}
Value generatepos(const Array& params, bool fHelp)
{
EnsureWalletIsUnlocked();
CWallet* const pwallet = pwalletMain.get();
if (fHelp || params.size() < 1 || params.size() > 4) {
throw std::runtime_error(
"generate nblocks\n"
"\nMine one block with proof of stake immediately (before the RPC call returns)\n"
"\nBe aware that staking is a complex principle that requires accurate timing. It's "
"recommended that you manage timing manually and generate only 1 block at a time\n"
"\nArguments:\n"
"1. count (numeric, required) Number of blocks to generate.\n"
"2. submit block (bool, optional, default=true) whether to submit the block after creating "
"it or return its serialized hex form"
"3. inputs to use (optional list of pairs (list of two elements), every one is a hash and "
"an output index); the staker will filter the available outputs with these"
"4. extra payout for tests (numeric, optional): Extra payout for the stake for testing; "
"\nResult:\n"
"[ blockhashes ] (array) hashes of blocks generated\n"
"\nExamples:\n"
"\nGenerate 11 blocks\n"
"generate 11");
}
int num_generate = params[0].get_int();
bool fSubmitBlock = true;
if (params.size() > 1 && params[1].type() == Value_type::bool_type) {
fSubmitBlock = params[1].get_bool();
}
boost::optional<std::set<std::pair<uint256, unsigned>>> customInputs;
if (params.size() > 2 && params[2].type() != Value_type::null_type) {
customInputs = ParseCustomInputs(params[2]);
}
CAmount extraPayoutForTests = 0;
if (params.size() > 3 && params[3].type() != Value_type::null_type) {
extraPayoutForTests = params[3].get_int();
}
return generatePOSBlocks(num_generate, pwallet, fSubmitBlock, customInputs, extraPayoutForTests);
}
Value generatetoaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
throw std::runtime_error(
"generatetoaddress nblocks address (maxtries)\n"
"\nMine blocks immediately to a specified address (before the RPC call returns)\n"
"\nArguments:\n"
"1. nblocks (numeric, required) How many blocks are generated immediately.\n"
"2. address (string, required) The address to send the newly generated nebls to.\n"
"3. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n"
"\nResult:\n"
"[ blockhashes ] (array) hashes of blocks generated\n"
"\nExamples:\n"
"\nGenerate 11 blocks to myaddress\n");
if (!Params().MineBlocksOnDemand())
throw JSONRPCError(RPC_INVALID_REQUEST, "This method can only be used on regtest");
EnsureWalletIsUnlocked();
CWallet* const pwallet = pwalletMain.get();
int num_generate = params[0].get_int();
uint64_t max_tries = 1000000;
if (params.size() > 2 && params[2].type() != Value_type::null_type) {
max_tries = params[2].get_int();
}
CBitcoinAddress destination(params[1].get_str());
if (!destination.IsValid()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address");
}
return generateBlocks(num_generate, max_tries, pwallet, destination);
}
static CKey WIFSecretToKey(const std::string& wifKey)
{
// decode the wif string of the private key
CBitcoinSecret bitcoinSecret;
bitcoinSecret.SetString(wifKey);
bool fCompressed = false;
// set the ECC key of the secret
CKey key;
const CSecret secret = bitcoinSecret.GetSecret(fCompressed);
key.SetSecret(secret, fCompressed);
return key;
}
static CTransaction TxFromHex(const std::string& tx_hex)
{
vector<unsigned char> blockData(ParseHex(tx_hex));
CDataStream ssTx(blockData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
try {
ssTx >> tx;
} catch (std::exception& e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Failed to deserialize transaction");
}
return tx;
}
Value generateblockwithkey(const Array& params, bool fHelp)
{
// clang-format off
if (fHelp || params.size() < 3 || params.size() > 5)
throw std::runtime_error(
"generateblockwithkey output-tx-hash output-index private-key txs (maxtries)\n"
"\nMine blocks immediately to a specified address (before the RPC call returns)\n"
"\nArguments:\n"
"1. output-tx-hash (string, required) The output transaction that should be used as stake kernel.\n"
"2. output-index (int, required) The index of the output to be used in the transaction above.\n"
"3. private-key (string, required) The private key of the address the UTXO is from.\n"
"4. txs (list<string>, optional) raw txs to include in the block\n"
"5. maxtries (numeric, optional) How many times to try to create the block (default = 10000).\n"
"\nResult:\n"
"raw block; raw block as hex string, to be submitted using `submitblock` rpc function\n"
"\nExamples:\n\n"
"generateblockwithkey 0xabcdefg 1 Vxyzabc [0xabc, 0xdef]\n");
// clang-format on
uint256 outputHash(params[0].get_str());
uint32_t outputIndex = static_cast<uint32_t>(params[1].get_int());
const CKey key = WIFSecretToKey(params[2].get_str());
uint32_t maxRetries = 10000;
std::vector<CTransaction> txs;
if (params.size() > 3) {
if (params[3].type() != Value_type::array_type) {
throw JSONRPCError(RPC_INVALID_PARAMS,
"Parameter txs must be an array of strings (top type isn't an array)");
}
const Array& txs_json = params[3].get_array();
for (const Value& val : txs_json) {
if (val.type() != Value_type::str_type) {
throw JSONRPCError(RPC_INVALID_PARAMS,
"Parameter txs must be an array of strings (element is not str)");
}
txs.push_back(TxFromHex(val.get_str()));
}
}
if (params.size() > 4) {
maxRetries = static_cast<uint32_t>(params[4].get_int());
}
const auto BlockMaker = [&]() {
std::unique_ptr<CBlock> block = CreateNewBlock(nullptr, true, 0);
if (!block)
throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't assemble new block");
block->vtx.insert(block->vtx.end(), txs.begin(), txs.end());
if (!block->SignBlockWithSpecificKey(COutPoint(outputHash, outputIndex), key, 0)) {
block.reset();
}
return block;
};
for (uint32_t i = 0; i < maxRetries; i++) {
const std::unique_ptr<CBlock> block = BlockMaker();
if (block) {
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << *block;
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
}
throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block; max retries exceeded");
}
|
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/usdImaging/usdRiImaging/tokens.h"
PXR_NAMESPACE_OPEN_SCOPE
TF_DEFINE_PUBLIC_TOKENS(UsdRiImagingTokens, USDRIIMAGING_TOKENS);
PXR_NAMESPACE_CLOSE_SCOPE
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "platform/impl/windows/wifi_lan.h"
// Windows headers
#include <windows.h>
// Standard C/C++ headers
#include <codecvt>
#include <locale>
#include <string>
// ABSL headers
#include "absl/strings/str_format.h"
// Nearby connections headers
#include "platform/base/cancellation_flag_listener.h"
#include "platform/impl/windows/utils.h"
#include "platform/public/logging.h"
#include "platform/public/mutex_lock.h"
namespace location {
namespace nearby {
namespace windows {
bool WifiLanMedium::StartAdvertising(const NsdServiceInfo& nsd_service_info) {
absl::MutexLock lock(&mutex_);
if (!IsAccepting()) {
NEARBY_LOGS(WARNING)
<< "cannot start advertising without accepting connetions.";
return false;
}
if (IsAdvertising()) {
NEARBY_LOGS(WARNING)
<< "cannot start advertising again when it is running.";
return false;
}
if (nsd_service_info.GetTxtRecord(KEY_ENDPOINT_INFO.data()).empty()) {
NEARBY_LOGS(ERROR) << "cannot start advertising without endpoint info.";
return false;
}
if (nsd_service_info.GetServiceName().empty()) {
NEARBY_LOGS(ERROR) << "cannot start advertising without service name.";
return false;
}
std::string instance_name = absl::StrFormat(
MDNS_INSTANCE_NAME_FORMAT.data(), nsd_service_info.GetServiceName(),
nsd_service_info.GetServiceType());
NEARBY_LOGS(INFO) << "mDNS instance name is " << instance_name;
dnssd_service_instance_ = DnssdServiceInstance{
string_to_wstring(instance_name),
nullptr, // let windows use default computer's local name
(uint16)nsd_service_info.GetPort()};
// Add TextRecords from NsdServiceInfo
auto text_attributes = dnssd_service_instance_.TextAttributes();
auto text_records = nsd_service_info.GetTxtRecords();
auto it = text_records.begin();
while (it != text_records.end()) {
text_attributes.Insert(string_to_wstring(it->first),
string_to_wstring(it->second));
it++;
}
dnssd_regirstraion_result_ = dnssd_service_instance_
.RegisterStreamSocketListenerAsync(
server_socket_ptr_->GetSocketListener())
.get();
if (dnssd_regirstraion_result_.HasInstanceNameChanged()) {
NEARBY_LOGS(WARNING) << "advertising instance name was changed due to have "
"same name instance was running.";
// stop the service and return false
StopAdvertising(nsd_service_info);
return false;
}
if (dnssd_regirstraion_result_.Status() == DnssdRegistrationStatus::Success) {
NEARBY_LOGS(INFO) << "started to advertising.";
medium_status_ |= MEDIUM_STATUS_ADVERTISING;
return true;
}
// Clean up
NEARBY_LOGS(ERROR)
<< "failed to start advertising due to registration failure.";
dnssd_service_instance_ = nullptr;
dnssd_regirstraion_result_ = nullptr;
return false;
}
// Win32 call only can use globel function or static method in class
void WifiLanMedium::Advertising_StopCompleted(DWORD Status, PVOID pQueryContext,
PDNS_SERVICE_INSTANCE pInstance) {
NEARBY_LOGS(INFO) << "unregister with status=" << Status;
try {
WifiLanMedium* medium = static_cast<WifiLanMedium*>(pQueryContext);
medium->NotifyDnsServiceUnregistered(Status);
} catch (...) {
NEARBY_LOGS(ERROR) << "failed to notify the stop of DNS service instance."
<< Status;
}
}
void WifiLanMedium::NotifyDnsServiceUnregistered(DWORD status) {
if (dns_service_stop_latch_.get() != nullptr) {
dns_service_stop_status_ = status;
dns_service_stop_latch_.get()->CountDown();
}
}
bool WifiLanMedium::StopAdvertising(const NsdServiceInfo& nsd_service_info) {
// Need to use Win32 API to deregister the Dnssd instance
if (!IsAdvertising()) {
NEARBY_LOGS(WARNING)
<< "Cannot stop advertising because no advertising is running.";
return false;
}
// Init DNS service instance
std::string instance_name = absl::StrFormat(
MDNS_INSTANCE_NAME_FORMAT.data(), nsd_service_info.GetServiceName(),
nsd_service_info.GetServiceType());
int port = nsd_service_info.GetPort();
dns_service_instance_name_ =
std::make_unique<std::wstring>(string_to_wstring(instance_name));
dns_service_instance_.pszInstanceName =
(LPWSTR)dns_service_instance_name_->c_str();
dns_service_instance_.pszHostName = (LPWSTR)MDNS_HOST_NAME.data();
dns_service_instance_.wPort = port;
// Init DNS service register request
dns_service_register_request_.Version = DNS_QUERY_REQUEST_VERSION1;
dns_service_register_request_.InterfaceIndex =
0; // all interfaces will be considered
dns_service_register_request_.unicastEnabled = false;
dns_service_register_request_.hCredentials = NULL;
dns_service_register_request_.pServiceInstance = &dns_service_instance_;
dns_service_register_request_.pQueryContext = this; // callback use it
dns_service_register_request_.pRegisterCompletionCallback =
WifiLanMedium::Advertising_StopCompleted;
dns_service_stop_latch_ = std::make_unique<CountDownLatch>(1);
DWORD status = DnsServiceDeRegister(&dns_service_register_request_, nullptr);
if (status != DNS_REQUEST_PENDING) {
NEARBY_LOGS(ERROR) << "failed to stop mDNS advertising for service type ="
<< nsd_service_info.GetServiceType();
return false;
}
// Wait for stop finish
dns_service_stop_latch_.get()->Await();
dns_service_stop_latch_ = nullptr;
if (dns_service_stop_status_ != 0) {
NEARBY_LOGS(INFO) << "failed to stop mDNS advertising for service type ="
<< nsd_service_info.GetServiceType();
return false;
}
NEARBY_LOGS(INFO) << "succeeded to stop mDNS advertising for service type ="
<< nsd_service_info.GetServiceType();
medium_status_ &= (~MEDIUM_STATUS_ADVERTISING);
return true;
}
// Returns true once the WifiLan discovery has been initiated.
bool WifiLanMedium::StartDiscovery(const std::string& service_type,
DiscoveredServiceCallback callback) {
if (IsDiscovering()) {
NEARBY_LOGS(WARNING) << "discovery already running for service type ="
<< service_type;
return false;
}
std::string selector =
absl::StrFormat(MDNS_DEVICE_SELECTOR_FORMAT.data(), service_type);
std::vector<winrt::hstring> requestedProperties{
L"System.Devices.IpAddress",
L"System.Devices.Dnssd.HostName",
L"System.Devices.Dnssd.InstanceName",
L"System.Devices.Dnssd.PortNumber",
L"System.Devices.Dnssd.ServiceName",
L"System.Devices.Dnssd.TextAttributes"};
device_watcher_ = DeviceInformation::CreateWatcher(
string_to_wstring(selector), requestedProperties,
DeviceInformationKind::AssociationEndpointService);
device_watcher_added_event_token =
device_watcher_.Added({this, &WifiLanMedium::Watcher_DeviceAdded});
device_watcher_updated_event_token =
device_watcher_.Updated({this, &WifiLanMedium::Watcher_DeviceUpdated});
device_watcher_removed_event_token =
device_watcher_.Removed({this, &WifiLanMedium::Watcher_DeviceRemoved});
device_watcher_.Start();
discovered_service_callback_ = std::move(callback);
medium_status_ |= MEDIUM_STATUS_DISCOVERING;
NEARBY_LOGS(INFO) << "started to discovery.";
return true;
}
// Returns true once WifiLan discovery for service_id is well and truly
// stopped; after this returns, there must be no more invocations of the
// DiscoveredServiceCallback passed in to StartDiscovery() for service_id.
bool WifiLanMedium::StopDiscovery(const std::string& service_type) {
if (!IsDiscovering()) {
NEARBY_LOGS(WARNING) << "no discovering service to stop.";
return false;
}
device_watcher_.Stop();
device_watcher_.Added(device_watcher_added_event_token);
device_watcher_.Updated(device_watcher_updated_event_token);
device_watcher_.Removed(device_watcher_removed_event_token);
medium_status_ &= (~MEDIUM_STATUS_DISCOVERING);
device_watcher_ = nullptr;
return true;
}
std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
const NsdServiceInfo& remote_service_info,
CancellationFlag* cancellation_flag) {
NEARBY_LOGS(ERROR)
<< "connect to service by NSD service info. service type is "
<< remote_service_info.GetServiceType();
return ConnectToService(remote_service_info.GetIPAddress(),
remote_service_info.GetPort(), cancellation_flag);
}
std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
const std::string& ip_address, int port,
CancellationFlag* cancellation_flag) {
if (ip_address.empty() || port == 0) {
NEARBY_LOGS(ERROR) << "no valid service address and port to connect.";
return nullptr;
}
HostName host_name{string_to_wstring(ip_address)};
winrt::hstring service_name{winrt::to_hstring(port)};
StreamSocket socket{};
// setup cancel listener
if (cancellation_flag != nullptr) {
if (cancellation_flag->Cancelled()) {
NEARBY_LOGS(INFO) << "connect has been cancelled to service "
<< ip_address << ":" << port;
return nullptr;
}
location::nearby::CancellationFlagListener cancellationFlagListener(
cancellation_flag, [socket]() { socket.CancelIOAsync().get(); });
}
// connection to the service
try {
socket.ConnectAsync(host_name, service_name).get();
// connected need to keep connection
std::unique_ptr<WifiLanSocket> wifi_lan_socket =
std::make_unique<WifiLanSocket>(socket);
NEARBY_LOGS(INFO) << "connected to remote service " << ip_address << ":"
<< port;
return wifi_lan_socket;
} catch (...) {
NEARBY_LOGS(ERROR) << "failed to connect remote service " << ip_address
<< ":" << port;
}
return nullptr;
}
std::unique_ptr<api::WifiLanServerSocket> WifiLanMedium::ListenForService(
int port) {
absl::MutexLock lock(&mutex_);
// check current status
if (IsAccepting()) {
NEARBY_LOGS(WARNING) << "accepting connections already started on port "
<< server_socket_ptr_->GetPort();
return nullptr;
}
std::unique_ptr<WifiLanServerSocket> server_socket =
std::make_unique<WifiLanServerSocket>(port);
server_socket_ptr_ = server_socket.get();
server_socket->SetCloseNotifier([this]() {
absl::MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << "server socket was closed on port "
<< server_socket_ptr_->GetPort();
medium_status_ &= (~MEDIUM_STATUS_ACCEPTING);
server_socket_ptr_ = nullptr;
});
if (server_socket->listen()) {
medium_status_ |= MEDIUM_STATUS_ACCEPTING;
NEARBY_LOGS(INFO) << "started to listen serive on port " << port;
return server_socket;
}
NEARBY_LOGS(ERROR) << "Failed to listen service on port " << port;
return nullptr;
}
NsdServiceInfo WifiLanMedium::GetNsdServiceInformation(
IMapView<winrt::hstring, IInspectable> properties) {
NsdServiceInfo nsd_service_info{};
// Service name information
IInspectable inspectable =
properties.TryLookup(L"System.Devices.Dnssd.InstanceName");
if (inspectable == nullptr) {
NEARBY_LOGS(WARNING)
<< "no service name information in device information.";
return nsd_service_info;
}
nsd_service_info.SetServiceName(InspectableReader::ReadString(inspectable));
// IP Address information
inspectable = properties.TryLookup(L"System.Devices.IPAddress");
if (inspectable == nullptr) {
NEARBY_LOGS(WARNING) << "no IP address information in device information.";
return nsd_service_info;
}
auto ipaddresses = InspectableReader::ReadStringArray(inspectable);
if (ipaddresses.size() == 0) {
NEARBY_LOGS(WARNING) << "no IP address information in device information.";
return nsd_service_info;
}
std::string ip_address = ipaddresses[0];
// read IP port
inspectable = properties.TryLookup(L"System.Devices.Dnssd.PortNumber");
if (inspectable == nullptr) {
NEARBY_LOGS(WARNING) << "no IP port information in device information.";
return nsd_service_info;
}
int port = InspectableReader::ReadUint16(inspectable);
nsd_service_info.SetIPAddress(ip_address);
nsd_service_info.SetPort(port);
// read text record
inspectable = properties.TryLookup(L"System.Devices.Dnssd.TextAttributes");
if (inspectable == nullptr) {
NEARBY_LOGS(WARNING)
<< "no text attributes information in device information.";
return nsd_service_info;
}
auto text_attributes = InspectableReader::ReadStringArray(inspectable);
for (auto text_attribute : text_attributes) {
// text attribute in format key=value
int pos = text_attribute.find("=");
if (pos <= 0 || pos == text_attribute.size() - 1) {
NEARBY_LOGS(WARNING) << "found invalid text attribute " << text_attribute;
continue;
}
std::string key = text_attribute.substr(0, pos);
std::string value = text_attribute.substr(pos + 1);
nsd_service_info.SetTxtRecord(key, value);
}
return nsd_service_info;
}
fire_and_forget WifiLanMedium::Watcher_DeviceAdded(
DeviceWatcher sender, DeviceInformation deviceInfo) {
// need to read IP address and port information from deviceInfo
NsdServiceInfo nsd_service_info =
GetNsdServiceInformation(deviceInfo.Properties());
NEARBY_LOGS(INFO) << "device added for service name "
<< nsd_service_info.GetServiceName();
std::string endpoint =
nsd_service_info.GetTxtRecord(KEY_ENDPOINT_INFO.data());
if (endpoint.empty()) {
return fire_and_forget{};
}
discovered_service_callback_.service_discovered_cb(nsd_service_info);
return fire_and_forget();
}
fire_and_forget WifiLanMedium::Watcher_DeviceUpdated(
DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate) {
// TODO(b/200421481): discovery servcie callback needs to support device
// update.
NsdServiceInfo nsd_service_info =
GetNsdServiceInformation(deviceInfoUpdate.Properties());
NEARBY_LOGS(INFO) << "device updated for service name "
<< nsd_service_info.GetServiceName();
return fire_and_forget();
}
fire_and_forget WifiLanMedium::Watcher_DeviceRemoved(
DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate) {
// need to read IP address and port information from deviceInfo
NsdServiceInfo nsd_service_info =
GetNsdServiceInformation(deviceInfoUpdate.Properties());
NEARBY_LOGS(INFO) << "device removed for service name "
<< nsd_service_info.GetServiceName();
std::string endpoint =
nsd_service_info.GetTxtRecord(KEY_ENDPOINT_INFO.data());
if (endpoint.empty()) {
return fire_and_forget{};
}
discovered_service_callback_.service_lost_cb(nsd_service_info);
return fire_and_forget();
}
std::string WifiLanMedium::GetErrorMessage(std::exception_ptr eptr) {
try {
if (eptr) {
std::rethrow_exception(eptr);
} else {
return "";
}
} catch (const std::exception& e) {
return e.what();
}
}
} // namespace windows
} // namespace nearby
} // namespace location
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.